@glueforms/react 0.0.0-stage → 0.2.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.
@@ -0,0 +1,557 @@
1
+ import { nativeSelectable } from "./shared/native.js";
2
+ import * as React from "react";
3
+ import { acquire } from "./shared/ownership.js";
4
+ import {
5
+ copy,
6
+ civil,
7
+ iso,
8
+ parse,
9
+ today,
10
+ bounds,
11
+ inBounds,
12
+ bounded,
13
+ monthDate,
14
+ canNavigate,
15
+ monthValues,
16
+ keyDate,
17
+ language,
18
+ formats,
19
+ navigation,
20
+ } from "./shared/dates.js";
21
+ const { useRef, useState, useEffect, useId, useImperativeHandle, forwardRef } =
22
+ React;
23
+ function Icon({ path }) {
24
+ return (
25
+ <svg
26
+ viewBox="0 0 24 24"
27
+ fill="none"
28
+ stroke="currentColor"
29
+ strokeWidth="2"
30
+ strokeLinecap="round"
31
+ strokeLinejoin="round"
32
+ aria-hidden="true"
33
+ focusable="false"
34
+ >
35
+ <path d={path} />
36
+ </svg>
37
+ );
38
+ }
39
+ export const DateField = forwardRef(function DateField(props, forwardedRef) {
40
+ const {
41
+ appearance = "native",
42
+ datePolicy = "any",
43
+ value,
44
+ defaultValue,
45
+ onChange,
46
+ onValueChange,
47
+ min,
48
+ max,
49
+ step,
50
+ ...native
51
+ } = props;
52
+ const controlled = value !== undefined;
53
+ const probe = useRef(null),
54
+ inputRef = useRef(null),
55
+ scope = useRef(null),
56
+ latest = useRef(props),
57
+ mounted = useRef(false),
58
+ sync = useRef(() => {}),
59
+ constraint = useRef(""),
60
+ boundsKey = useRef(null),
61
+ previous = useRef(controlled ? value : defaultValue || ""),
62
+ focusTarget = useRef("");
63
+ latest.current = props;
64
+
65
+ const [internal, setInternal] = useState(defaultValue || ""),
66
+ [facts, setFacts] = useState(null),
67
+ [display, setDisplay] = useState(null),
68
+ [cursor, setCursor] = useState(""),
69
+ [announcement, setAnnouncement] = useState("");
70
+ const titleId = useId();
71
+ useImperativeHandle(forwardedRef, () => inputRef.current, []);
72
+ const selected = controlled ? value : internal;
73
+ const range = facts?.range || {
74
+ min: parse(min) ? min : "",
75
+ max: parse(max) ? max : "",
76
+ };
77
+ const locale = facts?.locale || "en",
78
+ words = copy[locale],
79
+ format = formats(locale);
80
+ function propose(next, reason) {
81
+ const p = latest.current,
82
+ input = inputRef.current;
83
+ if (!input || input.readOnly || input.matches(":disabled")) return;
84
+ const current = p.value !== undefined ? p.value : input.value;
85
+ if (next === current) return;
86
+ if (p.value === undefined) {
87
+ input.value = next;
88
+ previous.current = next;
89
+ setInternal(next);
90
+ }
91
+ p.onValueChange?.(next, reason);
92
+ setAnnouncement(
93
+ next
94
+ ? copy[
95
+ language(
96
+ input.closest("[lang]")?.getAttribute("lang") ||
97
+ input.ownerDocument.documentElement.lang,
98
+ )
99
+ ][9] + formats(locale).full.format(parse(next))
100
+ : words[8],
101
+ );
102
+ }
103
+ sync.current = (options = {}) => {
104
+ const input = inputRef.current;
105
+ if (!mounted.current || !input) return;
106
+ const p = latest.current,
107
+ doc = input.ownerDocument;
108
+ const day = today(),
109
+ nextRange = bounds(p.min, p.max, p.datePolicy, day);
110
+ const lang = language(
111
+ input.closest("[lang]")?.getAttribute("lang") || doc.documentElement.lang,
112
+ );
113
+ const locked = input.readOnly || input.matches(":disabled");
114
+ const nextFacts = { range: nextRange, day: iso(day), locale: lang, locked };
115
+ // Update native constraints before the browser's synchronous submission validation.
116
+ const effective = nextRange.min || p.min;
117
+ if (effective === undefined) input.removeAttribute("min");
118
+ else if (input.getAttribute("min") !== effective)
119
+ input.setAttribute("min", effective);
120
+ setFacts((old) =>
121
+ JSON.stringify(old) === JSON.stringify(nextFacts) ? old : nextFacts,
122
+ );
123
+ const current = p.value !== undefined ? p.value : input.value;
124
+ if (p.value === undefined) {
125
+ previous.current = current;
126
+ setInternal((old) => (old === current ? old : current));
127
+ }
128
+ const tuple = JSON.stringify([current, nextRange.min, nextRange.max]);
129
+ const signature = JSON.stringify([nextRange.min, nextRange.max]);
130
+ const constraintsChanged = boundsKey.current !== signature || options.reset;
131
+ if (!locked) boundsKey.current = signature;
132
+ if (current && !inBounds(current, nextRange) && !locked) {
133
+ if (
134
+ p.value === undefined
135
+ ? constraintsChanged
136
+ : constraint.current !== tuple
137
+ ) {
138
+ constraint.current = tuple;
139
+ propose("", "constraint");
140
+ setAnnouncement(copy[lang][10]);
141
+ }
142
+ } else constraint.current = "";
143
+ setDisplay((old) => {
144
+ const anchor = bounded(current || iso(day), nextRange);
145
+ if (!old) return parse(anchor) || day;
146
+ const start = iso(civil(old.getFullYear(), old.getMonth(), 1)),
147
+ end = iso(civil(old.getFullYear(), old.getMonth() + 1, 0));
148
+ return anchor &&
149
+ ((nextRange.min && end < nextRange.min) ||
150
+ (nextRange.max && start > nextRange.max))
151
+ ? parse(anchor)
152
+ : old;
153
+ });
154
+ };
155
+ useEffect(() => {
156
+ const input = inputRef.current,
157
+ root = scope.current;
158
+ const owner = acquire(root, "react", (doc, win, release) => {
159
+ const controller = new win.AbortController(),
160
+ pending = new Set();
161
+ const listen = (target, type, handler, capture = false) =>
162
+ win.EventTarget.prototype.addEventListener.call(target, type, handler, {
163
+ signal: controller.signal,
164
+ capture,
165
+ });
166
+ mounted.current = true;
167
+ probe.current = doc.createElement("input");
168
+ const refresh = () => sync.current();
169
+ listen(win, "focus", refresh);
170
+ listen(doc, "visibilitychange", () => {
171
+ if (!doc.hidden) refresh();
172
+ });
173
+ listen(input, "focus", refresh);
174
+ const observer = new win.MutationObserver((records) => {
175
+ if (
176
+ records.some(
177
+ (r) =>
178
+ r.target === input ||
179
+ r.target.matches?.("fieldset") ||
180
+ r.attributeName === "lang",
181
+ )
182
+ )
183
+ refresh();
184
+ });
185
+ observer.observe(doc.documentElement, {
186
+ subtree: true,
187
+ attributes: true,
188
+ attributeFilter: ["disabled", "readonly", "lang"],
189
+ });
190
+ let day = iso(today());
191
+ const timer = win.setInterval(() => {
192
+ const next = iso(today());
193
+ if (next !== day) {
194
+ day = next;
195
+ refresh();
196
+ }
197
+ }, 30000);
198
+ const form = input.form;
199
+ if (form) {
200
+ const validate = (event, submitter) => {
201
+ refresh();
202
+ if (
203
+ !win.Element.prototype.hasAttribute.call(form, "novalidate") &&
204
+ !submitter?.formNoValidate &&
205
+ !win.HTMLFormElement.prototype.checkValidity.call(form)
206
+ ) {
207
+ event.preventDefault();
208
+ event.stopImmediatePropagation();
209
+ win.HTMLFormElement.prototype.reportValidity.call(form);
210
+ }
211
+ };
212
+ listen(
213
+ form,
214
+ "click",
215
+ (event) => {
216
+ const target = event.target.closest?.("button,input");
217
+ if (
218
+ target?.form === form &&
219
+ ["submit", "image"].includes(target.type)
220
+ )
221
+ validate(event, target);
222
+ },
223
+ true,
224
+ );
225
+ listen(
226
+ form,
227
+ "keydown",
228
+ (event) => {
229
+ if (
230
+ event.key === "Enter" &&
231
+ event.target.matches?.(
232
+ "input:not([type=button]):not([type=reset])",
233
+ )
234
+ )
235
+ validate(
236
+ event,
237
+ ["submit", "image"].includes(event.target.type)
238
+ ? event.target
239
+ : Array.from(
240
+ Object.getOwnPropertyDescriptor(
241
+ win.HTMLFormElement.prototype,
242
+ "elements",
243
+ ).get.call(form),
244
+ ).find(
245
+ (el) =>
246
+ ["submit", "image"].includes(el.type) && !el.disabled,
247
+ ),
248
+ );
249
+ },
250
+ true,
251
+ );
252
+ listen(
253
+ form,
254
+ "submit",
255
+ (event) => validate(event, event.submitter),
256
+ true,
257
+ );
258
+ listen(form, "reset", (event) => {
259
+ const token = win.setTimeout(() => {
260
+ pending.delete(token);
261
+ if (!mounted.current || event.defaultPrevented) return;
262
+ const p = latest.current;
263
+ if (p.value !== undefined) input.value = p.value;
264
+ setAnnouncement("");
265
+ setCursor("");
266
+ sync.current({ reset: true });
267
+ }, 0);
268
+ pending.add(token);
269
+ });
270
+ }
271
+ refresh();
272
+ return {
273
+ dispose() {
274
+ mounted.current = false;
275
+ controller.abort();
276
+ observer.disconnect();
277
+ win.clearInterval(timer);
278
+ for (const token of pending) win.clearTimeout(token);
279
+ pending.clear();
280
+ release();
281
+ },
282
+ };
283
+ });
284
+ return () => owner.dispose();
285
+ }, [native.form]);
286
+ useEffect(() => {
287
+ sync.current();
288
+ }, [
289
+ min,
290
+ max,
291
+ step,
292
+ datePolicy,
293
+ value,
294
+ defaultValue,
295
+ native.disabled,
296
+ native.readOnly,
297
+ native.lang,
298
+ appearance,
299
+ ]);
300
+ useEffect(() => {
301
+ if (focusTarget.current) {
302
+ const target = scope.current?.querySelector(
303
+ '[data-gf-date="' + focusTarget.current + '"]',
304
+ );
305
+ focusTarget.current = "";
306
+ if (target && !target.disabled) target.focus();
307
+ }
308
+ }, [cursor, display, facts, selected]);
309
+ function changed(event) {
310
+ const old = previous.current;
311
+ sync.current();
312
+ const next = event.currentTarget.value;
313
+ previous.current = next;
314
+ if (!controlled) setInternal(next);
315
+ if (parse(next)) {
316
+ setCursor(next);
317
+ setDisplay(parse(next));
318
+ }
319
+ const currentRange = bounds(min, max, datePolicy);
320
+ if (
321
+ JSON.stringify([currentRange.min, currentRange.max]) === boundsKey.current
322
+ ) {
323
+ constraint.current = JSON.stringify([
324
+ next,
325
+ currentRange.min,
326
+ currentRange.max,
327
+ ]);
328
+ }
329
+ onChange?.(event);
330
+ if (next !== old) onValueChange?.(next, "input");
331
+ }
332
+ useEffect(() => {
333
+ previous.current = selected;
334
+ }, [selected]);
335
+ const active = facts ? display || parse(selected) : null,
336
+ values = active ? monthValues(active) : [];
337
+ const allowed = (next) =>
338
+ nativeSelectable(
339
+ probe.current,
340
+ next,
341
+ range,
342
+ step,
343
+ defaultValue ?? (controlled ? value : ""),
344
+ );
345
+ const focusValue =
346
+ values.includes(cursor) && allowed(cursor) ? cursor : values.find(allowed);
347
+ function choose(next) {
348
+ sync.current();
349
+ const p = latest.current;
350
+ const currentRange = bounds(p.min, p.max, p.datePolicy);
351
+ if (
352
+ next &&
353
+ !nativeSelectable(
354
+ probe.current,
355
+ next,
356
+ currentRange,
357
+ p.step,
358
+ p.defaultValue ?? (p.value !== undefined ? p.value : ""),
359
+ )
360
+ )
361
+ return;
362
+ propose(next, next ? "selection" : "clear");
363
+ if (next) {
364
+ setCursor(next);
365
+ setDisplay(parse(next));
366
+ focusTarget.current = next;
367
+ } else inputRef.current.focus();
368
+ }
369
+ function key(event) {
370
+ sync.current();
371
+ const date = keyDate(
372
+ event.currentTarget.getAttribute("data-gf-date"),
373
+ event.key,
374
+ event.shiftKey,
375
+ );
376
+ if (!date) return;
377
+ event.preventDefault();
378
+ let next = bounded(iso(date), range);
379
+ if (!next) return;
380
+ const direction =
381
+ next < event.currentTarget.getAttribute("data-gf-date") ? -1 : 1;
382
+ for (let i = 0; i < 366 && !allowed(next) && inBounds(next, range); i++) {
383
+ const d = parse(next);
384
+ next = iso(civil(d.getFullYear(), d.getMonth(), d.getDate() + direction));
385
+ }
386
+ if (!allowed(next)) return;
387
+ setCursor(next);
388
+ setDisplay(parse(next));
389
+ focusTarget.current = next;
390
+ }
391
+ const label =
392
+ facts &&
393
+ (native["aria-label"] ||
394
+ Array.from(inputRef.current?.labels || [], (label) =>
395
+ label.textContent.trim(),
396
+ ).join(" ") ||
397
+ words[11]);
398
+ return (
399
+ <div ref={scope} data-gf-react-date-field="">
400
+ <input
401
+ {...native}
402
+ type="date"
403
+ ref={inputRef}
404
+ min={facts ? range.min || min : min}
405
+ max={max}
406
+ step={step}
407
+ value={controlled ? value : undefined}
408
+ defaultValue={controlled ? undefined : defaultValue}
409
+ onChange={changed}
410
+ />
411
+ {facts && appearance === "calendar" && active && (
412
+ <div className="gf-calendar" role="group" aria-label={label}>
413
+ <div className="gf-calendar-header">
414
+ <div className="gf-calendar-nav">
415
+ {navigation.slice(0, 2).map(([offset, index, path]) => (
416
+ <button
417
+ type="button"
418
+ className="gf-calendar-nav-button"
419
+ key={offset}
420
+ aria-label={words[index]}
421
+ title={words[index]}
422
+ disabled={facts.locked || !canNavigate(active, offset, range)}
423
+ onClick={() => {
424
+ sync.current();
425
+ const next = monthDate(active, offset);
426
+ setDisplay(next);
427
+ setCursor(bounded(iso(next), range));
428
+ }}
429
+ >
430
+ <Icon path={path} />
431
+ </button>
432
+ ))}
433
+ </div>
434
+ <span
435
+ className="gf-calendar-month"
436
+ id={titleId}
437
+ aria-live="polite"
438
+ aria-atomic="true"
439
+ >
440
+ {format.month.format(active)}
441
+ </span>
442
+ <div className="gf-calendar-nav">
443
+ {navigation.slice(2).map(([offset, index, path]) => (
444
+ <button
445
+ type="button"
446
+ className="gf-calendar-nav-button"
447
+ key={offset}
448
+ aria-label={words[index]}
449
+ title={words[index]}
450
+ disabled={facts.locked || !canNavigate(active, offset, range)}
451
+ onClick={() => {
452
+ sync.current();
453
+ const next = monthDate(active, offset);
454
+ setDisplay(next);
455
+ setCursor(bounded(iso(next), range));
456
+ }}
457
+ >
458
+ <Icon path={path} />
459
+ </button>
460
+ ))}
461
+ </div>
462
+ </div>
463
+ <div
464
+ className="gf-calendar-grid"
465
+ role="grid"
466
+ aria-labelledby={titleId}
467
+ >
468
+ <div className="gf-calendar-row" role="row">
469
+ {Array.from({ length: 7 }, (_, i) => (
470
+ <div
471
+ className="gf-calendar-weekday"
472
+ role="columnheader"
473
+ key={i}
474
+ aria-label={format.fullWeekday.format(civil(2024, 0, i + 1))}
475
+ >
476
+ {format.shortWeekday.format(civil(2024, 0, i + 1))}
477
+ </div>
478
+ ))}
479
+ </div>
480
+ <div className="gf-calendar-days" role="rowgroup">
481
+ {Array.from({ length: values.length / 7 }, (_, week) => (
482
+ <div className="gf-calendar-row" role="row" key={week}>
483
+ {values.slice(week * 7, week * 7 + 7).map((day) => {
484
+ const date = parse(day),
485
+ disabled = facts.locked || !allowed(day);
486
+ return (
487
+ <div
488
+ className="gf-calendar-cell"
489
+ role="gridcell"
490
+ key={day}
491
+ aria-selected={day === selected}
492
+ aria-disabled={disabled}
493
+ >
494
+ {date && (
495
+ <button
496
+ type="button"
497
+ className="gf-calendar-day"
498
+ data-gf-date={day}
499
+ data-outside={date.getMonth() !== active.getMonth()}
500
+ aria-label={format.full.format(date)}
501
+ aria-pressed={day === selected}
502
+ aria-current={
503
+ day === facts.day ? "date" : undefined
504
+ }
505
+ tabIndex={day === focusValue && !disabled ? 0 : -1}
506
+ disabled={disabled}
507
+ onClick={() => choose(day)}
508
+ onKeyDown={key}
509
+ >
510
+ {date.getDate()}
511
+ </button>
512
+ )}
513
+ </div>
514
+ );
515
+ })}
516
+ </div>
517
+ ))}
518
+ </div>
519
+ </div>
520
+ <div className="gf-calendar-footer">
521
+ <span className="gf-calendar-policy">
522
+ {datePolicy === "today"
523
+ ? words[6]
524
+ : datePolicy === "tomorrow"
525
+ ? words[7]
526
+ : words[5]}
527
+ </span>
528
+ <button
529
+ type="button"
530
+ className="gf-calendar-clear"
531
+ disabled={facts.locked || !selected}
532
+ onClick={() => choose("")}
533
+ >
534
+ {words[4]}
535
+ </button>
536
+ </div>
537
+ <div
538
+ className="gf-calendar-selection"
539
+ data-selected={!!parse(selected)}
540
+ >
541
+ {parse(selected) ? format.date.format(parse(selected)) : words[8]}
542
+ </div>
543
+ </div>
544
+ )}
545
+ {facts && (
546
+ <span
547
+ className="gf-calendar-sr-only"
548
+ role="status"
549
+ aria-live="polite"
550
+ aria-atomic="true"
551
+ >
552
+ {announcement}
553
+ </span>
554
+ )}
555
+ </div>
556
+ );
557
+ });