@kaizen/components 1.64.12 → 1.64.14

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.
@@ -57,6 +57,8 @@ var FilterSelect = function (_a) {
57
57
  triggerProps = _c.triggerProps,
58
58
  menuProps = _c.menuProps;
59
59
  var buttonProps = button.useButton(triggerProps, triggerRef).buttonProps;
60
+ // `aria-labelledby` and `aria-controls` are being remapped because the `buttonProps` ids generated by React Aria point to nothing.
61
+ // This should ideally be refactored but for now the `aria-controls` is set to the Filter's Listbox (menuProps.id) and the `aria-labelledby` to undefined so the accessible name is derived from the buttons content.
60
62
  var renderTriggerButtonProps = tslib.__assign(tslib.__assign({}, buttonProps), {
61
63
  "aria-labelledby": undefined,
62
64
  "aria-controls": menuProps.id
@@ -4,6 +4,7 @@ var tslib = require('tslib');
4
4
  var React = require('react');
5
5
  var listbox = require('@react-aria/listbox');
6
6
  var classnames = require('classnames');
7
+ var useIsClientReady = require('../../../../__utilities__/useIsClientReady/useIsClientReady.cjs');
7
8
  var SelectContext = require('../../context/SelectContext.cjs');
8
9
  var ListBox_module = require('./ListBox.module.scss.cjs');
9
10
  function _interopDefault(e) {
@@ -13,16 +14,59 @@ function _interopDefault(e) {
13
14
  }
14
15
  var React__default = /*#__PURE__*/_interopDefault(React);
15
16
  var classnames__default = /*#__PURE__*/_interopDefault(classnames);
17
+
18
+ /** A util to retrieve the key of the correct focusable items based of the focus strategy
19
+ * This is used to determine which element from the collection to focus to on open base on the keyboard event
20
+ * ie: UpArrow will set the focusStrategy to "last"
21
+ */
22
+ var getOptionKeyFromCollection = function (state) {
23
+ if (state.selectedItem) {
24
+ return state.selectedItem.key;
25
+ } else if (state.focusStrategy === "last") {
26
+ return state.collection.getLastKey();
27
+ }
28
+ return state.collection.getFirstKey();
29
+ };
30
+ /** This makes the use of query selector less brittle in instances where a failed selector is passed in
31
+ */
32
+ var safeQuerySelector = function (selector) {
33
+ try {
34
+ return document.querySelector(selector);
35
+ } catch (error) {
36
+ // eslint-disable-next-line no-console
37
+ console.error("Kaizen querySelector failed:", error);
38
+ return null;
39
+ }
40
+ };
16
41
  var ListBox = function (_a) {
17
42
  var children = _a.children,
18
43
  menuProps = _a.menuProps,
19
44
  classNameOverride = _a.classNameOverride,
20
45
  restProps = tslib.__rest(_a, ["children", "menuProps", "classNameOverride"]);
46
+ var isClientReady = useIsClientReady.useIsClientReady();
21
47
  var state = SelectContext.useSelectContext().state;
22
- var ref = React__default.default.useRef(null);
48
+ var ref = React.useRef(null);
23
49
  var listBoxProps = listbox.useListBox(tslib.__assign(tslib.__assign({}, menuProps), {
24
- disallowEmptySelection: true
50
+ disallowEmptySelection: true,
51
+ // This is to ensure that the listbox doesn't use React Aria's auto focus feature for Listbox, which creates a visual bug
52
+ autoFocus: false
25
53
  }), state, ref).listBoxProps;
54
+ /**
55
+ * This uses the new useIsClientReady to ensure document exists before trying to querySelector and give the time to focus to the correct element
56
+ */
57
+ React.useEffect(function () {
58
+ var _a;
59
+ if (isClientReady) {
60
+ var optionKey = getOptionKeyFromCollection(state);
61
+ var focusToElement = safeQuerySelector("[data-key='".concat(optionKey, "']"));
62
+ if (focusToElement) {
63
+ focusToElement.focus();
64
+ } else {
65
+ // If an element is not found, focus on the listbox. This ensures the list can still be navigated to via keyboard if the keys do not align to the data attributes of the list items.
66
+ (_a = ref.current) === null || _a === void 0 ? void 0 : _a.focus();
67
+ }
68
+ }
69
+ }, [isClientReady]);
26
70
  return React__default.default.createElement("ul", tslib.__assign({
27
71
  ref: ref,
28
72
  className: classnames__default.default(ListBox_module.listBox, classNameOverride)
@@ -32,7 +32,7 @@ var Overlay = function (_a) {
32
32
  ref: overlayRef,
33
33
  className: classNameOverride
34
34
  }, overlayProps, restProps), React__default.default.createElement(focus.FocusScope, {
35
- autoFocus: true,
35
+ autoFocus: false,
36
36
  restoreFocus: true
37
37
  }, React__default.default.createElement(overlays.DismissButton, {
38
38
  onDismiss: state.close
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+
5
+ /**
6
+ * A hook that returns a truthy value indicating if the code can be run on client side.
7
+ * This is a useful hook for determining if the `document` or `window` objects are available.
8
+ */
9
+ var useIsClientReady = function () {
10
+ var _a = React.useState(false),
11
+ isClientReady = _a[0],
12
+ setIsClientReady = _a[1];
13
+ React.useEffect(function () {
14
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
15
+ setIsClientReady(true);
16
+ }
17
+ }, []);
18
+ return isClientReady;
19
+ };
20
+ exports.useIsClientReady = useIsClientReady;
@@ -50,6 +50,8 @@ const FilterSelect = /*#__PURE__*/function () {
50
50
  triggerProps = _c.triggerProps,
51
51
  menuProps = _c.menuProps;
52
52
  var buttonProps = useButton(triggerProps, triggerRef).buttonProps;
53
+ // `aria-labelledby` and `aria-controls` are being remapped because the `buttonProps` ids generated by React Aria point to nothing.
54
+ // This should ideally be refactored but for now the `aria-controls` is set to the Filter's Listbox (menuProps.id) and the `aria-labelledby` to undefined so the accessible name is derived from the buttons content.
53
55
  var renderTriggerButtonProps = __assign(__assign({}, buttonProps), {
54
56
  "aria-labelledby": undefined,
55
57
  "aria-controls": menuProps.id
@@ -1,20 +1,64 @@
1
1
  import { __rest, __assign } from 'tslib';
2
- import React from 'react';
2
+ import React, { useRef, useEffect } from 'react';
3
3
  import { useListBox } from '@react-aria/listbox';
4
4
  import classnames from 'classnames';
5
+ import { useIsClientReady } from '../../../../__utilities__/useIsClientReady/useIsClientReady.mjs';
5
6
  import { useSelectContext } from '../../context/SelectContext.mjs';
6
7
  import styles from './ListBox.module.scss.mjs';
8
+
9
+ /** A util to retrieve the key of the correct focusable items based of the focus strategy
10
+ * This is used to determine which element from the collection to focus to on open base on the keyboard event
11
+ * ie: UpArrow will set the focusStrategy to "last"
12
+ */
13
+ var getOptionKeyFromCollection = function (state) {
14
+ if (state.selectedItem) {
15
+ return state.selectedItem.key;
16
+ } else if (state.focusStrategy === "last") {
17
+ return state.collection.getLastKey();
18
+ }
19
+ return state.collection.getFirstKey();
20
+ };
21
+ /** This makes the use of query selector less brittle in instances where a failed selector is passed in
22
+ */
23
+ var safeQuerySelector = function (selector) {
24
+ try {
25
+ return document.querySelector(selector);
26
+ } catch (error) {
27
+ // eslint-disable-next-line no-console
28
+ console.error("Kaizen querySelector failed:", error);
29
+ return null;
30
+ }
31
+ };
7
32
  const ListBox = /*#__PURE__*/function () {
8
33
  const ListBox = function (_a) {
9
34
  var children = _a.children,
10
35
  menuProps = _a.menuProps,
11
36
  classNameOverride = _a.classNameOverride,
12
37
  restProps = __rest(_a, ["children", "menuProps", "classNameOverride"]);
38
+ var isClientReady = useIsClientReady();
13
39
  var state = useSelectContext().state;
14
- var ref = React.useRef(null);
40
+ var ref = useRef(null);
15
41
  var listBoxProps = useListBox(__assign(__assign({}, menuProps), {
16
- disallowEmptySelection: true
42
+ disallowEmptySelection: true,
43
+ // This is to ensure that the listbox doesn't use React Aria's auto focus feature for Listbox, which creates a visual bug
44
+ autoFocus: false
17
45
  }), state, ref).listBoxProps;
46
+ /**
47
+ * This uses the new useIsClientReady to ensure document exists before trying to querySelector and give the time to focus to the correct element
48
+ */
49
+ useEffect(function () {
50
+ var _a;
51
+ if (isClientReady) {
52
+ var optionKey = getOptionKeyFromCollection(state);
53
+ var focusToElement = safeQuerySelector("[data-key='".concat(optionKey, "']"));
54
+ if (focusToElement) {
55
+ focusToElement.focus();
56
+ } else {
57
+ // If an element is not found, focus on the listbox. This ensures the list can still be navigated to via keyboard if the keys do not align to the data attributes of the list items.
58
+ (_a = ref.current) === null || _a === void 0 ? void 0 : _a.focus();
59
+ }
60
+ }
61
+ }, [isClientReady]);
18
62
  return /*#__PURE__*/React.createElement("ul", __assign({
19
63
  ref: ref,
20
64
  className: classnames(styles.listBox, classNameOverride)
@@ -25,7 +25,7 @@ const Overlay = /*#__PURE__*/function () {
25
25
  ref: overlayRef,
26
26
  className: classNameOverride
27
27
  }, overlayProps, restProps), /*#__PURE__*/React.createElement(FocusScope, {
28
- autoFocus: true,
28
+ autoFocus: false,
29
29
  restoreFocus: true
30
30
  }, /*#__PURE__*/React.createElement(DismissButton, {
31
31
  onDismiss: state.close
@@ -0,0 +1,18 @@
1
+ import { useState, useEffect } from 'react';
2
+
3
+ /**
4
+ * A hook that returns a truthy value indicating if the code can be run on client side.
5
+ * This is a useful hook for determining if the `document` or `window` objects are available.
6
+ */
7
+ var useIsClientReady = function () {
8
+ var _a = useState(false),
9
+ isClientReady = _a[0],
10
+ setIsClientReady = _a[1];
11
+ useEffect(function () {
12
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
13
+ setIsClientReady(true);
14
+ }
15
+ }, []);
16
+ return isClientReady;
17
+ };
18
+ export { useIsClientReady };
package/dist/styles.css CHANGED
@@ -91,9 +91,6 @@
91
91
  .MenuItem-module_item__DPerF[data-disabled] {
92
92
  opacity: 0.3;
93
93
  }
94
- .Focusable-module_focusableWrapper__NfuIi {
95
- display: inline-flex;
96
- }
97
94
  .Button-module_button__QOSYH {
98
95
  --button-min-height-width: var(--spacing-48);
99
96
  --button-padding-x: calc(
@@ -182,6 +179,9 @@
182
179
  --button-icon-size: var(--spacing-16);
183
180
  gap: var(--spacing-8);
184
181
  }
182
+ .Focusable-module_focusableWrapper__NfuIi {
183
+ display: inline-flex;
184
+ }
185
185
  /** THIS IS AN AUTOGENERATED FILE **/
186
186
  /** THIS IS AN AUTOGENERATED FILE **/
187
187
  /** THIS IS AN AUTOGENERATED FILE **/
@@ -1,9 +1,9 @@
1
- import React, { HTMLAttributes } from "react";
1
+ import { HTMLAttributes, ReactNode } from "react";
2
2
  import { AriaListBoxOptions } from "@react-aria/listbox";
3
3
  import { OverrideClassName } from "../../../../types/OverrideClassName";
4
4
  import { SelectOption, SelectItem } from "../../types";
5
5
  export type SingleListBoxProps<Option extends SelectOption> = OverrideClassName<HTMLAttributes<HTMLUListElement>> & {
6
- children: React.ReactNode;
6
+ children: ReactNode;
7
7
  /** Props for the popup. */
8
8
  menuProps: AriaListBoxOptions<SelectItem<Option>>;
9
9
  };
@@ -0,0 +1 @@
1
+ export * from "./useIsClientReady";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A hook that returns a truthy value indicating if the code can be run on client side.
3
+ * This is a useful hook for determining if the `document` or `window` objects are available.
4
+ */
5
+ export declare const useIsClientReady: () => boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaizen/components",
3
- "version": "1.64.12",
3
+ "version": "1.64.14",
4
4
  "description": "Kaizen component library",
5
5
  "author": "Geoffrey Chong <geoff.chong@cultureamp.com>",
6
6
  "homepage": "https://cultureamp.design",
@@ -74,13 +74,13 @@
74
74
  "react-aria-components": "^1.3.1",
75
75
  "react-day-picker": "8.10.1",
76
76
  "react-focus-lock": "^2.13.2",
77
- "react-focus-on": "^3.9.3",
77
+ "react-focus-on": "^3.9.4",
78
78
  "react-media": "^1.10.0",
79
79
  "react-popper": "^2.3.0",
80
80
  "react-select": "^5.8.1",
81
81
  "react-textfit": "^1.1.1",
82
82
  "resize-observer-polyfill": "^1.5.1",
83
- "tsx": "^4.17.0",
83
+ "tsx": "^4.19.1",
84
84
  "use-debounce": "^10.0.3",
85
85
  "uuid": "^10.0.0"
86
86
  },
@@ -88,9 +88,9 @@
88
88
  "react-day-picker": "Version locked until a11y gets fixed (https://github.com/gpbl/react-day-picker/pull/1708)"
89
89
  },
90
90
  "devDependencies": {
91
- "@cultureamp/frontend-apis": "^9.9.0",
91
+ "@cultureamp/frontend-apis": "^10.0.0",
92
92
  "@cultureamp/i18n-react-intl": "^2.6.3",
93
- "@tanstack/react-query": "^5.56.2",
93
+ "@tanstack/react-query": "^5.59.0",
94
94
  "@testing-library/dom": "^10.4.0",
95
95
  "@types/jest-axe": "^3.5.9",
96
96
  "@types/lodash.debounce": "^4.0.9",
@@ -106,21 +106,21 @@
106
106
  "postcss": "^8.4.47",
107
107
  "postcss-cli": "^11.0.0",
108
108
  "postcss-import": "^16.1.0",
109
- "postcss-preset-env": "^10.0.2",
109
+ "postcss-preset-env": "^10.0.6",
110
110
  "postcss-scss": "^4.0.9",
111
111
  "query-string": "^9.1.0",
112
112
  "react": "^18.3.1",
113
113
  "react-dom": "^18.3.1",
114
114
  "react-highlight": "^0.15.0",
115
115
  "react-intl": "^6.7.0",
116
- "rollup": "^4.22.5",
116
+ "rollup": "^4.24.0",
117
117
  "sass": "^1.77.8",
118
118
  "serialize-query-params": "^2.0.2",
119
119
  "svgo": "^3.3.2",
120
120
  "tslib": "^2.7.0",
121
- "tsx": "^4.17.0",
122
- "@kaizen/package-bundler": "1.1.6",
123
- "@kaizen/design-tokens": "10.6.2"
121
+ "tsx": "^4.19.1",
122
+ "@kaizen/design-tokens": "10.6.3",
123
+ "@kaizen/package-bundler": "1.1.7"
124
124
  },
125
125
  "peerDependencies": {
126
126
  "@cultureamp/i18n-react-intl": "^2.5.9",
@@ -48,7 +48,7 @@ describe("<FilterSelect>", () => {
48
48
  it("shows the options initially when isOpen is true", async () => {
49
49
  render(<FilterSelectWrapper isOpen />)
50
50
  await waitFor(() => {
51
- expect(screen.queryByRole("listbox")).toBeVisible()
51
+ expect(screen.getByRole("listbox")).toBeVisible()
52
52
  })
53
53
  })
54
54
 
@@ -107,10 +107,82 @@ describe("<FilterSelect>", () => {
107
107
  render(<FilterSelectWrapper isOpen />)
108
108
  expect(screen.queryByRole("listbox")).toBeVisible()
109
109
  await waitFor(() => {
110
- expect(screen.queryByRole("listbox")).toHaveFocus()
110
+ expect(screen.getAllByRole("option")[0]).toHaveFocus()
111
111
  })
112
112
  })
113
113
 
114
+ it("moves focus to the first item on ArrowDown if nothing has been selected", async () => {
115
+ render(<FilterSelectWrapper selectedKey={undefined} />)
116
+ const trigger = screen.getByRole("button", { name: "Coffee" })
117
+ await user.tab()
118
+ await waitFor(() => {
119
+ expect(trigger).toHaveFocus()
120
+ })
121
+ await user.keyboard("{ArrowDown}")
122
+
123
+ await waitFor(() => {
124
+ expect(screen.getAllByRole("option")[0]).toHaveFocus()
125
+ })
126
+ })
127
+ it("moves focus to the last item on ArrowUp if nothing has been selected", async () => {
128
+ render(<FilterSelectWrapper selectedKey={undefined} />)
129
+ const trigger = screen.getByRole("button", { name: "Coffee" })
130
+ await user.tab()
131
+ await waitFor(() => {
132
+ expect(trigger).toHaveFocus()
133
+ })
134
+ await user.keyboard("{ArrowUp}")
135
+
136
+ await waitFor(() => {
137
+ const options = screen.getAllByRole("option")
138
+ expect(options[options.length - 1]).toHaveFocus()
139
+ })
140
+ })
141
+ it("moves focus to the current selected item on Enter", async () => {
142
+ render(<FilterSelectWrapper selectedKey="hazelnut" />)
143
+ const trigger = screen.getByRole("button", {
144
+ name: "Coffee : Hazelnut",
145
+ })
146
+ await user.tab()
147
+ await waitFor(() => {
148
+ expect(trigger).toHaveFocus()
149
+ })
150
+ await user.keyboard("{Enter}")
151
+
152
+ await waitFor(() => {
153
+ expect(screen.getByRole("option", { name: "Hazelnut" })).toHaveFocus()
154
+ })
155
+ })
156
+ it("moves focus to the current selected item on ArrowUp", async () => {
157
+ render(<FilterSelectWrapper selectedKey="hazelnut" />)
158
+ const trigger = screen.getByRole("button", {
159
+ name: "Coffee : Hazelnut",
160
+ })
161
+ await user.tab()
162
+ await waitFor(() => {
163
+ expect(trigger).toHaveFocus()
164
+ })
165
+ await user.keyboard("{ArrowUp}")
166
+
167
+ await waitFor(() => {
168
+ expect(screen.getByRole("option", { name: "Hazelnut" })).toHaveFocus()
169
+ })
170
+ })
171
+ it("moves focus to the current selected item on ArrowDown", async () => {
172
+ render(<FilterSelectWrapper selectedKey="hazelnut" />)
173
+ const trigger = screen.getByRole("button", {
174
+ name: "Coffee : Hazelnut",
175
+ })
176
+ await user.tab()
177
+ await waitFor(() => {
178
+ expect(trigger).toHaveFocus()
179
+ })
180
+ await user.keyboard("{ArrowDown}")
181
+
182
+ await waitFor(() => {
183
+ expect(screen.getByRole("option", { name: "Hazelnut" })).toHaveFocus()
184
+ })
185
+ })
114
186
  it("closes when user hits the escape key", async () => {
115
187
  render(<FilterSelectWrapper isOpen />)
116
188
  expect(screen.queryByRole("listbox")).toBeVisible()
@@ -168,6 +240,29 @@ describe("<FilterSelect>", () => {
168
240
  })
169
241
  })
170
242
 
243
+ describe("Stringified object values", () => {
244
+ it("finds selected option when value is a stringified object", () => {
245
+ const { getByRole } = render(
246
+ <FilterSelectWrapper
247
+ items={[
248
+ {
249
+ value: '{"sortBy":"creator_name","sortOrder":"asc"}',
250
+ label: "Created by A-Z",
251
+ },
252
+ {
253
+ value: '{"sortBy":"creator_name","sortOrder":"dsc"}',
254
+ label: "Created by Z-A",
255
+ },
256
+ ]}
257
+ selectedKey='{"sortBy":"creator_name","sortOrder":"asc"}'
258
+ />
259
+ )
260
+ expect(
261
+ getByRole("button", { name: "Coffee : Created by A-Z" })
262
+ ).toBeInTheDocument()
263
+ })
264
+ })
265
+
171
266
  const defaultProps: FilterSelectProps = {
172
267
  label: "Coffee",
173
268
  isOpen: false,
@@ -78,6 +78,9 @@ export const FilterSelect = <Option extends SelectOption = SelectOption>({
78
78
  )
79
79
 
80
80
  const { buttonProps } = useButton(triggerProps, triggerRef)
81
+
82
+ // `aria-labelledby` and `aria-controls` are being remapped because the `buttonProps` ids generated by React Aria point to nothing.
83
+ // This should ideally be refactored but for now the `aria-controls` is set to the Filter's Listbox (menuProps.id) and the `aria-labelledby` to undefined so the accessible name is derived from the buttons content.
81
84
  const renderTriggerButtonProps = {
82
85
  ...buttonProps,
83
86
  "aria-labelledby": undefined,
@@ -194,11 +194,13 @@ describe("<Select />", () => {
194
194
  })
195
195
 
196
196
  describe("Given the menu is opened", () => {
197
- it("focuses the listbox initially", async () => {
198
- const { getByRole } = render(<SelectWrapper defaultOpen />)
197
+ it("focuses on the first item", async () => {
198
+ const { getByRole, getAllByRole } = render(
199
+ <SelectWrapper defaultOpen />
200
+ )
199
201
  expect(getByRole("listbox")).toBeVisible()
200
202
  await waitFor(() => {
201
- expect(getByRole("listbox")).toHaveFocus()
203
+ expect(getAllByRole("option")[0]).toHaveFocus()
202
204
  })
203
205
  })
204
206
  it("is closed when hits the escape key", async () => {
@@ -98,8 +98,6 @@ Set `isFullWidth` to `true` to have the Select span the full width of its contai
98
98
 
99
99
  By default, the Select's popover will attach itself to the `body` of the document using React's `createPortal`.
100
100
 
101
- You can change the default behaviour by providing a `portalContainerId` to attach this to different element in the DOM. This can help to resolve issues that may arise with `z-index` or having a Select in a modal.
101
+ You can change the default behavior by providing a `portalContainerId` to attach this to different element in the DOM. This can help to resolve issues that may arise with `z-index` or having a Select in a modal.
102
102
 
103
103
  <Canvas of={SelectStories.PortalContainer} />
104
-
105
- There is currently a known issue whereby a selected option will cause the page to scroll to the top of the window on open (click on [default to see example](https://cultureamp.design/?path=/docs/components-select-future--docs#portals)). This can be solved by setting a `portalContainerId` to the closest parent of the Select.
@@ -1,5 +1,6 @@
1
1
  import React from "react"
2
2
  import { Meta, StoryObj } from "@storybook/react"
3
+ import { ContextModal } from "~components/Modal"
3
4
  import { RadioField, RadioGroup } from "~components/Radio"
4
5
  import { Select } from "../Select"
5
6
  import { SelectOption } from "../types"
@@ -170,25 +171,40 @@ export const FullWidth: Story = {
170
171
  export const PortalContainer: Story = {
171
172
  render: args => {
172
173
  const portalContainerId = "id--portal-container"
174
+
175
+ const [isOpen, setIsOpen] = React.useState(false)
176
+
177
+ const handleOpen = (): void => setIsOpen(true)
178
+ const handleClose = (): void => setIsOpen(false)
173
179
  return (
174
180
  <>
175
- <div
176
- id={portalContainerId}
177
- className="flex gap-24 bg-gray-200 p-12 overflow-hidden h-[200px] relative"
178
- >
179
- <Select
180
- {...args}
181
- label="Default"
182
- selectedKey="batch-brew"
183
- id="id--select-default"
184
- />
185
- <Select
186
- {...args}
187
- label="Inner portal"
188
- selectedKey="batch-brew"
189
- id="id--select-inner"
190
- portalContainerId={portalContainerId}
191
- />
181
+ <div className=" h-[500px] mb-24 block bg-gray-100 flex flex-col gap-16 justify-center items-center">
182
+ Page content
183
+ <button
184
+ type="button"
185
+ className="border border-gray-500"
186
+ onClick={handleOpen}
187
+ >
188
+ Open Modal
189
+ </button>
190
+ <ContextModal
191
+ isOpen={isOpen}
192
+ onConfirm={handleClose}
193
+ onDismiss={handleClose}
194
+ title="Select test"
195
+ >
196
+ <div
197
+ className="flex gap-24 bg-gray-200 p-12"
198
+ id={portalContainerId}
199
+ >
200
+ <Select
201
+ {...args}
202
+ label="Select within a modal"
203
+ id="id--select-inner"
204
+ portalContainerId={portalContainerId}
205
+ />
206
+ </div>
207
+ </ContextModal>
192
208
  </div>
193
209
  </>
194
210
  )
@@ -1,6 +1,8 @@
1
- import React, { HTMLAttributes } from "react"
1
+ import React, { HTMLAttributes, Key, useEffect, useRef, ReactNode } from "react"
2
2
  import { AriaListBoxOptions, useListBox } from "@react-aria/listbox"
3
+ import { SelectState } from "@react-stately/select"
3
4
  import classnames from "classnames"
5
+ import { useIsClientReady } from "~components/__utilities__/useIsClientReady"
4
6
  import { OverrideClassName } from "~components/types/OverrideClassName"
5
7
  import { useSelectContext } from "../../context"
6
8
  import { SelectOption, SelectItem } from "../../types"
@@ -9,25 +11,75 @@ import styles from "./ListBox.module.scss"
9
11
  export type SingleListBoxProps<Option extends SelectOption> = OverrideClassName<
10
12
  HTMLAttributes<HTMLUListElement>
11
13
  > & {
12
- children: React.ReactNode
14
+ children: ReactNode
13
15
  /** Props for the popup. */
14
16
  menuProps: AriaListBoxOptions<SelectItem<Option>>
15
17
  }
16
18
 
19
+ /** A util to retrieve the key of the correct focusable items based of the focus strategy
20
+ * This is used to determine which element from the collection to focus to on open base on the keyboard event
21
+ * ie: UpArrow will set the focusStrategy to "last"
22
+ */
23
+ const getOptionKeyFromCollection = (
24
+ state: SelectState<SelectItem<any>>
25
+ ): Key | null => {
26
+ if (state.selectedItem) {
27
+ return state.selectedItem.key
28
+ } else if (state.focusStrategy === "last") {
29
+ return state.collection.getLastKey()
30
+ }
31
+ return state.collection.getFirstKey()
32
+ }
33
+
34
+ /** This makes the use of query selector less brittle in instances where a failed selector is passed in
35
+ */
36
+ const safeQuerySelector = (selector: string): HTMLElement | null => {
37
+ try {
38
+ return document.querySelector(selector)
39
+ } catch (error) {
40
+ // eslint-disable-next-line no-console
41
+ console.error("Kaizen querySelector failed:", error)
42
+ return null
43
+ }
44
+ }
45
+
17
46
  export const ListBox = <Option extends SelectOption>({
18
47
  children,
19
48
  menuProps,
20
49
  classNameOverride,
21
50
  ...restProps
22
51
  }: SingleListBoxProps<Option>): JSX.Element => {
52
+ const isClientReady = useIsClientReady()
23
53
  const { state } = useSelectContext<Option>()
24
- const ref = React.useRef<HTMLUListElement>(null)
54
+ const ref = useRef<HTMLUListElement>(null)
25
55
  const { listBoxProps } = useListBox(
26
- { ...menuProps, disallowEmptySelection: true },
56
+ {
57
+ ...menuProps,
58
+ disallowEmptySelection: true,
59
+ // This is to ensure that the listbox doesn't use React Aria's auto focus feature for Listbox, which creates a visual bug
60
+ autoFocus: false,
61
+ },
27
62
  state,
28
63
  ref
29
64
  )
30
65
 
66
+ /**
67
+ * This uses the new useIsClientReady to ensure document exists before trying to querySelector and give the time to focus to the correct element
68
+ */
69
+ useEffect(() => {
70
+ if (isClientReady) {
71
+ const optionKey = getOptionKeyFromCollection(state)
72
+ const focusToElement = safeQuerySelector(`[data-key='${optionKey}']`)
73
+
74
+ if (focusToElement) {
75
+ focusToElement.focus()
76
+ } else {
77
+ // If an element is not found, focus on the listbox. This ensures the list can still be navigated to via keyboard if the keys do not align to the data attributes of the list items.
78
+ ref.current?.focus()
79
+ }
80
+ }
81
+ }, [isClientReady])
82
+
31
83
  return (
32
84
  <ul
33
85
  ref={ref}
@@ -36,7 +36,7 @@ export const Overlay = <Option extends SelectOption>({
36
36
  {...restProps}
37
37
  >
38
38
  {/* eslint-disable-next-line jsx-a11y/no-autofocus */}
39
- <FocusScope autoFocus restoreFocus>
39
+ <FocusScope autoFocus={false} restoreFocus>
40
40
  <DismissButton onDismiss={state.close} />
41
41
  {children}
42
42
  <DismissButton onDismiss={state.close} />
@@ -0,0 +1 @@
1
+ export * from "./useIsClientReady"
@@ -0,0 +1,17 @@
1
+ import { useState, useEffect } from "react"
2
+
3
+ /**
4
+ * A hook that returns a truthy value indicating if the code can be run on client side.
5
+ * This is a useful hook for determining if the `document` or `window` objects are available.
6
+ */
7
+ export const useIsClientReady = (): boolean => {
8
+ const [isClientReady, setIsClientReady] = useState(false)
9
+
10
+ useEffect(() => {
11
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
12
+ setIsClientReady(true)
13
+ }
14
+ }, [])
15
+
16
+ return isClientReady
17
+ }