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