lodash#update TypeScript Examples

The following examples show how to use lodash#update. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: handleComponentSchema.ts    From brick-design with MIT License 6 votes vote down vote up
/**
 * 复制组件
 * @param state
 * @returns {{pageConfig: *}}
 */
export function copyComponent(state: StateType): StateType {
  const { undo, redo, pageConfig, selectedInfo } = state;
  /**
   * 未选中组件不做任何操作
   */
  if (!selectedInfo) {
    warn('Please select the node you want to copy');
    return state;
  }
  if (selectedInfo.selectedKey === ROOT) {
    warn('Prohibit copying root node');
    return state;
  }
  const { selectedKey, parentPropName, parentKey } = selectedInfo;
  undo.push({ pageConfig });
  redo.length = 0;
  const newKey = getNewKey(pageConfig);
  return {
    ...state,
    pageConfig: produce(pageConfig, (oldState) => {
      update(
        oldState,
        getLocation(parentKey!, parentPropName),
        (childNodes) => [...childNodes, `${newKey}`],
      );
      copyConfig(oldState, selectedKey, newKey);
    }),
    undo,
    redo,
  };
}
Example #2
Source File: handleComponentSchema.ts    From brick-design with MIT License 6 votes vote down vote up
/**
 * 清除所有子节点
 * @param state
 * @returns {{undo: *, pageConfig, redo: *}}
 */

export function clearChildNodes(state: StateType): StateType {
  const { pageConfig, selectedInfo, undo, redo } = state;
  if (!selectedInfo) {
    warn(
      'Please select the component or property you want to clear the child nodes',
    );
    return state;
  }
  const { selectedKey, propName } = selectedInfo;
  const childNodes = get(pageConfig, getLocation(selectedKey));
  if (!childNodes) return state;
  undo.push({ pageConfig });

  redo.length = 0;
  return {
    ...state,
    pageConfig: produce(pageConfig, (oldState) => {
      deleteChildNodes(oldState, childNodes, propName);
      update(oldState, getLocation(selectedKey), (childNodes) => {
        /**
         * 如果 没有propName说明要清除组件的所有子节点
         */
        if (!propName) {
          return undefined;
        } else {
          return restObject(childNodes, propName);
        }
      });
    }),
    undo,
    redo,
  };
}
Example #3
Source File: handleStyles.ts    From brick-design with MIT License 6 votes vote down vote up
export function resizeChange(state: StateType, payload: ResizePayload) {
  const { pageConfig, undo, redo, selectedInfo } = state;
  if (!selectedInfo) return state;
  const { selectedKey } = selectedInfo;
  const { width, height } = payload;
  if (width || height) {
    undo.push({ pageConfig });
    redo.length = 0;
  }

  return {
    ...state,
    pageConfig: produce(pageConfig, (oldConfigs) => {
      if (width) {
        update(oldConfigs[selectedKey], 'props.style.width', () => width);
      }
      if (height) {
        update(oldConfigs[selectedKey], 'props.style.height', () => height);
      }
    }),
  };
}
Example #4
Source File: CaaSMapper.ts    From fsxa-api with Apache License 2.0 6 votes vote down vote up
/**
   * Calls ResolveReferences for currentProject and each RemoteProject
   *
   * @param data
   * @returns data
   */
  async resolveAllReferences<Type extends {}>(data: Type, filterContext?: unknown): Promise<Type> {
    const remoteIds = Object.keys(this._remoteReferences)
    this.logger.debug('CaaSMapper.resolveAllReferences', { remoteIds })

    await Promise.all([
      this.resolveReferencesPerProject(data, undefined, filterContext),
      ...remoteIds.map((remoteId) =>
        this.resolveReferencesPerProject(data, remoteId, filterContext)
      ),
    ])

    // force a single resolution for image map media
    this._imageMapForcedResolutions.forEach(({ path, resolution }) => {
      update(data, [...path, 'resolutions'], (resolutions) =>
        resolution in resolutions ? { [resolution]: resolutions[resolution] } : resolutions
      )
    })

    return data
  }
Example #5
Source File: handleComponentSchema.ts    From brick-design with MIT License 5 votes vote down vote up
/**
 * 往画板或者容器组件添加组件
 * @param state
 * @returns {{pageConfig: *}}
 */
