@cloudlet/toast 1.0.0-rc.3 → 1.0.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +42 -7
  2. package/README.md +5 -4
  3. package/dist/contracts/events.d.ts +1 -1
  4. package/dist/contracts/events.d.ts.map +1 -1
  5. package/dist/core/bridge.d.ts +5 -0
  6. package/dist/core/bridge.d.ts.map +1 -0
  7. package/dist/core/bridge.js +277 -0
  8. package/dist/core/bridge.js.map +1 -0
  9. package/dist/core/controller.d.ts +113 -3
  10. package/dist/core/controller.d.ts.map +1 -1
  11. package/dist/core/controller.js +416 -583
  12. package/dist/core/controller.js.map +1 -1
  13. package/dist/react/announcer.d.ts.map +1 -1
  14. package/dist/react/announcer.js +29 -23
  15. package/dist/react/announcer.js.map +1 -1
  16. package/dist/react/bindings.d.ts +9 -0
  17. package/dist/react/bindings.d.ts.map +1 -1
  18. package/dist/react/bindings.js +32 -69
  19. package/dist/react/bindings.js.map +1 -1
  20. package/dist/react/card.d.ts +1 -1
  21. package/dist/react/card.js.map +1 -1
  22. package/dist/react/generators.d.ts +2 -2
  23. package/dist/react/generators.js.map +1 -1
  24. package/dist/react/gestures.js.map +1 -1
  25. package/dist/react/host.d.ts.map +1 -1
  26. package/dist/react/host.js +1 -1
  27. package/dist/react/host.js.map +1 -1
  28. package/dist/react/motion.d.ts +3 -3
  29. package/dist/react/motion.js.map +1 -1
  30. package/dist/react/plan.d.ts +1 -1
  31. package/dist/react/plan.d.ts.map +1 -1
  32. package/dist/react/plan.js.map +1 -1
  33. package/dist/react/renderer.d.ts +7 -0
  34. package/dist/react/renderer.d.ts.map +1 -0
  35. package/dist/react/renderer.js +62 -0
  36. package/dist/react/renderer.js.map +1 -0
  37. package/dist/react.d.ts +4 -4
  38. package/dist/react.d.ts.map +1 -1
  39. package/package.json +4 -2
  40. package/src/contracts/events.ts +2 -1
  41. package/src/core/bridge.ts +280 -0
  42. package/src/core/controller.ts +83 -268
  43. package/src/react/announcer.ts +9 -0
  44. package/src/react/bindings.tsx +28 -72
  45. package/src/react/card.tsx +3 -3
  46. package/src/react/generators.ts +2 -2
  47. package/src/react/gestures.ts +1 -1
  48. package/src/react/host.tsx +10 -4
  49. package/src/react/motion.ts +4 -4
  50. package/src/react/plan.ts +2 -2
  51. package/src/react/renderer.tsx +77 -0
  52. package/src/react.ts +4 -4
@@ -1,8 +1,17 @@
1
1
  import type { ReactElement } from 'react';
2
2
  import type { CloudletProviderProps, ReactCloudletController, ToasterProps } from '../react.js';
3
+ type Renderer = typeof import('./renderer.js');
3
4
  export declare function CloudletProvider({ controller, children }: CloudletProviderProps): ReactElement;
4
5
  export declare function useCloudlet(): ReactCloudletController;
5
6
  /** The controller, or null outside a provider and while the provider's controller is null. */
6
7
  export declare function useOptionalCloudlet(): ReactCloudletController | null;
8
+ /** Fetches the renderer chunk once for every Toaster; after a failure the next attempt fetches again. */
9
+ export declare function loadRenderer(): Promise<Renderer>;
10
+ /**
11
+ * The renderer stays out of the start bundle: the chunk loads after mount, and
12
+ * notifications shown meanwhile wait in the controller. On the server and during
13
+ * hydration this renders nothing, exactly like the attached renderer does.
14
+ */
7
15
  export declare function Toaster(options: ToasterProps): ReactElement | null;
16
+ export {};
8
17
  //# sourceMappingURL=bindings.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.d.ts","sourceRoot":"","sources":["../../src/react/bindings.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAI1C,OAAO,KAAK,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAShG,wBAAgB,gBAAgB,CAAC,EAAE,UAAU,EAAE,QAAQ,EAAE,EAAE,qBAAqB,GAAG,YAAY,CAE9F;AAED,wBAAgB,WAAW,IAAI,uBAAuB,CAIrD;AAED,8FAA8F;AAC9F,wBAAgB,mBAAmB,IAAI,uBAAuB,GAAG,IAAI,CAEpE;AASD,wBAAgB,OAAO,CAAC,OAAO,EAAE,YAAY,GAAG,YAAY,GAAG,IAAI,CAKlE"}
