@govuk-react/primitives 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +271 -2
  2. package/dist/accordion/element.d.ts +14 -0
  3. package/dist/accordion/element.js +302 -0
  4. package/dist/accordion/element.js.map +1 -0
  5. package/dist/accordion/index.d.ts +74 -0
  6. package/dist/accordion/index.js +138 -0
  7. package/dist/accordion/index.js.map +1 -0
  8. package/dist/auto-focus/element.d.ts +1 -0
  9. package/dist/auto-focus/element.js +75 -0
  10. package/dist/auto-focus/element.js.map +1 -0
  11. package/dist/auto-focus/index.d.ts +297 -0
  12. package/dist/auto-focus/index.js +29 -0
  13. package/dist/auto-focus/index.js.map +1 -0
  14. package/dist/autocomplete/element.d.ts +27 -0
  15. package/dist/autocomplete/element.js +597 -0
  16. package/dist/autocomplete/element.js.map +1 -0
  17. package/dist/autocomplete/index.d.ts +350 -0
  18. package/dist/autocomplete/index.js +108 -0
  19. package/dist/autocomplete/index.js.map +1 -0
  20. package/dist/button/element.d.ts +1 -0
  21. package/dist/button/element.js +59 -0
  22. package/dist/button/element.js.map +1 -0
  23. package/dist/button/index.d.ts +10 -0
  24. package/dist/button/index.js +9 -0
  25. package/dist/button/index.js.map +1 -0
  26. package/dist/character-count/element.d.ts +7 -0
  27. package/dist/character-count/element.js +287 -0
  28. package/dist/character-count/element.js.map +1 -0
  29. package/dist/character-count/index.d.ts +57 -0
  30. package/dist/character-count/index.js +79 -0
  31. package/dist/character-count/index.js.map +1 -0
  32. package/dist/character-count/messages.d.ts +20 -0
  33. package/dist/character-count/messages.js +54 -0
  34. package/dist/character-count/messages.js.map +1 -0
  35. package/dist/choices/element.d.ts +5 -0
  36. package/dist/choices/element.js +202 -0
  37. package/dist/choices/element.js.map +1 -0
  38. package/dist/choices/index.d.ts +309 -0
  39. package/dist/choices/index.js +37 -0
  40. package/dist/choices/index.js.map +1 -0
  41. package/dist/disclosure/element.d.ts +14 -0
  42. package/dist/disclosure/element.js +123 -0
  43. package/dist/disclosure/element.js.map +1 -0
  44. package/dist/disclosure/index.d.ts +307 -0
  45. package/dist/disclosure/index.js +66 -0
  46. package/dist/disclosure/index.js.map +1 -0
  47. package/dist/exit-this-page/element.d.ts +19 -0
  48. package/dist/exit-this-page/element.js +201 -0
  49. package/dist/exit-this-page/element.js.map +1 -0
  50. package/dist/exit-this-page/index.d.ts +330 -0
  51. package/dist/exit-this-page/index.js +54 -0
  52. package/dist/exit-this-page/index.js.map +1 -0
  53. package/dist/file-upload/element.d.ts +23 -0
  54. package/dist/file-upload/element.js +270 -0
  55. package/dist/file-upload/element.js.map +1 -0
  56. package/dist/file-upload/index.d.ts +46 -0
  57. package/dist/file-upload/index.js +65 -0
  58. package/dist/file-upload/index.js.map +1 -0
  59. package/dist/focus-links/element.d.ts +1 -0
  60. package/dist/focus-links/element.js +90 -0
  61. package/dist/focus-links/element.js.map +1 -0
  62. package/dist/focus-links/index.d.ts +288 -0
  63. package/dist/focus-links/index.js +7 -0
  64. package/dist/focus-links/index.js.map +1 -0
  65. package/dist/index.d.ts +13 -0
  66. package/dist/index.js +14 -0
  67. package/dist/index.js.map +1 -0
  68. package/dist/inline/accordion-element.js +1 -0
  69. package/dist/inline/auto-focus-element.js +1 -0
  70. package/dist/inline/autocomplete-element.js +2 -0
  71. package/dist/inline/button-element.js +1 -0
  72. package/dist/inline/character-count-element.js +1 -0
  73. package/dist/inline/choices-element.js +1 -0
  74. package/dist/inline/disclosure-element.js +1 -0
  75. package/dist/inline/exit-this-page-element.js +1 -0
  76. package/dist/inline/file-upload-element.js +1 -0
  77. package/dist/inline/focus-links-element.js +1 -0
  78. package/dist/inline/modal-element.js +1 -0
  79. package/dist/inline/password-input-element.js +1 -0
  80. package/dist/inline/tabs-element.js +1 -0
  81. package/dist/inline-script/index.d.ts +26 -0
  82. package/dist/inline-script/index.js +31 -0
  83. package/dist/inline-script/index.js.map +1 -0
  84. package/dist/modal/element.d.ts +10 -0
  85. package/dist/modal/element.js +114 -0
  86. package/dist/modal/element.js.map +1 -0
  87. package/dist/modal/index.d.ts +36 -0
  88. package/dist/modal/index.js +109 -0
  89. package/dist/modal/index.js.map +1 -0
  90. package/dist/password-input/element.d.ts +1 -0
  91. package/dist/password-input/element.js +134 -0
  92. package/dist/password-input/element.js.map +1 -0
  93. package/dist/password-input/index.d.ts +318 -0
  94. package/dist/password-input/index.js +35 -0
  95. package/dist/password-input/index.js.map +1 -0
  96. package/dist/tabs/element.d.ts +19 -0
  97. package/dist/tabs/element.js +416 -0
  98. package/dist/tabs/element.js.map +1 -0
  99. package/dist/tabs/index.d.ts +83 -0
  100. package/dist/tabs/index.js +138 -0
  101. package/dist/tabs/index.js.map +1 -0
  102. package/dist/utils/dom.d.ts +9 -0
  103. package/dist/utils/dom.js +27 -0
  104. package/dist/utils/dom.js.map +1 -0
  105. package/dist/utils/on-property-set.d.ts +9 -0
  106. package/dist/utils/on-property-set.js +38 -0
  107. package/dist/utils/on-property-set.js.map +1 -0
  108. package/dist/utils/set-focus.d.ts +11 -0
  109. package/dist/utils/set-focus.js +38 -0
  110. package/dist/utils/set-focus.js.map +1 -0
  111. package/dist/utils/set-up-when-ready.d.ts +6 -0
  112. package/dist/utils/set-up-when-ready.js +16 -0
  113. package/dist/utils/set-up-when-ready.js.map +1 -0
  114. package/dist/utils/slot.d.ts +13 -0
  115. package/dist/utils/slot.js +40 -0
  116. package/dist/utils/slot.js.map +1 -0
  117. package/dist/utils/translation.d.ts +13 -0
  118. package/dist/utils/translation.js +57 -0
  119. package/dist/utils/translation.js.map +1 -0
  120. package/licences/accessible-autocomplete.txt +20 -0
  121. package/package.json +49 -4
