@govuk-react/primitives 0.2.1 → 0.3.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 (89) hide show
  1. package/README.md +100 -25
  2. package/dist/accordion/element.d.ts +3 -0
  3. package/dist/accordion/element.js.map +1 -1
  4. package/dist/accordion/index.d.ts +3 -7
  5. package/dist/accordion/index.js +35 -33
  6. package/dist/accordion/index.js.map +1 -1
  7. package/dist/auto-focus/index.d.ts +3 -285
  8. package/dist/auto-focus/index.js +13 -3
  9. package/dist/auto-focus/index.js.map +1 -1
  10. package/dist/autocomplete/element.d.ts +7 -4
  11. package/dist/autocomplete/element.js +11 -11
  12. package/dist/autocomplete/element.js.map +1 -1
  13. package/dist/autocomplete/index.d.ts +7 -7
  14. package/dist/autocomplete/index.js +17 -25
  15. package/dist/autocomplete/index.js.map +1 -1
  16. package/dist/character-count/element.d.ts +5 -0
  17. package/dist/character-count/element.js +5 -5
  18. package/dist/character-count/element.js.map +1 -1
  19. package/dist/character-count/index.d.ts +7 -7
  20. package/dist/character-count/index.js +13 -13
  21. package/dist/character-count/index.js.map +1 -1
  22. package/dist/character-count/messages.d.ts +1 -1
  23. package/dist/character-count/messages.js +13 -13
  24. package/dist/character-count/messages.js.map +1 -1
  25. package/dist/choices/element.d.ts +5 -0
  26. package/dist/choices/element.js +6 -31
  27. package/dist/choices/element.js.map +1 -1
  28. package/dist/disclosure/element.d.ts +3 -0
  29. package/dist/disclosure/element.js +21 -12
  30. package/dist/disclosure/element.js.map +1 -1
  31. package/dist/disclosure/index.d.ts +6 -5
  32. package/dist/disclosure/index.js +21 -11
  33. package/dist/disclosure/index.js.map +1 -1
  34. package/dist/exit-this-page/element.d.ts +1 -1
  35. package/dist/exit-this-page/element.js +20 -21
  36. package/dist/exit-this-page/element.js.map +1 -1
  37. package/dist/exit-this-page/index.d.ts +11 -11
  38. package/dist/exit-this-page/index.js +7 -7
  39. package/dist/exit-this-page/index.js.map +1 -1
  40. package/dist/file-upload/element.d.ts +11 -6
  41. package/dist/file-upload/element.js +15 -15
  42. package/dist/file-upload/element.js.map +1 -1
  43. package/dist/file-upload/index.d.ts +9 -9
  44. package/dist/file-upload/index.js +11 -11
  45. package/dist/file-upload/index.js.map +1 -1
  46. package/dist/inline/accordion-element.js +1 -1
  47. package/dist/inline/auto-focus-element.js +1 -1
  48. package/dist/inline/autocomplete-element.js +1 -1
  49. package/dist/inline/character-count-element.js +1 -1
  50. package/dist/inline/choices-element.js +1 -1
  51. package/dist/inline/disclosure-element.js +1 -1
  52. package/dist/inline/exit-this-page-element.js +1 -1
  53. package/dist/inline/file-upload-element.js +1 -1
  54. package/dist/inline/focus-links-element.js +1 -1
  55. package/dist/inline/modal-element.js +1 -1
  56. package/dist/inline/password-input-element.js +1 -1
  57. package/dist/inline/tabs-element.js +1 -1
  58. package/dist/inline-script/index.js +12 -12
  59. package/dist/modal/element.js +126 -11
  60. package/dist/modal/element.js.map +1 -1
  61. package/dist/modal/index.d.ts +8 -3
  62. package/dist/modal/index.js +56 -20
  63. package/dist/modal/index.js.map +1 -1
  64. package/dist/password-input/element.js +27 -11
  65. package/dist/password-input/element.js.map +1 -1
  66. package/dist/password-input/index.d.ts +3 -3
  67. package/dist/password-input/index.js +4 -2
  68. package/dist/password-input/index.js.map +1 -1
  69. package/dist/styles.css +11 -0
  70. package/dist/tabs/element.d.ts +3 -0
  71. package/dist/tabs/element.js +17 -10
  72. package/dist/tabs/element.js.map +1 -1
  73. package/dist/tabs/index.d.ts +9 -18
  74. package/dist/tabs/index.js +48 -44
  75. package/dist/tabs/index.js.map +1 -1
  76. package/dist/utils/change-details.d.ts +11 -0
  77. package/dist/utils/change-details.js +3 -0
  78. package/dist/utils/change-details.js.map +1 -0
  79. package/dist/utils/on-property-change.d.ts +7 -0
  80. package/dist/utils/on-property-change.js +19 -0
  81. package/dist/utils/on-property-change.js.map +1 -0
  82. package/dist/utils/set-focus.js.map +1 -1
  83. package/dist/utils/slot.d.ts +5 -3
  84. package/dist/utils/slot.js +24 -2
  85. package/dist/utils/slot.js.map +1 -1
  86. package/package.json +8 -2
  87. package/dist/utils/on-property-set.d.ts +0 -9
  88. package/dist/utils/on-property-set.js +0 -38
  89. package/dist/utils/on-property-set.js.map +0 -1
package/README.md CHANGED
@@ -1,17 +1,73 @@
1
1
  # @govuk-react/primitives
2
2
 
3
- Headless behaviour for design system components, as light-DOM custom elements with unstyled React parts over them. It ships no styles and no GOV.UK markup, so any library can use it. govuk-react's components are the reference implementation, built with govuk-frontend-react's markup.
3
+ Headless behaviour for design system components, as light-DOM custom elements with unstyled React parts over them. It sets no look and ships no GOV.UK markup, so any library can use it. govuk-react's components are the reference implementation, built with govuk-frontend-react's markup.
4
4
 
5
5
  Each primitive:
6
6
 
7
7
  - works without JavaScript, through a fallback you choose
8
8
  - upgrades to the full WAI-ARIA pattern when its custom element is defined, with or without React
9
- - adds React state (`value`, `defaultValue`, `onValueChange`) once hydrated
10
- - takes `asChild` on every part, so you render your own elements
9
+ - adds React props for its state once hydrated, where it has any, such as `value` and `onValueChange`, or `open` and `onOpenChange`
10
+ - takes `asChild` on its parts, so you render your own elements. A `Root` is the custom element, except Button's
11
+ - names its parts and props alike: the control that operates it is `Trigger`, and a text prop ends in `Text` when it's shown, `Label` when it's an accessible name and `Announcement` when only screen readers hear it
12
+
13
+ Import each primitive from its own path, such as `@govuk-react/primitives/tabs`. Each path defines its element when imported.
14
+
15
+ ## Controlled state
16
+
17
+ Prefer uncontrolled: leave out `value` and `open`, start from `defaultValue` or `defaultOpen` where there is one, and listen with `onValueChange` or `onOpenChange`. The markup then holds the state, so it's the same before hydration, without React and without JavaScript.
18
+
19
+ Control a primitive only when your app has to set its state, such as closing a menu after navigating. When controlled, a user's action calls the change handler and the primitive changes only when the prop does. That has limits that can't be removed:
20
+
21
+ - A controlled prop applies once React has hydrated. Until then the primitive is uncontrolled, so it still works, and what the user did by then is reported through the change handler rather than undone. If your handler doesn't adopt it, the primitive goes back to the prop.
22
+ - Without JavaScript, a controlled prop does nothing.
23
+ - Each change waits for React to render, where an uncontrolled one happens in the browser straight away.
24
+ - A browser doesn't let a page cancel a script calling `close()` on a dialog, nor a script calling `showModal()` before it fired `beforetoggle` on dialogs (Chrome 132, Firefox 133 and Safari 26). A controlled Modal reports such a change through `onOpenChange` and, unless `open` changes within 100ms, puts the dialog back as `open` says. So it always ends up matching `open`, but the user can see it change and change back.
25
+
26
+ ### Changes made before hydration
27
+
28
+ `onValueChange` and `onOpenChange` on Tabs, Accordion, Disclosure and Modal get a second argument, `{ beforeHydration }`. It's `true` for a change the user made before React hydrated, which is reported once React has hydrated, whether or not the primitive is controlled.
29
+
30
+ Such a report differs from a live change:
31
+
32
+ - It's the state the user left, not each step. Three tabs picked before hydration are reported as one change, to the last.
33
+ - It doesn't happen as the user acts, so a handler that navigates, fetches or logs runs at hydration.
34
+ - Several primitives report in the order React runs their effects, not the order the user used them.
35
+
36
+ So where one primitive's handler changes another's state, or has side effects, check the argument and decide what a late report should do:
37
+
38
+ ```tsx
39
+ <Tabs.Root
40
+ value={tab}
41
+ onValueChange={(value, { beforeHydration }) => {
42
+ if (beforeHydration) return;
43
+ setTab(value);
44
+ }}
45
+ >
46
+ ```
47
+
48
+ Returning without changing `value` puts the tabs back to `value`.
49
+
50
+ ## Styles
51
+
52
+ Two fallbacks need a CSS rule each, which only set `display`: the Tabs radios fallback and the Accordion. Load the package's stylesheet once, or copy its rules into your own:
53
+
54
+ ```ts
55
+ import '@govuk-react/primitives/styles.css';
56
+ ```
57
+
58
+ No part renders a `style` element or attribute, so the primitives work under a strict Content Security Policy.
59
+
60
+ ## Without React
61
+
62
+ Each element is also exported on its own, with no React, from `@govuk-react/primitives/<name>-element`, such as `tabs-element`. Importing it defines the element, such as `<govuk-react-tabs>`. Render the same markup as the React parts do: the element finds its parts by `data-` attributes, takes its options as attributes, and reports changes with bubbling events named after it, such as `govuk-react-tabs:change`. The comment at the top of each element's source lists its markup, attributes and events:
63
+
64
+ [accordion](src/accordion/element.ts), [auto-focus](src/auto-focus/element.ts), [autocomplete](src/autocomplete/element.ts), [button](src/button/element.ts), [character-count](src/character-count/element.ts), [choices](src/choices/element.ts), [disclosure](src/disclosure/element.ts), [exit-this-page](src/exit-this-page/element.ts), [file-upload](src/file-upload/element.ts), [focus-links](src/focus-links/element.ts), [modal](src/modal/element.ts), [password-input](src/password-input/element.ts) and [tabs](src/tabs/element.ts).
65
+
66
+ Each element that changes how its markup shows sets `data-upgraded` on itself once upgraded, to style it apart from its fallback.
11
67
 
12
68
  ## Inline scripts