1
+ {"version":3,"file":"bindings.d.ts","sourceRoot":"","sources":["../../src/react/bindings.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAE1C,OAAO,KAAK,EAAE,qBAAqB,EAAE,uBAAuB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhG,KAAK,QAAQ,GAAG,cAAc,eAAe,CAAC,CAAC;AAO/C,wBAAgB,gBAAgB,CAAC,EAAE,UAAU,EAAE,QAAQ,EAAE,EAAE,qBAAqB,GAAG,YAAY,CAE9F;AAED,wBAAgB,WAAW,IAAI,uBAAuB,CAIrD;AAED,8FAA8F;AAC9F,wBAAgB,mBAAmB,IAAI,uBAAuB,GAAG,IAAI,CAEpE;AAED,yGAAyG;AACzG,wBAAgB,YAAY,IAAI,OAAO,CAAC,QAAQ,CAAC,CAMhD;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,OAAO,EAAE,YAAY,GAAG,YAAY,GAAG,IAAI,CAclE"}
@@ -1,84 +1,47 @@
1
- import { getRendererBridge as e } from "../core/controller.js";
2
- import { Host as t } from "./host.js";
3
- import { createContext as n, useContext as r, useEffect as i, useRef as a, useState as o, useSyncExternalStore as s } from "react";
4
- import { createPortal as c } from "react-dom";
5
- import { Fragment as l, jsx as u, jsxs as d } from "react/jsx-runtime";
1
+ import { getControllerKernel as e } from "../core/controller.js";
2
+ import { createContext as t, useContext as n, useEffect as r, useState as i } from "react";
3
+ import { jsx as a } from "react/jsx-runtime";
6
4
  //#region src/react/bindings.tsx
7
- var f = n(void 0), p = () => () => {}, m = () => !0, h = () => !1;
8
- function g({ controller: e, children: t }) {
9
- return /* @__PURE__ */ u(f.Provider, {
5
+ var o = t(void 0), s, c;
6
+ function l({ controller: e, children: t }) {
7
+ return /* @__PURE__ */ a(o.Provider, {
10
8
  value: e,
11
9
  children: t
12
10
  });
13
11
  }
14
- function _() {
15
- let e = r(f);
12
+ function u() {
13
+ let e = n(o);
16
14
  if (!e) throw Error("useCloudlet must be used within a CloudletProvider that has a controller");
17
15
  return e;
18
16
  }
19
- function v() {
20
- return r(f) ?? null;
17
+ function d() {
18
+ return n(o) ?? null;
21
19
  }
22
- function y(e) {
23
- let t = r(f);
24
- if (t === void 0) throw Error("Toaster must be used within a CloudletProvider");
25
- return t ? /* @__PURE__ */ u(b, {
26
- controller: t,
27
- options: e
28
- }) : null;
20
+ function f() {
21
+ return c ??= import("./renderer.js").then((e) => s = e, (e) => {
22
+ throw c = void 0, e;
23
+ }), c;
29
24
  }
30
- function b({ controller: n, options: r }) {
31
- let f = s(p, m, h), g = e(n), _ = s(g.subscribe, g.getSnapshot, g.getServerSnapshot), v = a(null), [y, b] = o(null);
32
- i(() => {
33
- if (!f || !v.current) return;
34
- let e = v.current.ownerDocument, t;
35
- try {
36
- let n = (typeof r.container == "function" ? r.container() : r.container) ?? e.body;
37
- if (!n || n.nodeType !== 1 || n.ownerDocument !== e || n.namespaceURI !== "http://www.w3.org/1999/xhtml" || !n.isConnected || n.getRootNode().nodeType === 11) {
38
- g.reportInvalidContainer("Toaster container must be a connected HTML Element in the mounting document, outside Shadow DOM");
39
- return;
40
- }
41
- t = n;
42
- } catch (e) {
43
- g.reportInvalidContainer("Toaster container resolver failed", e);
44
- return;
45
- }
46
- let i = r.attention?.delay, a = g.attach(i === void 0 ? void 0 : { attentionDelay: i }), o = a.status === "rejected" && a.reason === "invalid-input";
47
- if (o && (a = g.attach()), a.status !== "attached") return;
48
- o && g.reportDiagnostic(a.lease, {
49
- code: "invalid-input",
50
- source: "Toaster.attention",
51
- message: "attention.delay must be a finite nonnegative number of milliseconds"
52
- });
53
- let s = {
54
- controller: n,
55
- lease: a.lease,
56
- container: t,
57
- document: e
58
- };
59
- return x(s.lease, !1), b(s), () => {
60
- g.detach(s.lease);
25
+ function p(t) {
26
+ let c = n(o);
27
+ if (c === void 0) throw Error("Toaster must be used within a CloudletProvider");
28
+ let [l, u] = i(s);
29
+ return r(() => {
30
+ if (l) return;
31
+ let t = !0;
32
+ return f().then((e) => {
33
+ t && u(e);
34
+ }, (n) => {
35
+ t && c && e(c).reportRendererLoadError(n);
36
+ }), () => {
37
+ t = !1;
61
38
  };
62
- }, [n, f]);
63
- function x(e, t) {
64
- let n = r.autoDismiss, i = n === void 0 || typeof n == "boolean";
65
- g.setAutoDismiss(e, i ? n : void 0), !i && t && g.reportDiagnostic(e, {
66
- code: "invalid-input",
67
- source: "Toaster.autoDismiss",
68
- message: "autoDismiss must be a boolean"
69
- });
70
- }
71
- return i(() => {
72
- y && x(y.lease, !0);
73
- }, [y, r.autoDismiss]), f ? /* @__PURE__ */ d(l, { children: [/* @__PURE__ */ u("template", { ref: v }), y?.controller === n && !_.disposed ? c(/* @__PURE__ */ u(t, {
74
- bridge: g,
75
- lease: y.lease,
76
- snapshot: _,
77
- options: r,
78
- document: y.document
79
- }, y.lease), y.container) : null] }) : null;
39
+ }, [l, c]), c && l ? /* @__PURE__ */ a(l.AttachedToaster, {
40
+ controller: c,
41
+ options: t
42
+ }) : null;
80
43
  }
81
44
  //#endregion
82
- export { g as CloudletProvider, y as Toaster, _ as useCloudlet, v as useOptionalCloudlet };
45
+ export { l as CloudletProvider, p as Toaster, f as loadRenderer, u as useCloudlet, d as useOptionalCloudlet };
83
46
 
84
47
  //# sourceMappingURL=bindings.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.js","names":["_Fragment","CloudletContext","createContext","subscribeMount","clientMounted","serverMounted","CloudletProvider","controller","useCloudlet","useContext","useOptionalCloudlet","Toaster","AttachedToaster","mounted","useSyncExternalStore","bridge","getRendererBridge","snapshot","marker","useRef","attachment","setAttachment","useState","ownerDocument","container","candidate","options","error","delay","attached","invalidDelay","current","applyAutoDismiss","value","valid","lease","report","useEffect","Fragment","createPortal","Host"],"sources":["../../src/react/bindings.tsx"],"sourcesContent":["import { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport type { ReactElement } from 'react';\nimport { createPortal } from 'react-dom';\nimport { getRendererBridge } from '../core/controller.js';\nimport type { HostLease } from '../contracts/internal.js';\nimport type { CloudletProviderProps, ReactCloudletController, ToasterProps } from '../react.js';\nimport { Host } from './host.js';\n\n/** Undefined outside a provider; null inside one whose controller does not exist yet. */\nconst CloudletContext = createContext<ReactCloudletController | null | undefined>(undefined);\nconst subscribeMount = () => () => {};\nconst clientMounted = () => true;\nconst serverMounted = () => false;\n\nexport function CloudletProvider({ controller, children }: CloudletProviderProps): ReactElement {\n return <CloudletContext.Provider value={controller}>{children}</CloudletContext.Provider>;\n}\n\nexport function useCloudlet(): ReactCloudletController {\n const controller = useContext(CloudletContext);\n if (!controller) throw new Error('useCloudlet must be used within a CloudletProvider that has a controller');\n return controller;\n}\n\n/** The controller, or null outside a provider and while the provider's controller is null. */\nexport function useOptionalCloudlet(): ReactCloudletController | null {\n return useContext(CloudletContext) ?? null;\n}\n\ninterface Attachment {\n readonly controller: ReactCloudletController;\n readonly lease: HostLease;\n readonly container: Element;\n readonly document: Document;\n}\n\nexport function Toaster(options: ToasterProps): ReactElement | null {\n const controller = useContext(CloudletContext);\n if (controller === undefined) throw new Error('Toaster must be used within a CloudletProvider');\n // A provider without a controller yet (server, first client render) renders nothing.\n return controller ? <AttachedToaster controller={controller} options={options} /> : null;\n}\n\nfunction AttachedToaster({ controller, options }: { controller: ReactCloudletController; options: ToasterProps }): ReactElement | null {\n // React supplies the server value during hydration, then the client value.\n // The inert marker can therefore identify the owner document without a store\n // or effect whose only purpose is an extra mounting render.\n const mounted = useSyncExternalStore(subscribeMount, clientMounted, serverMounted);\n const bridge = getRendererBridge(controller);\n const snapshot = useSyncExternalStore(bridge.subscribe, bridge.getSnapshot, bridge.getServerSnapshot);\n const marker = useRef<HTMLTemplateElement>(null);\n const [attachment, setAttachment] = useState<Attachment | null>(null);\n useEffect(() => {\n if (!mounted || !marker.current) return;\n const ownerDocument = marker.current.ownerDocument;\n let container: Element;\n try {\n const requested = typeof options.container === 'function' ? options.container() : options.container;\n const candidate = requested ?? ownerDocument.body;\n // nodeType/ownerDocument also work when the mounting React root is in another realm.\n if (!candidate || candidate.nodeType !== 1 || candidate.ownerDocument !== ownerDocument\n || candidate.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !candidate.isConnected\n || candidate.getRootNode().nodeType === 11) {\n bridge.reportInvalidContainer('Toaster container must be a connected HTML Element in the mounting document, outside Shadow DOM');\n return;\n }\n container = candidate;\n } catch (error) {\n bridge.reportInvalidContainer('Toaster container resolver failed', error);\n return;\n }\n const delay = options.attention?.delay;\n let attached = bridge.attach(delay === undefined ? undefined : { attentionDelay: delay });\n // An invalid delay must not suppress the host: fall back to the controller default and report it.\n const invalidDelay = attached.status === 'rejected' && attached.reason === 'invalid-input';\n if (invalidDelay) attached = bridge.attach();\n if (attached.status !== 'attached') return;\n if (invalidDelay) bridge.reportDiagnostic(attached.lease, { code: 'invalid-input', source: 'Toaster.attention',\n message: 'attention.delay must be a finite nonnegative number of milliseconds' });\n const current = { controller, lease: attached.lease, container, document: ownerDocument };\n applyAutoDismiss(current.lease, false);\n setAttachment(current);\n return () => { bridge.detach(current.lease); };\n // Container and attention delay are fixed for this attachment; changing them requires remount.\n }, [controller, mounted]);\n // Applied before the first presentation, then whenever the prop changes (which reports an invalid value once).\n function applyAutoDismiss(lease: HostLease, report: boolean) {\n const value = options.autoDismiss;\n const valid = value === undefined || typeof value === 'boolean';\n bridge.setAutoDismiss(lease, valid ? value : undefined);\n if (!valid && report) bridge.reportDiagnostic(lease, { code: 'invalid-input', source: 'Toaster.autoDismiss',\n message: 'autoDismiss must be a boolean' });\n }\n useEffect(() => { if (attachment) applyAutoDismiss(attachment.lease, true); }, [attachment, options.autoDismiss]);\n\n if (!mounted) return null;\n return <><template ref={marker} />{attachment?.controller === controller && !snapshot.disposed\n ? createPortal(<Host key={attachment.lease} bridge={bridge} lease={attachment.lease} snapshot={snapshot}\n options={options} document={attachment.document} />, attachment.container) : null}</>;\n}\n"],"mappings":";;;;;;AASA,IAAMC,IAAkBC,EAA0D,KAAA,CAAS,GACrFC,gBAA6B,CAAC,GAC9BC,UAAsB,IACtBC,UAAsB;AAE5B,SAAgBC,EAAiB,EAAE,eAAY,eAAiD;CAC9F,OAAO,kBAACL,EAAgB,UAAjB;EAA0B,OAAOM;EAAa;CAAmC,CAAA;AAC1F;AAEA,SAAgBC,IAAuC;CACrD,IAAMD,IAAaE,EAAWR,CAAe;CAC7C,IAAI,CAACM,GAAY,MAAU,MAAM,0EAA0E;CAC3G,OAAOA;AACT;AAGA,SAAgBG,IAAsD;CACpE,OAAOD,EAAWR,CAAe,KAAK;AACxC;AASA,SAAgBU,EAAQ,GAA4C;CAClE,IAAMJ,IAAaE,EAAWR,CAAe;CAC7C,IAAIM,MAAe,KAAA,GAAW,MAAU,MAAM,gDAAgD;CAE9F,OAAOA,IAAa,kBAACK,GAAD;EAA6B;EAAqB;CAAU,CAAA,IAAI;AACtF;AAEA,SAASA,EAAgB,EAAE,eAAY,cAAgG;CAIrI,IAAMC,IAAUC,EAAqBX,GAAgBC,GAAeC,CAAa,GAC3EU,IAASC,EAAkBT,CAAU,GACrCU,IAAWH,EAAqBC,EAAO,WAAWA,EAAO,aAAaA,EAAO,iBAAiB,GAC9FG,IAASC,EAA4B,IAAI,GACzC,CAACC,GAAYC,KAAiBC,EAA4B,IAAI;CACpE,QAAgB;EACd,IAAI,CAACT,KAAW,CAACK,EAAO,SAAS;EACjC,IAAMK,IAAgBL,EAAO,QAAQ,eACjCM;EACJ,IAAI;GAEF,IAAMC,KADY,OAAOC,EAAQ,aAAc,aAAaA,EAAQ,UAAU,IAAIA,EAAQ,cAC3DH,EAAc;GAE7C,IAAI,CAACE,KAAaA,EAAU,aAAa,KAAKA,EAAU,kBAAkBF,KACrEE,EAAU,iBAAiB,kCAAkC,CAACA,EAAU,eACxEA,EAAU,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GAAD;EAAqC;EAAQ,OAAOpB,EAAW;EAAiB;EACpF;EAAS,UAAUA,EAAW;CAAW,GAD1BA,EAAW,KACe,GAAGA,EAAW,SAAS,IAAI,IAAO,EAAA,CAAA,IAHnE;AAIvB"}
1
+ {"version":3,"file":"bindings.js","names":["CloudletContext","createContext","renderer","loading","CloudletProvider","controller","useCloudlet","useContext","useOptionalCloudlet","loadRenderer","module","error","Toaster","loaded","setLoaded","useState","useEffect","live","getControllerKernel"],"sources":["../../src/react/bindings.tsx"],"sourcesContent":["import { createContext, useContext, useEffect, useState } from 'react';\nimport type { ReactElement } from 'react';\nimport { getControllerKernel } from '../core/controller.js';\nimport type { CloudletProviderProps, ReactCloudletController, ToasterProps } from '../react.js';\n\ntype Renderer = typeof import('./renderer.js');\n\n/** Undefined outside a provider; null inside one whose controller does not exist yet. */\nconst CloudletContext = createContext<ReactCloudletController | null | undefined>(undefined);\nlet renderer: Renderer | undefined;\nlet loading: Promise<Renderer> | undefined;\n\nexport function CloudletProvider({ controller, children }: CloudletProviderProps): ReactElement {\n return <CloudletContext.Provider value={controller}>{children}</CloudletContext.Provider>;\n}\n\nexport function useCloudlet(): ReactCloudletController {\n const controller = useContext(CloudletContext);\n if (!controller) throw new Error('useCloudlet must be used within a CloudletProvider that has a controller');\n return controller;\n}\n\n/** The controller, or null outside a provider and while the provider's controller is null. */\nexport function useOptionalCloudlet(): ReactCloudletController | null {\n return useContext(CloudletContext) ?? null;\n}\n\n/** Fetches the renderer chunk once for every Toaster; after a failure the next attempt fetches again. */\nexport function loadRenderer(): Promise<Renderer> {\n loading ??= import('./renderer.js').then((module) => (renderer = module), (error: unknown) => {\n loading = undefined;\n throw error;\n });\n return loading;\n}\n\n/**\n * The renderer stays out of the start bundle: the chunk loads after mount, and\n * notifications shown meanwhile wait in the controller. On the server and during\n * hydration this renders nothing, exactly like the attached renderer does.\n */\nexport function Toaster(options: ToasterProps): ReactElement | null {\n const controller = useContext(CloudletContext);\n if (controller === undefined) throw new Error('Toaster must be used within a CloudletProvider');\n const [loaded, setLoaded] = useState(renderer);\n useEffect(() => {\n if (loaded) return;\n let live = true;\n loadRenderer().then((module) => { if (live) setLoaded(module); }, (error: unknown) => {\n if (live && controller) getControllerKernel(controller).reportRendererLoadError(error);\n });\n return () => { live = false; };\n }, [loaded, controller]);\n // A provider without a controller yet (server, first client render) renders nothing.\n return controller && loaded ? <loaded.AttachedToaster controller={controller} options={options} /> : null;\n}\n"],"mappings":";;;;AAQA,IAAMA,IAAkBC,EAA0D,KAAA,CAAS,GACvFC,GACAC;AAEJ,SAAgBC,EAAiB,EAAE,eAAY,eAAiD;CAC9F,OAAO,kBAACJ,EAAgB,UAAjB;EAA0B,OAAOK;EAAa;CAAmC,CAAA;AAC1F;AAEA,SAAgBC,IAAuC;CACrD,IAAMD,IAAaE,EAAWP,CAAe;CAC7C,IAAI,CAACK,GAAY,MAAU,MAAM,0EAA0E;CAC3G,OAAOA;AACT;AAGA,SAAgBG,IAAsD;CACpE,OAAOD,EAAWP,CAAe,KAAK;AACxC;AAGA,SAAgBS,IAAkC;CAKhD,OAJA,MAAY,OAAO,gBAAgB,CAAC,MAAM,MAAY,IAAWC,IAAU,MAAmB;EAE5F,MADA,IAAU,KAAA,GACJC;CACR,CAAC,GACMR;AACT;AAOA,SAAgBS,EAAQ,GAA4C;CAClE,IAAMP,IAAaE,EAAWP,CAAe;CAC7C,IAAIK,MAAe,KAAA,GAAW,MAAU,MAAM,gDAAgD;CAC9F,IAAM,CAACQ,GAAQC,KAAaC,EAASb,CAAQ;CAU7C,OATAc,QAAgB;EACd,IAAIH,GAAQ;EACZ,IAAII,IAAO;EAIX,OAHAR,EAAa,CAAC,CAAC,MAAM,MAAW;GAAE,AAAIQ,KAAMH,EAAUJ,CAAM;EAAG,IAAI,MAAmB;GACpF,AAAIO,KAAQZ,KAAYa,EAAoBb,CAAU,CAAC,CAAC,wBAAwBM,CAAK;EACvF,CAAC,SACY;GAAE,IAAO;EAAO;CAC/B,GAAG,CAACE,GAAQR,CAAU,CAAC,GAEhBA,KAAcQ,IAAS,kBAACA,EAAO,iBAAR;EAAoC;EAAqB;CAAU,CAAA,IAAI;AACvG"}
@@ -35,7 +35,7 @@ export declare function Heading({ notification, slot, part, titleId }: {
35
35
  /** Rich content of the inert neighbour preview: rendered as is, never checked or reported twice. */
36
36
  export declare const previewSlot: (value: ReactNode) => import("react").JSX.Element;
37
37
  /**
38
- * The neighbour shown only while a finger drags the Island content (DESIGN §3, §9):
38
+ * The neighbour shown only while a finger drags the Island content:
39
39
  * the same layout as a live slide, but every control is a lookalike without
40
40
  * handlers, ids, links or tab stops. The caller puts it in an `inert` container.
41
41
  */
@@ -1 +1 @@
1
- {"version":3,"file":"card.js","names":["defaultLabels","title","count","missed","index","total","SlotBoundary","Component","props","state","Suspense","CheckedSlot","ref","useRef","invalidContent","setInvalidContent","useState","invalid","content","useEffect","element","reported","check","bridge","lease","Observer","observer","handle","rejectFocus","event","control","name","glyph","path","partClasses","extra","classNames","part","own","glyphs","StatusIcon","notification","determinate","progress","kind","preview","slot","slotRenderer","value","rejectSlotFocus","Heading","titleId","previewSlot","retryable","operation","SlidePreview","action","lookalike","primary","labels","Body","neutral","id","useId","command","activateLink","navigate","closeButton","onClick"],"sources":["../../src/react/card.tsx"],"sourcesContent":["import { Component, Suspense, useEffect, useId, useRef, useState } from 'react';\nimport type { ComponentPropsWithRef, ReactNode } from 'react';\nimport type { HostLease, RendererBridge } from '../contracts/internal.js';\nimport type { NotificationHandle } from '../contracts/identity.js';\nimport type { NotificationKind } from '../contracts/notifications.js';\nimport type { NotificationSnapshot } from '../contracts/snapshots.js';\nimport type { CloudletLabels, CloudletPart, ToasterProps } from '../react.js';\n\nexport const defaultLabels: CloudletLabels = {\n region: 'Notifications', island: 'Current notifications', carousel: 'carousel', slide: 'slide',\n close: 'Close notification', retry: 'Retry',\n cancel: 'Request cancellation', cancellationRequested: 'Cancellation requested',\n acknowledgeOverflow: 'Acknowledge missed notifications', collapse: 'Press Escape to collapse',\n stackSummary: (title, count, missed) => [title, ...(count > 1 ? [`${count} notifications`] : []),\n ...(missed > 0 ? [`${missed} missed`] : [])].join(', '),\n page: (index, total) => `${index} of ${total}`,\n overflowCount: count => `${count} missed notifications`,\n};\n\ninterface SlotProps {\n readonly content: ReactNode;\n readonly bridge: RendererBridge<ReactNode>;\n readonly lease: HostLease;\n readonly handle: NotificationHandle;\n readonly rejectFocus: (previous: EventTarget | null) => void;\n}\n\nclass SlotBoundary extends Component<SlotProps, { failed: boolean; content: ReactNode }> {\n override state = { failed: false, content: this.props.content };\n static getDerivedStateFromError() { return { failed: true }; }\n static getDerivedStateFromProps(props: SlotProps, state: { content: ReactNode }) {\n return props.content === state.content ? null : { failed: false, content: props.content };\n }\n override componentDidCatch(error: unknown) {\n this.props.bridge.reportDiagnostic(this.props.lease, { code: 'slot-error', source: 'Toaster.slot',\n message: 'A rich slot could not be rendered', handle: this.props.handle, error });\n }\n override render() {\n return this.state.failed ? this.props.bridge.renderError\n : <Suspense fallback={this.props.bridge.renderError}><CheckedSlot {...this.props} /></Suspense>;\n }\n}\n\nfunction CheckedSlot({ content, bridge, lease, handle, rejectFocus }: SlotProps) {\n const ref = useRef<HTMLDivElement>(null);\n const [invalidContent, setInvalidContent] = useState<{ content: ReactNode } | null>(null);\n const invalid = invalidContent?.content === content;\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n let reported = false;\n const check = () => {\n if (reported || !element.querySelector('a[href],button,input,select,textarea,summary,iframe,[tabindex],[contenteditable]:not([contenteditable=\"false\"]),audio[controls],video[controls]')) return;\n reported = true;\n setInvalidContent({ content });\n bridge.reportDiagnostic(lease, { code: 'slot-error', source: 'Toaster.slot',\n message: 'Rich slots must be non-interactive; use the notification action', handle });\n };\n check();\n const Observer = element.ownerDocument.defaultView?.MutationObserver;\n const observer = Observer ? new Observer(check) : null;\n observer?.observe(element, { childList: true, subtree: true, attributes: true });\n return () => observer?.disconnect();\n }, [content, bridge, lease, handle]);\n return <div ref={ref} className=\"cloudlet-slot\" onFocusCapture={event => rejectFocus(event.relatedTarget)}>\n {invalid ? bridge.renderError : content}\n </div>;\n}\n\nfunction control(name: string, children: ReactNode, onClick: () => void, props?: ComponentPropsWithRef<'button'>) {\n return <button type=\"button\" data-cloudlet-control={name} {...props} onClick={onClick}>{children}</button>;\n}\n\nfunction glyph(path: string) {\n return <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\"><path d={path} /></svg>;\n}\n\n/** Adds the application's `classNames` part to an own `cloudlet-*` class, never replacing it. */\nexport type PartClass = (part: CloudletPart, own: string) => string;\nexport function partClasses(classNames: ToasterProps['classNames']): PartClass {\n return (part, own) => {\n const extra = classNames?.[part];\n return typeof extra === 'string' && extra.trim() ? `${own} ${extra.trim()}` : own;\n };\n}\n\n/** 16 px stroke glyphs drawn in the status colour (DESIGN §8). */\nconst glyphs: Record<Exclude<NotificationKind, 'loading'>, string> = {\n success: 'M4.5 8.5 7 11l4.5-5.5',\n error: 'm5.5 5.5 5 5m0-5-5 5',\n info: 'M8 7.5V11M8 5h.01',\n warning: 'M8 4.75V8.5M8 11.25h.01',\n};\n\n/**\n * The status icon: a 24 px tinted circle with a glyph, the loading spinner or the\n * notification's own icon, and the 2 px progress ring around it (pill and Island\n * share these nodes). With progress the icon is the accessible progressbar. The\n * determinate arc is owned by the host sampler (one RAF per host, 240 ms tween);\n * `preview` draws the value statically for the inert swipe neighbour.\n */\nexport function StatusIcon({ notification, slot, part, preview = false }: {\n notification: NotificationSnapshot<ReactNode>; slot: (value: ReactNode) => ReactNode; part: PartClass; preview?: boolean;\n}) {\n const { content, kind } = notification;\n const { progress } = content;\n const determinate = progress?.kind === 'determinate';\n return <div className={part('icon', 'cloudlet-icon')} data-kind={kind}\n {...(progress && !preview ? { role: 'progressbar', 'aria-valuemin': 0, 'aria-valuemax': 100,\n 'aria-valuenow': determinate ? Math.round(progress.value * 100) : undefined, 'aria-label': progress.label ?? content.title }\n : { 'aria-hidden': 'true' })}>\n {content.icon !== undefined\n ? <span className=\"cloudlet-glyph\" aria-hidden=\"true\">{slot(content.icon)}</span>\n // With progress the ring is the activity indicator of a loading record.\n : kind === 'loading' ? !progress && <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" className=\"cloudlet-glyph cloudlet-spinner\">\n <circle cx=\"8\" cy=\"8\" r=\"5.5\" strokeDasharray=\"22 13\" /></svg>\n : <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" className=\"cloudlet-glyph\"><path d={glyphs[kind]} /></svg>}\n {progress && <svg aria-hidden=\"true\" viewBox=\"0 0 32 32\" className=\"cloudlet-ring\" data-progress={progress.kind}>\n <circle className=\"cloudlet-ring-track\" cx=\"16\" cy=\"16\" r=\"15\" />\n <circle className=\"cloudlet-progress-fill\" cx=\"16\" cy=\"16\" r=\"15\" pathLength=\"100\" transform=\"rotate(-90 16 16)\"\n strokeDasharray={!determinate ? '25 75' : preview ? `${Math.round(progress.value * 10000) / 100} 100` : '0 100'} />\n </svg>}\n </div>;\n}\n\nexport function slotRenderer(bridge: RendererBridge<ReactNode>, lease: HostLease, handle: NotificationHandle,\n rejectSlotFocus: (previous: EventTarget | null) => void) {\n return (value: ReactNode) => <SlotBoundary content={value} bridge={bridge} lease={lease} handle={handle} rejectFocus={rejectSlotFocus} />;\n}\n\n/**\n * Status icon and title: the same DOM nodes in the pill and in the Island header,\n * so opening never re-creates them and the title can receive focus in place.\n */\nexport function Heading({ notification, slot, part, titleId }: {\n notification: NotificationSnapshot<ReactNode>; slot: (value: ReactNode) => ReactNode; part: PartClass;\n /** Omitted for the inert neighbour preview: no id, focus target, data hook or live progress. */\n titleId?: string;\n}) {\n const title = part('title', 'cloudlet-title');\n return <div className=\"cloudlet-heading\">\n <StatusIcon notification={notification} slot={slot} part={part} preview={titleId === undefined} />\n {titleId === undefined ? <h2 className={title}>{notification.content.title}</h2>\n : <h2 id={titleId} tabIndex={-1} data-cloudlet-title=\"\" className={title}>{notification.content.title}</h2>}\n </div>;\n}\n\n/** Rich content of the inert neighbour preview: rendered as is, never checked or reported twice. */\nexport const previewSlot = (value: ReactNode) => <div className=\"cloudlet-slot\">{value}</div>;\n\n/** A settled factory can always retry through the API; only an unsuccessful attempt offers the button. */\ntype Operation = NotificationSnapshot<ReactNode>['operation'];\nconst retryable = (operation: Operation): operation is NonNullable<Operation> => !!operation?.canRetry && operation.status !== 'fulfilled';\n\n/**\n * The neighbour shown only while a finger drags the Island content (DESIGN §3, §9):\n * the same layout as a live slide, but every control is a lookalike without\n * handlers, ids, links or tab stops. The caller puts it in an `inert` container.\n */\nexport function SlidePreview({ notification, labels, part }: { notification: NotificationSnapshot<ReactNode>; labels: CloudletLabels; part: PartClass }) {\n const { content, operation, kind } = notification;\n const action = part('action', 'cloudlet-action');\n const lookalike = (children: ReactNode, primary = false) =>\n <button type=\"button\" tabIndex={-1} className={primary ? `${action} cloudlet-primary` : action}>{children}</button>;\n // Only the body slides (DESIGN §7, task 17): the preview shows the neighbour's body under the live heading.\n return <div className=\"cloudlet-slide\" data-kind={kind}>\n <div className={part('body', 'cloudlet-body')} data-kind={kind}>\n {content.description && <div className={part('description', 'cloudlet-description')}>\n {content.description.kind === 'text' ? <p>{content.description.text}</p> : previewSlot(content.description.content)}\n </div>}\n <div className={part('actions', 'cloudlet-actions')}>\n {content.action?.kind === 'command' && lookalike(content.action.label, true)}\n {content.action?.kind === 'link' && <a className={`${action} cloudlet-primary`}>{content.action.label}</a>}\n {retryable(operation) && lookalike(labels.retry)}\n {operation?.canCancel && lookalike(operation.cancelRequested ? labels.cancellationRequested : labels.cancel)}\n </div>\n {notification.action.status === 'failed' && <p className=\"cloudlet-action-error\">{notification.action.message}</p>}\n </div>\n </div>;\n}\n\n/** Island slide body: description, progress, actions and the action error. */\nexport function Body({ notification, bridge, lease, labels, navigate, slot, part }: {\n notification: NotificationSnapshot<ReactNode>; bridge: RendererBridge<ReactNode>; lease: HostLease;\n labels: CloudletLabels; navigate: (handle: NotificationHandle) => void; slot: (value: ReactNode) => ReactNode; part: PartClass;\n}) {\n const { handle, content, operation, action, kind } = notification;\n // The primary action is tinted with the status; retry and cancel stay neutral.\n const neutral = part('action', 'cloudlet-action');\n const primary = `${neutral} cloudlet-primary`;\n const id = useId();\n const command = content.action;\n const activateLink = (event: MouseEvent) => {\n // Observe cancellation after portal/application ancestors have handled activation.\n queueMicrotask(() => { if (!event.defaultPrevented) navigate(handle); });\n };\n return <div className={part('body', 'cloudlet-body')} data-kind={kind}>\n {content.description && <div className={part('description', 'cloudlet-description')}>\n {content.description.kind === 'text' && <p>{content.description.text}</p>}\n {content.description.kind === 'rich' && slot(content.description.content)}\n </div>}\n <div className={part('actions', 'cloudlet-actions')}>\n {command?.kind === 'command' && control('action', command.label, () => {\n if (action.status !== 'pending') bridge.invokeAction(lease, handle);\n }, { className: primary, 'aria-disabled': action.status === 'pending', 'aria-busy': action.status === 'pending',\n 'aria-describedby': action.status === 'failed' ? `${id}-action-error` : undefined })}\n {command?.kind === 'link' && <a data-cloudlet-control=\"action\" className={primary} href={command.href} target={command.target}\n rel={command.target === '_blank' ? [...new Set(`${command.rel ?? ''} noopener`.trim().split(/\\s+/u))].join(' ') : command.rel}\n onClick={event => activateLink(event.nativeEvent)}\n onAuxClick={event => { if (event.button === 1) activateLink(event.nativeEvent); }}>{command.label}</a>}\n {retryable(operation) && control('retry', labels.retry, () => bridge.retryOperation(lease, handle, operation.token), { className: neutral })}\n {operation?.canCancel && control('cancel', operation.cancelRequested ? labels.cancellationRequested : labels.cancel, () => {\n if (!operation.cancelRequested) bridge.cancelOperation(lease, handle, operation.token);\n }, { className: neutral, 'aria-disabled': operation.cancelRequested })}\n </div>\n {action.status === 'failed' && <p id={`${id}-action-error`} className=\"cloudlet-action-error\">{action.message}</p>}\n </div>;\n}\n\nexport function closeButton(labels: CloudletLabels, part: PartClass, onClick: () => void) {\n return control('close', glyph('m4.5 4.5 7 7m0-7-7 7'), onClick, { 'aria-label': labels.close, className: part('close', 'cloudlet-close') });\n}\n"],"mappings":";;;AAQA,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AyB,UAAAN,EAAO;GAAW,CAAA;EAC9G;;AACP;AAEA,SAAgBW,EAAY,GAAwB,GAAiB,GAAqB;CACxF,OAAOrC,EAAQ,SAASE,EAAM,sBAAsB,GAAGoC,GAAS;EAAE,cAAcT,EAAO;EAAO,WAAWtB,EAAK,SAAS,gBAAgB;CAAE,CAAC;AAC5I"}
1
+ {"version":3,"file":"card.js","names":["defaultLabels","title","count","missed","index","total","SlotBoundary","Component","props","state","Suspense","CheckedSlot","ref","useRef","invalidContent","setInvalidContent","useState","invalid","content","useEffect","element","reported","check","bridge","lease","Observer","observer","handle","rejectFocus","event","control","name","glyph","path","partClasses","extra","classNames","part","own","glyphs","StatusIcon","notification","determinate","progress","kind","preview","slot","slotRenderer","value","rejectSlotFocus","Heading","titleId","previewSlot","retryable","operation","SlidePreview","action","lookalike","primary","labels","Body","neutral","id","useId","command","activateLink","navigate","closeButton","onClick"],"sources":["../../src/react/card.tsx"],"sourcesContent":["import { Component, Suspense, useEffect, useId, useRef, useState } from 'react';\nimport type { ComponentPropsWithRef, ReactNode } from 'react';\nimport type { HostLease, RendererBridge } from '../contracts/internal.js';\nimport type { NotificationHandle } from '../contracts/identity.js';\nimport type { NotificationKind } from '../contracts/notifications.js';\nimport type { NotificationSnapshot } from '../contracts/snapshots.js';\nimport type { CloudletLabels, CloudletPart, ToasterProps } from '../react.js';\n\nexport const defaultLabels: CloudletLabels = {\n region: 'Notifications', island: 'Current notifications', carousel: 'carousel', slide: 'slide',\n close: 'Close notification', retry: 'Retry',\n cancel: 'Request cancellation', cancellationRequested: 'Cancellation requested',\n acknowledgeOverflow: 'Acknowledge missed notifications', collapse: 'Press Escape to collapse',\n stackSummary: (title, count, missed) => [title, ...(count > 1 ? [`${count} notifications`] : []),\n ...(missed > 0 ? [`${missed} missed`] : [])].join(', '),\n page: (index, total) => `${index} of ${total}`,\n overflowCount: count => `${count} missed notifications`,\n};\n\ninterface SlotProps {\n readonly content: ReactNode;\n readonly bridge: RendererBridge<ReactNode>;\n readonly lease: HostLease;\n readonly handle: NotificationHandle;\n readonly rejectFocus: (previous: EventTarget | null) => void;\n}\n\nclass SlotBoundary extends Component<SlotProps, { failed: boolean; content: ReactNode }> {\n override state = { failed: false, content: this.props.content };\n static getDerivedStateFromError() { return { failed: true }; }\n static getDerivedStateFromProps(props: SlotProps, state: { content: ReactNode }) {\n return props.content === state.content ? null : { failed: false, content: props.content };\n }\n override componentDidCatch(error: unknown) {\n this.props.bridge.reportDiagnostic(this.props.lease, { code: 'slot-error', source: 'Toaster.slot',\n message: 'A rich slot could not be rendered', handle: this.props.handle, error });\n }\n override render() {\n return this.state.failed ? this.props.bridge.renderError\n : <Suspense fallback={this.props.bridge.renderError}><CheckedSlot {...this.props} /></Suspense>;\n }\n}\n\nfunction CheckedSlot({ content, bridge, lease, handle, rejectFocus }: SlotProps) {\n const ref = useRef<HTMLDivElement>(null);\n const [invalidContent, setInvalidContent] = useState<{ content: ReactNode } | null>(null);\n const invalid = invalidContent?.content === content;\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n let reported = false;\n const check = () => {\n if (reported || !element.querySelector('a[href],button,input,select,textarea,summary,iframe,[tabindex],[contenteditable]:not([contenteditable=\"false\"]),audio[controls],video[controls]')) return;\n reported = true;\n setInvalidContent({ content });\n bridge.reportDiagnostic(lease, { code: 'slot-error', source: 'Toaster.slot',\n message: 'Rich slots must be non-interactive; use the notification action', handle });\n };\n check();\n const Observer = element.ownerDocument.defaultView?.MutationObserver;\n const observer = Observer ? new Observer(check) : null;\n observer?.observe(element, { childList: true, subtree: true, attributes: true });\n return () => observer?.disconnect();\n }, [content, bridge, lease, handle]);\n return <div ref={ref} className=\"cloudlet-slot\" onFocusCapture={event => rejectFocus(event.relatedTarget)}>\n {invalid ? bridge.renderError : content}\n </div>;\n}\n\nfunction control(name: string, children: ReactNode, onClick: () => void, props?: ComponentPropsWithRef<'button'>) {\n return <button type=\"button\" data-cloudlet-control={name} {...props} onClick={onClick}>{children}</button>;\n}\n\nfunction glyph(path: string) {\n return <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\"><path d={path} /></svg>;\n}\n\n/** Adds the application's `classNames` part to an own `cloudlet-*` class, never replacing it. */\nexport type PartClass = (part: CloudletPart, own: string) => string;\nexport function partClasses(classNames: ToasterProps['classNames']): PartClass {\n return (part, own) => {\n const extra = classNames?.[part];\n return typeof extra === 'string' && extra.trim() ? `${own} ${extra.trim()}` : own;\n };\n}\n\n/** 16 px stroke glyphs drawn in the status colour. */\nconst glyphs: Record<Exclude<NotificationKind, 'loading'>, string> = {\n success: 'M4.5 8.5 7 11l4.5-5.5',\n error: 'm5.5 5.5 5 5m0-5-5 5',\n info: 'M8 7.5V11M8 5h.01',\n warning: 'M8 4.75V8.5M8 11.25h.01',\n};\n\n/**\n * The status icon: a 24 px tinted circle with a glyph, the loading spinner or the\n * notification's own icon, and the 2 px progress ring around it (pill and Island\n * share these nodes). With progress the icon is the accessible progressbar. The\n * determinate arc is owned by the host sampler (one RAF per host, 240 ms tween);\n * `preview` draws the value statically for the inert swipe neighbour.\n */\nexport function StatusIcon({ notification, slot, part, preview = false }: {\n notification: NotificationSnapshot<ReactNode>; slot: (value: ReactNode) => ReactNode; part: PartClass; preview?: boolean;\n}) {\n const { content, kind } = notification;\n const { progress } = content;\n const determinate = progress?.kind === 'determinate';\n return <div className={part('icon', 'cloudlet-icon')} data-kind={kind}\n {...(progress && !preview ? { role: 'progressbar', 'aria-valuemin': 0, 'aria-valuemax': 100,\n 'aria-valuenow': determinate ? Math.round(progress.value * 100) : undefined, 'aria-label': progress.label ?? content.title }\n : { 'aria-hidden': 'true' })}>\n {content.icon !== undefined\n ? <span className=\"cloudlet-glyph\" aria-hidden=\"true\">{slot(content.icon)}</span>\n // With progress the ring is the activity indicator of a loading record.\n : kind === 'loading' ? !progress && <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" className=\"cloudlet-glyph cloudlet-spinner\">\n <circle cx=\"8\" cy=\"8\" r=\"5.5\" strokeDasharray=\"22 13\" /></svg>\n : <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" className=\"cloudlet-glyph\"><path d={glyphs[kind]} /></svg>}\n {progress && <svg aria-hidden=\"true\" viewBox=\"0 0 32 32\" className=\"cloudlet-ring\" data-progress={progress.kind}>\n <circle className=\"cloudlet-ring-track\" cx=\"16\" cy=\"16\" r=\"15\" />\n <circle className=\"cloudlet-progress-fill\" cx=\"16\" cy=\"16\" r=\"15\" pathLength=\"100\" transform=\"rotate(-90 16 16)\"\n strokeDasharray={!determinate ? '25 75' : preview ? `${Math.round(progress.value * 10000) / 100} 100` : '0 100'} />\n </svg>}\n </div>;\n}\n\nexport function slotRenderer(bridge: RendererBridge<ReactNode>, lease: HostLease, handle: NotificationHandle,\n rejectSlotFocus: (previous: EventTarget | null) => void) {\n return (value: ReactNode) => <SlotBoundary content={value} bridge={bridge} lease={lease} handle={handle} rejectFocus={rejectSlotFocus} />;\n}\n\n/**\n * Status icon and title: the same DOM nodes in the pill and in the Island header,\n * so opening never re-creates them and the title can receive focus in place.\n */\nexport function Heading({ notification, slot, part, titleId }: {\n notification: NotificationSnapshot<ReactNode>; slot: (value: ReactNode) => ReactNode; part: PartClass;\n /** Omitted for the inert neighbour preview: no id, focus target, data hook or live progress. */\n titleId?: string;\n}) {\n const title = part('title', 'cloudlet-title');\n return <div className=\"cloudlet-heading\">\n <StatusIcon notification={notification} slot={slot} part={part} preview={titleId === undefined} />\n {titleId === undefined ? <h2 className={title}>{notification.content.title}</h2>\n : <h2 id={titleId} tabIndex={-1} data-cloudlet-title=\"\" className={title}>{notification.content.title}</h2>}\n </div>;\n}\n\n/** Rich content of the inert neighbour preview: rendered as is, never checked or reported twice. */\nexport const previewSlot = (value: ReactNode) => <div className=\"cloudlet-slot\">{value}</div>;\n\n/** A settled factory can always retry through the API; only an unsuccessful attempt offers the button. */\ntype Operation = NotificationSnapshot<ReactNode>['operation'];\nconst retryable = (operation: Operation): operation is NonNullable<Operation> => !!operation?.canRetry && operation.status !== 'fulfilled';\n\n/**\n * The neighbour shown only while a finger drags the Island content:\n * the same layout as a live slide, but every control is a lookalike without\n * handlers, ids, links or tab stops. The caller puts it in an `inert` container.\n */\nexport function SlidePreview({ notification, labels, part }: { notification: NotificationSnapshot<ReactNode>; labels: CloudletLabels; part: PartClass }) {\n const { content, operation, kind } = notification;\n const action = part('action', 'cloudlet-action');\n const lookalike = (children: ReactNode, primary = false) =>\n <button type=\"button\" tabIndex={-1} className={primary ? `${action} cloudlet-primary` : action}>{children}</button>;\n // Only the body slides: the preview shows the neighbour's body under the live heading.\n return <div className=\"cloudlet-slide\" data-kind={kind}>\n <div className={part('body', 'cloudlet-body')} data-kind={kind}>\n {content.description && <div className={part('description', 'cloudlet-description')}>\n {content.description.kind === 'text' ? <p>{content.description.text}</p> : previewSlot(content.description.content)}\n </div>}\n <div className={part('actions', 'cloudlet-actions')}>\n {content.action?.kind === 'command' && lookalike(content.action.label, true)}\n {content.action?.kind === 'link' && <a className={`${action} cloudlet-primary`}>{content.action.label}</a>}\n {retryable(operation) && lookalike(labels.retry)}\n {operation?.canCancel && lookalike(operation.cancelRequested ? labels.cancellationRequested : labels.cancel)}\n </div>\n {notification.action.status === 'failed' && <p className=\"cloudlet-action-error\">{notification.action.message}</p>}\n </div>\n </div>;\n}\n\n/** Island slide body: description, progress, actions and the action error. */\nexport function Body({ notification, bridge, lease, labels, navigate, slot, part }: {\n notification: NotificationSnapshot<ReactNode>; bridge: RendererBridge<ReactNode>; lease: HostLease;\n labels: CloudletLabels; navigate: (handle: NotificationHandle) => void; slot: (value: ReactNode) => ReactNode; part: PartClass;\n}) {\n const { handle, content, operation, action, kind } = notification;\n // The primary action is tinted with the status; retry and cancel stay neutral.\n const neutral = part('action', 'cloudlet-action');\n const primary = `${neutral} cloudlet-primary`;\n const id = useId();\n const command = content.action;\n const activateLink = (event: MouseEvent) => {\n // Observe cancellation after portal/application ancestors have handled activation.\n queueMicrotask(() => { if (!event.defaultPrevented) navigate(handle); });\n };\n return <div className={part('body', 'cloudlet-body')} data-kind={kind}>\n {content.description && <div className={part('description', 'cloudlet-description')}>\n {content.description.kind === 'text' && <p>{content.description.text}</p>}\n {content.description.kind === 'rich' && slot(content.description.content)}\n </div>}\n <div className={part('actions', 'cloudlet-actions')}>\n {command?.kind === 'command' && control('action', command.label, () => {\n if (action.status !== 'pending') bridge.invokeAction(lease, handle);\n }, { className: primary, 'aria-disabled': action.status === 'pending', 'aria-busy': action.status === 'pending',\n 'aria-describedby': action.status === 'failed' ? `${id}-action-error` : undefined })}\n {command?.kind === 'link' && <a data-cloudlet-control=\"action\" className={primary} href={command.href} target={command.target}\n rel={command.target === '_blank' ? [...new Set(`${command.rel ?? ''} noopener`.trim().split(/\\s+/u))].join(' ') : command.rel}\n onClick={event => activateLink(event.nativeEvent)}\n onAuxClick={event => { if (event.button === 1) activateLink(event.nativeEvent); }}>{command.label}</a>}\n {retryable(operation) && control('retry', labels.retry, () => bridge.retryOperation(lease, handle, operation.token), { className: neutral })}\n {operation?.canCancel && control('cancel', operation.cancelRequested ? labels.cancellationRequested : labels.cancel, () => {\n if (!operation.cancelRequested) bridge.cancelOperation(lease, handle, operation.token);\n }, { className: neutral, 'aria-disabled': operation.cancelRequested })}\n </div>\n {action.status === 'failed' && <p id={`${id}-action-error`} className=\"cloudlet-action-error\">{action.message}</p>}\n </div>;\n}\n\nexport function closeButton(labels: CloudletLabels, part: PartClass, onClick: () => void) {\n return control('close', glyph('m4.5 4.5 7 7m0-7-7 7'), onClick, { 'aria-label': labels.close, className: part('close', 'cloudlet-close') });\n}\n"],"mappings":";;;AAQA,IAAaA,IAAgC;CAC3C,QAAQ;CAAiB,QAAQ;CAAyB,UAAU;CAAY,OAAO;CACvF,OAAO;CAAsB,OAAO;CACpC,QAAQ;CAAwB,uBAAuB;CACvD,qBAAqB;CAAoC,UAAU;CACnE,eAAe,GAAO,GAAO,MAAW;EAACC;EAAO,GAAIC,IAAQ,IAAI,CAAC,GAAGA,EAAM,eAAe,IAAI,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**
2
2
  * Numeric animation generators for the shell sampler (motion.ts), ported from Motion 14.3.0
3
- * so that every frame matches what the owner accepted on the laboratory (D47):
3
+ * so that every frame matches what was tuned on the laboratory:
4
4
  *
5
5
  * - `spring` is the numeric part of motion-dom/dist/es/animation/generators/spring.mjs
6
6
  * (physics-defined and duration/bounce-defined springs, `findSpring`, analytical velocity,
@@ -8,7 +8,7 @@
8
8
  * - `tween` is the two-keyframe fast path of motion-dom's `keyframes` generator for numbers,
9
9
  * with `easeOut` = `cubicBezier(0, 0, 0.58, 1)` from motion-utils 14.1.1.
10
10
  *
11
- * Motion is Copyright (c) 2024 Motion B.V., MIT (packages/cloudlet/THIRD_PARTY_NOTICES.md).
11
+ * Motion is Copyright (c) 2024 Motion B.V., MIT (packages/toast/THIRD_PARTY_NOTICES.md).
12
12
  * Colour/string mixing, keyframe arrays and the rest of Motion are not needed here: Cloudlet
13
13
  * animates numbers only. tests/unit/generators-reference.test.ts samples both implementations
14
14
  * every millisecond against the installed Motion 14.3.0 (|Δ| < 1e-9, same `done` frame).
@@ -1 +1 @@
1
- {"version":3,"file":"generators.js","names":["clamp","v","max","min","millisecondsToSeconds","milliseconds","secondsToMilliseconds","seconds","calcBezier","t","a1","a2","cubicBezier","mX1","mY1","mX2","mY2","x","lowerBound","upperBound","i","currentX","easeOut","tween","state","from","mixes","to","duration","springDefaults","bounceToDampingRatio","bounce","rootIterations","approximateRoot","result","initialGuess","envelope","derivative","overdampedFreqScale","dampingRatio","root","slow","fast","target","criticalFreqTime","freqTime","calcAngularFreq","undampedFreq","safeMin","findSpring","exponentialDecay","delta","b","c","e","f","g","criticalFreq","stiffness","isValidPhysics","canBeZero","value","spring","origin","options","validStiffness","validDamping","validMass","damping","mass","isResolvedFromDuration","isTimeDefined","resolved","inheritVelocity","velocity","undampedAngularFreq","decay","isGranularScale","restSpeed","restDelta","resolveSpring","resolveVelocity","angularFreq","A","sinC","cosC","sample","C","dampedAngularFreq","limit","decayAt","rate","P","S","F","current","currentVelocity"],"sources":["../../src/react/generators.ts"],"sourcesContent":["/**\n * Numeric animation generators for the shell sampler (motion.ts), ported from Motion 14.3.0\n * so that every frame matches what the owner accepted on the laboratory (D47):\n *\n * - `spring` is the numeric part of motion-dom/dist/es/animation/generators/spring.mjs\n * (physics-defined and duration/bounce-defined springs, `findSpring`, analytical velocity,\n * granular rest thresholds, the overdamped settle limit);\n * - `tween` is the two-keyframe fast path of motion-dom's `keyframes` generator for numbers,\n * with `easeOut` = `cubicBezier(0, 0, 0.58, 1)` from motion-utils 14.1.1.\n *\n * Motion is Copyright (c) 2024 Motion B.V., MIT (packages/cloudlet/THIRD_PARTY_NOTICES.md).\n * Colour/string mixing, keyframe arrays and the rest of Motion are not needed here: Cloudlet\n * animates numbers only. tests/unit/generators-reference.test.ts samples both implementations\n * every millisecond against the installed Motion 14.3.0 (|Δ| < 1e-9, same `done` frame).\n * Expressions keep Motion's operation order on purpose: a re-association changes the last bits.\n */\n\nexport interface GeneratorState { value: number; done: boolean }\nexport interface Generator {\n /** `t` in generator milliseconds. Returns a mutable state object, like Motion's iterator. */\n readonly next: (t: number) => GeneratorState;\n /** Analytical derivative in units per second; tweens have none (a following spring starts at rest). */\n readonly velocity?: (t: number) => number;\n}\n\nexport interface SpringOptions {\n readonly from: number;\n readonly to: number;\n /** Units per second; ignored by duration/bounce springs, as in Motion. */\n readonly velocity?: number | undefined;\n readonly stiffness?: number | undefined;\n readonly damping?: number | undefined;\n readonly mass?: number | undefined;\n readonly duration?: number | undefined;\n readonly bounce?: number | undefined;\n}\n\nconst clamp = (min: number, max: number, v: number) => (v > max ? max : v < min ? min : v);\nconst millisecondsToSeconds = (milliseconds: number) => milliseconds / 1000;\nconst secondsToMilliseconds = (seconds: number) => seconds * 1000;\n\n/* ------------------------------------------------------------------------------------------ */\n/* motion-utils/dist/es/easing/cubic-bezier.mjs (modified from Gaëtan Renaudeau's BezierEasing) */\n\nconst calcBezier = (t: number, a1: number, a2: number) => t * (3 * (1 - t) * ((1 - t) * a1 + t * a2) + t * t);\nfunction cubicBezier(mX1: number, mY1: number, mX2: number, mY2: number): (x: number) => number {\n if (mX1 === mY1 && mX2 === mY2) return (x) => x;\n return (x) => {\n let lowerBound = 0;\n let upperBound = 1;\n let t = x;\n for (let i = 0; ; i++) {\n // Outside the bracket (x out of range or a Newton overshoot on a flat part): bisect.\n if (!(t >= lowerBound && t <= upperBound)) t = (lowerBound + upperBound) / 2;\n const currentX = calcBezier(t, mX1, mX2) - x;\n if (currentX * currentX < 1e-28 || i === 40) break;\n currentX > 0 ? (upperBound = t) : (lowerBound = t);\n // Newton-Raphson step, dx/dt from a forward difference.\n t -= (currentX * 1e-7) / (calcBezier(t + 1e-7, mX1, mX2) - x - currentX);\n }\n return calcBezier(t, mY1, mY2);\n };\n}\nconst easeOut = cubicBezier(0, 0, 0.58, 1);\n\n/* ------------------------------------------------------------------------------------------ */\n/* motion-dom/dist/es/animation/generators/keyframes.mjs: two numeric keyframes, one easing */\n\n/** `keyframes({ keyframes: [from, to], duration, ease: 'easeOut' })` for numbers. */\nexport function tween(from: number, to: number, duration: number): Generator {\n const state: GeneratorState = { done: false, value: from };\n const mixes = from !== to;\n return {\n next: (t) => {\n state.value = mixes ? from + (to - from) * easeOut(duration > 0 ? clamp(0, 1, t / duration) : 1) : to;\n state.done = t >= duration;\n return state;\n },\n };\n}\n\n/* ------------------------------------------------------------------------------------------ */\n/* motion-dom/dist/es/animation/generators/spring.mjs */\n\nconst springDefaults = {\n stiffness: 100,\n damping: 10,\n mass: 1.0,\n duration: 800,\n bounce: 0.3,\n restSpeed: { granular: 0.01, default: 2 },\n restDelta: { granular: 0.005, default: 0.5 },\n minDuration: 0.01,\n maxDuration: 10.0,\n minDamping: 0.05,\n};\n\n/** Bounce → damping ratio as SwiftUI does: 0 critically damped, towards 1 undamped, towards −1 overdamped. */\nconst bounceToDampingRatio = (bounce: number) => bounce < 0\n ? 1 / Math.max(1 + bounce, springDefaults.minDamping)\n : Math.max(1 - bounce, springDefaults.minDamping);\n\nconst rootIterations = 12;\nfunction approximateRoot(envelope: (v: number) => number, derivative: (v: number) => number, initialGuess: number) {\n let result = initialGuess;\n for (let i = 1; i < rootIterations; i++) result = result - envelope(result) / derivative(result);\n return result;\n}\n\n/** Scales an overdamped spring's undamped frequency so a negative bounce changes the shape, not the arrival. */\nfunction overdampedFreqScale(dampingRatio: number, criticalFreqTime: number) {\n if (!(dampingRatio > 1)) return 1;\n const root = Math.sqrt(dampingRatio * dampingRatio - 1);\n const slow = dampingRatio - root;\n const fast = dampingRatio + root;\n const target = 2 * root * Math.exp(-criticalFreqTime) * (1 + criticalFreqTime);\n return approximateRoot(\n (freqTime) => fast * Math.exp(-slow * freqTime) - slow * Math.exp(-fast * freqTime) - target,\n (freqTime) => Math.exp(-fast * freqTime) - Math.exp(-slow * freqTime),\n criticalFreqTime,\n ) / criticalFreqTime;\n}\n\nfunction calcAngularFreq(undampedFreq: number, dampingRatio: number) {\n return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);\n}\n\nconst safeMin = 0.001;\n/** Duration/bounce → stiffness/damping (zero initial velocity, default mass), by Newton's method. */\nfunction findSpring(duration: number, bounce: number) {\n let envelope: (undampedFreq: number) => number;\n let derivative: (undampedFreq: number) => number;\n const dampingRatio = bounceToDampingRatio(bounce);\n duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, millisecondsToSeconds(duration));\n if (dampingRatio < 1) {\n envelope = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio;\n const delta = exponentialDecay * duration;\n const b = calcAngularFreq(undampedFreq, dampingRatio);\n const c = Math.exp(-delta);\n return safeMin - (exponentialDecay / b) * c;\n };\n derivative = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio;\n const delta = exponentialDecay * duration;\n const e = dampingRatio * dampingRatio * undampedFreq * undampedFreq * duration;\n const f = Math.exp(-delta);\n const g = calcAngularFreq(undampedFreq * undampedFreq, dampingRatio);\n const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;\n return (factor * -e * f) / g;\n };\n } else {\n // Critically damped; overdamped springs reuse this root, scaled below.\n envelope = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration);\n const b = undampedFreq * duration + 1;\n return -safeMin + a * b;\n };\n derivative = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration);\n const b = -undampedFreq * (duration * duration);\n return a * b;\n };\n }\n const initialGuess = 5 / duration;\n const criticalFreq = approximateRoot(envelope, derivative, initialGuess);\n const undampedFreq = criticalFreq * overdampedFreqScale(dampingRatio, criticalFreq * duration);\n const stiffness = undampedFreq * undampedFreq;\n return { stiffness, damping: dampingRatio * 2 * Math.sqrt(stiffness), duration: secondsToMilliseconds(duration) };\n}\n\n/** Stiffness and mass are divisors (positive); damping 0 is a valid perpetual oscillation. */\nconst isValidPhysics = (value: number | undefined, canBeZero = false): value is number =>\n (canBeZero ? (value as number) >= 0 : (value as number) > 0) && (value as number) < Infinity;\n\n/**\n * `spring({ keyframes: [from, to], velocity, stiffness, damping, mass })` or\n * `spring({ keyframes: [from, to], duration, bounce })`. Physics, when valid, wins over\n * duration/bounce; a duration/bounce spring that fails to resolve falls back to Motion's defaults.\n */\nexport function spring(options: SpringOptions): Generator {\n const origin = options.from;\n const target = options.to;\n const state: GeneratorState = { done: false, value: origin };\n\n const validStiffness = isValidPhysics(options.stiffness) ? options.stiffness : undefined;\n const validDamping = isValidPhysics(options.damping, true) ? options.damping : undefined;\n const validMass = isValidPhysics(options.mass) ? options.mass : undefined;\n let stiffness = validStiffness ?? springDefaults.stiffness;\n let damping = validDamping ?? springDefaults.damping;\n const mass = validMass ?? springDefaults.mass;\n let duration = 0;\n let isResolvedFromDuration = false;\n const isTimeDefined = (validStiffness ?? validDamping ?? validMass) === undefined\n && (options.duration !== undefined || options.bounce !== undefined);\n if (isTimeDefined) {\n const resolved = findSpring(options.duration ?? springDefaults.duration, options.bounce ?? springDefaults.bounce);\n stiffness = resolved.stiffness;\n damping = resolved.damping;\n duration = resolved.duration;\n isResolvedFromDuration = true;\n // Degenerate time options (NaN bounce, no convergence): replace the pair together.\n if (!isValidPhysics(stiffness) || !isValidPhysics(damping, true)) {\n stiffness = springDefaults.stiffness;\n damping = springDefaults.damping;\n }\n }\n\n // Time-defined springs ignore inherited velocity (it would oscillate small ranges heavily).\n const inheritVelocity = (velocity: number) => (isTimeDefined ? 0 : -millisecondsToSeconds(velocity));\n const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));\n const undampedAngularFreq = millisecondsToSeconds(Math.sqrt(stiffness / mass));\n const decay = dampingRatio * undampedAngularFreq;\n const delta = target - origin;\n const velocity = inheritVelocity(options.velocity || 0) || 0;\n const isGranularScale = Math.abs(delta) < 5;\n const restSpeed = isGranularScale ? springDefaults.restSpeed.granular : springDefaults.restSpeed.default;\n const restDelta = isGranularScale ? springDefaults.restDelta.granular : springDefaults.restDelta.default;\n\n let resolveSpring: (t: number) => number;\n let resolveVelocity: (t: number) => number;\n if (dampingRatio < 1) {\n // Underdamped. exp/sin/cos depend only on t: memoised per t, as in Motion.\n const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);\n const A = (velocity + decay * delta) / angularFreq;\n const sinC = decay * A + delta * angularFreq;\n const cosC = decay * delta - A * angularFreq;\n const c = { t: -1, env: 0, sin: 0, cos: 0 };\n const sample = (t: number) => {\n if (t !== c.t) {\n c.t = t;\n c.env = Math.exp(-decay * t);\n c.sin = Math.sin(angularFreq * t);\n c.cos = Math.cos(angularFreq * t);\n }\n };\n resolveSpring = (t) => { sample(t); return target - c.env * (A * c.sin + delta * c.cos); };\n resolveVelocity = (t) => { sample(t); return c.env * (sinC * c.sin + cosC * c.cos); };\n } else if (dampingRatio === 1) {\n // Critically damped.\n const C = velocity + undampedAngularFreq * delta;\n resolveSpring = (t) => target - Math.exp(-undampedAngularFreq * t) * (delta + (velocity + undampedAngularFreq * delta) * t);\n resolveVelocity = (t) => Math.exp(-undampedAngularFreq * t) * (undampedAngularFreq * C * t - velocity);\n } else {\n // Overdamped: a slow and a fast decaying exponential, so no term overflows.\n const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);\n const slow = decay - dampedAngularFreq;\n const fast = decay + dampedAngularFreq;\n // Physics-defined springs settle at the damping rate once dampedAngularFreq·t passes 300;\n // time-defined (negative bounce) springs keep the exact curve.\n const limit = isTimeDefined ? Infinity : 300 / dampedAngularFreq;\n const decayAt = (rate: number, t: number) => Math.exp(t > limit ? -rate * limit - decay * (t - limit) : -rate * t);\n const P = (velocity + decay * delta) / dampedAngularFreq;\n const S = (delta + P) / 2;\n const F = (delta - P) / 2;\n resolveSpring = (t) => target - S * decayAt(slow, t) - F * decayAt(fast, t);\n resolveVelocity = (t) => slow * S * decayAt(slow, t) + fast * F * decayAt(fast, t);\n }\n\n return {\n velocity: (t) => secondsToMilliseconds(resolveVelocity(t)),\n next: (t) => {\n const current = resolveSpring(t);\n if (!isResolvedFromDuration) {\n const currentVelocity = secondsToMilliseconds(resolveVelocity(t));\n state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target - current) <= restDelta;\n } else {\n state.done = t >= duration;\n }\n state.value = state.done ? target : current;\n return state;\n },\n };\n}\n"],"mappings":";AAqCA,IAAMA,KAAS,GAAa,GAAa,MAAeC,IAAIC,IAAMA,IAAMD,IAAIE,IAAMA,IAAMF,GAClFG,KAAyB,MAAyBC,IAAe,KACjEC,KAAyB,MAAoBC,IAAU,KAKvDC,KAAc,GAAW,GAAY,MAAeC,KAAK,KAAK,IAAIA,OAAO,IAAIA,KAAKC,IAAKD,IAAIE,KAAMF,IAAIA;AAC3G,SAASG,EAAY,GAAa,GAAa,GAAa,GAAoC;CAE9F,OADIC,MAAQC,KAAOC,MAAQC,KAAa,MAAMC,KACtC,MAAM;EACZ,IAAIC,IAAa,GACbC,IAAa,GACbV,IAAIQ;EACR,KAAK,IAAIG,IAAI,IAAK,KAAK;GAErB,AAAMX,KAAKS,KAAcT,KAAKU,MAAa,KAAKD,IAAaC,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C,IAAsBlE,CAAC,KAAK0C,KAASuB,IAAWC,IAAsBxB,KAAS1C,IACzH,KAAmB,MAAM,KAAK,IAAI,CAACkE,IAAsB,CAAC,KAAKA,IAAsBY,IAAI,IAAIb;CAC/F,OAAO;EAEL,IAAMc,IAAoBb,IAAsB,KAAK,KAAKpC,IAAeA,IAAe,CAAC,GACnFE,IAAOmC,IAAQY,GACf9C,IAAOkC,IAAQY,GAGfC,IAAQlB,IAAgB,WAAW,MAAMiB,GACzCE,KAAW,GAAc,MAAc,KAAK,IAAI,IAAID,IAAQ,CAACE,IAAOF,IAAQb,KAAS,IAAIa,KAAS,CAACE,IAAO,CAAC,GAC3GC,KAAKlB,IAAWE,IAAQzB,KAASqC,GACjCK,KAAK1C,IAAQyC,KAAK,GAClBE,KAAK3C,IAAQyC,KAAK;EAExB,AADA,KAAiB,MAAMjD,IAASkD,IAAIH,EAAQjD,GAAMhC,CAAC,IAAIqF,IAAIJ,EAAQhD,GAAMjC,CAAC,GAC1E,KAAmB,MAAMgC,IAAOoD,IAAIH,EAAQjD,GAAMhC,CAAC,IAAIiC,IAAOoD,IAAIJ,EAAQhD,GAAMjC,CAAC;CACnF;CAEA,OAAO;EACL,WAAW,MAAMH,EAAsB2E,EAAgBxE,CAAC,CAAC;EACzD,OAAO,MAAM;GACX,IAAMsF,IAAUf,EAAcvE,CAAC;GAC/B,IAAK6D,GAIH,EAAM,OAAO7D,KAAKmB;QAJS;IAC3B,IAAMoE,IAAkB1F,EAAsB2E,EAAgBxE,CAAC,CAAC;IAChE,EAAM,OAAO,KAAK,IAAIuF,CAAe,KAAKlB,KAAa,KAAK,IAAInC,IAASoD,CAAO,KAAKhB;GACvF;GAIA,OADA,EAAM,QAAQvD,EAAM,OAAOmB,IAASoD,GAC7BvE;EACT;CACF;AACF"}
1
+ {"version":3,"file":"generators.js","names":["clamp","v","max","min","millisecondsToSeconds","milliseconds","secondsToMilliseconds","seconds","calcBezier","t","a1","a2","cubicBezier","mX1","mY1","mX2","mY2","x","lowerBound","upperBound","i","currentX","easeOut","tween","state","from","mixes","to","duration","springDefaults","bounceToDampingRatio","bounce","rootIterations","approximateRoot","result","initialGuess","envelope","derivative","overdampedFreqScale","dampingRatio","root","slow","fast","target","criticalFreqTime","freqTime","calcAngularFreq","undampedFreq","safeMin","findSpring","exponentialDecay","delta","b","c","e","f","g","criticalFreq","stiffness","isValidPhysics","canBeZero","value","spring","origin","options","validStiffness","validDamping","validMass","damping","mass","isResolvedFromDuration","isTimeDefined","resolved","inheritVelocity","velocity","undampedAngularFreq","decay","isGranularScale","restSpeed","restDelta","resolveSpring","resolveVelocity","angularFreq","A","sinC","cosC","sample","C","dampedAngularFreq","limit","decayAt","rate","P","S","F","current","currentVelocity"],"sources":["../../src/react/generators.ts"],"sourcesContent":["/**\n * Numeric animation generators for the shell sampler (motion.ts), ported from Motion 14.3.0\n * so that every frame matches what was tuned on the laboratory:\n *\n * - `spring` is the numeric part of motion-dom/dist/es/animation/generators/spring.mjs\n * (physics-defined and duration/bounce-defined springs, `findSpring`, analytical velocity,\n * granular rest thresholds, the overdamped settle limit);\n * - `tween` is the two-keyframe fast path of motion-dom's `keyframes` generator for numbers,\n * with `easeOut` = `cubicBezier(0, 0, 0.58, 1)` from motion-utils 14.1.1.\n *\n * Motion is Copyright (c) 2024 Motion B.V., MIT (packages/toast/THIRD_PARTY_NOTICES.md).\n * Colour/string mixing, keyframe arrays and the rest of Motion are not needed here: Cloudlet\n * animates numbers only. tests/unit/generators-reference.test.ts samples both implementations\n * every millisecond against the installed Motion 14.3.0 (|Δ| < 1e-9, same `done` frame).\n * Expressions keep Motion's operation order on purpose: a re-association changes the last bits.\n */\n\nexport interface GeneratorState { value: number; done: boolean }\nexport interface Generator {\n /** `t` in generator milliseconds. Returns a mutable state object, like Motion's iterator. */\n readonly next: (t: number) => GeneratorState;\n /** Analytical derivative in units per second; tweens have none (a following spring starts at rest). */\n readonly velocity?: (t: number) => number;\n}\n\nexport interface SpringOptions {\n readonly from: number;\n readonly to: number;\n /** Units per second; ignored by duration/bounce springs, as in Motion. */\n readonly velocity?: number | undefined;\n readonly stiffness?: number | undefined;\n readonly damping?: number | undefined;\n readonly mass?: number | undefined;\n readonly duration?: number | undefined;\n readonly bounce?: number | undefined;\n}\n\nconst clamp = (min: number, max: number, v: number) => (v > max ? max : v < min ? min : v);\nconst millisecondsToSeconds = (milliseconds: number) => milliseconds / 1000;\nconst secondsToMilliseconds = (seconds: number) => seconds * 1000;\n\n/* ------------------------------------------------------------------------------------------ */\n/* motion-utils/dist/es/easing/cubic-bezier.mjs (modified from Gaëtan Renaudeau's BezierEasing) */\n\nconst calcBezier = (t: number, a1: number, a2: number) => t * (3 * (1 - t) * ((1 - t) * a1 + t * a2) + t * t);\nfunction cubicBezier(mX1: number, mY1: number, mX2: number, mY2: number): (x: number) => number {\n if (mX1 === mY1 && mX2 === mY2) return (x) => x;\n return (x) => {\n let lowerBound = 0;\n let upperBound = 1;\n let t = x;\n for (let i = 0; ; i++) {\n // Outside the bracket (x out of range or a Newton overshoot on a flat part): bisect.\n if (!(t >= lowerBound && t <= upperBound)) t = (lowerBound + upperBound) / 2;\n const currentX = calcBezier(t, mX1, mX2) - x;\n if (currentX * currentX < 1e-28 || i === 40) break;\n currentX > 0 ? (upperBound = t) : (lowerBound = t);\n // Newton-Raphson step, dx/dt from a forward difference.\n t -= (currentX * 1e-7) / (calcBezier(t + 1e-7, mX1, mX2) - x - currentX);\n }\n return calcBezier(t, mY1, mY2);\n };\n}\nconst easeOut = cubicBezier(0, 0, 0.58, 1);\n\n/* ------------------------------------------------------------------------------------------ */\n/* motion-dom/dist/es/animation/generators/keyframes.mjs: two numeric keyframes, one easing */\n\n/** `keyframes({ keyframes: [from, to], duration, ease: 'easeOut' })` for numbers. */\nexport function tween(from: number, to: number, duration: number): Generator {\n const state: GeneratorState = { done: false, value: from };\n const mixes = from !== to;\n return {\n next: (t) => {\n state.value = mixes ? from + (to - from) * easeOut(duration > 0 ? clamp(0, 1, t / duration) : 1) : to;\n state.done = t >= duration;\n return state;\n },\n };\n}\n\n/* ------------------------------------------------------------------------------------------ */\n/* motion-dom/dist/es/animation/generators/spring.mjs */\n\nconst springDefaults = {\n stiffness: 100,\n damping: 10,\n mass: 1.0,\n duration: 800,\n bounce: 0.3,\n restSpeed: { granular: 0.01, default: 2 },\n restDelta: { granular: 0.005, default: 0.5 },\n minDuration: 0.01,\n maxDuration: 10.0,\n minDamping: 0.05,\n};\n\n/** Bounce → damping ratio as SwiftUI does: 0 critically damped, towards 1 undamped, towards −1 overdamped. */\nconst bounceToDampingRatio = (bounce: number) => bounce < 0\n ? 1 / Math.max(1 + bounce, springDefaults.minDamping)\n : Math.max(1 - bounce, springDefaults.minDamping);\n\nconst rootIterations = 12;\nfunction approximateRoot(envelope: (v: number) => number, derivative: (v: number) => number, initialGuess: number) {\n let result = initialGuess;\n for (let i = 1; i < rootIterations; i++) result = result - envelope(result) / derivative(result);\n return result;\n}\n\n/** Scales an overdamped spring's undamped frequency so a negative bounce changes the shape, not the arrival. */\nfunction overdampedFreqScale(dampingRatio: number, criticalFreqTime: number) {\n if (!(dampingRatio > 1)) return 1;\n const root = Math.sqrt(dampingRatio * dampingRatio - 1);\n const slow = dampingRatio - root;\n const fast = dampingRatio + root;\n const target = 2 * root * Math.exp(-criticalFreqTime) * (1 + criticalFreqTime);\n return approximateRoot(\n (freqTime) => fast * Math.exp(-slow * freqTime) - slow * Math.exp(-fast * freqTime) - target,\n (freqTime) => Math.exp(-fast * freqTime) - Math.exp(-slow * freqTime),\n criticalFreqTime,\n ) / criticalFreqTime;\n}\n\nfunction calcAngularFreq(undampedFreq: number, dampingRatio: number) {\n return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);\n}\n\nconst safeMin = 0.001;\n/** Duration/bounce → stiffness/damping (zero initial velocity, default mass), by Newton's method. */\nfunction findSpring(duration: number, bounce: number) {\n let envelope: (undampedFreq: number) => number;\n let derivative: (undampedFreq: number) => number;\n const dampingRatio = bounceToDampingRatio(bounce);\n duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, millisecondsToSeconds(duration));\n if (dampingRatio < 1) {\n envelope = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio;\n const delta = exponentialDecay * duration;\n const b = calcAngularFreq(undampedFreq, dampingRatio);\n const c = Math.exp(-delta);\n return safeMin - (exponentialDecay / b) * c;\n };\n derivative = (undampedFreq) => {\n const exponentialDecay = undampedFreq * dampingRatio;\n const delta = exponentialDecay * duration;\n const e = dampingRatio * dampingRatio * undampedFreq * undampedFreq * duration;\n const f = Math.exp(-delta);\n const g = calcAngularFreq(undampedFreq * undampedFreq, dampingRatio);\n const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;\n return (factor * -e * f) / g;\n };\n } else {\n // Critically damped; overdamped springs reuse this root, scaled below.\n envelope = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration);\n const b = undampedFreq * duration + 1;\n return -safeMin + a * b;\n };\n derivative = (undampedFreq) => {\n const a = Math.exp(-undampedFreq * duration);\n const b = -undampedFreq * (duration * duration);\n return a * b;\n };\n }\n const initialGuess = 5 / duration;\n const criticalFreq = approximateRoot(envelope, derivative, initialGuess);\n const undampedFreq = criticalFreq * overdampedFreqScale(dampingRatio, criticalFreq * duration);\n const stiffness = undampedFreq * undampedFreq;\n return { stiffness, damping: dampingRatio * 2 * Math.sqrt(stiffness), duration: secondsToMilliseconds(duration) };\n}\n\n/** Stiffness and mass are divisors (positive); damping 0 is a valid perpetual oscillation. */\nconst isValidPhysics = (value: number | undefined, canBeZero = false): value is number =>\n (canBeZero ? (value as number) >= 0 : (value as number) > 0) && (value as number) < Infinity;\n\n/**\n * `spring({ keyframes: [from, to], velocity, stiffness, damping, mass })` or\n * `spring({ keyframes: [from, to], duration, bounce })`. Physics, when valid, wins over\n * duration/bounce; a duration/bounce spring that fails to resolve falls back to Motion's defaults.\n */\nexport function spring(options: SpringOptions): Generator {\n const origin = options.from;\n const target = options.to;\n const state: GeneratorState = { done: false, value: origin };\n\n const validStiffness = isValidPhysics(options.stiffness) ? options.stiffness : undefined;\n const validDamping = isValidPhysics(options.damping, true) ? options.damping : undefined;\n const validMass = isValidPhysics(options.mass) ? options.mass : undefined;\n let stiffness = validStiffness ?? springDefaults.stiffness;\n let damping = validDamping ?? springDefaults.damping;\n const mass = validMass ?? springDefaults.mass;\n let duration = 0;\n let isResolvedFromDuration = false;\n const isTimeDefined = (validStiffness ?? validDamping ?? validMass) === undefined\n && (options.duration !== undefined || options.bounce !== undefined);\n if (isTimeDefined) {\n const resolved = findSpring(options.duration ?? springDefaults.duration, options.bounce ?? springDefaults.bounce);\n stiffness = resolved.stiffness;\n damping = resolved.damping;\n duration = resolved.duration;\n isResolvedFromDuration = true;\n // Degenerate time options (NaN bounce, no convergence): replace the pair together.\n if (!isValidPhysics(stiffness) || !isValidPhysics(damping, true)) {\n stiffness = springDefaults.stiffness;\n damping = springDefaults.damping;\n }\n }\n\n // Time-defined springs ignore inherited velocity (it would oscillate small ranges heavily).\n const inheritVelocity = (velocity: number) => (isTimeDefined ? 0 : -millisecondsToSeconds(velocity));\n const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));\n const undampedAngularFreq = millisecondsToSeconds(Math.sqrt(stiffness / mass));\n const decay = dampingRatio * undampedAngularFreq;\n const delta = target - origin;\n const velocity = inheritVelocity(options.velocity || 0) || 0;\n const isGranularScale = Math.abs(delta) < 5;\n const restSpeed = isGranularScale ? springDefaults.restSpeed.granular : springDefaults.restSpeed.default;\n const restDelta = isGranularScale ? springDefaults.restDelta.granular : springDefaults.restDelta.default;\n\n let resolveSpring: (t: number) => number;\n let resolveVelocity: (t: number) => number;\n if (dampingRatio < 1) {\n // Underdamped. exp/sin/cos depend only on t: memoised per t, as in Motion.\n const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);\n const A = (velocity + decay * delta) / angularFreq;\n const sinC = decay * A + delta * angularFreq;\n const cosC = decay * delta - A * angularFreq;\n const c = { t: -1, env: 0, sin: 0, cos: 0 };\n const sample = (t: number) => {\n if (t !== c.t) {\n c.t = t;\n c.env = Math.exp(-decay * t);\n c.sin = Math.sin(angularFreq * t);\n c.cos = Math.cos(angularFreq * t);\n }\n };\n resolveSpring = (t) => { sample(t); return target - c.env * (A * c.sin + delta * c.cos); };\n resolveVelocity = (t) => { sample(t); return c.env * (sinC * c.sin + cosC * c.cos); };\n } else if (dampingRatio === 1) {\n // Critically damped.\n const C = velocity + undampedAngularFreq * delta;\n resolveSpring = (t) => target - Math.exp(-undampedAngularFreq * t) * (delta + (velocity + undampedAngularFreq * delta) * t);\n resolveVelocity = (t) => Math.exp(-undampedAngularFreq * t) * (undampedAngularFreq * C * t - velocity);\n } else {\n // Overdamped: a slow and a fast decaying exponential, so no term overflows.\n const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);\n const slow = decay - dampedAngularFreq;\n const fast = decay + dampedAngularFreq;\n // Physics-defined springs settle at the damping rate once dampedAngularFreq·t passes 300;\n // time-defined (negative bounce) springs keep the exact curve.\n const limit = isTimeDefined ? Infinity : 300 / dampedAngularFreq;\n const decayAt = (rate: number, t: number) => Math.exp(t > limit ? -rate * limit - decay * (t - limit) : -rate * t);\n const P = (velocity + decay * delta) / dampedAngularFreq;\n const S = (delta + P) / 2;\n const F = (delta - P) / 2;\n resolveSpring = (t) => target - S * decayAt(slow, t) - F * decayAt(fast, t);\n resolveVelocity = (t) => slow * S * decayAt(slow, t) + fast * F * decayAt(fast, t);\n }\n\n return {\n velocity: (t) => secondsToMilliseconds(resolveVelocity(t)),\n next: (t) => {\n const current = resolveSpring(t);\n if (!isResolvedFromDuration) {\n const currentVelocity = secondsToMilliseconds(resolveVelocity(t));\n state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target - current) <= restDelta;\n } else {\n state.done = t >= duration;\n }\n state.value = state.done ? target : current;\n return state;\n },\n };\n}\n"],"mappings":";AAqCA,IAAMA,KAAS,GAAa,GAAa,MAAeC,IAAI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,OAAO,MAAM;GACX,IAAMsF,IAAUf,EAAcvE,CAAC;GAC/B,IAAK6D,GAIH,EAAM,OAAO7D,KAAKmB;QAJS;IAC3B,IAAMoE,IAAkB1F,EAAsB2E,EAAgBxE,CAAC,CAAC;IAChE,EAAM,OAAO,KAAK,IAAIuF,CAAe,KAAKlB,KAAa,KAAK,IAAInC,IAASoD,CAAO,KAAKhB;GACvF;GAIA,OADA,EAAM,QAAQvD,EAAM,OAAOmB,IAASoD,GAC7BvE;EACT;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"gestures.js","names":["MOTION","rubberBand","swipe","offset","dimension","coefficient","decideRelease","sign","allowed","toward","velocity","distance","interactive","createSwipe","view","root","current","wheel","suppressUntil","disposed","finish","gesture","endWheel","stream","commit","cancel","secondPointer","event","down","target","control","candidate","options","sample","elapsed","axis","position","last","release","move","horizontal","vertical","session","selection","up","x","cancelled","lost","native","listeners","unit","dx","dy","time","previous","type","listener","capture"],"sources":["../../src/react/gestures.ts"],"sourcesContent":["import { MOTION } from './motion.js';\n\nconst { swipe } = MOTION;\n\n/**\n * Edge resistance (iOS-style rubber band): the result approaches `dimension`\n * asymptotically and keeps the sign of the raw finger travel.\n */\nexport function rubberBand(offset: number, dimension: number, coefficient: number = swipe.rubberBand): number {\n if (!Number.isFinite(offset) || !(dimension > 0)) return 0;\n const travel = Math.abs(offset);\n return Math.sign(offset) * (1 - 1 / (travel * coefficient / dimension + 1)) * dimension;\n}\n\n/**\n * Release decision along one axis. Returns the sign of the travel when the swipe\n * commits that way (distance past `MOTION.swipe.distance` of `dimension`, or a flick of\n * at least `minDistance` px faster than `velocity` px/ms), 0 when it springs back.\n * A direction without a destination never commits; a flick back always cancels.\n */\nexport function decideRelease(offset: number, velocity: number, dimension: number,\n allowed: { readonly negative: boolean; readonly positive: boolean }): -1 | 0 | 1 {\n const sign = offset > 0 ? 1 : offset < 0 ? -1 : 0;\n if (!sign || !(sign > 0 ? allowed.positive : allowed.negative)) return 0;\n const toward = Number.isFinite(velocity) ? velocity * sign : 0;\n if (toward < -swipe.velocity) return 0;\n const distance = Math.abs(offset);\n if (dimension > 0 && distance > dimension * swipe.distance) return sign;\n return distance >= swipe.minDistance && toward > swipe.velocity ? sign : 0;\n}\n\nexport type SwipeAxis = 'x' | 'y';\n\n/** A started swipe along one axis. Offsets are raw finger travel in CSS px. */\nexport interface SwipeSession {\n readonly move: (offset: number) => void;\n /** Velocity is CSS px/ms along the axis, positive in the direction of positive offsets. */\n readonly end: (offset: number, velocity: number) => void;\n /** Lost capture, a second pointer, orientation change or an external cancel. */\n readonly cancel: () => void;\n}\n\n/** What may start from one pointerdown or wheel stream; `release` ends the intent window. */\nexport interface SwipeCandidate {\n readonly x: boolean;\n readonly y: boolean;\n readonly start: (axis: SwipeAxis) => SwipeSession | null;\n readonly release: () => void;\n}\n\ninterface SwipeOptions {\n /** Null ignores the input; the candidate is released exactly once. */\n readonly begin: (target: Element, input: 'pointer' | 'wheel') => SwipeCandidate | null;\n readonly now: () => number;\n}\n\ninterface PointerSwipe {\n readonly pointer: number;\n readonly candidate: SwipeCandidate;\n readonly startX: number;\n readonly startY: number;\n session: SwipeSession | null;\n axis: SwipeAxis | null;\n captured: boolean;\n x: number;\n y: number;\n lastX: number;\n lastY: number;\n time: number;\n velocityX: number;\n velocityY: number;\n}\n\ninterface WheelSwipe {\n readonly candidate: SwipeCandidate | null;\n session: SwipeSession | null;\n /** Committed early: the rest of the stream (macOS momentum) is swallowed until it goes idle. */\n spent: boolean;\n spentAt: number;\n lastDx: number;\n offset: number;\n velocity: number;\n time: number;\n timer: number;\n}\n\nconst interactive = 'button,a,input,select,textarea,summary,label,[role=\"button\"],[role=\"link\"],[contenteditable]:not([contenteditable=\"false\"])';\n\n/**\n * Pointer and trackpad ownership for one host. The axis is decided by the first\n * `MOTION.swipe.intent` px; an axis the target does not own is given back to the\n * browser (native scroll) for the rest of the gesture. Buttons and links never start\n * a swipe, except the collapsed pill, which is itself the swipe surface. Layout,\n * physics and store commands stay with the caller.\n */\nexport function createSwipe(root: HTMLElement, options: SwipeOptions) {\n const view = root.ownerDocument.defaultView;\n let current: PointerSwipe | null = null;\n let wheel: WheelSwipe | null = null;\n let suppressUntil = 0;\n let disposed = false;\n if (!view) return { cancel() {}, dispose() {}, get active() { return false; } };\n\n function finish(): PointerSwipe | null {\n const gesture = current;\n if (!gesture) return null;\n // Lost capture, store updates and callbacks can be synchronous/reentrant:\n // clear ownership before releasing anything.\n current = null;\n delete root.dataset.dragging;\n if (gesture.captured && root.hasPointerCapture?.(gesture.pointer)) root.releasePointerCapture(gesture.pointer);\n gesture.candidate.release();\n return gesture;\n }\n function endWheel(commit: boolean) {\n const stream = wheel;\n if (!stream) return;\n wheel = null;\n view!.clearTimeout(stream.timer);\n if (stream.session) delete root.dataset.dragging;\n stream.candidate?.release();\n if (commit) stream.session?.end(stream.offset, stream.velocity);\n else stream.session?.cancel();\n }\n const cancel = () => {\n finish()?.session?.cancel();\n endWheel(false);\n };\n const secondPointer = (event: PointerEvent) => {\n if (current && event.pointerId !== current.pointer) cancel();\n };\n const down = (event: PointerEvent) => {\n // A new deliberate activation must work even if a previous browser did not\n // generate the compatibility click suppressed after an accepted drag.\n if (disposed || current || !event.isPrimary || event.button !== 0) return;\n suppressUntil = 0;\n const target = event.target;\n if (!(target instanceof view.Element)) return;\n const control = target.closest(interactive);\n if (control && root.contains(control) && !control.matches('[data-cloudlet-pill]')) return;\n endWheel(false);\n const candidate = options.begin(target, 'pointer');\n if (!candidate) return;\n current = {\n pointer: event.pointerId, candidate, startX: event.clientX, startY: event.clientY, session: null, axis: null,\n captured: false, x: 0, y: 0, lastX: event.clientX, lastY: event.clientY, time: event.timeStamp, velocityX: 0, velocityY: 0,\n };\n };\n function sample(gesture: PointerSwipe, event: PointerEvent, release = false) {\n const elapsed = event.timeStamp - gesture.time;\n for (const axis of ['X', 'Y'] as const) {\n const position = axis === 'X' ? event.clientX : event.clientY;\n const last = gesture[`last${axis}`];\n // A pause before lifting the finger is not a flick.\n if (elapsed > 0 && position !== last) gesture[`velocity${axis}`] = (position - last) / elapsed;\n else if (elapsed > 0 && (!release || elapsed > 80)) gesture[`velocity${axis}`] = 0;\n gesture[`last${axis}`] = position;\n }\n gesture.x = event.clientX - gesture.startX;\n gesture.y = event.clientY - gesture.startY;\n gesture.time = event.timeStamp;\n }\n const move = (event: PointerEvent) => {\n const gesture = current;\n if (!gesture || event.pointerId !== gesture.pointer) return;\n sample(gesture, event);\n if (!gesture.session) {\n const horizontal = Math.abs(gesture.x);\n const vertical = Math.abs(gesture.y);\n if (Math.max(horizontal, vertical) < swipe.intent) return;\n // The first directional intent wins; an axis the target does not own stays native.\n const axis: SwipeAxis = horizontal > vertical ? 'x' : 'y';\n const session = gesture.candidate[axis] ? gesture.candidate.start(axis) : null;\n if (!session || current !== gesture) { cancel(); return; }\n gesture.session = session;\n gesture.axis = axis;\n try {\n root.setPointerCapture(gesture.pointer);\n gesture.captured = true;\n } catch { cancel(); return; }\n root.dataset.dragging = axis;\n // A text selection left in the host would turn the next press into native drag and drop.\n const selection = view.getSelection();\n if (selection?.anchorNode && root.contains(selection.anchorNode)) selection.removeAllRanges();\n }\n suppressUntil = options.now() + swipe.suppressClick;\n if (event.cancelable) event.preventDefault();\n gesture.session.move(gesture.axis === 'x' ? gesture.x : gesture.y);\n };\n const up = (event: PointerEvent) => {\n const gesture = current;\n if (!gesture || event.pointerId !== gesture.pointer) return;\n sample(gesture, event, true);\n finish();\n const x = gesture.axis === 'x';\n gesture.session?.end(x ? gesture.x : gesture.y, x ? gesture.velocityX : gesture.velocityY);\n };\n const cancelled = (event: PointerEvent) => {\n if (current?.pointer === event.pointerId) cancel();\n };\n // Touch input is implicitly captured by the pressed element; moving the capture to\n // the host fires a bubbling lostpointercapture there. Only the host's own loss counts.\n const lost = (event: PointerEvent) => {\n if (event.target === root && current?.captured && current.pointer === event.pointerId) cancel();\n };\n // While the host owns a press, the browser must not start selecting or dragging content.\n const native = (event: Event) => { if (current && (event.type === 'dragstart' || current.session)) event.preventDefault(); };\n const click = (event: MouseEvent) => {\n // Keyboard/AT clicks have detail=0 and remain available during any return.\n if (event.detail === 0 || suppressUntil === 0 || options.now() > suppressUntil) return;\n suppressUntil = 0;\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n const scroll = (event: WheelEvent) => {\n // Pinch zoom (ctrl+wheel) and a running pointer swipe stay untouched.\n if (disposed || current || event.ctrlKey) return;\n const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? root.clientWidth || 1 : 1;\n const dx = event.deltaX * unit;\n const dy = event.deltaY * unit;\n const time = event.timeStamp;\n if (wheel?.spent) {\n // Momentum only decays. A new swipe accelerates or reverses and starts a fresh stream;\n // vertical scrolling stays native.\n const previous = wheel.lastDx;\n const renewed = time - wheel.spentAt > swipe.wheelLock\n && (Math.abs(dx) > Math.abs(previous) * 1.5 + 2 || (dx !== 0 && previous !== 0 && Math.sign(dx) !== Math.sign(previous)));\n if (renewed) endWheel(false);\n else {\n view.clearTimeout(wheel.timer);\n wheel.timer = view.setTimeout(() => endWheel(true), swipe.wheelIdle);\n wheel.lastDx = dx;\n if (Math.abs(dx) >= Math.abs(dy)) event.preventDefault();\n return;\n }\n }\n if (!wheel) {\n const target = event.target;\n const candidate = Math.abs(dx) > Math.abs(dy) && target instanceof view.Element ? options.begin(target, 'wheel') : null;\n const session = candidate?.x ? candidate.start('x') : null;\n if (candidate && !session) candidate.release();\n // A stream that started vertical stays native until it goes idle.\n wheel = { candidate: session ? candidate : null, session, spent: false, spentAt: 0, lastDx: dx, offset: 0, velocity: 0, time, timer: 0 };\n }\n const stream = wheel;\n view.clearTimeout(stream.timer);\n stream.timer = view.setTimeout(() => endWheel(true), swipe.wheelIdle);\n stream.lastDx = dx;\n if (!stream.session) return;\n event.preventDefault();\n // Fingers moving left scroll right (positive deltaX): the content follows the fingers.\n const elapsed = time - stream.time;\n if (elapsed > 0) stream.velocity = -dx / elapsed;\n stream.offset -= dx;\n stream.time = time;\n root.dataset.dragging = 'x';\n stream.session.move(stream.offset);\n // A trackpad swipe commits as soon as its release would (task 17): macOS momentum keeps\n // sending wheel events for a second or more, which otherwise holds the preview in place.\n if (decideRelease(stream.offset, stream.velocity, root.clientWidth || 0, { negative: true, positive: true })) {\n const session = stream.session;\n stream.session = null;\n stream.spent = true;\n stream.spentAt = time;\n delete root.dataset.dragging;\n stream.candidate?.release();\n session.end(stream.offset, stream.velocity);\n }\n };\n const listeners: [EventTarget, string, EventListener, boolean][] = [\n [view, 'pointerdown', secondPointer as EventListener, true],\n [root, 'pointerdown', down as EventListener, false],\n [view, 'pointermove', move as EventListener, true],\n [view, 'pointerup', up as EventListener, true],\n [view, 'pointercancel', cancelled as EventListener, true],\n [root, 'lostpointercapture', lost as EventListener, false],\n [root, 'click', click as EventListener, true],\n [root, 'dragstart', native, false],\n [root, 'selectstart', native, false],\n [root, 'wheel', scroll as EventListener, false],\n [view, 'orientationchange', cancel, false],\n ];\n if (view.screen?.orientation) listeners.push([view.screen.orientation, 'change', cancel, false]);\n for (const [target, type, listener, capture] of listeners) target.addEventListener(type, listener, { capture, passive: false });\n return {\n cancel,\n /** True while a pointer or trackpad swipe (or its intent window) owns the input. */\n get active() { return current !== null || wheel?.session != null; },\n dispose() {\n if (disposed) return;\n disposed = true;\n cancel();\n for (const [target, type, listener, capture] of listeners) target.removeEventListener(type, listener, capture);\n },\n };\n}\n"],"mappings":";;AAEA,IAAM,EAAE,aAAUA;AAMlB,SAAgBC,EAAW,GAAgB,GAAmB,IAAsBC,EAAM,YAAoB;CAG5G,OAFI,CAAC,OAAO,SAASC,CAAM,KAAK,EAAEC,IAAY,KAAW,IAElD,KAAK,KAAKD,CAAM,KAAK,IAAI,KADjB,KAAK,IAAIA,CACa,IAASE,IAAcD,IAAY,MAAMA;AAChF;AAQA,SAAgBE,EAAc,GAAgB,GAAkB,GAC9D,GAAiF;CACjF,IAAMC,IAAOJ,IAAS,IAAI,IAAIA,IAAS,IAAI,KAAK;CAChD,IA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QAAQ,GAC1BmB,EAAQ,IAAInB,EAAO,QAAQA,EAAO,QAAQ;IAC5C;GACF;GAW2C;EAAK;EAC9C;GAACT;GAAM;GAAqBW;GAAQ;EAAK;CAC3C;CACA,AAAIX,EAAK,QAAQ,eAAamC,EAAU,KAAK;EAACnC,EAAK,OAAO;EAAa;EAAUW;EAAQ;CAAK,CAAC;CAC/F,KAAK,IAAM,CAACI,GAAQ0B,GAAMC,GAAUC,MAAYR,GAAW,EAAO,iBAAiBM,GAAMC,GAAU;EAAE;EAAS,SAAS;CAAM,CAAC;CAC9H,OAAO;EACL;EAEA,IAAI,SAAS;GAAE,OAAOxC,MAAY,QAAQC,GAAO,WAAW;EAAM;EAClE,UAAU;GACR,IAAI,IACJ;IACA,AADA,IAAW,IACXQ,EAAO;IACP,KAAK,IAAM,CAACI,GAAQ0B,GAAMC,GAAUC,MAAYR,GAAW,EAAO,oBAAoBM,GAAMC,GAAUC,CAAO;GAFlG;EAGb;CACF;AACF"}
1
+ {"version":3,"file":"gestures.js","names":["MOTION","rubberBand","swipe","offset","dimension","coefficient","decideRelease","sign","allowed","toward","velocity","distance","interactive","createSwipe","view","root","current","wheel","suppressUntil","disposed","finish","gesture","endWheel","stream","commit","cancel","secondPointer","event","down","target","control","candidate","options","sample","elapsed","axis","position","last","release","move","horizontal","vertical","session","selection","up","x","cancelled","lost","native","listeners","unit","dx","dy","time","previous","type","listener","capture"],"sources":["../../src/react/gestures.ts"],"sourcesContent":["import { MOTION } from './motion.js';\n\nconst { swipe } = MOTION;\n\n/**\n * Edge resistance (iOS-style rubber band): the result approaches `dimension`\n * asymptotically and keeps the sign of the raw finger travel.\n */\nexport function rubberBand(offset: number, dimension: number, coefficient: number = swipe.rubberBand): number {\n if (!Number.isFinite(offset) || !(dimension > 0)) return 0;\n const travel = Math.abs(offset);\n return Math.sign(offset) * (1 - 1 / (travel * coefficient / dimension + 1)) * dimension;\n}\n\n/**\n * Release decision along one axis. Returns the sign of the travel when the swipe\n * commits that way (distance past `MOTION.swipe.distance` of `dimension`, or a flick of\n * at least `minDistance` px faster than `velocity` px/ms), 0 when it springs back.\n * A direction without a destination never commits; a flick back always cancels.\n */\nexport function decideRelease(offset: number, velocity: number, dimension: number,\n allowed: { readonly negative: boolean; readonly positive: boolean }): -1 | 0 | 1 {\n const sign = offset > 0 ? 1 : offset < 0 ? -1 : 0;\n if (!sign || !(sign > 0 ? allowed.positive : allowed.negative)) return 0;\n const toward = Number.isFinite(velocity) ? velocity * sign : 0;\n if (toward < -swipe.velocity) return 0;\n const distance = Math.abs(offset);\n if (dimension > 0 && distance > dimension * swipe.distance) return sign;\n return distance >= swipe.minDistance && toward > swipe.velocity ? sign : 0;\n}\n\nexport type SwipeAxis = 'x' | 'y';\n\n/** A started swipe along one axis. Offsets are raw finger travel in CSS px. */\nexport interface SwipeSession {\n readonly move: (offset: number) => void;\n /** Velocity is CSS px/ms along the axis, positive in the direction of positive offsets. */\n readonly end: (offset: number, velocity: number) => void;\n /** Lost capture, a second pointer, orientation change or an external cancel. */\n readonly cancel: () => void;\n}\n\n/** What may start from one pointerdown or wheel stream; `release` ends the intent window. */\nexport interface SwipeCandidate {\n readonly x: boolean;\n readonly y: boolean;\n readonly start: (axis: SwipeAxis) => SwipeSession | null;\n readonly release: () => void;\n}\n\ninterface SwipeOptions {\n /** Null ignores the input; the candidate is released exactly once. */\n readonly begin: (target: Element, input: 'pointer' | 'wheel') => SwipeCandidate | null;\n readonly now: () => number;\n}\n\ninterface PointerSwipe {\n readonly pointer: number;\n readonly candidate: SwipeCandidate;\n readonly startX: number;\n readonly startY: number;\n session: SwipeSession | null;\n axis: SwipeAxis | null;\n captured: boolean;\n x: number;\n y: number;\n lastX: number;\n lastY: number;\n time: number;\n velocityX: number;\n velocityY: number;\n}\n\ninterface WheelSwipe {\n readonly candidate: SwipeCandidate | null;\n session: SwipeSession | null;\n /** Committed early: the rest of the stream (macOS momentum) is swallowed until it goes idle. */\n spent: boolean;\n spentAt: number;\n lastDx: number;\n offset: number;\n velocity: number;\n time: number;\n timer: number;\n}\n\nconst interactive = 'button,a,input,select,textarea,summary,label,[role=\"button\"],[role=\"link\"],[contenteditable]:not([contenteditable=\"false\"])';\n\n/**\n * Pointer and trackpad ownership for one host. The axis is decided by the first\n * `MOTION.swipe.intent` px; an axis the target does not own is given back to the\n * browser (native scroll) for the rest of the gesture. Buttons and links never start\n * a swipe, except the collapsed pill, which is itself the swipe surface. Layout,\n * physics and store commands stay with the caller.\n */\nexport function createSwipe(root: HTMLElement, options: SwipeOptions) {\n const view = root.ownerDocument.defaultView;\n let current: PointerSwipe | null = null;\n let wheel: WheelSwipe | null = null;\n let suppressUntil = 0;\n let disposed = false;\n if (!view) return { cancel() {}, dispose() {}, get active() { return false; } };\n\n function finish(): PointerSwipe | null {\n const gesture = current;\n if (!gesture) return null;\n // Lost capture, store updates and callbacks can be synchronous/reentrant:\n // clear ownership before releasing anything.\n current = null;\n delete root.dataset.dragging;\n if (gesture.captured && root.hasPointerCapture?.(gesture.pointer)) root.releasePointerCapture(gesture.pointer);\n gesture.candidate.release();\n return gesture;\n }\n function endWheel(commit: boolean) {\n const stream = wheel;\n if (!stream) return;\n wheel = null;\n view!.clearTimeout(stream.timer);\n if (stream.session) delete root.dataset.dragging;\n stream.candidate?.release();\n if (commit) stream.session?.end(stream.offset, stream.velocity);\n else stream.session?.cancel();\n }\n const cancel = () => {\n finish()?.session?.cancel();\n endWheel(false);\n };\n const secondPointer = (event: PointerEvent) => {\n if (current && event.pointerId !== current.pointer) cancel();\n };\n const down = (event: PointerEvent) => {\n // A new deliberate activation must work even if a previous browser did not\n // generate the compatibility click suppressed after an accepted drag.\n if (disposed || current || !event.isPrimary || event.button !== 0) return;\n suppressUntil = 0;\n const target = event.target;\n if (!(target instanceof view.Element)) return;\n const control = target.closest(interactive);\n if (control && root.contains(control) && !control.matches('[data-cloudlet-pill]')) return;\n endWheel(false);\n const candidate = options.begin(target, 'pointer');\n if (!candidate) return;\n current = {\n pointer: event.pointerId, candidate, startX: event.clientX, startY: event.clientY, session: null, axis: null,\n captured: false, x: 0, y: 0, lastX: event.clientX, lastY: event.clientY, time: event.timeStamp, velocityX: 0, velocityY: 0,\n };\n };\n function sample(gesture: PointerSwipe, event: PointerEvent, release = false) {\n const elapsed = event.timeStamp - gesture.time;\n for (const axis of ['X', 'Y'] as const) {\n const position = axis === 'X' ? event.clientX : event.clientY;\n const last = gesture[`last${axis}`];\n // A pause before lifting the finger is not a flick.\n if (elapsed > 0 && position !== last) gesture[`velocity${axis}`] = (position - last) / elapsed;\n else if (elapsed > 0 && (!release || elapsed > 80)) gesture[`velocity${axis}`] = 0;\n gesture[`last${axis}`] = position;\n }\n gesture.x = event.clientX - gesture.startX;\n gesture.y = event.clientY - gesture.startY;\n gesture.time = event.timeStamp;\n }\n const move = (event: PointerEvent) => {\n const gesture = current;\n if (!gesture || event.pointerId !== gesture.pointer) return;\n sample(gesture, event);\n if (!gesture.session) {\n const horizontal = Math.abs(gesture.x);\n const vertical = Math.abs(gesture.y);\n if (Math.max(horizontal, vertical) < swipe.intent) return;\n // The first directional intent wins; an axis the target does not own stays native.\n const axis: SwipeAxis = horizontal > vertical ? 'x' : 'y';\n const session = gesture.candidate[axis] ? gesture.candidate.start(axis) : null;\n if (!session || current !== gesture) { cancel(); return; }\n gesture.session = session;\n gesture.axis = axis;\n try {\n root.setPointerCapture(gesture.pointer);\n gesture.captured = true;\n } catch { cancel(); return; }\n root.dataset.dragging = axis;\n // A text selection left in the host would turn the next press into native drag and drop.\n const selection = view.getSelection();\n if (selection?.anchorNode && root.contains(selection.anchorNode)) selection.removeAllRanges();\n }\n suppressUntil = options.now() + swipe.suppressClick;\n if (event.cancelable) event.preventDefault();\n gesture.session.move(gesture.axis === 'x' ? gesture.x : gesture.y);\n };\n const up = (event: PointerEvent) => {\n const gesture = current;\n if (!gesture || event.pointerId !== gesture.pointer) return;\n sample(gesture, event, true);\n finish();\n const x = gesture.axis === 'x';\n gesture.session?.end(x ? gesture.x : gesture.y, x ? gesture.velocityX : gesture.velocityY);\n };\n const cancelled = (event: PointerEvent) => {\n if (current?.pointer === event.pointerId) cancel();\n };\n // Touch input is implicitly captured by the pressed element; moving the capture to\n // the host fires a bubbling lostpointercapture there. Only the host's own loss counts.\n const lost = (event: PointerEvent) => {\n if (event.target === root && current?.captured && current.pointer === event.pointerId) cancel();\n };\n // While the host owns a press, the browser must not start selecting or dragging content.\n const native = (event: Event) => { if (current && (event.type === 'dragstart' || current.session)) event.preventDefault(); };\n const click = (event: MouseEvent) => {\n // Keyboard/AT clicks have detail=0 and remain available during any return.\n if (event.detail === 0 || suppressUntil === 0 || options.now() > suppressUntil) return;\n suppressUntil = 0;\n event.preventDefault();\n event.stopImmediatePropagation();\n };\n const scroll = (event: WheelEvent) => {\n // Pinch zoom (ctrl+wheel) and a running pointer swipe stay untouched.\n if (disposed || current || event.ctrlKey) return;\n const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? root.clientWidth || 1 : 1;\n const dx = event.deltaX * unit;\n const dy = event.deltaY * unit;\n const time = event.timeStamp;\n if (wheel?.spent) {\n // Momentum only decays. A new swipe accelerates or reverses and starts a fresh stream;\n // vertical scrolling stays native.\n const previous = wheel.lastDx;\n const renewed = time - wheel.spentAt > swipe.wheelLock\n && (Math.abs(dx) > Math.abs(previous) * 1.5 + 2 || (dx !== 0 && previous !== 0 && Math.sign(dx) !== Math.sign(previous)));\n if (renewed) endWheel(false);\n else {\n view.clearTimeout(wheel.timer);\n wheel.timer = view.setTimeout(() => endWheel(true), swipe.wheelIdle);\n wheel.lastDx = dx;\n if (Math.abs(dx) >= Math.abs(dy)) event.preventDefault();\n return;\n }\n }\n if (!wheel) {\n const target = event.target;\n const candidate = Math.abs(dx) > Math.abs(dy) && target instanceof view.Element ? options.begin(target, 'wheel') : null;\n const session = candidate?.x ? candidate.start('x') : null;\n if (candidate && !session) candidate.release();\n // A stream that started vertical stays native until it goes idle.\n wheel = { candidate: session ? candidate : null, session, spent: false, spentAt: 0, lastDx: dx, offset: 0, velocity: 0, time, timer: 0 };\n }\n const stream = wheel;\n view.clearTimeout(stream.timer);\n stream.timer = view.setTimeout(() => endWheel(true), swipe.wheelIdle);\n stream.lastDx = dx;\n if (!stream.session) return;\n event.preventDefault();\n // Fingers moving left scroll right (positive deltaX): the content follows the fingers.\n const elapsed = time - stream.time;\n if (elapsed > 0) stream.velocity = -dx / elapsed;\n stream.offset -= dx;\n stream.time = time;\n root.dataset.dragging = 'x';\n stream.session.move(stream.offset);\n // A trackpad swipe commits as soon as its release would: macOS momentum keeps\n // sending wheel events for a second or more, which otherwise holds the preview in place.\n if (decideRelease(stream.offset, stream.velocity, root.clientWidth || 0, { negative: true, positive: true })) {\n const session = stream.session;\n stream.session = null;\n stream.spent = true;\n stream.spentAt = time;\n delete root.dataset.dragging;\n stream.candidate?.release();\n session.end(stream.offset, stream.velocity);\n }\n };\n const listeners: [EventTarget, string, EventListener, boolean][] = [\n [view, 'pointerdown', secondPointer as EventListener, true],\n [root, 'pointerdown', down as EventListener, false],\n [view, 'pointermove', move as EventListener, true],\n [view, 'pointerup', up as EventListener, true],\n [view, 'pointercancel', cancelled as EventListener, true],\n [root, 'lostpointercapture', lost as EventListener, false],\n [root, 'click', click as EventListener, true],\n [root, 'dragstart', native, false],\n [root, 'selectstart', native, false],\n [root, 'wheel', scroll as EventListener, false],\n [view, 'orientationchange', cancel, false],\n ];\n if (view.screen?.orientation) listeners.push([view.screen.orientation, 'change', cancel, false]);\n for (const [target, type, listener, capture] of listeners) target.addEventListener(type, listener, { capture, passive: false });\n return {\n cancel,\n /** True while a pointer or trackpad swipe (or its intent window) owns the input. */\n get active() { return current !== null || wheel?.session != null; },\n dispose() {\n if (disposed) return;\n disposed = true;\n cancel();\n for (const [target, type, listener, capture] of listeners) target.removeEventListener(type, listener, capture);\n },\n };\n}\n"],"mappings":";;AAEA,IAAM,EAAE,aAAUA;AAMlB,SAAgBC,EAAW,GAAgB,GAAmB,IAAsBC,EAAM,YAAoB;CAG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, e.radius), r / 2, i / 2), o = Ve(), s = o ? H.height - i : 0;
134
134
  t.shell && (t.shell.opacity = String(O(e.opacity)), t.shell.transform = n ? "none" : `translate(${k(e.dragX)}, ${k(e.y + e.dragY)}) scale(${e.scale})`);
135
135
  let c = ce.current;
136
- if (c && (c.setAttribute("width", String(r)), c.setAttribute("height", String(i)), le.current?.setAttribute("d", m(r, i, a))), t.bg && (t.bg.borderRadius = k(a)), t.clip && (t.clip.clipPath = `path("${m(r, i, a, (H.width - r) / 2, s)}")`), t.badge) {
136
+ if (c && (c.setAttribute("width", String(r)), c.setAttribute("height", String(i)), le.current?.setAttribute("d", m(r, i, a))), t.bg && (t.bg.borderRadius = k(a), t.bg.top = "0px", t.bg.bottom = "auto", t.bg.transform = `translateX(-50%) translateY(${k(s)})`), t.clip && (t.clip.clipPath = `path("${m(r, i, a, (H.width - r) / 2, s)}")`), t.badge) {
137
137
  let i = n ? 1 : z.badge.scale + (1 - z.badge.scale) * e.badge, a = (r / 2 - 10) * (Ae ? -1 : 1);
138
138
  t.badge.opacity = String(O(e.badge)), t.badge.transform = `translate(calc(${k(a)} - 50%), ${o ? "6px" : "-6px"}) scale(${i})`;
139
139
  }