@@ -0,0 +1,59 @@
1
+ /*
2
+ * Headless button behaviour, with or without React, as govuk-frontend's button script has. Importing
3
+ * this module adds two listeners to the document, once, for any element with `data-button`:
4
+ *
5
+ * - With `data-prevent-double-click="true"`, a second click within a second of the first is
6
+ * cancelled, so a form isn't submitted twice. Unlike govuk-frontend, the click is also stopped
7
+ * before it reaches React, so an `onClick` doesn't run twice either.
8
+ * - A link with `role="button"` is activated with the Space key, as a button is.
9
+ *
10
+ * Unlike a custom element, the listeners need no wrapper, which would change a button group's
11
+ * layout.
12
+ */
13
+ const debounceMs = 1000;
14
+ // Shared by every copy of this module on the page.
15
+ const installed = Symbol.for('govuk-react-button');
16
+ const lastClicks = new WeakMap();
17
+ // The path, rather than the target, reaches into shadow roots.
18
+ const buttonOf = (event) => {
19
+ for (const target of event.composedPath()) {
20
+ if (target instanceof HTMLElement && target.hasAttribute('data-button'))
21
+ return target;
22
+ }
23
+ return null;
24
+ };
25
+ function onClick(event) {
26
+ const button = buttonOf(event);
27
+ if (!button || button.getAttribute('data-prevent-double-click') !== 'true')
28
+ return;
29
+ const last = lastClicks.get(button);
30
+ if (last !== undefined && event.timeStamp - last < debounceMs) {
31
+ event.preventDefault();
32
+ event.stopImmediatePropagation();
33
+ return;
34
+ }
35
+ lastClicks.set(button, event.timeStamp);
36
+ }
37
+ function onKeyDown(event) {
38
+ // Held down, Space activates once, as on a button. A handler that took the key keeps it.
39
+ if (event.key !== ' ' || event.repeat || event.defaultPrevented)
40
+ return;
41
+ const button = buttonOf(event);
42
+ if (!button || button !== event.composedPath()[0] || button.getAttribute('role') !== 'button')
43
+ return;
44
+ if (button instanceof HTMLButtonElement)
45
+ return;
46
+ // Space would scroll the page.
47
+ event.preventDefault();
48
+ button.click();
49
+ }
50
+ if (typeof document !== 'undefined') {
51
+ if (!Reflect.get(globalThis, installed)) {
52
+ Reflect.set(globalThis, installed, true);
53
+ // Capture, to cancel a second click before anything else hears it.
54
+ document.addEventListener('click', onClick, true);
55
+ document.addEventListener('keydown', onKeyDown);
56
+ }
57
+ }
58
+ export {};
59
+ //# sourceMappingURL=element.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"element.js","sourceRoot":"","sources":["../../src/button/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAA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CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,QAAQ;QAAE,OAAO;IACtG,IAAI,MAAM,YAAY,iBAAiB;QAAE,OAAO;IAChD,+BAA+B;IAC/B,KAAK,CAAC,cAAc,EAAE,CAAC;IACvB,MAAM,CAAC,KAAK,EAAE,CAAC;AACjB,CAAC;AAED,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;IACpC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,CAAC,EAAE,CAAC;QACxC,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;QACzC,mEAAmE;QACnE,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;QAClD,QAAQ,CAAC,gBAAgB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;IAClD,CAAC;AACH,CAAC","sourcesContent":["/*\n * Headless button behaviour, with or without React, as govuk-frontend's button script has. Importing\n * this module adds two listeners to the document, once, for any element with `data-button`:\n *\n * - With `data-prevent-double-click=\"true\"`, a second click within a second of the first is\n * cancelled, so a form isn't submitted twice. Unlike govuk-frontend, the click is also stopped\n * before it reaches React, so an `onClick` doesn't run twice either.\n * - A link with `role=\"button\"` is activated with the Space key, as a button is.\n *\n * Unlike a custom element, the listeners need no wrapper, which would change a button group's\n * layout.\n */\n\nconst debounceMs = 1000;\n\n// Shared by every copy of this module on the page.\nconst installed = Symbol.for('govuk-react-button');\n\nconst lastClicks = new WeakMap<Element, number>();\n\n// The path, rather than the target, reaches into shadow roots.\nconst buttonOf = (event: Event) => {\n for (const target of event.composedPath()) {\n if (target instanceof HTMLElement && target.hasAttribute('data-button')) return target;\n }\n return null;\n};\n\nfunction onClick(event: MouseEvent) {\n const button = buttonOf(event);\n if (!button || button.getAttribute('data-prevent-double-click') !== 'true') return;\n const last = lastClicks.get(button);\n if (last !== undefined && event.timeStamp - last < debounceMs) {\n event.preventDefault();\n event.stopImmediatePropagation();\n return;\n }\n lastClicks.set(button, event.timeStamp);\n}\n\nfunction onKeyDown(event: KeyboardEvent) {\n // Held down, Space activates once, as on a button. A handler that took the key keeps it.\n if (event.key !== ' ' || event.repeat || event.defaultPrevented) return;\n const button = buttonOf(event);\n if (!button || button !== event.composedPath()[0] || button.getAttribute('role') !== 'button') return;\n if (button instanceof HTMLButtonElement) return;\n // Space would scroll the page.\n event.preventDefault();\n button.click();\n}\n\nif (typeof document !== 'undefined') {\n if (!Reflect.get(globalThis, installed)) {\n Reflect.set(globalThis, installed, true);\n // Capture, to cancel a second click before anything else hears it.\n document.addEventListener('click', onClick, true);\n document.addEventListener('keydown', onKeyDown);\n }\n}\n\nexport {};\n"]}
@@ -0,0 +1,10 @@
1
+ import * as React from 'react';
2
+ import type { ComponentProps } from 'react';
3
+ import './element.js';
4
+ export type RootProps = ComponentProps<'button'> & {
5
+ /** Render the only child instead, such as a link with `role="button"`, with this part's props merged onto it. */
6
+ asChild?: boolean;
7
+ /** Cancel a second click within a second of the first, so a form isn't submitted twice. */
8
+ preventDoubleClick?: boolean;
9
+ };
10
+ export declare function Root({ asChild, preventDoubleClick, ...props }: RootProps): React.JSX.Element;
@@ -0,0 +1,9 @@
1
+ 'use client';
2
+ import * as React from 'react';
3
+ import { Slot } from '../utils/slot.js';
4
+ import './element.js';
5
+ export function Root({ asChild, preventDoubleClick, ...props }) {
6
+ const Element = asChild ? Slot : 'button';
7
+ return (React.createElement(Element, { "data-button": "", "data-prevent-double-click": preventDoubleClick === undefined ? undefined : String(preventDoubleClick), ...props }));
8
+ }
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/button/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,cAAc,CAAC;AActB,MAAM,UAAU,IAAI,CAAC,EAAE,OAAO,EAAE,kBAAkB,EAAE,GAAG,KAAK,EAAa;IACvE,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC;IAC1C,OAAO,CACL,oBAAC,OAAO,mBACM,EAAE,+BACa,kBAAkB,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,kBAAkB,CAAC,KAChG,KAAK,GACT,CACH,CAAC;AACJ,CAAC","sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport type { ComponentProps } from 'react';\nimport { Slot } from '../utils/slot.js';\nimport './element.js';\n\n/*\n * Headless button behaviour (./element.ts): `Root` marks a button or link button for it. Prevents\n * double clicks with `preventDoubleClick`, and makes Space activate a link with `role=\"button\"`.\n */\n\nexport type RootProps = ComponentProps<'button'> & {\n /** Render the only child instead, such as a link with `role=\"button\"`, with this part's props merged onto it. */\n asChild?: boolean;\n /** Cancel a second click within a second of the first, so a form isn't submitted twice. */\n preventDoubleClick?: boolean;\n};\n\nexport function Root({ asChild, preventDoubleClick, ...props }: RootProps) {\n const Element = asChild ? Slot : 'button';\n return (\n <Element\n data-button=\"\"\n data-prevent-double-click={preventDoubleClick === undefined ? undefined : String(preventDoubleClick)}\n {...props}\n />\n );\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export declare const tagName = "govuk-react-character-count";
2
+ export interface CharacterCountElement extends HTMLElement {
3
+ /** The count, once upgraded. */
4
+ readonly count: number | undefined;
5
+ /** Counts the field again and updates the visible count, such as after setting its value. */
6
+ update(): void;
7
+ }
@@ -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`, `characters-at-limit`, `characters-over-limit`, `words-under-limit`,
28
+ * `words-at-limit`, `words-over-limit`: the messages, English by default, with `%{count}` for
29
+ * the number. Add a plural form to the name, such as `characters-under-limit-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 { onPropertySet } from '../utils/on-property-set.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 = onPropertySet(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":["../../src/character-count/element.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAkB,MAAM,eAAe,CAAC;AAC3G,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAErD,MAAM,CAAC,MAAM,OAAO,GAAG,6BAA6B,CAAC;AASrD,uDAAuD;AACvD,MAAM,cAAc,GAA2B;IAC7C,QAAQ,EAAE,UAAU;IACpB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,KAAK;IACb,MAAM,EAAE,GAAG;IACX,OAAO,EAAE,GAAG;IACZ,QAAQ,EAAE,QAAQ;IAClB,IAAI,EAAE,eAAe;IACrB,WAAW,EAAE,YAAY;IACzB,MAAM,EAAE,GAAG;IACX,aAAa,EAAE,QAAQ;CACxB,CAAC;AAEF,MAAM,OAAO,GAAG,CAAC,OAA4B,EAAqD,EAAE,CAClG,OAAO,YAAY,mBAAmB,IAAI,OAAO,YAAY,gBAAgB,CAAC;AAEhF,IAAI,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;IAChF,MAAM,wBAAyB,SAAQ,WAAW;QAAlD;;YAgBU,iBAAY,GAAG,CAAC,CAAC;YAYR,Y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iBAAiB;YACvB,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;YACvB,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;YAC5D,IAAI,CAAC,KAAK,IAAI,CAAC,MAAM;gBAAE,OAAO;YAC9B,IAAI,KAAK,CAAC,KAAK,KAAK,IAAI,CAAC,kBAAkB;gBAAE,OAAO;YACpD,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`, `characters-at-limit`, `characters-over-limit`, `words-under-limit`,\n * `words-at-limit`, `words-over-limit`: the messages, English by default, with `%{count}` for\n * the number. Add a plural form to the name, such as `characters-under-limit-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 { onPropertySet } from '../utils/on-property-set.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\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 = onPropertySet(input, 'value', () => this.update());\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
+ charactersUnderLimit?: Translation;
17
+ /** Shown at the limit. */
18
+ charactersAtLimit?: Translation;
19
+ /** Shown while over the limit. `%{count}` is the number too many. */
20
+ charactersOverLimit?: Translation;
21
+ /** Shown while under the limit when counting words. `%{count}` is the number left. */
22
+ wordsUnderLimit?: Translation;
23
+ /** Shown at the limit when counting words. */
24
+ wordsAtLimit?: Translation;
25
+ /** Shown while over the limit when counting words. `%{count}` is the number too many. */
26
+ wordsOverLimit?: 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, charactersUnderLimit, charactersAtLimit, charactersOverLimit, wordsUnderLimit, wordsAtLimit, wordsOverLimit, 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, charactersUnderLimit, charactersAtLimit, charactersOverLimit, wordsUnderLimit, wordsAtLimit, wordsOverLimit, hiddenDescriptionClass, withinLimitClass, overLimitClass, belowThresholdClass, inputOverLimitClass, ...props }) {
12
+ const element = useRef(null);
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,
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', 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),
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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,MAAM,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;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 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"]}
@@ -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", "characters-at-limit", "characters-over-limit", "words-under-limit", "words-at-limit", "words-over-limit"];
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
+ };