@astryxdesign/core 0.7.7-canary.bf14580 → 0.7.7-canary.c19ca12

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 (266) hide show
  1. package/dist/AlertDialog/AlertDialog.d.ts +4 -1
  2. package/dist/AlertDialog/AlertDialog.d.ts.map +1 -1
  3. package/dist/AlertDialog/AlertDialog.js +36 -6
  4. package/dist/BottomSheet/BottomSheet.d.ts.map +1 -1
  5. package/dist/BottomSheet/BottomSheet.js +76 -6
  6. package/dist/BottomSheet/BottomSheetPanel.d.ts.map +1 -1
  7. package/dist/BottomSheet/BottomSheetPanel.js +23 -4
  8. package/dist/BottomSheet/bottomSheetStack.d.ts.map +1 -1
  9. package/dist/BottomSheet/bottomSheetStack.js +5 -4
  10. package/dist/BottomSheet/useSheetGestures.d.ts.map +1 -1
  11. package/dist/BottomSheet/useSheetGestures.js +3 -1
  12. package/dist/Button/Button.d.ts.map +1 -1
  13. package/dist/Button/Button.js +47 -3
  14. package/dist/CheckboxInput/CheckboxInput.d.ts.map +1 -1
  15. package/dist/CheckboxInput/CheckboxInput.js +13 -2
  16. package/dist/ComplexSelector/ComplexSelector.d.ts +4 -1
  17. package/dist/ComplexSelector/ComplexSelector.d.ts.map +1 -1
  18. package/dist/ComplexSelector/ComplexSelector.js +14 -4
  19. package/dist/ContextMenu/ContextMenu.js +2 -2
  20. package/dist/DateInput/MonthScroller.d.ts.map +1 -1
  21. package/dist/DateInput/MonthScroller.js +13 -27
  22. package/dist/DateInput/Wheel.d.ts.map +1 -1
  23. package/dist/DateInput/Wheel.js +22 -41
  24. package/dist/Dialog/Dialog.d.ts.map +1 -1
  25. package/dist/Dialog/Dialog.js +7 -31
  26. package/dist/Field/Field.js +2 -2
  27. package/dist/HoverCard/HoverCard.d.ts +4 -3
  28. package/dist/HoverCard/HoverCard.d.ts.map +1 -1
  29. package/dist/HoverCard/HoverCard.js +27 -2
  30. package/dist/HoverCard/useHoverCard.d.ts +5 -4
  31. package/dist/HoverCard/useHoverCard.d.ts.map +1 -1
  32. package/dist/HoverCard/useHoverCard.js +17 -31
  33. package/dist/Icon/Icon.d.ts +5 -1
  34. package/dist/Icon/Icon.d.ts.map +1 -1
  35. package/dist/Icon/Icon.js +5 -2
  36. package/dist/Layer/layerAnimations.stylex.d.ts +7 -8
  37. package/dist/Layer/layerAnimations.stylex.d.ts.map +1 -1
  38. package/dist/Layer/layerAnimations.stylex.js +25 -20
  39. package/dist/Layer/usePressPin.d.ts +17 -5
  40. package/dist/Layer/usePressPin.d.ts.map +1 -1
  41. package/dist/Layer/usePressPin.js +62 -12
  42. package/dist/Lightbox/Lightbox.d.ts.map +1 -1
  43. package/dist/Lightbox/Lightbox.js +18 -0
  44. package/dist/PowerSearch/PowerSearch.d.ts +36 -3
  45. package/dist/PowerSearch/PowerSearch.d.ts.map +1 -1
  46. package/dist/PowerSearch/PowerSearch.js +522 -269
  47. package/dist/PowerSearch/PowerSearchBottomSheet.d.ts +100 -0
  48. package/dist/PowerSearch/PowerSearchBottomSheet.d.ts.map +1 -0
  49. package/dist/PowerSearch/PowerSearchBottomSheet.js +1913 -0
  50. package/dist/PowerSearch/PowerSearchEditPopover.d.ts +32 -1
  51. package/dist/PowerSearch/PowerSearchEditPopover.d.ts.map +1 -1
  52. package/dist/PowerSearch/PowerSearchEditPopover.js +17 -6
  53. package/dist/PowerSearch/PowerSearchValueEditor.d.ts +38 -3
  54. package/dist/PowerSearch/PowerSearchValueEditor.d.ts.map +1 -1
  55. package/dist/PowerSearch/PowerSearchValueEditor.js +170 -61
  56. package/dist/PowerSearch/formatFilterValue.d.ts +7 -0
  57. package/dist/PowerSearch/formatFilterValue.d.ts.map +1 -1
  58. package/dist/PowerSearch/formatFilterValue.js +11 -1
  59. package/dist/PowerSearch/formatTokenValue.d.ts +28 -0
  60. package/dist/PowerSearch/formatTokenValue.d.ts.map +1 -0
  61. package/dist/PowerSearch/formatTokenValue.js +160 -0
  62. package/dist/PowerSearch/powerSearchSheetUtils.d.ts +65 -0
  63. package/dist/PowerSearch/powerSearchSheetUtils.d.ts.map +1 -0
  64. package/dist/PowerSearch/powerSearchSheetUtils.js +168 -0
  65. package/dist/RadioList/RadioList.d.ts.map +1 -1
  66. package/dist/RadioList/RadioList.js +3 -2
  67. package/dist/RadioList/RadioListItem.d.ts +1 -1
  68. package/dist/RadioList/RadioListItem.d.ts.map +1 -1
  69. package/dist/RadioList/RadioListItem.js +5 -3
  70. package/dist/SegmentedControl/useSegmentedSelectionMotion.d.ts.map +1 -1
  71. package/dist/SegmentedControl/useSegmentedSelectionMotion.js +3 -3
  72. package/dist/Slider/sliderTouchController.js +2 -2
  73. package/dist/Spinner/Spinner.d.ts +1 -1
  74. package/dist/Spinner/Spinner.d.ts.map +1 -1
  75. package/dist/Spinner/Spinner.js +60 -58
  76. package/dist/Switch/useSwitchTouch.js +4 -4
  77. package/dist/Table/BaseTable.d.ts.map +1 -1
  78. package/dist/Table/BaseTable.js +29 -8
  79. package/dist/TextInput/TextInput.d.ts +2 -2
  80. package/dist/TextInput/TextInput.d.ts.map +1 -1
  81. package/dist/TextInput/TextInput.js +10 -7
  82. package/dist/Toast/Toast.d.ts +11 -1
  83. package/dist/Toast/Toast.d.ts.map +1 -1
  84. package/dist/Toast/Toast.js +25 -15
  85. package/dist/Toast/ToastViewport.d.ts.map +1 -1
  86. package/dist/Toast/ToastViewport.js +94 -34
  87. package/dist/Toast/types.d.ts +9 -3
  88. package/dist/Toast/types.d.ts.map +1 -1
  89. package/dist/Token/Token.d.ts +2 -2
  90. package/dist/Token/Token.d.ts.map +1 -1
  91. package/dist/Token/Token.js +12 -4
  92. package/dist/Token/TokenNamingContext.d.ts +14 -0
  93. package/dist/Token/TokenNamingContext.d.ts.map +1 -0
  94. package/dist/Token/TokenNamingContext.js +23 -0
  95. package/dist/Tooltip/useTooltip.d.ts +19 -1
  96. package/dist/Tooltip/useTooltip.d.ts.map +1 -1
  97. package/dist/Tooltip/useTooltip.js +34 -53
  98. package/dist/Typeahead/TypeaheadItem.d.ts +2 -1
  99. package/dist/Typeahead/TypeaheadItem.d.ts.map +1 -1
  100. package/dist/animator/createAnimator.d.ts +98 -0
  101. package/dist/animator/createAnimator.d.ts.map +1 -0
  102. package/dist/animator/createAnimator.js +259 -0
  103. package/dist/astryx.css +22 -6
  104. package/dist/gestures/GestureHost.d.ts +27 -1
  105. package/dist/gestures/GestureHost.d.ts.map +1 -1
  106. package/dist/gestures/GestureHost.js +90 -8
  107. package/dist/gestures/PressTracker.d.ts.map +1 -1
  108. package/dist/gestures/PressTracker.js +4 -3
  109. package/dist/hooks/actionGroupTracker.d.ts +4 -1
  110. package/dist/hooks/actionGroupTracker.d.ts.map +1 -1
  111. package/dist/hooks/actionGroupTracker.js +13 -3
  112. package/dist/hooks/index.d.ts +1 -0
  113. package/dist/hooks/index.d.ts.map +1 -1
  114. package/dist/hooks/index.js +1 -0
  115. package/dist/hooks/pressGroupContext.d.ts +6 -0
  116. package/dist/hooks/pressGroupContext.d.ts.map +1 -0
  117. package/dist/hooks/pressGroupContext.js +20 -0
  118. package/dist/hooks/useActionGroupTracking.d.ts +53 -0
  119. package/dist/hooks/useActionGroupTracking.d.ts.map +1 -0
  120. package/dist/hooks/useActionGroupTracking.js +174 -0
  121. package/dist/hooks/useAnimator.d.ts +41 -0
  122. package/dist/hooks/useAnimator.d.ts.map +1 -0
  123. package/dist/hooks/useAnimator.js +70 -0
  124. package/dist/hooks/useAttachment.d.ts +1 -1
  125. package/dist/hooks/useAttachment.js +1 -1
  126. package/dist/hooks/useInputStatusIcon.d.ts +1 -1
  127. package/dist/hooks/useInputStatusIcon.d.ts.map +1 -1
  128. package/dist/hooks/useInputStatusIcon.js +2 -2
  129. package/dist/hooks/useLongPress.d.ts +6 -2
  130. package/dist/hooks/useLongPress.d.ts.map +1 -1
  131. package/dist/hooks/useLongPress.js +95 -15
  132. package/dist/hooks/useMenuPress.d.ts.map +1 -1
  133. package/dist/hooks/useMenuPress.js +4 -2
  134. package/dist/i18n/generated-english/PowerSearch/PowerSearchBottomSheet.generated.d.ts +8 -0
  135. package/dist/i18n/generated-english/PowerSearch/PowerSearchBottomSheet.generated.d.ts.map +1 -0
  136. package/dist/i18n/generated-english/PowerSearch/PowerSearchBottomSheet.generated.js +42 -0
  137. package/dist/i18n/generated-english/PowerSearch/PowerSearchValueEditor.generated.d.ts.map +1 -1
  138. package/dist/i18n/generated-english/PowerSearch/PowerSearchValueEditor.generated.js +6 -0
  139. package/dist/i18n/generated-english/PowerSearch/formatTokenValue.generated.d.ts +8 -0
  140. package/dist/i18n/generated-english/PowerSearch/formatTokenValue.generated.d.ts.map +1 -0
  141. package/dist/i18n/generated-english/PowerSearch/formatTokenValue.generated.js +14 -0
  142. package/dist/i18n/generated-locales/en.generated.d.ts.map +1 -1
  143. package/dist/i18n/generated-locales/en.generated.js +30 -0
  144. package/dist/i18n/generated-locales/pseudo.generated.d.ts.map +1 -1
  145. package/dist/i18n/generated-locales/pseudo.generated.js +30 -0
  146. package/dist/index.d.ts +1 -0
  147. package/dist/index.d.ts.map +1 -1
  148. package/dist/index.js +4 -0
  149. package/dist/internal/indicatorPress.stylex.d.ts +20 -0
  150. package/dist/internal/indicatorPress.stylex.d.ts.map +1 -0
  151. package/dist/internal/indicatorPress.stylex.js +26 -0
  152. package/dist/motion/animator.d.ts +14 -14
  153. package/dist/motion/animator.d.ts.map +1 -1
  154. package/dist/motion/animator.js +41 -18
  155. package/dist/motion/reducedMotion.d.ts +24 -0
  156. package/dist/motion/reducedMotion.d.ts.map +1 -1
  157. package/dist/motion/reducedMotion.js +78 -1
  158. package/dist/motion/uikit/alert.d.ts +41 -0
  159. package/dist/motion/uikit/alert.d.ts.map +1 -0
  160. package/dist/motion/uikit/alert.js +43 -0
  161. package/dist/privateAttributes/pressGroupItem.stylex.d.ts +15 -0
  162. package/dist/privateAttributes/pressGroupItem.stylex.d.ts.map +1 -0
  163. package/dist/privateAttributes/pressGroupItem.stylex.js +23 -0
  164. package/dist/utils/clickGuard.d.ts +8 -1
  165. package/dist/utils/clickGuard.d.ts.map +1 -1
  166. package/dist/utils/clickGuard.js +24 -1
  167. package/dist/utils/dateParser.d.ts.map +1 -1
  168. package/dist/utils/dateParser.js +12 -0
  169. package/dist/utils/focusReturn.d.ts +15 -0
  170. package/dist/utils/focusReturn.d.ts.map +1 -1
  171. package/dist/utils/focusReturn.js +28 -0
  172. package/dist/utils/interactionOverlay.stylex.d.ts +3 -2
  173. package/dist/utils/interactionOverlay.stylex.d.ts.map +1 -1
  174. package/dist/utils/interactionOverlay.stylex.js +3 -2
  175. package/dist/utils/pressFeedback.d.ts.map +1 -1
  176. package/dist/utils/pressFeedback.js +19 -6
  177. package/dist/utils/triggerFocus.d.ts +36 -0
  178. package/dist/utils/triggerFocus.d.ts.map +1 -0
  179. package/dist/utils/triggerFocus.js +65 -0
  180. package/locales/en.json +120 -0
  181. package/locales/pseudo.json +90 -0
  182. package/package.json +9 -4
  183. package/src/AlertDialog/AlertDialog.doc.mjs +2 -2
  184. package/src/AlertDialog/AlertDialog.tsx +37 -5
  185. package/src/BottomSheet/BottomSheet.tsx +85 -5
  186. package/src/BottomSheet/BottomSheetPanel.tsx +40 -5
  187. package/src/BottomSheet/bottomSheetStack.ts +8 -4
  188. package/src/BottomSheet/useSheetGestures.ts +3 -1
  189. package/src/Button/Button.tsx +63 -5
  190. package/src/CheckboxInput/CheckboxInput.doc.mjs +18 -0
  191. package/src/CheckboxInput/CheckboxInput.tsx +36 -9
  192. package/src/ComplexSelector/ComplexSelector.tsx +20 -5
  193. package/src/ContextMenu/ContextMenu.tsx +2 -2
  194. package/src/DateInput/MonthScroller.tsx +18 -22
  195. package/src/DateInput/Wheel.tsx +30 -32
  196. package/src/Dialog/Dialog.tsx +10 -31
  197. package/src/Field/Field.tsx +2 -2
  198. package/src/HoverCard/HoverCard.doc.mjs +4 -2
  199. package/src/HoverCard/HoverCard.tsx +35 -4
  200. package/src/HoverCard/useHoverCard.doc.mjs +178 -36
  201. package/src/HoverCard/useHoverCard.tsx +46 -52
  202. package/src/Icon/Icon.doc.mjs +49 -8
  203. package/src/Icon/Icon.tsx +15 -7
  204. package/src/Layer/layerAnimations.stylex.ts +24 -16
  205. package/src/Layer/usePressPin.ts +81 -15
  206. package/src/Lightbox/Lightbox.tsx +18 -0
  207. package/src/PowerSearch/PowerSearch.doc.mjs +54 -5
  208. package/src/PowerSearch/PowerSearch.tsx +734 -288
  209. package/src/PowerSearch/PowerSearchBottomSheet.tsx +2515 -0
  210. package/src/PowerSearch/PowerSearchEditPopover.tsx +28 -6
  211. package/src/PowerSearch/PowerSearchValueEditor.tsx +203 -38
  212. package/src/PowerSearch/formatFilterValue.ts +18 -1
  213. package/src/PowerSearch/formatTokenValue.ts +215 -0
  214. package/src/PowerSearch/powerSearchSheetUtils.ts +224 -0
  215. package/src/RadioList/RadioList.tsx +3 -2
  216. package/src/RadioList/RadioListItem.tsx +5 -3
  217. package/src/SegmentedControl/useSegmentedSelectionMotion.ts +6 -3
  218. package/src/Slider/sliderTouchController.ts +2 -2
  219. package/src/Spinner/Spinner.tsx +77 -63
  220. package/src/Switch/useSwitchTouch.ts +4 -4
  221. package/src/Table/BaseTable.tsx +46 -12
  222. package/src/TextInput/TextInput.tsx +11 -10
  223. package/src/Toast/Toast.doc.mjs +4 -3
  224. package/src/Toast/Toast.tsx +52 -32
  225. package/src/Toast/ToastViewport.tsx +121 -35
  226. package/src/Toast/types.ts +9 -3
  227. package/src/Token/Token.tsx +13 -4
  228. package/src/Token/TokenNamingContext.ts +28 -0
  229. package/src/Tooltip/useTooltip.doc.mjs +24 -0
  230. package/src/Tooltip/useTooltip.tsx +61 -56
  231. package/src/Typeahead/TypeaheadItem.doc.mjs +6 -3
  232. package/src/Typeahead/TypeaheadItem.tsx +2 -1
  233. package/src/animator/createAnimator.doc.mjs +153 -0
  234. package/src/animator/createAnimator.ts +324 -0
  235. package/src/gestures/GestureHost.ts +105 -10
  236. package/src/gestures/PressTracker.ts +4 -3
  237. package/src/gestures/README.md +7 -1
  238. package/src/hooks/actionGroupTracker.ts +20 -5
  239. package/src/hooks/index.ts +2 -0
  240. package/src/hooks/pressGroupContext.ts +21 -0
  241. package/src/hooks/useActionGroupTracking.ts +224 -0
  242. package/src/hooks/useAnimator.doc.mjs +109 -0
  243. package/src/hooks/useAnimator.ts +67 -0
  244. package/src/hooks/useAttachment.ts +1 -1
  245. package/src/hooks/useInputStatusIcon.tsx +3 -2
  246. package/src/hooks/useLongPress.doc.mjs +2 -2
  247. package/src/hooks/useLongPress.ts +136 -15
  248. package/src/hooks/useMenuPress.ts +8 -2
  249. package/src/i18n/generated-english/PowerSearch/PowerSearchBottomSheet.generated.ts +43 -0
  250. package/src/i18n/generated-english/PowerSearch/PowerSearchValueEditor.generated.ts +6 -0
  251. package/src/i18n/generated-english/PowerSearch/formatTokenValue.generated.ts +15 -0
  252. package/src/i18n/generated-locales/en.generated.ts +41 -0
  253. package/src/i18n/generated-locales/pseudo.generated.ts +42 -0
  254. package/src/index.ts +13 -0
  255. package/src/internal/indicatorPress.stylex.ts +24 -0
  256. package/src/motion/README.md +8 -5
  257. package/src/motion/animator.ts +61 -29
  258. package/src/motion/reducedMotion.ts +79 -1
  259. package/src/motion/uikit/alert.ts +43 -0
  260. package/src/privateAttributes/pressGroupItem.stylex.ts +23 -0
  261. package/src/utils/clickGuard.ts +37 -1
  262. package/src/utils/dateParser.ts +16 -0
  263. package/src/utils/focusReturn.ts +30 -0
  264. package/src/utils/interactionOverlay.stylex.ts +3 -2
  265. package/src/utils/pressFeedback.ts +19 -6
  266. package/src/utils/triggerFocus.ts +80 -0
