antd#TableColumnProps TypeScript Examples

The following examples show how to use antd#TableColumnProps. 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: PermissionTable.tsx    From datart with Apache License 2.0 4 votes vote down vote up
PermissionTable = memo(
  ({
    viewpoint,
    viewpointType,
    dataSourceType,
    dataSource,
    resourceLoading,
    privileges,
    onPrivilegeChange,
  }: PermissionTableProps) => {
    const { height, ref } = useResizeObserver();
    const t = useI18NPrefix('permission');

    const treeData = useMemo(() => {
      if (dataSource && privileges) {
        const originTreeData = listToTree(
          dataSource,
          null,
          [],
        ) as DataSourceTreeNode[];
        return setTreeDataWithPrivilege(
          originTreeData,
          [...privileges],
          viewpoint,
          viewpointType,
          dataSourceType,
        );
      } else {
        return [];
      }
    }, [viewpoint, viewpointType, dataSourceType, dataSource, privileges]);

    const {
      filteredData,
      expandedRowKeys,
      onExpand,
      debouncedSearch,
      setExpandedRowKeys,
    } = useSearchAndExpand(treeData, (keywords, d) =>
      d.name.includes(keywords),
    );

    useEffect(() => {
      if (dataSource?.length && viewpoint === Viewpoints.Subject) {
        setExpandedRowKeys([dataSource[0].id]);
      }
    }, [viewpoint, dataSource, setExpandedRowKeys]);

    const privilegeChange = useMemo(
      () => onPrivilegeChange(treeData),
      [treeData, onPrivilegeChange],
    );

    const columns = useMemo(() => {
      const columns: TableColumnProps<DataSourceTreeNode>[] = [
        {
          dataIndex: 'name',
          title:
            viewpoint === Viewpoints.Resource
              ? t('subjectName')
              : t('resourceName'),
        },
        {
          title: t('privileges'),
          align: 'center' as const,
          width: getPrivilegeSettingWidth(
            viewpoint,
            viewpointType,
            dataSourceType,
          ),
          render: (_, record) => (
            <PrivilegeSetting
              record={record}
              viewpoint={viewpoint}
              viewpointType={viewpointType}
              dataSourceType={dataSourceType}
              onChange={privilegeChange}
            />
          ),
        },
      ];
      return columns;
    }, [viewpoint, viewpointType, dataSourceType, privilegeChange, t]);

    return (
      <>
        <Toolbar>
          <Col span={12}>
            <Input
              placeholder={t('searchResources')}
              prefix={<SearchOutlined className="icon" />}
              bordered={false}
              onChange={debouncedSearch}
            />
          </Col>
        </Toolbar>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={filteredData}
          loading={resourceLoading}
          pagination={false}
          size="middle"
          expandable={{
            expandedRowKeys,
            onExpandedRowsChange: onExpand,
          }}
          bordered
        />
      </>
    );
  },
)
Example #2
Source File: ArrayConfig.tsx    From datart with Apache License 2.0 4 votes vote down vote up
export function ArrayConfig({
  attr,
  value,
  sourceId,
  testLoading,
  disabled,
  allowManage,
  onChange,
  onSubFormTest,
}: ArrayConfigProps) {
  const [formVisible, setFormVisible] = useState(false);
  const [editingRowKey, setEditingRowKey] = useState('');
  const [schemaDataSource, setSchemaDataSource] = useState<object[]>([]);
  const formRef = useRef<FormInstance<SourceFormModel>>();
  const t = useI18NPrefix('source');
  const tg = useI18NPrefix('global');

  const showForm = useCallback(() => {
    setFormVisible(true);
  }, []);

  const hideForm = useCallback(() => {
    setFormVisible(false);
  }, []);

  const afterClose = useCallback(() => {
    setEditingRowKey('');
    setSchemaDataSource([]);
  }, []);

  const test = useCallback(async () => {
    await formRef.current?.validateFields();
    const values = formRef.current?.getFieldsValue();
    if (values) {
      onSubFormTest &&
        onSubFormTest(values.config, result => {
          const columns = (values.config as any).columns;
          const lastModel = columns
            ? (columns as Schema[]).reduce<Model>(
                (model, column) => ({
                  ...model,
                  [column.name]: {
                    ...column,
                    category: ColumnCategories.Uncategorized, // FIXEME
                  },
                }),
                {},
              )
            : {};
          const modelAndDataSource = transformQueryResultToModelAndDataSource(
            result,
            lastModel,
          );
          setSchemaDataSource(modelAndDataSource.dataSource);
          formRef.current?.setFieldsValue({
            config: {
              columns: Object.entries(
                modelAndDataSource?.model?.columns || {},
              ).map(([name, model]) => ({ ...model, name: name })),
            },
          });
        });
    }
  }, [formRef, onSubFormTest]);

  const subFormRowKeyValidator = useCallback(
    val => {
      const configRowKey = attr.key;
      if (value && configRowKey) {
        return (
          val === editingRowKey || !value.find(v => v[configRowKey] === val)
        );
      }
      return true;
    },
    [attr, value, editingRowKey],
  );

  const formSave = useCallback(
    (formValues: SourceFormModel) => {
      const configRowKey = attr.key;
      if (value && configRowKey) {
        const index = value.findIndex(
          o => o[configRowKey] === formValues.config[configRowKey],
        );
        if (index >= 0) {
          onChange &&
            onChange([
              ...value.slice(0, index),
              formValues.config,
              ...value.slice(index + 1),
            ]);
        } else {
          onChange && onChange(value.concat(formValues.config));
        }
      } else {
        onChange && onChange([formValues.config]);
      }
      setFormVisible(false);
    },
    [attr, value, onChange],
  );

  const editConfig = useCallback(
    tableRowKey => () => {
      const configRowKey = attr.key;
      if (value && configRowKey) {
        const config = value.find(o => o[configRowKey] === tableRowKey);
        if (config) {
          setFormVisible(true);
          setEditingRowKey(tableRowKey);
          formRef.current?.setFieldsValue({ config });
          if (config['path'] && config['format']) {
            test();
          }
        }
      }
    },
    [attr, value, formRef, test],
  );

  const delConfig = useCallback(
    tableRowKey => () => {
      const configRowKey = attr.key;
      if (value && configRowKey) {
        onChange &&
          onChange(value.filter(o => o[configRowKey] !== tableRowKey));
      }
    },
    [attr, value, onChange],
  );

  const columns: TableColumnProps<object>[] = useMemo(
    () => [
      { title: attr.displayName, dataIndex: attr.key },
      {
        title: tg('title.action'),
        align: 'center',
        width: 120,
        render: (_, record) => (
          <Space>
            <ActionButton
              key="edit"
              type="link"
              onClick={editConfig(record[attr.key!])}
            >
              {tg('button.edit')}
            </ActionButton>
            {allowManage && (
              <Popconfirm
                key="del"
                title={tg('operation.deleteConfirm')}
                onConfirm={delConfig(record[attr.key!])}
              >
                <ActionButton type="link">{tg('button.delete')}</ActionButton>
              </Popconfirm>
            )}
          </Space>
        ),
      },
    ],
    [attr, editConfig, delConfig, allowManage, tg],
  );

  return (
    <Wrapper>
      {allowManage && !disabled && (
        <AddButton type="link" icon={<PlusOutlined />} onClick={showForm}>
          {t('form.addConfig')}
        </AddButton>
      )}
      <Table
        rowKey={attr.key}
        dataSource={value}
        columns={columns}
        size="small"
        pagination={false}
        bordered
      />
      <ModalForm
        title={t('form.editConfig')}
        visible={formVisible}
        width={SPACE_TIMES(240)}
        formProps={{
          labelAlign: 'left',
          labelCol: { offset: 1, span: 5 },
          wrapperCol: { span: 8 },
        }}
        onSave={formSave}
        onCancel={hideForm}
        afterClose={afterClose}
        footer={allowManage ? void 0 : false}
        ref={formRef}
      >
        {attr.children?.map(childAttr => (
          <ConfigComponent
            key={childAttr.name}
            attr={childAttr}
            form={formRef.current}
            sourceId={sourceId}
            testLoading={testLoading}
            schemaDataSource={schemaDataSource}
            subFormRowKey={attr.key}
            subFormRowKeyValidator={subFormRowKeyValidator}
            disabled={disabled}
            allowManage={allowManage}
            onTest={test}
          />
        ))}
      </ModalForm>
    </Wrapper>
  );
}
Example #3
Source File: RowPermissionTable.tsx    From datart with Apache License 2.0 4 votes vote down vote up
RowPermissionTable = memo(
  ({
    type,
    visible,
    editingVariable,
    loading,
    listLoading,
    selectedRowKeys,
    rowPermissionSubjects,
    onSelectedRowKeyChange,
    onRowPermissionSubjectChange,
  }: SubjectFormProps) => {
    const t = useI18NPrefix('variable');

    const checkUseDefaultValue = useCallback(
      id => e => {
        onRowPermissionSubjectChange(
          produce(rowPermissionSubjects, draft => {
            const permission = draft?.find(p => p.id === id)!;
            permission.useDefaultValue = e.target.checked;
          }),
        );
      },
      [rowPermissionSubjects, onRowPermissionSubjectChange],
    );

    const valueChange = useCallback(
      id => value => {
        onRowPermissionSubjectChange(
          produce(rowPermissionSubjects, draft => {
            const permission = draft?.find(p => p.id === id)!;
            permission.value = value;
          }),
        );
      },
      [rowPermissionSubjects, onRowPermissionSubjectChange],
    );

    const columns: TableColumnProps<RowPermissionSubject>[] = useMemo(
      () => [
        { dataIndex: 'name', title: t('name') },
        {
          title: t('useDefaultValue'),
          width: SPACE_TIMES(32),
          render: (_, record) => {
            return (
              <Checkbox
                checked={record.useDefaultValue}
                disabled={!selectedRowKeys.includes(record.id)}
                onChange={checkUseDefaultValue(record.id)}
              />
            );
          },
        },
        {
          title: t('value'),
          width: SPACE_TIMES(72),
          render: (_, record) =>
            editingVariable && (
              <DefaultValue
                type={editingVariable.valueType}
                expression={false}
                disabled={
                  !selectedRowKeys.includes(record.id) || record.useDefaultValue
                }
                value={record.value}
                onChange={valueChange(record.id)}
              />
            ),
        },
      ],
      [selectedRowKeys, editingVariable, checkUseDefaultValue, valueChange, t],
    );

    const rowClassName = useCallback(
      (record: RowPermissionSubject) => {
        return selectedRowKeys.includes(record.id) ? '' : 'disabled-row';
      },
      [selectedRowKeys],
    );

    return (
      <LoadingMask loading={loading}>
        <TableWrapper visible={visible}>
          <Table
            rowKey="id"
            size="small"
            columns={columns}
            loading={listLoading}
            dataSource={rowPermissionSubjects}
            rowClassName={rowClassName}
            rowSelection={{
              selectedRowKeys,
              onChange: onSelectedRowKeyChange,
            }}
            bordered
          />
        </TableWrapper>
      </LoadingMask>
    );
  },
)
Example #4
Source File: index.tsx    From datart with Apache License 2.0 4 votes vote down vote up
export function VariablePage() {
  useMemberSlice();
  useVariableSlice();
  const [formType, setFormType] = useState(CommonFormTypes.Add);
  const [formVisible, setFormVisible] = useState(false);
  const [editingVariable, setEditingVariable] = useState<undefined | Variable>(
    void 0,
  );
  const [rowPermissions, setRowPermissions] = useState<
    undefined | RowPermission[]
  >(void 0);
  const [rowPermissionLoading, setRowPermissionLoading] = useState(false);
  const [subjectFormVisible, setSubjectFormVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [updateRowPermissionLoading, setUpdateRowPermissionLoading] =
    useState(false);
  const dispatch = useDispatch();
  const variables = useSelector(selectVariables);
  const listLoading = useSelector(selectVariableListLoading);
  const saveLoading = useSelector(selectSaveVariableLoading);
  const deleteVariablesLoading = useSelector(selectDeleteVariablesLoading);
  const orgId = useSelector(selectOrgId);
  const t = useI18NPrefix('variable');
  const tg = useI18NPrefix('global');

  useEffect(() => {
    dispatch(getVariables(orgId));
    dispatch(getMembers(orgId));
    dispatch(getRoles(orgId));
  }, [dispatch, orgId]);

  const showAddForm = useCallback(() => {
    setFormType(CommonFormTypes.Add);
    setFormVisible(true);
  }, []);

  const hideForm = useCallback(() => {
    setFormVisible(false);
  }, []);

  const afterFormClose = useCallback(() => {
    setEditingVariable(void 0);
  }, []);

  const showEditForm = useCallback(
    id => () => {
      setEditingVariable(variables.find(v => v.id === id));
      setFormType(CommonFormTypes.Edit);
      setFormVisible(true);
    },
    [variables],
  );

  const showSubjectForm = useCallback(
    id => async () => {
      const variable = variables.find(v => v.id === id)!;
      setEditingVariable(variable);
      setSubjectFormVisible(true);

      try {
        setRowPermissionLoading(true);
        const { data } = await request<RowPermissionRaw[]>(
          `/variables/value?variableId=${id}`,
        );
        setRowPermissions(
          data.map(d => ({
            ...d,
            value: d.value && JSON.parse(d.value),
          })),
        );
      } catch (error) {
        errorHandle(error);
        throw error;
      } finally {
        setRowPermissionLoading(false);
      }
    },
    [variables],
  );

  const hideSubjectForm = useCallback(() => {
    setSubjectFormVisible(false);
  }, []);

  const del = useCallback(
    id => () => {
      dispatch(
        deleteVariable({
          ids: [id],
          resolve: () => {
            message.success(tg('operation.deleteSuccess'));
          },
        }),
      );
    },
    [dispatch, tg],
  );

  const delSelectedVariables = useCallback(() => {
    dispatch(
      deleteVariable({
        ids: selectedRowKeys as string[],
        resolve: () => {
          message.success(tg('operation.deleteSuccess'));
          setSelectedRowKeys([]);
        },
      }),
    );
  }, [dispatch, selectedRowKeys, tg]);

  const save = useCallback(
    (values: VariableFormModel) => {
      let defaultValue: any = values.defaultValue;
      if (values.valueType === VariableValueTypes.Date && !values.expression) {
        defaultValue = values.defaultValue.map(d =>
          (d as Moment).format(TIME_FORMATTER),
        );
      }

      try {
        if (defaultValue !== void 0 && defaultValue !== null) {
          defaultValue = JSON.stringify(defaultValue);
        }
      } catch (error) {
        errorHandle(error);
        throw error;
      }

      if (formType === CommonFormTypes.Add) {
        dispatch(
          addVariable({
            variable: { ...values, orgId, defaultValue },
            resolve: () => {
              hideForm();
            },
          }),
        );
      } else {
        dispatch(
          editVariable({
            variable: { ...editingVariable!, ...values, defaultValue },
            resolve: () => {
              hideForm();
              message.success(tg('operation.updateSuccess'));
            },
          }),
        );
      }
    },
    [dispatch, formType, orgId, editingVariable, hideForm, tg],
  );

  const saveRelations = useCallback(
    async (changedRowPermissions: RowPermission[]) => {
      let changedRowPermissionsRaw = changedRowPermissions.map(cr => ({
        ...cr,
        value:
          cr.value &&
          (editingVariable?.valueType === VariableValueTypes.Date
            ? cr.value.map(m => (m as Moment).format(TIME_FORMATTER))
            : cr.value),
      }));

      if (rowPermissions) {
        const { created, updated, deleted } = getDiffParams(
          [...rowPermissions],
          changedRowPermissionsRaw,
          (oe, ce) =>
            oe.subjectId === ce.subjectId && oe.variableId === ce.variableId,
          (oe, ce) =>
            oe.useDefaultValue !== ce.useDefaultValue || oe.value !== ce.value,
        );

        if (created.length > 0 || updated.length > 0 || deleted.length > 0) {
          try {
            setUpdateRowPermissionLoading(true);
            await request<null>({
              url: '/variables/rel',
              method: 'PUT',
              data: {
                relToCreate: created.map(r => ({
                  ...r,
                  value: JSON.stringify(r.value),
                })),
                relToUpdate: updated.map(r => ({
                  ...r,
                  value: JSON.stringify(r.value),
                })),
                relToDelete: deleted.map(({ id }) => id),
              },
            });
            message.success(tg('operation.updateSuccess'));
            setSubjectFormVisible(false);
          } catch (error) {
            errorHandle(error);
            throw error;
          } finally {
            setUpdateRowPermissionLoading(false);
          }
        } else {
          setSubjectFormVisible(false);
        }
      }
    },
    [rowPermissions, editingVariable, tg],
  );

  const columns: TableColumnProps<VariableViewModel>[] = useMemo(
    () => [
      { dataIndex: 'name', title: t('name') },
      { dataIndex: 'label', title: t('label') },
      {
        dataIndex: 'type',
        title: t('type'),
        render: (_, record) => (
          <Tag
            color={record.type === VariableTypes.Permission ? WARNING : INFO}
          >
            {t(`variableType.${record.type.toLowerCase()}`)}
          </Tag>
        ),
      },
      {
        dataIndex: 'valueType',
        title: t('valueType'),
        render: (_, record) =>
          t(`variableValueType.${record.valueType.toLowerCase()}`),
      },
      {
        title: tg('title.action'),
        align: 'center',
        width: 140,
        render: (_, record) => (
          <Actions>
            {record.type === VariableTypes.Permission && (
              <Tooltip title={t('related')}>
                <Button
                  type="link"
                  icon={<TeamOutlined />}
                  onClick={showSubjectForm(record.id)}
                />
              </Tooltip>
            )}
            <Tooltip title={tg('button.edit')}>
              <Button
                type="link"
                icon={<EditOutlined />}
                onClick={showEditForm(record.id)}
              />
            </Tooltip>
            <Tooltip title={tg('button.delete')}>
              <Popconfirm
                title={tg('operation.deleteConfirm')}
                onConfirm={del(record.id)}
              >
                <Button type="link" icon={<DeleteOutlined />} />
              </Popconfirm>
            </Tooltip>
          </Actions>
        ),
      },
    ],
    [del, showEditForm, showSubjectForm, t, tg],
  );

  const pagination = useMemo(
    () => ({ pageSize: 20, pageSizeOptions: ['20', '50', '100'] }),
    [],
  );

  return (
    <Wrapper>
      <Card>
        <TableHeader>
          <h3>{t('title')}</h3>
          <Toolbar>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={t('deleteAllConfirm')}
                onConfirm={delSelectedVariables}
              >
                <Button
                  icon={<DeleteOutlined />}
                  loading={deleteVariablesLoading}
                >
                  {t('deleteAll')}
                </Button>
              </Popconfirm>
            )}
            <Button
              icon={<PlusOutlined />}
              type="primary"
              onClick={showAddForm}
            >
              {tg('button.create')}
            </Button>
          </Toolbar>
        </TableHeader>
        <Table
          rowKey="id"
          size="small"
          dataSource={variables}
          columns={columns}
          loading={listLoading}
          rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
          pagination={pagination}
        />
        <VariableForm
          scope={VariableScopes.Public}
          orgId={orgId}
          editingVariable={editingVariable}
          visible={formVisible}
          title={t('public')}
          type={formType}
          confirmLoading={saveLoading}
          onSave={save}
          onCancel={hideForm}
          afterClose={afterFormClose}
          keyboard={false}
          maskClosable={false}
        />
        <SubjectForm
          scope={VariableScopes.Public}
          editingVariable={editingVariable}
          loading={rowPermissionLoading}
          rowPermissions={rowPermissions}
          visible={subjectFormVisible}
          confirmLoading={updateRowPermissionLoading}
          onSave={saveRelations}
          onCancel={hideSubjectForm}
          afterClose={afterFormClose}
          keyboard={false}
          maskClosable={false}
        />
      </Card>
    </Wrapper>
  );
}