@joniguerini/lume 0.0.0-stage → 1.9.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 (226) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +62 -2
  3. package/base.css +165 -0
  4. package/bin/lumeui.mjs +163 -0
  5. package/components/alert.css +156 -0
  6. package/components/banner.css +98 -0
  7. package/components/button.css +291 -0
  8. package/components/calendar.css +532 -0
  9. package/components/carousel.css +175 -0
  10. package/components/chart.css +813 -0
  11. package/components/chat.css +670 -0
  12. package/components/checkbox.css +212 -0
  13. package/components/chip.css +224 -0
  14. package/components/code.css +36 -0
  15. package/components/color-picker.css +192 -0
  16. package/components/command.css +148 -0
  17. package/components/content.css +211 -0
  18. package/components/editor.css +174 -0
  19. package/components/feedback.css +320 -0
  20. package/components/filters.css +103 -0
  21. package/components/form.css +455 -0
  22. package/components/image-viewer.css +237 -0
  23. package/components/layers.css +138 -0
  24. package/components/link.css +87 -0
  25. package/components/loading.css +260 -0
  26. package/components/menu.css +180 -0
  27. package/components/modal.css +209 -0
  28. package/components/navigation.css +507 -0
  29. package/components/notifications.css +186 -0
  30. package/components/number-field.css +52 -0
  31. package/components/otp.css +119 -0
  32. package/components/panel.css +208 -0
  33. package/components/picker.css +207 -0
  34. package/components/rating.css +143 -0
  35. package/components/resizable.css +173 -0
  36. package/components/scrollbar.css +110 -0
  37. package/components/select.css +477 -0
  38. package/components/shell.css +837 -0
  39. package/components/slider.css +189 -0
  40. package/components/sortable.css +287 -0
  41. package/components/surfaces.css +182 -0
  42. package/components/switch.css +115 -0
  43. package/components/table.css +228 -0
  44. package/components/tabs.css +190 -0
  45. package/components/tags.css +83 -0
  46. package/components/toast.css +164 -0
  47. package/components/toolbar.css +80 -0
  48. package/components/upload.css +181 -0
  49. package/ds.css +48 -0
  50. package/fonts/Geist-LICENSE.txt +92 -0
  51. package/fonts/Geist-Variable.woff2 +0 -0
  52. package/fonts/GeistSerif-Regular.woff2 +0 -0
  53. package/fonts/JetBrainsMono-LICENSE.txt +93 -0
  54. package/fonts/JetBrainsMono-Variable.woff2 +0 -0
  55. package/fonts.css +29 -0
  56. package/icons/icons.d.ts +5 -0
  57. package/icons/icons.js +266 -0
  58. package/js/back-to-top.d.ts +2 -0
  59. package/js/back-to-top.js +62 -0
  60. package/js/banner.js +87 -0
  61. package/js/calendar.d.ts +3 -0
  62. package/js/calendar.js +472 -0
  63. package/js/carousel.d.ts +2 -0
  64. package/js/carousel.js +258 -0
  65. package/js/charts/bar.js +361 -0
  66. package/js/charts/core.js +604 -0
  67. package/js/charts/donut.js +206 -0
  68. package/js/charts/figures.js +97 -0
  69. package/js/charts/heatmap.js +410 -0
  70. package/js/charts/line.js +268 -0
  71. package/js/charts/scatter.js +211 -0
  72. package/js/charts.d.ts +12 -0
  73. package/js/charts.js +27 -0
  74. package/js/code-block.d.ts +3 -0
  75. package/js/code-block.js +32 -0
  76. package/js/color-picker.d.ts +4 -0
  77. package/js/color-picker.js +448 -0
  78. package/js/command-palette.js +233 -0
  79. package/js/composer.js +573 -0
  80. package/js/context-menu.d.ts +2 -0
  81. package/js/context-menu.js +154 -0
  82. package/js/date-picker.d.ts +2 -0
  83. package/js/date-picker.js +430 -0
  84. package/js/drawer.js +48 -0
  85. package/js/editor.d.ts +5 -0
  86. package/js/editor.js +615 -0
  87. package/js/field-support.js +77 -0
  88. package/js/file-upload.d.ts +2 -0
  89. package/js/file-upload.js +230 -0
  90. package/js/filters.js +266 -0
  91. package/js/form.d.ts +2 -0
  92. package/js/form.js +409 -0
  93. package/js/i18n.d.ts +14 -0
  94. package/js/i18n.js +83 -0
  95. package/js/image-viewer.d.ts +4 -0
  96. package/js/image-viewer.js +275 -0
  97. package/js/menu.d.ts +4 -0
  98. package/js/menu.js +237 -0
  99. package/js/messages.js +908 -0
  100. package/js/modal.d.ts +7 -0
  101. package/js/modal.js +183 -0
  102. package/js/notifications.d.ts +4 -0
  103. package/js/notifications.js +204 -0
  104. package/js/number-field.d.ts +2 -0
  105. package/js/number-field.js +175 -0
  106. package/js/otp-field.d.ts +2 -0
  107. package/js/otp-field.js +107 -0
  108. package/js/pagination.d.ts +3 -0
  109. package/js/pagination.js +143 -0
  110. package/js/popover.d.ts +2 -0
  111. package/js/popover.js +155 -0
  112. package/js/progress-ring.js +48 -0
  113. package/js/rating.d.ts +3 -0
  114. package/js/rating.js +130 -0
  115. package/js/resizable.d.ts +2 -0
  116. package/js/resizable.js +311 -0
  117. package/js/scrollbar.d.ts +2 -0
  118. package/js/scrollbar.js +273 -0
  119. package/js/segmented.js +60 -0
  120. package/js/select.d.ts +3 -0
  121. package/js/select.js +784 -0
  122. package/js/shell.d.ts +6 -0
  123. package/js/shell.js +373 -0
  124. package/js/slider.d.ts +2 -0
  125. package/js/slider.js +89 -0
  126. package/js/sortable.d.ts +5 -0
  127. package/js/sortable.js +463 -0
  128. package/js/stepper.d.ts +2 -0
  129. package/js/stepper.js +72 -0
  130. package/js/tabs.js +99 -0
  131. package/js/tag-field.d.ts +2 -0
  132. package/js/tag-field.js +177 -0
  133. package/js/theme.d.ts +9 -0
  134. package/js/theme.js +114 -0
  135. package/js/time-picker.d.ts +2 -0
  136. package/js/time-picker.js +279 -0
  137. package/js/toast.d.ts +17 -0
  138. package/js/toast.js +171 -0
  139. package/js/toolbar.d.ts +2 -0
  140. package/js/toolbar.js +107 -0
  141. package/js/tooltip.d.ts +2 -0
  142. package/js/tooltip.js +208 -0
  143. package/js/tree.d.ts +2 -0
  144. package/js/tree.js +168 -0
  145. package/lume.css +11574 -0
  146. package/lume.d.ts +104 -0
  147. package/lume.js +67 -0
  148. package/package.json +66 -4
  149. package/react/Alert.d.ts +24 -0
  150. package/react/Alert.js +21 -0
  151. package/react/AppShell.d.ts +67 -0
  152. package/react/AppShell.js +94 -0
  153. package/react/Avatar.d.ts +39 -0
  154. package/react/Avatar.js +40 -0
  155. package/react/Badge.d.ts +17 -0
  156. package/react/Badge.js +10 -0
  157. package/react/Button.d.ts +32 -0
  158. package/react/Button.js +17 -0
  159. package/react/Calendar.d.ts +48 -0
  160. package/react/Calendar.js +67 -0
  161. package/react/Carousel.d.ts +30 -0
  162. package/react/Carousel.js +38 -0
  163. package/react/Charts.d.ts +186 -0
  164. package/react/Charts.js +58 -0
  165. package/react/Chip.d.ts +34 -0
  166. package/react/Chip.js +26 -0
  167. package/react/Choice.d.ts +72 -0
  168. package/react/Choice.js +51 -0
  169. package/react/ColorPicker.d.ts +43 -0
  170. package/react/ColorPicker.js +73 -0
  171. package/react/Content.d.ts +58 -0
  172. package/react/Content.js +42 -0
  173. package/react/Controls.d.ts +97 -0
  174. package/react/Controls.js +118 -0
  175. package/react/Editor.d.ts +28 -0
  176. package/react/Editor.js +57 -0
  177. package/react/Field.d.ts +90 -0
  178. package/react/Field.js +65 -0
  179. package/react/Form.d.ts +36 -0
  180. package/react/Form.js +45 -0
  181. package/react/Icon.d.ts +13 -0
  182. package/react/Icon.js +8 -0
  183. package/react/IconButton.d.ts +19 -0
  184. package/react/IconButton.js +12 -0
  185. package/react/ImageViewer.d.ts +20 -0
  186. package/react/ImageViewer.js +22 -0
  187. package/react/InlineAction.d.ts +15 -0
  188. package/react/InlineAction.js +12 -0
  189. package/react/Layers.d.ts +118 -0
  190. package/react/Layers.js +115 -0
  191. package/react/Link.d.ts +32 -0
  192. package/react/Link.js +26 -0
  193. package/react/Loading.d.ts +67 -0
  194. package/react/Loading.js +49 -0
  195. package/react/Navigation.d.ts +181 -0
  196. package/react/Navigation.js +197 -0
  197. package/react/Notices.d.ts +43 -0
  198. package/react/Notices.js +89 -0
  199. package/react/Panel.d.ts +57 -0
  200. package/react/Panel.js +33 -0
  201. package/react/Pickers.d.ts +83 -0
  202. package/react/Pickers.js +70 -0
  203. package/react/Rating.d.ts +39 -0
  204. package/react/Rating.js +41 -0
  205. package/react/Resizable.d.ts +44 -0
  206. package/react/Resizable.js +30 -0
  207. package/react/Select.d.ts +53 -0
  208. package/react/Select.js +79 -0
  209. package/react/Sortable.d.ts +52 -0
  210. package/react/Sortable.js +113 -0
  211. package/react/Table.d.ts +60 -0
  212. package/react/Table.js +34 -0
  213. package/react/Toolbar.d.ts +45 -0
  214. package/react/Toolbar.js +45 -0
  215. package/react/cx.d.ts +2 -0
  216. package/react/cx.js +5 -0
  217. package/react/icon-names.d.ts +1 -0
  218. package/react/icon-names.js +2 -0
  219. package/react/index.d.ts +42 -0
  220. package/react/index.js +52 -0
  221. package/react/useController.d.ts +8 -0
  222. package/react/useController.js +16 -0
  223. package/react/useLocale.d.ts +5 -0
  224. package/react/useLocale.js +15 -0
  225. package/tokens.css +739 -0
  226. package/tokens.js +4911 -0
