@jsenv/dom 0.1.0

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