13
69
 
14
- Each element is also built as a small, self-contained classic script, with no imports and no React, at `@govuk-react/primitives/inline/<name>-element.js`, such as `inline/tabs-element.js`. Inline the ones your page uses, so the markup is interactive as soon as it loads, before React has downloaded and hydrated. React's parts then pick up from the elements, including anything the user did before hydration. Each element is defined only once, whichever runs first: the inline script or React's bundle.
70
+ Each element is also built as a small, self-contained classic script, with no imports and no React, at `@govuk-react/primitives/inline/<name>-element.js`, such as `inline/tabs-element.js`. Inline the ones your page uses, so the markup is interactive as soon as it loads, before React has downloaded and hydrated. React's parts then pick up from the elements, including anything the user did before hydration. Each element is defined only once, whichever runs first: the inline script or React's bundle. So inline the scripts from the same version of this package as the one in your bundle.
15
71
 
16
72
  To render them from React on the server, `inline-script` has each script as a string, and an `InlineScript` component:
17
73
 
@@ -48,7 +104,7 @@ import * as Accordion from '@govuk-react/primitives/accordion';
48
104
  </Accordion.Root>;
49
105
  ```
50
106
 
51
- Without JavaScript every section is shown under its `Fallback` heading. Each section also renders a hidden `Trigger` with the same heading, which the element shows on upgrade while hiding the fallback. Nothing is moved, so React can keep rendering the markup. Closed content gets `hidden="until-found"`, so find in page opens it. `Label`s name the trigger, followed by "Show this section" or "Hide this section".
107
+ Without JavaScript every section is shown under its `Fallback` heading. It needs the package's [stylesheet](#styles). Each section also renders a hidden `Trigger` with the same heading, which the element shows on upgrade while hiding the fallback. Nothing is moved, so React can keep rendering the markup. Closed content gets `hidden="until-found"`, so find in page opens it. `Label`s name the trigger, followed by "Show this section" or "Hide this section".
52
108
 
53
109
  `ShowAll` opens every section, or closes them all when every one is open. `value` and `onValueChange` control the open sections once hydrated, and a section opened before hydration is reported rather than undone. As in govuk-frontend, open sections are remembered for the session by content id, unless `rememberExpanded` is `false`. In an island without a `Root`, pass `defaultExpanded` to `Section`.
54
110
 
@@ -72,21 +128,23 @@ Each panel holds a hidden radio, and the radio group is the source of truth, as
72
128
  The root sets how the tabs work without JavaScript, and its parts match it:
73
129
 
74
130
  - `Root`, with `Trigger` and `Content`: each tab links to its panel, and every panel shows.
75
- - `RadiosRoot`, with `RadioTrigger` and `RadioContent`: each tab is a label for a hidden radio in its panel, so tabs switch with no JavaScript when clicked. It needs `defaultValue` or `value`. Without JavaScript the labels can't be reached by keyboard, as in the reference. Pass `name` when tabs render in separate React roots, such as islands. `RadiosRoot` adds the fallback's CSS inline; under a strict CSP, add `radiosFallbackCss` to a stylesheet instead.
131
+ - `RadiosRoot`, with `RadiosTrigger` and `RadiosContent`: each tab is a label for a hidden radio in its panel, so tabs switch with no JavaScript when clicked. It needs `defaultValue` or `value`. Without JavaScript the labels can't be reached by keyboard, as in the reference. Pass `name` when tabs render in separate React roots, such as islands. It needs the package's [stylesheet](#styles).
76
132
 
77
133
  They are separate components rather than a prop, because a prop can change after the first render, and the markup each needs can't.
78
134
 
79
- When controlled with `value`, a user's choice calls `onValueChange` and the tab changes only when `value` does. `preHydration` sets what happens to a tab the user picked before React hydrated: `"ignore"` (the default) keeps `value`, `"report"` calls `onValueChange` with it. When uncontrolled, the pick is always reported.
135
+ When controlled with `value`, a user's choice calls `onValueChange` and the tab changes only when `value` does. `value` applies once hydrated, so tabs still switch before then, and a tab picked before hydration is reported through `onValueChange` rather than undone.
80
136
 
81
137
  `orientation` (`"horizontal"` or `"vertical"`) sets the axis of the arrow keys.
82
138
 
83
- `media` limits the tab behaviour to a media query. Below it, `Root`'s tabs are a list of links to panels, and `RadiosRoot`'s keep switching through their radios. With `Root`, the URL hash follows the selected tab, as in govuk-frontend.
139
+ `media` limits the tab behaviour to a media query, and can change. Below it, `Root`'s tabs are a list of links to panels, and `RadiosRoot`'s keep switching through their radios. With `Root`, the URL hash follows the selected tab, as in govuk-frontend.
140
+
141
+ Each `value` is also its panel's `id`, and its tab links to it, so it must be unique on the page and valid as an id. For another id, pass `id` to the panel and the matching `href` to its `Trigger`.
84
142
 
85
143
  In an island without a root, pass `name` and `defaultSelected` to the triggers and panels. `upgradedClass`, `activeItemClass` and `hiddenContentClass` add classes for styles that key off classes rather than `data-state`, `aria-selected` and `hidden`.
86
144
 
87
- Without React, use the `<govuk-react-tabs>` element from `@govuk-react/primitives/tabs-element` with the same markup, including a hidden radio as the first child of each panel. Listen for its `govuk-react-tabs:change` event. See [the element's source](src/tabs/element.ts) for its attributes.
145
+ Without React, the markup includes a hidden radio as the first child of each panel.
88
146
 
89
- It follows the Tabs reference in [react-design-system-apis](https://github.com/penx/react-design-system-apis). Browser tests in `packages/primitives-e2e` cover it without JavaScript, upgraded without React, hydrated, before hydration, controlled, nested, in islands and rendered only on the client.
147
+ It follows the Tabs reference in [react-design-system-apis](https://github.com/penx/react-design-system-apis).
90
148
 
91
149
  ## Disclosure
92
150
 
@@ -95,7 +153,7 @@ import * as Disclosure from '@govuk-react/primitives/disclosure';
95
153
 
96
154
  <nav aria-label="Menu">
97
155
  <Disclosure.Root media="(min-width: 40.0625em)">
98
- <Disclosure.Toggle>Menu</Disclosure.Toggle>
156
+ <Disclosure.Trigger>Menu</Disclosure.Trigger>
99
157
  <Disclosure.Content asChild>
100
158
  <ul id="navigation">…</ul>
101
159
  </Disclosure.Content>
@@ -125,7 +183,7 @@ import * as Modal from '@govuk-react/primitives/modal';
125
183
 
126
184
  `Title` names the dialog, so always include one, or pass `aria-label` to `Content`. Pass `closedby="any"` to `Content` to also close it when the user clicks outside it.
127
185
 
128
- `open` and `onOpenChange` control the dialog once hydrated. In an island without a `Root`, pass `dialogId` to `Trigger` and `Close`, and `id` and `aria-labelledby` to `Content`.
186
+ `open` and `onOpenChange` control the dialog once hydrated: `Trigger`, `Close` and Escape then call `onOpenChange`, and the dialog changes only when `open` does. See [Controlled state](#controlled-state) for its limits. In an island without a `Root`, pass `dialogId` to `Trigger` and `Close`, and `id` and `aria-labelledby` to `Content`.
129
187
 
130
188
  ## Character count
131
189
 
@@ -161,12 +219,12 @@ import * as Autocomplete from '@govuk-react/primitives/autocomplete';
161
219
  ))}
162
220
  <Autocomplete.NoResults />
163
221
  </Autocomplete.Listbox>
164
- <Autocomplete.Status />
222
+ <Autocomplete.Status className="visually-hidden" />
165
223
  <Autocomplete.AssistiveHint />
166
224
  </Autocomplete.Root>;
167
225
  ```
168
226
 
169
- A port of GOV.UK's [accessible-autocomplete](https://github.com/alphagov/accessible-autocomplete) that enhances your own input. Without JavaScript the input is a plain input. On upgrade it's a combobox with accessible-autocomplete's behaviour: options that match the query show in the `Listbox`, Up and Down move focus through them, Enter, Space or a click confirms one, and Escape closes the menu. `Status` tells screen readers how many options there are once the user pauses, and `AssistiveHint` describes the input while the query is empty.
227
+ A port of GOV.UK's [accessible-autocomplete](https://github.com/alphagov/accessible-autocomplete) that enhances your own input. Without JavaScript the input is a plain input. On upgrade it's a combobox with accessible-autocomplete's behaviour: options that match the query show in the `Listbox`, Up and Down move focus through them, Enter, Space or a click confirms one, and Escape closes the menu. `Status` tells screen readers how many options there are once the user pauses, so hide it visually with your own class, and `AssistiveHint` describes the input while the query is empty.
170
228
 
171
229
  The input's value is the query, and the options are whatever you render, so there is nothing else to control. `onQueryChange` is called when options are due, such as to fetch them, including for a query typed before hydration. `filter` sets which options match the query: "contains" (the default), "starts-with", or "none" for options that already match, such as results from a server. Leave out `NoResults` to show nothing when no option matches.
172
230
 
@@ -184,20 +242,20 @@ import * as FileUpload from '@govuk-react/primitives/file-upload';
184
242
  <label id="photo-label" htmlFor="photo">Upload a photo</label>
185
243
  <FileUpload.Root>
186
244
  <FileUpload.DropZone>
187
- <FileUpload.Button>
245
+ <FileUpload.Trigger>
188
246
  <FileUpload.Status />
189
247
  <FileUpload.Separator className="visually-hidden" />
190
248
  Choose file or drop file
191
- </FileUpload.Button>
249
+ </FileUpload.Trigger>
192
250
  <FileUpload.Input id="photo" name="photo" />
193
251
  </FileUpload.DropZone>
194
252
  <FileUpload.Announcements className="visually-hidden" />
195
253
  </FileUpload.Root>;
