@jobber/components 8.4.0 → 8.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/Autocomplete/Autocomplete.d.ts +6 -4
  2. package/dist/Autocomplete/Autocomplete.types.d.ts +3 -137
  3. package/dist/Autocomplete/components/FloatingMenu.d.ts +6 -6
  4. package/dist/Autocomplete/components/MenuList.d.ts +4 -4
  5. package/dist/Autocomplete/components/PersistentRegion.d.ts +3 -3
  6. package/dist/Autocomplete/index.cjs +25 -1658
  7. package/dist/Autocomplete/index.d.ts +3 -30
  8. package/dist/Autocomplete/index.mjs +25 -1647
  9. package/dist/Autocomplete/tests/Autocomplete.setup.d.ts +15 -15
  10. package/dist/Autocomplete/useAutocomplete.d.ts +2 -2
  11. package/dist/Autocomplete-cjs.js +1306 -0
  12. package/dist/Autocomplete-es.js +1304 -0
  13. package/dist/FormField/FormFieldTypes.d.ts +0 -7
  14. package/dist/InputDate/InputDate.types.d.ts +1 -1
  15. package/dist/InputEmail/InputEmail.types.d.ts +1 -1
  16. package/dist/InputNumber/InputNumber.types.d.ts +1 -1
  17. package/dist/InputPhoneNumber/InputPhoneNumber.types.d.ts +1 -1
  18. package/dist/InputText/InputText.types.d.ts +1 -5
  19. package/dist/InputTime/InputTime.types.d.ts +1 -1
  20. package/dist/Menu-es.js +1 -1
  21. package/dist/MenuSubmenuTrigger-es.js +1 -1
  22. package/dist/Select/OptionGroup.d.ts +2 -2
  23. package/dist/Select/Select.types.d.ts +1 -1
  24. package/dist/docs/Autocomplete/{AutocompleteV2.md → Autocomplete.md} +13 -107
  25. package/dist/docs/Banner/Banner.md +3 -3
  26. package/dist/docs/Box/Box.md +2 -2
  27. package/dist/docs/Chips/Chips.md +1 -1
  28. package/dist/docs/DataList/DataList.md +1 -1
  29. package/dist/docs/FormField/FormField.md +0 -1
  30. package/dist/docs/Icon/Icon.md +1 -1
  31. package/dist/docs/InputGroup/InputGroup.md +1 -1
  32. package/dist/docs/InputPassword/InputPassword.md +0 -1
  33. package/dist/docs/Menu/Menu.md +1 -1
  34. package/dist/docs/Modal/Modal.md +3 -3
  35. package/dist/docs/MultiSelect/MultiSelect.md +1 -1
  36. package/dist/docs/index.md +1 -2
  37. package/dist/docs/usage-guidelines/usage-guidelines.md +13 -44
  38. package/dist/floating-ui.react-dom-es.js +1 -1
  39. package/dist/floating-ui.react-es.js +1 -1
  40. package/dist/index.cjs +2 -2
  41. package/dist/index.esm-es.js +1 -1
  42. package/dist/index.mjs +1 -1
  43. package/dist/sharedHelpers/types.d.ts +0 -4
  44. package/dist/styles.css +29 -153
  45. package/package.json +2 -2
  46. package/dist/Autocomplete/Autocomplete.rebuilt.d.ts +0 -8
  47. package/dist/Autocomplete/Autocomplete.utils.d.ts +0 -8
  48. package/dist/Autocomplete/Menu/DefaultMenu.d.ts +0 -16
  49. package/dist/Autocomplete/Menu/Menu.d.ts +0 -3
  50. package/dist/Autocomplete/Menu/MenuWrapper.d.ts +0 -23
  51. package/dist/Autocomplete/Option.d.ts +0 -78
  52. package/dist/Autocomplete/V1.docgen.d.ts +0 -4
  53. package/dist/Autocomplete/V2.docgen.d.ts +0 -6
  54. package/dist/Autocomplete/useKeyboardNavigation.d.ts +0 -35
  55. package/dist/Autocomplete/useRepositionMenu.d.ts +0 -10
  56. package/dist/docs/Autocomplete/AutocompleteV1.md +0 -1328
@@ -1,1646 +1,37 @@
1
1
  'use strict';
2
2
 
3
- var React = require('react');
4
- var floatingUi_react = require('../floating-ui.react-cjs.js');
5
- var classnames = require('classnames');
6
- var design = require('@jobber/design');
7
- var jobberHooks = require('@jobber/hooks');
8
- var maxHeight = require('../maxHeight-cjs.js');
9
- var floatingUi_reactDom = require('../floating-ui.react-dom-cjs.js');
10
- var Heading = require('../Heading-cjs.js');
11
- var Text = require('../Text-cjs.js');
12
- var Typography = require('../Typography-cjs.js');
13
- var Icon = require('../Icon-cjs.js');
14
- var Glimmer = require('../Glimmer-cjs.js');
15
- var InputText = require('../InputText-cjs.js');
16
- var FormFieldWrapper = require('../FormFieldWrapper-cjs.js');
17
- var tslib_es6 = require('../tslib.es6-cjs.js');
18
- require('react-hook-form');
19
- var mergeRefs = require('../mergeRefs-cjs.js');
20
- require('../Button-cjs.js');
21
- var filterDataAttributes = require('../filterDataAttributes-cjs.js');
3
+ var Autocomplete = require('../Autocomplete-cjs.js');
4
+ require('react');
5
+ require('../floating-ui.react-cjs.js');
22
6
  require('../floating-ui.utils.dom-cjs.js');
23
7
  require('../index.esm-cjs.js');
24
8
  require('react/jsx-runtime');
25
9
  require('react-dom');
10
+ require('../floating-ui.react-dom-cjs.js');
11
+ require('classnames');
12
+ require('@jobber/design');
13
+ require('@jobber/hooks');
14
+ require('../maxHeight-cjs.js');
15
+ require('../Heading-cjs.js');
16
+ require('../Typography-cjs.js');
17
+ require('../Text-cjs.js');
18
+ require('../Icon-cjs.js');
19
+ require('../Glimmer-cjs.js');
20
+ require('../tslib.es6-cjs.js');
26
21
  require('../Content-cjs.js');
27
- require('../FormFieldPostFix-cjs.js');
28
- require('../Spinner-cjs.js');
29
- require('../useAtlantisFormFieldName-cjs.js');
22
+ require('../InputText-cjs.js');
23
+ require('../FormFieldWrapper-cjs.js');
30
24
  require('framer-motion');
25
+ require('../Button-cjs.js');
26
+ require('react-router-dom');
31
27
  require('../useFormFieldFocus-cjs.js');
32
28
  require('../InputValidation-cjs.js');
