types#ValueOf TypeScript Examples

The following examples show how to use types#ValueOf. 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: useFieldActionModal.tsx    From datart with Apache License 2.0 4 votes vote down vote up
function useFieldActionModal({ i18nPrefix }: I18NComponentProps) {
  const t = useI18NPrefix(i18nPrefix);
  const [show, contextHolder] = useStateModal({ initState: {} });

  const getContent = (
    actionType,
    config?: ChartDataSectionField,
    dataset?: ChartDataSetDTO,
    dataView?: ChartDataView,
    dataConfig?: ChartDataConfig,
    onChange?,
    aggregation?: boolean,
    form?: FormInstance,
  ) => {
    if (!config) {
      return null;
    }

    const props = {
      config,
      dataset,
      dataView,
      dataConfig,
      onConfigChange: onChange,
      aggregation,
      i18nPrefix,
      form,
    };

    switch (actionType) {
      case ChartDataSectionFieldActionType.Sortable:
        return <FieldActions.SortAction {...props} />;
      case ChartDataSectionFieldActionType.Alias:
        return <FieldActions.AliasAction {...props} />;
      case ChartDataSectionFieldActionType.Format:
        return <FieldActions.NumberFormatAction {...props} />;
      case ChartDataSectionFieldActionType.Aggregate:
        return <FieldActions.AggregationAction {...props} />;
      case ChartDataSectionFieldActionType.AggregateLimit:
        return <FieldActions.AggregationLimitAction {...props} />;
      case ChartDataSectionFieldActionType.Filter:
        return <FieldActions.FilterAction {...props} />;
      case ChartDataSectionFieldActionType.Colorize:
        return <FieldActions.AggregationColorizeAction {...props} />;
      case ChartDataSectionFieldActionType.Size:
        return <FieldActions.SizeOptionsAction {...props} />;
      case ChartDataSectionFieldActionType.ColorRange:
        return <FieldActions.ColorizeRangeAction {...props} />;
      case ChartDataSectionFieldActionType.ColorizeSingle:
        return <FieldActions.ColorizeSingleAction {...props} />;
      default:
        return 'Please use correct action key!';
    }
  };

  const handleOk =
    (onConfigChange, columnUid: string) => (config, needRefresh) => {
      onConfigChange(columnUid, config, needRefresh);
    };

  const showModal = (
    columnUid: string,
    actionType: ValueOf<typeof ChartDataSectionFieldActionType>,
    dataConfig: ChartDataConfig,
    onConfigChange,
    dataset?: ChartDataSetDTO,
    dataView?: ChartDataView,
    modalSize?: string,
    aggregation?: boolean,
  ) => {
    const currentConfig = dataConfig.rows?.find(c => c.uid === columnUid);
    let _modalSize = StateModalSize.MIDDLE;
    if (actionType === ChartDataSectionFieldActionType.Colorize) {
      _modalSize = StateModalSize.XSMALL;
    } else if (actionType === ChartDataSectionFieldActionType.ColorizeSingle) {
      _modalSize = StateModalSize.XSMALL;
    }
    return (show as Function)({
      title: t(actionType),
      modalSize: modalSize || _modalSize,
      content: (onChange, from) =>
        getContent(
          actionType,
          currentConfig,
          dataset,
          dataView,
          dataConfig,
          onChange,
          aggregation,
          from,
        ),
      onOk: handleOk(onConfigChange, columnUid),
      maskClosable: true,
    });
  };

  return [showModal, contextHolder];
}
Example #2
Source File: ChartDraggableTargetContainer.tsx    From datart with Apache License 2.0 4 votes vote down vote up
ChartDraggableTargetContainer: FC<ChartDataConfigSectionProps> =
  memo(function ChartDraggableTargetContainer({
    ancestors,
    modalSize,
    config,
    translate: t = (...args) => args?.[0],
    onConfigChanged,
  }) {
    const { dataset } = useContext(ChartDatasetContext);
    const { drillOption } = useContext(ChartDrillContext);
    const { dataView, availableSourceFunctions } =
      useContext(VizDataViewContext);
    const [currentConfig, setCurrentConfig] = useState(config);
    const [showModal, contextHolder] = useFieldActionModal({
      i18nPrefix: 'viz.palette.data.enum.actionType',
    });
    const { aggregation } = useContext(ChartAggregationContext);

    useEffect(() => {
      setCurrentConfig(config);
    }, [config]);

    const [{ isOver, canDrop }, drop] = useDrop(
      () => ({
        accept: [
          CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN,
          CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN_GROUP,
          CHART_DRAG_ELEMENT_TYPE.DATA_CONFIG_COLUMN,
        ],
        drop(item: ChartDataSectionField & DragItem, monitor) {
          let items = Array.isArray(item) ? item : [item];
          let needDelete = true;

          if (
            monitor.getItemType() === CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN
          ) {
            const currentColumns: ChartDataSectionField[] = (
              currentConfig.rows || []
            ).concat(
              items.map(val => {
                let config: ChartDataSectionField = {
                  uid: uuidv4(),
                  ...val,
                  aggregate: getDefaultAggregate(val),
                };
                if (
                  val.category ===
                  ChartDataViewFieldCategory.DateLevelComputedField
                ) {
                  config.colName = `${val.colName}(${t(val.expression)})`;
                  config.expression = `${val.expression}(${val.colName})`;
                  config.field = val.colName;
                }
                return config;
              }),
            );
            updateCurrentConfigColumns(currentConfig, currentColumns, true);
          } else if (
            monitor.getItemType() ===
            CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN_GROUP
          ) {
            const hierarchyChildFields = items?.[0]?.children || [];
            const currentColumns: ChartDataSectionField[] = (
              currentConfig.rows || []
            ).concat(
              hierarchyChildFields.map(val => ({
                uid: uuidv4(),
                ...val,
                aggregate: getDefaultAggregate(val),
              })),
            );
            updateCurrentConfigColumns(currentConfig, currentColumns, true);
          } else if (
            monitor.getItemType() === CHART_DRAG_ELEMENT_TYPE.DATA_CONFIG_COLUMN
          ) {
            const originItemIndex = (currentConfig.rows || []).findIndex(
              r => r.uid === item.uid,
            );
            if (originItemIndex > -1) {
              const needRefreshData =
                currentConfig?.type === ChartDataSectionType.GROUP;
              needDelete = false;
              const currentColumns = updateBy(
                currentConfig?.rows || [],
                draft => {
                  draft.splice(originItemIndex, 1);
                  item.aggregate = getDefaultAggregate(item);
                  return draft.splice(item?.index!, 0, item);
                },
              );
              updateCurrentConfigColumns(
                currentConfig,
                currentColumns,
                needRefreshData,
              );
            } else {
              const currentColumns = updateBy(
                currentConfig?.rows || [],
                draft => {
                  item.aggregate = getDefaultAggregate(item);
                  return draft.splice(item?.index!, 0, item);
                },
              );
              updateCurrentConfigColumns(currentConfig, currentColumns);
            }
          }

          return { delete: needDelete };
        },
        canDrop: (item: ChartDataSectionField, monitor) => {
          let items = Array.isArray(item) ? item : [item];
          if (
            [CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN_GROUP].includes(
              monitor.getItemType() as any,
            ) &&
            ![
              ChartDataSectionType.GROUP,
              ChartDataSectionType.COLOR,
              ChartDataSectionType.MIXED,
            ].includes(currentConfig.type as ChartDataSectionType)
          ) {
            return false;
          }

          if (
            typeof currentConfig.actions === 'object' &&
            !items.every(val => val.type in (currentConfig.actions || {}))
          ) {
            //zh: 判断现在拖动的数据项是否可以拖动到当前容器中 en: Determine whether the currently dragged data item can be dragged into the current container
            return false;
          }

          // if (
          //   typeof currentConfig.actions === 'object' &&
          //   !(item.type in currentConfig.actions)
          // ) {
          //   return false;
          // }

          if (currentConfig.allowSameField) {
            return true;
          }

          if (
            monitor.getItemType() === CHART_DRAG_ELEMENT_TYPE.DATA_CONFIG_COLUMN
          ) {
            return true;
          }

          if (
            items[0].category ===
            ChartDataViewFieldCategory.DateLevelComputedField
          ) {
            const colNames = currentConfig.rows?.map(col => col.colName);
            return colNames
              ? colNames.every(v => !v?.includes(items[0].colName))
              : true;
          }

          const exists = currentConfig.rows?.map(col => col.colName);
          return items.every(i => !exists?.includes(i.colName));
        },
        collect: (monitor: DropTargetMonitor) => ({
          isOver: monitor.isOver(),
          canDrop: monitor.canDrop(),
        }),
      }),
      [onConfigChanged, currentConfig, dataView, dataset],
    );

    const updateCurrentConfigColumns = (
      currentConfig,
      newColumns,
      refreshDataset = false,
    ) => {
      const newCurrentConfig = updateByKey(currentConfig, 'rows', newColumns);
      setCurrentConfig(newCurrentConfig);
      onConfigChanged?.(ancestors, newCurrentConfig, refreshDataset);
    };

    const getDefaultAggregate = (item: ChartDataSectionField) => {
      if (
        currentConfig?.type === ChartDataSectionType.AGGREGATE ||
        currentConfig?.type === ChartDataSectionType.SIZE ||
        currentConfig?.type === ChartDataSectionType.INFO ||
        currentConfig?.type === ChartDataSectionType.MIXED
      ) {
        if (
          currentConfig.disableAggregate ||
          item.category === ChartDataViewFieldCategory.AggregateComputedField
        ) {
          return;
        }
        if (item.aggregate) {
          return item.aggregate;
        }

        let aggType: string = '';
        if (currentConfig?.actions instanceof Array) {
          currentConfig?.actions?.find(
            type =>
              type === ChartDataSectionFieldActionType.Aggregate ||
              type === ChartDataSectionFieldActionType.AggregateLimit,
          );
        } else if (currentConfig?.actions instanceof Object) {
          aggType = currentConfig?.actions?.[item?.type]?.find(
            type =>
              type === ChartDataSectionFieldActionType.Aggregate ||
              type === ChartDataSectionFieldActionType.AggregateLimit,
          );
        }
        if (aggType) {
          return AggregateFieldSubAggregateType?.[aggType]?.[0];
        }
      }
    };

    const onDraggableItemMove = (dragIndex: number, hoverIndex: number) => {
      const draggedItem = currentConfig.rows?.[dragIndex];
      if (draggedItem) {
        const newCurrentConfig = updateBy(currentConfig, draft => {
          const columns = draft.rows || [];
          columns.splice(dragIndex, 1);
          columns.splice(hoverIndex, 0, draggedItem);
        });
        setCurrentConfig(newCurrentConfig);
      } else {
        // const placeholder = {
        //   uid: CHARTCONFIG_FIELD_PLACEHOLDER_UID,
        //   colName: 'Placeholder',
        //   category: 'field',
        //   type: 'STRING',
        // } as any;
        // const newCurrentConfig = updateBy(currentConfig, draft => {
        //   const columns = draft.rows || [];
        //   if (dragIndex) {
        //     columns.splice(dragIndex, 1);
        //   }
        //   columns.splice(hoverIndex, 0, placeholder);
        // });
        // setCurrentConfig(newCurrentConfig);
      }
    };

    const handleOnDeleteItem = config => () => {
      if (config.uid) {
        let newCurrentConfig = updateBy(currentConfig, draft => {
          draft.rows = draft.rows?.filter(c => c.uid !== config.uid);
          if (
            config.category ===
            ChartDataViewFieldCategory.DateLevelComputedField
          ) {
            draft.replacedColName = config.colName;
          }
        });
        setCurrentConfig(newCurrentConfig);
        onConfigChanged?.(ancestors, newCurrentConfig, true);
      }
    };

    const renderDropItems = () => {
      if (
        !currentConfig.rows ||
        !currentConfig?.rows?.filter(Boolean)?.length
      ) {
        const fieldCount = reachLowerBoundCount(currentConfig?.limit, 0);
        if (fieldCount > 0) {
          return (
            <DropPlaceholder>
              {t('dropCount', undefined, { count: fieldCount })}
            </DropPlaceholder>
          );
        }
        return <DropPlaceholder>{t('drop')}</DropPlaceholder>;
      }
      return currentConfig.rows?.map((columnConfig, index) => {
        return (
          <ChartDraggableElement
            key={columnConfig.uid}
            id={columnConfig.uid}
            index={index}
            config={columnConfig}
            content={() => {
              const contentProps = {
                modalSize: modalSize,
                config: currentConfig,
                columnConfig: columnConfig,
                ancestors: ancestors,
                aggregation: aggregation,
                availableSourceFunctions,
                onConfigChanged: onConfigChanged,
                handleOpenActionModal: handleOpenActionModal,
              };
              return columnConfig.category ===
                ChartDataViewFieldCategory.Hierarchy ? (
                <ChartDraggableElementHierarchy {...contentProps} />
              ) : (
                <ChartDraggableElementField {...contentProps} />
              );
            }}
            moveCard={onDraggableItemMove}
            onDelete={handleOnDeleteItem(columnConfig)}
          ></ChartDraggableElement>
        );
      });
    };

    const renderDrillFilters = () => {
      if (currentConfig?.type !== ChartDataSectionType.FILTER) {
        return;
      }
      return getDillConditions()?.map(drill => {
        const field = drill.field;
        return (
          <StyledDillFilter type={field.type}>
            {getColumnRenderName(field)}
          </StyledDillFilter>
        );
      });
    };

    const getDillConditions = () => {
      return drillOption
        ?.getAllDrillDownFields()
        ?.filter(drill => Boolean(drill?.condition));
    };

    const handleFieldConfigChanged = (
      columnUid: string,
      fieldConfig: ChartDataSectionField,
      needRefresh?: boolean,
    ) => {
      if (!fieldConfig) {
        return;
      }
      const newConfig = updateDataConfigByField(
        columnUid,
        currentConfig,
        fieldConfig,
      );
      onConfigChanged?.(ancestors, newConfig, needRefresh);
    };

    const handleOpenActionModal =
      (uid: string) =>
      (actionType: ValueOf<typeof ChartDataSectionFieldActionType>) => {
        (showModal as Function)(
          uid,
          actionType,
          currentConfig,
          handleFieldConfigChanged,
          dataset,
          dataView,
          modalSize,
          aggregation,
        );
      };

    return (
      <StyledContainer ref={drop} isOver={isOver} canDrop={canDrop}>
        {renderDropItems()}
        {renderDrillFilters()}
        {contextHolder}
      </StyledContainer>
    );
  })