@jsenv/dom 0.6.1 → 0.7.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 (109) hide show
  1. package/dist/jsenv_dom.js +339 -327
  2. package/package.json +2 -4
  3. package/index.js +0 -124
  4. package/src/attr/add_attribute_effect.js +0 -93
  5. package/src/attr/attributes.js +0 -32
  6. package/src/color/color_constrast.js +0 -69
  7. package/src/color/color_parsing.js +0 -319
  8. package/src/color/color_scheme.js +0 -28
  9. package/src/color/pick_light_or_dark.js +0 -34
  10. package/src/color/resolve_css_color.js +0 -60
  11. package/src/demos/3_columns_resize_demo.html +0 -84
  12. package/src/demos/3_rows_resize_demo.html +0 -89
  13. package/src/demos/aside_and_main_demo.html +0 -93
  14. package/src/demos/coordinates_demo.html +0 -450
  15. package/src/demos/document_autoscroll_demo.html +0 -517
  16. package/src/demos/drag_gesture_constraints_demo.html +0 -701
  17. package/src/demos/drag_gesture_demo.html +0 -1047
  18. package/src/demos/drag_gesture_element_to_impact_demo.html +0 -445
  19. package/src/demos/drag_reference_element_demo.html +0 -480
  20. package/src/demos/flex_details_set_demo.html +0 -302
  21. package/src/demos/flex_details_set_demo_2.html +0 -315
  22. package/src/demos/visible_rect_demo.html +0 -525
  23. package/src/element_signature.js +0 -100
  24. package/src/interaction/drag/constraint_feedback_line.js +0 -92
  25. package/src/interaction/drag/drag_constraint.js +0 -659
  26. package/src/interaction/drag/drag_debug_markers.js +0 -635
  27. package/src/interaction/drag/drag_element_positioner.js +0 -382
  28. package/src/interaction/drag/drag_gesture.js +0 -566
  29. package/src/interaction/drag/drag_resize_demo.html +0 -571
  30. package/src/interaction/drag/drag_to_move.js +0 -301
  31. package/src/interaction/drag/drag_to_resize_gesture.js +0 -68
  32. package/src/interaction/drag/drop_target_detection.js +0 -148
  33. package/src/interaction/drag/sticky_frontiers.js +0 -160
  34. package/src/interaction/event_marker.js +0 -14
  35. package/src/interaction/focus/active_element.js +0 -33
  36. package/src/interaction/focus/arrow_navigation.js +0 -599
  37. package/src/interaction/focus/element_is_focusable.js +0 -57
  38. package/src/interaction/focus/element_visibility.js +0 -111
  39. package/src/interaction/focus/find_focusable.js +0 -21
  40. package/src/interaction/focus/focus_group.js +0 -91
  41. package/src/interaction/focus/focus_group_registry.js +0 -12
  42. package/src/interaction/focus/focus_nav.js +0 -12
  43. package/src/interaction/focus/focus_nav_event_marker.js +0 -14
  44. package/src/interaction/focus/focus_trap.js +0 -105
  45. package/src/interaction/focus/tab_navigation.js +0 -128
  46. package/src/interaction/focus/tests/focus_group_skip_tab_test.html +0 -206
  47. package/src/interaction/focus/tests/tree_focus_test.html +0 -304
  48. package/src/interaction/focus/tests/tree_focus_test.jsx +0 -261
  49. package/src/interaction/focus/tests/tree_focus_test_preact.html +0 -13
  50. package/src/interaction/isolate_interactions.js +0 -161
  51. package/src/interaction/keyboard.js +0 -26
  52. package/src/interaction/scroll/capture_scroll.js +0 -47
  53. package/src/interaction/scroll/is_scrollable.js +0 -159
  54. package/src/interaction/scroll/scroll_container.js +0 -110
  55. package/src/interaction/scroll/scroll_trap.js +0 -44
  56. package/src/interaction/scroll/scrollbar_size.js +0 -20
  57. package/src/interaction/scroll/wheel_through.js +0 -138
  58. package/src/iterable_weak_set.js +0 -66
  59. package/src/position/dom_coords.js +0 -340
  60. package/src/position/offset_parent.js +0 -15
  61. package/src/position/position_fixed.js +0 -15
  62. package/src/position/position_sticky.js +0 -213
  63. package/src/position/sticky_rect.js +0 -79
  64. package/src/position/visible_rect.js +0 -486
  65. package/src/pub_sub.js +0 -31
  66. package/src/size/can_take_size.js +0 -11
  67. package/src/size/details_content_full_height.js +0 -63
  68. package/src/size/flex_details_set.js +0 -974
  69. package/src/size/get_available_height.js +0 -22
  70. package/src/size/get_available_width.js +0 -22
  71. package/src/size/get_border_sizes.js +0 -14
  72. package/src/size/get_height.js +0 -4
  73. package/src/size/get_inner_height.js +0 -15
  74. package/src/size/get_inner_width.js +0 -15
  75. package/src/size/get_margin_sizes.js +0 -10
  76. package/src/size/get_max_height.js +0 -57
  77. package/src/size/get_max_width.js +0 -47
  78. package/src/size/get_min_height.js +0 -14
  79. package/src/size/get_min_width.js +0 -14
  80. package/src/size/get_padding_sizes.js +0 -10
  81. package/src/size/get_width.js +0 -4
  82. package/src/size/hooks/use_available_height.js +0 -27
  83. package/src/size/hooks/use_available_width.js +0 -27
  84. package/src/size/hooks/use_max_height.js +0 -10
  85. package/src/size/hooks/use_max_width.js +0 -10
  86. package/src/size/hooks/use_resize_status.js +0 -62
  87. package/src/size/resize.js +0 -695
  88. package/src/size/resolve_css_size.js +0 -32
  89. package/src/style/dom_styles.js +0 -97
  90. package/src/style/style_composition.js +0 -121
  91. package/src/style/style_controller.js +0 -345
  92. package/src/style/style_default.js +0 -153
  93. package/src/style/style_default_demo.html +0 -128
  94. package/src/style/style_parsing.js +0 -375
  95. package/src/transition/demos/animation_resumption_test.xhtml +0 -500
  96. package/src/transition/demos/height_toggle_test.xhtml +0 -515
  97. package/src/transition/dom_transition.js +0 -254
  98. package/src/transition/easing.js +0 -48
  99. package/src/transition/group_transition.js +0 -261
  100. package/src/transition/transform_style_parser.js +0 -32
  101. package/src/transition/transition_playback.js +0 -366
  102. package/src/transition/transition_timeline.js +0 -79
  103. package/src/traversal.js +0 -247
  104. package/src/ui_transition/demos/content_states_transition_demo.html +0 -628
  105. package/src/ui_transition/demos/smooth_height_transition_demo.html +0 -149
  106. package/src/ui_transition/demos/transition_testing.html +0 -354
  107. package/src/ui_transition/ui_transition.js +0 -1470
  108. package/src/utils.js +0 -69
  109. package/src/value_effect.js +0 -35
