@telus-uds/components-base 1.34.0 → 1.34.2

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,4 +1,4 @@
1
- import React, { forwardRef, useState } from 'react'
1
+ import React, { useState } from 'react'
2
2
  import PropTypes from 'prop-types'
3
3
 
4
4
  import { useThemeTokens, useThemeTokensCallback } from '../ThemeProvider'
@@ -7,8 +7,10 @@ import {
7
7
  getTokensPropType,
8
8
  getPressHandlersWithArgs,
9
9
  selectTokens,
10
+ useOverlaidPosition,
10
11
  useCopy,
11
12
  useMultipleInputValues,
13
+ useResponsiveProp,
12
14
  variantProp
13
15
  } from '../utils'
14
16
  import dictionary from './dictionary'
@@ -37,134 +39,149 @@ const selectDividerToknes = ({ dividerColor, width, decorative = true, weight =
37
39
  weight
38
40
  })
39
41
 
40
- const MultiSelectFilter = forwardRef(
41
- (
42
- {
43
- label,
44
- subtitle,
45
- id = label,
46
- variant,
47
- tokens,
48
- items = [],
49
- values,
50
- initialValues,
51
- maxValues,
52
- onChange,
53
- copy = 'en',
54
- readOnly = false,
55
- inactive = false,
56
- rowLimit = 12,
57
- ...rest
58
- },
59
- ref
60
- ) => {
61
- const { currentValues, setValues } = useMultipleInputValues({
62
- initialValues,
63
- values,
64
- maxValues,
65
- onChange,
66
- readOnly
67
- })
42
+ const MultiSelectFilter = ({
43
+ label,
44
+ subtitle,
45
+ id = label,
46
+ variant,
47
+ tokens,
48
+ items = [],
49
+ values,
50
+ initialValues,
51
+ maxValues,
52
+ onChange,
53
+ copy = 'en',
54
+ readOnly = false,
55
+ inactive = false,
56
+ rowLimit = 12,
57
+ ...rest
58
+ }) => {
59
+ const { currentValues, setValues } = useMultipleInputValues({
60
+ initialValues,
61
+ values,
62
+ maxValues,
63
+ onChange,
64
+ readOnly
65
+ })
68
66
 
69
- const themeTokens = useThemeTokens('ButtonDropdown', tokens, variant)
70
- const getItemTokens = useThemeTokensCallback('ButtonDropdown', tokens, variant)
71
- const getButtonTokens = (buttonState) => selectTokens('Button', getItemTokens(buttonState))
72
- const getCopy = useCopy({ dictionary, copy })
67
+ const themeTokens = useThemeTokens('ButtonDropdown', tokens, variant)
68
+ const getItemTokens = useThemeTokensCallback('ButtonDropdown', tokens, variant)
69
+ const getButtonTokens = (buttonState) => selectTokens('Button', getItemTokens(buttonState))
70
+ const getCopy = useCopy({ dictionary, copy })
73
71
 
74
- const [isOpen, setIsOpen] = useState(false)
75
- const [checkedIds, setCheckedIds] = useState(currentValues ?? [])
72
+ const [isOpen, setIsOpen] = useState(false)
73
+ const [checkedIds, setCheckedIds] = useState(currentValues ?? [])
76
74
 
77
- const colSize = items.length > rowLimit ? 2 : 1
78
- const isSelected = currentValues.length > 0
75
+ const colSize = items.length > rowLimit ? 2 : 1
76
+ const isSelected = currentValues.length > 0
79
77
 
80
- const uniqueFields = ['id', 'label']
81
- if (!containUniqueFields(items, uniqueFields)) {
82
- throw new Error(`MultiSelectFilter items must have unique ${uniqueFields.join(', ')}`)
83
- }
78
+ const uniqueFields = ['id', 'label']
79
+ if (!containUniqueFields(items, uniqueFields)) {
80
+ throw new Error(`MultiSelectFilter items must have unique ${uniqueFields.join(', ')}`)
81
+ }
84
82
 
85
- // Pass an object of relevant component state as first argument for any passed-in press handlers
86
- const pressHandlers = getPressHandlersWithArgs(rest, [{ id, label, currentValues }])
83
+ // Pass an object of relevant component state as first argument for any passed-in press handlers
84
+ const pressHandlers = getPressHandlersWithArgs(rest, [{ id, label, currentValues }])
87
85
 
88
- const handleChange = (event) => {
89
- if (pressHandlers.onPress) pressHandlers?.onPress(event)
90
- setIsOpen(!isOpen)
91
- }
86
+ const handleChange = (event) => {
87
+ if (pressHandlers.onPress) pressHandlers?.onPress(event)
88
+ setIsOpen(!isOpen)
89
+ }
90
+
91
+ const onApply = (e) => {
92
+ setValues(e)
93
+ setIsOpen(false)
94
+ }
92
95
 
93
- const onApply = (e) => {
94
- setValues(e)
95
- setIsOpen(false)
96
+ const { align, offsets } = useResponsiveProp({
97
+ xs: { align: { top: 'top', left: 'left', bottom: 'bottom', right: 'right' } },
98
+ sm: {
99
+ align: { top: 'bottom', left: 'left' },
100
+ offsets: { vertical: 4 }
96
101
  }
102
+ })
97
103
 
98
- return (
99
- <>
100
- <ButtonDropdown
101
- ref={ref}
102
- key={id}
103
- {...pressHandlers}
104
- value={isOpen}
105
- selected={isSelected}
106
- label={label}
107
- onChange={handleChange}
108
- tokens={getButtonTokens}
109
- inactive={inactive}
110
- />
111
- {isOpen && (
112
- <ModalOverlay
113
- variant={{ width: colSize > 1 ? 'size576' : 's' }}
114
- onClose={() => setIsOpen(false)}
115
- >
116
- <Row>
117
- <Typography variant={{ size: 'h4' }}>
118
- {getCopy('filterByLabel').replace(/%\{filterCategory\}/g, label.toLowerCase())}
119
- </Typography>
120
- </Row>
121
- {subtitle && (
122
- <>
123
- <Spacer space={5} />
124
- <Row>
125
- <Typography variant={{ size: 'h5' }} tokens={selectSubTitleTokens(themeTokens)}>
126
- {subtitle}
127
- </Typography>
128
- </Row>
129
- </>
130
- )}
131
- <Spacer space={4} />
132
- <Box scroll={true}>
133
- <Row distribute="between">
134
- {[...Array(colSize).keys()].map((i) => (
135
- <Col xs={12 / colSize} key={i}>
136
- <CheckboxGroup
137
- items={items.slice(i * rowLimit, (i + 1) * rowLimit)}
138
- checkedIds={checkedIds}
139
- onChange={(e) => setCheckedIds(e, i)}
140
- />
141
- <Spacer size={4} />
142
- </Col>
143
- ))}
104
+ const { overlaidPosition, onTargetLayout, isReady, sourceRef } = useOverlaidPosition({
105
+ isShown: isOpen,
106
+ offsets,
107
+ align
108
+ })
109
+
110
+ return (
111
+ <>
112
+ <ButtonDropdown
113
+ ref={sourceRef}
114
+ key={id}
115
+ {...pressHandlers}
116
+ value={isOpen}
117
+ selected={isSelected}
118
+ label={label}
119
+ onChange={handleChange}
120
+ tokens={getButtonTokens}
121
+ inactive={inactive}
122
+ />
123
+ {isOpen && (
124
+ <ModalOverlay
125
+ overlaidPosition={overlaidPosition}
126
+ variant={{ width: colSize > 1 ? 'size576' : 's' }}
127
+ onClose={() => setIsOpen(false)}
128
+ tokens={tokens}
129
+ copy={copy}
130
+ isReady={isReady}
131
+ onLayout={onTargetLayout}
132
+ >
133
+ <Row>
134
+ <Typography variant={{ size: 'h4' }}>
135
+ {getCopy('filterByLabel').replace(/%\{filterCategory\}/g, label.toLowerCase())}
136
+ </Typography>
137
+ </Row>
138
+ {subtitle && (
139
+ <>
140
+ <Spacer space={5} />
141
+ <Row>
142
+ <Typography variant={{ size: 'h5' }} tokens={selectSubTitleTokens(themeTokens)}>
143
+ {subtitle}
144
+ </Typography>
144
145
  </Row>
145
- </Box>
146
- <Divider variant={selectDividerToknes({ ...themeTokens, width: 'full' })} space={4} />
147
- <Row>
148
- <StackView direction="row" space={3} tokens={{ alignItems: 'center' }}>
149
- <Button
150
- onPress={() => onApply(checkedIds)}
151
- variant={{ size: 'small', priority: 'high' }}
152
- >
153
- {getCopy('applyButtonLabel')}
154
- </Button>
155
- <Box>
156
- <TextButton onPress={() => setCheckedIds([])}>
157
- {getCopy('clearButtonLabel')}
158
- </TextButton>
159
- </Box>
160
- </StackView>
146
+ </>
147
+ )}
148
+ <Spacer space={4} />
149
+ <Box scroll={true}>
150
+ <Row distribute="between">
151
+ {[...Array(colSize).keys()].map((i) => (
152
+ <Col xs={12 / colSize} key={i}>
153
+ <CheckboxGroup
154
+ items={items.slice(i * rowLimit, (i + 1) * rowLimit)}
155
+ checkedIds={checkedIds}
156
+ onChange={(e) => setCheckedIds(e, i)}
157
+ />
158
+ <Spacer size={4} />
159
+ </Col>
160
+ ))}
161
161
  </Row>
162
- </ModalOverlay>
163
- )}
164
- </>
165
- )
166
- }
167
- )
162
+ </Box>
163
+ <Divider variant={selectDividerToknes({ ...themeTokens, width: 'full' })} space={4} />
164
+ <Row>
165
+ <StackView direction="row" space={3} tokens={{ alignItems: 'center' }}>
166
+ <Button
167
+ onPress={() => onApply(checkedIds)}
168
+ variant={{ size: 'small', priority: 'high' }}
169
+ >
170
+ {getCopy('applyButtonLabel')}
171
+ </Button>
172
+ <Box>
173
+ <TextButton onPress={() => setCheckedIds([])}>
174
+ {getCopy('clearButtonLabel')}
175
+ </TextButton>
176
+ </Box>
177
+ </StackView>
178
+ </Row>
179
+ </ModalOverlay>
180
+ )}
181
+ </>
182
+ )
183
+ }
184
+
168
185
  MultiSelectFilter.displayName = 'MultiSelectFilter'
169
186
 
170
187
  MultiSelectFilter.propTypes = {
@@ -34,8 +34,8 @@ const selectHighlightBarStyles = ({
34
34
  borderRadius: highlightBarBorderRadius,
35
35
  borderWidth: highlightBarBorderWidth,
36
36
  bottom: -1 * (highlightBarHeight + highlightBarBorderWidth),
37
- left: -1 * highlightBarBorderWidth,
38
- right: -1 * highlightBarBorderWidth,
37
+ left: 0,
38
+ right: 0,
39
39
  zIndex: 1 + highlightBarBorderWidth
40
40
  })
41
41
 
@@ -10,6 +10,7 @@ export { default as useCopy } from './useCopy'
10
10
  export { default as useHash } from './useHash'
11
11
  export { default as useSpacingScale } from './useSpacingScale'
12
12
  export { default as useResponsiveProp } from './useResponsiveProp'
13
+ export { default as useOverlaidPosition } from './useOverlaidPosition'
13
14
  export { default as useSafeLayoutEffect } from './useSafeLayoutEffect'
14
15
  export { default as useScrollBlocking } from './useScrollBlocking'
15
16
  export * from './useResponsiveProp'
@@ -0,0 +1,223 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import { Dimensions } from 'react-native'
3
+
4
+ const adjustHorizontalToFit = (initialOffset, windowWidth, sourceWidth) => {
5
+ const offset = Math.max(0, initialOffset)
6
+ const otherEdgeOverflow = Math.max(0, offset + sourceWidth - windowWidth)
7
+ const tooWideBy = Math.max(0, otherEdgeOverflow - offset)
8
+
9
+ const adjusted = {
10
+ offset: Math.max(0, offset - otherEdgeOverflow)
11
+ }
12
+ if (tooWideBy) adjusted.width = Math.max(0, sourceWidth - tooWideBy)
13
+
14
+ return adjusted
15
+ }
16
+
17
+ const getPosition = ({ edge, fromEdge, sourceSize }) => {
18
+ switch (edge) {
19
+ case 'near':
20
+ return fromEdge
21
+ case 'mid':
22
+ return fromEdge + sourceSize / 2
23
+ case 'far':
24
+ return fromEdge + sourceSize
25
+ default:
26
+ return 0
27
+ }
28
+ }
29
+
30
+ const getEdgeType = (align, alignSide) => {
31
+ const alignTo = align[alignSide]
32
+ const edge =
33
+ (['center', 'middle'].includes(alignTo) && 'mid') || (alignSide === alignTo ? 'near' : 'far')
34
+ return edge
35
+ }
36
+
37
+ /**
38
+ * Based on UDS's private getTooltipPosition but generalised.
39
+ *
40
+ * Used for absolute positioning of the tooltip. Since the tooltip is always centered relatively
41
+ * to the source (button) and we have a limited set of positions, an easy and consistent way
42
+ * of positioning it is to check all of the possible positions and pick one that will be rendered
43
+ * within the window bounds. This way we can also rely on the tooltip being actually rendered
44
+ * before it is shown, which makes it account for the width being limiting in styles, custom font
45
+ * rendering, etc.
46
+ */
47
+ function getOverlaidPosition({
48
+ sourceLayout,
49
+ targetDimensions,
50
+ windowDimensions,
51
+ offsets = {},
52
+ align
53
+ }) {
54
+ // Web-only: this will be difficult to mimic on native because there's no global scroll position.
55
+ // TODO: wire something in e.g. a scroll ref accessible from a provider included in Allium provider
56
+ // that can be passed to the appropriate ScrollView?
57
+ const { scrollX = 0, scrollY = 0 } = typeof window === 'object' ? window : {}
58
+
59
+ // Will have top, bottom, left and/or right offsets depending on `align`
60
+ const positioning = {}
61
+
62
+ if (align.top)
63
+ positioning.top = getPosition({
64
+ edge: getEdgeType(align, 'top'),
65
+ fromEdge: sourceLayout.y + scrollY + (offsets.vertical ?? 0),
66
+ sourceSize: sourceLayout.height
67
+ })
68
+ if (align.middle)
69
+ positioning.top = getPosition({
70
+ edge: getEdgeType(align, 'middle'),
71
+ fromEdge: sourceLayout.y + scrollY + (offsets.vertical ?? 0) - targetDimensions.height / 2,
72
+ sourceSize: sourceLayout.height
73
+ })
74
+ if (align.bottom)
75
+ positioning.bottom = getPosition({
76
+ edge: getEdgeType(align, 'bottom'),
77
+ fromEdge:
78
+ windowDimensions.height -
79
+ (sourceLayout.y + scrollY + sourceLayout.height - (offsets.vertical ?? 0)),
80
+ sourceSize: sourceLayout.height
81
+ })
82
+
83
+ if (align.left)
84
+ positioning.left = getPosition({
85
+ edge: getEdgeType(align, 'left'),
86
+ fromEdge: sourceLayout.x + scrollX + (offsets.horizontal ?? 0),
87
+ sourceSize: sourceLayout.width
88
+ })
89
+ if (align.center)
90
+ positioning.left = getPosition({
91
+ edge: getEdgeType(align, 'center'),
92
+ fromEdge: sourceLayout.x + scrollX + (offsets.horizontal ?? 0) - targetDimensions.width / 2,
93
+ sourceSize: sourceLayout.width
94
+ })
95
+ if (align.right)
96
+ positioning.right = getPosition({
97
+ edge: getEdgeType(align, 'right'),
98
+ fromEdge:
99
+ windowDimensions.width -
100
+ (sourceLayout.x + scrollX + sourceLayout.width - (offsets.horizontal ?? 0)),
101
+ sourceSize: sourceLayout.width
102
+ })
103
+
104
+ if (!(align.left && align.right)) {
105
+ // Check if the position and/or width need adjusting to fit on the screen
106
+ const side = align.right ? 'right' : 'left'
107
+ const adjusted = adjustHorizontalToFit(
108
+ positioning[side],
109
+ windowDimensions.width,
110
+ sourceLayout.width
111
+ )
112
+ if (typeof adjusted.width === 'number') positioning.width = adjusted.width
113
+ if (typeof adjusted.offset === 'number') {
114
+ positioning[side] = adjusted.offset
115
+ }
116
+ }
117
+
118
+ return positioning
119
+ }
120
+
121
+ /**
122
+ * Positions an element in a modal or portal so that it appears tooltip-like below the
123
+ * target element.
124
+ *
125
+ * @TODO - add support for positioning other than 'below' like UDS's tooltip (this is not
126
+ * a small task because UDS's tooltip logic only really works for short text - it might be
127
+ * better to use a third-party library).
128
+ */
129
+ const useOverlaidPosition = ({
130
+ isShown = false,
131
+ offsets,
132
+ // By default, align the overlaid target's `top` to the bottom of the source, and center horizontally.
133
+ align = {
134
+ center: 'center',
135
+ top: 'bottom'
136
+ }
137
+ }) => {
138
+ // Element in main document flow that the targetRef element is positioned around
139
+ const sourceRef = useRef(null)
140
+ const [sourceLayout, setSourceLayout] = useState(null)
141
+
142
+ // Element in a modal or portal overlay positioned to appear adjacent to sourceRef
143
+ const targetRef = useRef(null)
144
+ const [targetDimensions, setTargetDimensions] = useState(null)
145
+
146
+ const [windowDimensions, setWindowDimensions] = useState(null)
147
+
148
+ const onTargetLayout = useCallback(
149
+ ({
150
+ nativeEvent: {
151
+ layout: { width, height }
152
+ }
153
+ }) => {
154
+ // NOTE: UDS's Tooltip logic injects some additional width to allow for antialiasing etc of text,
155
+ // avoiding adding unnecessary line breaks to text that is slightly wider than it thinks it is.
156
+ // That is probably something specific to text tooltips that doesn't belong in a generic hook.
157
+ setTargetDimensions((previousDimensions) => {
158
+ // Re-render on first non-zero width / height: avoid infinite loops on changes, or mispositioning
159
+ // if user scrolls while a slidedown animation is changing the height and recalculating position.
160
+ if (!previousDimensions && width && height) {
161
+ return { width, height }
162
+ }
163
+ return previousDimensions
164
+ })
165
+ },
166
+ []
167
+ )
168
+
169
+ const readyToShow = Boolean(isShown && sourceRef.current)
170
+ useEffect(() => {
171
+ const handleDimensionsChange = ({ window }) => {
172
+ sourceRef.current?.measureInWindow((x, y, width, height) => {
173
+ // Could add a debouncer here if there's too many rerenders during gradual resizes
174
+ setWindowDimensions(window)
175
+ setSourceLayout({ x, y, width, height })
176
+ })
177
+ }
178
+
179
+ let subscription
180
+ const unsubscribe = () => {
181
+ if (typeof subscription?.remove === 'function') {
182
+ // React Native >=0.65.0
183
+ subscription.remove()
184
+ } else if (typeof Dimensions.removeEventListener === 'function') {
185
+ // React Native <0.65.0
186
+ Dimensions.removeEventListener('change', handleDimensionsChange)
187
+ }
188
+ setSourceLayout(null)
189
+ setTargetDimensions(null)
190
+ }
191
+
192
+ if (readyToShow) {
193
+ subscription = Dimensions.addEventListener('change', handleDimensionsChange)
194
+ handleDimensionsChange({ window: Dimensions.get('window') })
195
+ } else {
196
+ unsubscribe()
197
+ }
198
+
199
+ return unsubscribe
200
+ }, [readyToShow])
201
+
202
+ const isReady = Boolean(isShown && sourceLayout && windowDimensions && targetDimensions)
203
+
204
+ const overlaidPosition = isReady
205
+ ? getOverlaidPosition({
206
+ sourceLayout,
207
+ targetDimensions,
208
+ windowDimensions,
209
+ offsets,
210
+ align
211
+ })
212
+ : {}
213
+
214
+ return {
215
+ overlaidPosition,
216
+ sourceRef,
217
+ targetRef,
218
+ onTargetLayout,
219
+ isReady
220
+ }
221
+ }
222
+
223
+ export default useOverlaidPosition