@wardic/foldkit 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +100 -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 +222 -0
  105. package/dist/internal/services.d.ts.map +1 -0
  106. package/dist/internal/services.js +338 -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 +124 -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 +486 -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,486 @@
1
+ /**
2
+ * Where elements get Wardic's services (ADR-0071, decisions 9 and 31; *Amendment (#791)*): the seam
3
+ * that differs on Foldkit's preview. On 0.170, a **Handle** (`Wardic.make`) holds its **Provider**:
4
+ * Wardic's Layer built on the Handle's `env` into a Scope the Handle owns, by the first `w.*` element to
5
+ * mount while none is live, on that element's Mount fiber (so Foldkit's scheduler is inherited, decision
6
+ * 11), inside the patch (P2). Every `w.*` element counts itself in at mount and out at its release; once
7
+ * the last has left, the Handle closes the Scope at the end of the task, so a patch that swaps every
8
+ * element keeps the runtime. `w.Provider(options)` names the element the subtree options hang on (slice
9
+ * 2's); a second one while that element is mounted is reported and ignored.
10
+ *
11
+ * @module
12
+ */
13
+ import * as DefaultTransition from "@wardic/core/DefaultTransition"
14
+ import * as FrameLoop from "@wardic/core/FrameLoop"
15
+ import * as Probe from "@wardic/core/Probe"
16
+ import * as ReducedMotion from "@wardic/core/ReducedMotion"
17
+ import * as RefreshFrameSource from "@wardic/core/RefreshFrameSource"
18
+ import * as Renderer from "@wardic/core/Renderer"
19
+ import * as MeasuredPairs from "@wardic/core/unstable/MeasuredPairs"
20
+ import * as OwnValues from "@wardic/core/unstable/OwnValues"
21
+ import * as VariableValues from "@wardic/core/unstable/VariableValues"
22
+ import * as WardicServices from "@wardic/core/unstable/WardicServices"
23
+ import * as FlushGate from "@wardic/dom/FlushGate"
24
+ import type * as ProjectionSystem from "@wardic/dom/ProjectionSystem"
25
+ import * as Report from "@wardic/dom/Report"
26
+ import * as ElementSetup from "@wardic/dom/unstable/ElementSetup"
27
+ import * as Feature from "@wardic/dom/unstable/Feature"
28
+ import * as GestureFeatures from "@wardic/dom/unstable/GestureFeatures"
29
+ import * as InstanceFeatures from "@wardic/dom/unstable/InstanceFeatures"
30
+ import * as LiveStyle from "@wardic/dom/unstable/LiveStyle"
31
+ import * as Bool from "effect/Boolean"
32
+ import * as Cause from "effect/Cause"
33
+ import * as Context from "effect/Context"
34
+ import * as Deferred from "effect/Deferred"
35
+ import * as Effect from "effect/Effect"
36
+ import * as Exit from "effect/Exit"
37
+ import { constFalse, constVoid, identity } from "effect/Function"
38
+ import * as Iter from "effect/Iterable"
39
+ import * as Layer from "effect/Layer"
40
+ import * as Option from "effect/Option"
41
+ import * as Predicate from "effect/Predicate"
42
+ import * as UndefinedOr from "effect/UndefinedOr"
43
+ import * as AtomRegistry from "effect/reactivity/AtomRegistry"
44
+ import * as Scope from "effect/Scope"
45
+ import * as WardicConfigValue from "@wardic/core/unstable/WardicConfigValue"
46
+ import type * as Ward from "../Ward.ts"
47
+ import type { MakeOptions } from "../Wardic.ts"
48
+ import { reactivity } from "./reactivity.ts"
49
+ import { rootConfigValueOf } from "./tree.ts"
50
+ import { DEV } from "@wardic/foldkit/internal/dev"
51
+
52
+ /** A live **Provider**: Wardic's services built on an app's `env`, read once, as a Solid provider's context value holds them. */
53
+ export interface Provider {
54
+ /** Its runtime: the Runner the legs fork on, with the memo map its Features build into. */
55
+ readonly runtime: Feature.FeatureRuntime
56
+ /** Its services, built: what `Wardic.provide` runs a Command's Effect with. */
57
+ readonly context: Context.Context<Feature.ProviderServices>
58
+ /** Its Frame loop, for the binding's hint (decision 32). */
59
+ readonly loop: FrameLoop.FrameLoop["Service"]
60
+ /** Its Atom registry: what Live values are read through (decision 16). */
61
+ readonly atoms: AtomRegistry.AtomRegistry
62
+ /** The Environment's Renderer (ADR-0003): what a presence's retained node commits its exit through. */
63
+ readonly renderer: Renderer.Renderer["Service"]
64
+ /** Its flush gate (ADR-0006). */
65
+ readonly gate: FlushGate.Shape
66
+ /** Whether reduced motion applies now (ADR-0029): the user's preference, read as each animation starts. */
67
+ readonly reducedMotion: () => boolean
68
+ /** Whether the user prefers reduced motion now, through the Probe's atom: what a `w.Config` setting is applied with. */
69
+ readonly prefers: () => boolean
70
+ readonly positionalKeys: ReducedMotion.PositionalKeys["Service"]
71
+ readonly defaultTransition: DefaultTransition.DefaultTransition["Service"]
72
+ /** Its elements' reads of their values (#672): the Environment's, the DOM's where it gives none. */
73
+ readonly valueReads: ElementSetup.ElementValueReads
74
+ /** The Environment's Refresh frames (ADR-0031), for what waits a frame out; `undefined` for one that gives none. */
75
+ readonly frames: RefreshFrameSource.Shape | undefined
76
+ /** Its Features (#511), each built on first need. */
77
+ readonly registry: Feature.FeatureRegistry
78
+ /**
79
+ * The Handle's Features in it (#516; #793, Q2): their services now, those given built on first need
80
+ * and each load's built as it arrives, and whether a load is still on its way.
81
+ */
82
+ readonly features: Feature.Own
83
+ /** Run `recheck` as a load's Features arrive, until what's returned is called: an element re-checks what it wants then (Q15). */
84
+ readonly onFeatures: (recheck: () => void) => () => void
85
+ /** The Scope the Handle owns it in: closed once its last element has left. */
86
+ readonly scope: Scope.Closeable
87
+ /** The element carrying `w.Provider(options)`, while it's mounted: what the subtree options (slice 2) hang on, and what a selector resolves under. */
88
+ root: Element | undefined
89
+ /** Its members, counted: its mounted `w.*` elements, and the Commands' animations and `provide`s while they run. */
90
+ elements: number
91
+ /** The Mounts whose view DevTools replay has (decision 34): while any, no hint is given from a provider-wide delivery. */
92
+ readonly pausedViews: Set<object>
93
+ /** Whether DevTools replay has a view now. */
94
+ readonly paused: () => boolean
95
+ }
96
+
97
+ /** How the Measure passes are triggered (decision 30; #792, Q17): `Wardic.make`'s `layoutTrigger` and `layoutAttributes`. */
98
+ export interface LayoutOptions {
99
+ readonly trigger: "patch" | "declared" | undefined
100
+ readonly attributes: ReadonlyArray<string> | undefined
101
+ }
102
+
103
+ /** What a Handle holds of its provider: the live one, the `Deferred` a build in flight completes, and its Features. */
104
+ export interface State {
105
+ readonly env: WardicServices.WardicEnv
106
+ /** Its Features (#516), as a Wardic instance's: those given, and each load started once per Handle (dom's `InstanceFeatures`); none without any. */
107
+ readonly instance: Feature.InstanceFeatures | undefined
108
+ /** The Handle's app-wide config (`Wardic.make({ config })`), the root of every element's `w.Config` chain; none without one. */
109
+ readonly rootConfig: WardicConfigValue.WardicConfigValue | undefined
110
+ /** How its Measure passes are triggered (decision 30). */
111
+ readonly layout: LayoutOptions
112
+ /**
113
+ * Whether the render under way is a View Transition's (decision 33): the next pass asked for by the
114
+ * app's own changes, a `w.LayoutDependency` change or `Wardic.animateLayout` is an Instant change of
115
+ * the layout. Set by each decision, cleared by the pass that consumes it.
116
+ */
117
+ transitioning: boolean
118
+ deferred: Deferred.Deferred<Provider>
119
+ live: Provider | undefined
120
+ /** Whether a build is in flight: an `env` that waits as it builds has the elements after the first await the `Deferred`. */
121
+ building: boolean
122
+ /** A server render's Appear animations (#794, Q3, Q13): `Wardic.make({ appear, nonce })`, read by the walk at the Provider element's build. */
123
+ readonly server: ServerOptions
124
+ /** On a server, in development (#794, Q4): the render under way, or none between renders. */
125
+ render: ServerRender | undefined
126
+ /** Development's words on the server, each said once a Handle. */
127
+ readonly said: Set<string>
128
+ /**
129
+ * Whether a client render names each element's Appear slot (#794, Q9 and Q10): the hydration render,
130
+ * and every render after it while a Handoff is still under way, so hydration keeps the inline
131
+ * `animation` the CSS plays through and no render strips one before its ward has taken it over. Set
132
+ * by `wardic.hydrate` when the page carries the Appear chunk a server rendered; cleared once every
133
+ * Handoff the hydration patch's Mounts found has released (its first commit), or, with none found,
134
+ * after those Mounts ({@link hydrationMounted}).
135
+ */
136
+ hydrating: boolean
137
+ /** The Handoffs under way: hydrated elements whose Appear animation their ward hasn't yet taken over. */
138
+ pending: number
139
+ /** The live `w.Presence`s (#840), each with what the Handle calls on it: see {@link LivePresence}. */
140
+ readonly presences: Set<LivePresence>
141
+ /** Whether the live presences' snapshots stand (#840): taken by {@link snapshotPopLayouts}, spent by {@link snapshotSpent}. */
142
+ snapshotted: boolean
143
+ }
144
+
145
+ /**
146
+ * A live `w.Presence`'s hooks the Handle calls (#840): `snapshot`, its children measured where they are,
147
+ * ahead of a patch, which `popLayout` pins the next change's leavers at; `flush`, its delivery run now
148
+ * from the records its observer holds, ahead of a `w.*` element's mount, so a presence inside an entering
149
+ * child starts that child's elements after this one has pinned its leavers.
150
+ */
151
+ export interface LivePresence {
152
+ readonly snapshot: () => void
153
+ readonly flush: () => void
154
+ }
155
+
156
+ /**
157
+ * Every live `popLayout` presence's children measured where they are (#840): called as a view renders a
158
+ * `w.Presence({ mode: "popLayout" })` element, before that render's patch. A presence's delivery comes a
159
+ * microtask after the patch, when a sibling the patch put in has already moved a leaver, so the box to
160
+ * pin the leaver at is read here, as Motion's `PopChild` reads it before React's update. Taken once for
161
+ * every such element a view renders: the snapshots stand until a microtask later, when the patch's
162
+ * deliveries have had them, or until a delivery spends them ({@link snapshotSpent}), so a render after
163
+ * it in the same task, as a Mount's message brings, measures afresh.
164
+ */
165
+ export const snapshotPopLayouts = (state: State): void => {
166
+ if (state.snapshotted) return
167
+ Iter.forEach(state.presences, (presence) => presence.snapshot())
168
+ state.snapshotted = true
169
+ queueMicrotask(() => {
170
+ state.snapshotted = false
171
+ })
172
+ }
173
+
174
+ /** The live presences' snapshots spent (#840): what a presence's delivery says as it tells its controller what's shown, which pins at the snapshot and clears it. */
175
+ export const snapshotSpent = (state: State): void => {
176
+ state.snapshotted = false
177
+ }
178
+
179
+ /** Every live presence's delivery run now (#840): what a `w.*` element's Mount does before the element registers anything. */
180
+ export const flushPresences = (state: State): void => {
181
+ Iter.forEach(state.presences, (presence) => presence.flush())
182
+ }
183
+
184
+ /** What a Handle renders a server's Appear animations with (ADR-0044; #794): `Wardic.make`'s `appear` and `nonce`. */
185
+ export interface ServerOptions {
186
+ readonly appear: boolean | "explain" | undefined
187
+ readonly nonce: string | undefined
188
+ }
189
+
190
+ /**
191
+ * A server render under way, in development (#794, Q4): opened by its first `w.*` element and closed by
192
+ * a microtask after the view's build (one synchronous call, the Provider element built last), when it
193
+ * gets its word with no Provider element, or with more than one. One a tick: two views built in one
194
+ * synchronous run share it.
195
+ */
196
+ export interface ServerRender {
197
+ /** Its Provider elements, counted as they build. */
198
+ providers: number
199
+ }
200
+
201
+ /** Development's word on a server render with no Provider element (#794, Q4): the Starting style alone, no Appear animation. */
202
+ const NO_PROVIDER =
203
+ "wardic.appear: a w.* element rendered on a server with no w.Provider() above it keeps its Starting style until the script runs: its Appear animation needs the Provider element, which renders the rules. Put w.Provider() on the topmost w.* element."
204
+
205
+ /** Development's word on more than one Provider element in a server render: their Appear rules collide, and a nested one's are dropped for the one above (the client reports and ignores a second). */
206
+ const MANY_PROVIDERS =
207
+ "wardic.appear: more than one w.Provider() in a server render: the Appear rules of one collide with another's, and a nested one's are dropped for the one above it. Give w.Provider() once, on the topmost w.* element."
208
+
209
+ /** Whether a Handle's server render plays Appear animations: unless `Wardic.make({ appear: false })` (ADR-0044 decision 5). */
210
+ export const appearsOn = (options: ServerOptions): boolean => options.appear !== false
211
+
212
+ /**
213
+ * `wardic.hydrate`'s word (#794, Q10): whether the page carries an Appear chunk, so the hydration render
214
+ * names each element's slot ({@link State.hydrating}); no Handoff under way yet.
215
+ */
216
+ export const hydrationStarts = (state: State, chunked: boolean): void => {
217
+ state.hydrating = chunked
218
+ state.pending = 0
219
+ }
220
+
221
+ /**
222
+ * A Mount's word while hydration's window is open (#794, Q10): `handoff`, whether its element's Appear
223
+ * animation was found to take over. One found is counted in until what's returned is called, at its
224
+ * first commit (the Handoff's release) or at its teardown, and the last one out closes the window. A
225
+ * microtask after the hydration patch's Mounts, which run in one task, closes it with none found. A
226
+ * render in the window names each slot as the hydration render did; the first after it names none.
227
+ */
228
+ export const hydrationMounted = (state: State, handoff: boolean): (() => void) => {
229
+ if (Bool.not(state.hydrating)) return constVoid
230
+ if (handoff) state.pending++
231
+ queueMicrotask(() => closeUnlessPending(state))
232
+ let released = false
233
+ return () => {
234
+ if (released) return
235
+ released = true
236
+ if (Bool.not(handoff)) return
237
+ state.pending--
238
+ closeUnlessPending(state)
239
+ }
240
+ }
241
+
242
+ /** The window closed, unless a Handoff is still under way. */
243
+ const closeUnlessPending = (state: State): void => {
244
+ if (state.pending > 0) return
245
+ state.hydrating = false
246
+ }
247
+
248
+ /** Note a `w.*` element's build on a server, in development ({@link ServerRender}): `provider` when it carries `w.Provider()`. None of the words under `appear: false`. */
249
+ export const noteServerRender = (state: State, provider: boolean): void => {
250
+ const render = UndefinedOr.match(state.render, {
251
+ onDefined: identity,
252
+ onUndefined: () => {
253
+ const opened: ServerRender = { providers: 0 }
254
+ state.render = opened
255
+ queueMicrotask(() => {
256
+ state.render = undefined
257
+ if (Bool.not(appearsOn(state.server))) return
258
+ if (opened.providers === 0) sayOnce(state, NO_PROVIDER)
259
+ if (opened.providers > 1) sayOnce(state, MANY_PROVIDERS)
260
+ })
261
+ return opened
262
+ },
263
+ })
264
+ if (provider) render.providers++
265
+ }
266
+
267
+ /** `message` said once a Handle, with Effect's logger: a server builds no runtime from the app's `env` (dom's `explainerOf` says its words so too). */
268
+ const sayOnce = (state: State, message: string): void => {
269
+ if (state.said.has(message)) return
270
+ state.said.add(message)
271
+ Effect.runSync(Effect.logWarning(message))
272
+ }
273
+
274
+ // Module state (#460, Q7): each Handle's state, held weakly by the Handle, for the Commands' Effects.
275
+ const states = new WeakMap<object, State>()
276
+
277
+ /** Keep `state` as `handle`'s, for {@link stateOf}. */
278
+ export const remember = (handle: object, state: State): void => {
279
+ states.set(handle, state)
280
+ }
281
+
282
+ /** The state of a Handle `Wardic.make` made: what `Wardic.animate` and `provide` reach through the `Wardic` service. */
283
+ export const stateOf = (handle: object): State => UndefinedOr.getOrThrow(states.get(handle))
284
+
285
+ /**
286
+ * The registry a Handle's Live values are read through now (#791, Q12): the live Provider's, else a
287
+ * scratch one, which gives a plain Atom its value and a derived one its initial, as a server render
288
+ * reads them, for a Starting style rendered before the Provider exists.
289
+ */
290
+ export const registryOf =
291
+ (state: State): (() => AtomRegistry.AtomRegistry) =>
292
+ () =>
293
+ UndefinedOr.match(state.live, { onUndefined: LiveStyle.serverRegistryOf, onDefined: (provider) => provider.atoms })
294
+
295
+ /** A Handle's state: no provider yet. */
296
+ export const makeState = (options: MakeOptions<Feature.InstanceFeaturesProp>): State => ({
297
+ env: options.env,
298
+ instance: UndefinedOr.map(options.features, InstanceFeatures.instanceFeaturesOf),
299
+ rootConfig: rootConfigValueOf(options.config),
300
+ layout: { trigger: options.layoutTrigger, attributes: options.layoutAttributes },
301
+ transitioning: false,
302
+ deferred: Deferred.makeUnsafe<Provider>(),
303
+ live: undefined,
304
+ building: false,
305
+ server: { appear: options.appear, nonce: options.nonce },
306
+ render: undefined,
307
+ said: new Set(),
308
+ hydrating: false,
309
+ pending: 0,
310
+ presences: new Set(),
311
+ snapshotted: false,
312
+ })
313
+
314
+ /**
315
+ * The service of a Feature the Handle has, built now if nothing has built it (#792, Q9): what
316
+ * `w.Presence` finds its controller by, and a gesture its recognizer. `undefined` when the Handle wasn't
317
+ * given the Feature, or its load hasn't arrived.
318
+ */
319
+ export const featureIn = <I, S>(provider: Provider, key: Context.Key<I, S>): S | undefined => GestureFeatures.serviceIn(provider.features.services(), key)
320
+
321
+ /** A load of the Handle's Features that failed (#793, Q15): reported once, and the rest stand. */
322
+ const LOAD_FAILED = "wardic.features: a load of the Handle's Features failed; its Features are left out"
323
+
324
+ /** Development's word on a Feature the Handle wasn't given (#511, ADR-0067 decision 7): dom's, with how a Handle takes one. */
325
+ export const missingMessage = (feature: string, what: string): string =>
326
+ Feature.missingMessage(feature, what, "@wardic/foldkit", `which this Handle wasn't given. Add it: \`import { Features } from "@wardic/foldkit"\`, then \`Wardic.make({ env, features: [Features.${feature}] })\`.`)
327
+
328
+ /**
329
+ * Development's word on `feature`, wanted by an element without being given (#511, ADR-0067 decision 7):
330
+ * once per provider, and not while a load is on its way (#793, Q15), which may bring it.
331
+ */
332
+ export const warnMissing = (provider: Provider, feature: string, what: string): void => {
333
+ if (DEV && Bool.not(provider.features.pending())) provider.registry.warnOnce(feature, missingMessage(feature, what))
334
+ }
335
+
336
+ /** What reports an element's failure on the provider, `label` with its cause, annotated with the element's id. */
337
+ export const reporterOf =
338
+ (provider: Provider, id: string): ((label: string, cause: Cause.Cause<never>) => void) =>
339
+ (label, cause) => {
340
+ provider.runtime.runFork(Report.failure(label, cause).pipe(Effect.annotateLogs({ id })))
341
+ }
342
+
343
+ /** No Features: a Handle made without any. */
344
+ const NO_FEATURES: Feature.Own = { services: () => Feature.NONE, pending: constFalse }
345
+
346
+ /** A second `w.Provider()` for one Handle, while the first's element is mounted: reported, then ignored. */
347
+ const SECOND_PROVIDER =
348
+ "wardic.provider: a second w.Provider() mounted while this Handle's is. A Handle has one: put w.Provider() on one w.* element at " +
349
+ "the top of the view, or make a Handle (Wardic.make) for each program."
350
+
351
+ /** An Option's value, or `undefined`: an optional Environment member read from a built context. */
352
+ const optional = <S extends Context.Service<any, any>>(context: Context.Context<never>, service: S): Context.Service.Shape<S> | undefined =>
353
+ Option.getOrUndefined(Context.getOption(context as Context.Context<S>, service))
354
+
355
+ /**
356
+ * Build Wardic's Layer on `state`'s `env` into a Scope of the Handle's own, with the flush gate and the
357
+ * projection options a provider adds (ADR-0006), on the current fiber: the first element's Mount's.
358
+ */
359
+ const build = (state: State): Effect.Effect<Provider> =>
360
+ Effect.gen(function* () {
361
+ const pausedViews = new Set<object>()
362
+ const scope = Scope.makeUnsafe()
363
+ const memoMap = Layer.makeMemoMapUnsafe()
364
+ // Read as each layout animation starts (slice 2), through the Provider's own reader once it's made.
365
+ let reducedMotionNow: () => boolean = constFalse
366
+ const projection: ProjectionSystem.Options = { reducedMotion: () => reducedMotionNow() }
367
+ const layer = Layer.merge(FlushGate.layer({ batch: (apply) => apply() }), Layer.succeed(Feature.ProjectionOptions)(projection)).pipe(Layer.provideMerge(state.env))
368
+ const context = yield* Layer.buildWithMemoMap(layer, memoMap, scope)
369
+ const runner = yield* Effect.provideContext(WardicServices.makeRunner<Feature.ProviderServices>(), Context.add(context, Scope.Scope, scope))
370
+ const runtime: Feature.FeatureRuntime = { ...runner, memoMap }
371
+ // The user's preference, through the Probe's atom (ADR-0029); an app's setting comes with `w.Config` (slice 1, PR 2).
372
+ const atoms = Context.get(context, AtomRegistry.AtomRegistry)
373
+ const probe = Context.get(context, Probe.Probe)
374
+ const prefers = (): boolean => atoms.get(probe.prefersReducedMotion)
375
+ const reducedMotion = (): boolean => ReducedMotion.applies("user", prefers())
376
+ reducedMotionNow = reducedMotion
377
+ const services = context as Context.Context<never>
378
+ // Its Features' Scope is a child of the runtime's, closed with it: nothing more to dispose.
379
+ const registry = Feature.clientRegistry(runtime, () => Promise.resolve())
380
+ // The Handle's Features in it (#793, Q2 and Q15): each load started now, its arrival told to the
381
+ // elements' re-checks directly, since no patch ran; a failed load reported once.
382
+ const rechecks = new Set<() => void>()
383
+ const arrived = (): void => Iter.forEach(rechecks, (recheck) => recheck())
384
+ const host: Feature.InstanceHost = { reactivity: { ...reactivity, trigger: () => ({ track: constVoid, notify: arrived }) }, server: false, report: (cause) => runner.runFork(Report.failure(LOAD_FAILED, cause)) }
385
+ const features = UndefinedOr.match(state.instance, { onUndefined: () => NO_FEATURES, onDefined: (instance) => instance.own(registry, host) })
386
+ return {
387
+ runtime,
388
+ context,
389
+ loop: Context.get(context, FrameLoop.FrameLoop),
390
+ atoms,
391
+ gate: Context.get(context, FlushGate.FlushGate),
392
+ reducedMotion,
393
+ prefers,
394
+ renderer: Context.get(context, Renderer.Renderer),
395
+ positionalKeys: Context.get(context, ReducedMotion.PositionalKeys),
396
+ defaultTransition: Context.get(context, DefaultTransition.DefaultTransition),
397
+ valueReads: ElementSetup.valueReadsOf({
398
+ ownValues: optional(services, OwnValues.OwnValues),
399
+ measuredPairs: optional(services, MeasuredPairs.MeasuredPairs),
400
+ variableValues: optional(services, VariableValues.VariableValues),
401
+ }),
402
+ frames: optional(services, RefreshFrameSource.RefreshFrameSource),
403
+ registry,
404
+ features,
405
+ onFeatures: (recheck) => {
406
+ rechecks.add(recheck)
407
+ return () => {
408
+ rechecks.delete(recheck)
409
+ }
410
+ },
411
+ scope,
412
+ root: undefined,
413
+ elements: 0,
414
+ pausedViews,
415
+ paused: () => pausedViews.size > 0,
416
+ }
417
+ })
418
+
419
+ /**
420
+ * The Handle's Provider for a mounting element: the live one; else, with a build in flight, the one
421
+ * its `Deferred` completes with; else built now, on this fiber. With `options` (the element carries
422
+ * `w.Provider(options)`), `element` becomes the Provider's root, unless another is mounted as one.
423
+ */
424
+ export const providerFor = (state: State, element: Element | undefined, options: Ward.ProviderOptions | undefined): Effect.Effect<Provider> =>
425
+ Effect.gen(function* () {
426
+ let provider = state.live
427
+ if (Predicate.isUndefined(provider)) provider = yield* Bool.match(state.building, { onTrue: () => Deferred.await(state.deferred), onFalse: () => first(state) })
428
+ if (Predicate.isNotUndefined(options)) yield* UndefinedOr.match(element, { onUndefined: () => Effect.void, onDefined: (root) => takeRoot(provider, root) })
429
+ return provider
430
+ })
431
+
432
+ /**
433
+ * Reduced motion (ADR-0029) under `value`, the nearest `w.Config` (decision 22): its setting applied to
434
+ * the user's preference, read as each animation starts; the Provider's own where no `w.Config` is above.
435
+ */
436
+ export const reducedMotionUnder = (provider: Provider, value: WardicConfigValue.WardicConfigValue | undefined): (() => boolean) =>
437
+ UndefinedOr.match(value, {
438
+ onUndefined: () => provider.reducedMotion,
439
+ onDefined: (config) => () => ReducedMotion.applies(UndefinedOr.match(WardicConfigValue.settingOf(config), { onUndefined: () => "user" as const, onDefined: identity }), provider.prefers()),
440
+ })
441
+
442
+ /** The first element's build: the Provider made live, and the `Deferred` done for the elements after it. */
443
+ const first = (state: State): Effect.Effect<Provider> =>
444
+ Effect.gen(function* () {
445
+ state.building = true
446
+ const provider = yield* build(state)
447
+ state.building = false
448
+ state.live = provider
449
+ Deferred.doneUnsafe(state.deferred, Effect.succeed(provider))
450
+ return provider
451
+ })
452
+
453
+ /** `element` as `provider`'s root, unless another is mounted as one: then reported, and ignored. */
454
+ const takeRoot = (provider: Provider, element: Element): Effect.Effect<void> => {
455
+ if (Predicate.isUndefined(provider.root)) {
456
+ provider.root = element
457
+ return Effect.void
458
+ }
459
+ return Report.failure(SECOND_PROVIDER, Cause.die(new Error(SECOND_PROVIDER)))
460
+ }
461
+
462
+ /**
463
+ * Count a member in: a mounted element, or a Command's animation or `provide` (`undefined`, never the
464
+ * root). Returns what its release calls: the count out, the root given up when it was this element, and,
465
+ * once the last member has left, the Scope closed at the end of the task, so a patch that removes every
466
+ * element and inserts new ones keeps the runtime.
467
+ */
468
+ export const joined = (state: State, provider: Provider, member: Element | undefined): (() => void) => {
469
+ provider.elements++
470
+ let left = false
471
+ return () => {
472
+ if (left) return
473
+ left = true
474
+ provider.elements--
475
+ if (Bool.and(Predicate.isNotUndefined(member), provider.root === member)) provider.root = undefined
476
+ if (provider.elements > 0) return
477
+ queueMicrotask(() => {
478
+ if (provider.elements > 0) return
479
+ if (state.live !== provider) return
480
+ state.live = undefined
481
+ state.deferred = Deferred.makeUnsafe<Provider>()
482
+ // Its Features ended first (what the layout's observer goes with), then its Scope.
483
+ Effect.runFork(Effect.andThen(Effect.promise(() => provider.registry.dispose()), Scope.close(provider.scope, Exit.void)))
484
+ })
485
+ }
486
+ }