@cloud-ru/ds-uikit-product-upload-files 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/LICENSE +201 -0
  3. package/README.md +238 -0
  4. package/dist/cjs/UploadFiles.d.ts +20 -0
  5. package/dist/cjs/UploadFiles.js +93 -0
  6. package/dist/cjs/components/Attachments/Attachments.d.ts +10 -0
  7. package/dist/cjs/components/Attachments/Attachments.js +18 -0
  8. package/dist/cjs/components/Attachments/index.d.ts +2 -0
  9. package/dist/cjs/components/Attachments/index.js +5 -0
  10. package/dist/cjs/components/UploadFilesDropZone/UploadFilesDropZone.d.ts +2 -0
  11. package/dist/cjs/components/UploadFilesDropZone/UploadFilesDropZone.js +14 -0
  12. package/dist/cjs/components/UploadFilesDropZone/index.d.ts +1 -0
  13. package/dist/cjs/components/UploadFilesDropZone/index.js +5 -0
  14. package/dist/cjs/components/index.d.ts +2 -0
  15. package/dist/cjs/components/index.js +18 -0
  16. package/dist/cjs/constants.d.ts +18 -0
  17. package/dist/cjs/constants.js +22 -0
  18. package/dist/cjs/hooks/index.d.ts +2 -0
  19. package/dist/cjs/hooks/index.js +5 -0
  20. package/dist/cjs/hooks/useUploadFilesController.d.ts +30 -0
  21. package/dist/cjs/hooks/useUploadFilesController.js +116 -0
  22. package/dist/cjs/index.d.ts +8 -0
  23. package/dist/cjs/index.js +31 -0
  24. package/dist/cjs/locale/index.d.ts +87 -0
  25. package/dist/cjs/locale/index.js +48 -0
  26. package/dist/cjs/package.json +3 -0
  27. package/dist/cjs/style.css +42 -0
  28. package/dist/cjs/styles.module.css +42 -0
  29. package/dist/cjs/types.d.ts +72 -0
  30. package/dist/cjs/types.js +2 -0
  31. package/dist/cjs/utils.d.ts +15 -0
  32. package/dist/cjs/utils.js +67 -0
  33. package/dist/esm/UploadFiles.d.ts +20 -0
  34. package/dist/esm/UploadFiles.js +87 -0
  35. package/dist/esm/components/Attachments/Attachments.d.ts +10 -0
  36. package/dist/esm/components/Attachments/Attachments.js +12 -0
  37. package/dist/esm/components/Attachments/index.d.ts +2 -0
  38. package/dist/esm/components/Attachments/index.js +1 -0
  39. package/dist/esm/components/UploadFilesDropZone/UploadFilesDropZone.d.ts +2 -0
  40. package/dist/esm/components/UploadFilesDropZone/UploadFilesDropZone.js +8 -0
  41. package/dist/esm/components/UploadFilesDropZone/index.d.ts +1 -0
  42. package/dist/esm/components/UploadFilesDropZone/index.js +1 -0
  43. package/dist/esm/components/index.d.ts +2 -0
  44. package/dist/esm/components/index.js +2 -0
  45. package/dist/esm/constants.d.ts +18 -0
  46. package/dist/esm/constants.js +19 -0
  47. package/dist/esm/hooks/index.d.ts +2 -0
  48. package/dist/esm/hooks/index.js +1 -0
  49. package/dist/esm/hooks/useUploadFilesController.d.ts +30 -0
  50. package/dist/esm/hooks/useUploadFilesController.js +113 -0
  51. package/dist/esm/index.d.ts +8 -0
  52. package/dist/esm/index.js +7 -0
  53. package/dist/esm/locale/index.d.ts +87 -0
  54. package/dist/esm/locale/index.js +45 -0
  55. package/dist/esm/style.css +42 -0
  56. package/dist/esm/styles.module.css +42 -0
  57. package/dist/esm/types.d.ts +72 -0
  58. package/dist/esm/types.js +1 -0
  59. package/dist/esm/utils.d.ts +15 -0
  60. package/dist/esm/utils.js +60 -0
  61. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  62. package/dist/tsconfig.esm.tsbuildinfo +1 -0
  63. package/package.json +56 -0
  64. package/src/UploadFiles.tsx +212 -0
  65. package/src/components/Attachments/Attachments.tsx +44 -0
  66. package/src/components/Attachments/index.ts +2 -0
  67. package/src/components/UploadFilesDropZone/UploadFilesDropZone.tsx +27 -0
  68. package/src/components/UploadFilesDropZone/index.ts +1 -0
  69. package/src/components/index.ts +2 -0
  70. package/src/constants.ts +27 -0
  71. package/src/hooks/index.ts +7 -0
  72. package/src/hooks/useUploadFilesController.ts +199 -0
  73. package/src/index.ts +14 -0
  74. package/src/locale/index.ts +49 -0
  75. package/src/styles.module.scss +52 -0
  76. package/src/types.ts +78 -0
  77. package/src/utils.ts +84 -0
