@oslokommune/punkt-react 19.8.0 → 19.9.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 (34) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/components/checkboxgroup/CheckboxGroup.d.ts +17 -0
  3. package/dist/components/checkboxgroup/CheckboxGroup.forms.test.d.ts +0 -0
  4. package/dist/components/checkboxgroup/CheckboxGroup.test.d.ts +0 -0
  5. package/dist/components/checkboxgroup/CheckboxGroupContext.d.ts +12 -0
  6. package/dist/components/index.d.ts +3 -1
  7. package/dist/components/inputwrapper/InputWrapper.d.ts +4 -1
  8. package/dist/components/interfaces.d.ts +2 -0
  9. package/dist/components/radio/RadioButton.d.ts +1 -1
  10. package/dist/components/radiogroup/RadioGroup.d.ts +17 -0
  11. package/dist/components/radiogroup/RadioGroup.forms.test.d.ts +0 -0
  12. package/dist/components/radiogroup/RadioGroup.test.d.ts +0 -0
  13. package/dist/components/radiogroup/RadioGroupContext.d.ts +13 -0
  14. package/dist/punkt-react.cjs +1 -1
  15. package/dist/punkt-react.js +2416 -2164
  16. package/dist/shared-strings/nb.d.ts +1 -0
  17. package/dist/shared-types/index.d.ts +4 -2
  18. package/dist/shared-types/option-group.d.ts +50 -0
  19. package/package.json +3 -3
  20. package/src/components/checkbox/Checkbox.test.tsx +77 -0
  21. package/src/components/checkbox/Checkbox.tsx +40 -6
  22. package/src/components/checkboxgroup/CheckboxGroup.forms.test.tsx +149 -0
  23. package/src/components/checkboxgroup/CheckboxGroup.test.tsx +495 -0
  24. package/src/components/checkboxgroup/CheckboxGroup.tsx +162 -0
  25. package/src/components/checkboxgroup/CheckboxGroupContext.ts +15 -0
  26. package/src/components/index.ts +3 -7
  27. package/src/components/inputwrapper/InputWrapper.tsx +21 -2
  28. package/src/components/interfaces.ts +2 -0
  29. package/src/components/radio/RadioButton.test.tsx +70 -0
  30. package/src/components/radio/RadioButton.tsx +52 -9
  31. package/src/components/radiogroup/RadioGroup.forms.test.tsx +145 -0
  32. package/src/components/radiogroup/RadioGroup.test.tsx +472 -0
  33. package/src/components/radiogroup/RadioGroup.tsx +123 -0
  34. package/src/components/radiogroup/RadioGroupContext.ts +16 -0
@@ -1,6 +1,6 @@
1
1
  'use client'
2
2
 
3
- import { ForwardedRef, forwardRef, type ReactNode, RefAttributes, useMemo } from 'react'
3
+ import { type FocusEventHandler, ForwardedRef, forwardRef, type ReactNode, RefAttributes, useMemo } from 'react'
4
4
 
5
5
  import { useFocusModality } from '../../hooks/useFocusModality'
6
6
  import { usePktStrings } from '../../hooks/usePktStrings'
@@ -12,6 +12,7 @@ import { PktAlert } from '../alert/Alert'
12
12
  import { PktHelptext } from '../helptext/Helptext'
13
13
 
14
14
  export interface IPktInputWrapper extends RefAttributes<HTMLElement>, IPktStringsProps<'forms' | 'validation'> {
15
+ id?: string
15
16
  forId: string
16
17
  label: string
17
18
  helptext?: string | ReactNode
@@ -41,11 +42,14 @@ export interface IPktInputWrapper extends RefAttributes<HTMLElement>, IPktString
41
42
  role?: string
42
43
  counterPosition?: 'top' | 'bottom'
43
44
  size?: 'small' | 'medium' | 'xsmall'
45
+ onFocus?: FocusEventHandler<HTMLDivElement>
46
+ onBlur?: FocusEventHandler<HTMLDivElement>
44
47
  }
45
48
 
