Skip to content

Commit

Permalink
refactor(client): refactor hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
mytharcher committed May 12, 2024
1 parent fdcef61 commit 207b793
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/

import { RecursionField, connect, useField, useFieldSchema } from '@formily/react';
import { RecursionField, connect, useExpressionScope, useField, useFieldSchema } from '@formily/react';
import { differenceBy, unionBy } from 'lodash';
import cls from 'classnames';
import React, { useContext, useEffect, useState } from 'react';
Expand Down Expand Up @@ -84,8 +84,9 @@ const useTableSelectorProps = () => {
function FileSelector(props) {
const { disabled, multiple, value, onChange, onSelect, quickUpload, selectFile } = props;
const { wrapSSR, hashId, componentCls: prefixCls } = useStyles();
const { scope } = useSchemaOptionsContext();
const { useFileCollectionStorageRules } = useExpressionScope();
const { t } = useTranslation();
const rules = useFileCollectionStorageRules();
// 兼容旧版本
const showSelectButton = selectFile === undefined && quickUpload === undefined;

Expand Down Expand Up @@ -119,7 +120,7 @@ function FileSelector(props) {
multiple={multiple}
// onRemove={handleRemove}
onChange={onChange}
useRules={scope.useFileCollectionStorageRules}
rules={rules}
/>
) : null}
{selectFile && (multiple || !value) ? (
Expand Down
42 changes: 20 additions & 22 deletions packages/core/client/src/schema-component/antd/upload/Upload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,11 @@ export const Upload: ComposedUpload = connect(

Upload.ReadPretty = ReadPretty;

function useSizeHint(size: number = DEFAULT_MAX_FILE_SIZE) {
function useSizeHint(size: number) {
const s = size ?? DEFAULT_MAX_FILE_SIZE;
const { t, i18n } = useTranslation();
const sizeString = filesize(size, { base: 2, standard: 'jedec', locale: i18n.language });
return size !== 0 ? t('File size should not exceed {{size}}.', { size: sizeString }) : '';
const sizeString = filesize(s, { base: 2, standard: 'jedec', locale: i18n.language });
return s !== 0 ? t('File size should not exceed {{size}}.', { size: sizeString }) : '';
}

function AttachmentListItem(props) {
Expand Down Expand Up @@ -342,11 +343,7 @@ export function AttachmentList(props) {
);
}

function useDefaultRules(props) {
return props.rules;
}

export function Uploader({ useRules = useDefaultRules, rules: propsRules, ...props }: UploadProps) {
export function Uploader({ rules, ...props }: UploadProps) {
const { disabled, multiple, value, onChange } = props;
const [pendingList, setPendingList] = useState<any[]>([]);
const { t } = useTranslation();
Expand All @@ -355,7 +352,6 @@ export function Uploader({ useRules = useDefaultRules, rules: propsRules, ...pro

const uploadProps = useUploadProps(props);

const rules = useRules({ rules: propsRules, ...props });
const beforeUpload = useBeforeUpload(rules);

useEffect(() => {
Expand Down Expand Up @@ -446,18 +442,21 @@ export function Uploader({ useRules = useDefaultRules, rules: propsRules, ...pro
);
}

Upload.Attachment = connect((props: UploadProps) => {
const { wrapSSR, hashId, componentCls: prefixCls } = useStyles();
Upload.Attachment = withDynamicSchemaProps(
connect((props: UploadProps) => {
const { wrapSSR, hashId, componentCls: prefixCls } = useStyles();

return wrapSSR(
<div className={cls(`${prefixCls}-wrapper`, `${prefixCls}-picture-card-wrapper`, 'nb-upload', hashId)}>
<div className={cls(`${prefixCls}-list`, `${prefixCls}-list-picture-card`)}>
<AttachmentList {...props} />
<Uploader {...props} />
</div>
</div>,
);
}, mapReadPretty(ReadPretty.File));
return wrapSSR(
<div className={cls(`${prefixCls}-wrapper`, `${prefixCls}-picture-card-wrapper`, 'nb-upload', hashId)}>
<div className={cls(`${prefixCls}-list`, `${prefixCls}-list-picture-card`)}>
<AttachmentList {...props} />
<Uploader {...props} />
</div>
</div>,
);
}, mapReadPretty(ReadPretty.File)),
{ displayName: 'Upload.Attachment' },
);

Upload.Dragger = connect(
(props: DraggerProps) => {
Expand Down Expand Up @@ -485,7 +484,7 @@ Upload.Dragger = connect(

Upload.DraggerV2 = withDynamicSchemaProps(
connect(
({ rules: propsRules, useRules = useDefaultRules, ...props }: DraggerV2Props) => {
({ rules, ...props }: DraggerV2Props) => {
const { t } = useTranslation();
const defaultTitle = t('Click or drag file to this area to upload');

Expand All @@ -495,7 +494,6 @@ Upload.DraggerV2 = withDynamicSchemaProps(
const [loading, setLoading] = useState(false);
const { wrapSSR, hashId, componentCls: prefixCls } = useStyles();

const rules = useRules({ rules: propsRules });
const beforeUpload = useBeforeUpload(rules);
const { size, mimetype: accept } = rules ?? {};
const sizeHint = useSizeHint(size);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,12 @@ export const toValue = (fileList: any) => {
};

const Rules: Record<string, RuleFunction> = {
size(file, options: number = DEFAULT_MAX_FILE_SIZE): null | string {
if (options === 0) {
size(file, options: number): null | string {
const size = options ?? DEFAULT_MAX_FILE_SIZE;
if (size === 0) {
return null;
}
return file.size <= options ? null : 'File size exceeds the limit';
return file.size <= size ? null : 'File size exceeds the limit';
},
mimetype(file, options: string | string[] = '*'): null | string {
const pattern = options.toString().trim();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ export type UploadProps = Omit<AntdUploadProps, 'onChange'> & {
value?: any;
size?: string;
rules?: PropsRules;
useRules?(rules: PropsRules): PropsRules;
};

export type DraggerProps = Omit<AntdDraggerProps, 'onChange'> & {
Expand All @@ -34,7 +33,6 @@ export type DraggerV2Props = Omit<AntdDraggerProps, 'onChange'> & {
serviceErrorMessage?: string;
title?: string;
rules?: PropsRules;
useRules?(rules: PropsRules): PropsRules;
children?: React.ReactNode;
/** @deprecated */
useProps?: () => any;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ const schema: ISchema = {
'x-component-props': {
action: 'attachments:create',
multiple: false,
useRules: '{{useCollectionFieldStorageRules}}',
// accept: 'jpg,png'
},
'x-use-component-props': 'useCollectionFieldStorageRules',
},
enabledLanguages: {
type: 'array',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/

import { useCollectionField, useCollectionManager, useRequest } from '@nocobase/client';

export function useStorageRules(name = '') {
Expand All @@ -12,12 +21,13 @@ export function useStorageRules(name = '') {
return (!loading && data?.data) || null;
}

export function useCollectionFieldStorageRules(props) {
export function useCollectionFieldStorageRules() {
const field = useCollectionField();
return useStorageRules(field?.storage);
const rules = useStorageRules(field?.storage);
return { rules };
}

export function useFileCollectionStorageRules(props) {
export function useFileCollectionStorageRules() {
const field = useCollectionField();
const collectionManager = useCollectionManager();
const collection = collectionManager.getCollection(field?.target);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const useUploadFiles = () => {
const { props: blockProps } = useBlockRequestContext();
const collection = useCollection();
const sourceId = useSourceIdFromParentRecord();
const rules = useFileCollectionStorageRules();
const action = useMemo(() => {
let action = `${collection.name}:create`;
if (blockProps?.association) {
Expand Down Expand Up @@ -60,6 +61,6 @@ export const useUploadFiles = () => {
setVisible(false);
}
},
useRules: useFileCollectionStorageRules,
rules,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ export class AttachmentFieldInterface extends CollectionFieldInterface {
type: 'array',
// title,
'x-component': 'Upload.Attachment',
'x-component-props': {
useRules: '{{useCollectionFieldStorageRules}}',
},
'x-use-component-props': 'useCollectionFieldStorageRules',
},
};
availableTypes = ['belongsToMany'];
Expand All @@ -45,7 +43,7 @@ export class AttachmentFieldInterface extends CollectionFieldInterface {
field.storage ? `?attachmentField=${field.collectionName}.${field.name}` : ''
}`;

schema['x-component-props'].useRules = '{{useCollectionFieldStorageRules}}';
schema['x-use-component-props'] = 'useCollectionFieldStorageRules';
}
initialize(values: any) {
if (!values.through) {
Expand Down

0 comments on commit 207b793

Please sign in to comment.