@entur/dropdown 9.3.1 → 9.4.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.
package/dist/dropdown.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { useDebounce, getActiveElement, mergeRefs, warnAboutMissingStyles } from "@entur/utils";
2
2
  import { jsx, jsxs, Fragment } from "react/jsx-runtime";
3
- import React, { forwardRef, createElement, useRef, useLayoutEffect, useCallback, useMemo, useState, useEffect, useId } from "react";
3
+ import React, { forwardRef, useRef, useLayoutEffect, useCallback, useMemo, useState, useEffect, useId } from "react";
4
4
  import { useCombobox, useMultipleSelection, useSelect } from "downshift";
5
5
  import classNames from "classnames";
6
6
  import { useFloating, offset, shift, size, flip, autoUpdate } from "@floating-ui/react-dom";
@@ -178,19 +178,30 @@ const DropdownList = ({
178
178
  const SelectedItemTag = ({
179
179
  ariaLabelRemoveSelected,
180
180
  ariaLabelChosen = "valgt",
181
+ closeButtonRef,
181
182
  disabled,
182
183
  getSelectedItemProps,
183
184
  index,
185
+ onKeyDown,
184
186
  readOnly,
185
187
  removeSelectedItem,
186
188
  selectedItem
187
189
  }) => {
188
190
  if (!selectedItem) return null;
189
- const { tabIndex: _, ...selectedItemProps } = getSelectedItemProps?.({
191
+ const {
192
+ tabIndex: _tabIndex,
193
+ onClick: _onClick,
194
+ ...selectedItemProps
195
+ } = getSelectedItemProps?.({
190
196
  selectedItem,
191
197
  index
192
198
  }) ?? {};
193
- return /* @__PURE__ */ createElement(
199
+ const handleKeyDown = (e) => {
200
+ if (e.key === "Backspace" || e.key === "Delete") e.preventDefault();
201
+ selectedItemProps.onKeyDown?.(e);
202
+ onKeyDown?.(e);
203
+ };
204
+ return /* @__PURE__ */ jsx(
194
205
  TagChip,
195
206
  {
196
207
  size: "small",
@@ -198,24 +209,24 @@ const SelectedItemTag = ({
198
209
  "eds-dropdown__selected-item-tag--readonly": readOnly,
199
210
  "eds-dropdown__selected-item-tag--disabled": disabled
200
211
  }),
212
+ ref: closeButtonRef,
201
213
  ...selectedItemProps,
214
+ onKeyDown: handleKeyDown,
202
215
  onClose: (e) => {
203
216
  e.stopPropagation();
204
217
  removeSelectedItem(selectedItem);
205
218
  },
206
- onClick: (e) => e.stopPropagation(),
207
219
  closeButtonAriaLabel: `${selectedItem.label} ${ariaLabelChosen}, ${ariaLabelRemoveSelected} `,
208
- key: selectedItem.value,
209
- "aria-live": "polite"
210
- },
211
- /* @__PURE__ */ jsx(
212
- "span",
213
- {
214
- "aria-hidden": "true",
215
- className: "eds-dropdown__selected-item-tag__text",
216
- children: selectedItem.label
217
- }
218
- )
220
+ closeButtonTabIndex: -1,
221
+ children: /* @__PURE__ */ jsx(
222
+ "span",
223
+ {
224
+ "aria-hidden": disabled || readOnly ? void 0 : true,
225
+ className: "eds-dropdown__selected-item-tag__text",
226
+ children: selectedItem.label
227
+ }
228
+ )
229
+ }
219
230
  );
220
231
  };
221
232
  const DropdownFieldAppendix = forwardRef(
@@ -521,7 +532,7 @@ const useMultiselectUtils = ({
521
532
  unselectAllListItems
522
533
  };
523
534
  };
524
- function getA11yStatusMessage(options) {
535
+ function getResultsStatusMessage(options) {
525
536
  const { isOpen, selectAllItemIncluded = false, resultCount } = options;
526
537
  if (!isOpen) {
527
538
  return "";
@@ -532,6 +543,35 @@ function getA11yStatusMessage(options) {
532
543
  }
533
544
  return `${resultCountWithoutSelectAll} resultat${resultCountWithoutSelectAll === 1 ? "" : "er"} tilgjengelig, naviger med pil opp eller ned, velg elementer med Enter.`;
534
545
  }
546
+ function getSelectionStatusMessage({
547
+ previousSelectedItems,
548
+ selectedItems,
549
+ ariaLabelChosenSingular,
550
+ ariaLabelAddedPlural,
551
+ ariaLabelChosenTotal,
552
+ ariaLabelRemovedSingular,
553
+ ariaLabelRemovedPlural
554
+ }) {
555
+ const includesValue = (items, item) => items.some((other) => other.value === item.value);
556
+ const added = selectedItems.filter(
557
+ (item) => !includesValue(previousSelectedItems, item)
558
+ );
559
+ const removed = previousSelectedItems.filter(
560
+ (item) => !includesValue(selectedItems, item)
561
+ );
562
+ const messages = [];
563
+ if (added.length === 1)
564
+ messages.push(`${added[0].label} ${ariaLabelChosenSingular}`);
565
+ else if (added.length > 1)
566
+ messages.push(
567
+ `${added.length} ${ariaLabelAddedPlural}, ${selectedItems.length} ${ariaLabelChosenTotal}`
568
+ );
569
+ if (removed.length === 1)
570
+ messages.push(`${removed[0].label} ${ariaLabelRemovedSingular}`);
571
+ else if (removed.length > 1)
572
+ messages.push(`${removed.length} ${ariaLabelRemovedPlural}`);
573
+ return messages.join(", ");
574
+ }
535
575
  const SearchableDropdown = React.forwardRef(
536
576
  ({
537
577
  ariaLabelChosenSingular,
@@ -675,7 +715,7 @@ const SearchableDropdown = React.forwardRef(
675
715
  if (highlightedIndex2 >= 0) setLastHighlightedIndex(highlightedIndex2);
676
716
  },
677
717
  // Accessibility
678
- getA11yStatusMessage: (options) => getA11yStatusMessage({ ...options, resultCount: listItems.length })
718
+ getA11yStatusMessage: (options) => getResultsStatusMessage({ ...options, resultCount: listItems.length })
679
719
  });
680
720
  useEffect(() => {
681
721
  if (value !== null && !inputHasFocus) {
@@ -881,10 +921,15 @@ const MultiSelect = React.forwardRef(
881
921
  selectOnTab = false,
882
922
  style,
883
923
  variant = "information",
884
- ariaLabelChosenSingular,
924
+ ariaLabelChosenSingular = "valgt",
885
925
  ariaLabelChosenPlural = "valgte",
926
+ ariaLabelRemovedSingular = "fjernet",
927
+ ariaLabelRemovedPlural = "valg fjernet",
928
+ ariaLabelAddedPlural = "lagt til",
929
+ ariaLabelChosenTotal = "valgte totalt",
886
930
  ariaLabelCloseList = "Lukk liste med valg",
887
- ariaLabelJumpToInput = `${selectedItems.length} valgte elementer, trykk for å hoppe til tekstfeltet`,
931
+ ariaLabelJumpToInput: _deprecatedAriaLabelJumpToInput,
932
+ ariaLabelNavigateToSelected = `${selectedItems.length} valgte, bruk venstre piltast for å gå til dem`,
888
933
  ariaLabelOpenList = "Åpne liste med valg",
889
934
  ariaLabelRemoveSelected = "trykk for å fjerne valg",
890
935
  ariaLabelSelectedItem,
@@ -909,6 +954,11 @@ const MultiSelect = React.forwardRef(
909
954
  fetchItems
910
955
  } = useResolvedItems(initialItems, debounceTimeout);
911
956
  const isAllNonAsyncItemsSelected = typeof initialItems !== "function" && selectedItems.length === normalizedItems.length;
957
+ const navigateToSelectedId = `eds-multiselect-navigate-to-selected${useId()}`;
958
+ const selectedLabelsId = `eds-multiselect-selected-labels${useId()}`;
959
+ const showSummary = selectedItems.length > maxChips;
960
+ const canNavigateToSelected = selectedItems.length > 0 && !disabled && !readOnly;
961
+ const summaryRef = useRef(null);
912
962
  const selectAllUniqueId = `select-all${useId()}`;
913
963
  const selectAll = React.useMemo(
914
964
  () => ({
@@ -962,11 +1012,15 @@ const MultiSelect = React.forwardRef(
962
1012
  selectAll,
963
1013
  selectedItems
964
1014
  });
1015
+ const pendingSelectionChange = useRef(null);
1016
+ const removalActiveIndex = useRef();
965
1017
  const {
1018
+ activeIndex,
966
1019
  getSelectedItemProps,
967
1020
  getDropdownProps,
968
1021
  reset,
969
1022
  removeSelectedItem,
1023
+ setActiveIndex,
970
1024
  setSelectedItems
971
1025
  } = useMultipleSelection({
972
1026
  selectedItems,
@@ -974,15 +1028,70 @@ const MultiSelect = React.forwardRef(
974
1028
  itemToString,
975
1029
  itemToKey,
976
1030
  ...environment && { environment },
977
- onSelectedItemsChange({ selectedItems: newSelectedItems }) {
1031
+ // Removing with the close button keeps focus where Backspace would. Done
1032
+ // here, in the same action, since a second dispatch would reapply the
1033
+ // controlled selectedItems and undo the removal
1034
+ stateReducer: (state, { type, changes }) => {
1035
+ if (type !== useMultipleSelection.stateChangeTypes.FunctionRemoveSelectedItem)
1036
+ return changes;
1037
+ const remaining = changes.selectedItems ?? [];
1038
+ const removedIndex = state.selectedItems.findIndex(
1039
+ (item) => !remaining.includes(item)
1040
+ );
1041
+ return {
1042
+ ...changes,
1043
+ activeIndex: remaining.length === 0 ? -1 : Math.min(removedIndex, remaining.length - 1)
1044
+ };
1045
+ },
1046
+ onSelectedItemsChange({ selectedItems: newSelectedItems = [] }) {
1047
+ pendingSelectionChange.current = {
1048
+ previousSelectedItems: selectedItems,
1049
+ requestedSelectedItems: newSelectedItems,
1050
+ previousActiveIndex: removalActiveIndex.current
1051
+ };
1052
+ removalActiveIndex.current = void 0;
978
1053
  onChange(newSelectedItems);
979
- }
1054
+ },
1055
+ // Only passed after a user action, so changes from the parent aren't
1056
+ // announced and an empty message can't cut off the result count
1057
+ getA11yStatusMessage: pendingSelectionChange.current ? (state) => {
1058
+ const {
1059
+ previousSelectedItems,
1060
+ requestedSelectedItems,
1061
+ previousActiveIndex
1062
+ } = pendingSelectionChange.current ?? {
1063
+ previousSelectedItems: state.selectedItems,
1064
+ requestedSelectedItems: state.selectedItems
1065
+ };
1066
+ pendingSelectionChange.current = null;
1067
+ const requestAccepted = requestedSelectedItems.length === state.selectedItems.length && requestedSelectedItems.every(
1068
+ (item) => state.selectedItems.some((s) => s.value === item.value)
1069
+ );
1070
+ if (!requestAccepted) return "";
1071
+ const message = getSelectionStatusMessage({
1072
+ previousSelectedItems,
1073
+ selectedItems: state.selectedItems,
1074
+ ariaLabelChosenSingular,
1075
+ ariaLabelAddedPlural,
1076
+ ariaLabelChosenTotal,
1077
+ ariaLabelRemovedSingular,
1078
+ ariaLabelRemovedPlural
1079
+ });
1080
+ const removed = previousSelectedItems.filter(
1081
+ (item) => !state.selectedItems.some((s) => s.value === item.value)
1082
+ );
1083
+ const removedIndex = removed.length === 1 ? previousSelectedItems.indexOf(removed[0]) : -1;
1084
+ const focusStayed = removedIndex >= 0 && state.activeIndex === removedIndex && (previousActiveIndex ?? removedIndex) === removedIndex;
1085
+ const focusedItem = focusStayed ? state.selectedItems[state.activeIndex] : void 0;
1086
+ return message && focusedItem ? `${message}, ${focusedItem.label}` : message;
1087
+ } : void 0
980
1088
  });
981
1089
  const stateReducer = React.useCallback(
982
1090
  (state, {
983
1091
  type,
984
1092
  changes
985
1093
  }) => {
1094
+ if (readOnly) return { ...state, isOpen: false };
986
1095
  switch (type) {
987
1096
  // keep menu open and edit input value on item selection
988
1097
  case useCombobox.stateChangeTypes.InputKeyDownEnter:
@@ -1037,7 +1146,7 @@ const MultiSelect = React.forwardRef(
1037
1146
  return changes;
1038
1147
  }
1039
1148
  },
1040
- [hideSelectAll, listItems, clearInputOnSelect]
1149
+ [hideSelectAll, listItems, clearInputOnSelect, readOnly]
1041
1150
  );
1042
1151
  const {
1043
1152
  getInputProps,
@@ -1070,7 +1179,7 @@ const MultiSelect = React.forwardRef(
1070
1179
  if (highlightedIndex2 >= 0) setLastHighlightedIndex(highlightedIndex2);
1071
1180
  },
1072
1181
  // Accessibility
1073
- getA11yStatusMessage: (options) => getA11yStatusMessage({
1182
+ getA11yStatusMessage: (options) => getResultsStatusMessage({
1074
1183
  ...options,
1075
1184
  selectAllItemIncluded: !hideSelectAll,
1076
1185
  resultCount: listItems.length
@@ -1116,12 +1225,35 @@ const MultiSelect = React.forwardRef(
1116
1225
  reset();
1117
1226
  };
1118
1227
  const dropdownProps = getDropdownProps({
1119
- preventKeyAction: isOpen,
1228
+ preventKeyAction: isOpen || readOnly,
1120
1229
  value: inputValue ?? EMPTY_INPUT,
1121
1230
  ref: mergeRefs(inputRef, ref)
1122
1231
  });
1123
1232
  const inputProps = getInputProps({
1233
+ onBlur,
1234
+ onFocus: (e) => {
1235
+ if (activeIndex !== -1) setActiveIndex(-1);
1236
+ onFocus?.(e);
1237
+ },
1238
+ ...dropdownProps,
1124
1239
  onKeyDown: (e) => {
1240
+ if (readOnly) {
1241
+ if (e.key === "Backspace" || e.key === "Delete") e.preventDefault();
1242
+ return;
1243
+ }
1244
+ const caretAtStart = e.currentTarget.selectionStart === 0 && e.currentTarget.selectionEnd === 0;
1245
+ const hasModifier = e.shiftKey || e.ctrlKey || e.metaKey || e.altKey;
1246
+ if (e.key === "ArrowLeft" && !hasModifier && caretAtStart && canNavigateToSelected) {
1247
+ if (showSummary) {
1248
+ summaryRef.current?.focus();
1249
+ return;
1250
+ }
1251
+ if (isOpen) {
1252
+ setActiveIndex(selectedItems.length - 1);
1253
+ return;
1254
+ }
1255
+ }
1256
+ dropdownProps.onKeyDown?.(e);
1125
1257
  if (selectOnTab && isOpen && e.key === "Tab") {
1126
1258
  const highlitedItem = listItems[highlightedIndex];
1127
1259
  if (!highlitedItem) return;
@@ -1133,13 +1265,12 @@ const MultiSelect = React.forwardRef(
1133
1265
  });
1134
1266
  }
1135
1267
  },
1136
- onBlur,
1137
- onFocus,
1138
- ...dropdownProps,
1139
1268
  className: "eds-dropdown__input eds-form-control",
1140
- disabled: readOnly || disabled,
1269
+ disabled,
1270
+ readOnly,
1141
1271
  placeholder,
1142
- tabIndex: disabled || readOnly ? -1 : void 0
1272
+ tabIndex: disabled ? -1 : void 0,
1273
+ "aria-describedby": canNavigateToSelected ? navigateToSelectedId : readOnly && selectedItems.length > 0 ? selectedLabelsId : void 0
1143
1274
  });
1144
1275
  const labelProps = getLabelProps();
1145
1276
  const menuProps = getMenuProps({
@@ -1170,7 +1301,10 @@ const MultiSelect = React.forwardRef(
1170
1301
  labelTooltip,
1171
1302
  onClick: (e) => {
1172
1303
  if (e.target === e.currentTarget) inputProps?.onClick?.(e);
1173
- onClick?.(e);
1304
+ const clickedSelectedItem = e.target.closest(
1305
+ ".eds-dropdown__selected-item-tag"
1306
+ );
1307
+ if (!clickedSelectedItem) onClick?.(e);
1174
1308
  },
1175
1309
  onKeyDown,
1176
1310
  readOnly,
@@ -1209,8 +1343,9 @@ const MultiSelect = React.forwardRef(
1209
1343
  }
1210
1344
  ),
1211
1345
  children: [
1212
- selectedItems.length > 1 ? /* @__PURE__ */ jsx(VisuallyHidden, { onClick: () => inputRef.current?.focus(), children: ariaLabelJumpToInput }) : null,
1213
- selectedItems.length <= maxChips ? selectedItems.map((selectedItem, index) => /* @__PURE__ */ jsx(
1346
+ canNavigateToSelected ? /* @__PURE__ */ jsx(VisuallyHidden, { id: navigateToSelectedId, children: ariaLabelNavigateToSelected }) : null,
1347
+ (readOnly || disabled && showSummary) && selectedItems.length > 0 ? /* @__PURE__ */ jsx(VisuallyHidden, { id: selectedLabelsId, children: selectedItems.map((item) => item.label).join(", ") }) : null,
1348
+ !showSummary ? selectedItems.map((selectedItem, index) => /* @__PURE__ */ jsx(
1214
1349
  SelectedItemTag,
1215
1350
  {
1216
1351
  ariaLabelChosen: ariaLabelChosenSingular,
@@ -1220,18 +1355,26 @@ const MultiSelect = React.forwardRef(
1220
1355
  index,
1221
1356
  readOnly,
1222
1357
  removeSelectedItem: () => {
1358
+ removalActiveIndex.current = activeIndex;
1223
1359
  removeSelectedItem(selectedItem);
1224
- inputRef?.current?.focus();
1360
+ if (selectedItems.length === 1 && activeIndex === -1)
1361
+ inputRef.current?.focus();
1225
1362
  },
1226
1363
  selectedItem
1227
1364
  },
1228
- selectedItem?.label + (typeof selectedItem?.value === "string" ? selectedItem.value : "")
1365
+ index
1229
1366
  )) : /* @__PURE__ */ jsx(
1230
1367
  SelectedItemTag,
1231
1368
  {
1232
1369
  ariaLabelRemoveSelected: labelClearAllItems,
1233
1370
  ariaLabelChosen: "",
1371
+ closeButtonRef: summaryRef,
1234
1372
  disabled,
1373
+ onKeyDown: (e) => {
1374
+ if (e.key === "ArrowRight") inputRef.current?.focus();
1375
+ if (e.key === "Backspace" || e.key === "Delete")
1376
+ handleOnClear();
1377
+ },
1235
1378
  readOnly,
1236
1379
  removeSelectedItem: handleOnClear,
1237
1380
  selectedItem: summarySelectedItems