@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.
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@raketa-builder/file-input",
3
+ "version": "0.1.0",
4
+ "main": "./dist/index.js",
5
+ "types": "./dist/index.d.ts",
6
+ "license": "MIT",
7
+ "scripts": {
8
+ "lint": "TIMING=1 eslint \"**/*.js\"",
9
+ "build": "tsup src/index.js --format cjs --loader \".js=jsx\"",
10
+ "dev": "tsup src/index.js --format cjs --loader \".js=jsx\" --watch"
11
+ },
12
+ "peerDependencies": {
13
+ "react": "18.2.0",
14
+ "react-dom": "18.2.0"
15
+ },
16
+ "dependencies": {
17
+ "react-dropzone": "14.2.3",
18
+ "ui": "*"
19
+ },
20
+ "devDependencies": {
21
+ "@types/react": "17.0.37",
22
+ "@types/react-dom": "17.0.11",
23
+ "eslint": "7.32.0",
24
+ "eslint-config-custom": "*",
25
+ "react": "18.2.0",
26
+ "tsconfig": "*",
27
+ "tsup": "6.5.0",
28
+ "typescript": "4.5.2"
29
+ }
30
+ }
@@ -0,0 +1,277 @@
1
+ const DOCUMENTS_QUERY = `
2
+ query($input: DocumentsInput!) {
3
+ documents(input: $input) {
4
+ list {
5
+ id
6
+ filename
7
+ mimeType
8
+ size
9
+ uploadStatus
10
+ url
11
+ createdAt
12
+ }
13
+ pagination {
14
+ cursor
15
+ }
16
+ }
17
+ }
18
+ `;
19
+
20
+ const CREATE_DOCUMENT_MUTATION = `
21
+ mutation($input: CreateDocumentInput!) {
22
+ createDocument(input: $input) {
23
+ document {
24
+ id
25
+ filename
26
+ mimeType
27
+ size
28
+ uploadStatus
29
+ url
30
+ createdAt
31
+ uploadUrl
32
+ }
33
+ errors {
34
+ key
35
+ message
36
+ codes {
37
+ key
38
+ placeholders
39
+ }
40
+ }
41
+ }
42
+ }
43
+ `;
44
+
45
+ const NOTIFY_UPLOADED_DOCUMENT_MUTATION = `
46
+ mutation($input: NotifyUploadedDocumentInput!) {
47
+ notifyUploadedDocument(input: $input) {
48
+ document {
49
+ id
50
+ filename
51
+ mimeType
52
+ size
53
+ uploadStatus
54
+ url
55
+ createdAt
56
+ }
57
+ errors {
58
+ key
59
+ message
60
+ codes {
61
+ key
62
+ placeholders
63
+ }
64
+ }
65
+ }
66
+ }
67
+ `;
68
+
69
+ const DELETE_DOCUMENT_MUTATION = `
70
+ mutation($input: DeleteDocumentInput!) {
71
+ deleteDocument(input: $input) {
72
+ document {
73
+ id
74
+ filename
75
+ mimeType
76
+ size
77
+ uploadStatus
78
+ url
79
+ createdAt
80
+ }
81
+ errors {
82
+ key
83
+ message
84
+ codes {
85
+ key
86
+ placeholders
87
+ }
88
+ }
89
+ }
90
+ }
91
+ `;
92
+
93
+ async function uploadFile(file, document, progressCallback) {
94
+ const blob = new Blob([new Uint8Array(file.size + 20)]);
95
+ const xhr = new XMLHttpRequest();
96
+
97
+ return new Promise((resolve) => {
98
+ xhr.upload.addEventListener("progress", (event) => {
99
+ if (event.lengthComputable) {
100
+ progressCallback({
101
+ type: "progress",
102
+ payload: {
103
+ loaded: event.loaded,
104
+ total: event.total,
105
+ },
106
+ });
107
+ }
108
+ });
109
+
110
+ xhr.addEventListener("loadend", (event) => {
111
+ // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
112
+ if (xhr.readyState === 4 && xhr.status === 200) {
113
+ progressCallback({
114
+ type: "uploaded",
115
+ payload: {},
116
+ });
117
+ } else {
118
+ progressCallback({
119
+ type: "errored",
120
+ payload: {
121
+ errors: `ReadyState: ${xhr.readyState} - ${xhr.status} - ${event.type}: ${event.loaded} bytes transferred.`,
122
+ },
123
+ });
124
+ }
125
+
126
+ resolve(xhr.readyState === 4 && xhr.status === 200);
127
+ });
128
+
129
+ xhr.withCredentials = false;
130
+ xhr.open("PUT", document.uploadUrl, true);
131
+ xhr.setRequestHeader("content-type", file.type);
132
+ xhr.send(blob);
133
+ });
134
+ }
135
+
136
+ export default class FileManager {
137
+ constructor(url, headers) {
138
+ this.url = url;
139
+ this.headers = headers;
140
+ }
141
+
142
+ async graphQLRequest(query, variables) {
143
+ return fetch(this.url, {
144
+ method: "POST",
145
+ headers: Object.assign(
146
+ { "Content-Type": "application/json" },
147
+ this.headers
148
+ ),
149
+ body: JSON.stringify({
150
+ query: query,
151
+ variables: variables,
152
+ }),
153
+ }).then((res) => res.json());
154
+ }
155
+
156
+ buildFilters(params) {
157
+ let filters = {
158
+ uploadStatus: "COMPLETED",
159
+ };
160
+
161
+ if (params?.mimeTypes?.length > 0) {
162
+ filters.mimeTypes = params.mimeTypes;
163
+ }
164
+
165
+ if (params?.excludeMimeTypes?.length > 0) {
166
+ filters.excludeMimeTypes = params.excludeMimeTypes;
167
+ }
168
+
169
+ if (params?.keyword) {
170
+ filters.keyword = params.keyword;
171
+ }
172
+
173
+ return filters;
174
+ }
175
+
176
+ buildVariables(params) {
177
+ const variables = {
178
+ input: {
179
+ filters: this.buildFilters(params),
180
+ },
181
+ };
182
+
183
+ if (params.nextCursor) {
184
+ variables.input.pagination = { cursor: params.nextCursor };
185
+ }
186
+
187
+ return variables;
188
+ }
189
+
190
+ async all(params = {}) {
191
+ return this.graphQLRequest(
192
+ DOCUMENTS_QUERY,
193
+ this.buildVariables(params)
194
+ ).then((d) => {
195
+ return d?.data.documents || {};
196
+ });
197
+ }
198
+
199
+ async createAndUpload(fileInfo, progressCallback) {
200
+ const { file, id } = fileInfo;
201
+
202
+ const { document, errors } = await this.create({
203
+ filename: file.name,
204
+ mime_type: file.type,
205
+ size: file.size,
206
+ });
207
+
208
+ if (errors) {
209
+ progressCallback(id, {
210
+ type: "errored",
211
+ payload: {
212
+ errors,
213
+ },
214
+ });
215
+ return;
216
+ }
217
+
218
+ const result = await uploadFile(file, document, (state) =>
219
+ progressCallback(id, state)
220
+ );
221
+
222
+ if (result) {
223
+ const notify = await this.notifyUploaded(document.id);
224
+
225
+ if (notify.errors) {
226
+ progressCallback(id, {
227
+ type: "errored",
228
+ payload: {
229
+ errors,
230
+ },
231
+ });
232
+ return;
233
+ }
234
+
235
+ progressCallback(id, {
236
+ type: "completed",
237
+ payload: {
238
+ document: notify.document,
239
+ },
240
+ });
241
+ }
242
+ }
243
+
244
+ async create(params) {
245
+ return this.graphQLRequest(CREATE_DOCUMENT_MUTATION, {
246
+ input: {
247
+ document: {
248
+ filename: params.filename,
249
+ mime_type: params.mime_type,
250
+ size: params.size,
251
+ },
252
+ },
253
+ }).then((d) => {
254
+ return d?.data?.createDocument || {};
255
+ });
256
+ }
257
+
258
+ async notifyUploaded(id) {
259
+ return this.graphQLRequest(NOTIFY_UPLOADED_DOCUMENT_MUTATION, {
260
+ input: {
261
+ id: id,
262
+ },
263
+ }).then((d) => {
264
+ return d?.data?.notifyUploadedDocument || {};
265
+ });
266
+ }
267
+
268
+ async destroy(id) {
269
+ return this.graphQLRequest(DELETE_DOCUMENT_MUTATION, {
270
+ input: {
271
+ id: id,
272
+ },
273
+ }).then((d) => {
274
+ return d?.data?.deleteDocument || {};
275
+ });
276
+ }
277
+ }
@@ -0,0 +1,73 @@
1
+ import React, { useCallback } from "react";
2
+ import { useDropzone } from "react-dropzone";
3
+ import { Modal, Button, cn } from "@raketa-builder/ui";
4
+
5
+ const DropZone = ({ children, onDrop }) => {
6
+ const onFilesDrop = useCallback(
7
+ (acceptedFiles) => {
8
+ onDrop(acceptedFiles);
9
+ },
10
+ [onDrop]
11
+ );
12
+
13
+ const { getRootProps, getInputProps, isDragActive } = useDropzone({
14
+ onDropAccepted: onFilesDrop,
15
+ noClick: true,
16
+ });
17
+
18
+ return (
19
+ <div
20
+ className={cn(
21
+ "r-reset",
22
+ "r-dropzone-modal",
23
+ isDragActive ? "r-dropzone-modal-active" : ""
24
+ )}
25
+ {...getRootProps()}
26
+ >
27
+ <input {...getInputProps()} />
28
+
29
+ <div>
30
+ {isDragActive && <strong className="r-fs-large">Drop here</strong>}
31
+ </div>
32
+
33
+ {!isDragActive && children}
34
+ </div>
35
+ );
36
+ };
37
+
38
+ const Dialog = ({
39
+ disablePrimary = false,
40
+ onClose,
41
+ onPrimary,
42
+ onDrop,
43
+ children,
44
+ }) => {
45
+ return (
46
+ <Modal
47
+ title="Files"
48
+ onClose={onClose}
49
+ onDrop={onDrop}
50
+ customWrapper={DropZone}
51
+ FooterContent={() => (
52
+ <>
53
+ <Button
54
+ type="button"
55
+ variant="primary"
56
+ disabled={disablePrimary}
57
+ onClick={onPrimary}
58
+ >
59
+ Select
60
+ </Button>
61
+
62
+ <Button type="button" variant="secondary" onClick={onClose}>
63
+ Cancel
64
+ </Button>
65
+ </>
66
+ )}
67
+ >
68
+ {children}
69
+ </Modal>
70
+ );
71
+ };
72
+
73
+ export default Dialog;
@@ -0,0 +1,130 @@
1
+ const VIDEO = ["video/3gpp", "video/3gpp2", "video/mp4", "video/webm"];
2
+
3
+ const AUDIO = [
4
+ "audio/webm",
5
+ "audio/wav",
6
+ "audio/mpeg",
7
+ "audio/aac",
8
+ "audio/midi",
9
+ "audio/x-midi",
10
+ "audio/ogg",
11
+ "audio/3gpp",
12
+ "audio/3gpp2",
13
+ "audio/m4a",
14
+ ];
15
+
16
+ const DOCUMENT = [
17
+ "application/pdf",
18
+ "application/msword",
19
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
20
+ "application/vnd.ms-excel",
21
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
22
+ "application/vnd.ms-powerpoint",
23
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
24
+ "text/plain",
25
+ "application/epub+zip",
26
+ "application/x-mobipocket-ebook",
27
+ "application/rtf",
28
+ "text/csv",
29
+ "application/vnd.apple.pages",
30
+ "application/vnd.apple.numbers",
31
+ "application/vnd.apple.keynote",
32
+ ];
33
+
34
+ const IMAGE = [
35
+ "image/png",
36
+ "image/x-png",
37
+ "image/vnd.mozilla.apng",
38
+ "image/jpeg",
39
+ "image/svg+xml",
40
+ "image/gif",
41
+ "image/avif",
42
+ "image/webp",
43
+ "application/postscript",
44
+ "mage/heic",
45
+ "mage/heic-sequence",
46
+ ];
47
+
48
+ const ARCHIVE = [
49
+ "application/zip",
50
+ "application/gzip",
51
+ "application/x-gtar",
52
+ "application/x-tar",
53
+ "application/x-rar-compressed",
54
+ "application/x-7z-compressed",
55
+ ];
56
+
57
+ const MIME_TYPES = IMAGE.concat(VIDEO)
58
+ .concat(DOCUMENT)
59
+ .concat(AUDIO)
60
+ .concat(ARCHIVE);
61
+
62
+ const MAPPING = {
63
+ video: VIDEO,
64
+ document: DOCUMENT,
65
+ image: IMAGE,
66
+ audio: AUDIO,
67
+ archive: ARCHIVE,
68
+ other: [],
69
+ };
70
+
71
+ const FILE_CATEGORIES = {
72
+ document: "Document",
73
+ archive: "Archive",
74
+ image: "Image",
75
+ video: "Video",
76
+ audio: "Audio",
77
+ other: "Other",
78
+ };
79
+
80
+ export function toMimeTypes(fileCategory) {
81
+ return MAPPING[fileCategory] || [];
82
+ }
83
+
84
+ export function toExcludedMimeTypes(fileCategory) {
85
+ if (fileCategory === "other") {
86
+ return MIME_TYPES;
87
+ }
88
+
89
+ return [];
90
+ }
91
+
92
+ export function toFileCategory(mimeType, format = "robot") {
93
+ let fileCategory = null;
94
+
95
+ Object.keys(FILE_CATEGORIES).forEach((key) => {
96
+ if (fileCategory) {
97
+ return;
98
+ }
99
+
100
+ if (MAPPING[key].find((mt) => mt === mimeType)) {
101
+ fileCategory = key;
102
+ }
103
+ });
104
+
105
+ if (!fileCategory) {
106
+ fileCategory = "other";
107
+ }
108
+
109
+ if (format === "human") {
110
+ return FILE_CATEGORIES[fileCategory] || fileCategory;
111
+ } else {
112
+ return fileCategory;
113
+ }
114
+ }
115
+
116
+ export function fileCategoriesOptions() {
117
+ return Object.keys(FILE_CATEGORIES).map((key) => [key, FILE_CATEGORIES[key]]);
118
+ }
119
+
120
+ export function sanitizeFileCategory(fileCategory) {
121
+ if (fileCategory === "other") {
122
+ return null;
123
+ }
124
+
125
+ if (Object.keys(FILE_CATEGORIES).includes(fileCategory)) {
126
+ return fileCategory;
127
+ }
128
+
129
+ return null;
130
+ }
@@ -0,0 +1,37 @@
1
+ import React from "react";
2
+ import {
3
+ FormGroup,
4
+ Label,
5
+ Input,
6
+ Hint,
7
+ Button,
8
+ Stack,
9
+ } from "@raketa-builder/ui";
10
+
11
+ const FileInput = ({ value, label, hint, onBrowse, onClear }) => {
12
+ const filename = value?.document?.filename;
13
+
14
+ return (
15
+ <FormGroup>
16
+ {label && <Label>{label}</Label>}
17
+
18
+ <Stack className="r-stack-justify-center" style={{ gap: "0.5rem" }}>
19
+ <Input
20
+ disabled
21
+ placeholder={filename ? filename : "No file selected"}
22
+ />
23
+
24
+ <Button type="button" variant="primary" onClick={onBrowse}>
25
+ Browse...
26
+ </Button>
27
+ <Button type="button" variant="secondary" onClick={() => onClear()}>
28
+ Clear
29
+ </Button>
30
+ </Stack>
31
+
32
+ {hint && <Hint>{hint}</Hint>}
33
+ </FormGroup>
34
+ );
35
+ };
36
+
37
+ export default FileInput;
@@ -0,0 +1,132 @@
1
+ import React from "react";
2
+ import { Button, Stack, Input, cn } from "@raketa-builder/ui";
3
+ import { fileSizeFormatter } from "./utils";
4
+ import { toFileCategory } from "./FileCategory";
5
+
6
+ const DeleteIcon = (props) => {
7
+ return (
8
+ <svg
9
+ width="24"
10
+ height="25"
11
+ viewBox="0 0 24 25"
12
+ fill="none"
13
+ xmlns="http://www.w3.org/2000/svg"
14
+ className="r-file-input-delete-icon"
15
+ {...props}
16
+ >
17
+ <path
18
+ d="M3 6.5H5H21"
19
+ stroke="currentColor"
20
+ strokeWidth="2"
21
+ strokeLinecap="round"
22
+ strokeLinejoin="round"
23
+ />
24
+ <path
25
+ d="M19 6.5V20.5C19 21.0304 18.7893 21.5391 18.4142 21.9142C18.0391 22.2893 17.5304 22.5 17 22.5H7C6.46957 22.5 5.96086 22.2893 5.58579 21.9142C5.21071 21.5391 5 21.0304 5 20.5V6.5M8 6.5V4.5C8 3.96957 8.21071 3.46086 8.58579 3.08579C8.96086 2.71071 9.46957 2.5 10 2.5H14C14.5304 2.5 15.0391 2.71071 15.4142 3.08579C15.7893 3.46086 16 3.96957 16 4.5V6.5"
26
+ stroke="currentColor"
27
+ strokeWidth="2"
28
+ strokeLinecap="round"
29
+ strokeLinejoin="round"
30
+ />
31
+ <path
32
+ d="M10 11.5V17.5"
33
+ stroke="currentColor"
34
+ strokeWidth="2"
35
+ strokeLinecap="round"
36
+ strokeLinejoin="round"
37
+ />
38
+ <path
39
+ d="M14 11.5V17.5"
40
+ stroke="currentColor"
41
+ strokeWidth="2"
42
+ strokeLinecap="round"
43
+ strokeLinejoin="round"
44
+ />
45
+ </svg>
46
+ );
47
+ };
48
+
49
+ const formatDate = (dateStr) =>
50
+ new Date(dateStr).toLocaleDateString(undefined, {
51
+ year: "numeric",
52
+ month: "long",
53
+ day: "numeric",
54
+ });
55
+
56
+ const FileList = ({
57
+ files,
58
+ fetching,
59
+ selected,
60
+ onMore,
61
+ onSelect,
62
+ onDelete,
63
+ }) => {
64
+ const showLoadMore = !fetching && onMore;
65
+
66
+ return (
67
+ <div className="r-reset">
68
+ <table className="r-table">
69
+ <thead>
70
+ <tr>
71
+ <th>Name</th>
72
+ <th>Type</th>
73
+ <th>Size</th>
74
+ <th>Uploaded</th>
75
+ </tr>
76
+ </thead>
77
+
78
+ <tbody>
79
+ {files.map((file) => (
80
+ <tr
81
+ key={file.id}
82
+ className={cn(
83
+ "r-file-input-file-row",
84
+ selected?.id === file.id ? "r-file-input-file-row-active" : ""
85
+ )}
86
+ onClick={() => onSelect(file.id)}
87
+ >
88
+ <td
89
+ style={{
90
+ width: "50%",
91
+ }}
92
+ >
93
+ <Stack
94
+ className="r-stack-align-center"
95
+ style={{ gap: "0.5rem" }}
96
+ >
97
+ <Input
98
+ type="radio"
99
+ checked={selected?.id === file.id}
100
+ readOnly
101
+ />
102
+
103
+ <div>{decodeURI(file.filename)}</div>
104
+ <DeleteIcon
105
+ onClick={(event) => {
106
+ event.stopPropagation();
107
+
108
+ if (confirm("Are you sure?")) {
109
+ onDelete(file.id);
110
+ }
111
+ }}
112
+ />
113
+ </Stack>
114
+ </td>
115
+ <td>{toFileCategory(file.mimeType, "human")}</td>
116
+ <td>{fileSizeFormatter(file.size)}</td>
117
+ <td>{formatDate(file.createdAt)}</td>
118
+ </tr>
119
+ ))}
120
+ </tbody>
121
+ </table>
122
+
123
+ {showLoadMore && (
124
+ <Button variant="secondary" disabled={fetching} onClick={onMore}>
125
+ Load more
126
+ </Button>
127
+ )}
128
+ </div>
129
+ );
130
+ };
131
+
132
+ export default FileList;