@govuk-react/primitives 0.2.0 → 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 (267) hide show
  1. package/README.md +100 -25
  2. package/dist/{accordion-element.d.ts → accordion/element.d.ts} +5 -5
  3. package/dist/accordion/element.js +302 -0
  4. package/dist/accordion/element.js.map +1 -0
  5. package/dist/accordion/index.d.ts +70 -0
  6. package/dist/accordion/index.js +140 -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 +15 -0
  12. package/dist/auto-focus/index.js +39 -0
  13. package/dist/auto-focus/index.js.map +1 -0
  14. package/dist/{autocomplete-element.d.ts → autocomplete/element.d.ts} +11 -11
  15. package/dist/autocomplete/element.js +597 -0
  16. package/dist/autocomplete/element.js.map +1 -0
  17. package/dist/{index-D7lMYMUR.d.ts → autocomplete/index.d.ts} +39 -62
  18. package/dist/autocomplete/index.js +100 -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 +12 -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 +10 -0
  36. package/dist/choices/element.js +177 -0
  37. package/dist/choices/element.js.map +1 -0
  38. package/dist/{index-WuGvkTxu.d.ts → choices/index.d.ts} +30 -44
  39. package/dist/choices/index.js +37 -0
  40. package/dist/choices/index.js.map +1 -0
  41. package/dist/{disclosure-element.d.ts → disclosure/element.d.ts} +5 -5
  42. package/dist/disclosure/element.js +132 -0
  43. package/dist/disclosure/element.js.map +1 -0
  44. package/dist/{index-D4Gzyvfu.d.ts → disclosure/index.d.ts} +43 -56
  45. package/dist/disclosure/index.js +76 -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 +200 -0
  49. package/dist/exit-this-page/element.js.map +1 -0
  50. package/dist/{index-qF0jIQCW.d.ts → exit-this-page/index.d.ts} +44 -68
  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 +28 -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/{index-BR3MAGF8.d.ts → focus-links/index.d.ts} +24 -35
  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 -17
  66. package/dist/index.js +13 -72
  67. package/dist/index.js.map +1 -1
  68. package/dist/inline/accordion-element.js +1 -1
  69. package/dist/inline/auto-focus-element.js +1 -1
  70. package/dist/inline/autocomplete-element.js +1 -1
  71. package/dist/inline/character-count-element.js +1 -1
  72. package/dist/inline/choices-element.js +1 -1
  73. package/dist/inline/disclosure-element.js +1 -1
  74. package/dist/inline/exit-this-page-element.js +1 -1
  75. package/dist/inline/file-upload-element.js +1 -1
  76. package/dist/inline/focus-links-element.js +1 -1
  77. package/dist/inline/modal-element.js +1 -1
  78. package/dist/inline/password-input-element.js +1 -1
  79. package/dist/inline/tabs-element.js +1 -1
  80. package/dist/inline-script/index.d.ts +26 -0
  81. package/dist/inline-script/index.js +31 -0
  82. package/dist/inline-script/index.js.map +1 -0
  83. package/dist/{modal-element.d.ts → modal/element.d.ts} +2 -4
  84. package/dist/modal/element.js +229 -0
  85. package/dist/modal/element.js.map +1 -0
  86. package/dist/modal/index.d.ts +41 -0
  87. package/dist/modal/index.js +145 -0
  88. package/dist/modal/index.js.map +1 -0
  89. package/dist/password-input/element.d.ts +1 -0
  90. package/dist/password-input/element.js +150 -0
  91. package/dist/password-input/element.js.map +1 -0
  92. package/dist/{index-sEHnx4-M.d.ts → password-input/index.d.ts} +33 -49
  93. package/dist/password-input/index.js +37 -0
  94. package/dist/password-input/index.js.map +1 -0
  95. package/dist/styles.css +11 -0
  96. package/dist/{tabs-element.d.ts → tabs/element.d.ts} +5 -5
  97. package/dist/tabs/element.js +423 -0
  98. package/dist/tabs/element.js.map +1 -0
  99. package/dist/tabs/index.d.ts +74 -0
  100. package/dist/tabs/index.js +142 -0
  101. package/dist/tabs/index.js.map +1 -0
  102. package/dist/utils/change-details.d.ts +11 -0
  103. package/dist/utils/change-details.js +3 -0
  104. package/dist/utils/change-details.js.map +1 -0
  105. package/dist/utils/dom.d.ts +9 -0
  106. package/dist/utils/dom.js +27 -0
  107. package/dist/utils/dom.js.map +1 -0
  108. package/dist/utils/on-property-change.d.ts +7 -0
  109. package/dist/utils/on-property-change.js +19 -0
  110. package/dist/utils/on-property-change.js.map +1 -0
  111. package/dist/utils/set-focus.d.ts +11 -0
  112. package/dist/utils/set-focus.js +38 -0
  113. package/dist/utils/set-focus.js.map +1 -0
  114. package/dist/utils/set-up-when-ready.d.ts +6 -0
  115. package/dist/utils/set-up-when-ready.js +16 -0
  116. package/dist/utils/set-up-when-ready.js.map +1 -0
  117. package/dist/utils/slot.d.ts +15 -0
  118. package/dist/utils/slot.js +62 -0
  119. package/dist/utils/slot.js.map +1 -0
  120. package/dist/utils/translation.d.ts +13 -0
  121. package/dist/utils/translation.js +57 -0
  122. package/dist/utils/translation.js.map +1 -0
  123. package/package.json +17 -4
  124. package/dist/accordion-element.js +0 -9
  125. package/dist/accordion-element.js.map +0 -1
  126. package/dist/accordion.d.ts +0 -2
  127. package/dist/accordion.js +0 -34
  128. package/dist/accordion.js.map +0 -1
  129. package/dist/auto-focus-element.d.ts +0 -3
  130. package/dist/auto-focus-element.js +0 -10
  131. package/dist/auto-focus-element.js.map +0 -1
  132. package/dist/auto-focus.d.ts +0 -2
  133. package/dist/auto-focus.js +0 -15
  134. package/dist/auto-focus.js.map +0 -1
  135. package/dist/autocomplete-element.js +0 -12
  136. package/dist/autocomplete-element.js.map +0 -1
  137. package/dist/autocomplete.d.ts +0 -4
  138. package/dist/autocomplete.js +0 -25
  139. package/dist/autocomplete.js.map +0 -1
  140. package/dist/button-element.d.ts +0 -2
  141. package/dist/button-element.js +0 -3
  142. package/dist/button-element.js.map +0 -1
  143. package/dist/button.d.ts +0 -2
  144. package/dist/button.js +0 -12
  145. package/dist/button.js.map +0 -1
  146. package/dist/character-count-element.d.ts +0 -10
  147. package/dist/character-count-element.js +0 -10
  148. package/dist/character-count-element.js.map +0 -1
  149. package/dist/character-count.d.ts +0 -3
  150. package/dist/character-count.js +0 -26
  151. package/dist/character-count.js.map +0 -1
  152. package/dist/choices-element.d.ts +0 -8
  153. package/dist/choices-element.js +0 -9
  154. package/dist/choices-element.js.map +0 -1
  155. package/dist/choices.d.ts +0 -2
  156. package/dist/choices.js +0 -16
  157. package/dist/choices.js.map +0 -1
  158. package/dist/chunk-2IHAQAYF.js +0 -23
  159. package/dist/chunk-2IHAQAYF.js.map +0 -1
  160. package/dist/chunk-2ZJVSNC2.js +0 -31
  161. package/dist/chunk-2ZJVSNC2.js.map +0 -1
  162. package/dist/chunk-47NMY4SS.js +0 -108
  163. package/dist/chunk-47NMY4SS.js.map +0 -1
  164. package/dist/chunk-4XAR4FFG.js +0 -83
  165. package/dist/chunk-4XAR4FFG.js.map +0 -1
  166. package/dist/chunk-5HWRMQK2.js +0 -91
  167. package/dist/chunk-5HWRMQK2.js.map +0 -1
  168. package/dist/chunk-6ZFU4VYW.js +0 -41
  169. package/dist/chunk-6ZFU4VYW.js.map +0 -1
  170. package/dist/chunk-B2I4J5NL.js +0 -264
  171. package/dist/chunk-B2I4J5NL.js.map +0 -1
  172. package/dist/chunk-DPERPCUH.js +0 -188
  173. package/dist/chunk-DPERPCUH.js.map +0 -1
  174. package/dist/chunk-ECYGKE4D.js +0 -168
  175. package/dist/chunk-ECYGKE4D.js.map +0 -1
  176. package/dist/chunk-ESBMTI25.js +0 -11
  177. package/dist/chunk-ESBMTI25.js.map +0 -1
  178. package/dist/chunk-ET7DCQM7.js +0 -133
  179. package/dist/chunk-ET7DCQM7.js.map +0 -1
  180. package/dist/chunk-F5XFC4QJ.js +0 -177
  181. package/dist/chunk-F5XFC4QJ.js.map +0 -1
  182. package/dist/chunk-GVGBDSDN.js +0 -78
  183. package/dist/chunk-GVGBDSDN.js.map +0 -1
  184. package/dist/chunk-IZQ2C4BC.js +0 -351
  185. package/dist/chunk-IZQ2C4BC.js.map +0 -1
  186. package/dist/chunk-L7E6GN2D.js +0 -87
  187. package/dist/chunk-L7E6GN2D.js.map +0 -1
  188. package/dist/chunk-LWIA644X.js +0 -34
  189. package/dist/chunk-LWIA644X.js.map +0 -1
  190. package/dist/chunk-NX4B3NKM.js +0 -35
  191. package/dist/chunk-NX4B3NKM.js.map +0 -1
  192. package/dist/chunk-PNWPGD7B.js +0 -68
  193. package/dist/chunk-PNWPGD7B.js.map +0 -1
  194. package/dist/chunk-QLQ6O7OW.js +0 -111
  195. package/dist/chunk-QLQ6O7OW.js.map +0 -1
  196. package/dist/chunk-RDUPELOK.js +0 -55
  197. package/dist/chunk-RDUPELOK.js.map +0 -1
  198. package/dist/chunk-RPMHI67T.js +0 -104
  199. package/dist/chunk-RPMHI67T.js.map +0 -1
  200. package/dist/chunk-TE4RUYVK.js +0 -97
  201. package/dist/chunk-TE4RUYVK.js.map +0 -1
  202. package/dist/chunk-TJVBFRIE.js +0 -60
  203. package/dist/chunk-TJVBFRIE.js.map +0 -1
  204. package/dist/chunk-U5OKNKYC.js +0 -510
  205. package/dist/chunk-U5OKNKYC.js.map +0 -1
  206. package/dist/chunk-UXJO4AJP.js +0 -290
  207. package/dist/chunk-UXJO4AJP.js.map +0 -1
  208. package/dist/chunk-VNXXENCU.js +0 -39
  209. package/dist/chunk-VNXXENCU.js.map +0 -1
  210. package/dist/chunk-XGK73UCD.js +0 -62
  211. package/dist/chunk-XGK73UCD.js.map +0 -1
  212. package/dist/chunk-XJYLFTYE.js +0 -157
  213. package/dist/chunk-XJYLFTYE.js.map +0 -1
  214. package/dist/chunk-YCESNTXQ.js +0 -241
  215. package/dist/chunk-YCESNTXQ.js.map +0 -1
  216. package/dist/chunk-ZTJLVNR4.js +0 -62
  217. package/dist/chunk-ZTJLVNR4.js.map +0 -1
  218. package/dist/disclosure-element.js +0 -9
  219. package/dist/disclosure-element.js.map +0 -1
  220. package/dist/disclosure.d.ts +0 -2
  221. package/dist/disclosure.js +0 -16
  222. package/dist/disclosure.js.map +0 -1
  223. package/dist/exit-this-page-element.d.ts +0 -22
  224. package/dist/exit-this-page-element.js +0 -13
  225. package/dist/exit-this-page-element.js.map +0 -1
  226. package/dist/exit-this-page.d.ts +0 -3
  227. package/dist/exit-this-page.js +0 -25
  228. package/dist/exit-this-page.js.map +0 -1
  229. package/dist/file-upload-element.d.ts +0 -27
  230. package/dist/file-upload-element.js +0 -14
  231. package/dist/file-upload-element.js.map +0 -1
  232. package/dist/file-upload.d.ts +0 -3
  233. package/dist/file-upload.js +0 -25
  234. package/dist/file-upload.js.map +0 -1
  235. package/dist/focus-links-element.d.ts +0 -3
  236. package/dist/focus-links-element.js +0 -10
  237. package/dist/focus-links-element.js.map +0 -1
  238. package/dist/focus-links.d.ts +0 -2
  239. package/dist/focus-links.js +0 -12
  240. package/dist/focus-links.js.map +0 -1
  241. package/dist/index--FxJgSOS.d.ts +0 -108
  242. package/dist/index-Bul0NJh_.d.ts +0 -310
  243. package/dist/index-CikOyFud.d.ts +0 -54
  244. package/dist/index-D8N5vxTL.d.ts +0 -90
  245. package/dist/index-DMWpkC_d.d.ts +0 -105
  246. package/dist/index-DN7fGMc3.d.ts +0 -20
  247. package/dist/index-DPXR1Yua.d.ts +0 -69
  248. package/dist/inline-script.d.ts +0 -29
  249. package/dist/inline-script.js +0 -63
  250. package/dist/inline-script.js.map +0 -1
  251. package/dist/modal-element.js +0 -11
  252. package/dist/modal-element.js.map +0 -1
  253. package/dist/modal.d.ts +0 -2
  254. package/dist/modal.js +0 -20
  255. package/dist/modal.js.map +0 -1
  256. package/dist/password-input-element.d.ts +0 -3
  257. package/dist/password-input-element.js +0 -9
  258. package/dist/password-input-element.js.map +0 -1
  259. package/dist/password-input.d.ts +0 -2
  260. package/dist/password-input.js +0 -18
  261. package/dist/password-input.js.map +0 -1
  262. package/dist/tabs-element.js +0 -9
  263. package/dist/tabs-element.js.map +0 -1
  264. package/dist/tabs.d.ts +0 -2
  265. package/dist/tabs.js +0 -28
  266. package/dist/tabs.js.map +0 -1
  267. package/dist/translation-BnpO2mN2.d.ts +0 -4
