@wardic/foldkit 0.0.0-stage → 1.3.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 (154) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +59 -2
  3. package/THIRD_PARTY_NOTICES.md +145 -0
  4. package/dist/AnimationControls.d.ts +37 -0
  5. package/dist/AnimationControls.d.ts.map +1 -0
  6. package/dist/AnimationControls.js +37 -0
  7. package/dist/AnimationControls.js.map +1 -0
  8. package/dist/AnimationScope.d.ts +20 -0
  9. package/dist/AnimationScope.d.ts.map +1 -0
  10. package/dist/AnimationScope.js +20 -0
  11. package/dist/AnimationScope.js.map +1 -0
  12. package/dist/DragControls.d.ts +25 -0
  13. package/dist/DragControls.d.ts.map +1 -0
  14. package/dist/DragControls.js +21 -0
  15. package/dist/DragControls.js.map +1 -0
  16. package/dist/Features.d.ts +36 -0
  17. package/dist/Features.d.ts.map +1 -0
  18. package/dist/Features.js +44 -0
  19. package/dist/Features.js.map +1 -0
  20. package/dist/Ward.d.ts +301 -0
  21. package/dist/Ward.d.ts.map +1 -0
  22. package/dist/Ward.js +6 -0
  23. package/dist/Ward.js.map +1 -0
  24. package/dist/Wardic.d.ts +363 -0
  25. package/dist/Wardic.d.ts.map +1 -0
  26. package/dist/Wardic.js +85 -0
  27. package/dist/Wardic.js.map +1 -0
  28. package/dist/index.d.ts +15 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +20 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/internal/builder.d.ts +8 -0
  33. package/dist/internal/builder.d.ts.map +1 -0
  34. package/dist/internal/builder.js +242 -0
  35. package/dist/internal/builder.js.map +1 -0
  36. package/dist/internal/commands.d.ts +143 -0
  37. package/dist/internal/commands.d.ts.map +1 -0
  38. package/dist/internal/commands.js +242 -0
  39. package/dist/internal/commands.js.map +1 -0
  40. package/dist/internal/delivery.d.ts +44 -0
  41. package/dist/internal/delivery.d.ts.map +1 -0
  42. package/dist/internal/delivery.js +85 -0
  43. package/dist/internal/delivery.js.map +1 -0
  44. package/dist/internal/dev.d.ts +10 -0
  45. package/dist/internal/dev.d.ts.map +1 -0
  46. package/dist/internal/dev.js +10 -0
  47. package/dist/internal/dev.js.map +1 -0
  48. package/dist/internal/dev.production.d.ts +8 -0
  49. package/dist/internal/dev.production.d.ts.map +1 -0
  50. package/dist/internal/dev.production.js +8 -0
  51. package/dist/internal/dev.production.js.map +1 -0
  52. package/dist/internal/drag.d.ts +66 -0
  53. package/dist/internal/drag.d.ts.map +1 -0
  54. package/dist/internal/drag.js +71 -0
  55. package/dist/internal/drag.js.map +1 -0
  56. package/dist/internal/element.d.ts +59 -0
  57. package/dist/internal/element.d.ts.map +1 -0
  58. package/dist/internal/element.js +582 -0
  59. package/dist/internal/element.js.map +1 -0
  60. package/dist/internal/gestures.d.ts +62 -0
  61. package/dist/internal/gestures.d.ts.map +1 -0
  62. package/dist/internal/gestures.js +109 -0
  63. package/dist/internal/gestures.js.map +1 -0
  64. package/dist/internal/hydrate.d.ts +5 -0
  65. package/dist/internal/hydrate.d.ts.map +1 -0
  66. package/dist/internal/hydrate.js +27 -0
  67. package/dist/internal/hydrate.js.map +1 -0
  68. package/dist/internal/keys.d.ts +21 -0
  69. package/dist/internal/keys.d.ts.map +1 -0
  70. package/dist/internal/keys.js +12 -0
  71. package/dist/internal/keys.js.map +1 -0
  72. package/dist/internal/layout.d.ts +29 -0
  73. package/dist/internal/layout.d.ts.map +1 -0
  74. package/dist/internal/layout.js +88 -0
  75. package/dist/internal/layout.js.map +1 -0
  76. package/dist/internal/mount.d.ts +22 -0
  77. package/dist/internal/mount.d.ts.map +1 -0
  78. package/dist/internal/mount.js +152 -0
  79. package/dist/internal/mount.js.map +1 -0
  80. package/dist/internal/presence.d.ts +33 -0
  81. package/dist/internal/presence.d.ts.map +1 -0
  82. package/dist/internal/presence.js +338 -0
  83. package/dist/internal/presence.js.map +1 -0
  84. package/dist/internal/reactivity.d.ts +15 -0
  85. package/dist/internal/reactivity.d.ts.map +1 -0
  86. package/dist/internal/reactivity.js +26 -0
  87. package/dist/internal/reactivity.js.map +1 -0
  88. package/dist/internal/reorder.d.ts +47 -0
  89. package/dist/internal/reorder.d.ts.map +1 -0
  90. package/dist/internal/reorder.js +250 -0
  91. package/dist/internal/reorder.js.map +1 -0
  92. package/dist/internal/scope.d.ts +28 -0
  93. package/dist/internal/scope.d.ts.map +1 -0
  94. package/dist/internal/scope.js +44 -0
  95. package/dist/internal/scope.js.map +1 -0
  96. package/dist/internal/server.d.ts +13 -0
  97. package/dist/internal/server.d.ts.map +1 -0
  98. package/dist/internal/server.js +13 -0
  99. package/dist/internal/server.js.map +1 -0
  100. package/dist/internal/server.node.d.ts +8 -0
  101. package/dist/internal/server.node.d.ts.map +1 -0
  102. package/dist/internal/server.node.js +8 -0
  103. package/dist/internal/server.node.js.map +1 -0
  104. package/dist/internal/services.d.ts +231 -0
  105. package/dist/internal/services.d.ts.map +1 -0
  106. package/dist/internal/services.js +350 -0
  107. package/dist/internal/services.js.map +1 -0
  108. package/dist/internal/tree.d.ts +71 -0
  109. package/dist/internal/tree.d.ts.map +1 -0
  110. package/dist/internal/tree.js +207 -0
  111. package/dist/internal/tree.js.map +1 -0
  112. package/dist/internal/variant-node.d.ts +62 -0
  113. package/dist/internal/variant-node.d.ts.map +1 -0
  114. package/dist/internal/variant-node.js +279 -0
  115. package/dist/internal/variant-node.js.map +1 -0
  116. package/dist/internal/view-transition.d.ts +10 -0
  117. package/dist/internal/view-transition.d.ts.map +1 -0
  118. package/dist/internal/view-transition.js +36 -0
  119. package/dist/internal/view-transition.js.map +1 -0
  120. package/dist/internal/walk.d.ts +26 -0
  121. package/dist/internal/walk.d.ts.map +1 -0
  122. package/dist/internal/walk.js +162 -0
  123. package/dist/internal/walk.js.map +1 -0
  124. package/package.json +99 -4
  125. package/src/AnimationControls.ts +46 -0
  126. package/src/AnimationScope.ts +19 -0
  127. package/src/DragControls.ts +27 -0
  128. package/src/Features.ts +45 -0
  129. package/src/Ward.ts +434 -0
  130. package/src/Wardic.ts +410 -0
  131. package/src/index.ts +20 -0
  132. package/src/internal/builder.ts +262 -0
  133. package/src/internal/commands.ts +359 -0
  134. package/src/internal/delivery.ts +116 -0
  135. package/src/internal/dev.production.ts +7 -0
  136. package/src/internal/dev.ts +9 -0
  137. package/src/internal/drag.ts +136 -0
  138. package/src/internal/element.ts +668 -0
  139. package/src/internal/gestures.ts +184 -0
  140. package/src/internal/hydrate.ts +29 -0
  141. package/src/internal/keys.ts +19 -0
  142. package/src/internal/layout.ts +109 -0
  143. package/src/internal/mount.ts +181 -0
  144. package/src/internal/presence.ts +362 -0
  145. package/src/internal/reactivity.ts +45 -0
  146. package/src/internal/reorder.ts +313 -0
  147. package/src/internal/scope.ts +60 -0
  148. package/src/internal/server.node.ts +7 -0
  149. package/src/internal/server.ts +12 -0
  150. package/src/internal/services.ts +508 -0
  151. package/src/internal/tree.ts +230 -0
  152. package/src/internal/variant-node.ts +352 -0
  153. package/src/internal/view-transition.ts +43 -0
  154. package/src/internal/walk.ts +211 -0