export function addComponent(state: StateType): StateType {
  const { undo, redo, pageConfig, dragSource, dropTarget,dragSort } = state;
  /**
   * 如果没有拖拽的组件不做添加动作, 如果没有
   */
  if (!dragSource || (!dropTarget && pageConfig[ROOT]))
    return { ...state, dragSource: null,dragSort:null };
  const { vDOMCollection, dragKey, parentKey, parentPropName } = dragSource;
  /**
   * 如果没有root根节点,新添加的组件添加到root
   */
  if (!pageConfig[ROOT]) {
    undo.push({ pageConfig });
    redo.length = 0;
    return {
      ...state,
      pageConfig: vDOMCollection!,
      dragSource: null,
      dropTarget: null,
      dragSort:null,
      undo,
      redo,
    };
  }
  // eslint-disable-next-line prefer-const
  let { selectedKey, propName,childNodeKeys } = dropTarget;
  /**
   * 如果有root根节点,并且即没有选中的容器组件也没有drop的目标,那么就要回退到drag目标,
   * 添加之前的页面配置
   */
  if (!selectedKey) {
    /**
     * 如果有parentKey说明是拖拽的是新添加的组件,
     * 返回原先的state状态
     */
    if (!parentKey) {
      return { ...state, ...undo.pop(), dragSource: null,dragSort:null };
    } else {
      return { ...state, dragSource: null,dragSort:null };
    }
  }

  if (!dragSort||
    parentKey===selectedKey&&isEqual(childNodeKeys,dragSort)||
    handleRules(pageConfig, dragKey!, selectedKey, propName)
  ) {
    return { ...state, dragSource: null, dropTarget: null ,dragSort:null};
  }

  parentKey && undo.push({ pageConfig });
  redo.length = 0;
  return {
    ...state,
    pageConfig: produce(pageConfig, (oldConfigs) => {
      //添加新组件到指定容器中
      update(oldConfigs, getLocation(selectedKey!, propName), () => dragSort);
      //如果有父key说明是跨组件的拖拽,原先的父容器需要删除该组件的引用
      if (parentKey&&(parentKey!==selectedKey||parentPropName!==propName)) {
        update(oldConfigs, getLocation(parentKey), (childNodes) =>
          deleteChildNodesKey(childNodes, dragKey!, parentPropName),
        );
      }
    }),
    dragSource: null,
    dropTarget: null,
    dragSort:null,
    undo,
    redo,
  };
}
Example #6
Source File: handleComponentSchema.ts    From brick-design with MIT License 5 votes vote down vote up
/**
 * 当domTree中拖拽节点调整顺序时触发
 * @param state
 * @param payload
 * @returns {{pageConfig: *}}
 */
export function onLayoutSortChange(
  state: StateType,
  payload: LayoutSortPayload,
): StateType {
  const { sortKeys, parentKey, parentPropName, dragInfo } = payload;
  const { undo, redo, pageConfig } = state;
  undo.push({ pageConfig });
  redo.length = 0;
  return {
    ...state,
    pageConfig: produce(pageConfig, (oldConfigs) => {
      update(
        oldConfigs,
        getLocation(parentKey, parentPropName),
        () => sortKeys,
      );
      /**
       * dragInfo有值说明为跨组件排序,需要删除拖拽组件原先父组件中的引用
       */
      if (
        dragInfo &&
        (dragInfo.parentKey !== parentKey ||
          dragInfo.parentPropName !== parentPropName)
      ) {
        const { key, parentKey, parentPropName } = dragInfo;
        update(oldConfigs, getLocation(parentKey), (childNodes) =>
          deleteChildNodesKey(childNodes, key, parentPropName),
        );
      }
    }),
    undo,
    redo,
  };
}
Example #7
Source File: handleComponentSchema.ts    From brick-design with MIT License 5 votes vote down vote up
/**
 * 删除组件
 * @param state
 * @returns {{propsSetting: *, pageConfig: *, selectedInfo: *}}
 */
