@barqjs/aria 0.2.0-next.0 → 0.2.0-next.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 (78) hide show
  1. package/README.md +24 -13
  2. package/package.json +127 -37
  3. package/src/autocomplete.tsx +581 -0
  4. package/src/breadcrumbs.tsx +21 -20
  5. package/src/button.tsx +151 -25
  6. package/src/calendar.tsx +1019 -92
  7. package/src/checkbox.tsx +214 -52
  8. package/src/collections.ts +88 -5
  9. package/src/color.ts +1580 -23
  10. package/src/colorpicker.tsx +698 -153
  11. package/src/colorswatchpicker.tsx +240 -0
  12. package/src/combobox.tsx +635 -113
  13. package/src/command.tsx +78 -59
  14. package/src/date.ts +31 -9
  15. package/src/datefield.tsx +1451 -336
  16. package/src/datepicker.tsx +465 -114
  17. package/src/dialog.tsx +302 -115
  18. package/src/disclosure.tsx +81 -29
  19. package/src/dnd/clipboard.ts +125 -0
  20. package/src/dnd/collection.ts +1265 -0
  21. package/src/dnd/data.ts +409 -0
  22. package/src/dnd/drag-drop.ts +801 -0
  23. package/src/dnd/index.ts +133 -0
  24. package/src/dnd/manager.ts +639 -0
  25. package/src/dnd/strings.ts +1279 -0
  26. package/src/dnd/targets.ts +726 -0
  27. package/src/dnd/types.ts +212 -0
  28. package/src/dom.ts +3 -6
  29. package/src/drag-and-drop.tsx +669 -0
  30. package/src/dropzone.tsx +208 -0
  31. package/src/file-trigger.tsx +103 -0
  32. package/src/form.tsx +18 -18
  33. package/src/gridlist.tsx +912 -121
  34. package/src/group.tsx +146 -0
  35. package/src/index.ts +402 -0
  36. package/src/interactions/focus-events.ts +13 -5
  37. package/src/interactions/keyboard.ts +195 -2
  38. package/src/interactions/modality.ts +18 -6
  39. package/src/interactions/open-link.ts +46 -13
  40. package/src/interactions/press.ts +35 -18
  41. package/src/label.ts +18 -6
  42. package/src/link.tsx +146 -50
  43. package/src/listbox.tsx +615 -89
  44. package/src/live.ts +4 -0
  45. package/src/menu.tsx +182 -89
  46. package/src/menubar.tsx +21 -17
  47. package/src/navigation-tree.tsx +357 -0
  48. package/src/numberfield.tsx +164 -60
  49. package/src/overlay-arrow.tsx +157 -0
  50. package/src/overlays.ts +364 -62
  51. package/src/platform.ts +2 -1
  52. package/src/preview-trigger.tsx +582 -0
  53. package/src/progress-bar-context.ts +15 -0
  54. package/src/questionnaire.tsx +109 -104
  55. package/src/radio.tsx +101 -27
  56. package/src/select.tsx +225 -145
  57. package/src/selection-indicator.tsx +74 -0
  58. package/src/selection.ts +73 -16
  59. package/src/shared-element-transition.tsx +316 -0
  60. package/src/sheet.tsx +1461 -0
  61. package/src/slider.tsx +139 -44
  62. package/src/switch.tsx +47 -21
  63. package/src/table.tsx +0 -0
  64. package/src/tabs.tsx +198 -89
  65. package/src/tag.tsx +217 -32
  66. package/src/textarea.tsx +186 -0
  67. package/src/textfield.tsx +103 -37
  68. package/src/toast-components.tsx +589 -0
  69. package/src/toggle-button-group.tsx +175 -0
  70. package/src/toggle-input.tsx +38 -0
  71. package/src/toggle.ts +68 -5
  72. package/src/tokenfield.tsx +1673 -0
  73. package/src/toolbar.tsx +15 -10
  74. package/src/tooltip.tsx +46 -29
  75. package/src/tree.tsx +2075 -0
  76. package/src/utils.ts +30 -1
  77. package/src/validation.ts +79 -22
  78. package/src/virtualizer.tsx +186 -23