@@ -1,1470 +0,0 @@
1
- /**
2
- * Required HTML structure for UI transitions with smooth size and phase/content animations:
3
- *
4
- * <div
5
- * class="ui_transition_container" <!-- Main container with relative positioning and overflow hidden -->
6
- * data-size-transition <!-- Optional: enable size animations -->
7
- * data-size-transition-duration <!-- Optional: size transition duration, default 300ms -->
8
- * data-content-transition <!-- Content transition type: cross-fade, slide-left -->
9
- * data-content-transition-duration <!-- Content transition duration -->
10
- * data-phase-transition <!-- Phase transition type: cross-fade only -->
11
- * data-phase-transition-duration <!-- Phase transition duration -->
12
- * >
13
- * <div class="ui_transition_outer_wrapper"> <!-- Size animation target: width/height constraints are applied here during transitions -->
14
- * <div class="ui_transition_measure_wrapper"> <!-- Content measurement layer: ResizeObserver watches this to detect natural content size changes -->
15
- * <div class="ui_transition_slot" data-content-key></div> <!-- Content slot: actual content is here -->
16
- * <div class="ui_transition_phase_overlay"> <!-- Used to transition to new phase: crossfade to new phase -->
17
- * <!-- Clone of ".ui_transition_slot" children for phase transition -->
18
- * </div>
19
- * </div>
20
- * </div>
21
- *
22
- * <div class="ui_transition_content_overlay"> <!-- Used to transition to new content: crossfade/slide to new content -->
23
- * <!-- Clone of ".ui_transition_slot" children for content transition -->
24
- * </div>
25
- * </div>
26
- *
27
- * This separation allows:
28
- * - Optional smooth size transitions by constraining outer-wrapper dimensions (when data-size-transition is present)
29
- * - Instant size updates by default
30
- * - Accurate content measurement via measure-wrapper ResizeObserver
31
- * - Content transitions (slide, etc.) that operate at container level and can outlive content phase changes
32
- * - Phase transitions (cross-fade only) that operate on individual elements for loading/error states
33
- * - Independent content updates in the slot without affecting ongoing animations
34
- */
35
-
36
- import { getElementSignature } from "../element_signature.js";
37
- import { getHeight } from "../size/get_height.js";
38
- import { getInnerWidth } from "../size/get_inner_width.js";
39
- import { getWidth } from "../size/get_width.js";
40
- import {
41
- createHeightTransition,
42
- createOpacityTransition,
43
- createTranslateXTransition,
44
- createWidthTransition,
45
- getOpacity,
46
- getOpacityWithoutTransition,
47
- getTranslateX,
48
- getTranslateXWithoutTransition,
49
- } from "../transition/dom_transition.js";
50
- import { createGroupTransitionController } from "../transition/group_transition.js";
51
-
52
- import.meta.css = /* css */ `
53
- .ui_transition_container,
54
- .ui_transition_outer_wrapper,
55
- .ui_transition_measure_wrapper,
56
- .ui_transition_slot {
57
- display: inline-flex;
58
- width: fit-content;
59
- height: fit-content;
60
- }
61
-
62
- .ui_transition_container,
63
- .ui_transition_slot {
64
- position: relative;
65
- }
66
-
67
- .ui_transition_phase_overlay,
68
- .ui_transition_content_overlay {
69
- position: absolute;
70
- inset: 0;
71
- pointer-events: none;
72
- }
73
- `;
74
-
75
- const DEBUG = {
76
- size: false,
77
- transition: false,
78
- transition_updates: false,
79
- };
80
-
81
- // Utility function to format content key states consistently for debug logs
82
- const formatContentKeyState = (contentKey, hasChild, hasTextNode = false) => {
83
- if (hasTextNode) {
84
- return "[text]";
85
- }
86
- if (!hasChild) {
87
- return "[empty]";
88
- }
89
- if (contentKey === null || contentKey === undefined) {
90
- return "[unkeyed]";
91
- }
92
- return `[data-content-key="${contentKey}"]`;
93
- };
94
-
95
- const SIZE_TRANSITION_DURATION = 150; // Default size transition duration
96
- const SIZE_DIFF_EPSILON = 0.5; // Ignore size transition when difference below this (px)
97
- const CONTENT_TRANSITION = "cross-fade"; // Default content transition type
98
- const CONTENT_TRANSITION_DURATION = 300; // Default content transition duration
99
- const PHASE_TRANSITION = "cross-fade";
100
- const PHASE_TRANSITION_DURATION = 300; // Default phase transition duration
101
-
102
- export const initUITransition = (container) => {
103
- const localDebug = {
104
- ...DEBUG,
105
- transition: container.hasAttribute("data-debug-transition"),
106
- };
107
-
108
- const debug = (type, ...args) => {
109
- if (localDebug[type]) {
110
- console.debug(`[${type}]`, ...args);
111
- }
112
- };
113
-
114
- if (!container.classList.contains("ui_transition_container")) {
115
- console.error("Element must have ui_transition_container class");
116
- return { cleanup: () => {} };
117
- }
118
-
119
- const outerWrapper = container.querySelector(".ui_transition_outer_wrapper");
120
- const measureWrapper = container.querySelector(
121
- ".ui_transition_measure_wrapper",
122
- );
123
- const slot = container.querySelector(".ui_transition_slot");
124
- let phaseOverlay = measureWrapper.querySelector(
125
- ".ui_transition_phase_overlay",
126
- );
127
- let contentOverlay = container.querySelector(
128
- ".ui_transition_content_overlay",
129
- );
130
-
131
- if (!phaseOverlay) {
132
- phaseOverlay = document.createElement("div");
133
- phaseOverlay.className = "ui_transition_phase_overlay";
134
- measureWrapper.appendChild(phaseOverlay);
135
- }
136
- if (!contentOverlay) {
137
- contentOverlay = document.createElement("div");
138
- contentOverlay.className = "ui_transition_content_overlay";
139
- container.appendChild(contentOverlay);
140
- }
141
-
142
- if (
143
- !outerWrapper ||
144
- !measureWrapper ||
145
- !slot ||
146
- !phaseOverlay ||
147
- !contentOverlay
148
- ) {
149
- console.error("Missing required ui-transition structure");
150
- return { cleanup: () => {} };
151
- }
152
-
153
- const transitionController = createGroupTransitionController();
154
-
155
- // Transition state
156
- let activeContentTransition = null;
157
- let activeContentTransitionType = null;
158
- let activePhaseTransition = null;
159
- let activePhaseTransitionType = null;
160
- let isPaused = false;
161
-
162
- // Size state
163
- let naturalContentWidth = 0; // Natural size of actual content (not loading/error states)
164
- let naturalContentHeight = 0;
165
- let constrainedWidth = 0; // Current constrained dimensions (what outer wrapper is set to)
166
- let constrainedHeight = 0;
167
- let sizeTransition = null;
168
- let resizeObserver = null;
169
- let sizeHoldActive = false; // Hold previous dimensions during content transitions when size transitions are disabled
170
-
171
- // Prevent reacting to our own constrained size changes while animating
172
- let suppressResizeObserver = false;
173
- let pendingResizeSync = false; // ensure one measurement after suppression ends
174
-
175
- // Handle size updates based on content state
176
- let hasSizeTransitions = container.hasAttribute("data-size-transition");
177
- const initialTransitionEnabled = container.hasAttribute(
178
- "data-initial-transition",
179
- );
180
- let hasPopulatedOnce = false; // track if we've already populated once (null → something)
181
-
182
- // Child state
183
- let lastContentKey = null;
184
- let previousChild = null;
185
- let isContentPhase = false; // Current state: true when showing content phase (loading/error)
186
- let wasContentPhase = false; // Previous state for comparison
187
-
188
- const measureContentSize = () => {
189
- return [getWidth(measureWrapper), getHeight(measureWrapper)];
190
- };
191
-
192
- const updateContentDimensions = () => {
193
- const [newWidth, newHeight] = measureContentSize();
194
- debug("size", "Content size changed:", {
195
- width: `${naturalContentWidth} → ${newWidth}`,
196
- height: `${naturalContentHeight} → ${newHeight}`,
197
- });
198
-
199
- updateNaturalContentSize(newWidth, newHeight);
200
-
201
- if (sizeTransition) {
202
- debug("size", "Updating animation target:", newHeight);
203
- updateToSize(newWidth, newHeight);
204
- } else {
205
- constrainedWidth = newWidth;
206
- constrainedHeight = newHeight;
207
- }
208
- };
209
-
210
- const stopResizeObserver = () => {
211
- if (resizeObserver) {
212
- resizeObserver.disconnect();
213
- resizeObserver = null;
214
- }
215
- };
216
-
217
- const startResizeObserver = () => {
218
- resizeObserver = new ResizeObserver(() => {
219
- if (!hasSizeTransitions) {
220
- return;
221
- }
222
- if (suppressResizeObserver) {
223
- pendingResizeSync = true;
224
- debug("size", "Resize ignored (suppressed during size transition)");
225
- return;
226
- }
227
- updateContentDimensions();
228
- });
229
- resizeObserver.observe(measureWrapper);
230
- };
231
-
232
- const releaseConstraints = (reason) => {
233
- debug("size", `Releasing constraints (${reason})`);
234
- const [beforeWidth, beforeHeight] = measureContentSize();
235
- outerWrapper.style.width = "";
236
- outerWrapper.style.height = "";
237
- outerWrapper.style.overflow = "";
238
- const [afterWidth, afterHeight] = measureContentSize();
239
- debug("size", "Size after release:", {
240
- width: `${beforeWidth} → ${afterWidth}`,
241
- height: `${beforeHeight} → ${afterHeight}`,
242
- });
243
- constrainedWidth = afterWidth;
244
- constrainedHeight = afterHeight;
245
- naturalContentWidth = afterWidth;
246
- naturalContentHeight = afterHeight;
247
- // Defer a sync if suppression just ended; actual dispatch will come from resize observer
248
- if (!suppressResizeObserver && pendingResizeSync) {
249
- pendingResizeSync = false;
250
- updateContentDimensions();
251
- }
252
- };
253
-
254
- const updateToSize = (targetWidth, targetHeight) => {
255
- if (
256
- constrainedWidth === targetWidth &&
257
- constrainedHeight === targetHeight
258
- ) {
259
- return;
260
- }
261
-
262
- const shouldAnimate = container.hasAttribute("data-size-transition");
263
- const widthDiff = Math.abs(targetWidth - constrainedWidth);
264
- const heightDiff = Math.abs(targetHeight - constrainedHeight);
265
-
266
- if (widthDiff <= SIZE_DIFF_EPSILON && heightDiff <= SIZE_DIFF_EPSILON) {
267
- // Both diffs negligible; just sync styles if changed and bail
268
- if (widthDiff > 0) {
269
- outerWrapper.style.width = `${targetWidth}px`;
270
- constrainedWidth = targetWidth;
271
- }
272
- if (heightDiff > 0) {
273
- outerWrapper.style.height = `${targetHeight}px`;
274
- constrainedHeight = targetHeight;
275
- }
276
- debug(
277
- "size",
278
- `Skip size animation entirely (diffs width:${widthDiff.toFixed(4)}px height:${heightDiff.toFixed(4)}px)`,
279
- );
280
- return;
281
- }
282
-
283
- if (!shouldAnimate) {
284
- // No size transitions - just update dimensions instantly
285
- debug("size", "Updating size instantly:", {
286
- width: `${constrainedWidth} → ${targetWidth}`,
287
- height: `${constrainedHeight} → ${targetHeight}`,
288
- });
289
- suppressResizeObserver = true;
290
- outerWrapper.style.width = `${targetWidth}px`;
291
- outerWrapper.style.height = `${targetHeight}px`;
292
- constrainedWidth = targetWidth;
293
- constrainedHeight = targetHeight;
294
- // allow any resize notifications to settle then re-enable
295
- requestAnimationFrame(() => {
296
- suppressResizeObserver = false;
297
- if (pendingResizeSync) {
298
- pendingResizeSync = false;
299
- updateContentDimensions();
300
- }
301
- });
302
- return;
303
- }
304
-
305
- // Animated size transition
306
- debug("size", "Animating size:", {
307
- width: `${constrainedWidth} → ${targetWidth}`,
308
- height: `${constrainedHeight} → ${targetHeight}`,
309
- });
310
-
311
- const duration = parseInt(
312
- container.getAttribute("data-size-transition-duration") ||
313
- SIZE_TRANSITION_DURATION,
314
- );
315
-
316
- outerWrapper.style.overflow = "hidden";
317
- const transitions = [];
318
-
319
- // heightDiff & widthDiff already computed earlier in updateToSize when deciding to skip entirely
320
- if (heightDiff <= SIZE_DIFF_EPSILON) {
321
- // Treat as identical
322
- if (heightDiff > 0) {
323
- debug(
324
- "size",
325
- `Skip height transition (negligible diff ${heightDiff.toFixed(4)}px)`,
326
- );
327
- }
328
- outerWrapper.style.height = `${targetHeight}px`;
329
- constrainedHeight = targetHeight;
330
- } else if (targetHeight !== constrainedHeight) {
331
- transitions.push(
332
- createHeightTransition(outerWrapper, targetHeight, {
333
- duration,
334
- onUpdate: ({ value }) => {
335
- constrainedHeight = value;
336
- },
337
- }),
338
- );
339
- }
340
-
341
- if (widthDiff <= SIZE_DIFF_EPSILON) {
342
- if (widthDiff > 0) {
343
- debug(
344
- "size",
345
- `Skip width transition (negligible diff ${widthDiff.toFixed(4)}px)`,
346
- );
347
- }
348
- outerWrapper.style.width = `${targetWidth}px`;
349
- constrainedWidth = targetWidth;
350
- } else if (targetWidth !== constrainedWidth) {
351
- transitions.push(
352
- createWidthTransition(outerWrapper, targetWidth, {
353
- duration,
354
- onUpdate: ({ value }) => {
355
- constrainedWidth = value;
356
- },
357
- }),
358
- );
359
- }
360
-
361
- if (transitions.length > 0) {
362
- suppressResizeObserver = true;
363
- sizeTransition = transitionController.animate(transitions, {
364
- onFinish: () => {
365
- releaseConstraints("animated size transition completed");
366
- // End suppression next frame to avoid RO loop warnings
367
- requestAnimationFrame(() => {
368
- suppressResizeObserver = false;
369
- if (pendingResizeSync) {
370
- pendingResizeSync = false;
371
- updateContentDimensions();
372
- }
373
- });
374
- },
375
- });
376
- sizeTransition.play();
377
- } else {
378
- debug(
379
- "size",
380
- "No size transitions created (identical or negligible differences)",
381
- );
382
- }
383
- };
384
-
385
- const applySizeConstraints = (targetWidth, targetHeight) => {
386
- debug("size", "Applying size constraints:", {
387
- width: `${constrainedWidth} → ${targetWidth}`,
388
- height: `${constrainedHeight} → ${targetHeight}`,
389
- });
390
-
391
- outerWrapper.style.width = `${targetWidth}px`;
392
- outerWrapper.style.height = `${targetHeight}px`;
393
- outerWrapper.style.overflow = "hidden";
394
- constrainedWidth = targetWidth;
395
- constrainedHeight = targetHeight;
396
- };
397
-
398
- const updateNaturalContentSize = (newWidth, newHeight) => {
399
- debug("size", "Updating natural content size:", {
400
- width: `${naturalContentWidth} → ${newWidth}`,
401
- height: `${naturalContentHeight} → ${newHeight}`,
402
- });
403
- naturalContentWidth = newWidth;
404
- naturalContentHeight = newHeight;
405
- };
406
-
407
- let isUpdating = false;
408
-
409
- // Shared transition setup function
410
- const setupTransition = ({
411
- isPhaseTransition = false,
412
- overlay,
413
- existingOldContents,
414
- needsOldChildClone,
415
- previousChild,
416
- firstChild,
417
- attributeToRemove = [],
418
- }) => {
419
- let oldChild = null;
420
- let cleanup = () => {};
421
- const currentTransitionElement = existingOldContents[0];
422
-
423
- if (currentTransitionElement) {
424
- oldChild = currentTransitionElement;
425
- debug(
426
- "transition",
427
- `Continuing from current ${isPhaseTransition ? "phase" : "content"} transition element`,
428
- );
429
- cleanup = () => oldChild.remove();
430
- } else if (needsOldChildClone) {
431
- overlay.innerHTML = "";
432
-
433
- // Clone the individual element for the transition
434
- oldChild = previousChild.cloneNode(true);
435
-
436
- // Remove specified attributes
437
- attributeToRemove.forEach((attr) => oldChild.removeAttribute(attr));
438
-
439
- oldChild.setAttribute("data-ui-transition-old", "");
440
- overlay.appendChild(oldChild);
441
- debug(
442
- "transition",
443
- `Cloned previous child for ${isPhaseTransition ? "phase" : "content"} transition:`,
444
- getElementSignature(previousChild),
445
- );
446
- cleanup = () => oldChild.remove();
447
- } else {
448
- overlay.innerHTML = "";
449
- debug(
450
- "transition",
451
- `No old child to clone for ${isPhaseTransition ? "phase" : "content"} transition`,
452
- );
453
- }
454
-
455
- // Determine which elements to return based on transition type:
456
- // - Phase transitions: operate on individual elements (cross-fade between specific elements)
457
- // - Content transitions: operate at container level (slide entire containers, outlive content phases)
458
- let oldElement;
459
- let newElement;
460
- if (isPhaseTransition) {
461
- // Phase transitions work on individual elements
462
- oldElement = oldChild;
463
- newElement = firstChild;
464
- } else {
465
- // Content transitions work at container level and can outlive content phase changes
466
- oldElement = oldChild ? overlay : null;
467
- newElement = firstChild ? measureWrapper : null;
468
- }
469
-
470
- return {
471
- oldChild,
472
- cleanup,
473
- oldElement,
474
- newElement,
475
- };
476
- };
477
-
478
- // Initialize with current size
479
- [constrainedWidth, constrainedHeight] = measureContentSize();
480
-
481
- const handleChildSlotMutation = (reason = "mutation") => {
482
- if (isUpdating) {
483
- debug("transition", "Preventing recursive update");
484
- return;
485
- }
486
-
487
- hasSizeTransitions = container.hasAttribute("data-size-transition");
488
-
489
- try {
490
- isUpdating = true;
491
- const firstChild = slot.children[0] || null;
492
- const childUIName = firstChild?.getAttribute("data-ui-name");
493
- if (localDebug.transition) {
494
- const updateLabel =
495
- childUIName ||
496
- (firstChild ? getElementSignature(firstChild) : "cleared/empty");
497
- console.group(`UI Update: ${updateLabel} (reason: ${reason})`);
498
- }
499
-
500
- // Check for text nodes in the slot (not supported)
501
- const hasTextNode = Array.from(slot.childNodes).some(
502
- (node) => node.nodeType === Node.TEXT_NODE && node.textContent.trim(),
503
- );
504
- if (hasTextNode) {
505
- console.warn(
506
- "UI Transition: Text nodes in transition slots are not supported. Please wrap text content in an element.",
507
- { slot, textContent: slot.textContent.trim() },
508
- );
509
- }
510
-
511
- // Check for multiple elements in the slot (not supported yet)
512
- const hasMultipleElements = slot.children.length > 1;
513
- if (hasMultipleElements) {
514
- console.warn(
515
- "UI Transition: Multiple elements in transition slots are not supported yet. Please use a single container element.",
516
- { slot, elementCount: slot.children.length },
517
- );
518
- }
519
-
520
- // Prefer data-content-key on child, fallback to slot
521
- let currentContentKey = null;
522
- let slotContentKey = slot.getAttribute("data-content-key");
523
- let childContentKey = firstChild?.getAttribute("data-content-key");
524
- if (childContentKey && slotContentKey) {
525
- console.warn(
526
- "Both data-content-key found on child and ui_transition_slot. Using child value.",
527
- { childContentKey, slotContentKey },
528
- );
529
- }
530
- currentContentKey = childContentKey || slotContentKey || null;
531
-
532
- // Determine transition scenarios early for early registration check
533
- const hadChild = previousChild !== null;
534
- const hasChild = firstChild !== null;
535
-
536
- // Check for text nodes in previous state (reconstruct from previousChild)
537
- const hadTextNode =
538
- previousChild && previousChild.nodeType === Node.TEXT_NODE;
539
-
540
- // Compute formatted content key states ONCE per mutation (requirement: max 2 calls)
541
- const previousContentKeyState = formatContentKeyState(
542
- lastContentKey,
543
- hadChild,
544
- hadTextNode,
545
- );
546
- const currentContentKeyState = formatContentKeyState(
547
- currentContentKey,
548
- hasChild,
549
- hasTextNode,
550
- );
551
-
552
- // Track previous key before any potential early registration update
553
- const prevKeyBeforeRegistration = lastContentKey;
554
-
555
- // Prepare phase info early so logging can be unified (even for early return)
556
- wasContentPhase = isContentPhase;
557
- isContentPhase = firstChild
558
- ? firstChild.hasAttribute("data-content-phase")
559
- : true; // empty (no child) is treated as content phase
560
-
561
- const previousIsContentPhase = !hadChild || wasContentPhase;
562
- const currentIsContentPhase = !hasChild || isContentPhase;
563
-
564
- // Early conceptual registration path: empty slot, text nodes, or multiple elements (no visual transition)
565
- const shouldGiveUpEarlyAndJustRegister =
566
- (!hadChild && !hasChild && !hasTextNode) ||
567
- hasTextNode ||
568
- hasMultipleElements;
569
- let earlyAction = null;
570
- if (shouldGiveUpEarlyAndJustRegister) {
571
- if (hasTextNode) {
572
- earlyAction = "text_nodes_unsupported";
573
- } else if (hasMultipleElements) {
574
- earlyAction = "multiple_elements_unsupported";
575
- } else {
576
- const prevKey = prevKeyBeforeRegistration;
577
- const keyChanged = prevKey !== currentContentKey;
578
- if (!keyChanged) {
579
- earlyAction = "unchanged";
580
- } else if (prevKey === null && currentContentKey !== null) {
581
- earlyAction = "registered";
582
- } else if (prevKey !== null && currentContentKey === null) {
583
- earlyAction = "cleared";
584
- } else {
585
- earlyAction = "changed";
586
- }
587
- }
588
- // Will update lastContentKey after unified logging
589
- }
590
-
591
- // Decide which representation to display for previous/current in early case
592
- const conceptualPrevDisplay =
593
- prevKeyBeforeRegistration === null
594
- ? "[unkeyed]"
595
- : `[data-content-key="${prevKeyBeforeRegistration}"]`;
596
- const conceptualCurrentDisplay =
597
- currentContentKey === null
598
- ? "[unkeyed]"
599
- : `[data-content-key="${currentContentKey}"]`;
600
- const previousDisplay = shouldGiveUpEarlyAndJustRegister
601
- ? conceptualPrevDisplay
602
- : previousContentKeyState;
603
- const currentDisplay = shouldGiveUpEarlyAndJustRegister
604
- ? conceptualCurrentDisplay
605
- : currentContentKeyState;
606
-
607
- // Build a simple descriptive sentence
608
- let contentKeysSentence = `Content key: ${previousDisplay} → ${currentDisplay}`;
609
- debug("transition", contentKeysSentence);
610
-
611
- if (shouldGiveUpEarlyAndJustRegister) {
612
- // Log decision explicitly (was previously embedded)
613
- debug("transition", `Decision: EARLY_RETURN (${earlyAction})`);
614
- // Register new conceptual key & return early (skip rest of transition logic)
615
- lastContentKey = currentContentKey;
616
- if (localDebug.transition) {
617
- console.groupEnd();
618
- }
619
- return;
620
- }
621
- debug(
622
- "size",
623
- `Update triggered, size: ${constrainedWidth}x${constrainedHeight}`,
624
- );
625
-
626
- if (sizeTransition) {
627
- sizeTransition.cancel();
628
- }
629
-
630
- const [newWidth, newHeight] = measureContentSize();
631
- debug("size", `Measured size: ${newWidth}x${newHeight}`);
632
- outerWrapper.style.width = `${constrainedWidth}px`;
633
- outerWrapper.style.height = `${constrainedHeight}px`;
634
-
635
- // Handle resize observation
636
- stopResizeObserver();
637
- if (firstChild && !isContentPhase) {
638
- startResizeObserver();
639
- debug("size", "Observing child resize");
640
- }
641
-
642
- // Determine transition scenarios (hadChild/hasChild already computed above for logging)
643
-
644
- /**
645
- * Content Phase Logic: Why empty slots are treated as content phases
646
- *
647
- * When there is no child element (React component returns null), it is considered
648
- * that the component does not render anything temporarily. This might be because:
649
- * - The component is loading but does not have a loading state
650
- * - The component has an error but does not have an error state
651
- * - The component is conceptually unloaded (underlying content was deleted/is not accessible)
652
- *
653
- * This represents a phase of the given content: having nothing to display.
654
- *
655
- * We support transitions between different contents via the ability to set
656
- * [data-content-key] on the ".ui_transition_slot". This is also useful when you want
657
- * all children of a React component to inherit the same data-content-key without
658
- * explicitly setting the attribute on each child element.
659
- */
660
-
661
- // Content key change when either slot or child has data-content-key and it changed
662
- let shouldDoContentTransition = false;
663
- if (
664
- (slot.getAttribute("data-content-key") ||
665
- firstChild?.getAttribute("data-content-key")) &&
666
- lastContentKey !== null
667
- ) {
668
- shouldDoContentTransition = currentContentKey !== lastContentKey;
669
- }
670
-
671
- const becomesEmpty = hadChild && !hasChild;
672
- const becomesPopulated = !hadChild && hasChild;
673
- const isInitialPopulationWithoutTransition =
674
- becomesPopulated && !hasPopulatedOnce && !initialTransitionEnabled;
675
-
676
- // Content phase change: any transition between content/content-phase/null except when slot key changes
677
- // This includes: null→loading, loading→content, content→loading, loading→null, etc.
678
- const shouldDoPhaseTransition =
679
- !shouldDoContentTransition &&
680
- (becomesPopulated ||
681
- becomesEmpty ||
682
- (hadChild &&
683
- hasChild &&
684
- (previousIsContentPhase !== currentIsContentPhase ||
685
- (previousIsContentPhase && currentIsContentPhase))));
686
-
687
- const contentChange = hadChild && hasChild && shouldDoContentTransition;
688
- const phaseChange = hadChild && hasChild && shouldDoPhaseTransition;
689
-
690
- // Determine if we only need to preserve an existing content transition (no new change)
691
- const preserveOnlyContentTransition =
692
- activeContentTransition !== null &&
693
- !shouldDoContentTransition &&
694
- !shouldDoPhaseTransition &&
695
- !becomesPopulated &&
696
- !becomesEmpty;
697
-
698
- // Include becomesPopulated in content transition only if it's not a phase transition
699
- const shouldDoContentTransitionIncludingPopulation =
700
- shouldDoContentTransition ||
701
- (becomesPopulated && !shouldDoPhaseTransition);
702
-
703
- const decisions = [];
704
- if (shouldDoContentTransition) decisions.push("CONTENT TRANSITION");
705
- if (shouldDoPhaseTransition) decisions.push("PHASE TRANSITION");
706
- if (preserveOnlyContentTransition)
707
- decisions.push("PRESERVE CONTENT TRANSITION");
708
- if (decisions.length === 0) decisions.push("NO TRANSITION");
709
-
710
- debug("transition", `Decision: ${decisions.join(" + ")}`);
711
- if (preserveOnlyContentTransition) {
712
- const progress = (activeContentTransition.progress * 100).toFixed(1);
713
- debug(
714
- "transition",
715
- `Preserving existing content transition (progress ${progress}%)`,
716
- );
717
- }
718
-
719
- // Early return optimization: if no transition decision and we are not continuing
720
- // an existing active content transition (animationProgress > 0), we can skip
721
- // all transition setup logic below.
722
- if (
723
- decisions.length === 1 &&
724
- decisions[0] === "NO TRANSITION" &&
725
- activeContentTransition === null &&
726
- activePhaseTransition === null
727
- ) {
728
- debug(
729
- "transition",
730
- `Early return: no transition or continuation required`,
731
- );
732
- // Still ensure size logic executes below (so do not return before size alignment)
733
- }
734
-
735
- // Handle initial population skip (first null → something): no content or size animations
736
- if (isInitialPopulationWithoutTransition) {
737
- debug(
738
- "transition",
739
- "Initial population detected: skipping transitions (opt-in with data-initial-transition)",
740
- );
741
-
742
- // Apply sizes instantly, no animation
743
- if (isContentPhase) {
744
- applySizeConstraints(newWidth, newHeight);
745
- } else {
746
- updateNaturalContentSize(newWidth, newHeight);
747
- releaseConstraints("initial population - skip transitions");
748
- }
749
-
750
- // Register state and mark initial population done
751
- previousChild = firstChild;
752
- lastContentKey = currentContentKey;
753
- hasPopulatedOnce = true;
754
- if (localDebug.transition) {
755
- console.groupEnd();
756
- }
757
- return;
758
- }
759
-
760
- // Plan size transition upfront; execution will happen after content/phase transitions
761
- let sizePlan = {
762
- action: "none",
763
- targetWidth: constrainedWidth,
764
- targetHeight: constrainedHeight,
765
- };
766
-
767
- size_transition: {
768
- const getTargetDimensions = () => {
769
- if (!isContentPhase) {
770
- return [newWidth, newHeight];
771
- }
772
- const shouldUseNewDimensions =
773
- naturalContentWidth === 0 && naturalContentHeight === 0;
774
- const targetWidth = shouldUseNewDimensions
775
- ? newWidth
776
- : naturalContentWidth || newWidth;
777
- const targetHeight = shouldUseNewDimensions
778
- ? newHeight
779
- : naturalContentHeight || newHeight;
780
- return [targetWidth, targetHeight];
781
- };
782
-
783
- const [targetWidth, targetHeight] = getTargetDimensions();
784
- sizePlan.targetWidth = targetWidth;
785
- sizePlan.targetHeight = targetHeight;
786
-
787
- if (
788
- targetWidth === constrainedWidth &&
789
- targetHeight === constrainedHeight
790
- ) {
791
- debug("size", "No size change required");
792
- // We'll handle potential constraint release in final section (if not holding)
793
- break size_transition;
794
- }
795
-
796
- debug("size", "Size change needed:", {
797
- width: `${constrainedWidth} → ${targetWidth}`,
798
- height: `${constrainedHeight} → ${targetHeight}`,
799
- });
800
-
801
- if (isContentPhase) {
802
- // Content phases (loading/error) always use size constraints for consistent sizing
803
- sizePlan.action = hasSizeTransitions ? "animate" : "applyConstraints";
804
- } else {
805
- // Actual content: update natural content dimensions for future content phases
806
- updateNaturalContentSize(targetWidth, targetHeight);
807
- sizePlan.action = hasSizeTransitions ? "animate" : "release";
808
- }
809
- }
810
-
811
- content_transition: {
812
- // Handle content transitions (slide-left, cross-fade for content key changes)
813
- if (
814
- decisions.length === 1 &&
815
- decisions[0] === "NO TRANSITION" &&
816
- activeContentTransition === null &&
817
- activePhaseTransition === null
818
- ) {
819
- // Skip creating any new transitions entirely
820
- } else if (
821
- shouldDoContentTransitionIncludingPopulation &&
822
- !preserveOnlyContentTransition
823
- ) {
824
- const existingOldContents = contentOverlay.querySelectorAll(
825
- "[data-ui-transition-old]",
826
- );
827
- const animationProgress = activeContentTransition?.progress || 0;
828
-
829
- if (animationProgress > 0) {
830
- debug(
831
- "transition",
832
- `Preserving content transition progress: ${(animationProgress * 100).toFixed(1)}%`,
833
- );
834
- }
835
-
836
- const newTransitionType =
837
- container.getAttribute("data-content-transition") ||
838
- CONTENT_TRANSITION;
839
- const canContinueSmoothly =
840
- activeContentTransitionType === newTransitionType &&
841
- activeContentTransition;
842
-
843
- if (canContinueSmoothly) {
844
- debug(
845
- "transition",
846
- "Continuing with same content transition type (restarting due to actual change)",
847
- );
848
- activeContentTransition.cancel();
849
- } else if (
850
- activeContentTransition &&
851
- activeContentTransitionType !== newTransitionType
852
- ) {
853
- debug(
854
- "transition",
855
- "Different content transition type, keeping both",
856
- `${activeContentTransitionType} → ${newTransitionType}`,
857
- );
858
- } else if (activeContentTransition) {
859
- debug("transition", "Cancelling current content transition");
860
- activeContentTransition.cancel();
861
- }
862
-
863
- const needsOldChildClone =
864
- (contentChange || becomesEmpty) &&
865
- previousChild &&
866
- !existingOldContents[0];
867
-
868
- const duration = parseInt(
869
- container.getAttribute("data-content-transition-duration") ||
870
- CONTENT_TRANSITION_DURATION,
871
- );
872
- const type =
873
- container.getAttribute("data-content-transition") ||
874
- CONTENT_TRANSITION;
875
-
876
- const setupContentTransition = () =>
877
- setupTransition({
878
- isPhaseTransition: false,
879
- overlay: contentOverlay,
880
- existingOldContents,
881
- needsOldChildClone,
882
- previousChild,
883
- firstChild,
884
- attributeToRemove: ["data-content-key"],
885
- });
886
-
887
- // If size transitions are disabled and the new content is smaller,
888
- // hold the previous size to avoid cropping during the transition.
889
- if (!hasSizeTransitions) {
890
- const willShrinkWidth = constrainedWidth > newWidth;
891
- const willShrinkHeight = constrainedHeight > newHeight;
892
- sizeHoldActive = willShrinkWidth || willShrinkHeight;
893
- if (sizeHoldActive) {
894
- debug(
895
- "size",
896
- `Holding previous size during content transition: ${constrainedWidth}x${constrainedHeight}`,
897
- );
898
- applySizeConstraints(constrainedWidth, constrainedHeight);
899
- }
900
- }
901
-
902
- activeContentTransition = animateTransition(
903
- transitionController,
904
- firstChild,
905
- setupContentTransition,
906
- {
907
- duration,
908
- type,
909
- animationProgress,
910
- isPhaseTransition: false,
911
- fromContentKeyState: previousContentKeyState,
912
- toContentKeyState: currentContentKeyState,
913
- onComplete: () => {
914
- activeContentTransition = null;
915
- activeContentTransitionType = null;
916
- if (sizeHoldActive) {
917
- // Release the hold after the content transition completes
918
- releaseConstraints(
919
- "content transition completed - release size hold",
920
- );
921
- sizeHoldActive = false;
922
- }
923
- },
924
- debug,
925
- },
926
- );
927
-
928
- if (activeContentTransition) {
929
- activeContentTransition.play();
930
- }
931
- activeContentTransitionType = type;
932
- } else if (
933
- !shouldDoContentTransition &&
934
- !preserveOnlyContentTransition
935
- ) {
936
- // Clean up content overlay if no content transition needed and nothing to preserve
937
- contentOverlay.innerHTML = "";
938
- activeContentTransition = null;
939
- activeContentTransitionType = null;
940
- }
941
-
942
- // Handle phase transitions (cross-fade for content phase changes)
943
- if (shouldDoPhaseTransition) {
944
- const phaseTransitionType =
945
- container.getAttribute("data-phase-transition") || PHASE_TRANSITION;
946
-
947
- const existingOldPhaseContents = phaseOverlay.querySelectorAll(
948
- "[data-ui-transition-old]",
949
- );
950
- const phaseAnimationProgress = activePhaseTransition?.progress || 0;
951
-
952
- if (phaseAnimationProgress > 0) {
953
- debug(
954
- "transition",
955
- `Preserving phase transition progress: ${(phaseAnimationProgress * 100).toFixed(1)}%`,
956
- );
957
- }
958
-
959
- const canContinueSmoothly =
960
- activePhaseTransitionType === phaseTransitionType &&
961
- activePhaseTransition;
962
-
963
- if (canContinueSmoothly) {
964
- debug("transition", "Continuing with same phase transition type");
965
- activePhaseTransition.cancel();
966
- } else if (
967
- activePhaseTransition &&
968
- activePhaseTransitionType !== phaseTransitionType
969
- ) {
970
- debug(
971
- "transition",
972
- "Different phase transition type, keeping both",
973
- `${activePhaseTransitionType} → ${phaseTransitionType}`,
974
- );
975
- } else if (activePhaseTransition) {
976
- debug("transition", "Cancelling current phase transition");
977
- activePhaseTransition.cancel();
978
- }
979
-
980
- const needsOldPhaseClone =
981
- (becomesEmpty || becomesPopulated || phaseChange) &&
982
- previousChild &&
983
- !existingOldPhaseContents[0];
984
-
985
- const phaseDuration = parseInt(
986
- container.getAttribute("data-phase-transition-duration") ||
987
- PHASE_TRANSITION_DURATION,
988
- );
989
-
990
- const setupPhaseTransition = () =>
991
- setupTransition({
992
- isPhaseTransition: true,
993
- overlay: phaseOverlay,
994
- existingOldContents: existingOldPhaseContents,
995
- needsOldChildClone: needsOldPhaseClone,
996
- previousChild,
997
- firstChild,
998
- attributeToRemove: ["data-content-key", "data-content-phase"],
999
- });
1000
-
1001
- const fromPhase = !hadChild
1002
- ? "null"
1003
- : wasContentPhase
1004
- ? "content-phase"
1005
- : "content";
1006
- const toPhase = !hasChild
1007
- ? "null"
1008
- : isContentPhase
1009
- ? "content-phase"
1010
- : "content";
1011
-
1012
- debug(
1013
- "transition",
1014
- `Starting phase transition: ${fromPhase} → ${toPhase}`,
1015
- );
1016
-
1017
- activePhaseTransition = animateTransition(
1018
- transitionController,
1019
- firstChild,
1020
- setupPhaseTransition,
1021
- {
1022
- duration: phaseDuration,
1023
- type: phaseTransitionType,
1024
- animationProgress: phaseAnimationProgress,
1025
- isPhaseTransition: true,
1026
- fromContentKeyState: previousContentKeyState,
1027
- toContentKeyState: currentContentKeyState,
1028
- onComplete: () => {
1029
- activePhaseTransition = null;
1030
- activePhaseTransitionType = null;
1031
- debug("transition", "Phase transition complete");
1032
- },
1033
- debug,
1034
- },
1035
- );
1036
-
1037
- if (activePhaseTransition) {
1038
- activePhaseTransition.play();
1039
- }
1040
- activePhaseTransitionType = phaseTransitionType;
1041
- }
1042
- }
1043
-
1044
- // Store current child for next transition
1045
- previousChild = firstChild;
1046
- lastContentKey = currentContentKey;
1047
- if (becomesPopulated) {
1048
- hasPopulatedOnce = true;
1049
- }
1050
-
1051
- // Execute planned size action, unless holding size during a content transition
1052
- if (!sizeHoldActive) {
1053
- if (
1054
- sizePlan.targetWidth === constrainedWidth &&
1055
- sizePlan.targetHeight === constrainedHeight
1056
- ) {
1057
- // no size changes planned; possibly release constraints
1058
- if (!isContentPhase) {
1059
- releaseConstraints("no size change needed");
1060
- }
1061
- } else if (sizePlan.action === "animate") {
1062
- updateToSize(sizePlan.targetWidth, sizePlan.targetHeight);
1063
- } else if (sizePlan.action === "applyConstraints") {
1064
- applySizeConstraints(sizePlan.targetWidth, sizePlan.targetHeight);
1065
- } else if (sizePlan.action === "release") {
1066
- releaseConstraints("actual content - no size transitions needed");
1067
- }
1068
- }
1069
- } finally {
1070
- isUpdating = false;
1071
- if (localDebug.transition) {
1072
- console.groupEnd();
1073
- }
1074
- }
1075
- };
1076
-
1077
- // Run once at init to process current slot content (warnings, sizing, transitions)
1078
- handleChildSlotMutation("init");
1079
-
1080
- // Watch for child changes and attribute changes on children
1081
- const mutationObserver = new MutationObserver((mutations) => {
1082
- let childListMutation = false;
1083
- const attributeMutationSet = new Set();
1084
-
1085
- for (const mutation of mutations) {
1086
- if (mutation.type === "childList") {
1087
- childListMutation = true;
1088
- continue;
1089
- }
1090
- if (mutation.type === "attributes") {
1091
- const { attributeName, target } = mutation;
1092
- if (
1093
- attributeName === "data-content-key" ||
1094
- attributeName === "data-content-phase"
1095
- ) {
1096
- attributeMutationSet.add(attributeName);
1097
- debug(
1098
- "transition",
1099
- `Attribute change detected: ${attributeName} on`,
1100
- getElementSignature(target),
1101
- );
1102
- }
1103
- }
1104
- }
1105
-
1106
- if (!childListMutation && attributeMutationSet.size === 0) {
1107
- return;
1108
- }
1109
- const reasonParts = [];
1110
- if (childListMutation) {
1111
- reasonParts.push("childList change");
1112
- }
1113
- if (attributeMutationSet.size) {
1114
- for (const attr of attributeMutationSet) {
1115
- reasonParts.push(`[${attr}] change`);
1116
- }
1117
- }
1118
- const reason = reasonParts.join("+");
1119
- handleChildSlotMutation(reason);
1120
- });
1121
-
1122
- mutationObserver.observe(slot, {
1123
- childList: true,
1124
- attributes: true,
1125
- attributeFilter: ["data-content-key", "data-content-phase"],
1126
- characterData: false,
1127
- });
1128
-
1129
- // Return API
1130
- return {
1131
- slot,
1132
-
1133
- cleanup: () => {
1134
- mutationObserver.disconnect();
1135
- stopResizeObserver();
1136
- if (sizeTransition) {
1137
- sizeTransition.cancel();
1138
- }
1139
- if (activeContentTransition) {
1140
- activeContentTransition.cancel();
1141
- }
1142
- if (activePhaseTransition) {
1143
- activePhaseTransition.cancel();
1144
- }
1145
- },
1146
- pause: () => {
1147
- if (activeContentTransition?.pause) {
1148
- activeContentTransition.pause();
1149
- isPaused = true;
1150
- }
1151
- if (activePhaseTransition?.pause) {
1152
- activePhaseTransition.pause();
1153
- isPaused = true;
1154
- }
1155
- },
1156
- resume: () => {
1157
- if (activeContentTransition?.play && isPaused) {
1158
- activeContentTransition.play();
1159
- isPaused = false;
1160
- }
1161
- if (activePhaseTransition?.play && isPaused) {
1162
- activePhaseTransition.play();
1163
- isPaused = false;
1164
- }
1165
- },
1166
- getState: () => ({
1167
- isPaused,
1168
- contentTransitionInProgress: activeContentTransition !== null,
1169
- phaseTransitionInProgress: activePhaseTransition !== null,
1170
- }),
1171
- };
1172
- };
1173
-
1174
- const animateTransition = (
1175
- transitionController,
1176
- newChild,
1177
- setupTransition,
1178
- {
1179
- type,
1180
- duration,
1181
- animationProgress = 0,
1182
- isPhaseTransition,
1183
- onComplete,
1184
- fromContentKeyState,
1185
- toContentKeyState,
1186
- debug,
1187
- },
1188
- ) => {
1189
- let transitionType;
1190
- if (type === "cross-fade") {
1191
- transitionType = crossFade;
1192
- } else if (type === "slide-left") {
1193
- transitionType = slideLeft;
1194
- } else {
1195
- return null;
1196
- }
1197
-
1198
- const { cleanup, oldElement, newElement } = setupTransition();
1199
- // Use precomputed content key states (expected to be provided by caller)
1200
- const fromContentKey = fromContentKeyState;
1201
- const toContentKey = toContentKeyState;
1202
-
1203
- debug("transition", "Setting up animation:", {
1204
- type,
1205
- from: fromContentKey,
1206
- to: toContentKey,
1207
- progress: `${(animationProgress * 100).toFixed(1)}%`,
1208
- });
1209
-
1210
- const remainingDuration = Math.max(100, duration * (1 - animationProgress));
1211
- debug("transition", `Animation duration: ${remainingDuration}ms`);
1212
-
1213
- const transitions = transitionType.apply(oldElement, newElement, {
1214
- duration: remainingDuration,
1215
- startProgress: animationProgress,
1216
- isPhaseTransition,
1217
- debug,
1218
- });
1219
-
1220
- debug(
1221
- "transition",
1222
- `Created ${transitions.length} transition(s) for animation`,
1223
- );
1224
-
1225
- if (transitions.length === 0) {
1226
- debug("transition", "No transitions to animate, cleaning up immediately");
1227
- cleanup();
1228
- onComplete?.();
1229
- return null;
1230
- }
1231
-
1232
- const groupTransition = transitionController.animate(transitions, {
1233
- onFinish: () => {
1234
- groupTransition.cancel();
1235
- cleanup();
1236
- onComplete?.();
1237
- },
1238
- });
1239
-
1240
- return groupTransition;
1241
- };
1242
-
1243
- const slideLeft = {
1244
- name: "slide-left",
1245
- apply: (
1246
- oldElement,
1247
- newElement,
1248
- { duration, startProgress = 0, isPhaseTransition = false, debug },
1249
- ) => {
1250
- if (!oldElement && !newElement) {
1251
- return [];
1252
- }
1253
-
1254
- if (!newElement) {
1255
- // Content -> Empty (slide out left only)
1256
- const currentPosition = getTranslateX(oldElement);
1257
- const containerWidth = getInnerWidth(oldElement.parentElement);
1258
- const from = currentPosition;
1259
- const to = -containerWidth;
1260
- debug("transition", "Slide out to empty:", { from, to });
1261
-
1262
- return [
1263
- createTranslateXTransition(oldElement, to, {
1264
- from,
1265
- duration,
1266
- startProgress,
1267
- onUpdate: ({ value, timing }) => {
1268
- debug("transition_updates", "Slide out progress:", value);
1269
- if (timing === "end") {
1270
- debug("transition", "Slide out complete");
1271
- }
1272
- },
1273
- }),
1274
- ];
1275
- }
1276
-
1277
- if (!oldElement) {
1278
- // Empty -> Content (slide in from right)
1279
- const containerWidth = getInnerWidth(newElement.parentElement);
1280
- const from = containerWidth; // Start from right edge for slide-in effect
1281
- const to = getTranslateXWithoutTransition(newElement);
1282
- debug("transition", "Slide in from empty:", { from, to });
1283
- return [
1284
- createTranslateXTransition(newElement, to, {
1285
- from,
1286
- duration,
1287
- startProgress,
1288
- onUpdate: ({ value, timing }) => {
1289
- debug("transition_updates", "Slide in progress:", value);
1290
- if (timing === "end") {
1291
- debug("transition", "Slide in complete");
1292
- }
1293
- },
1294
- }),
1295
- ];
1296
- }
1297
-
1298
- // Content -> Content (slide left)
1299
- // The old content (oldElement) slides OUT to the left
1300
- // The new content (newElement) slides IN from the right
1301
-
1302
- // Get positions for the slide animation
1303
- const containerWidth = getInnerWidth(newElement.parentElement);
1304
- const oldContentPosition = getTranslateX(oldElement);
1305
- const currentNewPosition = getTranslateX(newElement);
1306
- const naturalNewPosition = getTranslateXWithoutTransition(newElement);
1307
-
1308
- // For smooth continuation: if newElement is mid-transition,
1309
- // calculate new position to maintain seamless sliding
1310
- let startNewPosition;
1311
- if (currentNewPosition !== 0 && naturalNewPosition === 0) {
1312
- startNewPosition = currentNewPosition + containerWidth;
1313
- debug(
1314
- "transition",
1315
- "Calculated seamless position:",
1316
- `${currentNewPosition} + ${containerWidth} = ${startNewPosition}`,
1317
- );
1318
- } else {
1319
- startNewPosition = naturalNewPosition || containerWidth;
1320
- }
1321
-
1322
- // For phase transitions, force new content to start from right edge for proper slide-in
1323
- const effectiveFromPosition = isPhaseTransition
1324
- ? containerWidth
1325
- : startNewPosition;
1326
-
1327
- debug("transition", "Slide transition:", {
1328
- oldContent: `${oldContentPosition} → ${-containerWidth}`,
1329
- newContent: `${effectiveFromPosition} → ${naturalNewPosition}`,
1330
- });
1331
-
1332
- const transitions = [];
1333
-
1334
- // Slide old content out
1335
- transitions.push(
1336
- createTranslateXTransition(oldElement, -containerWidth, {
1337
- from: oldContentPosition,
1338
- duration,
1339
- startProgress,
1340
- onUpdate: ({ value }) => {
1341
- debug("transition_updates", "Old content slide out:", value);
1342
- },
1343
- }),
1344
- );
1345
-
1346
- // Slide new content in
1347
- transitions.push(
1348
- createTranslateXTransition(newElement, naturalNewPosition, {
1349
- from: effectiveFromPosition,
1350
- duration,
1351
- startProgress,
1352
- onUpdate: ({ value, timing }) => {
1353
- debug("transition_updates", "New content slide in:", value);
1354
- if (timing === "end") {
1355
- debug("transition", "Slide complete");
1356
- }
1357
- },
1358
- }),
1359
- );
1360
-
1361
- return transitions;
1362
- },
1363
- };
1364
-
1365
- const crossFade = {
1366
- name: "cross-fade",
1367
- apply: (
1368
- oldElement,
1369
- newElement,
1370
- { duration, startProgress = 0, isPhaseTransition = false, debug },
1371
- ) => {
1372
- if (!oldElement && !newElement) {
1373
- return [];
1374
- }
1375
-
1376
- if (!newElement) {
1377
- // Content -> Empty (fade out only)
1378
- const from = getOpacity(oldElement);
1379
- const to = 0;
1380
- debug("transition", "Fade out to empty:", { from, to });
1381
- return [
1382
- createOpacityTransition(oldElement, to, {
1383
- from,
1384
- duration,
1385
- startProgress,
1386
- onUpdate: ({ value, timing }) => {
1387
- debug("transition_updates", "Content fade out:", value.toFixed(3));
1388
- if (timing === "end") {
1389
- debug("transition", "Fade out complete");
1390
- }
1391
- },
1392
- }),
1393
- ];
1394
- }
1395
-
1396
- if (!oldElement) {
1397
- // Empty -> Content (fade in only)
1398
- const from = 0;
1399
- const to = getOpacityWithoutTransition(newElement);
1400
- debug("transition", "Fade in from empty:", { from, to });
1401
- return [
1402
- createOpacityTransition(newElement, to, {
1403
- from,
1404
- duration,
1405
- startProgress,
1406
- onUpdate: ({ value, timing }) => {
1407
- debug("transition_updates", "Fade in progress:", value.toFixed(3));
1408
- if (timing === "end") {
1409
- debug("transition", "Fade in complete");
1410
- }
1411
- },
1412
- }),
1413
- ];
1414
- }
1415
-
1416
- // Content -> Content (cross-fade)
1417
- // Get current opacity for both elements
1418
- const oldOpacity = getOpacity(oldElement);
1419
- const newOpacity = getOpacity(newElement);
1420
- const newNaturalOpacity = getOpacityWithoutTransition(newElement);
1421
-
1422
- // For phase transitions, always start new content from 0 for clean visual transition
1423
- // For content transitions, check for ongoing transitions to continue smoothly
1424
- let effectiveFromOpacity;
1425
- if (isPhaseTransition) {
1426
- effectiveFromOpacity = 0; // Always start fresh for phase transitions (loading → content, etc.)
1427
- } else {
1428
- // For content transitions: if new element has ongoing opacity transition
1429
- // (indicated by non-zero opacity when natural opacity is different),
1430
- // start from current opacity to continue smoothly, otherwise start from 0
1431
- const hasOngoingTransition =
1432
- newOpacity !== newNaturalOpacity && newOpacity > 0;
1433
- effectiveFromOpacity = hasOngoingTransition ? newOpacity : 0;
1434
- }
1435
-
1436
- debug("transition", "Cross-fade transition:", {
1437
- oldOpacity: `${oldOpacity} → 0`,
1438
- newOpacity: `${effectiveFromOpacity} → ${newNaturalOpacity}`,
1439
- isPhaseTransition,
1440
- });
1441
-
1442
- return [
1443
- createOpacityTransition(oldElement, 0, {
1444
- from: oldOpacity,
1445
- duration,
1446
- startProgress,
1447
- onUpdate: ({ value }) => {
1448
- if (value > 0) {
1449
- debug(
1450
- "transition_updates",
1451
- "Old content fade out:",
1452
- value.toFixed(3),
1453
- );
1454
- }
1455
- },
1456
- }),
1457
- createOpacityTransition(newElement, newNaturalOpacity, {
1458
- from: effectiveFromOpacity,
1459
- duration,
1460
- startProgress: isPhaseTransition ? 0 : startProgress, // Phase transitions: new content always starts fresh
1461
- onUpdate: ({ value, timing }) => {
1462
- debug("transition_updates", "New content fade in:", value.toFixed(3));
1463
- if (timing === "end") {
1464
- debug("transition", "Cross-fade complete");
1465
- }
1466
- },
1467
- }),
1468
- ];
1469
- },
1470
- };