@govuk-react/primitives 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/README.md +100 -25
  2. package/dist/{accordion-element.d.ts → accordion/element.d.ts} +5 -5
  3. package/dist/accordion/element.js +302 -0
  4. package/dist/accordion/element.js.map +1 -0
  5. package/dist/accordion/index.d.ts +70 -0
  6. package/dist/accordion/index.js +140 -0
  7. package/dist/accordion/index.js.map +1 -0
  8. package/dist/auto-focus/element.d.ts +1 -0
  9. package/dist/auto-focus/element.js +75 -0
  10. package/dist/auto-focus/element.js.map +1 -0
  11. package/dist/auto-focus/index.d.ts +15 -0
  12. package/dist/auto-focus/index.js +39 -0
  13. package/dist/auto-focus/index.js.map +1 -0
  14. package/dist/{autocomplete-element.d.ts → autocomplete/element.d.ts} +11 -11
  15. package/dist/autocomplete/element.js +597 -0
  16. package/dist/autocomplete/element.js.map +1 -0
  17. package/dist/{index-D7lMYMUR.d.ts → autocomplete/index.d.ts} +39 -62
  18. package/dist/autocomplete/index.js +100 -0
  19. package/dist/autocomplete/index.js.map +1 -0
  20. package/dist/button/element.d.ts +1 -0
  21. package/dist/button/element.js +59 -0
  22. package/dist/button/element.js.map +1 -0
  23. package/dist/button/index.d.ts +10 -0
  24. package/dist/button/index.js +9 -0
  25. package/dist/button/index.js.map +1 -0
  26. package/dist/character-count/element.d.ts +12 -0
  27. package/dist/character-count/element.js +287 -0
  28. package/dist/character-count/element.js.map +1 -0
  29. package/dist/character-count/index.d.ts +57 -0
  30. package/dist/character-count/index.js +79 -0
  31. package/dist/character-count/index.js.map +1 -0
  32. package/dist/character-count/messages.d.ts +20 -0
  33. package/dist/character-count/messages.js +54 -0
  34. package/dist/character-count/messages.js.map +1 -0
  35. package/dist/choices/element.d.ts +10 -0
  36. package/dist/choices/element.js +177 -0
  37. package/dist/choices/element.js.map +1 -0
  38. package/dist/{index-WuGvkTxu.d.ts → choices/index.d.ts} +30 -44
  39. package/dist/choices/index.js +37 -0
  40. package/dist/choices/index.js.map +1 -0
  41. package/dist/{disclosure-element.d.ts → disclosure/element.d.ts} +5 -5
  42. package/dist/disclosure/element.js +132 -0
  43. package/dist/disclosure/element.js.map +1 -0
  44. package/dist/{index-D4Gzyvfu.d.ts → disclosure/index.d.ts} +43 -56
  45. package/dist/disclosure/index.js +76 -0
  46. package/dist/disclosure/index.js.map +1 -0
  47. package/dist/exit-this-page/element.d.ts +19 -0
  48. package/dist/exit-this-page/element.js +200 -0
  49. package/dist/exit-this-page/element.js.map +1 -0
  50. package/dist/{index-qF0jIQCW.d.ts → exit-this-page/index.d.ts} +44 -68
  51. package/dist/exit-this-page/index.js +54 -0
  52. package/dist/exit-this-page/index.js.map +1 -0
  53. package/dist/file-upload/element.d.ts +28 -0
  54. package/dist/file-upload/element.js +270 -0
  55. package/dist/file-upload/element.js.map +1 -0
  56. package/dist/file-upload/index.d.ts +46 -0
  57. package/dist/file-upload/index.js +65 -0
  58. package/dist/file-upload/index.js.map +1 -0
  59. package/dist/focus-links/element.d.ts +1 -0
  60. package/dist/focus-links/element.js +90 -0
  61. package/dist/focus-links/element.js.map +1 -0
  62. package/dist/{index-BR3MAGF8.d.ts → focus-links/index.d.ts} +24 -35
  63. package/dist/focus-links/index.js +7 -0
  64. package/dist/focus-links/index.js.map +1 -0
  65. package/dist/index.d.ts +13 -17
  66. package/dist/index.js +13 -72
  67. package/dist/index.js.map +1 -1
  68. package/dist/inline/accordion-element.js +1 -1
  69. package/dist/inline/auto-focus-element.js +1 -1
  70. package/dist/inline/autocomplete-element.js +1 -1
  71. package/dist/inline/character-count-element.js +1 -1
  72. package/dist/inline/choices-element.js +1 -1
  73. package/dist/inline/disclosure-element.js +1 -1
  74. package/dist/inline/exit-this-page-element.js +1 -1
  75. package/dist/inline/file-upload-element.js +1 -1
  76. package/dist/inline/focus-links-element.js +1 -1
  77. package/dist/inline/modal-element.js +1 -1
  78. package/dist/inline/password-input-element.js +1 -1
  79. package/dist/inline/tabs-element.js +1 -1
  80. package/dist/inline-script/index.d.ts +26 -0
  81. package/dist/inline-script/index.js +31 -0
  82. package/dist/inline-script/index.js.map +1 -0
  83. package/dist/{modal-element.d.ts → modal/element.d.ts} +2 -4
  84. package/dist/modal/element.js +229 -0
  85. package/dist/modal/element.js.map +1 -0
  86. package/dist/modal/index.d.ts +41 -0
  87. package/dist/modal/index.js +145 -0
  88. package/dist/modal/index.js.map +1 -0
  89. package/dist/password-input/element.d.ts +1 -0
  90. package/dist/password-input/element.js +150 -0
  91. package/dist/password-input/element.js.map +1 -0
  92. package/dist/{index-sEHnx4-M.d.ts → password-input/index.d.ts} +33 -49
  93. package/dist/password-input/index.js +37 -0
  94. package/dist/password-input/index.js.map +1 -0
  95. package/dist/styles.css +11 -0
  96. package/dist/{tabs-element.d.ts → tabs/element.d.ts} +5 -5
  97. package/dist/tabs/element.js +423 -0
  98. package/dist/tabs/element.js.map +1 -0
  99. package/dist/tabs/index.d.ts +74 -0
  100. package/dist/tabs/index.js +142 -0
  101. package/dist/tabs/index.js.map +1 -0
  102. package/dist/utils/change-details.d.ts +11 -0
  103. package/dist/utils/change-details.js +3 -0
  104. package/dist/utils/change-details.js.map +1 -0
  105. package/dist/utils/dom.d.ts +9 -0
  106. package/dist/utils/dom.js +27 -0
  107. package/dist/utils/dom.js.map +1 -0
  108. package/dist/utils/on-property-change.d.ts +7 -0
  109. package/dist/utils/on-property-change.js +19 -0
  110. package/dist/utils/on-property-change.js.map +1 -0
  111. package/dist/utils/set-focus.d.ts +11 -0
  112. package/dist/utils/set-focus.js +38 -0
  113. package/dist/utils/set-focus.js.map +1 -0
  114. package/dist/utils/set-up-when-ready.d.ts +6 -0
  115. package/dist/utils/set-up-when-ready.js +16 -0
  116. package/dist/utils/set-up-when-ready.js.map +1 -0
  117. package/dist/utils/slot.d.ts +15 -0
  118. package/dist/utils/slot.js +62 -0
  119. package/dist/utils/slot.js.map +1 -0
  120. package/dist/utils/translation.d.ts +13 -0
  121. package/dist/utils/translation.js +57 -0
  122. package/dist/utils/translation.js.map +1 -0
  123. package/package.json +17 -4
  124. package/dist/accordion-element.js +0 -9
  125. package/dist/accordion-element.js.map +0 -1
  126. package/dist/accordion.d.ts +0 -2
  127. package/dist/accordion.js +0 -34
  128. package/dist/accordion.js.map +0 -1
  129. package/dist/auto-focus-element.d.ts +0 -3
  130. package/dist/auto-focus-element.js +0 -10
  131. package/dist/auto-focus-element.js.map +0 -1
  132. package/dist/auto-focus.d.ts +0 -2
  133. package/dist/auto-focus.js +0 -15
  134. package/dist/auto-focus.js.map +0 -1
  135. package/dist/autocomplete-element.js +0 -12
  136. package/dist/autocomplete-element.js.map +0 -1
  137. package/dist/autocomplete.d.ts +0 -4
  138. package/dist/autocomplete.js +0 -25
  139. package/dist/autocomplete.js.map +0 -1
  140. package/dist/button-element.d.ts +0 -2
  141. package/dist/button-element.js +0 -3
  142. package/dist/button-element.js.map +0 -1
  143. package/dist/button.d.ts +0 -2
  144. package/dist/button.js +0 -12
  145. package/dist/button.js.map +0 -1
  146. package/dist/character-count-element.d.ts +0 -10
  147. package/dist/character-count-element.js +0 -10
  148. package/dist/character-count-element.js.map +0 -1
  149. package/dist/character-count.d.ts +0 -3
  150. package/dist/character-count.js +0 -26
  151. package/dist/character-count.js.map +0 -1
  152. package/dist/choices-element.d.ts +0 -8
  153. package/dist/choices-element.js +0 -9
  154. package/dist/choices-element.js.map +0 -1
  155. package/dist/choices.d.ts +0 -2
  156. package/dist/choices.js +0 -16
  157. package/dist/choices.js.map +0 -1
  158. package/dist/chunk-2IHAQAYF.js +0 -23
  159. package/dist/chunk-2IHAQAYF.js.map +0 -1
  160. package/dist/chunk-2ZJVSNC2.js +0 -31
  161. package/dist/chunk-2ZJVSNC2.js.map +0 -1
  162. package/dist/chunk-47NMY4SS.js +0 -108
  163. package/dist/chunk-47NMY4SS.js.map +0 -1
  164. package/dist/chunk-4XAR4FFG.js +0 -83
  165. package/dist/chunk-4XAR4FFG.js.map +0 -1
  166. package/dist/chunk-5HWRMQK2.js +0 -91
  167. package/dist/chunk-5HWRMQK2.js.map +0 -1
  168. package/dist/chunk-6ZFU4VYW.js +0 -41
  169. package/dist/chunk-6ZFU4VYW.js.map +0 -1
  170. package/dist/chunk-B2I4J5NL.js +0 -264
  171. package/dist/chunk-B2I4J5NL.js.map +0 -1
  172. package/dist/chunk-DPERPCUH.js +0 -188
  173. package/dist/chunk-DPERPCUH.js.map +0 -1
  174. package/dist/chunk-ECYGKE4D.js +0 -168
  175. package/dist/chunk-ECYGKE4D.js.map +0 -1
  176. package/dist/chunk-ESBMTI25.js +0 -11
  177. package/dist/chunk-ESBMTI25.js.map +0 -1
  178. package/dist/chunk-ET7DCQM7.js +0 -133
  179. package/dist/chunk-ET7DCQM7.js.map +0 -1
  180. package/dist/chunk-F5XFC4QJ.js +0 -177
  181. package/dist/chunk-F5XFC4QJ.js.map +0 -1
  182. package/dist/chunk-GVGBDSDN.js +0 -78
  183. package/dist/chunk-GVGBDSDN.js.map +0 -1
  184. package/dist/chunk-IZQ2C4BC.js +0 -351
  185. package/dist/chunk-IZQ2C4BC.js.map +0 -1
  186. package/dist/chunk-L7E6GN2D.js +0 -87
  187. package/dist/chunk-L7E6GN2D.js.map +0 -1
  188. package/dist/chunk-LWIA644X.js +0 -34
  189. package/dist/chunk-LWIA644X.js.map +0 -1
  190. package/dist/chunk-NX4B3NKM.js +0 -35
  191. package/dist/chunk-NX4B3NKM.js.map +0 -1
  192. package/dist/chunk-PNWPGD7B.js +0 -68
  193. package/dist/chunk-PNWPGD7B.js.map +0 -1
  194. package/dist/chunk-QLQ6O7OW.js +0 -111
  195. package/dist/chunk-QLQ6O7OW.js.map +0 -1
  196. package/dist/chunk-RDUPELOK.js +0 -55
  197. package/dist/chunk-RDUPELOK.js.map +0 -1
  198. package/dist/chunk-RPMHI67T.js +0 -104
  199. package/dist/chunk-RPMHI67T.js.map +0 -1
  200. package/dist/chunk-TE4RUYVK.js +0 -97
  201. package/dist/chunk-TE4RUYVK.js.map +0 -1
  202. package/dist/chunk-TJVBFRIE.js +0 -60
  203. package/dist/chunk-TJVBFRIE.js.map +0 -1
  204. package/dist/chunk-U5OKNKYC.js +0 -510
  205. package/dist/chunk-U5OKNKYC.js.map +0 -1
  206. package/dist/chunk-UXJO4AJP.js +0 -290
  207. package/dist/chunk-UXJO4AJP.js.map +0 -1
  208. package/dist/chunk-VNXXENCU.js +0 -39
  209. package/dist/chunk-VNXXENCU.js.map +0 -1
  210. package/dist/chunk-XGK73UCD.js +0 -62
  211. package/dist/chunk-XGK73UCD.js.map +0 -1
  212. package/dist/chunk-XJYLFTYE.js +0 -157
  213. package/dist/chunk-XJYLFTYE.js.map +0 -1
  214. package/dist/chunk-YCESNTXQ.js +0 -241
  215. package/dist/chunk-YCESNTXQ.js.map +0 -1
  216. package/dist/chunk-ZTJLVNR4.js +0 -62
  217. package/dist/chunk-ZTJLVNR4.js.map +0 -1
  218. package/dist/disclosure-element.js +0 -9
  219. package/dist/disclosure-element.js.map +0 -1
  220. package/dist/disclosure.d.ts +0 -2
  221. package/dist/disclosure.js +0 -16
  222. package/dist/disclosure.js.map +0 -1
  223. package/dist/exit-this-page-element.d.ts +0 -22
  224. package/dist/exit-this-page-element.js +0 -13
  225. package/dist/exit-this-page-element.js.map +0 -1
  226. package/dist/exit-this-page.d.ts +0 -3
  227. package/dist/exit-this-page.js +0 -25
  228. package/dist/exit-this-page.js.map +0 -1
  229. package/dist/file-upload-element.d.ts +0 -27
  230. package/dist/file-upload-element.js +0 -14
  231. package/dist/file-upload-element.js.map +0 -1
  232. package/dist/file-upload.d.ts +0 -3
  233. package/dist/file-upload.js +0 -25
  234. package/dist/file-upload.js.map +0 -1
  235. package/dist/focus-links-element.d.ts +0 -3
  236. package/dist/focus-links-element.js +0 -10
  237. package/dist/focus-links-element.js.map +0 -1
  238. package/dist/focus-links.d.ts +0 -2
  239. package/dist/focus-links.js +0 -12
  240. package/dist/focus-links.js.map +0 -1
  241. package/dist/index--FxJgSOS.d.ts +0 -108
  242. package/dist/index-Bul0NJh_.d.ts +0 -310
  243. package/dist/index-CikOyFud.d.ts +0 -54
  244. package/dist/index-D8N5vxTL.d.ts +0 -90
  245. package/dist/index-DMWpkC_d.d.ts +0 -105
  246. package/dist/index-DN7fGMc3.d.ts +0 -20
  247. package/dist/index-DPXR1Yua.d.ts +0 -69
  248. package/dist/inline-script.d.ts +0 -29
  249. package/dist/inline-script.js +0 -63
  250. package/dist/inline-script.js.map +0 -1
  251. package/dist/modal-element.js +0 -11
  252. package/dist/modal-element.js.map +0 -1
  253. package/dist/modal.d.ts +0 -2
  254. package/dist/modal.js +0 -20
  255. package/dist/modal.js.map +0 -1
  256. package/dist/password-input-element.d.ts +0 -3
  257. package/dist/password-input-element.js +0 -9
  258. package/dist/password-input-element.js.map +0 -1
  259. package/dist/password-input.d.ts +0 -2
  260. package/dist/password-input.js +0 -18
  261. package/dist/password-input.js.map +0 -1
  262. package/dist/tabs-element.js +0 -9
  263. package/dist/tabs-element.js.map +0 -1
  264. package/dist/tabs.d.ts +0 -2
  265. package/dist/tabs.js +0 -28
  266. package/dist/tabs.js.map +0 -1
  267. package/dist/translation-BnpO2mN2.d.ts +0 -4
