@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.
- package/CHANGELOG.md +8 -0
- package/LICENSE +201 -0
- package/README.md +238 -0
- package/dist/cjs/UploadFiles.d.ts +20 -0
- package/dist/cjs/UploadFiles.js +93 -0
- package/dist/cjs/components/Attachments/Attachments.d.ts +10 -0
- package/dist/cjs/components/Attachments/Attachments.js +18 -0
- package/dist/cjs/components/Attachments/index.d.ts +2 -0
- package/dist/cjs/components/Attachments/index.js +5 -0
- package/dist/cjs/components/UploadFilesDropZone/UploadFilesDropZone.d.ts +2 -0
- package/dist/cjs/components/UploadFilesDropZone/UploadFilesDropZone.js +14 -0
- package/dist/cjs/components/UploadFilesDropZone/index.d.ts +1 -0
- package/dist/cjs/components/UploadFilesDropZone/index.js +5 -0
- package/dist/cjs/components/index.d.ts +2 -0
- package/dist/cjs/components/index.js +18 -0
- package/dist/cjs/constants.d.ts +18 -0
- package/dist/cjs/constants.js +22 -0
- package/dist/cjs/hooks/index.d.ts +2 -0
- package/dist/cjs/hooks/index.js +5 -0
- package/dist/cjs/hooks/useUploadFilesController.d.ts +30 -0
- package/dist/cjs/hooks/useUploadFilesController.js +116 -0
- package/dist/cjs/index.d.ts +8 -0
- package/dist/cjs/index.js +31 -0
- package/dist/cjs/locale/index.d.ts +87 -0
- package/dist/cjs/locale/index.js +48 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/style.css +42 -0
- package/dist/cjs/styles.module.css +42 -0
- package/dist/cjs/types.d.ts +72 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/utils.d.ts +15 -0
- package/dist/cjs/utils.js +67 -0
- package/dist/esm/UploadFiles.d.ts +20 -0
- package/dist/esm/UploadFiles.js +87 -0
- package/dist/esm/components/Attachments/Attachments.d.ts +10 -0
- package/dist/esm/components/Attachments/Attachments.js +12 -0
- package/dist/esm/components/Attachments/index.d.ts +2 -0
- package/dist/esm/components/Attachments/index.js +1 -0
- package/dist/esm/components/UploadFilesDropZone/UploadFilesDropZone.d.ts +2 -0
- package/dist/esm/components/UploadFilesDropZone/UploadFilesDropZone.js +8 -0
- package/dist/esm/components/UploadFilesDropZone/index.d.ts +1 -0
- package/dist/esm/components/UploadFilesDropZone/index.js +1 -0
- package/dist/esm/components/index.d.ts +2 -0
- package/dist/esm/components/index.js +2 -0
- package/dist/esm/constants.d.ts +18 -0
- package/dist/esm/constants.js +19 -0
- package/dist/esm/hooks/index.d.ts +2 -0
- package/dist/esm/hooks/index.js +1 -0
- package/dist/esm/hooks/useUploadFilesController.d.ts +30 -0
- package/dist/esm/hooks/useUploadFilesController.js +113 -0
- package/dist/esm/index.d.ts +8 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/locale/index.d.ts +87 -0
- package/dist/esm/locale/index.js +45 -0
- package/dist/esm/style.css +42 -0
- package/dist/esm/styles.module.css +42 -0
- package/dist/esm/types.d.ts +72 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/utils.d.ts +15 -0
- package/dist/esm/utils.js +60 -0
- package/dist/tsconfig.cjs.tsbuildinfo +1 -0
- package/dist/tsconfig.esm.tsbuildinfo +1 -0
- package/package.json +56 -0
- package/src/UploadFiles.tsx +212 -0
- package/src/components/Attachments/Attachments.tsx +44 -0
- package/src/components/Attachments/index.ts +2 -0
- package/src/components/UploadFilesDropZone/UploadFilesDropZone.tsx +27 -0
- package/src/components/UploadFilesDropZone/index.ts +1 -0
- package/src/components/index.ts +2 -0
- package/src/constants.ts +27 -0
- package/src/hooks/index.ts +7 -0
- package/src/hooks/useUploadFilesController.ts +199 -0
- package/src/index.ts +14 -0
- package/src/locale/index.ts +49 -0
- package/src/styles.module.scss +52 -0
- package/src/types.ts +78 -0
- package/src/utils.ts +84 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./UploadFilesDropZone"), exports);
|
|
18
|
+
__exportStar(require("./Attachments"), exports);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { UploadFilesAcceptItem } from './types';
|
|
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,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TEST_IDS = exports.DEFAULT_ACCEPT = exports.DEFAULT_MAX_SIZE = exports.DEFAULT_MAX_FILES = exports.SUMMARY_ERROR_TYPE = exports.UPLOAD_STATUS = void 0;
|
|
4
|
+
exports.UPLOAD_STATUS = {
|
|
5
|
+
Uploading: 'uploading',
|
|
6
|
+
Success: 'success',
|
|
7
|
+
Error: 'error',
|
|
8
|
+
};
|
|
9
|
+
exports.SUMMARY_ERROR_TYPE = {
|
|
10
|
+
FileLimit: 'fileLimit',
|
|
11
|
+
SomeFilesNotUploaded: 'someFilesNotUploaded',
|
|
12
|
+
};
|
|
13
|
+
exports.DEFAULT_MAX_FILES = 3;
|
|
14
|
+
exports.DEFAULT_MAX_SIZE = 5 * 1024 * 1024;
|
|
15
|
+
// `*` — любой файл по умолчанию: без иконок и отображаемых имён форматов.
|
|
16
|
+
exports.DEFAULT_ACCEPT = [{ extention: '*' }];
|
|
17
|
+
const PREFIX = 'upload-files';
|
|
18
|
+
exports.TEST_IDS = {
|
|
19
|
+
root: PREFIX,
|
|
20
|
+
dropzone: `${PREFIX}__dropzone`,
|
|
21
|
+
attachment: `${PREFIX}__attachment`,
|
|
22
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.useUploadFilesController = void 0;
|
|
4
|
+
var useUploadFilesController_1 = require("./useUploadFilesController");
|
|
5
|
+
Object.defineProperty(exports, "useUploadFilesController", { enumerable: true, get: function () { return useUploadFilesController_1.useUploadFilesController; } });
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { FileRejection } from '@cloud-ru/ds-dropzone';
|
|
2
|
+
import { SUMMARY_ERROR_TYPE } from '../constants';
|
|
3
|
+
import { UploadFileItem, UploadFn } from '../types';
|
|
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,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.useUploadFilesController = useUploadFilesController;
|
|
4
|
+
const dropzone_1 = require("@cloud-ru/ds-dropzone");
|
|
5
|
+
const react_1 = require("react");
|
|
6
|
+
const constants_1 = require("../constants");
|
|
7
|
+
const utils_1 = require("../utils");
|
|
8
|
+
function useUploadFilesController({ value, onChange, upload, accept, maxFiles, maxSize, disabled, messages, }) {
|
|
9
|
+
const abortControllersRef = (0, react_1.useRef)(new Map());
|
|
10
|
+
const valueRef = (0, react_1.useRef)(value);
|
|
11
|
+
valueRef.current = value;
|
|
12
|
+
const onChangeRef = (0, react_1.useRef)(onChange);
|
|
13
|
+
onChangeRef.current = onChange;
|
|
14
|
+
const uploadRef = (0, react_1.useRef)(upload);
|
|
15
|
+
uploadRef.current = upload;
|
|
16
|
+
(0, react_1.useEffect)(() => {
|
|
17
|
+
const controllers = abortControllersRef.current;
|
|
18
|
+
return () => {
|
|
19
|
+
controllers.forEach(controller => controller.abort());
|
|
20
|
+
controllers.clear();
|
|
21
|
+
};
|
|
22
|
+
}, []);
|
|
23
|
+
const updateItems = (0, react_1.useCallback)((updater) => {
|
|
24
|
+
// Синхронно обновляем ref, чтобы параллельные загрузки, завершившиеся до
|
|
25
|
+
// следующего ре-рендера, строили обновление на актуальном состоянии, а не
|
|
26
|
+
// на устаревшем value — иначе последний onChange затирает остальные.
|
|
27
|
+
const next = updater(valueRef.current);
|
|
28
|
+
valueRef.current = next;
|
|
29
|
+
onChangeRef.current(next);
|
|
30
|
+
}, []);
|
|
31
|
+
const startUpload = (0, react_1.useCallback)((item) => {
|
|
32
|
+
const controller = new AbortController();
|
|
33
|
+
abortControllersRef.current.set(item.id, controller);
|
|
34
|
+
uploadRef
|
|
35
|
+
.current(item.file, { signal: controller.signal })
|
|
36
|
+
.then(result => {
|
|
37
|
+
abortControllersRef.current.delete(item.id);
|
|
38
|
+
updateItems(prev => prev.map(current => current.id === item.id
|
|
39
|
+
? { ...current, status: constants_1.UPLOAD_STATUS.Success, result, progress: 100, error: undefined }
|
|
40
|
+
: current));
|
|
41
|
+
})
|
|
42
|
+
.catch(() => {
|
|
43
|
+
abortControllersRef.current.delete(item.id);
|
|
44
|
+
if (controller.signal.aborted) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
updateItems(prev => prev.map(current => current.id === item.id
|
|
48
|
+
? { ...current, status: constants_1.UPLOAD_STATUS.Error, error: messages.uploadError }
|
|
49
|
+
: current));
|
|
50
|
+
});
|
|
51
|
+
}, [messages, updateItems]);
|
|
52
|
+
const handleFilesUpload = (0, react_1.useCallback)((files) => {
|
|
53
|
+
if (disabled || !files.length) {
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const { accepted, rejected } = (0, dropzone_1.partitionFiles)(files, { accept, maxSize });
|
|
57
|
+
const rejectedItems = rejected.map(({ file, reason }) => ({
|
|
58
|
+
id: (0, utils_1.makeId)(),
|
|
59
|
+
file,
|
|
60
|
+
status: constants_1.UPLOAD_STATUS.Error,
|
|
61
|
+
error: reason === dropzone_1.FILE_REJECTION_REASON.MaxSize ? messages.fileSizeError : messages.fileFormatError,
|
|
62
|
+
}));
|
|
63
|
+
const acceptedItems = accepted.map(file => ({
|
|
64
|
+
id: (0, utils_1.makeId)(),
|
|
65
|
+
file,
|
|
66
|
+
status: constants_1.UPLOAD_STATUS.Uploading,
|
|
67
|
+
}));
|
|
68
|
+
const next = [...valueRef.current, ...rejectedItems, ...acceptedItems];
|
|
69
|
+
valueRef.current = next;
|
|
70
|
+
onChangeRef.current(next);
|
|
71
|
+
acceptedItems.forEach(startUpload);
|
|
72
|
+
}, [accept, disabled, maxSize, messages, startUpload]);
|
|
73
|
+
// Отклонённые валидацией файлы (формат/размер) показываем в списке как error-вложения. Причина
|
|
74
|
+
// из `FileRejection` определяет текст: превышение размера vs недопустимый формат. Файлы не грузятся.
|
|
75
|
+
const handleFilesReject = (0, react_1.useCallback)((rejections) => {
|
|
76
|
+
if (disabled || !rejections.length) {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const rejectedItems = rejections.map(({ file, reason }) => ({
|
|
80
|
+
id: (0, utils_1.makeId)(),
|
|
81
|
+
file,
|
|
82
|
+
status: constants_1.UPLOAD_STATUS.Error,
|
|
83
|
+
error: reason === dropzone_1.FILE_REJECTION_REASON.MaxSize ? messages.fileSizeError : messages.fileFormatError,
|
|
84
|
+
}));
|
|
85
|
+
const next = [...valueRef.current, ...rejectedItems];
|
|
86
|
+
valueRef.current = next;
|
|
87
|
+
onChangeRef.current(next);
|
|
88
|
+
}, [disabled, messages]);
|
|
89
|
+
const handleDelete = (0, react_1.useCallback)((id) => {
|
|
90
|
+
const controller = abortControllersRef.current.get(id);
|
|
91
|
+
if (controller) {
|
|
92
|
+
controller.abort();
|
|
93
|
+
abortControllersRef.current.delete(id);
|
|
94
|
+
}
|
|
95
|
+
updateItems(prev => prev.filter(item => item.id !== id));
|
|
96
|
+
}, [updateItems]);
|
|
97
|
+
const hasItemErrors = value.some(item => item.status === constants_1.UPLOAD_STATUS.Error || Boolean(item.error));
|
|
98
|
+
const isOverLimit = typeof maxFiles === 'number' && value.length > maxFiles;
|
|
99
|
+
let summaryError;
|
|
100
|
+
let summaryErrorType = null;
|
|
101
|
+
if (isOverLimit) {
|
|
102
|
+
summaryError = messages.fileLimitError;
|
|
103
|
+
summaryErrorType = constants_1.SUMMARY_ERROR_TYPE.FileLimit;
|
|
104
|
+
}
|
|
105
|
+
else if (hasItemErrors) {
|
|
106
|
+
summaryErrorType = constants_1.SUMMARY_ERROR_TYPE.SomeFilesNotUploaded;
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
items: value,
|
|
110
|
+
summaryError,
|
|
111
|
+
summaryErrorType,
|
|
112
|
+
handleFilesUpload,
|
|
113
|
+
handleFilesReject,
|
|
114
|
+
handleDelete,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { buildAcceptAttribute } from '@cloud-ru/ds-dropzone';
|
|
2
|
+
export { UploadFiles } from './UploadFiles';
|
|
3
|
+
export * from './constants';
|
|
4
|
+
export * from './types';
|
|
5
|
+
export { formatFileSize, formatFileDescription, joinWithConjunction, makeId } from './utils';
|
|
6
|
+
export { useUploadFilesController } from './hooks';
|
|
7
|
+
export type { SummaryErrorType, UploadFilesMessages, UseUploadFilesControllerOptions, UseUploadFilesControllerResult, } from './hooks';
|
|
8
|
+
export * from './locale';
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.useUploadFilesController = exports.makeId = exports.joinWithConjunction = exports.formatFileDescription = exports.formatFileSize = exports.UploadFiles = exports.buildAcceptAttribute = void 0;
|
|
18
|
+
var dropzone_1 = require("@cloud-ru/ds-dropzone");
|
|
19
|
+
Object.defineProperty(exports, "buildAcceptAttribute", { enumerable: true, get: function () { return dropzone_1.buildAcceptAttribute; } });
|
|
20
|
+
var UploadFiles_1 = require("./UploadFiles");
|
|
21
|
+
Object.defineProperty(exports, "UploadFiles", { enumerable: true, get: function () { return UploadFiles_1.UploadFiles; } });
|
|
22
|
+
__exportStar(require("./constants"), exports);
|
|
23
|
+
__exportStar(require("./types"), exports);
|
|
24
|
+
var utils_1 = require("./utils");
|
|
25
|
+
Object.defineProperty(exports, "formatFileSize", { enumerable: true, get: function () { return utils_1.formatFileSize; } });
|
|
26
|
+
Object.defineProperty(exports, "formatFileDescription", { enumerable: true, get: function () { return utils_1.formatFileDescription; } });
|
|
27
|
+
Object.defineProperty(exports, "joinWithConjunction", { enumerable: true, get: function () { return utils_1.joinWithConjunction; } });
|
|
28
|
+
Object.defineProperty(exports, "makeId", { enumerable: true, get: function () { return utils_1.makeId; } });
|
|
29
|
+
var hooks_1 = require("./hooks");
|
|
30
|
+
Object.defineProperty(exports, "useUploadFilesController", { enumerable: true, get: function () { return hooks_1.useUploadFilesController; } });
|
|
31
|
+
__exportStar(require("./locale"), exports);
|
|
@@ -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,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.uploadFilesLocale = void 0;
|
|
4
|
+
const locale_1 = require("@cloud-ru/ds-locale");
|
|
5
|
+
const UPLOAD_FILES_MESSAGES = (0, locale_1.defineMessages)({
|
|
6
|
+
'en-GB': {
|
|
7
|
+
optional: 'Optional',
|
|
8
|
+
dropzoneTitle: 'Drag a file here or click',
|
|
9
|
+
dropzoneButton: 'Select file',
|
|
10
|
+
dropzoneDescription: '{{formats}} no more than {{count}} files up to {{size}}',
|
|
11
|
+
dropzoneDescriptionNoFormats: 'No more than {{count}} files up to {{size}}',
|
|
12
|
+
errorRequired: 'Required field',
|
|
13
|
+
errorSomeFilesNotUploaded: 'Some files were not uploaded',
|
|
14
|
+
errorFileLimit: 'You can upload no more than {{count}} files',
|
|
15
|
+
errorFileFormat: 'Only {{formats}} are supported',
|
|
16
|
+
errorFileSize: 'File size must not exceed {{size}}',
|
|
17
|
+
formatsConjunction: 'and',
|
|
18
|
+
uploadError: 'Upload failed',
|
|
19
|
+
units: {
|
|
20
|
+
b: 'B',
|
|
21
|
+
kb: 'KB',
|
|
22
|
+
mb: 'MB',
|
|
23
|
+
gb: 'GB',
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
'ru-RU': {
|
|
27
|
+
optional: 'Опционально',
|
|
28
|
+
dropzoneTitle: 'Перетащите файл или нажмите',
|
|
29
|
+
dropzoneButton: 'Выбрать файл',
|
|
30
|
+
dropzoneDescription: '{{formats}} не более {{count}} файлов до {{size}}',
|
|
31
|
+
dropzoneDescriptionNoFormats: 'Не более {{count}} файлов до {{size}}',
|
|
32
|
+
errorRequired: 'Обязательное поле',
|
|
33
|
+
errorSomeFilesNotUploaded: 'Некоторые файлы не загружены',
|
|
34
|
+
errorFileLimit: 'Можно загрузить не более {{count}} файлов',
|
|
35
|
+
errorFileFormat: 'Поддерживаются только {{formats}}',
|
|
36
|
+
errorFileSize: 'Размер файла превышает {{size}}',
|
|
37
|
+
formatsConjunction: 'и',
|
|
38
|
+
uploadError: 'Ошибка загрузки',
|
|
39
|
+
units: {
|
|
40
|
+
b: 'Б',
|
|
41
|
+
kb: 'Кб',
|
|
42
|
+
mb: 'Мб',
|
|
43
|
+
gb: 'Гб',
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
/** locale компонента UploadFiles: `uploadFilesLocale.useTranslations()` в коде, `.extend(...)` в сервисе. */
|
|
48
|
+
exports.uploadFilesLocale = (0, locale_1.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
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { IconPredefinedProps } from '@cloud-ru/ds-icon-predefined';
|
|
2
|
+
import { ValueOf, WithSupportProps } from '@cloud-ru/ds-utils';
|
|
3
|
+
import { FocusEventHandler, ReactNode } from 'react';
|
|
4
|
+
import { UPLOAD_STATUS } from './constants';
|
|
5
|
+
export type UploadStatus = ValueOf<typeof UPLOAD_STATUS>;
|
|
6
|
+
/** Локализованные единицы измерения размера файла */
|
|
7
|
+
export type FileSizeUnits = {
|
|
8
|
+
b: string;
|
|
9
|
+
kb: string;
|
|
10
|
+
mb: string;
|
|
11
|
+
gb: string;
|
|
12
|
+
};
|
|
13
|
+
export type UploadFileItem<TResult = unknown> = {
|
|
14
|
+
id: string;
|
|
15
|
+
file: File;
|
|
16
|
+
status: UploadStatus;
|
|
17
|
+
progress?: number;
|
|
18
|
+
error?: string;
|
|
19
|
+
result?: TResult;
|
|
20
|
+
};
|
|
21
|
+
export type UploadFn<TResult = unknown> = (file: File, ctx: {
|
|
22
|
+
signal: AbortSignal;
|
|
23
|
+
}) => Promise<TResult>;
|
|
24
|
+
export type UploadFilesAcceptItem = {
|
|
25
|
+
/** Расширение файла (например `.pdf` или `*` для всех типов файлов) */
|
|
26
|
+
extention: string;
|
|
27
|
+
/** Иконка, отображаемая для файлов этого типа во вложениях */
|
|
28
|
+
icon?: IconPredefinedProps['icon'];
|
|
29
|
+
/** Отображаемое расширение файла для пользователя (например `PDF`) */
|
|
30
|
+
displayExtension?: string;
|
|
31
|
+
};
|
|
32
|
+
export type UploadFilesProps<TResult = unknown> = WithSupportProps<{
|
|
33
|
+
/** Текст метки поля */
|
|
34
|
+
label?: string;
|
|
35
|
+
/** Подсказка question tooltip у метки */
|
|
36
|
+
hint?: ReactNode;
|
|
37
|
+
/**
|
|
38
|
+
* Показывает «Опционально» справа от метки
|
|
39
|
+
* @default true
|
|
40
|
+
*/
|
|
41
|
+
optional?: boolean;
|
|
42
|
+
/** Заблокировано */
|
|
43
|
+
disabled?: boolean;
|
|
44
|
+
/** Контролируемое значение */
|
|
45
|
+
value?: UploadFileItem<TResult>[];
|
|
46
|
+
/** Начальное значение */
|
|
47
|
+
defaultValue?: UploadFileItem<TResult>[];
|
|
48
|
+
/** Колбэк изменения значения */
|
|
49
|
+
onChange?(items: UploadFileItem<TResult>[]): void;
|
|
50
|
+
/** Имя поля формы */
|
|
51
|
+
name?: string;
|
|
52
|
+
onBlur?: FocusEventHandler<HTMLDivElement>;
|
|
53
|
+
/** Ошибка формы (например required из RHF) */
|
|
54
|
+
error?: string;
|
|
55
|
+
/** Обязательная кастомная функция загрузки */
|
|
56
|
+
upload: UploadFn<TResult>;
|
|
57
|
+
/** CSS-класс корня */
|
|
58
|
+
className?: string;
|
|
59
|
+
/** Допустимые типы файлов с иконкой для каждого расширения */
|
|
60
|
+
accept?: UploadFilesAcceptItem[];
|
|
61
|
+
/** Максимальное количество файлов */
|
|
62
|
+
maxFiles?: number;
|
|
63
|
+
/** Максимальный размер файла в байтах */
|
|
64
|
+
maxSize?: number;
|
|
65
|
+
/** CSS-класс прикрепленного файла */
|
|
66
|
+
attachmentClassname?: string;
|
|
67
|
+
}>;
|
|
68
|
+
export type UploadFilesDropZoneProps = {
|
|
69
|
+
title?: string;
|
|
70
|
+
description?: ReactNode;
|
|
71
|
+
buttonLabel?: string;
|
|
72
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { FileSizeUnits, UploadFilesAcceptItem } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Подбирает иконку для файла по его расширению из списка accept.
|
|
4
|
+
* Возвращает undefined, если расширение не описано — тогда Attachment
|
|
5
|
+
* использует свою дефолтную иконку.
|
|
6
|
+
*/
|
|
7
|
+
export declare function resolveFileIcon(file: File, accept: UploadFilesAcceptItem[]): UploadFilesAcceptItem['icon'] | undefined;
|
|
8
|
+
export declare function makeId(): string;
|
|
9
|
+
/**
|
|
10
|
+
* Объединяет значения в перечисление: разделитель «, » между элементами,
|
|
11
|
+
* а последние два соединяются союзом (`PDF, TXT и DOCX`).
|
|
12
|
+
*/
|
|
13
|
+
export declare function joinWithConjunction(parts: string[], conjunction: string): string;
|
|
14
|
+
export declare function formatFileSize(bytes: number, units: FileSizeUnits): string;
|
|
15
|
+
export declare function formatFileDescription(file: File, units: FileSizeUnits, descriptionOverride?: string): string;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.resolveFileIcon = resolveFileIcon;
|
|
4
|
+
exports.makeId = makeId;
|
|
5
|
+
exports.joinWithConjunction = joinWithConjunction;
|
|
6
|
+
exports.formatFileSize = formatFileSize;
|
|
7
|
+
exports.formatFileDescription = formatFileDescription;
|
|
8
|
+
function getFileExtension(fileName) {
|
|
9
|
+
return fileName?.split('.').pop()?.toUpperCase();
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Подбирает иконку для файла по его расширению из списка accept.
|
|
13
|
+
* Возвращает undefined, если расширение не описано — тогда Attachment
|
|
14
|
+
* использует свою дефолтную иконку.
|
|
15
|
+
*/
|
|
16
|
+
function resolveFileIcon(file, accept) {
|
|
17
|
+
const extension = getFileExtension(file.name);
|
|
18
|
+
if (!extension) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
const match = accept.find(item => item.extention.replace(/^\./, '').toUpperCase() === extension);
|
|
22
|
+
return match?.icon;
|
|
23
|
+
}
|
|
24
|
+
function makeId() {
|
|
25
|
+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
26
|
+
return `upload-file-${crypto.randomUUID()}`;
|
|
27
|
+
}
|
|
28
|
+
return `upload-file-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Объединяет значения в перечисление: разделитель «, » между элементами,
|
|
32
|
+
* а последние два соединяются союзом (`PDF, TXT и DOCX`).
|
|
33
|
+
*/
|
|
34
|
+
function joinWithConjunction(parts, conjunction) {
|
|
35
|
+
if (parts.length <= 1) {
|
|
36
|
+
return parts.join('');
|
|
37
|
+
}
|
|
38
|
+
const head = parts.slice(0, -1).join(', ');
|
|
39
|
+
const last = parts[parts.length - 1];
|
|
40
|
+
return `${head} ${conjunction} ${last}`;
|
|
41
|
+
}
|
|
42
|
+
function formatFileSize(bytes, units) {
|
|
43
|
+
if (bytes < 1024) {
|
|
44
|
+
return `${bytes} ${units.b}`;
|
|
45
|
+
}
|
|
46
|
+
if (bytes < 1024 * 1024) {
|
|
47
|
+
const kb = bytes / 1024;
|
|
48
|
+
const rounded = kb >= 10 ? Math.round(kb) : Math.round(kb * 10) / 10;
|
|
49
|
+
return `${rounded} ${units.kb}`;
|
|
50
|
+
}
|
|
51
|
+
if (bytes < 1024 * 1024 * 1024) {
|
|
52
|
+
const mb = bytes / (1024 * 1024);
|
|
53
|
+
const rounded = mb >= 10 ? Math.round(mb) : Math.round(mb * 10) / 10;
|
|
54
|
+
return `${rounded} ${units.mb}`;
|
|
55
|
+
}
|
|
56
|
+
const gb = bytes / (1024 * 1024 * 1024);
|
|
57
|
+
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10;
|
|
58
|
+
return `${rounded} ${units.gb}`;
|
|
59
|
+
}
|
|
60
|
+
function formatFileDescription(file, units, descriptionOverride) {
|
|
61
|
+
if (descriptionOverride) {
|
|
62
|
+
return descriptionOverride;
|
|
63
|
+
}
|
|
64
|
+
const extension = getFileExtension(file.name) ?? '';
|
|
65
|
+
const size = formatFileSize(file.size, units);
|
|
66
|
+
return extension ? `${extension}, ${size}` : size;
|
|
67
|
+
}
|