@ibnlanre/jumi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ type ViewTransitionConcurrency = 'auto' | 'coalesce' | 'supersede';
2
+ /** Shared policy for every invocation of this controller's wrapped operations. */
3
+ type ViewTransitionControllerOptions = ViewTransitionOptions;
4
+ /**
5
+ * The lifecycle, which is total per run and exclusive in its shapes: a run that materialises reports start and
6
+ * then end; one that is declined reports decline and never starts; one that rejects reports error.
7
+ *
8
+ * A hook is told *which operation* it is observing by being that operation's hook rather than by an
9
+ * identifier: ownership is what `wrap(update, hooks)` buys. Overlapping calls of one wrapped operation stay
10
+ * distinct internally without the distinction being handed out, so these hooks cannot identify which overlapping invocation fired. Each returned promise
11
+ * remains the individual caller’s outcome channel.
12
+ */
13
+ type ViewTransitionHooks = {
14
+ onDecline?: (reason: ViewTransitionReason) => void;
15
+ onError?: (error: unknown) => void;
16
+ onTransitionEnd?: () => void;
17
+ onTransitionStart?: () => void;
18
+ };
19
+ type ViewTransitionOptions = {
20
+ /**
21
+ * What to do when a transition is already running, which is a question about *who* is calling.
22
+ *
23
+ * `auto` — the default — tells an echo from a new intent by when the call arrives, because that is the one
24
+ * signal a caller cannot fake by accident: a second call in the same task (its microtasks included) cannot
25
+ * be a second human gesture, while a call from a later task can be. An echo is coalesced and a gesture
26
+ * supersedes, which is what makes `transition.run(change)` the right call for both — see the marker's
27
+ * own note for the measurements behind that.
28
+ *
29
+ * `coalesce` applies the update exactly once and starts no second transition, whatever the timing. The
30
+ * careful choice, and the right one for a caller writing on a schedule rather than on a gesture — a poll, a
31
+ * resize, an animation frame — where a second transition per write is noise.
32
+ *
33
+ * `supersede` always starts a transition, aborting the one in flight. Starting one is the operation with a
34
+ * hazard: the platform aborts the first, the aborted call's callback still runs, and the survivor can end
35
+ * up animating a boundary it did not fill in. Safe once the first transition has materialised (measured),
36
+ * which is why `auto` is willing to do it for a real gesture and not for an echo.
37
+ */
38
+ concurrency?: ViewTransitionConcurrency;
39
+ };
40
+ type ViewTransitionOutcome = {
41
+ reason: ViewTransitionReason;
42
+ transitioned: false;
43
+ } | {
44
+ transitioned: true;
45
+ };
46
+ /**
47
+ * Jumi's view transition orchestration: the smallest thing that removes the platform's lifecycle footguns
48
+ * without owning the caller's state.
49
+ *
50
+ * import { createViewTransition } from '@ibnlanre/jumi/view-transition'
51
+ *
52
+ * const transition = createViewTransition()
53
+ * await transition.run(() => {
54
+ * active = next
55
+ * apply()
56
+ * })
57
+ *
58
+ * The browser's contract is unavoidable — capture old, run the application's mutation, capture new — and no
59
+ * class can say what state to change. What is avoidable is knowing six things about that contract:
60
+ *
61
+ * the callback is deferred a guard keyed on the value the callback sets does not catch a second call
62
+ * in the same task (measured: the callback runs 52ms after the call on a cold
63
+ * document, 16ms warm)
64
+ * a second call aborts the first and the aborted call's callback *still runs*, so the surviving transition
65
+ * can animate a boundary it did not fill in — which works only while the
66
+ * browser happens to order those two things that way
67
+ * the boundary can be empty the layout changes and nothing animates, and `finished` resolves either way.
68
+ * Only `ready` separates "this materialised" from "this was cut short", so an
69
+ * outcome has to read both and cannot be derived from `finished` alone
70
+ * a hidden document skips it `ready` rejects, `finished` resolves, the update runs
71
+ * the update's error is published three times on `ready`, on `updateCallbackDone` and on `finished`, so a
72
+ * wrapper that consumes two of them still leaks an unhandled rejection
73
+ * the pseudo tree takes the hit while a transition runs a click's target becomes `<html>`, so anything
74
+ * resolving clicks during one has to notice that itself
75
+ *
76
+ * None of that is discoverable from `document.startViewTransition`'s shape, and all six were hit building one
77
+ * demo. See `engineering/research/vt-orchestration.md`.
78
+ *
79
+ * **The update must complete synchronously**, and that is enforced rather than documented. An update that
80
+ * returns a promise is handed to the platform as a pending callback, and `await requestAnimationFrame()`
81
+ * inside it deadlocks the transition permanently — measured: no `ready`, no `finished`, and the mutation never
82
+ * happens, because the transition waits for the promise and the promise waits for a rendering update the
83
+ * transition is holding. So a returned thenable is never handed over: it throws, which abandons the transition
84
+ * at once and comes back to the caller as its own error rather than as an outcome, because an async callback
85
+ * passed to a synchronous API is a mistake and not a platform situation.
86
+ */
87
+ /** Why a transition did not run. A reason is an occasion, never a mistake — mistakes reject. */
88
+ type ViewTransitionReason = 'aborted' | 'hidden' | 'in-flight' | 'unsupported';
89
+ /** A promise-returning update is not this API's shape, and saying so in the type is half of enforcing it. */
90
+ type Synchronous<T> = T extends PromiseLike<unknown> ? never : T;
91
+ /**
92
+ * Configure a shared policy interface, not an independent transition domain. All controllers in this
93
+ * module instance coordinate the document's active transition. `run` executes a one-off update; `wrap`
94
+ * attaches lifecycle observation to a reusable operation.
95
+ *
96
+ * const transition = createViewTransition({ concurrency: 'auto' })
97
+ * const open = transition.wrap(updateOpen, {
98
+ * onTransitionStart() {},
99
+ * onTransitionEnd() {},
100
+ * onDecline(reason) {},
101
+ * onError(error) {},
102
+ * })
103
+ * await open(true)
104
+ *
105
+ * Arguments and the call receiver are forwarded. The original return value is replaced by an outcome
106
+ * promise. Each invocation has its own browser transition and promise, even when wrappers are shared.
107
+ * Updates must commit DOM changes synchronously; framework setters may require an explicit flush.
108
+ * Hooks observe the operation, not a publicly identified invocation. A started transition ending does not
109
+ * promise it reached its visual endpoint. An error hook observes rejection without changing the result.
110
+ */
111
+ declare const createViewTransition: (options?: ViewTransitionControllerOptions) => {
112
+ /** Run a one-off synchronous DOM update, optionally overriding this controller's policy. */
113
+ run<Result>(update: () => Result & Synchronous<Result>, overrides?: ViewTransitionOptions): Promise<ViewTransitionOutcome>;
114
+ wrap<Args extends unknown[], Result, Receiver>(update: (this: Receiver, ...args: Args) => Result & Synchronous<Result>, hooks?: ViewTransitionHooks): (this: Receiver, ...args: Args) => Promise<ViewTransitionOutcome>;
115
+ };
116
+
117
+ export { type ViewTransitionConcurrency, type ViewTransitionControllerOptions, type ViewTransitionHooks, type ViewTransitionOptions, type ViewTransitionOutcome, type ViewTransitionReason, createViewTransition };
@@ -0,0 +1,117 @@
1
+ "use client"
2
+
3
+ // src/view-transition.ts
4
+ var AsyncUpdateError = class extends TypeError {
5
+ constructor() {
6
+ super(
7
+ "View transition update requires a synchronous update: do not await, schedule a frame, or return a promise from the update callback. A promise is handed to the browser as a pending callback, and awaiting a rendering frame inside it deadlocks the transition permanently."
8
+ );
9
+ this.name = "AsyncUpdateError";
10
+ }
11
+ };
12
+ var isThenable = (value) => (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
13
+ var current = null;
14
+ var calledThisInteraction = false;
15
+ var interactionEnded = true;
16
+ var interactionEnd = null;
17
+ var endInteraction = () => {
18
+ interactionEnded = true;
19
+ calledThisInteraction = false;
20
+ };
21
+ var repeatsCurrentInteraction = () => {
22
+ const repeats = calledThisInteraction;
23
+ calledThisInteraction = true;
24
+ if (interactionEnded) {
25
+ interactionEnded = false;
26
+ if (typeof MessageChannel === "function") {
27
+ interactionEnd ??= new MessageChannel();
28
+ interactionEnd.port1.onmessage = endInteraction;
29
+ interactionEnd.port2.postMessage(0);
30
+ } else setTimeout(endInteraction, 0);
31
+ }
32
+ return repeats;
33
+ };
34
+ var engine = async (update, options, hooks) => {
35
+ const mutate = () => {
36
+ const result = update();
37
+ if (isThenable(result)) {
38
+ void Promise.resolve(result).catch(() => {
39
+ });
40
+ throw new AsyncUpdateError();
41
+ }
42
+ };
43
+ if (typeof document === "undefined" || typeof document.startViewTransition !== "function") {
44
+ mutate();
45
+ return declined(hooks, "unsupported");
46
+ }
47
+ if (document.visibilityState === "hidden") {
48
+ mutate();
49
+ return declined(hooks, "hidden");
50
+ }
51
+ const repeats = repeatsCurrentInteraction();
52
+ const concurrency = options?.concurrency ?? "auto";
53
+ if (current && (concurrency === "coalesce" || concurrency === "auto" && repeats)) {
54
+ mutate();
55
+ return declined(hooks, "in-flight");
56
+ }
57
+ const transition = document.startViewTransition(mutate);
58
+ current = transition;
59
+ const readiness = transition.ready.then(
60
+ () => {
61
+ report(hooks.onTransitionStart);
62
+ return true;
63
+ },
64
+ () => false
65
+ );
66
+ void transition.updateCallbackDone.catch(() => {
67
+ });
68
+ return transition.finished.then(
69
+ async () => {
70
+ if (await readiness) {
71
+ report(hooks.onTransitionEnd);
72
+ return { transitioned: true };
73
+ }
74
+ return declined(hooks, "aborted");
75
+ },
76
+ (error) => {
77
+ throw error;
78
+ }
79
+ ).finally(() => {
80
+ if (current === transition) current = null;
81
+ });
82
+ };
83
+ var declined = (hooks, reason) => {
84
+ report(hooks.onDecline, reason);
85
+ return Promise.resolve({ reason, transitioned: false });
86
+ };
87
+ var report = (hook, ...args) => {
88
+ if (!hook) return;
89
+ try {
90
+ hook(...args);
91
+ } catch (error) {
92
+ if (typeof reportError === "function") reportError(error);
93
+ else console.error(error);
94
+ }
95
+ };
96
+ var createViewTransition = (options = {}) => ({
97
+ /** Run a one-off synchronous DOM update, optionally overriding this controller's policy. */
98
+ run(update, overrides) {
99
+ return engine(
100
+ update,
101
+ { concurrency: overrides?.concurrency ?? options.concurrency ?? "auto" },
102
+ {}
103
+ );
104
+ },
105
+ wrap(update, hooks = {}) {
106
+ return function(...args) {
107
+ const running = engine(() => update.apply(this, args), options, hooks);
108
+ if (hooks.onError)
109
+ void running.catch((error) => report(hooks.onError, error));
110
+ return running;
111
+ };
112
+ }
113
+ });
114
+ export {
115
+ createViewTransition
116
+ };
117
+ //# sourceMappingURL=view-transition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/view-transition.ts"],"mappings":";;;AAkGA,IAAM,mBAAN,cAA+B,UAAU;AAAA,EACvC,cAAc;AACZ;AAAA,MACE;AAAA,IAGF;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,aAAa,CAAC,WACjB,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,UAAU,QACV,OAAQ,MAA+B,SAAS;AAGlD,IAAI,UAAiC;AAoBrC,IAAI,wBAAwB;AAC5B,IAAI,mBAAmB;AACvB,IAAI,iBAAwC;AAE5C,IAAM,iBAAiB,MAAM;AAC3B,qBA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