@lumx/react 4.3.2-alpha.24 → 4.3.2-alpha.25

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.
@@ -1,1768 +0,0 @@
1
- import React__default, { useContext, useEffect, useMemo, useRef, createContext } from 'react';
2
- import { jsx, Fragment } from 'react/jsx-runtime';
3
- import isEmpty from 'lodash/isEmpty.js';
4
- import { join, visuallyHidden } from '@lumx/core/js/utils/classNames';
5
- import { createPortal } from 'react-dom';
6
- import noop from 'lodash/noop.js';
7
- import uniqueId from 'lodash/uniqueId.js';
8
- import findLast from 'lodash/findLast.js';
9
- import find from 'lodash/find.js';
10
- import findLastIndex from 'lodash/findLastIndex.js';
11
- import isNil from 'lodash/isNil.js';
12
- import groupBy from 'lodash/groupBy.js';
13
-
14
- const DisabledStateContext = /*#__PURE__*/React__default.createContext({
15
- state: null
16
- });
17
- /**
18
- * Disabled state provider.
19
- * All nested LumX Design System components inherit this disabled state.
20
- */
21
- function DisabledStateProvider({
22
- children,
23
- ...value
24
- }) {
25
- return /*#__PURE__*/jsx(DisabledStateContext.Provider, {
26
- value: value,
27
- children: children
28
- });
29
- }
30
-
31
- /**
32
- * Get DisabledState context value
33
- */
34
- function useDisabledStateContext() {
35
- return useContext(DisabledStateContext);
36
- }
37
-
38
- const EVENT_TYPES = ['mousedown', 'touchstart'];
39
- function isClickAway(targets, refs) {
40
- // The targets elements are not contained in any of the listed element references.
41
- return !refs.some(ref => targets.some(target => ref?.current?.contains(target)));
42
- }
43
- /**
44
- * Listen to clicks away from the given elements and callback the passed in function.
45
- *
46
- * Warning: If you need to detect click away on nested React portals, please use the `ClickAwayProvider` component.
47
- */
48
- function useClickAway({
49
- callback,
50
- childrenRefs
51
- }) {
52
- useEffect(() => {
53
- const {
54
- current: currentRefs
55
- } = childrenRefs;
56
- if (!callback || !currentRefs || isEmpty(currentRefs)) {
57
- return undefined;
58
- }
59
- const listener = evt => {
60
- const targets = [evt.composedPath?.()[0], evt.target];
61
- if (isClickAway(targets, currentRefs)) {
62
- callback(evt);
63
- }
64
- };
65
- EVENT_TYPES.forEach(evtType => document.addEventListener(evtType, listener));
66
- return () => {
67
- EVENT_TYPES.forEach(evtType => document.removeEventListener(evtType, listener));
68
- };
69
- }, [callback, childrenRefs]);
70
- }
71
-
72
- const ClickAwayAncestorContext = /*#__PURE__*/createContext(null);
73
- /**
74
- * Component combining the `useClickAway` hook with a React context to hook into the React component tree and make sure
75
- * we take into account both the DOM tree and the React tree to detect click away.
76
- *
77
- * @return the react component.
78
- */
79
- const ClickAwayProvider = ({
80
- children,
81
- callback,
82
- childrenRefs,
83
- parentRef
84
- }) => {
85
- const parentContext = useContext(ClickAwayAncestorContext);
86
- const currentContext = useMemo(() => {
87
- const context = {
88
- childrenRefs: [],
89
- /**
90
- * Add element refs to the current context and propagate to the parent context.
91
- */
92
- addRefs(...newChildrenRefs) {
93
- // Add element refs that should be considered as inside the click away context.
94
- context.childrenRefs.push(...newChildrenRefs);
95
- if (parentContext) {
96
- // Also add then to the parent context
97
- parentContext.addRefs(...newChildrenRefs);
98
- if (parentRef) {
99
- // The parent element is also considered as inside the parent click away context but not inside the current context
100
- parentContext.addRefs(parentRef);
101
- }
102
- }
103
- }
104
- };
105
- return context;
106
- }, [parentContext, parentRef]);
107
- useEffect(() => {
108
- const {
109
- current: currentRefs
110
- } = childrenRefs;
111
- if (!currentRefs) {
112
- return;
113
- }
114
- currentContext.addRefs(...currentRefs);
115
- }, [currentContext, childrenRefs]);
116
- useClickAway({
117
- callback,
118
- childrenRefs: useRef(currentContext.childrenRefs)
119
- });
120
- return /*#__PURE__*/jsx(ClickAwayAncestorContext.Provider, {
121
- value: currentContext,
122
- children: children
123
- });
124
- };
125
- ClickAwayProvider.displayName = 'ClickAwayProvider';
126
-
127
- /**
128
- * Live region to read a message to screen readers.
129
- * Messages can be "polite" and be read when possible or
130
- * "assertive" and interrupt any message currently be read. (To be used sparingly)
131
- *
132
- * More information here: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions
133
- *
134
- * @family A11Y
135
- * @param A11YLiveMessageProps
136
- * @returns A11YLiveMessage
137
- */
138
- const A11YLiveMessage = ({
139
- type = 'polite',
140
- atomic,
141
- role,
142
- hidden,
143
- relevant,
144
- children,
145
- className,
146
- ...forwardedProps
147
- }) => {
148
- return /*#__PURE__*/jsx("div", {
149
- ...forwardedProps,
150
- className: join(hidden ? visuallyHidden() : undefined, className),
151
- role: role,
152
- "aria-live": type,
153
- "aria-atomic": atomic,
154
- "aria-relevant": relevant,
155
- children: children
156
- });
157
- };
158
-
159
- /**
160
- * Portal initializing function.
161
- * If it does not provide a container, the Portal children will render in classic React tree and not in a portal.
162
- */
163
-
164
- const PortalContext = /*#__PURE__*/React__default.createContext(() => ({
165
- container: document.body
166
- }));
167
- /**
168
- * Customize where <Portal> wrapped elements render (tooltip, popover, dialog, etc.)
169
- */
170
- const PortalProvider = PortalContext.Provider;
171
-
172
- /**
173
- * Render children in a portal outside the current DOM position
174
- * (defaults to `document.body` but can be customized with the PortalContextProvider)
175
- */
176
- const Portal = ({
177
- children,
178
- enabled = true
179
- }) => {
180
- const init = React__default.useContext(PortalContext);
181
- const context = React__default.useMemo(() => {
182
- return enabled ? init() : null;
183
- },
184
- // Only update on 'enabled'
185
- // eslint-disable-next-line react-hooks/exhaustive-deps
186
- [enabled]);
187
- React__default.useLayoutEffect(() => {
188
- return context?.teardown;
189
- }, [context?.teardown, enabled]);
190
- if (!context?.container) {
191
- return /*#__PURE__*/jsx(Fragment, {
192
- children: children
193
- });
194
- }
195
- return /*#__PURE__*/createPortal(children, context.container);
196
- };
197
-
198
- /**
199
- * Create a map from the given tab stop to sort them by rowKey;
200
- */
201
- function createGridMap(tabStops) {
202
- /** Group all tabStop by rows to easily access them by their row keys */
203
- const tabStopsByRowKey = groupBy(tabStops, 'rowKey');
204
- /**
205
- * An array with each row key in the order set in the tabStops array.
206
- * Each rowKey will only appear once.
207
- */
208
- const rowKeys = tabStops.reduce((acc, {
209
- rowKey
210
- }) => {
211
- if (!isNil(rowKey) && !acc.includes(rowKey)) {
212
- return [...acc, rowKey];
213
- }
214
- return acc;
215
- }, []);
216
- return {
217
- tabStopsByRowKey,
218
- rowKeys
219
- };
220
- }
221
-
222
- /** Check if the given tab stop is enabled */
223
- const tabStopIsEnabled = tabStop => !tabStop.disabled;
224
-
225
- const LOOP_AROUND_TYPES = {
226
- /**
227
- * Will continue navigation to the next row or column and loop back to the start
228
- * when the last tab stop is reached
229
- */
230
- nextLoop: 'next-loop',
231
- /**
232
- * Will continue navigation to the next row or column until
233
- * the last tab stop is reached
234
- */
235
- nextEnd: 'next-end',
236
- /**
237
- * Will loop within the current row or column
238
- */
239
- inside: 'inside'
240
- };
241
- const CELL_SEARCH_DIRECTION = {
242
- /** Look ahead of the given position */
243
- asc: 'asc',
244
- /** Look before the given position */
245
- desc: 'desc'
246
- };
247
-
248
- /**
249
- * Build a loopAround configuration to ensure both row and col behavior are set.
250
- *
251
- * Setting a boolean will set the following behaviors:
252
- *
253
- * * true => { row: 'next-loop', col: 'next-loop' }
254
- * * false => { row: 'next-end', col: 'next-end' }
255
- */
256
- function buildLoopAroundObject(loopAround) {
257
- if (typeof loopAround === 'boolean' || loopAround === undefined) {
258
- const newLoopAround = loopAround ? {
259
- row: LOOP_AROUND_TYPES.nextLoop,
260
- col: LOOP_AROUND_TYPES.nextLoop
261
- } : {
262
- row: LOOP_AROUND_TYPES.nextEnd,
263
- col: LOOP_AROUND_TYPES.nextEnd
264
- };
265
- return newLoopAround;
266
- }
267
- return loopAround;
268
- }
269
-
270
- /**
271
- * Check that the given coordinate is a simple number
272
- */
273
- const isNumberCoords = coords => typeof coords === 'number';
274
-
275
- /**
276
- * Check that the given coordinate is a direction
277
- */
278
- function isDirectionCoords(coords) {
279
- return Boolean(typeof coords !== 'number' && typeof coords?.from === 'number');
280
- }
281
-
282
- /**
283
- * Search the given column of a grid map for a cell.
284
- */
285
- function findCellInCol(gridMap, col, rowCoords, cellSelector = tabStopIsEnabled) {
286
- /** The rowIndex might not be strictly successive, so we need to use the actual row index keys. */
287
- const {
288
- rowKeys,
289
- tabStopsByRowKey
290
- } = gridMap;
291
- const lastIndex = rowKeys.length - 1;
292
- /**
293
- * If the rowCoords.from is set at -1, it means we should search from the start/end.
294
- */
295
- let searchIndex = rowCoords.from;
296
- if (searchIndex === -1) {
297
- searchIndex = rowCoords.direction === CELL_SEARCH_DIRECTION.desc ? lastIndex : 0;
298
- }
299
- const searchCellFunc = rowCoords.direction === CELL_SEARCH_DIRECTION.desc ? findLast : find;
300
- const rowKeyWithEnabledCell = searchCellFunc(rowKeys, (rowKey, index) => {
301
- const row = tabStopsByRowKey[rowKey];
302
- const cell = row[col];
303
- const hasCell = Boolean(cell);
304
- const cellRowIndex = index;
305
-
306
- /** Check that the target row index is in the right direction of the search */
307
- const correctRowIndex = rowCoords.direction === CELL_SEARCH_DIRECTION.desc ? cellRowIndex <= searchIndex : cellRowIndex >= searchIndex;
308
- if (cell && correctRowIndex) {
309
- return cellSelector ? hasCell && cellSelector(cell) : hasCell;
310
- }
311
- return false;
312
- });
313
- const row = rowKeyWithEnabledCell !== undefined ? tabStopsByRowKey[rowKeyWithEnabledCell] : undefined;
314
- return row?.[col];
315
- }
316
-
317
- /**
318
- * Search the given column of a grid map for a cell.
319
- */
320
- function findCellInRow(gridMap, row, colCoords, cellSelector = tabStopIsEnabled) {
321
- const {
322
- direction,
323
- from
324
- } = colCoords || {};
325
- const {
326
- rowKeys,
327
- tabStopsByRowKey
328
- } = gridMap;
329
- const rowKey = rowKeys[row];
330
- const currentRow = tabStopsByRowKey[rowKey];
331
- if (!currentRow) {
332
- return undefined;
333
- }
334
- const searchCellFunc = direction === CELL_SEARCH_DIRECTION.desc ? findLast : find;
335
- const cell = searchCellFunc(currentRow, cellSelector, from);
336
- return cell;
337
- }
338
-
339
- /**
340
- * Parse each column of the given gridMap to find the first cell matching the selector.
341
- * The direction and starting point of the search can be set using the coordinates attribute.
342
- */
343
- function parseColsForCell(/** The gridMap to search */
344
- gridMap, /** The coordinate to search */
345
- {
346
- direction = CELL_SEARCH_DIRECTION.asc,
347
- from
348
- }, cellSelector = tabStopIsEnabled) {
349
- if (from === undefined) {
350
- return undefined;
351
- }
352
- const {
353
- rowKeys,
354
- tabStopsByRowKey
355
- } = gridMap;
356
-
357
- /** As we cannot know for certain when to stop, we need to know which column is the last column */
358
- const maxColIndex = rowKeys.reduce((maxLength, rowIndex) => {
359
- const rowLength = tabStopsByRowKey[rowIndex].length;
360
- return rowLength > maxLength ? rowLength - 1 : maxLength;
361
- }, 0);
362
-
363
- /** If "from" is set as -1, start from the end. */
364
- const fromIndex = from === -1 ? maxColIndex : from || 0;
365
- for (let index = fromIndex; direction === CELL_SEARCH_DIRECTION.desc ? index > -1 : index <= maxColIndex; direction === CELL_SEARCH_DIRECTION.desc ? index -= 1 : index += 1) {
366
- const rowWithEnabledCed = findCellInCol(gridMap, index, {
367
- direction,
368
- from: direction === CELL_SEARCH_DIRECTION.desc ? -1 : 0
369
- }, cellSelector);
370
- if (rowWithEnabledCed) {
371
- return rowWithEnabledCed;
372
- }
373
- }
374
- return undefined;
375
- }
376
-
377
- /**
378
- * Search for a cell in a gridMap
379
- *
380
- * This allows you to
381
- * * Select a cell at a specific coordinate
382
- * * Search for a cell from a specific column in any direction
383
- * * Search for a cell from a specific row in any direction
384
- *
385
- * If no cell is found, returns undefined
386
- */
387
- function getCell(/** The gridMap object to search in. */
388
- gridMap, /** The coordinates of the cell to select */
389
- coords,
390
- /**
391
- * A selector function to select the cell.
392
- * Selects enabled cells by default.
393
- */
394
- cellSelector = tabStopIsEnabled) {
395
- const {
396
- row,
397
- col
398
- } = coords || {};
399
- const {
400
- rowKeys,
401
- tabStopsByRowKey
402
- } = gridMap || {};
403
-
404
- /** Defined row and col */
405
- if (isNumberCoords(row) && isNumberCoords(col)) {
406
- const rowKey = rowKeys[row];
407
- return tabStopsByRowKey[rowKey][col];
408
- }
409
-
410
- /** Defined row but variable col */
411
- if (isDirectionCoords(col) && isNumberCoords(row)) {
412
- return findCellInRow(gridMap, row, col, cellSelector);
413
- }
414
- if (isDirectionCoords(row)) {
415
- if (isDirectionCoords(col)) {
416
- return parseColsForCell(gridMap, col, cellSelector);
417
- }
418
- return findCellInCol(gridMap, col, row, cellSelector);
419
- }
420
- return undefined;
421
- }
422
-
423
- function getCellCoordinates(gridMap, tabStop) {
424
- const currentRowKey = tabStop.rowKey;
425
- if (isNil(currentRowKey)) {
426
- return undefined;
427
- }
428
- const {
429
- rowKeys,
430
- tabStopsByRowKey
431
- } = gridMap;
432
- const rowIndex = rowKeys.findIndex(rowKey => rowKey === currentRowKey);
433
- const row = tabStopsByRowKey[currentRowKey];
434
- const columnOffset = row.findIndex(ts => ts.id === tabStop.id);
435
- return {
436
- rowIndex,
437
- row,
438
- columnOffset
439
- };
440
- }
441
-
442
- /** Check whether the list should vertically loop with the given configuration */
443
- function shouldLoopListVertically(direction, loopAround) {
444
- return direction === 'vertical' && loopAround?.col !== 'next-end' || direction === 'both' && loopAround?.col !== 'next-end';
445
- }
446
-
447
- /** Check whether the list should horizontally loop with the given configuration */
448
- function shouldLoopListHorizontally(direction, loopAround) {
449
- return direction === 'horizontal' && loopAround?.row !== 'next-end' || direction === 'both' && loopAround?.row !== 'next-end';
450
- }
451
-
452
- /**
453
- * Get the correct pointer type from the given event.
454
- * This is used when a tab stop is selected, to check if is has been selected using a keyboard or a pointer
455
- * (pen / mouse / touch)
456
- */
457
- function getPointerTypeFromEvent(event) {
458
- return event && 'pointerType' in event && Boolean(event.pointerType) ? 'pointer' : 'keyboard';
459
- }
460
-
461
- // Event keys used for keyboard navigation.
462
- const VERTICAL_NAV_KEYS = ['ArrowUp', 'ArrowDown', 'Home', 'End'];
463
- const HORIZONTAL_NAV_KEYS = ['ArrowLeft', 'ArrowRight', 'Home', 'End'];
464
- const KEY_NAV_KEYS = [...HORIZONTAL_NAV_KEYS, ...VERTICAL_NAV_KEYS];
465
- const NAV_KEYS = {
466
- both: KEY_NAV_KEYS,
467
- vertical: VERTICAL_NAV_KEYS,
468
- horizontal: HORIZONTAL_NAV_KEYS
469
- };
470
-
471
- // Event keys union type
472
-
473
- // Handle all navigation moves resulting in a new state.
474
- const MOVES = {
475
- // Move to the next item.
476
- // The grid is flatten so the item after the last of a row will be the
477
- // first item of the next row.
478
- NEXT(state, _, index) {
479
- for (let i = index + 1; i < state.tabStops.length; ++i) {
480
- const tabStop = state.tabStops[i];
481
- if (!tabStop.disabled) {
482
- return {
483
- ...state,
484
- allowFocusing: true,
485
- selectedId: tabStop.id
486
- };
487
- }
488
- }
489
- return state;
490
- },
491
- // Move to the previous item.
492
- // The grid is flatten so the item before the first of a row will be the
493
- // last item of the previous row.
494
- PREVIOUS(state, _, index) {
495
- for (let i = index - 1; i >= 0; --i) {
496
- const tabStop = state.tabStops[i];
497
- if (!tabStop.disabled) {
498
- return {
499
- ...state,
500
- allowFocusing: true,
501
- selectedId: tabStop.id
502
- };
503
- }
504
- }
505
- return state;
506
- },
507
- // Moving to the next row
508
- // We move to the next row, and we stay in the same column.
509
- // If we are in the last row, then we move to the first not disabled item of the next column.
510
- NEXT_ROW(state, currentTabStop) {
511
- const currentRowKey = currentTabStop.rowKey;
512
- if (isNil(currentRowKey)) {
513
- return state;
514
- }
515
- const gridMap = state.gridMap || createGridMap(state.tabStops);
516
- const cellCoordinates = getCellCoordinates(gridMap, currentTabStop);
517
- if (!cellCoordinates) {
518
- return state;
519
- }
520
- const {
521
- rowIndex,
522
- columnOffset
523
- } = cellCoordinates;
524
- const nextRow = rowIndex + 1;
525
-
526
- /** First try to get the next cell in the current column */
527
- let tabStop = getCell(gridMap, {
528
- row: {
529
- from: nextRow,
530
- direction: 'asc'
531
- },
532
- col: columnOffset
533
- });
534
-
535
- // If none were found, search for the next cell depending on the loop around parameter
536
- if (!tabStop) {
537
- switch (state.loopAround.col) {
538
- /**
539
- * If columns are configured to be looped inside,
540
- * get the first enabled cell of the current column
541
- */
542
- case LOOP_AROUND_TYPES.inside:
543
- tabStop = getCell(gridMap, {
544
- col: columnOffset,
545
- row: {
546
- from: 0,
547
- direction: 'asc'
548
- }
549
- });
550
- break;
551
- /**
552
- * If columns are configured to be go to the next,
553
- * search for the next enabled cell from the next column
554
- */
555
- case LOOP_AROUND_TYPES.nextEnd:
556
- case LOOP_AROUND_TYPES.nextLoop:
557
- default:
558
- tabStop = getCell(gridMap, {
559
- row: {
560
- from: 0,
561
- direction: 'asc'
562
- },
563
- col: {
564
- from: columnOffset + 1,
565
- direction: 'asc'
566
- }
567
- });
568
- break;
569
- }
570
- }
571
-
572
- /**
573
- * If still none is found and the columns are configured to loop
574
- * search starting from the start
575
- */
576
- if (!tabStop && state.loopAround.col === LOOP_AROUND_TYPES.nextLoop) {
577
- tabStop = getCell(gridMap, {
578
- row: {
579
- from: 0,
580
- direction: 'asc'
581
- },
582
- col: {
583
- from: 0,
584
- direction: 'asc'
585
- }
586
- });
587
- }
588
- if (tabStop) {
589
- return {
590
- ...state,
591
- allowFocusing: true,
592
- selectedId: tabStop.id,
593
- gridMap
594
- };
595
- }
596
- return {
597
- ...state,
598
- allowFocusing: true,
599
- gridMap
600
- };
601
- },
602
- // Moving to the previous row
603
- // We move to the previous row, and we stay in the same column.
604
- // If we are in the first row, then we move to the last not disabled item of the previous column.
605
- PREVIOUS_ROW(state, currentTabStop) {
606
- const currentRowKey = currentTabStop.rowKey;
607
- if (isNil(currentRowKey)) {
608
- return state;
609
- }
610
- const gridMap = state.gridMap || createGridMap(state.tabStops);
611
- const cellCoordinates = getCellCoordinates(gridMap, currentTabStop);
612
- if (!cellCoordinates) {
613
- return state;
614
- }
615
- const {
616
- rowIndex,
617
- columnOffset
618
- } = cellCoordinates;
619
- const previousRow = rowIndex - 1;
620
- let tabStop;
621
- /** Search for the previous enabled cell in the current column */
622
- if (previousRow >= 0) {
623
- tabStop = getCell(gridMap, {
624
- row: {
625
- from: previousRow,
626
- direction: 'desc'
627
- },
628
- col: columnOffset
629
- });
630
- }
631
-
632
- // If none were found, search for the previous cell depending on the loop around parameter
633
- if (!tabStop) {
634
- switch (state.loopAround.col) {
635
- /**
636
- * If columns are configured to be looped inside,
637
- * get the last enabled cell of the current column
638
- */
639
- case LOOP_AROUND_TYPES.inside:
640
- tabStop = getCell(gridMap, {
641
- col: columnOffset,
642
- row: {
643
- from: -1,
644
- direction: 'desc'
645
- }
646
- });
647
- break;
648
- /**
649
- * If columns are configured to be go to the previous,
650
- * search for the last enabled cell from the previous column
651
- */
652
- case LOOP_AROUND_TYPES.nextEnd:
653
- case LOOP_AROUND_TYPES.nextLoop:
654
- default:
655
- if (columnOffset - 1 >= 0) {
656
- tabStop = getCell(gridMap, {
657
- row: {
658
- from: -1,
659
- direction: 'desc'
660
- },
661
- col: {
662
- from: columnOffset - 1,
663
- direction: 'desc'
664
- }
665
- });
666
- break;
667
- }
668
- }
669
- }
670
- /**
671
- * If still none is found and the columns are configured to loop
672
- * search starting from the end
673
- */
674
- if (!tabStop && state.loopAround.col === LOOP_AROUND_TYPES.nextLoop) {
675
- tabStop = getCell(gridMap, {
676
- row: {
677
- from: -1,
678
- direction: 'desc'
679
- },
680
- col: {
681
- from: -1,
682
- direction: 'desc'
683
- }
684
- });
685
- }
686
- if (tabStop) {
687
- return {
688
- ...state,
689
- allowFocusing: true,
690
- selectedId: tabStop.id,
691
- gridMap
692
- };
693
- }
694
- return {
695
- ...state,
696
- allowFocusing: true,
697
- gridMap
698
- };
699
- },
700
- // Moving to the very first not disabled item of the list
701
- VERY_FIRST(state) {
702
- // The very first not disabled item' index.
703
- const tabStop = state.tabStops.find(tabStopIsEnabled);
704
- if (tabStop) {
705
- return {
706
- ...state,
707
- allowFocusing: true,
708
- selectedId: tabStop.id
709
- };
710
- }
711
- return state;
712
- },
713
- // Moving to the very last not disabled item of the list
714
- VERY_LAST(state) {
715
- // The very last not disabled item' index.
716
- const tabStop = findLast(state.tabStops, tabStopIsEnabled);
717
- if (tabStop) {
718
- return {
719
- ...state,
720
- allowFocusing: true,
721
- selectedId: tabStop.id
722
- };
723
- }
724
- return state;
725
- },
726
- NEXT_COLUMN(state, currentTabStop, index) {
727
- const currentRowKey = currentTabStop.rowKey;
728
- if (isNil(currentRowKey)) {
729
- return state;
730
- }
731
- const gridMap = state.gridMap || createGridMap(state.tabStops);
732
- const cellCoordinates = getCellCoordinates(gridMap, currentTabStop);
733
- if (!cellCoordinates) {
734
- return state;
735
- }
736
- const {
737
- rowIndex,
738
- columnOffset
739
- } = cellCoordinates;
740
- // Parse the current row and look for the next enabled cell
741
- let tabStop = getCell(gridMap, {
742
- row: rowIndex,
743
- col: {
744
- from: columnOffset + 1,
745
- direction: 'asc'
746
- }
747
- });
748
-
749
- // If none were found, search for the next cell depending on the loop around parameter
750
- if (!tabStop) {
751
- switch (state.loopAround.row) {
752
- /**
753
- * If rows are configured to be looped inside,
754
- * get the first enabled cell of the current rows
755
- */
756
- case LOOP_AROUND_TYPES.inside:
757
- tabStop = getCell(gridMap, {
758
- row: rowIndex,
759
- col: {
760
- from: 0,
761
- direction: 'asc'
762
- }
763
- });
764
- break;
765
- /**
766
- * If rows are configured to be go to the next,
767
- * search for the next enabled cell from the next row
768
- */
769
- case LOOP_AROUND_TYPES.nextEnd:
770
- case LOOP_AROUND_TYPES.nextLoop:
771
- default:
772
- tabStop = find(state.tabStops, tabStopIsEnabled, index + 1);
773
- break;
774
- }
775
- }
776
- /**
777
- * If still none is found and the row are configured to loop
778
- * search starting from the start
779
- */
780
- if (!tabStop && state.loopAround.row === LOOP_AROUND_TYPES.nextLoop) {
781
- tabStop = find(state.tabStops, tabStopIsEnabled);
782
- }
783
- return {
784
- ...state,
785
- allowFocusing: true,
786
- selectedId: tabStop?.id || state.selectedId,
787
- gridMap
788
- };
789
- },
790
- PREVIOUS_COLUMN(state, currentTabStop, index) {
791
- const currentRowKey = currentTabStop.rowKey;
792
- if (isNil(currentRowKey)) {
793
- return state;
794
- }
795
- const gridMap = state.gridMap || createGridMap(state.tabStops);
796
- const cellCoordinates = getCellCoordinates(gridMap, currentTabStop);
797
- if (!cellCoordinates) {
798
- return state;
799
- }
800
- const {
801
- rowIndex,
802
- columnOffset
803
- } = cellCoordinates;
804
- const previousColumn = columnOffset - 1;
805
- let tabStop;
806
- if (previousColumn >= 0) {
807
- // Parse the current row and look for the next enable cell
808
- tabStop = getCell(gridMap, {
809
- row: rowIndex,
810
- col: {
811
- from: previousColumn,
812
- direction: 'desc'
813
- }
814
- });
815
- }
816
- if (!tabStop) {
817
- switch (state.loopAround.row) {
818
- /**
819
- * If rows are configured to be looped inside,
820
- * get the last enabled cell of the current row
821
- */
822
- case LOOP_AROUND_TYPES.inside:
823
- tabStop = getCell(gridMap, {
824
- row: rowIndex,
825
- col: {
826
- from: -1,
827
- direction: 'desc'
828
- }
829
- });
830
- break;
831
- /**
832
- * If rows are configured to be go to the next,
833
- * search for the previous enabled cell from the previous row
834
- */
835
- case LOOP_AROUND_TYPES.nextEnd:
836
- case LOOP_AROUND_TYPES.nextLoop:
837
- default:
838
- if (index - 1 >= 0) {
839
- tabStop = findLast(state.tabStops, tabStopIsEnabled, index - 1);
840
- }
841
- break;
842
- }
843
- }
844
- /**
845
- * If still none is found and the rows are configured to loop
846
- * search starting from the end
847
- */
848
- if (!tabStop && state.loopAround.row === LOOP_AROUND_TYPES.nextLoop) {
849
- tabStop = findLast(state.tabStops, tabStopIsEnabled);
850
- }
851
- return {
852
- ...state,
853
- allowFocusing: true,
854
- selectedId: tabStop?.id || state.selectedId,
855
- gridMap
856
- };
857
- },
858
- FIRST_IN_COLUMN(state, currentTabStop) {
859
- const currentRowKey = currentTabStop.rowKey;
860
- if (isNil(currentRowKey)) {
861
- return state;
862
- }
863
- const gridMap = state.gridMap || createGridMap(state.tabStops);
864
- const cellCoordinates = getCellCoordinates(gridMap, currentTabStop);
865
- if (!cellCoordinates) {
866
- return state;
867
- }
868
- const {
869
- columnOffset
870
- } = cellCoordinates;
871
- const tabStop = getCell(gridMap, {
872
- col: columnOffset,
873
- row: {
874
- from: 0,
875
- direction: 'asc'
876
- }
877
- });
878
- return {
879
- ...state,
880
- allowFocusing: true,
881
- selectedId: tabStop?.id || state.selectedId,
882
- gridMap
883
- };
884
- },
885
- LAST_IN_COLUMN(state, currentTabStop) {
886
- const currentRowKey = currentTabStop.rowKey;
887
- if (isNil(currentRowKey)) {
888
- return state;
889
- }
890
- const gridMap = state.gridMap || createGridMap(state.tabStops);
891
- const cellCoordinates = getCellCoordinates(gridMap, currentTabStop);
892
- if (!cellCoordinates) {
893
- return state;
894
- }
895
- const {
896
- columnOffset
897
- } = cellCoordinates;
898
- const tabStop = getCell(gridMap, {
899
- col: columnOffset,
900
- row: {
901
- from: -1,
902
- direction: 'desc'
903
- }
904
- });
905
- return {
906
- ...state,
907
- allowFocusing: true,
908
- selectedId: tabStop?.id || state.selectedId,
909
- gridMap
910
- };
911
- },
912
- // Moving to the first item in row
913
- FIRST_IN_ROW(state, currentTabStop) {
914
- const currentRowKey = currentTabStop.rowKey;
915
- if (isNil(currentRowKey)) {
916
- return state;
917
- }
918
- const gridMap = state.gridMap || createGridMap(state.tabStops);
919
- const cellCoordinates = getCellCoordinates(gridMap, currentTabStop);
920
- if (!cellCoordinates) {
921
- return state;
922
- }
923
- const {
924
- rowIndex
925
- } = cellCoordinates;
926
- const tabStop = getCell(gridMap, {
927
- row: rowIndex,
928
- col: {
929
- from: 0,
930
- direction: 'asc'
931
- }
932
- });
933
- return {
934
- ...state,
935
- allowFocusing: true,
936
- selectedId: tabStop?.id || state.selectedId,
937
- gridMap
938
- };
939
- },
940
- // Moving to the last item in row
941
- LAST_IN_ROW(state, currentTabStop) {
942
- const currentRowKey = currentTabStop.rowKey;
943
- if (isNil(currentRowKey)) {
944
- return state;
945
- }
946
- const gridMap = state.gridMap || createGridMap(state.tabStops);
947
- const cellCoordinates = getCellCoordinates(gridMap, currentTabStop);
948
- if (!cellCoordinates) {
949
- return state;
950
- }
951
- const {
952
- rowIndex
953
- } = cellCoordinates;
954
- const tabStop = getCell(gridMap, {
955
- row: rowIndex,
956
- col: {
957
- from: -1,
958
- direction: 'desc'
959
- }
960
- });
961
- return {
962
- ...state,
963
- allowFocusing: true,
964
- selectedId: tabStop?.id || state.selectedId,
965
- gridMap
966
- };
967
- }
968
- };
969
-
970
- /** Handle `KEY_NAV` action to update */
971
- const KEY_NAV = (state, action) => {
972
- const {
973
- id = state.selectedId || state.tabStops[0]?.id,
974
- key,
975
- ctrlKey
976
- } = action.payload;
977
- const index = state.tabStops.findIndex(tabStop => tabStop.id === id);
978
- if (index === -1) {
979
- // tab stop not registered
980
- return state;
981
- }
982
- const currentTabStop = state.tabStops[index];
983
- if (currentTabStop.disabled) {
984
- return state;
985
- }
986
- const isGrid = currentTabStop.rowKey !== null;
987
- const isFirst = index === state.tabStops.findIndex(tabStopIsEnabled);
988
- const isLast = index === findLastIndex(state.tabStops, tabStopIsEnabled);
989
- // Translates the user key down event info into a navigation instruction.
990
- let navigation = null;
991
- // eslint-disable-next-line default-case
992
- switch (key) {
993
- case 'ArrowLeft':
994
- if (isGrid) {
995
- navigation = 'PREVIOUS_COLUMN';
996
- } else if (state.direction === 'horizontal' || state.direction === 'both') {
997
- navigation = shouldLoopListHorizontally(state.direction, state.loopAround) && isFirst ? 'VERY_LAST' : 'PREVIOUS';
998
- }
999
- break;
1000
- case 'ArrowRight':
1001
- if (isGrid) {
1002
- navigation = 'NEXT_COLUMN';
1003
- } else if (state.direction === 'horizontal' || state.direction === 'both') {
1004
- navigation = shouldLoopListHorizontally(state.direction, state.loopAround) && isLast ? 'VERY_FIRST' : 'NEXT';
1005
- }
1006
- break;
1007
- case 'ArrowUp':
1008
- if (isGrid) {
1009
- navigation = 'PREVIOUS_ROW';
1010
- } else if (state.direction === 'vertical' || state.direction === 'both') {
1011
- navigation = shouldLoopListVertically(state.direction, state.loopAround) && isFirst ? 'VERY_LAST' : 'PREVIOUS';
1012
- }
1013
- break;
1014
- case 'ArrowDown':
1015
- if (isGrid) {
1016
- navigation = 'NEXT_ROW';
1017
- } else if (state.direction === 'vertical' || state.direction === 'both') {
1018
- navigation = shouldLoopListVertically(state.direction, state.loopAround) && isLast ? 'VERY_FIRST' : 'NEXT';
1019
- }
1020
- break;
1021
- case 'Home':
1022
- if (isGrid && !ctrlKey) {
1023
- navigation = state.gridJumpToShortcutDirection === 'vertical' ? 'FIRST_IN_COLUMN' : 'FIRST_IN_ROW';
1024
- } else {
1025
- navigation = 'VERY_FIRST';
1026
- }
1027
- break;
1028
- case 'End':
1029
- if (isGrid && !ctrlKey) {
1030
- navigation = state.gridJumpToShortcutDirection === 'vertical' ? 'LAST_IN_COLUMN' : 'LAST_IN_ROW';
1031
- } else {
1032
- navigation = 'VERY_LAST';
1033
- }
1034
- break;
1035
- }
1036
- if (!navigation) {
1037
- return state;
1038
- }
1039
- const newState = MOVES[navigation](state, currentTabStop, index);
1040
- return {
1041
- ...newState,
1042
- isUsingKeyboard: true
1043
- };
1044
- };
1045
-
1046
- /** Determine the updated value for selectedId: */
1047
- const getUpdatedSelectedId = (tabStops, currentSelectedId, defaultSelectedId = null) => {
1048
- // Get tab stop by id
1049
- const tabStop = currentSelectedId && tabStops.find(ts => ts.id === currentSelectedId && !ts.disabled);
1050
- if (!tabStop) {
1051
- // Fallback to default selected id if available, or first enabled tab stop if not
1052
- return tabStops.find(ts => ts.id === defaultSelectedId)?.id || tabStops.find(tabStopIsEnabled)?.id || null;
1053
- }
1054
- return tabStop?.id || defaultSelectedId;
1055
- };
1056
-
1057
- /** Handle `REGISTER_TAB_STOP` action registering a new tab stop. */
1058
- const REGISTER_TAB_STOP = (state, action) => {
1059
- const newTabStop = action.payload;
1060
- const newTabStopElement = newTabStop.domElementRef.current;
1061
- if (!newTabStopElement) {
1062
- return state;
1063
- }
1064
-
1065
- // Find index of tab stop that
1066
- const indexToInsertAt = findLastIndex(state.tabStops, tabStop => {
1067
- if (tabStop.id === newTabStop.id) {
1068
- // tab stop already registered
1069
- return false;
1070
- }
1071
- const domTabStop = tabStop.domElementRef.current;
1072
-
1073
- // New tab stop is following the current tab stop
1074
- return domTabStop?.compareDocumentPosition(newTabStopElement) === Node.DOCUMENT_POSITION_FOLLOWING;
1075
- });
1076
- const insertIndex = indexToInsertAt + 1;
1077
-
1078
- // Insert new tab stop at position `indexToInsertAt`.
1079
- const newTabStops = [...state.tabStops];
1080
- newTabStops.splice(insertIndex, 0, newTabStop);
1081
-
1082
- // Handle autofocus if needed
1083
- let {
1084
- selectedId,
1085
- allowFocusing
1086
- } = state;
1087
- if (state.autofocus === 'first' && insertIndex === 0 || state.autofocus === 'last' && insertIndex === newTabStops.length - 1 || newTabStop.autofocus) {
1088
- allowFocusing = true;
1089
- selectedId = newTabStop.id;
1090
- }
1091
- const newSelectedId = newTabStop.id === state.defaultSelectedId && !newTabStop.disabled ? newTabStop.id : getUpdatedSelectedId(newTabStops, selectedId, state.defaultSelectedId);
1092
- return {
1093
- ...state,
1094
- /**
1095
- * If the tab currently being registered is enabled and set as default selected,
1096
- * set as selected.
1097
- *
1098
- */
1099
- selectedId: newSelectedId,
1100
- tabStops: newTabStops,
1101
- gridMap: null,
1102
- allowFocusing
1103
- };
1104
- };
1105
-
1106
- /** Handle `UNREGISTER_TAB_STOP` action un-registering a new tab stop. */
1107
- const UNREGISTER_TAB_STOP = (state, action) => {
1108
- const {
1109
- id
1110
- } = action.payload;
1111
- const newTabStops = state.tabStops.filter(tabStop => tabStop.id !== id);
1112
- if (newTabStops.length === state.tabStops.length) {
1113
- // tab stop already unregistered
1114
- return state;
1115
- }
1116
-
1117
- /** Get the previous enabled tab stop */
1118
- const previousTabStopIndex = state.tabStops.findIndex(tabStop => tabStop.id === state.selectedId && tabStopIsEnabled(tabStop));
1119
- const newLocal = previousTabStopIndex - 1 > -1;
1120
- const previousTabStop = newLocal ? findLast(newTabStops, tabStopIsEnabled, previousTabStopIndex - 1) : undefined;
1121
- return {
1122
- ...state,
1123
- /** Set the focus on either the previous tab stop if found or the one set as default */
1124
- selectedId: getUpdatedSelectedId(newTabStops, state.selectedId, previousTabStop?.id || state.defaultSelectedId),
1125
- tabStops: newTabStops,
1126
- gridMap: null
1127
- };
1128
- };
1129
-
1130
- /** Handle `UPDATE_TAB_STOP` action updating properties of a tab stop. */
1131
- const UPDATE_TAB_STOP = (state, action) => {
1132
- const {
1133
- id,
1134
- rowKey,
1135
- disabled
1136
- } = action.payload;
1137
- const index = state.tabStops.findIndex(tabStop => tabStop.id === id);
1138
- if (index === -1) {
1139
- // tab stop not registered
1140
- return state;
1141
- }
1142
- const tabStop = state.tabStops[index];
1143
- if (tabStop.disabled === disabled && tabStop.rowKey === rowKey) {
1144
- // Nothing to do so short-circuit.
1145
- return state;
1146
- }
1147
- const newTabStop = {
1148
- ...tabStop,
1149
- rowKey,
1150
- disabled
1151
- };
1152
- const newTabStops = [...state.tabStops];
1153
- newTabStops.splice(index, 1, newTabStop);
1154
- return {
1155
- ...state,
1156
- selectedId: getUpdatedSelectedId(newTabStops, state.selectedId, state.defaultSelectedId),
1157
- tabStops: newTabStops,
1158
- gridMap: null
1159
- };
1160
- };
1161
-
1162
- /** Handle `SELECT_TAB_STOP` action selecting a tab stop. */
1163
- const SELECT_TAB_STOP = (state, action) => {
1164
- const {
1165
- id,
1166
- type
1167
- } = action.payload;
1168
- const tabStop = state.tabStops.find(ts => ts.id === id);
1169
- if (!tabStop || tabStop.disabled) {
1170
- return state;
1171
- }
1172
- return {
1173
- ...state,
1174
- allowFocusing: true,
1175
- selectedId: tabStop.id,
1176
- isUsingKeyboard: type === 'keyboard'
1177
- };
1178
- };
1179
- const SET_ALLOW_FOCUSING = (state, action) => {
1180
- return {
1181
- ...state,
1182
- selectedId: getUpdatedSelectedId(state.tabStops, null, state.defaultSelectedId),
1183
- allowFocusing: action.payload.allow,
1184
- isUsingKeyboard: Boolean(action.payload.isKeyboardNavigation)
1185
- };
1186
- };
1187
-
1188
- /** Handle `RESET_SELECTED_TAB_STOP` action reseting the selected tab stop. */
1189
- const RESET_SELECTED_TAB_STOP = state => {
1190
- return {
1191
- ...state,
1192
- allowFocusing: false,
1193
- selectedId: getUpdatedSelectedId(state.tabStops, null, state.defaultSelectedId),
1194
- defaultSelectedId: getUpdatedSelectedId(state.tabStops, null, state.defaultSelectedId),
1195
- isUsingKeyboard: false
1196
- };
1197
- };
1198
-
1199
- const INITIAL_STATE = {
1200
- selectedId: null,
1201
- allowFocusing: false,
1202
- tabStops: [],
1203
- direction: 'horizontal',
1204
- loopAround: buildLoopAroundObject(false),
1205
- gridMap: null,
1206
- defaultSelectedId: null,
1207
- autofocus: undefined,
1208
- isUsingKeyboard: false
1209
- };
1210
- const OPTIONS_UPDATED = (state, action) => {
1211
- const {
1212
- autofocus
1213
- } = action.payload;
1214
- let {
1215
- selectedId,
1216
- allowFocusing
1217
- } = state;
1218
-
1219
- // Update selectedId when updating the `autofocus` option.
1220
- if (!state.autofocus && autofocus) {
1221
- if (autofocus === 'first') {
1222
- selectedId = state.tabStops.find(tabStopIsEnabled)?.id || null;
1223
- } else if (autofocus === 'last') {
1224
- selectedId = findLast(state.tabStops, tabStopIsEnabled)?.id || null;
1225
- }
1226
- allowFocusing = true;
1227
- }
1228
- return {
1229
- ...state,
1230
- ...action.payload,
1231
- selectedId,
1232
- allowFocusing: action.payload.allowFocusing || allowFocusing,
1233
- loopAround: buildLoopAroundObject(action.payload.loopAround)
1234
- };
1235
- };
1236
-
1237
- /** Reducers for each action type: */
1238
- const REDUCERS$1 = {
1239
- REGISTER_TAB_STOP,
1240
- UNREGISTER_TAB_STOP,
1241
- UPDATE_TAB_STOP,
1242
- SELECT_TAB_STOP,
1243
- OPTIONS_UPDATED,
1244
- KEY_NAV,
1245
- SET_ALLOW_FOCUSING,
1246
- RESET_SELECTED_TAB_STOP
1247
- };
1248
-
1249
- /** Main reducer */
1250
- const reducer$1 = (state, action) => {
1251
- return REDUCERS$1[action.type]?.(state, action) || state;
1252
- };
1253
-
1254
- const MovingFocusContext = /*#__PURE__*/React__default.createContext({
1255
- state: INITIAL_STATE,
1256
- dispatch: noop
1257
- });
1258
-
1259
- /**
1260
- * Hook options
1261
- */
1262
-
1263
- /**
1264
- * Hook to use in tab stop element of a virtual focus (ex: options of a listbox in a combobox).
1265
- *
1266
- * @returns true if the current tab stop has virtual focus
1267
- */
1268
- const useVirtualFocus = (id, domElementRef, disabled = false, rowKey = null, autofocus = false) => {
1269
- const isMounted = React__default.useRef(false);
1270
- const {
1271
- state,
1272
- dispatch
1273
- } = React__default.useContext(MovingFocusContext);
1274
-
1275
- // Register the tab stop on mount and unregister it on unmount:
1276
- React__default.useEffect(() => {
1277
- const {
1278
- current: domElement
1279
- } = domElementRef;
1280
- if (!domElement) {
1281
- return undefined;
1282
- }
1283
- // Select tab stop on click
1284
- const onClick = event => {
1285
- dispatch({
1286
- type: 'SELECT_TAB_STOP',
1287
- payload: {
1288
- id,
1289
- type: getPointerTypeFromEvent(event)
1290
- }
1291
- });
1292
- };
1293
- domElement.addEventListener('click', onClick);
1294
-
1295
- // Register tab stop in context
1296
- dispatch({
1297
- type: 'REGISTER_TAB_STOP',
1298
- payload: {
1299
- id,
1300
- domElementRef,
1301
- rowKey,
1302
- disabled,
1303
- autofocus
1304
- }
1305
- });
1306
- return () => {
1307
- domElement.removeEventListener('click', onClick);
1308
- dispatch({
1309
- type: 'UNREGISTER_TAB_STOP',
1310
- payload: {
1311
- id
1312
- }
1313
- });
1314
- };
1315
- },
1316
- /**
1317
- * Pass the list key as dependency to make tab stops
1318
- * re-register when it changes.
1319
- */
1320
- // eslint-disable-next-line react-hooks/exhaustive-deps
1321
- [state.listKey]);
1322
-
1323
- /*
1324
- * Update the tab stop data if `rowKey` or `disabled` change.
1325
- * The isMounted flag is used to prevent this effect running on mount, which is benign but redundant (as the
1326
- * REGISTER_TAB_STOP action would have just been dispatched).
1327
- */
1328
- React__default.useEffect(() => {
1329
- if (isMounted.current) {
1330
- dispatch({
1331
- type: 'UPDATE_TAB_STOP',
1332
- payload: {
1333
- id,
1334
- rowKey,
1335
- disabled
1336
- }
1337
- });
1338
- } else {
1339
- isMounted.current = true;
1340
- }
1341
- },
1342
- // eslint-disable-next-line react-hooks/exhaustive-deps
1343
- [disabled, rowKey]);
1344
- const isActive = id === state.selectedId;
1345
-
1346
- // Scroll element into view when highlighted
1347
- useEffect(() => {
1348
- const {
1349
- current
1350
- } = domElementRef;
1351
- if (isActive && current && current.scrollIntoView) {
1352
- /**
1353
- * In some cases, the selected item is contained in a popover
1354
- * that won't be immediately set in the correct position.
1355
- * Setting a small timeout before scroll the item into view
1356
- * leaves it time to settle at the correct position.
1357
- */
1358
- const timeout = setTimeout(() => {
1359
- current.scrollIntoView({
1360
- block: 'nearest'
1361
- });
1362
- }, 10);
1363
- return () => {
1364
- clearTimeout(timeout);
1365
- };
1366
- }
1367
- return undefined;
1368
- }, [domElementRef, isActive]);
1369
- const focused = isActive && state.allowFocusing;
1370
-
1371
- // Determine if the current tab stop is the currently active one:
1372
- return focused;
1373
- };
1374
-
1375
- /** Generate the combobox option id from the combobox id and the given id */
1376
- const generateOptionId = (comboboxId, optionId) => `${comboboxId}-option-${optionId}`;
1377
-
1378
- /** Verifies that the combobox registered option is an action */
1379
- const isComboboxAction = option => Boolean(option?.isAction);
1380
-
1381
- /** Verifies that the combobox registered option is the option's value */
1382
- const isComboboxValue = option => {
1383
- return !isComboboxAction(option);
1384
- };
1385
-
1386
- const comboboxId = `combobox-${uniqueId()}`;
1387
- const initialState = {
1388
- comboboxId,
1389
- listboxId: `${comboboxId}-popover`,
1390
- status: 'idle',
1391
- isOpen: false,
1392
- inputValue: '',
1393
- showAll: true,
1394
- options: {},
1395
- type: 'listbox',
1396
- optionsLength: 0
1397
- };
1398
-
1399
- /** Actions when the combobox opens. */
1400
- const OPEN_COMBOBOX = (state, action) => {
1401
- const {
1402
- manual
1403
- } = action.payload || {};
1404
- // If the combobox was manually opened, show all suggestions
1405
- return {
1406
- ...state,
1407
- showAll: Boolean(manual),
1408
- isOpen: true
1409
- };
1410
- };
1411
-
1412
- /** Actions when the combobox closes */
1413
- const CLOSE_COMBOBOX = state => {
1414
- return {
1415
- ...state,
1416
- showAll: true,
1417
- isOpen: false
1418
- };
1419
- };
1420
-
1421
- /** Actions on input update. */
1422
- const SET_INPUT_VALUE = (state, action) => {
1423
- return {
1424
- ...state,
1425
- inputValue: action.payload,
1426
- // When the user is changing the value, show only values that are related to the input value.
1427
- showAll: false,
1428
- isOpen: true
1429
- };
1430
- };
1431
-
1432
- /** Register an option to the state */
1433
- const ADD_OPTION = (state, action) => {
1434
- const {
1435
- id,
1436
- option
1437
- } = action.payload;
1438
- const {
1439
- options
1440
- } = state;
1441
- if (options[id]) {
1442
- // Option already exists, return state unchanged
1443
- return state;
1444
- }
1445
- const newOptions = {
1446
- ...options,
1447
- [id]: option
1448
- };
1449
- let newType = state.type;
1450
- if (isComboboxAction(option)) {
1451
- newType = 'grid';
1452
- }
1453
- let newOptionsLength = state.optionsLength;
1454
- if (isComboboxValue(option)) {
1455
- newOptionsLength += 1;
1456
- }
1457
- return {
1458
- ...state,
1459
- options: newOptions,
1460
- type: newType,
1461
- optionsLength: newOptionsLength
1462
- };
1463
- };
1464
-
1465
- /** Remove an option from the state */
1466
- const REMOVE_OPTION = (state, action) => {
1467
- const {
1468
- id
1469
- } = action.payload;
1470
- const {
1471
- options
1472
- } = state;
1473
- const option = options[id];
1474
- if (!options[id]) {
1475
- // Option doesn't exist, return state unchanged
1476
- return state;
1477
- }
1478
- const newOptions = {
1479
- ...options
1480
- };
1481
- delete newOptions[id];
1482
- let newOptionsLength = state.optionsLength;
1483
- if (isComboboxValue(option)) {
1484
- newOptionsLength -= 1;
1485
- }
1486
- return {
1487
- ...state,
1488
- options: newOptions,
1489
- optionsLength: newOptionsLength
1490
- };
1491
- };
1492
-
1493
- /** Reducers for each action type: */
1494
- const REDUCERS = {
1495
- OPEN_COMBOBOX,
1496
- CLOSE_COMBOBOX,
1497
- SET_INPUT_VALUE,
1498
- ADD_OPTION,
1499
- REMOVE_OPTION
1500
- };
1501
-
1502
- /** Main reducer */
1503
- const reducer = (state, action) => {
1504
- return REDUCERS[action.type]?.(state, action) || state;
1505
- };
1506
-
1507
- /** Dispatch for the combobox component */
1508
-
1509
- /** Context for the Combobox component */
1510
- const ComboboxContext = /*#__PURE__*/React__default.createContext({
1511
- ...initialState,
1512
- openOnFocus: false,
1513
- openOnClick: false,
1514
- selectionType: 'single',
1515
- optionsLength: 0,
1516
- onSelect: noop,
1517
- onInputChange: noop,
1518
- onOpen: noop,
1519
- dispatch: noop,
1520
- translations: {
1521
- clearLabel: '',
1522
- tryReloadLabel: '',
1523
- showSuggestionsLabel: '',
1524
- noResultsForInputLabel: input => input || '',
1525
- loadingLabel: '',
1526
- serviceUnavailableLabel: '',
1527
- nbOptionsLabel: options => `${options}`
1528
- }
1529
- });
1530
-
1531
- /** Context for a combobox section to store its unique id */
1532
- const SectionContext = /*#__PURE__*/React__default.createContext({
1533
- sectionId: ''
1534
- });
1535
-
1536
- const ComboboxOptionContext = /*#__PURE__*/createContext({});
1537
- /** Context Provider to store the current combobox option id. */
1538
- const ComboboxOptionContextProvider = ({
1539
- optionId,
1540
- isKeyboardHighlighted,
1541
- children
1542
- }) => {
1543
- const value = React__default.useMemo(() => ({
1544
- optionId,
1545
- isKeyboardHighlighted
1546
- }), [optionId, isKeyboardHighlighted]);
1547
- return /*#__PURE__*/jsx(ComboboxOptionContext.Provider, {
1548
- value: value,
1549
- children: children
1550
- });
1551
- };
1552
-
1553
- /**
1554
- * Retrieve the current combobox option id.
1555
- * Must be used within a ComboboxOptionIdProvider
1556
- */
1557
- const useComboboxOptionContext = () => {
1558
- const comboboxOption = useContext(ComboboxOptionContext);
1559
- if (!comboboxOption?.optionId) {
1560
- throw new Error('This hook must be used within a ComboboxOptionIdProvider');
1561
- }
1562
- return comboboxOption;
1563
- };
1564
-
1565
- /** Context to store the refs of the combobox elements */
1566
- const ComboboxRefsContext = /*#__PURE__*/createContext({
1567
- triggerRef: {
1568
- current: null
1569
- },
1570
- anchorRef: {
1571
- current: null
1572
- }
1573
- });
1574
- /** Provider to store the required refs for the Combobox */
1575
- const ComboboxRefsProvider = ({
1576
- triggerRef,
1577
- anchorRef,
1578
- children
1579
- }) => {
1580
- const value = useMemo(() => ({
1581
- triggerRef,
1582
- anchorRef
1583
- }), [triggerRef, anchorRef]);
1584
- return /*#__PURE__*/jsx(ComboboxRefsContext.Provider, {
1585
- value: value,
1586
- children: children
1587
- });
1588
- };
1589
-
1590
- /** Retrieves the combobox elements references from context */
1591
- const useComboboxRefs = () => {
1592
- const refs = useContext(ComboboxRefsContext);
1593
- if (!refs) {
1594
- throw new Error('The useComboboxRefs hook must be called within a ComboboxRefsProvider');
1595
- }
1596
- return refs;
1597
- };
1598
-
1599
- /** Retrieve the current combobox state and actions */
1600
- const useCombobox = () => {
1601
- const comboboxContext = React__default.useContext(ComboboxContext);
1602
- const {
1603
- dispatch: movingFocusDispatch
1604
- } = React__default.useContext(MovingFocusContext);
1605
- const {
1606
- onSelect,
1607
- onInputChange,
1608
- onOpen,
1609
- dispatch,
1610
- inputValue,
1611
- ...contextValues
1612
- } = comboboxContext;
1613
- const {
1614
- triggerRef
1615
- } = useComboboxRefs();
1616
-
1617
- /** Action triggered when the listBox is closed without selecting any option */
1618
- const handleClose = React__default.useCallback(() => {
1619
- dispatch({
1620
- type: 'CLOSE_COMBOBOX'
1621
- });
1622
- // Reset visual focus
1623
- movingFocusDispatch({
1624
- type: 'RESET_SELECTED_TAB_STOP'
1625
- });
1626
- }, [dispatch, movingFocusDispatch]);
1627
-
1628
- // Handle callbacks on options mounted
1629
- const [optionsMountedCallbacks, setOptionsMountedCallback] = React__default.useState();
1630
- React__default.useEffect(() => {
1631
- if (comboboxContext.optionsLength > 0 && optionsMountedCallbacks?.length) {
1632
- const optionsArray = Object.values(comboboxContext.options);
1633
- // Execute callbacks
1634
- for (const callback of optionsMountedCallbacks) {
1635
- callback(optionsArray);
1636
- }
1637
- setOptionsMountedCallback(undefined);
1638
- }
1639
- }, [comboboxContext.options, comboboxContext.optionsLength, optionsMountedCallbacks]);
1640
-
1641
- /** Callback for when an option is selected */
1642
- const handleSelected = React__default.useCallback((option, source) => {
1643
- if (option?.isDisabled) {
1644
- return;
1645
- }
1646
- if (isComboboxValue(option)) {
1647
- /**
1648
- * We only close the list if the selection type is single.
1649
- * If it is multiple, we want to allow the user to continue
1650
- * selecting multiple options.
1651
- */
1652
- if (comboboxContext.selectionType !== 'multiple') {
1653
- handleClose();
1654
- }
1655
- /** Call parent onSelect callback */
1656
- if (onSelect) {
1657
- onSelect(option);
1658
- }
1659
- }
1660
-
1661
- /** If the option itself has a custom action, also call it */
1662
- if (option?.onSelect) {
1663
- option.onSelect(option, source);
1664
- }
1665
-
1666
- /** Reset focus on input */
1667
- if (triggerRef?.current) {
1668
- triggerRef.current?.focus();
1669
- }
1670
- }, [comboboxContext.selectionType, handleClose, onSelect, triggerRef]);
1671
-
1672
- /** Callback for when the input must be updated */
1673
- const handleInputChange = React__default.useCallback((value, ...args) => {
1674
- // Update the local state
1675
- dispatch({
1676
- type: 'SET_INPUT_VALUE',
1677
- payload: value
1678
- });
1679
- // If a callback if given, call it with the value
1680
- if (onInputChange) {
1681
- onInputChange(value, ...args);
1682
- }
1683
- // Reset visual focus
1684
- movingFocusDispatch({
1685
- type: 'RESET_SELECTED_TAB_STOP'
1686
- });
1687
- }, [dispatch, movingFocusDispatch, onInputChange]);
1688
-
1689
- /**
1690
- * Open the popover
1691
- *
1692
- * @returns a promise with the updated context once all options are mounted
1693
- */
1694
- const handleOpen = React__default.useCallback(params => {
1695
- /** update the local state */
1696
- dispatch({
1697
- type: 'OPEN_COMBOBOX',
1698
- payload: params
1699
- });
1700
- /** If a parent callback was given, trigger it with state information */
1701
- if (onOpen) {
1702
- onOpen({
1703
- currentValue: inputValue,
1704
- manual: Boolean(params?.manual)
1705
- });
1706
- }
1707
-
1708
- // Promise resolving options on mount
1709
- return new Promise(resolve => {
1710
- // Append to the list of callback on options mounted
1711
- setOptionsMountedCallback((callbacks = []) => {
1712
- callbacks.push(resolve);
1713
- return callbacks;
1714
- });
1715
- });
1716
- }, [dispatch, inputValue, onOpen]);
1717
- return React__default.useMemo(() => ({
1718
- handleClose,
1719
- handleOpen,
1720
- handleInputChange,
1721
- handleSelected,
1722
- dispatch,
1723
- inputValue,
1724
- ...contextValues
1725
- }), [contextValues, dispatch, handleClose, handleInputChange, handleOpen, handleSelected, inputValue]);
1726
- };
1727
-
1728
- /** Retrieve the current combobox section id */
1729
- const useComboboxSectionId = () => {
1730
- return useContext(SectionContext);
1731
- };
1732
-
1733
- /**
1734
- * Register the given option to the context
1735
- */
1736
- const useRegisterOption = (registerId, option, shouldRegister) => {
1737
- const {
1738
- dispatch
1739
- } = useCombobox();
1740
-
1741
- /** Register the given options */
1742
- React__default.useEffect(() => {
1743
- if (option && shouldRegister) {
1744
- dispatch({
1745
- type: 'ADD_OPTION',
1746
- payload: {
1747
- id: registerId,
1748
- option
1749
- }
1750
- });
1751
- }
1752
-
1753
- // Unregister ids if/when the component unmounts or if option changes
1754
- return () => {
1755
- if (option) {
1756
- dispatch({
1757
- type: 'REMOVE_OPTION',
1758
- payload: {
1759
- id: registerId
1760
- }
1761
- });
1762
- }
1763
- };
1764
- }, [dispatch, option, registerId, shouldRegister]);
1765
- };
1766
-
1767
- export { A11YLiveMessage as A, ComboboxOptionContextProvider as C, DisabledStateProvider as D, INITIAL_STATE as I, MovingFocusContext as M, NAV_KEYS as N, Portal as P, SectionContext as S, useComboboxSectionId as a, useCombobox as b, useRegisterOption as c, useVirtualFocus as d, useComboboxOptionContext as e, useComboboxRefs as f, generateOptionId as g, ClickAwayProvider as h, buildLoopAroundObject as i, getPointerTypeFromEvent as j, ComboboxContext as k, isComboboxValue as l, initialState as m, ComboboxOptionContext as n, reducer as o, ComboboxRefsProvider as p, PortalProvider as q, reducer$1 as r, useDisabledStateContext as u };
1768
- //# sourceMappingURL=BQFZG9jO.js.map