@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
@@ -8,15 +8,15 @@ export { countOf, countMessage } from './messages.js';
8
8
  // What the counts start with, so the element only changes text React rendered.
9
9
  const InitialMessage = createContext(undefined);
10
10
  const isCharacterCount = (element) => 'update' in element;
11
- export function Root({ maxLength, countType = 'length', threshold, charactersUnderLimit, charactersAtLimit, charactersOverLimit, wordsUnderLimit, wordsAtLimit, wordsOverLimit, hiddenDescriptionClass, withinLimitClass, overLimitClass, belowThresholdClass, inputOverLimitClass, ...props }) {
11
+ export function Root({ maxLength, countType = 'length', threshold, charactersUnderLimitText, charactersAtLimitText, charactersOverLimitText, wordsUnderLimitText, wordsAtLimitText, wordsOverLimitText, hiddenDescriptionClass, withinLimitClass, overLimitClass, belowThresholdClass, inputOverLimitClass, ...props }) {
12
12
  const element = useRef(null);
13
13
  const messages = {
14
- 'characters-under-limit': charactersUnderLimit,
15
- 'characters-at-limit': charactersAtLimit,
16
- 'characters-over-limit': charactersOverLimit,
17
- 'words-under-limit': wordsUnderLimit,
18
- 'words-at-limit': wordsAtLimit,
19
- 'words-over-limit': wordsOverLimit,
14
+ 'characters-under-limit-text': charactersUnderLimitText,
15
+ 'characters-at-limit-text': charactersAtLimitText,
16
+ 'characters-over-limit-text': charactersOverLimitText,
17
+ 'words-under-limit-text': wordsUnderLimitText,
18
+ 'words-at-limit-text': wordsAtLimitText,
19
+ 'words-over-limit-text': wordsOverLimitText,
20
20
  };
21
21
  // A value set by React, rather than typed, fires no `input` event.
22
22
  useEffect(() => {
@@ -34,12 +34,12 @@ export function Root({ maxLength, countType = 'length', threshold, charactersUnd
34
34
  maxlength: maxLength,
35
35
  'count-type': countType,
36
36
  threshold,
37
- ...messageAttributes('characters-under-limit', charactersUnderLimit),
38
- ...messageAttributes('characters-at-limit', charactersAtLimit),
39
- ...messageAttributes('characters-over-limit', charactersOverLimit),
40
- ...messageAttributes('words-under-limit', wordsUnderLimit),
41
- ...messageAttributes('words-at-limit', wordsAtLimit),
42
- ...messageAttributes('words-over-limit', wordsOverLimit),
37
+ ...messageAttributes('characters-under-limit-text', charactersUnderLimitText),
38
+ ...messageAttributes('characters-at-limit-text', charactersAtLimitText),
39
+ ...messageAttributes('characters-over-limit-text', charactersOverLimitText),
40
+ ...messageAttributes('words-under-limit-text', wordsUnderLimitText),
41
+ ...messageAttributes('words-at-limit-text', wordsAtLimitText),
42
+ ...messageAttributes('words-over-limit-text', wordsOverLimitText),
43
43
  'hidden-description-class': hiddenDescriptionClass,
44
44
  'within-limit-class': withinLimitClass,
45
45
  'over-limit-class': overLimitClass,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/character-count/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE/E,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,OAAO,EAA8B,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAoC,MAAM,eAAe,CAAC;AAElG,OAAO,EAAE,OAAO,EAAE,YAAY,EAAoC,MAAM,eAAe,CAAC;AA6CxF,+EAA+E;AAC/E,MAAM,cAAc,GAAG,aAAa,CAAqB,SAAS,CAAC,CAAC;AAEpE,MAAM,gBAAgB,GAAG,CAAC,OAAoB,EAAoC,EAAE,CAAC,QAAQ,IAAI,OAAO,CAAC;AAEzG,MAAM,UAAU,IAAI,CAAC,EACnB,SAAS,EACT,SAAS,GAAG,QAAQ,EACpB,SAAS,EACT,oBAAoB,EACpB,iBAAiB,EACjB,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BAAa,MAAM,EAAC,wBAAwB,WAAK,KAAK,IACjG,QAAQ,aAAR,QAAQ,cAAR,QAAQ,GAAI,OAAO,CACZ,CACX,CAAC;AACJ,CAAC;AAID,0FAA0F;AAC1F,MAAM,UAAU,kBAAkB,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,KAAK,EAA2B;IACzF,MAAM,OAAO,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC;IAC3C,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IACvC,uEAAuE;IACvE,OAAO,CACL,oBAAC,OAAO,sCAAgC,EAAE,EAAC,MAAM,qBAAW,QAAQ,EAAC,wBAAwB,WAAK,KAAK,IACpG,QAAQ,aAAR,QAAQ,cAAR,QAAQ,GAAI,OAAO,CACZ,CACX,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport { createContext, useContext, useEffect, useRef, useState } from 'react';\nimport type { ComponentProps } from 'react';\nimport { Slot } from '../utils/slot.js';\nimport { tagName, type CharacterCountElement } from './element.js';\nimport { countMessage, messageAttributes, type CountType, type Translation } from './messages.js';\n\nexport { countOf, countMessage, type CountType, type Translation } from './messages.js';\n\n/*\n * Headless character count: unstyled parts over the <govuk-react-character-count> element\n * (./element.ts), which shows the count on upgrade and keeps it up to date. Every part except Root\n * takes `asChild`.\n *\n * The field's value is the state, so there is nothing else to control. Without JavaScript the\n * description is shown and the counts are hidden.\n */\n\nexport type RootProps = React.HTMLAttributes<HTMLElement> & {\n /** The most characters, or words, the user should enter. Without it there's no count. */\n maxLength?: number;\n /**\n * What to count: \"length\" (the default) counts UTF-16 code units, as `maxlength` does;\n * \"characters\" counts characters as users see them, such as an emoji as one; \"words\" counts words.\n */\n countType?: CountType;\n /** The percentage of the limit from which the count is shown. */\n threshold?: number;\n /** Shown while under the limit. `%{count}` is the number left. */\n charactersUnderLimit?: Translation;\n /** Shown at the limit. */\n charactersAtLimit?: Translation;\n /** Shown while over the limit. `%{count}` is the number too many. */\n charactersOverLimit?: Translation;\n /** Shown while under the limit when counting words. `%{count}` is the number left. */\n wordsUnderLimit?: Translation;\n /** Shown at the limit when counting words. */\n wordsAtLimit?: Translation;\n /** Shown while over the limit when counting words. `%{count}` is the number too many. */\n wordsOverLimit?: Translation;\n /** Classes that visually hide the description once upgraded. Without them, inline styles do. */\n hiddenDescriptionClass?: string;\n /** Classes for the visible count while within the limit. */\n withinLimitClass?: string;\n /** Classes for the visible count while over the limit. */\n overLimitClass?: string;\n /** Classes for the visible count while below `threshold`. */\n belowThresholdClass?: string;\n /** Classes for the field while over the limit. */\n inputOverLimitClass?: string;\n};\n\n// What the counts start with, so the element only changes text React rendered.\nconst InitialMessage = createContext<string | undefined>(undefined);\n\nconst isCharacterCount = (element: HTMLElement): element is CharacterCountElement => 'update' in element;\n\nexport function Root({\n maxLength,\n countType = 'length',\n threshold,\n charactersUnderLimit,\n charactersAtLimit,\n charactersOverLimit,\n wordsUnderLimit,\n wordsAtLimit,\n wordsOverLimit,\n hiddenDescriptionClass,\n withinLimitClass,\n overLimitClass,\n belowThresholdClass,\n inputOverLimitClass,\n ...props\n}: RootProps) {\n const element = useRef<HTMLElement>(null);\n const messages = {\n 'characters-under-limit': charactersUnderLimit,\n 'characters-at-limit': charactersAtLimit,\n 'characters-over-limit': charactersOverLimit,\n 'words-under-limit': wordsUnderLimit,\n 'words-at-limit': wordsAtLimit,\n 'words-over-limit': wordsOverLimit,\n };\n\n // A value set by React, rather than typed, fires no `input` event.\n useEffect(() => {\n const node = element.current;\n if (node && isCharacterCount(node)) node.update();\n });\n\n // Rendered once and then left to the element, so a re-render never puts back a stale count.\n const [initial] = useState(() =>\n maxLength === undefined ? undefined : countMessage(maxLength, countType, messages, props.lang || 'en').text\n );\n\n return (\n <InitialMessage.Provider value={initial}>\n {React.createElement(tagName, {\n ...props,\n ref: element,\n // The element owns `data-upgraded`.\n suppressHydrationWarning: true,\n maxlength: maxLength,\n 'count-type': countType,\n threshold,\n ...messageAttributes('characters-under-limit', charactersUnderLimit),\n ...messageAttributes('characters-at-limit', charactersAtLimit),\n ...messageAttributes('characters-over-limit', charactersOverLimit),\n ...messageAttributes('words-under-limit', wordsUnderLimit),\n ...messageAttributes('words-at-limit', wordsAtLimit),\n ...messageAttributes('words-over-limit', wordsOverLimit),\n 'hidden-description-class': hiddenDescriptionClass,\n 'within-limit-class': withinLimitClass,\n 'over-limit-class': overLimitClass,\n 'below-threshold-class': belowThresholdClass,\n 'input-over-limit-class': inputOverLimitClass,\n })}\n </InitialMessage.Provider>\n );\n}\n\ntype PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E> & {\n /** Render the only child instead, with this part's props merged onto it. */\n asChild?: boolean;\n};\n\nexport type InputProps = PartProps<'textarea'>;\n\n/** The field: a `textarea`, or an `input` with `asChild`. Its `maxlength` is removed on upgrade. */\nexport function Input({ asChild, ...props }: InputProps) {\n const Element = asChild ? Slot : 'textarea';\n // The element owns `maxlength` and its over-limit classes after upgrade.\n return <Element data-character-count-input=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type DescriptionProps = PartProps<'div'>;\n\n/**\n * The description, such as \"You can enter up to 200 characters\", shown without JavaScript and\n * visually hidden on upgrade. Give it an id and add that to the field's `aria-describedby`.\n */\nexport function Description({ asChild, ...props }: DescriptionProps) {\n const Element = asChild ? Slot : 'div';\n // The element owns its hiding styles after upgrade.\n return <Element data-character-count-description=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type StatusProps = PartProps<'div'>;\n\n/** The visible count, hidden from assistive technology. Hidden until the element upgrades. */\nexport function Status({ asChild, children, ...props }: StatusProps) {\n const initial = useContext(InitialMessage);\n const Element = asChild ? Slot : 'div';\n // The element owns `hidden`, its text and its classes after upgrade.\n return (\n <Element data-character-count-status=\"\" hidden aria-hidden=\"true\" suppressHydrationWarning {...props}>\n {children ?? initial}\n </Element>\n );\n}\n\nexport type ScreenReaderStatusProps = PartProps<'div'>;\n\n/** The count for screen readers, once the user pauses typing. Make it visually hidden. */\nexport function ScreenReaderStatus({ asChild, children, ...props }: ScreenReaderStatusProps) {\n const initial = useContext(InitialMessage);\n const Element = asChild ? Slot : 'div';\n // The element owns `hidden`, `aria-hidden` and its text after upgrade.\n return (\n <Element data-character-count-sr-status=\"\" hidden aria-live=\"polite\" suppressHydrationWarning {...props}>\n {children ?? initial}\n </Element>\n );\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/character-count/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE/E,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,OAAO,EAA8B,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAoC,MAAM,eAAe,CAAC;AAElG,OAAO,EAAE,OAAO,EAAE,YAAY,EAAoC,MAAM,eAAe,CAAC;AA6CxF,+EAA+E;AAC/E,MAAM,cAAc,GAAG,aAAa,CAAqB,SAAS,CAAC,CAAC;AAEpE,MAAM,gBAAgB,GAAG,CAAC,OAAoB,EAAoC,EAAE,CAAC,QAAQ,IAAI,OAAO,CAAC;AAEzG,MAAM,UAAU,IAAI,CAAC,EACnB,SAAS,EACT,SAAS,GAAG,QAAQ,EACpB,SAAS,EACT,wBAAwB,EACxB,qBAAqB,EACrB,uBAAuB,EACvB,mBAAmB,EACnB,gBAAgB,EAChB,kBAAkB,EAClB,sBAAsB,EACtB,gBAAgB,EAChB,cAAc,EACd,mBAAmB,EACnB,mBAAmB,EACnB,GAAG,KAAK,EACE;IACV,MAAM,OAAO,GAAG,MAAM,CAAc,IAAI,CAAC,CAAC;IAC1C,MAAM,QAAQ,GAAG;QACf,6BAA6B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AA2B;IACzF,MAAM,OAAO,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC;IAC3C,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IACvC,uEAAuE;IACvE,OAAO,CACL,oBAAC,OAAO,sCAAgC,EAAE,EAAC,MAAM,qBAAW,QAAQ,EAAC,wBAAwB,WAAK,KAAK,IACpG,QAAQ,aAAR,QAAQ,cAAR,QAAQ,GAAI,OAAO,CACZ,CACX,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport { createContext, useContext, useEffect, useRef, useState } from 'react';\nimport type { ComponentProps } from 'react';\nimport { Slot } from '../utils/slot.js';\nimport { tagName, type CharacterCountElement } from './element.js';\nimport { countMessage, messageAttributes, type CountType, type Translation } from './messages.js';\n\nexport { countOf, countMessage, type CountType, type Translation } from './messages.js';\n\n/*\n * Headless character count: unstyled parts over the <govuk-react-character-count> element\n * (./element.ts), which shows the count on upgrade and keeps it up to date. Every part except Root\n * takes `asChild`.\n *\n * The field's value is the state, so there is nothing else to control. Without JavaScript the\n * description is shown and the counts are hidden.\n */\n\nexport type RootProps = React.HTMLAttributes<HTMLElement> & {\n /** The most characters, or words, the user should enter. Without it there's no count. */\n maxLength?: number;\n /**\n * What to count: \"length\" (the default) counts UTF-16 code units, as `maxlength` does;\n * \"characters\" counts characters as users see them, such as an emoji as one; \"words\" counts words.\n */\n countType?: CountType;\n /** The percentage of the limit from which the count is shown. */\n threshold?: number;\n /** Shown while under the limit. `%{count}` is the number left. */\n charactersUnderLimitText?: Translation;\n /** Shown at the limit. */\n charactersAtLimitText?: Translation;\n /** Shown while over the limit. `%{count}` is the number too many. */\n charactersOverLimitText?: Translation;\n /** Shown while under the limit when counting words. `%{count}` is the number left. */\n wordsUnderLimitText?: Translation;\n /** Shown at the limit when counting words. */\n wordsAtLimitText?: Translation;\n /** Shown while over the limit when counting words. `%{count}` is the number too many. */\n wordsOverLimitText?: Translation;\n /** Classes that visually hide the description once upgraded. Without them, inline styles do. */\n hiddenDescriptionClass?: string;\n /** Classes for the visible count while within the limit. */\n withinLimitClass?: string;\n /** Classes for the visible count while over the limit. */\n overLimitClass?: string;\n /** Classes for the visible count while below `threshold`. */\n belowThresholdClass?: string;\n /** Classes for the field while over the limit. */\n inputOverLimitClass?: string;\n};\n\n// What the counts start with, so the element only changes text React rendered.\nconst InitialMessage = createContext<string | undefined>(undefined);\n\nconst isCharacterCount = (element: HTMLElement): element is CharacterCountElement => 'update' in element;\n\nexport function Root({\n maxLength,\n countType = 'length',\n threshold,\n charactersUnderLimitText,\n charactersAtLimitText,\n charactersOverLimitText,\n wordsUnderLimitText,\n wordsAtLimitText,\n wordsOverLimitText,\n hiddenDescriptionClass,\n withinLimitClass,\n overLimitClass,\n belowThresholdClass,\n inputOverLimitClass,\n ...props\n}: RootProps) {\n const element = useRef<HTMLElement>(null);\n const messages = {\n 'characters-under-limit-text': charactersUnderLimitText,\n 'characters-at-limit-text': charactersAtLimitText,\n 'characters-over-limit-text': charactersOverLimitText,\n 'words-under-limit-text': wordsUnderLimitText,\n 'words-at-limit-text': wordsAtLimitText,\n 'words-over-limit-text': wordsOverLimitText,\n };\n\n // A value set by React, rather than typed, fires no `input` event.\n useEffect(() => {\n const node = element.current;\n if (node && isCharacterCount(node)) node.update();\n });\n\n // Rendered once and then left to the element, so a re-render never puts back a stale count.\n const [initial] = useState(() =>\n maxLength === undefined ? undefined : countMessage(maxLength, countType, messages, props.lang || 'en').text\n );\n\n return (\n <InitialMessage.Provider value={initial}>\n {React.createElement(tagName, {\n ...props,\n ref: element,\n // The element owns `data-upgraded`.\n suppressHydrationWarning: true,\n maxlength: maxLength,\n 'count-type': countType,\n threshold,\n ...messageAttributes('characters-under-limit-text', charactersUnderLimitText),\n ...messageAttributes('characters-at-limit-text', charactersAtLimitText),\n ...messageAttributes('characters-over-limit-text', charactersOverLimitText),\n ...messageAttributes('words-under-limit-text', wordsUnderLimitText),\n ...messageAttributes('words-at-limit-text', wordsAtLimitText),\n ...messageAttributes('words-over-limit-text', wordsOverLimitText),\n 'hidden-description-class': hiddenDescriptionClass,\n 'within-limit-class': withinLimitClass,\n 'over-limit-class': overLimitClass,\n 'below-threshold-class': belowThresholdClass,\n 'input-over-limit-class': inputOverLimitClass,\n })}\n </InitialMessage.Provider>\n );\n}\n\ntype PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E> & {\n /** Render the only child instead, with this part's props merged onto it. */\n asChild?: boolean;\n};\n\nexport type InputProps = PartProps<'textarea'>;\n\n/** The field: a `textarea`, or an `input` with `asChild`. Its `maxlength` is removed on upgrade. */\nexport function Input({ asChild, ...props }: InputProps) {\n const Element = asChild ? Slot : 'textarea';\n // The element owns `maxlength` and its over-limit classes after upgrade.\n return <Element data-character-count-input=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type DescriptionProps = PartProps<'div'>;\n\n/**\n * The description, such as \"You can enter up to 200 characters\", shown without JavaScript and\n * visually hidden on upgrade. Give it an id and add that to the field's `aria-describedby`.\n */\nexport function Description({ asChild, ...props }: DescriptionProps) {\n const Element = asChild ? Slot : 'div';\n // The element owns its hiding styles after upgrade.\n return <Element data-character-count-description=\"\" suppressHydrationWarning {...props} />;\n}\n\nexport type StatusProps = PartProps<'div'>;\n\n/** The visible count, hidden from assistive technology. Hidden until the element upgrades. */\nexport function Status({ asChild, children, ...props }: StatusProps) {\n const initial = useContext(InitialMessage);\n const Element = asChild ? Slot : 'div';\n // The element owns `hidden`, its text and its classes after upgrade.\n return (\n <Element data-character-count-status=\"\" hidden aria-hidden=\"true\" suppressHydrationWarning {...props}>\n {children ?? initial}\n </Element>\n );\n}\n\nexport type ScreenReaderStatusProps = PartProps<'div'>;\n\n/** The count for screen readers, once the user pauses typing. Make it visually hidden. */\nexport function ScreenReaderStatus({ asChild, children, ...props }: ScreenReaderStatusProps) {\n const initial = useContext(InitialMessage);\n const Element = asChild ? Slot : 'div';\n // The element owns `hidden`, `aria-hidden` and its text after upgrade.\n return (\n <Element data-character-count-sr-status=\"\" hidden aria-live=\"polite\" suppressHydrationWarning {...props}>\n {children ?? initial}\n </Element>\n );\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { type Translation } from '../utils/translation.js';
2
2
  export type { Translation };
3
3
  export type CountType = 'length' | 'characters' | 'words';
4
- export declare const messageNames: readonly ["characters-under-limit", "characters-at-limit", "characters-over-limit", "words-under-limit", "words-at-limit", "words-over-limit"];
4
+ export declare const messageNames: readonly ["characters-under-limit-text", "characters-at-limit-text", "characters-over-limit-text", "words-under-limit-text", "words-at-limit-text", "words-over-limit-text"];
5
5
  export type MessageName = (typeof messageNames)[number];
6
6
  /** govuk-frontend's English messages. `%{count}` is replaced with the number. */
7
7
  export declare const defaultMessages: Record<MessageName, Translation>;
@@ -4,27 +4,27 @@
4
4
  */
5
5
  import { translate, translationAttributes, translationFromAttributes, withLocale, } from '../utils/translation.js';
6
6
  export const messageNames = [
7
- 'characters-under-limit',
8
- 'characters-at-limit',
9
- 'characters-over-limit',
10
- 'words-under-limit',
11
- 'words-at-limit',
12
- 'words-over-limit',
7
+ 'characters-under-limit-text',
8
+ 'characters-at-limit-text',
9
+ 'characters-over-limit-text',
10
+ 'words-under-limit-text',
11
+ 'words-at-limit-text',
12
+ 'words-over-limit-text',
13
13
  ];
14
14
  /** govuk-frontend's English messages. `%{count}` is replaced with the number. */
15
15
  export const defaultMessages = {
16
- 'characters-under-limit': {
16
+ 'characters-under-limit-text': {
17
17
  one: 'You have %{count} character remaining',
18
18
  other: 'You have %{count} characters remaining',
19
19
  },
20
- 'characters-at-limit': 'You have 0 characters remaining',
21
- 'characters-over-limit': {
20
+ 'characters-at-limit-text': 'You have 0 characters remaining',
21
+ 'characters-over-limit-text': {
22
22
  one: 'You have %{count} character too many',
23
23
  other: 'You have %{count} characters too many',
24
24
  },
25
- 'words-under-limit': { one: 'You have %{count} word remaining', other: 'You have %{count} words remaining' },
26
- 'words-at-limit': 'You have 0 words remaining',
27
- 'words-over-limit': { one: 'You have %{count} word too many', other: 'You have %{count} words too many' },
25
+ 'words-under-limit-text': { one: 'You have %{count} word remaining', other: 'You have %{count} words remaining' },
26
+ 'words-at-limit-text': 'You have 0 words remaining',
27
+ 'words-over-limit-text': { one: 'You have %{count} word too many', other: 'You have %{count} words too many' },
28
28
  };
29
29
  /** The attributes for a message: the message itself, or one attribute for each plural form. */
30
30
  export const messageAttributes = (name, message) => translationAttributes(name, message);
@@ -47,7 +47,7 @@ export function countOf(text, countType, locale) {
47
47
  export function countMessage(remaining, countType, messages, locale) {
48
48
  var _a;
49
49
  const state = remaining < 0 ? 'over' : remaining === 0 ? 'at' : 'under';
50
- const name = `${countType === 'words' ? 'words' : 'characters'}-${state}-limit`;
50
+ const name = `${countType === 'words' ? 'words' : 'characters'}-${state}-limit-text`;
51
51
  const message = (_a = messages[name]) !== null && _a !== void 0 ? _a : defaultMessages[name];
52
52
  return { state, text: translate(message, Math.abs(remaining), locale) };
53
53
  }
@@ -1 +1 @@
1
- {"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/character-count/messages.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,SAAS,EACT,qBAAqB,EACrB,yBAAyB,EACzB,UAAU,GAEX,MAAM,yBAAyB,CAAC;AAMjC,MAAM,CAAC,MAAM,YAAY,GAAG;IAC1B,wBAAwB;IACxB,qBAAqB;IACrB,uBAAuB;IACvB,mBAAmB;IACnB,gBAAgB;IAChB,kBAAkB;CACV,CAAC;AAIX,iFAAiF;AACjF,MAAM,CAAC,MAAM,eAAe,GAAqC;IAC/D,wBAAwB,EAAE;QACxB,GAAG,EAAE,uCAAuC;QAC5C,KAAK,EAAE,wCAAwC;KAChD;IACD,qBAAqB,EAAE,iCAAiC;IACxD,uBAAuB,EAAE;QACvB,GAAG,EAAE,sCAAsC;QAC3C,KAAK,EAAE,uCAAuC;KAC/C;IACD,mBAAmB,EAAE,EAAE,GAAG,EAAE,kCAAkC,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AK,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC;AAC3G,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,YAAY,CAC1B,SAAiB,EACjB,SAAoB,EACpB,QAAmD,EACnD,MAAe;;IAEf,MAAM,KAAK,GAAG,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC;IACxE,MAAM,IAAI,GAAgB,GAAG,SAAS,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,YAAY,IAAI,KAAK,QAAQ,CAAC;IAC7F,MAAM,OAAO,GAAG,MAAA,QAAQ,CAAC,IAAI,CAAC,mCAAI,eAAe,CAAC,IAAI,CAAC,CAAC;IACxD,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,EAAE,CAAC;AAC1E,CAAC","sourcesContent":["/*\n * Counting and count messages, shared by the <govuk-react-character-count> element and its React\n * parts, so the server can render the message the element starts with.\n */\n\nimport {\n translate,\n translationAttributes,\n translationFromAttributes,\n withLocale,\n type Translation,\n} from '../utils/translation.js';\n\nexport type { Translation };\n\nexport type CountType = 'length' | 'characters' | 'words';\n\nexport const messageNames = [\n 'characters-under-limit',\n 'characters-at-limit',\n 'characters-over-limit',\n 'words-under-limit',\n 'words-at-limit',\n 'words-over-limit',\n] as const;\n\nexport type MessageName = (typeof messageNames)[number];\n\n/** govuk-frontend's English messages. `%{count}` is replaced with the number. */\nexport const defaultMessages: Record<MessageName, Translation> = {\n 'characters-under-limit': {\n one: 'You have %{count} character remaining',\n other: 'You have %{count} characters remaining',\n },\n 'characters-at-limit': 'You have 0 characters remaining',\n 'characters-over-limit': {\n one: 'You have %{count} character too many',\n other: 'You have %{count} characters too many',\n },\n 'words-under-limit': { one: 'You have %{count} word remaining', other: 'You have %{count} words remaining' },\n 'words-at-limit': 'You have 0 words remaining',\n 'words-over-limit': { one: 'You have %{count} word too many', other: 'You have %{count} words too many' },\n};\n\n/** The attributes for a message: the message itself, or one attribute for each plural form. */\nexport const messageAttributes = (name: MessageName, message: Translation | undefined) =>\n translationAttributes(name, message);\n\n/** Reads a message back from attributes written by `messageAttributes`. */\nexport const messageFromAttributes = (element: Element, name: MessageName) => translationFromAttributes(element, name);\n\n/** Counts the text as govuk-frontend does: UTF-16 code units, characters as users see them, or words. */\nexport function countOf(text: string, countType: CountType, locale?: string) {\n if (countType === 'length') return text.length;\n if (typeof Intl.Segmenter !== 'function') {\n // Older browsers: close enough, rather than no count at all.\n return countType === 'words' ? (text.match(/\\S+/g)?.length ?? 0) : Array.from(text).length;\n }\n const segmenter = withLocale(\n locale,\n (l) => new Intl.Segmenter(l, { granularity: countType === 'words' ? 'word' : 'grapheme' })\n );\n const segments = Array.from(segmenter.segment(text));\n return countType === 'words' ? segments.filter((segment) => segment.isWordLike).length : segments.length;\n}\n\n/** The message for the number of characters or words left, with its state. */\nexport function countMessage(\n remaining: number,\n countType: CountType,\n messages: Partial<Record<MessageName, Translation>>,\n locale?: string\n) {\n const state = remaining < 0 ? 'over' : remaining === 0 ? 'at' : 'under';\n const name: MessageName = `${countType === 'words' ? 'words' : 'characters'}-${state}-limit`;\n const message = messages[name] ?? defaultMessages[name];\n return { state, text: translate(message, Math.abs(remaining), locale) };\n}\n"]}
1
+ {"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/character-count/messages.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,SAAS,EACT,qBAAqB,EACrB,yBAAyB,EACzB,UAAU,GAEX,MAAM,yBAAyB,CAAC;AAMjC,MAAM,CAAC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react-character-count> element and its React\n * parts, so the server can render the message the element starts with.\n */\n\nimport {\n translate,\n translationAttributes,\n translationFromAttributes,\n withLocale,\n type Translation,\n} from '../utils/translation.js';\n\nexport type { Translation };\n\nexport type CountType = 'length' | 'characters' | 'words';\n\nexport const messageNames = [\n 'characters-under-limit-text',\n 'characters-at-limit-text',\n 'characters-over-limit-text',\n 'words-under-limit-text',\n 'words-at-limit-text',\n 'words-over-limit-text',\n] as const;\n\nexport type MessageName = (typeof messageNames)[number];\n\n/** govuk-frontend's English messages. `%{count}` is replaced with the number. */\nexport const defaultMessages: Record<MessageName, Translation> = {\n 'characters-under-limit-text': {\n one: 'You have %{count} character remaining',\n other: 'You have %{count} characters remaining',\n },\n 'characters-at-limit-text': 'You have 0 characters remaining',\n 'characters-over-limit-text': {\n one: 'You have %{count} character too many',\n other: 'You have %{count} characters too many',\n },\n 'words-under-limit-text': { one: 'You have %{count} word remaining', other: 'You have %{count} words remaining' },\n 'words-at-limit-text': 'You have 0 words remaining',\n 'words-over-limit-text': { one: 'You have %{count} word too many', other: 'You have %{count} words too many' },\n};\n\n/** The attributes for a message: the message itself, or one attribute for each plural form. */\nexport const messageAttributes = (name: MessageName, message: Translation | undefined) =>\n translationAttributes(name, message);\n\n/** Reads a message back from attributes written by `messageAttributes`. */\nexport const messageFromAttributes = (element: Element, name: MessageName) => translationFromAttributes(element, name);\n\n/** Counts the text as govuk-frontend does: UTF-16 code units, characters as users see them, or words. */\nexport function countOf(text: string, countType: CountType, locale?: string) {\n if (countType === 'length') return text.length;\n if (typeof Intl.Segmenter !== 'function') {\n // Older browsers: close enough, rather than no count at all.\n return countType === 'words' ? (text.match(/\\S+/g)?.length ?? 0) : Array.from(text).length;\n }\n const segmenter = withLocale(\n locale,\n (l) => new Intl.Segmenter(l, { granularity: countType === 'words' ? 'word' : 'grapheme' })\n );\n const segments = Array.from(segmenter.segment(text));\n return countType === 'words' ? segments.filter((segment) => segment.isWordLike).length : segments.length;\n}\n\n/** The message for the number of characters or words left, with its state. */\nexport function countMessage(\n remaining: number,\n countType: CountType,\n messages: Partial<Record<MessageName, Translation>>,\n locale?: string\n) {\n const state = remaining < 0 ? 'over' : remaining === 0 ? 'at' : 'under';\n const name: MessageName = `${countType === 'words' ? 'words' : 'characters'}-${state}-limit-text`;\n const message = messages[name] ?? defaultMessages[name];\n return { state, text: translate(message, Math.abs(remaining), locale) };\n}\n"]}
@@ -3,3 +3,8 @@ export interface ChoicesElement extends HTMLElement {
3
3
  /** Shows and hides the reveals to match the choices, such as after setting `checked`. */
4
4
  sync(): void;
5
5
  }
6
+ declare global {
7
+ interface HTMLElementTagNameMap {
8
+ 'govuk-react-choices': ChoicesElement;
9
+ }
10
+ }
@@ -23,7 +23,7 @@
23
23
  * `hidden` on it.
24
24
  */
25
25
  import { classesOf } from '../utils/dom.js';
26
- import { onPropertySet } from '../utils/on-property-set.js';
26
+ import { onPropertyChange } from '../utils/on-property-change.js';
27
27
  export const tagName = 'govuk-react-choices';
28
28
  const isChoice = (element) => element instanceof HTMLInputElement && (element.type === 'radio' || element.type === 'checkbox');
29
29
  if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {
@@ -31,20 +31,6 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
31
31
  constructor() {
32
32
  super(...arguments);
33
33
  this.upgraded = false;
34
- /** Puts back each choice's `checked` setter. */
35
- this.watched = new Map();
36
- this.syncQueued = false;
37
- // A `checked` set by a script, such as a form library's, fires no event. Checking a radio can
38
- // uncheck one in another element.
39
- this.onCheckedSet = () => {
40
- if (this.syncQueued)
41
- return;
42
- this.syncQueued = true;
43
- queueMicrotask(() => {
44
- this.syncQueued = false;
45
- this.syncAll();
46
- });
47
- };
48
34
  this.onClick = (event) => {
49
35
  const input = event.target;
50
36
  if (!isChoice(input) || !this.owns(input))
@@ -108,17 +94,19 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
108
94
  this.addEventListener('change', this.onChange);
109
95
  window.addEventListener('pageshow', this.onPageShow);
110
96
  document.addEventListener('reset', this.onReset, true);
97
+ this.stopWatchingChecked = onPropertyChange(() => this.choices()
98
+ .map((choice) => (choice.checked ? 1 : 0))
99
+ .join(''), () => this.syncAll());
111
100
  this.setup();
112
101
  }
113
102
  disconnectedCallback() {
114
- var _a;
103
+ var _a, _b;
115
104
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
116
105
  this.removeEventListener('click', this.onClick);
117
106
  this.removeEventListener('change', this.onChange);
118
107
  window.removeEventListener('pageshow', this.onPageShow);
119
108
  document.removeEventListener('reset', this.onReset, true);
120
- this.watched.forEach((stop) => stop());
121
- this.watched.clear();
109
+ (_b = this.stopWatchingChecked) === null || _b === void 0 ? void 0 : _b.call(this);
122
110
  }
123
111
  get root() {
124
112
  const root = this.getRootNode();
@@ -149,21 +137,8 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
149
137
  const target = root instanceof Document || root instanceof ShadowRoot ? root.getElementById(id) : null;
150
138
  return target instanceof HTMLElement && target.hasAttribute('data-choices-conditional') ? target : undefined;
151
139
  }
152
- watch(choices) {
153
- this.watched.forEach((stop, input) => {
154
- if (choices.includes(input))
155
- return;
156
- stop();
157
- this.watched.delete(input);
158
- });
159
- choices.forEach((input) => {
160
- if (!this.watched.has(input))
161
- this.watched.set(input, onPropertySet(input, 'checked', this.onCheckedSet));
162
- });
163
- }
164
140
  setup() {
165
141
  const choices = this.choices();
166
- this.watch(choices);
167
142
  if (!choices.length)
168
143
  return;
169
144
  if (!this.upgraded) {
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/choices/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAE5D,MAAM,CAAC,MAAM,OAAO,GAAG,qBAAqB,CA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,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;YAC3D,MAAM,aAAa,GAAG,SAAS,CAAC,IAAI,CAAC,YAAY,CAAC,0BAA0B,CAAC,CAAC,CAAC;YAC/E,8FAA8F;YAC9F,IAAI,aAAa,CAAC,MAAM;gBAAE,aAAa,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;;gBACpG,MAAM,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC;QACtC,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/*\n * <govuk-react-choices>: a headless, light-DOM custom element for a group of radios or checkboxes,\n * with or without React. It reveals content when a choice is checked, and makes a checkbox such\n * as \"None of these\" exclusive, as govuk-frontend's radios and checkboxes do.\n *\n * Without JavaScript every conditional reveal is shown, and an exclusive checkbox is an ordinary\n * one. On upgrade each reveal shows only while its choice is checked, and the choice gets\n * `aria-controls` and `aria-expanded`.\n *\n * Markup inside the element:\n * - `input[type=radio]` or `input[type=checkbox]`: the choices. `data-choices-controls` names the\n * id of the content it reveals. A checkbox with `data-choices-exclusive` unchecks the other\n * checkboxes with its name when checked, and is unchecked when one of them is.\n * - `[data-choices-conditional]`: the content a choice reveals, with an id.\n *\n * As in govuk-frontend, that covers checkboxes with the same name and form anywhere on the page,\n * and checking a radio updates the reveals of its whole group, even across elements. Choices are\n * unchecked with `click()`, so `change` events fire and React's `onChange` sees them.\n *\n * Attributes:\n * - `upgraded-class`: classes for the element once upgraded.\n * - `hidden-conditional-class`: classes that hide a reveal. Without them, the element sets\n * `hidden` on it.\n */\n\nimport { classesOf } from '../utils/dom.js';\nimport { onPropertySet } from '../utils/on-property-set.js';\n\nexport const tagName = 'govuk-react-choices';\n\nexport interface ChoicesElement extends HTMLElement {\n /** Shows and hides the reveals to match the choices, such as after setting `checked`. */\n sync(): void;\n}\n\nconst isChoice = (element: EventTarget | null): element is HTMLInputElement =>\n element instanceof HTMLInputElement && (element.type === 'radio' || element.type === 'checkbox');\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactChoices extends HTMLElement implements ChoicesElement {\n private upgraded = false;\n\n private observer?: MutationObserver;\n\n /** Puts back each choice's `checked` setter. */\n private readonly watched = new Map<HTMLInputElement, () => void>();\n\n private syncQueued = false;\n\n // A `checked` set by a script, such as a form library's, fires no event. Checking a radio can\n // uncheck one in another element.\n private readonly onCheckedSet = () => {\n if (this.syncQueued) return;\n this.syncQueued = true;\n queueMicrotask(() => {\n this.syncQueued = false;\n this.syncAll();\n });\n };\n\n private readonly onClick = (event: Event) => {\n const input = event.target;\n if (!isChoice(input) || !this.owns(input)) return;\n if (input.type === 'radio') {\n // Checking a radio unchecks another, with no event for it, maybe in another group.\n this.syncAll();\n return;\n }\n this.syncInput(input);\n if (!input.checked) return;\n const exclusive = input.hasAttribute('data-choices-exclusive');\n // As govuk-frontend: every checkbox with the name in the form, even in another group.\n const others = this.inputsNamed(input).filter(\n (other) =>\n other !== input &&\n other.type === 'checkbox' &&\n other.checked &&\n (exclusive || other.hasAttribute('data-choices-exclusive'))\n );\n // Unchecked once this click, and React's updates for it, are done, so each is its own event\n // that React sees.\n window.setTimeout(() => {\n others\n .filter((other) => other.checked)\n .forEach((other) => {\n // A disabled checkbox ignores `click()`.\n if (other.disabled) other.checked = false;\n else other.click();\n });\n this.syncAll();\n });\n };\n\n // `reset` changes the choices with no event for each, after it fires.\n private readonly onReset = (event: Event) => {\n if (event.target instanceof HTMLFormElement && this.choices().some((input) => input.form === event.target)) {\n window.setTimeout(() => this.sync());\n }\n };\n\n private readonly onChange = (event: Event) => {\n if (isChoice(event.target) && this.owns(event.target)) this.sync();\n };\n\n // A page restored from the back-forward cache keeps its choices.\n private readonly onPageShow = () => this.sync();\n\n connectedCallback() {\n this.observer = new MutationObserver((records) => {\n if (records.some((record) => record.type === 'childList')) this.setup();\n else {\n // React can rewrite the element's own class.\n if (this.upgraded) this.addUpgradedClasses();\n this.sync();\n }\n });\n // Choices rendered later, and a class React rewrites.\n this.observer.observe(this, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });\n this.addEventListener('click', this.onClick);\n this.addEventListener('change', this.onChange);\n window.addEventListener('pageshow', this.onPageShow);\n document.addEventListener('reset', this.onReset, true);\n this.setup();\n }\n\n disconnectedCallback() {\n this.observer?.disconnect();\n this.removeEventListener('click', this.onClick);\n this.removeEventListener('change', this.onChange);\n window.removeEventListener('pageshow', this.onPageShow);\n document.removeEventListener('reset', this.onReset, true);\n this.watched.forEach((stop) => stop());\n this.watched.clear();\n }\n\n private get root() {\n const root = this.getRootNode();\n return root instanceof Document || root instanceof ShadowRoot ? root : document;\n }\n\n /** The inputs with the same name and form, anywhere on the page. */\n private inputsNamed(input: HTMLInputElement) {\n return Array.from(this.root.querySelectorAll('input')).filter(\n (other) => other.type === input.type && other.name === input.name && other.form === input.form\n );\n }\n\n /** Syncs every element on the page, for choices that changed in another group. */\n private syncAll() {\n Array.from(this.root.querySelectorAll(tagName)).forEach((element) => {\n if (element instanceof GovukReactChoices) element.sync();\n });\n }\n\n private owns(element: Element) {\n return element.closest(tagName) === this;\n }\n\n private choices() {\n return Array.from(this.querySelectorAll('input')).filter((input) => isChoice(input) && this.owns(input));\n }\n\n private target(input: HTMLInputElement) {\n const id = input.getAttribute('data-choices-controls');\n if (!id) return undefined;\n const root = this.getRootNode();\n const target = root instanceof Document || root instanceof ShadowRoot ? root.getElementById(id) : null;\n return target instanceof HTMLElement && target.hasAttribute('data-choices-conditional') ? target : undefined;\n }\n\n private watch(choices: HTMLInputElement[]) {\n this.watched.forEach((stop, input) => {\n if (choices.includes(input)) return;\n stop();\n this.watched.delete(input);\n });\n choices.forEach((input) => {\n if (!this.watched.has(input)) this.watched.set(input, onPropertySet(input, 'checked', this.onCheckedSet));\n });\n }\n\n private setup() {\n const choices = this.choices();\n this.watch(choices);\n if (!choices.length) return;\n if (!this.upgraded) {\n this.upgraded = true;\n this.dataset.upgraded = '';\n this.addUpgradedClasses();\n }\n this.sync();\n }\n\n private addUpgradedClasses() {\n // `toggle` with force leaves a class that's already there alone, so the observer isn't woken.\n classesOf(this.getAttribute('upgraded-class')).forEach((name) => this.classList.toggle(name, true));\n }\n\n sync() {\n if (!this.upgraded) return;\n this.choices().forEach((input) => this.syncInput(input));\n }\n\n private syncInput(input: HTMLInputElement) {\n const target = this.target(input);\n if (!target) return;\n input.setAttribute('aria-controls', target.id);\n input.setAttribute('aria-expanded', String(input.checked));\n const hiddenClasses = classesOf(this.getAttribute('hidden-conditional-class'));\n // `toggle` with force leaves a class that's already there alone, so the observer isn't woken.\n if (hiddenClasses.length) hiddenClasses.forEach((name) => target.classList.toggle(name, !input.checked));\n else target.hidden = !input.checked;\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactChoices);\n}\n"]}
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/choices/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAElE,MAAM,CAAC,MAAM,OAAO,GAAG,qBAAqB,CAAC;AAa7C,MAAM,QAAQ,GAAG,CAAC,OAA2B,EAA+B,EAAE,CAC5E,OAAO,YAAY,gBAAgB,IAAI,CAAC,OAAO,CAAC,IAAI,KAAK,OAAO,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC;AAEnG,IAAI,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;IAChF,MAAM,iBA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K,CAAC,CAAC;YAClC,IAAI,CAAC,MAAM;gBAAE,OAAO;YACpB,KAAK,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC;YAC/C,KAAK,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;YAC3D,MAAM,aAAa,GAAG,SAAS,CAAC,IAAI,CAAC,YAAY,CAAC,0BAA0B,CAAC,CAAC,CAAC;YAC/E,8FAA8F;YAC9F,IAAI,aAAa,CAAC,MAAM;gBAAE,aAAa,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;;gBACpG,MAAM,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC;QACtC,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/*\n * <govuk-react-choices>: a headless, light-DOM custom element for a group of radios or checkboxes,\n * with or without React. It reveals content when a choice is checked, and makes a checkbox such\n * as \"None of these\" exclusive, as govuk-frontend's radios and checkboxes do.\n *\n * Without JavaScript every conditional reveal is shown, and an exclusive checkbox is an ordinary\n * one. On upgrade each reveal shows only while its choice is checked, and the choice gets\n * `aria-controls` and `aria-expanded`.\n *\n * Markup inside the element:\n * - `input[type=radio]` or `input[type=checkbox]`: the choices. `data-choices-controls` names the\n * id of the content it reveals. A checkbox with `data-choices-exclusive` unchecks the other\n * checkboxes with its name when checked, and is unchecked when one of them is.\n * - `[data-choices-conditional]`: the content a choice reveals, with an id.\n *\n * As in govuk-frontend, that covers checkboxes with the same name and form anywhere on the page,\n * and checking a radio updates the reveals of its whole group, even across elements. Choices are\n * unchecked with `click()`, so `change` events fire and React's `onChange` sees them.\n *\n * Attributes:\n * - `upgraded-class`: classes for the element once upgraded.\n * - `hidden-conditional-class`: classes that hide a reveal. Without them, the element sets\n * `hidden` on it.\n */\n\nimport { classesOf } from '../utils/dom.js';\nimport { onPropertyChange } from '../utils/on-property-change.js';\n\nexport const tagName = 'govuk-react-choices';\n\nexport interface ChoicesElement extends HTMLElement {\n /** Shows and hides the reveals to match the choices, such as after setting `checked`. */\n sync(): void;\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'govuk-react-choices': ChoicesElement;\n }\n}\n\nconst isChoice = (element: EventTarget | null): element is HTMLInputElement =>\n element instanceof HTMLInputElement && (element.type === 'radio' || element.type === 'checkbox');\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactChoices extends HTMLElement implements ChoicesElement {\n private upgraded = false;\n\n private observer?: MutationObserver;\n\n private stopWatchingChecked?: () => void;\n\n private readonly onClick = (event: Event) => {\n const input = event.target;\n if (!isChoice(input) || !this.owns(input)) return;\n if (input.type === 'radio') {\n // Checking a radio unchecks another, with no event for it, maybe in another group.\n this.syncAll();\n return;\n }\n this.syncInput(input);\n if (!input.checked) return;\n const exclusive = input.hasAttribute('data-choices-exclusive');\n // As govuk-frontend: every checkbox with the name in the form, even in another group.\n const others = this.inputsNamed(input).filter(\n (other) =>\n other !== input &&\n other.type === 'checkbox' &&\n other.checked &&\n (exclusive || other.hasAttribute('data-choices-exclusive'))\n );\n // Unchecked once this click, and React's updates for it, are done, so each is its own event\n // that React sees.\n window.setTimeout(() => {\n others\n .filter((other) => other.checked)\n .forEach((other) => {\n // A disabled checkbox ignores `click()`.\n if (other.disabled) other.checked = false;\n else other.click();\n });\n this.syncAll();\n });\n };\n\n // `reset` changes the choices with no event for each, after it fires.\n private readonly onReset = (event: Event) => {\n if (event.target instanceof HTMLFormElement && this.choices().some((input) => input.form === event.target)) {\n window.setTimeout(() => this.sync());\n }\n };\n\n private readonly onChange = (event: Event) => {\n if (isChoice(event.target) && this.owns(event.target)) this.sync();\n };\n\n // A page restored from the back-forward cache keeps its choices.\n private readonly onPageShow = () => this.sync();\n\n connectedCallback() {\n this.observer = new MutationObserver((records) => {\n if (records.some((record) => record.type === 'childList')) this.setup();\n else {\n // React can rewrite the element's own class.\n if (this.upgraded) this.addUpgradedClasses();\n this.sync();\n }\n });\n // Choices rendered later, and a class React rewrites.\n this.observer.observe(this, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] });\n this.addEventListener('click', this.onClick);\n this.addEventListener('change', this.onChange);\n window.addEventListener('pageshow', this.onPageShow);\n document.addEventListener('reset', this.onReset, true);\n this.stopWatchingChecked = onPropertyChange(\n () =>\n this.choices()\n .map((choice) => (choice.checked ? 1 : 0))\n .join(''),\n () => this.syncAll()\n );\n this.setup();\n }\n\n disconnectedCallback() {\n this.observer?.disconnect();\n this.removeEventListener('click', this.onClick);\n this.removeEventListener('change', this.onChange);\n window.removeEventListener('pageshow', this.onPageShow);\n document.removeEventListener('reset', this.onReset, true);\n this.stopWatchingChecked?.();\n }\n\n private get root() {\n const root = this.getRootNode();\n return root instanceof Document || root instanceof ShadowRoot ? root : document;\n }\n\n /** The inputs with the same name and form, anywhere on the page. */\n private inputsNamed(input: HTMLInputElement) {\n return Array.from(this.root.querySelectorAll('input')).filter(\n (other) => other.type === input.type && other.name === input.name && other.form === input.form\n );\n }\n\n /** Syncs every element on the page, for choices that changed in another group. */\n private syncAll() {\n Array.from(this.root.querySelectorAll(tagName)).forEach((element) => {\n if (element instanceof GovukReactChoices) element.sync();\n });\n }\n\n private owns(element: Element) {\n return element.closest(tagName) === this;\n }\n\n private choices() {\n return Array.from(this.querySelectorAll('input')).filter((input) => isChoice(input) && this.owns(input));\n }\n\n private target(input: HTMLInputElement) {\n const id = input.getAttribute('data-choices-controls');\n if (!id) return undefined;\n const root = this.getRootNode();\n const target = root instanceof Document || root instanceof ShadowRoot ? root.getElementById(id) : null;\n return target instanceof HTMLElement && target.hasAttribute('data-choices-conditional') ? target : undefined;\n }\n\n private setup() {\n const choices = this.choices();\n if (!choices.length) return;\n if (!this.upgraded) {\n this.upgraded = true;\n this.dataset.upgraded = '';\n this.addUpgradedClasses();\n }\n this.sync();\n }\n\n private addUpgradedClasses() {\n // `toggle` with force leaves a class that's already there alone, so the observer isn't woken.\n classesOf(this.getAttribute('upgraded-class')).forEach((name) => this.classList.toggle(name, true));\n }\n\n sync() {\n if (!this.upgraded) return;\n this.choices().forEach((input) => this.syncInput(input));\n }\n\n private syncInput(input: HTMLInputElement) {\n const target = this.target(input);\n if (!target) return;\n input.setAttribute('aria-controls', target.id);\n input.setAttribute('aria-expanded', String(input.checked));\n const hiddenClasses = classesOf(this.getAttribute('hidden-conditional-class'));\n // `toggle` with force leaves a class that's already there alone, so the observer isn't woken.\n if (hiddenClasses.length) hiddenClasses.forEach((name) => target.classList.toggle(name, !input.checked));\n else target.hidden = !input.checked;\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactChoices);\n}\n"]}
@@ -1,4 +1,7 @@
1
1
  declare global {
2
+ interface HTMLElementTagNameMap {
3
+ 'govuk-react-disclosure': DisclosureElement;
4
+ }
2
5
  interface HTMLElementEventMap {
3
6
  'govuk-react-disclosure:change': CustomEvent<{
4
7
  open: boolean;
@@ -7,7 +7,7 @@
7
7
  * `aria-expanded` is the state.
8
8
  *
9
9
  * Markup inside the element:
10
- * - `[data-disclosure-toggle]`: a `button` of type "button", rendered `hidden`.
10
+ * - `[data-disclosure-trigger]`: a `button` of type "button", rendered `hidden`.
11
11
  * - `[data-disclosure-content]`: the content, with an id for the button's `aria-controls`.
12
12
  *
13
13
  * Attributes:
@@ -17,8 +17,8 @@
17
17
  * fires the change event, and the content changes when `open` does.
18
18
  * - `default-open`: start with the content shown.
19
19
  *
20
- * A user's click fires a bubbling `govuk-react-disclosure:change` event with `{ open }`, for
21
- * code that doesn't use React.
20
+ * While upgraded it sets `data-upgraded`. A user's click fires a bubbling
21
+ * `govuk-react-disclosure:change` event with `{ open }`, for code that doesn't use React.
22
22
  */
23
23
  import { setUpWhenReady } from '../utils/set-up-when-ready.js';
24
24
  export const tagName = 'govuk-react-disclosure';
@@ -40,7 +40,7 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
40
40
  this.onModeChange = () => this.render();
41
41
  }
42
42
  static get observedAttributes() {
43
- return ['open'];
43
+ return ['open', 'media'];
44
44
  }
45
45
  get expanded() {
46
46
  return this.toggle ? this.isOpen : undefined;
@@ -60,7 +60,12 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
60
60
  this.content = undefined;
61
61
  this.mql = undefined;
62
62
  }
63
- attributeChangedCallback() {
63
+ attributeChangedCallback(name) {
64
+ if (name === 'media') {
65
+ if (this.toggle)
66
+ this.watchMedia();
67
+ return;
68
+ }
64
69
  const open = this.getAttribute('open');
65
70
  if (open === null)
66
71
  return;
@@ -74,7 +79,7 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
74
79
  setup() {
75
80
  if (this.toggle)
76
81
  return true;
77
- const toggle = this.own('[data-disclosure-toggle]', HTMLButtonElement);
82
+ const toggle = this.own('[data-disclosure-trigger]', HTMLButtonElement);
78
83
  const content = this.own('[data-disclosure-content]', HTMLElement);
79
84
  if (!toggle || !content)
80
85
  return false;
@@ -82,15 +87,19 @@ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined')
82
87
  this.content = content;
83
88
  const open = this.getAttribute('open');
84
89
  this.isOpen = open === null ? this.hasAttribute('default-open') : open === 'true';
85
- const media = this.getAttribute('media');
86
- if (media) {
87
- this.mql = window.matchMedia(media);
88
- this.mql.addEventListener('change', this.onModeChange);
89
- }
90
+ this.dataset.upgraded = '';
90
91
  toggle.addEventListener('click', this.onClick);
91
- this.render();
92
+ this.watchMedia();
92
93
  return true;
93
94
  }
95
+ watchMedia() {
96
+ var _a, _b;
97
+ (_a = this.mql) === null || _a === void 0 ? void 0 : _a.removeEventListener('change', this.onModeChange);
98
+ const media = this.getAttribute('media');
99
+ this.mql = media ? window.matchMedia(media) : undefined;
100
+ (_b = this.mql) === null || _b === void 0 ? void 0 : _b.addEventListener('change', this.onModeChange);
101
+ this.render();
102
+ }
94
103
  apply(open) {
95
104
  if (open === this.isOpen)
96
105
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/disclosure/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAQ/D,MAAM,CAAC,MAAM,OAAO,GAAG,wBAAwB,CAAC;AAShD,IAAI,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;IAChF,MAAM,oBAAqB,SAAQ,WAAW;QAA9C;;YAaU,WAAM,GAAG,KAAK,CAAC;YAIf,eAAU,GAAG,KAAK,CAAC;YAEV,YAAO,GAAG,GAAG,EAAE;gBAC9B,MAAM,IAAI,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC;gBAC1B,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;oBAC/B,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;oBACjB,IAAI,CAAC,IAAI,CAAC,UAAU;wBAAE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;gBAC3C,CAAC;gBACD,IAAI,CAAC,aAAa,CAAC,IAAI,WAAW,CAAC,+BAA+B,EAAE,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;YAC5G,CAAC,CAAC;YAEe,iBAAY,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;QA4EtD,CAAC;QAvGC,MAAM,KAAK,kBAAkB;YAC3B,OAAO,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC;QA2BD,IAAI,QAAQ;Y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AEO,MAAM;;YACZ,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;YACjC,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO;gBAAE,OAAO;YAChC,IAAI,MAAA,IAAI,CAAC,GAAG,0CAAE,OAAO,EAAE,CAAC;gBACtB,OAAO,CAAC,MAAM,GAAG,KAAK,CAAC;gBACvB,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;gBACrB,MAAM,CAAC,YAAY,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;gBAC3C,MAAM,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;gBACxC,OAAO;YACT,CAAC;YACD,MAAM,CAAC,MAAM,GAAG,KAAK,CAAC;YACtB,MAAM,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;YACtC,MAAM,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;YAC1D,IAAI,OAAO,CAAC,EAAE;gBAAE,MAAM,CAAC,YAAY,CAAC,eAAe,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;YACjE,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC;QAChC,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;AACzF,CAAC","sourcesContent":["/*\n * <govuk-react-disclosure>: a headless, light-DOM custom element that adds a show and hide\n * button to some content, such as a navigation menu on small screens, with or without React.\n *\n * Without JavaScript the content is shown and the button stays hidden. On upgrade the element\n * shows the button and hides the content, and the button shows and hides it. The button's\n * `aria-expanded` is the state.\n *\n * Markup inside the element:\n * - `[data-disclosure-toggle]`: a `button` of type \"button\", rendered `hidden`.\n * - `[data-disclosure-content]`: the content, with an id for the button's `aria-controls`.\n *\n * Attributes:\n * - `media`: while this media query matches, the content is always shown and the button hidden,\n * with `aria-hidden`, as in govuk-frontend's service navigation.\n * - `open`: controls the content. \"true\" shows it, anything else hides it. A user's click only\n * fires the change event, and the content changes when `open` does.\n * - `default-open`: start with the content shown.\n *\n * A user's click fires a bubbling `govuk-react-disclosure:change` event with `{ open }`, for\n * code that doesn't use React.\n */\n\nimport { setUpWhenReady } from '../utils/set-up-when-ready.js';\n\ndeclare global {\n interface HTMLElementEventMap {\n 'govuk-react-disclosure:change': CustomEvent<{ open: boolean }>;\n }\n}\n\nexport const tagName = 'govuk-react-disclosure';\n\nexport interface DisclosureElement extends HTMLElement {\n /** Whether the content is open, once upgraded, even while `media` shows it anyway. */\n readonly expanded: boolean | undefined;\n /** The user's last choice before `open` was first set, such as before React hydrated. */\n readonly pickedOpen: boolean | undefined;\n}\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactDisclosure extends HTMLElement implements DisclosureElement {\n static get observedAttributes() {\n return ['open'];\n }\n\n private toggle?: HTMLButtonElement;\n\n private content?: HTMLElement;\n\n private mql?: MediaQueryList;\n\n private observer?: MutationObserver;\n\n private isOpen = false;\n\n private picked?: boolean;\n\n private controlled = false;\n\n private readonly onClick = () => {\n const open = !this.isOpen;\n if (!this.hasAttribute('open')) {\n this.apply(open);\n if (!this.controlled) this.picked = open;\n }\n this.dispatchEvent(new CustomEvent('govuk-react-disclosure:change', { detail: { open }, bubbles: true }));\n };\n\n private readonly onModeChange = () => this.render();\n\n get expanded() {\n return this.toggle ? this.isOpen : undefined;\n }\n\n get pickedOpen() {\n return this.picked;\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.onClick);\n this.mql?.removeEventListener('change', this.onModeChange);\n this.toggle = undefined;\n this.content = undefined;\n this.mql = undefined;\n }\n\n attributeChangedCallback() {\n const open = this.getAttribute('open');\n if (open === null) return;\n this.controlled = true;\n this.apply(open === 'true');\n }\n\n private own<E extends Element>(selector: string, type: new () => E): E | undefined {\n const element = Array.from(this.querySelectorAll(selector)).find((found) => found.closest(tagName) === this);\n return element instanceof type ? element : undefined;\n }\n\n private setup() {\n if (this.toggle) return true;\n const toggle = this.own('[data-disclosure-toggle]', HTMLButtonElement);\n const content = this.own('[data-disclosure-content]', HTMLElement);\n if (!toggle || !content) return false;\n this.toggle = toggle;\n this.content = content;\n const open = this.getAttribute('open');\n this.isOpen = open === null ? this.hasAttribute('default-open') : open === 'true';\n const media = this.getAttribute('media');\n if (media) {\n this.mql = window.matchMedia(media);\n this.mql.addEventListener('change', this.onModeChange);\n }\n toggle.addEventListener('click', this.onClick);\n this.render();\n return true;\n }\n\n private apply(open: boolean) {\n if (open === this.isOpen) return;\n this.isOpen = open;\n this.render();\n }\n\n private render() {\n const { toggle, content } = this;\n if (!toggle || !content) return;\n if (this.mql?.matches) {\n content.hidden = false;\n toggle.hidden = true;\n toggle.setAttribute('aria-hidden', 'true');\n toggle.removeAttribute('aria-expanded');\n return;\n }\n toggle.hidden = false;\n toggle.removeAttribute('aria-hidden');\n toggle.setAttribute('aria-expanded', String(this.isOpen));\n if (content.id) toggle.setAttribute('aria-controls', content.id);\n content.hidden = !this.isOpen;\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactDisclosure);\n}\n"]}
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/disclosure/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAW/D,MAAM,CAAC,MAAM,OAAO,GAAG,wBAAwB,CAAC;AAShD,IAAI,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;IAChF,MAAM,oBAAqB,SAAQ,WAAW;QAA9C;;YAaU,WAAM,GAAG,KAAK,CAAC;YAIf,eAAU,GAAG,KAAK,CAAC;YAEV,YAAO,GAAG,GAA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,KAAK,CAAC;gBACvB,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;gBACrB,MAAM,CAAC,YAAY,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;gBAC3C,MAAM,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;gBACxC,OAAO;YACT,CAAC;YACD,MAAM,CAAC,MAAM,GAAG,KAAK,CAAC;YACtB,MAAM,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;YACtC,MAAM,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;YAC1D,IAAI,OAAO,CAAC,EAAE;gBAAE,MAAM,CAAC,YAAY,CAAC,eAAe,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;YACjE,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC;QAChC,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,oBAAoB,CAAC,CAAC;AACzF,CAAC","sourcesContent":["/*\n * <govuk-react-disclosure>: a headless, light-DOM custom element that adds a show and hide\n * button to some content, such as a navigation menu on small screens, with or without React.\n *\n * Without JavaScript the content is shown and the button stays hidden. On upgrade the element\n * shows the button and hides the content, and the button shows and hides it. The button's\n * `aria-expanded` is the state.\n *\n * Markup inside the element:\n * - `[data-disclosure-trigger]`: a `button` of type \"button\", rendered `hidden`.\n * - `[data-disclosure-content]`: the content, with an id for the button's `aria-controls`.\n *\n * Attributes:\n * - `media`: while this media query matches, the content is always shown and the button hidden,\n * with `aria-hidden`, as in govuk-frontend's service navigation.\n * - `open`: controls the content. \"true\" shows it, anything else hides it. A user's click only\n * fires the change event, and the content changes when `open` does.\n * - `default-open`: start with the content shown.\n *\n * While upgraded it sets `data-upgraded`. A user's click fires a bubbling\n * `govuk-react-disclosure:change` event with `{ open }`, for code that doesn't use React.\n */\n\nimport { setUpWhenReady } from '../utils/set-up-when-ready.js';\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'govuk-react-disclosure': DisclosureElement;\n }\n interface HTMLElementEventMap {\n 'govuk-react-disclosure:change': CustomEvent<{ open: boolean }>;\n }\n}\n\nexport const tagName = 'govuk-react-disclosure';\n\nexport interface DisclosureElement extends HTMLElement {\n /** Whether the content is open, once upgraded, even while `media` shows it anyway. */\n readonly expanded: boolean | undefined;\n /** The user's last choice before `open` was first set, such as before React hydrated. */\n readonly pickedOpen: boolean | undefined;\n}\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactDisclosure extends HTMLElement implements DisclosureElement {\n static get observedAttributes() {\n return ['open', 'media'];\n }\n\n private toggle?: HTMLButtonElement;\n\n private content?: HTMLElement;\n\n private mql?: MediaQueryList;\n\n private observer?: MutationObserver;\n\n private isOpen = false;\n\n private picked?: boolean;\n\n private controlled = false;\n\n private readonly onClick = () => {\n const open = !this.isOpen;\n if (!this.hasAttribute('open')) {\n this.apply(open);\n if (!this.controlled) this.picked = open;\n }\n this.dispatchEvent(new CustomEvent('govuk-react-disclosure:change', { detail: { open }, bubbles: true }));\n };\n\n private readonly onModeChange = () => this.render();\n\n get expanded() {\n return this.toggle ? this.isOpen : undefined;\n }\n\n get pickedOpen() {\n return this.picked;\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.onClick);\n this.mql?.removeEventListener('change', this.onModeChange);\n this.toggle = undefined;\n this.content = undefined;\n this.mql = undefined;\n }\n\n attributeChangedCallback(name: string) {\n if (name === 'media') {\n if (this.toggle) this.watchMedia();\n return;\n }\n const open = this.getAttribute('open');\n if (open === null) return;\n this.controlled = true;\n this.apply(open === 'true');\n }\n\n private own<E extends Element>(selector: string, type: new () => E): E | undefined {\n const element = Array.from(this.querySelectorAll(selector)).find((found) => found.closest(tagName) === this);\n return element instanceof type ? element : undefined;\n }\n\n private setup() {\n if (this.toggle) return true;\n const toggle = this.own('[data-disclosure-trigger]', HTMLButtonElement);\n const content = this.own('[data-disclosure-content]', HTMLElement);\n if (!toggle || !content) return false;\n this.toggle = toggle;\n this.content = content;\n const open = this.getAttribute('open');\n this.isOpen = open === null ? this.hasAttribute('default-open') : open === 'true';\n this.dataset.upgraded = '';\n toggle.addEventListener('click', this.onClick);\n this.watchMedia();\n return true;\n }\n\n private watchMedia() {\n this.mql?.removeEventListener('change', this.onModeChange);\n const media = this.getAttribute('media');\n this.mql = media ? window.matchMedia(media) : undefined;\n this.mql?.addEventListener('change', this.onModeChange);\n this.render();\n }\n\n private apply(open: boolean) {\n if (open === this.isOpen) return;\n this.isOpen = open;\n this.render();\n }\n\n private render() {\n const { toggle, content } = this;\n if (!toggle || !content) return;\n if (this.mql?.matches) {\n content.hidden = false;\n toggle.hidden = true;\n toggle.setAttribute('aria-hidden', 'true');\n toggle.removeAttribute('aria-expanded');\n return;\n }\n toggle.hidden = false;\n toggle.removeAttribute('aria-hidden');\n toggle.setAttribute('aria-expanded', String(this.isOpen));\n if (content.id) toggle.setAttribute('aria-controls', content.id);\n content.hidden = !this.isOpen;\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactDisclosure);\n}\n"]}
@@ -1,5 +1,7 @@
1
1
  import * as React from 'react';
2
2
  import type { ComponentProps } 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
  /** While this media query matches, the content is always shown and the button hidden. */
5
7
  media?: string;
@@ -8,10 +10,11 @@ export type RootProps = Omit<React.HTMLAttributes<HTMLElement>, 'onChange'> & {
8
10
  /** Whether the content starts shown once the element upgrades. */
9
11
  defaultOpen?: boolean;
10
12
  /** Called when the user shows or hides the content. */
11
- onOpenChange?: (open: boolean) => void;
13
+ onOpenChange?: (open: boolean, details: ChangeDetails) => void;
12
14
  };
13
15
  export declare function Root({ media, open, defaultOpen, onOpenChange, ...props }: RootProps): React.DOMElement<{
14
16
  ref: React.RefObject<HTMLElement>;
17
+ suppressHydrationWarning: boolean;
15
18
  media: string;
16
19
  'default-open': string;
17
20
  children?: React.ReactNode;
@@ -27,7 +30,6 @@ export declare function Root({ media, open, defaultOpen, onOpenChange, ...props
27
30
  defaultValue?: string | number | readonly string[];
28
31
  defaultChecked?: boolean;
29
32
  suppressContentEditableWarning?: boolean;
30
- suppressHydrationWarning?: boolean;
31
33
  accessKey?: string;
32
34
  autoCapitalize?: "off" | "none" | "on" | "sentences" | "words" | "characters" | (string & {});
33
35
  autoFocus?: boolean;
@@ -298,10 +300,9 @@ type PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E>
298
300
  /** Render the only child instead, with this part's props merged onto it. */
299
301
  asChild?: boolean;
300
302
  };
301
- export type ToggleProps = PartProps<'button'>;
303
+ export type TriggerProps = PartProps<'button'>;
302
304
  /** The show and hide button. Hidden until the element upgrades. */
303
- export declare function Toggle({ asChild, ...props }: ToggleProps): React.JSX.Element;
305
+ export declare function Trigger({ asChild, ...props }: TriggerProps): React.JSX.Element;
304
306
  export type ContentProps = PartProps<'div'>;
305
307
  /** The content the button shows and hides. Give it an id for the button's `aria-controls`. */
306
308
  export declare function Content({ asChild, ...props }: ContentProps): React.JSX.Element;
307
- export {};
@@ -1,6 +1,7 @@
1
1
  'use client';
2
2
  import * as React from 'react';
3
- import { useEffect, useRef } from 'react';
3
+ import { useEffect, useReducer, useRef } from 'react';
4
+ import { early, live } from '../utils/change-details.js';
4
5
  import { Slot } from '../utils/slot.js';
5
6
  import { tagName } from './element.js';
6
7
  const isDisclosure = (element) => 'pickedOpen' in element;
@@ -8,6 +9,7 @@ export function Root({ media, open, defaultOpen, onOpenChange, ...props }) {
8
9
  const element = useRef(null);
9
10
  const onOpenChangeRef = useRef(onOpenChange);
10
11
  const synced = useRef(false);
12
+ const [, render] = useReducer((count) => count + 1, 0);
11
13
  useEffect(() => {
12
14
  onOpenChangeRef.current = onOpenChange;
13
15
  });
@@ -19,7 +21,7 @@ export function Root({ media, open, defaultOpen, onOpenChange, ...props }) {
19
21
  const onChange = (event) => {
20
22
  var _a;
21
23
  if (event.target === node)
22
- (_a = onOpenChangeRef.current) === null || _a === void 0 ? void 0 : _a.call(onOpenChangeRef, event.detail.open);
24
+ (_a = onOpenChangeRef.current) === null || _a === void 0 ? void 0 : _a.call(onOpenChangeRef, event.detail.open, live);
23
25
  };
24
26
  node.addEventListener('govuk-react-disclosure:change', onChange);
25
27
  return () => node.removeEventListener('govuk-react-disclosure:change', onChange);
@@ -27,32 +29,40 @@ export function Root({ media, open, defaultOpen, onOpenChange, ...props }) {
27
29
  // `open` is set once hydrated, so the server markup is uncontrolled and a user's click before
28
30
  // hydration still works. That click is then reported, rather than undone.
29
31
  useEffect(() => {
32
+ var _a;
30
33
  const node = element.current;
31
- if (!node || open === undefined) {
32
- node === null || node === void 0 ? void 0 : node.removeAttribute('open');
34
+ if (!node)
33
35
  return;
34
- }
35
36
  if (!synced.current) {
36
37
  synced.current = true;
37
38
  const picked = isDisclosure(node) ? node.pickedOpen : undefined;
38
- if (picked !== undefined && picked !== open && onOpenChangeRef.current) {
39
- onOpenChangeRef.current(picked);
40
- return;
39
+ if (picked !== undefined && picked !== ((_a = open !== null && open !== void 0 ? open : defaultOpen) !== null && _a !== void 0 ? _a : false) && onOpenChangeRef.current) {
40
+ onOpenChangeRef.current(picked, early);
41
+ if (open !== undefined) {
42
+ // The click shows until the next render, which adopts it or goes back to `open`.
43
+ render();
44
+ return;
45
+ }
41
46
  }
42
47
  }
43
- node.setAttribute('open', String(open));
48
+ if (open === undefined)
49
+ node.removeAttribute('open');
50
+ else
51
+ node.setAttribute('open', String(open));
44
52
  });
45
53
  return React.createElement(tagName, {
46
54
  ...props,
47
55
  ref: element,
56
+ // The element owns `data-upgraded`.
57
+ suppressHydrationWarning: true,
48
58
  media,
49
59
  'default-open': defaultOpen ? '' : undefined,
50
60
  });
51
61
  }
52
62
  /** The show and hide button. Hidden until the element upgrades. */
53
- export function Toggle({ asChild, ...props }) {
63
+ export function Trigger({ asChild, ...props }) {
54
64
  // The element owns `hidden`, `aria-hidden` and `aria-expanded` after upgrade.
55
- const shared = { 'data-disclosure-toggle': '', hidden: true, suppressHydrationWarning: true };
65
+ const shared = { 'data-disclosure-trigger': '', hidden: true, suppressHydrationWarning: true };
56
66
  if (asChild)
57
67
  return React.createElement(Slot, { ...shared, ...props });
58
68
  return React.createElement("button", { type: "button", ...shared, ...props });