react-inp-chunker 0.1.2 → 0.2.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/README.md +141 -53
- package/core/package.json +10 -0
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/index.js +1 -1
- package/dist/deferred-task-CwjZA3K-.js +713 -0
- package/dist/deferred-task-CwjZA3K-.js.map +1 -0
- package/dist/deferred-task-EWH55ZyL.cjs +796 -0
- package/dist/deferred-task-EWH55ZyL.cjs.map +1 -0
- package/dist/{index-C6B_Nm3i.d.ts → index-DShDP2VN.d.cts} +51 -6
- package/dist/index-DShDP2VN.d.cts.map +1 -0
- package/dist/{index-C6B_Nm3i.d.cts → index-DShDP2VN.d.ts} +51 -6
- package/dist/index-DShDP2VN.d.ts.map +1 -0
- package/dist/index.cjs +47 -12
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +20 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +20 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +24 -10
- package/dist/index.js.map +1 -1
- package/dist/production/core/index.cjs +16 -0
- package/dist/production/core/index.js +1 -0
- package/dist/{deferred-task-5kfztF2G.js → production/deferred-task-BGsfee-L.js} +177 -86
- package/dist/production/deferred-task-BGsfee-L.js.map +1 -0
- package/dist/{deferred-task-BXVzapQg.cjs → production/deferred-task-zVnq18IN.cjs} +177 -86
- package/dist/production/deferred-task-zVnq18IN.cjs.map +1 -0
- package/dist/production/index.cjs +195 -0
- package/dist/production/index.cjs.map +1 -0
- package/dist/production/index.js +172 -0
- package/dist/production/index.js.map +1 -0
- package/package.json +65 -22
- package/dist/deferred-task-5kfztF2G.js.map +0 -1
- package/dist/deferred-task-BXVzapQg.cjs.map +0 -1
- package/dist/index-C6B_Nm3i.d.cts.map +0 -1
- package/dist/index-C6B_Nm3i.d.ts.map +0 -1
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
// \0rolldown/runtime.js
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
11
|
+
key = keys[i];
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
13
|
+
get: ((k) => from[k]).bind(null, key),
|
|
14
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
20
|
+
value: mod,
|
|
21
|
+
enumerable: true
|
|
22
|
+
}) : target, mod));
|
|
23
|
+
const require_deferred_task = require("./deferred-task-zVnq18IN.cjs");
|
|
24
|
+
let react = require("react");
|
|
25
|
+
react = __toESM(react, 1);
|
|
26
|
+
// src/react/task-controller.ts
|
|
27
|
+
function createTaskController() {
|
|
28
|
+
let current = null;
|
|
29
|
+
let detachFromCurrent;
|
|
30
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
31
|
+
const notify = () => {
|
|
32
|
+
for (const listener of listeners) listener();
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
subscribe: (listener) => {
|
|
36
|
+
listeners.add(listener);
|
|
37
|
+
return () => {
|
|
38
|
+
listeners.delete(listener);
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
getSnapshot: () => current?.getSnapshot(),
|
|
42
|
+
getCurrent: () => current,
|
|
43
|
+
replace: (task) => {
|
|
44
|
+
detachFromCurrent?.();
|
|
45
|
+
current = task;
|
|
46
|
+
detachFromCurrent = task?.subscribe(notify);
|
|
47
|
+
notify();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
// src/react/use-effect-event.ts
|
|
52
|
+
function useEffectEventFallback(callback) {
|
|
53
|
+
const latest = (0, react.useRef)(callback);
|
|
54
|
+
(0, react.useInsertionEffect)(() => {
|
|
55
|
+
latest.current = callback;
|
|
56
|
+
});
|
|
57
|
+
return (0, react.useCallback)((...args) => latest.current(...args), []);
|
|
58
|
+
}
|
|
59
|
+
const useEffectEvent = react.useEffectEvent ?? useEffectEventFallback;
|
|
60
|
+
// src/react/useChunkedTask.ts
|
|
61
|
+
const IDLE_STATUS = "idle";
|
|
62
|
+
/**
|
|
63
|
+
* Chunks a heavy, synchronous per-item computation over `items` so it never
|
|
64
|
+
* blocks the main thread for longer than a time slice — the thing that
|
|
65
|
+
* costs you Interaction to Next Paint. Starts automatically by default;
|
|
66
|
+
* pass `{ autoStart: false }` to wait for an explicit `start()` call (e.g.
|
|
67
|
+
* behind a button).
|
|
68
|
+
*
|
|
69
|
+
* `processItem` and `onItem` can be fresh closures every render — the hook
|
|
70
|
+
* always calls the latest version (via `useEffectEvent`) without that
|
|
71
|
+
* causing the task to restart. What *does* restart the task is `items`
|
|
72
|
+
* changing identity (a new array reference), or `timeSliceMs`/`autoStart`
|
|
73
|
+
* changing. That's deliberate: a new `items` array means new work, and
|
|
74
|
+
* memoizing it when you don't want that is the caller's call to make, the
|
|
75
|
+
* same as any other React dependency.
|
|
76
|
+
*/
|
|
77
|
+
function useChunkedTask(items, processItem, options) {
|
|
78
|
+
const { timeSliceMs, batchSize, collectResults, autoStart = true, onItem } = options ?? {};
|
|
79
|
+
const stableProcessItem = useEffectEvent((item, index) => processItem(item, index));
|
|
80
|
+
const stableOnItem = useEffectEvent((result, item, index) => {
|
|
81
|
+
onItem?.(result, item, index);
|
|
82
|
+
});
|
|
83
|
+
const [controller] = (0, react.useState)(() => createTaskController());
|
|
84
|
+
const idleSnapshot = (0, react.useMemo)(() => ({
|
|
85
|
+
status: IDLE_STATUS,
|
|
86
|
+
processed: 0,
|
|
87
|
+
total: items.length
|
|
88
|
+
}), [items.length]);
|
|
89
|
+
const snapshot = (0, react.useSyncExternalStore)(controller.subscribe, () => controller.getSnapshot() ?? idleSnapshot, () => idleSnapshot);
|
|
90
|
+
(0, react.useEffect)(() => {
|
|
91
|
+
const scheduler = require_deferred_task.createChunkScheduler({
|
|
92
|
+
items,
|
|
93
|
+
processItem: stableProcessItem,
|
|
94
|
+
onItem: stableOnItem,
|
|
95
|
+
...timeSliceMs !== void 0 ? { timeSliceMs } : {},
|
|
96
|
+
...batchSize !== void 0 ? { batchSize } : {},
|
|
97
|
+
...collectResults !== void 0 ? { collectResults } : {}
|
|
98
|
+
});
|
|
99
|
+
controller.replace(scheduler);
|
|
100
|
+
if (autoStart) scheduler.start();
|
|
101
|
+
return () => {
|
|
102
|
+
scheduler.cancel();
|
|
103
|
+
controller.replace(null);
|
|
104
|
+
};
|
|
105
|
+
}, [
|
|
106
|
+
items,
|
|
107
|
+
timeSliceMs,
|
|
108
|
+
batchSize,
|
|
109
|
+
collectResults,
|
|
110
|
+
autoStart,
|
|
111
|
+
controller
|
|
112
|
+
]);
|
|
113
|
+
const start = (0, react.useCallback)(() => controller.getCurrent()?.start(), [controller]);
|
|
114
|
+
const pause = (0, react.useCallback)(() => controller.getCurrent()?.pause(), [controller]);
|
|
115
|
+
const resume = (0, react.useCallback)(() => controller.getCurrent()?.resume(), [controller]);
|
|
116
|
+
const cancel = (0, react.useCallback)(() => controller.getCurrent()?.cancel(), [controller]);
|
|
117
|
+
return {
|
|
118
|
+
status: snapshot.status,
|
|
119
|
+
processed: snapshot.processed,
|
|
120
|
+
total: snapshot.total,
|
|
121
|
+
error: snapshot.error,
|
|
122
|
+
results: snapshot.results,
|
|
123
|
+
isIdle: snapshot.status === "idle",
|
|
124
|
+
isProcessing: snapshot.status === "processing",
|
|
125
|
+
isPaused: snapshot.status === "paused",
|
|
126
|
+
isDone: snapshot.status === "done",
|
|
127
|
+
isCancelled: snapshot.status === "cancelled",
|
|
128
|
+
isError: snapshot.status === "error",
|
|
129
|
+
start,
|
|
130
|
+
pause,
|
|
131
|
+
resume,
|
|
132
|
+
cancel
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
// src/react/useDeferredTask.ts
|
|
136
|
+
const IDLE_SNAPSHOT = { status: "idle" };
|
|
137
|
+
/**
|
|
138
|
+
* Runs an arbitrary heavy, synchronous generator function in chunks, so it
|
|
139
|
+
* never produces a long task on its own. Where `useChunkedTask` chunks "one
|
|
140
|
+
* function applied to every item of an array" automatically, this hook
|
|
141
|
+
* leaves the chunk boundaries to you — put `yield` wherever your function
|
|
142
|
+
* can safely pause (see `DeferredGenerator`'s doc comment for an example).
|
|
143
|
+
*
|
|
144
|
+
* `task` is only called when the effect (re)creates the underlying task, not
|
|
145
|
+
* on every render — list whatever it closes over in `deps`, the same way
|
|
146
|
+
* you would for `useMemo` or `useEffect`.
|
|
147
|
+
*/
|
|
148
|
+
function useDeferredTask(task, deps, options) {
|
|
149
|
+
const { timeSliceMs, batchSize, autoStart = true } = options ?? {};
|
|
150
|
+
const stableTask = useEffectEvent(() => task());
|
|
151
|
+
const [controller] = (0, react.useState)(() => createTaskController());
|
|
152
|
+
const snapshot = (0, react.useSyncExternalStore)(controller.subscribe, () => controller.getSnapshot() ?? IDLE_SNAPSHOT, () => IDLE_SNAPSHOT);
|
|
153
|
+
(0, react.useEffect)(() => {
|
|
154
|
+
const deferredTask = require_deferred_task.createDeferredTask({
|
|
155
|
+
task: stableTask,
|
|
156
|
+
...timeSliceMs !== void 0 ? { timeSliceMs } : {},
|
|
157
|
+
...batchSize !== void 0 ? { batchSize } : {}
|
|
158
|
+
});
|
|
159
|
+
controller.replace(deferredTask);
|
|
160
|
+
if (autoStart) deferredTask.start();
|
|
161
|
+
return () => {
|
|
162
|
+
deferredTask.cancel();
|
|
163
|
+
controller.replace(null);
|
|
164
|
+
};
|
|
165
|
+
}, [
|
|
166
|
+
...deps,
|
|
167
|
+
timeSliceMs,
|
|
168
|
+
batchSize,
|
|
169
|
+
autoStart,
|
|
170
|
+
controller
|
|
171
|
+
]);
|
|
172
|
+
const start = (0, react.useCallback)(() => controller.getCurrent()?.start(), [controller]);
|
|
173
|
+
const pause = (0, react.useCallback)(() => controller.getCurrent()?.pause(), [controller]);
|
|
174
|
+
const resume = (0, react.useCallback)(() => controller.getCurrent()?.resume(), [controller]);
|
|
175
|
+
const cancel = (0, react.useCallback)(() => controller.getCurrent()?.cancel(), [controller]);
|
|
176
|
+
return {
|
|
177
|
+
status: snapshot.status,
|
|
178
|
+
error: snapshot.error,
|
|
179
|
+
value: snapshot.value,
|
|
180
|
+
isIdle: snapshot.status === "idle",
|
|
181
|
+
isProcessing: snapshot.status === "processing",
|
|
182
|
+
isPaused: snapshot.status === "paused",
|
|
183
|
+
isDone: snapshot.status === "done",
|
|
184
|
+
isCancelled: snapshot.status === "cancelled",
|
|
185
|
+
isError: snapshot.status === "error",
|
|
186
|
+
start,
|
|
187
|
+
pause,
|
|
188
|
+
resume,
|
|
189
|
+
cancel
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
exports.useChunkedTask = useChunkedTask;
|
|
193
|
+
exports.useDeferredTask = useDeferredTask;
|
|
194
|
+
|
|
195
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["useRef","useCallback","React","useState","useMemo","useSyncExternalStore","createChunkScheduler","useCallback","useState","useSyncExternalStore","createDeferredTask","useCallback"],"sources":["../../src/react/task-controller.ts","../../src/react/use-effect-event.ts","../../src/react/useChunkedTask.ts","../../src/react/useDeferredTask.ts"],"sourcesContent":["/**\n * The glue between a task handle (`ChunkScheduler<R>`, `DeferredTask<T>` —\n * anything with `subscribe`/`getSnapshot`) recreated from scratch whenever a\n * hook's deps change, inside an effect, and `useSyncExternalStore`, which\n * wants one stable `subscribe` function for a component's whole lifetime.\n *\n * `useSyncExternalStore` resubscribes whenever the `subscribe` function\n * identity changes — fine for correctness, but it means the naive approach\n * (pass the current task's own `.subscribe` directly) either churns\n * subscriptions every render or, worse, drifts: the component keeps\n * `subscribe`d to whichever task was current when it last resubscribed, not\n * necessarily the one `getSnapshot` is reading from after a swap.\n *\n * A controller sidesteps that: it's created once per hook instance (lazy\n * `useState` initializer in the hook, so it's stable without touching a\n * ref), hands `useSyncExternalStore` a `subscribe`/`getSnapshot` pair that\n * never change identity, and internally forwards to whichever task is\n * \"current\" — re-pointing itself via `replace()` every time the effect\n * swaps in a new one. Generic over the task shape so both `useChunkedTask`\n * and `useDeferredTask` share this one implementation.\n *\n * Every property below is an arrow function, deliberately — not method\n * shorthand — so none of them close over `this`, and `controller.subscribe`\n * can be handed to `useSyncExternalStore` directly as a plain function\n * reference without an unbound-method footgun.\n */\nexport interface SubscribableTask<Snapshot> {\n subscribe(listener: () => void): () => void;\n getSnapshot(): Snapshot;\n}\n\nexport interface TaskController<Task extends SubscribableTask<unknown>> {\n subscribe: (listener: () => void) => () => void;\n getSnapshot: () => ReturnType<Task['getSnapshot']> | undefined;\n getCurrent: () => Task | null;\n /** Swaps in a new task (or none), detaching from the previous one first. */\n replace: (task: Task | null) => void;\n}\n\nexport function createTaskController<\n Task extends SubscribableTask<unknown>,\n>(): TaskController<Task> {\n let current: Task | null = null;\n let detachFromCurrent: (() => void) | undefined;\n const listeners = new Set<() => void>();\n\n const notify = (): void => {\n for (const listener of listeners) listener();\n };\n\n return {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n getSnapshot: () =>\n current?.getSnapshot() as ReturnType<Task['getSnapshot']> | undefined,\n getCurrent: () => current,\n replace: (task) => {\n detachFromCurrent?.();\n current = task;\n detachFromCurrent = task?.subscribe(notify);\n notify();\n },\n };\n}\n","import * as React from 'react';\nimport { useCallback, useInsertionEffect, useRef } from 'react';\n\n/**\n * `useEffectEvent` only became a stable React export in 19.2. On React 18\n * and 19.0–19.1 it doesn't exist at all — and a named\n * `import { useEffectEvent } from 'react'` then fails outright: at module\n * link time under Node ESM (\"Named export 'useEffectEvent' not found\"), or\n * as \"useEffectEvent is not a function\" on first render in a bundler. Both\n * versions are inside this package's declared peer range, so that has to\n * work, not just type-check.\n *\n * So the native hook is read as a property of the namespace object, where a\n * missing export is plain `undefined` rather than a link error, and used\n * whenever the running React has it. Otherwise the fallback keeps the same\n * contract: a stable function identity that always calls the latest\n * callback. The latest callback is committed from an insertion effect —\n * after render, before any layout or passive effect of the same commit can\n * observe it — so effects always see the current closure, without the\n * render-time ref mutation the React Compiler rejects.\n */\ntype EffectEventHook = <Args extends readonly unknown[], Return>(\n callback: (...args: Args) => Return,\n) => (...args: Args) => Return;\n\nexport function useEffectEventFallback<Args extends readonly unknown[], Return>(\n callback: (...args: Args) => Return,\n): (...args: Args) => Return {\n const latest = useRef(callback);\n useInsertionEffect(() => {\n latest.current = callback;\n });\n return useCallback((...args: Args) => latest.current(...args), []);\n}\n\n// Through `unknown` on purpose: React 18's types have no `useEffectEvent`\n// member at all, so a direct assertion wouldn't compile against them.\nconst nativeUseEffectEvent = (\n React as unknown as { readonly useEffectEvent?: EffectEventHook }\n).useEffectEvent;\n\nexport const useEffectEvent: EffectEventHook =\n nativeUseEffectEvent ?? useEffectEventFallback;\n","import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';\n\nimport type { ChunkStatus } from '../core/chunk-machine.js';\nimport { createChunkScheduler } from '../core/chunk-scheduler.js';\nimport type { ChunkScheduler, ChunkSnapshot } from '../core/chunk-scheduler.js';\nimport { createTaskController } from './task-controller.js';\nimport { useEffectEvent } from './use-effect-event.js';\n\nexport interface UseChunkedTaskOptions<T, R> {\n /** Max ms of uninterrupted work before yielding. Default 5. */\n readonly timeSliceMs?: number;\n /**\n * Items to process between clock checks. Default 1. Raise it only for\n * items measured in nanoseconds, where reading the clock costs more than\n * the work; a slice can then run up to `batchSize` items past its budget.\n * See the `batchSize` note on `createChunkScheduler`.\n */\n readonly batchSize?: number;\n /**\n * Keep every result in `results`. Default true. Set false when results\n * are consumed through `onItem`, to avoid retaining one result per item;\n * `results` is then an empty array once the task settles.\n */\n readonly collectResults?: boolean;\n /** Start processing automatically when the task is (re)created. Default `true`. */\n readonly autoStart?: boolean;\n /**\n * Called synchronously after each item is processed. This is the cheap\n * way to consume results incrementally while the task is still running —\n * write into a ref-backed buffer, a canvas, a chart, whatever you need —\n * without paying for an array copy on every yield checkpoint.\n */\n readonly onItem?: (result: R, item: T, index: number) => void;\n}\n\nexport interface UseChunkedTaskState<R> {\n readonly status: ChunkStatus;\n readonly processed: number;\n readonly total: number;\n readonly error: unknown;\n /** The full results array once the task has settled — `undefined` until then. */\n readonly results: readonly R[] | undefined;\n readonly isIdle: boolean;\n readonly isProcessing: boolean;\n readonly isPaused: boolean;\n readonly isDone: boolean;\n readonly isCancelled: boolean;\n readonly isError: boolean;\n readonly start: () => void;\n readonly pause: () => void;\n readonly resume: () => void;\n readonly cancel: () => void;\n}\n\nconst IDLE_STATUS: ChunkStatus = 'idle';\n\n/**\n * Chunks a heavy, synchronous per-item computation over `items` so it never\n * blocks the main thread for longer than a time slice — the thing that\n * costs you Interaction to Next Paint. Starts automatically by default;\n * pass `{ autoStart: false }` to wait for an explicit `start()` call (e.g.\n * behind a button).\n *\n * `processItem` and `onItem` can be fresh closures every render — the hook\n * always calls the latest version (via `useEffectEvent`) without that\n * causing the task to restart. What *does* restart the task is `items`\n * changing identity (a new array reference), or `timeSliceMs`/`autoStart`\n * changing. That's deliberate: a new `items` array means new work, and\n * memoizing it when you don't want that is the caller's call to make, the\n * same as any other React dependency.\n */\nexport function useChunkedTask<T, R>(\n items: readonly T[],\n processItem: (item: T, index: number) => R,\n options?: UseChunkedTaskOptions<T, R>,\n): UseChunkedTaskState<R> {\n const {\n timeSliceMs,\n batchSize,\n collectResults,\n autoStart = true,\n onItem,\n } = options ?? {};\n\n // Stable identity, always runs the latest processItem/onItem passed this\n // render — the React-Compiler-safe replacement for a ref mutated during\n // render. Effect Events are meant to be called from inside an effect\n // (here: from the scheduler's async loop, which the effect below owns),\n // never during render itself.\n const stableProcessItem = useEffectEvent((item: T, index: number) =>\n processItem(item, index),\n );\n const stableOnItem = useEffectEvent((result: R, item: T, index: number) => {\n onItem?.(result, item, index);\n });\n\n // Created once, lazily, via useState rather than a ref mutated during\n // render — the controller itself is inert (no subscriptions, no timers)\n // until an effect calls replace() on it, so a discarded render (double\n // render in dev, or one React throws away) never leaks anything.\n const [controller] = useState(() => createTaskController<ChunkScheduler<R>>());\n\n // What getSnapshot() reports before the effect below has ever run —\n // including during SSR, where effects never run at all.\n const idleSnapshot = useMemo<ChunkSnapshot<R>>(\n () => ({ status: IDLE_STATUS, processed: 0, total: items.length }),\n [items.length],\n );\n\n const snapshot = useSyncExternalStore(\n controller.subscribe,\n () => controller.getSnapshot() ?? idleSnapshot,\n () => idleSnapshot,\n );\n\n useEffect(() => {\n const scheduler = createChunkScheduler<T, R>({\n items,\n processItem: stableProcessItem,\n onItem: stableOnItem,\n ...(timeSliceMs !== undefined ? { timeSliceMs } : {}),\n ...(batchSize !== undefined ? { batchSize } : {}),\n ...(collectResults !== undefined ? { collectResults } : {}),\n });\n controller.replace(scheduler);\n if (autoStart) scheduler.start();\n\n return () => {\n // Safe even if the task already finished on its own — cancel() on a\n // terminal scheduler is a documented no-op, not an error.\n scheduler.cancel();\n controller.replace(null);\n };\n // stableProcessItem/stableOnItem are Effect Events: stable by\n // construction, intentionally excluded from the reactive dependency set\n // (that's the whole point of useEffectEvent) rather than omitted by\n // oversight.\n }, [items, timeSliceMs, batchSize, collectResults, autoStart, controller]);\n\n const start = useCallback(() => controller.getCurrent()?.start(), [controller]);\n const pause = useCallback(() => controller.getCurrent()?.pause(), [controller]);\n const resume = useCallback(() => controller.getCurrent()?.resume(), [controller]);\n const cancel = useCallback(() => controller.getCurrent()?.cancel(), [controller]);\n\n return {\n status: snapshot.status,\n processed: snapshot.processed,\n total: snapshot.total,\n error: snapshot.error,\n // From the snapshot, not a direct read of the scheduler: the engine\n // publishes results before it announces a terminal status, so the two\n // always arrive together and a concurrent render can never tear them\n // apart.\n results: snapshot.results,\n isIdle: snapshot.status === 'idle',\n isProcessing: snapshot.status === 'processing',\n isPaused: snapshot.status === 'paused',\n isDone: snapshot.status === 'done',\n isCancelled: snapshot.status === 'cancelled',\n isError: snapshot.status === 'error',\n start,\n pause,\n resume,\n cancel,\n };\n}\n","import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';\n\nimport type { ChunkStatus } from '../core/chunk-machine.js';\nimport { createDeferredTask } from '../core/deferred-task.js';\nimport type {\n DeferredGenerator,\n DeferredTask,\n DeferredTaskSnapshot,\n} from '../core/deferred-task.js';\nimport { createTaskController } from './task-controller.js';\nimport { useEffectEvent } from './use-effect-event.js';\n\nexport interface UseDeferredTaskOptions {\n /** Max ms of uninterrupted work before yielding. Default 5. */\n readonly timeSliceMs?: number;\n /**\n * Generator segments to run between clock checks. Default 1. Raise it\n * only for segments measured in nanoseconds; a slice can then run up to\n * `batchSize` segments past its budget.\n */\n readonly batchSize?: number;\n /** Start processing automatically when the task is (re)created. Default `true`. */\n readonly autoStart?: boolean;\n}\n\nexport interface UseDeferredTaskState<T> {\n readonly status: ChunkStatus;\n readonly error: unknown;\n /** The returned value once the task settles with `done` — `undefined` until then. */\n readonly value: T | undefined;\n readonly isIdle: boolean;\n readonly isProcessing: boolean;\n readonly isPaused: boolean;\n readonly isDone: boolean;\n readonly isCancelled: boolean;\n readonly isError: boolean;\n readonly start: () => void;\n readonly pause: () => void;\n readonly resume: () => void;\n readonly cancel: () => void;\n}\n\nconst IDLE_SNAPSHOT: DeferredTaskSnapshot<never> = { status: 'idle' };\n\n/**\n * Runs an arbitrary heavy, synchronous generator function in chunks, so it\n * never produces a long task on its own. Where `useChunkedTask` chunks \"one\n * function applied to every item of an array\" automatically, this hook\n * leaves the chunk boundaries to you — put `yield` wherever your function\n * can safely pause (see `DeferredGenerator`'s doc comment for an example).\n *\n * `task` is only called when the effect (re)creates the underlying task, not\n * on every render — list whatever it closes over in `deps`, the same way\n * you would for `useMemo` or `useEffect`.\n */\nexport function useDeferredTask<T>(\n task: () => DeferredGenerator<T>,\n deps: readonly unknown[],\n options?: UseDeferredTaskOptions,\n): UseDeferredTaskState<T> {\n const { timeSliceMs, batchSize, autoStart = true } = options ?? {};\n\n // Stable identity, always runs the latest `task` passed this render —\n // see useChunkedTask.ts for why this is useEffectEvent rather than a ref\n // mutated during render.\n const stableTask = useEffectEvent(() => task());\n\n const [controller] = useState(() => createTaskController<DeferredTask<T>>());\n\n const snapshot = useSyncExternalStore(\n controller.subscribe,\n () => controller.getSnapshot() ?? IDLE_SNAPSHOT,\n () => IDLE_SNAPSHOT,\n );\n\n useEffect(\n () => {\n const deferredTask = createDeferredTask<T>({\n task: stableTask,\n ...(timeSliceMs !== undefined ? { timeSliceMs } : {}),\n ...(batchSize !== undefined ? { batchSize } : {}),\n });\n controller.replace(deferredTask);\n if (autoStart) deferredTask.start();\n\n return () => {\n deferredTask.cancel();\n controller.replace(null);\n };\n },\n // `deps` plays the role `items` plays for useChunkedTask: it's the\n // caller's declaration of \"this is new work\". `stableTask` is an Effect\n // Event — stable by construction, intentionally excluded from the\n // reactive dependency set rather than omitted by oversight. `deps` is a\n // caller-supplied array, the same pattern (and the same reason it can't\n // be statically verified) as useMemo/useEffect's own deps parameter.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [...deps, timeSliceMs, batchSize, autoStart, controller],\n );\n\n const start = useCallback(() => controller.getCurrent()?.start(), [controller]);\n const pause = useCallback(() => controller.getCurrent()?.pause(), [controller]);\n const resume = useCallback(() => controller.getCurrent()?.resume(), [controller]);\n const cancel = useCallback(() => controller.getCurrent()?.cancel(), [controller]);\n\n return {\n status: snapshot.status,\n error: snapshot.error,\n // From the snapshot: the engine publishes the value before it\n // announces `done`, so a concurrent render can never see one without\n // the other. See useChunkedTask.ts.\n value: snapshot.value,\n isIdle: snapshot.status === 'idle',\n isProcessing: snapshot.status === 'processing',\n isPaused: snapshot.status === 'paused',\n isDone: snapshot.status === 'done',\n isCancelled: snapshot.status === 'cancelled',\n isError: snapshot.status === 'error',\n start,\n pause,\n resume,\n cancel,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,uBAEU;CACxB,IAAI,UAAuB;CAC3B,IAAI;CACJ,MAAM,4BAAY,IAAI,IAAgB;CAEtC,MAAM,eAAqB;EACzB,KAAK,MAAM,YAAY,WAAW,SAAS;CAC7C;CAEA,OAAO;EACL,YAAY,aAAa;GACvB,UAAU,IAAI,QAAQ;GACtB,aAAa;IACX,UAAU,OAAO,QAAQ;GAC3B;EACF;EACA,mBACE,SAAS,YAAY;EACvB,kBAAkB;EAClB,UAAU,SAAS;GACjB,oBAAoB;GACpB,UAAU;GACV,oBAAoB,MAAM,UAAU,MAAM;GAC1C,OAAO;EACT;CACF;AACF;;AC1CA,SAAgB,uBACd,UAC2B;CAC3B,MAAM,UAAA,GAASA,MAAAA,OAAAA,CAAO,QAAQ;CAC9B,CAAA,GAAA,MAAA,mBAAA,OAAyB;EACvB,OAAO,UAAU;CACnB,CAAC;CACD,QAAA,GAAOC,MAAAA,YAAAA,EAAa,GAAG,SAAe,OAAO,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC;AACnE;AAQA,MAAa,iBAHXC,MACA,kBAGwB;;ACY1B,MAAM,cAA2B;;;;;;;;;;;;;;;;AAiBjC,SAAgB,eACd,OACA,aACA,SACwB;CACxB,MAAM,EACJ,aACA,WACA,gBACA,YAAY,MACZ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,YAAAA,OAAkB,WAAW,WAAW,CAAC,EAAE,MAAM,GAAG,CAAC,UAAU,CAAC;CAC9E,MAAM,UAAA,GAASA,MAAAA,YAAAA,OAAkB,WAAW,WAAW,CAAC,EAAE,OAAO,GAAG,CAAC,UAAU,CAAC;CAChF,MAAM,UAAA,GAASA,MAAAA,YAAAA,OAAkB,WAAW,WAAW,CAAC,EAAE,OAAO,GAAG,CAAC,UAAU,CAAC;CAEhF,OAAO;EACL,QAAQ,SAAS;EACjB,OAAO,SAAS;EAIhB,OAAO,SAAS;EAChB,QAAQ,SAAS,WAAW;EAC5B,cAAc,SAAS,WAAW;EAClC,UAAU,SAAS,WAAW;EAC9B,QAAQ,SAAS,WAAW;EAC5B,aAAa,SAAS,WAAW;EACjC,SAAS,SAAS,WAAW;EAC7B;EACA;EACA;EACA;CACF;AACF"}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { n as createChunkScheduler, t as createDeferredTask } from "./deferred-task-BGsfee-L.js";
|
|
2
|
+
import * as React from "react";
|
|
3
|
+
import { useCallback, useEffect, useInsertionEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
|
4
|
+
// src/react/task-controller.ts
|
|
5
|
+
function createTaskController() {
|
|
6
|
+
let current = null;
|
|
7
|
+
let detachFromCurrent;
|
|
8
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
9
|
+
const notify = () => {
|
|
10
|
+
for (const listener of listeners) listener();
|
|
11
|
+
};
|
|
12
|
+
return {
|
|
13
|
+
subscribe: (listener) => {
|
|
14
|
+
listeners.add(listener);
|
|
15
|
+
return () => {
|
|
16
|
+
listeners.delete(listener);
|
|
17
|
+
};
|
|
18
|
+
},
|
|
19
|
+
getSnapshot: () => current?.getSnapshot(),
|
|
20
|
+
getCurrent: () => current,
|
|
21
|
+
replace: (task) => {
|
|
22
|
+
detachFromCurrent?.();
|
|
23
|
+
current = task;
|
|
24
|
+
detachFromCurrent = task?.subscribe(notify);
|
|
25
|
+
notify();
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
// src/react/use-effect-event.ts
|
|
30
|
+
function useEffectEventFallback(callback) {
|
|
31
|
+
const latest = useRef(callback);
|
|
32
|
+
useInsertionEffect(() => {
|
|
33
|
+
latest.current = callback;
|
|
34
|
+
});
|
|
35
|
+
return useCallback((...args) => latest.current(...args), []);
|
|
36
|
+
}
|
|
37
|
+
const useEffectEvent = React.useEffectEvent ?? useEffectEventFallback;
|
|
38
|
+
// src/react/useChunkedTask.ts
|
|
39
|
+
const IDLE_STATUS = "idle";
|
|
40
|
+
/**
|
|
41
|
+
* Chunks a heavy, synchronous per-item computation over `items` so it never
|
|
42
|
+
* blocks the main thread for longer than a time slice — the thing that
|
|
43
|
+
* costs you Interaction to Next Paint. Starts automatically by default;
|
|
44
|
+
* pass `{ autoStart: false }` to wait for an explicit `start()` call (e.g.
|
|
45
|
+
* behind a button).
|
|
46
|
+
*
|
|
47
|
+
* `processItem` and `onItem` can be fresh closures every render — the hook
|
|
48
|
+
* always calls the latest version (via `useEffectEvent`) without that
|
|
49
|
+
* causing the task to restart. What *does* restart the task is `items`
|
|
50
|
+
* changing identity (a new array reference), or `timeSliceMs`/`autoStart`
|
|
51
|
+
* changing. That's deliberate: a new `items` array means new work, and
|
|
52
|
+
* memoizing it when you don't want that is the caller's call to make, the
|
|
53
|
+
* same as any other React dependency.
|
|
54
|
+
*/
|
|
55
|
+
function useChunkedTask(items, processItem, options) {
|
|
56
|
+
const { timeSliceMs, batchSize, collectResults, autoStart = true, onItem } = options ?? {};
|
|
57
|
+
const stableProcessItem = useEffectEvent((item, index) => processItem(item, index));
|
|
58
|
+
const stableOnItem = useEffectEvent((result, item, index) => {
|
|
59
|
+
onItem?.(result, item, index);
|
|
60
|
+
});
|
|
61
|
+
const [controller] = useState(() => createTaskController());
|
|
62
|
+
const idleSnapshot = useMemo(() => ({
|
|
63
|
+
status: IDLE_STATUS,
|
|
64
|
+
processed: 0,
|
|
65
|
+
total: items.length
|
|
66
|
+
}), [items.length]);
|
|
67
|
+
const snapshot = useSyncExternalStore(controller.subscribe, () => controller.getSnapshot() ?? idleSnapshot, () => idleSnapshot);
|
|
68
|
+
useEffect(() => {
|
|
69
|
+
const scheduler = createChunkScheduler({
|
|
70
|
+
items,
|
|
71
|
+
processItem: stableProcessItem,
|
|
72
|
+
onItem: stableOnItem,
|
|
73
|
+
...timeSliceMs !== void 0 ? { timeSliceMs } : {},
|
|
74
|
+
...batchSize !== void 0 ? { batchSize } : {},
|
|
75
|
+
...collectResults !== void 0 ? { collectResults } : {}
|
|
76
|
+
});
|
|
77
|
+
controller.replace(scheduler);
|
|
78
|
+
if (autoStart) scheduler.start();
|
|
79
|
+
return () => {
|
|
80
|
+
scheduler.cancel();
|
|
81
|
+
controller.replace(null);
|
|
82
|
+
};
|
|
83
|
+
}, [
|
|
84
|
+
items,
|
|
85
|
+
timeSliceMs,
|
|
86
|
+
batchSize,
|
|
87
|
+
collectResults,
|
|
88
|
+
autoStart,
|
|
89
|
+
controller
|
|
90
|
+
]);
|
|
91
|
+
const start = useCallback(() => controller.getCurrent()?.start(), [controller]);
|
|
92
|
+
const pause = useCallback(() => controller.getCurrent()?.pause(), [controller]);
|
|
93
|
+
const resume = useCallback(() => controller.getCurrent()?.resume(), [controller]);
|
|
94
|
+
const cancel = useCallback(() => controller.getCurrent()?.cancel(), [controller]);
|
|
95
|
+
return {
|
|
96
|
+
status: snapshot.status,
|
|
97
|
+
processed: snapshot.processed,
|
|
98
|
+
total: snapshot.total,
|
|
99
|
+
error: snapshot.error,
|
|
100
|
+
results: snapshot.results,
|
|
101
|
+
isIdle: snapshot.status === "idle",
|
|
102
|
+
isProcessing: snapshot.status === "processing",
|
|
103
|
+
isPaused: snapshot.status === "paused",
|
|
104
|
+
isDone: snapshot.status === "done",
|
|
105
|
+
isCancelled: snapshot.status === "cancelled",
|
|
106
|
+
isError: snapshot.status === "error",
|
|
107
|
+
start,
|
|
108
|
+
pause,
|
|
109
|
+
resume,
|
|
110
|
+
cancel
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
// src/react/useDeferredTask.ts
|
|
114
|
+
const IDLE_SNAPSHOT = { status: "idle" };
|
|
115
|
+
/**
|
|
116
|
+
* Runs an arbitrary heavy, synchronous generator function in chunks, so it
|
|
117
|
+
* never produces a long task on its own. Where `useChunkedTask` chunks "one
|
|
118
|
+
* function applied to every item of an array" automatically, this hook
|
|
119
|
+
* leaves the chunk boundaries to you — put `yield` wherever your function
|
|
120
|
+
* can safely pause (see `DeferredGenerator`'s doc comment for an example).
|
|
121
|
+
*
|
|
122
|
+
* `task` is only called when the effect (re)creates the underlying task, not
|
|
123
|
+
* on every render — list whatever it closes over in `deps`, the same way
|
|
124
|
+
* you would for `useMemo` or `useEffect`.
|
|
125
|
+
*/
|
|
126
|
+
function useDeferredTask(task, deps, options) {
|
|
127
|
+
const { timeSliceMs, batchSize, autoStart = true } = options ?? {};
|
|
128
|
+
const stableTask = useEffectEvent(() => task());
|
|
129
|
+
const [controller] = useState(() => createTaskController());
|
|
130
|
+
const snapshot = useSyncExternalStore(controller.subscribe, () => controller.getSnapshot() ?? IDLE_SNAPSHOT, () => IDLE_SNAPSHOT);
|
|
131
|
+
useEffect(() => {
|
|
132
|
+
const deferredTask = createDeferredTask({
|
|
133
|
+
task: stableTask,
|
|
134
|
+
...timeSliceMs !== void 0 ? { timeSliceMs } : {},
|
|
135
|
+
...batchSize !== void 0 ? { batchSize } : {}
|
|
136
|
+
});
|
|
137
|
+
controller.replace(deferredTask);
|
|
138
|
+
if (autoStart) deferredTask.start();
|
|
139
|
+
return () => {
|
|
140
|
+
deferredTask.cancel();
|
|
141
|
+
controller.replace(null);
|
|
142
|
+
};
|
|
143
|
+
}, [
|
|
144
|
+
...deps,
|
|
145
|
+
timeSliceMs,
|
|
146
|
+
batchSize,
|
|
147
|
+
autoStart,
|
|
148
|
+
controller
|
|
149
|
+
]);
|
|
150
|
+
const start = useCallback(() => controller.getCurrent()?.start(), [controller]);
|
|
151
|
+
const pause = useCallback(() => controller.getCurrent()?.pause(), [controller]);
|
|
152
|
+
const resume = useCallback(() => controller.getCurrent()?.resume(), [controller]);
|
|
153
|
+
const cancel = useCallback(() => controller.getCurrent()?.cancel(), [controller]);
|
|
154
|
+
return {
|
|
155
|
+
status: snapshot.status,
|
|
156
|
+
error: snapshot.error,
|
|
157
|
+
value: snapshot.value,
|
|
158
|
+
isIdle: snapshot.status === "idle",
|
|
159
|
+
isProcessing: snapshot.status === "processing",
|
|
160
|
+
isPaused: snapshot.status === "paused",
|
|
161
|
+
isDone: snapshot.status === "done",
|
|
162
|
+
isCancelled: snapshot.status === "cancelled",
|
|
163
|
+
isError: snapshot.status === "error",
|
|
164
|
+
start,
|
|
165
|
+
pause,
|
|
166
|
+
resume,
|
|
167
|
+
cancel
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
export { useChunkedTask, useDeferredTask };
|
|
171
|
+
|
|
172
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/react/task-controller.ts","../../src/react/use-effect-event.ts","../../src/react/useChunkedTask.ts","../../src/react/useDeferredTask.ts"],"sourcesContent":["/**\n * The glue between a task handle (`ChunkScheduler<R>`, `DeferredTask<T>` —\n * anything with `subscribe`/`getSnapshot`) recreated from scratch whenever a\n * hook's deps change, inside an effect, and `useSyncExternalStore`, which\n * wants one stable `subscribe` function for a component's whole lifetime.\n *\n * `useSyncExternalStore` resubscribes whenever the `subscribe` function\n * identity changes — fine for correctness, but it means the naive approach\n * (pass the current task's own `.subscribe` directly) either churns\n * subscriptions every render or, worse, drifts: the component keeps\n * `subscribe`d to whichever task was current when it last resubscribed, not\n * necessarily the one `getSnapshot` is reading from after a swap.\n *\n * A controller sidesteps that: it's created once per hook instance (lazy\n * `useState` initializer in the hook, so it's stable without touching a\n * ref), hands `useSyncExternalStore` a `subscribe`/`getSnapshot` pair that\n * never change identity, and internally forwards to whichever task is\n * \"current\" — re-pointing itself via `replace()` every time the effect\n * swaps in a new one. Generic over the task shape so both `useChunkedTask`\n * and `useDeferredTask` share this one implementation.\n *\n * Every property below is an arrow function, deliberately — not method\n * shorthand — so none of them close over `this`, and `controller.subscribe`\n * can be handed to `useSyncExternalStore` directly as a plain function\n * reference without an unbound-method footgun.\n */\nexport interface SubscribableTask<Snapshot> {\n subscribe(listener: () => void): () => void;\n getSnapshot(): Snapshot;\n}\n\nexport interface TaskController<Task extends SubscribableTask<unknown>> {\n subscribe: (listener: () => void) => () => void;\n getSnapshot: () => ReturnType<Task['getSnapshot']> | undefined;\n getCurrent: () => Task | null;\n /** Swaps in a new task (or none), detaching from the previous one first. */\n replace: (task: Task | null) => void;\n}\n\nexport function createTaskController<\n Task extends SubscribableTask<unknown>,\n>(): TaskController<Task> {\n let current: Task | null = null;\n let detachFromCurrent: (() => void) | undefined;\n const listeners = new Set<() => void>();\n\n const notify = (): void => {\n for (const listener of listeners) listener();\n };\n\n return {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n getSnapshot: () =>\n current?.getSnapshot() as ReturnType<Task['getSnapshot']> | undefined,\n getCurrent: () => current,\n replace: (task) => {\n detachFromCurrent?.();\n current = task;\n detachFromCurrent = task?.subscribe(notify);\n notify();\n },\n };\n}\n","import * as React from 'react';\nimport { useCallback, useInsertionEffect, useRef } from 'react';\n\n/**\n * `useEffectEvent` only became a stable React export in 19.2. On React 18\n * and 19.0–19.1 it doesn't exist at all — and a named\n * `import { useEffectEvent } from 'react'` then fails outright: at module\n * link time under Node ESM (\"Named export 'useEffectEvent' not found\"), or\n * as \"useEffectEvent is not a function\" on first render in a bundler. Both\n * versions are inside this package's declared peer range, so that has to\n * work, not just type-check.\n *\n * So the native hook is read as a property of the namespace object, where a\n * missing export is plain `undefined` rather than a link error, and used\n * whenever the running React has it. Otherwise the fallback keeps the same\n * contract: a stable function identity that always calls the latest\n * callback. The latest callback is committed from an insertion effect —\n * after render, before any layout or passive effect of the same commit can\n * observe it — so effects always see the current closure, without the\n * render-time ref mutation the React Compiler rejects.\n */\ntype EffectEventHook = <Args extends readonly unknown[], Return>(\n callback: (...args: Args) => Return,\n) => (...args: Args) => Return;\n\nexport function useEffectEventFallback<Args extends readonly unknown[], Return>(\n callback: (...args: Args) => Return,\n): (...args: Args) => Return {\n const latest = useRef(callback);\n useInsertionEffect(() => {\n latest.current = callback;\n });\n return useCallback((...args: Args) => latest.current(...args), []);\n}\n\n// Through `unknown` on purpose: React 18's types have no `useEffectEvent`\n// member at all, so a direct assertion wouldn't compile against them.\nconst nativeUseEffectEvent = (\n React as unknown as { readonly useEffectEvent?: EffectEventHook }\n).useEffectEvent;\n\nexport const useEffectEvent: EffectEventHook =\n nativeUseEffectEvent ?? useEffectEventFallback;\n","import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';\n\nimport type { ChunkStatus } from '../core/chunk-machine.js';\nimport { createChunkScheduler } from '../core/chunk-scheduler.js';\nimport type { ChunkScheduler, ChunkSnapshot } from '../core/chunk-scheduler.js';\nimport { createTaskController } from './task-controller.js';\nimport { useEffectEvent } from './use-effect-event.js';\n\nexport interface UseChunkedTaskOptions<T, R> {\n /** Max ms of uninterrupted work before yielding. Default 5. */\n readonly timeSliceMs?: number;\n /**\n * Items to process between clock checks. Default 1. Raise it only for\n * items measured in nanoseconds, where reading the clock costs more than\n * the work; a slice can then run up to `batchSize` items past its budget.\n * See the `batchSize` note on `createChunkScheduler`.\n */\n readonly batchSize?: number;\n /**\n * Keep every result in `results`. Default true. Set false when results\n * are consumed through `onItem`, to avoid retaining one result per item;\n * `results` is then an empty array once the task settles.\n */\n readonly collectResults?: boolean;\n /** Start processing automatically when the task is (re)created. Default `true`. */\n readonly autoStart?: boolean;\n /**\n * Called synchronously after each item is processed. This is the cheap\n * way to consume results incrementally while the task is still running —\n * write into a ref-backed buffer, a canvas, a chart, whatever you need —\n * without paying for an array copy on every yield checkpoint.\n */\n readonly onItem?: (result: R, item: T, index: number) => void;\n}\n\nexport interface UseChunkedTaskState<R> {\n readonly status: ChunkStatus;\n readonly processed: number;\n readonly total: number;\n readonly error: unknown;\n /** The full results array once the task has settled — `undefined` until then. */\n readonly results: readonly R[] | undefined;\n readonly isIdle: boolean;\n readonly isProcessing: boolean;\n readonly isPaused: boolean;\n readonly isDone: boolean;\n readonly isCancelled: boolean;\n readonly isError: boolean;\n readonly start: () => void;\n readonly pause: () => void;\n readonly resume: () => void;\n readonly cancel: () => void;\n}\n\nconst IDLE_STATUS: ChunkStatus = 'idle';\n\n/**\n * Chunks a heavy, synchronous per-item computation over `items` so it never\n * blocks the main thread for longer than a time slice — the thing that\n * costs you Interaction to Next Paint. Starts automatically by default;\n * pass `{ autoStart: false }` to wait for an explicit `start()` call (e.g.\n * behind a button).\n *\n * `processItem` and `onItem` can be fresh closures every render — the hook\n * always calls the latest version (via `useEffectEvent`) without that\n * causing the task to restart. What *does* restart the task is `items`\n * changing identity (a new array reference), or `timeSliceMs`/`autoStart`\n * changing. That's deliberate: a new `items` array means new work, and\n * memoizing it when you don't want that is the caller's call to make, the\n * same as any other React dependency.\n */\nexport function useChunkedTask<T, R>(\n items: readonly T[],\n processItem: (item: T, index: number) => R,\n options?: UseChunkedTaskOptions<T, R>,\n): UseChunkedTaskState<R> {\n const {\n timeSliceMs,\n batchSize,\n collectResults,\n autoStart = true,\n onItem,\n } = options ?? {};\n\n // Stable identity, always runs the latest processItem/onItem passed this\n // render — the React-Compiler-safe replacement for a ref mutated during\n // render. Effect Events are meant to be called from inside an effect\n // (here: from the scheduler's async loop, which the effect below owns),\n // never during render itself.\n const stableProcessItem = useEffectEvent((item: T, index: number) =>\n processItem(item, index),\n );\n const stableOnItem = useEffectEvent((result: R, item: T, index: number) => {\n onItem?.(result, item, index);\n });\n\n // Created once, lazily, via useState rather than a ref mutated during\n // render — the controller itself is inert (no subscriptions, no timers)\n // until an effect calls replace() on it, so a discarded render (double\n // render in dev, or one React throws away) never leaks anything.\n const [controller] = useState(() => createTaskController<ChunkScheduler<R>>());\n\n // What getSnapshot() reports before the effect below has ever run —\n // including during SSR, where effects never run at all.\n const idleSnapshot = useMemo<ChunkSnapshot<R>>(\n () => ({ status: IDLE_STATUS, processed: 0, total: items.length }),\n [items.length],\n );\n\n const snapshot = useSyncExternalStore(\n controller.subscribe,\n () => controller.getSnapshot() ?? idleSnapshot,\n () => idleSnapshot,\n );\n\n useEffect(() => {\n const scheduler = createChunkScheduler<T, R>({\n items,\n processItem: stableProcessItem,\n onItem: stableOnItem,\n ...(timeSliceMs !== undefined ? { timeSliceMs } : {}),\n ...(batchSize !== undefined ? { batchSize } : {}),\n ...(collectResults !== undefined ? { collectResults } : {}),\n });\n controller.replace(scheduler);\n if (autoStart) scheduler.start();\n\n return () => {\n // Safe even if the task already finished on its own — cancel() on a\n // terminal scheduler is a documented no-op, not an error.\n scheduler.cancel();\n controller.replace(null);\n };\n // stableProcessItem/stableOnItem are Effect Events: stable by\n // construction, intentionally excluded from the reactive dependency set\n // (that's the whole point of useEffectEvent) rather than omitted by\n // oversight.\n }, [items, timeSliceMs, batchSize, collectResults, autoStart, controller]);\n\n const start = useCallback(() => controller.getCurrent()?.start(), [controller]);\n const pause = useCallback(() => controller.getCurrent()?.pause(), [controller]);\n const resume = useCallback(() => controller.getCurrent()?.resume(), [controller]);\n const cancel = useCallback(() => controller.getCurrent()?.cancel(), [controller]);\n\n return {\n status: snapshot.status,\n processed: snapshot.processed,\n total: snapshot.total,\n error: snapshot.error,\n // From the snapshot, not a direct read of the scheduler: the engine\n // publishes results before it announces a terminal status, so the two\n // always arrive together and a concurrent render can never tear them\n // apart.\n results: snapshot.results,\n isIdle: snapshot.status === 'idle',\n isProcessing: snapshot.status === 'processing',\n isPaused: snapshot.status === 'paused',\n isDone: snapshot.status === 'done',\n isCancelled: snapshot.status === 'cancelled',\n isError: snapshot.status === 'error',\n start,\n pause,\n resume,\n cancel,\n };\n}\n","import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';\n\nimport type { ChunkStatus } from '../core/chunk-machine.js';\nimport { createDeferredTask } from '../core/deferred-task.js';\nimport type {\n DeferredGenerator,\n DeferredTask,\n DeferredTaskSnapshot,\n} from '../core/deferred-task.js';\nimport { createTaskController } from './task-controller.js';\nimport { useEffectEvent } from './use-effect-event.js';\n\nexport interface UseDeferredTaskOptions {\n /** Max ms of uninterrupted work before yielding. Default 5. */\n readonly timeSliceMs?: number;\n /**\n * Generator segments to run between clock checks. Default 1. Raise it\n * only for segments measured in nanoseconds; a slice can then run up to\n * `batchSize` segments past its budget.\n */\n readonly batchSize?: number;\n /** Start processing automatically when the task is (re)created. Default `true`. */\n readonly autoStart?: boolean;\n}\n\nexport interface UseDeferredTaskState<T> {\n readonly status: ChunkStatus;\n readonly error: unknown;\n /** The returned value once the task settles with `done` — `undefined` until then. */\n readonly value: T | undefined;\n readonly isIdle: boolean;\n readonly isProcessing: boolean;\n readonly isPaused: boolean;\n readonly isDone: boolean;\n readonly isCancelled: boolean;\n readonly isError: boolean;\n readonly start: () => void;\n readonly pause: () => void;\n readonly resume: () => void;\n readonly cancel: () => void;\n}\n\nconst IDLE_SNAPSHOT: DeferredTaskSnapshot<never> = { status: 'idle' };\n\n/**\n * Runs an arbitrary heavy, synchronous generator function in chunks, so it\n * never produces a long task on its own. Where `useChunkedTask` chunks \"one\n * function applied to every item of an array\" automatically, this hook\n * leaves the chunk boundaries to you — put `yield` wherever your function\n * can safely pause (see `DeferredGenerator`'s doc comment for an example).\n *\n * `task` is only called when the effect (re)creates the underlying task, not\n * on every render — list whatever it closes over in `deps`, the same way\n * you would for `useMemo` or `useEffect`.\n */\nexport function useDeferredTask<T>(\n task: () => DeferredGenerator<T>,\n deps: readonly unknown[],\n options?: UseDeferredTaskOptions,\n): UseDeferredTaskState<T> {\n const { timeSliceMs, batchSize, autoStart = true } = options ?? {};\n\n // Stable identity, always runs the latest `task` passed this render —\n // see useChunkedTask.ts for why this is useEffectEvent rather than a ref\n // mutated during render.\n const stableTask = useEffectEvent(() => task());\n\n const [controller] = useState(() => createTaskController<DeferredTask<T>>());\n\n const snapshot = useSyncExternalStore(\n controller.subscribe,\n () => controller.getSnapshot() ?? IDLE_SNAPSHOT,\n () => IDLE_SNAPSHOT,\n );\n\n useEffect(\n () => {\n const deferredTask = createDeferredTask<T>({\n task: stableTask,\n ...(timeSliceMs !== undefined ? { timeSliceMs } : {}),\n ...(batchSize !== undefined ? { batchSize } : {}),\n });\n controller.replace(deferredTask);\n if (autoStart) deferredTask.start();\n\n return () => {\n deferredTask.cancel();\n controller.replace(null);\n };\n },\n // `deps` plays the role `items` plays for useChunkedTask: it's the\n // caller's declaration of \"this is new work\". `stableTask` is an Effect\n // Event — stable by construction, intentionally excluded from the\n // reactive dependency set rather than omitted by oversight. `deps` is a\n // caller-supplied array, the same pattern (and the same reason it can't\n // be statically verified) as useMemo/useEffect's own deps parameter.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [...deps, timeSliceMs, batchSize, autoStart, controller],\n );\n\n const start = useCallback(() => controller.getCurrent()?.start(), [controller]);\n const pause = useCallback(() => controller.getCurrent()?.pause(), [controller]);\n const resume = useCallback(() => controller.getCurrent()?.resume(), [controller]);\n const cancel = useCallback(() => controller.getCurrent()?.cancel(), [controller]);\n\n return {\n status: snapshot.status,\n error: snapshot.error,\n // From the snapshot: the engine publishes the value before it\n // announces `done`, so a concurrent render can never see one without\n // the other. See useChunkedTask.ts.\n value: snapshot.value,\n isIdle: snapshot.status === 'idle',\n isProcessing: snapshot.status === 'processing',\n isPaused: snapshot.status === 'paused',\n isDone: snapshot.status === 'done',\n isCancelled: snapshot.status === 'cancelled',\n isError: snapshot.status === 'error',\n start,\n pause,\n resume,\n cancel,\n };\n}\n"],"mappings":";;;;AAuCA,SAAgB,uBAEU;CACxB,IAAI,UAAuB;CAC3B,IAAI;CACJ,MAAM,4BAAY,IAAI,IAAgB;CAEtC,MAAM,eAAqB;EACzB,KAAK,MAAM,YAAY,W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AY,EAAE,UAAU,IAAI,CAAC;EACjD,CAAC;EACD,WAAW,QAAQ,YAAY;EAC/B,IAAI,WAAW,aAAa,MAAM;EAElC,aAAa;GACX,aAAa,OAAO;GACpB,WAAW,QAAQ,IAAI;EACzB;CACF,GAQA;EAAC,GAAG;EAAM;EAAa;EAAW;EAAW;CAAU,CACzD;CAEA,MAAM,QAAQ,kBAAkB,WAAW,WAAW,CAAC,EAAE,MAAM,GAAG,CAAC,UAAU,CAAC;CAC9E,MAAM,QAAQ,kBAAkB,WAAW,WAAW,CAAC,EAAE,MAAM,GAAG,CAAC,UAAU,CAAC;CAC9E,MAAM,SAAS,kBAAkB,WAAW,WAAW,CAAC,EAAE,OAAO,GAAG,CAAC,UAAU,CAAC;CAChF,MAAM,SAAS,kBAAkB,WAAW,WAAW,CAAC,EAAE,OAAO,GAAG,CAAC,UAAU,CAAC;CAEhF,OAAO;EACL,QAAQ,SAAS;EACjB,OAAO,SAAS;EAIhB,OAAO,SAAS;EAChB,QAAQ,SAAS,WAAW;EAC5B,cAAc,SAAS,WAAW;EAClC,UAAU,SAAS,WAAW;EAC9B,QAAQ,SAAS,WAAW;EAC5B,aAAa,SAAS,WAAW;EACjC,SAAS,SAAS,WAAW;EAC7B;EACA;EACA;EACA;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-inp-chunker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Headless React/TypeScript primitives that chunk heavy synchronous work and yield to the main thread, so long-running updates never cost you Interaction to Next Paint (INP).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"concurrent",
|
|
16
16
|
"headless"
|
|
17
17
|
],
|
|
18
|
-
"homepage": "https://github.
|
|
18
|
+
"homepage": "https://suprabhat02.github.io/react-inp-chunker/",
|
|
19
19
|
"bugs": "https://github.com/suprabhat02/react-inp-chunker/issues",
|
|
20
20
|
"repository": {
|
|
21
21
|
"type": "git",
|
|
@@ -26,18 +26,48 @@
|
|
|
26
26
|
"type": "module",
|
|
27
27
|
"sideEffects": false,
|
|
28
28
|
"engines": {
|
|
29
|
-
"node": ">=
|
|
29
|
+
"node": ">=18"
|
|
30
30
|
},
|
|
31
31
|
"exports": {
|
|
32
32
|
".": {
|
|
33
|
-
"
|
|
34
|
-
|
|
35
|
-
|
|
33
|
+
"production": {
|
|
34
|
+
"import": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"default": "./dist/production/index.js"
|
|
37
|
+
},
|
|
38
|
+
"require": {
|
|
39
|
+
"types": "./dist/index.d.cts",
|
|
40
|
+
"default": "./dist/production/index.cjs"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"import": {
|
|
44
|
+
"types": "./dist/index.d.ts",
|
|
45
|
+
"default": "./dist/index.js"
|
|
46
|
+
},
|
|
47
|
+
"require": {
|
|
48
|
+
"types": "./dist/index.d.cts",
|
|
49
|
+
"default": "./dist/index.cjs"
|
|
50
|
+
}
|
|
36
51
|
},
|
|
37
52
|
"./core": {
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
|
|
53
|
+
"production": {
|
|
54
|
+
"import": {
|
|
55
|
+
"types": "./dist/core/index.d.ts",
|
|
56
|
+
"default": "./dist/production/core/index.js"
|
|
57
|
+
},
|
|
58
|
+
"require": {
|
|
59
|
+
"types": "./dist/core/index.d.cts",
|
|
60
|
+
"default": "./dist/production/core/index.cjs"
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
"import": {
|
|
64
|
+
"types": "./dist/core/index.d.ts",
|
|
65
|
+
"default": "./dist/core/index.js"
|
|
66
|
+
},
|
|
67
|
+
"require": {
|
|
68
|
+
"types": "./dist/core/index.d.cts",
|
|
69
|
+
"default": "./dist/core/index.cjs"
|
|
70
|
+
}
|
|
41
71
|
},
|
|
42
72
|
"./package.json": "./package.json"
|
|
43
73
|
},
|
|
@@ -46,6 +76,7 @@
|
|
|
46
76
|
"types": "./dist/index.d.ts",
|
|
47
77
|
"files": [
|
|
48
78
|
"dist",
|
|
79
|
+
"core",
|
|
49
80
|
"README.md",
|
|
50
81
|
"LICENSE"
|
|
51
82
|
],
|
|
@@ -56,6 +87,7 @@
|
|
|
56
87
|
"build": "tsdown",
|
|
57
88
|
"dev": "tsdown --watch",
|
|
58
89
|
"typecheck": "tsc --noEmit",
|
|
90
|
+
"typecheck:react18": "tsc -p tsconfig.react18.json",
|
|
59
91
|
"lint": "eslint .",
|
|
60
92
|
"format": "prettier --write .",
|
|
61
93
|
"format:check": "prettier --check .",
|
|
@@ -63,52 +95,63 @@
|
|
|
63
95
|
"test:watch": "vitest",
|
|
64
96
|
"test:coverage": "vitest run --coverage",
|
|
65
97
|
"size": "size-limit",
|
|
66
|
-
"verify": "npm run lint && npm run format:check && npm run typecheck && npm run test:coverage && npm run build && npm run size",
|
|
67
|
-
"prepublishOnly": "npm run verify"
|
|
98
|
+
"verify": "npm run lint && npm run format:check && npm run typecheck && npm run test:coverage && npm run build && npm run api:check && npm run lint:package && npm run types:resolution && npm run types:consumer && npm run size",
|
|
99
|
+
"prepublishOnly": "npm run verify",
|
|
100
|
+
"bench": "npm run build && node bench/overhead.mjs",
|
|
101
|
+
"api:check": "node scripts/api-surface.mjs",
|
|
102
|
+
"api:update": "node scripts/api-surface.mjs --update",
|
|
103
|
+
"lint:package": "publint --strict",
|
|
104
|
+
"types:resolution": "node scripts/check-type-resolution.mjs",
|
|
105
|
+
"types:consumer": "tsc -p consumer/tsconfig.bundler.json && tsc -p consumer/tsconfig.nodenext.json",
|
|
106
|
+
"test:browser": "npm run build && node tests/browser/yielding.mjs"
|
|
68
107
|
},
|
|
69
108
|
"devDependencies": {
|
|
109
|
+
"@arethetypeswrong/core": "^0.18.2",
|
|
70
110
|
"@eslint/js": "10.0.1",
|
|
111
|
+
"@size-limit/preset-small-lib": "14.3.0",
|
|
71
112
|
"@testing-library/react": "16.3.3",
|
|
72
|
-
"@types/node": "
|
|
113
|
+
"@types/node": "^26.6.5",
|
|
73
114
|
"@types/react": "19.3.0",
|
|
74
115
|
"@types/react-dom": "19.3.0",
|
|
75
116
|
"@vitest/coverage-v8": "5.0.5",
|
|
76
117
|
"eslint": "10.13.0",
|
|
77
118
|
"eslint-plugin-react-hooks": "7.1.1",
|
|
119
|
+
"fast-check": "^4.5.0",
|
|
78
120
|
"globals": "17.13.0",
|
|
79
|
-
"jsdom": "
|
|
121
|
+
"jsdom": "^30.1.3",
|
|
122
|
+
"playwright": "^1.63.0",
|
|
80
123
|
"prettier": "3.9.10",
|
|
124
|
+
"publint": "^0.3.12",
|
|
81
125
|
"react": "19.3.1",
|
|
82
126
|
"react-dom": "19.3.1",
|
|
83
127
|
"size-limit": "14.3.0",
|
|
84
|
-
"@size-limit/preset-small-lib": "14.3.0",
|
|
85
128
|
"tsdown": "0.23.2",
|
|
86
|
-
"typescript": "6.0.3",
|
|
87
|
-
"typescript-eslint": "8.72.
|
|
129
|
+
"typescript": "^6.0.3",
|
|
130
|
+
"typescript-eslint": "8.72.1",
|
|
88
131
|
"vitest": "5.0.5"
|
|
89
132
|
},
|
|
90
133
|
"size-limit": [
|
|
91
134
|
{
|
|
92
135
|
"name": "core (import { createChunkScheduler })",
|
|
93
|
-
"path": "dist/core/index.js",
|
|
136
|
+
"path": "dist/production/core/index.js",
|
|
94
137
|
"import": "{ createChunkScheduler }",
|
|
95
|
-
"limit": "1.
|
|
138
|
+
"limit": "1.4 kB"
|
|
96
139
|
},
|
|
97
140
|
{
|
|
98
141
|
"name": "useChunkedTask",
|
|
99
|
-
"path": "dist/index.js",
|
|
142
|
+
"path": "dist/production/index.js",
|
|
100
143
|
"import": "{ useChunkedTask }",
|
|
101
144
|
"limit": "2.2 kB"
|
|
102
145
|
},
|
|
103
146
|
{
|
|
104
147
|
"name": "useDeferredTask",
|
|
105
|
-
"path": "dist/index.js",
|
|
148
|
+
"path": "dist/production/index.js",
|
|
106
149
|
"import": "{ useDeferredTask }",
|
|
107
|
-
"limit": "1.
|
|
150
|
+
"limit": "1.8 kB"
|
|
108
151
|
},
|
|
109
152
|
{
|
|
110
153
|
"name": "everything",
|
|
111
|
-
"path": "dist/index.js",
|
|
154
|
+
"path": "dist/production/index.js",
|
|
112
155
|
"limit": "3.5 kB"
|
|
113
156
|
}
|
|
114
157
|
]
|