package/js/form.js ADDED
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Validação de formulários — acessível, em português e sem pressa.
3
+ *
4
+ * const form = createForm(document.querySelector('#projeto'), {
5
+ * rules: { slug: (value) => (taken.has(value) ? 'Esse endereço já está em uso.' : null) },
6
+ * messages: { nome: { required: 'Dê um nome ao projeto.' } },
7
+ * onSubmit: (data) => salvar(data),
8
+ * });
9
+ * form.validate(); // valida tudo e mostra os erros (sem mover o foco); devolve true/false
10
+ * form.reset(); // limpa valores, erros e o resumo
11
+ * form.destroy();
12
+ *
13
+ * Quando valida (validateOn):
14
+ * 'blur' (padrão) — ao sair de um campo em que a pessoa digitou algo; listas e escolhas, ao mudar
15
+ * 'submit' — só ao enviar
16
+ * 'input' — a cada tecla (evite: acusa erro antes de a pessoa terminar)
17
+ * Em qualquer modo, um campo com erro é revalidado enquanto a pessoa corrige — o erro some na hora.
18
+ *
19
+ * Regras nativas: required, type="email" | "url" | "number", minlength, maxlength, min, max, pattern.
20
+ * Mensagens próprias por campo: data-error-required, data-error-email, data-error-pattern… ou `messages`.
21
+ * Grupos de checkbox: data-min="2" no <fieldset> pede pelo menos N marcados.
22
+ *
23
+ * Acessibilidade: aria-invalid, erro ligado por aria-describedby, ícone + texto (nunca só cor),
24
+ * resumo no topo que recebe o foco no envio, com links que levam a cada campo.
25
+ */
26
+ import { icon } from '../icons/icons.js';
27
+ import { createSelect } from './select.js';
28
+ import { msg } from './i18n.js';
29
+
30
+ const escape = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
31
+ let uid = 0;
32
+
33
+ const SKIP = new Set(['submit', 'button', 'reset', 'hidden', 'image', 'file']);
34
+
35
+ const DEFAULTS = {
36
+ required: (f) => msg(f.kind === 'select' || f.kind === 'radio' ? 'form.requiredChoice' : f.kind === 'check' ? 'form.requiredCheck' : f.kind === 'group' ? 'form.requiredGroup' : 'form.required'),
37
+ email: () => msg('form.email'),
38
+ url: () => msg('form.url'),
39
+ number: () => msg('form.number'),
40
+ minlength: (f, v) => msg('form.minlength', f.el.minLength, f.el.minLength - v.length),
41
+ maxlength: (f, v) => msg('form.maxlength', f.max, v.length - f.max),
42
+ min: (f) => msg('form.min', f.el.min),
43
+ max: (f) => msg('form.max', f.el.max),
44
+ pattern: (f) => f.el.title || msg('form.pattern'),
45
+ groupMin: (f) => msg('form.groupMin', f.min),
46
+ };
47
+
48
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
49
+
50
+ export function createForm(form, options = {}) {
51
+ const o = { validateOn: 'blur', summary: true, ...options };
52
+ const rules = o.rules ?? {};
53
+ const messages = o.messages ?? {};
54
+ form.noValidate = true;
55
+
56
+ const touched = new Set();
57
+ const errors = new Map(); // name → { field, message }
58
+ let submitted = false;
59
+ let summaryEl = null;
60
+ const fieldCache = new Map();
61
+ const formId = form.id || `ds-form-${++uid}`;
62
+
63
+ /* ───────── Campos ───────── */
64
+
65
+ const textOf = (label) => {
66
+ const choice = label.querySelector('.ds-choice__label');
67
+ if (choice) return choice.textContent.trim();
68
+ const clone = label.cloneNode(true);
69
+ clone.querySelectorAll('.ds-form-field__optional, .ds-visually-hidden').forEach((n) => n.remove());
70
+ return clone.textContent.trim();
71
+ };
72
+
73
+ const labelOf = (el) => {
74
+ // a seleção personalizada tira o "for" do rótulo e o liga ao gatilho
75
+ const trigger = el.matches('select[data-enhanced]') ? document.getElementById(`${el.id}-trigger`) : null;
76
+ const label = el.labels?.[0] ?? (trigger && document.getElementById(trigger.getAttribute('aria-labelledby'))) ?? el.closest('.ds-form-field')?.querySelector('.ds-form-field__label');
77
+ if (label) return textOf(label);
78
+ return el.getAttribute('aria-label') ?? el.name;
79
+ };
80
+
81
+ /** Um "campo" é um controle — ou um grupo de radios/checkboxes com o mesmo name. */
82
+ function fieldFor(el) {
83
+ const name = el.name || el.id;
84
+ if (fieldCache.has(name)) return fieldCache.get(name);
85
+ const all = [...form.elements].filter((x) => x.name && x.name === el.name);
86
+ let field;
87
+ if (el.type === 'radio' || (el.type === 'checkbox' && all.length > 1)) {
88
+ const group = el.closest('fieldset');
89
+ field = {
90
+ name,
91
+ kind: el.type === 'radio' ? 'radio' : 'group',
92
+ el: all[0],
93
+ inputs: all,
94
+ container: group,
95
+ required: all.some((x) => x.required) || group?.hasAttribute('data-required'),
96
+ min: Number(group?.dataset.min) || 0,
97
+ label: group?.querySelector('legend')?.textContent.trim() ?? labelOf(all[0]),
98
+ focusTarget: () => all.find((x) => x.checked) ?? all[0],
99
+ };
100
+ } else {
101
+ const kind = el.tagName === 'SELECT' ? 'select' : el.type === 'checkbox' ? 'check' : 'text';
102
+ const counter = el.closest('.ds-form-field')?.querySelector('.ds-form-field__counter');
103
+ field = {
104
+ name,
105
+ kind,
106
+ el,
107
+ inputs: [el],
108
+ container: el.closest('.ds-form-field'),
109
+ required: el.required,
110
+ max: Number(el.dataset.max) || (counter && el.maxLength > 0 ? el.maxLength : 0),
111
+ counter,
112
+ label: labelOf(el),
113
+ focusTarget: () => (el.matches('select[data-enhanced]') ? document.getElementById(`${el.id}-trigger`) ?? el : el),
114
+ };
115
+ }
116
+ field.describedby = field.kind === 'radio' || field.kind === 'group' ? field.container?.getAttribute('aria-describedby') ?? '' : field.el.getAttribute('aria-describedby') ?? '';
117
+ field.errorId = `${field.el.id || `ds-form-${++uid}`}-error`;
118
+ fieldCache.set(name, field);
119
+ return field;
120
+ }
121
+
122
+ const fields = () => {
123
+ const seen = new Set();
124
+ return [...form.elements]
125
+ .filter((el) => el.matches('input, select, textarea') && (el.name || el.id) && !SKIP.has(el.type) && !el.disabled && !el.closest('[data-form-ignore]'))
126
+ .map(fieldFor)
127
+ .filter((f) => !seen.has(f.name) && seen.add(f.name));
128
+ };
129
+
130
+ /* ───────── Regras ───────── */
131
+
132
+ const fieldMessage = (field, key, value) => {
133
+ const custom = messages[field.name]?.[key] ?? field.el.dataset[`error${key[0].toUpperCase()}${key.slice(1)}`] ?? (key === 'groupMin' ? field.container?.dataset.errorMin : undefined);
134
+ if (custom) return custom;
135
+ return DEFAULTS[key](field, value);
136
+ };
137
+
138
+ function check(field) {
139
+ const { el, kind } = field;
140
+ if (kind === 'radio') {
141
+ if (field.required && !field.inputs.some((x) => x.checked)) return fieldMessage(field, 'required');
142
+ } else if (kind === 'group') {
143
+ const n = field.inputs.filter((x) => x.checked).length;
144
+ if (field.required && !n) return fieldMessage(field, 'required');
145
+ if (field.min && n < field.min) return fieldMessage(field, 'groupMin');
146
+ } else if (kind === 'check') {
147
+ if (field.required && !el.checked) return fieldMessage(field, 'required');
148
+ } else {
149
+ // data-ds-invalid: erro de formato que o próprio campo já detectou; data-ds-filled: o valor está fora do input (tags)
150
+ if (el.dataset.dsInvalid) return el.dataset.dsInvalid;
151
+ const value = kind === 'select' && el.multiple ? [...el.selectedOptions].map((x) => x.value).join(',') : el.value.trim();
152
+ if (el.dataset.dsFilled && !value) {
153
+ // tem valor: nada a conferir no texto vazio
154
+ } else if (!value) {
155
+ if (field.required) return fieldMessage(field, 'required');
156
+ } else if (kind === 'text') {
157
+ if (el.type === 'email' && !EMAIL.test(value)) return fieldMessage(field, 'email', value);
158
+ if (el.type === 'url' && !/^https?:\/\/\S+\.\S+/.test(value)) return fieldMessage(field, 'url', value);
159
+ if (el.type === 'number' && Number.isNaN(Number(value))) return fieldMessage(field, 'number', value);
160
+ if (el.minLength > 0 && value.length < el.minLength) return fieldMessage(field, 'minlength', value);
161
+ if (field.max && value.length > field.max) return fieldMessage(field, 'maxlength', value);
162
+ if (el.min !== '' && el.type === 'number' && Number(value) < Number(el.min)) return fieldMessage(field, 'min', value);
163
+ if (el.max !== '' && el.type === 'number' && Number(value) > Number(el.max)) return fieldMessage(field, 'max', value);
164
+ if (el.pattern && !new RegExp(`^(?:${el.pattern})$`, 'u').test(value)) return fieldMessage(field, 'pattern', value);
165
+ }
166
+ }
167
+ const custom = rules[field.name];
168
+ if (custom) {
169
+ for (const rule of [].concat(custom)) {
170
+ const result = rule(field.kind === 'text' || field.kind === 'select' ? field.el.value.trim() : field.inputs.filter((x) => x.checked).map((x) => x.value), field.el, form);
171
+ if (result) return result;
172
+ }
173
+ }
174
+ return null;
175
+ }
176
+
177
+ /* ───────── Mensagens na tela ───────── */
178
+
179
+ function setDescribedby(field, withError) {
180
+ const ids = [withError && field.errorId, field.describedby].filter(Boolean).join(' ');
181
+ const targets = field.kind === 'radio' || field.kind === 'group' ? [field.container].filter(Boolean) : field.inputs;
182
+ targets.forEach((t) => (ids ? t.setAttribute('aria-describedby', ids) : t.removeAttribute('aria-describedby')));
183
+ }
184
+
185
+ function showError(field, message) {
186
+ errors.set(field.name, { field, message });
187
+ field.inputs.forEach((x) => x.setAttribute('aria-invalid', 'true'));
188
+ setDescribedby(field, true);
189
+
190
+ let err = document.getElementById(field.errorId);
191
+ if (!err) {
192
+ err = document.createElement('p');
193
+ err.id = field.errorId;
194
+ if (field.kind === 'radio' || field.kind === 'group') {
195
+ err.className = 'ds-choice-group__error';
196
+ field.container?.append(err);
197
+ } else if (field.container) {
198
+ err.className = 'ds-form-field__error';
199
+ let footer = field.container.querySelector('.ds-form-field__footer');
200
+ if (!footer) {
201
+ footer = document.createElement('div');
202
+ footer.className = 'ds-form-field__footer';
203
+ field.container.append(footer);
204
+ }
205
+ footer.prepend(err);
206
+ } else {
207
+ err.className = 'ds-form-field__error ds-form__choice-error';
208
+ (field.el.closest('label') ?? field.el).after(err);
209
+ }
210
+ }
211
+ err.innerHTML = `${icon('alert-circle', { size: 16 })}<span>${escape(message)}</span>`;
212
+ // a dica dá lugar ao erro (continua ligada por aria-describedby)
213
+ hintsOf(field).forEach((h) => (h.hidden = true));
214
+ if (field.kind === 'select' && field.el.matches('[data-enhanced]')) createSelect(field.el).sync();
215
+ }
216
+
217
+ function clearError(field) {
218
+ if (!errors.has(field.name) && !document.getElementById(field.errorId)) return;
219
+ errors.delete(field.name);
220
+ field.inputs.forEach((x) => x.removeAttribute('aria-invalid'));
221
+ setDescribedby(field, false);
222
+ document.getElementById(field.errorId)?.remove();
223
+ hintsOf(field).forEach((h) => (h.hidden = false));
224
+ if (field.kind === 'select' && field.el.matches('[data-enhanced]')) createSelect(field.el).sync();
225
+ }
226
+
227
+ const hintsOf = (field) => [...(field.container?.querySelectorAll('.ds-form-field__hint, .ds-choice-group__hint') ?? [])];
228
+
229
+ function run(field) {
230
+ const message = check(field);
231
+ if (message) showError(field, message);
232
+ else clearError(field);
233
+ return !message;
234
+ }
235
+
236
+ /* ───────── Resumo ───────── */
237
+
238
+ function summaryHost() {
239
+ if (o.summary === false) return null;
240
+ if (o.summary instanceof Element) return o.summary;
241
+ return form.querySelector('[data-form-summary]');
242
+ }
243
+
244
+ function renderSummary() {
245
+ if (o.summary === false) return null;
246
+ if (!errors.size) {
247
+ summaryEl?.remove();
248
+ summaryEl = null;
249
+ return null;
250
+ }
251
+ const list = fields()
252
+ .filter((f) => errors.has(f.name))
253
+ .map((f) => `<li><a href="#${escape(f.focusTarget()?.id ?? '')}" data-form-error="${escape(f.name)}">${escape(f.label)}: ${escape(errors.get(f.name).message.replace(/\.$/, '').replace(/^./, (c) => c.toLowerCase()))}</a></li>`)
254
+ .join('');
255
+ const title = o.summaryTitle?.(errors.size) ?? msg('form.summary', errors.size);
256
+ if (!summaryEl) {
257
+ summaryEl = document.createElement('div');
258
+ summaryEl.className = 'ds-alert ds-alert--danger ds-form__summary';
259
+ summaryEl.tabIndex = -1;
260
+ summaryEl.setAttribute('role', 'group');
261
+ const host = summaryHost();
262
+ if (host) host.append(summaryEl);
263
+ else form.prepend(summaryEl);
264
+ }
265
+ const titleId = `${formId}-summary-title`;
266
+ summaryEl.setAttribute('aria-labelledby', titleId);
267
+ summaryEl.innerHTML = `<span class="ds-alert__icon">${icon('alert-circle', { size: 18 })}</span>
268
+ <div class="ds-alert__body">
269
+ <p class="ds-alert__title" id="${titleId}">${escape(title)}</p>
270
+ <ul class="ds-alert__list" role="list">${list}</ul>
271
+ </div>`;
272
+ return summaryEl;
273
+ }
274
+
275
+ /* ───────── Eventos ───────── */
276
+
277
+ const fieldOfEvent = (target) => {
278
+ if (!target?.matches?.('input, select, textarea') || target.form !== form || !(target.name || target.id) || SKIP.has(target.type)) return null;
279
+ return fieldFor(target);
280
+ };
281
+
282
+ function updateCounter(field) {
283
+ if (!field.counter || !field.max) return;
284
+ const len = field.el.value.length;
285
+ field.counter.textContent = `${len}/${field.max}`;
286
+ field.counter.toggleAttribute('data-over', len > field.max);
287
+ }
288
+
289
+ const onInput = (event) => {
290
+ const field = fieldOfEvent(event.target);
291
+ if (!field) return;
292
+ updateCounter(field);
293
+ if (field.kind !== 'text') return;
294
+ if (o.validateOn === 'input' || errors.has(field.name)) {
295
+ touched.add(field.name);
296
+ run(field);
297
+ if (summaryEl) renderSummary();
298
+ } else if (event.target.value) touched.add(field.name);
299
+ };
300
+
301
+ const onChange = (event) => {
302
+ const field = fieldOfEvent(event.target);
303
+ if (!field || field.kind === 'text') return;
304
+ touched.add(field.name);
305
+ if (o.validateOn !== 'submit' || errors.has(field.name) || submitted) run(field);
306
+ if (summaryEl) renderSummary();
307
+ };
308
+
309
+ const onFocusOut = (event) => {
310
+ const field = fieldOfEvent(event.target);
311
+ if (!field || field.kind !== 'text') return;
312
+ if (o.validateOn === 'blur' && (touched.has(field.name) || errors.has(field.name))) {
313
+ run(field);
314
+ if (summaryEl) renderSummary();
315
+ }
316
+ };
317
+
318
+ const onSubmit = (event) => {
319
+ event.preventDefault();
320
+ submitted = true;
321
+ const ok = validate();
322
+ if (!ok) {
323
+ const summary = renderSummary();
324
+ if (summary) {
325
+ summary.focus({ preventScroll: true });
326
+ summary.scrollIntoView({ block: 'center', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
327
+ } else {
328
+ const first = fields().find((f) => errors.has(f.name));
329
+ first?.focusTarget()?.focus();
330
+ }
331
+ o.onInvalid?.([...errors.values()].map(({ field, message }) => ({ name: field.name, label: field.label, message })));
332
+ return;
333
+ }
334
+ summaryEl?.remove();
335
+ summaryEl = null;
336
+ o.onSubmit?.(data(), form);
337
+ };
338
+
339
+ const onSummaryClick = (event) => {
340
+ const link = event.target.closest('[data-form-error]');
341
+ if (!link || !summaryEl?.contains(link)) return;
342
+ event.preventDefault();
343
+ const field = fieldCache.get(link.dataset.formError);
344
+ const target = field?.focusTarget();
345
+ if (!target) return;
346
+ target.focus({ preventScroll: true });
347
+ target.scrollIntoView({ block: 'center', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
348
+ };
349
+
350
+ const onReset = () => setTimeout(() => clearAll());
351
+
352
+ form.addEventListener('input', onInput);
353
+ form.addEventListener('change', onChange);
354
+ form.addEventListener('focusout', onFocusOut);
355
+ form.addEventListener('submit', onSubmit);
356
+ form.addEventListener('click', onSummaryClick);
357
+ form.addEventListener('reset', onReset);
358
+ fields().forEach(updateCounter);
359
+
360
+ /* ───────── API ───────── */
361
+
362
+ function data() {
363
+ const out = {};
364
+ for (const [key, value] of new FormData(form)) {
365
+ if (key in out) out[key] = [].concat(out[key], value);
366
+ else out[key] = value;
367
+ }
368
+ return out;
369
+ }
370
+
371
+ function validate() {
372
+ let ok = true;
373
+ fields().forEach((f) => {
374
+ touched.add(f.name);
375
+ if (!run(f)) ok = false;
376
+ });
377
+ if (summaryEl) renderSummary();
378
+ return ok;
379
+ }
380
+
381
+ function clearAll() {
382
+ fields().forEach(clearError);
383
+ errors.clear();
384
+ touched.clear();
385
+ submitted = false;
386
+ summaryEl?.remove();
387
+ summaryEl = null;
388
+ fields().forEach(updateCounter);
389
+ }
390
+
391
+ return {
392
+ validate,
393
+ data,
394
+ errors: () => [...errors.values()].map(({ field, message }) => ({ name: field.name, label: field.label, message })),
395
+ reset() {
396
+ form.reset();
397
+ clearAll();
398
+ },
399
+ destroy() {
400
+ clearAll();
401
+ form.removeEventListener('input', onInput);
402
+ form.removeEventListener('change', onChange);
403
+ form.removeEventListener('focusout', onFocusOut);
404
+ form.removeEventListener('submit', onSubmit);
405
+ form.removeEventListener('click', onSummaryClick);
406
+ form.removeEventListener('reset', onReset);
407
+ },
408
+ };
409
+ }
package/js/i18n.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ // Gerado por scripts/build-react.mjs. Não edite.
2
+ export type Locale = 'pt-BR' | 'en' | 'es';
3
+ export declare const LOCALES: Locale[];
4
+ export declare const LOCALE_NAMES: Record<Locale, string>;
5
+ export declare function getLocalePreference(): string;
6
+ export declare function systemLocale(): Locale;
7
+ export declare function locale(): Locale;
8
+ export declare function setLocale(preference: string, options?: { persist?: boolean }): void;
9
+ export declare function initLocale(): void;
10
+ export declare function tr<T>(text: T | Record<Locale, T>): T;
11
+ export declare function msg(key: string, ...args: unknown[]): string;
12
+ export declare function numberFormat(options?: Intl.NumberFormatOptions): Intl.NumberFormat;
13
+ export declare function dateFormat(options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat;
14
+ export declare function formatNumber(n: number, options?: Intl.NumberFormatOptions): string;
package/js/i18n.js ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Idioma: 'pt-BR', 'en' ou 'es' — ou 'system', que segue o idioma do sistema (o que o Lume não tiver vira inglês).
3
+ * Aplica em <html lang="…">, persiste em localStorage e avisa com o evento ds:localechange.
4
+ *
5
+ * msg('select.empty', 'abc') // texto de um componente do DS no idioma atual
6
+ * tr({ 'pt-BR': 'Olá', en: 'Hi', es: 'Hola' })
7
+ * numberFormat({ style: 'percent' }) // Intl no idioma atual
8
+ */
9
+ import { MESSAGES } from './messages.js';
10
+
11
+ const KEY = 'ds-locale';
12
+ export const LOCALES = ['pt-BR', 'en', 'es'];
13
+ export const LOCALE_NAMES = { 'pt-BR': 'Português', en: 'English', es: 'Español' };
14
+ const PREFERENCES = ['system', ...LOCALES];
15
+ const FALLBACK = 'en';
16
+ // no servidor (renderização no servidor) não há documento: o idioma fica no padrão até o navegador assumir
17
+ const BROWSER = typeof document !== 'undefined';
18
+ const root = BROWSER ? document.documentElement : null;
19
+
20
+ export function getLocalePreference() {
21
+ try {
22
+ const saved = localStorage.getItem(KEY);
23
+ if (PREFERENCES.includes(saved)) return saved;
24
+ } catch {}
25
+ return 'system';
26
+ }
27
+
28
+ /** O primeiro idioma do sistema que o Lume tem; senão, inglês. */
29
+ export function systemLocale() {
30
+ const nav = typeof navigator === 'undefined' ? {} : navigator;
31
+ for (const tag of nav.languages?.length ? nav.languages : [nav.language]) {
32
+ const lang = String(tag).toLowerCase();
33
+ if (lang.startsWith('pt')) return 'pt-BR';
34
+ if (lang.startsWith('es')) return 'es';
35
+ if (lang.startsWith('en')) return 'en';
36
+ }
37
+ return FALLBACK;
38
+ }
39
+
40
+ const resolve = (preference) => (preference === 'system' ? systemLocale() : preference);
41
+ let current = resolve(getLocalePreference());
42
+
43
+ export const locale = () => current;
44
+
45
+ export function setLocale(preference, { persist = true } = {}) {
46
+ if (!PREFERENCES.includes(preference)) return;
47
+ if (persist) {
48
+ try {
49
+ localStorage.setItem(KEY, preference);
50
+ } catch {}
51
+ }
52
+ current = resolve(preference);
53
+ if (!root) return;
54
+ root.lang = current;
55
+ root.dispatchEvent(new CustomEvent('ds:localechange', { detail: { preference, locale: current } }));
56
+ }
57
+
58
+ export function initLocale() {
59
+ if (root) root.lang = current;
60
+ }
61
+
62
+ // quem segue o sistema acompanha a troca de idioma do navegador
63
+ if (BROWSER) {
64
+ addEventListener('languagechange', () => {
65
+ if (getLocalePreference() === 'system' && systemLocale() !== current) setLocale('system', { persist: false });
66
+ });
67
+ }
68
+
69
+ /** Texto do idioma atual num objeto { 'pt-BR', en, es }; qualquer outro valor volta como veio. */
70
+ export function tr(text) {
71
+ if (text && typeof text === 'object' && !Array.isArray(text) && 'pt-BR' in text) return text[current] ?? text[FALLBACK] ?? text['pt-BR'];
72
+ return text;
73
+ }
74
+
75
+ /** Texto de um componente do DS. Mensagens com valores são funções: msg('form.min', 3). */
76
+ export function msg(key, ...args) {
77
+ const value = MESSAGES[current]?.[key] ?? MESSAGES[FALLBACK][key] ?? key;
78
+ return typeof value === 'function' ? value(...args) : value;
79
+ }
80
+
81
+ export const numberFormat = (options) => new Intl.NumberFormat(current, options);
82
+ export const dateFormat = (options) => new Intl.DateTimeFormat(current, options);
83
+ export const formatNumber = (n, options) => numberFormat(options).format(n);
@@ -0,0 +1,4 @@
1
+ // Gerado por scripts/build-react.mjs. Não edite.
2
+ export interface ViewerImage { src: string; alt?: string; caption?: string }
3
+ export declare function openImageViewer(images: Array<ViewerImage | string>, options?: { index?: number; onChange?: (index: number) => void; onClose?: () => void }): { el: HTMLDialogElement; readonly index: number; readonly zoom: number; goTo(index: number): void; next(): void; prev(): void; zoomIn(): void; zoomOut(): void; fit(): void; close(): void };
4
+ export declare function mountImageViewer(area?: ParentNode & EventTarget, options?: { selector?: string; onChange?: (index: number) => void; onClose?: () => void }): () => void;