@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
@@ -21,14 +21,15 @@
21
21
  */
22
22
 
23
23
  import {
24
+ cells,
24
25
  type Accessor,
25
26
  type Child,
27
+ flush,
26
28
  createMemo,
27
29
  createContext,
28
30
  createEffect,
29
31
  getContext,
30
32
  getOwner,
31
- type Incoming,
32
33
  install,
33
34
  createSignal,
34
35
  } from "@barqjs/core";
@@ -172,11 +173,14 @@ export function numberFieldState(options: NumberFieldStateOptions): NumberFieldS
172
173
  if (!isServer) {
173
174
  // The number changing from OUTSIDE reformats the field. A change the field
174
175
  // made itself is already in it, as typed.
175
- createEffect(numberValue, (value) => {
176
- if (value === live) return;
177
- live = value;
178
- writeInputValue(asText(value));
179
- });
176
+ createEffect(
177
+ () => [numberValue(), asText(numberValue())] as const,
178
+ ([value, text]) => {
179
+ if (value === live) return;
180
+ live = value;
181
+ writeInputValue(text);
182
+ },
183
+ );
180
184
  }
181
185
 
182
186
  const parsed = createMemo(() => parser().parse(inputValue()));
@@ -324,7 +328,7 @@ const REPEAT_INTERVAL = 60;
324
328
  */