@@ -0,0 +1,20 @@
1
+ export declare const UploadFiles: import("react").ForwardRefExoticComponent<{
2
+ 'data-test-id'?: string;
3
+ } & import("react").AriaAttributes & {
4
+ label?: string;
5
+ hint?: import("react").ReactNode;
6
+ optional?: boolean;
7
+ disabled?: boolean;
8
+ value?: import("./types").UploadFileItem<unknown>[] | undefined;
9
+ defaultValue?: import("./types").UploadFileItem<unknown>[] | undefined;
10
+ onChange?(items: import("./types").UploadFileItem<unknown>[]): void;
11
+ name?: string;
12
+ onBlur?: import("react").FocusEventHandler<HTMLDivElement>;
13
+ error?: string;
14
+ upload: import("./types").UploadFn<unknown>;
15
+ className?: string;
16
+ accept?: import("./types").UploadFilesAcceptItem[];
17
+ maxFiles?: number;
18
+ maxSize?: number;
19
+ attachmentClassname?: string;
20
+ } & import("react").RefAttributes<HTMLDivElement>>;
@@ -0,0 +1,87 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { buildAcceptAttribute, Dropzone } from '@cloud-ru/ds-dropzone';
3
+ import { FieldDecorator, SIZE } from '@cloud-ru/ds-field-decorator';
4
+ import { extractSupportProps, useValueControl } from '@cloud-ru/ds-utils';
5
+ import cn from 'classnames';
6
+ import mergeRefs from 'merge-refs';
7
+ import { forwardRef, useMemo, useRef } from 'react';
8
+ import { Attachments, UploadFilesDropZone } from './components/index.js';
9
+ import { DEFAULT_ACCEPT, DEFAULT_MAX_FILES, DEFAULT_MAX_SIZE, SUMMARY_ERROR_TYPE, TEST_IDS, UPLOAD_STATUS, } from './constants.js';
10
+ import { useUploadFilesController } from './hooks/index.js';
11
+ import { uploadFilesLocale } from './locale/index.js';
12
+ import styles from './styles.module.css';
13
+ import { formatFileSize, joinWithConjunction } from './utils.js';
14
+ export const UploadFiles = forwardRef(function UploadFiles({ label, hint, optional = true, disabled = false, value: valueProp, defaultValue, onChange: onChangeProp, name, onBlur, error: formError, upload, accept: acceptProp = DEFAULT_ACCEPT, maxFiles = DEFAULT_MAX_FILES, maxSize = DEFAULT_MAX_SIZE, className, attachmentClassname, ...rest }, ref) {
15
+ const { t } = uploadFilesLocale.useTranslations();
16
+ const localRef = useRef(null);
17
+ const rootRef = mergeRefs(ref, localRef);
18
+ // `*` означает «любой файл» — не передаём его в accept, чтобы не ограничивать
19
+ // ни native picker, ни валидацию форматов в partitionFiles.
20
+ const accept = useMemo(() => acceptProp
21
+ .map(item => item.extention)
22
+ .filter(extension => extension && extension !== '*')
23
+ .join(','), [acceptProp]);
24
+ const displayExtensions = useMemo(() => acceptProp.map(item => item.displayExtension).filter((extension) => Boolean(extension)), [acceptProp]);
25
+ // Перечисление через запятую — для описания в дропзоне
26
+ const formatsList = useMemo(() => displayExtensions.join(', '), [displayExtensions]);
27
+ // Перечисление с союзом «и» — только для текста ошибки формата
28
+ const formatsConjunctionList = useMemo(() => joinWithConjunction(displayExtensions, t('formatsConjunction')), [displayExtensions, t]);
29
+ const units = useMemo(() => ({
30
+ b: t('units.b'),
31
+ kb: t('units.kb'),
32
+ mb: t('units.mb'),
33
+ gb: t('units.gb'),
34
+ }), [t]);
35
+ const [value = [], onChange] = useValueControl({
36
+ value: valueProp,
37
+ defaultValue: defaultValue ?? [],
38
+ onChange: onChangeProp,
39
+ });
40
+ const maxSizeLabel = useMemo(() => (typeof maxSize === 'number' ? formatFileSize(maxSize, units) : ''), [maxSize, units]);
41
+ const messages = useMemo(() => ({
42
+ fileFormatError: t('errorFileFormat', { formats: formatsConjunctionList }),
43
+ fileSizeError: t('errorFileSize', { size: maxSizeLabel }),
44
+ fileLimitError: typeof maxFiles === 'number' ? t('errorFileLimit', { count: maxFiles }) : '',
45
+ uploadError: t('uploadError'),
46
+ }), [t, formatsConjunctionList, maxSizeLabel, maxFiles]);
47
+ const { items, summaryError, summaryErrorType, handleFilesUpload, handleFilesReject, handleDelete } = useUploadFilesController({
48
+ value,
49
+ onChange,
50
+ upload,
51
+ accept,
52
+ maxFiles,
53
+ maxSize,
54
+ disabled,
55
+ messages,
56
+ });
57
+ const dropzoneDescription = useMemo(() => {
58
+ const count = maxFiles ?? '';
59
+ if (!formatsList && !count && !maxSizeLabel) {
60
+ return undefined;
61
+ }
62
+ return t(formatsList ? 'dropzoneDescription' : 'dropzoneDescriptionNoFormats', {
63
+ formats: formatsList,
64
+ count: String(count),
65
+ size: maxSizeLabel,
66
+ });
67
+ }, [formatsList, maxFiles, maxSizeLabel, t]);
68
+ const displayedError = useMemo(() => {
69
+ if (formError) {
70
+ return formError;
71
+ }
72
+ if (summaryErrorType === SUMMARY_ERROR_TYPE.FileLimit) {
73
+ return summaryError;
74
+ }
75
+ if (summaryErrorType === SUMMARY_ERROR_TYPE.SomeFilesNotUploaded) {
76
+ return t('errorSomeFilesNotUploaded');
77
+ }
78
+ return undefined;
79
+ }, [formError, summaryError, summaryErrorType, t]);
80
+ const formValue = useMemo(() => JSON.stringify(items.filter(item => item.status === UPLOAD_STATUS.Success).map(item => item.result)), [items]);
81
+ const acceptAttribute = buildAcceptAttribute(accept);
82
+ const hasError = Boolean(displayedError);
83
+ const isOverLimit = typeof maxFiles === 'number' && value.length > maxFiles;
84
+ const labelTooltip = useMemo(() => (hint ? { tip: hint } : undefined), [hint]);
85
+ const length = useMemo(() => (isOverLimit ? { current: value.length, max: maxFiles } : undefined), [isOverLimit, value.length, maxFiles]);
86
+ return (_jsxs("div", { ...extractSupportProps(rest), ref: rootRef, role: 'group', className: cn(styles.root, className), "data-test-id": TEST_IDS.root, onBlur: onBlur, children: [name && _jsx("input", { type: 'hidden', name: name, value: formValue, readOnly: true }), _jsx(FieldDecorator, { className: styles.dropzoneSection, label: label, labelTooltip: labelTooltip, caption: optional ? t('optional') : undefined, error: displayedError, showHintIcon: hasError, length: length, size: SIZE.S, disabled: disabled, children: _jsx(Dropzone, { onFilesUpload: handleFilesUpload, onFilesReject: handleFilesReject, disabled: disabled, accept: acceptAttribute, "aria-invalid": hasError || undefined, children: _jsx(UploadFilesDropZone, { title: t('dropzoneTitle'), description: dropzoneDescription, buttonLabel: t('dropzoneButton') }) }) }), _jsx(Attachments, { className: attachmentClassname, items: items, accept: acceptProp, disabled: disabled, units: units, onDelete: handleDelete })] }));
87
+ });
@@ -0,0 +1,10 @@
1
+ import { FileSizeUnits, UploadFileItem, UploadFilesAcceptItem } from '../../types.js';
2
+ export type AttachmentsProps<TResult> = {
3
+ items: UploadFileItem<TResult>[];
4
+ accept: UploadFilesAcceptItem[];
5
+ disabled?: boolean;
6
+ units: FileSizeUnits;
7
+ onDelete: (id: string) => void;
8
+ className?: string;
9
+ };
10
+ export declare function Attachments<TResult>({ items, accept, disabled, units, onDelete, className }: AttachmentsProps<TResult>): import("react/jsx-runtime").JSX.Element | null;
@@ -0,0 +1,12 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Attachment, SIZE } from '@cloud-ru/ds-attachment';
3
+ import cn from 'classnames';
4
+ import { TEST_IDS, UPLOAD_STATUS } from '../../constants.js';
5
+ import styles from '../../styles.module.css';
6
+ import { formatFileDescription, resolveFileIcon } from '../../utils.js';
7
+ export function Attachments({ items, accept, disabled, units, onDelete, className }) {
8
+ if (!items.length) {
9
+ return null;
10
+ }
11
+ return (_jsx("div", { className: styles.attachments, role: 'list', "aria-live": 'polite', "aria-relevant": 'additions text', children: items.map(item => (_jsx("div", { role: 'listitem', className: styles.attachmentItem, children: _jsx(Attachment, { file: item.file, title: undefined, description: formatFileDescription(item.file, units), icon: resolveFileIcon(item.file, accept), loading: item.status === UPLOAD_STATUS.Uploading, error: item.error, disabled: disabled, size: SIZE.S, onDelete: () => onDelete(item.id), "data-test-id": TEST_IDS.attachment, className: cn(styles.attachment, className) }) }, item.id))) }));
12
+ }
@@ -0,0 +1,2 @@
1
+ export { Attachments } from './Attachments.js';
2
+ export type { AttachmentsProps } from './Attachments.js';
@@ -0,0 +1 @@
1
+ export { Attachments } from './Attachments.js';
@@ -0,0 +1,2 @@
1
+ import { UploadFilesDropZoneProps } from '../../types.js';
2
+ export declare function UploadFilesDropZone({ title, description, buttonLabel }: UploadFilesDropZoneProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,8 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { APPEARANCE, Button, SIZE as BUTTON_SIZE, VIEW } from '@cloud-ru/ds-button';
3
+ import { Typography } from '@cloud-ru/ds-typography';
4
+ import { TEST_IDS } from '../../constants.js';
5
+ import styles from '../../styles.module.css';
6
+ export function UploadFilesDropZone({ title, description, buttonLabel }) {
7
+ return (_jsxs("div", { className: styles.dropzoneContent, "data-test-id": TEST_IDS.dropzone, children: [_jsx(Typography, { size: 's', as: 'span', variant: 'body', weight: 'regular', children: title }), _jsx(Button, { label: buttonLabel, appearance: APPEARANCE.Neutral, view: VIEW.Outline, size: BUTTON_SIZE.S, tabIndex: -1, as: 'div' }), _jsx(Typography, { className: styles.dropzoneDescription, size: 'm', as: 'span', variant: 'body', weight: 'regular', children: description })] }));
8
+ }
@@ -0,0 +1 @@
1
+ export { UploadFilesDropZone } from './UploadFilesDropZone.js';
@@ -0,0 +1 @@
1
+ export { UploadFilesDropZone } from './UploadFilesDropZone.js';
@@ -0,0 +1,2 @@
1
+ export * from './UploadFilesDropZone/index.js';
2
+ export * from './Attachments/index.js';
@@ -0,0 +1,2 @@
1
+ export * from './UploadFilesDropZone/index.js';
2
+ export * from './Attachments/index.js';
@@ -0,0 +1,18 @@
1
+ import type { UploadFilesAcceptItem } from './types.js';
2
+ export declare const UPLOAD_STATUS: {
3
+ readonly Uploading: "uploading";
4
+ readonly Success: "success";
5
+ readonly Error: "error";
6
+ };
7
+ export declare const SUMMARY_ERROR_TYPE: {
8
+ readonly FileLimit: "fileLimit";
9
+ readonly SomeFilesNotUploaded: "someFilesNotUploaded";
10
+ };
11
+ export declare const DEFAULT_MAX_FILES = 3;
12
+ export declare const DEFAULT_MAX_SIZE: number;
13
+ export declare const DEFAULT_ACCEPT: UploadFilesAcceptItem[];
14
+ export declare const TEST_IDS: {
15
+ readonly root: "upload-files";
16
+ readonly dropzone: "upload-files__dropzone";
17
+ readonly attachment: "upload-files__attachment";
18
+ };
@@ -0,0 +1,19 @@
1
+ export const UPLOAD_STATUS = {
2
+ Uploading: 'uploading',
3
+ Success: 'success',
4
+ Error: 'error',
5
+ };
6
+ export const SUMMARY_ERROR_TYPE = {
7
+ FileLimit: 'fileLimit',
8
+ SomeFilesNotUploaded: 'someFilesNotUploaded',
9
+ };
10
+ export const DEFAULT_MAX_FILES = 3;
11
+ export const DEFAULT_MAX_SIZE = 5 * 1024 * 1024;
12
+ // `*` — любой файл по умолчанию: без иконок и отображаемых имён форматов.
13
+ export const DEFAULT_ACCEPT = [{ extention: '*' }];
14
+ const PREFIX = 'upload-files';
15
+ export const TEST_IDS = {
16
+ root: PREFIX,
17
+ dropzone: `${PREFIX}__dropzone`,
18
+ attachment: `${PREFIX}__attachment`,
19
+ };
@@ -0,0 +1,2 @@
1
+ export { useUploadFilesController } from './useUploadFilesController.js';
2
+ export type { SummaryErrorType, UploadFilesMessages, UseUploadFilesControllerOptions, UseUploadFilesControllerResult, } from './useUploadFilesController.js';
@@ -0,0 +1 @@
1
+ export { useUploadFilesController } from './useUploadFilesController.js';
@@ -0,0 +1,30 @@
1
+ import { FileRejection } from '@cloud-ru/ds-dropzone';
2
+ import { SUMMARY_ERROR_TYPE } from '../constants.js';
3
+ import { UploadFileItem, UploadFn } from '../types.js';
4
+ export type SummaryErrorType = (typeof SUMMARY_ERROR_TYPE)[keyof typeof SUMMARY_ERROR_TYPE] | null;
5
+ /** Готовые локализованные тексты ошибок для контроллера */
6
+ export type UploadFilesMessages = {
7
+ fileFormatError: string;
8
+ fileSizeError: string;
9
+ fileLimitError: string;
10
+ uploadError: string;
11
+ };
12
+ export type UseUploadFilesControllerOptions<TResult> = {
13
+ value: UploadFileItem<TResult>[];
14
+ onChange: (items: UploadFileItem<TResult>[]) => void;
15
+ upload: UploadFn<TResult>;
16
+ accept?: string;
17
+ maxFiles?: number;
18
+ maxSize?: number;
19
+ disabled?: boolean;
20
+ messages: UploadFilesMessages;
21
+ };
22
+ export type UseUploadFilesControllerResult<TResult> = {
23
+ items: UploadFileItem<TResult>[];
24
+ summaryError: string | undefined;
25
+ summaryErrorType: SummaryErrorType;
26
+ handleFilesUpload: (files: File[]) => void;
27
+ handleFilesReject: (rejections: FileRejection[]) => void;
28
+ handleDelete: (id: string) => void;
29
+ };
30
+ export declare function useUploadFilesController<TResult>({ value, onChange, upload, accept, maxFiles, maxSize, disabled, messages, }: UseUploadFilesControllerOptions<TResult>): UseUploadFilesControllerResult<TResult>;
@@ -0,0 +1,113 @@
1
+ import { FILE_REJECTION_REASON, partitionFiles } from '@cloud-ru/ds-dropzone';
2
+ import { useCallback, useEffect, useRef } from 'react';
3
+ import { SUMMARY_ERROR_TYPE, UPLOAD_STATUS } from '../constants.js';
4
+ import { makeId } from '../utils.js';
5
+ export function useUploadFilesController({ value, onChange, upload, accept, maxFiles, maxSize, disabled, messages, }) {
6
+ const abortControllersRef = useRef(new Map());
7
+ const valueRef = useRef(value);
8
+ valueRef.current = value;
9
+ const onChangeRef = useRef(onChange);
10
+ onChangeRef.current = onChange;
11
+ const uploadRef = useRef(upload);
12
+ uploadRef.current = upload;
13
+ useEffect(() => {
14
+ const controllers = abortControllersRef.current;
15
+ return () => {
16
+ controllers.forEach(controller => controller.abort());
17
+ controllers.clear();
18
+ };
19
+ }, []);
20
+ const updateItems = useCallback((updater) => {
21
+ // Синхронно обновляем ref, чтобы параллельные загрузки, завершившиеся до
22
+ // следующего ре-рендера, строили обновление на актуальном состоянии, а не
23
+ // на устаревшем value — иначе последний onChange затирает остальные.
24
+ const next = updater(valueRef.current);
25
+ valueRef.current = next;
26
+ onChangeRef.current(next);
27
+ }, []);
28
+ const startUpload = useCallback((item) => {
29
+ const controller = new AbortController();
30
+ abortControllersRef.current.set(item.id, controller);
31
+ uploadRef
32
+ .current(item.file, { signal: controller.signal })
33
+ .then(result => {
34
+ abortControllersRef.current.delete(item.id);
35
+ updateItems(prev => prev.map(current => current.id === item.id
36
+ ? { ...current, status: UPLOAD_STATUS.Success, result, progress: 100, error: undefined }
37
+ : current));
38
+ })
39
+ .catch(() => {
40
+ abortControllersRef.current.delete(item.id);
41
+ if (controller.signal.aborted) {
42
+ return;
43
+ }
44
+ updateItems(prev => prev.map(current => current.id === item.id
45
+ ? { ...current, status: UPLOAD_STATUS.Error, error: messages.uploadError }
46
+ : current));
47
+ });
48
+ }, [messages, updateItems]);
49
+ const handleFilesUpload = useCallback((files) => {
50
+ if (disabled || !files.length) {
51
+ return;
52
+ }
53
+ const { accepted, rejected } = partitionFiles(files, { accept, maxSize });
54
+ const rejectedItems = rejected.map(({ file, reason }) => ({
55
+ id: makeId(),
56
+ file,
57
+ status: UPLOAD_STATUS.Error,
58
+ error: reason === FILE_REJECTION_REASON.MaxSize ? messages.fileSizeError : messages.fileFormatError,
59
+ }));
60
+ const acceptedItems = accepted.map(file => ({
61
+ id: makeId(),
62
+ file,
63
+ status: UPLOAD_STATUS.Uploading,
64
+ }));
65
+ const next = [...valueRef.current, ...rejectedItems, ...acceptedItems];
66
+ valueRef.current = next;
67
+ onChangeRef.current(next);
68
+ acceptedItems.forEach(startUpload);
69
+ }, [accept, disabled, maxSize, messages, startUpload]);
70
+ // Отклонённые валидацией файлы (формат/размер) показываем в списке как error-вложения. Причина
71
+ // из `FileRejection` определяет текст: превышение размера vs недопустимый формат. Файлы не грузятся.
72
+ const handleFilesReject = useCallback((rejections) => {
73
+ if (disabled || !rejections.length) {
74
+ return;
75
+ }
76
+ const rejectedItems = rejections.map(({ file, reason }) => ({
77
+ id: makeId(),
78
+ file,
79
+ status: UPLOAD_STATUS.Error,
80
+ error: reason === FILE_REJECTION_REASON.MaxSize ? messages.fileSizeError : messages.fileFormatError,
81
+ }));
82
+ const next = [...valueRef.current, ...rejectedItems];
83
+ valueRef.current = next;
84
+ onChangeRef.current(next);
85
+ }, [disabled, messages]);
86
+ const handleDelete = useCallback((id) => {
87
+ const controller = abortControllersRef.current.get(id);
88
+ if (controller) {
89
+ controller.abort();
90
+ abortControllersRef.current.delete(id);
91
+ }
92
+ updateItems(prev => prev.filter(item => item.id !== id));
93
+ }, [updateItems]);
94
+ const hasItemErrors = value.some(item => item.status === UPLOAD_STATUS.Error || Boolean(item.error));
95
+ const isOverLimit = typeof maxFiles === 'number' && value.length > maxFiles;
96
+ let summaryError;
97
+ let summaryErrorType = null;
98
+ if (isOverLimit) {
99
+ summaryError = messages.fileLimitError;
100
+ summaryErrorType = SUMMARY_ERROR_TYPE.FileLimit;
101
+ }
102
+ else if (hasItemErrors) {
103
+ summaryErrorType = SUMMARY_ERROR_TYPE.SomeFilesNotUploaded;
104
+ }
105
+ return {
106
+ items: value,
107
+ summaryError,
108
+ summaryErrorType,
109
+ handleFilesUpload,
110
+ handleFilesReject,
111
+ handleDelete,
112
+ };
113
+ }
@@ -0,0 +1,8 @@
1
+ export { buildAcceptAttribute } from '@cloud-ru/ds-dropzone';
2
+ export { UploadFiles } from './UploadFiles.js';
3
+ export * from './constants.js';
4
+ export * from './types.js';
5
+ export { formatFileSize, formatFileDescription, joinWithConjunction, makeId } from './utils.js';
6
+ export { useUploadFilesController } from './hooks/index.js';
7
+ export type { SummaryErrorType, UploadFilesMessages, UseUploadFilesControllerOptions, UseUploadFilesControllerResult, } from './hooks/index.js';
8
+ export * from './locale/index.js';
@@ -0,0 +1,7 @@
1
+ export { buildAcceptAttribute } from '@cloud-ru/ds-dropzone';
2
+ export { UploadFiles } from './UploadFiles.js';
3
+ export * from './constants.js';
4
+ export * from './types.js';
5
+ export { formatFileSize, formatFileDescription, joinWithConjunction, makeId } from './utils.js';
6
+ export { useUploadFilesController } from './hooks/index.js';
7
+ export * from './locale/index.js';
@@ -0,0 +1,87 @@
1
+ declare const UPLOAD_FILES_MESSAGES: {
2
+ readonly 'en-GB': {
3
+ readonly optional: "Optional";
4
+ readonly dropzoneTitle: "Drag a file here or click";
5
+ readonly dropzoneButton: "Select file";
6
+ readonly dropzoneDescription: "{{formats}} no more than {{count}} files up to {{size}}";
7
+ readonly dropzoneDescriptionNoFormats: "No more than {{count}} files up to {{size}}";
8
+ readonly errorRequired: "Required field";
9
+ readonly errorSomeFilesNotUploaded: "Some files were not uploaded";
10
+ readonly errorFileLimit: "You can upload no more than {{count}} files";
11
+ readonly errorFileFormat: "Only {{formats}} are supported";
12
+ readonly errorFileSize: "File size must not exceed {{size}}";
13
+ readonly formatsConjunction: "and";
14
+ readonly uploadError: "Upload failed";
15
+ readonly units: {
16
+ readonly b: "B";
17
+ readonly kb: "KB";
18
+ readonly mb: "MB";
19
+ readonly gb: "GB";
20
+ };
21
+ };
22
+ readonly 'ru-RU': {
23
+ readonly optional: "Опционально";
24
+ readonly dropzoneTitle: "Перетащите файл или нажмите";
25
+ readonly dropzoneButton: "Выбрать файл";
26
+ readonly dropzoneDescription: "{{formats}} не более {{count}} файлов до {{size}}";
27
+ readonly dropzoneDescriptionNoFormats: "Не более {{count}} файлов до {{size}}";
28
+ readonly errorRequired: "Обязательное поле";
29
+ readonly errorSomeFilesNotUploaded: "Некоторые файлы не загружены";
30
+ readonly errorFileLimit: "Можно загрузить не более {{count}} файлов";
31
+ readonly errorFileFormat: "Поддерживаются только {{formats}}";
32
+ readonly errorFileSize: "Размер файла превышает {{size}}";
33
+ readonly formatsConjunction: "и";
34
+ readonly uploadError: "Ошибка загрузки";
35
+ readonly units: {
36
+ readonly b: "Б";
37
+ readonly kb: "Кб";
38
+ readonly mb: "Мб";
39
+ readonly gb: "Гб";
40
+ };
41
+ };
42
+ };
43
+ export type UploadFilesMessages = (typeof UPLOAD_FILES_MESSAGES)['en-GB'];
44
+ /** locale компонента UploadFiles: `uploadFilesLocale.useTranslations()` в коде, `.extend(...)` в сервисе. */
45
+ export declare const uploadFilesLocale: import("@cloud-ru/ds-locale").DefinedLocale<{
46
+ readonly 'en-GB': {
47
+ readonly optional: "Optional";
48
+ readonly dropzoneTitle: "Drag a file here or click";
49
+ readonly dropzoneButton: "Select file";
50
+ readonly dropzoneDescription: "{{formats}} no more than {{count}} files up to {{size}}";
51
+ readonly dropzoneDescriptionNoFormats: "No more than {{count}} files up to {{size}}";
52
+ readonly errorRequired: "Required field";
53
+ readonly errorSomeFilesNotUploaded: "Some files were not uploaded";
54
+ readonly errorFileLimit: "You can upload no more than {{count}} files";
55
+ readonly errorFileFormat: "Only {{formats}} are supported";
56
+ readonly errorFileSize: "File size must not exceed {{size}}";
57
+ readonly formatsConjunction: "and";
58
+ readonly uploadError: "Upload failed";
59
+ readonly units: {
60
+ readonly b: "B";
61
+ readonly kb: "KB";
62
+ readonly mb: "MB";
63
+ readonly gb: "GB";
64
+ };
65
+ };
66
+ readonly 'ru-RU': {
67
+ readonly optional: "Опционально";
68
+ readonly dropzoneTitle: "Перетащите файл или нажмите";
69
+ readonly dropzoneButton: "Выбрать файл";
70
+ readonly dropzoneDescription: "{{formats}} не более {{count}} файлов до {{size}}";
71
+ readonly dropzoneDescriptionNoFormats: "Не более {{count}} файлов до {{size}}";
72
+ readonly errorRequired: "Обязательное поле";
73
+ readonly errorSomeFilesNotUploaded: "Некоторые файлы не загружены";
74
+ readonly errorFileLimit: "Можно загрузить не более {{count}} файлов";
75
+ readonly errorFileFormat: "Поддерживаются только {{formats}}";
76
+ readonly errorFileSize: "Размер файла превышает {{size}}";
77
+ readonly formatsConjunction: "и";
78
+ readonly uploadError: "Ошибка загрузки";
79
+ readonly units: {
80
+ readonly b: "Б";
81
+ readonly kb: "Кб";
82
+ readonly mb: "Мб";
83
+ readonly gb: "Гб";
84
+ };
85
+ };
86
+ }, "@cloud-ru/ds-uikit-product-upload-files">;
87
+ export {};
@@ -0,0 +1,45 @@
1
+ import { defineLocale, defineMessages } from '@cloud-ru/ds-locale';
2
+ const UPLOAD_FILES_MESSAGES = defineMessages({
3
+ 'en-GB': {
4
+ optional: 'Optional',
5
+ dropzoneTitle: 'Drag a file here or click',
6
+ dropzoneButton: 'Select file',
7
+ dropzoneDescription: '{{formats}} no more than {{count}} files up to {{size}}',
8
+ dropzoneDescriptionNoFormats: 'No more than {{count}} files up to {{size}}',
9
+ errorRequired: 'Required field',
10
+ errorSomeFilesNotUploaded: 'Some files were not uploaded',
11
+ errorFileLimit: 'You can upload no more than {{count}} files',
12
+ errorFileFormat: 'Only {{formats}} are supported',
13
+ errorFileSize: 'File size must not exceed {{size}}',
14
+ formatsConjunction: 'and',
15
+ uploadError: 'Upload failed',
16
+ units: {
17
+ b: 'B',
18
+ kb: 'KB',
19
+ mb: 'MB',
20
+ gb: 'GB',
21
+ },
22
+ },
23
+ 'ru-RU': {
24
+ optional: 'Опционально',
25
+ dropzoneTitle: 'Перетащите файл или нажмите',
26
+ dropzoneButton: 'Выбрать файл',
27
+ dropzoneDescription: '{{formats}} не более {{count}} файлов до {{size}}',
28
+ dropzoneDescriptionNoFormats: 'Не более {{count}} файлов до {{size}}',
29
+ errorRequired: 'Обязательное поле',
30
+ errorSomeFilesNotUploaded: 'Некоторые файлы не загружены',
31
+ errorFileLimit: 'Можно загрузить не более {{count}} файлов',
32
+ errorFileFormat: 'Поддерживаются только {{formats}}',
33
+ errorFileSize: 'Размер файла превышает {{size}}',
34
+ formatsConjunction: 'и',
35
+ uploadError: 'Ошибка загрузки',
36
+ units: {
37
+ b: 'Б',
38
+ kb: 'Кб',
39
+ mb: 'Мб',
40
+ gb: 'Гб',
41
+ },
42
+ },
43
+ });
44
+ /** locale компонента UploadFiles: `uploadFilesLocale.useTranslations()` в коде, `.extend(...)` в сервисе. */
45
+ export const uploadFilesLocale = defineLocale('@cloud-ru/ds-uikit-product-upload-files', UPLOAD_FILES_MESSAGES);
@@ -0,0 +1,42 @@
1
+ .root{
2
+ display:flex;
3
+ flex-direction:column;
4
+ gap:var(--sn-density-spacing-interval-s, var(--sn-primitive-dimension-8, 8px));
5
+ width:100%;
6
+ }
7
+
8
+ .dropzoneSection{
9
+ width:100%;
10
+ }
11
+
12
+ .dropzoneContent{
13
+ display:flex;
14
+ flex-direction:column;
15
+ gap:var(--sn-density-spacing-interval-s, var(--sn-primitive-dimension-8, 8px));
16
+ align-items:center;
17
+ justify-content:center;
18
+ width:100%;
19
+ }
20
+
21
+ .attachments{
22
+ display:flex;
23
+ flex-direction:column;
24
+ gap:var(--sn-density-spacing-interval-xs, var(--sn-primitive-dimension-4, 4px));
25
+ width:100%;
26
+ }
27
+ .attachments [data-test-id=attachment__icon] svg[data-size][data-appearance]{
28
+ width:var(--sn-density-size-icon-s, var(--sn-primitive-dimension-24, 24px)) !important;
29
+ height:var(--sn-density-size-icon-s, var(--sn-primitive-dimension-24, 24px)) !important;
30
+ }
31
+
32
+ .attachmentItem{
33
+ display:contents;
34
+ }
35
+
36
+ .attachment[data-acrylic-appearance]{
37
+ width:100%;
38
+ }
39
+
40
+ .dropzoneDescription{
41
+ color:var(--sn-theme-color-available-version-textTertiary, var(--sn-brand-color-text-version-tertiary, rgba(65, 66, 78, 0.5490196078)));
42
+ }
@@ -0,0 +1,42 @@
1
+ .root{
2
+ display:flex;
3
+ flex-direction:column;
4
+ gap:var(--sn-density-spacing-interval-s, var(--sn-primitive-dimension-8, 8px));
5
+ width:100%;
6
+ }
7
+
8
+ .dropzoneSection{
9
+ width:100%;
10
+ }
11
+
12
+ .dropzoneContent{
13
+ display:flex;
14
+ flex-direction:column;
15
+ gap:var(--sn-density-spacing-interval-s, var(--sn-primitive-dimension-8, 8px));
16
+ align-items:center;
17
+ justify-content:center;
18
+ width:100%;
19
+ }
20
+
21
+ .attachments{
22
+ display:flex;
23
+ flex-direction:column;
24
+ gap:var(--sn-density-spacing-interval-xs, var(--sn-primitive-dimension-4, 4px));
25
+ width:100%;
26
+ }
27
+ .attachments [data-test-id=attachment__icon] svg[data-size][data-appearance]{
28
+ width:var(--sn-density-size-icon-s, var(--sn-primitive-dimension-24, 24px)) !important;
29
+ height:var(--sn-density-size-icon-s, var(--sn-primitive-dimension-24, 24px)) !important;
30
+ }
31
+
32
+ .attachmentItem{
33
+ display:contents;
34
+ }
35
+
36
+ .attachment[data-acrylic-appearance]{
37
+ width:100%;
38
+ }
39
+
40
+ .dropzoneDescription{
41
+ color:var(--sn-theme-color-available-version-textTertiary, var(--sn-brand-color-text-version-tertiary, rgba(65, 66, 78, 0.5490196078)));
42
+ }