@oslokommune/punkt-react 18.7.1 → 18.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.
@@ -91,6 +91,7 @@ export declare const nb: {
91
91
  tooManySelected: string;
92
92
  alreadySelected: string;
93
93
  valueAdded: string;
94
+ valueSelected: string;
94
95
  noValidValue: string;
95
96
  };
96
97
  fileupload: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oslokommune/punkt-react",
3
- "version": "18.7.1",
3
+ "version": "18.8.0",
4
4
  "description": "React komponentbibliotek til Punkt, et designsystem laget av Oslo Origo",
5
5
  "homepage": "https://punkt.oslo.kommune.no",
6
6
  "author": "Team Designsystem, Oslo Origo",
@@ -40,7 +40,7 @@
40
40
  "@eslint/eslintrc": "^3.3.5",
41
41
  "@eslint/js": "^10.0.1",
42
42
  "@oslokommune/punkt-assets": "^18.7.1",
43
- "@oslokommune/punkt-css": "^18.7.1",
43
+ "@oslokommune/punkt-css": "^18.8.0",
44
44
  "@testing-library/jest-dom": "^6.9.1",
45
45
  "@testing-library/react": "^16.3.2",
46
46
  "@testing-library/user-event": "^14.6.1",
@@ -100,5 +100,5 @@
100
100
  "url": "https://github.com/oslokommune/punkt/issues"
101
101
  },
102
102
  "license": "MIT",
103
- "gitHead": "b9a5110dfcbbda5ade917339741350805b8a0152"
103
+ "gitHead": "30be2be7365f440b93da5bad8ca3e883255d647a"
104
104
  }
@@ -9,6 +9,7 @@ import {
9
9
  useRef,
10
10
  } from 'react'
11
11
  import { usePktStrings } from '../../hooks/usePktStrings'
12
+ import { useGeneratedId } from '../../hooks/useGeneratedId'
12
13
  import type { IPktStringsProps } from 'shared-strings'
13
14
 