@@ -0,0 +1,184 @@
1
+ /**
2
+ * A `w.*` element's gestures (#793, PR 1 and 2; ADR-0071 decision 23; ADR-0047): hover, press, focus, in
3
+ * view and pan, each started the first time a delivery wants it (its `While*`, or a callback of its)
4
+ * while its Feature is built, and kept from then on, as Motion's features start (ADR-0047 decision 5).
5
+ * Each is dom's Feature's `watch`, run in a Scope of the element's own on the provider and closed at its
6
+ * release. An Edge sets the element's entry in the Override stack and sends the callback's Message, at
7
+ * the event, through dom's gesture teller (Motion's order; a throw reported by name, the gesture going
8
+ * on): a function handler runs inside the recognizer's dispatch, so `stopPropagation()` and
9
+ * `preventDefault()` do what they say, and its Message reaches `update` a microtask later. The drag's
10
+ * samples and its hold on `x`/`y` come here too (its track is `drag.ts`'s), so its entry and its
11
+ * callbacks sit with the rest. A gesture wanted without its Feature is inert, and warned once in
12
+ * development.
13
+ *
14
+ * @module
15
+ */
16
+ import type * as Drag from "@wardic/core/Drag"
17
+ import type * as InputFeed from "@wardic/core/InputFeed"
18
+ import type * as Recognizer from "@wardic/core/Recognizer"
19
+ import type * as Spine from "@wardic/core/unstable/Spine"
20
+ import * as VariantTree from "@wardic/core/unstable/VariantTree"
21
+ import * as WardicConfigValue from "@wardic/core/unstable/WardicConfigValue"
22
+ import type * as WardicServices from "@wardic/core/unstable/WardicServices"
23
+ import * as GestureFeatures from "@wardic/dom/unstable/GestureFeatures"
24
+ import type * as WardConfig from "@wardic/dom/unstable/WardConfig"
25
+ import * as Keys from "@wardic/dom/unstable/features/Keys"
26
+ import * as OwnerScope from "@wardic/dom/unstable/OwnerScope"
27
+ import * as Press from "@wardic/dom/unstable/Press"
28
+ import * as Arr from "effect/Array"
29
+ import * as Bool from "effect/Boolean"
30
+ import * as Cause from "effect/Cause"
31
+ import * as Effect from "effect/Effect"
32
+ import * as Iter from "effect/Iterable"
33
+ import * as MutableRef from "effect/MutableRef"
34
+ import * as Scope from "effect/Scope"
35
+ import * as UndefinedOr from "effect/UndefinedOr"
36
+ import type * as Ward from "../Ward.ts"
37
+ import type { Dispatch, View } from "./element.ts"
38
+ import { featureIn, type Provider, reporterOf, warnMissing } from "./services.ts"
39
+
40
+ /** What an element's gestures are made with. */
41
+ export interface GestureOptions {
42
+ readonly provider: Provider
43
+ readonly element: HTMLElement
44
+ /** The element's config now, as its last delivery gave it: read at each event. */
45
+ readonly config: () => View
46
+ /** What sends a callback's Message: the element's Mount queue, unless replay has the view. */
47
+ readonly dispatch: Dispatch
48
+ /** Called after an entry flips, so the element re-resolves its Override stack. */
49
+ readonly onChange: () => void
50
+ /** The element's id, for a report. */
51
+ readonly id: string
52
+ /** The nearest `w.Config`'s `transformPagePoint` (Q9), read at each of the pan's downs. */
53
+ readonly pagePoint: () => WardConfig.WardicTransformPoint | undefined
54
+ /** Whether the element's keys are taken, as a Reorder item's are by its Keyboard reorder (ADR-0037): its press starts from no key. Read as the press starts. */
55
+ readonly keysTaken: () => boolean
56
+ }
57
+
58
+ /** An element's gestures (above). */
59
+ export interface Gestures {
60
+ /** Which entries of the Override stack are on now, the drag's among them. */
61
+ readonly active: () => Spine.Active
62
+ /** Which gestures are on, for the names the element's variant node hands down (#291). */
63
+ readonly states: () => VariantTree.GestureStates
64
+ /** Whether a drag holds `x`/`y` now (ADR-0004): what the spine's follower reads. */
65
+ readonly dragging: () => boolean
66
+ /** The drag took `x`/`y`, or handed them back (the track's `setDragging`): its entry flips once each way. */
67
+ readonly dragHeld: (on: boolean) => void
68
+ /** A Keyboard reorder's lift began or ended (ADR-0037): `WhileDrag` applies as to a drag, the translate keys stay the spine's. */
69
+ readonly lift: (lifted: boolean) => void
70
+ /** A drag's sample, after the track's write: `OnDirectionLock` at a locked start, `OnDragStart`, `OnDrag` at each move, `OnDragEnd`. */
71
+ readonly dragged: (sample: Drag.Sample) => void
72
+ /** The drag's release came to rest on its own: `OnDragTransitionEnd`. */
73
+ readonly released: () => void
74
+ /** Start what the config wants and the Features give, once each: at mount, at each delivery, and as a Feature arrives. */
75
+ readonly check: () => void
76
+ /** Close every recognizer's Scope: at the element's release. */
77
+ readonly dispose: () => void
78
+ }
79
+
80
+ /** A gesture the element may want: its Feature's name. */
81
+ type Gesture = "hover" | "press" | "focus" | "inView" | "pan"
82
+
83
+ /** A gesture's recognizer, as the element starts it: whether its config wants it, and its watch, `undefined` without its Feature. */
84
+ interface Recognizer {
85
+ readonly name: Gesture
86
+ readonly wants: (config: GestureFeatures.GestureWants) => boolean
87
+ readonly start: () => Scope.Closeable | undefined
88
+ }
89
+
90
+ /** Focus as the browser shows it (`:focus-visible`, Motion's `whileFocus`): a keyboard's, not a click's. */
91
+ const VISIBLE_FOCUS: Recognizer.FocusOptions = { visible: true }
92
+
93
+ /** A recognizer's end that failed, at the element's release. */
94
+ const END_FAILED = "wardic.gesture: a recognizer's end failed"
95
+
96
+ /** A recognizer's own handler threw, dom's or the port's, past the app's callbacks. */
97
+ const HANDLER_FAILED = "wardic.gesture: a recognizer's handler failed"
98
+
99
+ /** A callback as the teller hands it to `dispatch`: Foldkit's, told whatever the gesture tells. */
100
+ type Told = Ward.Callback<unknown, ReadonlyArray<unknown>>
101
+
102
+ /** An element's gestures (above): nothing started until `check` wants it. */
103
+ export const gesturesOf = ({ provider, element, config, dispatch, onChange, id, pagePoint, keysTaken }: GestureOptions): Gestures => {
104
+ const started = new Map<Gesture, Scope.Closeable>()
105
+ // Which gestures are on: the element's entries in the Override stack.
106
+ const on = MutableRef.make<VariantTree.GestureStates>(VariantTree.NO_GESTURE_STATES)
107
+ // Whether the drag holds `x`/`y` (ADR-0004): from its "start" through its release.
108
+ const dragging = MutableRef.make(false)
109
+ // Whether a Keyboard reorder has the element lifted (ADR-0037): `WhileDrag` applies with no drag.
110
+ const lifted = MutableRef.make(false)
111
+ const flip = (change: Partial<VariantTree.GestureStates>): void => {
112
+ MutableRef.set(on, { ...MutableRef.get(on), ...change })
113
+ onChange()
114
+ }
115
+ const report = reporterOf(provider, id)
116
+ const onDefect: InputFeed.OnDefect = (cause) => report(HANDLER_FAILED, cause)
117
+ // The callbacks' teller (decision 23; dom's, for both bindings): each callback's Message sent through
118
+ // `dispatch`, at the event; one that throws reported by name, and the gesture goes on.
119
+ const teller = GestureFeatures.gestureTellerOf({
120
+ config,
121
+ invoke: (handler, args) => dispatch(handler as Told)(...args),
122
+ report: (name, defect) => report(`wardic.gesture: ${name} failed`, Cause.die(defect)),
123
+ })
124
+ /** Run `watch` in a Scope of the element's own, on the provider, whose services (the Probe, for in view) it has. */
125
+ const run = (watch: Effect.Effect<void, never, Scope.Scope | WardicServices.WardicServices>): Scope.Closeable => {
126
+ const scope = OwnerScope.open(provider.runtime)
127
+ provider.runtime.runSync(watch.pipe(Scope.provide(scope)))
128
+ return scope
129
+ }
130
+ const hovered = (edge: Recognizer.Edge): void => {
131
+ teller.hovered(edge)
132
+ flip({ hovered: edge.active })
133
+ }
134
+ const pressed = (press: Recognizer.PressEvent): void => {
135
+ teller.pressed(press, element)
136
+ flip({ pressed: press.phase === "start" })
137
+ }
138
+ /** Whether its presses reach its pressable ancestors (#439): its `propagate`, read at each press's start. */
139
+ const propagates = (): boolean => Press.tapPropagates(config().propagate)
140
+ const focused = (has: boolean): void => flip({ focused: has })
141
+ const viewed = (edge: Recognizer.ViewEdge): void => {
142
+ teller.viewed(edge)
143
+ flip({ inView: edge.active })
144
+ }
145
+ const dragHeld = (held: boolean): void => {
146
+ if (MutableRef.get(dragging) === held) return
147
+ MutableRef.set(dragging, held)
148
+ flip({ dragged: Bool.or(held, MutableRef.get(lifted)) })
149
+ }
150
+ const lift = (on: boolean): void => {
151
+ if (MutableRef.get(lifted) === on) return
152
+ MutableRef.set(lifted, on)
153
+ flip({ dragged: Bool.or(MutableRef.get(dragging), on) })
154
+ }
155
+ // Each gesture's recognizer: its Feature's watch, with the element's handlers. In view as its
156
+ // `viewport` says, read as it starts (Motion's), over the Environment's Probe. A pan (Q9) moves
157
+ // nothing: its samples to the pan callbacks, its points through the nearest `transformPagePoint`.
158
+ const recognizers: ReadonlyArray<Recognizer> = [
159
+ { name: "hover", wants: GestureFeatures.wantsHover, start: () => UndefinedOr.map(featureIn(provider, Keys.HoverGesture), (hover) => run(hover.watch(element, { on: hovered, onDefect }))) },
160
+ { name: "press", wants: GestureFeatures.wantsPress, start: () => UndefinedOr.map(featureIn(provider, Keys.PressGesture), (press) => run(press.watch(element, { on: pressed, onDefect }, keysTaken(), propagates))) },
161
+ { name: "focus", wants: GestureFeatures.wantsFocus, start: () => UndefinedOr.map(featureIn(provider, Keys.FocusGesture), (focus) => run(focus.watch(element, VISIBLE_FOCUS, { on: focused, onDefect }))) },
162
+ { name: "inView", wants: GestureFeatures.wantsInView, start: () => UndefinedOr.map(featureIn(provider, Keys.InViewGesture), (inView) => run(inView.watch(element, GestureFeatures.inViewOptionsOf(config().viewport), { on: viewed, onDefect }))) },
163
+ { name: "pan", wants: GestureFeatures.wantsPan, start: () => UndefinedOr.map(featureIn(provider, Keys.PanGesture), (pan) => run(pan.watch(element, { on: teller.panned, onDefect }, { mapPoint: WardicConfigValue.pointMapOptionOf(pagePoint) }))) },
164
+ ]
165
+ const check = (): void => {
166
+ const c = config()
167
+ Arr.forEach(recognizers, ({ name, wants, start }) => {
168
+ if (started.has(name)) return
169
+ if (Bool.not(wants(c))) return
170
+ UndefinedOr.match(start(), { onUndefined: () => warnMissing(provider, name, GestureFeatures.GESTURE_WORDS[name]), onDefined: (scope) => started.set(name, scope) })
171
+ })
172
+ }
173
+ return {
174
+ active: () => ({ ...MutableRef.get(on), dragging: MutableRef.get(dragging) }),
175
+ states: () => MutableRef.get(on),
176
+ dragging: () => MutableRef.get(dragging),
177
+ dragHeld,
178
+ lift,
179
+ dragged: teller.dragged,
180
+ released: teller.released,
181
+ check,
182
+ dispose: () => Iter.forEach(started.values(), (scope) => OwnerScope.close(provider.runtime, scope, END_FAILED)),
183
+ }
184
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `wardic.hydrate(program, options)` (ADR-0071 *Amendment (#794)*, Q10 and Q17; ADR-0044): Foldkit's
3
+ * `Runtime.hydrate` with the Appear animations' two steps before it. The chunk `<style>` the Provider
4
+ * element rendered first among its children (PR 2) is moved into the head (dom's `adoptChunks`), since
5
+ * Foldkit adopts the server's children against the view's one by one, and a child the view lacks would
6
+ * have it rebuild the Provider element's subtree. And the Handle is told hydration's window opens: the
7
+ * walk names each element's slot as the server did (Q9) at the hydration render and at any render before
8
+ * the last Handoff has released, so hydration keeps the inline `animation` the CSS plays through, for each
9
+ * Mount's Handoff (decision 6), rather than stripping it as a value the client didn't reassert (probe
10
+ * P-C). Foldkit renders the hydration after this returns, on its own time (at once in production, after
11
+ * a wait for its vite plugin under a dev server); the window waits for it.
12
+ *
13
+ * @module
14
+ */
15
+ import * as Appear from "@wardic/dom/Appear"
16
+ import * as Predicate from "effect/Predicate"
17
+ import * as FoldkitRuntime from "foldkit/runtime"
18
+ import { hydrationStarts, type State } from "./services.ts"
19
+
20
+ /** The Handle's `hydrate` (above). */
21
+ export const hydrateOf =
22
+ (state: State): typeof FoldkitRuntime.hydrate =>
23
+ (program, options) => {
24
+ // Opened with a chunk on the page alone: a page the server rendered with none (no Provider element,
25
+ // `appear: false`, nothing that plays) names no slot, and its hydration render must name none either.
26
+ hydrationStarts(state, Predicate.isNotNull(document.querySelector(`style[${Appear.CHUNK_ATTRIBUTE}]`)))
27
+ Appear.adoptChunks(document)
28
+ FoldkitRuntime.hydrate(program, options)
29
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The keys of the binding's own Features (#792; ADR-0067 decision 3's pattern, dom's `features/Keys`):
3
+ * what an element looks a Feature's service up by, in a module of their own, so the code that uses a
4
+ * Feature imports no Feature's code, and an app that never gives the Feature ships none of it.
5
+ *
6
+ * @module
7
+ */
8
+ import * as Context from "effect/Context"
9
+ import type * as PresenceController from "@wardic/dom/unstable/PresenceController"
10
+
11
+ /** What the `presence` Feature gives: dom's presence controller, its events and its `propagate`. */
12
+ export interface PresenceMakerShape {
13
+ readonly make: (options: PresenceController.PresenceOptions) => PresenceController.PresenceController
14
+ readonly events: typeof PresenceController.exitCompleteEvents
15
+ readonly propagateTo: typeof PresenceController.propagateTo
16
+ }
17
+
18
+ /** The `presence` Feature's service (#792, Q9): what a `w.Presence` element's Mount makes its controller with. */
19
+ export class PresenceMaker extends Context.Service<PresenceMaker, PresenceMakerShape>()("@wardic/foldkit/PresenceMaker") {}
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Layout on Foldkit (ADR-0071 decision 30; *Amendment (#791)* at slice 2): a provider's `layout`
3
+ * Feature, built at the first layout element's mount, and what triggers its Measure passes. Under the
4
+ * default trigger (`"patch"`) one `MutationObserver` watches the subtree of the `w.Provider()` element,
5
+ * else the document's body, for the child list, the text, and the `class` and `hidden` attributes with
6
+ * the app's `layoutAttributes`; each delivery, a microtask after Foldkit's patch, gives the Frame loop
7
+ * the hint and asks the projection system for one pass, so every layout element moved by the patch
8
+ * animates from where it was (P13). Under `"declared"` there is no observer: a `w.LayoutDependency`
9
+ * change and `Wardic.animateLayout` ask for the passes.
10
+ *
11
+ * @module
12
+ */
13
+ import type * as ProjectionSystem from "@wardic/dom/ProjectionSystem"
14
+ import * as Feature from "@wardic/dom/unstable/Feature"
15
+ import * as Keys from "@wardic/dom/unstable/features/Keys"
16
+ import * as Arr from "effect/Array"
17
+ import * as Bool from "effect/Boolean"
18
+ import { identity } from "effect/Function"
19
+ import * as Predicate from "effect/Predicate"
20
+ import * as UndefinedOr from "effect/UndefinedOr"
21
+ import { hintFrameUnless } from "./delivery.ts"
22
+ import { type Provider, type State, warnMissing } from "./services.ts"
23
+ import { underWard } from "./tree.ts"
24
+
25
+ /** A provider's layout: its projection system, and the `layout` Feature's element code. */
26
+ export interface Layout {
27
+ readonly projection: ProjectionSystem.Shape
28
+ readonly nodes: Keys.ProjectionNodes["Service"]
29
+ }
30
+
31
+ // Module state (#460, Q7): each provider's layout, held weakly by the provider, made at the first layout element's mount.
32
+ const layouts = new WeakMap<Provider, Layout>()
33
+
34
+ // Module state (#460, Q7): the presence elements told not to affect layout (Motion's `presenceAffectsLayout: false`),
35
+ // held weakly: a change of their child list, the presence's own moves and Foldkit's among them, makes no pass (#792, Q21).
36
+ const quiet = new WeakSet<Element>()
37
+
38
+ /** What the observer watches beside the app's `layoutAttributes` (decision 30, R9 Q40): what CSS lays out by, not `style`, which the passes write. */
39
+ const WATCHED: ReadonlyArray<string> = ["class", "hidden"]
40
+
41
+ /**
42
+ * `provider`'s layout, its `layout` Feature built now if nothing has built it (#511): what a layout
43
+ * element makes its node on. `undefined` when the Handle wasn't given the Feature, warned once in
44
+ * development, as Solid 2's element warns.
45
+ */
46
+ export const layoutOf = (provider: Provider, state: State): Layout | undefined => {
47
+ const known = layouts.get(provider)
48
+ if (Predicate.isNotUndefined(known)) return known
49
+ const built = provider.features.services()
50
+ const projection = Keys.projectionIn(built)
51
+ if (Predicate.isUndefined(projection)) {
52
+ warnMissing(provider, "layout", Feature.LAYOUT_PROPS)
53
+ return undefined
54
+ }
55
+ const made: Layout = { projection, nodes: Keys.projectionNodesIn(built) }
56
+ layouts.set(provider, made)
57
+ // The observer, a microtask later: Foldkit mounts a child before its parent, so a `w.Provider()` root
58
+ // mounting in this patch, after its first layout element, is known by then (#792, Q17).
59
+ if (state.layout.trigger !== "declared") queueMicrotask(() => observe(provider, state, projection))
60
+ return made
61
+ }
62
+
63
+ /** Whether `element`'s child list's changes make a pass: `false` for a presence told not to affect layout, read at each of its deliveries. */
64
+ export const quietLayoutIn = (element: Element, isQuiet: boolean): void => {
65
+ Bool.match(isQuiet, { onTrue: () => quiet.add(element), onFalse: () => quiet.delete(element) })
66
+ }
67
+
68
+ /** A record of a change of the Handle's own: on a `w.*` element or under one. */
69
+ const isOwnChange = (record: MutationRecord): boolean => underWard(record.target)
70
+
71
+ /** A record of a quiet presence's child list: the presence's own moves, or Foldkit's children going and coming under it. */
72
+ const isQuietChange = (record: MutationRecord): boolean => Bool.and(record.type === "childList", Bool.and(record.target instanceof Element, quiet.has(record.target as Element)))
73
+
74
+ /**
75
+ * The observer under `"patch"` (decision 30): on the `w.Provider()` element when one is mounted as it's
76
+ * made, else the document's body (#792, Q17; the DevTools overlay's mutations under the body are a
77
+ * development-only cost, Q24), disconnected as the provider ends, with its Feature registry. A delivery
78
+ * of quiet changes alone asks for nothing.
79
+ */
80
+ const observe = (provider: Provider, state: State, projection: ProjectionSystem.Shape): void => {
81
+ // The provider ended before this ran: nothing to watch.
82
+ if (state.live !== provider) return
83
+ const observer = new MutationObserver((records) => {
84
+ // A View Transition's render (decision 33), its changes the Handle's own: they land as an Instant change
85
+ // of the layout, every node at its new box and nothing started. A foreign change under the body
86
+ // consumes no arming; a render that changed quiet lists alone consumes it and asks for nothing.
87
+ if (state.transitioning) {
88
+ if (Arr.some(records, isOwnChange)) {
89
+ state.transitioning = false
90
+ if (Arr.every(records, isQuietChange)) return
91
+ projection.instant()
92
+ return
93
+ }
94
+ }
95
+ if (Arr.every(records, isQuietChange)) return
96
+ // A microtask on (#840): a presence's observer, made at its mount, is told after this one when this
97
+ // one came first, and the pass would measure a `popLayout` leaver where the patch pushed it, before
98
+ // its presence pins it; a microtask later every presence has delivered, and the pass is still in the
99
+ // patch's task.
100
+ queueMicrotask(() => {
101
+ // The pass's first step paints in the patch's frame (decision 32; #792, Q7), unless replay has a view (decision 34).
102
+ hintFrameUnless(provider.loop, provider.paused)
103
+ projection.notify()
104
+ })
105
+ })
106
+ const root = UndefinedOr.match(provider.root, { onUndefined: (): Node => document.body, onDefined: identity })
107
+ observer.observe(root, { childList: true, characterData: true, subtree: true, attributes: true, attributeFilter: [...WATCHED, ...UndefinedOr.match(state.layout.attributes, { onUndefined: (): ReadonlyArray<string> => [], onDefined: identity })] })
108
+ provider.registry.onEnd(() => observer.disconnect())
109
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * The fused Mount (ADR-0071, decisions 18 and 31): the seam that differs on Foldkit's preview. A `w.*`
3
+ * element runs one Mount: Wardic's part, which gets the Handle's Provider (built by the first element
4
+ * to mount, *Amendment (#791)*) and mounts the element on it, merged with the user's own `OnMount` when
5
+ * there is one. With a
6
+ * user Mount, the fused one is `{ ...userAction, f }`, so it keeps the user's name and args, and a Scene
7
+ * test resolves the user's Mount as it would; without one, it's named `Wardic.Provider` or
8
+ * `Wardic.Element`, what a Scene test resolves by (#791, Q15; decision 36).
9
+ *
10
+ * @module
11
+ */
12
+ import * as Report from "@wardic/dom/Report"
13
+ import * as Arr from "effect/Array"
14
+ import * as Cause from "effect/Cause"
15
+ import * as Channel from "effect/Channel"
16
+ import * as Effect from "effect/Effect"
17
+ import * as Predicate from "effect/Predicate"
18
+ import type * as Scheduler from "effect/Scheduler"
19
+ import * as Scope from "effect/Scope"
20
+ import * as Stream from "effect/Stream"
21
+ import type { MountAction } from "foldkit/mount"
22
+ import type * as Ward from "../Ward.ts"
23
+ import { patchTouched } from "./delivery.ts"
24
+ import { mountElement } from "./element.ts"
25
+ import { mountPresence } from "./presence.ts"
26
+ import { mountReorderGroup } from "./reorder.ts"
27
+ import { flushPresences, joined, type Provider, providerFor, type State } from "./services.ts"
28
+ import { markMounted } from "./tree.ts"
29
+
30
+ /** The names a Scene test resolves Wardic's Mounts by (decision 36). */
31
+ export const PROVIDER_NAME = "Wardic.Provider"
32
+ export const ELEMENT_NAME = "Wardic.Element"
33
+ export const PRESENCE_NAME = "Wardic.Presence"
34
+ export const REORDER_NAME = "Wardic.Reorder"
35
+
36
+ /** A Mount's `f`: what runs on the element. */
37
+ type MountFn<Message> = MountAction<Message>["f"]
38
+
39
+ /** What a Mount's setup failing is reported as: contained at the binding's edge (decision 13), the element left at its Starting style. */
40
+ const FAILED = "wardic.mount: a w.* element's mount failed; it stays at its Starting style"
41
+
42
+ /** What a Mount whose setup failed pulls: nothing, ever, so its Stream stays open, sending nothing. */
43
+ const OPEN: Effect.Effect<never> = Effect.never
44
+
45
+ /** A Mount's Messages: what its callbacks offer, and the pull its Stream takes them by. */
46
+ interface Mailbox<Message> {
47
+ readonly offer: (message: unknown) => void
48
+ readonly pull: Effect.Effect<Arr.NonEmptyReadonlyArray<Message>>
49
+ }
50
+
51
+ /**
52
+ * A Mount's Messages, held until its Stream pulls them (#849, E4). The buffer is made at the element's
53
+ * first Message, so an element that sends none, as most don't, holds only its pull, which waits on a
54
+ * callback as `Effect.never` does. A Message offered while the pull waits wakes it a scheduler task
55
+ * later, as `Queue`'s offer does, so the Messages of one task leave together.
56
+ */
57
+ const mailbox = <Message>(): Mailbox<Message> => {
58
+ let messages: Array<Message> | undefined
59
+ let resume: ((effect: Effect.Effect<void>) => void) | undefined
60
+ let scheduler: Scheduler.Scheduler | undefined
61
+ let dispatcher: Scheduler.SchedulerDispatcher | undefined
62
+ let waking = false
63
+ const wake = (): void => {
64
+ waking = false
65
+ const waiting = resume
66
+ resume = undefined
67
+ if (Predicate.isNotUndefined(waiting)) waiting(Effect.void)
68
+ }
69
+ const offer = (message: unknown): void => {
70
+ if (Predicate.isUndefined(messages)) messages = []
71
+ messages.push(message as Message)
72
+ if (Predicate.isUndefined(resume) || Predicate.isUndefined(scheduler) || waking) return
73
+ waking = true
74
+ // The fiber's own dispatcher is what `Queue` wakes through; made here, at the first wake.
75
+ if (Predicate.isUndefined(dispatcher)) dispatcher = scheduler.makeDispatcher()
76
+ dispatcher.scheduleTask(wake, 0)
77
+ }
78
+ const wait = Effect.callback<void>(function (this: Scheduler.Scheduler, waiting) {
79
+ scheduler = this
80
+ resume = waiting
81
+ })
82
+ const take = (): Effect.Effect<Arr.NonEmptyReadonlyArray<Message>> => {
83
+ const taken = messages
84
+ messages = undefined
85
+ if (Predicate.isUndefined(taken) || !Arr.isArrayNonEmpty(taken)) return waitThenTake
86
+ return Effect.succeed(taken)
87
+ }
88
+ const pull = Effect.suspend(take)
89
+ const waitThenTake = Effect.flatMap(wait, () => pull)
90
+ return { offer, pull }
91
+ }
92
+
93
+ /** `element` mounted on `on`, its release a finalizer of `scope`: the pull of its Messages. */
94
+ const mountOn = <Message>(state: State, on: Provider, element: Element, scope: Scope.Scope): Effect.Effect<Effect.Effect<Arr.NonEmptyReadonlyArray<Message>>> => {
95
+ // The element's callbacks (PR 2) leave as Messages through its own Stream (P7).
96
+ const box = mailbox<Message>()
97
+ const offer = box.offer
98
+ const left = joined(state, on, element)
99
+ const isPaused = on.paused
100
+ // The live presences deliver before this element registers anything (#840): Foldkit runs a Mount
101
+ // in the patch's task, once the patch has committed and before the observers are told, and a
102
+ // presence this element carries starts its children at its own mount, a `layoutId` twin among
103
+ // them, which measures the one it takes over from where it is then: in a `popLayout` leaver an
104
+ // outer presence hasn't pinned yet. Delivered before this element's key is registered, a key
105
+ // re-entering during its exit is matched at the delivery its enrollment brings, a microtask on.
106
+ flushPresences(state)
107
+ const release = mountElement(on, state, element as HTMLElement, isPaused, offer, state.rootConfig)
108
+ markMounted(element)
109
+ // Its presence, when it carries `w.Presence` (decision 29): its children's exits, run by this Mount.
110
+ const releasePresence = mountPresence(on, state, element, isPaused, offer)
111
+ // Its Reorder group, when it carries `w.ReorderGroup` (decision 28): made by its first item's Mount or here, released here.
112
+ const releaseReorder = mountReorderGroup(on, element as HTMLElement, isPaused, offer)
113
+ const released = Effect.sync(() => {
114
+ releaseReorder()
115
+ releasePresence()
116
+ release()
117
+ left()
118
+ })
119
+ return Effect.map(Scope.addFinalizer(scope, released), () => {
120
+ patchTouched()
121
+ return box.pull
122
+ })
123
+ }
124
+
125
+ /** A Mount's setup failing: reported (decision 13), and its Stream left open. */
126
+ const failed = (defect: unknown): Effect.Effect<Effect.Effect<never>> => Effect.as(Report.failure(FAILED, Cause.die(defect)), OPEN)
127
+
128
+ /**
129
+ * Wardic's part of a `w.*` element's Mount: gets the Handle's Provider, building it when it's the first
130
+ * element to mount, and takes the root when the element carries `w.Provider(options)`; has the provider
131
+ * follow the view's state for DevTools replay (decision 34), the first Mount's stream serving every
132
+ * element's; mounts the element on it; and holds its Scope until
133
+ * the Mount's destroy, which runs the release before Foldkit removes the element. It never fails: a failure is reported, and the Stream
134
+ * stays open (decision 13). Emits no Message in slice 1's PR 1; PR 2's callbacks come through here.
135
+ *
136
+ * The setup runs as the Stream starts, on the Mount's own fiber (#849, Q3): no fiber of its own waiting
137
+ * on `Effect.never`, as `Stream.callback`'s was. The Stream is one Channel step (#849, E4): the setup
138
+ * returns its pull, and the release is a finalizer of the run's own Scope, which Foldkit's interrupt
139
+ * closes. Once the provider is live and follows the view state, an element without `w.Provider()`'s
140
+ * options has nothing to wait on, and mounts without the provider's Effects.
141
+ */
142
+ const wardicPart =
143
+ <Message>(state: State, provider: Ward.ProviderOptions | undefined): MountFn<Message> =>
144
+ (element, viewStateChanges) =>
145
+ Stream.fromChannel(
146
+ Channel.fromTransform((_, scope) => {
147
+ const live = state.live
148
+ if (Predicate.isUndefined(provider) && Predicate.isNotUndefined(live) && live.following())
149
+ return Effect.suspend(() => mountOn<Message>(state, live, element, scope)).pipe(Effect.catchDefect(failed))
150
+ return Effect.flatMap(providerFor(state, element, provider), (on) =>
151
+ // The view state is the program's (decision 34): the provider follows it once, for every element (#849, Q2).
152
+ Effect.flatMap(on.followViewState(viewStateChanges), () => mountOn<Message>(state, on, element, scope)),
153
+ ).pipe(Effect.catchDefect(failed))
154
+ }),
155
+ )
156
+
157
+ /** What a `w.*` element's Mount is made of. */
158
+ export interface Parts<Message> {
159
+ /** `w.Provider()`'s options, when the element carries it. */
160
+ readonly provider: Ward.ProviderOptions | undefined
161
+ /** The user's own `OnMount`, when the element has one. */
162
+ readonly user: MountAction<Message> | undefined
163
+ /** Whether the element carries `w.Presence` (decision 29): its Mount is then named `Wardic.Presence` (#792, Q19). */
164
+ readonly presence: boolean
165
+ /** Whether the element carries `w.ReorderGroup` (decision 28): its Mount is then named `Wardic.Reorder` (#793, Q18). */
166
+ readonly reorder: boolean
167
+ }
168
+
169
+ /** A `w.*` element's one Mount (above). */
170
+ export const mountOf = <Message>(state: State, parts: Parts<Message>): MountAction<Message> => {
171
+ const wardic = wardicPart<Message>(state, parts.provider)
172
+ const user = parts.user
173
+ if (Predicate.isUndefined(user)) {
174
+ if (Predicate.isNotUndefined(parts.provider)) return { name: PROVIDER_NAME, f: wardic }
175
+ if (parts.presence) return { name: PRESENCE_NAME, f: wardic }
176
+ if (parts.reorder) return { name: REORDER_NAME, f: wardic }
177
+ return { name: ELEMENT_NAME, f: wardic }
178
+ }
179
+ // Wardic's part first, so it starts before the user's (decision 31).
180
+ return { ...user, f: (element, viewStateChanges) => Stream.merge(wardic(element, viewStateChanges), user.f(element, viewStateChanges)) }
181
+ }