33
- require('react-router-dom');
34
-
35
- const AUTOCOMPLETE_MAX_HEIGHT$1 = 300;
36
- /** Stable empty array for cleared/empty selection state. Reuse to avoid reference churn. */
37
- const EMPTY_SELECTED_VALUES = [];
38
-
39
- var styles$1 = {"list":"_37kZB-nYE08-","loadingList":"ULib3TUQja0-","option":"h5-1Pp0eRyo-","defaultOptionContent":"iBkyj85vd-E-","icon":"I6wAbSJJHNQ-","optionActive":"_4yhnonWAWRY-","actionActive":"oGLMF6n8C74-","action":"LBrwH6TEUYA-","section":"DDOv4DR8bJQ-","emptyStateMessage":"Twgjn26oldE-","stickyTop":"mc1-CEwZtHE-","scrollRegion":"kOR88SFNOn0-","persistentHeader":"_0O-kEf3h9ZI-","persistentFooter":"rQ9ZS7Rb7Z4-","textPersistent":"vxk57ZhP8GU-","multiSelectField":"AWoK6-P8fFE-","chipArea":"zJm0oR5x4qY-","inlineInput":"Oa26ZaVEi3g-","selectionChip":"IarOrfyYExE-","selectionChipActive":"pmtAk9HEhF4-","selectionChipDisabled":"nmXqlAV-DJo-","chipDismiss":"SmrmwoOlZDo-","limitText":"pqwAJ8VczCU-","spinning":"_0d8hyvaCPAw-"};
40
-
41
- function flattenMenu(menu) {
42
- const optionItems = [];
43
- const sections = [];
44
- const persistentsHeaders = [];
45
- const persistentsFooters = [];
46
- menu.forEach(item => {
47
- if (item.type === "header") {
48
- persistentsHeaders.push(item);
49
- return;
50
- }
51
- if (item.type === "footer") {
52
- persistentsFooters.push(item);
53
- return;
54
- }
55
- const group = item;
56
- sections.push(group);
57
- optionItems.push(...group.options);
58
- });
59
- return { optionItems, sections, persistentsHeaders, persistentsFooters };
60
- }
61
- function buildItemsForGroup(group, optionsFilter) {
62
- var _a;
63
- const isSection = group.type === "section";
64
- const filtered = optionsFilter ? optionsFilter(group.options) : group.options;
65
- const actions = (_a = group.actions) !== null && _a !== void 0 ? _a : [];
66
- const result = [];
67
- // Only render a section header when that section has at least one option after filtering
68
- if (isSection && filtered.length > 0) {
69
- result.push({
70
- kind: "section",
71
- section: group,
72
- });
73
- }
74
- if (filtered.length > 0) {
75
- result.push(...filtered.map(o => ({
76
- kind: "option",
77
- value: o,
78
- })));
79
- }
80
- // Only render actions for a group when that group has at least one option after filtering
81
- if (actions.length > 0 && filtered.length > 0) {
82
- result.push(...actions.map(action => ({
83
- kind: "action",
84
- action,
85
- origin: "menu",
86
- })));
87
- }
88
- return result;
89
- }
90
- function buildRenderableList(sections, optionsFilter) {
91
- const items = [];
92
- for (const group of sections) {
93
- items.push(...buildItemsForGroup(group, optionsFilter));
94
- }
95
- return items;
96
- }
97
- function getNavigableItemAtIndex(activeIndex, renderable) {
98
- if (activeIndex == null)
99
- return null;
100
- let navigableIndex = -1;
101
- for (const item of renderable) {
102
- // Ignore sections
103
- if (item.kind === "section")
104
- continue;
105
- navigableIndex += 1;
106
- if (navigableIndex === activeIndex)
107
- return item;
108
- }
109
- return null;
110
- }
111
- function findNavigableIndexForValue(renderable, equals, selectedValue) {
112
- let navigableIndex = -1;
113
- for (const item of renderable) {
114
- // Ignore sections
115
- if (item.kind === "section")
116
- continue;
117
- navigableIndex += 1;
118
- if (item.kind === "option" && equals(item.value, selectedValue)) {
119
- return navigableIndex;
120
- }
121
- }
122
- return null;
123
- }
124
- function invokeActiveItemOnEnter(event, activeIndex, renderable, onSelect, onAction) {
125
- const activeItem = getNavigableItemAtIndex(activeIndex, renderable);
126
- if (!activeItem)
127
- return;
128
- event.preventDefault();
129
- if (activeItem.kind === "option") {
130
- onSelect(activeItem.value);
131
- }
132
- else if (activeItem.kind === "action") {
133
- onAction({
134
- run: activeItem.action.onClick,
135
- closeOnRun: activeItem.action.shouldClose,
136
- });
137
- }
138
- }
139
-
140
- const MENU_OFFSET = design.tokens["space-small"];
141
- const AUTOCOMPLETE_MAX_HEIGHT = 300;
142
- function useStableSetReference(refs) {
143
- const latestRefs = React.useRef(refs);
144
- latestRefs.current = refs;
145
- return React.useCallback((el) => latestRefs.current.setReference(el), []);
146
- }
147
- function useAutocompleteListNav({ navigableCount, shouldResetActiveIndexOnClose, onMenuOpen, onMenuClose, selectedIndex, readOnly = false, disabled = false, outsidePressExcludeSelector, }) {
148
- const [open, setOpen] = React.useState(false);
149
- const [activeIndex, setActiveIndex] = React.useState(null);
150
- const listRef = React.useRef([]);
151
- const { refs, floatingStyles, context } = floatingUi_react.useFloating({
152
- placement: "bottom",
153
- whileElementsMounted: floatingUi_reactDom.autoUpdate,
154
- open,
155
- onOpenChange: (isOpen, _event, reason) => {
156
- setOpen(isOpen);
157
- if (isOpen) {
158
- onMenuOpen === null || onMenuOpen === void 0 ? void 0 : onMenuOpen();
159
- }
160
- else {
161
- if (shouldResetActiveIndexOnClose === null || shouldResetActiveIndexOnClose === void 0 ? void 0 : shouldResetActiveIndexOnClose()) {
162
- setActiveIndex(null);
163
- }
164
- onMenuClose === null || onMenuClose === void 0 ? void 0 : onMenuClose(String(reason !== null && reason !== void 0 ? reason : ""));
165
- }
166
- },
167
- middleware: [
168
- floatingUi_reactDom.offset(MENU_OFFSET),
169
- floatingUi_reactDom.flip({ fallbackPlacements: ["top"] }),
170
- floatingUi_reactDom.size({
171
- apply({ availableHeight, rects, elements }) {
172
- const maxHeight$1 = maxHeight.calculateMaxHeight(availableHeight, {
173
- maxHeight: AUTOCOMPLETE_MAX_HEIGHT,
174
- });
175
- Object.assign(elements.floating.style, {
176
- maxHeight: `${maxHeight$1}px`,
177
- width: `${rects.reference.width}px`,
178
- });
179
- },
180
- }),
181
- ],
182
- });
183
- const enabled = !readOnly && !disabled;
184
- const click = floatingUi_react.useClick(context, {
185
- enabled,
186
- toggle: false, // Only open, never close on click
187
- });
188
- const listNav = floatingUi_react.useListNavigation(context, {
189
- listRef,
190
- activeIndex,
191
- selectedIndex,
192
- scrollItemIntoView: {
193
- behavior: "smooth",
194
- block: "end",
195
- },
196
- loop: true,
197
- onNavigate: setActiveIndex,
198
- virtual: true,
199
- enabled: open,
200
- openOnArrowKeyDown: false,
201
- focusItemOnOpen: "auto",
202
- focusItemOnHover: false,
203
- });
204
- const dismiss = floatingUi_react.useDismiss(context, {
205
- outsidePress: outsidePressExcludeSelector
206
- ? (event) => {
207
- var _a, _b, _c, _d;
208
- const target = event.target;
209
- const insideRef = (_b = (_a = context.elements.domReference) === null || _a === void 0 ? void 0 : _a.contains(target)) !== null && _b !== void 0 ? _b : false;
210
- const insideFloating = (_d = (_c = context.elements.floating) === null || _c === void 0 ? void 0 : _c.contains(target)) !== null && _d !== void 0 ? _d : false;
211
- const insideExclude = event.target.closest(outsidePressExcludeSelector);
212
- return !(insideRef || insideFloating || insideExclude);
213
- }
214
- : true,
215
- escapeKey: true,
216
- outsidePressEvent: "click",
217
- });
218
- const { getReferenceProps, getFloatingProps, getItemProps } = floatingUi_react.useInteractions([click, listNav, dismiss]);
219
- React.useEffect(() => {
220
- listRef.current.length = navigableCount;
221
- setActiveIndex(prev => {
222
- if (navigableCount <= 0)
223
- return null;
224
- if (prev == null)
225
- return null;
226
- return prev >= navigableCount ? navigableCount - 1 : prev;
227
- });
228
- }, [navigableCount, setActiveIndex, listRef]);
229
- const setReferenceElement = useStableSetReference(refs);
230
- return {
231
- refs,
232
- floatingStyles,
233
- context,
234
- getReferenceProps,
235
- getFloatingProps,
236
- getItemProps,
237
- activeIndex,
238
- setActiveIndex,
239
- listRef,
240
- open,
241
- setOpen,
242
- setReferenceElement,
243
- };
244
- }
245
-
246
- /**
247
- * Handler that prevents default pointer behavior.
248
- * Used to prevent blur/focus issues when clicking on non-interactive menu elements.
249
- */
250
- function preventDefaultPointerDown(e) {
251
- e.preventDefault();
252
- }
253
- /**
254
- * Creates a handler for pointer down events on interactive menu items (options/actions).
255
- * Prevents default to avoid blur and sets flag for focus management.
256
- *
257
- * @param isHandlingMenuInteractionRef - Ref to track if a menu interaction is in progress
258
- * @returns A pointer down event handler
259
- */
260
- function createInteractionPointerDownHandler(isHandlingMenuInteractionRef) {
261
- return (e) => {
262
- e.preventDefault();
263
- // Set flag to prevent blur/focus handlers from interfering
264
- isHandlingMenuInteractionRef.current = true;
265
- };
266
- }
267
-
268
- // Keeping this hook cohesive improves readability by centralizing related
269
- // interactions and state transitions.
270
- // eslint-disable-next-line max-statements
271
- function useAutocomplete(props, inputRef) {
272
- const { menu, emptyActions, getOptionLabel: getOptionLabelProp, isOptionEqualToValue, inputValue, onInputChange, value, onChange, multiple, openOnFocus = true, readOnly = false, disabled = false, debounce: debounceMs = 300, } = props;
273
- const isHandlingMenuInteractionRef = React.useRef(false);
274
- // TODO: Clean up the types in these refs by enhancing the type system in useCallbackRef
275
- const getOptionLabelPropRef = jobberHooks.useCallbackRef((opt) => getOptionLabelProp === null || getOptionLabelProp === void 0 ? void 0 : getOptionLabelProp(opt));
276
- const getOptionLabel = React.useCallback((opt) => {
277
- const maybe = getOptionLabelPropRef(opt);
278
- return maybe !== null && maybe !== void 0 ? maybe : opt.label;
279
- }, [getOptionLabelPropRef]);
280
- const isOptionEqualToValueRef = jobberHooks.useCallbackRef((a, b) => isOptionEqualToValue === null || isOptionEqualToValue === void 0 ? void 0 : isOptionEqualToValue(a, b));
281
- const equals = React.useCallback((a, b) => {
282
- const custom = isOptionEqualToValueRef(a, b);
283
- return custom != null ? custom : getOptionLabel(a) === getOptionLabel(b);
284
- }, [isOptionEqualToValueRef, getOptionLabel]);
285
- const isOptionSelected = React.useCallback((opt) => {
286
- var _a;
287
- if (multiple) {
288
- const current = (_a = value) !== null && _a !== void 0 ? _a : EMPTY_SELECTED_VALUES;
289
- return current.some(v => equals(v, opt));
290
- }
291
- const current = value;
292
- return current != null ? equals(current, opt) : false;
293
- }, [multiple, value, equals]);
294
- const flatInitial = React.useMemo(() => flattenMenu(menu), [menu]);
295
- const sections = flatInitial.sections;
296
- const optionItems = flatInitial.optionItems;
297
- const persistentsHeaders = flatInitial.persistentsHeaders;
298
- const persistentsFooters = flatInitial.persistentsFooters;
299
- // Stable wrappers for function props
300
- const inputEqualsOptionRef = jobberHooks.useCallbackRef((text, o) => {
301
- const fn = props.inputEqualsOption;
302
- return fn ? fn(text, o) : undefined;
303
- });
304
- const inputEquals = React.useCallback((text, o) => {
305
- const custom = inputEqualsOptionRef(text, o);
306
- return custom != null ? custom : getOptionLabel(o) === text;
307
- }, [inputEqualsOptionRef, getOptionLabel]);
308
- // inputValue changes very often, is this worth memoizing?
309
- const exactLabelMatch = React.useMemo(() => {
310
- return optionItems.some(o => inputEquals(inputValue, o));
311
- }, [optionItems, inputEquals, inputValue]);
312
- const lastInputWasUser = React.useRef(false);
313
- const [debouncedInputValue, setDebouncedInputValue] = React.useState(inputValue);
314
- const debouncedSetter = jobberHooks.useDebounce(setDebouncedInputValue, debounceMs);
315
- React.useEffect(() => {
316
- // Skip debounce when clearing input for immediate feedback, preventing flickering of last selected item
317
- if (debounceMs === 0 || inputValue === "") {
318
- setDebouncedInputValue(inputValue);
319
- // Cancel any pending debounced call so a stale intermediate value
320
- // (e.g. "P" while deleting "Pipe…") doesn't overwrite the immediate set.
321
- debouncedSetter.cancel();
322
- return;
323
- }
324
- debouncedSetter(inputValue);
325
- }, [inputValue, debounceMs, debouncedSetter]);
326
- const filterOptionsRef = jobberHooks.useCallbackRef((opts, term) => {
327
- const fn = (typeof props.filterOptions === "function"
328
- ? props.filterOptions
329
- : undefined) || undefined;
330
- return fn ? fn(opts, term) : undefined;
331
- });
332
- const applyFilter = React.useCallback((opts, term) => {
333
- if (props.filterOptions === false)
334
- return opts;
335
- const override = filterOptionsRef(opts, term);
336
- if (override)
337
- return override;
338
- const lowered = term.toLowerCase();
339
- return opts.filter(opt => getOptionLabel(opt).toLowerCase().includes(lowered));
340
- }, [props.filterOptions, filterOptionsRef, getOptionLabel]);
341
- const renderable = React.useMemo(() => {
342
- const filter = (opts) => {
343
- if (exactLabelMatch && !lastInputWasUser.current)
344
- return opts;
345
- return applyFilter(opts, debouncedInputValue);
346
- };
347
- const items = buildRenderableList(sections, filter);
348
- const hasAnyOptions = items.some(i => i.kind === "option");
349
- if (!hasAnyOptions) {
350
- if (emptyActions) {
351
- const derived = typeof emptyActions === "function"
352
- ? emptyActions({ inputValue })
353
- : emptyActions;
354
- return derived.map(act => ({
355
- kind: "action",
356
- action: act,
357
- origin: "empty",
358
- }));
359
- }
360
- // No options and no emptyActions: render empty state
361
- return [];
362
- }
363
- return items;
364
- }, [
365
- sections,
366
- applyFilter,
367
- debouncedInputValue,
368
- exactLabelMatch,
369
- emptyActions,
370
- inputValue,
371
- ]);
372
- // This is only options
373
- const optionCount = renderable.reduce((count, item) => count + (item.kind === "option" ? 1 : 0), 0);
374
- const hasSelection = React.useMemo(() => {
375
- var _a;
376
- if (multiple) {
377
- const current = (_a = value) !== null && _a !== void 0 ? _a : EMPTY_SELECTED_VALUES;
378
- return Array.isArray(current) && current.length > 0;
379
- }
380
- return value != null;
381
- }, [multiple, value]);
382
- const headerInteractivePersistents = persistentsHeaders.filter(p => Boolean(p.onClick));
383
- const footerInteractivePersistents = persistentsFooters.filter(p => Boolean(p.onClick));
384
- const mainNavigableCount = renderable.reduce((c, i) => c + (i.kind === "section" ? 0 : 1), 0);
385
- const totalNavigableCount = headerInteractivePersistents.length +
386
- mainNavigableCount +
387
- footerInteractivePersistents.length;
388
- // Compute the currently selected index in the global navigable list (header -> middle -> footer).
389
- // In multiple mode this is always null — there is no single "selected" index, and
390
- // floating-ui would otherwise jump the highlight whenever the value array changes.
391
- const selectedIndex = React.useMemo(() => {
392
- if (multiple)
393
- return null;
394
- const selectedValue = value;
395
- if (!selectedValue)
396
- return null;
397
- const middleIndex = findNavigableIndexForValue(renderable, equals, selectedValue);
398
- if (middleIndex == null)
399
- return null;
400
- return headerInteractivePersistents.length + middleIndex;
401
- }, [
402
- multiple,
403
- value,
404
- renderable,
405
- equals,
406
- headerInteractivePersistents.length,
407
- ]);
408
- const { refs, floatingStyles, context, getReferenceProps, getFloatingProps, getItemProps, activeIndex, setActiveIndex, listRef, open, setOpen, setReferenceElement, } = useAutocompleteListNav({
409
- navigableCount: totalNavigableCount,
410
- shouldResetActiveIndexOnClose: () => !hasSelection,
411
- selectedIndex,
412
- readOnly,
413
- disabled,
414
- outsidePressExcludeSelector: multiple
415
- ? "[data-testid='ATL-AutocompleteRebuilt-chipArea']"
416
- : undefined,
417
- onMenuOpen: () => {
418
- if (multiple)
419
- return;
420
- const selectedValue = value;
421
- if (selectedValue) {
422
- const selectedNavigableIndex = findNavigableIndexForValue(renderable, equals, selectedValue);
423
- if (selectedNavigableIndex != null) {
424
- setActiveIndex(selectedNavigableIndex);
425
- return;
426
- }
427
- }
428
- setActiveIndex(null);
429
- },
430
- onMenuClose: () => {
431
- if (props.allowFreeForm !== true) {
432
- const hasText = inputValue.trim().length > 0;
433
- if (hasText && !hasSelection) {
434
- lastInputWasUser.current = false;
435
- onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange("");
436
- setActiveIndex(null);
437
- }
438
- }
439
- },
440
- });
441
- const prevOpenRef = React.useRef(false);
442
- // TODO: Leverage FloatingUI useFocus, and onArrowKeyDown to manage open state and allow onOpenChange to be the source of truth
443
- // JOB-154442
444
- React.useEffect(() => {
445
- var _a, _b;
446
- if (open && !prevOpenRef.current) {
447
- (_a = props.onOpen) === null || _a === void 0 ? void 0 : _a.call(props);
448
- }
449
- else if (!open && prevOpenRef.current) {
450
- (_b = props.onClose) === null || _b === void 0 ? void 0 : _b.call(props);
451
- }
452
- prevOpenRef.current = open;
453
- }, [open, props.onOpen, props.onClose]);
454
- function selectOption(option) {
455
- var _a;
456
- if (multiple) {
457
- const current = (_a = value) !== null && _a !== void 0 ? _a : EMPTY_SELECTED_VALUES;
458
- const exists = current.some(v => equals(v, option));
459
- const next = exists
460
- ? current.filter(v => !equals(v, option))
461
- : [...current, option];
462
- onChange((next.length === 0 ? EMPTY_SELECTED_VALUES : next));
463
- lastInputWasUser.current = false;
464
- onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange("");
465
- }
466
- else {
467
- onChange(option);
468
- lastInputWasUser.current = false;
469
- onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange(getOptionLabel(option));
470
- }
471
- }
472
- function reHighlightSelectedItem() {
473
- const selectedValue = value;
474
- if (!selectedValue)
475
- return;
476
- const idx = findNavigableIndexForValue(renderable, equals, selectedValue);
477
- if (idx != null)
478
- setActiveIndex(idx);
479
- }
480
- function tryCommitFreeFormOnEnter() {
481
- if (props.allowFreeForm !== true)
482
- return false;
483
- if (open && activeIndex != null)
484
- return false;
485
- const inputText = inputValue.trim();
486
- if (inputText.length === 0)
487
- return false;
488
- commitFromInputText(inputText);
489
- return true;
490
- }
491
- const onSelection = React.useCallback((option) => {
492
- var _a;
493
- selectOption(option);
494
- if (!multiple) {
495
- setOpen(false);
496
- }
497
- (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
498
- }, [selectOption, setOpen, multiple, inputRef]);
499
- const onAction = React.useCallback((action) => {
500
- var _a;
501
- action.run();
502
- setActiveIndex(null);
503
- if (action.closeOnRun !== false)
504
- setOpen(false);
505
- (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
506
- }, [setOpen, setActiveIndex, inputRef]);
507
- /**
508
- * Handler for mousedown on interactive menu items (options/actions)
509
- * Prevents default to avoid blur and sets flag for focus management
510
- */
511
- const onInteractionPointerDown = React.useMemo(() => createInteractionPointerDownHandler(isHandlingMenuInteractionRef), []);
512
- function applyFreeFormValue(freeFormCreated) {
513
- var _a;
514
- const nextValue = multiple
515
- ? [...((_a = value) !== null && _a !== void 0 ? _a : EMPTY_SELECTED_VALUES), freeFormCreated]
516
- : freeFormCreated;
517
- props.onChange(nextValue);
518
- if (multiple) {
519
- lastInputWasUser.current = false;
520
- onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange("");
521
- }
522
- }
523
- function commitFromInputText(inputText) {
524
- var _a;
525
- if (inputText.length === 0)
526
- return false;
527
- const match = optionItems.find(o => inputEquals(inputText, o));
528
- if (match) {
529
- onSelection(match);
530
- return true;
531
- }
532
- setOpen(false);
533
- if (props.allowFreeForm !== true)
534
- return false;
535
- const freeFormCreated = (_a = props.createFreeFormValue) === null || _a === void 0 ? void 0 : _a.call(props, inputText);
536
- if (!freeFormCreated)
537
- return false;
538
- applyFreeFormValue(freeFormCreated);
539
- return true;
540
- }
541
- const tryRestoreInputToSelectedLabel = React.useCallback(() => {
542
- if (props.allowFreeForm === true)
543
- return;
544
- if (multiple) {
545
- if (inputValue.trim().length > 0) {
546
- lastInputWasUser.current = false;
547
- onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange("");
548
- }
549
- return;
550
- }
551
- const selectedValue = value;
552
- if (!selectedValue)
553
- return;
554
- const selectedLabel = getOptionLabel(selectedValue);
555
- if (inputValue === selectedLabel)
556
- return;
557
- lastInputWasUser.current = false;
558
- onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange(selectedLabel);
559
- }, [
560
- props.allowFreeForm,
561
- getOptionLabel,
562
- inputValue,
563
- onInputChange,
564
- multiple,
565
- value,
566
- ]);
567
- const onInputFocus = React.useCallback((event) => {
568
- var _a;
569
- if (!readOnly && openOnFocus && !isHandlingMenuInteractionRef.current) {
570
- setOpen(true);
571
- }
572
- // Only call user's onFocus for genuine focus events, not programmatic restorations
573
- if (!isHandlingMenuInteractionRef.current) {
574
- (_a = props.onFocus) === null || _a === void 0 ? void 0 : _a.call(props, event);
575
- }
576
- isHandlingMenuInteractionRef.current = false;
577
- }, [props.onFocus, readOnly, openOnFocus, setOpen]);
578
- const onInputBlur = React.useCallback((event) => {
579
- var _a, _b;
580
- if (isHandlingMenuInteractionRef.current) {
581
- return;
582
- }
583
- if (readOnly) {
584
- (_a = props.onBlur) === null || _a === void 0 ? void 0 : _a.call(props, event);
585
- return;
586
- }
587
- if (props.allowFreeForm === true) {
588
- const inputText = inputValue.trim();
589
- if (inputText.length > 0)
590
- commitFromInputText(inputText);
591
- }
592
- else {
593
- tryRestoreInputToSelectedLabel();
594
- }
595
- lastInputWasUser.current = false;
596
- (_b = props.onBlur) === null || _b === void 0 ? void 0 : _b.call(props, event);
597
- }, [
598
- readOnly,
599
- props.allowFreeForm,
600
- inputValue,
601
- props.onBlur,
602
- tryRestoreInputToSelectedLabel,
603
- setOpen,
604
- ]);
605
- function getRegionByActiveIndex(index) {
606
- const headerCount = headerInteractivePersistents.length;
607
- const mainCount = mainNavigableCount;
608
- if (index < headerCount)
609
- return { region: "header", regionIndex: index };
610
- const middleIndex = index - headerCount;
611
- if (middleIndex < mainCount) {
612
- return { region: "middle", regionIndex: middleIndex };
613
- }
614
- return {
615
- region: "footer",
616
- regionIndex: middleIndex - mainCount,
617
- };
618
- }
619
- function computeInitialIndexForArrowUp() {
620
- // If there are interactive footers, prefer the very last navigable item
621
- if (footerInteractivePersistents.length > 0) {
622
- return totalNavigableCount > 0 ? totalNavigableCount - 1 : null;
623
- }
624
- // Otherwise, prefer the last OPTION (not action), matching legacy behavior
625
- let navigable = -1;
626
- let lastOptionIdx = -1;
627
- for (const item of renderable) {
628
- if (item.kind === "section")
629
- continue;
630
- navigable += 1;
631
- if (item.kind === "option")
632
- lastOptionIdx = navigable;
633
- }
634
- if (lastOptionIdx >= 0) {
635
- return headerInteractivePersistents.length + lastOptionIdx;
636
- }
637
- return totalNavigableCount > 0 ? totalNavigableCount - 1 : null;
638
- }
639
- function handleArrowNavigation(key, event) {
640
- if (!open) {
641
- setOpen(true);
642
- return;
643
- }
644
- if (activeIndex == null) {
645
- setActiveIndex(key === "ArrowDown" ? 0 : computeInitialIndexForArrowUp());
646
- event.preventDefault();
647
- }
648
- }
649
- function handleEnterKey(event) {
650
- if (tryCommitFreeFormOnEnter()) {
651
- event.preventDefault();
652
- return;
653
- }
654
- if (!open || activeIndex == null)
655
- return;
656
- const { region, regionIndex } = getRegionByActiveIndex(activeIndex);
657
- if (region === "middle") {
658
- invokeActiveItemOnEnter(event, regionIndex, renderable, onSelection, onAction);
659
- return;
660
- }
661
- const persistent = region === "header"
662
- ? headerInteractivePersistents[regionIndex]
663
- : footerInteractivePersistents[regionIndex];
664
- if (persistent === null || persistent === void 0 ? void 0 : persistent.onClick) {
665
- onAction({
666
- run: persistent.onClick,
667
- closeOnRun: persistent.shouldClose,
668
- });
669
- }
670
- }
671
- const removeLastSelection = React.useCallback(() => {
672
- var _a;
673
- if (!multiple || readOnly)
674
- return;
675
- const current = (_a = value) !== null && _a !== void 0 ? _a : EMPTY_SELECTED_VALUES;
676
- if (current.length > 0) {
677
- const next = current.slice(0, -1);
678
- onChange((next.length === 0 ? EMPTY_SELECTED_VALUES : next));
679
- }
680
- }, [multiple, readOnly, value, onChange]);
681
- const removeSelection = React.useCallback((option) => {
682
- var _a;
683
- if (readOnly)
684
- return;
685
- if (multiple) {
686
- const current = (_a = value) !== null && _a !== void 0 ? _a : EMPTY_SELECTED_VALUES;
687
- const next = current.filter(v => !equals(v, option));
688
- onChange((next.length === 0
689
- ? EMPTY_SELECTED_VALUES
690
- : next));
691
- }
692
- else {
693
- const current = value;
694
- if (current && equals(current, option)) {
695
- onChange(undefined);
696
- }
697
- }
698
- }, [readOnly, multiple, value, equals, onChange]);
699
- const onInputKeyDown = React.useCallback((event) => {
700
- const key = event.key;
701
- if (key === "Backspace" && multiple && inputValue === "") {
702
- removeLastSelection();
703
- return;
704
- }
705
- if (key !== "ArrowDown" && key !== "ArrowUp" && key !== "Enter")
706
- return;
707
- if (key === "ArrowDown" || key === "ArrowUp") {
708
- handleArrowNavigation(key, event);
709
- return;
710
- }
711
- handleEnterKey(event);
712
- }, [open, onSelection, onAction, multiple, inputValue, removeLastSelection]);
713
- const onInputChangeFromUser = React.useCallback((val) => {
714
- lastInputWasUser.current = true;
715
- const isEmpty = val.trim().length === 0;
716
- if (isEmpty) {
717
- setActiveIndex(null);
718
- if (!multiple && hasSelection) {
719
- onChange === null || onChange === void 0 ? void 0 : onChange(undefined);
720
- }
721
- }
722
- else if (val.length > inputValue.length) {
723
- setActiveIndex(null);
724
- }
725
- else if (val.length < inputValue.length &&
726
- !multiple &&
727
- open &&
728
- hasSelection) {
729
- reHighlightSelectedItem();
730
- }
731
- if (!readOnly) {
732
- setOpen((!isEmpty && !props.allowFreeForm) || openOnFocus);
733
- }
734
- onInputChange === null || onInputChange === void 0 ? void 0 : onInputChange(val);
735
- }, [
736
- onInputChange,
737
- inputValue,
738
- setActiveIndex,
739
- readOnly,
740
- props.allowFreeForm,
741
- openOnFocus,
742
- setOpen,
743
- multiple,
744
- hasSelection,
745
- onChange,
746
- open,
747
- ]);
748
- const clearAll = React.useCallback(() => {
749
- if (multiple) {
750
- onChange(EMPTY_SELECTED_VALUES);
751
- }
752
- else {
753
- onChange(undefined);
754
- }
755
- onInputChangeFromUser("");
756
- }, [multiple, onChange, onInputChangeFromUser]);
757
- return {
758
- // rendering data
759
- renderable,
760
- optionCount,
761
- persistentsHeaders,
762
- persistentsFooters,
763
- headerInteractiveCount: headerInteractivePersistents.length,
764
- middleNavigableCount: mainNavigableCount,
765
- getOptionLabel,
766
- isOptionSelected,
767
- // floating-ui
768
- refs,
769
- floatingStyles,
770
- context,
771
- getReferenceProps,
772
- getFloatingProps,
773
- getItemProps,
774
- // state
775
- open,
776
- setOpen,
777
- activeIndex,
778
- setActiveIndex,
779
- listRef,
780
- // actions
781
- onSelection,
782
- onAction,
783
- onInteractionPointerDown,
784
- removeSelection,
785
- clearAll,
786
- // input handlers
787
- onInputChangeFromUser,
788
- onInputBlur,
789
- onInputFocus,
790
- onInputKeyDown,
791
- // ref attachment
792
- setReferenceElement,
793
- };
794
- }
795
-
796
- function useChipNavigation({ selectedValues, inputValue, readOnly, removeSelection, onInputKeyDown, onInputBlur, }) {
797
- const [rawActiveChipIndex, setRawActiveChipIndex] = React.useState(null);
798
- const [previousInputValue, setPreviousInputValue] = React.useState(inputValue);
799
- const activeChipIndex = clampActiveIndex(rawActiveChipIndex, selectedValues.length);
800
- if (previousInputValue !== inputValue) {
801
- setPreviousInputValue(inputValue);
802
- if (inputValue !== "" && rawActiveChipIndex !== null) {
803
- setRawActiveChipIndex(null);
804
- }
805
- }
806
- const handleActiveChipKey = React.useCallback(
807
- // eslint-disable-next-line max-statements
808
- (event) => {
809
- if (activeChipIndex === null)
810
- return false;
811
- const { key } = event;
812
- if (key === "ArrowLeft") {
813
- event.preventDefault();
814
- setRawActiveChipIndex(i => Math.max(0, (i !== null && i !== void 0 ? i : 0) - 1));
815
- return true;
816
- }
817
- if (key === "ArrowRight") {
818
- event.preventDefault();
819
- setRawActiveChipIndex(activeChipIndex + 1 >= selectedValues.length
820
- ? null
821
- : activeChipIndex + 1);
822
- return true;
823
- }
824
- if (key === "Backspace" || key === "Delete") {
825
- event.preventDefault();
826
- const option = selectedValues[activeChipIndex];
827
- const newLen = selectedValues.length - 1;
828
- if (newLen === 0) {
829
- setRawActiveChipIndex(null);
830
- }
831
- else if (activeChipIndex >= newLen) {
832
- setRawActiveChipIndex(newLen - 1);
833
- }
834
- removeSelection(option);
835
- return true;
836
- }
837
- if (key === "Escape") {
838
- setRawActiveChipIndex(null);
839
- return true;
840
- }
841
- setRawActiveChipIndex(null);
842
- return false;
843
- }, [activeChipIndex, selectedValues, removeSelection]);
844
- const onKeyDown = React.useCallback((event) => {
845
- if (handleActiveChipKey(event))
846
- return;
847
- if (event.key === "ArrowLeft" &&
848
- !readOnly &&
849
- inputValue === "" &&
850
- selectedValues.length > 0) {
851
- event.preventDefault();
852
- setRawActiveChipIndex(selectedValues.length - 1);
853
- return;
854
- }
855
- onInputKeyDown(event);
856
- }, [handleActiveChipKey, selectedValues, inputValue, readOnly, onInputKeyDown]);
857
- const onBlur = React.useCallback((event) => {
858
- setRawActiveChipIndex(null);
859
- onInputBlur(event);
860
- }, [onInputBlur]);
861
- return { activeChipIndex, onKeyDown, onBlur };
862
- }
863
- function clampActiveIndex(index, length) {
864
- if (index === null)
865
- return null;
866
- if (length === 0)
867
- return null;
868
- if (index >= length)
869
- return length - 1;
870
- return index;
871
- }
872
-
873
- function MenuList({ items, activeIndex, indexOffset = 0, getItemProps, listRef, listboxId, customRenderOption, customRenderSection, customRenderAction, getOptionLabel, onSelect, onAction, onInteractionPointerDown, isOptionSelected, slotOverrides, }) {
874
- let navigableIndex = -1;
875
- function renderItemNode(item) {
876
- var _a, _b, _c, _d, _e, _f;
877
- if (item.kind === "section") {
878
- return handleSectionRendering({
879
- section: item.section,
880
- customRenderSection,
881
- sectionClassName: (_a = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.section) === null || _a === void 0 ? void 0 : _a.className,
882
- sectionStyle: (_b = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.section) === null || _b === void 0 ? void 0 : _b.style,
883
- });
884
- }
885
- if (item.kind === "option") {
886
- const result = handleOptionRendering({
887
- option: item.value,
888
- activeIndex,
889
- navigableIndex,
890
- getItemProps,
891
- listRef,
892
- listboxId,
893
- isOptionSelected,
894
- customRenderOption,
895
- getOptionLabel,
896
- onSelect,
897
- onInteractionPointerDown,
898
- indexOffset,
899
- optionClassName: (_c = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.option) === null || _c === void 0 ? void 0 : _c.className,
900
- optionStyle: (_d = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.option) === null || _d === void 0 ? void 0 : _d.style,
901
- });
902
- navigableIndex = result.nextNavigableIndex;
903
- return result.node;
904
- }
905
- const result = handleActionRendering({
906
- action: item.action,
907
- activeIndex,
908
- navigableIndex,
909
- getItemProps,
910
- listRef,
911
- listboxId,
912
- customRenderAction,
913
- onAction,
914
- onInteractionPointerDown,
915
- indexOffset,
916
- actionClassName: (_e = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.action) === null || _e === void 0 ? void 0 : _e.className,
917
- actionStyle: (_f = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.action) === null || _f === void 0 ? void 0 : _f.style,
918
- origin: item.origin,
919
- });
920
- navigableIndex = result.nextNavigableIndex;
921
- return result.node;
922
- }
923
- return React.createElement(React.Fragment, null, items.map(renderItemNode));
924
- }
925
- function handleSectionRendering({ customRenderSection, section, sectionClassName, sectionStyle, }) {
926
- var _a;
927
- const headerContent = customRenderSection ? (customRenderSection(section)) : (React.createElement(DefaultSectionContent, { section: section }));
928
- return (React.createElement("div", { key: `section-${String((_a = section.key) !== null && _a !== void 0 ? _a : section.label)}`, role: "presentation", tabIndex: -1, "data-testid": "ATL-AutocompleteRebuilt-Section", className: classnames(styles$1.section, styles$1.stickyTop, sectionClassName), style: sectionStyle, onPointerDown: preventDefaultPointerDown }, headerContent));
929
- }
930
- function DefaultSectionContent({ section, }) {
931
- return React.createElement(Heading.Heading, { level: 5 }, section.label);
932
- }
933
- function handleOptionRendering({ option, activeIndex, navigableIndex, getItemProps, listRef, listboxId, isOptionSelected, customRenderOption, getOptionLabel, onSelect, onInteractionPointerDown, indexOffset = 0, optionClassName, optionStyle, }) {
934
- var _a;
935
- const nextNavigableIndex = navigableIndex + 1;
936
- const isActive = activeIndex === nextNavigableIndex;
937
- const isSelected = isOptionSelected(option);
938
- const optionContent = customRenderOption ? (customRenderOption({ value: option, isActive, isSelected })) : (React.createElement(DefaultOptionContent, { isSelected: isSelected, text: getOptionLabel(option) }));
939
- return {
940
- node: (React.createElement("div", Object.assign({ key: `option-${String((_a = option.key) !== null && _a !== void 0 ? _a : getOptionLabel(option))}` }, getItemProps({
941
- ref(node) {
942
- const idx = nextNavigableIndex + indexOffset;
943
- if (node)
944
- listRef.current[idx] = node;
945
- },
946
- onClick: () => onSelect(option),
947
- onPointerDown: onInteractionPointerDown,
948
- className: classnames(styles$1.option, isActive && styles$1.optionActive, optionClassName),
949
- style: optionStyle,
950
- }), { role: "option", tabIndex: -1, "aria-selected": isSelected ? true : false, id: `${listboxId}-item-${nextNavigableIndex + indexOffset}`, "data-index": nextNavigableIndex + indexOffset, "data-active": isActive ? true : undefined }), optionContent)),
951
- nextNavigableIndex,
952
- };
953
- }
954
- function DefaultOptionContent({ isSelected, text, }) {
955
- return (React.createElement("div", { className: styles$1.defaultOptionContent },
956
- React.createElement("div", { className: styles$1.icon, style: isSelected ? undefined : { visibility: "hidden" } },
957
- React.createElement(Icon.Icon, { name: "checkmark", size: "small" })),
958
- React.createElement(Text.Text, null, text)));
959
- }
960
- function handleActionRendering({ action, activeIndex, navigableIndex, getItemProps, listRef, listboxId, customRenderAction, onAction, onInteractionPointerDown, indexOffset = 0, actionClassName, actionStyle, origin, }) {
961
- var _a;
962
- const nextNavigableIndex = navigableIndex + 1;
963
- const isActive = activeIndex === nextNavigableIndex;
964
- const actionContent = customRenderAction ? (customRenderAction({ value: action, isActive, origin })) : (React.createElement(DefaultActionContent, { textContent: action.label }));
965
- const computedIndex = nextNavigableIndex + indexOffset;
966
- const itemProps = getItemProps({
967
- ref(node) {
968
- if (node) {
969
- listRef.current[computedIndex] = node;
970
- }
971
- },
972
- onClick: () => {
973
- onAction({
974
- run: action.onClick,
975
- closeOnRun: action.shouldClose,
976
- });
977
- },
978
- onPointerDown: onInteractionPointerDown,
979
- className: classnames(styles$1.action, isActive && styles$1.actionActive, actionClassName),
980
- style: actionStyle,
981
- });
982
- return {
983
- node: (React.createElement("div", Object.assign({ key: `action-${String((origin !== null && origin !== void 0 ? origin : "menu") + "-" + ((_a = action.key) !== null && _a !== void 0 ? _a : action.label))}` }, itemProps, { role: "button", tabIndex: -1, "data-testid": "ATL-AutocompleteRebuilt-Action", id: `${listboxId}-item-${computedIndex}`, "data-index": computedIndex, "data-origin": origin, "data-active": isActive ? true : undefined }), actionContent)),
984
- nextNavigableIndex,
985
- };
986
- }
987
- function DefaultActionContent({ textContent, }) {
988
- return (React.createElement(Typography.Typography, { textColor: "interactive", fontWeight: "semiBold", underline: "solid color-interactive", UNSAFE_style: {
989
- textStyle: {
990
- textDecorationThickness: "var(--border-thick)",
991
- textUnderlineOffset: "var(--space-smallest)",
992
- },
993
- } }, textContent));
994
- }
995
-
996
- function PersistentRegion({ items, position, activeIndex, indexOffset, getItemProps, listRef, customRenderHeader, customRenderFooter, className, style, onAction, onInteractionPointerDown, }) {
997
- if (!items || items.length === 0)
998
- return null;
999
- let navigableIndex = -1;
1000
- return (React.createElement("div", { className: className, style: style, "data-region": position, "data-testid": `ATL-AutocompleteRebuilt-${position}` }, items.map(persistent => {
1001
- const result = handlePersistentRendering({
1002
- persistent,
1003
- position,
1004
- activeIndex,
1005
- indexOffset,
1006
- getItemProps,
1007
- customRenderHeader,
1008
- customRenderFooter,
1009
- listRef,
1010
- onAction,
1011
- onInteractionPointerDown,
1012
- navigableIndex,
1013
- });
1014
- navigableIndex = result.nextNavigableIndex;
1015
- return result.node;
1016
- })));
1017
- }
1018
- function handlePersistentRendering({ persistent, position, activeIndex, indexOffset, getItemProps, customRenderHeader, customRenderFooter, listRef, onAction, onInteractionPointerDown, navigableIndex, }) {
1019
- const interactive = Boolean(persistent.onClick);
1020
- if (!interactive) {
1021
- const node = handleTextPersistentRendering({
1022
- persistent,
1023
- position,
1024
- customRenderHeader,
1025
- customRenderFooter,
1026
- });
1027
- return { node, nextNavigableIndex: navigableIndex };
1028
- }
1029
- return handleActionPersistentRendering({
1030
- persistent,
1031
- position,
1032
- activeIndex,
1033
- indexOffset,
1034
- getItemProps,
1035
- customRenderHeader,
1036
- customRenderFooter,
1037
- listRef,
1038
- onAction,
1039
- onInteractionPointerDown,
1040
- navigableIndex,
1041
- });
1042
- }
1043
- function handleTextPersistentRendering({ persistent, position, customRenderHeader, customRenderFooter, }) {
1044
- var _a;
1045
- let content;
1046
- if (position === "header" && customRenderHeader) {
1047
- content = customRenderHeader({ value: persistent });
1048
- }
1049
- else if (position === "footer" && customRenderFooter) {
1050
- content = customRenderFooter({ value: persistent });
1051
- }
1052
- else {
1053
- content = React.createElement(DefaultTextPersistentContent, { persistent: persistent });
1054
- }
1055
- return (React.createElement("div", { key: `persistent-${position}-${String((_a = persistent.key) !== null && _a !== void 0 ? _a : persistent.label)}`, role: "presentation", tabIndex: -1, className: styles$1.textPersistent, onPointerDown: preventDefaultPointerDown }, content));
1056
- }
1057
- function handleActionPersistentRendering({ persistent, position, activeIndex, indexOffset, getItemProps, customRenderHeader, customRenderFooter, listRef, onAction, onInteractionPointerDown, navigableIndex, }) {
1058
- var _a;
1059
- const nextNavigableIndex = navigableIndex + 1;
1060
- const isActive = activeIndex === indexOffset + nextNavigableIndex;
1061
- let content;
1062
- if (position === "header" && customRenderHeader) {
1063
- content = customRenderHeader({
1064
- value: persistent,
1065
- isActive,
1066
- });
1067
- }
1068
- else if (position === "footer" && customRenderFooter) {
1069
- content = customRenderFooter({
1070
- value: persistent,
1071
- isActive,
1072
- });
1073
- }
1074
- else {
1075
- content = React.createElement(DefaultActionContent, { textContent: persistent.label });
1076
- }
1077
- return {
1078
- node: (React.createElement("div", Object.assign({ key: `persistent-${position}-${String((_a = persistent.key) !== null && _a !== void 0 ? _a : persistent.label)}`, "data-index": indexOffset + nextNavigableIndex, id: `${position}-persistent-${indexOffset + nextNavigableIndex}`, "data-active": isActive ? true : undefined }, getItemProps({
1079
- ref(persistNode) {
1080
- const idx = indexOffset + nextNavigableIndex;
1081
- if (persistNode)
1082
- listRef.current[idx] = persistNode;
1083
- },
1084
- onClick: () => {
1085
- onAction({
1086
- run: () => {
1087
- var _a;
1088
- (_a = persistent.onClick) === null || _a === void 0 ? void 0 : _a.call(persistent);
1089
- },
1090
- closeOnRun: persistent.shouldClose,
1091
- });
1092
- },
1093
- onPointerDown: onInteractionPointerDown,
1094
- className: classnames(styles$1.action, isActive && styles$1.actionActive),
1095
- }), { role: "button", tabIndex: -1 }), content)),
1096
- nextNavigableIndex,
1097
- };
1098
- }
1099
- function DefaultTextPersistentContent({ persistent, }) {
1100
- return React.createElement("div", { className: styles$1.textPersistent }, persistent.label);
1101
- }
1102
-
1103
- function FloatingMenu({ context, getFloatingProps, refs, listboxId, className, floatingStyles, transitionStyles, menuStyle, renderable, persistentsHeaders, persistentsFooters, activeIndex, headerInteractiveCount, middleNavigableCount, getItemProps, listRef, onSelection, onAction, onInteractionPointerDown, getOptionLabel, isOptionSelected, loading, showEmptyStateMessage, emptyStateMessage, customRenderLoading, customRenderOption, customRenderSection, customRenderAction, customRenderHeader, customRenderFooter, slotOverrides, }) {
1104
- var _a, _b, _c, _d;
1105
- const activeIndexForMiddle = activeIndex != null ? activeIndex - headerInteractiveCount : null;
1106
- return (React.createElement(floatingUi_react.FloatingPortal, null,
1107
- React.createElement(floatingUi_react.FloatingFocusManager, { context: context, modal: false, initialFocus: -1, closeOnFocusOut: true, returnFocus: false },
1108
- React.createElement("div", Object.assign({}, getFloatingProps({
1109
- ref(node) {
1110
- if (node)
1111
- refs.setFloating(node);
1112
- },
1113
- id: listboxId,
1114
- role: "listbox",
1115
- className,
1116
- style: Object.assign(Object.assign(Object.assign({}, floatingStyles), transitionStyles), menuStyle),
1117
- })),
1118
- React.createElement(PersistentRegion, { items: persistentsHeaders, position: "header", activeIndex: activeIndex, indexOffset: 0, listboxId: listboxId, getItemProps: getItemProps, listRef: listRef, customRenderHeader: customRenderHeader, customRenderFooter: customRenderFooter, onAction: onAction, onInteractionPointerDown: onInteractionPointerDown, className: classnames(styles$1.persistentHeader, (_a = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.header) === null || _a === void 0 ? void 0 : _a.className), style: (_b = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.header) === null || _b === void 0 ? void 0 : _b.style }),
1119
- React.createElement("div", { className: styles$1.scrollRegion }, loading ? (customRenderLoading !== null && customRenderLoading !== void 0 ? customRenderLoading : React.createElement(LoadingContent, null)) : (React.createElement(React.Fragment, null,
1120
- showEmptyStateMessage && (React.createElement(EmptyStateMessage, { emptyState: emptyStateMessage })),
1121
- renderable.length > 0 && (React.createElement(MenuList, { items: renderable, activeIndex: activeIndexForMiddle, indexOffset: headerInteractiveCount, listboxId: listboxId, getItemProps: getItemProps, listRef: listRef, customRenderOption: customRenderOption, customRenderSection: customRenderSection, customRenderAction: customRenderAction, getOptionLabel: getOptionLabel, onSelect: onSelection, onAction: onAction, onInteractionPointerDown: onInteractionPointerDown, isOptionSelected: isOptionSelected, slotOverrides: slotOverrides }))))),
1122
- React.createElement(PersistentRegion, { items: persistentsFooters, position: "footer", activeIndex: activeIndex, indexOffset: headerInteractiveCount + middleNavigableCount, listboxId: listboxId, getItemProps: getItemProps, listRef: listRef, customRenderHeader: customRenderHeader, customRenderFooter: customRenderFooter, onAction: onAction, onInteractionPointerDown: onInteractionPointerDown, className: classnames(styles$1.persistentFooter, (_c = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.footer) === null || _c === void 0 ? void 0 : _c.className), style: (_d = slotOverrides === null || slotOverrides === void 0 ? void 0 : slotOverrides.footer) === null || _d === void 0 ? void 0 : _d.style })))));
1123
- }
1124
- function LoadingContent() {
1125
- return (React.createElement("div", { className: styles$1.loadingList, onPointerDown: preventDefaultPointerDown },
1126
- React.createElement(Glimmer.Glimmer, { shape: "rectangle", size: "base" }),
1127
- React.createElement(Glimmer.Glimmer, { shape: "rectangle", size: "base" }),
1128
- React.createElement(Glimmer.Glimmer, { shape: "rectangle", size: "base" })));
1129
- }
1130
- function EmptyStateMessage({ emptyState, }) {
1131
- const emptyStateDefault = "No options";
1132
- const emptyStateContent = emptyState !== null && emptyState !== void 0 ? emptyState : emptyStateDefault;
1133
- return (React.createElement("div", { className: styles$1.emptyStateMessage, onPointerDown: preventDefaultPointerDown }, emptyStateContent));
1134
- }
1135
-
1136
- const AutocompleteRebuilt = React.forwardRef(AutocompleteRebuiltInternal);
1137
- // eslint-disable-next-line max-statements
1138
- function AutocompleteRebuiltInternal(props, forwardedRef) {
1139
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
1140
- const { inputValue, placeholder, disabled, error, invalid, description, size: sizeProp, loading = false, } = props;
1141
- const formFieldRef = React.useRef(null);
1142
- // Ref for the multi-select input element, where we cannot use refs.domReference
1143
- // since it is not attached to the literal input element, whereas single + InputText only offers a
1144
- // ref to the literal input element.
1145
- const internalInputRef = React.useRef(null);
1146
- const { renderable, optionCount, persistentsHeaders, persistentsFooters, headerInteractiveCount, middleNavigableCount, getOptionLabel, isOptionSelected, refs, floatingStyles, context, getReferenceProps, getFloatingProps, getItemProps, activeIndex, open, listRef, onSelection, onAction, onInteractionPointerDown, removeSelection, onInputChangeFromUser, onInputBlur, onInputFocus, onInputKeyDown, setReferenceElement, clearAll, } = useAutocomplete(props, internalInputRef);
1147
- const listboxId = React.useId();
1148
- // Provides mount/unmount-aware transition styles for the floating element
1149
- const { isMounted, styles: transitionStyles } = floatingUi_react.useTransitionStyles(context, {
1150
- initial: { opacity: 0 },
1151
- open: { opacity: 1 },
1152
- close: { opacity: 0 },
1153
- duration: { open: design.tokens["timing-base"], close: design.tokens["timing-base"] },
1154
- });
1155
- const [positionRefEl, setPositionRefEl] = React.useState(null);
1156
- const inputId = React.useId();
1157
- const descriptionId = `descriptionUUID--${inputId}`;
1158
- const selectedValues = props.multiple
1159
- ? ((_a = props.value) !== null && _a !== void 0 ? _a : EMPTY_SELECTED_VALUES)
1160
- : EMPTY_SELECTED_VALUES;
1161
- const { activeChipIndex, onKeyDown: chipKeyDown, onBlur: chipBlur, } = useChipNavigation({
1162
- selectedValues,
1163
- inputValue,
1164
- readOnly: props.readOnly,
1165
- removeSelection,
1166
- onInputKeyDown,
1167
- onInputBlur,
1168
- });
1169
- const focusInputOnPointerDown = React.useCallback((e) => {
1170
- var _a;
1171
- const target = e.target;
1172
- if (target.closest("input, button"))
1173
- return;
1174
- e.preventDefault();
1175
- (_a = internalInputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
1176
- }, []);
1177
- const composedReferenceProps = getReferenceProps(Object.assign({ onKeyDown: props.multiple ? chipKeyDown : onInputKeyDown, onFocus: onInputFocus, onBlur: props.multiple ? chipBlur : onInputBlur }, (props.multiple ? { onPointerDown: focusInputOnPointerDown } : {})));
1178
- const dataAttrs = filterDataAttributes.filterDataAttributes(props);
1179
- const ariaProps = {
1180
- role: "combobox",
1181
- "aria-autocomplete": "list",
1182
- "aria-expanded": open ? true : false,
1183
- "aria-controls": listboxId,
1184
- "aria-activedescendant": activeChipIndex === null && open && activeIndex != null
1185
- ? `${listboxId}-item-${activeIndex}`
1186
- : undefined,
1187
- };
1188
- const inputProps = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ value: inputValue, onChange: props.readOnly ? undefined : onInputChangeFromUser }, (props.readOnly ? { onFocus: onInputFocus, onBlur: onInputBlur } : {})), { placeholder,
1189
- disabled, readOnly: props.readOnly, error: error !== null && error !== void 0 ? error : undefined, name: props.name, invalid, clearable: props.clearable, autoComplete: "off", autoFocus: props.autoFocus, description, size: sizeProp ? sizeProp : undefined, prefix: props.prefix, suffix: props.suffix }), (props.readOnly ? {} : composedReferenceProps)), ariaProps), dataAttrs);
1190
- const chipAreaRef = React.useCallback((node) => {
1191
- if (!node)
1192
- return;
1193
- // In multiple mode, we use the input as the reference so floating-ui's
1194
- // useListNavigation treats it as a typeable combobox and allows Space.
1195
- // Only use chipArea for positioning/sizing.
1196
- if (!props.multiple) {
1197
- setReferenceElement(node);
1198
- }
1199
- const multiContainer = node.closest("[data-testid='ATL-AutocompleteRebuilt-multiSelectContainer']");
1200
- if (multiContainer) {
1201
- setPositionRefEl(multiContainer);
1202
- }
1203
- }, [setReferenceElement, props.multiple]);
1204
- const referenceInputRef = React.useCallback((node) => {
1205
- setReferenceElement(node);
1206
- if (!props.multiple) {
1207
- // Workaround to get the visual InputText element, which is not the same
1208
- // as the literal input reference element when props like suffix/prefix
1209
- // are present. Used to set the position reference for the floating menu.
1210
- const visualInputTextElement = node === null || node === void 0 ? void 0 : node.closest("[data-testid='Form-Field-Wrapper']");
1211
- if (visualInputTextElement) {
1212
- setPositionRefEl(visualInputTextElement);
1213
- }
1214
- }
1215
- }, [setReferenceElement, props.multiple]);
1216
- const mergedInputRef = React.useMemo(() => mergeRefs.mergeRefs([
1217
- referenceInputRef,
1218
- internalInputRef,
1219
- forwardedRef,
1220
- ]), [referenceInputRef, forwardedRef]);
1221
- React.useEffect(() => {
1222
- if (!positionRefEl)
1223
- return;
1224
- refs.setPositionReference(positionRefEl);
1225
- }, [positionRefEl, refs]);
1226
- const menuClassName = classnames(styles$1.list, (_b = props.UNSAFE_className) === null || _b === void 0 ? void 0 : _b.menu);
1227
- const showEmptyStateMessage = optionCount === 0 && props.emptyStateMessage !== false;
1228
- const floatingMenu = isMounted && !props.readOnly && !disabled && (React.createElement(FloatingMenu, { context: context, getFloatingProps: getFloatingProps, refs: refs, listboxId: listboxId, className: menuClassName, floatingStyles: floatingStyles, transitionStyles: transitionStyles, menuStyle: (_c = props.UNSAFE_styles) === null || _c === void 0 ? void 0 : _c.menu, renderable: renderable, persistentsHeaders: persistentsHeaders, persistentsFooters: persistentsFooters, activeIndex: activeIndex, headerInteractiveCount: headerInteractiveCount, middleNavigableCount: middleNavigableCount, getItemProps: getItemProps, listRef: listRef, onSelection: onSelection, onAction: onAction, onInteractionPointerDown: onInteractionPointerDown, getOptionLabel: getOptionLabel, isOptionSelected: isOptionSelected, loading: loading, showEmptyStateMessage: showEmptyStateMessage, emptyStateMessage: props.emptyStateMessage, customRenderLoading: props.customRenderLoading, customRenderOption: props.customRenderOption, customRenderSection: props.customRenderSection, customRenderAction: props.customRenderAction, customRenderHeader: props.customRenderHeader, customRenderFooter: props.customRenderFooter, slotOverrides: {
1229
- option: {
1230
- className: (_d = props.UNSAFE_className) === null || _d === void 0 ? void 0 : _d.option,
1231
- style: (_e = props.UNSAFE_styles) === null || _e === void 0 ? void 0 : _e.option,
1232
- },
1233
- action: {
1234
- className: (_f = props.UNSAFE_className) === null || _f === void 0 ? void 0 : _f.action,
1235
- style: (_g = props.UNSAFE_styles) === null || _g === void 0 ? void 0 : _g.action,
1236
- },
1237
- section: {
1238
- className: (_h = props.UNSAFE_className) === null || _h === void 0 ? void 0 : _h.section,
1239
- style: (_j = props.UNSAFE_styles) === null || _j === void 0 ? void 0 : _j.section,
1240
- },
1241
- header: {
1242
- className: (_k = props.UNSAFE_className) === null || _k === void 0 ? void 0 : _k.header,
1243
- style: (_l = props.UNSAFE_styles) === null || _l === void 0 ? void 0 : _l.header,
1244
- },
1245
- footer: {
1246
- className: (_m = props.UNSAFE_className) === null || _m === void 0 ? void 0 : _m.footer,
1247
- style: (_o = props.UNSAFE_styles) === null || _o === void 0 ? void 0 : _o.footer,
1248
- },
1249
- } }));
1250
- if (props.customRenderInput) {
1251
- return (React.createElement("div", { "data-testid": "ATL-AutocompleteRebuilt" },
1252
- props.customRenderInput({ inputRef: mergedInputRef, inputProps }),
1253
- floatingMenu));
1254
- }
1255
- if (props.multiple) {
1256
- return (React.createElement(MultipleSelectionLayout, { selectedValues: selectedValues, inputValue: inputValue, disabled: disabled, error: error, invalid: invalid, sizeProp: sizeProp, inputId: inputId, descriptionId: descriptionId, description: description, placeholder: placeholder, clearable: props.clearable, prefix: props.prefix, suffix: props.suffix, readOnly: props.readOnly, name: props.name, autoFocus: props.autoFocus, formFieldRef: formFieldRef, chipAreaRef: chipAreaRef, mergedInputRef: mergedInputRef, internalInputRef: internalInputRef, activeChipIndex: activeChipIndex, getOptionLabel: getOptionLabel, customRenderValue: props.customRenderValue, removeSelection: removeSelection, clearAll: clearAll, onInputChangeFromUser: onInputChangeFromUser, chipAreaEventProps: props.readOnly
1257
- ? { onFocus: onInputFocus, onBlur: chipBlur }
1258
- : composedReferenceProps, inputAriaProps: ariaProps, inputDataAttrs: dataAttrs, limitVisibleSelections: props.limitVisibleSelections, limitSelectionText: props.limitSelectionText, unsafeClassName: (_p = props.UNSAFE_className) === null || _p === void 0 ? void 0 : _p.selection, unsafeStyle: (_q = props.UNSAFE_styles) === null || _q === void 0 ? void 0 : _q.selection }, floatingMenu));
1259
- }
1260
- return (React.createElement("div", { "data-testid": "ATL-AutocompleteRebuilt" },
1261
- React.createElement(InputText.InputText, Object.assign({ ref: mergedInputRef }, inputProps)),
1262
- floatingMenu));
1263
- }
1264
- function SelectionChip({ value, active, disabled, getOptionLabel, customRenderValue, canDismiss, onDismiss, unsafeClassName, unsafeStyle, }) {
1265
- return (React.createElement("span", { "data-selection-disabled": disabled, className: classnames(styles$1.selectionChip, {
1266
- [styles$1.selectionChipActive]: active,
1267
- [styles$1.selectionChipDisabled]: disabled,
1268
- }, unsafeClassName), style: unsafeStyle, "data-testid": "ATL-AutocompleteRebuilt-chip", onPointerDown: preventDefaultPointerDown },
1269
- customRenderValue ? (customRenderValue({ value, getOptionLabel })) : (React.createElement(Typography.Typography, { size: "small" }, getOptionLabel(value))),
1270
- canDismiss && (React.createElement("button", { type: "button", disabled: disabled, className: styles$1.chipDismiss, onClick: onDismiss, onPointerDown: preventDefaultPointerDown, "aria-label": `Remove ${getOptionLabel(value)}`, tabIndex: -1 },
1271
- React.createElement(Icon.Icon, { size: "small", name: "remove" })))));
1272
- }
1273
- function SelectionChipsList({ selectedValues, isFocused, limitVisibleSelections = 6, limitSelectionText = (count) => `+${count}`, activeChipIndex, disabled, getOptionLabel, customRenderValue, canDismiss, removeSelection, unsafeClassName, unsafeStyle, }) {
1274
- const shouldLimit = !isFocused &&
1275
- limitVisibleSelections !== -1 &&
1276
- selectedValues.length > limitVisibleSelections;
1277
- const visibleValues = shouldLimit
1278
- ? selectedValues.slice(0, limitVisibleSelections)
1279
- : selectedValues;
1280
- const hiddenCount = shouldLimit
1281
- ? selectedValues.length - limitVisibleSelections
1282
- : 0;
1283
- return (React.createElement(React.Fragment, null,
1284
- visibleValues.map((v, i) => {
1285
- var _a;
1286
- return (React.createElement(SelectionChip, { key: (_a = v.key) !== null && _a !== void 0 ? _a : getOptionLabel(v), value: v, active: activeChipIndex === i, disabled: disabled, getOptionLabel: getOptionLabel, customRenderValue: customRenderValue, canDismiss: canDismiss, onDismiss: () => removeSelection(v), unsafeClassName: unsafeClassName, unsafeStyle: unsafeStyle }));
1287
- }),
1288
- hiddenCount > 0 && (React.createElement("span", { className: styles$1.limitText, "data-testid": "ATL-AutocompleteRebuilt-limitText" },
1289
- React.createElement(Typography.Typography, { size: "small", element: "span" }, limitSelectionText(hiddenCount))))));
1290
- }
1291
- function MultipleSelectionLayout({ selectedValues, inputValue, disabled, error, invalid, sizeProp, inputId, descriptionId, description, placeholder, clearable, prefix, suffix, readOnly, name, autoFocus, formFieldRef, chipAreaRef, mergedInputRef, internalInputRef, activeChipIndex, getOptionLabel, customRenderValue, removeSelection, clearAll, onInputChangeFromUser, chipAreaEventProps, inputAriaProps, inputDataAttrs, limitVisibleSelections, limitSelectionText, unsafeClassName, unsafeStyle, children, }) {
1292
- var _a;
1293
- const [isFocused, setIsFocused] = React.useState(false);
1294
- const hasValue = selectedValues.length > 0 || inputValue;
1295
- const canDismissChip = !disabled && !readOnly;
1296
- const handleFocusIn = React.useCallback(() => {
1297
- setIsFocused(true);
1298
- }, []);
1299
- const handleFocusOut = React.useCallback((e) => {
1300
- if (!e.currentTarget.contains(e.relatedTarget)) {
1301
- setIsFocused(false);
1302
- }
1303
- }, []);
1304
- return (React.createElement("div", { "data-testid": "ATL-AutocompleteRebuilt", onFocus: handleFocusIn, onBlur: handleFocusOut },
1305
- React.createElement("div", { className: styles$1.multiSelectField, "data-testid": "ATL-AutocompleteRebuilt-multiSelectContainer" },
1306
- React.createElement(FormFieldWrapper.FormFieldWrapper, { disabled: disabled, size: sizeProp ? sizeProp : undefined, error: (_a = error) !== null && _a !== void 0 ? _a : "", invalid: Boolean(error || invalid), identifier: inputId, descriptionIdentifier: descriptionId, description: description, clearable: clearable !== null && clearable !== void 0 ? clearable : "never", onClear: () => {
1307
- var _a;
1308
- clearAll();
1309
- (_a = internalInputRef.current) === null || _a === void 0 ? void 0 : _a.focus();
1310
- }, type: "text", placeholder: placeholder, value: hasValue ? "has-value" : "", prefix: prefix, suffix: suffix, wrapperRef: formFieldRef },
1311
- React.createElement("div", Object.assign({ ref: chipAreaRef, className: styles$1.chipArea, "data-testid": "ATL-AutocompleteRebuilt-chipArea" }, chipAreaEventProps),
1312
- React.createElement(SelectionChipsList, { selectedValues: selectedValues, isFocused: isFocused, limitVisibleSelections: limitVisibleSelections, limitSelectionText: limitSelectionText, activeChipIndex: activeChipIndex, disabled: disabled, getOptionLabel: getOptionLabel, customRenderValue: customRenderValue, canDismiss: canDismissChip, removeSelection: removeSelection, unsafeClassName: unsafeClassName, unsafeStyle: unsafeStyle }),
1313
- React.createElement("input", Object.assign({ ref: mergedInputRef, className: styles$1.inlineInput, id: inputId, value: inputValue, onChange: readOnly
1314
- ? undefined
1315
- : e => onInputChangeFromUser(e.target.value), disabled: disabled, readOnly: readOnly, name: name, autoComplete: "off", autoFocus: autoFocus }, inputAriaProps, inputDataAttrs))))),
1316
- children));
1317
- }
1318
-
1319
- var styles = {"autocomplete":"_7mObJiwfPh4-","options":"dL5JShAJlKM-","heading":"PWZL-94hH7k-","visible":"_2RzcnTdaPyc-","option":"y9zhi8Wr8QA-","active":"_3Xg49dtL1Q8-","separator":"LIeh390F3W8-","icon":"K2phy6IC3TY-","text":"a6-LbUm5WnY-","label":"tQNbuxcE9nU-","details":"qacStG9-XbE-","spinning":"P9cQDL4MZ-s-"};
1320
-
1321
- function useRepositionMenu(attachTo, visible, cssManagedVisibility) {
1322
- const { refs, floatingStyles, update } = floatingUi_react.useFloating(Object.assign({ placement: "bottom", middleware: [
1323
- floatingUi_reactDom.offset(8),
1324
- floatingUi_reactDom.flip({ fallbackPlacements: ["top"] }),
1325
- floatingUi_reactDom.size({
1326
- apply({ availableHeight, elements }) {
1327
- const maxHeight$1 = maxHeight.calculateMaxHeight(availableHeight, {
1328
- maxHeight: AUTOCOMPLETE_MAX_HEIGHT$1,
1329
- });
1330
- Object.assign(elements.floating.style, {
1331
- maxHeight: `${maxHeight$1}px`,
1332
- });
1333
- },
1334
- }),
1335
- ], elements: {
1336
- reference: attachTo,
1337
- } }, (!cssManagedVisibility
1338
- ? {
1339
- whileElementsMounted: floatingUi_reactDom.autoUpdate,
1340
- }
1341
- : {})));
1342
- // While DefaultMenu leverages conditional rendering, CustomMenu is hidden with CSS
1343
- // We need to apply the correct update method to each case
1344
- jobberHooks.useSafeLayoutEffect(() => {
1345
- if (cssManagedVisibility && visible && attachTo && refs.floating.current) {
1346
- const cleanup = floatingUi_reactDom.autoUpdate(attachTo, refs.floating.current, update);
1347
- return cleanup;
1348
- }
1349
- return undefined;
1350
- }, [
1351
- cssManagedVisibility,
1352
- visible,
1353
- attachTo,
1354
- refs.floating.current,
1355
- update,
1356
- floatingUi_reactDom.autoUpdate,
1357
- ]);
1358
- const targetWidth = attachTo === null || attachTo === void 0 ? void 0 : attachTo.clientWidth;
1359
- return {
1360
- menuRef: refs.floating.current,
1361
- setMenuRef: refs.setFloating,
1362
- targetWidth,
1363
- styles: {
1364
- float: floatingStyles,
1365
- },
1366
- };
1367
- }
1368
-
1369
- function BaseAutocompleteMenuWrapperInternal({ setMenuRef, floatStyles, targetWidth, visible, children, }) {
1370
- return (React.createElement("div", { className: classnames(styles.options, { [styles.visible]: visible }), ref: setMenuRef, style: Object.assign(Object.assign({}, floatStyles.float), { width: targetWidth }), "data-elevation": "elevated" }, children));
1371
- }
1372
- /**
1373
- * Provides a wrapper for the Autocomplete menu that handles positioning and visibility.
1374
- * @param attachTo - The element that the menu should be attached to.
1375
- */
1376
- function useAutocompleteMenu({ attachTo, }) {
1377
- const [menuRef, setMenuRef] = React.useState(null);
1378
- const AutocompleteMenuWrapper = React.useCallback(({ children, visible, }) => {
1379
- const menuFloatProps = useRepositionMenu(attachTo, visible, true);
1380
- React.useEffect(() => {
1381
- setMenuRef(menuFloatProps.menuRef);
1382
- }, [menuFloatProps.menuRef]);
1383
- return (React.createElement(BaseAutocompleteMenuWrapper, { floatStyles: menuFloatProps.styles, setMenuRef: menuFloatProps.setMenuRef, targetWidth: menuFloatProps.targetWidth, visible: visible }, children));
1384
- }, [attachTo]);
1385
- return { MenuWrapper: AutocompleteMenuWrapper, menuRef };
1386
- }
1387
- function BaseAutocompleteMenuWrapper(props) {
1388
- const mounted = jobberHooks.useIsMounted();
1389
- const menu = React.createElement(BaseAutocompleteMenuWrapperInternal, Object.assign({}, props));
1390
- return mounted.current ? React.createElement(floatingUi_react.FloatingPortal, null, menu) : menu;
1391
- }
1392
-
1393
- function isOptionSelected(selectedOption, option) {
1394
- return Boolean(selectedOption && selectedOption.value === option.value);
1395
- }
1396
- /**
1397
- * Helper function to determine if the option is a group. This is used to
1398
- * determine if the option contains a list of options for rendering Section
1399
- * Labels in the Autocomplete component.
1400
- */
1401
- function isOptionGroup(option) {
1402
- return "options" in option;
1403
- }
1404
-
1405
- /**
1406
- * The rendering of the default MenuOption
1407
- */
1408
- function MenuOption({ isHighlighted, option, onOptionSelect, isSelected, addSeparators, UNSAFE_className = {}, UNSAFE_style = {}, }) {
1409
- if (isOptionGroup(option)) {
1410
- return (React.createElement(MenuGroupOptions, { UNSAFE_className: UNSAFE_className.groupOption, option: option, UNSAFE_style: UNSAFE_style.groupOption }));
1411
- }
1412
- return (React.createElement(BaseMenuOption, { UNSAFE_className: UNSAFE_className.option, UNSAFE_style: UNSAFE_style.option, option: option, isHighlighted: isHighlighted, onOptionSelect: onOptionSelect, addSeparators: addSeparators },
1413
- React.createElement(MenuOptionContent, { option: option, isSelected: isSelected, UNSAFE_className: UNSAFE_className.content, UNSAFE_style: UNSAFE_style.content })));
1414
- }
1415
- function MenuOptionContent({ option, isSelected, UNSAFE_className = {}, UNSAFE_style = {}, }) {
1416
- const iconClassName = classnames(styles.icon, UNSAFE_className.icon);
1417
- const textClassName = classnames(styles.text, UNSAFE_className.text);
1418
- const labelClassName = classnames(styles.label, UNSAFE_className.label);
1419
- const detailsClassName = classnames(styles.details, UNSAFE_className.details);
1420
- return (React.createElement(React.Fragment, null,
1421
- React.createElement("div", { className: iconClassName, style: UNSAFE_style.icon }, isSelected && React.createElement(Icon.Icon, { name: "checkmark", size: "small" })),
1422
- React.createElement("div", { className: textClassName, style: UNSAFE_style.text },
1423
- React.createElement("div", { className: labelClassName, style: UNSAFE_style.label },
1424
- React.createElement(Text.Text, null, option.label),
1425
- option.description !== undefined && (React.createElement(Text.Text, { variation: "subdued" }, option.description))),
1426
- option.details !== undefined && (React.createElement("div", { className: detailsClassName, style: UNSAFE_style.details },
1427
- React.createElement(Text.Text, null, option.details))))));
1428
- }
1429
- /**
1430
- * The rendering of the default MenuGroupOption
1431
- */
1432
- function MenuGroupOptions({ option, UNSAFE_className = {}, UNSAFE_style = {}, }) {
1433
- return (React.createElement(BaseMenuGroupOption, { UNSAFE_className: UNSAFE_className.heading, UNSAFE_style: UNSAFE_style.heading },
1434
- React.createElement(Heading.Heading, { level: 5 }, option.label)));
1435
- }
1436
- function BaseMenuGroupOption({ children, UNSAFE_className = "", UNSAFE_style = {}, }) {
1437
- const headingClassName = classnames(styles.heading, UNSAFE_className);
1438
- return (React.createElement("div", { className: headingClassName, style: UNSAFE_style }, children));
1439
- }
1440
- /**
1441
- * Renders the base option component. The component takes children and renders them inside a button.
1442
- */
1443
- function BaseMenuOption({ option, isHighlighted, onOptionSelect, addSeparators, children, UNSAFE_className = "", UNSAFE_style = {}, }) {
1444
- const optionClass = classnames(styles.option, {
1445
- [styles.active]: isHighlighted,
1446
- [styles.separator]: addSeparators,
1447
- }, UNSAFE_className);
1448
- return (React.createElement("button", { role: "option", type: "button", className: optionClass, onMouseDown: onOptionSelect === null || onOptionSelect === void 0 ? void 0 : onOptionSelect.bind(undefined, option), style: UNSAFE_style }, children));
1449
- }
1450
-
1451
- exports.KeyboardAction = void 0;
1452
- (function (KeyboardAction) {
1453
- KeyboardAction[KeyboardAction["Previous"] = -1] = "Previous";
1454
- KeyboardAction[KeyboardAction["Next"] = 1] = "Next";
1455
- KeyboardAction[KeyboardAction["Select"] = 0] = "Select";
1456
- })(exports.KeyboardAction || (exports.KeyboardAction = {}));
1457
- /**
1458
- * Hook to handle custom keyboard navigation for the Autocomplete component.
1459
- * Use this hook if you are using components in the menu that aren't MenuOption or BaseMenuOption.
1460
- */
1461
- function useCustomKeyboardNavigation({ onRequestHighlightChange, }) {
1462
- jobberHooks.useOnKeyDown(event => {
1463
- onRequestHighlightChange === null || onRequestHighlightChange === void 0 ? void 0 : onRequestHighlightChange(event, exports.KeyboardAction.Next);
1464
- }, "ArrowDown");
1465
- jobberHooks.useOnKeyDown(event => {
1466
- onRequestHighlightChange === null || onRequestHighlightChange === void 0 ? void 0 : onRequestHighlightChange(event, exports.KeyboardAction.Previous);
1467
- }, "ArrowUp");
1468
- jobberHooks.useOnKeyDown(event => {
1469
- onRequestHighlightChange === null || onRequestHighlightChange === void 0 ? void 0 : onRequestHighlightChange(event, exports.KeyboardAction.Select);
1470
- }, "Enter");
1471
- }
1472
- /**
1473
- * Hook to handle keyboard navigation for the Menu in the Autocomplete component.
1474
- * If using components in the menu that aren't MenuOption or BaseMenuOption, you should use the `useCustomKeyboardNavigation` hook.
1475
- */
1476
- function useKeyboardNavigation({ options, onOptionSelect, menuRef, visible, }) {
1477
- const [highlightedIndex, setHighlightedIndex] = React.useState(0);
1478
- const initialHighlight = options.some(isOptionGroup) ? 1 : 0;
1479
- React.useEffect(() => setHighlightedIndex(initialHighlight), [options]);
1480
- React.useEffect(() => {
1481
- var _a, _b;
1482
- (_b = (_a = menuRef === null || menuRef === void 0 ? void 0 : menuRef.children[highlightedIndex]) === null || _a === void 0 ? void 0 : _a.scrollIntoView) === null || _b === void 0 ? void 0 : _b.call(_a, {
1483
- behavior: "smooth",
1484
- block: "nearest",
1485
- inline: "start",
1486
- });
1487
- }, [highlightedIndex]);
1488
- const onRequestHighlightChange = React.useCallback((event, direction) => {
1489
- if (!visible)
1490
- return;
1491
- const indexChange = getRequestedIndexChange({
1492
- event,
1493
- options,
1494
- direction,
1495
- highlightedIndex,
1496
- });
1497
- switch (direction) {
1498
- case exports.KeyboardAction.Previous:
1499
- setHighlightedIndex(prev => Math.max(0, prev + indexChange));
1500
- break;
1501
- case exports.KeyboardAction.Next:
1502
- setHighlightedIndex(prev => Math.min(options.length - 1, prev + indexChange));
1503
- break;
1504
- case exports.KeyboardAction.Select:
1505
- if (isOptionGroup(options[highlightedIndex]))
1506
- return;
1507
- onOptionSelect(options[highlightedIndex]);
1508
- break;
1509
- }
1510
- }, [highlightedIndex, options, onOptionSelect, visible]);
1511
- useCustomKeyboardNavigation({ onRequestHighlightChange });
1512
- return { highlightedIndex };
1513
- }
1514
- /**
1515
- * Function to get the requested index change based on the current highlighted index and the direction of the keyboard action.
1516
- * Accounts for groups in the options array.
1517
- */
1518
- function getRequestedIndexChange({ event, options, direction, highlightedIndex, }) {
1519
- event.preventDefault();
1520
- const requestedIndex = options[highlightedIndex + direction];
1521
- return requestedIndex && isOptionGroup(requestedIndex)
1522
- ? direction + direction
1523
- : direction;
1524
- }
1525
-
1526
- /**
1527
- * Renders the default Menu for the Autocomplete component.
1528
- */
1529
- function DefaultMenu({ options, selectedOption, onOptionSelect, attachTo, visible, }) {
1530
- const { menuRef, setMenuRef, styles: floatStyles, targetWidth, } = useRepositionMenu(attachTo, visible, false);
1531
- const detectSeparatorCondition = (option) => option.description || option.details;
1532
- const addSeparators = options.some(detectSeparatorCondition);
1533
- const { highlightedIndex } = useKeyboardNavigation({
1534
- onOptionSelect,
1535
- options,
1536
- visible,
1537
- menuRef,
1538
- });
1539
- return (React.createElement(BaseAutocompleteMenuWrapper, { setMenuRef, floatStyles, targetWidth, visible }, options === null || options === void 0 ? void 0 : options.map((option, index) => {
1540
- return (React.createElement(MenuOption, { key: index, option: option, isHighlighted: index === highlightedIndex, onOptionSelect: onOptionSelect, isSelected: isOptionSelected(selectedOption, option), addSeparators: addSeparators }));
1541
- })));
1542
- }
1543
-
1544
- function Menu({ options, selectedOption, onOptionSelect, inputFocused, attachTo, inputRef, customRenderMenu, }) {
1545
- if (customRenderMenu) {
1546
- return (React.createElement(CustomMenu, { attachTo: attachTo, inputFocused: inputFocused, inputRef: inputRef, customRenderMenu: customRenderMenu, options: options, onOptionSelect: onOptionSelect, selectedOption: selectedOption }));
1547
- }
1548
- if (!inputFocused || !options.length)
1549
- return null;
1550
- return (React.createElement(DefaultMenu, { attachTo: attachTo, options: options, onOptionSelect: onOptionSelect, selectedOption: selectedOption, visible: inputFocused }));
1551
- }
1552
- /**
1553
- * Renders the custom Menu for the Autocomplete component.
1554
- * Provides the menuRef and MenuWrapper to the customRenderMenu function.
1555
- */
1556
- function CustomMenu({ options, selectedOption, onOptionSelect, customRenderMenu, attachTo, inputFocused, inputRef, }) {
1557
- const { MenuWrapper, menuRef } = useAutocompleteMenu({ attachTo });
1558
- const menuContent = customRenderMenu({
1559
- options,
1560
- menuRef,
1561
- onOptionSelect,
1562
- selectedOption,
1563
- inputFocused,
1564
- MenuWrapper,
1565
- inputRef,
1566
- });
1567
- return menuContent;
1568
- }
1569
-
1570
- // Max statements increased to make room for the debounce functions
1571
- // eslint-disable-next-line max-statements
1572
- function AutocompleteInternal(_a, ref) {
1573
- var _b;
1574
- var { initialOptions = [], value, allowFreeForm = true, size = undefined, debounce: debounceRate = 300, onChange, getOptions, placeholder, onBlur, onFocus, customRenderMenu } = _a, inputProps = tslib_es6.__rest(_a, ["initialOptions", "value", "allowFreeForm", "size", "debounce", "onChange", "getOptions", "placeholder", "onBlur", "onFocus", "customRenderMenu"]);
1575
- const initialOptionsMemo = React.useMemo(() => mapToOptions(initialOptions), [initialOptions]);
1576
- const [options, setOptions] = React.useState(initialOptionsMemo);
1577
- const [inputFocused, setInputFocused] = React.useState(false);
1578
- const [inputText, setInputText] = React.useState((_b = value === null || value === void 0 ? void 0 : value.label) !== null && _b !== void 0 ? _b : "");
1579
- const [autocompleteRef, setAutocompleteRef] = React.useState(null);
1580
- const delayedSearch = jobberHooks.useDebounce(updateSearch, debounceRate);
1581
- const inputRef = React.useRef(null);
1582
- React.useEffect(() => {
1583
- delayedSearch();
1584
- }, [inputText]);
1585
- React.useEffect(() => {
1586
- var _a;
1587
- updateInput((_a = value === null || value === void 0 ? void 0 : value.label) !== null && _a !== void 0 ? _a : "");
1588
- }, [value]);
1589
- return (React.createElement("div", { className: styles.autocomplete, ref: setAutocompleteRef },
1590
- React.createElement(InputText.InputText, Object.assign({ ref: mergeRefs.mergeRefs([ref, inputRef]), autoComplete: "off", size: size, value: inputText, onChange: handleInputChange, placeholder: placeholder, onFocus: handleInputFocus, onBlur: handleInputBlur }, inputProps)),
1591
- React.createElement(Menu, { attachTo: autocompleteRef, inputRef: inputRef, inputFocused: inputFocused, options: options, customRenderMenu: customRenderMenu, selectedOption: value, onOptionSelect: handleMenuChange })));
1592
- function updateInput(newText) {
1593
- setInputText(newText);
1594
- if (newText === "") {
1595
- setOptions(mapToOptions(initialOptions));
1596
- }
1597
- }
1598
- function updateSearch() {
1599
- return tslib_es6.__awaiter(this, void 0, void 0, function* () {
1600
- const updatedOptions = yield getOptions(inputText);
1601
- const filteredOptions = updatedOptions.filter(option => isOptionGroup(option) ? option.options.length > 0 : true);
1602
- setOptions(mapToOptions(filteredOptions));
1603
- });
1604
- }
1605
- function handleMenuChange(chosenOption) {
1606
- var _a;
1607
- onChange(chosenOption);
1608
- updateInput((_a = chosenOption === null || chosenOption === void 0 ? void 0 : chosenOption.label) !== null && _a !== void 0 ? _a : "");
1609
- setInputFocused(false);
1610
- }
1611
- function handleInputChange(newText) {
1612
- updateInput(newText);
1613
- if (allowFreeForm) {
1614
- onChange({ label: newText });
1615
- }
1616
- }
1617
- function handleInputBlur() {
1618
- setInputFocused(false);
1619
- if (value == undefined || value.label !== inputText) {
1620
- setInputText("");
1621
- onChange(undefined);
1622
- }
1623
- onBlur && onBlur();
1624
- }
1625
- function handleInputFocus() {
1626
- setInputFocused(true);
1627
- if (onFocus) {
1628
- onFocus();
1629
- }
1630
- }
1631
- }
1632
- function mapToOptions(items) {
1633
- const retVal = items.reduce((result, item) => {
1634
- result.push(item);
1635
- if (isOptionGroup(item) && item.options) {
1636
- result = result.concat(item.options);
1637
- }
1638
- return result;
1639
- }, []);
1640
- return retVal;
1641
- }
1642
- // Casts the Generics to the forward ref so autocomplete works as expected for consumers
1643
- const Autocomplete$1 = React.forwardRef(AutocompleteInternal);
29
+ require('../FormFieldPostFix-cjs.js');
30
+ require('../Spinner-cjs.js');
31
+ require('../useAtlantisFormFieldName-cjs.js');
32
+ require('react-hook-form');
33
+ require('../mergeRefs-cjs.js');
34
+ require('../filterDataAttributes-cjs.js');
1644
35
 
