effect-browser 0.3.0-beta.22 → 0.3.0-beta.24

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 (138) hide show
  1. package/README.md +124 -5
  2. package/dist/ActionPort.d.mts +1 -1
  3. package/dist/ActionPort.mjs +1 -1
  4. package/dist/{Browser-Cq2K1FEA.mjs → Browser-CAQFhTkM.mjs} +561 -334
  5. package/dist/Browser-CAQFhTkM.mjs.map +1 -0
  6. package/dist/{Browser-wZhwZSlG.d.mts → Browser-DGR6ZEYo.d.mts} +9 -3
  7. package/dist/Browser.d.mts +1 -1
  8. package/dist/Browser.mjs +1 -1
  9. package/dist/{BrowserEvent-lLqJ3GJS.d.mts → BrowserEvent-C2p-NwuU.d.mts} +30 -6
  10. package/dist/BrowserEvent.d.mts +2 -2
  11. package/dist/BrowserEvent.mjs +20 -1
  12. package/dist/BrowserEvent.mjs.map +1 -1
  13. package/dist/{Change-Ba7INmay.d.mts → Change-CxT1mp2e.d.mts} +13 -2
  14. package/dist/Change.d.mts +1 -1
  15. package/dist/Change.mjs +7 -1
  16. package/dist/Change.mjs.map +1 -1
  17. package/dist/Clock-Du5nP-nK.d.mts +57 -0
  18. package/dist/Clock.d.mts +2 -57
  19. package/dist/Layout.d.mts +2 -0
  20. package/dist/Layout.mjs +81 -0
  21. package/dist/Layout.mjs.map +1 -0
  22. package/dist/Matching-MtcWZ_hA.d.mts +266 -0
  23. package/dist/Matching.d.mts +2 -37
  24. package/dist/Matching.mjs +22 -17
  25. package/dist/Matching.mjs.map +1 -1
  26. package/dist/Overlay-CoGw5tL_.d.mts +27 -0
  27. package/dist/Overlay.d.mts +2 -0
  28. package/dist/Overlay.mjs +30 -0
  29. package/dist/Overlay.mjs.map +1 -0
  30. package/dist/{Page-BF5izr8R.mjs → Page-BaAOshxo.mjs} +3 -1
  31. package/dist/Page-BaAOshxo.mjs.map +1 -0
  32. package/dist/{Page-CvsOEorc.d.mts → Page-CLzh5E9w.d.mts} +158 -6
  33. package/dist/Page.d.mts +2 -2
  34. package/dist/Page.mjs +1 -1
  35. package/dist/PageTime-68UPUZpZ.d.mts +29 -0
  36. package/dist/PageTime.d.mts +2 -0
  37. package/dist/PageTime.mjs +7 -0
  38. package/dist/PageTime.mjs.map +1 -0
  39. package/dist/Pose-2qqGzPvb.d.mts +32 -0
  40. package/dist/Pose.d.mts +2 -0
  41. package/dist/Pose.mjs +44 -0
  42. package/dist/Pose.mjs.map +1 -0
  43. package/dist/Site.d.mts +714 -0
  44. package/dist/Site.mjs +102 -0
  45. package/dist/Site.mjs.map +1 -0
  46. package/dist/{Stillness-CNlvayIo.mjs → Stillness-BwP0RdI4.mjs} +27 -6
  47. package/dist/Stillness-BwP0RdI4.mjs.map +1 -0
  48. package/dist/{Style-AO4V7Czt.mjs → Style-T3ezDYLI.mjs} +25 -2
  49. package/dist/{Style-AO4V7Czt.mjs.map → Style-T3ezDYLI.mjs.map} +1 -1
  50. package/dist/Style.d.mts +15 -2
  51. package/dist/Style.mjs +2 -2
  52. package/dist/Url-B7P-TWwL.d.mts +26 -0
  53. package/dist/Url.d.mts +2 -26
  54. package/dist/{Window-CMddGMt1.d.mts → Window-BDa8MtNP.d.mts} +4 -4
  55. package/dist/Window.d.mts +1 -1
  56. package/dist/{connection-BTeO0Hiz.mjs → connection-C_jWYIwe.mjs} +2 -2
  57. package/dist/{connection-BTeO0Hiz.mjs.map → connection-C_jWYIwe.mjs.map} +1 -1
  58. package/dist/{connection-2KHI4_KN.d.mts → connection-Db-YtlbE.d.mts} +2 -2
  59. package/dist/film/Film.d.mts +265 -0
  60. package/dist/film/Film.mjs +246 -0
  61. package/dist/film/Film.mjs.map +1 -0
  62. package/dist/fold.inpage-CyVZQHZL.d.mts +49 -0
  63. package/dist/index.d.mts +11 -8
  64. package/dist/index.mjs +8 -4
  65. package/dist/moment/Moment.d.mts +5 -5
  66. package/dist/plan/index.d.mts +2 -2
  67. package/dist/plan/index.mjs +2 -2
  68. package/dist/policy/Policy.d.mts +1 -1
  69. package/dist/policy/Policy.mjs +1 -1
  70. package/dist/pose.inpage-CLq7Mfdr.mjs +2042 -0
  71. package/dist/pose.inpage-CLq7Mfdr.mjs.map +1 -0
  72. package/dist/presentation/Presentation.d.mts +8 -1
  73. package/dist/presentation/Presentation.mjs +3 -1
  74. package/dist/presentation/Presentation.mjs.map +1 -1
  75. package/dist/presentation/Stage.d.mts +1 -1
  76. package/dist/providers/Cdp.d.mts +2 -2
  77. package/dist/providers/Cdp.mjs +1 -1
  78. package/dist/providers/Chromium.d.mts +1 -1
  79. package/dist/providers/Chromium.mjs +1 -1
  80. package/dist/stillness/Stillness.d.mts +1 -1
  81. package/dist/stillness/Stillness.mjs +1 -1
  82. package/dist/supervisor/Supervisor.mjs +3 -1
  83. package/dist/supervisor/Supervisor.mjs.map +1 -1
  84. package/dist/testing/index.d.mts +4 -30
  85. package/dist/testing/index.mjs +8 -2
  86. package/dist/testing/index.mjs.map +1 -1
  87. package/dist/workerd/Cdp.d.mts +2 -2
  88. package/dist/workerd/Cdp.mjs +1 -1
  89. package/package.json +35 -5
  90. package/src/Browser.ts +11 -6
  91. package/src/BrowserEvent.ts +19 -0
  92. package/src/Change.ts +7 -1
  93. package/src/Layout.ts +116 -0
  94. package/src/Matching.ts +24 -15
  95. package/src/Overlay.ts +37 -0
  96. package/src/Page.ts +45 -0
  97. package/src/PageTime.ts +47 -0
  98. package/src/Pose.ts +50 -0
  99. package/src/Site.ts +124 -0
  100. package/src/Style.ts +36 -0
  101. package/src/film/Film.ts +384 -0
  102. package/src/index.ts +4 -0
  103. package/src/internal/input/perform.ts +31 -3
  104. package/src/internal/input/pointer.ts +7 -4
  105. package/src/internal/input/targets.ts +1 -1
  106. package/src/internal/page/bridge.ts +65 -33
  107. package/src/internal/page/clock.inpage.ts +306 -0
  108. package/src/internal/page/compose.inpage.ts +101 -0
  109. package/src/internal/page/context.ts +2 -0
  110. package/src/internal/page/identity.ts +6 -5
  111. package/src/internal/page/overlay.inpage.ts +96 -0
  112. package/src/internal/page/overlay.ts +89 -0
  113. package/src/internal/page/page.ts +12 -0
  114. package/src/internal/page/pose.inpage.ts +200 -0
  115. package/src/internal/page/pose.ts +80 -0
  116. package/src/internal/page/time.inpage.ts +49 -0
  117. package/src/internal/page/time.ts +122 -0
  118. package/src/internal/page/viewport.ts +3 -2
  119. package/src/internal/pictures/pictures.ts +93 -32
  120. package/src/internal/reading/layout.inpage.ts +193 -0
  121. package/src/internal/reading/layout.ts +101 -0
  122. package/src/internal/reading/names.inpage.ts +15 -0
  123. package/src/internal/reading/outline.inpage.ts +2 -18
  124. package/src/internal/reading/reading.ts +22 -2
  125. package/src/internal/reading/ready.inpage.ts +18 -23
  126. package/src/internal/reading/ready.ts +23 -3
  127. package/src/internal/reading/text.inpage.ts +1 -14
  128. package/src/internal/timeline/changes.inpage.ts +7 -15
  129. package/src/internal/timeline/changes.ts +14 -1
  130. package/src/internal/timeline/record.inpage.ts +15 -6
  131. package/src/presentation/Presentation.ts +13 -0
  132. package/src/stillness/Pixels.ts +26 -0
  133. package/src/stillness/Stillness.ts +30 -5
  134. package/src/supervisor/runtime.ts +5 -1
  135. package/src/testing/page.ts +5 -0
  136. package/dist/Browser-Cq2K1FEA.mjs.map +0 -1
  137. package/dist/Page-BF5izr8R.mjs.map +0 -1
  138. package/dist/Stillness-CNlvayIo.mjs.map +0 -1
