@wardic/dom 1.0.1 → 1.1.1

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 (289) hide show
  1. package/dist/Appear.d.ts +3 -2
  2. package/dist/Appear.d.ts.map +1 -1
  3. package/dist/Appear.js +4 -3
  4. package/dist/Appear.js.map +1 -1
  5. package/dist/DomProjectionSystem.js +3 -3
  6. package/dist/DomProjectionSystem.js.map +1 -1
  7. package/dist/FlushGate.d.ts +6 -6
  8. package/dist/FlushGate.d.ts.map +1 -1
  9. package/dist/FlushGate.js +11 -8
  10. package/dist/FlushGate.js.map +1 -1
  11. package/dist/ReorderController.js +3 -3
  12. package/dist/ReorderController.js.map +1 -1
  13. package/dist/Report.d.ts +1 -1
  14. package/dist/Report.d.ts.map +1 -1
  15. package/dist/Report.js +3 -2
  16. package/dist/Report.js.map +1 -1
  17. package/dist/Style.d.ts +2 -1
  18. package/dist/Style.d.ts.map +1 -1
  19. package/dist/Style.js +3 -1
  20. package/dist/Style.js.map +1 -1
  21. package/dist/TimelineValue.d.ts +18 -0
  22. package/dist/TimelineValue.d.ts.map +1 -0
  23. package/dist/TimelineValue.js +20 -0
  24. package/dist/TimelineValue.js.map +1 -0
  25. package/dist/index.d.ts +13 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +10 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/internal/appear.d.ts +10 -4
  30. package/dist/internal/appear.d.ts.map +1 -1
  31. package/dist/internal/appear.js +18 -8
  32. package/dist/internal/appear.js.map +1 -1
  33. package/dist/internal/batch-handoff.d.ts +25 -0
  34. package/dist/internal/batch-handoff.d.ts.map +1 -0
  35. package/dist/internal/batch-handoff.js +64 -0
  36. package/dist/internal/batch-handoff.js.map +1 -0
  37. package/dist/internal/drag-defaults.js +4 -1
  38. package/dist/internal/drag-defaults.js.map +1 -1
  39. package/dist/internal/gate-environment.d.ts +4 -0
  40. package/dist/internal/gate-environment.d.ts.map +1 -0
  41. package/dist/internal/gate-environment.js +21 -0
  42. package/dist/internal/gate-environment.js.map +1 -0
  43. package/dist/internal/projection.d.ts.map +1 -1
  44. package/dist/internal/projection.js +22 -21
  45. package/dist/internal/projection.js.map +1 -1
  46. package/dist/internal/renderer.d.ts +13 -0
  47. package/dist/internal/renderer.d.ts.map +1 -1
  48. package/dist/internal/renderer.js +21 -0
  49. package/dist/internal/renderer.js.map +1 -1
  50. package/dist/internal/reorder.d.ts +2 -2
  51. package/dist/internal/reorder.d.ts.map +1 -1
  52. package/dist/internal/reorder.js +2 -2
  53. package/dist/internal/reorder.js.map +1 -1
  54. package/dist/internal/scroll.d.ts +17 -0
  55. package/dist/internal/scroll.d.ts.map +1 -1
  56. package/dist/internal/scroll.js +23 -15
  57. package/dist/internal/scroll.js.map +1 -1
  58. package/dist/internal/starting-style.d.ts +0 -83
  59. package/dist/internal/starting-style.d.ts.map +1 -1
  60. package/dist/internal/starting-style.js +16 -143
  61. package/dist/internal/starting-style.js.map +1 -1
  62. package/dist/internal/timeline.d.ts +56 -0
  63. package/dist/internal/timeline.d.ts.map +1 -0
  64. package/dist/internal/timeline.js +389 -0
  65. package/dist/internal/timeline.js.map +1 -0
  66. package/dist/unstable/AppearAnimations.d.ts +191 -0
  67. package/dist/unstable/AppearAnimations.d.ts.map +1 -0
  68. package/dist/unstable/AppearAnimations.js +561 -0
  69. package/dist/unstable/AppearAnimations.js.map +1 -0
  70. package/dist/unstable/BatchMembers.d.ts +513 -0
  71. package/dist/unstable/BatchMembers.d.ts.map +1 -0
  72. package/dist/unstable/BatchMembers.js +2490 -0
  73. package/dist/unstable/BatchMembers.js.map +1 -0
  74. package/dist/unstable/DomValues.d.ts +25 -0
  75. package/dist/unstable/DomValues.d.ts.map +1 -0
  76. package/dist/unstable/DomValues.js +45 -0
  77. package/dist/unstable/DomValues.js.map +1 -0
  78. package/dist/unstable/DragConstraints.d.ts +48 -0
  79. package/dist/unstable/DragConstraints.d.ts.map +1 -0
  80. package/dist/unstable/DragConstraints.js +49 -0
  81. package/dist/unstable/DragConstraints.js.map +1 -0
  82. package/dist/unstable/DragControls.d.ts +50 -0
  83. package/dist/unstable/DragControls.d.ts.map +1 -0
  84. package/dist/unstable/DragControls.js +55 -0
  85. package/dist/unstable/DragControls.js.map +1 -0
  86. package/dist/unstable/DragDefaults.d.ts +34 -0
  87. package/dist/unstable/DragDefaults.d.ts.map +1 -0
  88. package/dist/unstable/DragDefaults.js +47 -0
  89. package/dist/unstable/DragDefaults.js.map +1 -0
  90. package/dist/unstable/DragTrack.d.ts +236 -0
  91. package/dist/unstable/DragTrack.d.ts.map +1 -0
  92. package/dist/unstable/DragTrack.js +646 -0
  93. package/dist/unstable/DragTrack.js.map +1 -0
  94. package/dist/unstable/DragTransition.d.ts +22 -0
  95. package/dist/unstable/DragTransition.d.ts.map +1 -0
  96. package/dist/unstable/DragTransition.js +31 -0
  97. package/dist/unstable/DragTransition.js.map +1 -0
  98. package/dist/unstable/ElementSetup.d.ts +144 -0
  99. package/dist/unstable/ElementSetup.d.ts.map +1 -0
  100. package/dist/unstable/ElementSetup.js +297 -0
  101. package/dist/unstable/ElementSetup.js.map +1 -0
  102. package/dist/unstable/Feature.d.ts +221 -0
  103. package/dist/unstable/Feature.d.ts.map +1 -0
  104. package/dist/unstable/Feature.js +281 -0
  105. package/dist/unstable/Feature.js.map +1 -0
  106. package/dist/unstable/GestureFeatures.d.ts +30 -0
  107. package/dist/unstable/GestureFeatures.d.ts.map +1 -0
  108. package/dist/unstable/GestureFeatures.js +32 -0
  109. package/dist/unstable/GestureFeatures.js.map +1 -0
  110. package/dist/unstable/GestureInfo.d.ts +61 -0
  111. package/dist/unstable/GestureInfo.d.ts.map +1 -0
  112. package/dist/unstable/GestureInfo.js +23 -0
  113. package/dist/unstable/GestureInfo.js.map +1 -0
  114. package/dist/unstable/Imperative.d.ts +214 -0
  115. package/dist/unstable/Imperative.d.ts.map +1 -0
  116. package/dist/unstable/Imperative.js +768 -0
  117. package/dist/unstable/Imperative.js.map +1 -0
  118. package/dist/unstable/Instant.d.ts +46 -0
  119. package/dist/unstable/Instant.d.ts.map +1 -0
  120. package/dist/unstable/Instant.js +49 -0
  121. package/dist/unstable/Instant.js.map +1 -0
  122. package/dist/unstable/LayoutGroup.d.ts +14 -0
  123. package/dist/unstable/LayoutGroup.d.ts.map +1 -0
  124. package/dist/unstable/LayoutGroup.js +31 -0
  125. package/dist/unstable/LayoutGroup.js.map +1 -0
  126. package/dist/unstable/LayoutMember.d.ts +127 -0
  127. package/dist/unstable/LayoutMember.d.ts.map +1 -0
  128. package/dist/unstable/LayoutMember.js +176 -0
  129. package/dist/unstable/LayoutMember.js.map +1 -0
  130. package/dist/unstable/LiveStyle.d.ts +171 -0
  131. package/dist/unstable/LiveStyle.d.ts.map +1 -0
  132. package/dist/unstable/LiveStyle.js +329 -0
  133. package/dist/unstable/LiveStyle.js.map +1 -0
  134. package/dist/unstable/MemberHold.d.ts +3 -0
  135. package/dist/unstable/MemberHold.d.ts.map +1 -0
  136. package/dist/unstable/MemberHold.js +223 -0
  137. package/dist/unstable/MemberHold.js.map +1 -0
  138. package/dist/unstable/OwnerScope.d.ts +16 -0
  139. package/dist/unstable/OwnerScope.d.ts.map +1 -0
  140. package/dist/unstable/OwnerScope.js +35 -0
  141. package/dist/unstable/OwnerScope.js.map +1 -0
  142. package/dist/unstable/PresenceController.d.ts +128 -0
  143. package/dist/unstable/PresenceController.d.ts.map +1 -0
  144. package/dist/unstable/PresenceController.js +1427 -0
  145. package/dist/unstable/PresenceController.js.map +1 -0
  146. package/dist/unstable/Press.d.ts +26 -0
  147. package/dist/unstable/Press.d.ts.map +1 -0
  148. package/dist/unstable/Press.js +19 -0
  149. package/dist/unstable/Press.js.map +1 -0
  150. package/dist/unstable/ServerInterpolators.d.ts +17 -0
  151. package/dist/unstable/ServerInterpolators.d.ts.map +1 -0
  152. package/dist/unstable/ServerInterpolators.js +20 -0
  153. package/dist/unstable/ServerInterpolators.js.map +1 -0
  154. package/dist/unstable/WardConfig.d.ts +567 -0
  155. package/dist/unstable/WardConfig.d.ts.map +1 -0
  156. package/dist/unstable/WardConfig.js +2 -0
  157. package/dist/unstable/WardConfig.js.map +1 -0
  158. package/dist/unstable/features/All.d.ts +24 -0
  159. package/dist/unstable/features/All.d.ts.map +1 -0
  160. package/dist/unstable/features/All.js +20 -0
  161. package/dist/unstable/features/All.js.map +1 -0
  162. package/dist/unstable/features/Colors.d.ts +12 -0
  163. package/dist/unstable/features/Colors.d.ts.map +1 -0
  164. package/dist/unstable/features/Colors.js +38 -0
  165. package/dist/unstable/features/Colors.js.map +1 -0
  166. package/dist/unstable/features/DomAnimation.d.ts +16 -0
  167. package/dist/unstable/features/DomAnimation.d.ts.map +1 -0
  168. package/dist/unstable/features/DomAnimation.js +19 -0
  169. package/dist/unstable/features/DomAnimation.js.map +1 -0
  170. package/dist/unstable/features/DomMax.d.ts +12 -0
  171. package/dist/unstable/features/DomMax.d.ts.map +1 -0
  172. package/dist/unstable/features/DomMax.js +14 -0
  173. package/dist/unstable/features/DomMax.js.map +1 -0
  174. package/dist/unstable/features/Drag.d.ts +5 -0
  175. package/dist/unstable/features/Drag.d.ts.map +1 -0
  176. package/dist/unstable/features/Drag.js +32 -0
  177. package/dist/unstable/features/Drag.js.map +1 -0
  178. package/dist/unstable/features/Focus.d.ts +5 -0
  179. package/dist/unstable/features/Focus.d.ts.map +1 -0
  180. package/dist/unstable/features/Focus.js +20 -0
  181. package/dist/unstable/features/Focus.js.map +1 -0
  182. package/dist/unstable/features/Hover.d.ts +5 -0
  183. package/dist/unstable/features/Hover.d.ts.map +1 -0
  184. package/dist/unstable/features/Hover.js +20 -0
  185. package/dist/unstable/features/Hover.js.map +1 -0
  186. package/dist/unstable/features/InView.d.ts +5 -0
  187. package/dist/unstable/features/InView.d.ts.map +1 -0
  188. package/dist/unstable/features/InView.js +20 -0
  189. package/dist/unstable/features/InView.js.map +1 -0
  190. package/dist/unstable/features/Input.d.ts +28 -0
  191. package/dist/unstable/features/Input.d.ts.map +1 -0
  192. package/dist/unstable/features/Input.js +31 -0
  193. package/dist/unstable/features/Input.js.map +1 -0
  194. package/dist/unstable/features/Keys.d.ts +95 -0
  195. package/dist/unstable/features/Keys.d.ts.map +1 -0
  196. package/dist/unstable/features/Keys.js +44 -0
  197. package/dist/unstable/features/Keys.js.map +1 -0
  198. package/dist/unstable/features/Layout.d.ts +43 -0
  199. package/dist/unstable/features/Layout.d.ts.map +1 -0
  200. package/dist/unstable/features/Layout.js +44 -0
  201. package/dist/unstable/features/Layout.js.map +1 -0
  202. package/dist/unstable/features/Pan.d.ts +5 -0
  203. package/dist/unstable/features/Pan.d.ts.map +1 -0
  204. package/dist/unstable/features/Pan.js +20 -0
  205. package/dist/unstable/features/Pan.js.map +1 -0
  206. package/dist/unstable/features/Press.d.ts +13 -0
  207. package/dist/unstable/features/Press.d.ts.map +1 -0
  208. package/dist/unstable/features/Press.js +10 -0
  209. package/dist/unstable/features/Press.js.map +1 -0
  210. package/dist/unstable/features/Scroll.d.ts +20 -0
  211. package/dist/unstable/features/Scroll.d.ts.map +1 -0
  212. package/dist/unstable/features/Scroll.js +34 -0
  213. package/dist/unstable/features/Scroll.js.map +1 -0
  214. package/dist/unstable/features/TimelineKeys.d.ts +7 -0
  215. package/dist/unstable/features/TimelineKeys.d.ts.map +1 -0
  216. package/dist/unstable/features/TimelineKeys.js +103 -0
  217. package/dist/unstable/features/TimelineKeys.js.map +1 -0
  218. package/package.json +4 -3
  219. package/src/Appear.ts +4 -2
  220. package/src/DomProjectionSystem.ts +3 -3
  221. package/src/FlushGate.ts +15 -12
  222. package/src/ReorderController.ts +3 -3
  223. package/src/Report.ts +3 -7
  224. package/src/Style.ts +4 -1
  225. package/src/TimelineValue.ts +19 -0
  226. package/src/index.ts +15 -5
  227. package/src/internal/appear.ts +20 -8
  228. package/src/internal/batch-handoff.ts +75 -0
  229. package/src/internal/drag-defaults.ts +4 -4
  230. package/src/internal/gate-environment.ts +21 -0
  231. package/src/internal/projection.ts +22 -21
  232. package/src/internal/renderer.ts +22 -0
  233. package/src/internal/reorder.ts +4 -4
  234. package/src/internal/scroll.ts +32 -15
  235. package/src/internal/starting-style.ts +5 -204
  236. package/src/internal/timeline.ts +480 -0
  237. package/src/unstable/AppearAnimations.ts +837 -0
  238. package/src/unstable/BatchMembers.ts +3085 -0
  239. package/src/unstable/DomValues.ts +53 -0
  240. package/src/unstable/DragConstraints.ts +107 -0
  241. package/src/unstable/DragControls.ts +98 -0
  242. package/src/unstable/DragDefaults.ts +57 -0
  243. package/src/unstable/DragTrack.ts +959 -0
  244. package/src/unstable/DragTransition.ts +46 -0
  245. package/src/unstable/ElementSetup.ts +411 -0
  246. package/src/unstable/Feature.ts +494 -0
  247. package/src/unstable/GestureFeatures.ts +38 -0
  248. package/src/unstable/GestureInfo.ts +85 -0
  249. package/src/unstable/Imperative.ts +1037 -0
  250. package/src/unstable/Instant.ts +93 -0
  251. package/src/unstable/LayoutGroup.ts +36 -0
  252. package/src/unstable/LayoutMember.ts +319 -0
  253. package/src/unstable/LiveStyle.ts +497 -0
  254. package/src/unstable/MemberHold.ts +211 -0
  255. package/src/unstable/OwnerScope.ts +35 -0
  256. package/src/unstable/PresenceController.ts +1747 -0
  257. package/src/unstable/Press.ts +43 -0
  258. package/src/unstable/ServerInterpolators.ts +39 -0
  259. package/src/unstable/WardConfig.ts +704 -0
  260. package/src/unstable/features/All.ts +39 -0
  261. package/src/unstable/features/Colors.ts +40 -0
  262. package/src/unstable/features/DomAnimation.ts +19 -0
  263. package/src/unstable/features/DomMax.ts +14 -0
  264. package/src/unstable/features/Drag.ts +34 -0
  265. package/src/unstable/features/Focus.ts +21 -0
  266. package/src/unstable/features/Hover.ts +21 -0
  267. package/src/unstable/features/InView.ts +21 -0
  268. package/src/unstable/features/Input.ts +37 -0
  269. package/src/unstable/features/Keys.ts +124 -0
  270. package/src/unstable/features/Layout.ts +75 -0
  271. package/src/unstable/features/Pan.ts +21 -0
  272. package/src/unstable/features/Press.ts +21 -0
  273. package/src/unstable/features/Scroll.ts +35 -0
  274. package/src/unstable/features/TimelineKeys.ts +115 -0
  275. package/dist/internal/gate.d.ts +0 -188
  276. package/dist/internal/gate.d.ts.map +0 -1
  277. package/dist/internal/gate.js +0 -458
  278. package/dist/internal/gate.js.map +0 -1
  279. package/dist/internal/report.d.ts +0 -30
  280. package/dist/internal/report.d.ts.map +0 -1
  281. package/dist/internal/report.js +0 -60
  282. package/dist/internal/report.js.map +0 -1
  283. package/dist/internal/runner.d.ts +0 -21
  284. package/dist/internal/runner.d.ts.map +0 -1
  285. package/dist/internal/runner.js +0 -48
  286. package/dist/internal/runner.js.map +0 -1
  287. package/src/internal/gate.ts +0 -598
  288. package/src/internal/report.ts +0 -69
  289. package/src/internal/runner.ts +0 -64