14
15
  export interface IPktCheckbox extends InputHTMLAttributes<HTMLInputElement>, IPktStringsProps<'forms'> {
@@ -38,7 +39,7 @@ export interface IPktCheckbox extends InputHTMLAttributes<HTMLInputElement>, IPk
38
39
  export const PktCheckbox = forwardRef(
39
40
  (
40
41
  {
41
- id,
42
+ id: idProp,
42
43
  hasTile = false,
43
44
  disabled = false,
44
45
  label,
@@ -57,11 +58,13 @@ export const PktCheckbox = forwardRef(
57
58
  requiredText,
58
59
  strings,
59
60
  tagText,
61
+ 'aria-describedby': ariaDescribedbyProp,
60
62
  ...props
61
63
  }: IPktCheckbox,
62
64
  ref: ForwardedRef<HTMLInputElement>,
63
65
  ): ReactElement => {
64
66
  const s = usePktStrings(['forms'], strings)
67
+ const id = useGeneratedId(idProp)
65
68
  const internalRef = useRef<HTMLInputElement>(null)
66
69
 
67
70
  useEffect(() => {
@@ -112,15 +115,28 @@ export const PktCheckbox = forwardRef(
112
115
  )
113
116
  }
114
117
 
118
+ const labelId = `${id}-check-label`
119
+ const helptextId = `${id}-check-helptext`
120
+ const describedBy =
121
+ [checkHelptext ? helptextId : undefined, ariaDescribedbyProp].filter(Boolean).join(' ') || undefined
122
+
123
+ const renderLabel = () => (
124
+ <label className={labelClasses} htmlFor={id}>
125
+ <span id={labelId}>
126
+ {label} {renderTags()}
127
+ </span>
128
+ {checkHelptext && (
129
+ <div id={helptextId} className="pkt-input-check__input-helptext">
130
+ {checkHelptext}
131
+ </div>
132
+ )}
133
+ </label>
134
+ )
135
+
115
136
  return (
116
137
  <div className={classes}>
117
138
  <div className={inputTileClasses}>
118
- {labelPosition === 'left' && (
119
- <label className={labelClasses} htmlFor={id}>
120
- {label} {renderTags()}
121
- {checkHelptext && <div className="pkt-input-check__input-helptext">{checkHelptext}</div>}
122
- </label>
123
- )}
139
+ {labelPosition === 'left' && renderLabel()}
124
140
  <input
125
141
  role={isSwitch ? 'switch' : 'checkbox'}
126
142
  ref={internalRef}
@@ -128,15 +144,12 @@ export const PktCheckbox = forwardRef(
128
144
  type="checkbox"
129
145
  id={id}
130
146
  disabled={disabled}
147
+ aria-labelledby={label ? labelId : undefined}
148
+ aria-describedby={describedBy}
131
149
  {...(checked !== undefined ? { checked } : { defaultChecked })}
132
150
  {...props}
133
151
  />
134
- {labelPosition === 'right' && (
135
- <label className={labelClasses} htmlFor={id}>
136
- {label} {renderTags()}
137
- {checkHelptext && <div className="pkt-input-check__input-helptext">{checkHelptext}</div>}
138
- </label>
139
- )}
152
+ {labelPosition === 'right' && renderLabel()}
140
153
  </div>
141
154
  </div>
142
155
  )
@@ -72,12 +72,7 @@ describe('PktCombobox', () => {
72
72
  options: getDefaultOptions(),
73
73
  })
74
74
 
75
- // Exclude nested-interactive: the decorative checkbox inside li[role="option"]
76
- // is aria-hidden and non-focusable, but axe flags it anyway.
77
- // Selection state is conveyed by aria-selected on the option element.
78
- const results = await axe(container, {
79
- rules: { 'nested-interactive': { enabled: false } },
80
- })
75
+ const results = await axe(container)
81
76
  expect(results).toHaveNoViolations()
82
77
  })
83
78
 
@@ -173,7 +168,13 @@ describe('PktCombobox', () => {
173
168
  })
174
169
 
175
170
  const textInput = container.querySelector('input[type="text"]')
176
- expect(textInput?.getAttribute('aria-activedescendant')).toBeTruthy()
171
+ expect(textInput).not.toHaveAttribute('aria-activedescendant')
172
+
173
+ fireEvent.click(textInput!)
174
+
175
+ const active = textInput?.getAttribute('aria-activedescendant')
176
+ expect(active).toBeTruthy()
177
+ expect(container.querySelector(`[id="${active}"]`)).not.toBeNull()
177
178
  })
178
179
 
179
180
  test('text input aria-expanded reflects dropdown state', () => {
@@ -270,6 +270,44 @@ describe('PktCombobox', () => {
270
270
  })
271
271
  })
272
272
 
273
+ describe('Focus after committing a value', () => {
274
+ const commit = async (container: HTMLElement, typed: string) => {
275
+ const input = container.querySelector('input[type="text"]') as HTMLInputElement
276
+ await act(async () => {
277
+ input.focus()
278
+ fireEvent.change(input, { target: { value: typed } })
279
+ fireEvent.keyDown(input, { key: 'Enter' })
280
+ await new Promise((resolve) => setTimeout(resolve, 0))
281
+ })
282
+ }
283
+
284
+ test('moves focus out of the text input after adding a user value', async () => {
285
+ const { container } = createComboboxTest({
286
+ allowUserInput: true,
287
+ options: getDefaultOptions(),
288
+ })
289
+
290
+ await commit(container, 'NewFruit')
291
+
292
+ const input = container.querySelector('input[type="text"]')
293
+ expect(document.activeElement).not.toBe(input)
294
+ expect(document.activeElement).toBe(container.querySelector('.pkt-combobox__input'))
295
+ })
296
+
297
+ test('moves focus out of the text input after selecting a typeahead match', async () => {
298
+ const { container } = createComboboxTest({
299
+ typeahead: true,
300
+ options: getDefaultOptions(),
301
+ })
302
+
303
+ await commit(container, 'apple')
304
+
305
+ const input = container.querySelector('input[type="text"]')
306
+ expect(document.activeElement).not.toBe(input)
307
+ expect(document.activeElement).toBe(container.querySelector('.pkt-combobox__input'))
308
+ })
309
+ })
310
+
273
311
  describe('Focus-out behavior', () => {
274
312
  test('closes dropdown when clicking outside combobox', () => {
275
313
  const { container } = createComboboxTest({
@@ -0,0 +1,247 @@
1
+ import '@testing-library/jest-dom'
2
+
3
+ import { act, fireEvent, render } from '@testing-library/react'
4
+
5
+ import type { IPktComboboxOption } from 'shared-types/combobox'
6
+ import { PktCombobox } from './Combobox'
7
+ import type { IPktCombobox } from './types'
8
+
9
+ const bydeler: IPktComboboxOption[] = [
10
+ { value: 'bfr', label: 'Frogner' },
11
+ { value: 'bga', label: 'Grünerløkka' },
12
+ { value: 'bsa', label: 'Sagene' },
13
+ { value: 'bgo', label: 'Gamle Oslo' },
14
+ ]
15
+
16
+ const createCombobox = (props: Partial<IPktCombobox> = {}) =>
17
+ render(<PktCombobox label="L" id="test" {...(props as IPktCombobox)} />)
18
+
19
+ /** Values the listbox renders as selected. */
20
+ const selectedInList = (container: HTMLElement) =>
21
+ Array.from(container.querySelectorAll('[role="option"]'))
22
+ .filter((el) => el.getAttribute('aria-selected') === 'true')
23
+ .map((el) => el.getAttribute('data-value'))
24
+
25
+ const tagCount = (container: HTMLElement) => container.querySelectorAll('.pkt-tag').length
26
+
27
+ const clickOption = async (container: HTMLElement, value: string) => {
28
+ const option = container.querySelector(`[data-value="${value}"]`) as HTMLElement
29
+ await act(async () => {
30
+ fireEvent.click(option)
31
+ await new Promise((resolve) => setTimeout(resolve, 0))
32
+ })
33
+ }
34
+
35
+ describe('PktCombobox preselection', () => {
36
+ describe('Preselected via the value prop', () => {
37
+ test('marks the preselected options in both the tag list and the listbox', () => {
38
+ const { container } = createCombobox({
39
+ multiple: true,
40
+ tagPlacement: 'outside',
41
+ defaultValue: ['bfr', 'bga', 'bsa'],
42
+ options: bydeler,
43
+ })
44
+
45
+ expect(selectedInList(container)).toEqual(['bfr', 'bga', 'bsa'])
46
+ expect(tagCount(container)).toBe(3)
47
+ })
48
+
49
+ test('keeps the existing selection in the listbox when another option is picked', async () => {
50
+ const { container } = createCombobox({
51
+ multiple: true,
52
+ tagPlacement: 'outside',
53
+ defaultValue: ['bfr', 'bga', 'bsa'],
54
+ options: bydeler,
55
+ })
56
+
57
+ await clickOption(container, 'bgo')
58
+
59
+ expect(selectedInList(container)).toEqual(['bfr', 'bga', 'bsa', 'bgo'])
60
+ expect(tagCount(container)).toBe(4)
61
+ })
62
+
63
+ test('keeps the listbox in sync when an option is deselected', async () => {
64
+ const { container } = createCombobox({
65
+ multiple: true,
66
+ defaultValue: ['bfr', 'bga', 'bsa'],
67
+ options: bydeler,
68
+ })
69
+
70
+ await clickOption(container, 'bga')
71
+
72
+ expect(selectedInList(container)).toEqual(['bfr', 'bsa'])
73
+ })
74
+ })
75
+
76
+ describe('Preselected via options.selected', () => {
77
+ test('seeds the value from options marked selected', () => {
78
+ const { container } = createCombobox({
79
+ multiple: true,
80
+ typeahead: true,
81
+ options: [
82
+ { value: 'HODEPINE', selected: true },
83
+ { value: 'KVALME' },
84
+ { value: 'INGEN', selected: true },
85
+ ],
86
+ })
87
+
88
+ expect(selectedInList(container)).toEqual(['HODEPINE', 'INGEN'])
89
+ expect(tagCount(container)).toBe(2)
90
+ })
91
+
92
+ test('adds to the preselected values rather than replacing them', async () => {
93
+ const { container } = createCombobox({
94
+ multiple: true,
95
+ typeahead: true,
96
+ options: [
97
+ { value: 'HODEPINE', selected: true },
98
+ { value: 'KVALME' },
99
+ { value: 'INGEN', selected: true },
100
+ ],
101
+ })
102
+
103
+ await clickOption(container, 'KVALME')
104
+
105
+ expect(selectedInList(container)).toEqual(['HODEPINE', 'KVALME', 'INGEN'])
106
+ expect(tagCount(container)).toBe(3)
107
+ })
108
+
109
+ test('takes only the first preselected option in single-select mode', () => {
110
+ const { container } = createCombobox({
111
+ options: [
112
+ { value: 'HODEPINE', selected: true },
113
+ { value: 'KVALME' },
114
+ ],
115
+ })
116
+
117
+ expect(selectedInList(container)).toEqual(['HODEPINE'])
118
+ })
119
+ })
120
+
121
+ describe('Preselected via defaultValue', () => {
122
+ test('seeds the value from defaultValue', () => {
123
+ const { container } = createCombobox({
124
+ multiple: true,
125
+ defaultValue: ['bfr', 'bga'],
126
+ options: bydeler,
127
+ })
128
+
129
+ expect(selectedInList(container)).toEqual(['bfr', 'bga'])
130
+ expect(tagCount(container)).toBe(2)
131
+ })
132
+
133
+ test('lets value take precedence over defaultValue', () => {
134
+ const { container } = createCombobox({
135
+ multiple: true,
136
+ value: ['bsa'],
137
+ defaultValue: ['bfr', 'bga'],
138
+ options: bydeler,
139
+ })
140
+
141
+ expect(selectedInList(container)).toEqual(['bsa'])
142
+ })
143
+
144
+ test('does not reapply defaultValue after the selection is cleared', async () => {
145
+ const { container } = createCombobox({
146
+ multiple: true,
147
+ defaultValue: ['bfr'],
148
+ options: bydeler,
149
+ })
150
+ expect(selectedInList(container)).toEqual(['bfr'])
151
+
152
+ await clickOption(container, 'bfr')
153
+
154
+ expect(selectedInList(container)).toEqual([])
155
+ })
156
+ })
157
+
158
+ describe('Form reset', () => {
159
+ const renderInForm = (props: Partial<IPktCombobox>) =>
160
+ render(
161
+ <form>
162
+ <PktCombobox label="L" id="test" name="test" {...(props as IPktCombobox)} />
163
+ </form>,
164
+ )
165
+
166
+ const addUserValue = async (container: HTMLElement, text: string) => {
167
+ const input = container.querySelector('input[type="text"]') as HTMLInputElement
168
+ await act(async () => {
169
+ input.focus()
170
+ fireEvent.change(input, { target: { value: text } })
171
+ fireEvent.keyDown(input, { key: 'Enter' })
172
+ await new Promise((resolve) => setTimeout(resolve, 0))
173
+ })
174
+ }
175
+
176
+ const reset = async (container: HTMLElement) => {
177
+ await act(async () => {
178
+ ;(container.querySelector('form') as HTMLFormElement).reset()
179
+ await new Promise((resolve) => setTimeout(resolve, 0))
180
+ })
181
+ }
182
+
183
+ test('clears a selected option', async () => {
184
+ const { container } = renderInForm({ multiple: true, options: bydeler })
185
+ await clickOption(container, 'bfr')
186
+ expect(tagCount(container)).toBe(1)
187
+
188
+ await reset(container)
189
+
190
+ expect(tagCount(container)).toBe(0)
191
+ expect(selectedInList(container)).toEqual([])
192
+ })
193
+
194
+ test('clears a user-added value', async () => {
195
+ const { container } = renderInForm({
196
+ multiple: true,
197
+ allowUserInput: true,
198
+ options: bydeler,
199
+ })
200
+ await addUserValue(container, 'egendefinert')
201
+ expect(tagCount(container)).toBe(1)
202
+
203
+ await reset(container)
204
+
205
+ expect(tagCount(container)).toBe(0)
206
+ })
207
+ })
208
+
209
+ describe('Selection state after picking an option', () => {
210
+ test('marks the option in the listbox on the first click', async () => {
211
+ const { container } = createCombobox({
212
+ multiple: true,
213
+ maxlength: 3,
214
+ includeSearch: true,
215
+ options: bydeler,
216
+ })
217
+
218
+ await clickOption(container, 'bfr')
219
+
220
+ expect(selectedInList(container)).toEqual(['bfr'])
221
+ expect(tagCount(container)).toBe(1)
222
+ })
223
+
224
+ test('keeps value and listbox in sync across repeated toggles', async () => {
225
+ const { container } = createCombobox({ multiple: true, options: bydeler })
226
+
227
+ for (const value of ['bfr', 'bga', 'bfr', 'bsa']) {
228
+ await clickOption(container, value)
229
+ }
230
+
231
+ expect(selectedInList(container)).toEqual(['bga', 'bsa'])
232
+ expect(tagCount(container)).toBe(2)
233
+ })
234
+
235
+ test('keeps selection when all options are preselected', async () => {
236
+ const { container } = createCombobox({
237
+ multiple: true,
238
+ defaultValue: ['bfr', 'bga', 'bsa', 'bgo'],
239
+ options: bydeler,
240
+ })
241
+
242
+ await clickOption(container, 'bfr')
243
+
244
+ expect(selectedInList(container)).toEqual(['bga', 'bsa', 'bgo'])
245
+ })
246
+ })
247
+ })
@@ -27,6 +27,8 @@ export const ComboboxInput = ({ state }: IComboboxInputProps) => {
27
27
  hasError,
28
28
  label,
29
29
  inputFocus,
30
+ skipInputTab,
31
+ restoreInputTab,
30
32
  inputRef,
31
33
  triggerRef,
32
34
  handleInputChange,
@@ -63,7 +65,7 @@ export const ComboboxInput = ({ state }: IComboboxInputProps) => {
63
65
 
64
66
  // Compute aria-activedescendant for select-only mode
65
67
  const activeDescendant =
66
- values[0] && findOptionByValue(options, values[0])
68
+ isOpen && values[0] && findOptionByValue(options, values[0])
67
69
  ? `${listboxId}-${findOptionIndex(options, values[0])}`
68
70
  : undefined
69
71
 
@@ -89,7 +91,16 @@ export const ComboboxInput = ({ state }: IComboboxInputProps) => {
89
91
  }
90
92
 
91
93
  return (
92
- <div ref={triggerRef} className={inputClasses} onClick={handleInputClick} {...selectOnlyProps}>
94
+ <div
95
+ ref={triggerRef}
96
+ className={inputClasses}
97
+ onClick={handleInputClick}
98
+ onBlur={(e) => {
99
+ // React's onBlur bubbles (focusout), so only react to the wrapper's own blur.
100
+ if (e.target === e.currentTarget) restoreInputTab()
101
+ }}
102
+ {...selectOnlyProps}
103
+ >
93
104
  {showPlaceholder ? (
94
105
  <span className="pkt-combobox__placeholder" onClick={handlePlaceholderClick}>
95
106
  {placeholder}
@@ -113,6 +124,7 @@ export const ComboboxInput = ({ state }: IComboboxInputProps) => {
113
124
  onKeyDown={handleInputKeydown}
114
125
  onFocus={handleInputFocus}
115
126
  onBlur={handleInputBlur}
127
+ tabIndex={skipInputTab ? -1 : undefined}
116
128
  placeholder={!values.length || (multiple && tagPlacement === 'outside') ? placeholder : undefined}
117
129
  autoComplete="off"
118
130
  role="combobox"
@@ -132,7 +144,6 @@ export const ComboboxInput = ({ state }: IComboboxInputProps) => {
132
144
  id={inputId}
133
145
  name={`${name || id}-input`}
134
146
  value={values.join(',')}
135
- readOnly
136
147
  />
137
148
  )}
138
149
 
@@ -142,10 +142,11 @@ export const Listbox = ({ state }: IListboxProps) => {
142
142
  <input
143
143
  className="pkt-input-check__input-checkbox"
144
144
  type="checkbox"
145
+ inert
145
146
  tabIndex={-1}
146
147
  value={option.value}
147
148
  checked={option.selected || false}
148
- readOnly
149
+ onChange={() => {}}
149
150
  aria-hidden="true"
150
151
  disabled={isOptionDisabled}
151
152
  />
@@ -90,6 +90,8 @@ export interface IComboboxState {
90
90
  maxIsReached: boolean
91
91
  editingSingleValue: boolean
92
92
  inputFocus: boolean
93
+ skipInputTab: boolean
94
+ restoreInputTab: () => void
93
95
  focusedTagIndex: number
94
96
 
95
97
  // Props passthrough