@@ -0,0 +1,96 @@
1
+ /**
2
+ * In the page: the library's overlay, a layer over the page that it draws a caller's SVG into,
3
+ * knowing nothing of what it shows. The layer is a closed shadow root on a host fixed over the
4
+ * viewport, above the page's own layers, that takes no pointer events, so input passes through to
5
+ * the page, and undoes the zoom the page sets on its root. Its styles are set through the CSSOM,
6
+ * which a strict `style-src` allows, and with priority, so the page's styles cannot reach it. The
7
+ * host is the library's own (see `names.inpage.ts`), so no reader reads it; the page's scripts can
8
+ * find the host, never what it holds. A site that owns its page can `mount` a layer of its own,
9
+ * whose root it renders into and whose parts may take the pointer. See `names.inpage.ts` for what a
10
+ * page-side part may use.
11
+ */
12
+ import type { Names } from "../reading/names.inpage.ts";
13
+
14
+ export const overlay = (names: Names) => {
15
+ const svgNamespace = "http://www.w3.org/2000/svg";
16
+ let host: HTMLElement | undefined;
17
+ let root: ShadowRoot | undefined;
18
+
19
+ const mount = (): ShadowRoot => {
20
+ if (host === undefined || root === undefined) {
21
+ host = document.createElement("div");
22
+ root = host.attachShadow({ mode: "closed" });
23
+ names.adopt(host);
24
+ const sheet = new CSSStyleSheet();
25
+
26
+ sheet.replaceSync(
27
+ "svg { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible }",
28
+ );
29
+ root.adoptedStyleSheets = [sheet];
30
+ }
31
+ const zoom = Number(getComputedStyle(document.documentElement).zoom) || 1;
32
+
33
+ for (const [name, value] of Object.entries({
34
+ all: "initial",
35
+ display: "block",
36
+ position: "fixed",
37
+ left: "0",
38
+ top: "0",
39
+ width: "100vw",
40
+ height: "100vh",
41
+ "pointer-events": "none",
42
+ "z-index": "2147483647",
43
+ contain: "strict",
44
+ zoom: String(1 / zoom),
45
+ }))
46
+ host.style.setProperty(name, value, "important");
47
+ if (host.parentNode !== document.documentElement) document.documentElement.append(host);
48
+
49
+ return root;
50
+ };
51
+
52
+ // The drawing's top-level parts, by their boxes in viewport CSS pixels; at most 32.
53
+ const boxes = (drawing: Element) =>
54
+ Array.from(drawing.children)
55
+ .slice(0, 32)
56
+ .map((part) => {
57
+ const { x, y, width, height } = part.getBoundingClientRect();
58
+
59
+ return { x, y, width, height };
60
+ })
61
+ .filter((box) => box.width > 0 && box.height > 0);
62
+
63
+ /**
64
+ * Draw an SVG document over the viewport, in place of what was drawn, or take the layer away
65
+ * with null. Says where the drawing's parts are. Its scripts and handlers are dropped.
66
+ */
67
+ const draw = (markup: string | null) => {
68
+ if (markup === null) {
69
+ host?.remove();
70
+
71
+ return [];
72
+ }
73
+ const parsed = new DOMParser().parseFromString(markup, "image/svg+xml");
74
+ const drawing = parsed.documentElement;
75
+
76
+ if (
77
+ parsed.getElementsByTagName("parsererror").length > 0 ||
78
+ drawing.namespaceURI !== svgNamespace ||
79
+ drawing.localName !== "svg"
80
+ )
81
+ throw new Error("the overlay's markup is not an SVG document");
82
+ for (const script of Array.from(drawing.getElementsByTagName("script"))) script.remove();
83
+ for (const element of [drawing, ...Array.from(drawing.querySelectorAll("*"))])
84
+ for (const attribute of Array.from(element.attributes))
85
+ if (/^on/i.test(attribute.name)) element.removeAttribute(attribute.name);
86
+ const shown = document.importNode(drawing, true);
87
+
88
+ mount().replaceChildren(shown);
89
+
90
+ return boxes(shown);
91
+ };
92
+
93
+ return { draw, mount };
94
+ };
95
+
96
+ export type Overlay = ReturnType<typeof overlay>;
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The page's overlay: one lease at a time, each drawing one call to the page, in turn after the
3
+ * actions asked before it, never two at once. Each new document gets what was last drawn once it
4
+ * has loaded; the lease's scope takes the layer away.
5
+ */
6
+ import { Duration, Effect, Schedule, Schema, type Scope, Semaphore } from "effect";
7
+
8
+ import type { BrowserError } from "../../BrowserError.ts";
9
+ import { Box } from "../../BrowserEvent.ts";
10
+ import type { Content, Overlay } from "../../Overlay.ts";
11
+ import { type Bridge, scriptCall } from "./bridge.ts";
12
+ import { decodeWith, type PageContext, refuse } from "./context.ts";
13
+
14
+ const Drawn = Schema.Array(Box);
15
+
16
+ export const make = (page: PageContext, bridge: Bridge) => {
17
+ const { lane, owned, span, within } = page;
18
+ const turns = Semaphore.makeUnsafe(1);
19
+ let open = false;
20
+ // What the layer shows, as markup, and where its parts were last drawn.
21
+ let shown: string | null = null;
22
+ let drawn: ReadonlyArray<Box> = [];
23
+
24
+ // What a call to the page drew, wherever it was drawn from.
25
+ const record = (markup: string | null, boxes: ReadonlyArray<Box>) => {
26
+ shown = markup;
27
+ drawn = boxes;
28
+ page.noteInput();
29
+ };
30
+
31
+ const send = (markup: string | null) =>
32
+ turns.withPermit(
33
+ lane.read("overlay")(
34
+ bridge.evaluate("overlay", scriptCall("overlay", markup)).pipe(
35
+ Effect.flatMap(decodeWith("overlay", Drawn)),
36
+ Effect.tap((boxes) => Effect.sync(() => record(markup, boxes))),
37
+ within("overlay"),
38
+ ),
39
+ ),
40
+ );
41
+
42
+ const draw = (content: Content) =>
43
+ send(content._tag === "Svg" ? content.markup : null).pipe(span("Overlay.draw"), owned);
44
+
45
+ // Once the document after `document` has parsed, it is drawn with what was shown. A redraw that
46
+ // fails leaves the layer off until the next draw, which reports its own failure.
47
+ const redraw = (document: number) =>
48
+ bridge.waitForDocument(document).pipe(
49
+ Effect.andThen(
50
+ Effect.void.pipe(
51
+ Effect.repeat({
52
+ schedule: Schedule.spaced(Duration.millis(50)),
53
+ until: () => bridge.loaded() !== undefined,
54
+ }),
55
+ within("overlay", page.settings.navigationTimeout),
56
+ ),
57
+ ),
58
+ Effect.andThen(Effect.suspend(() => (shown === null ? Effect.void : send(shown)))),
59
+ Effect.ignore,
60
+ );
61
+
62
+ const lease: Effect.Effect<Overlay, BrowserError, Scope.Scope> = Effect.gen(function* () {
63
+ if (open) return yield* refuse("overlay", "the page has an overlay already");
64
+ open = true;
65
+ yield* Effect.addFinalizer(() =>
66
+ Effect.suspend(() => {
67
+ open = false;
68
+
69
+ return shown === null ? Effect.void : send(null).pipe(Effect.ignore);
70
+ }),
71
+ );
72
+ yield* Effect.forkScoped(
73
+ Effect.suspend(() => redraw(bridge.frameTag().document)).pipe(Effect.forever),
74
+ );
75
+
76
+ return { draw };
77
+ });
78
+
79
+ return {
80
+ lease,
81
+ drawn: () => (shown === null ? undefined : drawn),
82
+ open: () => open,
83
+ record,
84
+ /** Run a call that draws in the overlay's turn, so no other drawing overtakes it. */
85
+ turn: <A, E, R>(effect: Effect.Effect<A, E, R>) => turns.withPermit(effect),
86
+ };
87
+ };
88
+
89
+ export type Overlays = ReturnType<typeof make>;
@@ -13,6 +13,7 @@ import { type Page, State } from "../../Page.ts";
13
13
  import * as Url from "../../Url.ts";