196
254
  ```
197
255
 
198
- Without JavaScript the native file input is shown and the `Button` is hidden. On upgrade the element hides the input and shows the button, which opens the file picker, takes files dropped on it, and says in `Status` which files are chosen. As in govuk-frontend, the button takes the input's `id` (the input's gets `-input` added), so the input's label names it, along with its `aria-describedby` and `disabled`. Give the label an id: without one the element adds it, which React warns about when it hydrates. `Announcements` tells screen readers when files are dragged into and out of the `DropZone`.
256
+ Without JavaScript the native file input is shown and the `Trigger` is hidden. On upgrade the element hides the input and shows the button, which opens the file picker, takes files dropped on it, and says in `Status` which files are chosen. As in govuk-frontend, the button takes the input's `id` (the input's gets `-input` added), so the input's label names it, along with its `aria-describedby` and `disabled`. Give the label an id: without one the element adds it, which React warns about when it hydrates. `Announcements` tells screen readers when files are dragged into and out of the `DropZone`.
199
257
 
200
- The input's files are the state, so there is nothing to control. Dropped files fire bubbling `input` and `change` events, so React's `onChange` hears them. The text is English by default, and `multipleFilesChosen` takes a message for each plural form. The button gets `data-empty` and `data-dragging`, and the drop zone `data-disabled`, for styling, or pass class names such as `emptyClass`.
258
+ The input's files are the state, so there is nothing to control. Dropped files fire bubbling `input` and `change` events, so React's `onChange` hears them. The text is English by default, and `multipleFilesChosenText` takes a message for each plural form. The button gets `data-empty` and `data-dragging`, and the drop zone `data-disabled`, for styling, or pass class names such as `emptyClass`.
201
259
 
202
260
  ## Choices
203
261
 
@@ -213,7 +271,24 @@ import * as Choices from '@govuk-react/primitives/choices';
213
271
 
214
272
  For a group of radios or checkboxes. Without JavaScript every `Conditional` is shown. On upgrade, each one shows only while the choice that `controls` it is checked, and that choice gets `aria-controls` and `aria-expanded`. A checkbox with `exclusive`, such as "None of these", unchecks the other checkboxes with its name when checked, and is unchecked when one of them is. They're unchecked with `click()`, so `change` events fire and controlled React inputs hear about it. Control the inputs as usual, with `checked` and `onChange`.
215
273
 
216
- ## AutoFocus
274
+ ## Password input
275
+
276
+ ```tsx
277
+ import * as PasswordInput from '@govuk-react/primitives/password-input';
278
+
279
+ <label htmlFor="password">Password</label>
280
+ <PasswordInput.Root>
281
+ <PasswordInput.Input id="password" name="password" autoComplete="current-password" />
282
+ <PasswordInput.Trigger />
283
+ <PasswordInput.Status className="visually-hidden" />
284
+ </PasswordInput.Root>;
285
+ ```
286
+
287
+ Without JavaScript the field is a plain password field and the `Trigger` is hidden. On upgrade the element shows the button, which switches the input between `type="password"` and `type="text"`, sets its own text ("Show" or "Hide") and accessible name ("Show password" or "Hide password"), and announces the change in `Status`. Leave out `Status` and the element adds a visually hidden one after the input.
288
+
289
+ The input's `type` is the state, kept when React renders the input again, so there is nothing to control. As in govuk-frontend, the password is hidden again when its form is submitted and when the page is restored from the back-forward cache. The text is English by default: pass `showText`, `hideText`, `showLabel`, `hideLabel`, `shownAnnouncement` and `hiddenAnnouncement` to `Root`.
290
+
291
+ ## Auto focus
217
292
 
218
293
  ```tsx
219
294
  import * as AutoFocus from '@govuk-react/primitives/auto-focus';
@@ -223,9 +298,9 @@ import * as AutoFocus from '@govuk-react/primitives/auto-focus';
223
298
  </AutoFocus.Root>;
224
299
  ```
225
300
 
226
- Moves focus to `Target` when it appears, such as an error summary after a form is submitted. The server renders the target with `tabindex="-1"` and `autofocus`, so the browser focuses it when the page loads, even without JavaScript. As in govuk-frontend, the target loses its `tabindex` once focus moves on. Pass `disabled` to both parts to leave focus alone.
301
+ Moves focus to `Target` when it appears, such as an error summary after a form is submitted. The server renders the target with `tabindex="-1"` and `autofocus`, so the browser focuses it when the page loads, even without JavaScript. As in govuk-frontend, the target loses its `tabindex` once focus moves on. Pass `disabled` to `Root` to leave focus alone, or to `Target` in an island without a `Root`.
227
302
 
228
- ## FocusLinks
303
+ ## Focus links
229
304
 
230
305
  ```tsx
231
306
  import * as FocusLinks from '@govuk-react/primitives/focus-links';
@@ -251,9 +326,9 @@ import * as Button from '@govuk-react/primitives/button';
251
326
  </Button.Root>;
252
327
  ```
253
328
 
254
- With `preventDoubleClick`, a second click within a second of the first is ignored, so a form isn't submitted twice. The click is stopped before React hears it, so `onClick` doesn't run twice either. Space activates a link with `role="button"`, as it does a button. Unlike the other primitives there's no wrapper element, which would change a button group's layout: importing the module adds one click and one keydown listener to the document, for any element marked by `Root`. Without React, import `@govuk-react/primitives/button-element` and mark buttons with `data-button`.
329
+ With `preventDoubleClick`, a second click within a second of the first is ignored, so a form isn't submitted twice. The click is stopped before React hears it, so `onClick` doesn't run twice either. Space activates a link with `role="button"`, as it does a button. Unlike the other primitives there's no wrapper element, which would change a button group's layout: importing the module adds one click and one keydown listener to the document, for any element marked by `Root`. Without React, mark buttons with `data-button`.
255
330
 
256
- ## ExitThisPage
331
+ ## Exit this page
257
332
 
258
333
  ```tsx
259
334
  import * as ExitThisPage from '@govuk-react/primitives/exit-this-page';
@@ -261,10 +336,10 @@ import * as ExitThisPage from '@govuk-react/primitives/exit-this-page';
261
336
  <ExitThisPage.SkipLink href="https://www.bbc.co.uk/weather">Exit this page</ExitThisPage.SkipLink>;
262
337
 
263
338
  <ExitThisPage.Root hideContentClass="hide-content" overlayClass="overlay">
264
- <ExitThisPage.Button href="https://www.bbc.co.uk/weather">
339
+ <ExitThisPage.Trigger href="https://www.bbc.co.uk/weather">
265
340
  Exit this page
266
341
  <ExitThisPage.Indicator />
267
- </ExitThisPage.Button>
342
+ </ExitThisPage.Trigger>
268
343
  <ExitThisPage.Status className="visually-hidden" />
269
344
  </ExitThisPage.Root>;
