@telus-uds/components-web 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.eslintignore +2 -0
  2. package/.vscode/settings.json +7 -0
  3. package/CHANGELOG.md +14 -2
  4. package/lib/BlockQuote/BlockQuote.js +173 -0
  5. package/lib/BlockQuote/index.js +13 -0
  6. package/lib/IconButton/IconButton.js +70 -0
  7. package/lib/IconButton/index.js +13 -0
  8. package/lib/Listbox/GroupControl.js +94 -0
  9. package/lib/Listbox/Listbox.js +164 -0
  10. package/lib/Listbox/ListboxGroup.js +129 -0
  11. package/lib/Listbox/ListboxItem.js +137 -0
  12. package/lib/Listbox/ListboxOverlay.js +89 -0
  13. package/lib/Listbox/PressableItem.js +149 -0
  14. package/lib/Listbox/index.js +13 -0
  15. package/lib/NavigationBar/resolveItemSelection.js +24 -0
  16. package/lib/baseExports.js +0 -6
  17. package/lib/index.js +28 -1
  18. package/lib/utils/useOverlaidPosition.js +246 -0
  19. package/lib-module/BlockQuote/BlockQuote.js +156 -0
  20. package/lib-module/BlockQuote/index.js +2 -0
  21. package/lib-module/IconButton/IconButton.js +52 -0
  22. package/lib-module/IconButton/index.js +2 -0
  23. package/lib-module/Listbox/GroupControl.js +80 -0
  24. package/lib-module/Listbox/Listbox.js +142 -0
  25. package/lib-module/Listbox/ListboxGroup.js +106 -0
  26. package/lib-module/Listbox/ListboxItem.js +112 -0
  27. package/lib-module/Listbox/ListboxOverlay.js +68 -0
  28. package/lib-module/Listbox/PressableItem.js +128 -0
  29. package/lib-module/Listbox/index.js +2 -0
  30. package/lib-module/NavigationBar/resolveItemSelection.js +16 -0
  31. package/lib-module/baseExports.js +1 -1
  32. package/lib-module/index.js +3 -0
  33. package/lib-module/utils/useOverlaidPosition.js +235 -0
  34. package/package.json +3 -3
  35. package/src/BlockQuote/BlockQuote.jsx +130 -0
  36. package/src/BlockQuote/index.js +3 -0
  37. package/src/IconButton/IconButton.jsx +46 -0
  38. package/src/IconButton/index.js +3 -0
  39. package/src/Listbox/GroupControl.jsx +65 -0
  40. package/src/Listbox/Listbox.jsx +148 -0
  41. package/src/Listbox/ListboxGroup.jsx +110 -0
  42. package/src/Listbox/ListboxItem.jsx +101 -0
  43. package/src/Listbox/ListboxOverlay.jsx +71 -0
  44. package/src/Listbox/PressableItem.jsx +121 -0
  45. package/src/Listbox/index.js +3 -0
  46. package/src/NavigationBar/resolveItemSelection.js +11 -0
  47. package/src/baseExports.js +0 -1
  48. package/src/index.js +3 -0
  49. package/src/utils/useOverlaidPosition.js +226 -0
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+
8
+ var _react = require("react");
9
+
10
+ var _Dimensions = _interopRequireDefault(require("react-native-web/dist/cjs/exports/Dimensions"));
11
+
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+
14
+ // TODO: add react-native as a peer dep and support native apps too.
15
+ // That requires some fiddling with Allium repo storybook config, babel, etc,
16
+ // unless ADS gets merged back into UDS monorepo.
17
+ const adjustHorizontalToFit = (initialOffset, windowWidth, sourceWidth) => {
18
+ const offset = Math.max(0, initialOffset);
19
+ const otherEdgeOverflow = Math.max(0, offset + sourceWidth - windowWidth);
20
+ const tooWideBy = Math.max(0, otherEdgeOverflow - offset);
21
+ const adjusted = {
22
+ offset: Math.max(0, offset - otherEdgeOverflow)
23
+ };
24
+ if (tooWideBy) adjusted.width = Math.max(0, sourceWidth - tooWideBy);
25
+ return adjusted;
26
+ };
27
+
28
+ const getPosition = _ref => {
29
+ let {
30
+ edge,
31
+ fromEdge,
32
+ sourceSize
33
+ } = _ref;
34
+
35
+ switch (edge) {
36
+ case 'near':
37
+ return fromEdge;
38
+
39
+ case 'mid':
40
+ return fromEdge + sourceSize / 2;
41
+
42
+ case 'far':
43
+ return fromEdge + sourceSize;
44
+
45
+ default:
46
+ return 0;
47
+ }
48
+ };
49
+
50
+ const getEdgeType = (align, alignSide) => {
51
+ const alignTo = align[alignSide];
52
+ const edge = ['center', 'middle'].includes(alignTo) && 'mid' || (alignSide === alignTo ? 'near' : 'far');
53
+ return edge;
54
+ };
55
+ /**
56
+ * Based on UDS's private getTooltipPosition but generalised.
57
+ *
58
+ * Used for absolute positioning of the tooltip. Since the tooltip is always centered relatively
59
+ * to the source (button) and we have a limited set of positions, an easy and consistent way
60
+ * of positioning it is to check all of the possible positions and pick one that will be rendered
61
+ * within the window bounds. This way we can also rely on the tooltip being actually rendered
62
+ * before it is shown, which makes it account for the width being limiting in styles, custom font
63
+ * rendering, etc.
64
+ */
65
+
66
+
67
+ function getOverlaidPosition(_ref2) {
68
+ let {
69
+ sourceLayout,
70
+ targetDimensions,
71
+ windowDimensions,
72
+ offsets = {},
73
+ align
74
+ } = _ref2;
75
+ // Web-only: this will be difficult to mimic on native because there's no global scroll position.
76
+ // TODO: wire something in e.g. a scroll ref accessible from a provider included in Allium provider
77
+ // that can be passed to the appropriate ScrollView?
78
+ const {
79
+ scrollX = 0,
80
+ scrollY = 0
81
+ } = typeof window === 'object' ? window : {}; // Will have top, bottom, left and/or right offsets depending on `align`
82
+
83
+ const positioning = {};
84
+ if (align.top) positioning.top = getPosition({
85
+ edge: getEdgeType(align, 'top'),
86
+ fromEdge: sourceLayout.y + scrollY + (offsets.vertical ?? 0),
87
+ sourceSize: sourceLayout.height
88
+ });
89
+ if (align.middle) positioning.top = getPosition({
90
+ edge: getEdgeType(align, 'middle'),
91
+ fromEdge: sourceLayout.y + scrollY + (offsets.vertical ?? 0) - targetDimensions.height / 2,
92
+ sourceSize: sourceLayout.height
93
+ });
94
+ if (align.bottom) positioning.bottom = getPosition({
95
+ edge: getEdgeType(align, 'bottom'),
96
+ fromEdge: windowDimensions.height - (sourceLayout.y + scrollY + sourceLayout.height - (offsets.vertical ?? 0)),
97
+ sourceSize: sourceLayout.height
98
+ });
99
+ if (align.left) positioning.left = getPosition({
100
+ edge: getEdgeType(align, 'left'),
101
+ fromEdge: sourceLayout.x + scrollX + (offsets.horizontal ?? 0),
102
+ sourceSize: sourceLayout.width
103
+ });
104
+ if (align.center) positioning.left = getPosition({
105
+ edge: getEdgeType(align, 'center'),
106
+ fromEdge: sourceLayout.x + scrollX + (offsets.horizontal ?? 0) - targetDimensions.width / 2,
107
+ sourceSize: sourceLayout.width
108
+ });
109
+ if (align.right) positioning.right = getPosition({
110
+ edge: getEdgeType(align, 'right'),
111
+ fromEdge: windowDimensions.width - (sourceLayout.x + scrollX + sourceLayout.width - (offsets.horizontal ?? 0)),
112
+ sourceSize: sourceLayout.width
113
+ });
114
+
115
+ if (!(align.left && align.right)) {
116
+ // Check if the position and/or width need adjusting to fit on the screen
117
+ const side = align.right ? 'right' : 'left';
118
+ const adjusted = adjustHorizontalToFit(positioning[side], windowDimensions.width, sourceLayout.width);
119
+ if (typeof adjusted.width === 'number') positioning.width = adjusted.width;
120
+
121
+ if (typeof adjusted.offset === 'number') {
122
+ positioning[side] = adjusted.offset;
123
+ }
124
+ }
125
+
126
+ return positioning;
127
+ }
128
+ /**
129
+ * Positions an element in a modal or portal so that it appears tooltip-like below the
130
+ * target element.
131
+ *
132
+ * @TODO - add support for positioning other than 'below' like UDS's tooltip (this is not
133
+ * a small task because UDS's tooltip logic only really works for short text - it might be
134
+ * better to use a third-party library).
135
+ */
136
+
137
+
138
+ const useOverlaidPosition = _ref3 => {
139
+ let {
140
+ isShown = false,
141
+ offsets,
142
+ // By default, align the overlaid target's `top` to the bottom of the source, and center horizontally.
143
+ align = {
144
+ center: 'center',
145
+ top: 'bottom'
146
+ }
147
+ } = _ref3;
148
+ // Element in main document flow that the targetRef element is positioned around
149
+ const sourceRef = (0, _react.useRef)(null);
150
+ const [sourceLayout, setSourceLayout] = (0, _react.useState)(null); // Element in a modal or portal overlay positioned to appear adjacent to sourceRef
151
+
152
+ const targetRef = (0, _react.useRef)(null);
153
+ const [targetDimensions, setTargetDimensions] = (0, _react.useState)(null);
154
+ const [windowDimensions, setWindowDimensions] = (0, _react.useState)(null);
155
+ const onTargetLayout = (0, _react.useCallback)(_ref4 => {
156
+ let {
157
+ nativeEvent: {
158
+ layout: {
159
+ width,
160
+ height
161
+ }
162
+ }
163
+ } = _ref4;
164
+ // NOTE: UDS's Tooltip logic injects some additional width to allow for antialiasing etc of text,
165
+ // avoiding adding unnecessary line breaks to text that is slightly wider than it thinks it is.
166
+ // That is probably something specific to text tooltips that doesn't belong in a generic hook.
167
+ setTargetDimensions(previousDimensions => {
168
+ // Re-render on first non-zero width / height: avoid infinite loops on changes, or mispositioning
169
+ // if user scrolls while a slidedown animation is changing the height and recalculating position.
170
+ if (!previousDimensions && width && height) {
171
+ return {
172
+ width,
173
+ height
174
+ };
175
+ }
176
+
177
+ return previousDimensions;
178
+ });
179
+ }, []);
180
+ const readyToShow = Boolean(isShown && sourceRef.current);
181
+ (0, _react.useEffect)(() => {
182
+ const handleDimensionsChange = _ref5 => {
183
+ var _sourceRef$current;
184
+
185
+ let {
186
+ window
187
+ } = _ref5;
188
+ (_sourceRef$current = sourceRef.current) === null || _sourceRef$current === void 0 ? void 0 : _sourceRef$current.measureInWindow((x, y, width, height) => {
189
+ // Could add a debouncer here if there's too many rerenders during gradual resizes
190
+ setWindowDimensions(window);
191
+ setSourceLayout({
192
+ x,
193
+ y,
194
+ width,
195
+ height
196
+ });
197
+ });
198
+ };
199
+
200
+ let subscription;
201
+
202
+ const unsubscribe = () => {
203
+ var _subscription;
204
+
205
+ if (typeof ((_subscription = subscription) === null || _subscription === void 0 ? void 0 : _subscription.remove) === 'function') {
206
+ // React Native >=0.65.0
207
+ subscription.remove();
208
+ } else if (typeof _Dimensions.default.removeEventListener === 'function') {
209
+ // React Native <0.65.0
210
+ _Dimensions.default.removeEventListener('change', handleDimensionsChange);
211
+ }
212
+
213
+ setSourceLayout(null);
214
+ setTargetDimensions(null);
215
+ };
216
+
217
+ if (readyToShow) {
218
+ subscription = _Dimensions.default.addEventListener('change', handleDimensionsChange);
219
+ handleDimensionsChange({
220
+ window: _Dimensions.default.get('window')
221
+ });
222
+ } else {
223
+ unsubscribe();
224
+ }
225
+
226
+ return unsubscribe;
227
+ }, [readyToShow]);
228
+ const isReady = Boolean(isShown && sourceLayout && windowDimensions && targetDimensions);
229
+ const overlaidPosition = isReady ? getOverlaidPosition({
230
+ sourceLayout,
231
+ targetDimensions,
232
+ windowDimensions,
233
+ offsets,
234
+ align
235
+ }) : {};
236
+ return {
237
+ overlaidPosition,
238
+ sourceRef,
239
+ targetRef,
240
+ onTargetLayout,
241
+ isReady
242
+ };
243
+ };
244
+
245
+ var _default = useOverlaidPosition;
246
+ exports.default = _default;
@@ -0,0 +1,156 @@
1
+ import React from 'react';
2
+ import PropTypes from 'prop-types';
3
+ import { Link, selectSystemProps, StackView, Typography, useThemeTokens, withLinkRouter } from '@telus-uds/components-base';
4
+ import styled from 'styled-components';
5
+ import { htmlAttrs, transformGradient } from '../utils';
6
+ import { jsx as _jsx } from "react/jsx-runtime";
7
+ import { jsxs as _jsxs } from "react/jsx-runtime";
8
+ const [selectProps, selectedSystemPropTypes] = selectSystemProps([htmlAttrs]);
9
+ const BlockQuoteContainer = /*#__PURE__*/styled.blockquote.withConfig({
10
+ displayName: "BlockQuote__BlockQuoteContainer",
11
+ componentId: "components-web__sc-vals3u-0"
12
+ })(["margin:0;position:relative;padding-left:", ";padding-right:", ";padding-bottom:", ";padding-top:", ";&::before{content:'';left:0;top:0;position:absolute;height:100%;width:", ";background:", ";}"], _ref => {
13
+ let {
14
+ paddingLeft
15
+ } = _ref;
16
+ return `${paddingLeft}px`;
17
+ }, _ref2 => {
18
+ let {
19
+ paddingRight
20
+ } = _ref2;
21
+ return `${paddingRight}px`;
22
+ }, _ref3 => {
23
+ let {
24
+ paddingBottom
25
+ } = _ref3;
26
+ return `${paddingBottom}px`;
27
+ }, _ref4 => {
28
+ let {
29
+ paddingTop
30
+ } = _ref4;
31
+ return `${paddingTop}px`;
32
+ }, _ref5 => {
33
+ let {
34
+ width
35
+ } = _ref5;
36
+ return `${width}px`;
37
+ }, _ref6 => {
38
+ let {
39
+ backgroundGradient
40
+ } = _ref6;
41
+ return backgroundGradient && transformGradient(backgroundGradient);
42
+ });
43
+ const QuoteContainer = /*#__PURE__*/styled.div.withConfig({
44
+ displayName: "BlockQuote__QuoteContainer",
45
+ componentId: "components-web__sc-vals3u-1"
46
+ })(["margin-bottom:", ";"], _ref7 => {
47
+ let {
48
+ marginBottom
49
+ } = _ref7;
50
+ return `${marginBottom}px`;
51
+ });
52
+
53
+ const BlockQuote = _ref8 => {
54
+ let {
55
+ children,
56
+ link,
57
+ additionalInfo,
58
+ linkHref,
59
+ textStyle = 'large',
60
+ LinkRouter,
61
+ linkRouterProps,
62
+ tokens,
63
+ variant,
64
+ ...rest
65
+ } = _ref8;
66
+ const {
67
+ color,
68
+ paddingTop,
69
+ paddingBottom,
70
+ paddingLeft,
71
+ paddingRight,
72
+ marginBottom,
73
+ width,
74
+ backgroundGradient
75
+ } = useThemeTokens('BlockQuote', tokens, variant);
76
+ const mappedTextSize = textStyle === 'heading' ? 'h3' : textStyle;
77
+
78
+ const renderLink = () => {
79
+ if (linkHref) {
80
+ return /*#__PURE__*/_jsx(Link, {
81
+ href: linkHref,
82
+ tokens: {
83
+ blockFontWeight: '500',
84
+ color
85
+ },
86
+ variant: {
87
+ alternative: true
88
+ },
89
+ LinkRouter: LinkRouter,
90
+ linkRouterProps: linkRouterProps,
91
+ children: link
92
+ });
93
+ }
94
+
95
+ return /*#__PURE__*/_jsx(Typography, {
96
+ tokens: {
97
+ color,
98
+ fontWeight: '500'
99
+ },
100
+ children: link
101
+ });
102
+ };
103
+
104
+ const renderQuote = () => {
105
+ const quote = /*#__PURE__*/_jsx(Typography, {
106
+ tokens: {
107
+ color,
108
+ fontWeight: '400'
109
+ },
110
+ variant: {
111
+ size: mappedTextSize
112
+ },
113
+ children: children
114
+ });
115
+
116
+ if (additionalInfo || link) {
117
+ return /*#__PURE__*/_jsx(QuoteContainer, {
118
+ marginBottom: marginBottom,
119
+ children: quote
120
+ });
121
+ }
122
+
123
+ return quote;
124
+ };
125
+
126
+ return /*#__PURE__*/_jsxs(BlockQuoteContainer, { ...selectProps(rest),
127
+ paddingTop: paddingTop,
128
+ paddingBottom: paddingBottom,
129
+ paddingLeft: paddingLeft,
130
+ paddingRight: paddingRight,
131
+ width: width,
132
+ backgroundGradient: backgroundGradient,
133
+ children: [renderQuote(), (additionalInfo || link) && /*#__PURE__*/_jsxs(StackView, {
134
+ space: 0,
135
+ children: [link && renderLink(), additionalInfo && /*#__PURE__*/_jsx(Typography, {
136
+ tokens: {
137
+ color
138
+ },
139
+ variant: {
140
+ size: 'small'
141
+ },
142
+ children: additionalInfo
143
+ })]
144
+ })]
145
+ });
146
+ };
147
+
148
+ BlockQuote.propTypes = { ...selectedSystemPropTypes,
149
+ ...withLinkRouter.propTypes,
150
+ children: PropTypes.node.isRequired,
151
+ link: PropTypes.string,
152
+ linkHref: PropTypes.string,
153
+ additionalInfo: PropTypes.string,
154
+ textStyle: PropTypes.oneOf(['large', 'heading'])
155
+ };
156
+ export default BlockQuote;
@@ -0,0 +1,2 @@
1
+ import BlockQuote from './BlockQuote';
2
+ export default BlockQuote;
@@ -0,0 +1,52 @@
1
+ import React, { forwardRef } from 'react';
2
+ import PropTypes from 'prop-types';
3
+ import { IconButton as IconButtonBase, useThemeTokens } from '@telus-uds/components-base';
4
+ import { jsx as _jsx } from "react/jsx-runtime";
5
+ const IconButton = /*#__PURE__*/forwardRef((_ref, ref) => {
6
+ let {
7
+ icon,
8
+ action,
9
+ tokens,
10
+ variant = {},
11
+ ...iconButtonProps
12
+ } = _ref;
13
+ const variantWithAction = action && !variant.action ? { ...variant,
14
+ action
15
+ } : variant;
16
+ const {
17
+ icon: themeIcon
18
+ } = useThemeTokens('IconButton', tokens, variantWithAction);
19
+ return (
20
+ /*#__PURE__*/
21
+ // If we want the arrow icons to have directional animation instead of scale, we can pass
22
+ // either appropriate iconTransateX/Y here, or define and pass variants like { direction: 'left' }
23
+ // which have theme rules that set `iconTranslateX` tokens in the theme rules and unset `iconScale`.
24
+ _jsx(IconButtonBase, {
25
+ ref: ref,
26
+ ...iconButtonProps,
27
+ tokens: tokens,
28
+ variant: variant,
29
+ icon: icon ?? themeIcon
30
+ })
31
+ );
32
+ });
33
+ const multiBrandIconNames = ['add', 'subtract', 'close', 'play', 'moveUp', 'moveDown', 'moveLeft', 'moveRight', 'expand'];
34
+ IconButton.displayName = 'IconButton';
35
+
36
+ const propsWithoutIcon = _ref2 => {
37
+ let {
38
+ icon,
39
+ ...props
40
+ } = _ref2;
41
+ return props;
42
+ };
43
+
44
+ IconButton.propTypes = { ...propsWithoutIcon(IconButtonBase.propTypes),
45
+ // eslint-disable-next-line react/require-default-props
46
+ action: PropTypes.oneOf(multiBrandIconNames),
47
+ icon: PropTypes.func
48
+ };
49
+ IconButton.defaultProps = {
50
+ icon: null
51
+ };
52
+ export default IconButton;
@@ -0,0 +1,2 @@
1
+ import IconButton from './IconButton';
2
+ export default IconButton;
@@ -0,0 +1,80 @@
1
+ import React from 'react';
2
+ import styled from 'styled-components';
3
+ import PropTypes from 'prop-types';
4
+ import { Icon, Spacer, useThemeTokens } from '@telus-uds/components-base';
5
+ import { jsx as _jsx } from "react/jsx-runtime";
6
+ import { jsxs as _jsxs } from "react/jsx-runtime";
7
+ const StyledControlWrapper = /*#__PURE__*/styled.div.withConfig({
8
+ displayName: "GroupControl__StyledControlWrapper",
9
+ componentId: "components-web__sc-1r7ts3q-0"
10
+ })(_ref => {
11
+ let {
12
+ focus,
13
+ tokens
14
+ } = _ref;
15
+ return {
16
+ fontFamily: `${tokens.groupFontName}${tokens.groupFontWeight}normal`,
17
+ fontSize: tokens.groupFontSize,
18
+ color: tokens.groupColor,
19
+ textDecoration: tokens.itemTextDecoration,
20
+ backgroundColor: tokens.groupBackgroundColor,
21
+ outline: tokens.itemOutline,
22
+ width: '100%',
23
+ display: 'flex',
24
+ justifyContent: 'space-between',
25
+ ...(focus ? {
26
+ border: `${tokens.groupBorderWidth} solid ${tokens.groupBorderColor}`,
27
+ borderRadius: tokens.groupBorderRadius,
28
+ paddingLeft: `calc(${tokens.groupPaddingLeft}px - ${tokens.groupBorderWidth}px)`,
29
+ paddingRight: `calc(${tokens.groupPaddingRight}px - ${tokens.groupBorderWidth}px)`,
30
+ paddingTop: `calc(${tokens.groupPaddingTop}px - ${tokens.groupBorderWidth}px)`,
31
+ paddingBottom: `calc(${tokens.groupPaddingBottom}px - ${tokens.groupBorderWidth}px)`
32
+ } : {
33
+ paddingLeft: tokens.groupPaddingLeft,
34
+ paddingRight: tokens.groupPaddingRight,
35
+ paddingTop: tokens.groupPaddingTop,
36
+ paddingBottom: tokens.groupPaddingBottom
37
+ })
38
+ };
39
+ });
40
+
41
+ const GroupControl = _ref2 => {
42
+ let {
43
+ expanded,
44
+ pressed,
45
+ hover,
46
+ focus,
47
+ current,
48
+ label
49
+ } = _ref2;
50
+ const tokens = useThemeTokens('ListBox', {}, {}, {
51
+ expanded,
52
+ pressed,
53
+ hover,
54
+ current,
55
+ focus
56
+ });
57
+ return /*#__PURE__*/_jsxs(StyledControlWrapper, {
58
+ focus,
59
+ tokens,
60
+ children: [label, /*#__PURE__*/_jsx(Spacer, {
61
+ space: 1,
62
+ direction: "row"
63
+ }), /*#__PURE__*/_jsx(Icon, {
64
+ icon: tokens.groupIcon,
65
+ variant: {
66
+ size: 'micro'
67
+ }
68
+ })]
69
+ });
70
+ };
71
+
72
+ GroupControl.propTypes = {
73
+ expanded: PropTypes.bool,
74
+ pressed: PropTypes.bool,
75
+ hover: PropTypes.bool,
76
+ focus: PropTypes.bool,
77
+ current: PropTypes.bool,
78
+ label: PropTypes.string
79
+ };
80
+ export default GroupControl;
@@ -0,0 +1,142 @@
1
+ import React, { useCallback, useEffect, useRef, useState } from 'react';
2
+ import PropTypes from 'prop-types';
3
+ import styled from 'styled-components';
4
+ import { ExpandCollapse, withLinkRouter } from '@telus-uds/components-base';
5
+ import ListboxGroup from './ListboxGroup';
6
+ import ListboxItem from './ListboxItem';
7
+ import DropdownOverlay from './ListboxOverlay';
8
+ import resolveItemSelection from '../NavigationBar/resolveItemSelection';
9
+ import { createElement as _createElement } from "react";
10
+ import { jsx as _jsx } from "react/jsx-runtime";
11
+ const StyledList = /*#__PURE__*/styled.ul.withConfig({
12
+ displayName: "Listbox__StyledList",
13
+ componentId: "components-web__sc-1564thh-0"
14
+ })({
15
+ margin: 0,
16
+ padding: 0,
17
+ listStyle: 'none'
18
+ });
19
+
20
+ const getInitialOpen = (items, selectedId) => items.filter(item => item.items && item.items.some(nestedItem => (nestedItem.id ?? nestedItem.label) === selectedId)).map(item => item.id ?? item.label);
21
+
22
+ const Listbox = _ref => {
23
+ let {
24
+ items = [],
25
+ firstItemRef = null,
26
+ // focus will be moved to this one once within the menu
27
+ parentRef = null,
28
+ // to return focus to after leaving the last menu item
29
+ selectedId,
30
+ LinkRouter,
31
+ itemRouterProps,
32
+ onClose
33
+ } = _ref;
34
+ const initialOpen = getInitialOpen(items, selectedId); // We need to keep track of each item's ref in order to be able to
35
+ // focus on a specific item via keyboard navigation
36
+
37
+ const itemRefs = useRef([]);
38
+ if (firstItemRef !== null && firstItemRef !== void 0 && firstItemRef.current) itemRefs.current[0] = firstItemRef.current;
39
+ const [focusedIndex, setFocusedIndex] = useState(0);
40
+ const handleKeydown = useCallback(event => {
41
+ const nextItemRef = itemRefs.current[focusedIndex + 1];
42
+ const prevItemRef = itemRefs.current[focusedIndex - 1];
43
+
44
+ if (event.key === 'ArrowUp' || event.shiftKey && event.key === 'Tab') {
45
+ var _parentRef$current;
46
+
47
+ // Move the focus to the previous item or to the parent one if on the first
48
+ if (prevItemRef) {
49
+ event.preventDefault();
50
+ prevItemRef.focus();
51
+ } else if (parentRef) (_parentRef$current = parentRef.current) === null || _parentRef$current === void 0 ? void 0 : _parentRef$current.focus();
52
+
53
+ setFocusedIndex(focusedIndex - 1);
54
+ } else if ((event.key === 'ArrowDown' || event.key === 'Tab') && nextItemRef) {
55
+ event.preventDefault();
56
+ setFocusedIndex(focusedIndex + 1);
57
+ nextItemRef.focus();
58
+ } else if (event.key === 'Escape') {
59
+ var _parentRef$current2, _parentRef$current3;
60
+
61
+ // Close the dropdown
62
+ parentRef === null || parentRef === void 0 ? void 0 : (_parentRef$current2 = parentRef.current) === null || _parentRef$current2 === void 0 ? void 0 : _parentRef$current2.click(); // Return focus to the dropdown control after leaving the last item
63
+
64
+ parentRef === null || parentRef === void 0 ? void 0 : (_parentRef$current3 = parentRef.current) === null || _parentRef$current3 === void 0 ? void 0 : _parentRef$current3.focus();
65
+ if (onClose) onClose(event);
66
+ }
67
+ }, [focusedIndex, onClose, parentRef]); // Add listeners for mouse clicks outside and for key presses
68
+
69
+ useEffect(() => {
70
+ window.addEventListener('click', onClose);
71
+ window.addEventListener('keydown', handleKeydown);
72
+ window.addEventListener('touchstart', onClose);
73
+ return () => {
74
+ window.removeEventListener('click', onClose);
75
+ window.removeEventListener('keydown', handleKeydown);
76
+ window.removeEventListener('touchstart', onClose);
77
+ };
78
+ }, [onClose, handleKeydown]);
79
+ return /*#__PURE__*/_jsx(ExpandCollapse, {
80
+ initialOpen: initialOpen,
81
+ maxOpen: 1,
82
+ children: expandProps => /*#__PURE__*/_jsx(StyledList, {
83
+ role: "listbox",
84
+ children: items.map((item, index) => {
85
+ const {
86
+ id,
87
+ label,
88
+ items: nestedItems
89
+ } = item;
90
+ const {
91
+ itemId,
92
+ selected
93
+ } = resolveItemSelection({
94
+ id,
95
+ label,
96
+ items: nestedItems
97
+ }, selectedId); // Give `firstItemRef` to the first focusable item
98
+
99
+ const itemRef = index === 0 && !itemId !== selectedId || index === 1 && items[0].id === selectedId ? firstItemRef : ref => {
100
+ itemRefs.current[index] = ref;
101
+ return ref;
102
+ };
103
+ return nestedItems ? /*#__PURE__*/_createElement(ListboxGroup, { ...item,
104
+ selectedId: selectedId,
105
+ key: itemId,
106
+ expandProps: expandProps,
107
+ LinkRouter: LinkRouter,
108
+ itemRouterProps: itemRouterProps,
109
+ prevItemRef: itemRefs.current[index - 1] ?? null,
110
+ nextItemRef: itemRefs.current[index + 1] ?? null,
111
+ ref: itemRef
112
+ }) : /*#__PURE__*/_createElement(ListboxItem, { ...item,
113
+ selected: selected,
114
+ key: itemId,
115
+ LinkRouter: LinkRouter,
116
+ itemRouterProps: itemRouterProps,
117
+ prevItemRef: itemRefs.current[index - 1] ?? null,
118
+ nextItemRef: itemRefs.current[index + 1] ?? null,
119
+ ref: itemRef
120
+ });
121
+ })
122
+ })
123
+ });
124
+ };
125
+
126
+ Listbox.propTypes = { ...withLinkRouter.propTypes,
127
+
128
+ /**
129
+ * Focus will be moved to the item with this ref once within the menu.
130
+ */
131
+ firstItemRef: PropTypes.object,
132
+
133
+ /**
134
+ * Focus will be returned to the dropdown control with this ref after leaving
135
+ * the last menu item.
136
+ */
137
+ parentRef: PropTypes.object,
138
+ items: PropTypes.array,
139
+ selectedId: PropTypes.string
140
+ };
141
+ Listbox.Overlay = DropdownOverlay;
142
+ export default Listbox;