@@ -0,0 +1,1747 @@
1
+ /**
2
+ * `<AnimatePresence>`'s work (ADR-0007), for every DOM binding: each leaving child's retained node,
3
+ * its parent-driven exit, and the twins it hands back (ADR-0010 *Amendment (#181)*). Each binding's
4
+ * `AnimatePresence` resolves its children with its own framework and tells
5
+ * {@link PresenceController.present} which are present after each change. The DOM's presence types,
6
+ * core's protocol over elements, are here.
7
+ *
8
+ * Many children (#277, ADR-0048): a child is its DOM node, so one that leaves is the node that left
9
+ * the resolved children, each exiting on its own, in its place. A child that comes back mid-exit is
10
+ * a new node: under the leaver's `key` it takes over from where the leaver is (#286); without one it
11
+ * enters beside the leaver while the leaver finishes.
12
+ *
13
+ * `mode="wait"` (#277, ADR-0048): while a child exits, one entering is held off the page, its wards
14
+ * not started, and goes on it once the last leaver is gone. Its framework has built it already, so
15
+ * its own code has run; what waits is its place on the page and everything Wardic does with it.
16
+ *
17
+ * `mode="popLayout"` (#277, ADR-0048): a leaver is measured before the change and popped out of the
18
+ * flow where it was (`position: absolute`, its size kept), so the children after it take their
19
+ * places at once. Whatever the mode, the projection is told when a leaver is popped or removed, so
20
+ * a `layout` sibling animates into the space, as Motion's presence re-renders its children then.
21
+ *
22
+ * Unstable, for Wardic's own packages: public, with no semver promise.
23
+ *
24
+ * @module
25
+ */
26
+ // Unstable: ADR-0071, decision 5. #672: solid's `presence-controller.ts`, moved to dom for every DOM
27
+ // binding's presence, with the DOM's presence types (PR5-Q3).
28
+ import type * as Box from "@wardic/core/Box"
29
+ import type * as DefaultTransition from "@wardic/core/DefaultTransition"
30
+ import * as Frame from "@wardic/core/Frame"
31
+ import * as Spans from "@wardic/core/Spans"
32
+ import type * as FrameLoop from "@wardic/core/FrameLoop"
33
+ import * as InterpolatorRegistry from "@wardic/core/InterpolatorRegistry"
34
+ import type * as ReducedMotion from "@wardic/core/ReducedMotion"
35
+ import * as Renderer from "@wardic/core/Renderer"
36
+ import * as Values from "@wardic/core/Values"
37
+ import * as Machine from "@wardic/core/Machine"
38
+ import * as Microtask from "@wardic/core/Microtask"
39
+ import * as Velocity from "@wardic/core/Velocity"
40
+ import * as ProjectionSystem from "../ProjectionSystem.ts"
41
+ import * as DomRenderer from "../DomRenderer.ts"
42
+ import * as DomValues from "./DomValues.ts"
43
+ import * as Report from "../Report.ts"
44
+ import * as Variables from "../Variables.ts"
45
+ import * as Arr from "effect/Array"
46
+ import * as Bool from "effect/Boolean"
47
+ import * as Cause from "effect/Cause"
48
+ import * as Effect from "effect/Effect"
49
+ import type * as Fiber from "effect/Fiber"
50
+ import { constFalse, constUndefined, constVoid, identity } from "effect/Function"
51
+ import * as Option from "effect/Option"
52
+ import * as Iter from "effect/Iterable"
53
+ import * as Predicate from "effect/Predicate"
54
+ import * as Rec from "effect/Record"
55
+ import * as UndefinedOr from "effect/UndefinedOr"
56
+ import type * as WardConfig from "./WardConfig.ts"
57
+ import type * as CorePresenceRecord from "@wardic/core/unstable/PresenceRecord"
58
+ import * as RetargetLegs from "@wardic/core/unstable/RetargetLegs"
59
+ import type * as WardicServices from "@wardic/core/unstable/WardicServices"
60
+ import * as VariantTree from "@wardic/core/unstable/VariantTree"
61
+
62
+ // #672 (PR5-Q3): the DOM's presence types, core's protocol over Element, here with the DOM's presence:
63
+ // what a DOM binding's presence, its Batch and its public types name.
64
+ /** A child's live presence registration ({@link CorePresenceRecord.PresenceRecord}), its Subject an element. */
65
+ export type PresenceRecord = CorePresenceRecord.PresenceRecord<Element>
66
+
67
+ /** The value `<AnimatePresence>` publishes to descendant `createWard` spines ({@link CorePresenceRecord.PresenceContextValue}), over elements. */
68
+ export type PresenceContextValue = CorePresenceRecord.PresenceContextValue<Element>
69
+
70
+ /** What a presence hook registers ({@link CorePresenceRecord.PresenceWatch}), its Subject an element. */
71
+ export type PresenceWatch = CorePresenceRecord.PresenceWatch<Element>
72
+
73
+ /** Whether a value-map has any keys (an empty exit means "remove immediately"). */
74
+ const isEmpty = (values: Values.Values): boolean => Rec.isEmptyRecord(values)
75
+
76
+ /**
77
+ * An element's values as they're drawn, without its Transform template (#443): it rides in its
78
+ * presence record to draw its exit through, and isn't a value a child back under its key takes over.
79
+ */
80
+ const valuesDrawn = (values: Values.Values): Values.Values => Rec.remove(values, DomRenderer.TEMPLATE_KEY)
81
+
82
+ /** An exit's spring: the defaults, one object, so core decodes it once (#66). */
83
+
84
+ /** A record's place in the variant tree (#290): left out, a lone element's. */
85
+ const LONE: CorePresenceRecord.PresenceTree = { joins: false, provides: false, twin: false }
86
+
87
+ /** A record's place in the variant tree, {@link LONE} without one. */
88
+ const treeOf = (rec: PresenceRecord): CorePresenceRecord.PresenceTree => UndefinedOr.match(rec.tree, { onUndefined: () => LONE, onDefined: identity })
89
+
90
+ /** No elements: a leaving child with none inside it exiting. */
91
+ const NO_PARTS: ReadonlyArray<Element> = []
92
+
93
+ /** No records: nothing registered inside a leaving child. */
94
+ const NO_RECORDS: ReadonlyArray<PresenceRecord | undefined> = []
95
+
96
+ /** No record of its own: a plain leaving child (#392). */
97
+ const NO_OWN: ReadonlyArray<PresenceRecord> = []
98
+
99
+ /** A leaving element's exit, and its Variant children's, resolved at the leave (#290). */
100
+ interface ExitNode {
101
+ readonly rec: PresenceRecord
102
+ readonly exit: CorePresenceRecord.PresenceExit
103
+ readonly kids: ReadonlyArray<ExitNode>
104
+ }
105
+
106
+ /** Whether an exit node, or one under it, has anything to animate. */
107
+ const busy = (node: ExitNode): boolean => Bool.or(Bool.not(isEmpty(node.exit.values)), Arr.some(node.kids, busy))
108
+
109
+ /** No velocities: an element with no spine to read them from (#464: one with a spine starts its exit from its own). */
110
+ const NO_VELOCITIES: Readonly<Record<string, number>> = {}
111
+
112
+ /** Where an element is drawn (#286): its values, and each numeric key's velocity. */
113
+ type Drawn = CorePresenceRecord.PresenceSeed
114
+
115
+ /** No boxes: a leaver none of whose elements was on the page. */
116
+ const NO_BOXES: ReadonlyMap<Element, Box.Box> = new Map()
117
+
118
+ /** A Wardic element made under a presence (#286): its `key`, if it has one, and whether it's a twin. */
119
+ interface Made {
120
+ readonly key: string | number | undefined
121
+ readonly twin: boolean
122
+ }
123
+
124
+ /** Whether two lists of elements have the same shape (#286): as many, each pair the same tag. */
125
+ const sameShape = (a: ReadonlyArray<Element>, b: ReadonlyArray<Element>): boolean =>
126
+ Bool.and(a.length === b.length, Arr.every(Arr.zip(a, b), ([x, y]) => x.tagName === y.tagName))
127
+
128
+ /**
129
+ * Each numeric key's velocity from a step's frame (#286): its change since the step before, over
130
+ * the step's `dt` (seconds), and 0 once the frame settles. A key's first step sets nothing.
131
+ */
132
+ const measure = (velocities: Record<string, number>, last: Record<string, number>, frame: Frame.Frame<Values.Values>, dt: number): void => {
133
+ Arr.forEach(Rec.keys(frame.value), (key) => {
134
+ const now = frame.value[key]
135
+ if (Predicate.isString(now)) return
136
+ const before = last[key]
137
+ last[key] = now
138
+ if (frame.done) {
139
+ velocities[key] = 0
140
+ return
141
+ }
142
+ if (Predicate.isUndefined(before)) return
143
+ if (dt <= 0) return
144
+ velocities[key] = Velocity.between(before, now, dt)
145
+ })
146
+ }
147
+
148
+ /** A blend's machine, its numeric keys' velocities measured each step (#286): a tween's frames carry none. */
149
+ const measuredInto =
150
+ (velocities: Record<string, number>) =>
151
+ (machine: Machine.Machine<Frame.Frame<Values.Values>>): Machine.Machine<Frame.Frame<Values.Values>> =>
152
+ Machine.make({
153
+ settles: machine.settles,
154
+ span: machine.span,
155
+ start: () => {
156
+ const step = machine.start()
157
+ const last: Record<string, number> = {}
158
+ return (dt) => {
159
+ const frame = step(dt)
160
+ measure(velocities, last, frame, Math.min(dt, Machine.MAX_DT))
161
+ return frame
162
+ }
163
+ },
164
+ })
165
+
166
+ /**
167
+ * One leg of an exit (#277), as the spine runs a Retarget's, committing onto the retained `el`. Each
168
+ * key's velocity goes into `velocities` (#286): a spring's from its frames, a blend's measured, a
169
+ * snap's 0, so a child back under its key starts with it.
170
+ */
171
+ const exitRunOf = (
172
+ leg: RetargetLegs.Leg,
173
+ el: Element,
174
+ commitFrame: FrameLoop.Sink<Frame.Frame<Values.Values>>,
175
+ velocities: Record<string, number>,
176
+ ): Effect.Effect<unknown, never, WardicServices.WardicServices> => {
177
+ if (leg._tag === "Blend") {
178
+ return Effect.suspend(leg.machine).pipe(
179
+ InterpolatorRegistry.withKeyRules([Variables.values(el)]),
180
+ Effect.map(measuredInto(velocities)),
181
+ Effect.flatMap(Machine.run(commitFrame)),
182
+ )
183
+ }
184
+ if (leg._tag === "Follow") {
185
+ const key = leg.key
186
+ return Effect.suspend(() =>
187
+ leg.machine().pipe(
188
+ Machine.run((frame) => {
189
+ velocities[key] = UndefinedOr.match(frame.velocity, { onUndefined: () => 0, onDefined: identity })
190
+ return commitFrame({ ...frame, value: { [key]: frame.value } })
191
+ }),
192
+ ))
193
+ }
194
+ if (leg._tag === "Numbers") {
195
+ return Effect.suspend(() =>
196
+ leg.machine().pipe(
197
+ Machine.run((frame) => {
198
+ velocitiesInto(velocities, frame)
199
+ return commitFrame(frame)
200
+ }),
201
+ ))
202
+ }
203
+ Arr.forEach(leg.keys, (key) => {
204
+ velocities[key] = 0
205
+ })
206
+ return Effect.suspend(() => leg.machine().pipe(Machine.run(commitFrame)))
207
+ }
208
+
209
+ /** A Numbers leg's Frame's velocities written into `into`: a spring's by index (#663), as it writes no velocity record. */
210
+ const velocitiesInto = (into: Record<string, number>, frame: Frame.MultiPhysics): void => {
211
+ if (Frame.isSpringValues(frame)) {
212
+ Arr.forEach(frame.keys, (key, i) => {
213
+ into[key] = UndefinedOr.getOrThrow(frame.velocities[i])
214
+ })
215
+ return
216
+ }
217
+ Object.assign(into, frame.velocity)
218
+ }
219
+
220
+ /** How far in each name's keys of an exit start (#297): seconds, by name; `undefined` for an exit that isn't a list's. */
221
+ type DelayOf = (name: string | undefined) => number
222
+
223
+ /** At once, every name. */
224
+ const NO_DELAY: DelayOf = () => 0
225
+
226
+ /** An element's exit made ready to run (#297's PR 2): its node, where it starts, what each frame commits, and its velocities. */
227
+ interface PreparedExit {
228
+ readonly el: Element
229
+ readonly from: Values.Values
230
+ /** Its Keyframes of more than two stops (#429), `from` at their first. */
231
+ readonly stops: RetargetLegs.StopsByKey | undefined
232
+ readonly commitFrame: FrameLoop.Sink<Frame.Frame<Values.Values>>
233
+ readonly velocities: Record<string, number>
234
+ }
235
+
236
+ /**
237
+ * An exit's Measured pairs (#430): each key whose start and target differ in type, asked of the
238
+ * end-of-task batch, but a key with Keyframes of more than two stops (`stops`, #460). `undefined` with
239
+ * none, nearly every exit.
240
+ */
241
+ const exitMeasuredOf = (element: Element, from: Values.Values, to: Values.Values, stops: RetargetLegs.StopsByKey | undefined): RetargetLegs.MeasuredPairs | undefined => {
242
+ const pairs = Rec.filter(to, (target, key) => Bool.and(Bool.and(Object.hasOwn(from, key), Bool.not(RetargetLegs.hasManyStops(stops, key))), keepsMeasured(key, from[key], target)))
243
+ if (Rec.isEmptyRecord(pairs)) return undefined
244
+ return DomValues.measuredPairs.measure(castForDom(element), Rec.map(pairs, (target, key) => ({ from: UndefinedOr.getOrThrow(from[key]), to: target })), from)
245
+ }
246
+
247
+ /** Whether a start and a target make a Measured pair (#430). */
248
+ const keepsMeasured = (key: string, start: number | string | undefined, target: number | string): boolean => {
249
+ if (Predicate.isUndefined(start)) return false
250
+ return DomValues.measuredPairs.needs(key, start, target)
251
+ }
252
+
253
+ /** An exit's name when it's one name, for its delay; `undefined` for a list or a values map. */
254
+ const singleNameOf = (name: WardConfig.WardicVariantLabels | undefined): string | undefined => {
255
+ if (Predicate.isString(name)) return name
256
+ return undefined
257
+ }
258
+
259
+ /** The transition a name of an exit orchestrates its Variant children's keys on (#297): its group's, else the exit's. */
260
+ const transitionOfName = (exit: CorePresenceRecord.PresenceExit, name: string | undefined): WardConfig.WardicTransition | undefined => {
261
+ const groups = exit.groups
262
+ if (Bool.or(Predicate.isUndefined(groups), Predicate.isUndefined(name))) return exit.transition
263
+ return Option.match(Arr.findFirst(groups as ReadonlyArray<CorePresenceRecord.ExitGroup>, (group) => group.name === name), {
264
+ onNone: () => exit.transition,
265
+ onSome: (group) => group.transition,
266
+ })
267
+ }
268
+
269
+ /**
270
+ * Whether a resolved child is a presence child (#702): any element, HTML, SVG or MathML; text never.
271
+ * Only called on the client, where `Element` exists.
272
+ */
273
+ const isPresenceChild = (node: unknown): node is Element => node instanceof Element
274
+
275
+ /** Whether an element is an HTML one, which `popLayout` measures by its offsets (#277, Motion's). */
276
+ const isHTMLElement = (node: unknown): node is HTMLElement => node instanceof HTMLElement
277
+
278
+ /**
279
+ * Whether an element is an outermost `<svg>` (#744): the one SVG element with a CSS box in the HTML
280
+ * flow, which `popLayout` pops too, beyond Motion's. The elements inside an `<svg>`, an inner `<svg>`
281
+ * included, have no flow to leave.
282
+ */
283
+ const isSvgRoot = (node: Element): node is SVGSVGElement => {
284
+ if (node instanceof SVGSVGElement) return Predicate.isNull(node.ownerSVGElement)
285
+ return false
286
+ }
287
+
288
+ /**
289
+ * An element as dom's projection and Measured pairs take it (#702): typed for HTML elements, they read
290
+ * only what an SVG element has too (lookups by element, `contains`, its box and its inline style), so an
291
+ * SVG presence child goes through as one, as the bindings' SVG Wardic elements already do.
292
+ */
293
+ const castForDom = (el: Element): HTMLElement => el as HTMLElement
294
+
295
+ /** The elements of what a binding's `children()` resolved: one node, a flat array, or none. */
296
+ const elementsOf = (resolved: unknown): ReadonlyArray<Element> => Arr.filter(Arr.ensure(resolved), isPresenceChild)
297
+
298
+ /** A child present at the last change: its element, and where it was then, to put it back as it leaves. */
299
+ interface Placed {
300
+ readonly el: Element
301
+ readonly parent: ParentNode | undefined
302
+ readonly next: ChildNode | undefined
303
+ }
304
+
305
+ /** Where `el` is now. */
306
+ const placedOf = (el: Element): Placed => ({
307
+ el,
308
+ parent: Option.getOrUndefined(Option.fromNullOr(el.parentNode)),
309
+ next: Option.getOrUndefined(Option.fromNullOr(el.nextSibling)),
310
+ })
311
+
312
+ /**
313
+ * Where `popLayout` pins a leaver (#277, ADR-0048), measured before the change as Motion's `PopChild`
314
+ * measures it: its size (`getComputedStyle`, so its own `box-sizing` reads it back), and its margin
315
+ * box's offset from its containing block's padding edge on the two edges its anchors name (#442):
316
+ * the top or the bottom, and its inline start or end (Motion's `anchorX` `"left"` or `"right"`, which
317
+ * a right-to-left one flips). An HTML one's offsets are whole pixels, the DOM's `offsetTop`; an
318
+ * `<svg>` root's are fractional, from rects (#744).
319
+ */
320
+ interface PopBox {
321
+ /** The element it pins: an HTML one, or an outermost `<svg>` (#744). No other SVG element is popped (#702). */
322
+ readonly el: HTMLElement | SVGSVGElement
323
+ readonly width: number
324
+ readonly height: number
325
+ readonly y: "top" | "bottom"
326
+ readonly yAt: number
327
+ readonly x: "left" | "right"
328
+ readonly xAt: number
329
+ }
330
+
331
+ /** Where a presence's `popLayout` pins a leaver (#442, Motion's `anchorX` and `anchorY`): its default, the inline start and the top. */
332
+ export interface PopAnchors {
333
+ readonly x: "left" | "right"
334
+ readonly y: "top" | "bottom"
335
+ }
336
+
337
+ /**
338
+ * A leaver's border box's gap from its containing block's padding edge on each side, in the block's
339
+ * own pixels (#744): what an HTML one reads from its offsets, and an `<svg>` root from rects.
340
+ */
341
+ interface EdgeGaps {
342
+ readonly left: number
343
+ readonly top: number
344
+ readonly right: number
345
+ readonly bottom: number
346
+ }
347
+
348
+ /** The size of the padding box `el`'s offsets are from: its offset parent's, or the viewport's. */
349
+ const containerOf = (el: HTMLElement): { readonly width: number; readonly height: number } => {
350
+ const parent = el.offsetParent
351
+ if (isHTMLElement(parent) && parent !== document.body) return { width: parent.clientWidth, height: parent.clientHeight }
352
+ return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight }
353
+ }
354
+
355
+ /** A px length of a computed style, `0` for none. */
356
+ const pxOf = (value: string): number => {
357
+ const px = Number.parseFloat(value)
358
+ if (Number.isNaN(px)) return 0
359
+ return px
360
+ }
361
+
362
+ /**
363
+ * Where `el` is now, to pop it (#277): `undefined` for one that isn't popped: an SVG element inside an
364
+ * `<svg>`, which runs its exit in place (#702), as Motion's, and one with no size of its own. An outermost
365
+ * `<svg>` is popped (#744), beyond Motion's.
366
+ */
367
+ const popBoxOf = (el: Element, anchors: PopAnchors): PopBox | undefined => {
368
+ if (isHTMLElement(el)) return pinBoxOf(el, anchors, htmlGapsOf)
369
+ if (isSvgRoot(el)) return pinBoxOf(el, anchors, svgGapsOf)
370
+ return undefined
371
+ }
372
+
373
+ /**
374
+ * Where `el` is now, to pop it, from its gaps as its kind reads them (`gapsOf`): `undefined` for one
375
+ * with no size of its own (an inline element, or an empty one), or whose gaps can't be read.
376
+ */
377
+ const pinBoxOf = <E extends HTMLElement | SVGSVGElement>(el: E, anchors: PopAnchors, gapsOf: (el: E) => EdgeGaps | undefined): PopBox | undefined => {
378
+ const style = getComputedStyle(el)
379
+ const width = Number.parseFloat(style.width)
380
+ const height = Number.parseFloat(style.height)
381
+ if (Bool.not(Bool.and(width > 0, height > 0))) return undefined
382
+ return UndefinedOr.map(gapsOf(el), (gaps) => {
383
+ // Positioned by its margin box, as its gaps are its border box's. `anchorX` names the inline start
384
+ // (`"left"`) or end, which a right-to-left one flips, as Motion's.
385
+ const x = Bool.match((anchors.x === "right") !== (style.direction === "rtl"), { onTrue: (): PopBox["x"] => "right", onFalse: (): PopBox["x"] => "left" })
386
+ const xAt = Bool.match(x === "right", {
387
+ onTrue: () => gaps.right - pxOf(style.marginRight),
388
+ onFalse: () => gaps.left - pxOf(style.marginLeft),
389
+ })
390
+ const yAt = Bool.match(anchors.y === "bottom", {
391
+ onTrue: () => gaps.bottom - pxOf(style.marginBottom),
392
+ onFalse: () => gaps.top - pxOf(style.marginTop),
393
+ })
394
+ return { el, width, height, y: anchors.y, yAt, x, xAt }
395
+ })
396
+ }
397
+
398
+ /** An HTML element's gaps (#277), from its offsets: whole pixels, against its offset parent's padding box or the viewport. */
399
+ const htmlGapsOf = (el: HTMLElement): EdgeGaps => {
400
+ const container = containerOf(el)
401
+ return {
402
+ left: el.offsetLeft,
403
+ top: el.offsetTop,
404
+ right: container.width - el.offsetLeft - el.offsetWidth,
405
+ bottom: container.height - el.offsetTop - el.offsetHeight,
406
+ }
407
+ }
408
+
409
+ /**
410
+ * A filler's style (#744): absolutely positioned and filling its containing block's padding box, over
411
+ * any rule of the page's (`all: initial`, each `important`).
412
+ */
413
+ const FILLER_STYLE = "all: initial !important; display: block !important; position: absolute !important; inset: 0 !important"
414
+
415
+ /** A containing block's padding box (#744): its rect as drawn, scrolled and transformed, and its own size. */
416
+ interface PaddingBox {
417
+ readonly rect: DOMRect
418
+ readonly width: number
419
+ readonly height: number
420
+ }
421
+
422
+ /**
423
+ * The padding box of the containing block an absolutely positioned `el` has (#744): the browser's own,
424
+ * which a filler put right after `el`, absolutely positioned with `inset: 0`, fills. It's read and
425
+ * removed at once. `undefined` for an `el` with no parent.
426
+ */
427
+ const paddingBoxOf = (el: Element): PaddingBox | undefined => {
428
+ const parent = el.parentNode
429
+ if (Predicate.isNull(parent)) return undefined
430
+ const filler = document.createElement("wardic-filler")
431
+ filler.style.cssText = FILLER_STYLE
432
+ parent.insertBefore(filler, el.nextSibling)
433
+ try {
434
+ const style = getComputedStyle(filler)
435
+ return { rect: filler.getBoundingClientRect(), width: Number.parseFloat(style.width), height: Number.parseFloat(style.height) }
436
+ } finally {
437
+ filler.remove()
438
+ }
439
+ }
440
+
441
+ /** How much a drawn length is of its own (#744): `drawn` over `own`, `1` for a box with no size. */
442
+ const scaleOf = (drawn: number, own: number): number => Bool.match(own > 0, { onTrue: () => drawn / own, onFalse: () => 1 })
443
+
444
+ /**
445
+ * An outermost `<svg>`'s gaps (#744, ADR-0048 *Amendment (#744)*), from rects, as it has no `offsetTop`,
446
+ * `offsetLeft` or `offsetParent`: its box, read without its own inline `transform` (Wardic's), less its
447
+ * containing block's padding box (`paddingBoxOf`), divided by that block's scale on each axis (a layout
448
+ * animation's on it). Fractional. A rotated or skewed ancestor puts them off, as rects undo only
449
+ * translation and scale, and so does a transform of its own from the page's CSS (a `rotate`, or a
450
+ * stylesheet's `transform`). `undefined` for one with no parent.
451
+ */
452
+ const svgGapsOf = (el: SVGSVGElement): EdgeGaps | undefined =>
453
+ UndefinedOr.map(paddingBoxOf(el), (block) => {
454
+ const own = ProjectionSystem.measureLayoutBox(castForDom(el))
455
+ const sx = scaleOf(block.rect.width, block.width)
456
+ const sy = scaleOf(block.rect.height, block.height)
457
+ return {
458
+ left: (own.left - block.rect.left) / sx,
459
+ top: (own.top - block.rect.top) / sy,
460
+ right: (block.rect.right - own.right) / sx,
461
+ bottom: (block.rect.bottom - own.bottom) / sy,
462
+ }
463
+ })
464
+
465
+ /** Pin a leaver where `box` measured it, out of the flow, over any style of its own. */
466
+ const pin = (box: PopBox): void => {
467
+ const style = box.el.style
468
+ style.setProperty("position", "absolute", "important")
469
+ style.setProperty("width", `${box.width}px`, "important")
470
+ style.setProperty("height", `${box.height}px`, "important")
471
+ style.setProperty(box.y, `${box.yAt}px`, "important")
472
+ style.setProperty(box.x, `${box.xAt}px`, "important")
473
+ // Out of the flow over what took its place, it takes none of its clicks (#486). Not Motion's: its
474
+ // popped child still takes input. It's never unpinned: a child that comes back is a new element.
475
+ style.setProperty("pointer-events", "none", "important")
476
+ }
477
+
478
+ /**
479
+ * A popped leaver moved by `by` in the page from where `box` pinned it (ADR-0048 *Amendment (#480)*):
480
+ * each pinned edge by its axis's move, a right or bottom one against it.
481
+ */
482
+ const movePin = (box: PopBox, by: { readonly x: number; readonly y: number }): void => {
483
+ const style = box.el.style
484
+ style.setProperty(box.y, `${box.yAt + EDGE_BY[box.y] * by.y}px`, "important")
485
+ style.setProperty(box.x, `${box.xAt + EDGE_BY[box.x] * by.x}px`, "important")
486
+ }
487
+
488
+ /** Which way a move along the page moves a pinned edge's offset: with a left or top one, against a right or bottom one. */
489
+ const EDGE_BY = { left: 1, right: -1, top: 1, bottom: -1 } as const
490
+
491
+ /** The element its first child sits in, if it's one (#277's PR 5c). */
492
+ const parentElementOf = (placed: ReadonlyArray<Placed>): Element | undefined =>
493
+ UndefinedOr.map(UndefinedOr.map(placed[0], (first) => first.parent), (parent) => {
494
+ if (parent instanceof Element) return parent
495
+ return undefined
496
+ })
497
+
498
+ /**
499
+ * The children in Motion's order for a change (#486, its `AnimatePresence`, #3746 there): `now`, with
500
+ * each of `before`, the children as they were, leavers still exiting among them, that isn't in `now`
501
+ * put back by Motion 14.9's arithmetic (#675). Walking `before`, each staying child sets the place to
502
+ * just after its own index in `now`, counting every leaver put back so far, and each leaver goes in
503
+ * there; first, while no staying child has set it. While the staying children keep their order, that's
504
+ * right after the staying child it followed, after the others put back there. Under a reorder it can
505
+ * be after a leaver put back after another child: `[a, b, c, d]`, b and d leaving, then `[c, a]`, is
506
+ * `[c, a, d, b]`, where "after the child it followed" would be `[c, d, a, b]`.
507
+ */
508
+ const orderOf = (before: ReadonlyArray<Element>, now: ReadonlyArray<Element>): ReadonlyArray<Element> => {
509
+ const at = new Map(Arr.map(now, (el, i) => [el, i] as const))
510
+ return Arr.reduce(before, { order: [...now], next: 0, back: 0 }, (acc, el) =>
511
+ UndefinedOr.match(at.get(el), {
512
+ onUndefined: () => {
513
+ acc.order.splice(acc.next, 0, el)
514
+ return { order: acc.order, next: acc.next + 1, back: acc.back + 1 }
515
+ },
516
+ onDefined: (i) => ({ order: acc.order, next: i + acc.back + 1, back: acc.back }),
517
+ })).order
518
+ }
519
+
520
+ /**
521
+ * Where a leaver goes back (#675), walking the order with a cursor: right after `cursor`, the element
522
+ * before it in the order, already in its place; with none before it, right before `anchor`, where the
523
+ * presence's children start; with neither, where it was. Each leaver is placed against one already in
524
+ * place, never against a leaver that isn't yet, as the nearest neighbour on the page might be (#561's
525
+ * P19).
526
+ */
527
+ const backPlaceOf = (placed: Placed, cursor: Element | undefined, anchor: ChildNode | undefined): Placed =>
528
+ UndefinedOr.match(cursor, {
529
+ onDefined: (at) => ({ ...placedOf(at), el: placed.el }),
530
+ onUndefined: () =>
531
+ UndefinedOr.match(anchor, {
532
+ onDefined: (at) => ({ el: placed.el, parent: Option.getOrUndefined(Option.fromNullOr(at.parentNode)), next: at }),
533
+ onUndefined: () => placed,
534
+ }),
535
+ })
536
+
537
+ /**
538
+ * Whether a leaver from an earlier change is at its place already (#675), so a change that doesn't
539
+ * move it leaves it be (its focus, and anything a removal would restart): the next element after
540
+ * `cursor`, text between them left be; with none, the anchor itself, the first of the order on the
541
+ * page; with neither, on the page.
542
+ */
543
+ const isInPlace = (el: Element, cursor: Element | undefined, anchor: ChildNode | undefined): boolean =>
544
+ UndefinedOr.match(cursor, {
545
+ onDefined: (at) => at.nextElementSibling === el,
546
+ onUndefined: () =>
547
+ UndefinedOr.match(anchor, {
548
+ onDefined: (at) => at === el,
549
+ onUndefined: () => Predicate.isNotNull(el.parentNode),
550
+ }),
551
+ })
552
+
553
+ /** Whether a node is there and on the page. */
554
+ const isOnPage = (node: ChildNode | undefined): node is ChildNode => {
555
+ if (Predicate.isUndefined(node)) return false
556
+ return node.isConnected
557
+ }
558
+
559
+ /** Put a retained node back into the parent it left: before its old next sibling while that's still there, else at the end. */
560
+ const reinsert = (el: Node, parent: ParentNode, next: ChildNode | undefined): void => {
561
+ if (Predicate.isNotUndefined(next) && next.parentNode === parent) {
562
+ parent.insertBefore(el, next)
563
+ return
564
+ }
565
+ parent.appendChild(el)
566
+ }
567
+
568
+ /**
569
+ * How a presence's children enter while others exit, Motion's `mode`: `"sync"`, at
570
+ * once, beside the leavers; `"wait"`, once every leaver is gone; `"popLayout"`, at once, each leaver
571
+ * popped out of the flow where it was.
572
+ */
573
+ export type PresenceMode = "sync" | "wait" | "popLayout"
574
+
575
+ /** What a presence reads from its provider and its props. */
576
+ export interface PresenceOptions {
577
+ readonly runtime: WardicServices.Runner<WardicServices.WardicServices>
578
+ /** The Environment's Renderer (ADR-0003), read once by the provider (#618, M1): what a retained node's values commit through. */
579
+ readonly renderer: Renderer.Renderer["Service"]
580
+ /** The provider's projection system once its `layout` Feature is built (#511), read at each use. */
581
+ readonly projection: () => ProjectionSystem.Shape | undefined
582
+ /** Whether reduced motion applies now (ADR-0029), read at each exit. */
583
+ readonly reducedMotion: () => boolean
584
+ readonly positionalKeys: ReducedMotion.PositionalKeys["Service"]
585
+ /** What an exit's key with no transition of its own runs on (ADR-0051). */
586
+ readonly defaultTransition: DefaultTransition.DefaultTransition["Service"]
587
+ /** The presence's `initial` prop: `false` starts the child present at its first render at its `animate` (#134). */
588
+ readonly initial: () => boolean | undefined
589
+ /** What its binding hears of its exits (#257); left out, nothing is told. */
590
+ readonly events?: PresenceEvents | undefined
591
+ /**
592
+ * Its `custom` prop (#277, Motion's), read as a child leaves: what the child's dynamic exit resolves
593
+ * with, over the child's own. Left out, the child's own.
594
+ */
595
+ readonly custom?: (() => unknown) | undefined
596
+ /** Its `mode` prop (#277), read at each change: left out, or `undefined`, `"sync"`. */
597
+ readonly mode?: (() => PresenceMode | undefined) | undefined
598
+ /**
599
+ * Its `anchorX` and `anchorY` props (#442, Motion's), read as `popLayout` measures a leaver: the
600
+ * edges it's pinned by. Left out, or `undefined`, the inline start (`"left"`) and the top.
601
+ */
602
+ readonly anchorX?: (() => PopAnchors["x"] | undefined) | undefined
603
+ readonly anchorY?: (() => PopAnchors["y"] | undefined) | undefined
604
+ /**
605
+ * Its `presenceAffectsLayout` prop (#442, Motion's), read at each change: whether the projection is
606
+ * told when its children move (a child entering, a leaver popped or removed), so a `layout` sibling
607
+ * animates into or out of the space. Left out, or `undefined`, `true`.
608
+ */
609
+ readonly presenceAffectsLayout?: (() => boolean | undefined) | undefined
610
+ /**
611
+ * The children `mode="wait"` held may go on the page now: the binding renders its children again,
612
+ * through {@link PresenceController.shown}. Left out, a held child stays held.
613
+ */
614
+ readonly release?: (() => void) | undefined
615
+ }
616
+
617
+ /**
618
+ * A presence's exits, told to its binding (#257, ADR-0046): Motion's `onExitComplete`, or a presence
619
+ * handle (Solid 2's). A child that leaves exits; a child with no record (not a Wardic element) leaves at
620
+ * once, its exit starting and ending together, as Motion's does.
621
+ */
622
+ export interface PresenceEvents {
623
+ /** A child left, and its exit starts. */
624
+ readonly exitStart: () => void
625
+ /** Whether any child is exiting, at each change: on at an exit's start, off once none is left. */
626
+ readonly exiting: (exiting: boolean) => void
627
+ /**
628
+ * Every exiting child has animated out and been removed, the last by completing (Motion's
629
+ * `onExitComplete`). Not when the last ended by an interrupt: a re-entry, or the teardown.
630
+ */
631
+ readonly exitComplete: () => void
632
+ }
633
+
634
+ /** A presence's work, driven by its binding. */
635
+ export interface PresenceController {
636
+ /** What its children's wards register with. */
637
+ readonly context: PresenceContextValue
638
+ /** The presence has mounted: a child that enters from now on animates in (#134). */
639
+ readonly mounted: () => void
640
+ /**
641
+ * The children present now, after a change (a node, a flat array of them, or none): each that left
642
+ * is retained in its place and exits. Called after the binding's framework has applied the change.
643
+ */
644
+ readonly present: (current: unknown) => void
645
+ /**
646
+ * What goes on the page of what the children resolved to (#277): all of it, but under `mode="wait"`,
647
+ * while a child exits or is leaving in this change, each child entering is held off it until the
648
+ * last leaver is gone ({@link PresenceOptions.release}). Called where the binding renders, before
649
+ * the change is applied; {@link present} is then told what it showed.
650
+ */
651
+ readonly shown: (resolved: unknown) => unknown
652
+ /**
653
+ * `propagate` (#277's PR 5c): every child present leaves, as if the change took them all, and
654
+ * `done` is called once none is left (at once with none).
655
+ */
656
+ readonly leaveAll: (done: () => void) => void
657
+ /**
658
+ * Where its children are: the parent node of the last it had (#277's PR 5c), what a parent
659
+ * presence finds it inside. `undefined` before it had one.
660
+ */
661
+ readonly anchor: () => Element | undefined
662
+ /** The presence's teardown: every exit in flight interrupted, every retained node removed. */
663
+ readonly teardown: () => void
664
+ }
665
+
666
+ /**
667
+ * {@link PresenceEvents} as Motion's (#257, Solid 1's): only its `onExitComplete`, read when it's called. One
668
+ * that throws is reported (`wardic.presence: onExitComplete failed`), and the presence goes on.
669
+ */
670
+ export const exitCompleteEvents = (runtime: WardicServices.Runner<WardicServices.WardicServices>, onExitComplete: () => (() => void) | undefined): PresenceEvents => ({
671
+ exitStart: constVoid,
672
+ exiting: constVoid,
673
+ exitComplete: () => {
674
+ const callback = onExitComplete()
675
+ if (Predicate.isUndefined(callback)) return
676
+ try {
677
+ callback()
678
+ } catch (defect) {
679
+ runtime.runFork(Report.failure("wardic.presence: onExitComplete failed", Cause.die(defect)))
680
+ }
681
+ },
682
+ })
683
+
684
+ /** A projection method that takes an HTML element first, taking any element. */
685
+ type TakingAnyElement<F> = F extends (...args: infer P) => infer A ? P extends [HTMLElement, ...infer R] ? (el: Element, ...rest: R) => A : F : F
686
+
687
+ /** What a presence asks of the projection system, of any presence child (#702). */
688
+ type PresenceProjection = {
689
+ readonly [K in "notify" | "handleLeave" | "handBackWithin" | "keepLeaving" | "awaitsTwin" | "keepSeen" | "registerValues" | "rootBoxOf" | "dropLeaver"]: TakingAnyElement<
690
+ ProjectionSystem.Shape[K]
691
+ >
692
+ }
693
+
694
+ /**
695
+ * The projection system as a presence asks it (#511): the provider's once its `layout` Feature is
696
+ * built, read at each call, as a presence brings no Feature; until then, what one with no layout node
697
+ * answers: no twin to cross-fade or hand back, no leaving node to keep, nothing to tell. A popped
698
+ * leaver isn't kept where it was seen across a scroll then (ADR-0048 *Amendment (#480)*): the
699
+ * projection's frame does that.
700
+ */
701
+ const presenceProjectionOf = (projection: () => ProjectionSystem.Shape | undefined): PresenceProjection => {
702
+ const call = <A>(use: (system: ProjectionSystem.Shape) => A, none: () => A): A => UndefinedOr.match(projection(), { onUndefined: none, onDefined: use })
703
+ return {
704
+ notify: () => call((system) => system.notify(), constVoid),
705
+ handleLeave: (el, onDone) => call((system) => system.handleLeave(castForDom(el), onDone), constFalse),
706
+ handBackWithin: (el, onDone) => call((system) => system.handBackWithin(castForDom(el), onDone), Option.none),
707
+ keepLeaving: (el, taken) => call((system) => system.keepLeaving(castForDom(el), taken), () => constVoid),
708
+ awaitsTwin: (el) => call((system) => system.awaitsTwin(castForDom(el)), constFalse),
709
+ keepSeen: (el, move) => call((system) => system.keepSeen(castForDom(el), move), constVoid),
710
+ registerValues: (el, read) => call((system) => system.registerValues(el, read), () => constVoid),
711
+ rootBoxOf: (el) => call((system) => system.rootBoxOf(castForDom(el)), Option.none),
712
+ dropLeaver: (el) => call((system) => system.dropLeaver(castForDom(el)), Option.none),
713
+ }
714
+ }
715
+
716
+ /** A presence's work: see the module. */
717
+ export const makePresence = (options: PresenceOptions): PresenceController => {
718
+ const { runtime, reducedMotion, positionalKeys, defaultTransition } = options
719
+ const projection = presenceProjectionOf(options.projection)
720
+ const { commit, project } = options.renderer
721
+
722
+ /**
723
+ * Debug-level lifecycle log for the parent-driven exit (observability
724
+ * convention): forked on the runtime, filtered out unless the logger is at
725
+ * Debug, so an exit that never removes its node — or a re-entry that interrupts
726
+ * the wrong one — is diagnosable. The per-frame commit stays silent.
727
+ */
728
+ const debug = Report.debugOf(runtime, "wardic.presence")
729
+
730
+ // The registry of live child records, keyed by their DOM element. Filled by
731
+ // register() (called from the child's spine on mount), drained as children
732
+ // leave (after their exit settles).
733
+ const registry = new Map<Element, PresenceRecord>()
734
+
735
+ // In-flight exit fibers keyed by the leaving node, so a re-entry (or this
736
+ // component's own teardown) can interrupt them. A Map, not Effect's `FiberMap` (#618): an exit's
737
+ // entry goes from inside its own `ensuring`, before its fiber has ended, and is checked right after;
738
+ // `FiberMap.remove` interrupts the fiber it removes, and its own removal waits for the fiber's end.
739
+ const exiting = new Map<Element, Fiber.Fiber<void, never>>()
740
+
741
+ // A leaving child's parts still running (ADR-0010 *Amendment (#181)*): its exit, and the handovers
742
+ // of the twins it handed back. It goes when the count reaches 0. Every retained child that runs its
743
+ // own exit is here; a twin presence left to the projection isn't.
744
+ const pending = new Map<Element, number>()
745
+ // The handed-back twins of a leaving child, by it: the call that drops them, for an interrupted exit.
746
+ const handovers = new Map<Element, () => void>()
747
+ // What lets go of the twins each leaving child keeps for a late take-over (#402): called as it goes.
748
+ const lates = new Map<Element, () => void>()
749
+ // The unregistration of each exit's values with the projection.
750
+ const exitValues = new Map<Element, () => void>()
751
+ // The Wardic elements exiting inside each leaving child (#290), dropped with it.
752
+ const exitParts = new Map<Element, ReadonlyArray<Element>>()
753
+
754
+ // `initial={false}` (#134): the children set up with this first render start at their
755
+ // `animate`; one that enters after it animates in.
756
+ let firstRender = true
757
+
758
+ // The children exiting now, each told once at its end (#257): completed, or interrupted.
759
+ const leaving = new Set<Element>()
760
+ // Each retained child's place when it left (#277): a framework that clears its nodes wholesale (a
761
+ // list emptied clears its parent) takes it out mid-exit, and it goes back there.
762
+ const places = new Map<Element, Placed>()
763
+ const events = options.events
764
+
765
+ // The presence hooks registered (#277's PR 5b), each told at its child's leave.
766
+ const watches = new Set<PresenceWatch>()
767
+ // The hooks each leaving child told it left, while its exit runs: told if it's cut short (#665, Q46).
768
+ const toldHooks = new Map<Element, ReadonlyArray<PresenceWatch>>()
769
+
770
+ // The children `mode="wait"` holds off the page now (#277), and the start of each ward inside one,
771
+ // by its element, called once the child is on the page.
772
+ let held: ReadonlyArray<Element> = []
773
+ const starts = new Map<Element, () => void>()
774
+ // `popLayout`'s leavers (#277), each where it was measured before the change: popped as it leaves,
775
+ // and kept until it's gone. Whether this change popped one, so the projection is told.
776
+ const pops = new Map<Element, PopBox>()
777
+ let popped = false
778
+ // Whether this change moved a leaver from an earlier one to its place (#675), so the projection is
779
+ // told: a twin leaver crossfading in the flow is drawn on its Lead from where it now is.
780
+ let moved = false
781
+
782
+ // Keys (#286, ADR-0048): each Wardic element made under this presence, told as it's made, so a
783
+ // child's key is known before what goes on the page is decided.
784
+ const made = new WeakMap<Element, Made>()
785
+ // The latest child exiting under each key: a child back under it takes over from that one.
786
+ const keyedLeavers = new Map<string | number, Element>()
787
+ // What each element exiting has drawn, kept by its exit's frames.
788
+ const draws = new Map<Element, Drawn>()
789
+ // The children entering now that take over from a leaver, each with that leaver: taken over at
790
+ // the first of their wards' mounts, or the presence's next look, whichever comes first.
791
+ const takeovers = new Map<Element, Element>()
792
+ // Where each Wardic element in a child that took over starts: read once, at its mount.
793
+ const seeds = new WeakMap<Element, Drawn>()
794
+ // The keyed leavers crossfading as twins (ADR-0010), the projection's: one taken over ends its
795
+ // leaving Follower at once (Q8: D).
796
+ const crossfades = new Set<Element>()
797
+ // Where each leaver taken over painted, it and the Wardic elements inside it, in the Root frame:
798
+ // read as the take-over is found, before the change moves anything.
799
+ const leaverBoxes = new Map<Element, ReadonlyMap<Element, Box.Box>>()
800
+ // Whether any keyed element was made: until then, no change looks for a take-over.
801
+ let keyed = false
802
+
803
+ /** A child's exit starts: told, and `exiting` turns on with the first. */
804
+ const leaveStarts = (el: Element): void => {
805
+ leaving.add(el)
806
+ if (Predicate.isUndefined(events)) return
807
+ if (leaving.size === 1) events.exiting(true)
808
+ events.exitStart()
809
+ }
810
+
811
+ /**
812
+ * A child's exit ended: with the last, `exiting` turns off, a completion is told, and the children
813
+ * `mode="wait"` held go on the page (#277), as Motion renders them after its `onExitComplete`.
814
+ */
815
+ const leaveEnds = (el: Element, completed: boolean): void => {
816
+ if (Bool.not(leaving.delete(el))) return
817
+ if (leaving.size > 0) return
818
+ UndefinedOr.map(events, (told) => {
819
+ told.exiting(false)
820
+ if (completed) told.exitComplete()
821
+ })
822
+ // `propagate` (#277's PR 5c): the last child that left lets the parent's child go.
823
+ allLeft()
824
+ if (held.length > 0) UndefinedOr.map(options.release, (release) => release())
825
+ }
826
+
827
+ // What `leaveAll` calls once none is left (#277's PR 5c), and where its children last were.
828
+ let onAllLeft: (() => void) | undefined
829
+ let anchor: Element | undefined
830
+
831
+ /** `leaveAll`'s end, told once (#277's PR 5c). */
832
+ const allLeft = (): void => {
833
+ if (Predicate.isUndefined(onAllLeft)) return
834
+ const done = onAllLeft
835
+ onAllLeft = undefined
836
+ done()
837
+ }
838
+
839
+ /** Whether `el` is inside a child held off the page (#277). */
840
+ const isHeld = (el: Element): boolean => Arr.some(held, (child) => child.contains(el))
841
+
842
+ const ctx: PresenceContextValue = {
843
+ register: (rec) => {
844
+ registry.set(rec.element, rec)
845
+ return () => {
846
+ registry.delete(rec.element)
847
+ }
848
+ },
849
+ blocksInitial: () => options.initial() === false && firstRender,
850
+ watch: (watch) => {
851
+ watches.add(watch)
852
+ watchesWithin = undefined
853
+ },
854
+ hold: (el, start) => {
855
+ if (Bool.not(isHeld(el))) return undefined
856
+ starts.set(el, start)
857
+ return () => {
858
+ starts.delete(el)
859
+ }
860
+ },
861
+ made: (el, key, twin) => {
862
+ made.set(el, { key, twin })
863
+ if (Predicate.isNotUndefined(key)) keyed = true
864
+ },
865
+ takeOverOf: (el) => {
866
+ settleTakeovers()
867
+ const seed = seeds.get(el)
868
+ seeds.delete(el)
869
+ return seed
870
+ },
871
+ }
872
+
873
+ // Commit a projected value-map onto a retained node via the Renderer.
874
+ const commitValues = (el: Element, values: Values.Values): void => {
875
+ const patch: Renderer.Patch = project(values)
876
+ commit(el, patch)
877
+ }
878
+
879
+ // Remove a retained node from the DOM + drop its registration + clear its
880
+ // in-flight fiber bookkeeping. Idempotent. `completed`: its exit ended on its own (#257).
881
+ const finishExit = (el: Element, completed = true): void => {
882
+ exiting.delete(el)
883
+ toldHooks.delete(el)
884
+ registry.delete(el)
885
+ draws.delete(el)
886
+ crossfades.delete(el)
887
+ leaverBoxes.delete(el)
888
+ // No longer one a child back under its key takes over from (#286).
889
+ UndefinedOr.map(keyOf(el), (key) => {
890
+ if (keyedLeavers.get(key) === el) keyedLeavers.delete(key)
891
+ })
892
+ pending.delete(el)
893
+ handovers.delete(el)
894
+ UndefinedOr.map(lates.get(el), (forget) => forget())
895
+ lates.delete(el)
896
+ places.delete(el)
897
+ // A popped leaver is out of the flow: its going moves nothing.
898
+ const moves = Bool.and(el.isConnected, Bool.not(pops.delete(el)))
899
+ const unregister = exitValues.get(el)
900
+ exitValues.delete(el)
901
+ if (Predicate.isNotUndefined(unregister)) unregister()
902
+ // The elements inside it that exited with it go with it (#290): their records, and their values.
903
+ Arr.forEach(UndefinedOr.match(exitParts.get(el), { onUndefined: () => NO_PARTS, onDefined: identity }), (part) => {
904
+ registry.delete(part)
905
+ draws.delete(part)
906
+ UndefinedOr.map(exitValues.get(part), (unregisterPart) => unregisterPart())
907
+ exitValues.delete(part)
908
+ })
909
+ exitParts.delete(el)
910
+ el.remove()
911
+ // Its siblings take the space it leaves (#277): a `layout` one animates there, as Motion's do.
912
+ if (Bool.and(moves, affectsLayout())) projection.notify()
913
+ // Told once the node is gone, as Motion's `onExitComplete` finds it (#257).
914
+ leaveEnds(el, completed)
915
+ }
916
+
917
+ // One of a leaving child's parts ended (#181): it goes with the last. A child already removed
918
+ // (an interrupted exit's fiber ending after) is ignored.
919
+ const partDone = (el: Element): void => {
920
+ const left = pending.get(el)
921
+ if (Predicate.isUndefined(left)) return
922
+ if (left > 1) {
923
+ pending.set(el, left - 1)
924
+ return
925
+ }
926
+ finishExit(el)
927
+ }
928
+
929
+ // Interrupt an in-flight exit for `el` (re-entry / teardown) and remove the
930
+ // retained node, the twins it handed back dropped with it. Idempotent.
931
+ const interruptExit = (el: Element): void => {
932
+ // Told first, as interrupted: the exit's fiber, interrupted below, ends at once through
933
+ // `partDone`, which would tell it completed (#257).
934
+ leaveEnds(el, false)
935
+ // The hooks it told it left hear it was cut short (#665, Q46).
936
+ const hooks = toldHooks.get(el)
937
+ toldHooks.delete(el)
938
+ if (Predicate.isNotUndefined(hooks)) {
939
+ Arr.forEach(hooks, (watch) => {
940
+ if (Predicate.isNotUndefined(watch.interrupted)) watch.interrupted()
941
+ })
942
+ }
943
+ const fiber = exiting.get(el)
944
+ if (Predicate.isNotUndefined(fiber)) {
945
+ debug("exit: interrupt")
946
+ // Nothing waits on its end: interrupted here, not by a fiber forked for it (#618, L2).
947
+ fiber.interruptUnsafe()
948
+ }
949
+ const drop = handovers.get(el)
950
+ if (Predicate.isNotUndefined(drop)) drop()
951
+ finishExit(el, false)
952
+ }
953
+
954
+ // A leaving child that isn't a twin (ADR-0010 *Amendment (#181)*): it hands back the twins inside
955
+ // it, then runs its own exit and the exits inside it, and goes once all have ended. A plain child
956
+ // (not a Wardic element, no `rec`) runs only those inside it (#392), as Motion's presence child does.
957
+ const leave = (el: Element, rec: PresenceRecord | undefined, custom: unknown, inside: ReadonlyArray<PresenceWatch>, holds: number): void => {
958
+ // A keyed one is what a child back under its key takes over from (#286), the latest the one.
959
+ UndefinedOr.map(keyOf(el), (key) => keyedLeavers.set(key, el))
960
+ const drop = projection.handBackWithin(el, () => partDone(el))
961
+ // Its parts: its exit, each hook holding it (#277's PR 5b), and the handovers of the twins it hands back.
962
+ pending.set(el, 1 + holds)
963
+ if (Option.isSome(drop)) {
964
+ handovers.set(el, drop.value)
965
+ pending.set(el, 2 + holds)
966
+ debug("leave: hands back its twins")
967
+ }
968
+ // The twins nobody took over stay a later twin's to take over while it's on the page (#402).
969
+ lates.set(el, projection.keepLeaving(el, (dropLate) => takenLate(el, dropLate)))
970
+ tellLeave(el, inside, true)
971
+ driveExit(el, rec, custom)
972
+ }
973
+
974
+ // A twin in a leaving child taken over late (ADR-0010 *Amendment (#402)*): one more of its parts,
975
+ // ended with that handover, and dropped with its others by an interrupted exit. Its own exit runs on:
976
+ // the handover draws the twin over it.
977
+ const takenLate = (el: Element, drop: () => void): (() => void) => {
978
+ const left = pending.get(el)
979
+ if (Predicate.isUndefined(left)) {
980
+ drop()
981
+ return constVoid
982
+ }
983
+ pending.set(el, left + 1)
984
+ const before = handovers.get(el)
985
+ handovers.set(el, () => {
986
+ UndefinedOr.map(before, (dropBefore) => dropBefore())
987
+ drop()
988
+ })
989
+ debug("leave: a twin taken over late")
990
+ return () => partDone(el)
991
+ }
992
+
993
+ /**
994
+ * The Wardic elements inside a leaving child (#290), in document order, each running its own exit
995
+ * with the child's: every registered one but a twin, whose crossfade replaces its exit (#181).
996
+ */
997
+ const partsOf = (el: Element): ReadonlyArray<PresenceRecord> => Arr.filter(registeredWithin(el), isPart)
998
+
999
+ /**
1000
+ * The records of the elements inside `el`, in document order, `undefined` for one not registered:
1001
+ * found by walking its own elements (#392), as many steps as it has, not as the presence has records.
1002
+ */
1003
+ const registeredWithin = (el: Element): ReadonlyArray<PresenceRecord | undefined> => {
1004
+ if (registry.size === 0) return NO_RECORDS
1005
+ return Arr.map(Arr.fromIterable(el.getElementsByTagName("*")), (inner) => registry.get(inner))
1006
+ }
1007
+
1008
+ /** A registered element but a twin. */
1009
+ const isPart = (part: PresenceRecord | undefined): part is PresenceRecord => {
1010
+ if (Predicate.isUndefined(part)) return false
1011
+ return Bool.not(treeOf(part).twin)
1012
+ }
1013
+
1014
+ /**
1015
+ * Whether a leaving child stays to exit (#392): a Wardic element, or a plain one with something
1016
+ * inside it to wait for, a Wardic element (an exit to run, a twin to hand back) or a hook's hold.
1017
+ */
1018
+ const retains = (el: Element): boolean => {
1019
+ if (registry.has(el)) return true
1020
+ if (holdsIn(el)) return true
1021
+ return registersWithin(el)
1022
+ }
1023
+
1024
+ /** Whether a Wardic element made under this presence is inside `el`. */
1025
+ const registersWithin = (el: Element): boolean => Arr.some(registeredWithin(el), Predicate.isNotUndefined)
1026
+
1027
+ /**
1028
+ * A leaving child's exit, and the exits inside it (#290), as Motion's `animateVariant` runs them:
1029
+ * each element's own exit, its Variant children's on the name it hands down, in its exit
1030
+ * orchestration (`delayChildren`, the stagger, `when`), and every other element's from the leave.
1031
+ * A plain child (no `rec`) has no exit of its own: the elements inside it are the roots (#392).
1032
+ * The child goes once all of them, and the handovers of the twins it handed back, have ended.
1033
+ */
1034
+ const driveExit = (el: Element, rec: PresenceRecord | undefined, custom: unknown): void => {
1035
+ const parts = partsOf(el)
1036
+ exitParts.set(el, Arr.map(parts, (part) => part.element))
1037
+ const own = UndefinedOr.match(rec, { onUndefined: () => NO_OWN, onDefined: Arr.of })
1038
+ const byElement = new Map<Element, PresenceRecord>(Arr.map([...own, ...parts], (r) => [r.element, r] as const))
1039
+ // The nearest element inside the child its Variant children join: one that provides a context.
1040
+ const providerOf = (node: Element | null): PresenceRecord | undefined => {
1041
+ if (node === null) return undefined
1042
+ const found = byElement.get(node)
1043
+ if (Predicate.isNotUndefined(found) && treeOf(found).provides) return found
1044
+ if (node === el) return undefined
1045
+ return providerOf(node.parentElement)
1046
+ }
1047
+ const joinsTo = new Map<PresenceRecord, PresenceRecord>()
1048
+ Arr.forEach(parts, (part) => {
1049
+ if (Bool.not(treeOf(part).joins)) return
1050
+ UndefinedOr.map(providerOf(part.element.parentElement), (provider) => joinsTo.set(part, provider))
1051
+ })
1052
+ const joinersOf = (provider: PresenceRecord): ReadonlyArray<PresenceRecord> => Arr.filter(parts, (part) => joinsTo.get(part) === provider)
1053
+ const nodeOf = (node: PresenceRecord, inherited: WardConfig.WardicVariantLabels | undefined): ExitNode => {
1054
+ const exit = node.exitOf(custom, inherited)
1055
+ return { rec: node, exit, kids: Arr.map(joinersOf(node), (kid) => nodeOf(kid, exit.name)) }
1056
+ }
1057
+ // The child's own tree, if it's a Wardic element, and each element inside it that joins nothing
1058
+ // inside it, from the leave.
1059
+ const roots = [
1060
+ ...Arr.map(own, (r) => nodeOf(r, undefined)),
1061
+ ...Arr.map(Arr.filter(parts, (part) => Bool.not(joinsTo.has(part))), (part) => nodeOf(part, undefined)),
1062
+ ]
1063
+ if (Bool.not(Arr.some(roots, busy))) {
1064
+ debug("exit: immediate (no target)")
1065
+ partDone(el)
1066
+ return
1067
+ }
1068
+ // One `wardic.presence.exit` span spans the whole exit, from the leave to the last part's end.
1069
+ // A failed run is logged and reported (ADR-0030, decision 4); the node is removed either way.
1070
+ const fiber = runtime.runFork(
1071
+ Effect.all(Arr.map(roots, (root) => runOf(root, NO_DELAY)), { concurrency: "unbounded", discard: true }).pipe(
1072
+ Effect.tapCause((cause) => Report.failure("wardic.presence: an exit failed", cause)),
1073
+ Effect.ensuring(Effect.sync(() => partDone(el))),
1074
+ // The app's to give, with no call-site stack (#746; ADR-0040, decision 2).
1075
+ Spans.withSpan("wardic.presence.exit", { attributes: { parts: parts.length + own.length } }),
1076
+ ),
1077
+ )
1078
+ exiting.set(el, fiber)
1079
+ }
1080
+
1081
+ /**
1082
+ * A node's exit and its Variant children's (#290), Motion's `animateVariant`: with `when`, one after
1083
+ * the other, the children's delays from 0; else together, the children's from `delay`.
1084
+ */
1085
+ const runOf = (node: ExitNode, delay: DelayOf): Effect.Effect<unknown, never, WardicServices.WardicServices> => {
1086
+ // A list's names each run on their own (#297's PR 2): each name's keys and its children's, in that
1087
+ // name's own `when`.
1088
+ const groups = node.exit.groups
1089
+ if (Predicate.isNotUndefined(groups)) {
1090
+ const first = UndefinedOr.match(groups[0], { onUndefined: constUndefined, onDefined: (group) => group.name })
1091
+ return Effect.all(Arr.map(groups, (group) => runName(node, group.name, delay, group.name === first)), { concurrency: "unbounded", discard: true })
1092
+ }
1093
+ const own = exitOf(node.rec, node.exit, delay)
1094
+ if (node.kids.length === 0) return own
1095
+ const n = node.kids.length
1096
+ // Each name orchestrates the children's keys of that name (#297, Motion's `animateVariant` a name):
1097
+ // its own transition's delay and stagger, else the exit's.
1098
+ const slot = (i: number) => (name: string | undefined): number => {
1099
+ const s = VariantTree.staggerOf(transitionOfName(node.exit, name))
1100
+ return VariantTree.childDelayOf(s, i, n)
1101
+ }
1102
+ const kidsFrom = (from: DelayOf): Effect.Effect<unknown, never, WardicServices.WardicServices> =>
1103
+ Effect.all(Arr.map(node.kids, (kid, i) => runOf(kid, (name) => from(name) + slot(i)(name))), { concurrency: "unbounded", discard: true })
1104
+ // `when` for a list as a whole, meanwhile (#297's PR 1): the exit's, its last name's that sets it.
1105
+ const when = UndefinedOr.map(node.exit.transition, (t) => t.when)
1106
+ if (when === "beforeChildren") return Effect.andThen(own, kidsFrom(NO_DELAY))
1107
+ if (when === "afterChildren") return Effect.andThen(kidsFrom(NO_DELAY), own)
1108
+ return Effect.all([own, kidsFrom(delay)], { concurrency: "unbounded", discard: true })
1109
+ }
1110
+
1111
+ /**
1112
+ * One name of a list's exit (#297's PR 2, Motion's `animateVariant` a name): the element's keys of that
1113
+ * name, and its Variant children's, one after the other with that name's `when`, else together. A
1114
+ * child whose exit isn't the list runs it whole, under the list's first name.
1115
+ */
1116
+ const runName = (node: ExitNode, name: string, delay: DelayOf, first: boolean): Effect.Effect<unknown, never, WardicServices.WardicServices> => {
1117
+ const own = exitOf(node.rec, node.exit, delay, name)
1118
+ const n = node.kids.length
1119
+ if (n === 0) return own
1120
+ const slot = (i: number) => (of: string | undefined): number => {
1121
+ const s = VariantTree.staggerOf(transitionOfName(node.exit, of))
1122
+ return VariantTree.childDelayOf(s, i, n)
1123
+ }
1124
+ const kidsFrom = (from: DelayOf): Effect.Effect<unknown, never, WardicServices.WardicServices> =>
1125
+ Effect.all(
1126
+ Arr.map(node.kids, (kid, i) => {
1127
+ const at: DelayOf = (of) => from(of) + slot(i)(of)
1128
+ if (Predicate.isNotUndefined(kid.exit.groups)) return runName(kid, name, at, first)
1129
+ if (first) return runOf(kid, at)
1130
+ return Effect.void
1131
+ }),
1132
+ { concurrency: "unbounded", discard: true },
1133
+ )
1134
+ const when = UndefinedOr.map(transitionOfName(node.exit, name), (t) => t.when)
1135
+ if (when === "beforeChildren") return Effect.andThen(own, kidsFrom(NO_DELAY))
1136
+ if (when === "afterChildren") return Effect.andThen(kidsFrom(NO_DELAY), own)
1137
+ return Effect.all([own, kidsFrom(delay)], { concurrency: "unbounded", discard: true })
1138
+ }
1139
+
1140
+ /**
1141
+ * One element's own exit on its retained node, `delay` seconds in (#290): a Retarget's legs (#277),
1142
+ * on the exit's own transition, else the element's, its positional keys snapping under reduced
1143
+ * motion (ADR-0029) unless it opts out. Nothing to run for an empty one.
1144
+ */
1145
+ const exitOf = (rec: PresenceRecord, exit: CorePresenceRecord.PresenceExit, delay: DelayOf, only?: string): Effect.Effect<unknown, never, WardicServices.WardicServices> => {
1146
+ const to = exit.values
1147
+ if (isEmpty(to)) return Effect.void
1148
+ const { from, stops, commitFrame, velocities, el } = preparedOf(rec, exit)
1149
+ // Its keys start with the velocity their frames gave them (#464, Motion's): 0 for one at rest.
1150
+ const moving = RetargetLegs.velocitiesOf(UndefinedOr.match(rec.velocities, { onUndefined: () => NO_VELOCITIES, onDefined: (of) => of() }))
1151
+ // A list's exit by name (#297): each name's keys on its own transition, at its own delay; one
1152
+ // name's alone when its `when` orders it (#297's PR 2).
1153
+ // The leaver's own, under its nearest WardicConfig (#434), else the presence's.
1154
+ const reduce = UndefinedOr.match(rec.reducedMotion, { onUndefined: reducedMotion, onDefined: (own) => own() })
1155
+ // Skipped (#468): every key lands at its end on the first tick, and the element leaves then.
1156
+ const skipped = UndefinedOr.match(rec.skipAnimations, { onUndefined: constFalse, onDefined: (own) => own() })
1157
+ // Measured pairs (#430): an exit from `auto` to 0 measures both ends, as a Retarget does, unless
1158
+ // reduced motion snaps them or the exit is skipped.
1159
+ const measured = Bool.match(Bool.or(reduce, skipped), { onTrue: constUndefined, onFalse: () => exitMeasuredOf(el, from, to, stops) })
1160
+ const legs = UndefinedOr.match(exit.groups, {
1161
+ onUndefined: () => RetargetLegs.legsOf(from, to, RetargetLegs.delayedBy(exit.transition, delay(singleNameOf(exit.name))), reduce, skipped, positionalKeys, defaultTransition, moving, undefined, stops, measured),
1162
+ onDefined: (groups) =>
1163
+ Arr.flatMap(
1164
+ Arr.filter(groups, (group) => Bool.or(Predicate.isUndefined(only), group.name === only)),
1165
+ (group: CorePresenceRecord.ExitGroup) => RetargetLegs.legsOf(from, group.values, RetargetLegs.delayedBy(group.transition, delay(group.name)), reduce, skipped, positionalKeys, defaultTransition, moving, undefined, stops, measured),
1166
+ ),
1167
+ })
1168
+ return Effect.all(Arr.map(legs, (leg) => exitRunOf(leg, el, commitFrame, velocities)), { concurrency: "unbounded", discard: true })
1169
+ }
1170
+
1171
+ // Each exit's start, made once though a list's names run its keys apart (#297's PR 2).
1172
+ const prepared = new WeakMap<CorePresenceRecord.PresenceExit, PreparedExit>()
1173
+
1174
+ /** An element's exit made ready to run: where it starts, and what each frame commits. */
1175
+ const preparedOf = (rec: PresenceRecord, exit: CorePresenceRecord.PresenceExit): PreparedExit => {
1176
+ const known = prepared.get(exit)
1177
+ if (Predicate.isNotUndefined(known)) return known
1178
+ const el = rec.element
1179
+ const to = exit.values
1180
+ // Seeded from the element's last snapshot, so its exit departs continuously. A key it never
1181
+ // animated starts from its Base value's start links (ADR-0022), else at its target.
1182
+ const snapshot = rec.snapshot.current
1183
+ const startOf = (key: string, target: number | string): number | string =>
1184
+ UndefinedOr.match(UndefinedOr.match(rec.startOf, { onUndefined: constUndefined, onDefined: (of) => of(key, target) }), {
1185
+ onUndefined: () => target,
1186
+ onDefined: identity,
1187
+ })
1188
+ const seeded: Values.Values = {
1189
+ ...snapshot,
1190
+ ...Rec.map(Rec.filter(to, (_, key) => Predicate.isUndefined(snapshot[key])), (target, key) => startOf(key, target)),
1191
+ }
1192
+ // Its Keyframes (#429) start at their first stop, a `null` one where the key is.
1193
+ const { from, stops } = UndefinedOr.match(exit.keyframes, {
1194
+ onUndefined: () => ({ from: seeded, stops: undefined }),
1195
+ onDefined: (keyframes) => RetargetLegs.keyframesFrom(seeded, to, keyframes),
1196
+ })
1197
+ // The merged latest value-map, so each committed frame carries every key.
1198
+ const latest: Values.Values = { ...from }
1199
+ // What the exit has drawn, for the projection (ADR-0010 *Amendment (#181)*): the twins handed back
1200
+ // follow it. Its last snapshot until the first frame commits.
1201
+ const drawn: Values.Values = { ...from }
1202
+ UndefinedOr.map(exitValues.get(el), (unregister) => unregister())
1203
+ exitValues.set(el, projection.registerValues(el, () => drawn))
1204
+ // And how fast each key moves (#286): a child back under its key starts with it.
1205
+ const velocities: Record<string, number> = {}
1206
+ draws.set(el, { values: drawn, velocities })
1207
+ const commitFrame: FrameLoop.Sink<Frame.Frame<Values.Values>> = (frame) => {
1208
+ Object.assign(latest, frame.value)
1209
+ commitValues(el, latest)
1210
+ Object.assign(drawn, latest)
1211
+ return undefined
1212
+ }
1213
+ const made: PreparedExit = { el, from, stops, commitFrame, velocities }
1214
+ prepared.set(exit, made)
1215
+ return made
1216
+ }
1217
+
1218
+ // The children present at the last change, and where each was, to retain one as it leaves.
1219
+ let previous: ReadonlyArray<Placed> = []
1220
+ // The children as the last change left them (#486): those on the page, the leavers among them.
1221
+ let rendered: ReadonlyArray<Element> = []
1222
+
1223
+ // Teardown: interrupt every in-flight exit + remove retained nodes, the twins they handed back
1224
+ // dropped with them (no leaks). Every child running its own exit is in `pending`.
1225
+ const teardown = (): void => {
1226
+ debug("teardown", { inflight: exiting.size, retained: pending.size })
1227
+ // A held child never goes on the page, nor do its wards start (#277): with none held, the exits
1228
+ // ended below release nothing, so the binding isn't rendered again as it's disposed.
1229
+ held = []
1230
+ starts.clear()
1231
+ // The hooks still waiting go with it, told nothing left (#277's PR 5b).
1232
+ Arr.forEach(Arr.fromIterable(watches), (watch) => watch.gone())
1233
+ watches.clear()
1234
+ // Each retained child, a leave waiting for its task's end (#482) among them.
1235
+ Arr.forEach(Arr.fromIterable(new Set([...pending.keys(), ...exiting.keys()])), (el) => interruptExit(el))
1236
+ // A crossfading leaver is the projection's, not in `pending`: its exit ends here too, uncompleted (#257).
1237
+ Arr.forEach(Arr.fromIterable(leaving), (el) => leaveEnds(el, false))
1238
+ }
1239
+
1240
+ /** Whether a hook inside `el` holds it as it leaves (#277's PR 5b). */
1241
+ const holdsIn = (el: Element): boolean => Arr.some(watchesIn(el), (watch) => watch.holds)
1242
+
1243
+ /** A record whose element is off the page, dropped; a leaver's is put back first, so it stays. */
1244
+ const dropDetached = (el: Element): void => {
1245
+ if (el.isConnected) return
1246
+ registry.delete(el)
1247
+ }
1248
+
1249
+ /** Pop a leaver `popLayout` measured. */
1250
+ const popOut = (el: Element): void => {
1251
+ const box = pops.get(el)
1252
+ if (Predicate.isUndefined(box)) return
1253
+ pin(box)
1254
+ // Where it was seen, through the page's scroll at this change: a router's to the top (#480).
1255
+ projection.keepSeen(box.el, (by) => movePin(box, by))
1256
+ popped = true
1257
+ }
1258
+
1259
+ /**
1260
+ * Measure each child leaving in this change that stays to exit, before the change is applied (#277):
1261
+ * a plain one too, with something inside it to wait for (#392).
1262
+ */
1263
+ const measureLeavers = (resolved: unknown): void => {
1264
+ const kept = new Set(elementsOf(resolved))
1265
+ // Its anchors now (#442).
1266
+ const anchors: PopAnchors = {
1267
+ x: UndefinedOr.match(UndefinedOr.map(options.anchorX, (read) => read()), { onUndefined: (): PopAnchors["x"] => "left", onDefined: identity }),
1268
+ y: UndefinedOr.match(UndefinedOr.map(options.anchorY, (read) => read()), { onUndefined: (): PopAnchors["y"] => "top", onDefined: identity }),
1269
+ }
1270
+ Arr.forEach(previous, (placed) => {
1271
+ if (kept.has(placed.el)) return
1272
+ if (Bool.not(retains(placed.el))) return
1273
+ UndefinedOr.map(popBoxOf(placed.el, anchors), (box) => pops.set(placed.el, box))
1274
+ })
1275
+ }
1276
+
1277
+ /** Put a retained child back where it was, if a framework took it out. */
1278
+ const putBack = (placed: Placed): void => {
1279
+ if (placed.el.parentNode !== null) return
1280
+ UndefinedOr.map(placed.parent, (parent) => reinsert(placed.el, parent, placed.next))
1281
+ }
1282
+
1283
+ /**
1284
+ * Every leaver at its place in `order` (#675), walking it with a cursor: a child that stays is where
1285
+ * its framework put it, and each leaver goes right after the element before it in the order, this
1286
+ * change's as they leave, an earlier change's moved there. A framework moves its own nodes around a
1287
+ * leaver it doesn't know of: Solid's swap of `[a, c]` puts `c` before `a`'s next sibling, the leaver
1288
+ * between them. So each change places them all again, as Motion's presence renders every exiting child
1289
+ * at its place.
1290
+ */
1291
+ const placeLeavers = (order: ReadonlyArray<Element>, kept: ReadonlySet<Element>, gone: ReadonlyMap<Element, Placed>): void => {
1292
+ const anchor = anchorOf(order, gone)
1293
+ Arr.reduce<Element, Element | undefined>(order, undefined, (cursor, el) => {
1294
+ UndefinedOr.match(gone.get(el), {
1295
+ onDefined: (placed) => left(placed, backPlaceOf(placed, cursor, anchor)),
1296
+ onUndefined: () => {
1297
+ if (Bool.not(kept.has(el))) moveBack(el, cursor, anchor)
1298
+ },
1299
+ })
1300
+ return Bool.match(el.isConnected, { onTrue: () => el, onFalse: () => cursor })
1301
+ })
1302
+ }
1303
+
1304
+ /**
1305
+ * Where the presence's children start, for the leavers no element precedes in the order (#675): the
1306
+ * first element of the order on the page as the walk starts, a child that stays or an earlier
1307
+ * change's leaver. With none, where they ended: the node after one of them at its last place, still on
1308
+ * the page. Solid empties a list beside a sibling around its leavers, its own nodes gone, and that's
1309
+ * the sibling. With neither, `undefined`: nothing of theirs is left, as when Solid clears the parent.
1310
+ */
1311
+ const anchorOf = (order: ReadonlyArray<Element>, gone: ReadonlyMap<Element, Placed>): ChildNode | undefined =>
1312
+ Option.getOrUndefined(Option.orElse(Arr.findFirst(order, isOnPage), () => Arr.findFirst(Arr.map(order, (el) => lastNextOf(el, gone)), isOnPage)))
1313
+
1314
+ /** The node after a child at its last place: as the last change left it, or, an earlier leaver, as it left. */
1315
+ const lastNextOf = (el: Element, gone: ReadonlyMap<Element, Placed>): ChildNode | undefined =>
1316
+ UndefinedOr.map(UndefinedOr.match(gone.get(el), { onDefined: identity, onUndefined: () => places.get(el) }), (placed) => placed.next)
1317
+
1318
+ /** A leaver from an earlier change, still retained, moved to its place in the walk (#675) unless it's there already. */
1319
+ const moveBack = (el: Element, cursor: Element | undefined, anchor: ChildNode | undefined): void => {
1320
+ if (isInPlace(el, cursor, anchor)) return
1321
+ UndefinedOr.map(places.get(el), (placed) => {
1322
+ const back = backPlaceOf(placed, cursor, anchor)
1323
+ UndefinedOr.map(back.parent, (parent) => reinsert(el, parent, back.next))
1324
+ moved = true
1325
+ })
1326
+ }
1327
+
1328
+ /** A child that left: retained at `back` (#486), and exiting, unless it's leaving already. */
1329
+ const left = (placed: Placed, back: Placed): void => {
1330
+ const el = placed.el
1331
+ const rec = registry.get(el)
1332
+ // The presence hooks inside it (#277's PR 5b): told it left; `usePresence`'s hold it until released.
1333
+ const inside = watchesIn(el)
1334
+ const holds = Arr.filter(inside, (watch) => watch.holds).length
1335
+ // A plain child (not a Wardic element) with nothing inside it to wait for, no Wardic element
1336
+ // (an exit to run, a twin to hand back) and no hook holding it, is gone at once (#257, #392).
1337
+ if (Bool.and(Predicate.isUndefined(rec), holds === 0)) {
1338
+ if (Bool.not(registersWithin(el))) {
1339
+ if (Bool.not(leaving.has(el))) {
1340
+ leaveStarts(el)
1341
+ tellLeave(el, inside, false)
1342
+ leaveEnds(el, true)
1343
+ }
1344
+ return
1345
+ }
1346
+ }
1347
+ if (Bool.or(exiting.has(el), pending.has(el))) return
1348
+ leaveStarts(el)
1349
+ // RE-INSERT: Solid's branch disposal may have already removed the node. Put it back, so the
1350
+ // parent-driven exit has a mounted node to animate: at `back`, moved there if Solid left it in.
1351
+ UndefinedOr.map(back.parent, (parent) => reinsert(el, parent, back.next))
1352
+ places.set(el, placedOf(el))
1353
+ // `popLayout` (#277): out of the flow where it was, so the children after it take their places.
1354
+ popOut(el)
1355
+ // A twin it is or holds left with none to take it over yet (ADR-0010 *Amendment (#482)*): its
1356
+ // partner may arrive later in this update, as Solid runs a presence before the children it mounts.
1357
+ // So it's decided at the task's end, before a frame, and stays on the page till then, an exit-less
1358
+ // one too, as Motion keeps its relegated leaver until `postRender`.
1359
+ if (projection.awaitsTwin(el)) {
1360
+ // Keyed, it's what a child back under its key in this update takes over from (#286), meanwhile too.
1361
+ UndefinedOr.map(keyOf(el), (key) => keyedLeavers.set(key, el))
1362
+ decideAtTaskEnd(el, () => decideLeave(el, rec, inside, holds))
1363
+ return
1364
+ }
1365
+ decideLeave(el, rec, inside, holds)
1366
+ }
1367
+
1368
+ /** A leave decided at the task's end (#482): kept as `exiting`, so a re-entry or the teardown interrupts it. */
1369
+ const decideAtTaskEnd = (el: Element, decide: () => void): void => {
1370
+ const fiber = runtime.runFork(
1371
+ Microtask.next.pipe(
1372
+ Effect.andThen(
1373
+ Effect.sync(() => {
1374
+ exiting.delete(el)
1375
+ decide()
1376
+ }),
1377
+ ),
1378
+ ),
1379
+ )
1380
+ exiting.set(el, fiber)
1381
+ }
1382
+
1383
+ /** What a retained leaver does: crossfade onto its twin, or run its exit, or hand back the twins inside it. */
1384
+ const decideLeave = (el: Element, rec: PresenceRecord | undefined, inside: ReadonlyArray<PresenceWatch>, holds: number): void => {
1385
+ // A plain child (#392): retained, as Motion's presence child, until the exits inside it, the
1386
+ // handovers of its twins and the hooks holding it (#277's PR 5b) have all ended.
1387
+ if (Predicate.isUndefined(rec)) {
1388
+ leave(el, undefined, customNow(), inside, holds)
1389
+ return
1390
+ }
1391
+ // Shared-element crossfade (ADR-0010): if the projection has a live twin (Lead) to crossfade
1392
+ // toward, defer to it — it drives the retained node as a leaving Follower and calls onDone
1393
+ // (-> finishExit) on the lead's settle. Otherwise run the normal exit animation. A crossfading
1394
+ // child goes with its handover: the hooks inside it are told, but don't hold it.
1395
+ const crossfaded = projection.handleLeave(el, () => finishExit(el))
1396
+ if (crossfaded) {
1397
+ debug("leave: crossfade (deferred to projection)")
1398
+ tellLeave(el, inside, false)
1399
+ // A keyed one is what a child back under its key takes over from (#286), its Follower ended.
1400
+ UndefinedOr.map(keyOf(el), (key) => {
1401
+ keyedLeavers.set(key, el)
1402
+ crossfades.add(el)
1403
+ })
1404
+ return
1405
+ }
1406
+ // Its exit, resolved now (#277): with the presence's `custom` when it has one, else the child's last.
1407
+ leave(el, rec, customNow(), inside, holds)
1408
+ }
1409
+
1410
+ /**
1411
+ * The presence hooks by each element they're inside, their own included: built once a change, as a
1412
+ * leaver's are first asked for, and again once a hook is added (#665, Q46). A hook dropped since is
1413
+ * left out as they're read.
1414
+ */
1415
+ // A scan of every hook for each leaver cost a change 12 ms at 1,000 Batch members, half of them leaving,
1416
+ // and 123 ms at 4,000 (against 1.1 and 2.8 with no presence).
1417
+ let watchesWithin: Map<Element, Array<PresenceWatch>> | undefined
1418
+
1419
+ /** `watch` under `at` and each element `at` is inside. */
1420
+ const indexUp = (index: Map<Element, Array<PresenceWatch>>, at: Element | null, watch: PresenceWatch): void => {
1421
+ if (Predicate.isNull(at)) return
1422
+ const known = index.get(at)
1423
+ if (Predicate.isUndefined(known)) index.set(at, [watch])
1424
+ if (Predicate.isNotUndefined(known)) known.push(watch)
1425
+ indexUp(index, at.parentElement, watch)
1426
+ }
1427
+
1428
+ /** The presence hooks inside `el` (#277's PR 5b): those whose element it holds, in the order they were added. */
1429
+ const watchesIn = (el: Element): ReadonlyArray<PresenceWatch> => {
1430
+ if (Predicate.isUndefined(watchesWithin)) {
1431
+ const index = new Map<Element, Array<PresenceWatch>>()
1432
+ Iter.forEach(watches, (watch) => UndefinedOr.map(watch.element(), (at) => indexUp(index, at, watch)))
1433
+ watchesWithin = index
1434
+ }
1435
+ return Arr.filter(UndefinedOr.match(watchesWithin.get(el), { onUndefined: (): ReadonlyArray<PresenceWatch> => [], onDefined: identity }), (watch) => watches.has(watch))
1436
+ }
1437
+
1438
+ /**
1439
+ * Tell the hooks inside a leaving child it left (#277's PR 5b), with the presence's `custom`. With
1440
+ * `counted`, each that holds it is one of its parts, ended by its release (once). A callback that
1441
+ * throws is reported, and lets the child go.
1442
+ */
1443
+ const tellLeave = (el: Element, inside: ReadonlyArray<PresenceWatch>, counted: boolean): void => {
1444
+ const custom = customNow()
1445
+ if (Bool.and(counted, inside.length > 0)) toldHooks.set(el, inside)
1446
+ Arr.forEach(inside, (watch) => {
1447
+ watches.delete(watch)
1448
+ let released = false
1449
+ // `release(false)`: its exit cut short, the child gone at once, uncompleted (#665, Q46).
1450
+ const release = (completed = true): void => {
1451
+ if (released) return
1452
+ released = true
1453
+ if (Bool.not(Bool.and(counted, watch.holds))) return
1454
+ if (Bool.and(Bool.not(completed), pending.has(el))) {
1455
+ interruptExit(el)
1456
+ return
1457
+ }
1458
+ partDone(el)
1459
+ }
1460
+ try {
1461
+ watch.leave(custom, release)
1462
+ } catch (defect) {
1463
+ runtime.runFork(Report.failure("wardic.presence: a usePresence callback failed", Cause.die(defect)))
1464
+ release()
1465
+ }
1466
+ })
1467
+ }
1468
+
1469
+ /** A hook whose element left the page some other way, dropped (#277's PR 5b): not one a held child holds. */
1470
+ const dropDetachedWatch = (watch: PresenceWatch): void => {
1471
+ UndefinedOr.map(watch.element(), (at) => {
1472
+ if (Bool.or(at.isConnected, isHeld(at))) return
1473
+ watches.delete(watch)
1474
+ watch.gone()
1475
+ })
1476
+ }
1477
+
1478
+ // --- Keys (#286, ADR-0048) ------------------------------------------------
1479
+
1480
+ /** An element's `key`, told as it was made: `undefined` for one with none, or not a Wardic element. */
1481
+ const keyOf = (el: Element): string | number | undefined => UndefinedOr.map(made.get(el), (m) => m.key)
1482
+
1483
+ /**
1484
+ * Where a Wardic element is drawn: what its exit has drawn, if it's exiting, over its last values;
1485
+ * else its last values, at the velocities its own animation left them.
1486
+ */
1487
+ const drawnOf = (rec: PresenceRecord): Drawn =>
1488
+ UndefinedOr.match(draws.get(rec.element), {
1489
+ onUndefined: (): Drawn => ({
1490
+ values: valuesDrawn(rec.snapshot.current),
1491
+ velocities: UndefinedOr.match(rec.velocities, { onUndefined: () => NO_VELOCITIES, onDefined: (of) => ({ ...of() }) }),
1492
+ }),
1493
+ onDefined: (drawn): Drawn => ({ values: valuesDrawn({ ...rec.snapshot.current, ...drawn.values }), velocities: { ...drawn.velocities } }),
1494
+ })
1495
+
1496
+ /** The Wardic elements made under this presence inside `el`, in document order, but the twins (#181). */
1497
+ const madeWithin = (el: Element): ReadonlyArray<Element> =>
1498
+ Arr.filter(Arr.fromIterable(el.querySelectorAll("*")), (inner) =>
1499
+ UndefinedOr.match(made.get(inner), { onUndefined: constFalse, onDefined: (m) => Bool.not(m.twin) }))
1500
+
1501
+ /**
1502
+ * The children entering in this change that take over from a leaver: one with the key of a child
1503
+ * exiting, or of one leaving in this change (Motion keeps an element whose key stays).
1504
+ */
1505
+ const findTakeovers = (resolved: unknown): void => {
1506
+ const onPage = new Set(Arr.map(previous, (placed) => placed.el))
1507
+ const now = elementsOf(resolved)
1508
+ const kept = new Set(now)
1509
+ // The keyed children leaving in this change, by key, over the ones exiting already.
1510
+ const byKey = new Map(keyedLeavers)
1511
+ Arr.forEach(previous, (placed) => {
1512
+ if (Bool.or(kept.has(placed.el), Bool.not(registry.has(placed.el)))) return
1513
+ UndefinedOr.map(keyOf(placed.el), (key) => byKey.set(key, placed.el))
1514
+ })
1515
+ if (byKey.size === 0) return
1516
+ Arr.forEach(now, (el) => {
1517
+ if (onPage.has(el)) return
1518
+ UndefinedOr.map(keyOf(el), (key) =>
1519
+ UndefinedOr.map(byKey.get(key), (leaver) => {
1520
+ if (leaver === el) return
1521
+ takeovers.set(el, leaver)
1522
+ if (Bool.not(leaverBoxes.has(leaver))) leaverBoxes.set(leaver, boxesOf(leaver))
1523
+ }))
1524
+ })
1525
+ }
1526
+
1527
+ /** Where a leaver and the Wardic elements inside it paint now, in the Root frame: each one on the page. */
1528
+ const boxesOf = (leaver: Element): ReadonlyMap<Element, Box.Box> => {
1529
+ const boxes = new Map<Element, Box.Box>()
1530
+ Arr.forEach([leaver, ...Arr.map(partsOf(leaver), (part) => part.element)], (el) =>
1531
+ Option.map(projection.rootBoxOf(el), (box) => boxes.set(el, box)))
1532
+ return boxes
1533
+ }
1534
+
1535
+ /** The take-overs found, each done once: at the first of the child's wards' mounts, or the presence's next look. */
1536
+ const settleTakeovers = (): void => {
1537
+ if (takeovers.size === 0) return
1538
+ const due = Arr.fromIterable(takeovers)
1539
+ takeovers.clear()
1540
+ Arr.forEach(due, ([el, leaver]) => takeOver(el, leaver))
1541
+ }
1542
+
1543
+ // Children taken over in the change they left in: they never start an exit.
1544
+ const takenOver = new WeakSet<Element>()
1545
+
1546
+ /**
1547
+ * `el` takes over from `leaver`: each Wardic element in it starts where the one it pairs with in
1548
+ * the leaver is drawn, the child itself with the leaver, and those inside in document order when
1549
+ * the two have the same shape (as many, each pair the same tag). The leaver goes at once. An exiting
1550
+ * one's exit ends, uncompleted, as an interrupted one's does (Motion tells no completion for a key
1551
+ * back); one leaving in this change never starts its exit, nor are its hooks told it left.
1552
+ */
1553
+ const takeOver = (el: Element, leaver: Element): void => {
1554
+ const from = registry.get(leaver)
1555
+ // Gone since (its exit ended): the child enters as any other.
1556
+ if (Predicate.isUndefined(from)) return
1557
+ const before = partsOf(leaver)
1558
+ const after = madeWithin(el)
1559
+ // Each as drawn, and where it painted: a layout node moves from there (#286's PR 2).
1560
+ const boxes = UndefinedOr.match(leaverBoxes.get(leaver), { onUndefined: (): ReadonlyMap<Element, Box.Box> => NO_BOXES, onDefined: identity })
1561
+ leaverBoxes.delete(leaver)
1562
+ const seedOf = (rec: PresenceRecord): Drawn => ({ ...drawnOf(rec), box: boxes.get(rec.element) })
1563
+ const paired = sameShape(Arr.map(before, (part) => part.element), after)
1564
+ if (paired) Arr.forEach(Arr.zip(before, after), ([part, into]) => seeds.set(into, seedOf(part)))
1565
+ debug("leave: taken over", { parts: before.length, paired })
1566
+ // A twin crossfading out (Q8: D): its leaving Follower goes at once, uncompleted, and the new
1567
+ // node's handover fades on from where it had faded to, as Motion's same element would.
1568
+ if (crossfades.has(leaver)) {
1569
+ leaveEnds(leaver, false)
1570
+ seeds.set(el, { ...seedOf(from), fade: Option.getOrUndefined(projection.dropLeaver(leaver)) })
1571
+ return
1572
+ }
1573
+ seeds.set(el, seedOf(from))
1574
+ // Retained, or its leave waiting for its task's end (#482).
1575
+ if (Bool.or(pending.has(leaver), exiting.has(leaver))) {
1576
+ interruptExit(leaver)
1577
+ return
1578
+ }
1579
+ // Leaving in this change: it goes as Solid took it, its records and hooks with it.
1580
+ takenOver.add(leaver)
1581
+ pops.delete(leaver)
1582
+ Arr.forEach([from, ...before], (rec) => registry.delete(rec.element))
1583
+ Arr.forEach(watchesIn(leaver), (watch) => {
1584
+ watches.delete(watch)
1585
+ watch.gone()
1586
+ })
1587
+ }
1588
+
1589
+ const present = (current: unknown): void => {
1590
+ // Its hooks' elements may have moved since the last change: indexed again as they're asked for.
1591
+ watchesWithin = undefined
1592
+ const now = elementsOf(current)
1593
+ const kept = new Set(now)
1594
+ // A child entering pushes its siblings (#442): not on the page at the last change, the first one
1595
+ // included, so a presence mounting moves a `layout` element after it, as Motion's re-render does.
1596
+ const wasThere = new Set(Arr.map(previous, (placed) => placed.el))
1597
+ const entered = Arr.some(now, (el) => Bool.not(wasThere.has(el)))
1598
+ // The take-overs found as these children went on the page (#286), before any leaves: a child
1599
+ // taken over in the change it left in doesn't leave.
1600
+ if (takeovers.size > 0) {
1601
+ Arr.forEach(Arr.fromIterable(takeovers.keys()), (el) => {
1602
+ if (Bool.not(kept.has(el))) takeovers.delete(el)
1603
+ })
1604
+ settleTakeovers()
1605
+ }
1606
+ // The children that left go back in Motion's order (#486), and every leaver from an earlier change,
1607
+ // still exiting, keeps its place in it (#675), one a framework took out (a list emptied) too.
1608
+ const gone = new Map(Arr.map(Arr.filter(previous, (placed) => Bool.and(Bool.not(kept.has(placed.el)), Bool.not(takenOver.has(placed.el)))), (placed) => [placed.el, placed] as const))
1609
+ const before = Arr.filter(rendered, (el) => Bool.or(Bool.or(kept.has(el), gone.has(el)), Bool.and(Bool.or(el.isConnected, places.has(el)), Bool.not(takenOver.has(el)))))
1610
+ const listed = new Set(before)
1611
+ const order = orderOf(Arr.appendAll(before, Arr.filter(Arr.map(previous, (placed) => placed.el), (el) => Bool.not(listed.has(el)))), now)
1612
+ placeLeavers(order, kept, gone)
1613
+ rendered = Arr.filter(order, (el) => el.isConnected)
1614
+ // A child still exiting that the framework took out since (a list emptied) goes back too.
1615
+ Arr.forEach(Arr.fromIterable(places.values()), putBack)
1616
+ previous = Arr.map(now, placedOf)
1617
+ // Where its children are (#277's PR 5c): a parent presence finds it inside its leaving child by it.
1618
+ if (now.length > 0) anchor = parentElementOf(previous)
1619
+ // A record whose element left the page some other way (its own control flow, inside a child that
1620
+ // stays) is dropped (#290): nothing exits it, and nothing else would.
1621
+ Arr.forEach(Arr.fromIterable(registry.keys()), dropDetached)
1622
+ Arr.forEach(Arr.fromIterable(watches), dropDetachedWatch)
1623
+ // A popped leaver moved its siblings (#277), and so did a child entering (#442): a `layout` one
1624
+ // animates into the space, as Motion's presence re-renders its children then. A leaver moved to its
1625
+ // place (#675) moved itself and them.
1626
+ if (Bool.and(Bool.or(Bool.or(popped, entered), moved), affectsLayout())) projection.notify()
1627
+ popped = false
1628
+ moved = false
1629
+ // The wards inside the children held until now start, the children on the page (#277). Held
1630
+ // children go on together, so none is left held then. (A ward started while its child is held
1631
+ // would only wait again: the check saves its re-run.)
1632
+ if (Bool.and(starts.size > 0, held.length === 0)) startHeld()
1633
+ }
1634
+
1635
+ /** The held wards' starts, each once. */
1636
+ const startHeld = (): void => {
1637
+ const ready = Arr.fromIterable(starts.values())
1638
+ starts.clear()
1639
+ Arr.forEach(ready, (start) => start())
1640
+ }
1641
+
1642
+ /** The presence's `custom` now (#277): `undefined` without one. */
1643
+ const customNow = (): unknown => UndefinedOr.map(options.custom, (custom) => custom())
1644
+
1645
+ /** The mode now: `"sync"` unless the prop says otherwise. */
1646
+ const modeNow = (): PresenceMode | undefined => UndefinedOr.map(options.mode, (mode) => mode())
1647
+
1648
+ /** Whether the projection is told when its children move (#442, `presenceAffectsLayout`): unless the prop says `false`. */
1649
+ const affectsLayout = (): boolean => UndefinedOr.map(options.presenceAffectsLayout, (affects) => affects()) !== false
1650
+
1651
+ /**
1652
+ * Whether an entering child waits (#277): under `mode="wait"`, while a child exits, or one shown at
1653
+ * the last change is leaving now and stays to exit (a Wardic element, or a plain one with something
1654
+ * inside it to wait for, #392).
1655
+ */
1656
+ const waits = (kept: ReadonlySet<Element>): boolean =>
1657
+ Bool.or(
1658
+ leaving.size > 0,
1659
+ Arr.some(previous, (placed) => {
1660
+ if (kept.has(placed.el)) return false
1661
+ return retains(placed.el)
1662
+ }),
1663
+ )
1664
+
1665
+ const shown = (resolved: unknown): unknown => {
1666
+ watchesWithin = undefined
1667
+ const mode = modeNow()
1668
+ // `popLayout` (#277): each child leaving in this change is measured where it is, before the change
1669
+ // moves it, as Motion's `getSnapshotBeforeUpdate`.
1670
+ if (mode === "popLayout") measureLeavers(resolved)
1671
+ // A child back under the key of one leaving takes over from it (#286): found before the mode
1672
+ // decides what goes on the page, so `wait` doesn't hold it. Nothing is looked up with no key.
1673
+ if (keyed) findTakeovers(resolved)
1674
+ if (mode !== "wait") {
1675
+ held = []
1676
+ return resolved
1677
+ }
1678
+ const now = elementsOf(resolved)
1679
+ const kept = new Set(now)
1680
+ // Entering: not on the page at the last change.
1681
+ const onPage = new Set(Arr.map(previous, (placed) => placed.el))
1682
+ held = Bool.match(waits(kept), { onTrue: () => Arr.filter(now, (el) => Bool.and(Bool.not(onPage.has(el)), Bool.not(takeovers.has(el)))), onFalse: () => [] })
1683
+ if (held.length === 0) return resolved
1684
+ const holding = new Set<unknown>(held)
1685
+ return Arr.filter(Arr.ensure(resolved), (node) => Bool.not(holding.has(node)))
1686
+ }
1687
+
1688
+ const leaveAll = (done: () => void): void => {
1689
+ onAllLeft = done
1690
+ present([])
1691
+ if (leaving.size === 0) allLeft()
1692
+ }
1693
+
1694
+ return {
1695
+ context: ctx,
1696
+ shown,
1697
+ leaveAll,
1698
+ anchor: () => anchor,
1699
+ mounted: () => {
1700
+ firstRender = false
1701
+ },
1702
+ present,
1703
+ teardown,
1704
+ }
1705
+ }
1706
+
1707
+ /**
1708
+ * `propagate` (#277's PR 5c, ADR-0048, Motion's): a presence inside another's child registers with
1709
+ * that one as a hook that holds it. When the child leaves, every child of this presence leaves, and
1710
+ * the parent's child goes once they've all gone. Its own disposal comes first (Solid disposes the
1711
+ * leaving child before its presence hears of it), so its teardown waits a microtask for that word.
1712
+ * Without `propagate`, or a presence above, its teardown runs at its disposal, as before. Returns
1713
+ * what its disposal runs.
1714
+ */
1715
+ export const propagateTo = (parent: PresenceContextValue | undefined, propagate: boolean, presence: PresenceController): (() => void) => {
1716
+ let torn = false
1717
+ const tear = (): void => {
1718
+ if (torn) return
1719
+ torn = true
1720
+ presence.teardown()
1721
+ }
1722
+ const watch = UndefinedOr.map(parent, (above) => above.watch)
1723
+ if (Bool.or(Bool.not(propagate), Predicate.isUndefined(watch))) return tear
1724
+ let disposed = false
1725
+ let leaving = false
1726
+ ;(watch as (watch: PresenceWatch) => void)({
1727
+ element: presence.anchor,
1728
+ holds: true,
1729
+ leave: (_custom, release) => {
1730
+ leaving = true
1731
+ presence.leaveAll(() => {
1732
+ release()
1733
+ tear()
1734
+ })
1735
+ },
1736
+ gone: () => {
1737
+ if (disposed) tear()
1738
+ },
1739
+ })
1740
+ return () => {
1741
+ disposed = true
1742
+ queueMicrotask(() => {
1743
+ if (Bool.not(leaving)) tear()
1744
+ })
1745
+ }
1746
+ }
1747
+