@@ -0,0 +1,287 @@
1
+ /*
2
+ * <govuk-react-character-count>: a headless, light-DOM custom element that tells users how many
3
+ * characters or words they can still enter, with or without React.
4
+ *
5
+ * Without JavaScript the field shows its description, such as "You can enter up to 200
6
+ * characters". On upgrade the element visually hides the description, shows the count, and keeps
7
+ * it up to date as the user types. As in govuk-frontend, screen readers hear the count once the
8
+ * user pauses, rather than on every key.
9
+ *
10
+ * Markup inside the element:
11
+ * - `[data-character-count-input]`: a `textarea` or `input`. Its `maxlength` is removed on
12
+ * upgrade, so users can type past the limit and see by how much.
13
+ * - `[data-character-count-description]`: the description, for `aria-describedby`.
14
+ * - `[data-character-count-status]`: the visible count, rendered `hidden` with `aria-hidden`.
15
+ * - `[data-character-count-sr-status]`: the count for screen readers, rendered `hidden` with
16
+ * `aria-live="polite"`. Make it visually hidden.
17
+ *
18
+ * The statuses get `data-state`, "under", "at" or "over" the limit. The visible one gets
19
+ * `data-below-threshold` while the count is below `threshold`, and the one for screen readers gets
20
+ * `aria-hidden` then.
21
+ *
22
+ * Attributes:
23
+ * - `maxlength`: the limit. Without it, the element doesn't upgrade.
24
+ * - `count-type`: "length" (the default) counts UTF-16 code units, as `maxlength` does;
25
+ * "characters" counts characters as users see them; "words" counts words.
26
+ * - `threshold`: the percentage of the limit from which the count is shown.
27
+ * - `characters-under-limit-text`, `characters-at-limit-text`, `characters-over-limit-text`, `words-under-limit-text`,
28
+ * `words-at-limit-text`, `words-over-limit-text`: the messages, English by default, with `%{count}` for
29
+ * the number. Add a plural form to the name, such as `characters-under-limit-text-one`, for a
30
+ * message for each form.
31
+ * - `hidden-description-class`: classes that visually hide the description. Without them, the
32
+ * element visually hides it with inline styles.
33
+ * - `within-limit-class`, `over-limit-class`, `below-threshold-class`: classes for the visible
34
+ * count.
35
+ * - `input-over-limit-class`: classes for the field while over the limit.
36
+ */
37
+ import { onPropertyChange } from '../utils/on-property-change.js';
38
+ import { translationAttributeNames } from '../utils/translation.js';
39
+ import { countMessage, countOf, messageFromAttributes, messageNames } from './messages.js';
40
+ import { classesOf, setText } from '../utils/dom.js';
41
+ export const tagName = 'govuk-react-character-count';
42
+ // The same visually hidden styles as govuk-frontend's.
43
+ const visuallyHidden = {
44
+ position: 'absolute',
45
+ width: '1px',
46
+ height: '1px',
47
+ margin: '0',
48
+ padding: '0',
49
+ overflow: 'hidden',
50
+ clip: 'rect(0 0 0 0)',
51
+ 'clip-path': 'inset(50%)',
52
+ border: '0',
53
+ 'white-space': 'nowrap',
54
+ };
55
+ const isField = (element) => element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement;
56
+ if (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {
57
+ class GovukReactCharacterCount extends HTMLElement {
58
+ constructor() {
59
+ super(...arguments);
60
+ this.currentCount = 0;
61
+ this.onInput = () => {
62
+ this.update();
63
+ this.lastInputTime = Date.now();
64
+ };
65
+ // As in govuk-frontend: while focused, announce the count once the user pauses typing.
66
+ this.onFocus = () => {
67
+ window.clearInterval(this.checker);
68
+ this.checker = window.setInterval(() => {
69
+ if (!this.lastInputTime || Date.now() - 500 >= this.lastInputTime)
70
+ this.announceIfChanged();
71
+ }, 1000);
72
+ };
73
+ this.onBlur = () => window.clearInterval(this.checker);
74
+ // `reset` changes the value with no event, after it fires.
75
+ this.onReset = (event) => {
76
+ if (this.input && event.target === this.input.form)
77
+ window.setTimeout(() => this.update());
78
+ };
79
+ // A page restored from the back-forward cache, or a browser that restores the field's value.
80
+ this.onPageShow = () => {
81
+ if (!this.input)
82
+ return;
83
+ this.update();
84
+ this.announceIfChanged();
85
+ };
86
+ }
87
+ static get observedAttributes() {
88
+ return [
89
+ 'maxlength',
90
+ 'count-type',
91
+ 'threshold',
92
+ 'within-limit-class',
93
+ 'over-limit-class',
94
+ 'below-threshold-class',
95
+ 'input-over-limit-class',
96
+ ...messageNames.flatMap(translationAttributeNames),
97
+ ];
98
+ }
99
+ get count() {
100
+ return this.input ? this.currentCount : undefined;
101
+ }
102
+ connectedCallback() {
103
+ // The parts may be parsed or rendered later, and React can rewrite a class attribute.
104
+ this.observer = new MutationObserver((records) => {
105
+ if (records.some((record) => record.type === 'childList'))
106
+ this.setup();
107
+ else
108
+ this.update();
109
+ });
110
+ // React can rewrite a class, or put back the field's `maxlength`.
111
+ this.observer.observe(this, {
112
+ childList: true,
113
+ subtree: true,
114
+ attributes: true,
115
+ attributeFilter: ['class', 'maxlength'],
116
+ });
117
+ window.addEventListener('pageshow', this.onPageShow);
118
+ document.addEventListener('reset', this.onReset, true);
119
+ this.setup();
120
+ }
121
+ disconnectedCallback() {
122
+ var _a;
123
+ (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
124
+ window.removeEventListener('pageshow', this.onPageShow);
125
+ document.removeEventListener('reset', this.onReset, true);
126
+ window.clearInterval(this.checker);
127
+ this.unbind();
128
+ }
129
+ attributeChangedCallback() {
130
+ // Wait for every attribute: React sets them one by one before connecting the element.
131
+ if (!this.isConnected)
132
+ return;
133
+ if (!this.input) {
134
+ this.setup();
135
+ return;
136
+ }
137
+ if (this.maxLength === undefined) {
138
+ this.downgrade();
139
+ return;
140
+ }
141
+ // Screen readers hear the new count when the user next pauses.
142
+ this.lastAnnouncedValue = undefined;
143
+ this.update();
144
+ }
145
+ own(selector) {
146
+ return Array.from(this.querySelectorAll(selector)).find((element) => element.closest(tagName) === this);
147
+ }
148
+ get maxLength() {
149
+ const value = Number(this.getAttribute('maxlength'));
150
+ return this.hasAttribute('maxlength') && Number.isFinite(value) ? value : undefined;
151
+ }
152
+ get countType() {
153
+ const type = this.getAttribute('count-type');
154
+ return type === 'characters' || type === 'words' ? type : 'length';
155
+ }
156
+ // As govuk-frontend: the field's closest `lang`, which can be inside the element, or English.
157
+ get locale() {
158
+ var _a, _b;
159
+ return ((_b = ((_a = this.input) !== null && _a !== void 0 ? _a : this).closest('[lang]')) === null || _b === void 0 ? void 0 : _b.getAttribute('lang')) || 'en';
160
+ }
161
+ setup() {
162
+ const input = this.own('[data-character-count-input]');
163
+ if (!isField(input) || this.maxLength === undefined)
164
+ return;
165
+ const fresh = input !== this.input;
166
+ if (fresh) {
167
+ this.unbind();
168
+ this.input = input;
169
+ input.addEventListener('input', this.onInput);
170
+ input.addEventListener('focus', this.onFocus);
171
+ input.addEventListener('blur', this.onBlur);
172
+ // A value set by a script, such as a form library's, fires no `input` event.
173
+ this.stopWatchingValue = onPropertyChange(() => input.value, () => this.update());
174
+ input.removeAttribute('maxlength');
175
+ this.lastAnnouncedValue = undefined;
176
+ }
177
+ this.dataset.upgraded = '';
178
+ const description = this.own('[data-character-count-description]');
179
+ if (description && !this.hasAttribute('hidden-description-class')) {
180
+ Object.entries(visuallyHidden).forEach(([name, value]) => description.style.setProperty(name, value));
181
+ }
182
+ [this.own('[data-character-count-status]'), this.own('[data-character-count-sr-status]')].forEach((status) => {
183
+ if (status)
184
+ status.hidden = false;
185
+ });
186
+ this.update();
187
+ if (fresh)
188
+ this.announceIfChanged();
189
+ }
190
+ unbind() {
191
+ var _a;
192
+ const { input } = this;
193
+ if (!input)
194
+ return;
195
+ input.removeEventListener('input', this.onInput);
196
+ input.removeEventListener('focus', this.onFocus);
197
+ input.removeEventListener('blur', this.onBlur);
198
+ (_a = this.stopWatchingValue) === null || _a === void 0 ? void 0 : _a.call(this);
199
+ window.clearInterval(this.checker);
200
+ this.input = undefined;
201
+ }
202
+ /** Back to the markup without JavaScript, when the limit is removed. */
203
+ downgrade() {
204
+ const { input } = this;
205
+ if (!input)
206
+ return;
207
+ classesOf(this.getAttribute('input-over-limit-class')).forEach((name) => input.classList.toggle(name, false));
208
+ this.unbind();
209
+ delete this.dataset.upgraded;
210
+ const description = this.own('[data-character-count-description]');
211
+ if (description) {
212
+ if (this.hasAttribute('hidden-description-class')) {
213
+ classesOf(this.getAttribute('hidden-description-class')).forEach((name) => description.classList.toggle(name, false));
214
+ }
215
+ else {
216
+ Object.keys(visuallyHidden).forEach((name) => description.style.removeProperty(name));
217
+ }
218
+ }
219
+ [this.own('[data-character-count-status]'), this.own('[data-character-count-sr-status]')].forEach((status) => {
220
+ if (status)
221
+ status.hidden = true;
222
+ });
223
+ }
224
+ update() {
225
+ if (!this.input)
226
+ return;
227
+ this.input.removeAttribute('maxlength');
228
+ this.currentCount = countOf(this.input.value, this.countType, this.locale);
229
+ this.render();
230
+ }
231
+ message() {
232
+ var _a;
233
+ const messages = Object.fromEntries(messageNames.map((name) => [name, messageFromAttributes(this, name)]));
234
+ return countMessage(((_a = this.maxLength) !== null && _a !== void 0 ? _a : Infinity) - this.currentCount, this.countType, messages, this.locale);
235
+ }
236
+ get belowThreshold() {
237
+ var _a;
238
+ const threshold = Number(this.getAttribute('threshold'));
239
+ if (!threshold)
240
+ return false;
241
+ return this.currentCount < (((_a = this.maxLength) !== null && _a !== void 0 ? _a : Infinity) * threshold) / 100;
242
+ }
243
+ /** The visible count and the classes, from the current count. */
244
+ render() {
245
+ const { input } = this;
246
+ if (!input)
247
+ return;
248
+ const { state, text } = this.message();
249
+ const over = state === 'over';
250
+ const description = this.own('[data-character-count-description]');
251
+ // `toggle` with force leaves a class that's already there alone, so the observer isn't woken.
252
+ classesOf(this.getAttribute('hidden-description-class')).forEach((name) => description === null || description === void 0 ? void 0 : description.classList.toggle(name, true));
253
+ classesOf(this.getAttribute('input-over-limit-class')).forEach((name) => input.classList.toggle(name, over));
254
+ const belowThreshold = this.belowThreshold;
255
+ const srStatus = this.own('[data-character-count-sr-status]');
256
+ if (belowThreshold)
257
+ srStatus === null || srStatus === void 0 ? void 0 : srStatus.setAttribute('aria-hidden', 'true');
258
+ else
259
+ srStatus === null || srStatus === void 0 ? void 0 : srStatus.removeAttribute('aria-hidden');
260
+ const status = this.own('[data-character-count-status]');
261
+ if (!status)
262
+ return;
263
+ status.dataset.state = state;
264
+ status.toggleAttribute('data-below-threshold', belowThreshold);
265
+ classesOf(this.getAttribute('below-threshold-class')).forEach((name) => status.classList.toggle(name, belowThreshold));
266
+ classesOf(this.getAttribute('within-limit-class')).forEach((name) => status.classList.toggle(name, !over));
267
+ classesOf(this.getAttribute('over-limit-class')).forEach((name) => status.classList.toggle(name, over));
268
+ setText(status, text);
269
+ }
270
+ /** Updates the count for screen readers, if the field changed since it last did. */
271
+ announceIfChanged() {
272
+ const { input } = this;
273
+ const status = this.own('[data-character-count-sr-status]');
274
+ if (!input || !status)
275
+ return;
276
+ if (input.value === this.lastAnnouncedValue)
277
+ return;
278
+ this.lastAnnouncedValue = input.value;
279
+ const { state, text } = this.message();
280
+ status.dataset.state = state;
281
+ setText(status, text);
282
+ }
283
+ }
284
+ if (!customElements.get(tagName))
285
+ customElements.define(tagName, GovukReactCharacterCount);
286
+ }
287
+ //# sourceMappingURL=element.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../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IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAC,KAAK,CAAC;YACtC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;YACvC,MAAM,CAAC,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC;YAC7B,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QACxB,CAAC;KACF;IAED,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,OAAO,CAAC;QAAE,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,wBAAwB,CAAC,CAAC;AAC7F,CAAC","sourcesContent":["/*\n * <govuk-react-character-count>: a headless, light-DOM custom element that tells users how many\n * characters or words they can still enter, with or without React.\n *\n * Without JavaScript the field shows its description, such as \"You can enter up to 200\n * characters\". On upgrade the element visually hides the description, shows the count, and keeps\n * it up to date as the user types. As in govuk-frontend, screen readers hear the count once the\n * user pauses, rather than on every key.\n *\n * Markup inside the element:\n * - `[data-character-count-input]`: a `textarea` or `input`. Its `maxlength` is removed on\n * upgrade, so users can type past the limit and see by how much.\n * - `[data-character-count-description]`: the description, for `aria-describedby`.\n * - `[data-character-count-status]`: the visible count, rendered `hidden` with `aria-hidden`.\n * - `[data-character-count-sr-status]`: the count for screen readers, rendered `hidden` with\n * `aria-live=\"polite\"`. Make it visually hidden.\n *\n * The statuses get `data-state`, \"under\", \"at\" or \"over\" the limit. The visible one gets\n * `data-below-threshold` while the count is below `threshold`, and the one for screen readers gets\n * `aria-hidden` then.\n *\n * Attributes:\n * - `maxlength`: the limit. Without it, the element doesn't upgrade.\n * - `count-type`: \"length\" (the default) counts UTF-16 code units, as `maxlength` does;\n * \"characters\" counts characters as users see them; \"words\" counts words.\n * - `threshold`: the percentage of the limit from which the count is shown.\n * - `characters-under-limit-text`, `characters-at-limit-text`, `characters-over-limit-text`, `words-under-limit-text`,\n * `words-at-limit-text`, `words-over-limit-text`: the messages, English by default, with `%{count}` for\n * the number. Add a plural form to the name, such as `characters-under-limit-text-one`, for a\n * message for each form.\n * - `hidden-description-class`: classes that visually hide the description. Without them, the\n * element visually hides it with inline styles.\n * - `within-limit-class`, `over-limit-class`, `below-threshold-class`: classes for the visible\n * count.\n * - `input-over-limit-class`: classes for the field while over the limit.\n */\n\nimport { onPropertyChange } from '../utils/on-property-change.js';\nimport { translationAttributeNames } from '../utils/translation.js';\nimport { countMessage, countOf, messageFromAttributes, messageNames, type CountType } from './messages.js';\nimport { classesOf, setText } from '../utils/dom.js';\n\nexport const tagName = 'govuk-react-character-count';\n\nexport interface CharacterCountElement extends HTMLElement {\n /** The count, once upgraded. */\n readonly count: number | undefined;\n /** Counts the field again and updates the visible count, such as after setting its value. */\n update(): void;\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'govuk-react-character-count': CharacterCountElement;\n }\n}\n\n// The same visually hidden styles as govuk-frontend's.\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\nconst isField = (element: Element | undefined): element is HTMLTextAreaElement | HTMLInputElement =>\n element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement;\n\nif (typeof HTMLElement !== 'undefined' && typeof customElements !== 'undefined') {\n class GovukReactCharacterCount extends HTMLElement implements CharacterCountElement {\n static get observedAttributes() {\n return [\n 'maxlength',\n 'count-type',\n 'threshold',\n 'within-limit-class',\n 'over-limit-class',\n 'below-threshold-class',\n 'input-over-limit-class',\n ...messageNames.flatMap(translationAttributeNames),\n ];\n }\n\n private input?: HTMLTextAreaElement | HTMLInputElement;\n\n private currentCount = 0;\n\n private lastInputTime?: number;\n\n private lastAnnouncedValue?: string;\n\n private checker?: number;\n\n private observer?: MutationObserver;\n\n private stopWatchingValue?: () => void;\n\n private readonly onInput = () => {\n this.update();\n this.lastInputTime = Date.now();\n };\n\n // As in govuk-frontend: while focused, announce the count once the user pauses typing.\n private readonly onFocus = () => {\n window.clearInterval(this.checker);\n this.checker = window.setInterval(() => {\n if (!this.lastInputTime || Date.now() - 500 >= this.lastInputTime) this.announceIfChanged();\n }, 1000);\n };\n\n private readonly onBlur = () => window.clearInterval(this.checker);\n\n // `reset` changes the value with no event, after it fires.\n private readonly onReset = (event: Event) => {\n if (this.input && event.target === this.input.form) window.setTimeout(() => this.update());\n };\n\n // A page restored from the back-forward cache, or a browser that restores the field's value.\n private readonly onPageShow = () => {\n if (!this.input) return;\n this.update();\n this.announceIfChanged();\n };\n\n get count() {\n return this.input ? this.currentCount : undefined;\n }\n\n connectedCallback() {\n // The parts may be parsed or rendered later, and React can rewrite a class attribute.\n this.observer = new MutationObserver((records) => {\n if (records.some((record) => record.type === 'childList')) this.setup();\n else this.update();\n });\n // React can rewrite a class, or put back the field's `maxlength`.\n this.observer.observe(this, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['class', 'maxlength'],\n });\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 window.removeEventListener('pageshow', this.onPageShow);\n document.removeEventListener('reset', this.onReset, true);\n window.clearInterval(this.checker);\n this.unbind();\n }\n\n attributeChangedCallback() {\n // Wait for every attribute: React sets them one by one before connecting the element.\n if (!this.isConnected) return;\n if (!this.input) {\n this.setup();\n return;\n }\n if (this.maxLength === undefined) {\n this.downgrade();\n return;\n }\n // Screen readers hear the new count when the user next pauses.\n this.lastAnnouncedValue = undefined;\n this.update();\n }\n\n private own(selector: string) {\n return Array.from(this.querySelectorAll<HTMLElement>(selector)).find(\n (element) => element.closest(tagName) === this\n );\n }\n\n private get maxLength() {\n const value = Number(this.getAttribute('maxlength'));\n return this.hasAttribute('maxlength') && Number.isFinite(value) ? value : undefined;\n }\n\n private get countType(): CountType {\n const type = this.getAttribute('count-type');\n return type === 'characters' || type === 'words' ? type : 'length';\n }\n\n // As govuk-frontend: the field's closest `lang`, which can be inside the element, or English.\n private get locale() {\n return (this.input ?? this).closest('[lang]')?.getAttribute('lang') || 'en';\n }\n\n private setup() {\n const input = this.own('[data-character-count-input]');\n if (!isField(input) || this.maxLength === undefined) return;\n const fresh = input !== this.input;\n if (fresh) {\n this.unbind();\n this.input = input;\n input.addEventListener('input', this.onInput);\n input.addEventListener('focus', this.onFocus);\n input.addEventListener('blur', this.onBlur);\n // A value set by a script, such as a form library's, fires no `input` event.\n this.stopWatchingValue = onPropertyChange(\n () => input.value,\n () => this.update()\n );\n input.removeAttribute('maxlength');\n this.lastAnnouncedValue = undefined;\n }\n this.dataset.upgraded = '';\n const description = this.own('[data-character-count-description]');\n if (description && !this.hasAttribute('hidden-description-class')) {\n Object.entries(visuallyHidden).forEach(([name, value]) => description.style.setProperty(name, value));\n }\n [this.own('[data-character-count-status]'), this.own('[data-character-count-sr-status]')].forEach((status) => {\n if (status) status.hidden = false;\n });\n this.update();\n if (fresh) this.announceIfChanged();\n }\n\n private unbind() {\n const { input } = this;\n if (!input) return;\n input.removeEventListener('input', this.onInput);\n input.removeEventListener('focus', this.onFocus);\n input.removeEventListener('blur', this.onBlur);\n this.stopWatchingValue?.();\n window.clearInterval(this.checker);\n this.input = undefined;\n }\n\n /** Back to the markup without JavaScript, when the limit is removed. */\n private downgrade() {\n const { input } = this;\n if (!input) return;\n classesOf(this.getAttribute('input-over-limit-class')).forEach((name) => input.classList.toggle(name, false));\n this.unbind();\n delete this.dataset.upgraded;\n const description = this.own('[data-character-count-description]');\n if (description) {\n if (this.hasAttribute('hidden-description-class')) {\n classesOf(this.getAttribute('hidden-description-class')).forEach((name) =>\n description.classList.toggle(name, false)\n );\n } else {\n Object.keys(visuallyHidden).forEach((name) => description.style.removeProperty(name));\n }\n }\n [this.own('[data-character-count-status]'), this.own('[data-character-count-sr-status]')].forEach((status) => {\n if (status) status.hidden = true;\n });\n }\n\n update() {\n if (!this.input) return;\n this.input.removeAttribute('maxlength');\n this.currentCount = countOf(this.input.value, this.countType, this.locale);\n this.render();\n }\n\n private message() {\n const messages = Object.fromEntries(messageNames.map((name) => [name, messageFromAttributes(this, name)]));\n return countMessage((this.maxLength ?? Infinity) - this.currentCount, this.countType, messages, this.locale);\n }\n\n private get belowThreshold() {\n const threshold = Number(this.getAttribute('threshold'));\n if (!threshold) return false;\n return this.currentCount < ((this.maxLength ?? Infinity) * threshold) / 100;\n }\n\n /** The visible count and the classes, from the current count. */\n private render() {\n const { input } = this;\n if (!input) return;\n const { state, text } = this.message();\n const over = state === 'over';\n const description = this.own('[data-character-count-description]');\n // `toggle` with force leaves a class that's already there alone, so the observer isn't woken.\n classesOf(this.getAttribute('hidden-description-class')).forEach((name) =>\n description?.classList.toggle(name, true)\n );\n classesOf(this.getAttribute('input-over-limit-class')).forEach((name) => input.classList.toggle(name, over));\n const belowThreshold = this.belowThreshold;\n const srStatus = this.own('[data-character-count-sr-status]');\n if (belowThreshold) srStatus?.setAttribute('aria-hidden', 'true');\n else srStatus?.removeAttribute('aria-hidden');\n const status = this.own('[data-character-count-status]');\n if (!status) return;\n status.dataset.state = state;\n status.toggleAttribute('data-below-threshold', belowThreshold);\n classesOf(this.getAttribute('below-threshold-class')).forEach((name) =>\n status.classList.toggle(name, belowThreshold)\n );\n classesOf(this.getAttribute('within-limit-class')).forEach((name) => status.classList.toggle(name, !over));\n classesOf(this.getAttribute('over-limit-class')).forEach((name) => status.classList.toggle(name, over));\n setText(status, text);\n }\n\n /** Updates the count for screen readers, if the field changed since it last did. */\n private announceIfChanged() {\n const { input } = this;\n const status = this.own('[data-character-count-sr-status]');\n if (!input || !status) return;\n if (input.value === this.lastAnnouncedValue) return;\n this.lastAnnouncedValue = input.value;\n const { state, text } = this.message();\n status.dataset.state = state;\n setText(status, text);\n }\n }\n\n if (!customElements.get(tagName)) customElements.define(tagName, GovukReactCharacterCount);\n}\n"]}
@@ -0,0 +1,57 @@
1
+ import * as React from 'react';
2
+ import type { ComponentProps } from 'react';
3
+ import { type CountType, type Translation } from './messages.js';
4
+ export { countOf, countMessage, type CountType, type Translation } from './messages.js';
5
+ export type RootProps = React.HTMLAttributes<HTMLElement> & {
6
+ /** The most characters, or words, the user should enter. Without it there's no count. */
7
+ maxLength?: number;
8
+ /**
9
+ * What to count: "length" (the default) counts UTF-16 code units, as `maxlength` does;
10
+ * "characters" counts characters as users see them, such as an emoji as one; "words" counts words.
11
+ */
12
+ countType?: CountType;
13
+ /** The percentage of the limit from which the count is shown. */
14
+ threshold?: number;
15
+ /** Shown while under the limit. `%{count}` is the number left. */
16
+ charactersUnderLimitText?: Translation;
17
+ /** Shown at the limit. */
18
+ charactersAtLimitText?: Translation;
19
+ /** Shown while over the limit. `%{count}` is the number too many. */
20
+ charactersOverLimitText?: Translation;
21
+ /** Shown while under the limit when counting words. `%{count}` is the number left. */
22
+ wordsUnderLimitText?: Translation;
23
+ /** Shown at the limit when counting words. */
24
+ wordsAtLimitText?: Translation;
25
+ /** Shown while over the limit when counting words. `%{count}` is the number too many. */
26
+ wordsOverLimitText?: Translation;
27
+ /** Classes that visually hide the description once upgraded. Without them, inline styles do. */
28
+ hiddenDescriptionClass?: string;
29
+ /** Classes for the visible count while within the limit. */
30
+ withinLimitClass?: string;
31
+ /** Classes for the visible count while over the limit. */
32
+ overLimitClass?: string;
33
+ /** Classes for the visible count while below `threshold`. */
34
+ belowThresholdClass?: string;
35
+ /** Classes for the field while over the limit. */
36
+ inputOverLimitClass?: string;
37
+ };
38
+ export declare function Root({ maxLength, countType, threshold, charactersUnderLimitText, charactersAtLimitText, charactersOverLimitText, wordsUnderLimitText, wordsAtLimitText, wordsOverLimitText, hiddenDescriptionClass, withinLimitClass, overLimitClass, belowThresholdClass, inputOverLimitClass, ...props }: RootProps): React.JSX.Element;
39
+ type PartProps<E extends keyof React.JSX.IntrinsicElements> = ComponentProps<E> & {
40
+ /** Render the only child instead, with this part's props merged onto it. */
41
+ asChild?: boolean;
42
+ };
43
+ export type InputProps = PartProps<'textarea'>;
44
+ /** The field: a `textarea`, or an `input` with `asChild`. Its `maxlength` is removed on upgrade. */
45
+ export declare function Input({ asChild, ...props }: InputProps): React.JSX.Element;
46
+ export type DescriptionProps = PartProps<'div'>;
47
+ /**
48
+ * The description, such as "You can enter up to 200 characters", shown without JavaScript and
49
+ * visually hidden on upgrade. Give it an id and add that to the field's `aria-describedby`.
50
+ */
51
+ export declare function Description({ asChild, ...props }: DescriptionProps): React.JSX.Element;
52
+ export type StatusProps = PartProps<'div'>;
53
+ /** The visible count, hidden from assistive technology. Hidden until the element upgrades. */
54
+ export declare function Status({ asChild, children, ...props }: StatusProps): React.JSX.Element;
55
+ export type ScreenReaderStatusProps = PartProps<'div'>;
56
+ /** The count for screen readers, once the user pauses typing. Make it visually hidden. */
57
+ export declare function ScreenReaderStatus({ asChild, children, ...props }: ScreenReaderStatusProps): React.JSX.Element;
@@ -0,0 +1,79 @@
1
+ 'use client';
2
+ import * as React from 'react';
3
+ import { createContext, useContext, useEffect, useRef, useState } from 'react';
4
+ import { Slot } from '../utils/slot.js';
5
+ import { tagName } from './element.js';
6
+ import { countMessage, messageAttributes } from './messages.js';
7
+ export { countOf, countMessage } from './messages.js';
8
+ // What the counts start with, so the element only changes text React rendered.
9
+ const InitialMessage = createContext(undefined);
10
+ const isCharacterCount = (element) => 'update' in element;
11
+ export function Root({ maxLength, countType = 'length', threshold, charactersUnderLimitText, charactersAtLimitText, charactersOverLimitText, wordsUnderLimitText, wordsAtLimitText, wordsOverLimitText, hiddenDescriptionClass, withinLimitClass, overLimitClass, belowThresholdClass, inputOverLimitClass, ...props }) {
12
+ const element = useRef(null);
13
+ const messages = {
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
+ };
21
+ // A value set by React, rather than typed, fires no `input` event.
22
+ useEffect(() => {
23
+ const node = element.current;
24
+ if (node && isCharacterCount(node))
25
+ node.update();
26
+ });
27
+ // Rendered once and then left to the element, so a re-render never puts back a stale count.
28
+ const [initial] = useState(() => maxLength === undefined ? undefined : countMessage(maxLength, countType, messages, props.lang || 'en').text);
29
+ return (React.createElement(InitialMessage.Provider, { value: initial }, React.createElement(tagName, {
30
+ ...props,
31
+ ref: element,
32
+ // The element owns `data-upgraded`.
33
+ suppressHydrationWarning: true,
34
+ maxlength: maxLength,
35
+ 'count-type': countType,
36
+ threshold,
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
+ 'hidden-description-class': hiddenDescriptionClass,
44
+ 'within-limit-class': withinLimitClass,
45
+ 'over-limit-class': overLimitClass,
46
+ 'below-threshold-class': belowThresholdClass,
47
+ 'input-over-limit-class': inputOverLimitClass,
48
+ })));
49
+ }
50
+ /** The field: a `textarea`, or an `input` with `asChild`. Its `maxlength` is removed on upgrade. */
51
+ export function Input({ asChild, ...props }) {
52
+ const Element = asChild ? Slot : 'textarea';
53
+ // The element owns `maxlength` and its over-limit classes after upgrade.
54
+ return React.createElement(Element, { "data-character-count-input": "", suppressHydrationWarning: true, ...props });
55
+ }
56
+ /**
57
+ * The description, such as "You can enter up to 200 characters", shown without JavaScript and
58
+ * visually hidden on upgrade. Give it an id and add that to the field's `aria-describedby`.
59
+ */
60
+ export function Description({ asChild, ...props }) {
61
+ const Element = asChild ? Slot : 'div';
62
+ // The element owns its hiding styles after upgrade.
63
+ return React.createElement(Element, { "data-character-count-description": "", suppressHydrationWarning: true, ...props });
64
+ }
65
+ /** The visible count, hidden from assistive technology. Hidden until the element upgrades. */
66
+ export function Status({ asChild, children, ...props }) {
67
+ const initial = useContext(InitialMessage);
68
+ const Element = asChild ? Slot : 'div';
69
+ // The element owns `hidden`, its text and its classes after upgrade.
70
+ return (React.createElement(Element, { "data-character-count-status": "", hidden: true, "aria-hidden": "true", suppressHydrationWarning: true, ...props }, children !== null && children !== void 0 ? children : initial));
71
+ }
72
+ /** The count for screen readers, once the user pauses typing. Make it visually hidden. */
73
+ export function ScreenReaderStatus({ asChild, children, ...props }) {
74
+ const initial = useContext(InitialMessage);
75
+ const Element = asChild ? Slot : 'div';
76
+ // The element owns `hidden`, `aria-hidden` and its text after upgrade.
77
+ return (React.createElement(Element, { "data-character-count-sr-status": "", hidden: true, "aria-live": "polite", suppressHydrationWarning: true, ...props }, children !== null && children !== void 0 ? children : initial));
78
+ }
79
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,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AAC;IACvC,qEAAqE;IACrE,OAAO,CACL,oBAAC,OAAO,mCAA6B,EAAE,EAAC,MAAM,uBAAa,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 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"]}
@@ -0,0 +1,20 @@
1
+ import { type Translation } from '../utils/translation.js';
2
+ export type { Translation };
3
+ export type CountType = 'length' | 'characters' | 'words';
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
+ export type MessageName = (typeof messageNames)[number];
6
+ /** govuk-frontend's English messages. `%{count}` is replaced with the number. */
7
+ export declare const defaultMessages: Record<MessageName, Translation>;
8
+ /** The attributes for a message: the message itself, or one attribute for each plural form. */
9
+ export declare const messageAttributes: (name: MessageName, message: Translation | undefined) => {
10
+ [x: string]: string;
11
+ };
12
+ /** Reads a message back from attributes written by `messageAttributes`. */
13
+ export declare const messageFromAttributes: (element: Element, name: MessageName) => Translation;
14
+ /** Counts the text as govuk-frontend does: UTF-16 code units, characters as users see them, or words. */
15
+ export declare function countOf(text: string, countType: CountType, locale?: string): number;
16
+ /** The message for the number of characters or words left, with its state. */
17
+ export declare function countMessage(remaining: number, countType: CountType, messages: Partial<Record<MessageName, Translation>>, locale?: string): {
18
+ state: string;
19
+ text: string;
20
+ };
@@ -0,0 +1,54 @@
1
+ /*
2
+ * Counting and count messages, shared by the <govuk-react-character-count> element and its React
3
+ * parts, so the server can render the message the element starts with.
4
+ */
5
+ import { translate, translationAttributes, translationFromAttributes, withLocale, } from '../utils/translation.js';
6
+ export const messageNames = [
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
+ ];
14
+ /** govuk-frontend's English messages. `%{count}` is replaced with the number. */
15
+ export const defaultMessages = {
16
+ 'characters-under-limit-text': {
17
+ one: 'You have %{count} character remaining',
18
+ other: 'You have %{count} characters remaining',
19
+ },
20
+ 'characters-at-limit-text': 'You have 0 characters remaining',
21
+ 'characters-over-limit-text': {
22
+ one: 'You have %{count} character too many',
23
+ other: 'You have %{count} characters too many',
24
+ },
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
+ };
29
+ /** The attributes for a message: the message itself, or one attribute for each plural form. */
30
+ export const messageAttributes = (name, message) => translationAttributes(name, message);
31
+ /** Reads a message back from attributes written by `messageAttributes`. */
32
+ export const messageFromAttributes = (element, name) => translationFromAttributes(element, name);
33
+ /** Counts the text as govuk-frontend does: UTF-16 code units, characters as users see them, or words. */
34
+ export function countOf(text, countType, locale) {
35
+ var _a, _b;
36
+ if (countType === 'length')
37
+ return text.length;
38
+ if (typeof Intl.Segmenter !== 'function') {
39
+ // Older browsers: close enough, rather than no count at all.
40
+ return countType === 'words' ? ((_b = (_a = text.match(/\S+/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) : Array.from(text).length;
41
+ }
42
+ const segmenter = withLocale(locale, (l) => new Intl.Segmenter(l, { granularity: countType === 'words' ? 'word' : 'grapheme' }));
43
+ const segments = Array.from(segmenter.segment(text));
44
+ return countType === 'words' ? segments.filter((segment) => segment.isWordLike).length : segments.length;
45
+ }
46
+ /** The message for the number of characters or words left, with its state. */
47
+ export function countMessage(remaining, countType, messages, locale) {
48
+ var _a;
49
+ const state = remaining < 0 ? 'over' : remaining === 0 ? 'at' : 'under';
50
+ const name = `${countType === 'words' ? 'words' : 'characters'}-${state}-limit-text`;
51
+ const message = (_a = messages[name]) !== null && _a !== void 0 ? _a : defaultMessages[name];
52
+ return { state, text: translate(message, Math.abs(remaining), locale) };
53
+ }
54
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +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,6BAA6B;IAC7B,0BAA0B;IAC1B,4BAA4B;IAC5B,wBAAwB;IACxB,qBAAqB;IACrB,uBAAuB;CACf,CAAC;AAIX,iFAAiF;AACjF,MAAM,CAAC,MAAM,eAAe,GAAqC;IAC/D,6BAA6B,EAAE;QAC7B,GAAG,EAAE,uCAAuC;QAC5C,KAAK,EAAE,wCAAwC;KAChD;IACD,0BAA0B,EAAE,iCAAiC;IAC7D,4BAA4B,EAAE;QAC5B,GAAG,EAAE,sCAAsC;QAC3C,KAAK,EAAE,uCAAuC;KAC/C;IACD,wBAAwB,EAAE,EAAE,GAAG,EAAE,kCAAkC,EAAE,KAAK,EAAE,mCAAmC,EAAE;IACjH,qBAAqB,EAAE,4BAA4B;IACnD,uBAAuB,EAAE,EAAE,GAAG,EAAE,iCAAiC,EAAE,KAAK,EAAE,kCAAkC,EAAE;CAC/G,CAAC;AAEF,+FAA+F;AAC/F,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,IAAiB,EAAE,OAAgC,EAAE,EAAE,CACvF,qBAAqB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;AAEvC,2EAA2E;AAC3E,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,OAAgB,EAAE,IAAiB,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,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,aAAa,CAAC;IAClG,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-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"]}
@@ -0,0 +1,10 @@
1
+ export declare const tagName = "govuk-react-choices";
2
+ export interface ChoicesElement extends HTMLElement {
3
+ /** Shows and hides the reveals to match the choices, such as after setting `checked`. */
4
+ sync(): void;
5
+ }
6
+ declare global {
7
+ interface HTMLElementTagNameMap {
8
+ 'govuk-react-choices': ChoicesElement;
9
+ }
10
+ }