@govuk-react/primitives 0.0.0-stage → 0.2.1

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 (121) hide show
  1. package/README.md +271 -2
  2. package/dist/accordion/element.d.ts +14 -0
  3. package/dist/accordion/element.js +302 -0
  4. package/dist/accordion/element.js.map +1 -0
  5. package/dist/accordion/index.d.ts +74 -0
  6. package/dist/accordion/index.js +138 -0
  7. package/dist/accordion/index.js.map +1 -0
  8. package/dist/auto-focus/element.d.ts +1 -0
  9. package/dist/auto-focus/element.js +75 -0
  10. package/dist/auto-focus/element.js.map +1 -0
  11. package/dist/auto-focus/index.d.ts +297 -0
  12. package/dist/auto-focus/index.js +29 -0
  13. package/dist/auto-focus/index.js.map +1 -0
  14. package/dist/autocomplete/element.d.ts +27 -0
  15. package/dist/autocomplete/element.js +597 -0
  16. package/dist/autocomplete/element.js.map +1 -0
  17. package/dist/autocomplete/index.d.ts +350 -0
  18. package/dist/autocomplete/index.js +108 -0
  19. package/dist/autocomplete/index.js.map +1 -0
  20. package/dist/button/element.d.ts +1 -0
  21. package/dist/button/element.js +59 -0
  22. package/dist/button/element.js.map +1 -0
  23. package/dist/button/index.d.ts +10 -0
  24. package/dist/button/index.js +9 -0
  25. package/dist/button/index.js.map +1 -0
  26. package/dist/character-count/element.d.ts +7 -0
  27. package/dist/character-count/element.js +287 -0
  28. package/dist/character-count/element.js.map +1 -0
  29. package/dist/character-count/index.d.ts +57 -0
  30. package/dist/character-count/index.js +79 -0
  31. package/dist/character-count/index.js.map +1 -0
  32. package/dist/character-count/messages.d.ts +20 -0
  33. package/dist/character-count/messages.js +54 -0
  34. package/dist/character-count/messages.js.map +1 -0
  35. package/dist/choices/element.d.ts +5 -0
  36. package/dist/choices/element.js +202 -0
  37. package/dist/choices/element.js.map +1 -0
  38. package/dist/choices/index.d.ts +309 -0
  39. package/dist/choices/index.js +37 -0
  40. package/dist/choices/index.js.map +1 -0
  41. package/dist/disclosure/element.d.ts +14 -0
  42. package/dist/disclosure/element.js +123 -0
  43. package/dist/disclosure/element.js.map +1 -0
  44. package/dist/disclosure/index.d.ts +307 -0
  45. package/dist/disclosure/index.js +66 -0
  46. package/dist/disclosure/index.js.map +1 -0
  47. package/dist/exit-this-page/element.d.ts +19 -0
  48. package/dist/exit-this-page/element.js +201 -0
  49. package/dist/exit-this-page/element.js.map +1 -0
  50. package/dist/exit-this-page/index.d.ts +330 -0
  51. package/dist/exit-this-page/index.js +54 -0
  52. package/dist/exit-this-page/index.js.map +1 -0
  53. package/dist/file-upload/element.d.ts +23 -0
  54. package/dist/file-upload/element.js +270 -0
  55. package/dist/file-upload/element.js.map +1 -0
  56. package/dist/file-upload/index.d.ts +46 -0
  57. package/dist/file-upload/index.js +65 -0
  58. package/dist/file-upload/index.js.map +1 -0
  59. package/dist/focus-links/element.d.ts +1 -0
  60. package/dist/focus-links/element.js +90 -0
  61. package/dist/focus-links/element.js.map +1 -0
  62. package/dist/focus-links/index.d.ts +288 -0
  63. package/dist/focus-links/index.js +7 -0
  64. package/dist/focus-links/index.js.map +1 -0
  65. package/dist/index.d.ts +13 -0
  66. package/dist/index.js +14 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/inline/accordion-element.js +1 -0
  69. package/dist/inline/auto-focus-element.js +1 -0
  70. package/dist/inline/autocomplete-element.js +2 -0
  71. package/dist/inline/button-element.js +1 -0
  72. package/dist/inline/character-count-element.js +1 -0
  73. package/dist/inline/choices-element.js +1 -0
  74. package/dist/inline/disclosure-element.js +1 -0
  75. package/dist/inline/exit-this-page-element.js +1 -0
  76. package/dist/inline/file-upload-element.js +1 -0
  77. package/dist/inline/focus-links-element.js +1 -0
  78. package/dist/inline/modal-element.js +1 -0
  79. package/dist/inline/password-input-element.js +1 -0
  80. package/dist/inline/tabs-element.js +1 -0
  81. package/dist/inline-script/index.d.ts +26 -0
  82. package/dist/inline-script/index.js +31 -0
  83. package/dist/inline-script/index.js.map +1 -0
  84. package/dist/modal/element.d.ts +10 -0
  85. package/dist/modal/element.js +114 -0
  86. package/dist/modal/element.js.map +1 -0
  87. package/dist/modal/index.d.ts +36 -0
  88. package/dist/modal/index.js +109 -0
  89. package/dist/modal/index.js.map +1 -0
  90. package/dist/password-input/element.d.ts +1 -0
  91. package/dist/password-input/element.js +134 -0
  92. package/dist/password-input/element.js.map +1 -0
  93. package/dist/password-input/index.d.ts +318 -0
  94. package/dist/password-input/index.js +35 -0
  95. package/dist/password-input/index.js.map +1 -0
  96. package/dist/tabs/element.d.ts +19 -0
  97. package/dist/tabs/element.js +416 -0
  98. package/dist/tabs/element.js.map +1 -0
  99. package/dist/tabs/index.d.ts +83 -0
  100. package/dist/tabs/index.js +138 -0
  101. package/dist/tabs/index.js.map +1 -0
  102. package/dist/utils/dom.d.ts +9 -0
  103. package/dist/utils/dom.js +27 -0
  104. package/dist/utils/dom.js.map +1 -0
  105. package/dist/utils/on-property-set.d.ts +9 -0
  106. package/dist/utils/on-property-set.js +38 -0
  107. package/dist/utils/on-property-set.js.map +1 -0
  108. package/dist/utils/set-focus.d.ts +11 -0
  109. package/dist/utils/set-focus.js +38 -0
  110. package/dist/utils/set-focus.js.map +1 -0
  111. package/dist/utils/set-up-when-ready.d.ts +6 -0
  112. package/dist/utils/set-up-when-ready.js +16 -0
  113. package/dist/utils/set-up-when-ready.js.map +1 -0
  114. package/dist/utils/slot.d.ts +13 -0
  115. package/dist/utils/slot.js +40 -0
  116. package/dist/utils/slot.js.map +1 -0
  117. package/dist/utils/translation.d.ts +13 -0
  118. package/dist/utils/translation.js +57 -0
  119. package/dist/utils/translation.js.map +1 -0
  120. package/licences/accessible-autocomplete.txt +20 -0
  121. package/package.json +49 -4