@@ -0,0 +1,74 @@
1
+ /**
2
+ * A selection indicator: the bar under the chosen tab, the pill behind the
3
+ * pressed segment, that slides to the new choice rather than blinking.
4
+ *
5
+ * Every item renders one, and only the selected item's is shown. It is a
6
+ * {@link SharedElement} named `SelectionIndicator`, so inside one
7
+ * {@link SharedElementTransition} the indicator leaving the old item and the
8
+ * one arriving at the new item are drawn as one element moving between them.
9
+ *
10
+ * Whether it is shown comes from the item it is in, which offers its selected
11
+ * state with {@link SelectionIndicatorProvider}, or from `isSelected` when the
12
+ * caller knows better.
13
+ */
14
+
15
+ import {
16
+ type Accessor,
17
+ type Child,
18
+ createContext,
19
+ getContext,
20
+ type Incoming,
21
+ omit,
22
+ provide,
23
+ } from "@barqjs/core";
24
+ import type { RefTarget } from "@barqjs/primitives/refs";
25
+ import { SharedElement } from "./shared-element-transition.tsx";
26
+ import type { StyleProps } from "./utils.ts";
27
+
28
+ export interface SelectionIndicatorValue {
29
+ isSelected: Accessor<boolean>;
30
+ }
31
+
32
+ const SelectionIndicatorContext = createContext<SelectionIndicatorValue | null>(null);
33
+
34
+ /** The enclosing item's selected state, if an item offered it. */
35
+ export function useSelectionIndicator(): SelectionIndicatorValue | null {
36
+ return getContext(SelectionIndicatorContext) ?? null;
37
+ }
38
+
39
+ export interface SelectionIndicatorProviderProps {
40
+ /** Whether the item the children are in is selected. */
41
+ isSelected: boolean;
42
+ children?: Child;
43
+ }
44
+
45
+ /**
46
+ * Offer an item's selected state to a {@link SelectionIndicator} among its
47
+ * children. An item component wraps its children in it.
48
+ */
49
+ export function SelectionIndicatorProvider(props: Incoming<SelectionIndicatorProviderProps>) {
50
+ const value: SelectionIndicatorValue = { isSelected: () => props.isSelected() };
51
+ return provide(
52
+ SelectionIndicatorContext,
53
+ () => value,
54
+ () => props.children as unknown,
55
+ );
56
+ }
57
+
58
+ export interface SelectionIndicatorComponentProps extends StyleProps {
59
+ /** @default the enclosing item's selected state */
60
+ isSelected?: boolean;
61
+ children?: Child;
62
+ ref?: RefTarget<HTMLDivElement>;
63
+ }
64
+
65
+ export function SelectionIndicator(props: SelectionIndicatorComponentProps) {
66
+ const item = useSelectionIndicator();
67
+ return (
68
+ <SharedElement
69
+ {...omit(props, "isSelected")}
70
+ name="SelectionIndicator"
71
+ isVisible={props.isSelected ?? item?.isSelected() ?? false}
72
+ />
73
+ );
74
+ }
package/src/selection.ts CHANGED
@@ -43,6 +43,7 @@ import type {
43
43
  } from "./collections.ts";
44
44
  import { focusableWalker } from "./focus.ts";
45
45
  import { collator, useLocale } from "./i18n.ts";
46
+ import { isOpeningLink } from "./interactions/flags.ts";
46
47
  import { focusSafely } from "./interactions/focusable.ts";
47
48
  import type { BaseEvent } from "./interactions/keyboard.ts";
48
49
  import { getInteractionModality, type PointerType } from "./interactions/modality.ts";
