@astryxdesign/core 0.4.3 → 0.4.4-canary.0f4d45f

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 (200) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +79 -45
  3. package/dist/Banner/Banner.d.ts +3 -0
  4. package/dist/Banner/Banner.d.ts.map +1 -1
  5. package/dist/Banner/Banner.js +13 -3
  6. package/dist/BottomSheet/BottomSheet.d.ts +66 -0
  7. package/dist/BottomSheet/BottomSheet.d.ts.map +1 -0
  8. package/dist/BottomSheet/BottomSheet.js +392 -0
  9. package/dist/BottomSheet/BottomSheetPanel.d.ts +60 -0
  10. package/dist/BottomSheet/BottomSheetPanel.d.ts.map +1 -0
  11. package/dist/BottomSheet/BottomSheetPanel.js +398 -0
  12. package/dist/BottomSheet/BottomSheetSwitcher.d.ts +61 -0
  13. package/dist/BottomSheet/BottomSheetSwitcher.d.ts.map +1 -0
  14. package/dist/BottomSheet/BottomSheetSwitcher.js +410 -0
  15. package/dist/BottomSheet/BottomSheetSwitcherContext.d.ts +21 -0
  16. package/dist/BottomSheet/BottomSheetSwitcherContext.d.ts.map +1 -0
  17. package/dist/BottomSheet/BottomSheetSwitcherContext.js +13 -0
  18. package/dist/BottomSheet/index.d.ts +11 -0
  19. package/dist/BottomSheet/index.d.ts.map +1 -0
  20. package/dist/BottomSheet/index.js +12 -0
  21. package/dist/BottomSheet/snapOffsets.d.ts +72 -0
  22. package/dist/BottomSheet/snapOffsets.d.ts.map +1 -0
  23. package/dist/BottomSheet/snapOffsets.js +130 -0
  24. package/dist/BottomSheet/useMobileKeyboard.d.ts +35 -0
  25. package/dist/BottomSheet/useMobileKeyboard.d.ts.map +1 -0
  26. package/dist/BottomSheet/useMobileKeyboard.js +373 -0
  27. package/dist/BottomSheet/useSheetGestures.d.ts +180 -0
  28. package/dist/BottomSheet/useSheetGestures.d.ts.map +1 -0
  29. package/dist/BottomSheet/useSheetGestures.js +989 -0
  30. package/dist/Chat/ChatComposerInput.d.ts.map +1 -1
  31. package/dist/Chat/ChatComposerInput.js +3 -4
  32. package/dist/ComplexSelector/ComplexSelector.d.ts.map +1 -1
  33. package/dist/ComplexSelector/ComplexSelector.js +12 -6
  34. package/dist/ContextMenu/ContextMenu.d.ts.map +1 -1
  35. package/dist/ContextMenu/ContextMenu.js +4 -2
  36. package/dist/DateInput/DateInput.d.ts.map +1 -1
  37. package/dist/DateInput/DateInput.js +9 -1
  38. package/dist/DateTimeInput/DateTimeInput.d.ts.map +1 -1
  39. package/dist/DateTimeInput/DateTimeInput.js +31 -1
  40. package/dist/Dialog/Dialog.d.ts.map +1 -1
  41. package/dist/Dialog/Dialog.js +2 -1
  42. package/dist/Field/InputClearButton.d.ts +2 -1
  43. package/dist/Field/InputClearButton.d.ts.map +1 -1
  44. package/dist/Field/InputClearButton.js +6 -1
  45. package/dist/Lightbox/Lightbox.d.ts.map +1 -1
  46. package/dist/Lightbox/Lightbox.js +9 -3
  47. package/dist/MobileNav/MobileNav.d.ts +12 -0
  48. package/dist/MobileNav/MobileNav.d.ts.map +1 -1
  49. package/dist/MobileNav/MobileNav.js +102 -30
  50. package/dist/MultiSelector/MultiSelector.d.ts.map +1 -1
  51. package/dist/MultiSelector/MultiSelector.js +21 -7
  52. package/dist/NumberInput/NumberInput.d.ts.map +1 -1
  53. package/dist/NumberInput/NumberInput.js +9 -1
  54. package/dist/PowerSearch/PowerSearchEditPopover.js +1 -1
  55. package/dist/Selector/Selector.d.ts.map +1 -1
  56. package/dist/Selector/Selector.js +14 -3
  57. package/dist/StatusDot/StatusDot.d.ts +43 -3
  58. package/dist/StatusDot/StatusDot.d.ts.map +1 -1
  59. package/dist/StatusDot/StatusDot.js +42 -5
  60. package/dist/Switch/Switch.d.ts.map +1 -1
  61. package/dist/Switch/Switch.js +5 -1
  62. package/dist/Table/plugins/rowExpansion/useTableRowExpansion.d.ts.map +1 -1
  63. package/dist/Table/plugins/rowExpansion/useTableRowExpansion.js +7 -2
  64. package/dist/TimeInput/TimeInput.d.ts.map +1 -1
  65. package/dist/TimeInput/TimeInput.js +8 -1
  66. package/dist/Tokenizer/Tokenizer.js +11 -5
  67. package/dist/Tooltip/useTooltip.d.ts.map +1 -1
  68. package/dist/Tooltip/useTooltip.js +4 -1
  69. package/dist/Typeahead/BaseTypeahead.d.ts.map +1 -1
  70. package/dist/Typeahead/BaseTypeahead.js +5 -3
  71. package/dist/Typeahead/Typeahead.d.ts.map +1 -1
  72. package/dist/Typeahead/Typeahead.js +10 -1
  73. package/dist/astryx.css +21 -0
  74. package/dist/hooks/index.d.ts +8 -1
  75. package/dist/hooks/index.d.ts.map +1 -1
  76. package/dist/hooks/index.js +8 -1
  77. package/dist/hooks/useFocusTrap.d.ts +0 -11
  78. package/dist/hooks/useFocusTrap.d.ts.map +1 -1
  79. package/dist/hooks/useFocusTrap.js +1 -11
  80. package/dist/hooks/useInputStatusIcon.d.ts.map +1 -1
  81. package/dist/hooks/useInputStatusIcon.js +1 -0
  82. package/dist/index.d.ts +1 -0
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +1 -0
  85. package/dist/theme/defineTheme.d.ts +22 -4
  86. package/dist/theme/defineTheme.d.ts.map +1 -1
  87. package/dist/theme/expandColorScale.d.ts +17 -2
  88. package/dist/theme/expandColorScale.d.ts.map +1 -1
  89. package/dist/theme/expandColorScale.js +63 -33
  90. package/dist/utils/ime.d.ts +5 -0
  91. package/dist/utils/ime.d.ts.map +1 -0
  92. package/dist/utils/ime.js +63 -0
  93. package/dist/utils/index.d.ts +1 -0
  94. package/dist/utils/index.d.ts.map +1 -1
  95. package/dist/utils/index.js +2 -1
  96. package/locales/af-ZA.json +958 -0
  97. package/locales/ar-SA.json +998 -0
  98. package/locales/ca-ES.json +974 -0
  99. package/locales/cs-CZ.json +990 -0
  100. package/locales/da-DK.json +966 -0
  101. package/locales/de-DE.json +966 -0
  102. package/locales/el-GR.json +990 -0
  103. package/locales/en.json +48 -0
  104. package/locales/es-ES.json +978 -0
  105. package/locales/fi-FI.json +990 -0
  106. package/locales/fr-FR.json +928 -0
  107. package/locales/he-IL.json +990 -0
  108. package/locales/hu-HU.json +990 -0
  109. package/locales/it-IT.json +978 -0
  110. package/locales/ja-JP.json +998 -0
  111. package/locales/ko-KR.json +990 -0
  112. package/locales/nl-NL.json +954 -0
  113. package/locales/no-NO.json +978 -0
  114. package/locales/pl-PL.json +982 -0
  115. package/locales/pseudo.json +36 -0
  116. package/locales/pt-BR.json +982 -0
  117. package/locales/pt-PT.json +982 -0
  118. package/locales/ro-RO.json +982 -0
  119. package/locales/ru-RU.json +990 -0
  120. package/locales/sr-SP.json +990 -0
  121. package/locales/sv-SE.json +986 -0
  122. package/locales/tr-TR.json +990 -0
  123. package/locales/uk-UA.json +990 -0
  124. package/locales/vi-VN.json +986 -0
  125. package/locales/zh-CN.json +998 -0
  126. package/locales/zh-TW.json +998 -0
  127. package/package.json +9 -8
  128. package/src/Banner/Banner.doc.mjs +3 -3
  129. package/src/Banner/Banner.test.tsx +40 -0
  130. package/src/Banner/Banner.tsx +27 -2
  131. package/src/BottomSheet/BottomSheet.doc.mjs +266 -0
  132. package/src/BottomSheet/BottomSheet.test.tsx +2114 -0
  133. package/src/BottomSheet/BottomSheet.tsx +545 -0
  134. package/src/BottomSheet/BottomSheetPanel.test.tsx +240 -0
  135. package/src/BottomSheet/BottomSheetPanel.tsx +547 -0
  136. package/src/BottomSheet/BottomSheetSwitcher.doc.mjs +219 -0
  137. package/src/BottomSheet/BottomSheetSwitcher.test.tsx +850 -0
  138. package/src/BottomSheet/BottomSheetSwitcher.tsx +628 -0
  139. package/src/BottomSheet/BottomSheetSwitcherContext.ts +51 -0
  140. package/src/BottomSheet/index.ts +15 -0
  141. package/src/BottomSheet/snapOffsets.test.ts +187 -0
  142. package/src/BottomSheet/snapOffsets.ts +159 -0
  143. package/src/BottomSheet/useMobileKeyboard.ts +499 -0
  144. package/src/BottomSheet/useSheetGestures.test.ts +1059 -0
  145. package/src/BottomSheet/useSheetGestures.ts +1459 -0
  146. package/src/Chat/ChatComposerInput.tsx +3 -4
  147. package/src/ComplexSelector/ComplexSelector.tsx +12 -5
  148. package/src/ContextMenu/ContextMenu.tsx +4 -2
  149. package/src/DateInput/DateInput.test.tsx +21 -0
  150. package/src/DateInput/DateInput.tsx +9 -1
  151. package/src/DateTimeInput/DateTimeInput.doc.mjs +4 -0
  152. package/src/DateTimeInput/DateTimeInput.test.tsx +137 -0
  153. package/src/DateTimeInput/DateTimeInput.tsx +39 -2
  154. package/src/Dialog/Dialog.tsx +2 -1
  155. package/src/Field/Field.doc.mjs +1 -0
  156. package/src/Field/InputClearButton.test.tsx +25 -0
  157. package/src/Field/InputClearButton.tsx +4 -1
  158. package/src/FileInput/FileInput.test.tsx +53 -9
  159. package/src/Lightbox/Lightbox.test.tsx +49 -28
  160. package/src/Lightbox/Lightbox.tsx +7 -3
  161. package/src/MobileNav/MobileNav.tsx +128 -37
  162. package/src/MobileNav/MobileNavCloseEdgeCases.test.tsx +426 -0
  163. package/src/MobileNav/MobileNavCloseTiming.test.ts +58 -0
  164. package/src/MobileNav/MobileNavCloseVisibility.test.tsx +172 -0
  165. package/src/MultiSelector/MultiSelector.test.tsx +195 -51
  166. package/src/MultiSelector/MultiSelector.tsx +22 -8
  167. package/src/NumberInput/NumberInput.test.tsx +18 -0
  168. package/src/NumberInput/NumberInput.tsx +9 -1
  169. package/src/PowerSearch/PowerSearchEditPopover.tsx +1 -1
  170. package/src/Selector/Selector.test.tsx +85 -26
  171. package/src/Selector/Selector.tsx +13 -4
  172. package/src/StatusDot/StatusDot.doc.mjs +13 -0
  173. package/src/StatusDot/StatusDot.test.tsx +115 -8
  174. package/src/StatusDot/StatusDot.tsx +74 -9
  175. package/src/Switch/Switch.test.tsx +16 -0
  176. package/src/Switch/Switch.tsx +7 -0
  177. package/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx +20 -2
  178. package/src/TimeInput/TimeInput.test.tsx +23 -0
  179. package/src/TimeInput/TimeInput.tsx +8 -0
  180. package/src/Tokenizer/Tokenizer.test.tsx +50 -32
  181. package/src/Tokenizer/Tokenizer.tsx +5 -5
  182. package/src/Tooltip/useTooltip.tsx +4 -1
  183. package/src/Typeahead/BaseTypeahead.tsx +10 -3
  184. package/src/Typeahead/Typeahead.test.tsx +116 -7
  185. package/src/Typeahead/Typeahead.tsx +10 -1
  186. package/src/__tests__/stubMatchMedia.test.ts +79 -0
  187. package/src/__tests__/stubMatchMedia.ts +95 -0
  188. package/src/hooks/index.ts +9 -5
  189. package/src/hooks/useFocusTrap.ts +1 -14
  190. package/src/hooks/useInputStatusIcon.test.tsx +19 -0
  191. package/src/hooks/useInputStatusIcon.tsx +7 -0
  192. package/src/index.ts +1 -0
  193. package/src/theme/defineTheme.ts +22 -4
  194. package/src/theme/expandColorScale.test.ts +138 -0
  195. package/src/theme/expandColorScale.ts +89 -44
  196. package/src/utils/ime.test.ts +32 -0
  197. package/src/utils/ime.ts +69 -0
  198. package/src/utils/index.ts +2 -0
  199. package/dist/astryx.umd.js +0 -147
  200. package/dist/astryx.umd.js.map +0 -7