@@ -0,0 +1,229 @@
1
+ /*
2
+ * <govuk-react-modal>: a headless, light-DOM custom element around a modal `dialog` and the
3
+ * buttons that open and close it.
4
+ *
5
+ * The buttons use invoker commands (`command="show-modal"` or `command="close"`, with
6
+ * `commandfor` naming the dialog), so a browser that supports them opens a true modal dialog
7
+ * with no JavaScript: the page behind is inert, focus moves into the dialog and Escape closes
8
+ * it. The `dialog` element is the state.
9
+ *
10
+ * The element only adds what HTML can't do on its own:
11
+ * - In a browser without invoker commands, it runs the commands of its own buttons.
12
+ * - `open` (when present) controls the dialog: "true" opens it with `showModal()`, anything
13
+ * else closes it. Changing `open` fires no change event. While `open` is present, the buttons
14
+ * and Escape don't open or close the dialog: they fire the change event with the state asked
15
+ * for, and the dialog changes only when `open` does. That covers a `form` with
16
+ * `method="dialog"`, and a script calling `showModal()` where the browser fires `beforetoggle`
17
+ * on dialogs (Chrome 132, Firefox 133, Safari 26). Escape is cancelled at its `keydown`, since the `cancel` event of a
18
+ * second Escape in a row isn't cancelable. The browser doesn't let a page cancel a script
19
+ * calling `close()`: that fires the change event, and the dialog goes back to `open` a moment
20
+ * later unless `open` has changed.
21
+ * - It fires a bubbling `govuk-react-modal:change` event with `{ open }` when the dialog opens
22
+ * or closes, for code that doesn't use React.
23
+ *
24
+ * While upgraded it sets `data-upgraded`.
25
+ *
26
+ * Markup inside the element:
27
+ * - a `dialog` with an id
28
+ * - `button`s with `commandfor` set to the dialog's id, and `command` set to "show-modal",
29
+ * "close" or "request-close"
30
+ */
31
+ import { setUpWhenReady } from '../utils/set-up-when-ready.js';
32
+ export const tagName = 'govuk-react-modal';
33
+ // How long the page has to accept a change the element couldn't cancel, before it's undone.
34
+ const restoreDelay = 100;
35
+ /** Whether the browser runs invoker commands itself. */
36
+ export const supportsCommands = () => typeof HTMLButtonElement !== 'undefined' && 'command' in HTMLButtonElement.prototype;
37
+ /** Whether Escape would close a popover in the dialog, not the dialog. A manual popover stays. */
38
+ function hasOpenPopover(dialog) {
39
+ try {
40
+ return Array.from(dialog.querySelectorAll(':popover-open')).some((popover) => popover.getAttribute('popover') !== 'manual');
41
+ }
42
+ catch (_a) {
43
+ // No popovers in this browser.
44
+ return false;
45
+ }
46
+ }
47
+ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {
48
+ class GovukReactModal extends HTMLElement {
49
+ constructor() {
50
+ super(...arguments);
51
+ this.wasOpen = false;
52
+ this.syncing = false;
53
+ // Runs the commands of the element's own buttons when the browser can't.
54
+ this.onClick = (event) => {
55
+ var _a;
56
+ const button = event.target instanceof Element ? event.target.closest('button[commandfor]') : null;
57
+ if (!(button instanceof HTMLButtonElement) || button.closest(tagName) !== this)
58
+ return;
59
+ const dialog = document.getElementById((_a = button.getAttribute('commandfor')) !== null && _a !== void 0 ? _a : '');
60
+ if (!(dialog instanceof HTMLDialogElement))
61
+ return;
62
+ const command = button.getAttribute('command');
63
+ if (this.request(dialog, command))
64
+ return;
65
+ if (command === 'show-modal' && !dialog.open)
66
+ dialog.showModal();
67
+ else if (command === 'close' && dialog.open)
68
+ dialog.close();
69
+ else if (command === 'request-close' && dialog.open) {
70
+ // Newer than this package's DOM types.
71
+ const requestClose = Reflect.get(dialog, 'requestClose');
72
+ if (typeof requestClose === 'function')
73
+ requestClose.call(dialog);
74
+ else
75
+ dialog.close();
76
+ }
77
+ };
78
+ // While controlled, the browser's own commands and Escape only ask for a change.
79
+ this.onCommand = (event) => {
80
+ const { dialog } = this;
81
+ const command = Reflect.get(event, 'command');
82
+ if (!dialog || event.target !== dialog || typeof command !== 'string')
83
+ return;
84
+ if (this.request(dialog, command))
85
+ event.preventDefault();
86
+ };
87
+ // A script opening the dialog, where the browser fires `beforetoggle` on dialogs.
88
+ this.onBeforeToggle = (event) => {
89
+ const { dialog } = this;
90
+ if (!dialog || event.target !== dialog || this.syncing || !event.cancelable)
91
+ return;
92
+ if (Reflect.get(event, 'newState') !== 'open' || this.getAttribute('open') === 'true')
93
+ return;
94
+ if (this.request(dialog, 'show-modal'))
95
+ event.preventDefault();
96
+ };
97
+ // Escape, before the browser asks the dialog to close: it lets a page cancel that only once in
98
+ // a row. Heard on the window, so a key that anything else handled first, React's handlers
99
+ // included, is left. So is one that closes a popover open in the dialog.
100
+ this.onKeydown = (event) => {
101
+ const { dialog } = this;
102
+ const { target } = event;
103
+ if (!dialog || event.key !== 'Escape' || event.defaultPrevented || event.isComposing)
104
+ return;
105
+ if (!(target instanceof Element) || target.closest('dialog') !== dialog)
106
+ return;
107
+ if (dialog.getAttribute('closedby') === 'none' || hasOpenPopover(dialog))
108
+ return;
109
+ if (this.request(dialog, 'request-close'))
110
+ event.preventDefault();
111
+ };
112
+ this.onCancel = (event) => {
113
+ const { dialog } = this;
114
+ if (!dialog || event.target !== dialog)
115
+ return;
116
+ if (this.request(dialog, 'request-close'))
117
+ event.preventDefault();
118
+ };
119
+ // A form with `method="dialog"` closes its dialog when submitted.
120
+ this.onSubmit = (event) => {
121
+ const { dialog } = this;
122
+ const form = event.target;
123
+ if (!dialog || !(form instanceof HTMLFormElement) || form.closest('dialog') !== dialog)
124
+ return;
125
+ const { submitter } = event;
126
+ const method = (submitter instanceof HTMLButtonElement || submitter instanceof HTMLInputElement) &&
127
+ submitter.hasAttribute('formmethod')
128
+ ? submitter.formMethod
129
+ : form.method;
130
+ if (method === 'dialog' && this.request(dialog, 'close'))
131
+ event.preventDefault();
132
+ };
133
+ this.onToggle = () => {
134
+ const { dialog } = this;
135
+ if (!dialog || dialog.open === this.wasOpen)
136
+ return;
137
+ this.wasOpen = dialog.open;
138
+ this.dispatchEvent(new CustomEvent('govuk-react-modal:change', { detail: { open: dialog.open }, bubbles: true }));
139
+ // While controlled, this is a change the element couldn't cancel.
140
+ if (!this.hasAttribute('open'))
141
+ return;
142
+ window.clearTimeout(this.restoreTimeout);
143
+ this.restoreTimeout = window.setTimeout(() => this.sync(), restoreDelay);
144
+ };
145
+ }
146
+ static get observedAttributes() {
147
+ return ['open'];
148
+ }
149
+ connectedCallback() {
150
+ if (!supportsCommands())
151
+ this.addEventListener('click', this.onClick);
152
+ this.addEventListener('submit', this.onSubmit);
153
+ window.addEventListener('keydown', this.onKeydown);
154
+ this.observer = setUpWhenReady(this, () => this.setup());
155
+ }
156
+ disconnectedCallback() {
157
+ var _a, _b, _c, _d, _e;
158
+ this.removeEventListener('click', this.onClick);
159
+ this.removeEventListener('submit', this.onSubmit);
160
+ window.removeEventListener('keydown', this.onKeydown);
161
+ window.clearTimeout(this.restoreTimeout);
162
+ (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
163
+ (_b = this.openObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
164
+ (_c = this.dialog) === null || _c === void 0 ? void 0 : _c.removeEventListener('command', this.onCommand);
165
+ (_d = this.dialog) === null || _d === void 0 ? void 0 : _d.removeEventListener('cancel', this.onCancel);
166
+ (_e = this.dialog) === null || _e === void 0 ? void 0 : _e.removeEventListener('beforetoggle', this.onBeforeToggle);
167
+ this.dialog = undefined;
168
+ }
169
+ attributeChangedCallback() {
170
+ this.sync();
171
+ }
172
+ setup() {
173
+ if (this.dialog)
174
+ return true;
175
+ const dialog = Array.from(this.querySelectorAll('dialog')).find((found) => found.closest(tagName) === this);
176
+ if (!dialog)
177
+ return false;
178
+ this.dialog = dialog;
179
+ this.dataset.upgraded = '';
180
+ this.wasOpen = dialog.open;
181
+ // Not every browser fires `toggle` on dialogs, so watch the dialog's `open` attribute.
182
+ this.openObserver = new MutationObserver(this.onToggle);
183
+ this.openObserver.observe(dialog, { attributes: true, attributeFilter: ['open'] });
184
+ dialog.addEventListener('command', this.onCommand);
185
+ dialog.addEventListener('cancel', this.onCancel);
186
+ dialog.addEventListener('beforetoggle', this.onBeforeToggle);
187
+ this.sync();
188
+ return true;
189
+ }
190
+ /**
191
+ * While controlled, fires the change event for the state a command asks for, in place of
192
+ * running it. Returns whether the command was handled.
193
+ */
194
+ request(dialog, command) {
195
+ if (!this.hasAttribute('open'))
196
+ return false;
197
+ const open = command === 'show-modal';
198
+ if (!open && command !== 'close' && command !== 'request-close')
199
+ return false;
200
+ if (open !== dialog.open)
201
+ this.dispatchEvent(new CustomEvent('govuk-react-modal:change', { detail: { open }, bubbles: true }));
202
+ return true;
203
+ }
204
+ /** Opens or closes the dialog to match `open`, without reporting it. */
205
+ sync() {
206
+ const { dialog } = this;
207
+ const controlled = this.getAttribute('open');
208
+ if (!dialog || controlled === null)
209
+ return;
210
+ const open = controlled === 'true';
211
+ if (open === dialog.open)
212
+ return;
213
+ this.wasOpen = open;
214
+ this.syncing = true;
215
+ try {
216
+ if (open && dialog.isConnected)
217
+ dialog.showModal();
218
+ else if (!open)
219
+ dialog.close();
220
+ }
221
+ finally {
222
+ this.syncing = false;
223
+ }
224
+ }
225
+ }
226
+ if (!customElements.get(tagName))
227
+ customElements.define(tagName, GovukReactModal);
228
+ }
229
+ //# sourceMappingURL=element.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/modal/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAQ/D,MAAM,CAAC,MAAM,OAAO,GAAG,mBAAmB,CAAC;AAE3C,4FAA4F;AAC5F,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,wDAAwD;AACxD,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,EAAE,CACnC,OAAO,iBAAiB,KAAK,WAAW,IAAI,SAAS,IAAI,iBAAiB,CAAC,SAAS,CAAC;AAEvF,kGAAkG;AAClG,SAAS,cAAc,CAAC,MAAyB;IAC/C,IAAI,CAAC;QACH,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,gBAAgB,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,CAC9D,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,SAAS,CAAC,KAAK,QAAQ,CAC1D,CAAC;IACJ,CAAC;IAAC,WAAM,CAAC;QACP,+BAA+B;QAC/B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,IAAI,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;IAChF,MAAM,eAAgB,SAAQ,WAAW;QAAzC;;YAWU,YAAO,GAAG,KAAK,CAAC;YAIhB,YAAO,GAAG,KAAK,CAAC;YAExB,yEAAyE;YACxD,YAAO,GAAG,CAAC,KAAiB,EAAE,EAAE;;gBAC/C,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,YAAY,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,IAAI,CAA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,IAAI,CAAC;gBACH,IAAI,IAAI,IAAI,MAAM,CAAC,WAAW;oBAAE,MAAM,CAAC,SAAS,EAAE,CAAC;qBAC9C,IAAI,CAAC,IAAI;oBAAE,MAAM,CAAC,KAAK,EAAE,CAAC;YACjC,CAAC;oBAAS,CAAC;gBACT,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;YACvB,CAAC;QACH,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;AACpF,CAAC","sourcesContent":["/*\n * <govuk-react-modal>: a headless, light-DOM custom element around a modal `dialog` and the\n * buttons that open and close it.\n *\n * The buttons use invoker commands (`command=\"show-modal\"` or `command=\"close\"`, with\n * `commandfor` naming the dialog), so a browser that supports them opens a true modal dialog\n * with no JavaScript: the page behind is inert, focus moves into the dialog and Escape closes\n * it. The `dialog` element is the state.\n *\n * The element only adds what HTML can't do on its own:\n * - In a browser without invoker commands, it runs the commands of its own buttons.\n * - `open` (when present) controls the dialog: \"true\" opens it with `showModal()`, anything\n * else closes it. Changing `open` fires no change event. While `open` is present, the buttons\n * and Escape don't open or close the dialog: they fire the change event with the state asked\n * for, and the dialog changes only when `open` does. That covers a `form` with\n * `method=\"dialog\"`, and a script calling `showModal()` where the browser fires `beforetoggle`\n * on dialogs (Chrome 132, Firefox 133, Safari 26). Escape is cancelled at its `keydown`, since the `cancel` event of a\n * second Escape in a row isn't cancelable. The browser doesn't let a page cancel a script\n * calling `close()`: that fires the change event, and the dialog goes back to `open` a moment\n * later unless `open` has changed.\n * - It fires a bubbling `govuk-react-modal:change` event with `{ open }` when the dialog opens\n * or closes, for code that doesn't use React.\n *\n * While upgraded it sets `data-upgraded`.\n *\n * Markup inside the element:\n * - a `dialog` with an id\n * - `button`s with `commandfor` set to the dialog's id, and `command` set to \"show-modal\",\n * \"close\" or \"request-close\"\n */\n\nimport { setUpWhenReady } from '../utils/set-up-when-ready.js';\n\ndeclare global {\n interface HTMLElementEventMap {\n 'govuk-react-modal:change': CustomEvent<{ open: boolean }>;\n }\n}\n\nexport const tagName = 'govuk-react-modal';\n\n// How long the page has to accept a change the element couldn't cancel, before it's undone.\nconst restoreDelay = 100;\n\n/** Whether the browser runs invoker commands itself. */\nexport const supportsCommands = () =>\n typeof HTMLButtonElement !== 'undefined' && 'command' in HTMLButtonElement.prototype;\n\n/** Whether Escape would close a popover in the dialog, not the dialog. A manual popover stays. */\nfunction hasOpenPopover(dialog: HTMLDialogElement) {\n try {\n return Array.from(dialog.querySelectorAll(':popover-open')).some(\n (popover) => popover.getAttribute('popover') !== 'manual'\n );\n } catch {\n // No popovers in this browser.\n return false;\n }\n}\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactModal extends HTMLElement {\n static get observedAttributes() {\n return ['open'];\n }\n\n private dialog?: HTMLDialogElement;\n\n private observer?: MutationObserver;\n\n private openObserver?: MutationObserver;\n\n private wasOpen = false;\n\n private restoreTimeout?: number;\n\n private syncing = false;\n\n // Runs the commands of the element's own buttons when the browser can't.\n private readonly onClick = (event: MouseEvent) => {\n const button = event.target instanceof Element ? event.target.closest('button[commandfor]') : null;\n if (!(button instanceof HTMLButtonElement) || button.closest(tagName) !== this) return;\n const dialog = document.getElementById(button.getAttribute('commandfor') ?? '');\n if (!(dialog instanceof HTMLDialogElement)) return;\n const command = button.getAttribute('command');\n if (this.request(dialog, command)) return;\n if (command === 'show-modal' && !dialog.open) dialog.showModal();\n else if (command === 'close' && dialog.open) dialog.close();\n else if (command === 'request-close' && dialog.open) {\n // Newer than this package's DOM types.\n const requestClose: unknown = Reflect.get(dialog, 'requestClose');\n if (typeof requestClose === 'function') requestClose.call(dialog);\n else dialog.close();\n }\n };\n\n // While controlled, the browser's own commands and Escape only ask for a change.\n private readonly onCommand = (event: Event) => {\n const { dialog } = this;\n const command: unknown = Reflect.get(event, 'command');\n if (!dialog || event.target !== dialog || typeof command !== 'string') return;\n if (this.request(dialog, command)) event.preventDefault();\n };\n\n // A script opening the dialog, where the browser fires `beforetoggle` on dialogs.\n private readonly onBeforeToggle = (event: Event) => {\n const { dialog } = this;\n if (!dialog || event.target !== dialog || this.syncing || !event.cancelable) return;\n if (Reflect.get(event, 'newState') !== 'open' || this.getAttribute('open') === 'true') return;\n if (this.request(dialog, 'show-modal')) event.preventDefault();\n };\n\n // Escape, before the browser asks the dialog to close: it lets a page cancel that only once in\n // a row. Heard on the window, so a key that anything else handled first, React's handlers\n // included, is left. So is one that closes a popover open in the dialog.\n private readonly onKeydown = (event: KeyboardEvent) => {\n const { dialog } = this;\n const { target } = event;\n if (!dialog || event.key !== 'Escape' || event.defaultPrevented || event.isComposing) return;\n if (!(target instanceof Element) || target.closest('dialog') !== dialog) return;\n if (dialog.getAttribute('closedby') === 'none' || hasOpenPopover(dialog)) return;\n if (this.request(dialog, 'request-close')) event.preventDefault();\n };\n\n private readonly onCancel = (event: Event) => {\n const { dialog } = this;\n if (!dialog || event.target !== dialog) return;\n if (this.request(dialog, 'request-close')) event.preventDefault();\n };\n\n // A form with `method=\"dialog\"` closes its dialog when submitted.\n private readonly onSubmit = (event: SubmitEvent) => {\n const { dialog } = this;\n const form = event.target;\n if (!dialog || !(form instanceof HTMLFormElement) || form.closest('dialog') !== dialog) return;\n const { submitter } = event;\n const method =\n (submitter instanceof HTMLButtonElement || submitter instanceof HTMLInputElement) &&\n submitter.hasAttribute('formmethod')\n ? submitter.formMethod\n : form.method;\n if (method === 'dialog' && this.request(dialog, 'close')) event.preventDefault();\n };\n\n private readonly onToggle = () => {\n const { dialog } = this;\n if (!dialog || dialog.open === this.wasOpen) return;\n this.wasOpen = dialog.open;\n this.dispatchEvent(new CustomEvent('govuk-react-modal:change', { detail: { open: dialog.open }, bubbles: true }));\n // While controlled, this is a change the element couldn't cancel.\n if (!this.hasAttribute('open')) return;\n window.clearTimeout(this.restoreTimeout);\n this.restoreTimeout = window.setTimeout(() => this.sync(), restoreDelay);\n };\n\n connectedCallback() {\n if (!supportsCommands()) this.addEventListener('click', this.onClick);\n this.addEventListener('submit', this.onSubmit);\n window.addEventListener('keydown', this.onKeydown);\n this.observer = setUpWhenReady(this, () => this.setup());\n }\n\n disconnectedCallback() {\n this.removeEventListener('click', this.onClick);\n this.removeEventListener('submit', this.onSubmit);\n window.removeEventListener('keydown', this.onKeydown);\n window.clearTimeout(this.restoreTimeout);\n this.observer?.disconnect();\n this.openObserver?.disconnect();\n this.dialog?.removeEventListener('command', this.onCommand);\n this.dialog?.removeEventListener('cancel', this.onCancel);\n this.dialog?.removeEventListener('beforetoggle', this.onBeforeToggle);\n this.dialog = undefined;\n }\n\n attributeChangedCallback() {\n this.sync();\n }\n\n private setup() {\n if (this.dialog) return true;\n const dialog = Array.from(this.querySelectorAll('dialog')).find((found) => found.closest(tagName) === this);\n if (!dialog) return false;\n this.dialog = dialog;\n this.dataset.upgraded = '';\n this.wasOpen = dialog.open;\n // Not every browser fires `toggle` on dialogs, so watch the dialog's `open` attribute.\n this.openObserver = new MutationObserver(this.onToggle);\n this.openObserver.observe(dialog, { attributes: true, attributeFilter: ['open'] });\n dialog.addEventListener('command', this.onCommand);\n dialog.addEventListener('cancel', this.onCancel);\n dialog.addEventListener('beforetoggle', this.onBeforeToggle);\n this.sync();\n return true;\n }\n\n /**\n * While controlled, fires the change event for the state a command asks for, in place of\n * running it. Returns whether the command was handled.\n */\n private request(dialog: HTMLDialogElement, command: string | null) {\n if (!this.hasAttribute('open')) return false;\n const open = command === 'show-modal';\n if (!open && command !== 'close' && command !== 'request-close') return false;\n if (open !== dialog.open)\n this.dispatchEvent(new CustomEvent('govuk-react-modal:change', { detail: { open }, bubbles: true }));\n return true;\n }\n\n /** Opens or closes the dialog to match `open`, without reporting it. */\n private sync() {\n const { dialog } = this;\n const controlled = this.getAttribute('open');\n if (!dialog || controlled === null) return;\n const open = controlled === 'true';\n if (open === dialog.open) return;\n this.wasOpen = open;\n this.syncing = true;\n try {\n if (open && dialog.isConnected) dialog.showModal();\n else if (!open) dialog.close();\n } finally {\n this.syncing = false;\n }\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactModal);\n}\n"]}
@@ -0,0 +1,41 @@
1
+ import * as React from 'react';
2
+ import type { ComponentProps, ReactNode } from 'react';
3
+ import { type ChangeDetails } from '../utils/change-details.js';
4
+ export type { ChangeDetails };
5
+ export type RootProps = Omit<React.HTMLAttributes<HTMLElement>, 'onChange'> & {
6
+ children?: ReactNode;
7
+ /**
8
+ * Whether the dialog is open, to control it once hydrated: the buttons and Escape then call
9
+ * `onOpenChange`, and the dialog changes only when `open` does. Without it, the buttons alone
10
+ * open and close it, which is best unless you need to open or close it yourself.
11
+ */
12
+ open?: boolean;
13
+ /** Called when the dialog opens or closes. */
14
+ onOpenChange?: (open: boolean, details: ChangeDetails) => void;
15
+ /** The dialog's id, which the buttons' `commandfor` names. Defaults to a generated one. */
16
+ dialogId?: string;
17
+ };
18
+ export declare function Root({ children, open, onOpenChange, dialogId: dialogIdProp, ...props }: RootProps): React.JSX.Element;
19
+ type PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E> & {
20
+ /** Render the only child instead, with this part's props merged onto it. */
21
+ asChild?: boolean;
22
+ };
23
+ type CommandProps = PartProps<'button'> & {
24
+ /** The dialog's id. Set by Root. */
25
+ dialogId?: string;
26
+ };
27
+ export type TriggerProps = CommandProps;
28
+ /** A button that opens the dialog as a modal. */
29
+ export declare function Trigger(props: TriggerProps): React.JSX.Element;
30
+ export type CloseProps = CommandProps;
31
+ /** A button that closes the dialog. */
32
+ export declare function Close(props: CloseProps): React.JSX.Element;
33
+ export type ContentProps = PartProps<'dialog'>;
34
+ /**
35
+ * The dialog. It's named by Title, unless you pass `aria-labelledby` or `aria-label`. Pass
36
+ * `closedby="any"` to also close it when the user clicks outside it.
37
+ */
38
+ export declare function Content({ asChild, id, onClose, ref, ...props }: ContentProps): React.JSX.Element;
39
+ export type TitleProps = PartProps<'h2'>;
40
+ /** The dialog's heading, which names it. */
41
+ export declare function Title({ asChild, ...props }: TitleProps): React.JSX.Element;
@@ -0,0 +1,145 @@
1
+ 'use client';
2
+ import * as React from 'react';
3
+ import { createContext, useCallback, useContext, useEffect, useId, useReducer, useRef } from 'react';
4
+ import { early, live } from '../utils/change-details.js';
5
+ import { composeRefs, Slot } from '../utils/slot.js';
6
+ import { tagName } from './element.js';
7
+ /*
8
+ * Headless modal dialog: unstyled parts over a native `dialog` and the <govuk-react-modal>
9
+ * element (./element.ts). Every part except Root takes `asChild`.
10
+ *
11
+ * Trigger and Close are buttons with invoker commands (`command` and `commandfor`), so where
12
+ * the browser supports them the dialog opens as a true modal with no JavaScript: the page behind
13
+ * is inert, focus moves into the dialog, and Escape closes it. The element runs the commands in
14
+ * browsers without them, and applies `open` when controlled.
15
+ *
16
+ * Context only fills in ids: in an island without a Root, pass `dialogId` to Trigger and Close,
17
+ * and `id` to Content.
18
+ */
19
+ const ModalContext = createContext({});
20
+ export function Root({ children, open, onOpenChange, dialogId: dialogIdProp, ...props }) {
21
+ const generatedId = useId();
22
+ const dialogId = dialogIdProp !== null && dialogIdProp !== void 0 ? dialogIdProp : generatedId;
23
+ const element = useRef(null);
24
+ const synced = useRef(false);
25
+ const [, render] = useReducer((count) => count + 1, 0);
26
+ // `open` is set once hydrated, so the server markup is uncontrolled and the buttons work before
27
+ // hydration. A dialog opened by then is reported by Content, rather than closed.
28
+ useEffect(() => {
29
+ const node = element.current;
30
+ if (!node || open === undefined) {
31
+ node === null || node === void 0 ? void 0 : node.removeAttribute('open');
32
+ return;
33
+ }
34
+ if (!synced.current) {
35
+ synced.current = true;
36
+ const dialog = document.getElementById(dialogId);
37
+ if (onOpenChange && !open && dialog instanceof HTMLDialogElement && dialog.open) {
38
+ // The dialog stays open until the next render, which adopts it or closes it.
39
+ render();
40
+ return;
41
+ }
42
+ }
43
+ node.setAttribute('open', String(open));
44
+ });
45
+ return (React.createElement(ModalContext.Provider, { value: { dialogId, titleId: `${dialogId}-title`, onOpenChange } }, React.createElement(tagName, {
46
+ ...props,
47
+ ref: element,
48
+ suppressHydrationWarning: true,
49
+ }, children)));
50
+ }
51
+ function Command({ command, asChild, dialogId, ...props }) {
52
+ const context = useContext(ModalContext);
53
+ // `command` and `commandfor` aren't in React's types yet, so they go in as a spread.
54
+ const invoker = { command, commandfor: dialogId !== null && dialogId !== void 0 ? dialogId : context.dialogId };
55
+ if (asChild)
56
+ return React.createElement(Slot, { ...invoker, ...props });
57
+ return React.createElement("button", { type: "button", ...invoker, ...props });
58
+ }
59
+ /** A button that opens the dialog as a modal. */
60
+ export function Trigger(props) {
61
+ return React.createElement(Command, { command: "show-modal", ...props });
62
+ }
63
+ /** A button that closes the dialog. */
64
+ export function Close(props) {
65
+ return React.createElement(Command, { command: "close", ...props });
66
+ }
67
+ /**
68
+ * The dialog. It's named by Title, unless you pass `aria-labelledby` or `aria-label`. Pass
69
+ * `closedby="any"` to also close it when the user clicks outside it.
70
+ */
71
+ export function Content({ asChild, id, onClose, ref, ...props }) {
72
+ const context = useContext(ModalContext);
73
+ const reported = useRef(undefined);
74
+ const onOpenChange = useRef(context.onOpenChange);
75
+ useEffect(() => {
76
+ onOpenChange.current = context.onOpenChange;
77
+ });
78
+ // Report each change once.
79
+ const report = useCallback((dialog) => {
80
+ var _a, _b;
81
+ if (reported.current === dialog.open)
82
+ return;
83
+ reported.current = dialog.open;
84
+ // A controlled dialog that arrives at `open` is no news.
85
+ if (((_a = dialog.closest(tagName)) === null || _a === void 0 ? void 0 : _a.getAttribute('open')) === String(dialog.open))
86
+ return;
87
+ (_b = onOpenChange.current) === null || _b === void 0 ? void 0 : _b.call(onOpenChange, dialog.open, live);
88
+ }, []);
89
+ // A dialog the user opened before hydration, through its invoker command or the element, fired
90
+ // nothing React heard, so report it once.
91
+ const dialogRef = useRef(null);
92
+ useEffect(() => {
93
+ var _a;
94
+ const dialog = dialogRef.current;
95
+ if ((dialog === null || dialog === void 0 ? void 0 : dialog.open) && reported.current === undefined) {
96
+ reported.current = true;
97
+ (_a = onOpenChange.current) === null || _a === void 0 ? void 0 : _a.call(onOpenChange, true, early);
98
+ }
99
+ }, []);
100
+ // Not every browser fires `toggle` on dialogs, so watch the dialog's `open` attribute.
101
+ const listen = useCallback((dialog) => {
102
+ dialogRef.current = dialog;
103
+ if (!dialog)
104
+ return undefined;
105
+ const forget = composeRefs(ref)(dialog);
106
+ const observer = new MutationObserver(() => report(dialog));
107
+ observer.observe(dialog, { attributes: true, attributeFilter: ['open'] });
108
+ // While controlled, the element asks for a change the dialog hasn't made.
109
+ const root = dialog.closest(tagName);
110
+ const onRequest = (event) => {
111
+ var _a;
112
+ if (event.target !== root || event.detail.open === dialog.open)
113
+ return;
114
+ (_a = onOpenChange.current) === null || _a === void 0 ? void 0 : _a.call(onOpenChange, event.detail.open, live);
115
+ };
116
+ root === null || root === void 0 ? void 0 : root.addEventListener('govuk-react-modal:change', onRequest);
117
+ return () => {
118
+ observer.disconnect();
119
+ root === null || root === void 0 ? void 0 : root.removeEventListener('govuk-react-modal:change', onRequest);
120
+ dialogRef.current = null;
121
+ forget();
122
+ };
123
+ }, [ref, report]);
124
+ const shared = {
125
+ id: id !== null && id !== void 0 ? id : context.dialogId,
126
+ 'aria-labelledby': props['aria-label'] ? undefined : context.titleId,
127
+ ref: listen,
128
+ onClose: (event) => {
129
+ onClose === null || onClose === void 0 ? void 0 : onClose(event);
130
+ report(event.currentTarget);
131
+ },
132
+ // The dialog's open state belongs to the browser.
133
+ suppressHydrationWarning: true,
134
+ };
135
+ if (asChild)
136
+ return React.createElement(Slot, { ...shared, ...props });
137
+ return React.createElement("dialog", { ...shared, ...props });
138
+ }
139
+ /** The dialog's heading, which names it. */
140
+ export function Title({ asChild, ...props }) {
141
+ const context = useContext(ModalContext);
142
+ const Element = asChild ? Slot : 'h2';
143
+ return React.createElement(Element, { id: context.titleId, ...props });
144
+ }
145
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"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ext, useEffect, useId, useReducer, useRef } from 'react';\nimport type { ComponentProps, ReactNode, SyntheticEvent } from 'react';\nimport { early, live, type ChangeDetails } from '../utils/change-details.js';\nimport { composeRefs, Slot } from '../utils/slot.js';\nimport { tagName } from './element.js';\n\nexport type { ChangeDetails };\n\n/*\n * Headless modal dialog: unstyled parts over a native `dialog` and the <govuk-react-modal>\n * element (./element.ts). Every part except Root takes `asChild`.\n *\n * Trigger and Close are buttons with invoker commands (`command` and `commandfor`), so where\n * the browser supports them the dialog opens as a true modal with no JavaScript: the page behind\n * is inert, focus moves into the dialog, and Escape closes it. The element runs the commands in\n * browsers without them, and applies `open` when controlled.\n *\n * Context only fills in ids: in an island without a Root, pass `dialogId` to Trigger and Close,\n * and `id` to Content.\n */\n\nconst ModalContext = createContext<{\n dialogId?: string;\n titleId?: string;\n onOpenChange?: (open: boolean, details: ChangeDetails) => void;\n}>({});\n\nexport type RootProps = Omit<React.HTMLAttributes<HTMLElement>, 'onChange'> & {\n children?: ReactNode;\n /**\n * Whether the dialog is open, to control it once hydrated: the buttons and Escape then call\n * `onOpenChange`, and the dialog changes only when `open` does. Without it, the buttons alone\n * open and close it, which is best unless you need to open or close it yourself.\n */\n open?: boolean;\n /** Called when the dialog opens or closes. */\n onOpenChange?: (open: boolean, details: ChangeDetails) => void;\n /** The dialog's id, which the buttons' `commandfor` names. Defaults to a generated one. */\n dialogId?: string;\n};\n\nexport function Root({ children, open, onOpenChange, dialogId: dialogIdProp, ...props }: RootProps) {\n const generatedId = useId();\n const dialogId = dialogIdProp ?? generatedId;\n const element = useRef<HTMLElement>(null);\n const synced = useRef(false);\n const [, render] = useReducer((count: number) => count + 1, 0);\n // `open` is set once hydrated, so the server markup is uncontrolled and the buttons work before\n // hydration. A dialog opened by then is reported by Content, rather than closed.\n useEffect(() => {\n const node = element.current;\n if (!node || open === undefined) {\n node?.removeAttribute('open');\n return;\n }\n if (!synced.current) {\n synced.current = true;\n const dialog = document.getElementById(dialogId);\n if (onOpenChange && !open && dialog instanceof HTMLDialogElement && dialog.open) {\n // The dialog stays open until the next render, which adopts it or closes it.\n render();\n return;\n }\n }\n node.setAttribute('open', String(open));\n });\n return (\n <ModalContext.Provider value={{ dialogId, titleId: `${dialogId}-title`, onOpenChange }}>\n {React.createElement(\n tagName,\n {\n ...props,\n ref: element,\n suppressHydrationWarning: true,\n },\n children\n )}\n </ModalContext.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\ntype CommandProps = PartProps<'button'> & {\n /** The dialog's id. Set by Root. */\n dialogId?: string;\n};\n\nfunction Command({ command, asChild, dialogId, ...props }: CommandProps & { command: string }) {\n const context = useContext(ModalContext);\n // `command` and `commandfor` aren't in React's types yet, so they go in as a spread.\n const invoker = { command, commandfor: dialogId ?? context.dialogId };\n if (asChild) return <Slot {...invoker} {...props} />;\n return <button type=\"button\" {...invoker} {...props} />;\n}\n\nexport type TriggerProps = CommandProps;\n\n/** A button that opens the dialog as a modal. */\nexport function Trigger(props: TriggerProps) {\n return <Command command=\"show-modal\" {...props} />;\n}\n\nexport type CloseProps = CommandProps;\n\n/** A button that closes the dialog. */\nexport function Close(props: CloseProps) {\n return <Command command=\"close\" {...props} />;\n}\n\nexport type ContentProps = PartProps<'dialog'>;\n\n/**\n * The dialog. It's named by Title, unless you pass `aria-labelledby` or `aria-label`. Pass\n * `closedby=\"any\"` to also close it when the user clicks outside it.\n */\nexport function Content({ asChild, id, onClose, ref, ...props }: ContentProps) {\n const context = useContext(ModalContext);\n const reported = useRef<boolean | undefined>(undefined);\n const onOpenChange = useRef(context.onOpenChange);\n useEffect(() => {\n onOpenChange.current = context.onOpenChange;\n });\n // Report each change once.\n const report = useCallback((dialog: HTMLDialogElement) => {\n if (reported.current === dialog.open) return;\n reported.current = dialog.open;\n // A controlled dialog that arrives at `open` is no news.\n if (dialog.closest(tagName)?.getAttribute('open') === String(dialog.open)) return;\n onOpenChange.current?.(dialog.open, live);\n }, []);\n // A dialog the user opened before hydration, through its invoker command or the element, fired\n // nothing React heard, so report it once.\n const dialogRef = useRef<HTMLDialogElement | null>(null);\n useEffect(() => {\n const dialog = dialogRef.current;\n if (dialog?.open && reported.current === undefined) {\n reported.current = true;\n onOpenChange.current?.(true, early);\n }\n }, []);\n // Not every browser fires `toggle` on dialogs, so watch the dialog's `open` attribute.\n const listen = useCallback(\n (dialog: HTMLDialogElement | null) => {\n dialogRef.current = dialog;\n if (!dialog) return undefined;\n const forget = composeRefs(ref)(dialog);\n const observer = new MutationObserver(() => report(dialog));\n observer.observe(dialog, { attributes: true, attributeFilter: ['open'] });\n // While controlled, the element asks for a change the dialog hasn't made.\n const root = dialog.closest(tagName);\n const onRequest = (event: CustomEvent<{ open: boolean }>) => {\n if (event.target !== root || event.detail.open === dialog.open) return;\n onOpenChange.current?.(event.detail.open, live);\n };\n root?.addEventListener('govuk-react-modal:change', onRequest);\n return () => {\n observer.disconnect();\n root?.removeEventListener('govuk-react-modal:change', onRequest);\n dialogRef.current = null;\n forget();\n };\n },\n [ref, report]\n );\n const shared = {\n id: id ?? context.dialogId,\n 'aria-labelledby': props['aria-label'] ? undefined : context.titleId,\n ref: listen,\n onClose: (event: SyntheticEvent<HTMLDialogElement>) => {\n onClose?.(event);\n report(event.currentTarget);\n },\n // The dialog's open state belongs to the browser.\n suppressHydrationWarning: true,\n };\n if (asChild) return <Slot {...shared} {...props} />;\n return <dialog {...shared} {...props} />;\n}\n\nexport type TitleProps = PartProps<'h2'>;\n\n/** The dialog's heading, which names it. */\nexport function Title({ asChild, ...props }: TitleProps) {\n const context = useContext(ModalContext);\n const Element = asChild ? Slot : 'h2';\n return <Element id={context.titleId} {...props} />;\n}\n"]}
@@ -0,0 +1 @@
1
+ export declare const tagName = "govuk-react-password-input";
@@ -0,0 +1,150 @@
1
+ /*
2
+ * <govuk-react-password-input>: a headless, light-DOM custom element that adds a show and hide
3
+ * button to a password field, with or without React.
4
+ *
5
+ * The input's `type` is the state, kept when React sets it again. Without JavaScript the field
6
+ * stays a password field and the button stays hidden. On upgrade the element shows the button, which switches the input between
7
+ * "password" and "text", updates its own text and label, and announces the change.
8
+ *
9
+ * Markup inside the element:
10
+ * - `[data-password-input]`: an `input` of type "password".
11
+ * - `[data-password-trigger]`: a `button` of type "button", rendered `hidden`.
12
+ * - `[data-password-status]` (optional): a visually hidden live region for the announcements.
13
+ * Without one, the element adds one after the input.
14
+ *
15
+ * While upgraded it sets `data-upgraded`.
16
+ *
17
+ * Attributes, for the text (English by default):
18
+ * - `show-text`, `hide-text`: the button's text.
19
+ * - `show-label`, `hide-label`: the button's accessible name.
20
+ * - `shown-announcement`, `hidden-announcement`: announced when the password is shown or hidden.
21
+ *
22
+ * As in govuk-frontend, the password is hidden again when its form is submitted, unless by a hidden
23
+ * submit button such as a form library's, and when the page is restored from the back-forward cache.
24
+ */
25
+ import { setText } from '../utils/dom.js';
26
+ import { setUpWhenReady } from '../utils/set-up-when-ready.js';
27
+ export const tagName = 'govuk-react-password-input';
28
+ const defaults = {
29
+ 'show-text': 'Show',
30
+ 'hide-text': 'Hide',
31
+ 'show-label': 'Show password',
32
+ 'hide-label': 'Hide password',
33
+ 'shown-announcement': 'Your password is visible',
34
+ 'hidden-announcement': 'Your password is hidden',
35
+ };
36
+ // The same visually hidden styles as govuk-frontend's, for a live region the element adds itself.
37
+ const visuallyHidden = {
38
+ position: 'absolute',
39
+ width: '1px',
40
+ height: '1px',
41
+ margin: '0',
42
+ padding: '0',
43
+ overflow: 'hidden',
44
+ clip: 'rect(0 0 0 0)',
45
+ 'clip-path': 'inset(50%)',
46
+ border: '0',
47
+ 'white-space': 'nowrap',
48
+ };
49
+ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {
50
+ class GovukReactPasswordInput extends HTMLElement {
51
+ constructor() {
52
+ super(...arguments);
53
+ this.visible = false;
54
+ // React sets `type` again whenever it updates a controlled input.
55
+ this.typeObserver = new MutationObserver(() => {
56
+ const type = this.visible ? 'text' : 'password';
57
+ if (this.input && this.input.type !== type)
58
+ this.input.type = type;
59
+ });
60
+ this.onToggle = (event) => {
61
+ event.preventDefault();
62
+ this.setVisible(!this.visible);
63
+ };
64
+ // A hidden submitter isn't the user submitting, but a script, such as Conform validating as the
65
+ // user types.
66
+ this.onSubmit = (event) => {
67
+ var _a;
68
+ const submitter = event instanceof SubmitEvent ? event.submitter : null;
69
+ if (event.target === ((_a = this.input) === null || _a === void 0 ? void 0 : _a.form) && !(submitter instanceof HTMLElement && submitter.hidden)) {
70
+ this.setVisible(false);
71
+ }
72
+ };
73
+ this.onPageShow = (event) => {
74
+ if (event.persisted)
75
+ this.setVisible(false);
76
+ };
77
+ }
78
+ connectedCallback() {
79
+ this.observer = setUpWhenReady(this, () => this.setup());
80
+ }
81
+ disconnectedCallback() {
82
+ var _a, _b;
83
+ (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
84
+ (_b = this.toggle) === null || _b === void 0 ? void 0 : _b.removeEventListener('click', this.onToggle);
85
+ document.removeEventListener('submit', this.onSubmit);
86
+ window.removeEventListener('pageshow', this.onPageShow);
87
+ this.typeObserver.disconnect();
88
+ this.input = undefined;
89
+ this.toggle = undefined;
90
+ }
91
+ text(name) {
92
+ var _a;
93
+ return (_a = this.getAttribute(name)) !== null && _a !== void 0 ? _a : defaults[name];
94
+ }
95
+ own(selector, type) {
96
+ const element = this.querySelector(selector);
97
+ return element instanceof type && element.closest(tagName) === this ? element : undefined;
98
+ }
99
+ setup() {
100
+ if (this.input)
101
+ return true;
102
+ const input = this.own('[data-password-input]', HTMLInputElement);
103
+ const toggle = this.own('[data-password-trigger]', HTMLButtonElement);
104
+ if (!input || !toggle)
105
+ return false;
106
+ this.input = input;
107
+ this.toggle = toggle;
108
+ this.status = this.own('[data-password-status]', HTMLElement);
109
+ if (!this.status) {
110
+ this.status = document.createElement('div');
111
+ this.status.dataset.passwordStatus = '';
112
+ this.status.setAttribute('aria-live', 'polite');
113
+ // Set one by one: a Content Security Policy can block a whole `style` attribute.
114
+ const { style } = this.status;
115
+ Object.entries(visuallyHidden).forEach(([name, value]) => style.setProperty(name, value));
116
+ input.insertAdjacentElement('afterend', this.status);
117
+ }
118
+ this.dataset.upgraded = '';
119
+ toggle.hidden = false;
120
+ toggle.addEventListener('click', this.onToggle);
121
+ document.addEventListener('submit', this.onSubmit);
122
+ window.addEventListener('pageshow', this.onPageShow);
123
+ // Start hidden, with the text set but nothing announced.
124
+ this.visible = false;
125
+ input.type = 'password';
126
+ this.typeObserver.observe(input, { attributes: true, attributeFilter: ['type'] });
127
+ this.label(false);
128
+ return true;
129
+ }
130
+ setVisible(visible) {
131
+ const { input } = this;
132
+ if (!input || visible === this.visible)
133
+ return;
134
+ this.visible = visible;
135
+ input.type = visible ? 'text' : 'password';
136
+ this.label(visible);
137
+ if (this.status)
138
+ this.status.textContent = this.text(visible ? 'shown-announcement' : 'hidden-announcement');
139
+ }
140
+ label(visible) {
141
+ if (!this.toggle)
142
+ return;
143
+ setText(this.toggle, this.text(visible ? 'hide-text' : 'show-text'));
144
+ this.toggle.setAttribute('aria-label', this.text(visible ? 'hide-label' : 'show-label'));
145
+ }
146
+ }
147
+ if (!customElements.get(tagName))
148
+ customElements.define(tagName, GovukReactPasswordInput);
149
+ }
150
+ //# sourceMappingURL=element.js.map