package/README.md CHANGED
@@ -1,3 +1,272 @@
1
- # Temporary Holding Version
1
+ # @govuk-react/primitives
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
4
+
5
+ Each primitive:
6
+
7
+ - works without JavaScript, through a fallback you choose
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
11
+
12
+ ## Inline scripts
13
+
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.
15
+
16
+ To render them from React on the server, `inline-script` has each script as a string, and an `InlineScript` component:
17
+
18
+ ```tsx
19
+ import { InlineScript, tabs } from '@govuk-react/primitives/inline-script';
20
+
21
+ <head>
22
+ <InlineScript script={tabs} nonce={nonce} />
23
+ </head>;
24
+ ```
25
+
26
+ The scripts are `accordion`, `autocomplete`, `autoFocus`, `button`, `characterCount`, `choices`, `disclosure`, `exitThisPage`, `fileUpload`, `focusLinks`, `modal`, `passwordInput` and `tabs`. `InlineScript` isn't a client component, so the scripts stay out of client bundles. A script React adds in the browser doesn't run, and isn't needed, since React's parts define their elements.
27
+
28
+ ## Accordion
29
+
30
+ ```tsx
31
+ import * as Accordion from '@govuk-react/primitives/accordion';
32
+
33
+ <Accordion.Root defaultValue={['web']}>
34
+ <Accordion.Controls>
35
+ <Accordion.ShowAll>
36
+ <Accordion.ShowAllText />
37
+ </Accordion.ShowAll>
38
+ </Accordion.Controls>
39
+ <Accordion.Section value="web">
40
+ <h2>
41
+ <Accordion.Fallback>Writing well for the web</Accordion.Fallback>
42
+ <Accordion.Trigger>
43
+ <Accordion.Label>Writing well for the web</Accordion.Label> <Accordion.ToggleText />
44
+ </Accordion.Trigger>
45
+ </h2>
46
+ <Accordion.Content id="web-content">…</Accordion.Content>
47
+ </Accordion.Section>
48
+ </Accordion.Root>;
49
+ ```
50
+
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".
52
+
53
+ `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
+
55
+ ## Tabs
56
+
57
+ ```tsx
58
+ import * as Tabs from '@govuk-react/primitives/tabs';
59
+
60
+ <Tabs.Root defaultValue="past-day">
61
+ <Tabs.List>
62
+ <Tabs.Trigger value="past-day">Past day</Tabs.Trigger>
63
+ <Tabs.Trigger value="past-week">Past week</Tabs.Trigger>
64
+ </Tabs.List>
65
+ <Tabs.Content value="past-day">…</Tabs.Content>
66
+ <Tabs.Content value="past-week">…</Tabs.Content>
67
+ </Tabs.Root>;
68
+ ```
69
+
70
+ Each panel holds a hidden radio, and the radio group is the source of truth, as in the reference. Choosing a tab checks its radio, and the radio's native change updates the tabs and calls `onValueChange`.
71
+
72
+ The root sets how the tabs work without JavaScript, and its parts match it:
73
+
74
+ - `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.
76
+
77
+ 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
+
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.
80
+
81
+ `orientation` (`"horizontal"` or `"vertical"`) sets the axis of the arrow keys.
82
+
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.
84
+
85
+ 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
+
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.
88
+
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.
90
+
91
+ ## Disclosure
92
+
93
+ ```tsx
94
+ import * as Disclosure from '@govuk-react/primitives/disclosure';
95
+
96
+ <nav aria-label="Menu">
97
+ <Disclosure.Root media="(min-width: 40.0625em)">
98
+ <Disclosure.Toggle>Menu</Disclosure.Toggle>
99
+ <Disclosure.Content asChild>
100
+ <ul id="navigation">…</ul>
101
+ </Disclosure.Content>
102
+ </Disclosure.Root>
103
+ </nav>;
104
+ ```
105
+
106
+ A button that shows and hides some content, such as a navigation menu on small screens. Without JavaScript the content is shown and the button hidden. While `media` matches, the content is always shown and the button hidden.
107
+
108
+ `open` and `onOpenChange` control it once hydrated, such as to close a menu after navigating. A user's click before hydration is reported through `onOpenChange` rather than undone. `defaultOpen` starts it open.
109
+
110
+ ## Modal
111
+
112
+ ```tsx
113
+ import * as Modal from '@govuk-react/primitives/modal';
114
+
115
+ <Modal.Root>
116
+ <Modal.Trigger>Delete account</Modal.Trigger>
117
+ <Modal.Content>
118
+ <Modal.Title>Are you sure?</Modal.Title>
119
+ <Modal.Close>Cancel</Modal.Close>
120
+ </Modal.Content>
121
+ </Modal.Root>;
122
+ ```
123
+
124
+ `Content` is a native `dialog`, and `Trigger` and `Close` are buttons with invoker commands (`command="show-modal"` and `command="close"`, with `commandfor` naming the dialog). Where the browser supports them (Chrome and Edge 135, Firefox 144, Safari 26.2), the dialog opens as a true modal without JavaScript: the page behind is inert, focus moves into the dialog and Escape closes it. In older browsers, the `<govuk-react-modal>` element runs the commands once its script loads.
125
+
126
+ `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
+
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`.
129
+
130
+ ## Character count
131
+
132
+ ```tsx
133
+ import * as CharacterCount from '@govuk-react/primitives/character-count';
134
+
135
+ <CharacterCount.Root maxLength={200}>
136
+ <label htmlFor="more-detail">Can you provide more detail?</label>
137
+ <CharacterCount.Input id="more-detail" aria-describedby="more-detail-info" maxLength={200} />
138
+ <CharacterCount.Description id="more-detail-info">You can enter up to 200 characters</CharacterCount.Description>
139
+ <CharacterCount.Status />
140
+ <CharacterCount.ScreenReaderStatus className="visually-hidden" />
141
+ </CharacterCount.Root>;
142
+ ```
143
+
144
+ Without JavaScript the `Description` is shown and both statuses are hidden. On upgrade the element visually hides the description, removes the field's `maxlength` so users can see by how much they're over, and shows `Status`, which updates as the user types. As in govuk-frontend, `ScreenReaderStatus` updates once the user pauses, rather than on every key, and is hidden from screen readers below `threshold`.
145
+
146
+ `countType` is "length" (the default, as `maxlength` counts), "characters" (as users see them, such as an emoji as one) or "words". The messages are English by default, and take a message for each plural form. The statuses get `data-state` ("under", "at" or "over") for styling, or pass class names such as `overLimitClass`. The field's value is the state, so a value React sets is counted too.
147
+
148
+ ## Autocomplete
149
+
150
+ ```tsx
151
+ import * as Autocomplete from '@govuk-react/primitives/autocomplete';
152
+
153
+ <label htmlFor="country">Country</label>
154
+ <Autocomplete.Root onQueryChange={fetchCountries} onConfirm={setCountry}>
155
+ <Autocomplete.Input id="country" name="country" />
156
+ <Autocomplete.Listbox>
157
+ {countries.map((country) => (
158
+ <Autocomplete.Option key={country} value={country}>
159
+ {country}
160
+ </Autocomplete.Option>
161
+ ))}
162
+ <Autocomplete.NoResults />
163
+ </Autocomplete.Listbox>
164
+ <Autocomplete.Status />
165
+ <Autocomplete.AssistiveHint />
166
+ </Autocomplete.Root>;
167
+ ```
168
+
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.
170
+
171
+ 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
+
173
+ `minLength` is the length the query needs before options show. `onConfirm` is called when the user confirms an option. With `submitOnConfirm`, confirming an option submits the form, and Enter submits it while no option is highlighted. As in accessible-autocomplete, focus leaving a highlighted option confirms it, unless `confirmOnBlur` is `false`. The status messages are English by default, and take a message for each plural form.
174
+
175
+ Not ported from accessible-autocomplete: `showAllValues` and its dropdown arrow, `enhanceSelectElement`, `autoselect` and its inline hint, `displayMenu` (style the `Listbox` instead) and the iOS position workaround.
176
+
177
+ accessible-autocomplete is Copyright (c) 2017 Crown Copyright (Government Digital Service), under the [MIT licence](licences/accessible-autocomplete.txt).
178
+
179
+ ## File upload
180
+
181
+ ```tsx
182
+ import * as FileUpload from '@govuk-react/primitives/file-upload';
183
+
184
+ <label id="photo-label" htmlFor="photo">Upload a photo</label>
185
+ <FileUpload.Root>
186
+ <FileUpload.DropZone>
187
+ <FileUpload.Button>
188
+ <FileUpload.Status />
189
+ <FileUpload.Separator className="visually-hidden" />
190
+ Choose file or drop file
191
+ </FileUpload.Button>
192
+ <FileUpload.Input id="photo" name="photo" />
193
+ </FileUpload.DropZone>
194
+ <FileUpload.Announcements className="visually-hidden" />
195
+ </FileUpload.Root>;
196
+ ```
197
+
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`.
199
+
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`.
201
+
202
+ ## Choices
203
+
204
+ ```tsx
205
+ import * as Choices from '@govuk-react/primitives/choices';
206
+
207
+ <Choices.Root>
208
+ <Choices.Input type="radio" id="email" name="contact" value="email" controls="email-reveal" />
209
+ <label htmlFor="email">Email</label>
210
+ <Choices.Conditional id="email-reveal">…</Choices.Conditional>
211
+ </Choices.Root>;
212
+ ```
213
+
214
+ 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
+
216
+ ## AutoFocus
217
+
218
+ ```tsx
219
+ import * as AutoFocus from '@govuk-react/primitives/auto-focus';
220
+
221
+ <AutoFocus.Root>
222
+ <AutoFocus.Target role="alert">There is a problem</AutoFocus.Target>
223
+ </AutoFocus.Root>;
224
+ ```
225
+
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.
227
+
228
+ ## FocusLinks
229
+
230
+ ```tsx
231
+ import * as FocusLinks from '@govuk-react/primitives/focus-links';
232
+
233
+ <FocusLinks.Root focusedClass="focused">
234
+ <a href="#main-content">Skip to main content</a>
235
+ </FocusLinks.Root>;
236
+ ```
237
+
238
+ Makes links inside it, to a part of the same page, move focus there. A link to a form field focuses the field and scrolls its label into view, or its fieldset's legend, as govuk-frontend's error summary does. A link to anything else focuses it with `tabindex="-1"` and `focusedClass` until focus moves on, as govuk-frontend's skip link does. Without JavaScript the browser follows the link as usual.
239
+
240
+ ## Button
241
+
242
+ ```tsx
243
+ import * as Button from '@govuk-react/primitives/button';
244
+
245
+ <Button.Root preventDoubleClick>Save and continue</Button.Root>;
246
+
247
+ <Button.Root asChild>
248
+ <a href="/start" role="button">
249
+ Start now
250
+ </a>
251
+ </Button.Root>;
252
+ ```
253
+
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`.
255
+
256
+ ## ExitThisPage
257
+
258
+ ```tsx
259
+ import * as ExitThisPage from '@govuk-react/primitives/exit-this-page';
260
+
261
+ <ExitThisPage.SkipLink href="https://www.bbc.co.uk/weather">Exit this page</ExitThisPage.SkipLink>;
262
+
263
+ <ExitThisPage.Root hideContentClass="hide-content" overlayClass="overlay">
264
+ <ExitThisPage.Button href="https://www.bbc.co.uk/weather">
265
+ Exit this page
266
+ <ExitThisPage.Indicator />
267
+ </ExitThisPage.Button>
268
+ <ExitThisPage.Status className="visually-hidden" />
269
+ </ExitThisPage.Root>;
270
+ ```
271
+
272
+ Lets users leave the page quickly. Without JavaScript the button is a plain link. Once upgraded, the button, a `SkipLink`, or pressing Shift 3 times within 5 seconds hides the page behind an overlay that says it's loading, and goes to the button's `href`. `Indicator` shows the presses, and `Status` tells screen readers how many more are needed. Only the page's first `Root` listens for Shift and skip links. Before leaving, the element fires a cancelable `govuk-react-exit-this-page:exit` event, so a test can stay on the page.
@@ -0,0 +1,14 @@
1
+ declare global {
2
+ interface HTMLElementEventMap {
3
+ 'govuk-react-accordion:change': CustomEvent<{
4
+ value: string[];
5
+ }>;
6
+ }
7
+ }
8
+ export declare const tagName = "govuk-react-accordion";
9
+ export interface AccordionElement extends HTMLElement {
10
+ /** The open sections' values, once upgraded. */
11
+ readonly openValues: string[] | undefined;
12
+ /** The open sections after the user's last change before `value` was first set, such as before React hydrated. */
13
+ readonly pickedValue: string[] | undefined;
14
+ }
@@ -0,0 +1,302 @@
1
+ /*
2
+ * <govuk-react-accordion>: a headless, light-DOM custom element that lets users show and hide
3
+ * sections of content, with or without React.
4
+ *
5
+ * Without JavaScript every section is shown, under a plain heading. Each section also holds a
6
+ * hidden button with the same heading. On upgrade the element shows the buttons and hides the
7
+ * plain headings, then each button shows and hides its section's content, and a "show all"
8
+ * button shows or hides every section. The rendered markup is never moved, so React can keep
9
+ * rendering it. Content is hidden with `hidden="until-found"`, so find in page still opens it.
10
+ *
11
+ * Markup inside the element:
12
+ * - `[data-accordion-controls]` (optional): holds the "show all" button. Rendered `hidden`.
13
+ * - `button[data-accordion-show-all]`, with a `[data-accordion-show-all-text]` for its text.
14
+ * - `[data-accordion-section][data-value]`: a section. `data-expanded` opens it at first.
15
+ * - `[data-accordion-fallback]`: the plain heading and summary, hidden on upgrade.
16
+ * - `button[data-accordion-trigger]`: rendered `hidden`. Its accessible name is the text of its
17
+ * `[data-accordion-label]` elements and the show or hide label. Its
18
+ * `[data-accordion-toggle-text]` shows the show or hide text.
19
+ * - `[data-accordion-content]`: the content, with an id.
20
+ * - `[data-accordion-icon]` (optional): in the buttons, given `collapsed-icon-class` while
21
+ * collapsed.
22
+ *
23
+ * Attributes:
24
+ * - `value`: the open sections' values, separated by spaces, to control them. A user's click only
25
+ * fires the change event, and the sections change when `value` does.
26
+ * - `default-value`: the sections open at first, instead of `data-expanded`.
27
+ * - `remember-expanded`: "false" stops the open sections being remembered in session storage,
28
+ * keyed by content id, as govuk-frontend does.
29
+ * - `show-section-text`, `hide-section-text`, `show-section-label`, `hide-section-label`,
30
+ * `show-all-sections-text`, `hide-all-sections-text`: the text, English by default.
31
+ * - `upgraded-class`, `expanded-section-class`, `collapsed-icon-class`: classes to add, for styles
32
+ * keyed off classes rather than `data-upgraded`, `data-state` and `aria-expanded`.
33
+ *
34
+ * A user's click fires a bubbling `govuk-react-accordion:change` event with `{ value }`, the open
35
+ * sections' values.
36
+ */
37
+ import { classesOf, setText } from '../utils/dom.js';
38
+ export const tagName = 'govuk-react-accordion';
39
+ const defaults = {
40
+ 'show-section-text': 'Show',
41
+ 'hide-section-text': 'Hide',
42
+ 'show-section-label': 'Show this section',
43
+ 'hide-section-label': 'Hide this section',
44
+ 'show-all-sections-text': 'Show all sections',
45
+ 'hide-all-sections-text': 'Hide all sections',
46
+ };
47
+ const valuesOf = (attribute) => attribute === null || attribute === void 0 ? void 0 : attribute.split(/\s+/).filter(Boolean);
48
+ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {
49
+ class GovukReactAccordion extends HTMLElement {
50
+ constructor() {
51
+ super(...arguments);
52
+ this.open = new Set();
53
+ this.upgraded = false;
54
+ this.controlled = false;
55
+ this.prepared = new WeakSet();
56
+ this.onClick = (event) => {
57
+ var _a;
58
+ const target = event.target instanceof Element ? event.target : null;
59
+ const trigger = target === null || target === void 0 ? void 0 : target.closest('button[data-accordion-trigger]');
60
+ if (trigger && this.ownsElement(trigger)) {
61
+ const value = (_a = this.sectionOf(trigger)) === null || _a === void 0 ? void 0 : _a.dataset.value;
62
+ if (value === undefined)
63
+ return;
64
+ const next = new Set(this.open);
65
+ if (next.has(value))
66
+ next.delete(value);
67
+ else
68
+ next.add(value);
69
+ this.change(next);
70
+ return;
71
+ }
72
+ const showAll = target === null || target === void 0 ? void 0 : target.closest('button[data-accordion-show-all]');
73
+ if (showAll && this.ownsElement(showAll)) {
74
+ const values = this.sections.map((section) => { var _a; return (_a = section.dataset.value) !== null && _a !== void 0 ? _a : ''; });
75
+ this.change(new Set(this.allOpen ? [] : values));
76
+ }
77
+ };
78
+ // Find in page opens a collapsed section that holds the match.
79
+ this.onBeforeMatch = (event) => {
80
+ const section = event.target instanceof Element ? this.sectionOf(event.target) : undefined;
81
+ const value = section === null || section === void 0 ? void 0 : section.dataset.value;
82
+ if (value === undefined || this.open.has(value))
83
+ return;
84
+ this.change(new Set([...this.open, value]), true);
85
+ };
86
+ }
87
+ static get observedAttributes() {
88
+ return ['value'];
89
+ }
90
+ get openValues() {
91
+ return this.upgraded ? [...this.open] : undefined;
92
+ }
93
+ get pickedValue() {
94
+ return this.picked;
95
+ }
96
+ connectedCallback() {
97
+ // Sections can be parsed or rendered later, and React can rewrite a class attribute.
98
+ this.observer = new MutationObserver((records) => {
99
+ if (!this.upgraded) {
100
+ this.setup();
101
+ return;
102
+ }
103
+ if (records.some((record) => record.type === 'childList'))
104
+ this.sections.forEach((section) => this.prepare(section));
105
+ this.render();
106
+ });
107
+ this.observer.observe(this, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });
108
+ if (this.upgraded) {
109
+ // Moved, rather than new: keep the open sections.
110
+ this.listen();
111
+ this.render();
112
+ }
113
+ else {
114
+ this.setup();
115
+ }
116
+ }
117
+ disconnectedCallback() {
118
+ var _a;
119
+ (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
120
+ this.removeEventListener('click', this.onClick);
121
+ this.removeEventListener('beforematch', this.onBeforeMatch, true);
122
+ }
123
+ attributeChangedCallback() {
124
+ const value = valuesOf(this.getAttribute('value'));
125
+ this.controlled = value !== undefined;
126
+ if (!value)
127
+ return;
128
+ this.open = new Set(value);
129
+ this.render();
130
+ }
131
+ get sections() {
132
+ return this.own('[data-accordion-section]');
133
+ }
134
+ get allOpen() {
135
+ return this.sections.every((section) => { var _a; return this.open.has((_a = section.dataset.value) !== null && _a !== void 0 ? _a : ''); });
136
+ }
137
+ own(selector) {
138
+ // Leave nested accordions to their own element.
139
+ return Array.from(this.querySelectorAll(selector)).filter((element) => this.ownsElement(element));
140
+ }
141
+ ownsElement(element) {
142
+ return element.closest(tagName) === this;
143
+ }
144
+ sectionOf(element) {
145
+ const section = element.closest('[data-accordion-section]');
146
+ return section && this.ownsElement(section) ? section : undefined;
147
+ }
148
+ find(section, selector) {
149
+ return Array.from(section.querySelectorAll(selector)).find((element) => this.sectionOf(element) === section);
150
+ }
151
+ text(name) {
152
+ var _a;
153
+ return (_a = this.getAttribute(name)) !== null && _a !== void 0 ? _a : defaults[name];
154
+ }
155
+ get remember() {
156
+ return this.getAttribute('remember-expanded') !== 'false';
157
+ }
158
+ setup() {
159
+ const sections = this.sections;
160
+ if (!sections.some((section) => this.find(section, 'button[data-accordion-trigger]')))
161
+ return;
162
+ this.upgraded = true;
163
+ const value = valuesOf(this.getAttribute('value'));
164
+ this.controlled = value !== undefined;
165
+ this.open = new Set(value !== null && value !== void 0 ? value : valuesOf(this.getAttribute('default-value')));
166
+ this.dataset.upgraded = '';
167
+ const upgradedClasses = classesOf(this.getAttribute('upgraded-class'));
168
+ if (upgradedClasses.length)
169
+ this.classList.add(...upgradedClasses);
170
+ this.own('[data-accordion-controls]').forEach((controls) => {
171
+ controls.hidden = false;
172
+ });
173
+ sections.forEach((section) => this.prepare(section));
174
+ this.listen();
175
+ this.render();
176
+ }
177
+ listen() {
178
+ this.addEventListener('click', this.onClick);
179
+ // `beforematch` doesn't bubble.
180
+ this.addEventListener('beforematch', this.onBeforeMatch, true);
181
+ }
182
+ /** Swaps a section's fallback for its trigger, once, and sets its first state. */
183
+ prepare(section) {
184
+ var _a;
185
+ const trigger = this.find(section, 'button[data-accordion-trigger]');
186
+ if (!trigger || this.prepared.has(section))
187
+ return;
188
+ this.prepared.add(section);
189
+ const value = (_a = section.dataset.value) !== null && _a !== void 0 ? _a : '';
190
+ if (!this.controlled) {
191
+ const defaultValue = valuesOf(this.getAttribute('default-value'));
192
+ if (defaultValue ? defaultValue.includes(value) : section.hasAttribute('data-expanded'))
193
+ this.open.add(value);
194
+ this.restore(section);
195
+ }
196
+ Array.from(section.querySelectorAll('[data-accordion-fallback]'))
197
+ .filter((fallback) => this.sectionOf(fallback) === section)
198
+ .forEach((fallback) => {
199
+ fallback.hidden = true;
200
+ });
201
+ trigger.hidden = false;
202
+ const content = this.find(section, '[data-accordion-content]');
203
+ if (content === null || content === void 0 ? void 0 : content.id)
204
+ trigger.setAttribute('aria-controls', content.id);
205
+ }
206
+ /** A section remembered from earlier in the session, as in govuk-frontend. */
207
+ restore(section) {
208
+ var _a;
209
+ const id = (_a = this.find(section, '[data-accordion-content]')) === null || _a === void 0 ? void 0 : _a.id;
210
+ const value = section.dataset.value;
211
+ if (!this.remember || !id || value === undefined)
212
+ return;
213
+ try {
214
+ const state = window.sessionStorage.getItem(id);
215
+ if (state === 'true')
216
+ this.open.add(value);
217
+ else if (state === 'false')
218
+ this.open.delete(value);
219
+ }
220
+ catch (_b) {
221
+ // Storage can be unavailable.
222
+ }
223
+ }
224
+ /** Remembers the sections that changed, as govuk-frontend does. */
225
+ store(previous) {
226
+ if (!this.remember)
227
+ return;
228
+ this.sections.forEach((section) => {
229
+ var _a, _b;
230
+ const value = (_a = section.dataset.value) !== null && _a !== void 0 ? _a : '';
231
+ const id = (_b = this.find(section, '[data-accordion-content]')) === null || _b === void 0 ? void 0 : _b.id;
232
+ if (!id || previous.has(value) === this.open.has(value))
233
+ return;
234
+ try {
235
+ window.sessionStorage.setItem(id, String(this.open.has(value)));
236
+ }
237
+ catch (_c) {
238
+ // Storage can be unavailable.
239
+ }
240
+ });
241
+ }
242
+ change(next, force = false) {
243
+ const value = this.sections.map((section) => { var _a; return (_a = section.dataset.value) !== null && _a !== void 0 ? _a : ''; }).filter((v) => next.has(v));
244
+ // Find in page must show the match, so it opens the section even when controlled.
245
+ if (!this.controlled || force) {
246
+ const previous = this.open;
247
+ this.open = new Set(value);
248
+ if (!this.controlled) {
249
+ this.picked = value;
250
+ this.store(previous);
251
+ }
252
+ this.render();
253
+ }
254
+ this.dispatchEvent(new CustomEvent('govuk-react-accordion:change', { detail: { value }, bubbles: true }));
255
+ }
256
+ render() {
257
+ if (!this.upgraded)
258
+ return;
259
+ const expandedClasses = classesOf(this.getAttribute('expanded-section-class'));
260
+ const collapsedIconClasses = classesOf(this.getAttribute('collapsed-icon-class'));
261
+ const setIcon = (root, expanded) => {
262
+ Array.from(root.querySelectorAll('[data-accordion-icon]')).forEach((icon) => {
263
+ collapsedIconClasses.forEach((name) => icon.classList.toggle(name, !expanded));
264
+ });
265
+ };
266
+ this.sections.forEach((section) => {
267
+ var _a;
268
+ const expanded = this.open.has((_a = section.dataset.value) !== null && _a !== void 0 ? _a : '');
269
+ const trigger = this.find(section, 'button[data-accordion-trigger]');
270
+ const content = this.find(section, '[data-accordion-content]');
271
+ section.dataset.state = expanded ? 'open' : 'closed';
272
+ expandedClasses.forEach((name) => section.classList.toggle(name, expanded));
273
+ if (content) {
274
+ if (expanded)
275
+ content.removeAttribute('hidden');
276
+ else
277
+ content.setAttribute('hidden', 'until-found');
278
+ }
279
+ if (!trigger)
280
+ return;
281
+ trigger.setAttribute('aria-expanded', String(expanded));
282
+ const labels = Array.from(trigger.querySelectorAll('[data-accordion-label]')).map((label) => { var _a, _b; return (_b = (_a = label.textContent) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : ''; });
283
+ trigger.setAttribute('aria-label', [...labels, this.text(expanded ? 'hide-section-label' : 'show-section-label')].join(' , '));
284
+ const toggleText = trigger.querySelector('[data-accordion-toggle-text]');
285
+ if (toggleText)
286
+ setText(toggleText, this.text(expanded ? 'hide-section-text' : 'show-section-text'));
287
+ setIcon(trigger, expanded);
288
+ });
289
+ const allOpen = this.allOpen;
290
+ this.own('button[data-accordion-show-all]').forEach((showAll) => {
291
+ showAll.setAttribute('aria-expanded', String(allOpen));
292
+ const text = showAll.querySelector('[data-accordion-show-all-text]');
293
+ if (text)
294
+ setText(text, this.text(allOpen ? 'hide-all-sections-text' : 'show-all-sections-text'));
295
+ setIcon(showAll, allOpen);
296
+ });
297
+ }
298
+ }
299
+ if (!customElements.get(tagName))
300
+ customElements.define(tagName, GovukReactAccordion);
301
+ }
302
+ //# sourceMappingURL=element.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/accordion/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAQrD,MAAM,CAAC,MAAM,OAAO,GAAG,uBAAuB,CAAC;AAS/C,MAAM,QAAQ,GAAG;IACf,mBAAmB,EAAE,MAAM;IAC3B,mBAAmB,EAAE,MAAM;IAC3B,oBAAoB,EAAE,mBAAmB;IACzC,oBAAoB,EAAE,mBAAmB;IACzC,wBAAwB,EAAE,mBAAmB;IAC7C,wBAAwB,EAAE,mBAAmB;CAC9C,CAAC;AAEF,MAAM,QAAQ,GAAG,CAAC,SAAwB,EAAE,EAAE,CAAC,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;AAEvF,IAAI,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;IAChF,MAAM,mBAAoB,SAAQ,WAAW;QAA7C;;YAKU,SAAI,GAAG,IAAI,GAAG,EAAU,CAAC;YAEzB,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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 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"]}