@@ -74,15 +75,29 @@ export function isCtrlKeyPressed(event: { ctrlKey?: boolean; metaKey?: boolean }
74
75
  /** The rendered element for a key, if it is rendered at all. */
75
76
  export function itemElement(container: Element | null | undefined, key: Key): Element | null {
76
77
  if (container === null || container === undefined) return null;
77
- let selector = `[data-key="${CSS.escape(String(key))}"]`;
78
- const collection = (container as HTMLElement).dataset?.collection;
78
+ const collection = container.getAttribute("data-collection");
79
79
  // Scoped to this collection, so a nested one — a tag group inside a table
80
- // cell — does not answer for its parent.
81
- if (collection !== undefined)
82
- selector = `[data-collection="${CSS.escape(collection)}"]${selector}`;
83
- return container.querySelector(selector);
80
+ // cell — does not answer for its parent: the nearest collection around the
81
+ // element has to be this one. An item may carry the collection's id itself.
82
+ for (const element of container.querySelectorAll(`[data-key="${CSS.escape(String(key))}"]`)) {
83
+ if (collection === null) return element;
84
+ const owner = element.closest("[data-collection]");
85
+ if (owner === container || owner?.getAttribute("data-collection") === collection)
86
+ return element;
87
+ }
88
+ return null;
84
89
  }
85
90
 
91
+ /**
92
+ * The id each collection writes as `data-collection`, by the selection
93
+ * manager accessor its items are handed too.
94
+ *
95
+ * The collection's hook runs in its component's body, before the items are
96
+ * built, so an item finds the id as it is set up. An item handed a different
97
+ * accessor finds nothing and goes without; `itemElement` still finds it.
98
+ */
99
+ const collectionIds = new WeakMap<Accessor<SelectionManager>, Accessor<string>>();
100
+
86
101
  // ---------------------------------------------------------------------------
87
102
  // Layout and keyboard delegates
88
103
  // ---------------------------------------------------------------------------
@@ -370,11 +385,13 @@ export class ListKeyboardDelegate implements KeyboardDelegate {
370
385
  return at ?? this.getLastKey();
371
386
  }
372
387
 
388
+ /** The first item after `fromKey` whose text starts with `search`, or from the top without one. */
373
389
  getKeyForSearch(search: string, fromKey?: Key | null): Key | null {
374
390
  const compare = this.#options.collator?.();
375
391
  if (compare === undefined) return null;
376
392
 
377
- let key = fromKey ?? this.getFirstKey();
393
+ let key =
394
+ fromKey === undefined || fromKey === null ? this.getFirstKey() : this.getNextKey(fromKey);
378
395
  while (key !== null) {
379
396
  const item = this.#collection.getItem(key);
380
397
  if (item === null) return null;
@@ -412,7 +429,11 @@ export interface TypeSelectResult {
412
429
  * the selection handler sees the key.
413
430
  */
414
431
  export function typeSelect(options: TypeSelectOptions): TypeSelectResult {
415
- const state = { search: "", timeout: undefined as ReturnType<typeof setTimeout> | undefined };
432
+ const state = {
433
+ search: "",
434
+ startKey: null as Key | null,
435
+ timeout: undefined as ReturnType<typeof setTimeout> | undefined,
436
+ };
416
437
 
417
438
  tryCleanup(() => clearTimeout(state.timeout));
418
439
 
@@ -420,14 +441,15 @@ export function typeSelect(options: TypeSelectOptions): TypeSelectResult {
420
441
  clearTimeout(state.timeout);
421
442
  state.timeout = setTimeout(() => {
422
443
  state.search = "";
444
+ state.startKey = null;
423
445
  }, TYPEAHEAD_TIMEOUT);
424
446
  };
425
447
 
426
448
  const jump = (): boolean => {
427
449
  const manager = options.selectionManager();
428
- // After the focused item first, so repeated letters cycle forwards rather
429
- // than always landing on the first match.
430
- let key = options.keyboardDelegate.getKeyForSearch?.(state.search, manager.focusedKey) ?? null;
450
+ // After the item that was focused when the search began, so a longer
451
+ // prefix can still land on the item a shorter one reached.
452
+ let key = options.keyboardDelegate.getKeyForSearch?.(state.search, state.startKey) ?? null;
431
453
  if (key === null) key = options.keyboardDelegate.getKeyForSearch?.(state.search) ?? null;
432
454
  if (key === null) return false;
433
455
 
@@ -451,7 +473,14 @@ export function typeSelect(options: TypeSelectOptions): TypeSelectResult {
451
473
  return;
452
474
  }
453
475
 
454
- state.search += character;
476
+ // The same letter again steps to the next item starting with it rather than
477
+ // searching for "bb", as a native select does.
478
+ if (state.search === "" || state.search === character) {
479
+ state.search = character;
480
+ state.startKey = options.selectionManager().focusedKey;
481
+ } else {
482
+ state.search += character;
483
+ }
455
484
 
456
485
  if (jump()) {
457
486
  event.preventDefault();
@@ -576,6 +605,7 @@ function isSelectionKey(key: string | undefined): boolean {
576
605
  */
577
606
  export function selectableItem(options: SelectableItemOptions): SelectableItemResult {
578
607
  const itemId = id(options.id);
608
+ const collectionId = collectionIds.get(options.selectionManager);
579
609
  const navigate = router();
580
610
 
581
611
  const manager = (): SelectionManager => options.selectionManager();
@@ -684,7 +714,9 @@ export function selectableItem(options: SelectableItemOptions): SelectableItemRe
684
714
  (focused) => {
685
715
  if (focused === null) return;
686
716
  const { element } = focused;
687
- if (element !== null && activeElement(ownerDocument(element)) !== element) {
717
+ // Focus already inside the item, on a field or a button in the row, is
718
+ // where the user put it.
719
+ if (element !== null && !contains(element, activeElement(ownerDocument(element)))) {
688
720
  focusSafely(element);
689
721
  }
690
722
  },
@@ -847,15 +879,39 @@ export function selectableItem(options: SelectableItemOptions): SelectableItemRe
847
879
  if (modality === "touch" && longPressWasEnabled) event.preventDefault();
848
880
  };
849
881
 
850
- // A link's navigation is ours to time, so the browser's is cancelled.
882
+ // A link's navigation is ours to time, so the browser's is cancelled. The
883
+ // click the router dispatches to open it bubbles through here too, and that
884
+ // one is let through.
851
885
  const onClick = (event: MouseEvent): void => {
852
886
  if (linkBehavior() === "none" || !manager().isLink(options.key)) return;
853
- event.preventDefault();
887
+ if (!isOpeningLink()) event.preventDefault();
888
+ };
889
+
890
+ const linkData = (name: string): (() => unknown) => {
891
+ return () => {
892
+ if (linkBehavior() === "none") return undefined;
893
+ const props = manager().getItemProps(options.key);
894
+ if (props?.href === undefined) return undefined;
895
+ if (name === "href") return navigate.href(props.href as string);
896
+ return props[name];
897
+ };
854
898
  };
855
899
 
856
900
  const itemProps = mergeProps(
857
901
  focusProps,
858
- { "data-key": String(options.key), id: itemId },
902
+ {
903
+ "data-key": String(options.key),
904
+ "data-collection": collectionId,
905
+ id: itemId,
906
+ // The native router opens a link by reading these off the element it is
907
+ // handed, so an item that is not an anchor carries them itself.
908
+ "data-href": linkData("href"),
909
+ "data-target": linkData("target"),
910
+ "data-rel": linkData("rel"),
911
+ "data-download": linkData("download"),
912
+ "data-ping": linkData("ping"),
913
+ "data-referrer-policy": linkData("referrerPolicy"),
914
+ },
859
915
  pressProps,
860
916
  longPressProps,
861
917
  { onDoubleClick, onDragStartCapture, onClick },
@@ -954,6 +1010,7 @@ export function selectableCollection(
954
1010
  const navigate = router();
955
1011
  const delegate = options.keyboardDelegate;
956
1012
  const collectionId = id();
1013
+ collectionIds.set(options.selectionManager, collectionId);
957
1014
 
958
1015
  const manager = (): SelectionManager => options.selectionManager();
959
1016
  const virtualFocus = (): boolean => access(options.shouldUseVirtualFocus) === true;
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Shared elements: one element that appears to move from one parent to another.
3
+ *
4
+ * A selection indicator under the chosen tab is the case. Every tab renders
5
+ * its own indicator and only the selected one is shown; when the selection
6
+ * moves, the old indicator goes and a new one appears somewhere else. Drawn as
7
+ * that, it blinks. Drawn as one bar sliding across, it reads as the selection
8
+ * moving, which is what happened.
9
+ *
10
+ * The technique is FLIP. When a shared element leaves, its box and the current
11
+ * value of every property it transitions are recorded under its name. When one
12
+ * of the same name arrives, it is put where the old one was, with the old
13
+ * values, for one frame, and then let go: the stylesheet's own transitions
14
+ * carry it to where it now belongs. Nothing here animates anything, so the
15
+ * motion, its duration and `prefers-reduced-motion` all stay the stylesheet's.
16
+ *
17
+ * An element with nothing to continue from ENTERS: `data-entering` for one
18
+ * frame. One that leaves with nothing to take over from it EXITS:
19
+ * `data-exiting`, held until its exit transition has finished.
20
+ */
21
+
22
+ import {
23
+ cells,
24
+ type Accessor,
25
+ type Child,
26
+ createContext,
27
+ createEffect,
28
+ createRenderEffect,
29
+ createSignal,
30
+ getContext,
31
+ type Incoming,
32
+ onCleanup,
33
+ provide,
34
+ Show,
35
+ untrack,
36
+ } from "@barqjs/core";
37
+ import { isServer } from "@barqjs/web";
38
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
39
+ import { exitDuration } from "./presence.ts";
40
+ import {
41
+ access,
42
+ type DOMProps,
43
+ filterDOMProps,
44
+ fromProps,
45
+ type MaybeAccessor,
46
+ mergeProps,
47
+ type StyleProps,
48
+ styleProps,
49
+ } from "./utils.ts";
50
+
51
+ interface Snapshot {
52
+ rect: DOMRect;
53
+ style: [property: string, value: string][];
54
+ /** The element it was taken from. */
55
+ source: HTMLElement;
56
+ }
57
+
58
+ interface LiveElement {
59
+ name: Accessor<string>;
60
+ element: Accessor<HTMLElement | null>;
61
+ isVisible: Accessor<boolean>;
62
+ }
63
+
64
+ /** What a {@link SharedElementTransition} holds for the shared elements inside it. */
65
+ export interface SharedElementScope {
66
+ /** The boxes of elements that have left, by name, until one of the same name arrives. */
67
+ snapshots: Map<string, Snapshot>;
68
+ /** Every shared element currently mounted in the scope. */
69
+ live: Set<LiveElement>;
70
+ }
71
+
72
+ const SharedElementContext = createContext<SharedElementScope | null>(null);
73
+
74
+ export interface SharedElementTransitionComponentProps {
75
+ children?: Child;
76
+ }
77
+
78
+ /**
79
+ * The scope a shared element's name is unique in.
80
+ *
81
+ * ```tsx
82
+ * <SharedElementTransition>
83
+ * <For each={tabs()}>{(tab) => <Tab>{tab.name}<Show when={selected() === tab.id}><SharedElement name="underline" /></Show></Tab>}</For>
84
+ * </SharedElementTransition>
85
+ * ```
86
+ */
87
+ export function SharedElementTransition(props: Incoming<SharedElementTransitionComponentProps>) {
88
+ const scope: SharedElementScope = { snapshots: new Map(), live: new Set() };
89
+ return provide(
90
+ SharedElementContext,
91
+ () => scope,
92
+ () => props.children as unknown,
93
+ );
94
+ }
95
+
96
+ export type SharedElementPhase = "visible" | "hidden" | "entering" | "exiting";
97
+
98
+ export interface SharedElementOptions {
99
+ name: MaybeAccessor<string>;
100
+ /** @default true */
101
+ isVisible?: MaybeAccessor<boolean | undefined>;
102
+ ref: Accessor<HTMLElement | null>;
103
+ }
104
+
105
+ export interface SharedElementResult {
106
+ /** Whether the element belongs in the document: shown, or still leaving. */
107
+ isRendered: Accessor<boolean>;
108
+ phase: Accessor<SharedElementPhase>;
109
+ elementProps: DOMProps;
110
+ }
111
+
112
+ type StyleRecord = Record<string, string>;
113
+
114
+ function animationsOf(element: HTMLElement): Animation[] {
115
+ const source = element as HTMLElement & { getAnimations?: () => Animation[] };
116
+ return typeof source.getAnimations === "function" ? source.getAnimations() : [];
117
+ }
118
+
119
+ function snapshotOf(element: HTMLElement): Snapshot | null {
120
+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);
121
+ if (style === undefined) return null;
122
+ const transitioned = style.transitionProperty.trim();
123
+ if (transitioned === "" || transitioned === "none") return null;
124
+ const values = style as unknown as StyleRecord;
125
+ return {
126
+ rect: element.getBoundingClientRect(),
127
+ style: transitioned.split(/\s*,\s*/).map((property) => [property, values[property] ?? ""]),
128
+ source: element,
129
+ };
130
+ }
131
+
132
+ export function sharedElement(
133
+ options: SharedElementOptions,
134
+ scope: SharedElementScope,
135
+ ): SharedElementResult {
136
+ const name = (): string => access(options.name);
137
+ const isVisible = (): boolean => access(options.isVisible) !== false;
138
+ const [phase, setPhase] = createSignal<SharedElementPhase>(
139
+ untrack(isVisible) ? "visible" : "hidden",
140
+ { ownedWrite: true },
141
+ );
142
+ const self: LiveElement = { name, element: options.ref, isVisible };
143
+
144
+ const record = (element: HTMLElement | null): void => {
145
+ if (element === null || !element.isConnected || element.hasAttribute("data-exiting")) return;
146
+ const snapshot = snapshotOf(element);
147
+ if (snapshot !== null) scope.snapshots.set(untrack(name), snapshot);
148
+ };
149
+
150
+ /** Whether the element a snapshot came from is still mounted and still shown. */
151
+ const stays = (source: HTMLElement): boolean => {
152
+ for (const other of scope.live) {
153
+ if (other !== self && untrack(other.element) === source) return untrack(other.isVisible);
154
+ }
155
+ return false;
156
+ };
157
+
158
+ if (!isServer) {
159
+ // An element whose PARENT unmounts it is gone from the document by the
160
+ // time its own cleanup runs, too late to measure. One arriving in the same
161
+ // flush is built while the other is still in place, so it measures it.
162
+ if (untrack(isVisible) && !scope.snapshots.has(untrack(name))) {
163
+ for (const other of scope.live) {
164
+ if (untrack(other.name) !== untrack(name)) continue;
165
+ const element = untrack(other.element);
166
+ if (element !== null && element.isConnected) {
167
+ record(element);
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ scope.live.add(self);
173
+ onCleanup(() => scope.live.delete(self));
174
+
175
+ // In the render phase, so the leaving element's box is on record before
176
+ // any arriving one, built in the same flush, looks for it.
177
+ createRenderEffect(isVisible, (visible, previous) => {
178
+ if (previous === true && !visible) record(untrack(options.ref));
179
+ });
180
+
181
+ createEffect(
182
+ () => ({ visible: isVisible(), element: options.ref(), key: name() }),
183
+ ({ visible, element, key }) => {
184
+ if (element === null) return undefined;
185
+ let frame: number | null = null;
186
+ let timer: ReturnType<typeof setTimeout> | null = null;
187
+ let cancelled = false;
188
+
189
+ let previous = scope.snapshots.get(key);
190
+ if (visible && previous !== undefined) {
191
+ scope.snapshots.delete(key);
192
+ // Taken from one that has not left after all: two of one name shown
193
+ // at once, which is nothing to move between.
194
+ if (stays(previous.source)) previous = undefined;
195
+ }
196
+
197
+ if (visible && previous !== undefined) {
198
+ const from = previous;
199
+ setPhase("visible");
200
+ const running = animationsOf(element);
201
+ const inline = element.style as unknown as StyleRecord;
202
+ const restore = from.style.map(([property, value]): [string, string] => {
203
+ const current = inline[property] ?? "";
204
+ if (property === "translate") {
205
+ const now = element.getBoundingClientRect();
206
+ element.style.setProperty(
207
+ "translate",
208
+ `${from.rect.left - now.left}px ${from.rect.top - now.top}px`,
209
+ );
210
+ } else {
211
+ inline[property] = value;
212
+ }
213
+ return [property, current];
214
+ });
215
+ // Moving it back to the old values must not itself animate: only the
216
+ // release next frame should.
217
+ for (const animation of animationsOf(element)) {
218
+ if (!running.includes(animation)) animation.cancel();
219
+ }
220
+ frame = requestAnimationFrame(() => {
221
+ frame = null;
222
+ for (const [property, value] of restore) inline[property] = value;
223
+ });
224
+ } else if (visible) {
225
+ queueMicrotask(() => {
226
+ if (!cancelled) setPhase("entering");
227
+ });
228
+ frame = requestAnimationFrame(() => {
229
+ frame = null;
230
+ setPhase("visible");
231
+ });
232
+ } else {
233
+ // A microtask later, once any element arriving in the same flush has
234
+ // had its chance to take the snapshot over.
235
+ queueMicrotask(() => {
236
+ if (cancelled) return;
237
+ if (!scope.snapshots.has(key)) {
238
+ setPhase("hidden");
239
+ return;
240
+ }
241
+ scope.snapshots.delete(key);
242
+ element.setAttribute("data-exiting", "");
243
+ setPhase("exiting");
244
+ const duration = exitDuration(element);
245
+ if (duration <= 0) {
246
+ setPhase("hidden");
247
+ return;
248
+ }
249
+ timer = setTimeout(() => {
250
+ timer = null;
251
+ setPhase("hidden");
252
+ }, duration);
253
+ });
254
+ }
255
+
256
+ return () => {
257
+ cancelled = true;
258
+ if (frame !== null) cancelAnimationFrame(frame);
259
+ if (timer !== null) clearTimeout(timer);
260
+ };
261
+ },
262
+ );
263
+ }
264
+
265
+ return {
266
+ phase,
267
+ isRendered: () => isVisible() || phase() !== "hidden",
268
+ elementProps: {
269
+ "data-entering": () => phase() === "entering",
270
+ "data-exiting": () => phase() === "exiting",
271
+ },
272
+ };
273
+ }
274
+
275
+ /** The enclosing {@link SharedElementTransition}'s scope. */
276
+ export function useSharedElementScope(): SharedElementScope {
277
+ const scope = getContext(SharedElementContext);
278
+ if (scope === null || scope === undefined) {
279
+ throw new Error("A SharedElement must be rendered inside a SharedElementTransition.");
280
+ }
281
+ return scope;
282
+ }
283
+
284
+ export interface SharedElementComponentProps extends StyleProps {
285
+ /** Elements of one name, in one scope, are one element moving. */
286
+ name: string;
287
+ /** @default true */
288
+ isVisible?: boolean;
289
+ children?: Child;
290
+ ref?: RefTarget<HTMLDivElement>;
291
+ }
292
+
293
+ /** An element that moves, rather than reappears, when it changes parent. */
294
+ export function SharedElement(props: SharedElementComponentProps) {
295
+ const scope = useSharedElementScope();
296
+ const domRef = makeRef<HTMLDivElement>();
297
+ const { isRendered, elementProps } = sharedElement(
298
+ { name: () => props.name, isVisible: () => props.isVisible, ref: domRef },
299
+ scope,
300
+ );
301
+
302
+ const forwarded = mergeProps(
303
+ filterDOMProps(fromProps(cells(props)), { global: true, labelable: true }),
304
+ styleProps(cells(props)),
305
+ elementProps,
306
+ { "data-testid": () => props["data-testid"] },
307
+ );
308
+
309
+ return (
310
+ <Show when={isRendered()}>
311
+ <div {...forwarded} ref={mergeRefs(domRef.set, props.ref)}>
312
+ {props.children}
313
+ </div>
314
+ </Show>
315
+ );
316
+ }