14
14
  import * as Actions from "../input/actions.ts";
15
15
  import * as Pictures from "../pictures/pictures.ts";
16
+ import * as Layouts from "../reading/layout.ts";
16
17
  import * as Reading from "../reading/reading.ts";
17
18
  import * as Ready from "../reading/ready.ts";
18
19
  import * as Changes from "../timeline/changes.ts";
@@ -20,7 +21,10 @@ import * as Window from "../timeline/window.ts";
20
21
  import * as Bridge from "./bridge.ts";
21
22
  import * as Context from "./context.ts";
22
23
  import * as Navigation from "./navigation.ts";
24
+ import * as Overlay from "./overlay.ts";
25
+ import * as Poses from "./pose.ts";
23
26
  import * as Scripts from "./scripts.ts";
27
+ import * as Time from "./time.ts";
24
28
  import * as Viewport from "./viewport.ts";
25
29
 
26
30
  export const make = Effect.fnUntraced(function* (options: Context.MakeOptions) {
@@ -34,6 +38,8 @@ export const make = Effect.fnUntraced(function* (options: Context.MakeOptions) {
34
38
  const navigation = Navigation.make(page, input.perform, input.preparePolicy);
35
39
  const { capture } = pictures;
36
40
  const changes = Changes.make(page, bridge, pictures.estimate);
41
+ const overlay = Overlay.make(page, bridge);
42
+ const poses = Poses.make(page, bridge);
37
43
  const titles = lane.shared<string>("title", true);
38
44
  const viewports = lane.shared<Effect.Success<Page["viewport"]>>("viewport", true);
39
45
 
@@ -52,6 +58,7 @@ export const make = Effect.fnUntraced(function* (options: Context.MakeOptions) {
52
58
  committedAt: Number.isFinite(committedAt) ? committedAt : undefined,
53
59
  load: bridge.loaded(),
54
60
  frame: Option.getOrUndefined(latest),
61
+ overlay: overlay.drawn(),
55
62
  text: reading.viewedSince(committedAt),
56
63
  });
57
64
  });
@@ -108,11 +115,16 @@ export const make = Effect.fnUntraced(function* (options: Context.MakeOptions) {
108
115
  screenshot: pictures.screenshot,
109
116
  frame: pictures.frame,
110
117
  zoom: pictures.zoom,
118
+ paint: pictures.paint,
111
119
  viewport: viewports("", viewport.viewportFor("viewport").pipe(within("viewport"))).pipe(
112
120
  span("Page.viewport"),
113
121
  owned,
114
122
  ),
115
123
  find: reading.find,
124
+ layout: Layouts.make(page, bridge),
125
+ overlay: overlay.lease,
126
+ poses: poses.lease,
127
+ hold: Time.make(page, bridge, overlay, poses).hold,
116
128
  text: reading.text,
117
129
  changes,
118
130
  window: Window.make(page, changes, capture.recent),
@@ -0,0 +1,200 @@
1
+ /**
2
+ * In the page: element poses. A pose moves, turns and scales one of the page's own elements about
3
+ * a point in the viewport, through the CSS `translate`, `rotate` and `scale` properties, which
4
+ * apply around the element's `transform`, so the page's own transform still holds beneath. Each is
5
+ * a Web Animation with no end and one value: it sets no attribute and starts none of the page's
6
+ * transitions, the page clock's holding leaves its value as it is, and `ready` waits only for
7
+ * animations that end. Taking poses off cancels them. See `names.inpage.ts` for what a page-side
8
+ * part may use.
9
+ */
10
+ import type { Pose } from "../../Pose.ts";
11
+ import type { Names } from "../reading/names.inpage.ts";
12
+
13
+ export interface PoseRequest {
14
+ readonly ref: string;
15
+ readonly dx: number;
16
+ readonly dy: number;
17
+ readonly sx: number;
18
+ readonly sy: number;
19
+ /** Degrees, clockwise. */
20
+ readonly rotate: number;
21
+ /** In the viewport, or null for the middle of where the page draws it. */
22
+ readonly origin: { readonly x: number; readonly y: number } | null;
23
+ }
24
+
25
+ /** A pose as the page takes it, each part left out made the one that changes nothing. */
26
+ export const poseRequest = (pose: Pose): PoseRequest => ({
27
+ ref: pose.ref,
28
+ dx: pose.dx ?? 0,
29
+ dy: pose.dy ?? 0,
30
+ sx: pose.sx ?? 1,
31
+ sy: pose.sy ?? 1,
32
+ rotate: pose.rotate ?? 0,
33
+ origin: pose.origin ?? null,
34
+ });
35
+
36
+ type Prepared =
37
+ | { readonly stale: string }
38
+ | { readonly invalid: string }
39
+ | { readonly apply: () => void };
40
+
41
+ interface Applied {
42
+ readonly x: number;
43
+ readonly y: number;
44
+ readonly rotate: number;
45
+ readonly sx: number;
46
+ readonly sy: number;
47
+ }
48
+
49
+ export const pose = (names: Names) => {
50
+ const posed = new Map<
51
+ HTMLElement,
52
+ { animation: Animation; effect: KeyframeEffect; applied: Applied }
53
+ >();
54
+
55
+ // Elements of a same-origin frame come from another realm, so a property decides, not instanceof.
56
+ const isHtml = (element: Element): element is HTMLElement => "offsetWidth" in element;
57
+
58
+ // Where the element's border box is laid out in the viewport, and its transform origin there,
59
+ // from where it is drawn: its corners, about the origin, through the page's transform and then
60
+ // the pose last set. Exact unless an ancestor is transformed.
61
+ const laidOut = (element: HTMLElement, applied: Applied | undefined) => {
62
+ const style = getComputedStyle(element);
63
+ const [cx = 0, cy = 0] = style.transformOrigin.split(" ").map(Number.parseFloat);
64
+ const own = style.transform === "none" ? new DOMMatrix() : new DOMMatrix(style.transform);
65
+
66
+ const whole =
67
+ applied === undefined
68
+ ? own
69
+ : new DOMMatrix()
70
+ .translate(applied.x, applied.y)
71
+ .rotate(applied.rotate)
72
+ .scale(applied.sx, applied.sy)
73
+ .multiply(own);
74
+
75
+ const drawn = element.getBoundingClientRect();
76
+ const plain = whole.isIdentity;
77
+ const width = plain ? drawn.width : element.offsetWidth;
78
+ const height = plain ? drawn.height : element.offsetHeight;
79
+ let left = Infinity;
80
+ let top = Infinity;
81
+
82
+ for (const [x, y] of [
83
+ [0, 0],
84
+ [width, 0],
85
+ [0, height],
86
+ [width, height],
87
+ ] as const) {
88
+ const corner = whole.transformPoint({ x: x - cx, y: y - cy });
89
+
90
+ left = Math.min(left, corner.x + cx);
91
+ top = Math.min(top, corner.y + cy);
92
+ }
93
+ const origin = { x: drawn.x - left + cx, y: drawn.y - top + cy };
94
+ // The middle of the box as the page's own transform draws it.
95
+ const middle = own.transformPoint({ x: width / 2 - cx, y: height / 2 - cy });
96
+
97
+ return { origin, middle: { x: origin.x + middle.x, y: origin.y + middle.y } };
98
+ };
99
+
100
+ const apply = (element: HTMLElement, request: PoseRequest) => {
101
+ const known = posed.get(element);
102
+ const { origin, middle } = laidOut(element, known?.applied);
103
+ const about = request.origin ?? middle;
104
+ const away = { x: about.x - origin.x, y: about.y - origin.y };
105
+
106
+ const turned = new DOMMatrix()
107
+ .rotate(request.rotate)
108
+ .scale(request.sx, request.sy)
109
+ .transformPoint(away);
110
+
111
+ // Turning and scaling about the element's own origin, then moving it by the difference, turns
112
+ // and scales it about `about`.
113
+ const applied = {
114
+ x: request.dx + away.x - turned.x,
115
+ y: request.dy + away.y - turned.y,
116
+ rotate: request.rotate,
117
+ sx: request.sx,
118
+ sy: request.sy,
119
+ };
120
+
121
+ const frame = {
122
+ translate: `${applied.x}px ${applied.y}px`,
123
+ rotate: `${applied.rotate}deg`,
124
+ scale: `${applied.sx} ${applied.sy}`,
125
+ };
126
+
127
+ if (known === undefined) {
128
+ const effect = new KeyframeEffect(element, [frame, frame], {
129
+ duration: Infinity,
130
+ fill: "both",
131
+ });
132
+
133
+ const animation = new Animation(effect, document.timeline);
134
+
135
+ animation.play();
136
+ posed.set(element, { animation, effect, applied });
137
+ } else {
138
+ known.effect.setKeyframes([frame, frame]);
139
+ known.applied = applied;
140
+ }
141
+ };
142
+
143
+ const takeOff = (element: HTMLElement) => {
144
+ posed.get(element)?.animation.cancel();
145
+ posed.delete(element);
146
+ };
147
+
148
+ /**
149
+ * The elements `requests` name, or the first that names none in the current document, or one
150
+ * that is not an HTML element; then, to apply them, a function that poses them and takes poses
151
+ * off every other element.
152
+ */
153
+ const prepare = (requests: ReadonlyArray<PoseRequest>): Prepared => {
154
+ const elements: Array<HTMLElement> = [];
155
+
156
+ for (const request of requests) {
157
+ const element = names.lookup(request.ref);
158
+
159
+ const { dx, dy, sx, sy, rotate, origin } = request;
160
+
161
+ if (element === undefined) return { stale: request.ref };
162
+ if (!isHtml(element)) return { invalid: `${request.ref} is not an HTML element` };
163
+ if (![dx, dy, sx, sy, rotate, origin?.x ?? 0, origin?.y ?? 0].every(Number.isFinite))
164
+ return { invalid: `${request.ref}'s pose is not finite numbers` };
165
+ elements.push(element);
166
+ }
167
+
168
+ return {
169
+ apply: () => {
170
+ for (const element of Array.from(posed.keys()))
171
+ if (!elements.includes(element)) takeOff(element);
172
+ requests.forEach((request, index) => {
173
+ const element = elements[index];
174
+
175
+ if (element !== undefined) apply(element, request);
176
+ });
177
+ },
178
+ };
179
+ };
180
+
181
+ const set = (requests: ReadonlyArray<PoseRequest>) => {
182
+ const prepared = prepare(requests);
183
+
184
+ if ("apply" in prepared) {
185
+ prepared.apply();
186
+
187
+ return {};
188
+ }
189
+
190
+ return prepared;
191
+ };
192
+
193
+ const clear = () => {
194
+ for (const element of Array.from(posed.keys())) takeOff(element);
195
+ };
196
+
197
+ return { prepare, set, clear };
198
+ };
199
+
200
+ export type Posing = ReturnType<typeof pose>;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The page's poses: one lease at a time, each `set` one call to the page in the page's turn, as an
3
+ * action takes it, so no action resolves a target that a pose then moves. The lease's scope takes
4
+ * every pose off. See `Pose`.
5
+ */
6
+ import { Effect, Schema, type Scope } from "effect";
7
+
8
+ import { type BrowserError, StaleRef } from "../../BrowserError.ts";
9
+ import { Pose, type Poses } from "../../Pose.ts";
10
+ import { type Bridge, scriptCall } from "./bridge.ts";
11
+ import { decodeWith, failWith, type PageContext, refuse } from "./context.ts";
12
+ import { poseRequest } from "./pose.inpage.ts";
13
+
14
+ /** What posing answered: nothing, or the ref it could not pose and why. */
15
+ export const Posed = Schema.Struct({
16
+ stale: Schema.optional(Schema.String),
17
+ invalid: Schema.optional(Schema.String),
18
+ });
19
+
20
+ export const make = (page: PageContext, bridge: Bridge) => {
21
+ const { lane, owned, span, within } = page;
22
+ let open = false;
23
+
24
+ /** The page's requests for `poses`, each part left out made the one that changes nothing. */
25
+ const requests = Effect.fnUntraced(function* (operation: string, poses: ReadonlyArray<Pose>) {
26
+ const decoded = yield* Schema.decodeEffect(Schema.Array(Pose))(poses).pipe(
27
+ Effect.catch(() => refuse(operation, "each pose is a ref and finite numbers")),
28
+ );
29
+
30
+ if (decoded.length > 256)
31
+ return yield* refuse(operation, "at most 256 elements are posed at once");
32
+
33
+ return decoded.map(poseRequest);
34
+ });
35
+
36
+ /** Fail as the page's answer says, if it posed nothing. */
37
+ const answered = (operation: string, posed: typeof Posed.Type) =>
38
+ posed.stale !== undefined
39
+ ? failWith(operation, new StaleRef({ ref: posed.stale }))
40
+ : posed.invalid !== undefined
41
+ ? refuse(operation, posed.invalid)
42
+ : Effect.void;
43
+
44
+ const send = (operation: string, script: string) =>
45
+ lane.write(
46
+ operation,
47
+ page.settings.actionTimeout,
48
+ )(
49
+ bridge.evaluate(operation, script).pipe(
50
+ Effect.flatMap(decodeWith(operation, Posed)),
51
+ Effect.flatMap((posed) => answered(operation, posed)),
52
+ Effect.tap(() => Effect.sync(page.noteInput)),
53
+ within(operation),
54
+ ),
55
+ );
56
+
57
+ const set = (poses: ReadonlyArray<Pose>) =>
58
+ requests("pose", poses).pipe(
59
+ Effect.flatMap((made) => send("pose", scriptCall("pose", made))),
60
+ span("Poses.set"),
61
+ owned,
62
+ );
63
+
64
+ const lease: Effect.Effect<Poses, BrowserError, Scope.Scope> = Effect.gen(function* () {
65
+ if (open) return yield* refuse("pose", "the page's poses are open already");
66
+ open = true;
67
+ yield* Effect.addFinalizer(() =>
68
+ send("pose", scriptCall("unpose")).pipe(
69
+ Effect.ignore,
70
+ Effect.ensuring(Effect.sync(() => (open = false))),
71
+ ),
72
+ );
73
+
74
+ return { set };
75
+ });
76
+
77
+ return { lease, open: () => open, requests, answered };
78
+ };
79
+
80
+ export type Posing = ReturnType<typeof make>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * In the page: one step of what a held page shows, in one call. The document is scrolled first,
3
+ * then the page clock in the main world is told what to do, so the page's own handlers see the
4
+ * scroll as its time moves, then elements are posed and the overlay is drawn. A pose naming an
5
+ * element the document no longer has is found before any of it, and the step does nothing. The
6
+ * clock hears an event only it and the
7
+ * library know the name of (see `clock.inpage.ts`), and acknowledges it. See `names.inpage.ts` for
8
+ * what a page-side part may use.
9
+ */
10
+ import type { Overlay } from "./overlay.inpage.ts";
11
+ import type { PoseRequest, Posing } from "./pose.inpage.ts";
12
+
13
+ export interface StepRequest {
14
+ /** The page clock's event name. */
15
+ readonly clock: string;
16
+ readonly op: "hold" | "advance" | "release";
17
+ readonly by: number;
18
+ /** Where to scroll the document to, in CSS pixels down it, or null to leave it. */
19
+ readonly scroll: number | null;
20
+ /** What the overlay shows, null for nothing; left out, the overlay is left alone. */
21
+ readonly markup?: string | null | undefined;
22
+ /** The elements to pose, and no others; left out, poses are left alone. */
23
+ readonly poses?: ReadonlyArray<PoseRequest> | undefined;
24
+ }
25
+
26
+ export const time = (overlaid: Overlay, posing: Posing) => {
27
+ const step = (request: StepRequest) => {
28
+ const posed = request.poses === undefined ? undefined : posing.prepare(request.poses);
29
+
30
+ if (posed !== undefined && !("apply" in posed))
31
+ return { told: false, drawn: null, scroll: { x: scrollX, y: scrollY }, ...posed };
32
+ if (request.scroll !== null)
33
+ scrollTo({ left: scrollX, top: request.scroll, behavior: "instant" });
34
+ const detail = { op: request.op, by: request.by };
35
+
36
+ const told = !document.dispatchEvent(
37
+ new CustomEvent(request.clock, { detail, cancelable: true }),
38
+ );
39
+
40
+ posed?.apply();
41
+ const drawn = request.markup === undefined ? null : overlaid.draw(request.markup);
42
+
43
+ return { told, drawn, scroll: { x: scrollX, y: scrollY } };
44
+ };
45
+
46
+ return { step };
47
+ };
48
+
49
+ export type Time = ReturnType<typeof time>;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Holding a page's time: one hold at a time, each step one call to the page that takes the page
3
+ * to itself, as an action does, so no read sees a step half made. See `PageTime`.
4
+ */
5
+ import { Duration, Effect, Option, Schema, type Scope } from "effect";
6
+
7
+ import { type BrowserError, NotActionable } from "../../BrowserError.ts";
8
+ import { Box } from "../../BrowserEvent.ts";
9
+ import { Point } from "../../Geometry.ts";
10
+ import type { Held, Step } from "../../PageTime.ts";
11
+ import { type Bridge, scriptCall } from "./bridge.ts";
12
+ import { decodeWith, failWith, type PageContext, refuse } from "./context.ts";
13
+ import type { Overlays } from "./overlay.ts";
14
+ import { Posed, type Posing } from "./pose.ts";
15
+ import type { StepRequest } from "./time.inpage.ts";
16
+
17
+ const Stepped = Schema.Struct({
18
+ ...Posed.fields,
19
+ told: Schema.Boolean,
20
+ drawn: Schema.NullOr(Schema.Array(Box)),
21
+ scroll: Point,
22
+ });
23
+
24
+ export const make = (page: PageContext, bridge: Bridge, overlays: Overlays, posing: Posing) => {
25
+ const { lane, owned, span, within } = page;
26
+ let holding = false;
27
+
28
+ // One step, the page to itself, the overlay's turn too when it draws.
29
+ const step = (operation: string, request: StepRequest) => {
30
+ const sent = lane
31
+ .write(
32
+ operation,
33
+ page.settings.actionTimeout,
34
+ )(
35
+ bridge.evaluate(operation, scriptCall("step", request)).pipe(
36
+ Effect.flatMap(decodeWith(operation, Stepped)),
37
+ Effect.tap(({ drawn }) =>
38
+ Effect.sync(() => {
39
+ if (drawn !== null && request.markup !== undefined)
40
+ overlays.record(request.markup, drawn);
41
+ page.noteInput();
42
+ }),
43
+ ),
44
+ within(operation),
45
+ ),
46
+ )
47
+ .pipe(span(`PageTime.${operation}`), owned);
48
+
49
+ return request.markup === undefined ? sent : overlays.turn(sent);
50
+ };
51
+
52
+ const unclocked = (operation: string) =>
53
+ failWith(operation, new NotActionable({ detail: "the page's document has no page clock" }));
54
+
55
+ const hold: Effect.Effect<Held, BrowserError, Scope.Scope> = Effect.gen(function* () {
56
+ const clock = page.settings.pageTime;
57
+
58
+ if (clock === undefined)
59
+ return yield* refuse("hold", "holding page time needs the browser's pageTime option");
60
+ if (holding) return yield* refuse("hold", "the page's time is held already");
61
+ holding = true;
62
+ let ended = false;
63
+
64
+ yield* Effect.addFinalizer(() =>
65
+ Effect.sync(() => (ended = true)).pipe(
66
+ Effect.andThen(step("release", { clock, op: "release", by: 0, scroll: null })),
67
+ Effect.ignore,
68
+ Effect.ensuring(Effect.sync(() => (holding = false))),
69
+ ),
70
+ );
71
+ const held = yield* step("hold", { clock, op: "hold", by: 0, scroll: null });
72
+
73
+ if (!held.told) return yield* unclocked("hold");
74
+ let elapsed = 0;
75
+
76
+ const advance = (by: Duration.Input, options: Step = {}) =>
77
+ Effect.gen(function* () {
78
+ const millis = Option.map(Duration.fromInput(by), Duration.toMillis).pipe(
79
+ Option.getOrElse(() => Number.NaN),
80
+ );
81
+
82
+ if (ended) return yield* refuse("advance", "the hold has ended");
83
+ if (!Number.isFinite(millis) || millis < 0)
84
+ return yield* refuse("advance", "page time moves on by a finite, nonnegative duration");
85
+ if (options.scroll !== undefined && !Number.isFinite(options.scroll))
86
+ return yield* refuse("advance", "the scroll must be finite");
87
+ if (options.overlay !== undefined && !overlays.open())
88
+ return yield* refuse("advance", "drawing needs the page's overlay open");
89
+ if (options.poses !== undefined && !posing.open())
90
+ return yield* refuse("advance", "posing needs the page's poses open");
91
+
92
+ const poses =
93
+ options.poses === undefined
94
+ ? undefined
95
+ : yield* posing.requests("advance", options.poses);
96
+
97
+ const stepped = yield* step("advance", {
98
+ clock,
99
+ op: "advance",
100
+ by: millis,
101
+ scroll: options.scroll ?? null,
102
+ markup:
103
+ options.overlay === undefined
104
+ ? undefined
105
+ : options.overlay._tag === "Svg"
106
+ ? options.overlay.markup
107
+ : null,
108
+ poses,
109
+ });
110
+
111
+ yield* posing.answered("advance", stepped);
112
+ if (!stepped.told) return yield* unclocked("advance");
113
+ elapsed += millis;
114
+
115
+ return stepped.scroll;
116
+ });
117
+
118
+ return { advance, elapsed: Effect.sync(() => Duration.millis(elapsed)) };
119
+ });
120
+
121
+ return { hold };
122
+ };