@@ -0,0 +1,130 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file snapOffsets.ts
5
+ * @input Pure geometry helpers — no React, no DOM.
6
+ * @output Converts snap points to translateY offsets for the sheet surface.
7
+ * @position Internal to BottomSheet; consumed by useSheetGestures, tested by
8
+ * snapOffsets.test.ts.
9
+ *
10
+ * A detent is represented as an offset in px from the fully-open position
11
+ * (0 = fully open, larger = more collapsed). The panel may render that offset
12
+ * as a translate or as a reduction in layout height. These
13
+ * helpers turn snap points into the shared offset list; they are pure so the
14
+ * geometry can be unit-tested without a DOM.
15
+ */
16
+
17
+ /**
18
+ * Detents whose resting offsets land within this many px of each other are
19
+ * treated as the same stop (the taller one wins). Stops the sheet from having
20
+ * two near-identical rest positions — e.g. when a content-hugging height sits
21
+ * a hair away from a fractional snap point.
22
+ */
23
+ export const DETENT_DEDUP_PX = 48;
24
+
25
+ /** Resolve snap points given as viewport fractions (0, 1] to px heights. */
26
+ export function snapFractionsToHeights(fractions, viewportPx) {
27
+ return fractions.filter(f => f > 0 && f <= 1).map(f => f * viewportPx);
28
+ }
29
+
30
+ /**
31
+ * Given the sheet's full height (px, as rendered fully open) and a set of
32
+ * candidate detent *visible heights* (px), return the resting offsets from
33
+ * fully-open, ascending and de-duplicated.
34
+ *
35
+ * - `0` (fully open) is always the first detent.
36
+ * - Only heights strictly shorter than the sheet become collapsed detents; a
37
+ * height >= the sheet is already covered by the fully-open stop.
38
+ * - Offsets closer than `dedupPx` collapse to the smaller (taller) offset, so
39
+ * near-identical detents — e.g. a hug height ≈ a snap point — become one stop.
40
+ */
41
+ export function computeDetentOffsets(sheetHeight, detentHeights, dedupPx = DETENT_DEDUP_PX) {
42
+ const collapsed = detentHeights.filter(h => h > 0 && h < sheetHeight).map(h => sheetHeight - h);
43
+ const ascending = [0, ...collapsed].sort((a, b) => a - b);
44
+ const deduped = [];
45
+ for (const offset of ascending) {
46
+ const last = deduped[deduped.length - 1];
47
+ if (last === undefined || offset - last >= dedupPx) {
48
+ deduped.push(offset);
49
+ }
50
+ }
51
+ return deduped;
52
+ }
53
+
54
+ /** Nearest value in `offsets` to `value` (offsets must be non-empty). */
55
+ export function nearestOffset(value, offsets) {
56
+ return offsets.reduce((best, o) => Math.abs(o - value) < Math.abs(best - value) ? o : best, offsets[0]);
57
+ }
58
+
59
+ /**
60
+ * Minimum scrim opacity at the peek detent. The scrim thins to a glance state
61
+ * but never fully vanishes, because a modal sheet keeps the background inert —
62
+ * a fully clear backdrop would read as "interactive" when it isn't. (For a
63
+ * genuinely interactive, undimmed peek, use a non-modal sheet, `hasScrim=false`.)
64
+ */
65
+ export const MIN_PEEK_SCRIM_OPACITY = 0.3;
66
+
67
+ /**
68
+ * Whether `offset` is the peek detent: the shortest stop, where the sheet is a
69
+ * glance rather than a working surface. A sheet with no collapsed stop at all
70
+ * has no peek — the same rule `scrimOpacityForOffset` thins the scrim by.
71
+ *
72
+ * The peek is the one detent the sheet does NOT express as layout height: at a
73
+ * sliver of viewport there is nothing useful to lay out, and reflowing the
74
+ * content into it (then back out on the way up) is churn the user sees. It
75
+ * keeps the full layout height and slides below the viewport instead.
76
+ */
77
+ export function isPeekOffset(offset, offsets, tolerancePx = 0.5) {
78
+ if (offsets.length < 2) {
79
+ return false;
80
+ }
81
+ return Math.abs(offset - offsets[offsets.length - 1]) <= tolerancePx;
82
+ }
83
+
84
+ /**
85
+ * Scrim opacity (1 = fully visible) for a drag/settle `offset`.
86
+ * The scrim stays full while the sheet is at or above its second-shortest
87
+ * detent, then fades as it collapses onto the shortest ("peek") detent — a
88
+ * glance state that thins the backdrop to `MIN_PEEK_SCRIM_OPACITY` (not fully
89
+ * gone, since the sheet is still modal) and holds there below it.
90
+ * A single-detent sheet has no peek, so it instead fades all the way to 0
91
+ * across the dismiss overshoot toward `dismissOffset` (the sheet is leaving).
92
+ */
93
+ export function scrimOpacityForOffset(offset, offsets, dismissOffset) {
94
+ const shortest = offsets[offsets.length - 1];
95
+ const hasPeek = offsets.length >= 2;
96
+ const fadeStart = hasPeek ? offsets[offsets.length - 2] : 0;
97
+ const fadeEnd = hasPeek ? shortest : dismissOffset;
98
+ // Peek is a resting state on a still-modal sheet, so keep a floor; the
99
+ // dismiss overshoot is a sheet on its way out, so let it clear completely.
100
+ const floor = hasPeek ? MIN_PEEK_SCRIM_OPACITY : 0;
101
+ if (offset <= fadeStart) {
102
+ return 1;
103
+ }
104
+ if (offset >= fadeEnd) {
105
+ return floor;
106
+ }
107
+ return 1 - (1 - floor) * ((offset - fadeStart) / (fadeEnd - fadeStart));
108
+ }
109
+
110
+ /**
111
+ * Settle target for a released drag. Restricts candidates to the drag
112
+ * direction so a committed drag never snaps *back past* where it started
113
+ * (a down-drag settles at/below the start, an up-drag at/above), then picks
114
+ * the nearest remaining detent. `dir`: 1 = dragged down, -1 = up, 0 = neither.
115
+ */
116
+ export function resolveSettleOffset(value, offsets, dir, baseOffset) {
117
+ let candidates = offsets;
118
+ if (dir > 0) {
119
+ const downward = offsets.filter(o => o >= baseOffset);
120
+ if (downward.length > 0) {
121
+ candidates = downward;
122
+ }
123
+ } else if (dir < 0) {
124
+ const upward = offsets.filter(o => o <= baseOffset);
125
+ if (upward.length > 0) {
126
+ candidates = upward;
127
+ }
128
+ }
129
+ return nearestOffset(value, candidates);
130
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @file useMobileKeyboard.ts
3
+ * @input Uses React effects and refs supplied by BottomSheet
4
+ * @output Exports internal useMobileKeyboard hook
5
+ * @position Internal to BottomSheet; not exported from the core entry point
6
+ *
7
+ * Gives a fully expanded, explicitly Tall sheet a keyboard-aware internal
8
+ * scroll range while leaving the sheet itself stationary. Shorter detents and
9
+ * other heights opt out entirely. Starting Tall-sheet travel or closing the
10
+ * sheet blurs the field and dismisses the keyboard.
11
+ *
12
+ * Every route into a field also has to reach it without the browser revealing
13
+ * it for us. On iOS that reveal scrolls the DOCUMENT, and a fixed sheet travels
14
+ * with it, so the whole page lurches. The reveal is attached to the focus
15
+ * operation, which is where it can be refused: take the focus transition over
16
+ * on the capture-phase blur, deliver it with preventScroll, and bring the
17
+ * control into view with the sheet's own scroller afterwards. Every route in —
18
+ * a tap, the keyboard's Next, Tab, a programmatic focus() — passes through that
19
+ * one transition.
20
+ */
21
+ import { type RefObject } from 'react';
22
+ interface UseMobileKeyboardOptions {
23
+ bodyRef: RefObject<HTMLElement | null>;
24
+ bottomClearance: number;
25
+ isEnabled: boolean;
26
+ isFullyExpanded: boolean;
27
+ isPageScrollLocked: boolean;
28
+ isSheetTraveling: boolean;
29
+ isOpen: boolean;
30
+ isPresented: boolean;
31
+ sheetRef: RefObject<HTMLDivElement | null>;
32
+ }
33
+ export declare function useMobileKeyboard({ bodyRef, bottomClearance, isEnabled, isFullyExpanded, isPageScrollLocked, isSheetTraveling, isOpen, isPresented, sheetRef, }: UseMobileKeyboardOptions): void;
34
+ export {};
35
+ //# sourceMappingURL=useMobileKeyboard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useMobileKeyboard.d.ts","sourceRoot":"","sources":["../../src/BottomSheet/useMobileKeyboard.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAoB,KAAK,SAAS,EAAC,MAAM,OAAO,CAAC;AAgBxD,UAAU,wBAAwB;IAChC,OAAO,EAAE,SAAS,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IACvC,eAAe,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,OAAO,CAAC;IACnB,eAAe,EAAE,OAAO,CAAC;IACzB,kBAAkB,EAAE,OAAO,CAAC;IAC5B,gBAAgB,EAAE,OAAO,CAAC;IAC1B,MAAM,EAAE,OAAO,CAAC;IAChB,WAAW,EAAE,OAAO,CAAC;IACrB,QAAQ,EAAE,SAAS,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;CAC5C;AA8DD,wBAAgB,iBAAiB,CAAC,EAChC,OAAO,EACP,eAAe,EACf,SAAS,EACT,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,MAAM,EACN,WAAW,EACX,QAAQ,GACT,EAAE,wBAAwB,GAAG,IAAI,CAuXjC"}
@@ -0,0 +1,373 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ /**
6
+ * @file useMobileKeyboard.ts
7
+ * @input Uses React effects and refs supplied by BottomSheet
8
+ * @output Exports internal useMobileKeyboard hook
9
+ * @position Internal to BottomSheet; not exported from the core entry point
10
+ *
11
+ * Gives a fully expanded, explicitly Tall sheet a keyboard-aware internal
12
+ * scroll range while leaving the sheet itself stationary. Shorter detents and
13
+ * other heights opt out entirely. Starting Tall-sheet travel or closing the
14
+ * sheet blurs the field and dismisses the keyboard.
15
+ *
16
+ * Every route into a field also has to reach it without the browser revealing
17
+ * it for us. On iOS that reveal scrolls the DOCUMENT, and a fixed sheet travels
18
+ * with it, so the whole page lurches. The reveal is attached to the focus
19
+ * operation, which is where it can be refused: take the focus transition over
20
+ * on the capture-phase blur, deliver it with preventScroll, and bring the
21
+ * control into view with the sheet's own scroller afterwards. Every route in —
22
+ * a tap, the keyboard's Next, Tab, a programmatic focus() — passes through that
23
+ * one transition.
24
+ */
25
+ import { useEffect, useRef } from 'react';
26
+ const MOBILE_KEYBOARD_INSET_VAR = '--_sheet-keyboard-inset';
27
+ const NON_TEXT_INPUT_TYPES = new Set(['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit']);
28
+ function getObstructionTop() {
29
+ return window.visualViewport?.height ?? window.innerHeight;
30
+ }
31
+
32
+ // The keyboard is gone once the visible band reaches the layout viewport bottom.
33
+ function isVisualViewportRecovered() {
34
+ return getObstructionTop() >= window.innerHeight - 0.5;
35
+ }
36
+ function isIOSWebKit() {
37
+ const userAgent = window.navigator.userAgent;
38
+ return /iPad|iPhone|iPod/.test(userAgent) || userAgent.includes('Macintosh') && window.navigator.maxTouchPoints > 1;
39
+ }
40
+ function isTextEntryControl(element) {
41
+ if (element instanceof HTMLTextAreaElement) {
42
+ return !element.disabled && !element.readOnly;
43
+ }
44
+ if (element instanceof HTMLInputElement) {
45
+ return !element.disabled && !element.readOnly && !NON_TEXT_INPUT_TYPES.has((element.getAttribute('type') ?? 'text').toLowerCase());
46
+ }
47
+ return element instanceof HTMLElement && element.matches('[contenteditable]:not([contenteditable="false"])');
48
+ }
49
+ function findTextEntryControl(target, body) {
50
+ if (!(target instanceof Element)) {
51
+ return null;
52
+ }
53
+ const direct = target.closest('input, textarea, [contenteditable]:not([contenteditable="false"])');
54
+ if (body.contains(direct) && isTextEntryControl(direct)) {
55
+ return direct;
56
+ }
57
+ const label = target.closest('label');
58
+ const control = label instanceof HTMLLabelElement ? label.control : null;
59
+ return body.contains(control) && isTextEntryControl(control) ? control : null;
60
+ }
61
+ export function useMobileKeyboard({
62
+ bodyRef,
63
+ bottomClearance,
64
+ isEnabled,
65
+ isFullyExpanded,
66
+ isPageScrollLocked,
67
+ isSheetTraveling,
68
+ isOpen,
69
+ isPresented,
70
+ sheetRef
71
+ }) {
72
+ const hasKeyboardLayoutRef = useRef(false);
73
+ const retainKeyboardLayoutRef = useRef(false);
74
+ const isFullyExpandedRef = useRef(isFullyExpanded);
75
+ const isOpenRef = useRef(isOpen);
76
+ isFullyExpandedRef.current = isFullyExpanded;
77
+ isOpenRef.current = isOpen;
78
+ useEffect(() => {
79
+ if (!isEnabled || !isSheetTraveling) {
80
+ return;
81
+ }
82
+ const sheet = sheetRef.current;
83
+ const activeElement = document.activeElement;
84
+ if (sheet && activeElement instanceof HTMLElement && activeElement !== sheet && sheet.contains(activeElement)) {
85
+ // Keep the current keyboard scroll range while focusing the sheet
86
+ // dismisses the keyboard. Viewport resize events unwind that layout as
87
+ // the visual viewport recovers, avoiding a content jump on the first
88
+ // drag frame.
89
+ retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;
90
+ sheet.focus({
91
+ preventScroll: true
92
+ });
93
+ }
94
+ }, [isEnabled, isSheetTraveling, sheetRef]);
95
+ useEffect(() => {
96
+ if (!isEnabled || !isPresented || isOpen) {
97
+ return;
98
+ }
99
+ const sheet = sheetRef.current;
100
+ const activeElement = document.activeElement;
101
+ if (sheet && activeElement instanceof HTMLElement && activeElement !== sheet && sheet.contains(activeElement)) {
102
+ retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;
103
+ activeElement.blur();
104
+ }
105
+ }, [isEnabled, isOpen, isPresented, sheetRef]);
106
+ useEffect(() => {
107
+ const body = bodyRef.current;
108
+ const sheet = sheetRef.current;
109
+ if (!isEnabled || !isPresented || !body) {
110
+ return;
111
+ }
112
+ let keyboardGeometry = null;
113
+ let documentScrollAtKeyboard = null;
114
+ const ownsFocusTransitions = isIOSWebKit();
115
+ const clearKeyboardLayout = () => {
116
+ body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, '0px');
117
+ keyboardGeometry = null;
118
+ documentScrollAtKeyboard = null;
119
+ hasKeyboardLayoutRef.current = false;
120
+ retainKeyboardLayoutRef.current = false;
121
+ };
122
+ const scrollBodyBy = (distance, smoothly) => {
123
+ if (typeof body.scrollBy !== 'function') {
124
+ body.scrollTop += distance;
125
+ return;
126
+ }
127
+ const reduceMotion = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
128
+ body.scrollBy({
129
+ top: distance,
130
+ // Not 'auto': that defers to the element's computed `scroll-behavior`,
131
+ // so a consumer's `scroll-behavior: smooth` would animate a scroll this
132
+ // hook needs to land in the same frame.
133
+ behavior: smoothly && !reduceMotion ? 'smooth' : 'instant'
134
+ });
135
+ };
136
+
137
+ // Scroll `control` into the part of the body the keyboard leaves visible,
138
+ // reading live geometry each time.
139
+ const scrollControlIntoSafeArea = (control, smoothly) => {
140
+ const measuredBodyRect = body.getBoundingClientRect();
141
+ const measuredControlRect = control.getBoundingClientRect();
142
+ const obstructionTop = getObstructionTop();
143
+ const overlap = Math.max(0, measuredBodyRect.bottom - obstructionTop);
144
+ const clearance = overlap > 0 ? bottomClearance : 0;
145
+ const safeTop = measuredBodyRect.top;
146
+ const safeBottom = Math.min(measuredBodyRect.bottom, obstructionTop - clearance);
147
+ if (safeBottom <= safeTop) {
148
+ return;
149
+ }
150
+ if (measuredControlRect.bottom > safeBottom) {
151
+ scrollBodyBy(measuredControlRect.bottom - safeBottom, smoothly);
152
+ } else if (measuredControlRect.top < safeTop) {
153
+ scrollBodyBy(measuredControlRect.top - safeTop, smoothly);
154
+ }
155
+ };
156
+ const applyKeyboardGeometry = geometry => {
157
+ const obstructionTop = getObstructionTop();
158
+ // A collapsed detent can extend the body below the layout viewport even
159
+ // after the keyboard closes, so body overlap alone cannot identify
160
+ // recovery. Once the visual viewport is full height again, release the
161
+ // retained keyboard layout unconditionally.
162
+ if (isVisualViewportRecovered()) {
163
+ clearKeyboardLayout();
164
+ return;
165
+ }
166
+ const overlap = Math.max(0, geometry.bodyBottom - obstructionTop);
167
+ if (overlap === 0) {
168
+ clearKeyboardLayout();
169
+ return;
170
+ }
171
+ const inset = Math.max(0, geometry.bodyBottom - (obstructionTop - bottomClearance));
172
+ body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);
173
+ };
174
+
175
+ // Take the focus transition over before the browser performs it.
176
+ //
177
+ // `blur` is dispatched in the capture phase ahead of the browser's own
178
+ // focus step, and it names the destination in `relatedTarget`. Focusing it
179
+ // here with preventScroll settles the transition: the browser's step finds
180
+ // the element already active, so it dispatches nothing further and has
181
+ // nothing to reveal.
182
+ const claimFocusTransition = event => {
183
+ if (!isFullyExpandedRef.current) {
184
+ return;
185
+ }
186
+ const destination = findTextEntryControl(event.relatedTarget, body);
187
+ if (destination) {
188
+ if (destination !== document.activeElement) {
189
+ // Revealing the field is not this handler's job: focusing it raises
190
+ // focusin, and the viewport resize that follows the keyboard raises
191
+ // another — both already schedule the reveal below, which knows the
192
+ // safe area and scrolls only the sheet's own body.
193
+ destination.focus({
194
+ preventScroll: true
195
+ });
196
+ }
197
+ return;
198
+ }
199
+
200
+ // Focus left for nothing — the keyboard's Done button parks it on the
201
+ // body. Park it on the sheet instead, so re-tapping the same field is
202
+ // still a transition this handler sees. Left on the body, the field is
203
+ // already `document.activeElement` on the next tap, no blur fires, and
204
+ // the browser reveals it its own way.
205
+ //
206
+ // Only while the sheet is open: closing blurs the field too, and there
207
+ // is no next tap to keep claimable — the host restores focus to whatever
208
+ // opened the sheet.
209
+ const origin = findTextEntryControl(event.target, body);
210
+ if (isOpenRef.current && origin && !event.relatedTarget) {
211
+ sheet?.focus({
212
+ preventScroll: true
213
+ });
214
+ }
215
+ };
216
+ const revealFocusedControl = () => {
217
+ const activeElement = document.activeElement;
218
+ if (!isFullyExpandedRef.current || !(activeElement instanceof HTMLElement) || !body.contains(activeElement) || !isTextEntryControl(activeElement)) {
219
+ if (retainKeyboardLayoutRef.current && keyboardGeometry) {
220
+ applyKeyboardGeometry(keyboardGeometry);
221
+ return;
222
+ }
223
+ clearKeyboardLayout();
224
+ return;
225
+ }
226
+ retainKeyboardLayoutRef.current = false;
227
+ const measuredBodyRect = body.getBoundingClientRect();
228
+ const obstructionTop = getObstructionTop();
229
+ const overlap = Math.max(0, measuredBodyRect.bottom - obstructionTop);
230
+ // The extra clearance leaves room for mobile suggestion UI, but only
231
+ // while the visual viewport actually overlaps the sheet. With no
232
+ // obstruction, ordinary desktop and hardware-keyboard focus must not
233
+ // shift an already visible control.
234
+ const clearance = overlap > 0 ? bottomClearance : 0;
235
+ keyboardGeometry = overlap > 0 ? {
236
+ bodyBottom: measuredBodyRect.bottom
237
+ } : null;
238
+ // Where the document sits with the keyboard up and nothing yet shifted:
239
+ // the position handleDocumentScroll returns to. Captured on the
240
+ // transition only — a reveal that runs after the browser has already
241
+ // scrolled would otherwise record the shifted position as correct.
242
+ if (isPageScrollLocked && overlap > 0 && !hasKeyboardLayoutRef.current) {
243
+ documentScrollAtKeyboard = {
244
+ x: window.scrollX,
245
+ y: window.scrollY
246
+ };
247
+ }
248
+ hasKeyboardLayoutRef.current = overlap > 0;
249
+ const inset = overlap > 0 ? Math.max(0, measuredBodyRect.bottom - (obstructionTop - clearance)) : 0;
250
+ body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);
251
+ scrollControlIntoSafeArea(activeElement, overlap > 0);
252
+ };
253
+ let animationFrame = 0;
254
+ const scheduleReveal = () => {
255
+ cancelAnimationFrame(animationFrame);
256
+ animationFrame = requestAnimationFrame(revealFocusedControl);
257
+ };
258
+
259
+ // Resuming the app re-reveals the focused field with no focus event to
260
+ // claim, so the reveal above never runs and the document scrolls — taking
261
+ // the fixed sheet with it. Put that scroll back on the event that reports
262
+ // it and re-reveal inside the sheet.
263
+ //
264
+ // Only while the page is locked, which is the only state in which a
265
+ // document scroll cannot be the user's own: behind a non-modal sheet the
266
+ // page stays scrollable, and reverting there would fight them.
267
+ const handleDocumentScroll = () => {
268
+ const expected = documentScrollAtKeyboard;
269
+ if (expected == null || window.scrollX === expected.x && window.scrollY === expected.y) {
270
+ return;
271
+ }
272
+ window.scrollTo(expected.x, expected.y);
273
+ const activeElement = document.activeElement;
274
+ if (activeElement instanceof HTMLElement && body.contains(activeElement) && isTextEntryControl(activeElement)) {
275
+ scrollControlIntoSafeArea(activeElement, false);
276
+ }
277
+ };
278
+ const resizeObserver = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(scheduleReveal);
279
+ const refreshObservedLayout = () => {
280
+ if (!resizeObserver) {
281
+ return;
282
+ }
283
+ resizeObserver.disconnect();
284
+
285
+ // Body/sheet box changes include public height and xstyle updates. The
286
+ // generated inset pseudo-element changes only scroll overflow, so these
287
+ // observations do not feed the keyboard inset back into sheet geometry.
288
+ const targets = new Set([body]);
289
+ if (sheet) {
290
+ targets.add(sheet);
291
+ }
292
+ for (const child of body.children) {
293
+ targets.add(child);
294
+ }
295
+ const activeElement = document.activeElement;
296
+ if (activeElement instanceof HTMLElement && body.contains(activeElement)) {
297
+ for (let element = activeElement; element && element !== body; element = element.parentElement) {
298
+ targets.add(element);
299
+ }
300
+ }
301
+ for (const target of targets) {
302
+ resizeObserver.observe(target);
303
+ }
304
+ };
305
+ const mutationObserver = typeof MutationObserver === 'undefined' ? null : new MutationObserver(records => {
306
+ // Ignore the internal inset written on the body. Consumer DOM,
307
+ // text, class, style, or visibility changes can all move the
308
+ // focused control without a viewport event.
309
+ if (records.every(record => record.type === 'attributes' && record.target === body)) {
310
+ return;
311
+ }
312
+ refreshObservedLayout();
313
+ scheduleReveal();
314
+ });
315
+ const handleFocusIn = () => {
316
+ refreshObservedLayout();
317
+ scheduleReveal();
318
+ };
319
+ const handleFocusOut = () => {
320
+ // Keep the added scroll range while the keyboard animates away. A focus
321
+ // transition to another text-entry control cancels this in focusin.
322
+ retainKeyboardLayoutRef.current = hasKeyboardLayoutRef.current;
323
+ scheduleReveal();
324
+ };
325
+ const handleSheetTransitionEnd = event => {
326
+ if (event.target === sheet && event.propertyName === 'transform') {
327
+ scheduleReveal();
328
+ }
329
+ };
330
+ const viewport = window.visualViewport;
331
+ if (ownsFocusTransitions) {
332
+ // `blur` does not bubble, so the capture phase is the only place to hear
333
+ // every one of them — and it runs before the browser's own focus step,
334
+ // which is the only window in which the transition can still be claimed.
335
+ document.addEventListener('blur', claimFocusTransition, true);
336
+ }
337
+ body.addEventListener('focusin', handleFocusIn);
338
+ body.addEventListener('focusout', handleFocusOut);
339
+ sheet?.addEventListener('transitionend', handleSheetTransitionEnd);
340
+ viewport?.addEventListener('resize', scheduleReveal);
341
+ viewport?.addEventListener('scroll', scheduleReveal);
342
+ window.addEventListener('scroll', handleDocumentScroll);
343
+ window.addEventListener('resize', scheduleReveal);
344
+ mutationObserver?.observe(body, {
345
+ attributes: true,
346
+ characterData: true,
347
+ childList: true,
348
+ subtree: true
349
+ });
350
+ refreshObservedLayout();
351
+ // The dialog enters the top layer in a later effect. Wait until the next
352
+ // frame so flex geometry is final before measuring the body.
353
+ scheduleReveal();
354
+ return () => {
355
+ cancelAnimationFrame(animationFrame);
356
+ if (ownsFocusTransitions) {
357
+ document.removeEventListener('blur', claimFocusTransition, true);
358
+ }
359
+ body.removeEventListener('focusin', handleFocusIn);
360
+ body.removeEventListener('focusout', handleFocusOut);
361
+ sheet?.removeEventListener('transitionend', handleSheetTransitionEnd);
362
+ viewport?.removeEventListener('resize', scheduleReveal);
363
+ viewport?.removeEventListener('scroll', scheduleReveal);
364
+ window.removeEventListener('scroll', handleDocumentScroll);
365
+ window.removeEventListener('resize', scheduleReveal);
366
+ resizeObserver?.disconnect();
367
+ mutationObserver?.disconnect();
368
+ body.style.removeProperty(MOBILE_KEYBOARD_INSET_VAR);
369
+ hasKeyboardLayoutRef.current = false;
370
+ retainKeyboardLayoutRef.current = false;
371
+ };
372
+ }, [bodyRef, bottomClearance, isEnabled, isPageScrollLocked, isPresented, sheetRef]);
373
+ }