@raketa-builder/file-input 0.1.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.
@@ -0,0 +1,96 @@
1
+ import React from "react";
2
+ import { Input, Stack, cn } from "@raketa-builder/ui";
3
+ import { fileCategoriesOptions } from "./FileCategory";
4
+
5
+ const useDebunce = (value, onDebouncedChange) => {
6
+ const timerRef = React.useRef(null);
7
+
8
+ React.useEffect(() => {
9
+ timerRef.current = setTimeout(() => {
10
+ onDebouncedChange(value);
11
+ }, 500);
12
+
13
+ return () => {
14
+ clearTimeout(timerRef.current);
15
+ };
16
+ }, [value]);
17
+ };
18
+
19
+ const SearchInput = ({ onChange }) => {
20
+ const [q, setQ] = React.useState("");
21
+
22
+ useDebunce(q, onChange);
23
+
24
+ return (
25
+ <Input
26
+ placeholder="Start typing file name..."
27
+ value={q}
28
+ onChange={(e) => {
29
+ setQ(e.target.value);
30
+ }}
31
+ />
32
+ );
33
+ };
34
+
35
+ const FileSearch = ({ fetching, value, allowedFileCategory, onChange }) => {
36
+ const onCategoryPick = (val) => {
37
+ onChange({
38
+ ...value,
39
+ category: val,
40
+ });
41
+ };
42
+
43
+ const onSearchTermChange = (q) => {
44
+ onChange({
45
+ ...value,
46
+ keyword: q,
47
+ });
48
+ };
49
+
50
+ if (allowedFileCategory) {
51
+ return (
52
+ <div className="r-spacing-bottom-sm">
53
+ <SearchInput onChange={onSearchTermChange} />
54
+ </div>
55
+ );
56
+ }
57
+
58
+ return (
59
+ <>
60
+ <SearchInput onChange={onSearchTermChange} />
61
+
62
+ <Stack className="r-spacing-both-sm">
63
+ <div className={cn("r-reset", "r-tab-wrapper")}>
64
+ <button
65
+ disabled={fetching}
66
+ className={`r-reset-button r-tab-button ${
67
+ value?.category === "" ? "r-tab-button-active" : ""
68
+ }`}
69
+ onClick={() => onCategoryPick("")}
70
+ >
71
+ All
72
+ </button>
73
+
74
+ {fileCategoriesOptions().map((category) => {
75
+ const [key, label] = category;
76
+
77
+ return (
78
+ <button
79
+ key={key}
80
+ disabled={fetching}
81
+ className={`r-reset-button r-tab-button ${
82
+ value?.category === key ? "r-tab-button-active" : ""
83
+ }`}
84
+ onClick={() => onCategoryPick(key)}
85
+ >
86
+ {label}
87
+ </button>
88
+ );
89
+ })}
90
+ </div>
91
+ </Stack>
92
+ </>
93
+ );
94
+ };
95
+
96
+ export default FileSearch;
@@ -0,0 +1,31 @@
1
+ import React from "react";
2
+ import { cn } from "@raketa-builder/ui";
3
+ import { toMimeTypes } from "./FileCategory";
4
+
5
+ const UploadFilesButton = ({ allowedFileCategory, onSelect }) => (
6
+ <div
7
+ className={cn("r-reset", "r-spacing-both-sm", "r-file-input-upload-button")}
8
+ >
9
+ <label className={cn("r-button", "r-button-secondary")}>
10
+ Upload files...
11
+ <input
12
+ id="r-files-input"
13
+ type="file"
14
+ multiple
15
+ accept={allowedFileCategory ? toMimeTypes(allowedFileCategory) : ""}
16
+ onChange={(event) => {
17
+ const fileList = event.target.files;
18
+ const files = [];
19
+
20
+ for (let i = 0; i < fileList.length; i++) {
21
+ files[i] = fileList.item(i);
22
+ }
23
+
24
+ onSelect(files);
25
+ }}
26
+ />
27
+ </label>
28
+ </div>
29
+ );
30
+
31
+ export default UploadFilesButton;
@@ -0,0 +1,84 @@
1
+ import React from "react";
2
+ import { Stack, cn } from "@raketa-builder/ui";
3
+ import { fileSizeFormatter } from "./utils";
4
+
5
+ const UploadState = ({ upload }) => {
6
+ switch (upload.state.type) {
7
+ case "pending":
8
+ return (
9
+ <div className="r-reset">
10
+ {fileSizeFormatter(0)} / {fileSizeFormatter(upload.file.size || 0)}
11
+ </div>
12
+ );
13
+ case "progress":
14
+ return (
15
+ <div
16
+ className={cn(
17
+ "r-reset",
18
+ "r-stack",
19
+ "r-stack-justify-beteen",
20
+ "r-stack-align-center"
21
+ )}
22
+ >
23
+ {fileSizeFormatter(upload.state?.payload?.loaded || 0)} /{" "}
24
+ {fileSizeFormatter(upload.file.size || 0)}
25
+ </div>
26
+ );
27
+
28
+ case "uploaded":
29
+ case "completed":
30
+ return (
31
+ <div className="r-reset">
32
+ {fileSizeFormatter(upload.file.size || 0)} /{" "}
33
+ {fileSizeFormatter(upload.file.size || 0)}
34
+ </div>
35
+ );
36
+
37
+ case "errored":
38
+ console.error({ upload });
39
+
40
+ return (
41
+ <div className={cn("r-reset", "r-hint-error")}>Failed to upload</div>
42
+ );
43
+ case "rejected":
44
+ return (
45
+ <div className={cn("r-reset", "r-hint-error")}>
46
+ {upload.state.payload.errors.join("; ")}
47
+ </div>
48
+ );
49
+ default:
50
+ console.error({ upload });
51
+ throw `Unknown state: ${upload.state}`;
52
+ }
53
+ };
54
+
55
+ const UploadName = ({ upload }) => {
56
+ return <div className="r-reset">{upload.file.name}</div>;
57
+ };
58
+
59
+ const UploadProgress = ({ uploads }) => {
60
+ if (uploads.length === 0) {
61
+ return null;
62
+ }
63
+
64
+ return (
65
+ <div className={cn("r-reset", "r-spacing-top-sm")}>
66
+ {uploads.map((upload) => (
67
+ <Stack
68
+ key={upload.id}
69
+ className={cn(
70
+ "r-reset",
71
+ "r-stack-justify-beteen",
72
+ "r-stack-align-center",
73
+ "r-file-progress"
74
+ )}
75
+ >
76
+ <UploadName upload={upload} />
77
+ <UploadState upload={upload} />
78
+ </Stack>
79
+ ))}
80
+ </div>
81
+ );
82
+ };
83
+
84
+ export default UploadProgress;
@@ -0,0 +1,123 @@
1
+ import React from "react";
2
+ import { H } from "@raketa-builder/ui";
3
+ import {
4
+ uploadFiles,
5
+ loadFiles,
6
+ searchFiles,
7
+ deleteFile,
8
+ selectFile,
9
+ loadMoreFiles,
10
+ initialState,
11
+ } from "./stateManagement";
12
+ import Dialog from "./Dialog";
13
+ import FileSearch from "./FileSearch";
14
+ import FileList from "./FileList";
15
+ import FileInput from "./FileInput";
16
+ import UploadProgress from "./UploadProgress";
17
+ import UploadFilesButton from "./UploadFilesButton";
18
+ import { sanitizeFileCategory } from "./FileCategory";
19
+
20
+ const FilePicker = ({
21
+ fileManager,
22
+ value: initialValue,
23
+ label,
24
+ hint,
25
+ fileCategory = null,
26
+ onChange,
27
+ }) => {
28
+ const allowedFileCategory = React.useMemo(
29
+ () => sanitizeFileCategory(fileCategory),
30
+ [fileCategory]
31
+ );
32
+
33
+ const [state, setState] = React.useState(
34
+ initialState(initialValue, allowedFileCategory)
35
+ );
36
+
37
+ const onFilesUpload = (files) => {
38
+ uploadFiles(fileManager, files, allowedFileCategory, setState);
39
+ };
40
+
41
+ const onBrowse = async () => {
42
+ loadFiles(fileManager, state, setState);
43
+ };
44
+
45
+ const onClear = () => {
46
+ setState((currentState) => ({
47
+ ...currentState,
48
+ selected: null,
49
+ }));
50
+
51
+ onChange(null);
52
+ };
53
+
54
+ const onSelectFile = () => {
55
+ if (state.selected) {
56
+ onChange(state.selected);
57
+
58
+ setState((currentState) => ({ ...currentState, open: false }));
59
+ } else {
60
+ alert("No file selected!");
61
+ }
62
+ };
63
+
64
+ const onClose = () => {
65
+ setState((currentState) => ({ ...currentState, open: false }));
66
+ };
67
+
68
+ const onSearchFiltersUpdate = async (value) => {
69
+ searchFiles(fileManager, value, state, setState);
70
+ };
71
+
72
+ const onDeleteFile = async (fileId) => {
73
+ deleteFile(fileManager, fileId, state, setState, onChange);
74
+ };
75
+
76
+ return (
77
+ <>
78
+ <FileInput
79
+ label={label}
80
+ hint={hint}
81
+ value={initialValue}
82
+ onBrowse={onBrowse}
83
+ onClear={onClear}
84
+ />
85
+
86
+ {state.open && (
87
+ <Dialog
88
+ disablePrimary={!Boolean(state.selected)}
89
+ onPrimary={onSelectFile}
90
+ onClose={onClose}
91
+ onDrop={onFilesUpload}
92
+ >
93
+ <UploadFilesButton
94
+ allowedFileCategory={allowedFileCategory}
95
+ onSelect={onFilesUpload}
96
+ />
97
+
98
+ <UploadProgress uploads={state.uploads} />
99
+
100
+ <H className="r-spacing-top-sm">Search</H>
101
+
102
+ <FileSearch
103
+ allowedFileCategory={allowedFileCategory}
104
+ fetching={state.fetching}
105
+ value={state.files.filters}
106
+ onChange={onSearchFiltersUpdate}
107
+ />
108
+
109
+ <FileList
110
+ fetching={state.fetching}
111
+ files={state.files.list}
112
+ onMore={loadMoreFiles(fileManager, state, setState)}
113
+ onDelete={onDeleteFile}
114
+ selected={state.selected?.document}
115
+ onSelect={(fileId) => selectFile(fileId, setState)}
116
+ />
117
+ </Dialog>
118
+ )}
119
+ </>
120
+ );
121
+ };
122
+
123
+ export default FilePicker;
@@ -0,0 +1,276 @@
1
+ import { toExcludedMimeTypes, toMimeTypes } from "./FileCategory";
2
+
3
+ function mimeTypes(category) {
4
+ return toMimeTypes(category);
5
+ }
6
+
7
+ function excludeMimeTypes(category) {
8
+ return toExcludedMimeTypes(category);
9
+ }
10
+
11
+ export function initialState(initialSelected, initialCategory) {
12
+ return {
13
+ open: false,
14
+ fetching: false,
15
+ selected: initialSelected,
16
+ uploads: [],
17
+ files: {
18
+ initial: true,
19
+ list: [],
20
+ nextCursor: null,
21
+ filters: {
22
+ keyword: "",
23
+ category: initialCategory || "",
24
+ },
25
+ },
26
+ };
27
+ }
28
+
29
+ function initialUploadState(file, allowedMimeTypes) {
30
+ if (allowedMimeTypes.length === 0 || allowedMimeTypes.includes(file.type)) {
31
+ return {
32
+ type: "pending",
33
+ payload: {},
34
+ };
35
+ }
36
+
37
+ return {
38
+ type: "rejected",
39
+ payload: {
40
+ errors: [`Files of type "${file.type}" are not supported.`],
41
+ },
42
+ };
43
+ }
44
+
45
+ export function uploadFiles(fileManager, files, allowedFileCategory, setState) {
46
+ // Prepare uploads
47
+ const allowedMimeTypes = toMimeTypes(allowedFileCategory);
48
+
49
+ const fileUploads = files.map((file) => ({
50
+ file: file,
51
+ id: (Math.random() * 1000000).toFixed(0),
52
+ state: initialUploadState(file, allowedMimeTypes),
53
+ }));
54
+
55
+ // set current uploads state
56
+ setState((currentState) => ({
57
+ ...currentState,
58
+ uploads: [...currentState.uploads, ...fileUploads],
59
+ }));
60
+
61
+ // Initiate upload and pass update callback...
62
+ fileUploads
63
+ .filter((fu) => fu.state.type === "pending")
64
+ .forEach((fileUpload) =>
65
+ fileManager.createAndUpload(fileUpload, (tmpId, newState) =>
66
+ setState((currentState) => {
67
+ if (newState.type === "completed") {
68
+ if (
69
+ currentState.files.list.find(
70
+ (file) => file.id === newState.payload.document.id
71
+ )
72
+ ) {
73
+ return currentState;
74
+ }
75
+
76
+ return {
77
+ ...currentState,
78
+ uploads: currentState.uploads.filter(
79
+ (upload) => upload.id !== tmpId
80
+ ),
81
+ files: {
82
+ ...currentState.files,
83
+ list: [
84
+ { ...newState.payload.document },
85
+ ...currentState.files.list,
86
+ ],
87
+ },
88
+ };
89
+ } else {
90
+ const newUploads = currentState.uploads.map((upload) => {
91
+ if (upload.id === tmpId) {
92
+ return { ...upload, state: newState };
93
+ } else {
94
+ return upload;
95
+ }
96
+ });
97
+
98
+ return { ...currentState, uploads: newUploads };
99
+ }
100
+ })
101
+ )
102
+ );
103
+ }
104
+
105
+ export async function loadFiles(fileManager, state, setState) {
106
+ if (state.files.initial) {
107
+ setState((currentState) => ({
108
+ ...currentState,
109
+ open: true,
110
+ fetching: true,
111
+ }));
112
+
113
+ const resp = await fileManager.all({
114
+ mimeTypes: mimeTypes(state.files.filters.category),
115
+ excludeMimeTypes: excludeMimeTypes(state.files.filters.category),
116
+ });
117
+
118
+ setState((currentState) => ({
119
+ ...currentState,
120
+ fetching: false,
121
+ files: {
122
+ initial: false,
123
+ list: resp.list || [],
124
+ nextCursor: resp.pagination.cursor,
125
+ filters: {
126
+ keyword: "",
127
+ category: "",
128
+ },
129
+ },
130
+ }));
131
+ } else {
132
+ setState((currentState) => ({
133
+ ...currentState,
134
+ open: true,
135
+ }));
136
+ }
137
+ }
138
+
139
+ export async function searchFiles(fileManager, filters, state, setState) {
140
+ if (
141
+ (filters.keyword !== state.files.filters.keyword ||
142
+ filters.category !== state.files.filters.category) &&
143
+ !state.fetching
144
+ ) {
145
+ setState((currentState) => ({
146
+ ...currentState,
147
+ fetching: true,
148
+ }));
149
+
150
+ const resp = await fileManager.all({
151
+ nextCursor: null,
152
+ keyword: filters.keyword,
153
+ mimeTypes: mimeTypes(filters.category),
154
+ excludeMimeTypes: excludeMimeTypes(filters.category),
155
+ });
156
+
157
+ setState((currentState) => ({
158
+ ...currentState,
159
+ fetching: false,
160
+ files: {
161
+ list: [...resp.list],
162
+ nextCursor: resp.pagination.cursor,
163
+ filters: {
164
+ keyword: filters.keyword,
165
+ category: filters.category,
166
+ },
167
+ },
168
+ }));
169
+ } else {
170
+ setState((currentState) => ({
171
+ ...currentState,
172
+ fetching: false,
173
+ files: {
174
+ ...currentState.files,
175
+ filters: {
176
+ keyword: filters.keyword,
177
+ category: filters.category,
178
+ },
179
+ },
180
+ }));
181
+ }
182
+ }
183
+
184
+ export async function deleteFile(
185
+ fileManager,
186
+ fileId,
187
+ state,
188
+ setState,
189
+ onChange
190
+ ) {
191
+ setState((currentState) => ({
192
+ ...currentState,
193
+ fetching: true,
194
+ }));
195
+
196
+ const response = await fileManager.destroy(fileId);
197
+
198
+ let removeFromList = false;
199
+ let removeSelected = false;
200
+
201
+ if (response.errors) {
202
+ alert(`Something went wrong while deleting document#${fileId}`);
203
+ }
204
+
205
+ if (!response.errors && response.document) {
206
+ removeFromList = true;
207
+
208
+ if (fileId === state.selected?.document?.id) {
209
+ removeSelected = true;
210
+ }
211
+ }
212
+
213
+ setState((currentState) => ({
214
+ ...currentState,
215
+ fetching: false,
216
+ selected: removeSelected ? null : currentState.selected,
217
+ files: {
218
+ ...currentState.files,
219
+ list: currentState.files.list.filter((f) => f.id !== fileId),
220
+ },
221
+ }));
222
+
223
+ if (removeSelected) {
224
+ onChange(null);
225
+ }
226
+ }
227
+
228
+ export function selectFile(fileId, setState) {
229
+ setState((currentState) => {
230
+ const file = currentState.files.list.find((f) => f.id === fileId);
231
+
232
+ let newSelected = null;
233
+
234
+ if (file) {
235
+ newSelected = {
236
+ document: file,
237
+ uri: `raketacloud://documents/${file.id}`,
238
+ };
239
+ }
240
+
241
+ return {
242
+ ...currentState,
243
+ selected: newSelected,
244
+ };
245
+ });
246
+ }
247
+
248
+ export function loadMoreFiles(fileManager, state, setState) {
249
+ if (!state.files.nextCursor) {
250
+ return null;
251
+ }
252
+
253
+ return async function loadMore() {
254
+ setState((currentState) => ({
255
+ ...currentState,
256
+ fetching: true,
257
+ }));
258
+
259
+ const resp = await fileManager.all({
260
+ nextCursor: state.files.nextCursor,
261
+ keyword: state.files.filters.keyword,
262
+ mimeTypes: mimeTypes(state.files.filters.category),
263
+ excludeMimeTypes: excludeMimeTypes(state.files.filters.category),
264
+ });
265
+
266
+ setState((currentState) => ({
267
+ ...currentState,
268
+ fetching: false,
269
+ files: {
270
+ list: [...currentState.files.list, ...resp.list],
271
+ nextCursor: resp.pagination.cursor,
272
+ filters: { ...currentState.files.filters },
273
+ },
274
+ }));
275
+ };
276
+ }
@@ -0,0 +1,15 @@
1
+ export function fileSizeFormatter(size) {
2
+ if (size < 1024) {
3
+ return `${size} B`;
4
+ }
5
+
6
+ if (size < 1024 * 1024) {
7
+ return `${(size / 1024).toFixed(2)} kB`;
8
+ }
9
+
10
+ if (size < 1024 * 1024 * 1024) {
11
+ return `${(size / 1024 / 1024).toFixed(2)} MB`;
12
+ }
13
+
14
+ return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`;
15
+ }
package/src/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import FilePicker from "./FilePicker";
2
+ import FileManager from "./FileManager";
3
+
4
+ export { FilePicker, FileManager };
package/src/styles.css ADDED
@@ -0,0 +1,79 @@
1
+ @layer raketa-builder {
2
+ .r-file-input-upload-button input[type="file"] {
3
+ display: none;
4
+ }
5
+
6
+ .r-file-input-upload-button label {
7
+ cursor: pointer;
8
+ }
9
+
10
+ /* Dropzone modal overrides*/
11
+ .r-dropzone-modal {
12
+ position: fixed;
13
+ top: 0;
14
+ right: 0;
15
+ bottom: 0;
16
+ left: 0;
17
+ z-index: 1200;
18
+ display: flex;
19
+ justify-content: center;
20
+ align-items: center;
21
+ transition: 0.3s all ease-in-out;
22
+ }
23
+
24
+ .r-dropzone-modal-active {
25
+ top: 1rem;
26
+ right: 1rem;
27
+ bottom: 1rem;
28
+ left: 1rem;
29
+ border-radius: 5px;
30
+ background-color: var(--r-lighter-gray);
31
+ }
32
+
33
+ .r-dropzone-modal .r-modal-inner {
34
+ display: flex;
35
+ flex-direction: column;
36
+ height: 80vh;
37
+ }
38
+ .r-dropzone-modal .r-modal-content {
39
+ height: 100%;
40
+ overflow-y: auto;
41
+ }
42
+
43
+ .r-file-input-file-row {
44
+ cursor: pointer;
45
+ }
46
+
47
+ .r-file-input-delete-icon {
48
+ display: none;
49
+ color: var(--r-gray);
50
+ width: auto;
51
+ height: 0.8rem;
52
+ }
53
+
54
+ .r-file-input-delete-icon:hover {
55
+ color: var(--r-danger);
56
+ }
57
+
58
+ .r-file-input-file-row:hover {
59
+ border-bottom: 1px solid var(--r-gray);
60
+ }
61
+
62
+ .r-file-input-file-row:hover .r-file-input-delete-icon {
63
+ display: block;
64
+ }
65
+
66
+ .r-file-input-file-row-active {
67
+ background-color: var(--r-true-white);
68
+ }
69
+
70
+ .r-file-progress {
71
+ padding: 0.5rem 0;
72
+ border-bottom: 1px solid var(--r-light-gray);
73
+ transition: all 0.3s ease-in-out;
74
+ }
75
+
76
+ .r-file-progress:hover {
77
+ border-color: var(--r-gray);
78
+ }
79
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "tsconfig/react-library.json",
3
+ "include": ["src"],
4
+ "exclude": ["dist", "build", "node_modules"]
5
+ }