cloudrop 0.1.1 → 0.3.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 +115 -0
- package/README.md +34 -4
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/drizzle.js +3 -3
- package/dist/adapters/drizzle.js.map +1 -1
- package/dist/adapters/prisma.d.ts +1 -1
- package/dist/adapters/prisma.js +1 -1
- package/dist/adapters/sql.d.ts +4 -1
- package/dist/adapters/sql.js +8 -1
- package/dist/adapters/sql.js.map +1 -1
- package/dist/cli.js +2045 -0
- package/dist/{client-Dj6ON4MN.d.ts → client-CP_ajLF4.d.ts} +43 -25
- package/dist/{client-Y1zUEbCj.js → client-DxP3uv8V.js} +172 -44
- package/dist/client-DxP3uv8V.js.map +1 -0
- package/dist/client.d.ts +3 -3
- package/dist/client.js +1 -1
- package/dist/errors-CUxMmFAe.js.map +1 -1
- package/dist/index.d.ts +92 -7
- package/dist/index.js +432 -152
- package/dist/index.js.map +1 -1
- package/dist/next.d.ts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/react.d.ts +18 -4
- package/dist/react.js +23 -3
- package/dist/react.js.map +1 -1
- package/dist/{route-CspI1Ypt.js → route-C8-YjzdY.js} +3 -2
- package/dist/{route-CspI1Ypt.js.map → route-C8-YjzdY.js.map} +1 -1
- package/dist/{store-BfCJejGh.d.ts → store-B539nY3J.d.ts} +41 -3
- package/dist/testing.d.ts +81 -0
- package/dist/testing.js +1243 -0
- package/dist/testing.js.map +1 -0
- package/dist/{transactional-DnvnGsVH.js → transactional-CiNwMiDb.js} +215 -105
- package/dist/transactional-CiNwMiDb.js.map +1 -0
- package/dist/{types-BrAx3dA4.d.ts → types-CFfMw-n_.d.ts} +1 -1
- package/docs/README.md +30 -0
- package/docs/bucket-setup.md +226 -0
- package/docs/client.md +386 -0
- package/docs/command.md +129 -0
- package/docs/deployment.md +169 -0
- package/docs/errors.md +150 -0
- package/docs/hono.md +276 -0
- package/docs/react.md +508 -0
- package/docs/resume.md +253 -0
- package/docs/server.md +603 -0
- package/docs/store.md +804 -0
- package/docs/testing-your-app.md +328 -0
- package/docs/troubleshooting.md +176 -0
- package/package.json +16 -8
- package/dist/client-Y1zUEbCj.js.map +0 -1
- package/dist/transactional-DnvnGsVH.js.map +0 -1
package/docs/react.md
ADDED
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
# React
|
|
2
|
+
|
|
3
|
+
This page is for React developers adding uploads to their components. `cloudrop/react` turns the browser client into two
|
|
4
|
+
hooks: `useUpload` for a file input, a drop zone and a list of files with progress and controls, and `useResumable` for
|
|
5
|
+
continuing large uploads after a reload. They are a thin layer over [`cloudrop/client`](client.md): every upload is a
|
|
6
|
+
client job, and the hooks only render it.
|
|
7
|
+
|
|
8
|
+
This page covers setup, a one-file input, a list of several files with progress and controls, drag and drop, resume
|
|
9
|
+
after a reload, building a full upload UI on the hooks, what each hook returns, and how the hooks behave under server
|
|
10
|
+
rendering, StrictMode and unmounting.
|
|
11
|
+
|
|
12
|
+
## Set up
|
|
13
|
+
|
|
14
|
+
React 18 or 19 is required; `react` is an optional peer dependency of `cloudrop`, needed only by this entry. Create the
|
|
15
|
+
hooks once, in a module of their own:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
// lib/upload.ts
|
|
19
|
+
import { createUploadHooks } from "cloudrop/react";
|
|
20
|
+
import type { cloudrop } from "./cloudrop"; // a type import: no server code or secret reaches the browser
|
|
21
|
+
|
|
22
|
+
export const { useUpload, useResumable } = createUploadHooks<typeof cloudrop>();
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Import `lib/upload.ts` only from `"use client"` modules. A Server Component that imports it pulls `cloudrop/react` into
|
|
26
|
+
the server's module graph, where React exports no `useState` or `useSyncExternalStore`, and the build fails.
|
|
27
|
+
|
|
28
|
+
`createUploadHooks` takes the [client's options](client.md#create-a-client) (`basePath`, `concurrency`, `namespace`
|
|
29
|
+
and the rest), or `{ client }` to share a client you already created for the same server's type. With options, the
|
|
30
|
+
client is created at the first upload, the first `useResumable` read or `close()` in the browser, never while a server
|
|
31
|
+
renders the page. A wrong option never throws from your code: `upload()`, `resume()` and `refresh()` resolve
|
|
32
|
+
`{ data: null, error }` with its `INVALID_CONFIG` error, and a pick or a drop, which has no caller to resolve to, throws
|
|
33
|
+
it in a separate task, so it reaches the console and your error reporting.
|
|
34
|
+
|
|
35
|
+
The factory also returns `close()`, the client's [`close()`](client.md#close-the-client) for every route its hooks
|
|
36
|
+
upload to: see [Signed-in users](#signed-in-users).
|
|
37
|
+
|
|
38
|
+
The type argument gives the hooks your route names, each route's metadata and what each route's `onComplete` returns.
|
|
39
|
+
`useUpload("avatar")` knows the rest from the route name.
|
|
40
|
+
|
|
41
|
+
The hooks keep their uploads in the factory, one list per route. Every `useUpload("documents")` of these hooks shows the
|
|
42
|
+
same files, and a component that unmounts and mounts again, after a navigation or when a dialog closes and opens again,
|
|
43
|
+
finds its running and failed files there, and a failed file's `retry()` still sends it. That is why the factory is
|
|
44
|
+
created once, at module level: a factory created inside a component would start an empty list on every mount.
|
|
45
|
+
|
|
46
|
+
## One file
|
|
47
|
+
|
|
48
|
+
```tsx
|
|
49
|
+
"use client";
|
|
50
|
+
import { useUpload } from "../lib/upload";
|
|
51
|
+
|
|
52
|
+
export function AvatarPicker() {
|
|
53
|
+
const { files, getInputProps } = useUpload("avatar", { accept: "image/*" });
|
|
54
|
+
const avatar = files.at(-1);
|
|
55
|
+
return (
|
|
56
|
+
<label>
|
|
57
|
+
Avatar <input {...getInputProps()} />
|
|
58
|
+
{avatar?.status === "uploading" && <progress value={avatar.progress} />}
|
|
59
|
+
{avatar?.error && <p role="alert">{avatar.error.message}</p>}
|
|
60
|
+
{avatar?.result && <p>Saved as {avatar.result.file.key}</p>}
|
|
61
|
+
</label>
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`getInputProps()` gives the input `type="file"`, `multiple`, `accept` and an `onChange` that uploads the picked files.
|
|
67
|
+
It then clears the input, so picking the same file again uploads it again: a browser fires no `change` for an
|
|
68
|
+
unchanged selection.
|
|
69
|
+
|
|
70
|
+
`accept` only filters the file picker. The route's own `accept` decides on the server, and a file it refuses ends
|
|
71
|
+
`failed` with `FILE_TYPE_NOT_ALLOWED`.
|
|
72
|
+
|
|
73
|
+
## Several files, with progress and controls
|
|
74
|
+
|
|
75
|
+
```tsx
|
|
76
|
+
"use client";
|
|
77
|
+
import { useUpload } from "../lib/upload";
|
|
78
|
+
|
|
79
|
+
export function DocumentUploader({ folderId }: { folderId: string }) {
|
|
80
|
+
const { files, totals, isUploading, getInputProps, pause, resume, abort, clear } = useUpload("documents", {
|
|
81
|
+
metadata: { folderId },
|
|
82
|
+
multiple: true,
|
|
83
|
+
});
|
|
84
|
+
return (
|
|
85
|
+
<section>
|
|
86
|
+
<input {...getInputProps()} aria-label="Documents" />
|
|
87
|
+
<progress value={totals.progress} />
|
|
88
|
+
<button type="button" onClick={pause} disabled={!isUploading}>Pause all</button>
|
|
89
|
+
<button type="button" onClick={() => resume()}>Resume all</button>
|
|
90
|
+
<button type="button" onClick={abort}>Cancel all</button>
|
|
91
|
+
<button type="button" onClick={clear}>Clear finished</button>
|
|
92
|
+
<ul>
|
|
93
|
+
{files.map((file) => (
|
|
94
|
+
<li key={file.id}>
|
|
95
|
+
{file.name}: {file.status} {Math.round(file.progress * 100)}%
|
|
96
|
+
{file.status === "uploading" && <button type="button" onClick={file.pause}>Pause</button>}
|
|
97
|
+
{file.status === "paused" && <button type="button" onClick={file.resume}>Resume</button>}
|
|
98
|
+
{file.status === "failed" && <button type="button" onClick={() => file.retry()}>Retry</button>}
|
|
99
|
+
{file.error && <span role="alert"> {file.error.message}</span>}
|
|
100
|
+
</li>
|
|
101
|
+
))}
|
|
102
|
+
</ul>
|
|
103
|
+
</section>
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
- `files` holds every file of the uploads started on this route through these hooks, from any component, in start
|
|
109
|
+
order. Each is the client's
|
|
110
|
+
[file snapshot](client.md#snapshots-and-react) (`status`, `bytes`, `progress`, `speed`, `eta`, `error`, `result`)
|
|
111
|
+
with that file's `pause`, `resume`, `abort` and `retry`. A file's object changes only when that file changes, so a
|
|
112
|
+
`memo` row renders again only for its own file.
|
|
113
|
+
- `totals` adds the uploads up as a job's totals do: failed and cancelled files are left out of the bytes, so they
|
|
114
|
+
never hold the bar below 1.
|
|
115
|
+
- `metadata` is read from the latest render: when `folderId` changes, the next upload sends the new one. It is required
|
|
116
|
+
when the route's schema requires it, and TypeScript says so.
|
|
117
|
+
- `clear()` removes the uploads whose every file ended done or cancelled, for every component on the route. An upload
|
|
118
|
+
with a running or failed file stays: a failed file can still be retried, and the client keeps what it needs for that.
|
|
119
|
+
Until `clear()` or a reload, the hooks keep every upload with its `File`, so call `clear()` after a page that pastes
|
|
120
|
+
or drops many large files is done with them.
|
|
121
|
+
- `pause()`, `resume()`, `abort()` and `retry()` act on every file in `files`, so on the route's uploads that another
|
|
122
|
+
component started too.
|
|
123
|
+
|
|
124
|
+
## Drag and drop
|
|
125
|
+
|
|
126
|
+
```tsx
|
|
127
|
+
"use client";
|
|
128
|
+
import { useUpload } from "../lib/upload";
|
|
129
|
+
|
|
130
|
+
export function DropZone() {
|
|
131
|
+
const { files, isDragOver, getDropProps, getInputProps } = useUpload("documents", {
|
|
132
|
+
metadata: { folderId: "inbox" },
|
|
133
|
+
multiple: true,
|
|
134
|
+
});
|
|
135
|
+
return (
|
|
136
|
+
<div {...getDropProps()} style={{ outline: isDragOver ? "2px dashed" : "none", padding: "2rem" }}>
|
|
137
|
+
<p>Drop files here, or <input {...getInputProps()} aria-label="Choose files" /></p>
|
|
138
|
+
<p>{files.length} files</p>
|
|
139
|
+
</div>
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`getDropProps()` works on any element. `isDragOver` stays true while the drag crosses the element's children and turns
|
|
145
|
+
false when it leaves or drops. A hook without `multiple` uploads only the first dropped file, as its input takes one.
|
|
146
|
+
Only drags that carry files count: dragged text or a link keeps the browser's own behaviour, such as dropping text
|
|
147
|
+
into an input inside the zone.
|
|
148
|
+
|
|
149
|
+
## Start uploads yourself
|
|
150
|
+
|
|
151
|
+
`upload(files, { metadata })` starts one upload and resolves with its
|
|
152
|
+
[`UploadResult`](client.md#jobs-progress-pause-and-retry) once every file has first settled. It takes a `File`, an array
|
|
153
|
+
or a `FileList`, checked as the client checks them: anything that is not a `File` of this page, such as one from
|
|
154
|
+
another frame, resolves `INVALID_INPUT`. `null` or an empty list resolves `null` and starts nothing. The call's
|
|
155
|
+
metadata replaces the hook's.
|
|
156
|
+
|
|
157
|
+
```tsx
|
|
158
|
+
"use client";
|
|
159
|
+
import { useUpload } from "../lib/upload";
|
|
160
|
+
|
|
161
|
+
export function PasteTarget() {
|
|
162
|
+
const { upload } = useUpload("documents", { metadata: { folderId: "inbox" } });
|
|
163
|
+
return (
|
|
164
|
+
<textarea
|
|
165
|
+
aria-label="Paste files here"
|
|
166
|
+
onPaste={async (event) => {
|
|
167
|
+
const result = await upload(event.clipboardData.files);
|
|
168
|
+
if (result?.error) console.warn(result.error.message);
|
|
169
|
+
}}
|
|
170
|
+
/>
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`upload`, `pause`, `resume`, `abort`, `retry`, `clear` and `getDropProps` keep their identity across renders, and
|
|
176
|
+
`getInputProps` keeps it while `multiple` and `accept` stay the same, so an effect that lists one of them in its
|
|
177
|
+
dependencies does not run again on every render.
|
|
178
|
+
|
|
179
|
+
## Resume after a reload
|
|
180
|
+
|
|
181
|
+
```tsx
|
|
182
|
+
"use client";
|
|
183
|
+
import { useResumable, useUpload } from "../lib/upload";
|
|
184
|
+
|
|
185
|
+
export function Unfinished() {
|
|
186
|
+
const { uploads } = useResumable("documents");
|
|
187
|
+
const { files, resume, clear } = useUpload("documents", { metadata: { folderId: "inbox" } });
|
|
188
|
+
return (
|
|
189
|
+
<ul>
|
|
190
|
+
{uploads.map((upload) => (
|
|
191
|
+
<li key={upload.id}>
|
|
192
|
+
{upload.name} was not finished. Pick it again to continue:{" "}
|
|
193
|
+
<input
|
|
194
|
+
type="file"
|
|
195
|
+
aria-label={`Pick ${upload.name} again`}
|
|
196
|
+
onChange={(event) => {
|
|
197
|
+
const file = event.currentTarget.files?.[0];
|
|
198
|
+
if (file) void resume(upload, file);
|
|
199
|
+
}}
|
|
200
|
+
/>
|
|
201
|
+
</li>
|
|
202
|
+
))}
|
|
203
|
+
{files.map((file) => (
|
|
204
|
+
<li key={file.id}>
|
|
205
|
+
{file.name}: {Math.round(file.progress * 100)}%
|
|
206
|
+
{file.status === "failed" && (
|
|
207
|
+
<>
|
|
208
|
+
<span role="alert"> {file.error?.message}</span>
|
|
209
|
+
<button type="button" onClick={() => file.retry()}>Retry</button>
|
|
210
|
+
<button type="button" onClick={() => { file.abort(); clear(); }}>Dismiss</button>
|
|
211
|
+
</>
|
|
212
|
+
)}
|
|
213
|
+
</li>
|
|
214
|
+
))}
|
|
215
|
+
</ul>
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`useResumable(route?)` returns `{ uploads, discarding, refresh, discard, forget }`. `uploads` is the client's `resumable()` list, of
|
|
221
|
+
one route or of every route, newest first. It leaves out the uploads this page holds: a file that is running, paused, or
|
|
222
|
+
failed and kept for `retry()`, and an upload while its resume runs. A failed file is continued with `files[n].retry()`,
|
|
223
|
+
never `resume()`, which would be refused. A listed upload leaves the list as soon as its resume starts.
|
|
224
|
+
|
|
225
|
+
A refused resume, `UPLOAD_IN_USE` while another tab sends the upload or `INVALID_INPUT` for a different file, stays in
|
|
226
|
+
`files` as a failed file with its error, and the upload is listed again: `retry()` checks again, and `abort()` ends the
|
|
227
|
+
row without touching the upload, which stays listed. Dismiss on a file that had already started, a resume that passed
|
|
228
|
+
its checks or a new upload, discards the upload: `abort()` tells the server to delete what it sent, unless a
|
|
229
|
+
`/complete` may have finished it.
|
|
230
|
+
|
|
231
|
+
The list is read after mount, when an upload of these hooks starts, whenever one of its files ends or starts again, and
|
|
232
|
+
when it settles, so a record the client deletes, for a file that ends done or is cancelled, leaves the list at once.
|
|
233
|
+
`refresh()` reads it again and resolves with the client's `Result`, whose `error` says why the list is empty. `uploads`
|
|
234
|
+
is `[]` on the server, before the first read and when the read failed. An upload started on a shared client directly,
|
|
235
|
+
not through the hooks, is not followed: call `refresh()` after it.
|
|
236
|
+
|
|
237
|
+
`resume(upload, file)` continues a record with the file the user picked again, as one more upload in the hook's
|
|
238
|
+
`files`, which every component on the hook's route shows. A browser never gives a page a file back after a reload, so
|
|
239
|
+
the user has to pick it. What counts as the same file, and what the server is asked first:
|
|
240
|
+
[Resume after reload](resume.md).
|
|
241
|
+
|
|
242
|
+
`discard(upload)` drops a listed upload without its file: the client's
|
|
243
|
+
[`discard()`](resume.md#discard-one-upload) tells the server to abort it and deletes its record, and the list is read
|
|
244
|
+
again. It resolves `{ data: { aborted }, error }`; on an error, such as no connection, the upload stays listed.
|
|
245
|
+
Meanwhile `discarding` holds the upload's id, until the list is read again: a second `discard()` of it would answer
|
|
246
|
+
`UPLOAD_IN_USE`, so disable its button while `discarding.has(upload.id)`.
|
|
247
|
+
`forget()` is the client's `forget()`: it deletes every record of the client's namespace, of every route, sending no
|
|
248
|
+
`/abort`, and reads the list again; call it at sign-out. Either one also makes every other `useResumable` of the
|
|
249
|
+
factory read its list again, such as a badge that counts every route's uploads. Neither needs the client itself.
|
|
250
|
+
|
|
251
|
+
## Signed-in users
|
|
252
|
+
|
|
253
|
+
The module-level factory of [Set up](#set-up) suits an app without accounts. An app where users sign in needs a client
|
|
254
|
+
per user, created with the user's id as its `namespace` (see [Resume](resume.md#namespace-and-sign-out)): one client
|
|
255
|
+
for everyone would list one user's unfinished uploads to the next user of the browser. Create each user's client and
|
|
256
|
+
hooks once, provide them in a context keyed by the user, and close the other users' clients when the user changes:
|
|
257
|
+
|
|
258
|
+
```tsx
|
|
259
|
+
// lib/upload.ts
|
|
260
|
+
"use client";
|
|
261
|
+
import { createCloudropClient } from "cloudrop/client";
|
|
262
|
+
import { createUploadHooks } from "cloudrop/react";
|
|
263
|
+
import { createContext, useContext, useEffect } from "react";
|
|
264
|
+
import type { cloudrop } from "./cloudrop"; // a type import
|
|
265
|
+
|
|
266
|
+
function createUploads(userId: string) {
|
|
267
|
+
const client = createCloudropClient<typeof cloudrop>({ namespace: userId });
|
|
268
|
+
return { client, ...createUploadHooks<typeof cloudrop>({ client }) };
|
|
269
|
+
}
|
|
270
|
+
export type Uploads = ReturnType<typeof createUploads>;
|
|
271
|
+
|
|
272
|
+
const byUser = new Map<string, Uploads>();
|
|
273
|
+
export function uploadsFor(userId: string): Uploads {
|
|
274
|
+
const known = byUser.get(userId) ?? createUploads(userId);
|
|
275
|
+
byUser.set(userId, known);
|
|
276
|
+
return known;
|
|
277
|
+
}
|
|
278
|
+
export const UploadsContext = createContext(uploadsFor(""));
|
|
279
|
+
export const useUploads = () => useContext(UploadsContext);
|
|
280
|
+
|
|
281
|
+
/** Once the page shows `userId`, every other user's uploads stop, and their records stay for that user. */
|
|
282
|
+
export function useCloseOtherUsers(userId: string) {
|
|
283
|
+
useEffect(() => {
|
|
284
|
+
for (const [id, uploads] of byUser) {
|
|
285
|
+
if (id === userId) continue;
|
|
286
|
+
uploads.close(); // a closed client stays closed: the user's next sign-in gets a new one
|
|
287
|
+
byUser.delete(id);
|
|
288
|
+
}
|
|
289
|
+
}, [userId]);
|
|
290
|
+
}
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
```tsx
|
|
294
|
+
// The app's root: keyed by the user, so a new user's components mount with that user's hooks.
|
|
295
|
+
const userId = useSession().data?.user.id ?? ""; // your auth library's session
|
|
296
|
+
useCloseOtherUsers(userId);
|
|
297
|
+
// React 19 renders a context as its provider; on React 18 write <UploadsContext.Provider>.
|
|
298
|
+
<UploadsContext key={userId} value={uploadsFor(userId)}>
|
|
299
|
+
{/* the app */}
|
|
300
|
+
</UploadsContext>;
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Sign out in this order:
|
|
304
|
+
|
|
305
|
+
```tsx
|
|
306
|
+
const { close, client } = useUploads();
|
|
307
|
+
|
|
308
|
+
async function signOut() {
|
|
309
|
+
await close({ abort: true }); // first: cancels every upload of every route, and nothing asks /upload any more
|
|
310
|
+
await client.forget(); // deletes the user's unfinished uploads and the tokens they hold
|
|
311
|
+
await auth.signOut(); // your auth library's sign-out
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
- **Close before you forget.** `forget()` deletes records and stops nothing (see
|
|
316
|
+
[Resume](resume.md#namespace-and-sign-out)). An upload still waiting for its ticket would ask `/upload` after
|
|
317
|
+
`forget()`, save a new record, and, once the session cookie changed, ask with the next user's session.
|
|
318
|
+
- **`close({ abort: true })` cancels** every file of every route the hooks upload to, as each file's `abort()` does:
|
|
319
|
+
its `/abort` is sent with the file's own upload token, so it reaches the server whoever is signed in by then, and
|
|
320
|
+
with the [store](store.md) the file's row ends `aborted` and its bytes stop counting against the quota. A file whose
|
|
321
|
+
`/complete` may already have finished is kept, not deleted. `close()` resolves once each `/abort` was answered, so a
|
|
322
|
+
`headers` function still finds the session it reads; they go with `keepalive` too.
|
|
323
|
+
- **`close()` without options** is for a user who changed without signing out here, such as a sign-in in another tab:
|
|
324
|
+
this tab sees it when its session hook does, and `useCloseOtherUsers` then closes the last user's client. Its uploads
|
|
325
|
+
stop without an `/abort`, as when a tab closes, so each unfinished multipart upload keeps its record, and that user
|
|
326
|
+
resumes it on their next sign-in. The cookie changed earlier, when the other tab signed in: an `/upload` this tab
|
|
327
|
+
sent in between, for a queued file or a retry, went with the new user's session, and that file became that user's.
|
|
328
|
+
- **After `close()`** every `upload()` and `resume()` of the hooks resolves `CLIENT_CLOSED` without a request.
|
|
329
|
+
`useResumable()` and `forget()` keep working. The first `close()` decides: a later one, with or without options,
|
|
330
|
+
changes nothing. A sign-out that fails leaves the page on a closed client, so reload then, as the example's
|
|
331
|
+
`src/components/auth-panel.tsx` does after every sign-out.
|
|
332
|
+
- **Keep the hooks per user.** A factory keeps its uploads in memory, so `uploadsFor` returns the same one while the
|
|
333
|
+
same user stays signed in, and a component that unmounts finds its files again on its next mount.
|
|
334
|
+
- **Effects, not render.** `close()` is permanent, so call it from an event handler or from an effect that runs again
|
|
335
|
+
harmlessly, as `useCloseOtherUsers` does; never from an effect's cleanup, which StrictMode runs once on mount.
|
|
336
|
+
|
|
337
|
+
## Build your upload UI
|
|
338
|
+
|
|
339
|
+
cloudrop ships no components. A ready-made upload widget would bring its own look and icon set into your app, and the
|
|
340
|
+
hooks already hold everything a UI needs: build it from your own components, in your own style. The home page of
|
|
341
|
+
[`examples/next`](https://github.com/vcode-sh/cloudrop/blob/main/examples/next) is a full upload UI built this way, with shadcn on Base UI, Tailwind and Tabler
|
|
342
|
+
icons, in four components of 30 to 125 lines under `components/upload/`. Three of them call `useUpload("files")`
|
|
343
|
+
themselves and show one list, because every hook of the factory shares the route's files; the row takes one file.
|
|
344
|
+
|
|
345
|
+
**Drop zone.** A `<label>` with `getDropProps()` around a visually hidden input with `getInputProps()`: a click
|
|
346
|
+
anywhere opens the file picker, Tab reaches the input and Enter opens the picker, and dropped files upload. Hide the
|
|
347
|
+
input with an `sr-only` class, not `display: none`, so it keeps its keyboard focus and its name.
|
|
348
|
+
|
|
349
|
+
```tsx
|
|
350
|
+
const { isDragOver, getDropProps, getInputProps } = useUpload("files", { multiple: true });
|
|
351
|
+
return (
|
|
352
|
+
<label {...getDropProps()} data-drag-over={isDragOver || undefined} className="… has-focus-visible:ring-3">
|
|
353
|
+
<IconUpload aria-hidden />
|
|
354
|
+
<span>{isDragOver ? "Drop to upload" : "Drop files here, or click to choose"}</span>
|
|
355
|
+
<input {...getInputProps()} aria-label="Files to upload" className="sr-only" />
|
|
356
|
+
</label>
|
|
357
|
+
);
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
**File states.** Most design systems draw a file in a handful of states. The example maps the client's seven statuses
|
|
361
|
+
on the five of shadcn's `Attachment` and keeps the difference in the line under the name:
|
|
362
|
+
|
|
363
|
+
| `file.status` | Attachment state | Line under the name |
|
|
364
|
+
| --- | --- | --- |
|
|
365
|
+
| `queued` | `idle` | size, waiting for a connection |
|
|
366
|
+
| `uploading` | `uploading` | bytes of size, speed, time left |
|
|
367
|
+
| `paused` | `idle` | paused at n % |
|
|
368
|
+
| `completing` | `processing` | all bytes sent, finishing |
|
|
369
|
+
| `done` | `done` | size, `stored as` the key from `file.result.data` |
|
|
370
|
+
| `failed` | `error` | `file.error.code: file.error.message`, never cut short |
|
|
371
|
+
| `aborted` | `idle` | Cancelled |
|
|
372
|
+
|
|
373
|
+
**File list.** One row per entry of `files`, with the controls its status allows. A file's object changes only when that
|
|
374
|
+
file does, so a `memo` row renders again only for its own progress. Pause and Resume are one button whose label
|
|
375
|
+
changes, so the element, and a keyboard user's focus, stay put; Retry and Cancel remove their own button, so they move
|
|
376
|
+
focus to the row first.
|
|
377
|
+
|
|
378
|
+
```tsx
|
|
379
|
+
export const UploadRow = memo(function UploadRow({ file }: { file: FileItem }) {
|
|
380
|
+
const row = useRef<HTMLLIElement>(null);
|
|
381
|
+
const thenFocusRow = (action: () => unknown) => () => {
|
|
382
|
+
row.current?.focus();
|
|
383
|
+
void action();
|
|
384
|
+
};
|
|
385
|
+
const moving = file.status === "queued" || file.status === "uploading";
|
|
386
|
+
return (
|
|
387
|
+
<li ref={row} tabIndex={-1}>
|
|
388
|
+
<Attachment state={ATTACHMENT_STATE[file.status]}>
|
|
389
|
+
<AttachmentTitle>{file.name}</AttachmentTitle>
|
|
390
|
+
<AttachmentDescription>{statusLine(file)}</AttachmentDescription>
|
|
391
|
+
{(moving || file.status === "paused") && (
|
|
392
|
+
<>
|
|
393
|
+
<Progress value={Math.floor(file.progress * 100)} aria-label={`${file.name} progress`} />
|
|
394
|
+
<AttachmentAction
|
|
395
|
+
aria-label={`${moving ? "Pause" : "Resume"} ${file.name}`}
|
|
396
|
+
onClick={moving ? file.pause : file.resume}
|
|
397
|
+
>
|
|
398
|
+
{moving ? <IconPlayerPause /> : <IconPlayerPlay />}
|
|
399
|
+
</AttachmentAction>
|
|
400
|
+
</>
|
|
401
|
+
)}
|
|
402
|
+
{file.status === "failed" && (
|
|
403
|
+
<AttachmentAction aria-label={`Retry ${file.name}`} onClick={thenFocusRow(file.retry)}>…</AttachmentAction>
|
|
404
|
+
)}
|
|
405
|
+
{/* Cancel likewise, for every status but done and aborted. */}
|
|
406
|
+
</Attachment>
|
|
407
|
+
</li>
|
|
408
|
+
);
|
|
409
|
+
});
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
`FileItem` is `UploadItem<RouteResult<typeof cloudrop, "files">>`. Above the rows, `totals` gives one bar and a line
|
|
413
|
+
such as "2 of 3 uploaded, 12.0 MiB of 40.0 MiB". The hook's `pause`, `resume`, `abort`, `retry` and `clear` act on the
|
|
414
|
+
whole list, each on the files its contract names (see [What the hooks return](#what-the-hooks-return)): the example
|
|
415
|
+
enables each button from `files` by the same rule, so none is offered when it would do nothing. For screen readers,
|
|
416
|
+
keep a visually hidden `role="status"` line rendered from the start, and change it in coarse steps (the example rounds
|
|
417
|
+
`totals.progress` down to 10 %): a polite region fed every progress event would never stop talking.
|
|
418
|
+
|
|
419
|
+
**Unfinished uploads.** After a reload, `useResumable("files").uploads` lists what can be continued. A browser never
|
|
420
|
+
hands a file back, so each row has a file input; the picked file goes to `resume(upload, file)` and the resumed upload
|
|
421
|
+
joins `files` like any other. A different file is refused before any request and shows as a failed row. Each row's
|
|
422
|
+
Discard calls `discard(upload)`, which needs no file, and is disabled while it runs; on an error the upload stays
|
|
423
|
+
listed, so show the error's message.
|
|
424
|
+
|
|
425
|
+
```tsx
|
|
426
|
+
const { uploads, discarding, discard } = useResumable("files");
|
|
427
|
+
const { resume } = useUpload("files");
|
|
428
|
+
// For each upload:
|
|
429
|
+
<input
|
|
430
|
+
type="file"
|
|
431
|
+
aria-label={`Pick ${upload.name} again to resume`}
|
|
432
|
+
onChange={(event) => {
|
|
433
|
+
const file = event.currentTarget.files?.[0];
|
|
434
|
+
event.currentTarget.value = "";
|
|
435
|
+
if (file) void resume(upload, file);
|
|
436
|
+
}}
|
|
437
|
+
/>
|
|
438
|
+
<button
|
|
439
|
+
type="button"
|
|
440
|
+
aria-label={`Discard ${upload.name}`}
|
|
441
|
+
disabled={discarding.has(upload.id)}
|
|
442
|
+
onClick={() => void discard(upload)}
|
|
443
|
+
>
|
|
444
|
+
…
|
|
445
|
+
</button>
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
The example's **Discard all** discards every listed upload the same way, so each is aborted on the server. `forget()`
|
|
449
|
+
deletes the records alone and suits sign-out.
|
|
450
|
+
|
|
451
|
+
None of this depends on shadcn, Tailwind or Tabler. Radix, Base UI, MUI, Chakra, plain CSS, any icon set: the hooks
|
|
452
|
+
give data and functions, and the UI is yours. Why there is no registry: `M4-E1` in
|
|
453
|
+
[m4-dx.md](https://github.com/vcode-sh/cloudrop/blob/main/docs/decisions/m4-dx.md).
|
|
454
|
+
|
|
455
|
+
## What the hooks return
|
|
456
|
+
|
|
457
|
+
`useUpload(route, options?)`. Options: `metadata`, `multiple` (default `false`), `accept`.
|
|
458
|
+
|
|
459
|
+
| Field | What it is |
|
|
460
|
+
| --- | --- |
|
|
461
|
+
| `files` | Every file of the route's uploads, in start order, with its own `pause`, `resume`, `abort` and `retry`. |
|
|
462
|
+
| `totals` | `bytes`, `size`, `progress`, `speed`, `eta`, `done`, `failed`, `aborted` and `count` across those uploads. |
|
|
463
|
+
| `isUploading` | True while a file is queued, uploading or completing. A paused file is not uploading. |
|
|
464
|
+
| `isDragOver` | True while files are dragged over the element that has `getDropProps()`. |
|
|
465
|
+
| `upload(files, { metadata }?)` | Starts one upload; resolves with its `UploadResult`, or `null` for no file. |
|
|
466
|
+
| `getInputProps()` | `type`, `multiple`, `accept` and `onChange` for an `<input>`. |
|
|
467
|
+
| `getDropProps()` | `onDragEnter`, `onDragOver`, `onDragLeave` and `onDrop` for any element. |
|
|
468
|
+
| `pause()`, `resume()`, `abort()` | Pause, resume or cancel every file in `files`, as each file's own control does. |
|
|
469
|
+
| `retry()` | Sends every failed file again; resolves once they have settled. |
|
|
470
|
+
| `resume(upload, file)` | Continues a record from `useResumable`; resolves with its `UploadResult`. |
|
|
471
|
+
| `clear()` | Removes the uploads whose every file ended done or cancelled, for every component on the route. |
|
|
472
|
+
|
|
473
|
+
`useResumable(route?)`:
|
|
474
|
+
|
|
475
|
+
| Field | What it is |
|
|
476
|
+
| --- | --- |
|
|
477
|
+
| `uploads` | The unfinished uploads this browser can continue, newest first, without those this page holds. |
|
|
478
|
+
| `discarding` | The ids of the listed uploads this hook's `discard()` is dropping: disable their buttons meanwhile. |
|
|
479
|
+
| `refresh()` | Reads the list again; resolves with the client's `Result`. |
|
|
480
|
+
| `discard(upload)` | Aborts one listed upload without its file and deletes its record; resolves `{ aborted }` or the error. |
|
|
481
|
+
| `forget()` | Deletes every record of the client's namespace, of every route, sending no `/abort`. |
|
|
482
|
+
|
|
483
|
+
## Server rendering, StrictMode and unmounting
|
|
484
|
+
|
|
485
|
+
- **Server rendering.** React Server Components and server rendering load a `"use client"` module too. The hooks read a
|
|
486
|
+
constant empty state there (no files, zero totals, no resumable uploads) and never create the client, so nothing
|
|
487
|
+
touches `fetch`, IndexedDB or the page's lifecycle on the server, and the first browser render matches.
|
|
488
|
+
- **StrictMode.** No upload starts in an effect or during render, only in `upload()`, the input's `onChange`, a drop
|
|
489
|
+
and `resume()`. StrictMode's second render and second effect start nothing; `useResumable` only reads once more.
|
|
490
|
+
- **Unmounting.** A component that unmounts stops listening and cancels nothing. The client owns its uploads: they
|
|
491
|
+
finish, and a multipart upload's resume record stays. The route's list stays in the factory, so the next component
|
|
492
|
+
on the route shows those uploads and can retry a failed file; until the page reloads, `useResumable` does not list
|
|
493
|
+
them, because this page still holds them. Cancel on unmount yourself when that is what you want:
|
|
494
|
+
`useEffect(() => abort, [abort])`, which cancels every upload of the route, including other components'. Under
|
|
495
|
+
React 19's `<Activity mode="hidden">` that effect's cleanup runs too, so hiding counts as unmounting; without it, a
|
|
496
|
+
hidden component shows what its uploads did once it is visible again.
|
|
497
|
+
|
|
498
|
+
## Types
|
|
499
|
+
|
|
500
|
+
The hooks infer everything from the route name: `useUpload("avatar")` has `files[n].result` typed by the avatar route's
|
|
501
|
+
`onComplete`, and `metadata` typed by its schema, required when the schema requires it. A record from
|
|
502
|
+
`useResumable("documents")` resumes only into a `documents` hook; records of every route narrow by `upload.route`.
|
|
503
|
+
|
|
504
|
+
For a component that takes a file as a prop, `UploadItem<R>` is the type of one `files` entry, where `R` is the route's
|
|
505
|
+
result type: `UploadItem<RouteResult<typeof cloudrop, "documents">>`, with `RouteResult` from `cloudrop/client`. The
|
|
506
|
+
other types (`UploadHooks`, `UseUploadOptions`, `UseUploadResult`, `UseResumableResult`, `InputProps`, `DropProps`,
|
|
507
|
+
`UploadHooksOptions`) are exported from `cloudrop/react` too. `{ client }` takes only a client created for a server with
|
|
508
|
+
the same route names: `createCloudropClient<typeof cloudrop>()`.
|