325
329
  export function spinButton(options: SpinButtonOptions): SpinButtonResult {
326
330
  let timer: ReturnType<typeof setTimeout> | undefined;
327
- let announced = false;
331
+ let focused = false;
328
332
 
329
333
  const stop = (): void => {
330
334
  if (timer !== undefined) clearTimeout(timer);
@@ -392,24 +396,30 @@ export function spinButton(options: SpinButtonOptions): SpinButtonResult {
392
396
  if (!isServer) {
393
397
  // Announced assertively, because the input carries no spin button role to
394
398
  // announce it for us. `clearAnnouncer` first, so holding a stepper does
395
- // not queue up thirty values to read out in turn.
399
+ // not queue up thirty values to read out in turn. Only while the field or
400
+ // one of its steppers has focus: a value set from elsewhere on the page
401
+ // is not something the user is doing, and interrupts whatever they are.
396
402
  createEffect(
397
403
  () => [access(options.textValue), access(options.value)] as const,
398
404
  ([textValue, value]) => {
405
+ if (!focused) return;
399
406
  const text = textValue ?? String(value ?? "");
400
407
  // A hyphen-minus between a currency symbol and a number is read as a
401
408
  // hyphen and swallowed; the real minus sign is announced.
402
409
  const spoken = text === "" ? "Empty" : text.replace("-", "−");
403
- if (!announced) {
404
- announced = true;
405
- return;
406
- }
407
410
  clearAnnouncer("assertive");
408
411
  announce(spoken, "assertive");
409
412
  },
410
413
  );
411
414
  }
412
415
 
416
+ const onFocus = (): void => {
417
+ focused = true;
418
+ };
419
+ const onBlur = (): void => {
420
+ focused = false;
421
+ };
422
+
413
423
  /**
414
424
  * One step now, then a repeat while it is held.
415
425
  *
@@ -422,14 +432,21 @@ export function spinButton(options: SpinButtonOptions): SpinButtonResult {
422
432
  guard: () => boolean,
423
433
  ): {
424
434
  onPressStart: (event: { pointerType: string }) => void;
435
+ onPressUp: (event: { pointerType: string }) => void;
425
436
  onPressEnd: (event: { pointerType: string }) => void;
437
+ onFocus: () => void;
438
+ onBlur: () => void;
426
439
  } => {
427
440
  let held = false;
428
441
  let spun = false;
442
+ // A touch that ends without lifting the finger over the button (it moved
443
+ // off to scroll, and the browser cancelled the pointer) is not a press.
444
+ let lifted = false;
429
445
  return {
430
446
  onPressStart: (event) => {
431
447
  stop();
432
448
  spun = false;
449
+ lifted = false;
433
450
  held = event.pointerType === "touch";
434
451
  if (!enabled()) return;
435
452
  if (!held) act();
@@ -442,16 +459,22 @@ export function spinButton(options: SpinButtonOptions): SpinButtonResult {
442
459
  REPEAT_DELAY,
443
460
  );
444
461
  },
462
+ onPressUp: () => {
463
+ lifted = true;
464
+ },
445
465
  onPressEnd: () => {
446
466
  stop();
447
- if (held && !spun && enabled()) act();
467
+ if (held && lifted && !spun && enabled()) act();
448
468
  held = false;
469
+ lifted = false;
449
470
  },
471
+ onFocus,
472
+ onBlur,
450
473
  };
451
474
  };
452
475
 
453
476
  return {
454
- spinButtonProps: { onKeyDown },
477
+ spinButtonProps: { onKeyDown, onFocus, onBlur },
455
478
  incrementButtonProps: stepper(() => options.onIncrement?.(), belowMax),
456
479
  decrementButtonProps: stepper(() => options.onDecrement?.(), aboveMin),
457
480
  };
@@ -476,6 +499,15 @@ export interface NumberFieldOptions extends Omit<
476
499
  formatOptions?: MaybeAccessor<Intl.NumberFormatOptions | undefined>;
477
500
  minValue?: MaybeAccessor<number | undefined>;
478
501
  maxValue?: MaybeAccessor<number | undefined>;
502
+ step?: MaybeAccessor<number | undefined>;
503
+ /**
504
+ * What the state does with a value off the range or the step. Under
505
+ * `"validate"` it is kept, and this marks the field invalid with the
506
+ * browser's own message for it.
507
+ *
508
+ * @default "snap"
509
+ */
510
+ commitBehavior?: MaybeAccessor<"snap" | "validate" | undefined>;
479
511
  /** Stop the scroll wheel changing the value. @default false */
480
512
  isWheelDisabled?: MaybeAccessor<boolean | undefined>;
481
513
  incrementAriaLabel?: MaybeAccessor<string | undefined>;
@@ -560,6 +592,30 @@ export function numberField(
560
592
  return "numeric";
561
593
  };
562
594
 
595
+ /**
596
+ * What the browser would say about this number, when the state kept it off
597
+ * the range or the step rather than snapping it.
598
+ *
599
+ * Asked of an `<input type="number">` that is never attached, so the
600
+ * message is the browser's, in the browser's language. With no `step` any
601
+ * value is on it: a field with decimals and no step holds 1.5 when snapping,
602
+ * and must not call it invalid when validating.
603
+ */
604
+ const outOfRange = (value: number): string[] => {
605
+ if (isServer || access(options.commitBehavior) !== "validate" || Number.isNaN(value)) {
606
+ return [];
607
+ }
608
+ const probe = rangeProbe();
609
+ const min = access(options.minValue);
610
+ const max = access(options.maxValue);
611
+ const size = access(options.step);
612
+ probe.min = min === undefined || Number.isNaN(min) ? "" : String(min);
613
+ probe.max = max === undefined || Number.isNaN(max) ? "" : String(max);
614
+ probe.step = size === undefined || Number.isNaN(size) ? "any" : String(size);
615
+ probe.value = String(value);
616
+ return probe.validity.valid ? [] : [probe.validationMessage];
617
+ };
618
+
563
619
  const {
564
620
  labelProps,
565
621
  inputProps: fieldProps,
@@ -576,9 +632,17 @@ export function numberField(
576
632
  // The caller validates the NUMBER; `textField` validates a string, so
577
633
  // the typed text is ignored and the parsed value is handed over instead.
578
634
  validate:
579
- options.validate === undefined
635
+ options.validate === undefined && options.commitBehavior === undefined
580
636
  ? undefined
581
- : () => (options.validate as ValidateFunction<number>)(state.numberValue()),
637
+ : () => {
638
+ const value = state.numberValue();
639
+ const own = options.validate?.(value);
640
+ const found = [
641
+ ...(own === true || own === null || own === undefined ? [] : [own].flat()),
642
+ ...outOfRange(value),
643
+ ];
644
+ return found.length === 0 ? null : found;
645
+ },
582
646
  value: state.inputValue,
583
647
  // Rejected keystrokes never reach the state, so a field that cannot hold
584
648
  // a letter never shows one.
@@ -592,16 +656,19 @@ export function numberField(
592
656
 
593
657
  formReset(options.inputRef, state.defaultNumberValue, (value) => state.setNumberValue(value));
594
658
 
595
- const onBlur = (): void => {
596
- state.commit();
597
- validation.commitValidation();
598
- };
659
+ // What the validation is told is left to the text field, which commits it
660
+ // only for an edit: tabbing through must not clear a server's error.
661
+ const onBlur = (): void => state.commit();
599
662
 
600
663
  const onKeyDown = (event: KeyboardEvent): void => {
601
- if (event.key !== "Enter") return;
664
+ if (event.key !== "Enter" || isDisabled() || isReadOnly()) return;
602
665
  // Not prevented: a number field inside a form still submits it, with the
603
- // committed value rather than the typed one.
666
+ // committed value rather than the typed one. The submit reads the form
667
+ // as soon as this handler returns, so the commit is applied now rather
668
+ // than at the next flush.
604
669
  state.commit();
670
+ flush();
671
+ validation.commitValidation();
605
672
  };
606
673
 
607
674
  const onPaste = (event: ClipboardEvent): void => {
@@ -638,6 +705,10 @@ export function numberField(
638
705
  "aria-disabled": () => isDisabled() || undefined,
639
706
  }),
640
707
  inputProps: mergeProps(spinButtonProps, fieldProps, {
708
+ // The typed text is not the value. A form gets the number from a hidden
709
+ // input of its own; the name stays on the options for server errors.
710
+ name: () => undefined,
711
+ form: () => undefined,
641
712
  onKeyDown,
642
713
  onBlur,
643
714
  onPaste,
@@ -667,6 +738,16 @@ export function numberField(
667
738
  };
668
739
  }
669
740
 
741
+ let probeInput: HTMLInputElement | null = null;
742
+
743
+ function rangeProbe(): HTMLInputElement {
744
+ if (probeInput === null) {
745
+ probeInput = document.createElement("input");
746
+ probeInput.type = "number";
747
+ }
748
+ return probeInput;
749
+ }
750
+
670
751
  // ---------------------------------------------------------------------------
671
752
  // Components
672
753
  // ---------------------------------------------------------------------------
@@ -695,6 +776,13 @@ export interface NumberFieldComponentProps extends StyleProps {
695
776
  maxValue?: number;
696
777
  step?: number;
697
778
  formatOptions?: Intl.NumberFormatOptions;
779
+ /**
780
+ * Whether committing snaps to the range and the step, or leaves the value
781
+ * as typed and marks it invalid.
782
+ *
783
+ * @default "snap"
784
+ */
785
+ commitBehavior?: "snap" | "validate";
698
786
  placeholder?: string;
699
787
  isDisabled?: boolean;
700
788
  isReadOnly?: boolean;
@@ -722,21 +810,22 @@ export interface NumberFieldComponentProps extends StyleProps {
722
810
  * <NumberField label="Price" formatOptions={{ style: "currency", currency: "GBP" }} />
723
811
  * ```
724
812
  */
725
- export function NumberField(props: Incoming<NumberFieldComponentProps>) {
813
+ export function NumberField(props: NumberFieldComponentProps) {
726
814
  const inputRef = makeRef<HTMLInputElement>();
727
815
  const incrementRef = makeRef<HTMLButtonElement>();
728
816
  const decrementRef = makeRef<HTMLButtonElement>();
729
817
 
730
818
  const state = numberFieldState({
731
- value: () => props.value?.(),
732
- defaultValue: () => props.defaultValue?.(),
733
- minValue: () => props.minValue?.(),
734
- maxValue: () => props.maxValue?.(),
735
- step: () => props.step?.(),
736
- formatOptions: () => props.formatOptions?.(),
737
- isDisabled: () => props.isDisabled?.(),
738
- isReadOnly: () => props.isReadOnly?.(),
739
- onChange: (value) => props.onChange?.()?.(value),
819
+ value: () => props.value,
820
+ defaultValue: () => props.defaultValue,
821
+ minValue: () => props.minValue,
822
+ maxValue: () => props.maxValue,
823
+ step: () => props.step,
824
+ formatOptions: () => props.formatOptions,
825
+ commitBehavior: () => props.commitBehavior,
826
+ isDisabled: () => props.isDisabled,
827
+ isReadOnly: () => props.isReadOnly,
828
+ onChange: (value) => props.onChange?.(value),
740
829
  });
741
830
 
742
831
  const {
@@ -752,25 +841,29 @@ export function NumberField(props: Incoming<NumberFieldComponentProps>) {
752
841
  } = numberField(
753
842
  {
754
843
  inputRef,
755
- label: () => props.label?.(),
756
- name: () => props.name?.(),
757
- form: () => props.form?.(),
758
- validate: callback<[number], string | string[] | true | null | undefined>(props.validate),
759
- validationBehavior: () => props.validationBehavior?.(),
760
- minValue: () => props.minValue?.(),
761
- maxValue: () => props.maxValue?.(),
762
- formatOptions: () => props.formatOptions?.(),
763
- placeholder: () => props.placeholder?.(),
764
- isDisabled: () => props.isDisabled?.(),
765
- isReadOnly: () => props.isReadOnly?.(),
766
- isRequired: () => props.isRequired?.(),
767
- isInvalid: () => props.isInvalid?.(),
768
- isWheelDisabled: () => props.isWheelDisabled?.(),
769
- autoFocus: () => props.autoFocus?.(),
770
- incrementAriaLabel: () => props.incrementAriaLabel?.(),
771
- decrementAriaLabel: () => props.decrementAriaLabel?.(),
772
- "aria-label": () => props["aria-label"]?.(),
773
- "aria-labelledby": () => props["aria-labelledby"]?.(),
844
+ label: () => props.label,
845
+ name: () => props.name,
846
+ form: () => props.form,
847
+ validate: callback<[number], string | string[] | true | null | undefined>(
848
+ cells(props).validate,
849
+ ),
850
+ validationBehavior: () => props.validationBehavior,
851
+ minValue: () => props.minValue,
852
+ maxValue: () => props.maxValue,
853
+ step: () => props.step,
854
+ commitBehavior: () => props.commitBehavior,
855
+ formatOptions: () => props.formatOptions,
856
+ placeholder: () => props.placeholder,
857
+ isDisabled: () => props.isDisabled,
858
+ isReadOnly: () => props.isReadOnly,
859
+ isRequired: () => props.isRequired,
860
+ isInvalid: () => props.isInvalid,
861
+ isWheelDisabled: () => props.isWheelDisabled,
862
+ autoFocus: () => props.autoFocus,
863
+ incrementAriaLabel: () => props.incrementAriaLabel,
864
+ decrementAriaLabel: () => props.decrementAriaLabel,
865
+ "aria-label": () => props["aria-label"],
866
+ "aria-labelledby": () => props["aria-labelledby"],
774
867
  },
775
868
  state,
776
869
  );
@@ -778,7 +871,7 @@ export function NumberField(props: Incoming<NumberFieldComponentProps>) {
778
871
  const increment = button(incrementButtonProps, incrementRef);
779
872
  const decrement = button(decrementButtonProps, decrementRef);
780
873
  const { focusProps, isFocusVisible } = focusRing();
781
- const { hoverProps, isHovered } = hover({ isDisabled: () => props.isDisabled?.() });
874
+ const { hoverProps, isHovered } = hover({ isDisabled: () => props.isDisabled });
782
875
 
783
876
  const owner = getOwner();
784
877
  if (owner !== null) install(owner, NumberFieldContext, () => ({ state }));
@@ -786,19 +879,19 @@ export function NumberField(props: Incoming<NumberFieldComponentProps>) {
786
879
  const elementProps = mergeProps(
787
880
  groupProps,
788
881
  hoverProps,
789
- filterDOMProps(fromProps(props), { global: true }),
790
- styleProps(props),
882
+ filterDOMProps(fromProps(cells(props)), { global: true }),
883
+ styleProps(cells(props)),
791
884
  {
792
885
  "data-hovered": isHovered,
793
- "data-disabled": () => props.isDisabled?.() === true,
886
+ "data-disabled": () => props.isDisabled === true,
887
+ "data-readonly": () => props.isReadOnly === true,
888
+ "data-required": () => props.isRequired === true,
794
889
  "data-invalid": isInvalid,
795
- "data-testid": () => props["data-testid"]?.(),
890
+ "data-testid": () => props["data-testid"],
796
891
  },
797
892
  );
798
893
 
799
894
  const inputElementProps = mergeProps(inputProps, focusProps, {
800
- name: () => props.name?.(),
801
- form: () => props.form?.(),
802
895
  "data-focus-visible": isFocusVisible,
803
896
  });
804
897
 
@@ -814,7 +907,18 @@ export function NumberField(props: Incoming<NumberFieldComponentProps>) {
814
907
  >
815
908
  <span aria-hidden="true">−</span>
816
909
  </button>
817
- <input {...inputElementProps} ref={mergeRefs(inputRef.set, props.ref?.())} />
910
+ <input {...inputElementProps} ref={mergeRefs(inputRef.set, props.ref)} />
911
+ {() =>
912
+ props.name === undefined ? null : (
913
+ <input
914
+ type="hidden"
915
+ name={props.name}
916
+ form={props.form}
917
+ value={Number.isNaN(state.numberValue()) ? "" : String(state.numberValue())}
918
+ disabled={props.isDisabled === true}
919
+ />
920
+ )
921
+ }
818
922
  <button
819
923
  {...increment.buttonProps}
820
924
  type="button"
@@ -827,7 +931,7 @@ export function NumberField(props: Incoming<NumberFieldComponentProps>) {
827
931
  <span {...descriptionProps}>{props.description}</span>
828
932
  <span {...errorMessageProps}>
829
933
  {() => {
830
- const given = props.errorMessage?.();
934
+ const given = props.errorMessage;
831
935
  if (given !== undefined && given !== null && given !== "") return given;
832
936
  const found = errors();
833
937
  return found.length === 0 ? null : found.join(" ");
@@ -0,0 +1,157 @@
1
+ /**
2
+ * The arrow on a popover or a tooltip, pointing at the trigger.
3
+ *
4
+ * Its shape is the caller's (an SVG, a rotated square); what is here is where
5
+ * it goes. It sits outside the overlay's edge on the side facing the trigger,
6
+ * which is the side the overlay ended up on after any flip and not the one it
7
+ * asked for, and along that edge it lines up with the trigger's centre.
8
+ *
9
+ * Both come from the overlay. The side is its placement; the position along
10
+ * the edge is `overlayPosition`'s `arrowProps`, measured once the overlay has
11
+ * been shifted to fit the viewport, since after a shift the overlay's middle
12
+ * is no longer the trigger's. An overlay that offers only its side gets an
13
+ * arrow centred on its own edge.
14
+ *
15
+ * `data-placement` names the side, so a stylesheet can turn the shape to face
16
+ * the trigger.
17
+ */
18
+
19
+ import {
20
+ cells,
21
+ type Accessor,
22
+ type Child,
23
+ createContext,
24
+ getContext,
25
+ type Incoming,
26
+ provide,
27
+ } from "@barqjs/core";
28
+ import { mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
29
+ import type { Axis } from "./overlays.ts";
30
+ import {
31
+ access,
32
+ type DOMProps,
33
+ filterDOMProps,
34
+ fromProps,
35
+ type MaybeAccessor,
36
+ mergeProps,
37
+ type StyleProps,
38
+ } from "./utils.ts";
39
+
40
+ export interface OverlayArrowValue {
41
+ /** The side of the trigger the overlay is on, after any flip. */
42
+ placement: Accessor<Axis | null>;
43
+ /** `overlayPosition`'s `arrowProps`: the measured offset along the edge. */
44
+ arrowProps?: DOMProps;
45
+ /** Where the arrow's element goes, for the overlay to measure it. */
46
+ ref?: (element: Element | null) => void;
47
+ }
48
+
49
+ const OverlayArrowContext = createContext<OverlayArrowValue | null>(null);
50
+
51
+ export interface OverlayArrowProviderProps {
52
+ value: OverlayArrowValue;
53
+ children?: Child;
54
+ }
55
+
56
+ /** Offer an overlay's placement and arrow position to an {@link OverlayArrow} inside it. */
57
+ export function OverlayArrowProvider(props: Incoming<OverlayArrowProviderProps>) {
58
+ return provide(
59
+ OverlayArrowContext,
60
+ () => props.value(),
61
+ () => props.children as unknown,
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Where the enclosing overlay is, as its {@link OverlayArrowProvider} says. A
67
+ * `<Popover>` and a `<Tooltip>` each provide one.
68
+ */
69
+ export function useOverlayArrow(): OverlayArrowValue | null {
70
+ return getContext(OverlayArrowContext) ?? null;
71
+ }
72
+
73
+ type CrossOffset = Partial<Record<"left" | "top", string>>;
74
+
75
+ export interface OverlayArrowOptions {
76
+ placement: MaybeAccessor<Axis | null>;
77
+ arrowProps?: DOMProps;
78
+ }
79
+
80
+ export interface OverlayArrowResult {
81
+ arrowProps: DOMProps;
82
+ placement: Accessor<Axis | null>;
83
+ }
84
+
85
+ export function overlayArrow(options: OverlayArrowOptions): OverlayArrowResult {
86
+ const placement = (): Axis | null => access(options.placement);
87
+ const measured = (): CrossOffset => {
88
+ const style = access(options.arrowProps?.style as MaybeAccessor<CrossOffset | undefined>);
89
+ return style ?? {};
90
+ };
91
+
92
+ return {
93
+ placement,
94
+ arrowProps: {
95
+ "data-placement": placement,
96
+ style: () => {
97
+ const side = placement();
98
+ const vertical = side === "top" || side === "bottom";
99
+ const offset = measured();
100
+ const style: Record<string, string> = { position: "absolute" };
101
+ if (side !== null) style[side] = "100%";
102
+ const along = vertical ? offset.left : offset.top;
103
+ if (along !== undefined) {
104
+ style[vertical ? "left" : "top"] = along;
105
+ } else if (side !== null) {
106
+ style[vertical ? "left" : "top"] = "50%";
107
+ style.transform = vertical ? "translateX(-50%)" : "translateY(-50%)";
108
+ }
109
+ return style;
110
+ },
111
+ },
112
+ };
113
+ }
114
+
115
+ export interface OverlayArrowComponentProps extends StyleProps {
116
+ children?: Child;
117
+ ref?: RefTarget<HTMLDivElement>;
118
+ }
119
+
120
+ /**
121
+ * ```tsx
122
+ * <Popover triggerRef={trigger} isOpen={open()}>
123
+ * <OverlayArrow>
124
+ * <svg width={12} height={12} viewBox="0 0 12 12"><path d="M0 0 L6 6 L12 0" /></svg>
125
+ * </OverlayArrow>
126
+ * …
127
+ * </Popover>
128
+ * ```
129
+ */
130
+ export function OverlayArrow(props: OverlayArrowComponentProps) {
131
+ const overlay = useOverlayArrow();
132
+ const { arrowProps } = overlayArrow({
133
+ placement: () => overlay?.placement() ?? null,
134
+ arrowProps: overlay?.arrowProps,
135
+ });
136
+
137
+ const elementProps = mergeProps(
138
+ arrowProps,
139
+ filterDOMProps(fromProps(cells(props)), { global: true }),
140
+ {
141
+ class: () => props.class ?? props.className,
142
+ // The caller's style on top of the position, so a size or a colour does
143
+ // not have to restate where the arrow goes.
144
+ style: () => ({
145
+ ...access(arrowProps.style as MaybeAccessor<Record<string, string>>),
146
+ ...props.style,
147
+ }),
148
+ "data-testid": () => props["data-testid"],
149
+ },
150
+ );
151
+
152
+ return (
153
+ <div {...elementProps} ref={mergeRefs(overlay?.ref, props.ref)}>
154
+ {props.children}
155
+ </div>
156
+ );
157
+ }