@@ -0,0 +1,2515 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ 'use client';
4
+
5
+ /**
6
+ * @file PowerSearchBottomSheet.tsx
7
+ * @input The field's InternalConfig, filters, onChange, the field typeahead
8
+ * source, and the sheet options PowerSearch forwards; BottomSheet,
9
+ * Button, EmptyState, Heading, Icon, IconButton, Indicator, List,
10
+ * RadioList, Text, TextInput, PowerSearchValueEditor, the internal sheet
11
+ * confirmation and search-drag owners, i18n
12
+ * @output Exports PowerSearchBottomSheet — the touch surface of
13
+ * `PowerSearch experimental.presentation="bottom-sheet"`: a Filters sheet
14
+ * with editable rows and trailing remove actions, Add filter in its fixed
15
+ * header and Clear all / Done in its fixed footer, an Add filter sheet with
16
+ * grouped field rows or the content search with inline suggestions, and a
17
+ * value step that stages field → operator → value and confirms from its
18
+ * footer
19
+ * @position Internal presentation surface of PowerSearch. Loaded on demand by
20
+ * PowerSearch.tsx so the popover presentation never carries it. The
21
+ * trigger lives in PowerSearch.tsx.
22
+ *
23
+ * The three steps are sibling standalone BottomSheets that stack: each step
24
+ * opens above the sheet that led to it, which stays open beneath as a covered
25
+ * sheet, so no sheet needs a Back action. A dismissal closes only the top
26
+ * sheet and reveals the step beneath; dismissing the bottom sheet ends the
27
+ * flow. A list value's Tokenizer opens its own sheet above the value step, as
28
+ * the top sheet of the stack.
29
+ *
30
+ * The sheets pad their own content (`padding={0}` on BottomSheet). The
31
+ * Filters and Add filter sheets keep their header and footer fixed around a
32
+ * scroll viewport that reaches the sheet edge; its content publishes the
33
+ * padding as container padding so `edge="bleed"` lists run edge to edge with
34
+ * row text on the header's inset. The sheets are pinned tall: the field list
35
+ * resizes as it is searched and the editor changes with the operator, and
36
+ * only a fully expanded tall sheet gives mobile-keyboard accommodation.
37
+ *
38
+ * SYNC: When modified, update:
39
+ * - /packages/core/src/PowerSearch/PowerSearch.tsx (the trigger and the lazy host)
40
+ * - /docs/specs/components/PowerSearch/PowerSearch.spec.md (FR10–FR21, AR4–AR6, PR5)
41
+ */
42
+
43
+ import React, {
44
+ useCallback,
45
+ useEffect,
46
+ useId,
47
+ useLayoutEffect,
48
+ useMemo,
49
+ useRef,
50
+ useState,
51
+ type ReactNode,
52
+ type RefObject,
53
+ type SVGProps,
54
+ } from 'react';
55
+ import {flushSync} from 'react-dom';
56
+ import * as stylex from '@stylexjs/stylex';
57
+ import {BottomSheet} from '../BottomSheet/BottomSheet';
58
+ import {Button} from '../Button/Button';
59
+ import {EmptyState} from '../EmptyState/EmptyState';
60
+ import {Heading} from '../Heading/Heading';
61
+ import {Icon} from '../Icon/Icon';
62
+ import {IconButton} from '../IconButton/IconButton';
63
+ import {CheckboxIndicator} from '../Indicator/CheckboxIndicator';
64
+ import {RadioIndicator} from '../Indicator/RadioIndicator';
65
+ import {focusOutlineStyles} from '../utils/focusOutline.stylex';
66
+ import {isRenderable} from '../utils/isRenderable';
67
+ import {containerPaddingInlineVarStyles} from '../Layout/padding.stylex';
68
+ import {List} from '../List/List';
69
+ import {ListItem} from '../List/ListItem';
70
+ import {RadioList} from '../RadioList/RadioList';
71
+ import {RadioListItem} from '../RadioList/RadioListItem';
72
+ import {Text} from '../Text/Text';
73
+ import {TextInput} from '../TextInput/TextInput';
74
+ import type {SearchSource} from '../Typeahead/types';
75
+ import {useAnnounce, type AnnounceFn} from '../hooks/useAnnounce';
76
+ import type {TranslatorFn} from '../i18n';
77
+ import {useListFormatter} from '../i18n/useListFormatter';
78
+ import {useLocale} from '../i18n/useLocale';
79
+ import {SheetConfirmation} from '../internal/SheetConfirmation';
80
+ import {useDismissSearchOnTouchDrag} from '../internal/useDismissSearchOnTouchDrag';
81
+ import {
82
+ colorVars,
83
+ fontWeightVars,
84
+ radiusVars,
85
+ spacingVars,
86
+ } from '../theme/tokens.stylex';
87
+ import {isImeKeyEvent} from '../utils/ime';
88
+ import {rtlStyles} from '../utils/rtlStyles';
89
+ import {formatTokenValueText} from './formatTokenValue';
90
+
91
+ function resolveRelativeDateLabel(
92
+ operatorValue: OperatorValue & {type: 'date_relative'},
93
+ value: string,
94
+ t: TranslatorFn,
95
+ buildRelativeDateOptions: PowerSearchSheetEditors['buildRelativeDateOptions'],
96
+ ): string {
97
+ return (
98
+ buildRelativeDateOptions(operatorValue, t).find(
99
+ option => option.value === value,
100
+ )?.label ?? value
101
+ );
102
+ }
103
+
104
+ // A placeholder the Filters row formats `labelValue` with, then splits on, so
105
+ // the value segment can render bold inside the catalog's ordering. A private
106
+ // use code point: never part of a label or value.
107
+ const ROW_VALUE_SLOT = '\uE000';
108
+ import type {
109
+ buildRelativeDateOptions,
110
+ PowerSearchValueEditor,
111
+ } from './PowerSearchValueEditor';
112
+ import type {NestedEditor} from './PowerSearchEditPopover';
113
+ import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
114
+ import {useInternalListFocus} from '../hooks/useListFocus';
115
+ import {useMergedRefs} from '../hooks/useMergedRefs';
116
+ import {groupItems} from '../utils/groupItems';
117
+ import {
118
+ createSheetSuggestionSource,
119
+ fieldMatchesQuery,
120
+ createFilterIdentities,
121
+ filterSignature,
122
+ isSupportedOperator,
123
+ nearestEditableIndex,
124
+ resolveFilterIdentityIndex,
125
+ } from './powerSearchSheetUtils';
126
+ import {resolveOperatorLabel} from './resolveOperatorLabel';
127
+ import type {InternalConfig} from './useInternalConfig';
128
+ import type {
129
+ FilterValue,
130
+ OperatorValue,
131
+ PartialFilter,
132
+ PowerSearchChangeType,
133
+ PowerSearchComponents,
134
+ PowerSearchConfig,
135
+ PowerSearchField,
136
+ PowerSearchFilter,
137
+ PowerSearchItem,
138
+ PowerSearchOperator,
139
+ } from './types';
140
+ import {
141
+ registerEnglishFallback,
142
+ useComponentTranslator,
143
+ } from '../i18n/useComponentTranslator';
144
+ import english from '../i18n/generated-english/PowerSearch/PowerSearchBottomSheet.generated';
145
+
146
+ registerEnglishFallback(english);
147
+
148
+ // =============================================================================
149
+ // Props
150
+ // =============================================================================
151
+
152
+ /**
153
+ * The popover presentation's editors, which the value step reuses. They come
154
+ * from PowerSearch.tsx, whose module graph already loads them for the popover
155
+ * presentation. Imported here, they and every component they reach would join
156
+ * this lazily imported graph, whose modules must import Core directly and
157
+ * never through a barrel.
158
+ */
159
+ export interface PowerSearchSheetEditors {
160
+ NestedEditor: typeof NestedEditor;
161
+ PowerSearchValueEditor: typeof PowerSearchValueEditor;
162
+ buildRelativeDateOptions: typeof buildRelativeDateOptions;
163
+ }
164
+
165
+ export interface PowerSearchBottomSheetProps {
166
+ /** Whether the flow is open; the trigger in PowerSearch.tsx owns it. */
167
+ isOpen: boolean;
168
+ onOpenChange: (isOpen: boolean) => void;
169
+ /**
170
+ * The trigger: where focus returns when the flow closes, whichever step
171
+ * closed it and however it opened (a tap on a token included).
172
+ */
173
+ finalFocusRef: RefObject<HTMLElement | null>;
174
+ /**
175
+ * The field's formatted result count, announced from inside the open
176
+ * sheet's dialog when it changes while the flow is open. `useAnnounce`
177
+ * routes a message by where its caller is, so the owner above the sheets
178
+ * cannot reach the dialog's region.
179
+ */
180
+ resultCountText?: string | null;
181
+ config: InternalConfig;
182
+ /** The caller's config, handed to Editor overrides as they expect it. */
183
+ configProp: PowerSearchConfig;
184
+ filters: ReadonlyArray<PowerSearchFilter>;
185
+ onChange: (
186
+ filters: ReadonlyArray<PowerSearchFilter>,
187
+ changeType: PowerSearchChangeType,
188
+ index: number,
189
+ ) => void;
190
+ /** The field typeahead source; the content search lists its suggestions. */
191
+ searchSource: SearchSource<PowerSearchItem>;
192
+ /** Placeholder of the content search. */
193
+ placeholder: string;
194
+ isReadOnly: boolean;
195
+ isDisabled: boolean;
196
+ hasClear: boolean;
197
+ maxOperatorMenuItems?: number;
198
+ maxSearchResults: number;
199
+ /** The caller's confirm label; the step picks a default per mode. */
200
+ saveButtonLabel?: string;
201
+ components?: PowerSearchComponents;
202
+ editors: PowerSearchSheetEditors;
203
+ }
204
+
205
+ // =============================================================================
206
+ // Styles
207
+ // =============================================================================
208
+
209
+ // The trailing plus a field row shows when choosing it adds the filter at
210
+ // once, and the Add filter actions' glyph. Core's default icon set has no plus.
211
+ function PlusIcon(props: SVGProps<SVGSVGElement>) {
212
+ return (
213
+ <svg
214
+ viewBox="0 0 24 24"
215
+ fill="none"
216
+ stroke="currentColor"
217
+ strokeWidth={1.5}
218
+ strokeLinecap="round"
219
+ strokeLinejoin="round"
220
+ {...props}>
221
+ <path d="M5 12h14" />
222
+ <path d="M12 5v14" />
223
+ </svg>
224
+ );
225
+ }
226
+
227
+ const styles = stylex.create({
228
+ // 44px touch targets for every sheet action, without resizing inputs.
229
+ touchAction: {
230
+ minHeight: 44,
231
+ },
232
+ // A sheet action drawn smaller than 44px keeps its drawn size and grows
233
+ // only its hit area to 44px, under a coarse pointer. The custom properties
234
+ // carry the media condition because StyleX allows plain values inside a
235
+ // pseudo-element. On a fine pointer the overlay is not generated, so it
236
+ // never takes hover from the action's own content.
237
+ touchHitArea: {
238
+ '--_power-search-sheet-hit-inset': {
239
+ default: '0px',
240
+ '@media (pointer: coarse)': 'min(0px, calc((100% - 44px) / 2))',
241
+ },
242
+ '--_power-search-sheet-hit-content': {
243
+ default: 'none',
244
+ '@media (pointer: coarse)': '""',
245
+ },
246
+ '::after': {
247
+ content: 'var(--_power-search-sheet-hit-content)',
248
+ position: 'absolute',
249
+ inset: 'var(--_power-search-sheet-hit-inset)',
250
+ },
251
+ },
252
+ // Scopes the sticky header's and footer's layer to this sheet's content:
253
+ // the List rows are `position: relative` and come after the header, so
254
+ // without a layer of its own the header is painted under the rows that
255
+ // scroll beneath it. Isolating the content keeps that z-index inside it, so
256
+ // the sheet's grab handle (z-index 1 on the panel, outside this wrapper)
257
+ // still paints above.
258
+ sheet: {
259
+ display: 'flex',
260
+ flexDirection: 'column',
261
+ minHeight: '100%',
262
+ isolation: 'isolate',
263
+ },
264
+ // The Filters and Add filter sheets fill the panel and scroll only their
265
+ // viewport, so the header and footer stay fixed.
266
+ sheetWithFixedFooter: {
267
+ height: '100%',
268
+ overflow: 'hidden',
269
+ },
270
+ header: {
271
+ position: 'sticky',
272
+ insetBlockStart: 0,
273
+ // Above the rows that scroll under it, within the isolated sheet content.
274
+ zIndex: 1,
275
+ display: 'flex',
276
+ flexDirection: 'column',
277
+ gap: spacingVars['--spacing-3'],
278
+ // Clears the sheet's floating grab handle.
279
+ paddingBlockStart: spacingVars['--spacing-6'],
280
+ paddingBlockEnd: spacingVars['--spacing-3'],
281
+ paddingInline: spacingVars['--spacing-4'],
282
+ backgroundColor: colorVars['--color-background-surface'],
283
+ },
284
+ headerRow: {
285
+ display: 'flex',
286
+ alignItems: 'center',
287
+ gap: spacingVars['--spacing-2'],
288
+ },
289
+ headerText: {
290
+ minWidth: 0,
291
+ flexGrow: 1,
292
+ display: 'flex',
293
+ flexDirection: 'column',
294
+ },
295
+ // The body pads the sheet's content and publishes that inline padding as
296
+ // the container padding its lists read: with `edge="bleed"` their rows run
297
+ // edge to edge (full-bleed dividers) while row text keeps this inset, so
298
+ // row text, group headings and the sheet title share one edge.
299
+ body: {
300
+ flexGrow: 1,
301
+ display: 'flex',
302
+ flexDirection: 'column',
303
+ gap: spacingVars['--spacing-4'],
304
+ paddingInline: spacingVars['--spacing-4'],
305
+ paddingBlockEnd: spacingVars['--spacing-4'],
306
+ },
307
+ // The viewport reaches the sheet edge, so its scrollbar does too; the
308
+ // content inside it carries the body's padding.
309
+ scrollViewport: {
310
+ flexGrow: 1,
311
+ minHeight: 0,
312
+ overflowY: 'auto',
313
+ overscrollBehaviorY: 'contain',
314
+ },
315
+ scrollContent: {
316
+ minHeight: '100%',
317
+ display: 'flex',
318
+ flexDirection: 'column',
319
+ gap: spacingVars['--spacing-4'],
320
+ paddingInline: spacingVars['--spacing-4'],
321
+ paddingBlockEnd: spacingVars['--spacing-4'],
322
+ },
323
+ footer: {
324
+ position: 'sticky',
325
+ insetBlockEnd: 0,
326
+ zIndex: 1,
327
+ display: 'flex',
328
+ alignItems: 'center',
329
+ justifyContent: 'space-between',
330
+ gap: spacingVars['--spacing-2'],
331
+ paddingBlock: spacingVars['--spacing-3'],
332
+ paddingInline: spacingVars['--spacing-4'],
333
+ backgroundColor: colorVars['--color-background-surface'],
334
+ },
335
+ fixedFooter: {
336
+ position: 'relative',
337
+ insetBlockEnd: 'auto',
338
+ flexShrink: 0,
339
+ },
340
+ footerEqualAction: {
341
+ flexGrow: 1,
342
+ flexBasis: 0,
343
+ minWidth: 0,
344
+ minHeight: 44,
345
+ },
346
+ footerSoleAction: {
347
+ flexGrow: 1,
348
+ },
349
+ empty: {
350
+ paddingBlock: spacingVars['--spacing-6'],
351
+ textAlign: 'center',
352
+ },
353
+ emptyState: {
354
+ flexGrow: 1,
355
+ display: 'flex',
356
+ alignItems: 'center',
357
+ justifyContent: 'center',
358
+ },
359
+ // With more than one section in the value step, each section is a muted
360
+ // container. Its inline padding is published as container padding, so
361
+ // choice rows run edge to edge inside the section.
362
+ controlSection: {
363
+ padding: spacingVars['--spacing-3'],
364
+ borderRadius: radiusVars['--radius-container'],
365
+ backgroundColor: colorVars['--color-background-muted'],
366
+ },
367
+ // The operator radios put their indicator at the row's end, as the choice
368
+ // rows do.
369
+ trailingControlRow: {
370
+ flexDirection: 'row-reverse',
371
+ },
372
+ // The built-in nested editor's sub-filter rows collapse from one line to
373
+ // wrapped lines under a container query on the popover's own container;
374
+ // the sheet renders no such container, so the editor's tree root is the
375
+ // query container here, and at phone widths the rows wrap instead of
376
+ // running past the sheet's edge.
377
+ nestedEditorContainer: {
378
+ containerType: 'inline-size',
379
+ overflow: 'hidden',
380
+ },
381
+ rowValue: {
382
+ fontWeight: fontWeightVars['--font-weight-bold'],
383
+ },
384
+ // Choice rows run edge to edge on the inset of the surface that holds them,
385
+ // the body or a muted section, with no dividers: the group reaches into
386
+ // that padding and each row pads back out to it.
387
+ choiceList: {
388
+ display: 'flex',
389
+ flexDirection: 'column',
390
+ marginInlineStart: 'calc(-1 * var(--container-padding-inline-start, 0px))',
391
+ marginInlineEnd: 'calc(-1 * var(--container-padding-inline-end, 0px))',
392
+ width:
393
+ 'calc(100% + var(--container-padding-inline-start, 0px) + var(--container-padding-inline-end, 0px))',
394
+ },
395
+ choiceRow: {
396
+ display: 'flex',
397
+ alignItems: 'center',
398
+ gap: spacingVars['--spacing-3'],
399
+ width: '100%',
400
+ minHeight: 44,
401
+ paddingBlock: spacingVars['--spacing-3'],
402
+ paddingInlineStart: 'var(--container-padding-inline-start, 0px)',
403
+ paddingInlineEnd: 'var(--container-padding-inline-end, 0px)',
404
+ borderWidth: 0,
405
+ borderRadius: 0,
406
+ backgroundColor: 'transparent',
407
+ color: colorVars['--color-text-primary'],
408
+ fontFamily: 'inherit',
409
+ textAlign: 'start',
410
+ cursor: {
411
+ default: 'pointer',
412
+ ':is([aria-disabled="true"])': 'default',
413
+ },
414
+ },
415
+ // An aria-disabled row gets no system disabled paint in forced colors;
416
+ // GrayText is the platform's disabled affordance there.
417
+ choiceRowDisabled: {
418
+ color: {
419
+ default: colorVars['--color-text-secondary'],
420
+ '@media (forced-colors: active)': 'GrayText',
421
+ },
422
+ },
423
+ choiceIcon: {
424
+ display: 'inline-flex',
425
+ flexShrink: 0,
426
+ },
427
+ choiceLabel: {
428
+ flexGrow: 1,
429
+ minWidth: 0,
430
+ },
431
+ editorInput: {
432
+ paddingBlockStart: spacingVars['--spacing-1'],
433
+ },
434
+ });
435
+
436
+ // =============================================================================
437
+ // Draft state
438
+ // =============================================================================
439
+
440
+ type SheetStep = 'manage' | 'fields' | 'value';
441
+
442
+ type PendingSheetFocus =
443
+ | {readonly type: 'manager-add'}
444
+ | {readonly type: 'content-search'}
445
+ | {
446
+ readonly type: 'manager-filter';
447
+ readonly sourceFilter: PowerSearchFilter;
448
+ readonly sourceSignature: string;
449
+ readonly preferredIndex: number;
450
+ /**
451
+ * After a removal, focus goes to the row's trailing remove action, so a
452
+ * run of removals needs no re-aiming; otherwise to the row.
453
+ */
454
+ readonly part?: 'remove';
455
+ }
456
+ | {readonly type: 'field'; readonly fieldKey: string};
457
+
458
+ interface FilterDraft {
459
+ readonly mode: 'create' | 'edit';
460
+ /**
461
+ * Counts the value steps opened in this flow. Part of the editor's `key`:
462
+ * the step's sheet stays mounted between openings, and an editor that
463
+ * reads its filter on mount (the built-in nested editor, a caller's
464
+ * override) must remount per opened filter, not per field and operator —
465
+ * two groups on one field would otherwise share one editor's state.
466
+ */
467
+ readonly generation: number;
468
+ /** Control within the Add filter sheet that launched this draft. */
469
+ readonly returnFocus?: 'field' | 'content-search';
470
+ /** Index in `filters` when edit mode opened. */
471
+ readonly filterIndex?: number;
472
+ /** Original controlled filter identity, used to follow immutable reorders. */
473
+ readonly sourceFilter?: PowerSearchFilter;
474
+ /** Structural snapshot, used when controlled parents clone their values. */
475
+ readonly sourceSignature?: string;
476
+ readonly field: string;
477
+ readonly operator?: string;
478
+ readonly value?: FilterValue;
479
+ }
480
+
481
+ function resolveDraftFilterIndex(
482
+ filters: ReadonlyArray<PowerSearchFilter>,
483
+ draft: FilterDraft,
484
+ ): number | null {
485
+ if (
486
+ draft.mode !== 'edit' ||
487
+ draft.filterIndex == null ||
488
+ draft.sourceFilter == null ||
489
+ draft.sourceSignature == null
490
+ ) {
491
+ return null;
492
+ }
493
+ return resolveFilterIdentityIndex(
494
+ filters,
495
+ draft.sourceFilter,
496
+ draft.sourceSignature,
497
+ draft.filterIndex,
498
+ );
499
+ }
500
+
501
+ // Below this many fields a search box is noise: the whole list is on screen.
502
+ const SEARCHABLE_FIELD_COUNT = 8;
503
+ // Empty-query browsing keeps the popover presentation's safety ceiling.
504
+ const MAX_BROWSE_MENU_ITEMS = 1000;
505
+
506
+ // =============================================================================
507
+ // Choice rows (enum, enum_list, date_relative)
508
+ // =============================================================================
509
+
510
+ /**
511
+ * Rendered inside a step's BottomSheet so that `useAnnounce` resolves the
512
+ * sheet's dialog as the enclosing modal; publishes that
513
+ * dialog's `announce` to the flow above through `onAnnounceChange` while
514
+ * mounted. Renders nothing.
515
+ */
516
+ function SheetAnnouncer({
517
+ onAnnounceChange,
518
+ }: {
519
+ onAnnounceChange: (announce: AnnounceFn | null) => void;
520
+ }) {
521
+ const announce = useAnnounce();
522
+ // Hands this dialog's announce function up; the cleanup withdraws it when
523
+ // the step changes or the flow closes.
524
+ useEffect(() => {
525
+ onAnnounceChange(announce);
526
+ return () => {
527
+ onAnnounceChange(null);
528
+ };
529
+ }, [announce, onAnnounceChange]);
530
+ return null;
531
+ }
532
+
533
+ /**
534
+ * The value step's "This filter is no longer available" message, rendered
535
+ * inside the step's dialog. The shared own-content module reads the rendered
536
+ * text and speaks it once per opened filter while the step is the open one.
537
+ * Called from inside the sheet's dialog, `useAnnounce` routes it into the
538
+ * dialog. The message is plain text, not an EmptyState, so nothing announces
539
+ * it a second time.
540
+ */
541
+ function SheetEmptyMessage({
542
+ id,
543
+ message,
544
+ occasion,
545
+ isShown,
546
+ }: {
547
+ id?: string;
548
+ message: string;
549
+ occasion: string;
550
+ /**
551
+ * Whether the message's step is the open one. A sheet beneath another, or
552
+ * closed with its body retained, speaks nothing, and the hook re-arms so
553
+ * the same occasion is spoken again when the step reopens on it.
554
+ */
555
+ isShown: boolean;
556
+ }) {
557
+ const ref = useRef<HTMLDivElement>(null);
558
+ useAnnounceRenderedText(ref, isShown, occasion);
559
+ return (
560
+ <div ref={ref} id={id} {...stylex.props(styles.empty)}>
561
+ <Text type="supporting" color="secondary">
562
+ {message}
563
+ </Text>
564
+ </div>
565
+ );
566
+ }
567
+
568
+ interface ChoiceItem {
569
+ readonly value: string;
570
+ readonly label: string;
571
+ readonly icon?: ReactNode;
572
+ }
573
+
574
+ // A radio group's one tab stop: the checked row, else the first.
575
+ function radioTabStopOrder(list: HTMLElement): ReadonlyArray<HTMLElement> {
576
+ const rows = Array.from(list.querySelectorAll<HTMLElement>('[role="radio"]'));
577
+ const checked = rows.find(row => row.getAttribute('aria-checked') === 'true');
578
+ return checked == null
579
+ ? rows
580
+ : [checked, ...rows.filter(row => row !== checked)];
581
+ }
582
+
583
+ /**
584
+ * Closed vocabularies render as full-width rows with a trailing check instead
585
+ * of the popover presentation's Selector or Tokenizer: a dropdown layer inside
586
+ * a sheet stacks a second overlay on a surface the person is already inside.
587
+ */
588
+ function ChoiceRows({
589
+ items,
590
+ selected,
591
+ isDisabled,
592
+ isMultiple,
593
+ label,
594
+ onToggle,
595
+ }: {
596
+ items: ReadonlyArray<ChoiceItem>;
597
+ selected: ReadonlySet<string>;
598
+ isDisabled?: boolean;
599
+ /** `enum_list`: checkbox rows that toggle. Otherwise radio rows. */
600
+ isMultiple: boolean;
601
+ /** The group's accessible name: the field label. */
602
+ label: string;
603
+ onToggle: (value: string, isSelected: boolean) => void;
604
+ }) {
605
+ // The rows carry their state as state, not as a name suffix: `radio` rows
606
+ // in a `radiogroup` for a single choice, `checkbox` rows in a `group` for
607
+ // `enum_list`, each with `aria-checked`, as the Tokenizer's sheet rows do.
608
+ // Disabled rows stay focusable with `aria-disabled`.
609
+ //
610
+ // Keyboard: a radio group is one tab stop — the checked row, else the
611
+ // first — and the arrow keys move focus and check the row they land on,
612
+ // wrapping; Home and End move to and check the first and last row. The
613
+ // shared list focus owns the tab stop and the moves; a row that takes focus
614
+ // from an arrow, Home or End is checked here. Space and Enter check the
615
+ // focused radio row and toggle a checkbox row: each row is a native
616
+ // `button`, whose activation fires `onClick` for both keys. A checkbox row
617
+ // is its own tab stop.
618
+ const isKeyMoveRef = useRef(false);
619
+ const {listRef, handleKeyDown, handleFocus} =
620
+ useInternalListFocus<HTMLDivElement>({
621
+ itemSelector: '[role="radio"]',
622
+ orientation: 'both',
623
+ hasRovingTabIndex: !isMultiple,
624
+ tabStopOrder: radioTabStopOrder,
625
+ });
626
+ const handleRadioKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
627
+ isKeyMoveRef.current = true;
628
+ try {
629
+ handleKeyDown(event);
630
+ } finally {
631
+ isKeyMoveRef.current = false;
632
+ }
633
+ };
634
+ const handleRadioFocus = (event: React.FocusEvent<HTMLDivElement>) => {
635
+ handleFocus(event);
636
+ if (!isKeyMoveRef.current || isDisabled) {
637
+ return;
638
+ }
639
+ const value = (event.target as HTMLElement).closest<HTMLElement>(
640
+ '[role="radio"]',
641
+ )?.dataset.value;
642
+ if (value != null && !selected.has(value)) {
643
+ onToggle(value, false);
644
+ }
645
+ };
646
+ return (
647
+ <div
648
+ ref={listRef}
649
+ role={isMultiple ? 'group' : 'radiogroup'}
650
+ aria-label={label}
651
+ onKeyDown={isMultiple ? undefined : handleRadioKeyDown}
652
+ onFocus={isMultiple ? undefined : handleRadioFocus}
653
+ {...stylex.props(styles.choiceList)}>
654
+ {items.map(item => {
655
+ const isSelected = selected.has(item.value);
656
+ return (
657
+ <button
658
+ key={item.value}
659
+ type="button"
660
+ role={isMultiple ? 'checkbox' : 'radio'}
661
+ aria-checked={isSelected}
662
+ aria-disabled={isDisabled || undefined}
663
+ data-value={item.value}
664
+ onClick={() => {
665
+ if (!isDisabled) {
666
+ onToggle(item.value, isSelected);
667
+ }
668
+ }}
669
+ {...stylex.props(
670
+ focusOutlineStyles.focusVisible,
671
+ styles.choiceRow,
672
+ isDisabled && styles.choiceRowDisabled,
673
+ )}>
674
+ {isRenderable(item.icon) && (
675
+ <span aria-hidden="true" {...stylex.props(styles.choiceIcon)}>
676
+ {item.icon}
677
+ </span>
678
+ )}
679
+ <Text
680
+ type="body"
681
+ color={isDisabled ? 'inherit' : undefined}
682
+ xstyle={styles.choiceLabel}>
683
+ {item.label}
684
+ </Text>
685
+ {isMultiple ? (
686
+ <CheckboxIndicator
687
+ state={isSelected ? 'checked' : 'unchecked'}
688
+ size="md"
689
+ isDisabled={isDisabled}
690
+ />
691
+ ) : (
692
+ <RadioIndicator
693
+ state={isSelected ? 'checked' : 'unchecked'}
694
+ size="md"
695
+ isDisabled={isDisabled}
696
+ />
697
+ )}
698
+ </button>
699
+ );
700
+ })}
701
+ </div>
702
+ );
703
+ }
704
+
705
+ /**
706
+ * The value control for one filter inside the value step. Closed vocabularies
707
+ * are rows here; every other type is the popover presentation's own editor in
708
+ * its sheet presentation.
709
+ */
710
+ function SheetValueEditor({
711
+ operatorValue,
712
+ filterValue,
713
+ onChange,
714
+ onUnstage,
715
+ config,
716
+ fieldLabel,
717
+ isDisabled,
718
+ maxMenuItems,
719
+ editors,
720
+ }: {
721
+ operatorValue: OperatorValue;
722
+ filterValue: FilterValue | undefined;
723
+ onChange: (value: FilterValue) => void;
724
+ onUnstage: () => void;
725
+ config: InternalConfig;
726
+ fieldLabel: string;
727
+ isDisabled: boolean;
728
+ maxMenuItems?: number;
729
+ editors: PowerSearchSheetEditors;
730
+ }) {
731
+ const {buildRelativeDateOptions, PowerSearchValueEditor} = editors;
732
+ const t = useComponentTranslator();
733
+ const selectedValues = useMemo<ReadonlySet<string>>(() => {
734
+ if (filterValue?.type === 'enum' || filterValue?.type === 'date_relative') {
735
+ return new Set([filterValue.value]);
736
+ }
737
+ if (filterValue?.type === 'enum_list') {
738
+ return new Set(filterValue.value);
739
+ }
740
+ return new Set();
741
+ }, [filterValue]);
742
+
743
+ switch (operatorValue.type) {
744
+ case 'empty':
745
+ case 'nested':
746
+ return null;
747
+ case 'enum':
748
+ return (
749
+ <ChoiceRows
750
+ items={operatorValue.values}
751
+ selected={selectedValues}
752
+ isDisabled={isDisabled}
753
+ isMultiple={false}
754
+ label={fieldLabel}
755
+ onToggle={value => onChange({type: 'enum', value})}
756
+ />
757
+ );
758
+ case 'enum_list':
759
+ return (
760
+ <ChoiceRows
761
+ items={operatorValue.values}
762
+ selected={selectedValues}
763
+ isDisabled={isDisabled}
764
+ isMultiple
765
+ label={fieldLabel}
766
+ onToggle={(value, isSelected) => {
767
+ const existing =
768
+ filterValue?.type === 'enum_list' ? filterValue.value : [];
769
+ onChange({
770
+ type: 'enum_list',
771
+ value: isSelected
772
+ ? existing.filter(v => v !== value)
773
+ : [...existing, value],
774
+ });
775
+ }}
776
+ />
777
+ );
778
+ case 'date_relative':
779
+ return (
780
+ <ChoiceRows
781
+ items={buildRelativeDateOptions(operatorValue, t)}
782
+ selected={selectedValues}
783
+ isDisabled={isDisabled}
784
+ isMultiple={false}
785
+ label={fieldLabel}
786
+ onToggle={value => onChange({type: 'date_relative', value})}
787
+ />
788
+ );
789
+ case 'string':
790
+ case 'string_list':
791
+ case 'integer':
792
+ case 'float':
793
+ case 'time':
794
+ case 'date_absolute':
795
+ case 'date_range':
796
+ case 'entity_list':
797
+ case 'custom':
798
+ return (
799
+ <div {...stylex.props(styles.editorInput)}>
800
+ <PowerSearchValueEditor
801
+ operatorValue={operatorValue}
802
+ filterValue={filterValue}
803
+ onChange={onChange}
804
+ onUnstage={onUnstage}
805
+ config={config}
806
+ maxMenuItems={maxMenuItems}
807
+ isDisabled={isDisabled}
808
+ presentation="bottom-sheet"
809
+ fieldLabel={fieldLabel}
810
+ />
811
+ </div>
812
+ );
813
+ }
814
+ }
815
+
816
+ // =============================================================================
817
+ // Component
818
+ // =============================================================================
819
+
820
+ /**
821
+ * The sheet flow of PowerSearch's touch presentation: Filters, Add filter,
822
+ * and the value step, as standalone sheets that stack, each open beneath the
823
+ * step it led to.
824
+ */
825
+ export function PowerSearchBottomSheet({
826
+ isOpen,
827
+ onOpenChange,
828
+ finalFocusRef,
829
+ resultCountText,
830
+ config,
831
+ configProp,
832
+ filters,
833
+ onChange,
834
+ searchSource,
835
+ placeholder,
836
+ isReadOnly,
837
+ isDisabled,
838
+ hasClear,
839
+ maxOperatorMenuItems,
840
+ maxSearchResults,
841
+ saveButtonLabel: saveButtonLabelFromProps,
842
+ components: componentOverrides,
843
+ editors,
844
+ }: PowerSearchBottomSheetProps) {
845
+ const {NestedEditor} = editors;
846
+ const t = useComponentTranslator();
847
+ const locale = useLocale();
848
+ const formatList = useListFormatter();
849
+ const isInteractive = !isDisabled && !isReadOnly;
850
+
851
+ const contentSearchFieldKey = config.config.contentSearchFieldKey;
852
+ const contentSearchOperator =
853
+ contentSearchFieldKey == null
854
+ ? undefined
855
+ : config.getDefaultOperator(contentSearchFieldKey);
856
+ const hasContentSearch = contentSearchOperator?.value.type === 'string';
857
+ const suggestionSource = useMemo(
858
+ () => createSheetSuggestionSource(config, searchSource),
859
+ [config, searchSource],
860
+ );
861
+
862
+ const contentResultsId = useId();
863
+ const managerAddButtonRef = useRef<HTMLButtonElement>(null);
864
+ const contentSearchRef = useRef<HTMLDivElement>(null);
865
+ const fieldSearchRef = useRef<HTMLDivElement>(null);
866
+ // The Add filter sheet's panel: the fallback focus target when the control
867
+ // a step came from is gone — its first focusable control, which is the
868
+ // search field when one shows, else the first field row.
869
+ const fieldsSheetRef = useRef<HTMLDivElement>(null);
870
+ // The content search and its suggestion rows are one vertical list for the
871
+ // arrow keys: ArrowDown from the searchbox reaches the first suggestion,
872
+ // ArrowUp from the first suggestion returns to the searchbox, and the ends
873
+ // do not wrap. Home and End stay with the searchbox's caret.
874
+ const contentListFocus = useInternalListFocus<HTMLDivElement>({
875
+ itemSelector: `[role="searchbox"], [id="${contentResultsId}"] button`,
876
+ wrap: false,
877
+ hasHomeEnd: false,
878
+ });
879
+ const fieldsSheetCallbackRef = useMergedRefs(
880
+ fieldsSheetRef,
881
+ contentListFocus.listRef,
882
+ );
883
+ const handleContentListKeyDown = (event: React.KeyboardEvent) => {
884
+ if (!isImeKeyEvent(event.nativeEvent)) {
885
+ contentListFocus.handleKeyDown(event);
886
+ }
887
+ };
888
+ const manageSheetRef = useRef<HTMLDivElement>(null);
889
+ // Where focus was inside the Filters or Add filter sheet, read on every
890
+ // focus change there, so a controlled update that unmounts the focused
891
+ // control (a filter's row, a dropped field's row, Clear all after the last
892
+ // filter) can put focus on the nearest remaining row by that index, else
893
+ // the sheet's first control, else the sheet panel. A removed element
894
+ // fires no blur, so the position is what the effect below reads.
895
+ const lastSheetFocusRef = useRef<{
896
+ sheet: 'manage' | 'fields';
897
+ rowIndex: number | null;
898
+ } | null>(null);
899
+ // One index space for the record and the recovery: rows that are buttons
900
+ // (a plain read-only row is passed over, as the removal and Apply/Cancel
901
+ // rules pass it over), in document order.
902
+ const buttonRowsOf = (panel: HTMLElement): HTMLElement[] =>
903
+ Array.from(panel.querySelectorAll<HTMLLIElement>('li'))
904
+ .map(row => row.querySelector<HTMLElement>('button'))
905
+ .filter((button): button is HTMLElement => button != null);
906
+ const noteSheetFocus = useCallback(
907
+ (sheet: 'manage' | 'fields') => (event: React.FocusEvent) => {
908
+ const row = (event.target as HTMLElement).closest('li');
909
+ const button = row?.querySelector<HTMLElement>('button') ?? null;
910
+ const rowIndex =
911
+ button == null
912
+ ? -1
913
+ : buttonRowsOf(event.currentTarget as HTMLElement).indexOf(button);
914
+ lastSheetFocusRef.current = {
915
+ sheet,
916
+ rowIndex: rowIndex === -1 ? null : rowIndex,
917
+ };
918
+ },
919
+ [],
920
+ );
921
+ const managerRowsRef = useRef(new Map<number, HTMLLIElement>());
922
+ const fieldRowsRef = useRef(new Map<string, HTMLLIElement>());
923
+ const latestFiltersRef = useRef(filters);
924
+ const pendingSheetFocusRef = useRef<PendingSheetFocus | null>(null);
925
+ const pendingMutationFocusRef = useRef(false);
926
+
927
+ // The step an open starts on: Add filter directly when an interactive field
928
+ // has nothing to manage yet, otherwise Filters. Neither search field takes
929
+ // focus on open, so the software keyboard stays down until the person taps
930
+ // the search. Add filter opened directly is the flow's entry point: no
931
+ // Filters sheet beneath it, and Done in its footer.
932
+ const isEntryAddFilter = filters.length === 0 && isInteractive;
933
+ const [step, setStep] = useState<SheetStep | null>(() =>
934
+ isOpen ? (isEntryAddFilter ? 'fields' : 'manage') : null,
935
+ );
936
+ const [fieldPickerOrigin, setFieldPickerOrigin] = useState<
937
+ 'manage' | 'trigger'
938
+ >(() => (isOpen && isEntryAddFilter ? 'trigger' : 'manage'));
939
+ // The current step, read by the sheets' close reports and by a removal that
940
+ // decides where to speak.
941
+ const stepRef = useRef(step);
942
+ useLayoutEffect(() => {
943
+ stepRef.current = step;
944
+ }, [step]);
945
+ // The draft outlives a step change on purpose: a closing value step stays
946
+ // presented through its exit, and clearing the draft with the step would
947
+ // blank that sheet mid-transition.
948
+ const [draft, setDraft] = useState<FilterDraft | null>(null);
949
+ const draftGenerationRef = useRef(0);
950
+ const nextDraftGeneration = useCallback(() => {
951
+ draftGenerationRef.current += 1;
952
+ return draftGenerationRef.current;
953
+ }, []);
954
+ const [fieldQuery, setFieldQuery] = useState('');
955
+ const [contentQuery, setContentQuery] = useState('');
956
+ const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);
957
+ const clearAllButtonRef = useRef<HTMLButtonElement>(null);
958
+ // Set while Clear all commits, so the result count that changes in that
959
+ // commit is spoken with Clear all's outcome, as one message.
960
+ const isClearingRef = useRef(false);
961
+
962
+ // `useAnnounce` delivers inside the open Astryx modal that encloses its
963
+ // caller, and this component renders above the
964
+ // sheets, so it cannot call the hook itself. Each step's body renders a
965
+ // `SheetAnnouncer` inside its BottomSheet, which publishes the dialog's own
966
+ // `announce` here while that step is the active one; the effects below
967
+ // speak through it, so every message about a sheet's content is delivered
968
+ // in that sheet's dialog.
969
+ const announceRef = useRef<AnnounceFn | null>(null);
970
+ const handleAnnounceChange = useCallback((next: AnnounceFn | null) => {
971
+ announceRef.current = next;
972
+ }, []);
973
+ const announce = useCallback((message: string) => {
974
+ announceRef.current?.(message);
975
+ }, []);
976
+ const pendingAnnouncementRef = useRef<string | null>(null);
977
+
978
+ // The controlled `isOpen` opens and closes the flow; the step follows it in
979
+ // the render that sees the change, not an effect, so the entry step's sheet
980
+ // opens in the same commit as the flow (React's adjust-state-on-
981
+ // prop-change pattern). Closing from outside — the field became disabled —
982
+ // ends the flow wherever it was, the Clear all confirmation included.
983
+ const [wasOpen, setWasOpen] = useState(isOpen);
984
+ if (isOpen !== wasOpen) {
985
+ setWasOpen(isOpen);
986
+ if (isOpen) {
987
+ setFieldQuery('');
988
+ setContentQuery('');
989
+ setStep(isEntryAddFilter ? 'fields' : 'manage');
990
+ setFieldPickerOrigin(isEntryAddFilter ? 'trigger' : 'manage');
991
+ } else {
992
+ setStep(null);
993
+ setIsClearConfirmationOpen(false);
994
+ }
995
+ }
996
+
997
+ const closeFlow = useCallback(() => {
998
+ pendingSheetFocusRef.current = null;
999
+ setStep(null);
1000
+ onOpenChange(false);
1001
+ }, [onOpenChange]);
1002
+
1003
+ // Whether a Filters row is a button: the field interactive and the
1004
+ // filter not read-only. The row opens the value step — the editor for its
1005
+ // operator's value type, the built-in nested editor for a `nested` one, or
1006
+ // for a filter the config no longer knows the unavailable state — and its
1007
+ // trailing remove action removes it, as the popover's token has its × for
1008
+ // it.
1009
+ const isRowButton = useCallback(
1010
+ (filter: PowerSearchFilter): boolean => !filter.isReadOnly && isInteractive,
1011
+ [isInteractive],
1012
+ );
1013
+
1014
+ // ------------------------------------------------------------------ focus --
1015
+
1016
+ // The control a step change named also becomes where the closing step
1017
+ // sheets return focus when their exit ends: a closing sheet that held focus
1018
+ // keeps it until then, and BottomSheet then returns it, so the named control
1019
+ // receives it even when the first move could not land. With no control
1020
+ // named, the closing steps return focus as the flow does.
1021
+ const stepReturnTargetRef = useRef<HTMLElement | null>(null);
1022
+ const stepFinalFocusRef = useMemo<React.RefObject<HTMLElement | null>>(
1023
+ () => ({
1024
+ get current() {
1025
+ return stepReturnTargetRef.current ?? finalFocusRef.current;
1026
+ },
1027
+ }),
1028
+ [finalFocusRef],
1029
+ );
1030
+ const placeFocus = (element: HTMLElement | null | undefined) => {
1031
+ if (element == null) {
1032
+ return;
1033
+ }
1034
+ stepReturnTargetRef.current = element;
1035
+ element.focus({preventScroll: true});
1036
+ };
1037
+ const focusPendingSheetTarget = useCallback(() => {
1038
+ const target = pendingSheetFocusRef.current;
1039
+ if (target == null) {
1040
+ return;
1041
+ }
1042
+ pendingSheetFocusRef.current = null;
1043
+ if (target.type === 'manager-add') {
1044
+ placeFocus(managerAddButtonRef.current);
1045
+ return;
1046
+ }
1047
+ // Add filter's fallback: a controlled update may have removed the field
1048
+ // whose row opened the step, or the content-search field itself; the
1049
+ // sheet's first focusable control then takes focus — the search field
1050
+ // when one shows, else the first field row.
1051
+ const firstFieldsControl = () => {
1052
+ const panel = fieldsSheetRef.current;
1053
+ return (
1054
+ panel?.querySelector<HTMLElement>('input') ??
1055
+ panel?.querySelector<HTMLElement>('li button') ??
1056
+ panel?.querySelector<HTMLElement>('button') ??
1057
+ null
1058
+ );
1059
+ };
1060
+ if (target.type === 'content-search') {
1061
+ placeFocus(
1062
+ contentSearchRef.current?.querySelector<HTMLInputElement>('input') ??
1063
+ firstFieldsControl(),
1064
+ );
1065
+ return;
1066
+ }
1067
+ if (target.type === 'field') {
1068
+ placeFocus(
1069
+ fieldRowsRef.current
1070
+ .get(target.fieldKey)
1071
+ ?.querySelector<HTMLButtonElement>('button') ?? firstFieldsControl(),
1072
+ );
1073
+ return;
1074
+ }
1075
+ // The row the step came from, followed across a controlled reorder or
1076
+ // clone; when a controlled update removed it, or left two filters it
1077
+ // could be, the nearest remaining row that is a button, as after a
1078
+ // removal; else Add filter.
1079
+ const index =
1080
+ resolveFilterIdentityIndex(
1081
+ latestFiltersRef.current,
1082
+ target.sourceFilter,
1083
+ target.sourceSignature,
1084
+ target.preferredIndex,
1085
+ ) ??
1086
+ nearestEditableIndex(
1087
+ latestFiltersRef.current,
1088
+ target.preferredIndex,
1089
+ isRowButton,
1090
+ );
1091
+ const row = index == null ? null : managerRowsRef.current.get(index);
1092
+ const rowButton =
1093
+ target.part === 'remove'
1094
+ ? (row?.querySelector<HTMLButtonElement>('[data-sheet-remove]') ??
1095
+ row?.querySelector<HTMLButtonElement>('button'))
1096
+ : row?.querySelector<HTMLButtonElement>('button');
1097
+ placeFocus(rowButton ?? managerAddButtonRef.current);
1098
+ }, [isRowButton]);
1099
+
1100
+ // A controlled update that unmounts the focused control of the Filters or
1101
+ // Add filter sheet leaves focus on the page body inside the open modal.
1102
+ // Read before paint on every commit of an open step: when focus is no
1103
+ // longer inside the sheet's dialog, the nearest remaining row by the last
1104
+ // focused index takes it, else the sheet's first control, else its panel.
1105
+ // The pending-target effects below run after and win when a step
1106
+ // change named a control.
1107
+ useLayoutEffect(() => {
1108
+ const last = lastSheetFocusRef.current;
1109
+ if (step !== 'manage' && step !== 'fields') {
1110
+ return;
1111
+ }
1112
+ if (last == null || last.sheet !== step) {
1113
+ return;
1114
+ }
1115
+ const panel =
1116
+ step === 'manage' ? manageSheetRef.current : fieldsSheetRef.current;
1117
+ const dialog = panel?.closest('dialog');
1118
+ const active = document.activeElement;
1119
+ if (
1120
+ panel == null ||
1121
+ dialog == null ||
1122
+ (active != null && active !== document.body && dialog.contains(active))
1123
+ ) {
1124
+ return;
1125
+ }
1126
+ const rowButtons = buttonRowsOf(panel);
1127
+ let target: HTMLElement | null = null;
1128
+ if (last.rowIndex != null && rowButtons.length > 0) {
1129
+ // The following button row, else the last.
1130
+ target = rowButtons[Math.min(last.rowIndex, rowButtons.length - 1)];
1131
+ }
1132
+ target ??=
1133
+ panel.querySelector<HTMLElement>('input') ??
1134
+ rowButtons[0] ??
1135
+ panel.querySelector<HTMLElement>('button') ??
1136
+ null;
1137
+ if (target != null) {
1138
+ target.focus({preventScroll: true});
1139
+ } else {
1140
+ const focusable = dialog.querySelector<HTMLElement>('[tabindex="-1"]');
1141
+ (focusable ?? dialog).focus({preventScroll: true});
1142
+ }
1143
+ });
1144
+
1145
+ // Both Effects move focus inside the entering sheet — the external system
1146
+ // is the document's focus — to the control the step named. They run after
1147
+ // the entering sheet's own
1148
+ // panel focus (child effects commit first), so the intended control wins,
1149
+ // and they acquire nothing, so they need no cleanup. The filters effect is
1150
+ // declared first so a mutation that lands in the same commit as the step
1151
+ // change resolves its row against the new filters.
1152
+ useEffect(() => {
1153
+ latestFiltersRef.current = filters;
1154
+ if (step === 'manage' && pendingMutationFocusRef.current) {
1155
+ pendingMutationFocusRef.current = false;
1156
+ focusPendingSheetTarget();
1157
+ }
1158
+ }, [filters, focusPendingSheetTarget, step]);
1159
+
1160
+ // A target still pending when the flow closes, such as a commit that
1161
+ // disabled the field, never carries into the next open.
1162
+ useEffect(() => {
1163
+ if (step == null) {
1164
+ stepReturnTargetRef.current = null;
1165
+ pendingSheetFocusRef.current = null;
1166
+ return;
1167
+ }
1168
+ // A step that opens starts with no named return target; a return to
1169
+ // Filters keeps the one its commit, or its removal, has just named.
1170
+ if (step !== 'manage') {
1171
+ stepReturnTargetRef.current = null;
1172
+ }
1173
+ focusPendingSheetTarget();
1174
+ }, [focusPendingSheetTarget, step]);
1175
+
1176
+ // An announcement queued by a step change — a suggestion or a removal that
1177
+ // changed the filters — is spoken in the commit that shows the next step,
1178
+ // so it lands in that step's dialog region rather than the one about to
1179
+ // close. It synchronizes the live region named above and acquires nothing.
1180
+ useEffect(() => {
1181
+ const message = pendingAnnouncementRef.current;
1182
+ if (step != null && message != null) {
1183
+ pendingAnnouncementRef.current = null;
1184
+ announce(message);
1185
+ }
1186
+ }, [announce, step]);
1187
+
1188
+ // ----------------------------------------------------------------- fields --
1189
+
1190
+ // Every visible field lists: the value step edits every operator's value,
1191
+ // `nested` through the popover's built-in editor.
1192
+ const fields = useMemo(() => config.getVisibleFields(), [config]);
1193
+
1194
+ const normalizedFieldQuery = fieldQuery.trim().toLowerCase();
1195
+ const matchingFields = useMemo(() => {
1196
+ const matches = fields.filter(field =>
1197
+ fieldMatchesQuery(field, normalizedFieldQuery),
1198
+ );
1199
+ return normalizedFieldQuery === ''
1200
+ ? matches
1201
+ : matches.slice(0, maxSearchResults);
1202
+ }, [fields, maxSearchResults, normalizedFieldQuery]);
1203
+
1204
+ // Ungrouped fields first, then each group in first-appearance order — the
1205
+ // same grouping the popover presentation's field suggestions use
1206
+ // (`groupItems` with `ungroupedFirst`), so the two presentations
1207
+ // list a config's fields in one order.
1208
+ const groupedFields = useMemo(
1209
+ () =>
1210
+ matchingFields.length === 0
1211
+ ? []
1212
+ : groupItems(
1213
+ matchingFields.map(field => ({
1214
+ id: field.key,
1215
+ label: field.label,
1216
+ auxiliaryData: {group: field.group},
1217
+ field,
1218
+ })),
1219
+ {ungroupedFirst: true},
1220
+ ).map(
1221
+ group =>
1222
+ [
1223
+ group.heading ?? '',
1224
+ group.items.map(item => item.field),
1225
+ ] as const,
1226
+ ),
1227
+ [matchingFields],
1228
+ );
1229
+
1230
+ const isFieldSearchShown = fields.length >= SEARCHABLE_FIELD_COUNT;
1231
+
1232
+ // A field whose only operator takes an `empty` value is a one-tap filter:
1233
+ // its row adds it with no value step, and shows a plus, not a chevron.
1234
+ const isImmediateAddField = useCallback(
1235
+ (field: PowerSearchField): boolean => {
1236
+ const operators = config.getVisibleOperators(field.key);
1237
+ return operators.length === 1 && operators[0].value.type === 'empty';
1238
+ },
1239
+ [config],
1240
+ );
1241
+
1242
+ // The steps stack: each opens above the sheet that led to it, which stays
1243
+ // open beneath. Add filter entered directly has no Filters sheet beneath.
1244
+ const isFieldPickerDirectEntry = fieldPickerOrigin === 'trigger';
1245
+ const isManageSheetOpen =
1246
+ step === 'manage' ||
1247
+ (step === 'fields' && !isFieldPickerDirectEntry) ||
1248
+ (step === 'value' && (draft?.mode === 'edit' || !isFieldPickerDirectEntry));
1249
+ const isFieldsSheetOpen =
1250
+ step === 'fields' || (step === 'value' && draft?.mode === 'create');
1251
+
1252
+ // The suggestions derive synchronously from the config, so a list never
1253
+ // waits on a request: an empty list means an empty result, not a pending
1254
+ // one. They stay listed while the value step covers Add filter.
1255
+ const contentResults = useMemo(() => {
1256
+ if (!isFieldsSheetOpen || !hasContentSearch || !isInteractive) {
1257
+ return [];
1258
+ }
1259
+ const results =
1260
+ contentQuery.trim() === ''
1261
+ ? suggestionSource.bootstrap()
1262
+ : suggestionSource.search(contentQuery);
1263
+ return results.slice(0, MAX_BROWSE_MENU_ITEMS);
1264
+ }, [
1265
+ contentQuery,
1266
+ hasContentSearch,
1267
+ isFieldsSheetOpen,
1268
+ isInteractive,
1269
+ suggestionSource,
1270
+ ]);
1271
+
1272
+ // The field's result count, while a sheet is open: the owner's own Effect
1273
+ // is quiet then, so the change is spoken here, inside the dialog. Only a
1274
+ // change after the flow opened is spoken.
1275
+ const announcedResultCountRef = useRef(resultCountText);
1276
+ // The latest result count, for Clear all's handler to read after its
1277
+ // commit has flushed.
1278
+ const latestResultCountRef = useRef(resultCountText);
1279
+ useLayoutEffect(() => {
1280
+ latestResultCountRef.current = resultCountText;
1281
+ }, [resultCountText]);
1282
+ useEffect(() => {
1283
+ if (
1284
+ isClearingRef.current ||
1285
+ resultCountText === announcedResultCountRef.current
1286
+ ) {
1287
+ return;
1288
+ }
1289
+ announcedResultCountRef.current = resultCountText;
1290
+ if (step != null && resultCountText != null) {
1291
+ announce(resultCountText);
1292
+ }
1293
+ }, [announce, resultCountText, step]);
1294
+
1295
+ // ------------------------------------------------------------------ draft --
1296
+
1297
+ const draftField = draft ? config.getField(draft.field) : undefined;
1298
+ const draftOperator =
1299
+ draft?.operator != null
1300
+ ? config.getOperator(draft.field, draft.operator)
1301
+ : undefined;
1302
+ const draftOperators = useMemo(
1303
+ () => (draft ? config.getVisibleOperators(draft.field) : []),
1304
+ [config, draft],
1305
+ );
1306
+
1307
+ // The two parts of a Filters row's text for `filter`: "{field} {operator}"
1308
+ // as one catalog message, and the value as the popover presentation's
1309
+ // token shows it — the same function, so the same words and the same zone
1310
+ // handling, before the token's width budget. The rows render these, and
1311
+ // the removal announcement joins them, so the three can never
1312
+ // disagree.
1313
+ const describeFilterParts = useCallback(
1314
+ (filter: PowerSearchFilter): {label: string; value: string | null} => {
1315
+ const field = config.getField(filter.field);
1316
+ const operator = config.getOperator(filter.field, filter.operator);
1317
+ // A filter whose field or operator the config no longer has still
1318
+ // lists, by its raw keys, as its token does on the trigger; its row
1319
+ // opens the unavailable step, and its trailing remove action removes
1320
+ // it.
1321
+ const fieldLabel = field?.label ?? filter.field;
1322
+ const operatorLabel =
1323
+ operator == null ? filter.operator : resolveOperatorLabel(operator, t);
1324
+ const label = operatorLabel
1325
+ ? t('@astryx.powersearch.sheet.fieldOperator', {
1326
+ field: fieldLabel,
1327
+ operator: operatorLabel,
1328
+ })
1329
+ : fieldLabel;
1330
+ if (operator == null) {
1331
+ return {label, value: null};
1332
+ }
1333
+ // A relative-date value is stored as a key (`3d_ago`); the row reads it
1334
+ // as the value step's choice row does ("3 days ago"), through the
1335
+ // catalog's relative-date messages, so the sheet agrees with itself. The popover token
1336
+ // shows the stored key (a known gap of the record).
1337
+ const value =
1338
+ operator.value.type === 'date_relative' &&
1339
+ filter.value.type === 'date_relative'
1340
+ ? resolveRelativeDateLabel(
1341
+ operator.value,
1342
+ filter.value.value,
1343
+ t,
1344
+ editors.buildRelativeDateOptions,
1345
+ )
1346
+ : formatTokenValueText(
1347
+ operator.value,
1348
+ filter.value,
1349
+ Number.MAX_SAFE_INTEGER,
1350
+ locale,
1351
+ t,
1352
+ formatList,
1353
+ );
1354
+ return {label, value};
1355
+ },
1356
+ [config, editors, formatList, locale, t],
1357
+ );
1358
+ const describeFilter = useCallback(
1359
+ (filter: PowerSearchFilter): string => {
1360
+ const parts = describeFilterParts(filter);
1361
+ return parts.value
1362
+ ? t('@astryx.powersearch.sheet.labelValue', {
1363
+ label: parts.label,
1364
+ value: parts.value,
1365
+ })
1366
+ : parts.label;
1367
+ },
1368
+ [describeFilterParts, t],
1369
+ );
1370
+
1371
+ const openFieldList = useCallback(() => {
1372
+ if (!isInteractive) {
1373
+ return;
1374
+ }
1375
+ setFieldPickerOrigin('manage');
1376
+ setFieldQuery('');
1377
+ setContentQuery('');
1378
+ pendingSheetFocusRef.current = null;
1379
+ setStep('fields');
1380
+ }, [isInteractive]);
1381
+
1382
+ const queueManagerAddFocus = useCallback(() => {
1383
+ pendingSheetFocusRef.current = {type: 'manager-add'};
1384
+ }, []);
1385
+
1386
+ const commitSavedFilter = useCallback(
1387
+ (next: FilterDraft, filter: PowerSearchFilter) => {
1388
+ if (!isInteractive) {
1389
+ queueManagerAddFocus();
1390
+ setStep('manage');
1391
+ return;
1392
+ }
1393
+ if (next.mode === 'edit') {
1394
+ const filterIndex = resolveDraftFilterIndex(filters, next);
1395
+ const currentFilter =
1396
+ filterIndex == null ? undefined : filters[filterIndex];
1397
+ if (
1398
+ filterIndex == null ||
1399
+ currentFilter == null ||
1400
+ currentFilter.isReadOnly
1401
+ ) {
1402
+ // A controlled update removed the edited filter, or left two it
1403
+ // could be, or made it read-only: nothing is written, and focus
1404
+ // returns to the nearest row that is a button around where it was,
1405
+ // else Add filter.
1406
+ pendingSheetFocusRef.current =
1407
+ next.sourceFilter != null &&
1408
+ next.sourceSignature != null &&
1409
+ next.filterIndex != null
1410
+ ? {
1411
+ type: 'manager-filter',
1412
+ sourceFilter: next.sourceFilter,
1413
+ sourceSignature: next.sourceSignature,
1414
+ preferredIndex: next.filterIndex,
1415
+ }
1416
+ : {type: 'manager-add'};
1417
+ setStep('manage');
1418
+ return;
1419
+ }
1420
+ pendingSheetFocusRef.current = {
1421
+ type: 'manager-filter',
1422
+ sourceFilter: filter,
1423
+ sourceSignature: filterSignature(filter),
1424
+ preferredIndex: filterIndex,
1425
+ };
1426
+ const updated = [...filters];
1427
+ updated[filterIndex] = filter;
1428
+ onChange(updated, 'edit', filterIndex);
1429
+ } else {
1430
+ queueManagerAddFocus();
1431
+ onChange([...filters, filter], 'add', filters.length);
1432
+ }
1433
+ setStep('manage');
1434
+ },
1435
+ [filters, isInteractive, onChange, queueManagerAddFocus],
1436
+ );
1437
+
1438
+ // Opening a new filter can come from a field row or a content-search
1439
+ // suggestion. The origin is kept so Cancel returns to the control the person
1440
+ // came from.
1441
+ const openCreateEditor = useCallback(
1442
+ (
1443
+ field: PowerSearchField,
1444
+ operator: PowerSearchOperator,
1445
+ returnFocus: 'field' | 'content-search' = 'field',
1446
+ ) => {
1447
+ setDraft({
1448
+ mode: 'create',
1449
+ generation: nextDraftGeneration(),
1450
+ returnFocus,
1451
+ field: field.key,
1452
+ operator: operator.key,
1453
+ value: operator.value.type === 'empty' ? {type: 'empty'} : undefined,
1454
+ });
1455
+ pendingSheetFocusRef.current = null;
1456
+ setStep('value');
1457
+ },
1458
+ [nextDraftGeneration],
1459
+ );
1460
+
1461
+ const handleFieldSelect = useCallback(
1462
+ (field: PowerSearchField) => {
1463
+ if (!isInteractive) {
1464
+ return;
1465
+ }
1466
+ // A one-tap filter has nothing to stage: choosing its field adds it
1467
+ // and returns to Filters.
1468
+ if (isImmediateAddField(field)) {
1469
+ const [operator] = config.getVisibleOperators(field.key);
1470
+ const nextFilter: PowerSearchFilter = {
1471
+ field: field.key,
1472
+ operator: operator.key,
1473
+ value: {type: 'empty'},
1474
+ };
1475
+ pendingSheetFocusRef.current = {
1476
+ type: 'manager-filter',
1477
+ sourceFilter: nextFilter,
1478
+ sourceSignature: filterSignature(nextFilter),
1479
+ preferredIndex: filters.length,
1480
+ };
1481
+ pendingMutationFocusRef.current = true;
1482
+ onChange([...filters, nextFilter], 'add', filters.length);
1483
+ pendingAnnouncementRef.current = t('@astryx.tokenizer.tokenAdded', {
1484
+ label: describeFilter(nextFilter),
1485
+ });
1486
+ setStep('manage');
1487
+ return;
1488
+ }
1489
+ const operator =
1490
+ config.getDefaultOperator(field.key) ?? field.operators[0];
1491
+ if (operator == null) {
1492
+ return;
1493
+ }
1494
+ openCreateEditor(field, operator);
1495
+ },
1496
+ [
1497
+ config,
1498
+ describeFilter,
1499
+ filters,
1500
+ isImmediateAddField,
1501
+ isInteractive,
1502
+ onChange,
1503
+ openCreateEditor,
1504
+ t,
1505
+ ],
1506
+ );
1507
+
1508
+ const handleContentSuggestionSelect = useCallback(
1509
+ (item: PowerSearchItem | null) => {
1510
+ if (!isInteractive || item?.auxiliaryData == null) {
1511
+ return;
1512
+ }
1513
+ const {fieldKey, filterValue, operatorKey} = item.auxiliaryData;
1514
+ const field = config.getField(fieldKey);
1515
+ const operator =
1516
+ operatorKey == null
1517
+ ? config.getDefaultOperator(fieldKey)
1518
+ : config.getOperator(fieldKey, operatorKey);
1519
+ if (field == null || operator == null) {
1520
+ return;
1521
+ }
1522
+ setContentQuery('');
1523
+ if (filterValue != null) {
1524
+ const nextFilter: PowerSearchFilter = {
1525
+ field: field.key,
1526
+ operator: operator.key,
1527
+ value: filterValue,
1528
+ };
1529
+ pendingSheetFocusRef.current = {
1530
+ type: 'manager-filter',
1531
+ sourceFilter: nextFilter,
1532
+ sourceSignature: filterSignature(nextFilter),
1533
+ preferredIndex: filters.length,
1534
+ };
1535
+ pendingMutationFocusRef.current = true;
1536
+ onChange([...filters, nextFilter], 'add', filters.length);
1537
+ // The same announcement the popover presentation's typeahead add
1538
+ // makes, so assistive technology hears one phrase for one outcome;
1539
+ // spoken once the Filters sheet is the open dialog.
1540
+ pendingAnnouncementRef.current = t('@astryx.tokenizer.tokenAdded', {
1541
+ label: item.label,
1542
+ });
1543
+ setStep('manage');
1544
+ return;
1545
+ }
1546
+ openCreateEditor(field, operator, 'content-search');
1547
+ },
1548
+ [config, filters, isInteractive, onChange, openCreateEditor, t],
1549
+ );
1550
+
1551
+ const handleFilterEdit = useCallback(
1552
+ (index: number) => {
1553
+ const filter = filters[index];
1554
+ if (!isInteractive || filter == null || filter.isReadOnly) {
1555
+ return;
1556
+ }
1557
+ setDraft({
1558
+ mode: 'edit',
1559
+ generation: nextDraftGeneration(),
1560
+ filterIndex: index,
1561
+ sourceFilter: filter,
1562
+ sourceSignature: filterSignature(filter),
1563
+ field: filter.field,
1564
+ operator: filter.operator,
1565
+ value: filter.value,
1566
+ });
1567
+ pendingSheetFocusRef.current = null;
1568
+ setStep('value');
1569
+ },
1570
+ [filters, isInteractive, nextDraftGeneration],
1571
+ );
1572
+
1573
+ const handleRemoveFilter = useCallback(
1574
+ (index: number) => {
1575
+ const filter = filters[index];
1576
+ if (!isInteractive || filter == null || filter.isReadOnly) {
1577
+ return;
1578
+ }
1579
+ const nextFilters = filters.filter((_, i) => i !== index);
1580
+ const nextIndex = nearestEditableIndex(nextFilters, index, isRowButton);
1581
+ if (nextIndex == null) {
1582
+ pendingSheetFocusRef.current = {type: 'manager-add'};
1583
+ } else {
1584
+ const nextFilter = nextFilters[nextIndex];
1585
+ pendingSheetFocusRef.current = {
1586
+ type: 'manager-filter',
1587
+ sourceFilter: nextFilter,
1588
+ sourceSignature: filterSignature(nextFilter),
1589
+ preferredIndex: nextIndex,
1590
+ part: 'remove',
1591
+ };
1592
+ }
1593
+ pendingMutationFocusRef.current = true;
1594
+ onChange(nextFilters, 'remove', index);
1595
+ // The popover presentation's token × announces the same phrase. A
1596
+ // removal from a Filters row stays in that sheet and speaks at once; a
1597
+ // caller's Editor that removes while returning to Filters speaks once
1598
+ // the Filters sheet is the open dialog.
1599
+ const message = t('@astryx.tokenizer.tokenRemoved', {
1600
+ label: describeFilter(filter),
1601
+ });
1602
+ if (stepRef.current === 'manage') {
1603
+ announce(message);
1604
+ } else {
1605
+ pendingAnnouncementRef.current = message;
1606
+ }
1607
+ },
1608
+ [
1609
+ announce,
1610
+ describeFilter,
1611
+ filters,
1612
+ isInteractive,
1613
+ isRowButton,
1614
+ onChange,
1615
+ t,
1616
+ ],
1617
+ );
1618
+
1619
+ // Closing Clear all's confirmation. Kept, focus returns to Clear all.
1620
+ // Confirmed, Clear all removes the filters the person can edit and keeps
1621
+ // read-only ones, which are the consumer's: one `remove` at the first
1622
+ // removed index. The Filters sheet stays open for further editing. The
1623
+ // confirmation must be gone before focus moves into the sheet and the
1624
+ // outcome is routed into the sheet's region, so its close is flushed
1625
+ // first. The outcome is "Editable filters removed" while a read-only filter
1626
+ // remains, otherwise "All filters removed", joined with a result count that
1627
+ // changed in the same commit as one catalog message; focus moves to the
1628
+ // sheet's first remaining control: a kept read-only row has none, so Add
1629
+ // filter.
1630
+ const closeClearConfirmation = (confirmed: boolean) => {
1631
+ const kept = filters.filter(filter => filter.isReadOnly);
1632
+ const firstRemovedIndex = filters.findIndex(filter => !filter.isReadOnly);
1633
+ const isClearing = confirmed && isInteractive && firstRemovedIndex >= 0;
1634
+ isClearingRef.current = isClearing;
1635
+ try {
1636
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the confirmation must be gone before focus moves into the sheet and the words are routed into it
1637
+ flushSync(() => {
1638
+ setIsClearConfirmationOpen(false);
1639
+ if (isClearing) {
1640
+ onChange(kept, 'remove', firstRemovedIndex);
1641
+ }
1642
+ });
1643
+ } finally {
1644
+ isClearingRef.current = false;
1645
+ }
1646
+ if (!isClearing) {
1647
+ clearAllButtonRef.current?.focus();
1648
+ return;
1649
+ }
1650
+ managerAddButtonRef.current?.focus({preventScroll: true});
1651
+ const resultCount = latestResultCountRef.current;
1652
+ const changedCount =
1653
+ resultCount !== announcedResultCountRef.current ? resultCount : null;
1654
+ announcedResultCountRef.current = resultCount;
1655
+ if (kept.length > 0) {
1656
+ announce(
1657
+ changedCount == null
1658
+ ? t('@astryx.powersearch.editableFiltersRemoved')
1659
+ : t('@astryx.powersearch.sheet.editableFiltersClearedWithCount', {
1660
+ resultCount: changedCount,
1661
+ }),
1662
+ );
1663
+ } else {
1664
+ announce(
1665
+ changedCount == null
1666
+ ? t('@astryx.powersearch.allFiltersRemoved')
1667
+ : t('@astryx.powersearch.sheet.filtersClearedWithCount', {
1668
+ resultCount: changedCount,
1669
+ }),
1670
+ );
1671
+ }
1672
+ };
1673
+
1674
+ const handleOperatorSelect = useCallback((operator: PowerSearchOperator) => {
1675
+ setDraft(current => {
1676
+ if (current == null) {
1677
+ return current;
1678
+ }
1679
+ // A value survives an operator change only when the new operator
1680
+ // reads the same value type.
1681
+ const keepsValue =
1682
+ current.value != null && current.value.type === operator.value.type;
1683
+ return {
1684
+ ...current,
1685
+ operator: operator.key,
1686
+ value:
1687
+ operator.value.type === 'empty'
1688
+ ? {type: 'empty'}
1689
+ : keepsValue
1690
+ ? current.value
1691
+ : undefined,
1692
+ };
1693
+ });
1694
+ }, []);
1695
+
1696
+ const handleDraftValueChange = useCallback((value: FilterValue) => {
1697
+ setDraft(current => (current == null ? current : {...current, value}));
1698
+ }, []);
1699
+ // The number input's draft was cleared or stopped parsing: nothing stands
1700
+ // to confirm, so the confirm action disables again.
1701
+ const handleDraftUnstage = useCallback(() => {
1702
+ setDraft(current =>
1703
+ current == null ? current : {...current, value: undefined},
1704
+ );
1705
+ }, []);
1706
+
1707
+ const handleSave = useCallback(() => {
1708
+ if (draft?.value == null || draft.operator == null) {
1709
+ return;
1710
+ }
1711
+ commitSavedFilter(draft, {
1712
+ field: draft.field,
1713
+ operator: draft.operator,
1714
+ value: draft.value,
1715
+ });
1716
+ }, [commitSavedFilter, draft]);
1717
+
1718
+ const returnFromValue = useCallback(() => {
1719
+ if (draft == null) {
1720
+ queueManagerAddFocus();
1721
+ setStep('manage');
1722
+ return;
1723
+ }
1724
+ if (
1725
+ draft.mode === 'edit' &&
1726
+ draft.sourceFilter != null &&
1727
+ draft.sourceSignature != null &&
1728
+ draft.filterIndex != null
1729
+ ) {
1730
+ pendingSheetFocusRef.current = {
1731
+ type: 'manager-filter',
1732
+ sourceFilter: draft.sourceFilter,
1733
+ sourceSignature: draft.sourceSignature,
1734
+ preferredIndex:
1735
+ resolveDraftFilterIndex(filters, draft) ?? draft.filterIndex,
1736
+ };
1737
+ setStep('manage');
1738
+ return;
1739
+ }
1740
+ if (draft.returnFocus === 'content-search') {
1741
+ pendingSheetFocusRef.current = {type: 'content-search'};
1742
+ setStep('fields');
1743
+ return;
1744
+ }
1745
+ pendingSheetFocusRef.current = {type: 'field', fieldKey: draft.field};
1746
+ setStep('fields');
1747
+ }, [draft, filters, queueManagerAddFocus]);
1748
+
1749
+ const handleRemove = useCallback(() => {
1750
+ if (draft?.mode !== 'edit') {
1751
+ return;
1752
+ }
1753
+ const filterIndex = resolveDraftFilterIndex(filters, draft);
1754
+ if (filterIndex == null || filters[filterIndex]?.isReadOnly) {
1755
+ queueManagerAddFocus();
1756
+ setStep('manage');
1757
+ return;
1758
+ }
1759
+ handleRemoveFilter(filterIndex);
1760
+ setStep('manage');
1761
+ }, [draft, filters, handleRemoveFilter, queueManagerAddFocus]);
1762
+
1763
+ // Each step sheet is controlled by `step`; a sheet only ever asks to close
1764
+ // (a dismissal its `purpose` allows: Escape, the scrim, a swipe, a platform
1765
+ // close request), which only the top sheet of the stack receives. Closing
1766
+ // the top step reveals the step beneath it; closing the bottom one ends the
1767
+ // flow. A stale report from a step that is no longer current is ignored.
1768
+ // Every step change goes through the handlers above.
1769
+ const handleManageOpenChange = useCallback(
1770
+ (isSheetOpen: boolean) => {
1771
+ if (!isSheetOpen && stepRef.current === 'manage') {
1772
+ closeFlow();
1773
+ }
1774
+ },
1775
+ [closeFlow],
1776
+ );
1777
+ const handleFieldsOpenChange = useCallback(
1778
+ (isSheetOpen: boolean) => {
1779
+ if (isSheetOpen || stepRef.current !== 'fields') {
1780
+ return;
1781
+ }
1782
+ if (fieldPickerOrigin === 'trigger') {
1783
+ closeFlow();
1784
+ return;
1785
+ }
1786
+ queueManagerAddFocus();
1787
+ setStep('manage');
1788
+ },
1789
+ [closeFlow, fieldPickerOrigin, queueManagerAddFocus],
1790
+ );
1791
+ const handleValueOpenChange = useCallback(
1792
+ (isSheetOpen: boolean) => {
1793
+ if (!isSheetOpen && stepRef.current === 'value') {
1794
+ returnFromValue();
1795
+ }
1796
+ },
1797
+ [returnFromValue],
1798
+ );
1799
+
1800
+ // ---------------------------------------------------------------- render --
1801
+
1802
+ // Rows are keyed by filter identity, not position: a parent's reorder or a
1803
+ // removal above the focused row then moves elements instead of remounting
1804
+ // them, and focus stays on the same filter. Only a filter that is
1805
+ // itself removed loses its element, and the re-home effect above takes
1806
+ // over.
1807
+ const [filterIdentities] = useState(createFilterIdentities);
1808
+ const filterIds = filterIdentities.next(filters);
1809
+ const filterRows = filters.map((filter, index) => {
1810
+ const {label, value} = describeFilterParts(filter);
1811
+ const isEditable = isRowButton(filter);
1812
+ // The row reads from the same catalog message the removal announcement
1813
+ // uses (`labelValue`), so a locale that reorders it reorders both: the
1814
+ // message is formatted with a placeholder for the value, and the text
1815
+ // either side of that placeholder wraps the bold value.
1816
+ let displayLabel: ReactNode = label;
1817
+ if (value) {
1818
+ const [before, after] = t('@astryx.powersearch.sheet.labelValue', {
1819
+ label,
1820
+ value: ROW_VALUE_SLOT,
1821
+ }).split(ROW_VALUE_SLOT);
1822
+ displayLabel = (
1823
+ <>
1824
+ {before}
1825
+ <span {...stylex.props(styles.rowValue)}>{value}</span>
1826
+ {after}
1827
+ </>
1828
+ );
1829
+ }
1830
+ return {
1831
+ displayLabel,
1832
+ filter,
1833
+ index,
1834
+ isEditable,
1835
+ key: `filter-${filterIds[index]}`,
1836
+ };
1837
+ });
1838
+
1839
+ const hasRemovableFilter = filters.some(filter => !filter.isReadOnly);
1840
+ const isClearAllShown = hasClear && isInteractive && hasRemovableFilter;
1841
+
1842
+ const EditorOverride =
1843
+ draftOperator != null
1844
+ ? componentOverrides?.[draftOperator.value.type]?.Editor
1845
+ : undefined;
1846
+
1847
+ const draftOperatorLabel =
1848
+ draftOperator == null ? '' : resolveOperatorLabel(draftOperator, t);
1849
+ // The title names the filter's own operator when the step offers no
1850
+ // Operator group: one visible operator, or an operator the config no longer
1851
+ // lists as visible. The step then never shows another operator's name.
1852
+ const showsOperatorGroup =
1853
+ draftOperators.length > 1 &&
1854
+ draftOperator != null &&
1855
+ draftOperators.includes(draftOperator);
1856
+ // The title — the dialog's name — reads the field and operator as
1857
+ // the Filters row does: by their labels, or, for a filter whose field or
1858
+ // operator the config no longer has, by the raw keys the row shows.
1859
+ const editorTitle =
1860
+ draft == null
1861
+ ? t('@astryx.powersearch.sheet.addFilter')
1862
+ : draftField == null || (draftOperator == null && draft.operator != null)
1863
+ ? t('@astryx.powersearch.sheet.fieldOperator', {
1864
+ field: draftField?.label ?? draft.field,
1865
+ operator:
1866
+ draftOperatorLabel !== ''
1867
+ ? draftOperatorLabel
1868
+ : (draft.operator ?? ''),
1869
+ }).trim()
1870
+ : !showsOperatorGroup && draftOperatorLabel !== ''
1871
+ ? t('@astryx.powersearch.sheet.fieldOperator', {
1872
+ field: draftField.label,
1873
+ operator: draftOperatorLabel,
1874
+ })
1875
+ : draftField.label;
1876
+ const saveButtonLabel =
1877
+ saveButtonLabelFromProps ??
1878
+ (draft?.mode === 'edit'
1879
+ ? t('@astryx.powersearch.editor.apply')
1880
+ : t('@astryx.powersearch.sheet.addFilter'));
1881
+
1882
+ // Every sheet body: padded, and publishing that padding to its lists.
1883
+ const bodyProps = stylex.props(
1884
+ styles.body,
1885
+ containerPaddingInlineVarStyles[4],
1886
+ );
1887
+ const scrollContentProps = stylex.props(
1888
+ styles.scrollContent,
1889
+ containerPaddingInlineVarStyles[4],
1890
+ );
1891
+ const controlSectionProps = stylex.props(
1892
+ styles.controlSection,
1893
+ containerPaddingInlineVarStyles[3],
1894
+ );
1895
+
1896
+ // A vertical touch drag on the Add filter rows moves focus off a focused
1897
+ // search to the sheet, so the software keyboard leaves and the rows can be
1898
+ // read.
1899
+ const fieldPickerDragProps = useDismissSearchOnTouchDrag(
1900
+ () => [
1901
+ contentSearchRef.current?.querySelector('input'),
1902
+ fieldSearchRef.current?.querySelector('input'),
1903
+ ],
1904
+ () => fieldsSheetRef.current?.closest<HTMLElement>('[tabindex="-1"]'),
1905
+ );
1906
+
1907
+ const isEditorDisabled = isDisabled || isReadOnly;
1908
+ const isSaveDisabled =
1909
+ isEditorDisabled || draft?.operator == null || draft.value == null;
1910
+ // The step has something to edit when the field and operator still exist
1911
+ // (a controlled config update can remove either). A caller's `Editor`
1912
+ // override replaces the body for its value type with the props the popover
1913
+ // hands it; otherwise a `nested` value takes the popover's built-in
1914
+ // NestedEditor and every other type the sheet's own control.
1915
+ const isDraftRenderable =
1916
+ draft != null && draftField != null && draftOperator != null;
1917
+ const isDraftNested =
1918
+ isDraftRenderable && !isSupportedOperator(draftOperator);
1919
+ // A controlled config update that removes the field or operator being
1920
+ // edited replaces the step's body with the unavailable state while focus
1921
+ // may be on one of the body's controls, which unmount without a blur. Focus
1922
+ // then moves to Cancel, the way back to the Filters row whose remove action
1923
+ // is the removal path, so it never falls to the page body inside the open
1924
+ // sheet. The message itself is announced by its rendered element.
1925
+ const cancelButtonRef = useRef<HTMLButtonElement>(null);
1926
+ const wasDraftRenderableRef = useRef(isDraftRenderable);
1927
+ useLayoutEffect(() => {
1928
+ const becameUnavailable =
1929
+ wasDraftRenderableRef.current && !isDraftRenderable && draft != null;
1930
+ wasDraftRenderableRef.current = isDraftRenderable;
1931
+ if (!becameUnavailable || step !== 'value') {
1932
+ return;
1933
+ }
1934
+ const active = document.activeElement;
1935
+ const dialog = cancelButtonRef.current?.closest('dialog');
1936
+ if (dialog != null && active != null && dialog.contains(active)) {
1937
+ return;
1938
+ }
1939
+ cancelButtonRef.current?.focus();
1940
+ }, [draft, isDraftRenderable, step]);
1941
+ // The operator group stays outside either editor, so switching operators
1942
+ // swaps the body — a `nested` operator beside a plain one included.
1943
+ const operatorGroup = isDraftRenderable && showsOperatorGroup && (
1944
+ <RadioList
1945
+ label={t('@astryx.powersearch.editor.operator')}
1946
+ isLabelHidden
1947
+ value={draft.operator ?? ''}
1948
+ onChange={operatorKey => {
1949
+ const operator = draftOperators.find(
1950
+ candidate => candidate.key === operatorKey,
1951
+ );
1952
+ if (operator != null) {
1953
+ handleOperatorSelect(operator);
1954
+ }
1955
+ }}
1956
+ isDisabled={isEditorDisabled}>
1957
+ {draftOperators.map(operator => (
1958
+ <RadioListItem
1959
+ key={operator.key}
1960
+ label={t('@astryx.powersearch.sheet.fieldOperator', {
1961
+ field: draftField.label,
1962
+ operator: resolveOperatorLabel(operator, t),
1963
+ })}
1964
+ value={operator.key}
1965
+ xstyle={styles.trailingControlRow}
1966
+ />
1967
+ ))}
1968
+ </RadioList>
1969
+ );
1970
+ // The step's Operator group owns the operator choice, so the built-in
1971
+ // nested editor's root operator picker is hidden and its root shows the
1972
+ // checked operator's label.
1973
+ const nestedOperatorOptions = useMemo(
1974
+ () =>
1975
+ draftOperator == null
1976
+ ? []
1977
+ : [
1978
+ {
1979
+ value: draftOperator.key,
1980
+ label: resolveOperatorLabel(draftOperator, t),
1981
+ },
1982
+ ],
1983
+ [draftOperator, t],
1984
+ );
1985
+ const handleNestedDraftChange = useCallback((next: PartialFilter) => {
1986
+ setDraft(current =>
1987
+ current == null ? current : {...current, value: next.value},
1988
+ );
1989
+ }, []);
1990
+
1991
+ const valueEditor =
1992
+ isDraftRenderable &&
1993
+ (isDraftNested ? (
1994
+ <NestedEditor
1995
+ key={`${draft.generation}-${draft.field}-${draft.operator}`}
1996
+ config={config}
1997
+ partialFilter={{
1998
+ field: draft.field,
1999
+ operator: draft.operator,
2000
+ value: draft.value,
2001
+ }}
2002
+ operatorOptions={nestedOperatorOptions}
2003
+ hasRootOperatorPicker={false}
2004
+ onOperatorChange={() => {}}
2005
+ onPartialFilterChange={handleNestedDraftChange}
2006
+ maxMenuItems={maxOperatorMenuItems}
2007
+ isReadOnly={isEditorDisabled}
2008
+ xstyle={styles.nestedEditorContainer}
2009
+ />
2010
+ ) : (
2011
+ <SheetValueEditor
2012
+ key={`${draft.generation}-${draft.field}-${draft.operator}`}
2013
+ operatorValue={draftOperator.value}
2014
+ filterValue={draft.value}
2015
+ onChange={handleDraftValueChange}
2016
+ onUnstage={handleDraftUnstage}
2017
+ config={config}
2018
+ fieldLabel={draftField.label}
2019
+ isDisabled={isEditorDisabled}
2020
+ maxMenuItems={maxOperatorMenuItems}
2021
+ editors={editors}
2022
+ />
2023
+ ));
2024
+
2025
+ return (
2026
+ <>
2027
+ <BottomSheet
2028
+ isOpen={isManageSheetOpen}
2029
+ onOpenChange={handleManageOpenChange}
2030
+ finalFocusRef={finalFocusRef}
2031
+ label={t('@astryx.powersearch.sheet.filtersTitle')}
2032
+ height="tall"
2033
+ padding={0}>
2034
+ <div
2035
+ ref={manageSheetRef}
2036
+ onFocus={noteSheetFocus('manage')}
2037
+ {...stylex.props(styles.sheet, styles.sheetWithFixedFooter)}>
2038
+ {step === 'manage' && (
2039
+ <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />
2040
+ )}
2041
+ <div {...stylex.props(styles.header)}>
2042
+ <div {...stylex.props(styles.headerRow)}>
2043
+ <div {...stylex.props(styles.headerText)}>
2044
+ <Heading level={3}>
2045
+ {t('@astryx.powersearch.sheet.filtersTitle')}
2046
+ </Heading>
2047
+ </div>
2048
+ {isInteractive && filterRows.length > 0 && (
2049
+ <Button
2050
+ ref={managerAddButtonRef}
2051
+ label={t('@astryx.powersearch.sheet.addFilter')}
2052
+ icon={<Icon icon={PlusIcon} size="sm" />}
2053
+ isIconOnly
2054
+ variant="secondary"
2055
+ size="md"
2056
+ xstyle={styles.touchHitArea}
2057
+ onClick={openFieldList}
2058
+ />
2059
+ )}
2060
+ </div>
2061
+ </div>
2062
+ <div {...stylex.props(styles.scrollViewport)}>
2063
+ <div {...scrollContentProps}>
2064
+ {filterRows.length === 0 ? (
2065
+ // With no filter the single thing to do is the only visible
2066
+ // action. Mounted only while the sheet is open, so its text
2067
+ // is spoken in this sheet when it appears.
2068
+ isManageSheetOpen && (
2069
+ <EmptyState
2070
+ title={t('@astryx.powersearch.sheet.noFilters')}
2071
+ description={t(
2072
+ '@astryx.powersearch.sheet.noFiltersDescription',
2073
+ )}
2074
+ headingLevel={4}
2075
+ icon={<Icon icon="funnel" size="lg" color="secondary" />}
2076
+ xstyle={styles.emptyState}
2077
+ actions={
2078
+ isInteractive ? (
2079
+ <Button
2080
+ ref={managerAddButtonRef}
2081
+ label={t('@astryx.powersearch.sheet.addFilter')}
2082
+ icon={<Icon icon={PlusIcon} size="sm" />}
2083
+ variant="primary"
2084
+ size="lg"
2085
+ xstyle={styles.touchHitArea}
2086
+ onClick={openFieldList}
2087
+ />
2088
+ ) : undefined
2089
+ }
2090
+ />
2091
+ )
2092
+ ) : (
2093
+ <List hasDividers density="spacious" edge="bleed">
2094
+ {filterRows.map(row => {
2095
+ const operator = config.getOperator(
2096
+ row.filter.field,
2097
+ row.filter.operator,
2098
+ );
2099
+ const fieldLabel =
2100
+ config.getField(row.filter.field)?.label ??
2101
+ row.filter.field;
2102
+ // A one-tap filter has no value to edit: its row removes
2103
+ // it.
2104
+ const isOneTap = operator?.value.type === 'empty';
2105
+ const removeLabel = t(
2106
+ '@astryx.powersearch.sheet.removeFilter',
2107
+ {field: fieldLabel},
2108
+ );
2109
+ return (
2110
+ <ListItem
2111
+ key={row.key}
2112
+ ref={node => {
2113
+ if (node == null) {
2114
+ managerRowsRef.current.delete(row.index);
2115
+ } else {
2116
+ managerRowsRef.current.set(row.index, node);
2117
+ }
2118
+ }}
2119
+ label={row.displayLabel}
2120
+ onClick={
2121
+ row.isEditable
2122
+ ? isOneTap
2123
+ ? () => handleRemoveFilter(row.index)
2124
+ : () => handleFilterEdit(row.index)
2125
+ : undefined
2126
+ }
2127
+ endContent={
2128
+ row.isEditable ? (
2129
+ <IconButton
2130
+ data-sheet-remove=""
2131
+ label={removeLabel}
2132
+ tooltip={removeLabel}
2133
+ icon={<Icon icon="close" size="sm" />}
2134
+ variant="ghost"
2135
+ size="md"
2136
+ xstyle={styles.touchHitArea}
2137
+ onClick={event => {
2138
+ event.stopPropagation();
2139
+ handleRemoveFilter(row.index);
2140
+ }}
2141
+ />
2142
+ ) : undefined
2143
+ }
2144
+ />
2145
+ );
2146
+ })}
2147
+ </List>
2148
+ )}
2149
+ </div>
2150
+ </div>
2151
+ {filterRows.length > 0 && (
2152
+ <div {...stylex.props(styles.footer, styles.fixedFooter)}>
2153
+ {isClearAllShown && (
2154
+ <Button
2155
+ ref={clearAllButtonRef}
2156
+ label={t('@astryx.powersearch.sheet.clearAll')}
2157
+ variant="secondary"
2158
+ size="lg"
2159
+ xstyle={styles.footerEqualAction}
2160
+ onClick={() => setIsClearConfirmationOpen(true)}
2161
+ />
2162
+ )}
2163
+ <Button
2164
+ label={t('@astryx.powersearch.sheet.done')}
2165
+ variant="primary"
2166
+ size="lg"
2167
+ xstyle={
2168
+ isClearAllShown
2169
+ ? styles.footerEqualAction
2170
+ : [styles.footerSoleAction, styles.touchHitArea]
2171
+ }
2172
+ onClick={closeFlow}
2173
+ width={isClearAllShown ? undefined : '100%'}
2174
+ />
2175
+ </div>
2176
+ )}
2177
+ </div>
2178
+ </BottomSheet>
2179
+
2180
+ <BottomSheet
2181
+ isOpen={isFieldsSheetOpen}
2182
+ onOpenChange={handleFieldsOpenChange}
2183
+ finalFocusRef={stepFinalFocusRef}
2184
+ label={t('@astryx.powersearch.sheet.addFilter')}
2185
+ height="tall"
2186
+ padding={0}>
2187
+ <div
2188
+ ref={fieldsSheetCallbackRef}
2189
+ onFocus={noteSheetFocus('fields')}
2190
+ onKeyDown={hasContentSearch ? handleContentListKeyDown : undefined}
2191
+ {...stylex.props(styles.sheet, styles.sheetWithFixedFooter)}>
2192
+ {step === 'fields' && (
2193
+ <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />
2194
+ )}
2195
+ <div {...stylex.props(styles.header)}>
2196
+ <div {...stylex.props(styles.headerRow)}>
2197
+ <div {...stylex.props(styles.headerText)}>
2198
+ <Heading level={3}>
2199
+ {t('@astryx.powersearch.sheet.addFilter')}
2200
+ </Heading>
2201
+ </div>
2202
+ </div>
2203
+ {hasContentSearch ? (
2204
+ <div ref={contentSearchRef}>
2205
+ <TextInput
2206
+ label={t('@astryx.powersearch.sheet.search')}
2207
+ isLabelHidden
2208
+ role="searchbox"
2209
+ aria-controls={contentResultsId}
2210
+ value={contentQuery}
2211
+ onChange={setContentQuery}
2212
+ onKeyDown={event => {
2213
+ if (isImeKeyEvent(event.nativeEvent)) {
2214
+ return;
2215
+ }
2216
+ if (event.key === 'Enter' && contentResults[0] != null) {
2217
+ event.preventDefault();
2218
+ handleContentSuggestionSelect(contentResults[0]);
2219
+ }
2220
+ }}
2221
+ placeholder={placeholder}
2222
+ hasClear
2223
+ startIcon={<Icon icon="search" size="sm" color="secondary" />}
2224
+ isDisabled={!isInteractive}
2225
+ size="lg"
2226
+ width="100%"
2227
+ />
2228
+ </div>
2229
+ ) : isFieldSearchShown ? (
2230
+ <div ref={fieldSearchRef}>
2231
+ <TextInput
2232
+ label={t('@astryx.powersearch.sheet.searchFields')}
2233
+ isLabelHidden
2234
+ placeholder={t(
2235
+ '@astryx.powersearch.sheet.searchFieldsPlaceholder',
2236
+ )}
2237
+ value={fieldQuery}
2238
+ onChange={setFieldQuery}
2239
+ startIcon={<Icon icon="search" size="sm" color="secondary" />}
2240
+ isDisabled={!isInteractive}
2241
+ size="lg"
2242
+ width="100%"
2243
+ />
2244
+ </div>
2245
+ ) : null}
2246
+ </div>
2247
+ <div
2248
+ {...stylex.props(styles.scrollViewport)}
2249
+ {...fieldPickerDragProps}>
2250
+ <div {...scrollContentProps}>
2251
+ {hasContentSearch ? (
2252
+ contentResults.length > 0 ? (
2253
+ <List
2254
+ id={contentResultsId}
2255
+ aria-label={t('@astryx.powersearch.sheet.searchResults')}
2256
+ hasDividers
2257
+ density="spacious"
2258
+ edge="bleed">
2259
+ {contentResults.map(item => (
2260
+ <ListItem
2261
+ key={item.id}
2262
+ label={item.label}
2263
+ isDisabled={!isInteractive}
2264
+ onClick={() => handleContentSuggestionSelect(item)}
2265
+ />
2266
+ ))}
2267
+ </List>
2268
+ ) : contentQuery.trim() !== '' ? (
2269
+ // The searchbox's `aria-controls` target while nothing
2270
+ // lists. The empty state mounts only while this step is the
2271
+ // open one and is spoken from its rendered text, once per
2272
+ // query that matches nothing.
2273
+ <div id={contentResultsId}>
2274
+ {step === 'fields' && (
2275
+ <EmptyState
2276
+ key={contentQuery}
2277
+ icon={
2278
+ <Icon icon="search" size="lg" color="secondary" />
2279
+ }
2280
+ title={t('@astryx.powersearch.sheet.noResults')}
2281
+ description={t(
2282
+ '@astryx.powersearch.sheet.tryDifferentSearch',
2283
+ )}
2284
+ headingLevel={4}
2285
+ isCompact
2286
+ xstyle={styles.emptyState}
2287
+ />
2288
+ )}
2289
+ </div>
2290
+ ) : (
2291
+ // An empty query with no bootstrap suggestion: the results
2292
+ // region exists, empty, so the searchbox's `aria-controls`
2293
+ // always names an element in the document.
2294
+ <div id={contentResultsId} />
2295
+ )
2296
+ ) : groupedFields.length === 0 ? (
2297
+ // A search outcome: only a non-empty query that matches
2298
+ // nothing shows it; a config with no field lists nothing.
2299
+ normalizedFieldQuery !== '' &&
2300
+ step === 'fields' && (
2301
+ <EmptyState
2302
+ key={normalizedFieldQuery}
2303
+ icon={<Icon icon="search" size="lg" color="secondary" />}
2304
+ title={t('@astryx.powersearch.sheet.noMatchingFields')}
2305
+ description={t(
2306
+ '@astryx.powersearch.sheet.tryDifferentSearch',
2307
+ )}
2308
+ headingLevel={4}
2309
+ isCompact
2310
+ xstyle={styles.emptyState}
2311
+ />
2312
+ )
2313
+ ) : (
2314
+ groupedFields.map(([group, groupFields]) => (
2315
+ <List
2316
+ key={group}
2317
+ hasDividers
2318
+ density="spacious"
2319
+ header={
2320
+ <Heading level={4}>
2321
+ {group === ''
2322
+ ? t('@astryx.powersearch.sheet.ungroupedFields')
2323
+ : group}
2324
+ </Heading>
2325
+ }
2326
+ edge="bleed">
2327
+ {groupFields.map(field => (
2328
+ <ListItem
2329
+ key={field.key}
2330
+ ref={node => {
2331
+ if (node == null) {
2332
+ fieldRowsRef.current.delete(field.key);
2333
+ } else {
2334
+ fieldRowsRef.current.set(field.key, node);
2335
+ }
2336
+ }}
2337
+ label={field.label}
2338
+ isDisabled={!isInteractive}
2339
+ startContent={field.icon}
2340
+ endContent={
2341
+ isImmediateAddField(field) ? (
2342
+ <Icon icon={PlusIcon} size="sm" color="secondary" />
2343
+ ) : (
2344
+ <Icon
2345
+ icon="chevronRight"
2346
+ size="sm"
2347
+ color="secondary"
2348
+ xstyle={rtlStyles.mirror}
2349
+ />
2350
+ )
2351
+ }
2352
+ onClick={() => handleFieldSelect(field)}
2353
+ />
2354
+ ))}
2355
+ </List>
2356
+ ))
2357
+ )}
2358
+ </div>
2359
+ </div>
2360
+ {isFieldPickerDirectEntry && (
2361
+ <div {...stylex.props(styles.footer, styles.fixedFooter)}>
2362
+ <Button
2363
+ label={t('@astryx.powersearch.sheet.done')}
2364
+ variant="primary"
2365
+ width="100%"
2366
+ xstyle={styles.touchAction}
2367
+ onClick={closeFlow}
2368
+ />
2369
+ </div>
2370
+ )}
2371
+ </div>
2372
+ </BottomSheet>
2373
+
2374
+ <BottomSheet
2375
+ isOpen={step === 'value'}
2376
+ onOpenChange={handleValueOpenChange}
2377
+ finalFocusRef={stepFinalFocusRef}
2378
+ label={editorTitle}
2379
+ height="tall"
2380
+ padding={0}
2381
+ purpose="info">
2382
+ <div {...stylex.props(styles.sheet)}>
2383
+ <div {...stylex.props(styles.header)}>
2384
+ <div {...stylex.props(styles.headerRow)}>
2385
+ <div {...stylex.props(styles.headerText)}>
2386
+ <Heading level={3} maxLines={1}>
2387
+ {editorTitle}
2388
+ </Heading>
2389
+ </div>
2390
+ </div>
2391
+ </div>
2392
+ {isDraftRenderable && EditorOverride != null ? (
2393
+ <div {...bodyProps}>
2394
+ {step === 'value' && (
2395
+ <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />
2396
+ )}
2397
+ {operatorGroup && (
2398
+ <div {...controlSectionProps}>{operatorGroup}</div>
2399
+ )}
2400
+ <EditorOverride
2401
+ key={`${draft.generation}-${draft.field}-${draft.operator}`}
2402
+ config={configProp}
2403
+ filter={{
2404
+ field: draft.field,
2405
+ operator: draft.operator,
2406
+ value: draft.value,
2407
+ }}
2408
+ mode={draft.mode}
2409
+ onSave={saved => {
2410
+ if (saved == null) {
2411
+ if (draft.mode === 'edit') {
2412
+ handleRemove();
2413
+ } else {
2414
+ queueManagerAddFocus();
2415
+ setStep('manage');
2416
+ }
2417
+ return;
2418
+ }
2419
+ commitSavedFilter(draft, saved);
2420
+ }}
2421
+ onCancel={returnFromValue}
2422
+ saveButtonLabel={saveButtonLabel}
2423
+ isReadOnly={isEditorDisabled}
2424
+ />
2425
+ </div>
2426
+ ) : (
2427
+ <>
2428
+ <div {...bodyProps}>
2429
+ {step === 'value' && (
2430
+ <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />
2431
+ )}
2432
+ {isDraftRenderable ? (
2433
+ // A lone editor sits on the sheet's surface; with the
2434
+ // Operator group above it, each section is a muted
2435
+ // container.
2436
+ operatorGroup ? (
2437
+ <>
2438
+ <div {...controlSectionProps}>{operatorGroup}</div>
2439
+ <div {...controlSectionProps}>{valueEditor}</div>
2440
+ </>
2441
+ ) : (
2442
+ valueEditor
2443
+ )
2444
+ ) : (
2445
+ // A controlled config update removed the field or operator
2446
+ // being edited: say so (the element's rendered text is
2447
+ // announced, once per opened filter, while this step is the
2448
+ // open one) and keep a way out.
2449
+ draft != null && (
2450
+ <SheetEmptyMessage
2451
+ message={t('@astryx.powersearch.sheet.filterUnavailable')}
2452
+ occasion={String(draft.generation)}
2453
+ isShown={step === 'value'}
2454
+ />
2455
+ )
2456
+ )}
2457
+ </div>
2458
+ <div {...stylex.props(styles.footer)}>
2459
+ {isReadOnly ? (
2460
+ <Button
2461
+ ref={cancelButtonRef}
2462
+ label={t('@astryx.powersearch.editor.cancel')}
2463
+ variant="secondary"
2464
+ width="100%"
2465
+ xstyle={[styles.footerSoleAction, styles.touchHitArea]}
2466
+ onClick={returnFromValue}
2467
+ />
2468
+ ) : (
2469
+ <>
2470
+ <Button
2471
+ ref={cancelButtonRef}
2472
+ label={t('@astryx.powersearch.editor.cancel')}
2473
+ variant="secondary"
2474
+ size="lg"
2475
+ xstyle={styles.footerEqualAction}
2476
+ onClick={returnFromValue}
2477
+ />
2478
+ {isDraftRenderable && (
2479
+ <Button
2480
+ label={saveButtonLabel}
2481
+ variant="primary"
2482
+ size="lg"
2483
+ isDisabled={isSaveDisabled}
2484
+ xstyle={styles.footerEqualAction}
2485
+ onClick={handleSave}
2486
+ />
2487
+ )}
2488
+ </>
2489
+ )}
2490
+ </div>
2491
+ </>
2492
+ )}
2493
+ </div>
2494
+ </BottomSheet>
2495
+
2496
+ {isClearConfirmationOpen && (
2497
+ <SheetConfirmation
2498
+ isOpen
2499
+ onOpenChange={isConfirmationOpen => {
2500
+ if (!isConfirmationOpen) {
2501
+ closeClearConfirmation(false);
2502
+ }
2503
+ }}
2504
+ title={t('@astryx.powersearch.sheet.clearAllTitle')}
2505
+ description={t('@astryx.powersearch.sheet.clearAllDescription')}
2506
+ actionLabel={t('@astryx.powersearch.sheet.clearAllConfirm')}
2507
+ cancelLabel={t('@astryx.powersearch.sheet.clearAllCancel')}
2508
+ onAction={() => closeClearConfirmation(true)}
2509
+ />
2510
+ )}
2511
+ </>
2512
+ );
2513
+ }
2514
+
2515
+ PowerSearchBottomSheet.displayName = 'PowerSearchBottomSheet';