270
345
  ```
@@ -1,4 +1,7 @@
1
1
  declare global {
2
+ interface HTMLElementTagNameMap {
3
+ 'govuk-react-accordion': AccordionElement;
4
+ }
2
5
  interface HTMLElementEventMap {
3
6
  'govuk-react-accordion:change': CustomE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C,OAAO,EAAE,mBAAmB,CAAC,CAAC;AACxF,CAAC","sourcesContent":["/*\n * <govuk-react-accordion>: a headless, light-DOM custom element that lets users show and hide\n * sections of content, with or without React.\n *\n * Without JavaScript every section is shown, under a plain heading. Each section also holds a\n * hidden button with the same heading. On upgrade the element shows the buttons and hides the\n * plain headings, then each button shows and hides its section's content, and a \"show all\"\n * button shows or hides every section. The rendered markup is never moved, so React can keep\n * rendering it. Content is hidden with `hidden=\"until-found\"`, so find in page still opens it.\n *\n * Markup inside the element:\n * - `[data-accordion-controls]` (optional): holds the \"show all\" button. Rendered `hidden`.\n * - `button[data-accordion-show-all]`, with a `[data-accordion-show-all-text]` for its text.\n * - `[data-accordion-section][data-value]`: a section. `data-expanded` opens it at first.\n * - `[data-accordion-fallback]`: the plain heading and summary, hidden on upgrade.\n * - `button[data-accordion-trigger]`: rendered `hidden`. Its accessible name is the text of its\n * `[data-accordion-label]` elements and the show or hide label. Its\n * `[data-accordion-toggle-text]` shows the show or hide text.\n * - `[data-accordion-content]`: the content, with an id.\n * - `[data-accordion-icon]` (optional): in the buttons, given `collapsed-icon-class` while\n * collapsed.\n *\n * Attributes:\n * - `value`: the open sections' values, separated by spaces, to control them. A user's click only\n * fires the change event, and the sections change when `value` does.\n * - `default-value`: the sections open at first, instead of `data-expanded`.\n * - `remember-expanded`: \"false\" stops the open sections being remembered in session storage,\n * keyed by content id, as govuk-frontend does.\n * - `show-section-text`, `hide-section-text`, `show-section-label`, `hide-section-label`,\n * `show-all-sections-text`, `hide-all-sections-text`: the text, English by default.\n * - `upgraded-class`, `expanded-section-class`, `collapsed-icon-class`: classes to add, for styles\n * keyed off classes rather than `data-upgraded`, `data-state` and `aria-expanded`.\n *\n * A user's click fires a bubbling `govuk-react-accordion:change` event with `{ value }`, the open\n * sections' values.\n */\n\nimport { classesOf, setText } from '../utils/dom.js';\n\ndeclare global {\n interface HTMLElementEventMap {\n 'govuk-react-accordion:change': CustomEvent<{ value: string[] }>;\n }\n}\n\nexport const tagName = 'govuk-react-accordion';\n\nexport interface AccordionElement extends HTMLElement {\n /** The open sections' values, once upgraded. */\n readonly openValues: string[] | undefined;\n /** The open sections after the user's last change before `value` was first set, such as before React hydrated. */\n readonly pickedValue: string[] | undefined;\n}\n\nconst defaults = {\n 'show-section-text': 'Show',\n 'hide-section-text': 'Hide',\n 'show-section-label': 'Show this section',\n 'hide-section-label': 'Hide this section',\n 'show-all-sections-text': 'Show all sections',\n 'hide-all-sections-text': 'Hide all sections',\n};\n\nconst valuesOf = (attribute: string | null) => attribute?.split(/\\s+/).filter(Boolean);\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactAccordion extends HTMLElement implements AccordionElement {\n static get observedAttributes() {\n return ['value'];\n }\n\n private open = new Set<string>();\n\n private upgraded = false;\n\n private controlled = false;\n\n private picked?: string[];\n\n private readonly prepared = new WeakSet<HTMLElement>();\n\n private observer?: MutationObserver;\n\n private readonly onClick = (event: MouseEvent) => {\n const target = event.target instanceof Element ? event.target : null;\n const trigger = target?.closest('button[data-accordion-trigger]');\n if (trigger && this.ownsElement(trigger)) {\n const value = this.sectionOf(trigger)?.dataset.value;\n if (value === undefined) return;\n const next = new Set(this.open);\n if (next.has(value)) next.delete(value);\n else next.add(value);\n this.change(next);\n return;\n }\n const showAll = target?.closest('button[data-accordion-show-all]');\n if (showAll && this.ownsElement(showAll)) {\n const values = this.sections.map((section) => section.dataset.value ?? '');\n this.change(new Set(this.allOpen ? [] : values));\n }\n };\n\n // Find in page opens a collapsed section that holds the match.\n private readonly onBeforeMatch = (event: Event) => {\n const section = event.target instanceof Element ? this.sectionOf(event.target) : undefined;\n const value = section?.dataset.value;\n if (value === undefined || this.open.has(value)) return;\n this.change(new Set([...this.open, value]), true);\n };\n\n get openValues() {\n return this.upgraded ? [...this.open] : undefined;\n }\n\n get pickedValue() {\n return this.picked;\n }\n\n connectedCallback() {\n // Sections can be parsed or rendered later, and React can rewrite a class attribute.\n this.observer = new MutationObserver((records) => {\n if (!this.upgraded) {\n this.setup();\n return;\n }\n if (records.some((record) => record.type === 'childList'))\n this.sections.forEach((section) => this.prepare(section));\n this.render();\n });\n this.observer.observe(this, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });\n if (this.upgraded) {\n // Moved, rather than new: keep the open sections.\n this.listen();\n this.render();\n } else {\n this.setup();\n }\n }\n\n disconnectedCallback() {\n this.observer?.disconnect();\n this.removeEventListener('click', this.onClick);\n this.removeEventListener('beforematch', this.onBeforeMatch, true);\n }\n\n attributeChangedCallback() {\n const value = valuesOf(this.getAttribute('value'));\n this.controlled = value !== undefined;\n if (!value) return;\n this.open = new Set(value);\n this.render();\n }\n\n private get sections() {\n return this.own('[data-accordion-section]');\n }\n\n private get allOpen() {\n return this.sections.every((section) => this.open.has(section.dataset.value ?? ''));\n }\n\n private own(selector: string) {\n // Leave nested accordions to their own element.\n return Array.from(this.querySelectorAll<HTMLElement>(selector)).filter((element) => this.ownsElement(element));\n }\n\n private ownsElement(element: Element) {\n return element.closest(tagName) === this;\n }\n\n private sectionOf(element: Element) {\n const section = element.closest<HTMLElement>('[data-accordion-section]');\n return section && this.ownsElement(section) ? section : undefined;\n }\n\n private find(section: HTMLElement, selector: string) {\n return Array.from(section.querySelectorAll<HTMLElement>(selector)).find(\n (element) => this.sectionOf(element) === section\n );\n }\n\n private text(name: keyof typeof defaults) {\n return this.getAttribute(name) ?? defaults[name];\n }\n\n private get remember() {\n return this.getAttribute('remember-expanded') !== 'false';\n }\n\n private setup() {\n const sections = this.sections;\n if (!sections.some((section) => this.find(section, 'button[data-accordion-trigger]'))) return;\n this.upgraded = true;\n const value = valuesOf(this.getAttribute('value'));\n this.controlled = value !== undefined;\n this.open = new Set(value ?? valuesOf(this.getAttribute('default-value')));\n this.dataset.upgraded = '';\n const upgradedClasses = classesOf(this.getAttribute('upgraded-class'));\n if (upgradedClasses.length) this.classList.add(...upgradedClasses);\n this.own('[data-accordion-controls]').forEach((controls) => {\n controls.hidden = false;\n });\n sections.forEach((section) => this.prepare(section));\n this.listen();\n this.render();\n }\n\n private listen() {\n this.addEventListener('click', this.onClick);\n // `beforematch` doesn't bubble.\n this.addEventListener('beforematch', this.onBeforeMatch, true);\n }\n\n /** Swaps a section's fallback for its trigger, once, and sets its first state. */\n private prepare(section: HTMLElement) {\n const trigger = this.find(section, 'button[data-accordion-trigger]');\n if (!trigger || this.prepared.has(section)) return;\n this.prepared.add(section);\n const value = section.dataset.value ?? '';\n if (!this.controlled) {\n const defaultValue = valuesOf(this.getAttribute('default-value'));\n if (defaultValue ? defaultValue.includes(value) : section.hasAttribute('data-expanded')) this.open.add(value);\n this.restore(section);\n }\n Array.from(section.querySelectorAll<HTMLElement>('[data-accordion-fallback]'))\n .filter((fallback) => this.sectionOf(fallback) === section)\n .forEach((fallback) => {\n fallback.hidden = true;\n });\n trigger.hidden = false;\n const content = this.find(section, '[data-accordion-content]');\n if (content?.id) trigger.setAttribute('aria-controls', content.id);\n }\n\n /** A section remembered from earlier in the session, as in govuk-frontend. */\n private restore(section: HTMLElement) {\n const id = this.find(section, '[data-accordion-content]')?.id;\n const value = section.dataset.value;\n if (!this.remember || !id || value === undefined) return;\n try {\n const state = window.sessionStorage.getItem(id);\n if (state === 'true') this.open.add(value);\n else if (state === 'false') this.open.delete(value);\n } catch {\n // Storage can be unavailable.\n }\n }\n\n /** Remembers the sections that changed, as govuk-frontend does. */\n private store(previous: Set<string>) {\n if (!this.remember) return;\n this.sections.forEach((section) => {\n const value = section.dataset.value ?? '';\n const id = this.find(section, '[data-accordion-content]')?.id;\n if (!id || previous.has(value) === this.open.has(value)) return;\n try {\n window.sessionStorage.setItem(id, String(this.open.has(value)));\n } catch {\n // Storage can be unavailable.\n }\n });\n }\n\n private change(next: Set<string>, force = false) {\n const value = this.sections.map((section) => section.dataset.value ?? '').filter((v) => next.has(v));\n // Find in page must show the match, so it opens the section even when controlled.\n if (!this.controlled || force) {\n const previous = this.open;\n this.open = new Set(value);\n if (!this.controlled) {\n this.picked = value;\n this.store(previous);\n }\n this.render();\n }\n this.dispatchEvent(new CustomEvent('govuk-react-accordion:change', { detail: { value }, bubbles: true }));\n }\n\n private render() {\n if (!this.upgraded) return;\n const expandedClasses = classesOf(this.getAttribute('expanded-section-class'));\n const collapsedIconClasses = classesOf(this.getAttribute('collapsed-icon-class'));\n const setIcon = (root: HTMLElement, expanded: boolean) => {\n Array.from(root.querySelectorAll<HTMLElement>('[data-accordion-icon]')).forEach((icon) => {\n collapsedIconClasses.forEach((name) => icon.classList.toggle(name, !expanded));\n });\n };\n this.sections.forEach((section) => {\n const expanded = this.open.has(section.dataset.value ?? '');\n const trigger = this.find(section, 'button[data-accordion-trigger]');\n const content = this.find(section, '[data-accordion-content]');\n section.dataset.state = expanded ? 'open' : 'closed';\n expandedClasses.forEach((name) => section.classList.toggle(name, expanded));\n if (content) {\n if (expanded) content.removeAttribute('hidden');\n else content.setAttribute('hidden', 'until-found');\n }\n if (!trigger) return;\n trigger.setAttribute('aria-expanded', String(expanded));\n const labels = Array.from(trigger.querySelectorAll('[data-accordion-label]')).map(\n (label) => label.textContent?.trim() ?? ''\n );\n trigger.setAttribute(\n 'aria-label',\n [...labels, this.text(expanded ? 'hide-section-label' : 'show-section-label')].join(' , ')\n );\n const toggleText = trigger.querySelector('[data-accordion-toggle-text]');\n if (toggleText) setText(toggleText, this.text(expanded ? 'hide-section-text' : 'show-section-text'));\n setIcon(trigger, expanded);\n });\n const allOpen = this.allOpen;\n this.own('button[data-accordion-show-all]').forEach((showAll) => {\n showAll.setAttribute('aria-expanded', String(allOpen));\n const text = showAll.querySelector('[data-accordion-show-all-text]');\n if (text) setText(text, this.text(allOpen ? 'hide-all-sections-text' : 'show-all-sections-text'));\n setIcon(showAll, allOpen);\n });\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactAccordion);\n}\n"]}
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/accordion/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;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AAC;gBACF,OAAO,CAAC,YAAY,CAClB,YAAY,EACZ,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAC3F,CAAC;gBACF,MAAM,UAAU,GAAG,OAAO,CAAC,aAAa,CAAC,8BAA8B,CAAC,CAAC;gBACzE,IAAI,UAAU;oBAAE,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC;gBACrG,OAAO,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAC7B,CAAC,CAAC,CAAC;YACH,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;YAC7B,IAAI,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;gBAC9D,OAAO,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;gBACvD,MAAM,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,gCAAgC,CAAC,CAAC;gBACrE,IAAI,IAAI;oBAAE,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC;gBAClG,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC5B,CAAC,CAAC,CAAC;QACL,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC;AACxF,CAAC","sourcesContent":["/*\n * <govuk-react-accordion>: a headless, light-DOM custom element that lets users show and hide\n * sections of content, with or without React.\n *\n * Without JavaScript every section is shown, under a plain heading. Each section also holds a\n * hidden button with the same heading. On upgrade the element shows the buttons and hides the\n * plain headings, then each button shows and hides its section's content, and a \"show all\"\n * button shows or hides every section. The rendered markup is never moved, so React can keep\n * rendering it. Content is hidden with `hidden=\"until-found\"`, so find in page still opens it.\n *\n * Markup inside the element:\n * - `[data-accordion-controls]` (optional): holds the \"show all\" button. Rendered `hidden`.\n * - `button[data-accordion-show-all]`, with a `[data-accordion-show-all-text]` for its text.\n * - `[data-accordion-section][data-value]`: a section. `data-expanded` opens it at first.\n * - `[data-accordion-fallback]`: the plain heading and summary, hidden on upgrade.\n * - `button[data-accordion-trigger]`: rendered `hidden`. Its accessible name is the text of its\n * `[data-accordion-label]` elements and the show or hide label. Its\n * `[data-accordion-toggle-text]` shows the show or hide text.\n * - `[data-accordion-content]`: the content, with an id.\n * - `[data-accordion-icon]` (optional): in the buttons, given `collapsed-icon-class` while\n * collapsed.\n *\n * Attributes:\n * - `value`: the open sections' values, separated by spaces, to control them. A user's click only\n * fires the change event, and the sections change when `value` does.\n * - `default-value`: the sections open at first, instead of `data-expanded`.\n * - `remember-expanded`: \"false\" stops the open sections being remembered in session storage,\n * keyed by content id, as govuk-frontend does.\n * - `show-section-text`, `hide-section-text`, `show-section-label`, `hide-section-label`,\n * `show-all-sections-text`, `hide-all-sections-text`: the text, English by default.\n * - `upgraded-class`, `expanded-section-class`, `collapsed-icon-class`: classes to add, for styles\n * keyed off classes rather than `data-upgraded`, `data-state` and `aria-expanded`.\n *\n * A user's click fires a bubbling `govuk-react-accordion:change` event with `{ value }`, the open\n * sections' values.\n */\n\nimport { classesOf, setText } from '../utils/dom.js';\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'govuk-react-accordion': AccordionElement;\n }\n interface HTMLElementEventMap {\n 'govuk-react-accordion:change': CustomEvent<{ value: string[] }>;\n }\n}\n\nexport const tagName = 'govuk-react-accordion';\n\nexport interface AccordionElement extends HTMLElement {\n /** The open sections' values, once upgraded. */\n readonly openValues: string[] | undefined;\n /** The open sections after the user's last change before `value` was first set, such as before React hydrated. */\n readonly pickedValue: string[] | undefined;\n}\n\nconst defaults = {\n 'show-section-text': 'Show',\n 'hide-section-text': 'Hide',\n 'show-section-label': 'Show this section',\n 'hide-section-label': 'Hide this section',\n 'show-all-sections-text': 'Show all sections',\n 'hide-all-sections-text': 'Hide all sections',\n};\n\nconst valuesOf = (attribute: string | null) => attribute?.split(/\\s+/).filter(Boolean);\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactAccordion extends HTMLElement implements AccordionElement {\n static get observedAttributes() {\n return ['value'];\n }\n\n private open = new Set<string>();\n\n private upgraded = false;\n\n private controlled = false;\n\n private picked?: string[];\n\n private readonly prepared = new WeakSet<HTMLElement>();\n\n private observer?: MutationObserver;\n\n private readonly onClick = (event: MouseEvent) => {\n const target = event.target instanceof Element ? event.target : null;\n const trigger = target?.closest('button[data-accordion-trigger]');\n if (trigger && this.ownsElement(trigger)) {\n const value = this.sectionOf(trigger)?.dataset.value;\n if (value === undefined) return;\n const next = new Set(this.open);\n if (next.has(value)) next.delete(value);\n else next.add(value);\n this.change(next);\n return;\n }\n const showAll = target?.closest('button[data-accordion-show-all]');\n if (showAll && this.ownsElement(showAll)) {\n const values = this.sections.map((section) => section.dataset.value ?? '');\n this.change(new Set(this.allOpen ? [] : values));\n }\n };\n\n // Find in page opens a collapsed section that holds the match.\n private readonly onBeforeMatch = (event: Event) => {\n const section = event.target instanceof Element ? this.sectionOf(event.target) : undefined;\n const value = section?.dataset.value;\n if (value === undefined || this.open.has(value)) return;\n this.change(new Set([...this.open, value]), true);\n };\n\n get openValues() {\n return this.upgraded ? [...this.open] : undefined;\n }\n\n get pickedValue() {\n return this.picked;\n }\n\n connectedCallback() {\n // Sections can be parsed or rendered later, and React can rewrite a class attribute.\n this.observer = new MutationObserver((records) => {\n if (!this.upgraded) {\n this.setup();\n return;\n }\n if (records.some((record) => record.type === 'childList'))\n this.sections.forEach((section) => this.prepare(section));\n this.render();\n });\n this.observer.observe(this, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });\n if (this.upgraded) {\n // Moved, rather than new: keep the open sections.\n this.listen();\n this.render();\n } else {\n this.setup();\n }\n }\n\n disconnectedCallback() {\n this.observer?.disconnect();\n this.removeEventListener('click', this.onClick);\n this.removeEventListener('beforematch', this.onBeforeMatch, true);\n }\n\n attributeChangedCallback() {\n const value = valuesOf(this.getAttribute('value'));\n this.controlled = value !== undefined;\n if (!value) return;\n this.open = new Set(value);\n this.render();\n }\n\n private get sections() {\n return this.own('[data-accordion-section]');\n }\n\n private get allOpen() {\n return this.sections.every((section) => this.open.has(section.dataset.value ?? ''));\n }\n\n private own(selector: string) {\n // Leave nested accordions to their own element.\n return Array.from(this.querySelectorAll<HTMLElement>(selector)).filter((element) => this.ownsElement(element));\n }\n\n private ownsElement(element: Element) {\n return element.closest(tagName) === this;\n }\n\n private sectionOf(element: Element) {\n const section = element.closest<HTMLElement>('[data-accordion-section]');\n return section && this.ownsElement(section) ? section : undefined;\n }\n\n private find(section: HTMLElement, selector: string) {\n return Array.from(section.querySelectorAll<HTMLElement>(selector)).find(\n (element) => this.sectionOf(element) === section\n );\n }\n\n private text(name: keyof typeof defaults) {\n return this.getAttribute(name) ?? defaults[name];\n }\n\n private get remember() {\n return this.getAttribute('remember-expanded') !== 'false';\n }\n\n private setup() {\n const sections = this.sections;\n if (!sections.some((section) => this.find(section, 'button[data-accordion-trigger]'))) return;\n this.upgraded = true;\n const value = valuesOf(this.getAttribute('value'));\n this.controlled = value !== undefined;\n this.open = new Set(value ?? valuesOf(this.getAttribute('default-value')));\n this.dataset.upgraded = '';\n const upgradedClasses = classesOf(this.getAttribute('upgraded-class'));\n if (upgradedClasses.length) this.classList.add(...upgradedClasses);\n this.own('[data-accordion-controls]').forEach((controls) => {\n controls.hidden = false;\n });\n sections.forEach((section) => this.prepare(section));\n this.listen();\n this.render();\n }\n\n private listen() {\n this.addEventListener('click', this.onClick);\n // `beforematch` doesn't bubble.\n this.addEventListener('beforematch', this.onBeforeMatch, true);\n }\n\n /** Swaps a section's fallback for its trigger, once, and sets its first state. */\n private prepare(section: HTMLElement) {\n const trigger = this.find(section, 'button[data-accordion-trigger]');\n if (!trigger || this.prepared.has(section)) return;\n this.prepared.add(section);\n const value = section.dataset.value ?? '';\n if (!this.controlled) {\n const defaultValue = valuesOf(this.getAttribute('default-value'));\n if (defaultValue ? defaultValue.includes(value) : section.hasAttribute('data-expanded')) this.open.add(value);\n this.restore(section);\n }\n Array.from(section.querySelectorAll<HTMLElement>('[data-accordion-fallback]'))\n .filter((fallback) => this.sectionOf(fallback) === section)\n .forEach((fallback) => {\n fallback.hidden = true;\n });\n trigger.hidden = false;\n const content = this.find(section, '[data-accordion-content]');\n if (content?.id) trigger.setAttribute('aria-controls', content.id);\n }\n\n /** A section remembered from earlier in the session, as in govuk-frontend. */\n private restore(section: HTMLElement) {\n const id = this.find(section, '[data-accordion-content]')?.id;\n const value = section.dataset.value;\n if (!this.remember || !id || value === undefined) return;\n try {\n const state = window.sessionStorage.getItem(id);\n if (state === 'true') this.open.add(value);\n else if (state === 'false') this.open.delete(value);\n } catch {\n // Storage can be unavailable.\n }\n }\n\n /** Remembers the sections that changed, as govuk-frontend does. */\n private store(previous: Set<string>) {\n if (!this.remember) return;\n this.sections.forEach((section) => {\n const value = section.dataset.value ?? '';\n const id = this.find(section, '[data-accordion-content]')?.id;\n if (!id || previous.has(value) === this.open.has(value)) return;\n try {\n window.sessionStorage.setItem(id, String(this.open.has(value)));\n } catch {\n // Storage can be unavailable.\n }\n });\n }\n\n private change(next: Set<string>, force = false) {\n const value = this.sections.map((section) => section.dataset.value ?? '').filter((v) => next.has(v));\n // Find in page must show the match, so it opens the section even when controlled.\n if (!this.controlled || force) {\n const previous = this.open;\n this.open = new Set(value);\n if (!this.controlled) {\n this.picked = value;\n this.store(previous);\n }\n this.render();\n }\n this.dispatchEvent(new CustomEvent('govuk-react-accordion:change', { detail: { value }, bubbles: true }));\n }\n\n private render() {\n if (!this.upgraded) return;\n const expandedClasses = classesOf(this.getAttribute('expanded-section-class'));\n const collapsedIconClasses = classesOf(this.getAttribute('collapsed-icon-class'));\n const setIcon = (root: HTMLElement, expanded: boolean) => {\n Array.from(root.querySelectorAll<HTMLElement>('[data-accordion-icon]')).forEach((icon) => {\n collapsedIconClasses.forEach((name) => icon.classList.toggle(name, !expanded));\n });\n };\n this.sections.forEach((section) => {\n const expanded = this.open.has(section.dataset.value ?? '');\n const trigger = this.find(section, 'button[data-accordion-trigger]');\n const content = this.find(section, '[data-accordion-content]');\n section.dataset.state = expanded ? 'open' : 'closed';\n expandedClasses.forEach((name) => section.classList.toggle(name, expanded));\n if (content) {\n if (expanded) content.removeAttribute('hidden');\n else content.setAttribute('hidden', 'until-found');\n }\n if (!trigger) return;\n trigger.setAttribute('aria-expanded', String(expanded));\n const labels = Array.from(trigger.querySelectorAll('[data-accordion-label]')).map(\n (label) => label.textContent?.trim() ?? ''\n );\n trigger.setAttribute(\n 'aria-label',\n [...labels, this.text(expanded ? 'hide-section-label' : 'show-section-label')].join(' , ')\n );\n const toggleText = trigger.querySelector('[data-accordion-toggle-text]');\n if (toggleText) setText(toggleText, this.text(expanded ? 'hide-section-text' : 'show-section-text'));\n setIcon(trigger, expanded);\n });\n const allOpen = this.allOpen;\n this.own('button[data-accordion-show-all]').forEach((showAll) => {\n showAll.setAttribute('aria-expanded', String(allOpen));\n const text = showAll.querySelector('[data-accordion-show-all-text]');\n if (text) setText(text, this.text(allOpen ? 'hide-all-sections-text' : 'show-all-sections-text'));\n setIcon(showAll, allOpen);\n });\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactAccordion);\n}\n"]}
@@ -1,17 +1,14 @@
1
1
  import * as React from 'react';
2
2
  import type { ComponentProps } from 'react';
3
- /**
4
- * Hides the parts the element hides, over styles that set their `display`. Root renders it
5
- * inline; under a strict CSP, add it to a stylesheet instead.
6
- */
7
- export declare const accordionCss = "govuk-react-accordion :is([data-accordion-fallback],[data-accordion-trigger],[data-accordion-controls])[hidden]{display:none!important}";
3
+ import { type ChangeDetails } from '../utils/change-details.js';
4
+ export type { ChangeDetails };
8
5
  export type RootProps = Omit<React.HTMLAttributes<HTMLElement>, 'defaultValue' | 'onChange'> & {
9
6
  /** The open sections' values, to control them once hydrated. */
10
7
  value?: string[];
11
8
  /** The sections open at first. */
12
9
  defaultValue?: string[];
13
10
  /** Called with the open sections' values when the user opens or closes a section. */
14
- onValueChange?: (value: string[]) => void;
11
+ onValueChange?: (value: string[], details: ChangeDetails) => void;
15
12
  /** Whether to remember the open sections for the rest of the session, keyed by content id. Defaults to `true`, as in govuk-frontend. */
16
13
  rememberExpanded?: boolean;
17
14
  /** Each button's text while its section is closed. Defaults to "Show". */
@@ -71,4 +68,3 @@ export declare function Icon({ asChild, ...props }: IconProps): React.JSX.Elemen
71
68
  export type ContentProps = PartProps<'div'>;
72
69
  /** The section's content. Give it an id, which the trigger's `aria-controls` names. */
73
70
  export declare function Content({ asChild, ...props }: ContentProps): React.JSX.Element;
74
- export {};
@@ -1,20 +1,18 @@
1
1
  'use client';
2
2
  import * as React from 'react';
3
- import { createContext, useContext, useEffect, useRef } from 'react';
3
+ import { createContext, useContext, useEffect, useReducer, useRef } from 'react';
4
+ import { early, live } from '../utils/change-details.js';
4
5
  import { Slot } from '../utils/slot.js';
5
6
  import { tagName } from './element.js';
6
7
  const AccordionContext = createContext({ texts: {} });
7
8
  const SectionContext = createContext({});
8
- /**
9
- * Hides the parts the element hides, over styles that set their `display`. Root renders it
10
- * inline; under a strict CSP, add it to a stylesheet instead.
11
- */
12
- export const accordionCss = `${tagName} :is([data-accordion-fallback],[data-accordion-trigger],[data-accordion-controls])[hidden]{display:none!important}`;
13
9
  const isAccordion = (element) => 'pickedValue' in element;
14
10
  export function Root({ value, defaultValue, onValueChange, rememberExpanded, showSectionText, hideSectionText, showSectionLabel, hideSectionLabel, showAllSectionsText, hideAllSectionsText, upgradedClass, expandedSectionClass, collapsedIconClass, children, ...props }) {
11
+ var _a;
15
12
  const element = useRef(null);
16
13
  const onValueChangeRef = useRef(onValueChange);
17
14
  const synced = useRef(false);
15
+ const [, render] = useReducer((count) => count + 1, 0);
18
16
  useEffect(() => {
19
17
  onValueChangeRef.current = onValueChange;
20
18
  });
@@ -26,7 +24,7 @@ export function Root({ value, defaultValue, onValueChange, rememberExpanded, sho
26
24
  const onChange = (event) => {
27
25
  var _a;
28
26
  if (event.target === node)
29
- (_a = onValueChangeRef.current) === null || _a === void 0 ? void 0 : _a.call(onValueChangeRef, event.detail.value);
27
+ (_a = onValueChangeRef.current) === null || _a === void 0 ? void 0 : _a.call(onValueChangeRef, event.detail.value, live);
30
28
  };
31
29
  node.addEventListener('govuk-react-accordion:change', onChange);
32
30
  return () => node.removeEventListener('govuk-react-accordion:change', onChange);
@@ -34,42 +32,46 @@ export function Root({ value, defaultValue, onValueChange, rememberExpanded, sho
34
32
  // `value` is set once hydrated, so the server markup is uncontrolled and a click before
35
33
  // hydration still works. That click is then reported, rather than undone.
36
34
  const controlled = value === null || value === void 0 ? void 0 : value.join(' ');
35
+ const initialValue = ((_a = value !== null && value !== void 0 ? value : defaultValue) !== null && _a !== void 0 ? _a : []).join(' ');
37
36
  useEffect(() => {
38
37
  const node = element.current;
39
- if (!node || controlled === undefined) {
40
- node === null || node === void 0 ? void 0 : node.removeAttribute('value');
38
+ if (!node)
41
39
  return;
42
- }
43
40
  if (!synced.current) {
44
41
  synced.current = true;
45
42
  const picked = isAccordion(node) ? node.pickedValue : undefined;
46
- if (picked !== undefined && picked.join(' ') !== controlled && onValueChangeRef.current) {
47
- onValueChangeRef.current(picked);
48
- return;
43
+ if (picked !== undefined && picked.join(' ') !== initialValue && onValueChangeRef.current) {
44
+ onValueChangeRef.current(picked, early);
45
+ if (controlled !== undefined) {
46
+ // The pick shows until the next render, which adopts it or goes back to `value`.
47
+ render();
48
+ return;
49
+ }
49
50
  }
50
51
  }
51
- node.setAttribute('value', controlled);
52
+ if (controlled === undefined)
53
+ node.removeAttribute('value');
54
+ else
55
+ node.setAttribute('value', controlled);
52
56
  });
53
57
  const initial = value !== null && value !== void 0 ? value : defaultValue;
54
- return (React.createElement(AccordionContext.Provider, { value: { open: initial, texts: { showSectionText, hideSectionText, showAllSectionsText, hideAllSectionsText } } },
55
- React.createElement("style", { href: `${tagName}-css`, precedence: "default" }, accordionCss),
56
- React.createElement(tagName, {
57
- ...props,
58
- ref: element,
59
- 'default-value': initial === null || initial === void 0 ? void 0 : initial.join(' '),
60
- 'remember-expanded': rememberExpanded === undefined ? undefined : String(rememberExpanded),
61
- 'show-section-text': showSectionText,
62
- 'hide-section-text': hideSectionText,
63
- 'show-section-label': showSectionLabel,
64
- 'hide-section-label': hideSectionLabel,
65
- 'show-all-sections-text': showAllSectionsText,
66
- 'hide-all-sections-text': hideAllSectionsText,
67
- 'upgraded-class': upgradedClass,
68
- 'expanded-section-class': expandedSectionClass,
69
- 'collapsed-icon-class': collapsedIconClass,
70
- // The element adds attributes on upgrade, so they can differ from the server's.
71
- suppressHydrationWarning: true,
72
- }, children)));
58
+ return (React.createElement(AccordionContext.Provider, { value: { open: initial, texts: { showSectionText, hideSectionText, showAllSectionsText, hideAllSectionsText } } }, React.createElement(tagName, {
59
+ ...props,
60
+ ref: element,
61
+ 'default-value': initial === null || initial === void 0 ? void 0 : initial.join(' '),
62
+ 'remember-expanded': rememberExpanded === undefined ? undefined : String(rememberExpanded),
63
+ 'show-section-text': showSectionText,
64
+ 'hide-section-text': hideSectionText,
65
+ 'show-section-label': showSectionLabel,
66
+ 'hide-section-label': hideSectionLabel,
67
+ 'show-all-sections-text': showAllSectionsText,
68
+ 'hide-all-sections-text': hideAllSectionsText,
69
+ 'upgraded-class': upgradedClass,
70
+ 'expanded-section-class': expandedSectionClass,
71
+ 'collapsed-icon-class': collapsedIconClass,
72
+ // The element adds attributes on upgrade, so they can differ from the server's.
73
+ suppressHydrationWarning: true,
74
+ }, children)));
73
75
  }
74
76
  /** Holds the "show all" button. Hidden until the element upgrades. */
75
77
  export function Controls({ asChild, ...props }) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/accordion/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAErE,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,OAAO,EAAyB,MAAM,cAAc,CAAC;AAoB9D,MAAM,gBAAgB,GAAG,aAAa,CAAoC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAEzF,MAAM,cAAc,GAAG,aAAa,CAAyB,EAAE,CAAC,CAAC;AAEjE;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,GAAG,OAAO,oHAAoH,CAAC;AAE3J,MAAM,WAAW,GAAG,CAAC,OAAoB,EAA+B,EAAE,CAAC,aAAa,IAAI,OAAO,CAAC;AA+BpG,MAAM,UAAU,IAAI,CAAC,EACnB,KAAK,EACL,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,mBAAmB,EACnB,mBAAmB,EACnB,aAAa,EACb,oBAAoB,EACpB,kBAAkB,EAClB,QAAQ,EACR,GAAG,KAAK,EACE;IACV,MAAM,OAAO,GAAG,MAAM,CAAc,IAAI,CAAC,CAAC;IAC1C,MAAM,gBAAgB,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;IAC/C,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAE7B,SAAS,CAAC,GAAG,EAAE;QACb,gBAAgB,CAAC,OAAO,GAAG,aAAa,CAAC;IAC3C,CAAC,CAAC,CAAC;IAEH,SAAS,CAAC,GAAG,EAAE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EAAE,GAAG,UAAU,CAAC,gBAAgB,CAAC,CAAC;IAC/C,MAAM,EAAE,QAAQ,EAAE,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC;IAChD,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;IACxC,4FAA4F;IAC5F,OAAO,CACL,oBAAC,OAAO,kCAA4B,EAAE,EAAC,wBAAwB,WAAK,KAAK,IACtE,QAAQ,aAAR,QAAQ,cAAR,QAAQ,GAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,MAAA,KAAK,CAAC,eAAe,mCAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,MAAA,KAAK,CAAC,eAAe,mCAAI,MAAM,CAAC,CAAC,CACvF,CACX,CAAC;AACJ,CAAC;AAID,8FAA8F;AAC9F,MAAM,UAAU,IAAI,CAAC,EAAE,OAAO,EAAE,GAAG,KAAK,EAAa;IACnD,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;IACxC,OAAO,oBAAC,OAAO,2BAAqB,EAAE,EAAC,wBAAwB,WAAK,KAAK,GAAI,CAAC;AAChF,CAAC;AAID,uFAAuF;AACvF,MAAM,UAAU,OAAO,CAAC,EAAE,OAAO,EAAE,GAAG,KAAK,EAAgB;IACzD,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IACvC,sCAAsC;IACtC,OAAO,oBAAC,OAAO,8BAAwB,EAAE,EAAC,wBAAwB,WAAK,KAAK,GAAI,CAAC;AACnF,CAAC","sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport { createContext, useContext, useEffect, useRef } from 'react';\nimport type { ComponentProps } from 'react';\nimport { Slot } from '../utils/slot.js';\nimport { tagName, type AccordionElement } from './element.js';\n\n/*\n * Headless accordion: unstyled parts over the <govuk-react-accordion> element (./element.ts).\n * Every part except Root takes `asChild`.\n *\n * Without JavaScript every section is shown under its `Fallback` heading. Each section also\n * holds a hidden `Trigger` with the same heading, which the element shows on upgrade. Put the\n * heading text in a `Label` inside the trigger, so the element can name the button.\n *\n * Context only fills in defaults: in an island without a Root, pass `defaultExpanded` to Section.\n */\n\ntype Texts = {\n showSectionText?: string;\n hideSectionText?: string;\n showAllSectionsText?: string;\n hideAllSectionsText?: string;\n};\n\nconst AccordionContext = createContext<{ open?: string[]; texts: Texts }>({ texts: {} });\n\nconst SectionContext = createContext<{ expanded?: boolean }>({});\n\n/**\n * Hides the parts the element hides, over styles that set their `display`. Root renders it\n * inline; under a strict CSP, add it to a stylesheet instead.\n */\nexport const accordionCss = `${tagName} :is([data-accordion-fallback],[data-accordion-trigger],[data-accordion-controls])[hidden]{display:none!important}`;\n\nconst isAccordion = (element: HTMLElement): element is AccordionElement => 'pickedValue' in element;\n\nexport type RootProps = Omit<React.HTMLAttributes<HTMLElement>, 'defaultValue' | 'onChange'> & {\n /** The open sections' values, to control them once hydrated. */\n value?: string[];\n /** The sections open at first. */\n defaultValue?: string[];\n /** Called with the open sections' values when the user opens or closes a section. */\n onValueChange?: (value: string[]) => void;\n /** Whether to remember the open sections for the rest of the session, keyed by content id. Defaults to `true`, as in govuk-frontend. */\n rememberExpanded?: boolean;\n /** Each button's text while its section is closed. Defaults to \"Show\". */\n showSectionText?: string;\n /** Each button's text while its section is open. Defaults to \"Hide\". */\n hideSectionText?: string;\n /** The end of each button's accessible name while its section is closed. Defaults to \"Show this section\". */\n showSectionLabel?: string;\n /** The end of each button's accessible name while its section is open. Defaults to \"Hide this section\". */\n hideSectionLabel?: string;\n /** The \"show all\" button's text while a section is closed. Defaults to \"Show all sections\". */\n showAllSectionsText?: string;\n /** The \"show all\" button's text while every section is open. Defaults to \"Hide all sections\". */\n hideAllSectionsText?: string;\n /** Classes added to the element when it upgrades. */\n upgradedClass?: string;\n /** Classes added to open sections. */\n expandedSectionClass?: string;\n /** Classes added to the icons of closed sections, and the \"show all\" icon while a section is closed. */\n collapsedIconClass?: string;\n};\n\nexport function Root({\n value,\n defaultValue,\n onValueChange,\n rememberExpanded,\n showSectionText,\n hideSectionText,\n showSectionLabel,\n hideSectionLabel,\n showAllSectionsText,\n hideAllSectionsText,\n upgradedClass,\n expandedSectionClass,\n collapsedIconClass,\n children,\n ...props\n}: RootProps) {\n const element = useRef<HTMLElement>(null);\n const onValueChangeRef = useRef(onValueChange);\n const synced = useRef(false);\n\n useEffect(() => {\n onValueChangeRef.current = onValueChange;\n });\n\n useEffect(() => {\n const node = element.current;\n if (!node) return undefined;\n // A nested accordion's change bubbles through this one.\n const onChange = (event: CustomEvent<{ value: string[] }>) => {\n if (event.target === node) onValueChangeRef.current?.(event.detail.value);\n };\n node.addEventListener('govuk-react-accordion:change', onChange);\n return () => node.removeEventListener('govuk-react-accordion:change', onChange);\n }, []);\n\n // `value` is set once hydrated, so the server markup is uncontrolled and a click before\n // hydration still works. That click is then reported, rather than undone.\n const controlled = value?.join(' ');\n useEffect(() => {\n const node = element.current;\n if (!node || controlled === undefined) {\n node?.removeAttribute('value');\n return;\n }\n if (!synced.current) {\n synced.current = true;\n const picked = isAccordion(node) ? node.pickedValue : undefined;\n if (picked !== undefined && picked.join(' ') !== controlled && onValueChangeRef.current) {\n onValueChangeRef.current(picked);\n return;\n }\n }\n node.setAttribute('value', controlled);\n });\n\n const initial = value ?? defaultValue;\n return (\n <AccordionContext.Provider\n value={{ open: initial, texts: { showSectionText, hideSectionText, showAllSectionsText, hideAllSectionsText } }}\n >\n <style href={`${tagName}-css`} precedence=\"default\">\n {accordionCss}\n </style>\n {React.createElement(\n tagName,\n {\n ...props,\n ref: element,\n 'default-value': initial?.join(' '),\n 'remember-expanded': rememberExpanded === undefined ? undefined : String(rememberExpanded),\n 'show-section-text': showSectionText,\n 'hide-section-text': hideSectionText,\n 'show-section-label': showSectionLabel,\n 'hide-section-label': hideSectionLabel,\n 'show-all-sections-text': showAllSectionsText,\n 'hide-all-sections-text': hideAllSectionsText,\n 'upgraded-class': upgradedClass,\n 'expanded-section-class': expandedSectionClass,\n 'collapsed-icon-class': collapsedIconClass,\n // The element adds attributes on upgrade, so they can differ from the server's.\n suppressHydrationWarning: true,\n },\n children\n )}\n </AccordionContext.Provider>\n );\n}\n\ntype PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E> & {\n /** Render the only child instead, with this part's props merged onto it. */\n asChild?: boolean;\n};\n\nexport type ControlsProps = PartProps<'div'>;\n\n/** Holds the \"show all\" button. Hidden until the element upgrades. */\nexport function Controls({ asChild, ...props }: ControlsProps) {\n const Element = asChild ? Slot : 'div';\n return <Element data-accordion-controls=\"\" hidden suppressHydrationWarning {...props} />;\n}\n\nexport type ShowAllProps = PartProps<'button'>;\n\n/** Shows every section, or hides every section when all are open. */\nexport function ShowAll({ asChild, ...props }: ShowAllProps) {\n if (asChild) return <Slot data-accordion-show-all=\"\" suppressHydrationWarning {...props} />;\n return <button type=\"button\" data-accordion-show-all=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type ShowAllTextProps = PartProps<'span'>;\n\n/** The \"show all\" button's text, which the element sets. */\nexport function ShowAllText({ asChild, children, ...props }: ShowAllTextProps) {\n const { texts } = useContext(AccordionContext);\n const Element = asChild ? Slot : 'span';\n // Rendered as the server would, so the element's text replaces it rather than adding to it.\n return (\n <Element data-accordion-show-all-text=\"\" suppressHydrationWarning {...props}>\n {children ?? texts.showAllSectionsText ?? 'Show all sections'}\n </Element>\n );\n}\n\nexport type SectionProps = PartProps<'div'> & {\n value: string;\n /** Whether it's open at first. Defaults to whether Root's value includes it. */\n defaultExpanded?: boolean;\n};\n\nexport function Section({ asChild, value, defaultExpanded, ...props }: SectionProps) {\n const context = useContext(AccordionContext);\n const expanded = defaultExpanded ?? context.open?.includes(value) ?? false;\n const Element = asChild ? Slot : 'div';\n return (\n <SectionContext.Provider value={{ expanded }}>\n <Element\n data-accordion-section=\"\"\n data-value={value}\n data-expanded={expanded ? '' : undefined}\n suppressHydrationWarning\n {...props}\n />\n </SectionContext.Provider>\n );\n}\n\nexport type FallbackProps = PartProps<'span'>;\n\n/** What shows without JavaScript in place of the trigger, such as the plain heading. Hidden on upgrade. */\nexport function Fallback({ asChild, ...props }: FallbackProps) {\n const Element = asChild ? Slot : 'span';\n return <Element data-accordion-fallback=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type TriggerProps = PartProps<'button'>;\n\n/** The button that shows and hides its section. Hidden until the element upgrades. */\nexport function Trigger({ asChild, ...props }: TriggerProps) {\n const shared = { 'data-accordion-trigger': '', hidden: true, suppressHydrationWarning: true };\n if (asChild) return <Slot {...shared} {...props} />;\n return <button type=\"button\" {...shared} {...props} />;\n}\n\nexport type LabelProps = PartProps<'span'>;\n\n/** Text in the trigger that names it, such as the heading or summary. */\nexport function Label({ asChild, ...props }: LabelProps) {\n const Element = asChild ? Slot : 'span';\n return <Element data-accordion-label=\"\" {...props} />;\n}\n\nexport type ToggleTextProps = PartProps<'span'>;\n\n/** The trigger's show or hide text, which the element sets. */\nexport function ToggleText({ asChild, children, ...props }: ToggleTextProps) {\n const { texts } = useContext(AccordionContext);\n const { expanded } = useContext(SectionContext);\n const Element = asChild ? Slot : 'span';\n // Rendered as the server would, so the element's text replaces it rather than adding to it.\n return (\n <Element data-accordion-toggle-text=\"\" suppressHydrationWarning {...props}>\n {children ?? (expanded ? (texts.hideSectionText ?? 'Hide') : (texts.showSectionText ?? 'Show'))}\n </Element>\n );\n}\n\nexport type IconProps = PartProps<'span'>;\n\n/** An icon in a trigger or the \"show all\" button, given `collapsedIconClass` while closed. */\nexport function Icon({ asChild, ...props }: IconProps) {\n const Element = asChild ? Slot : 'span';\n return <Element data-accordion-icon=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type ContentProps = PartProps<'div'>;\n\n/** The section's content. Give it an id, which the trigger's `aria-controls` names. */\nexport function Content({ asChild, ...props }: ContentProps) {\n const Element = asChild ? Slot : 'div';\n // The element hides it after upgrade.\n return <Element data-accordion-content=\"\" suppressHydrationWarning {...props} />;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/accordion/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAEjF,OAAO,EAAE,KAAK,EAAE,IAAI,EAAsB,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,OAAO,EAAyB,MAAM,cAAc,CAAC;AAsB9D,MAAM,gBAAgB,GAAG,aAAa,CAAoC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAEzF,MAAM,cAAc,GAAG,aAAa,CAAyB,EAAE,CAAC,CAAC;AAEjE,MAAM,WAAW,GAAG,CAAC,OAAoB,EAA+B,EAAE,CAAC,aAAa,IAAI,OAAO,CAAC;AA+BpG,MAAM,UAAU,IAAI,CAAC,EACnB,KAAK,EACL,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,gBAAgB,EAChB,gBAAgB,EAChB,mBAAmB,EACnB,mBAAmB,EACnB,aAAa,EACb,oBAAoB,EACpB,kBAAkB,EAClB,QAAQ,EACR,GAAG,KAAK,EACE;;IACV,MAAM,OAAO,GAAG,MAAM,CAAc,IAAI,CAAC,CAAC;IAC1C,MAAM,gBAAgB,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;IAC/C,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC,GAAG,UAAU,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IAE/D,SAAS,CAAC,GAAG,EAAE;QACb,gBAAgB,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,CAAC;AACnF,CAAC","sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport { createContext, useContext, useEffect, useReducer, useRef } from 'react';\nimport type { ComponentProps } from 'react';\nimport { early, live, type ChangeDetails } from '../utils/change-details.js';\nimport { Slot } from '../utils/slot.js';\nimport { tagName, type AccordionElement } from './element.js';\n\nexport type { ChangeDetails };\n\n/*\n * Headless accordion: unstyled parts over the <govuk-react-accordion> element (./element.ts).\n * Every part except Root takes `asChild`.\n *\n * Without JavaScript every section is shown under its `Fallback` heading. Each section also\n * holds a hidden `Trigger` with the same heading, which the element shows on upgrade. Put the\n * heading text in a `Label` inside the trigger, so the element can name the button.\n *\n * Context only fills in defaults: in an island without a Root, pass `defaultExpanded` to Section.\n */\n\ntype Texts = {\n showSectionText?: string;\n hideSectionText?: string;\n showAllSectionsText?: string;\n hideAllSectionsText?: string;\n};\n\nconst AccordionContext = createContext<{ open?: string[]; texts: Texts }>({ texts: {} });\n\nconst SectionContext = createContext<{ expanded?: boolean }>({});\n\nconst isAccordion = (element: HTMLElement): element is AccordionElement => 'pickedValue' in element;\n\nexport type RootProps = Omit<React.HTMLAttributes<HTMLElement>, 'defaultValue' | 'onChange'> & {\n /** The open sections' values, to control them once hydrated. */\n value?: string[];\n /** The sections open at first. */\n defaultValue?: string[];\n /** Called with the open sections' values when the user opens or closes a section. */\n onValueChange?: (value: string[], details: ChangeDetails) => void;\n /** Whether to remember the open sections for the rest of the session, keyed by content id. Defaults to `true`, as in govuk-frontend. */\n rememberExpanded?: boolean;\n /** Each button's text while its section is closed. Defaults to \"Show\". */\n showSectionText?: string;\n /** Each button's text while its section is open. Defaults to \"Hide\". */\n hideSectionText?: string;\n /** The end of each button's accessible name while its section is closed. Defaults to \"Show this section\". */\n showSectionLabel?: string;\n /** The end of each button's accessible name while its section is open. Defaults to \"Hide this section\". */\n hideSectionLabel?: string;\n /** The \"show all\" button's text while a section is closed. Defaults to \"Show all sections\". */\n showAllSectionsText?: string;\n /** The \"show all\" button's text while every section is open. Defaults to \"Hide all sections\". */\n hideAllSectionsText?: string;\n /** Classes added to the element when it upgrades. */\n upgradedClass?: string;\n /** Classes added to open sections. */\n expandedSectionClass?: string;\n /** Classes added to the icons of closed sections, and the \"show all\" icon while a section is closed. */\n collapsedIconClass?: string;\n};\n\nexport function Root({\n value,\n defaultValue,\n onValueChange,\n rememberExpanded,\n showSectionText,\n hideSectionText,\n showSectionLabel,\n hideSectionLabel,\n showAllSectionsText,\n hideAllSectionsText,\n upgradedClass,\n expandedSectionClass,\n collapsedIconClass,\n children,\n ...props\n}: RootProps) {\n const element = useRef<HTMLElement>(null);\n const onValueChangeRef = useRef(onValueChange);\n const synced = useRef(false);\n const [, render] = useReducer((count: number) => count + 1, 0);\n\n useEffect(() => {\n onValueChangeRef.current = onValueChange;\n });\n\n useEffect(() => {\n const node = element.current;\n if (!node) return undefined;\n // A nested accordion's change bubbles through this one.\n const onChange = (event: CustomEvent<{ value: string[] }>) => {\n if (event.target === node) onValueChangeRef.current?.(event.detail.value, live);\n };\n node.addEventListener('govuk-react-accordion:change', onChange);\n return () => node.removeEventListener('govuk-react-accordion:change', onChange);\n }, []);\n\n // `value` is set once hydrated, so the server markup is uncontrolled and a click before\n // hydration still works. That click is then reported, rather than undone.\n const controlled = value?.join(' ');\n const initialValue = (value ?? defaultValue ?? []).join(' ');\n useEffect(() => {\n const node = element.current;\n if (!node) return;\n if (!synced.current) {\n synced.current = true;\n const picked = isAccordion(node) ? node.pickedValue : undefined;\n if (picked !== undefined && picked.join(' ') !== initialValue && onValueChangeRef.current) {\n onValueChangeRef.current(picked, early);\n if (controlled !== undefined) {\n // The pick shows until the next render, which adopts it or goes back to `value`.\n render();\n return;\n }\n }\n }\n if (controlled === undefined) node.removeAttribute('value');\n else node.setAttribute('value', controlled);\n });\n\n const initial = value ?? defaultValue;\n return (\n <AccordionContext.Provider\n value={{ open: initial, texts: { showSectionText, hideSectionText, showAllSectionsText, hideAllSectionsText } }}\n >\n {React.createElement(\n tagName,\n {\n ...props,\n ref: element,\n 'default-value': initial?.join(' '),\n 'remember-expanded': rememberExpanded === undefined ? undefined : String(rememberExpanded),\n 'show-section-text': showSectionText,\n 'hide-section-text': hideSectionText,\n 'show-section-label': showSectionLabel,\n 'hide-section-label': hideSectionLabel,\n 'show-all-sections-text': showAllSectionsText,\n 'hide-all-sections-text': hideAllSectionsText,\n 'upgraded-class': upgradedClass,\n 'expanded-section-class': expandedSectionClass,\n 'collapsed-icon-class': collapsedIconClass,\n // The element adds attributes on upgrade, so they can differ from the server's.\n suppressHydrationWarning: true,\n },\n children\n )}\n </AccordionContext.Provider>\n );\n}\n\ntype PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E> & {\n /** Render the only child instead, with this part's props merged onto it. */\n asChild?: boolean;\n};\n\nexport type ControlsProps = PartProps<'div'>;\n\n/** Holds the \"show all\" button. Hidden until the element upgrades. */\nexport function Controls({ asChild, ...props }: ControlsProps) {\n const Element = asChild ? Slot : 'div';\n return <Element data-accordion-controls=\"\" hidden suppressHydrationWarning {...props} />;\n}\n\nexport type ShowAllProps = PartProps<'button'>;\n\n/** Shows every section, or hides every section when all are open. */\nexport function ShowAll({ asChild, ...props }: ShowAllProps) {\n if (asChild) return <Slot data-accordion-show-all=\"\" suppressHydrationWarning {...props} />;\n return <button type=\"button\" data-accordion-show-all=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type ShowAllTextProps = PartProps<'span'>;\n\n/** The \"show all\" button's text, which the element sets. */\nexport function ShowAllText({ asChild, children, ...props }: ShowAllTextProps) {\n const { texts } = useContext(AccordionContext);\n const Element = asChild ? Slot : 'span';\n // Rendered as the server would, so the element's text replaces it rather than adding to it.\n return (\n <Element data-accordion-show-all-text=\"\" suppressHydrationWarning {...props}>\n {children ?? texts.showAllSectionsText ?? 'Show all sections'}\n </Element>\n );\n}\n\nexport type SectionProps = PartProps<'div'> & {\n value: string;\n /** Whether it's open at first. Defaults to whether Root's value includes it. */\n defaultExpanded?: boolean;\n};\n\nexport function Section({ asChild, value, defaultExpanded, ...props }: SectionProps) {\n const context = useContext(AccordionContext);\n const expanded = defaultExpanded ?? context.open?.includes(value) ?? false;\n const Element = asChild ? Slot : 'div';\n return (\n <SectionContext.Provider value={{ expanded }}>\n <Element\n data-accordion-section=\"\"\n data-value={value}\n data-expanded={expanded ? '' : undefined}\n suppressHydrationWarning\n {...props}\n />\n </SectionContext.Provider>\n );\n}\n\nexport type FallbackProps = PartProps<'span'>;\n\n/** What shows without JavaScript in place of the trigger, such as the plain heading. Hidden on upgrade. */\nexport function Fallback({ asChild, ...props }: FallbackProps) {\n const Element = asChild ? Slot : 'span';\n return <Element data-accordion-fallback=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type TriggerProps = PartProps<'button'>;\n\n/** The button that shows and hides its section. Hidden until the element upgrades. */\nexport function Trigger({ asChild, ...props }: TriggerProps) {\n const shared = { 'data-accordion-trigger': '', hidden: true, suppressHydrationWarning: true };\n if (asChild) return <Slot {...shared} {...props} />;\n return <button type=\"button\" {...shared} {...props} />;\n}\n\nexport type LabelProps = PartProps<'span'>;\n\n/** Text in the trigger that names it, such as the heading or summary. */\nexport function Label({ asChild, ...props }: LabelProps) {\n const Element = asChild ? Slot : 'span';\n return <Element data-accordion-label=\"\" {...props} />;\n}\n\nexport type ToggleTextProps = PartProps<'span'>;\n\n/** The trigger's show or hide text, which the element sets. */\nexport function ToggleText({ asChild, children, ...props }: ToggleTextProps) {\n const { texts } = useContext(AccordionContext);\n const { expanded } = useContext(SectionContext);\n const Element = asChild ? Slot : 'span';\n // Rendered as the server would, so the element's text replaces it rather than adding to it.\n return (\n <Element data-accordion-toggle-text=\"\" suppressHydrationWarning {...props}>\n {children ?? (expanded ? (texts.hideSectionText ?? 'Hide') : (texts.showSectionText ?? 'Show'))}\n </Element>\n );\n}\n\nexport type IconProps = PartProps<'span'>;\n\n/** An icon in a trigger or the \"show all\" button, given `collapsedIconClass` while closed. */\nexport function Icon({ asChild, ...props }: IconProps) {\n const Element = asChild ? Slot : 'span';\n return <Element data-accordion-icon=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type ContentProps = PartProps<'div'>;\n\n/** The section's content. Give it an id, which the trigger's `aria-controls` names. */\nexport function Content({ asChild, ...props }: ContentProps) {\n const Element = asChild ? Slot : 'div';\n // The element hides it after upgrade.\n return <Element data-accordion-content=\"\" suppressHydrationWarning {...props} />;\n}\n"]}