@startsimpli/hooks 0.4.44 → 0.4.46
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 +3 -3
- package/src/__tests__/useUpload.test.ts +151 -0
- package/src/index.ts +4 -0
- package/src/useUpload.ts +218 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@startsimpli/hooks",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.46",
|
|
4
4
|
"description": "Shared React hooks for StartSimpli apps",
|
|
5
5
|
"main": "./src/index.ts",
|
|
6
6
|
"types": "./src/index.ts",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"@tanstack/react-query": ">=5.0.0",
|
|
24
24
|
"react": ">=18.0.0",
|
|
25
25
|
"react-native": ">=0.74.0",
|
|
26
|
-
"@startsimpli/api": "^0.5.
|
|
26
|
+
"@startsimpli/api": "^0.5.68"
|
|
27
27
|
},
|
|
28
28
|
"peerDependenciesMeta": {
|
|
29
29
|
"@tanstack/react-query": {
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"tsup": "^8.5.1",
|
|
47
47
|
"typescript": "^6.0.3",
|
|
48
48
|
"vitest": "^4.1.5",
|
|
49
|
-
"@startsimpli/api": "0.5.
|
|
49
|
+
"@startsimpli/api": "0.5.68"
|
|
50
50
|
},
|
|
51
51
|
"scripts": {
|
|
52
52
|
"build": "tsup",
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useUpload state machine (crochet_patterns-llmj): queued -> uploading -> ready,
|
|
3
|
+
* error + retry, timeout, remove aborts. The uploader is a fake; no network.
|
|
4
|
+
*/
|
|
5
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
6
|
+
import { renderHook, act, waitFor } from '@testing-library/react'
|
|
7
|
+
import { useUpload, type FileUploader } from '../useUpload'
|
|
8
|
+
|
|
9
|
+
type Rec = { id: string; status: 'ready' }
|
|
10
|
+
|
|
11
|
+
function deferred<T>() {
|
|
12
|
+
let resolve!: (v: T) => void
|
|
13
|
+
let reject!: (e: unknown) => void
|
|
14
|
+
const promise = new Promise<T>((res, rej) => {
|
|
15
|
+
resolve = res
|
|
16
|
+
reject = rej
|
|
17
|
+
})
|
|
18
|
+
return { promise, resolve, reject }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** An uploader whose calls the test settles by hand. */
|
|
22
|
+
function manualUploader() {
|
|
23
|
+
const calls: Array<{
|
|
24
|
+
file: File
|
|
25
|
+
opts: Parameters<FileUploader<Rec>['upload']>[1]
|
|
26
|
+
d: ReturnType<typeof deferred<Rec>>
|
|
27
|
+
}> = []
|
|
28
|
+
const upload = vi.fn((file: File, opts: Parameters<FileUploader<Rec>['upload']>[1]) => {
|
|
29
|
+
const d = deferred<Rec>()
|
|
30
|
+
calls.push({ file, opts, d })
|
|
31
|
+
return d.promise
|
|
32
|
+
})
|
|
33
|
+
return { uploader: { upload } as FileUploader<Rec>, upload, calls }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const pdf = (name = 'bunny.pdf') => new File(['%PDF-1.4'], name, { type: 'application/pdf' })
|
|
37
|
+
const OPTS = { app: 'crochet', kind: 'pattern_source' }
|
|
38
|
+
|
|
39
|
+
describe('useUpload', () => {
|
|
40
|
+
it('uploads an added file: uploading with progress, then ready with the record', async () => {
|
|
41
|
+
const { uploader, calls } = manualUploader()
|
|
42
|
+
const { result } = renderHook(() => useUpload(uploader, OPTS))
|
|
43
|
+
|
|
44
|
+
act(() => {
|
|
45
|
+
result.current.add([pdf()])
|
|
46
|
+
})
|
|
47
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('uploading'))
|
|
48
|
+
expect(result.current.isUploading).toBe(true)
|
|
49
|
+
expect(calls[0]!.opts).toMatchObject({ app: 'crochet', kind: 'pattern_source' })
|
|
50
|
+
|
|
51
|
+
act(() => calls[0]!.opts.onProgress?.(0.4))
|
|
52
|
+
await waitFor(() => expect(result.current.items[0]?.progress).toBe(0.4))
|
|
53
|
+
|
|
54
|
+
await act(async () => calls[0]!.d.resolve({ id: 'up_1', status: 'ready' }))
|
|
55
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('ready'))
|
|
56
|
+
expect(result.current.items[0]?.result).toEqual({ id: 'up_1', status: 'ready' })
|
|
57
|
+
expect(result.current.items[0]?.name).toBe('bunny.pdf')
|
|
58
|
+
expect(result.current.isUploading).toBe(false)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('with autoStart false, holds files as queued until start()', async () => {
|
|
62
|
+
const { uploader, upload, calls } = manualUploader()
|
|
63
|
+
const { result } = renderHook(() => useUpload(uploader, { ...OPTS, autoStart: false }))
|
|
64
|
+
|
|
65
|
+
act(() => {
|
|
66
|
+
result.current.add([pdf()])
|
|
67
|
+
})
|
|
68
|
+
expect(result.current.items[0]?.status).toBe('queued')
|
|
69
|
+
expect(result.current.isUploading).toBe(true)
|
|
70
|
+
expect(upload).not.toHaveBeenCalled()
|
|
71
|
+
|
|
72
|
+
act(() => result.current.start())
|
|
73
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('uploading'))
|
|
74
|
+
await act(async () => calls[0]!.d.resolve({ id: 'up_1', status: 'ready' }))
|
|
75
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('ready'))
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('a failed upload becomes error with the reason; retry re-runs it to ready', async () => {
|
|
79
|
+
const { uploader, upload, calls } = manualUploader()
|
|
80
|
+
const { result } = renderHook(() => useUpload(uploader, OPTS))
|
|
81
|
+
|
|
82
|
+
act(() => {
|
|
83
|
+
result.current.add([pdf()])
|
|
84
|
+
})
|
|
85
|
+
await waitFor(() => expect(calls).toHaveLength(1))
|
|
86
|
+
await act(async () => calls[0]!.d.reject(new Error('CORS: PUT blocked')))
|
|
87
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('error'))
|
|
88
|
+
expect(result.current.items[0]?.error).toContain('CORS: PUT blocked')
|
|
89
|
+
expect(result.current.isUploading).toBe(false)
|
|
90
|
+
|
|
91
|
+
act(() => result.current.retry(result.current.items[0]!.id))
|
|
92
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('uploading'))
|
|
93
|
+
expect(result.current.items[0]?.error).toBeUndefined()
|
|
94
|
+
await act(async () => calls[1]!.d.resolve({ id: 'up_2', status: 'ready' }))
|
|
95
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('ready'))
|
|
96
|
+
expect(upload).toHaveBeenCalledTimes(2)
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('retry is a no-op for an item that is not in error', async () => {
|
|
100
|
+
const { uploader, upload, calls } = manualUploader()
|
|
101
|
+
const { result } = renderHook(() => useUpload(uploader, OPTS))
|
|
102
|
+
act(() => {
|
|
103
|
+
result.current.add([pdf()])
|
|
104
|
+
})
|
|
105
|
+
await waitFor(() => expect(calls).toHaveLength(1))
|
|
106
|
+
act(() => result.current.retry(result.current.items[0]!.id))
|
|
107
|
+
expect(upload).toHaveBeenCalledTimes(1)
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it('a stalled upload becomes an error after timeoutMs', async () => {
|
|
111
|
+
const { uploader } = manualUploader()
|
|
112
|
+
const { result } = renderHook(() => useUpload(uploader, { ...OPTS, timeoutMs: 30 }))
|
|
113
|
+
act(() => {
|
|
114
|
+
result.current.add([pdf()])
|
|
115
|
+
})
|
|
116
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('error'), { timeout: 1000 })
|
|
117
|
+
expect(result.current.items[0]?.error).toMatch(/timed out/i)
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it('remove drops an in-flight item and aborts its upload', async () => {
|
|
121
|
+
const { uploader, calls } = manualUploader()
|
|
122
|
+
const { result } = renderHook(() => useUpload(uploader, OPTS))
|
|
123
|
+
let ids: string[] = []
|
|
124
|
+
act(() => {
|
|
125
|
+
ids = result.current.add([pdf('a.pdf'), pdf('b.pdf')])
|
|
126
|
+
})
|
|
127
|
+
await waitFor(() => expect(calls).toHaveLength(2))
|
|
128
|
+
act(() => result.current.remove(ids[0]!))
|
|
129
|
+
expect(result.current.items.map((i) => i.name)).toEqual(['b.pdf'])
|
|
130
|
+
expect(calls[0]!.opts.signal?.aborted).toBe(true)
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it('progress resets the stall timer, so a slow upload that keeps moving is not timed out', async () => {
|
|
134
|
+
const { uploader, calls } = manualUploader()
|
|
135
|
+
const { result } = renderHook(() => useUpload(uploader, { ...OPTS, timeoutMs: 50 }))
|
|
136
|
+
act(() => {
|
|
137
|
+
result.current.add([pdf()])
|
|
138
|
+
})
|
|
139
|
+
await waitFor(() => expect(calls).toHaveLength(1))
|
|
140
|
+
for (let i = 1; i <= 8; i++) {
|
|
141
|
+
await act(async () => {
|
|
142
|
+
await new Promise((r) => setTimeout(r, 20))
|
|
143
|
+
calls[0]!.opts.onProgress?.(i / 10)
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
expect(result.current.items[0]?.status).toBe('uploading')
|
|
147
|
+
await act(async () => calls[0]!.d.resolve({ id: 'up_1', status: 'ready' }))
|
|
148
|
+
await waitFor(() => expect(result.current.items[0]?.status).toBe('ready'))
|
|
149
|
+
expect(result.current.items[0]?.error).toBeUndefined()
|
|
150
|
+
})
|
|
151
|
+
})
|
package/src/index.ts
CHANGED
|
@@ -67,6 +67,10 @@ export type {
|
|
|
67
67
|
UseCSVImportState,
|
|
68
68
|
} from './useCSV'
|
|
69
69
|
export { useAsyncOptions } from './useAsyncOptions'
|
|
70
|
+
|
|
71
|
+
// Upload state machine (crochet_patterns-llmj; provisional)
|
|
72
|
+
export { useUpload } from './useUpload'
|
|
73
|
+
export type { FileUploader, UploadItem, UploadStatus, UseUploadOptions, UseUploadResult } from './useUpload'
|
|
70
74
|
export type { UseAsyncOptionsResult } from './useAsyncOptions'
|
|
71
75
|
|
|
72
76
|
// Vault — environments, secrets, access keys, audit (startsim-d30.3.2)
|
package/src/useUpload.ts
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useUpload — app-agnostic upload state machine (crochet_patterns-llmj).
|
|
3
|
+
*
|
|
4
|
+
* The neutral home for the queued/uploading/ready/error machine that today
|
|
5
|
+
* lives inside packages/ui chat/useComposerUploads (which is document-scoped).
|
|
6
|
+
* It drives any structural {@link FileUploader}; `@startsimpli/api`'s
|
|
7
|
+
* `UploadsApi` satisfies it without this package importing it.
|
|
8
|
+
*
|
|
9
|
+
* - `queued` added, not started (autoStart false, or waiting on `start()`)
|
|
10
|
+
* - `uploading` in flight, `progress` 0..1
|
|
11
|
+
* - `ready` done, `result` holds the uploader's record
|
|
12
|
+
* - `error` failed or timed out, `error` holds the reason; `retry(id)` re-runs it
|
|
13
|
+
*
|
|
14
|
+
* useComposerUploads is not re-pointed at this yet (crochet_patterns-znr8).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
18
|
+
|
|
19
|
+
export interface FileUploader<R extends { id: string } = { id: string }> {
|
|
20
|
+
upload(
|
|
21
|
+
file: File,
|
|
22
|
+
options: { app: string; kind: string; onProgress?: (fraction: number) => void; signal?: AbortSignal },
|
|
23
|
+
): Promise<R>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type UploadStatus = 'queued' | 'uploading' | 'ready' | 'error';
|
|
27
|
+
|
|
28
|
+
export interface UploadItem<R> {
|
|
29
|
+
/** Stable client id. */
|
|
30
|
+
id: string;
|
|
31
|
+
file: File;
|
|
32
|
+
name: string;
|
|
33
|
+
size: number;
|
|
34
|
+
status: UploadStatus;
|
|
35
|
+
progress: number;
|
|
36
|
+
result?: R;
|
|
37
|
+
error?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface UseUploadOptions {
|
|
41
|
+
app: string;
|
|
42
|
+
kind: string;
|
|
43
|
+
/** Start uploading as soon as files are added. Default true. */
|
|
44
|
+
autoStart?: boolean;
|
|
45
|
+
/** An upload with no progress for this long becomes an error. Default 90 s. */
|
|
46
|
+
timeoutMs?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface UseUploadResult<R> {
|
|
50
|
+
items: UploadItem<R>[];
|
|
51
|
+
/** Adds files; returns their client ids. */
|
|
52
|
+
add: (files: File[]) => string[];
|
|
53
|
+
/** Starts every queued item. */
|
|
54
|
+
start: () => void;
|
|
55
|
+
/** Re-runs an errored item (no-op for any other status). */
|
|
56
|
+
retry: (id: string) => void;
|
|
57
|
+
/** Drops an item, aborting it if in flight. */
|
|
58
|
+
remove: (id: string) => void;
|
|
59
|
+
clear: () => void;
|
|
60
|
+
/** True while anything is queued or uploading. */
|
|
61
|
+
isUploading: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const DEFAULT_TIMEOUT_MS = 90_000
|
|
65
|
+
|
|
66
|
+
let seq = 0
|
|
67
|
+
const nextId = () => `up-${Date.now().toString(36)}-${++seq}`
|
|
68
|
+
|
|
69
|
+
interface Attempt {
|
|
70
|
+
controller: AbortController
|
|
71
|
+
timer: ReturnType<typeof setTimeout>
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function useUpload<R extends { id: string }>(
|
|
75
|
+
uploader: FileUploader<R>,
|
|
76
|
+
options: UseUploadOptions,
|
|
77
|
+
): UseUploadResult<R> {
|
|
78
|
+
const [items, setItems] = useState<UploadItem<R>[]>([])
|
|
79
|
+
const itemsRef = useRef(items)
|
|
80
|
+
itemsRef.current = items
|
|
81
|
+
const uploaderRef = useRef(uploader)
|
|
82
|
+
uploaderRef.current = uploader
|
|
83
|
+
const optionsRef = useRef(options)
|
|
84
|
+
optionsRef.current = options
|
|
85
|
+
// The live attempt per item. A settled promise from an older attempt (timed
|
|
86
|
+
// out, removed, retried) finds a different entry here and is ignored.
|
|
87
|
+
const attempts = useRef(new Map<string, Attempt>())
|
|
88
|
+
|
|
89
|
+
const patch = useCallback((id: string, next: Partial<UploadItem<R>>) => {
|
|
90
|
+
setItems((cur) => cur.map((it) => (it.id === id ? { ...it, ...next } : it)))
|
|
91
|
+
}, [])
|
|
92
|
+
|
|
93
|
+
const cancel = useCallback((id: string) => {
|
|
94
|
+
const attempt = attempts.current.get(id)
|
|
95
|
+
if (!attempt) return
|
|
96
|
+
clearTimeout(attempt.timer)
|
|
97
|
+
attempt.controller.abort()
|
|
98
|
+
attempts.current.delete(id)
|
|
99
|
+
}, [])
|
|
100
|
+
|
|
101
|
+
const run = useCallback(
|
|
102
|
+
(id: string, file: File) => {
|
|
103
|
+
cancel(id)
|
|
104
|
+
const { app, kind, timeoutMs = DEFAULT_TIMEOUT_MS } = optionsRef.current
|
|
105
|
+
const controller = new AbortController()
|
|
106
|
+
// A stall timer, not a total limit: progress re-arms it, so a big file
|
|
107
|
+
// on a slow link is fine while it keeps moving.
|
|
108
|
+
const onStall = () => {
|
|
109
|
+
if (!isCurrent()) return
|
|
110
|
+
cancel(id)
|
|
111
|
+
patch(id, { status: 'error', error: 'Upload timed out' })
|
|
112
|
+
}
|
|
113
|
+
const attempt: Attempt = { controller, timer: setTimeout(onStall, timeoutMs) }
|
|
114
|
+
attempts.current.set(id, attempt)
|
|
115
|
+
const isCurrent = () => attempts.current.get(id) === attempt
|
|
116
|
+
patch(id, { status: 'uploading', progress: 0, error: undefined, result: undefined })
|
|
117
|
+
|
|
118
|
+
let pending: Promise<R>
|
|
119
|
+
try {
|
|
120
|
+
pending = uploaderRef.current.upload(file, {
|
|
121
|
+
app,
|
|
122
|
+
kind,
|
|
123
|
+
signal: controller.signal,
|
|
124
|
+
onProgress: (fraction) => {
|
|
125
|
+
if (!isCurrent()) return
|
|
126
|
+
clearTimeout(attempt.timer)
|
|
127
|
+
attempt.timer = setTimeout(onStall, timeoutMs)
|
|
128
|
+
patch(id, { progress: fraction })
|
|
129
|
+
},
|
|
130
|
+
})
|
|
131
|
+
} catch (err) {
|
|
132
|
+
pending = Promise.reject(err)
|
|
133
|
+
}
|
|
134
|
+
pending.then(
|
|
135
|
+
(result) => {
|
|
136
|
+
if (!isCurrent()) return
|
|
137
|
+
clearTimeout(attempt.timer)
|
|
138
|
+
attempts.current.delete(id)
|
|
139
|
+
patch(id, { status: 'ready', progress: 1, result })
|
|
140
|
+
},
|
|
141
|
+
(err: unknown) => {
|
|
142
|
+
if (!isCurrent()) return
|
|
143
|
+
clearTimeout(attempt.timer)
|
|
144
|
+
attempts.current.delete(id)
|
|
145
|
+
patch(id, { status: 'error', error: err instanceof Error ? err.message : 'Upload failed' })
|
|
146
|
+
},
|
|
147
|
+
)
|
|
148
|
+
},
|
|
149
|
+
[cancel, patch],
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
const add = useCallback(
|
|
153
|
+
(files: File[]) => {
|
|
154
|
+
const autoStart = optionsRef.current.autoStart ?? true
|
|
155
|
+
const added: UploadItem<R>[] = files.map((file) => ({
|
|
156
|
+
id: nextId(),
|
|
157
|
+
file,
|
|
158
|
+
name: file.name,
|
|
159
|
+
size: file.size,
|
|
160
|
+
status: 'queued',
|
|
161
|
+
progress: 0,
|
|
162
|
+
}))
|
|
163
|
+
setItems((cur) => [...cur, ...added])
|
|
164
|
+
if (autoStart) added.forEach((it) => run(it.id, it.file))
|
|
165
|
+
return added.map((it) => it.id)
|
|
166
|
+
},
|
|
167
|
+
[run],
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
const start = useCallback(() => {
|
|
171
|
+
itemsRef.current
|
|
172
|
+
.filter((it) => it.status === 'queued' && !attempts.current.has(it.id))
|
|
173
|
+
.forEach((it) => run(it.id, it.file))
|
|
174
|
+
}, [run])
|
|
175
|
+
|
|
176
|
+
const retry = useCallback(
|
|
177
|
+
(id: string) => {
|
|
178
|
+
const item = itemsRef.current.find((it) => it.id === id)
|
|
179
|
+
if (item?.status === 'error') run(item.id, item.file)
|
|
180
|
+
},
|
|
181
|
+
[run],
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
const remove = useCallback(
|
|
185
|
+
(id: string) => {
|
|
186
|
+
cancel(id)
|
|
187
|
+
setItems((cur) => cur.filter((it) => it.id !== id))
|
|
188
|
+
},
|
|
189
|
+
[cancel],
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
const clear = useCallback(() => {
|
|
193
|
+
Array.from(attempts.current.keys()).forEach(cancel)
|
|
194
|
+
setItems([])
|
|
195
|
+
}, [cancel])
|
|
196
|
+
|
|
197
|
+
// Abort anything still in flight on unmount.
|
|
198
|
+
useEffect(() => {
|
|
199
|
+
const live = attempts.current
|
|
200
|
+
return () => {
|
|
201
|
+
live.forEach((a) => {
|
|
202
|
+
clearTimeout(a.timer)
|
|
203
|
+
a.controller.abort()
|
|
204
|
+
})
|
|
205
|
+
live.clear()
|
|
206
|
+
}
|
|
207
|
+
}, [])
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
items,
|
|
211
|
+
add,
|
|
212
|
+
start,
|
|
213
|
+
retry,
|
|
214
|
+
remove,
|
|
215
|
+
clear,
|
|
216
|
+
isUploading: items.some((it) => it.status === 'queued' || it.status === 'uploading'),
|
|
217
|
+
}
|
|
218
|
+
}
|