@govuk-react/primitives 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +100 -25
  2. package/dist/accordion/element.d.ts +3 -0
  3. package/dist/accordion/element.js.map +1 -1
  4. package/dist/accordion/index.d.ts +3 -7
  5. package/dist/accordion/index.js +35 -33
  6. package/dist/accordion/index.js.map +1 -1
  7. package/dist/auto-focus/index.d.ts +3 -285
  8. package/dist/auto-focus/index.js +13 -3
  9. package/dist/auto-focus/index.js.map +1 -1
  10. package/dist/autocomplete/element.d.ts +7 -4
  11. package/dist/autocomplete/element.js +11 -11
  12. package/dist/autocomplete/element.js.map +1 -1
  13. package/dist/autocomplete/index.d.ts +7 -7
  14. package/dist/autocomplete/index.js +17 -25
  15. package/dist/autocomplete/index.js.map +1 -1
  16. package/dist/character-count/element.d.ts +5 -0
  17. package/dist/character-count/element.js +5 -5
  18. package/dist/character-count/element.js.map +1 -1
  19. package/dist/character-count/index.d.ts +7 -7
  20. package/dist/character-count/index.js +13 -13
  21. package/dist/character-count/index.js.map +1 -1
  22. package/dist/character-count/messages.d.ts +1 -1
  23. package/dist/character-count/messages.js +13 -13
  24. package/dist/character-count/messages.js.map +1 -1
  25. package/dist/choices/element.d.ts +5 -0
  26. package/dist/choices/element.js +6 -31
  27. package/dist/choices/element.js.map +1 -1
  28. package/dist/disclosure/element.d.ts +3 -0
  29. package/dist/disclosure/element.js +21 -12
  30. package/dist/disclosure/element.js.map +1 -1
  31. package/dist/disclosure/index.d.ts +6 -5
  32. package/dist/disclosure/index.js +21 -11
  33. package/dist/disclosure/index.js.map +1 -1
  34. package/dist/exit-this-page/element.d.ts +1 -1
  35. package/dist/exit-this-page/element.js +20 -21
  36. package/dist/exit-this-page/element.js.map +1 -1
  37. package/dist/exit-this-page/index.d.ts +11 -11
  38. package/dist/exit-this-page/index.js +7 -7
  39. package/dist/exit-this-page/index.js.map +1 -1
  40. package/dist/file-upload/element.d.ts +11 -6
  41. package/dist/file-upload/element.js +15 -15
  42. package/dist/file-upload/element.js.map +1 -1
  43. package/dist/file-upload/index.d.ts +9 -9
  44. package/dist/file-upload/index.js +11 -11
  45. package/dist/file-upload/index.js.map +1 -1
  46. package/dist/inline/accordion-element.js +1 -1
  47. package/dist/inline/auto-focus-element.js +1 -1
  48. package/dist/inline/autocomplete-element.js +1 -1
  49. package/dist/inline/character-count-element.js +1 -1
  50. package/dist/inline/choices-element.js +1 -1
  51. package/dist/inline/disclosure-element.js +1 -1
  52. package/dist/inline/exit-this-page-element.js +1 -1
  53. package/dist/inline/file-upload-element.js +1 -1
  54. package/dist/inline/focus-links-element.js +1 -1
  55. package/dist/inline/modal-element.js +1 -1
  56. package/dist/inline/password-input-element.js +1 -1
  57. package/dist/inline/tabs-element.js +1 -1
  58. package/dist/inline-script/index.js +12 -12
  59. package/dist/modal/element.js +126 -11
  60. package/dist/modal/element.js.map +1 -1
  61. package/dist/modal/index.d.ts +8 -3
  62. package/dist/modal/index.js +56 -20
  63. package/dist/modal/index.js.map +1 -1
  64. package/dist/password-input/element.js +27 -11
  65. package/dist/password-input/element.js.map +1 -1
  66. package/dist/password-input/index.d.ts +3 -3
  67. package/dist/password-input/index.js +4 -2
  68. package/dist/password-input/index.js.map +1 -1
  69. package/dist/styles.css +11 -0
  70. package/dist/tabs/element.d.ts +3 -0
  71. package/dist/tabs/element.js +17 -10
  72. package/dist/tabs/element.js.map +1 -1
  73. package/dist/tabs/index.d.ts +9 -18
  74. package/dist/tabs/index.js +48 -44
  75. package/dist/tabs/index.js.map +1 -1
  76. package/dist/utils/change-details.d.ts +11 -0
  77. package/dist/utils/change-details.js +3 -0
  78. package/dist/utils/change-details.js.map +1 -0
  79. package/dist/utils/on-property-change.d.ts +7 -0
  80. package/dist/utils/on-property-change.js +19 -0
  81. package/dist/utils/on-property-change.js.map +1 -0
  82. package/dist/utils/set-focus.js.map +1 -1
  83. package/dist/utils/slot.d.ts +5 -3
  84. package/dist/utils/slot.js +24 -2
  85. package/dist/utils/slot.js.map +1 -1
  86. package/package.json +8 -2
  87. package/dist/utils/on-property-set.d.ts +0 -9
  88. package/dist/utils/on-property-set.js +0 -38
  89. package/dist/utils/on-property-set.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/modal/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAQ/D,MAAM,CAAC,MAAM,OAAO,GAAG,mBAAmB,CAAC;AAE3C,wDAAwD;AACxD,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,EAAE,CACnC,OAAO,iBAAiB,KAAK,WAAW,IAAI,SAAS,IAAI,iBAAiB,CAAC,SAAS,CAAC;AAEvF,IAAI,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;IAChF,MAAM,eAAgB,SAAQ,WAAW;QAAzC;;YASU,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,CAAC;gBACnG,IAAI,CAAC,CAAC,MAAM,YAAY,iBAAiB,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI;oBAAE,OAAO;gBACvF,MAAM,MAAM,GAAG,QAAQ,CAAC,cAAc,CAAC,MAAA,MAAM,CAAC,YAAY,CAAC,YAAY,CAAC,mCAAI,EAAE,CAAC,CAAC;gBAChF,IAAI,CAAC,CAAC,MAAM,YAAY,iBAAiB,CAAC;oBAAE,OAAO;gBACnD,MAAM,OAAO,GAAG,MAAM,CAA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GAAG,IAAI,CAAC;YACxB,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;YAC7C,IAAI,CAAC,MAAM,IAAI,UAAU,KAAK,IAAI;gBAAE,OAAO;YAC3C,MAAM,IAAI,GAAG,UAAU,KAAK,MAAM,CAAC;YACnC,IAAI,IAAI,KAAK,MAAM,CAAC,IAAI;gBAAE,OAAO;YACjC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;YACpB,IAAI,IAAI,IAAI,MAAM,CAAC,WAAW;gBAAE,MAAM,CAAC,SAAS,EAAE,CAAC;iBAC9C,IAAI,CAAC,IAAI;gBAAE,MAAM,CAAC,KAAK,EAAE,CAAC;QACjC,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.\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 * 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/** Whether the browser runs invoker commands itself. */\nexport const supportsCommands = () =>\n typeof HTMLButtonElement !== 'undefined' && 'command' in HTMLButtonElement.prototype;\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 wasOpen = 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 (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 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 };\n\n connectedCallback() {\n if (!supportsCommands()) this.addEventListener('click', this.onClick);\n this.observer = setUpWhenReady(this, () => this.setup());\n }\n\n disconnectedCallback() {\n this.removeEventListener('click', this.onClick);\n this.observer?.disconnect();\n this.dialog?.removeEventListener('close', this.onToggle);\n this.dialog?.removeEventListener('toggle', this.onToggle);\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.wasOpen = dialog.open;\n // `toggle` fires on open and close where supported, and `close` everywhere.\n dialog.addEventListener('toggle', this.onToggle);\n dialog.addEventListener('close', this.onToggle);\n this.sync();\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 if (open && dialog.isConnected) dialog.showModal();\n else if (!open) dialog.close();\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactModal);\n}\n"]}
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,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IAAI,CAAC,MAAM,IAAI,UAAU,KAAK,IAAI;gBAAE,OAAO;YAC3C,MAAM,IAAI,GAAG,UAAU,KAAK,MAAM,CAAC;YACnC,IAAI,IAAI,KAAK,MAAM,CAAC,IAAI;gBAAE,OAAO;YACjC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;YACpB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;YACpB,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"]}
@@ -1,11 +1,17 @@
1
1
  import * as React from 'react';
2
2
  import type { ComponentProps, ReactNode } from 'react';
3
+ import { type ChangeDetails } from '../utils/change-details.js';
4
+ export type { ChangeDetails };
3
5
  export type RootProps = Omit<React.HTMLAttributes<HTMLElement>, 'onChange'> & {
4
6
  children?: ReactNode;
5
- /** Whether the dialog is open, to control it. Without it, the buttons alone open and close it. */
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
+ */
6
12
  open?: boolean;
7
13
  /** Called when the dialog opens or closes. */
8
- onOpenChange?: (open: boolean) => void;
14
+ onOpenChange?: (open: boolean, details: ChangeDetails) => void;
9
15
  /** The dialog's id, which the buttons' `commandfor` names. Defaults to a generated one. */
10
16
  dialogId?: string;
11
17
  };
@@ -33,4 +39,3 @@ export declare function Content({ asChild, id, onClose, ref, ...props }: Content
33
39
  export type TitleProps = PartProps<'h2'>;
34
40
  /** The dialog's heading, which names it. */
35
41
  export declare function Title({ asChild, ...props }: TitleProps): React.JSX.Element;
36
- export {};
@@ -1,7 +1,8 @@
1
1
  'use client';
2
2
  import * as React from 'react';
3
- import { createContext, useContext, useEffect, useId, useRef } from 'react';
4
- import { Slot } from '../utils/slot.js';
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';
5
6
  import { tagName } from './element.js';
6
7
  /*
7
8
  * Headless modal dialog: unstyled parts over a native `dialog` and the <govuk-react-modal>
@@ -19,9 +20,31 @@ const ModalContext = createContext({});
19
20
  export function Root({ children, open, onOpenChange, dialogId: dialogIdProp, ...props }) {
20
21
  const generatedId = useId();
21
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
+ });
22
45
  return (React.createElement(ModalContext.Provider, { value: { dialogId, titleId: `${dialogId}-title`, onOpenChange } }, React.createElement(tagName, {
23
46
  ...props,
24
- open: open === undefined ? undefined : String(open),
47
+ ref: element,
25
48
  suppressHydrationWarning: true,
26
49
  }, children)));
27
50
  }
@@ -52,15 +75,17 @@ export function Content({ asChild, id, onClose, ref, ...props }) {
52
75
  useEffect(() => {
53
76
  onOpenChange.current = context.onOpenChange;
54
77
  });
55
- // Report each change once: `toggle` fires on opening and closing where the browser fires it on
56
- // dialogs, and `close` on closing everywhere.
57
- const report = (dialog) => {
58
- var _a;
78
+ // Report each change once.
79
+ const report = useCallback((dialog) => {
80
+ var _a, _b;
59
81
  if (reported.current === dialog.open)
60
82
  return;
61
83
  reported.current = dialog.open;
62
- (_a = onOpenChange.current) === null || _a === void 0 ? void 0 : _a.call(onOpenChange, dialog.open);
63
- };
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
+ }, []);
64
89
  // A dialog the user opened before hydration, through its invoker command or the element, fired
65
90
  // nothing React heard, so report it once.
66
91
  const dialogRef = useRef(null);
@@ -69,22 +94,33 @@ export function Content({ asChild, id, onClose, ref, ...props }) {
69
94
  const dialog = dialogRef.current;
70
95
  if ((dialog === null || dialog === void 0 ? void 0 : dialog.open) && reported.current === undefined) {
71
96
  reported.current = true;
72
- (_a = onOpenChange.current) === null || _a === void 0 ? void 0 : _a.call(onOpenChange, true);
97
+ (_a = onOpenChange.current) === null || _a === void 0 ? void 0 : _a.call(onOpenChange, true, early);
73
98
  }
74
99
  }, []);
75
- // React doesn't listen for `toggle` on a dialog, so listen natively.
76
- const listen = (dialog) => {
100
+ // Not every browser fires `toggle` on dialogs, so watch the dialog's `open` attribute.
101
+ const listen = useCallback((dialog) => {
77
102
  dialogRef.current = dialog;
78
- if (typeof ref === 'function')
79
- ref(dialog);
80
- else if (ref)
81
- ref.current = dialog;
82
103
  if (!dialog)
83
104
  return undefined;
84
- const onToggle = () => report(dialog);
85
- dialog.addEventListener('toggle', onToggle);
86
- return () => dialog.removeEventListener('toggle', onToggle);
87
- };
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]);
88
124
  const shared = {
89
125
  id: id !== null && id !== void 0 ? id : context.dialogId,
90
126
  'aria-labelledby': props['aria-label'] ? undefined : context.titleId,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/modal/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAE5E,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAEvC;;;;;;;;;;;GAWG;AAEH,MAAM,YAAY,GAAG,aAAa,CAI/B,EAAE,CAAC,CAAC;AAYP,MAAM,UAAU,IAAI,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,KAAK,EAAa;IAChG,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,YAAY,aAAZ,YAAY,cAAZ,YAAY,GAAI,WAAW,CAAC;IAC7C,OAAO,CACL,oBAAC,YAAY,CAAC,QAAQ,IAAC,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,QAAQ,QAAQ,EAAE,YAAY,EAAE,IACnF,KAAK,CAAC,aAAa,CAClB,OAAO,EACP;QACE,GAAG,KAAK;QACR,IAAI,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,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AAE,QAAQ,CAAC,CAAC;IAC9D,CAAC,CAAC;IACF,MAAM,MAAM,GAAG;QACb,EAAE,EAAE,EAAE,aAAF,EAAE,cAAF,EAAE,GAAI,OAAO,CAAC,QAAQ;QAC1B,iBAAiB,EAAE,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO;QACpE,GAAG,EAAE,MAAM;QACX,OAAO,EAAE,CAAC,KAAwC,EAAE,EAAE;YACpD,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAG,KAAK,CAAC,CAAC;YACjB,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;QAC9B,CAAC;QACD,kDAAkD;QAClD,wBAAwB,EAAE,IAAI;KAC/B,CAAC;IACF,IAAI,OAAO;QAAE,OAAO,oBAAC,IAAI,OAAK,MAAM,KAAM,KAAK,GAAI,CAAC;IACpD,OAAO,mCAAY,MAAM,KAAM,KAAK,GAAI,CAAC;AAC3C,CAAC;AAID,4CAA4C;AAC5C,MAAM,UAAU,KAAK,CAAC,EAAE,OAAO,EAAE,GAAG,KAAK,EAAc;IACrD,MAAM,OAAO,GAAG,UAAU,CAAC,YAAY,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;IACtC,OAAO,oBAAC,OAAO,IAAC,EAAE,EAAE,OAAO,CAAC,OAAO,KAAM,KAAK,GAAI,CAAC;AACrD,CAAC","sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport { createContext, useContext, useEffect, useId, useRef } from 'react';\nimport type { ComponentProps, ReactNode, SyntheticEvent } from 'react';\nimport { Slot } from '../utils/slot.js';\nimport { tagName } from './element.js';\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) => void;\n}>({});\n\nexport type RootProps = Omit<React.HTMLAttributes<HTMLElement>, 'onChange'> & {\n children?: ReactNode;\n /** Whether the dialog is open, to control it. Without it, the buttons alone open and close it. */\n open?: boolean;\n /** Called when the dialog opens or closes. */\n onOpenChange?: (open: boolean) => 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 return (\n <ModalContext.Provider value={{ dialogId, titleId: `${dialogId}-title`, onOpenChange }}>\n {React.createElement(\n tagName,\n {\n ...props,\n open: open === undefined ? undefined : String(open),\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: `toggle` fires on opening and closing where the browser fires it on\n // dialogs, and `close` on closing everywhere.\n const report = (dialog: HTMLDialogElement) => {\n if (reported.current === dialog.open) return;\n reported.current = dialog.open;\n onOpenChange.current?.(dialog.open);\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);\n }\n }, []);\n // React doesn't listen for `toggle` on a dialog, so listen natively.\n const listen = (dialog: HTMLDialogElement | null) => {\n dialogRef.current = dialog;\n if (typeof ref === 'function') ref(dialog);\n else if (ref) ref.current = dialog;\n if (!dialog) return undefined;\n const onToggle = () => report(dialog);\n dialog.addEventListener('toggle', onToggle);\n return () => dialog.removeEventListener('toggle', onToggle);\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';\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'use client';\n\nimport * as React from 'react';\nimport { createContext, useCallback, useContext, 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"]}
@@ -8,10 +8,12 @@
8
8
  *
9
9
  * Markup inside the element:
10
10
  * - `[data-password-input]`: an `input` of type "password".
11
- * - `[data-password-toggle]`: a `button` of type "button", rendered `hidden`.
11
+ * - `[data-password-trigger]`: a `button` of type "button", rendered `hidden`.
12
12
  * - `[data-password-status]` (optional): a visually hidden live region for the announcements.
13
13
  * Without one, the element adds one after the input.
14
14
  *
15
+ * While upgraded it sets `data-upgraded`.
16
+ *
15
17
  * Attributes, for the text (English by default):
16
18
  * - `show-text`, `hide-text`: the button's text.
17
19
  * - `show-label`, `hide-label`: the button's accessible name.
@@ -20,7 +22,7 @@
20
22
  * As in govuk-frontend, the password is hidden again when its form is submitted, unless by a hidden
21
23
  * submit button such as a form library's, and when the page is restored from the back-forward cache.
22
24
  */
23
- import { onPropertySet } from '../utils/on-property-set.js';
25
+ import { setText } from '../utils/dom.js';
24
26
  import { setUpWhenReady } from '../utils/set-up-when-ready.js';
25
27
  export const tagName = 'govuk-react-password-input';
26
28
  const defaults = {
@@ -32,18 +34,29 @@ const defaults = {
32
34
  'hidden-announcement': 'Your password is hidden',
33
35
  };
34
36
  // The same visually hidden styles as govuk-frontend's, for a live region the element adds itself.
35
- const visuallyHidden = 'position:absolute;width:1px;height:1px;margin:0;padding:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);border:0;white-space:nowrap';
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
+ };
36
49
  if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {
37
50
  class GovukReactPasswordInput extends HTMLElement {
38
51
  constructor() {
39
52
  super(...arguments);
40
53
  this.visible = false;
41
54
  // React sets `type` again whenever it updates a controlled input.
42
- this.onTypeSet = () => {
55
+ this.typeObserver = new MutationObserver(() => {
43
56
  const type = this.visible ? 'text' : 'password';
44
57
  if (this.input && this.input.type !== type)
45
58
  this.input.type = type;
46
- };
59
+ });
47
60
  this.onToggle = (event) => {
48
61
  event.preventDefault();
49
62
  this.setVisible(!this.visible);
@@ -66,12 +79,12 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
66
79
  this.observer = setUpWhenReady(this, () => this.setup());
67
80
  }
68
81
  disconnectedCallback() {
69
- var _a, _b, _c;
82
+ var _a, _b;
70
83
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
71
84
  (_b = this.toggle) === null || _b === void 0 ? void 0 : _b.removeEventListener('click', this.onToggle);
72
85
  document.removeEventListener('submit', this.onSubmit);
73
86
  window.removeEventListener('pageshow', this.onPageShow);
74
- (_c = this.stopWatchingType) === null || _c === void 0 ? void 0 : _c.call(this);
87
+ this.typeObserver.disconnect();
75
88
  this.input = undefined;
76
89
  this.toggle = undefined;
77
90
  }
@@ -87,7 +100,7 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
87
100
  if (this.input)
88
101
  return true;
89
102
  const input = this.own('[data-password-input]', HTMLInputElement);
90
- const toggle = this.own('[data-password-toggle]', HTMLButtonElement);
103
+ const toggle = this.own('[data-password-trigger]', HTMLButtonElement);
91
104
  if (!input || !toggle)
92
105
  return false;
93
106
  this.input = input;
@@ -97,9 +110,12 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
97
110
  this.status = document.createElement('div');
98
111
  this.status.dataset.passwordStatus = '';
99
112
  this.status.setAttribute('aria-live', 'polite');
100
- this.status.setAttribute('style', visuallyHidden);
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));
101
116
  input.insertAdjacentElement('afterend', this.status);
102
117
  }
118
+ this.dataset.upgraded = '';
103
119
  toggle.hidden = false;
104
120
  toggle.addEventListener('click', this.onToggle);
105
121
  document.addEventListener('submit', this.onSubmit);
@@ -107,7 +123,7 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
107
123
  // Start hidden, with the text set but nothing announced.
108
124
  this.visible = false;
109
125
  input.type = 'password';
110
- this.stopWatchingType = onPropertySet(input, 'type', this.onTypeSet);
126
+ this.typeObserver.observe(input, { attributes: true, attributeFilter: ['type'] });
111
127
  this.label(false);
112
128
  return true;
113
129
  }
@@ -124,7 +140,7 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
124
140
  label(visible) {
125
141
  if (!this.toggle)
126
142
  return;
127
- this.toggle.textContent = this.text(visible ? 'hide-text' : 'show-text');
143
+ setText(this.toggle, this.text(visible ? 'hide-text' : 'show-text'));
128
144
  this.toggle.setAttribute('aria-label', this.text(visible ? 'hide-label' : 'show-label'));
129
145
  }
130
146
  }
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/password-input/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,MAAM,CAAC,MAAM,OAAO,GAAG,4BAA4B,CAAC;AAEpD,MAAM,QAAQ,GAAG;IACf,WAAW,EAAE,MAAM;IACnB,WAAW,EAAE,MAAM;IACnB,YAAY,EAAE,eAAe;IAC7B,YAAY,EAAE,eAAe;IAC7B,oBAAoB,EAAE,0BAA0B;IAChD,qBAAqB,EAAE,yBAAyB;CACjD,CAAC;AAEF,kGAAkG;AAClG,MAAM,cAAc,GAClB,+IAA+I,CAAC;AAElJ,IAAI,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;IAChF,MAAM,uBAAwB,SAAQ,WAAW;QAAjD;;YASU,YAAO,GAAG,KAAK,CAAC;YAIxB,kEAAkE;YACjD,cAAS,GAAG,GAAG,EAAE;gBAChC,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAA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YACpB,IAAI,IAAI,CAAC,MAAM;gBAAE,IAAI,CAAC,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC;QAC/G,CAAC;QAEO,KAAK,CAAC,OAAgB;YAC5B,IAAI,CAAC,IAAI,CAAC,MAAM;gBAAE,OAAO;YACzB,IAAI,CAAC,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;YACzE,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC;QAC3F,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,uBAAuB,CAAC,CAAC;AAC5F,CAAC","sourcesContent":["/*\n * <govuk-react-password-input>: a headless, light-DOM custom element that adds a show and hide\n * button to a password field, with or without React.\n *\n * The input's `type` is the state, kept when React sets it again. Without JavaScript the field\n * stays a password field and the button stays hidden. On upgrade the element shows the button, which switches the input between\n * \"password\" and \"text\", updates its own text and label, and announces the change.\n *\n * Markup inside the element:\n * - `[data-password-input]`: an `input` of type \"password\".\n * - `[data-password-toggle]`: a `button` of type \"button\", rendered `hidden`.\n * - `[data-password-status]` (optional): a visually hidden live region for the announcements.\n * Without one, the element adds one after the input.\n *\n * Attributes, for the text (English by default):\n * - `show-text`, `hide-text`: the button's text.\n * - `show-label`, `hide-label`: the button's accessible name.\n * - `shown-announcement`, `hidden-announcement`: announced when the password is shown or hidden.\n *\n * As in govuk-frontend, the password is hidden again when its form is submitted, unless by a hidden\n * submit button such as a form library's, and when the page is restored from the back-forward cache.\n */\n\nimport { onPropertySet } from '../utils/on-property-set.js';\nimport { setUpWhenReady } from '../utils/set-up-when-ready.js';\n\nexport const tagName = 'govuk-react-password-input';\n\nconst defaults = {\n 'show-text': 'Show',\n 'hide-text': 'Hide',\n 'show-label': 'Show password',\n 'hide-label': 'Hide password',\n 'shown-announcement': 'Your password is visible',\n 'hidden-announcement': 'Your password is hidden',\n};\n\n// The same visually hidden styles as govuk-frontend's, for a live region the element adds itself.\nconst visuallyHidden =\n 'position:absolute;width:1px;height:1px;margin:0;padding:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);border:0;white-space:nowrap';\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactPasswordInput extends HTMLElement {\n private input?: HTMLInputElement;\n\n private toggle?: HTMLButtonElement;\n\n private status?: HTMLElement;\n\n private observer?: MutationObserver;\n\n private visible = false;\n\n private stopWatchingType?: () => void;\n\n // React sets `type` again whenever it updates a controlled input.\n private readonly onTypeSet = () => {\n const type = this.visible ? 'text' : 'password';\n if (this.input && this.input.type !== type) this.input.type = type;\n };\n\n private readonly onToggle = (event: MouseEvent) => {\n event.preventDefault();\n this.setVisible(!this.visible);\n };\n\n // A hidden submitter isn't the user submitting, but a script, such as Conform validating as the\n // user types.\n private readonly onSubmit = (event: Event) => {\n const submitter = event instanceof SubmitEvent ? event.submitter : null;\n if (event.target === this.input?.form && !(submitter instanceof HTMLElement && submitter.hidden)) {\n this.setVisible(false);\n }\n };\n\n private readonly onPageShow = (event: PageTransitionEvent) => {\n if (event.persisted) this.setVisible(false);\n };\n\n connectedCallback() {\n this.observer = setUpWhenReady(this, () => this.setup());\n }\n\n disconnectedCallback() {\n this.observer?.disconnect();\n this.toggle?.removeEventListener('click', this.onToggle);\n document.removeEventListener('submit', this.onSubmit);\n window.removeEventListener('pageshow', this.onPageShow);\n this.stopWatchingType?.();\n this.input = undefined;\n this.toggle = undefined;\n }\n\n private text(name: keyof typeof defaults) {\n return this.getAttribute(name) ?? defaults[name];\n }\n\n private own<E extends Element>(selector: string, type: new () => E): E | undefined {\n const element = this.querySelector(selector);\n return element instanceof type && element.closest(tagName) === this ? element : undefined;\n }\n\n private setup() {\n if (this.input) return true;\n const input = this.own('[data-password-input]', HTMLInputElement);\n const toggle = this.own('[data-password-toggle]', HTMLButtonElement);\n if (!input || !toggle) return false;\n this.input = input;\n this.toggle = toggle;\n this.status = this.own('[data-password-status]', HTMLElement);\n if (!this.status) {\n this.status = document.createElement('div');\n this.status.dataset.passwordStatus = '';\n this.status.setAttribute('aria-live', 'polite');\n this.status.setAttribute('style', visuallyHidden);\n input.insertAdjacentElement('afterend', this.status);\n }\n toggle.hidden = false;\n toggle.addEventListener('click', this.onToggle);\n document.addEventListener('submit', this.onSubmit);\n window.addEventListener('pageshow', this.onPageShow);\n // Start hidden, with the text set but nothing announced.\n this.visible = false;\n input.type = 'password';\n this.stopWatchingType = onPropertySet(input, 'type', this.onTypeSet);\n this.label(false);\n return true;\n }\n\n private setVisible(visible: boolean) {\n const { input } = this;\n if (!input || visible === this.visible) return;\n this.visible = visible;\n input.type = visible ? 'text' : 'password';\n this.label(visible);\n if (this.status) this.status.textContent = this.text(visible ? 'shown-announcement' : 'hidden-announcement');\n }\n\n private label(visible: boolean) {\n if (!this.toggle) return;\n this.toggle.textContent = this.text(visible ? 'hide-text' : 'show-text');\n this.toggle.setAttribute('aria-label', this.text(visible ? 'hide-label' : 'show-label'));\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactPasswordInput);\n}\n"]}
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/password-input/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,MAAM,CAAC,MAAM,OAAO,GAAG,4BAA4B,CAAC;AAEpD,MAAM,QAAQ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AC,OAAgB;YAC5B,IAAI,CAAC,IAAI,CAAC,MAAM;gBAAE,OAAO;YACzB,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC;YACrE,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC;QAC3F,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,uBAAuB,CAAC,CAAC;AAC5F,CAAC","sourcesContent":["/*\n * <govuk-react-password-input>: a headless, light-DOM custom element that adds a show and hide\n * button to a password field, with or without React.\n *\n * The input's `type` is the state, kept when React sets it again. Without JavaScript the field\n * stays a password field and the button stays hidden. On upgrade the element shows the button, which switches the input between\n * \"password\" and \"text\", updates its own text and label, and announces the change.\n *\n * Markup inside the element:\n * - `[data-password-input]`: an `input` of type \"password\".\n * - `[data-password-trigger]`: a `button` of type \"button\", rendered `hidden`.\n * - `[data-password-status]` (optional): a visually hidden live region for the announcements.\n * Without one, the element adds one after the input.\n *\n * While upgraded it sets `data-upgraded`.\n *\n * Attributes, for the text (English by default):\n * - `show-text`, `hide-text`: the button's text.\n * - `show-label`, `hide-label`: the button's accessible name.\n * - `shown-announcement`, `hidden-announcement`: announced when the password is shown or hidden.\n *\n * As in govuk-frontend, the password is hidden again when its form is submitted, unless by a hidden\n * submit button such as a form library's, and when the page is restored from the back-forward cache.\n */\n\nimport { setText } from '../utils/dom.js';\nimport { setUpWhenReady } from '../utils/set-up-when-ready.js';\n\nexport const tagName = 'govuk-react-password-input';\n\nconst defaults = {\n 'show-text': 'Show',\n 'hide-text': 'Hide',\n 'show-label': 'Show password',\n 'hide-label': 'Hide password',\n 'shown-announcement': 'Your password is visible',\n 'hidden-announcement': 'Your password is hidden',\n};\n\n// The same visually hidden styles as govuk-frontend's, for a live region the element adds itself.\nconst visuallyHidden: Record<string, string> = {\n position: 'absolute',\n width: '1px',\n height: '1px',\n margin: '0',\n padding: '0',\n overflow: 'hidden',\n clip: 'rect(0 0 0 0)',\n 'clip-path': 'inset(50%)',\n border: '0',\n 'white-space': 'nowrap',\n};\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactPasswordInput extends HTMLElement {\n private input?: HTMLInputElement;\n\n private toggle?: HTMLButtonElement;\n\n private status?: HTMLElement;\n\n private observer?: MutationObserver;\n\n private visible = false;\n\n // React sets `type` again whenever it updates a controlled input.\n private readonly typeObserver = new MutationObserver(() => {\n const type = this.visible ? 'text' : 'password';\n if (this.input && this.input.type !== type) this.input.type = type;\n });\n\n private readonly onToggle = (event: MouseEvent) => {\n event.preventDefault();\n this.setVisible(!this.visible);\n };\n\n // A hidden submitter isn't the user submitting, but a script, such as Conform validating as the\n // user types.\n private readonly onSubmit = (event: Event) => {\n const submitter = event instanceof SubmitEvent ? event.submitter : null;\n if (event.target === this.input?.form && !(submitter instanceof HTMLElement && submitter.hidden)) {\n this.setVisible(false);\n }\n };\n\n private readonly onPageShow = (event: PageTransitionEvent) => {\n if (event.persisted) this.setVisible(false);\n };\n\n connectedCallback() {\n this.observer = setUpWhenReady(this, () => this.setup());\n }\n\n disconnectedCallback() {\n this.observer?.disconnect();\n this.toggle?.removeEventListener('click', this.onToggle);\n document.removeEventListener('submit', this.onSubmit);\n window.removeEventListener('pageshow', this.onPageShow);\n this.typeObserver.disconnect();\n this.input = undefined;\n this.toggle = undefined;\n }\n\n private text(name: keyof typeof defaults) {\n return this.getAttribute(name) ?? defaults[name];\n }\n\n private own<E extends Element>(selector: string, type: new () => E): E | undefined {\n const element = this.querySelector(selector);\n return element instanceof type && element.closest(tagName) === this ? element : undefined;\n }\n\n private setup() {\n if (this.input) return true;\n const input = this.own('[data-password-input]', HTMLInputElement);\n const toggle = this.own('[data-password-trigger]', HTMLButtonElement);\n if (!input || !toggle) return false;\n this.input = input;\n this.toggle = toggle;\n this.status = this.own('[data-password-status]', HTMLElement);\n if (!this.status) {\n this.status = document.createElement('div');\n this.status.dataset.passwordStatus = '';\n this.status.setAttribute('aria-live', 'polite');\n // Set one by one: a Content Security Policy can block a whole `style` attribute.\n const { style } = this.status;\n Object.entries(visuallyHidden).forEach(([name, value]) => style.setProperty(name, value));\n input.insertAdjacentElement('afterend', this.status);\n }\n this.dataset.upgraded = '';\n toggle.hidden = false;\n toggle.addEventListener('click', this.onToggle);\n document.addEventListener('submit', this.onSubmit);\n window.addEventListener('pageshow', this.onPageShow);\n // Start hidden, with the text set but nothing announced.\n this.visible = false;\n input.type = 'password';\n this.typeObserver.observe(input, { attributes: true, attributeFilter: ['type'] });\n this.label(false);\n return true;\n }\n\n private setVisible(visible: boolean) {\n const { input } = this;\n if (!input || visible === this.visible) return;\n this.visible = visible;\n input.type = visible ? 'text' : 'password';\n this.label(visible);\n if (this.status) this.status.textContent = this.text(visible ? 'shown-announcement' : 'hidden-announcement');\n }\n\n private label(visible: boolean) {\n if (!this.toggle) return;\n setText(this.toggle, this.text(visible ? 'hide-text' : 'show-text'));\n this.toggle.setAttribute('aria-label', this.text(visible ? 'hide-label' : 'show-label'));\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactPasswordInput);\n}\n"]}
@@ -15,6 +15,7 @@ export type RootProps = React.HTMLAttributes<HTMLElement> & {
15
15
  hiddenAnnouncement?: string;
16
16
  };
17
17
  export declare function Root({ showText, hideText, showLabel, hideLabel, shownAnnouncement, hiddenAnnouncement, ...props }: RootProps): React.DOMElement<{
18
+ suppressHydrationWarning: boolean;
18
19
  'show-text': string;
19
20
  'hide-text': string;
20
21
  'show-label': string;
@@ -24,7 +25,6 @@ export declare function Root({ showText, hideText, showLabel, hideLabel, shownAn
24
25
  defaultChecked?: boolean;
25
26
  defaultValue?: string | number | readonly string[];
26
27
  suppressContentEditableWarning?: boolean;
27
- suppressHydrationWarning?: boolean;
28
28
  accessKey?: string;
29
29
  autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | (string & {});
30
30
  autoFocus?: boolean;
@@ -309,9 +309,9 @@ type PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E>
309
309
  export type InputProps = PartProps<'input'>;
310
310
  /** The password field. Its `type` starts as "password" and the element switches it. */
311
311
  export declare function Input({ asChild, ...props }: InputProps): React.JSX.Element;
312
- export type ToggleProps = PartProps<'button'>;
312
+ export type TriggerProps = PartProps<'button'>;
313
313
  /** The show and hide button. Hidden until the element upgrades, which then sets its text and label. */
314
- export declare function Toggle({ asChild, children, ...props }: ToggleProps): React.JSX.Element;
314
+ export declare function Trigger({ asChild, children, ...props }: TriggerProps): React.JSX.Element;
315
315
  export type StatusProps = PartProps<'div'>;
316
316
  /** A live region for the announcements. Make it visually hidden. */
317
317
  export declare function Status({ asChild, ...props }: StatusProps): React.JSX.Element;
@@ -5,6 +5,8 @@ import { tagName } from './element.js';
5
5
  export function Root({ showText, hideText, showLabel, hideLabel, shownAnnouncement, hiddenAnnouncement, ...props }) {
6
6
  return React.createElement(tagName, {
7
7
  ...props,
8
+ // The element owns `data-upgraded`.
9
+ suppressHydrationWarning: true,
8
10
  'show-text': showText,
9
11
  'hide-text': hideText,
10
12
  'show-label': showLabel,
@@ -21,8 +23,8 @@ export function Input({ asChild, ...props }) {
21
23
  return React.createElement("input", { type: "password", "data-password-input": "", suppressHydrationWarning: true, ...props });
22
24
  }
23
25
  /** The show and hide button. Hidden until the element upgrades, which then sets its text and label. */
24
- export function Toggle({ asChild, children = 'Show', ...props }) {
25
- const shared = { 'data-password-toggle': '', hidden: true, suppressHydrationWarning: true };
26
+ export function Trigger({ asChild, children = 'Show', ...props }) {
27
+ const shared = { 'data-password-trigger': '', hidden: true, suppressHydrationWarning: true };
26
28
  if (asChild)
27
29
  return (React.createElement(Slot, { ...shared, ...props }, children));
28
30
  return (React.createElement("button", { type: "button", "aria-label": "Show password", ...shared, ...props }, children));
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/password-input/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAyBvC,MAAM,UAAU,IAAI,CAAC,EACnB,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,GAAG,KAAK,EACE;IACV,OAAO,KAAK,CAAC,aAAa,CAAC,OAAO,EAAE;QAClC,GAAG,KAAK;QACR,WAAW,EAAE,QAAQ;QACrB,WAAW,EAAE,QAAQ;QACrB,YAAY,EAAE,SAAS;QACvB,YAAY,EAAE,SAAS;QACvB,oBAAoB,EAAE,iBAAiB;QACvC,qBAAqB,EAAE,kBAAkB;KAC1C,CAAC,CAAC;AACL,CAAC;AASD,uFAAuF;AACvF,MAAM,UAAU,KAAK,CAAC,EAAE,OAAO,EAAE,GAAG,KAAK,EAAc;IACrD,IAAI,OAAO;QAAE,OAAO,oBAAC,IAAI,2BAAqB,EAAE,EAAC,wBAAwB,WAAK,KAAK,GAAI,CAAC;IACxF,6EAA6E;IAC7E,OAAO,+BAAO,IAAI,EAAC,UAAU,yBAAqB,EAAE,EAAC,wBAAwB,WAAK,KAAK,GAAI,CAAC;AAC9F,CAAC;AAID,uGAAuG;AACvG,MAAM,UAAU,MAAM,CAAC,EAAE,OAAO,EAAE,QAAQ,GAAG,MAAM,EAAE,GAAG,KAAK,EAAe;IAC1E,MAAM,MAAM,GAAG,EAAE,sBAAsB,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,wBAAwB,EAAE,IAAI,EAAE,CAAC;IAC5F,IAAI,OAAO;QACT,OAAO,CACL,oBAAC,IAAI,OAAK,MAAM,KAAM,KAAK,IACxB,QAAQ,CACJ,CACR,CAAC;IACJ,OAAO,CACL,gCAAQ,IAAI,EAAC,QAAQ,gBAAY,eAAe,KAAK,MAAM,KAAM,KAAK,IACnE,QAAQ,CACF,CACV,CAAC;AACJ,CAAC;AAID,oEAAoE;AACpE,MAAM,UAAU,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,KAAK,EAAe;IACvD,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IACvC,OAAO,oBAAC,OAAO,4BAAsB,EAAE,eAAW,QAAQ,EAAC,wBAAwB,WAAK,KAAK,GAAI,CAAC;AACpG,CAAC","sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport type { ComponentProps } from 'react';\nimport { Slot } from '../utils/slot.js';\nimport { tagName } from './element.js';\n\n/*\n * Headless password input: unstyled parts over the <govuk-react-password-input> element\n * (./element.ts), which adds the show and hide button on upgrade. Every part except Root takes\n * `asChild`.\n *\n * The input's `type` is the state, owned by the element, so there is no React state to control.\n */\n\nexport type RootProps = React.HTMLAttributes<HTMLElement> & {\n /** The button's text when the password is hidden. Defaults to \"Show\". */\n showText?: string;\n /** The button's text when the password is visible. Defaults to \"Hide\". */\n hideText?: string;\n /** The button's accessible name when the password is hidden. Defaults to \"Show password\". */\n showLabel?: string;\n /** The button's accessible name when the password is visible. Defaults to \"Hide password\". */\n hideLabel?: string;\n /** Announced when the password becomes visible. Defaults to \"Your password is visible\". */\n shownAnnouncement?: string;\n /** Announced when the password is hidden. Defaults to \"Your password is hidden\". */\n hiddenAnnouncement?: string;\n};\n\nexport function Root({\n showText,\n hideText,\n showLabel,\n hideLabel,\n shownAnnouncement,\n hiddenAnnouncement,\n ...props\n}: RootProps) {\n return React.createElement(tagName, {\n ...props,\n 'show-text': showText,\n 'hide-text': hideText,\n 'show-label': showLabel,\n 'hide-label': hideLabel,\n 'shown-announcement': shownAnnouncement,\n 'hidden-announcement': hiddenAnnouncement,\n });\n}\n\ntype PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E> & {\n /** Render the only child instead, with this part's props merged onto it. */\n asChild?: boolean;\n};\n\nexport type InputProps = PartProps<'input'>;\n\n/** The password field. Its `type` starts as \"password\" and the element switches it. */\nexport function Input({ asChild, ...props }: InputProps) {\n if (asChild) return <Slot data-password-input=\"\" suppressHydrationWarning {...props} />;\n // The element sets `type` after upgrade, so it can differ from the server's.\n return <input type=\"password\" data-password-input=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type ToggleProps = PartProps<'button'>;\n\n/** The show and hide button. Hidden until the element upgrades, which then sets its text and label. */\nexport function Toggle({ asChild, children = 'Show', ...props }: ToggleProps) {\n const shared = { 'data-password-toggle': '', hidden: true, suppressHydrationWarning: true };\n if (asChild)\n return (\n <Slot {...shared} {...props}>\n {children}\n </Slot>\n );\n return (\n <button type=\"button\" aria-label=\"Show password\" {...shared} {...props}>\n {children}\n </button>\n );\n}\n\nexport type StatusProps = PartProps<'div'>;\n\n/** A live region for the announcements. Make it visually hidden. */\nexport function Status({ asChild, ...props }: StatusProps) {\n const Element = asChild ? Slot : 'div';\n return <Element data-password-status=\"\" aria-live=\"polite\" suppressHydrationWarning {...props} />;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/password-input/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAyBvC,MAAM,UAAU,IAAI,CAAC,EACnB,QAAQ,EACR,QAAQ,EACR,SAAS,EACT,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,GAAG,KAAK,EACE;IACV,OAAO,KAAK,CAAC,aAAa,CAAC,OAAO,EAAE;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I,CAAC;AACpG,CAAC","sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport type { ComponentProps } from 'react';\nimport { Slot } from '../utils/slot.js';\nimport { tagName } from './element.js';\n\n/*\n * Headless password input: unstyled parts over the <govuk-react-password-input> element\n * (./element.ts), which adds the show and hide button on upgrade. Every part except Root takes\n * `asChild`.\n *\n * The input's `type` is the state, owned by the element, so there is no React state to control.\n */\n\nexport type RootProps = React.HTMLAttributes<HTMLElement> & {\n /** The button's text when the password is hidden. Defaults to \"Show\". */\n showText?: string;\n /** The button's text when the password is visible. Defaults to \"Hide\". */\n hideText?: string;\n /** The button's accessible name when the password is hidden. Defaults to \"Show password\". */\n showLabel?: string;\n /** The button's accessible name when the password is visible. Defaults to \"Hide password\". */\n hideLabel?: string;\n /** Announced when the password becomes visible. Defaults to \"Your password is visible\". */\n shownAnnouncement?: string;\n /** Announced when the password is hidden. Defaults to \"Your password is hidden\". */\n hiddenAnnouncement?: string;\n};\n\nexport function Root({\n showText,\n hideText,\n showLabel,\n hideLabel,\n shownAnnouncement,\n hiddenAnnouncement,\n ...props\n}: RootProps) {\n return React.createElement(tagName, {\n ...props,\n // The element owns `data-upgraded`.\n suppressHydrationWarning: true,\n 'show-text': showText,\n 'hide-text': hideText,\n 'show-label': showLabel,\n 'hide-label': hideLabel,\n 'shown-announcement': shownAnnouncement,\n 'hidden-announcement': hiddenAnnouncement,\n });\n}\n\ntype PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E> & {\n /** Render the only child instead, with this part's props merged onto it. */\n asChild?: boolean;\n};\n\nexport type InputProps = PartProps<'input'>;\n\n/** The password field. Its `type` starts as \"password\" and the element switches it. */\nexport function Input({ asChild, ...props }: InputProps) {\n if (asChild) return <Slot data-password-input=\"\" suppressHydrationWarning {...props} />;\n // The element sets `type` after upgrade, so it can differ from the server's.\n return <input type=\"password\" data-password-input=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type TriggerProps = PartProps<'button'>;\n\n/** The show and hide button. Hidden until the element upgrades, which then sets its text and label. */\nexport function Trigger({ asChild, children = 'Show', ...props }: TriggerProps) {\n const shared = { 'data-password-trigger': '', hidden: true, suppressHydrationWarning: true };\n if (asChild)\n return (\n <Slot {...shared} {...props}>\n {children}\n </Slot>\n );\n return (\n <button type=\"button\" aria-label=\"Show password\" {...shared} {...props}>\n {children}\n </button>\n );\n}\n\nexport type StatusProps = PartProps<'div'>;\n\n/** A live region for the announcements. Make it visually hidden. */\nexport function Status({ asChild, ...props }: StatusProps) {\n const Element = asChild ? Slot : 'div';\n return <Element data-password-status=\"\" aria-live=\"polite\" suppressHydrationWarning {...props} />;\n}\n"]}
@@ -0,0 +1,11 @@
1
+ /* Rules the primitives' fallbacks need. They set no look, only `display`. */
2
+
3
+ /* Tabs: the radios fallback shows only the checked tab's panel, until the element upgrades. */
4
+ govuk-react-tabs:not([data-upgraded]) [data-tabs-content]:has(> input[data-tabs-fallback]):not(:has(> input:checked)) {
5
+ display: none;
6
+ }
7
+
8
+ /* Accordion: `hidden` wins over a display set on a fallback heading, trigger or controls. */
9
+ govuk-react-accordion :is([data-accordion-fallback], [data-accordion-trigger], [data-accordion-controls])[hidden] {
10
+ display: none !important;
11
+ }
@@ -1,4 +1,7 @@
1
1
  declare global {
2
+ interface HTMLElementTagNameMap {
3
+ 'govuk-react-tabs': TabsElement;
4
+ }
2
5
  interface HTMLElementEventMap {
3
6
  'govuk-react-tabs:change': CustomEvent<{
4
7
  value: string;
@@ -24,7 +24,6 @@
24
24
  * - `media`: below this media query the element leaves the no-JS behaviour as it is.
25
25
  * - `upgraded-class`, `active-item-class`, `hidden-content-class`: classes to add, for styles
26
26
  * keyed off classes rather than `data-state`, `aria-selected` and `hidden`.
27
- * - `prefer-pick`: a tab picked before upgrade (checked radio or URL hash) wins over `value`.
28
27
  *
29
28
  * While upgraded it sets `data-upgraded`. A user's choice fires a bubbling
30
29
  * `govuk-react-tabs:change` event with `{ value }`, for code that doesn't use React. With
@@ -120,7 +119,7 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
120
119
  };
121
120
  }
122
121
  static get observedAttributes() {
123
- return ['value'];
122
+ return ['value', 'media'];
124
123
  }
125
124
  get value() {
126
125
  return this.getAttribute('value');
@@ -186,10 +185,15 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
186
185
  this.started = false;
187
186
  this.teardown();
188
187
  }
189
- attributeChangedCallback(_name, oldValue, value) {
190
- // Until it starts, the element reads `value` when it sets up, after any pick before upgrade.
188
+ attributeChangedCallback(name, oldValue, value) {
189
+ // Until it starts, the element reads its attributes when it sets up, after any pick before upgrade.
191
190
  if (!this.started)
192
191
  return;
192
+ if (name === 'media') {
193
+ if (oldValue !== value)
194
+ this.watchMedia();
195
+ return;
196
+ }
193
197
  if (value != null && oldValue !== value && value !== this.dataset.value)
194
198
  this.select(value);
195
199
  }
@@ -262,11 +266,14 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
262
266
  if (this.started)
263
267
  return;
264
268
  this.started = true;
269
+ this.watchMedia();
270
+ }
271
+ watchMedia() {
272
+ var _a, _b;
273
+ (_a = this.mql) === null || _a === void 0 ? void 0 : _a.removeEventListener('change', this.onModeChange);
265
274
  const media = this.getAttribute('media');
266
- if (media) {
267
- this.mql = window.matchMedia(media);
268
- this.mql.addEventListener('change', this.onModeChange);
269
- }
275
+ this.mql = media ? window.matchMedia(media) : undefined;
276
+ (_b = this.mql) === null || _b === void 0 ? void 0 : _b.addEventListener('change', this.onModeChange);
270
277
  this.checkMode();
271
278
  }
272
279
  checkMode() {
@@ -286,12 +293,12 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
286
293
  return this.triggerFor(valueOf(checked));
287
294
  }
288
295
  initialTrigger() {
289
- var _a, _b, _c, _d;
296
+ var _a, _b;
290
297
  const controlled = this.triggerFor(this.getAttribute('value'));
291
298
  const remembered = this.triggerFor(this.dataset.value);
292
299
  const picked = this.pickedTrigger();
293
300
  const fallback = this.triggerFor(this.getAttribute('default-value'));
294
- const initial = (_d = (_c = (_b = (_a = (this.hasAttribute('prefer-pick') && !remembered ? picked : undefined)) !== null && _a !== void 0 ? _a : controlled) !== null && _b !== void 0 ? _b : remembered) !== null && _c !== void 0 ? _c : picked) !== null && _d !== void 0 ? _d : fallback;
301
+ const initial = (_b = (_a = controlled !== null && controlled !== void 0 ? controlled : remembered) !== null && _a !== void 0 ? _a : picked) !== null && _b !== void 0 ? _b : fallback;
295
302
  this.provisional = !initial;
296
303
  return initial !== null && initial !== void 0 ? initial : this.triggers[0];
297
304
  }