46
49
  export const PktInputWrapper = forwardRef(
47
50
  (
48
51
  {
52
+ id,
49
53
  forId: forIdProp,
50
54
  label,
51
55
  helptext,
@@ -73,6 +77,8 @@ export const PktInputWrapper = forwardRef(
73
77
  counterPosition = 'bottom',
74
78
  size = 'medium',
75
79
  strings,
80
+ onFocus,
81
+ onBlur,
76
82
  }: IPktInputWrapper,
77
83
  ref: ForwardedRef<HTMLDivElement>,
78
84
  ) => {
@@ -222,13 +228,26 @@ export const PktInputWrapper = forwardRef(
222
228
 
223
229
  return (
224
230
  <div
231
+ id={id}
225
232
  className={wrapperClasses}
226
233
  role={role}
227
234
  aria-labelledby={role ? `${forId}-label` : undefined}
228
235
  {...focusModality}
236
+ onFocus={(event) => {
237
+ focusModality.onFocus()
238
+ onFocus?.(event)
239
+ }}
240
+ onBlur={(event) => {
241
+ focusModality.onBlur(event)
242
+ onBlur?.(event)
243
+ }}
229
244
  >
230
245
  {hasFieldset ? (
231
- <fieldset className="pkt-inputwrapper__fieldset" aria-describedby={describedBy}>
246
+ <fieldset
247
+ className="pkt-inputwrapper__fieldset"
248
+ aria-describedby={describedBy}
249
+ disabled={disabled || undefined}
250
+ >
232
251
  {content}
233
252
  </fieldset>
234
253
  ) : (
@@ -6,6 +6,7 @@ export type { IPktBreadcrumbs } from './breadcrumbs/Breadcrumbs'
6
6
  export type { IPktButton } from './button/Button'
7
7
  export type { IPktCard } from './card/Card'
8
8
  export type { IPktCheckbox } from './checkbox/Checkbox'
9
+ export type { IPktCheckboxGroup } from './checkboxgroup/CheckboxGroup'
9
10
  export type { IPktCombobox } from './combobox/Combobox'
10
11
  export type { IPktDatepicker } from './datepicker/Datepicker'
11
12
  export type { IPktFileUpload } from './fileupload/FileUpload'
@@ -21,6 +22,7 @@ export type { IPktMessagebox } from './messagebox/Messagebox'
21
22
  export type { IPktModal } from './modal/Modal'
22
23
  export type { IPktProgressbar } from './progressbar/Progressbar'
23
24
  export type { IPktRadioButton } from './radio/RadioButton'
25
+ export type { IPktRadioGroup } from './radiogroup/RadioGroup'
24
26
  export type { IPktStep } from './stepper/Step'
25
27
  export type { IPktStepper } from './stepper/Stepper'
26
28
  export type { IPktTab } from './tabs/Tabs'
@@ -4,6 +4,7 @@ import { fireEvent, render } from '@testing-library/react'
4
4
  import { axe, toHaveNoViolations } from 'jest-axe'
5
5
  import { vi } from 'vitest'
6
6
 
7
+ import { radioContexts } from '../../utils/option-contexts'
7
8
  import { PktInputWrapper } from '../inputwrapper/InputWrapper'
8
9
  import { PktRadioButton } from './RadioButton'
9
10
 
@@ -92,3 +93,72 @@ describe('PktRadioButton inputSize', () => {
92
93
  expect(document.getElementById('n')).not.toHaveAttribute('inputSize')
93
94
  })
94
95
  })
96
+
97
+ describe.each(radioContexts)('PktRadioButton $name', ({ wrap }) => {
98
+ const input = () => document.getElementById('valg') as HTMLInputElement
99
+
100
+ it('renders the input with its label and value', () => {
101
+ render(wrap(<PktRadioButton id="valg" value="a" label="Valg" />))
102
+
103
+ expect(input()).toHaveAttribute('type', 'radio')
104
+ expect(input()).toHaveAttribute('value', 'a')
105
+ expect(input()).toHaveAccessibleName('Valg')
106
+ })
107
+
108
+ it('is checked when checked is set', () => {
109
+ render(wrap(<PktRadioButton id="valg" value="a" label="Valg" checked onChange={() => {}} />))
110
+
111
+ expect(input()).toBeChecked()
112
+ })
113
+
114
+ it('starts checked with defaultChecked', () => {
115
+ render(wrap(<PktRadioButton id="valg" value="a" label="Valg" defaultChecked />))
116
+
117
+ expect(input()).toBeChecked()
118
+ })
119
+
120
+ it('calls its own onChange when the user selects it', () => {
121
+ const onChange = vi.fn()
122
+ render(wrap(<PktRadioButton id="valg" value="a" label="Valg" onChange={onChange} />))
123
+
124
+ fireEvent.click(input())
125
+
126
+ expect(onChange).toHaveBeenCalledTimes(1)
127
+ expect(input()).toBeChecked()
128
+ })
129
+
130
+ it('keeps its own name', () => {
131
+ render(wrap(<PktRadioButton id="valg" name="eget" value="a" label="Valg" />))
132
+
133
+ expect(input()).toHaveAttribute('name', 'eget')
134
+ })
135
+
136
+ it('adds the tile, error and size classes', () => {
137
+ const { container } = render(
138
+ wrap(<PktRadioButton id="valg" value="a" label="Valg" hasTile hasError inputSize="small" />),
139
+ )
140
+
141
+ expect(container.querySelector('.pkt-input-check')).toHaveClass('pkt-input-check--small')
142
+ expect(container.querySelector('.pkt-input-check__input')).toHaveClass('pkt-input-check__input--tile')
143
+ expect(input()).toHaveClass('pkt-input-check__input-checkbox--error')
144
+ })
145
+
146
+ it('is required when required is set', () => {
147
+ render(wrap(<PktRadioButton id="valg" value="a" label="Valg" required />))
148
+
149
+ expect(input()).toBeRequired()
150
+ expect(input().validity.valueMissing).toBe(true)
151
+ })
152
+
153
+ it('is disabled when disabled is set', () => {
154
+ render(wrap(<PktRadioButton id="valg" value="a" label="Valg" disabled />))
155
+
156
+ expect(input()).toBeDisabled()
157
+ })
158
+
159
+ it('has no axe violations', async () => {
160
+ const { container } = render(wrap(<PktRadioButton id="valg" value="a" label="Valg" />))
161
+
162
+ expect(await axe(container)).toHaveNoViolations()
163
+ })
164
+ })
@@ -1,12 +1,22 @@
1
- import { ChangeEventHandler, ForwardedRef, forwardRef, type InputHTMLAttributes, ReactElement, ReactNode } from 'react'
1
+ import {
2
+ ChangeEvent,
3
+ ChangeEventHandler,
4
+ ForwardedRef,
5
+ forwardRef,
6
+ type InputHTMLAttributes,
7
+ ReactElement,
8
+ ReactNode,
9
+ useEffect,
10
+ } from 'react'
2
11
  import { usePktStrings } from '../../hooks/usePktStrings'
3
12
  import { useGeneratedId } from '../../hooks/useGeneratedId'
4
13
  import type { IPktStringsProps } from 'shared-strings'
5
14
  import type { TPktInputSize } from 'shared-types'
15
+ import { useRadioGroupContext } from '../radiogroup/RadioGroupContext'
6
16
 
7
17
  export interface IPktRadioButton extends InputHTMLAttributes<HTMLInputElement>, IPktStringsProps<'forms'> {
8
18
  id: string
9
- name: string
19
+ name?: string
10
20
  label: string
11
21
  hasTile?: boolean
12
22
  inputSize?: TPktInputSize
@@ -46,6 +56,9 @@ export const PktRadioButton = forwardRef(
46
56
  requiredText,
47
57
  strings,
48
58
  tagText,
59
+ value,
60
+ required,
61
+ onChange,
49
62
  'aria-describedby': ariaDescribedbyProp,
50
63
  ...props
51
64
  }: IPktRadioButton,
@@ -53,26 +66,51 @@ export const PktRadioButton = forwardRef(
53
66
  ): ReactElement => {
54
67
  const s = usePktStrings(['forms'], strings)
55
68
  const id = useGeneratedId(idProp)
69
+ const group = useRadioGroupContext()
70
+ const optionValue = value ?? 'on'
71
+ const groupValue = group?.value
72
+ const groupControlled = groupValue !== undefined
73
+ const resolvedChecked = groupControlled ? groupValue === optionValue : checked
74
+ const resolvedDefaultChecked =
75
+ defaultChecked ?? (group?.defaultValue !== undefined ? group.defaultValue === optionValue : undefined)
76
+ const tile = hasTile || !!group?.hasTile
77
+ const error = hasError || !!group?.hasError
78
+ const isDisabled = disabled || !!group?.disabled
79
+
80
+ useEffect(() => {
81
+ if (groupControlled && checked !== undefined) {
82
+ // eslint-disable-next-line no-console
83
+ console.warn(
84
+ `PktRadioButton (${id}): checked ignoreres når PktRadioGroup har value. Styr valget med value på gruppen.`,
85
+ )
86
+ }
87
+ }, [groupControlled, checked, id])
88
+
89
+ const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
90
+ onChange?.(event)
91
+ group?.onOptionChange(event)
92
+ }
93
+
56
94
  const classes = [className, 'pkt-input-check', inputSize ? `pkt-input-check--${inputSize}` : '']
57
95
  .filter(Boolean)
58
96
  .join(' ')
59
97
 
60
98
  const inputTileClasses = [
61
99
  'pkt-input-check__input',
62
- hasTile ? 'pkt-input-check__input--tile' : '',
63
- disabled && hasTile ? 'pkt-input-check__input--tile-disabled' : '',
100
+ tile ? 'pkt-input-check__input--tile' : '',
101
+ isDisabled && tile ? 'pkt-input-check__input--tile-disabled' : '',
64
102
  ]
65
103
  .filter(Boolean)
66
104
  .join(' ')
67
105
 
68
106
  const inputCheckBoxClasses = [
69
107
  'pkt-input-check__input-checkbox',
70
- hasError ? 'pkt-input-check__input-checkbox--error' : '',
108
+ error ? 'pkt-input-check__input-checkbox--error' : '',
71
109
  ]
72
110
  .filter(Boolean)
73
111
  .join(' ')
74
112
 
75
- const labelClasses = ['pkt-input-check__input-label', disabled ? 'pkt-input-check__input-label--disabled' : '']
113
+ const labelClasses = ['pkt-input-check__input-label', isDisabled ? 'pkt-input-check__input-label--disabled' : '']
76
114
  .filter(Boolean)
77
115
  .join(' ')
78
116
 
@@ -102,12 +140,17 @@ export const PktRadioButton = forwardRef(
102
140
  ref={ref}
103
141
  id={id}
104
142
  type="radio"
105
- name={name}
106
- disabled={disabled}
143
+ name={name ?? group?.name}
144
+ value={value}
145
+ required={required || group?.required || undefined}
146
+ disabled={isDisabled}
107
147
  className={inputCheckBoxClasses}
108
148
  aria-labelledby={label ? labelId : undefined}
109
149
  aria-describedby={describedBy}
110
- {...(checked !== undefined ? { checked } : { defaultChecked })}
150
+ {...(resolvedChecked !== undefined
151
+ ? { checked: resolvedChecked }
152
+ : { defaultChecked: resolvedDefaultChecked })}
153
+ onChange={group ? handleChange : onChange}
111
154
  {...props}
112
155
  />
113
156
  <label className={labelClasses} htmlFor={id}>
@@ -0,0 +1,145 @@
1
+ import '@testing-library/jest-dom'
2
+
3
+ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
4
+ import { type ReactNode } from 'react'
5
+ import { Controller, useForm, type UseFormReturn } from 'react-hook-form'
6
+ import { vi } from 'vitest'
7
+
8
+ import { PktRadioButton } from '../radio/RadioButton'
9
+ import { PktRadioGroup } from './RadioGroup'
10
+
11
+ type TValues = { reise: string }
12
+
13
+ const radio = (id: string) => document.getElementById(id) as HTMLInputElement
14
+
15
+ const options = (extra: object = {}) => (
16
+ <>
17
+ <PktRadioButton id="buss" value="buss" label="Buss" {...extra} />
18
+ <PktRadioButton id="tog" value="tog" label="Tog" {...extra} />
19
+ </>
20
+ )
21
+
22
+ const renderForm = (fields: (form: UseFormReturn<TValues>) => ReactNode) => {
23
+ const onSubmit = vi.fn()
24
+ let form!: UseFormReturn<TValues>
25
+ const Form = () => {
26
+ form = useForm<TValues>({ defaultValues: { reise: '' } })
27
+ return (
28
+ <form onSubmit={form.handleSubmit(onSubmit)}>
29
+ {fields(form)}
30
+ <button type="submit">Send</button>
31
+ </form>
32
+ )
33
+ }
34
+ render(<Form />)
35
+ return { form: () => form, onSubmit }
36
+ }
37
+
38
+ const patterns: Array<[string, (form: UseFormReturn<TValues>) => ReactNode]> = [
39
+ [
40
+ 'register on the group',
41
+ (form) => (
42
+ <PktRadioGroup label="Reisemåte" {...form.register('reise', { required: true })}>
43
+ {options()}
44
+ </PktRadioGroup>
45
+ ),
46
+ ],
47
+ [
48
+ 'Controller with the field spread on the group',
49
+ (form) => (
50
+ <Controller
51
+ name="reise"
52
+ control={form.control}
53
+ rules={{ required: true }}
54
+ render={({ field }) => (
55
+ <PktRadioGroup label="Reisemåte" {...field}>
56
+ {options()}
57
+ </PktRadioGroup>
58
+ )}
59
+ />
60
+ ),
61
+ ],
62
+ [
63
+ 'Controller with onValueChange',
64
+ (form) => (
65
+ <Controller
66
+ name="reise"
67
+ control={form.control}
68
+ rules={{ required: true }}
69
+ render={({ field }) => (
70
+ <PktRadioGroup
71
+ label="Reisemåte"
72
+ name={field.name}
73
+ value={field.value}
74
+ onValueChange={field.onChange}
75
+ onBlur={field.onBlur}
76
+ ref={field.ref}
77
+ >
78
+ {options()}
79
+ </PktRadioGroup>
80
+ )}
81
+ />
82
+ ),
83
+ ],
84
+ [
85
+ 'register on each radio',
86
+ (form) => <PktRadioGroup label="Reisemåte">{options(form.register('reise', { required: true }))}</PktRadioGroup>,
87
+ ],
88
+ ]
89
+
90
+ describe.each(patterns)('PktRadioGroup with React Hook Form: %s', (_, fields) => {
91
+ it('tracks the value the user selects', () => {
92
+ const { form } = renderForm(fields)
93
+
94
+ fireEvent.click(radio('tog'))
95
+
96
+ expect(form().getValues('reise')).toBe('tog')
97
+ })
98
+
99
+ it('shows a value set with setValue and clears it with reset', async () => {
100
+ const { form } = renderForm(fields)
101
+
102
+ await act(async () => form().setValue('reise', 'buss'))
103
+ expect(radio('buss')).toBeChecked()
104
+ expect(form().getValues('reise')).toBe('buss')
105
+
106
+ await act(async () => form().reset({ reise: '' }))
107
+ expect(radio('buss')).not.toBeChecked()
108
+ expect(form().getValues('reise')).toBe('')
109
+ })
110
+
111
+ it('blocks submit while required and empty, and submits the selected value', async () => {
112
+ const { onSubmit } = renderForm(fields)
113
+
114
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }))
115
+ await waitFor(() => expect(radio('buss')).toHaveFocus())
116
+ expect(onSubmit).not.toHaveBeenCalled()
117
+
118
+ fireEvent.click(radio('tog'))
119
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }))
120
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1))
121
+ expect(onSubmit.mock.calls[0][0]).toEqual({ reise: 'tog' })
122
+ })
123
+ })
124
+
125
+ describe('PktRadioGroup with a handler that reads event.target', () => {
126
+ it('gives the group name and value, as form libraries such as Formik expect', () => {
127
+ const values: Record<string, unknown> = {}
128
+ render(
129
+ <PktRadioGroup
130
+ name="reise"
131
+ label="Reisemåte"
132
+ onChange={(event) => {
133
+ const { name, value, type } = event.target as unknown as { name: string; value: string; type?: string }
134
+ values[name] = type === 'checkbox' ? undefined : value
135
+ }}
136
+ >
137
+ {options()}
138
+ </PktRadioGroup>,
139
+ )
140
+
141
+ fireEvent.click(radio('buss'))
142
+
143
+ expect(values).toEqual({ reise: 'buss' })
144
+ })
145
+ })