export function deleteComponent(state: StateType): StateType {
  const { undo, redo, pageConfig, selectedInfo } = state;
  /**
   * 未选中组件将不做任何操作
   */
  if (!selectedInfo) {
    warn('Please select the components you want to delete');
    return state;
  }
  const { selectedKey, parentKey, parentPropName } = selectedInfo;
  undo.push({ pageConfig, selectedInfo });

  redo.length = 0;
  return {
    ...state,
    pageConfig: produce(pageConfig, (oldState) => {
      /**
       * 如果选中的是根节点说明要删除整个页面
       */
      if (selectedKey === ROOT) {
        return {};
      } else {
        // 删除选中组件在其父组件中的引用
        update(oldState, getLocation(parentKey), (childNodes) =>
          deleteChildNodesKey(childNodes, selectedKey, parentPropName),
        );
        const childNodes = oldState[selectedKey].childNodes;
        /**
         * 如果childNodes有值,就遍历childNodes删除其中的子节点
         */
        if (childNodes) {
          deleteChildNodes(oldState, childNodes);
        }
        delete oldState[selectedKey];
      }
    }),
    selectedInfo: null,
    undo,
    redo,
  };
}
Example #8
Source File: index.tsx    From brick-design with MIT License 5 votes vote down vote up
function getFilterCategory(
  prevComponentsCategory: CategoryType,
  value?: string,
  rule?: string[],
) {
  const filterOpenKeys: string[] = [];
  const filterCategory: CategoryType = {};
  value = isEmpty(value) ? undefined : value;

  if (value && rule) {
    rule = rule.filter((name) => name.includes(value!));
  } else if (!value && !rule) {
    return { filterCategory: prevComponentsCategory, filterOpenKeys };
  }
  each(prevComponentsCategory, (infos, category) => {
    const { components } = infos || { components: null };
    if (components) {
      each(components, (componentInfo, componentName) => {
        if (
          (!rule && componentName.includes(value!)) ||
          (rule && rule.includes(componentName))
        ) {
          !filterOpenKeys.includes(category) && filterOpenKeys.push(category);
          update(
            filterCategory,
            `${category}.components`,
            (componentInfos = {}) => {
              componentInfos[componentName] = componentInfo;
              return componentInfos;
            },
          );
        }
      });
    } else if (
      (!rule && category.includes(value!)) ||
      (rule && rule.includes(category))
    ) {
      filterOpenKeys.push(category);
      filterCategory[category] = infos;
    }
  });
  return { filterOpenKeys, filterCategory };
}
Example #9
Source File: index.tsx    From yugong with MIT License 4 votes vote down vote up
TablePreset: React.FC<CustomPersetProps> = ({
  runningData,
  onChange,
}) => {
  const [disabled, setDisabled] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<Object[]>([]);
  const { runningTimes } = useSelector((state: RootState) => state);
  const rtRef = React.useRef<any>(null);

  useEffect(() => {
    const path: string = get(runningData, tableValuePath.runningTimes);
    if (path) {
      const dataSource = (get(runningTimes, path) || []) as Object[];
      if (dataSource.length) {
        setDataSource(dataSource);
      }
      setDisabled(!dataSource?.length);
    } else {
      setDisabled(true);
    }
  }, [dataSource, runningData, runningTimes]);

  const onChangeDebounce = useMemo(
    () =>
      throttle((value) => {
        onChange(value);
      }, 500),
    [onChange],
  );

  const onChangeRunningData = useCallback(
    (params: {
      [keys in TablePathKeys]?: any;
    }) => {
      const copyRunningData = cloneDeep(runningData);
      for (const key in params) {
        if (Object.prototype.hasOwnProperty.call(params, key)) {
          const value = params[key];
          update(copyRunningData, tableValuePath[key], () => value);
        }
      }
      onChangeDebounce(copyRunningData);
    },
    [onChangeDebounce, runningData],
  );

  const onChangeRunningTimes = useCallback(
    (e) => {
      onChangeRunningData({ runningTimes: e.target.value });
    },
    [onChangeRunningData],
  );

  const onBlurRunningTimes = useCallback(
    (e) => {
      const key = e.target.value;
      if (!key) return;
      const dataSource = (get(runningTimes, key) || []) as Object[];
      if (
        Array.isArray(dataSource) &&
        dataSource.length &&
        isObject(dataSource[0])
      ) {
        onChangeRunningData({ runningTimes: key });
      } else {
        message.error(
          '请从runningTimes中选择合规数组对象 [ { element:string, ... }, ... ]',
        );
        onChangeRunningData({ runningTimes: '' });
      }
    },
    [onChangeRunningData, runningTimes],
  );

  const selectChangeRunningData = useCallback(
    (e) => {
      onChangeRunningData({ runningTimes: e });
      rtRef.current!.focus({
        cursor: 'end',
      });
    },
    [onChangeRunningData],
  );

  const getDataFromRunningData = useCallback(
    (keys: TablePathKeys[]) => {
      const objRes: { [keys in TablePathKeys]?: any } = {};
      keys.forEach((key) => {
        objRes[key] = get(runningData, tableValuePath[key]);
      });

      return objRes;
    },
    [runningData],
  );

  return (
    <>
      <TableModuleContext.Provider
        value={{
          disabled,
          setDisabled,
          dataSource,
          runningData,
          onChangeRunningData,
          getDataFromRunningData,
        }}
      >
        <PageHeader title="表格设置" />
        <LineItem label="数据源">
          <Input
            value={get(runningData, tableValuePath.runningTimes)}
            onChange={onChangeRunningTimes}
            onBlur={onBlurRunningTimes}
            placeholder="请从runningTimes中选择"
            ref={rtRef}
            addonAfter={
              <Select
                style={{ width: '100px' }}
                placeholder="选择"
                value="运行时"
                onChange={selectChangeRunningData}
              >
                {Object.keys(runningTimes)?.map((item, index) => (
                  <Option key={index} value={item}>
                    {item}
                  </Option>
                ))}
              </Select>
            }
          />
        </LineItem>
        <LineItem label="表格列" />
        <SortableTableData />
      </TableModuleContext.Provider>
    </>
  );
}
Example #10
Source File: resources-usage-trend.tsx    From erda-ui with GNU Affero General Public License v3.0 4 votes vote down vote up
ResourceTrend = React.memo(
  ({ clusterNameStr, resourceType }: { clusterNameStr: string; resourceType: ORG_DASHBOARD.CpuMem }) => {
    const [state, updater] = useUpdate({
      interval: 'day',
      projectId: [333, 735],
      clusterDateRange: [moment().startOf('day'), moment().endOf('day')],
    });
    const [clusterTrend, loadingClusterTrend] = getClusterTrend.useState();
    const [projectTrend, loadingProjectTrend] = getProjectTrend.useState();
    React.useEffect(() => {
      if (clusterNameStr) {
        getClusterTrend.fetch({
          clusterName: clusterNameStr.split(','),
          resourceType,
          interval: state.interval,
          start: state.clusterDateRange[0].valueOf(),
          end: state.clusterDateRange[1].valueOf(),
        });
        getProjectTrend.fetch({
          clusterName: clusterNameStr.split(','),
          resourceType,
          projectId: state.projectId,
          interval: state.interval,
          start: state.clusterDateRange[0].valueOf(),
          end: state.clusterDateRange[1].valueOf(),
        });
      }
    }, [clusterNameStr, resourceType, state.clusterDateRange, state.interval, state.projectId]);

    const projectList = getProjectListNew.useData();
    useMount(() => {
      getProjectListNew.fetch({ pageNo: 1, pageSize: 1000 }); // TODO: if total is more than 1000
    });

    const getBarOption = (option: ORG_DASHBOARD.EchartOption) => {
      if (!option) return {};
      let newOption = option;
      const defaultOption = {
        xAxis: { splitLine: { show: false } },
        tooltip: { trigger: 'axis' },
        yAxis: { type: 'value' },
        series: option.series.map((item: Obj) => ({
          type: 'bar',
          barWidth: '60%',
          ...item,
          label: item.label ? { show: true, ...item.label } : undefined,
        })),
        grid: {
          top: '10%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
      };
      newOption = merge(defaultOption, option);
      return newOption;
    };

    const conditionsFilter = [
      {
        type: 'select',
        key: 'projectNames',
        label: i18n.t('project'),
        haveFilter: true,
        fixed: true,
        emptyText: i18n.t('dop:All'),
        showIndex: 1,
        options: (projectList?.list || []).map((prj) => ({ label: prj.displayName || prj.name, value: prj.id })),
        customProps: {
          mode: 'single',
        },
      },
    ];

    return (
      <>
        <Title
          level={2}
          mt={16}
          title={i18n.t('cmp:Trend of cluster resources')}
          operations={[
            <DatePicker.RangePicker
              allowClear={false}
              allowEmpty={[false, false]}
              value={state.clusterDateRange}
              ranges={{
                Today: [moment().startOf('day'), moment().endOf('day')],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
              }}
              onChange={(dates) => updater.clusterDateRange(dates)}
            />,
            <Radio.Group
              buttonStyle="solid"
              onChange={(e) => updater.interval(e.target.value)}
              defaultValue={state.interval}
            >
              <Radio.Button value="day">{i18n.t('cmp:Daily')}</Radio.Button>
              <Radio.Button value="week">{i18n.t('cmp:Weekly')}</Radio.Button>
              <Radio.Button value="month">{i18n.t('cmp:Monthly')}</Radio.Button>
            </Radio.Group>,
          ]}
        />
        <Row justify="space-between" gutter={12}>
          <Col span={12}>
            <CardContainer.ChartContainer title={clusterTrend?.series[0]?.name} holderWhen={!clusterTrend}>
              <Echarts
                style={{ height: '320px' }}
                showLoading={loadingClusterTrend}
                option={getBarOption(clusterTrend)}
              />
            </CardContainer.ChartContainer>
          </Col>
          <Col span={12}>
            <CardContainer.ChartContainer
              title={projectTrend?.series[0]?.name}
              operation={
                <ContractiveFilter delay={1000} conditions={conditionsFilter} onChange={(values) => update(values)} />
              }
              holderWhen={!projectTrend}
            >
              <Echarts
                style={{ height: '320px' }}
                showLoading={loadingProjectTrend}
                option={getBarOption(projectTrend)}
              />
            </CardContainer.ChartContainer>
          </Col>
        </Row>
      </>
    );
  },
)