1645
36
  // Convenience builder helpers (optional usage)
1646
37
  // Helper to improve inference from inline menu literals
@@ -1648,29 +39,5 @@ function defineMenu(menu) {
1648
39
  return menu;
1649
40
  }
1650
41
 
1651
- function isNewAutocompleteProps(props) {
1652
- return props.version === 2;
1653
- }
1654
- function AutocompleteShim(props, ref) {
1655
- if (isNewAutocompleteProps(props)) {
1656
- return (React.createElement(AutocompleteRebuilt, Object.assign({}, props, { ref: ref })));
1657
- }
1658
- return (React.createElement(Autocomplete$1, Object.assign({}, props, { ref: ref })));
1659
- }
1660
- const AutocompleteForwarded = React.forwardRef(AutocompleteShim);
1661
- AutocompleteForwarded.displayName = "Autocomplete";
1662
- const Autocomplete = AutocompleteForwarded;
1663
-
1664
- exports.Autocomplete = Autocomplete;
1665
- exports.BaseAutocompleteMenuWrapper = BaseAutocompleteMenuWrapper;
1666
- exports.BaseMenuGroupOption = BaseMenuGroupOption;
1667
- exports.BaseMenuOption = BaseMenuOption;
1668
- exports.MenuOption = MenuOption;
42
+ exports.Autocomplete = Autocomplete.Autocomplete;
1669
43
  exports.defineMenu = defineMenu;
1670
- exports.getRequestedIndexChange = getRequestedIndexChange;
1671
- exports.isOptionGroup = isOptionGroup;
1672
- exports.isOptionSelected = isOptionSelected;
1673
- exports.useAutocompleteMenu = useAutocompleteMenu;
1674
- exports.useCustomKeyboardNavigation = useCustomKeyboardNavigation;
1675
- exports.useKeyboardNavigation = useKeyboardNavigation;
1676
- exports.useRepositionMenu = useRepositionMenu;