actual-css 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +8 -4
  3. package/components.json +19 -4
  4. package/dist/actual.full.css +393 -69
  5. package/dist/actual.full.js +2 -1
  6. package/dist/actual.full.min.css +1 -1
  7. package/docs/design-notes/app-ui.md +37 -3
  8. package/docs/design-notes/enhancement-contract.md +3 -1
  9. package/docs/navigation.json +14 -1
  10. package/docs/pages/components/alert.md +45 -17
  11. package/docs/pages/components/button.md +3 -0
  12. package/docs/pages/components/dialog.md +36 -0
  13. package/docs/pages/components/drawer.md +52 -8
  14. package/docs/pages/components/navbar.md +26 -2
  15. package/docs/pages/components/rating.md +111 -12
  16. package/docs/pages/components/segmented.md +36 -1
  17. package/docs/pages/components/spinner.md +2 -0
  18. package/docs/pages/components/table.md +77 -0
  19. package/docs/pages/components/timeline.md +3 -1
  20. package/docs/pages/enhancements/flyout.md +83 -14
  21. package/docs/pages/enhancements/tabs.md +5 -0
  22. package/docs/pages/examples/overview.md +5 -1
  23. package/docs/pages/forms/ajax.md +101 -0
  24. package/docs/pages/forms/color-swatches.md +31 -2
  25. package/docs/pages/forms/joined-controls.md +8 -3
  26. package/docs/pages/forms/overview.md +1 -1
  27. package/docs/pages/forms/unsaved-changes.md +198 -0
  28. package/docs/pages/foundations/philosophy.md +2 -1
  29. package/docs/pages/foundations/theming.md +2 -1
  30. package/docs/pages/foundations/tokens.md +1 -1
  31. package/docs/pages/guides/introduction.md +1 -1
  32. package/docs/pages/guides/progressive-enhancement.md +30 -49
  33. package/docs/pages/guides/upgrading.md +15 -2
  34. package/docs/pages/layout/choosing.md +5 -0
  35. package/docs/pages/layout/column-layout.md +22 -8
  36. package/docs/pages/layout/sidebar-shell.md +68 -0
  37. package/docs/pages/patterns/empty-state.md +74 -0
  38. package/docs/pages/patterns/hierarchical-nav.md +40 -19
  39. package/docs/pages/patterns/navigation-list.md +3 -60
  40. package/docs/pages/patterns/stat.md +61 -0
  41. package/docs/pages/utilities/accessibility.md +32 -10
  42. package/package.json +4 -1
  43. package/reserved-classes.json +2 -0
  44. package/src/css/components/busy.css +25 -0
  45. package/src/css/components/button.css +3 -0
  46. package/src/css/components/drawer.css +37 -3
  47. package/src/css/components/flyout.css +37 -0
  48. package/src/css/components/modal.css +3 -0
  49. package/src/css/components/navbar.css +99 -38
  50. package/src/css/components/rating.css +50 -5
  51. package/src/css/components/segmented.css +25 -2
  52. package/src/css/forms/color-swatch.css +38 -19
  53. package/src/css/forms/custom-select.css +5 -0
  54. package/src/css/layout/index.css +2 -0
  55. package/src/css/layout/sidebar-shell.css +67 -0
  56. package/src/js/ajax.js +148 -0
  57. package/src/js/dialog.js +59 -2
  58. package/src/js/dirty.js +140 -0
  59. package/src/js/dismiss.js +25 -0
  60. package/src/js/events.js +17 -0
  61. package/src/js/focus.js +12 -0
  62. package/src/js/form-submission.js +34 -0
  63. package/src/js/full.js +2 -0
  64. package/src/js/tab.js +16 -2
  65. package/src/js/validation.js +12 -4
  66. package/src/tooling/theme-contrast.js +3 -2
@@ -16,11 +16,11 @@
16
16
  * rows sit one gap apart like columns. Edge, selection ring and focus ring all
17
17
  * belong to the visible swatch.
18
18
  *
19
- * The color is arbitrary, so nothing drawn on it may assume a contrast: the
20
- * selected mark is a double ring (--text outside, --surface-opaque inside) that
21
- * reads on any fill, and a hairline edge keeps a near-white color apart from
22
- * the page. ::before opts out of forced colors to keep the color, so it takes
23
- * system colors itself there.
19
+ * The color is arbitrary, so nothing is drawn on it: the selected mark is a
20
+ * --text ring outside the swatch (::after), past a transparent gap, so it reads
21
+ * on any color and any background and leaves the color whole. A hairline edge
22
+ * keeps a near-white color apart from the page. Both pseudo-elements opt out of
23
+ * forced colors to keep the color, so they take system colors themselves there.
24
24
  *
25
25
  * Without :has() the native radio stays visible in the swatch and carries the
26
26
  * state; the ring needs :has() to mirror it.
@@ -28,16 +28,18 @@
28
28
  * Public hooks:
29
29
  * --color-swatch-value (fallback-only: the color, set per swatch)
30
30
  * --color-swatch-size
31
- * --color-swatch-radius
31
+ * --color-swatch-radius (fallback-only: set it on the palette or a swatch)
32
32
  */
33
33
  .color-swatch {
34
34
  /* The .switch track height (switch.css); a browser test holds them equal. */
35
35
  --color-swatch-size: calc(var(--choice-control-size) + 0.125em);
36
- --color-swatch-radius: var(--radius-full);
37
36
  /* Internal: what the hit area adds to the swatch, half on each side. One gap
38
37
  at most, so two neighbours never claim the same point — a wider reach let
39
38
  the next swatch take a click on this one's center. */
40
39
  --color-swatch-reach: clamp(0px, var(--control-size) - var(--color-swatch-size), var(--gap));
40
+ /* Internal: how far the selection ring (gap + stroke) reaches past the
41
+ swatch. The focus ring moves out by as much on a checked swatch. */
42
+ --color-swatch-ring: 4px;
41
43
 
42
44
  position: relative;
43
45
  display: inline-grid;
@@ -69,13 +71,29 @@
69
71
  block-size: var(--color-swatch-size);
70
72
  box-sizing: border-box;
71
73
  border: var(--border-width) solid var(--border-control);
72
- border-radius: var(--color-swatch-radius);
74
+ border-radius: var(--color-swatch-radius, var(--radius-full));
73
75
  background: var(--color-swatch-value, transparent) padding-box;
74
76
  /* The color is the content, as on .color (native.css). */
75
77
  forced-color-adjust: none;
76
- transition:
77
- border-color var(--duration),
78
- box-shadow var(--duration);
78
+ transition: border-color var(--duration);
79
+ }
80
+
81
+ /* Selection ring, drawn on every swatch and colored when checked. Its negative
82
+ margin lays it out at the swatch size: a ring wider than the grid track
83
+ would widen it and push the swatch off-center in a tight palette. */
84
+ .color-swatch::after {
85
+ content: "";
86
+ grid-area: 1 / 1;
87
+ inline-size: calc(var(--color-swatch-size) + 2 * var(--color-swatch-ring));
88
+ block-size: calc(var(--color-swatch-size) + 2 * var(--color-swatch-ring));
89
+ margin: calc(-1 * var(--color-swatch-ring));
90
+ box-sizing: border-box;
91
+ border: calc(var(--color-swatch-ring) / 2) solid transparent;
92
+ border-radius: calc(var(--color-swatch-radius, var(--radius-full)) + var(--color-swatch-ring));
93
+ pointer-events: none;
94
+ /* The gap stays transparent; forced colors would paint it. */
95
+ forced-color-adjust: none;
96
+ transition: border-color var(--duration);
79
97
  }
80
98
 
81
99
  /* Shares the swatch's cell and paints after ::before, so a native radio left
@@ -107,10 +125,8 @@
107
125
  border-color: var(--text-subtle);
108
126
  }
109
127
 
110
- .color-swatch:has(> input:checked)::before {
111
- box-shadow:
112
- inset 0 0 0 2px var(--text),
113
- inset 0 0 0 4px var(--surface-opaque);
128
+ .color-swatch:has(> input:checked)::after {
129
+ border-color: var(--text);
114
130
  }
115
131
 
116
132
  /* The ring goes around the visible swatch, not the larger hit area. */
@@ -128,6 +144,11 @@
128
144
  outline-offset: var(--focus-outline-offset);
129
145
  }
130
146
 
147
+ /* Outside the selection ring, so the two never share a stroke. */
148
+ .color-swatch:has(> input:checked:focus-visible)::before {
149
+ outline-offset: calc(var(--focus-outline-offset) + var(--color-swatch-ring));
150
+ }
151
+
131
152
  .color-swatch:disabled {
132
153
  opacity: var(--disabled-opacity);
133
154
  cursor: not-allowed;
@@ -147,10 +168,8 @@
147
168
  border-color: CanvasText;
148
169
  }
149
170
 
150
- .color-swatch:has(> input:checked)::before {
151
- box-shadow:
152
- inset 0 0 0 2px CanvasText,
153
- inset 0 0 0 4px Canvas;
171
+ .color-swatch:has(> input:checked)::after {
172
+ border-color: CanvasText;
154
173
  }
155
174
 
156
175
  .color-swatch:disabled::before {
@@ -20,6 +20,11 @@
20
20
  .select:not([multiple], .native, [size]:not([size="1"])) {
21
21
  appearance: base-select;
22
22
  align-items: center;
23
+ /* why: base-select brings a UA padding-block (0.25em) that the native
24
+ select lacks; with a 24px line it pushed a .compact select to 34px
25
+ against --control-size 32px. min-block-size and align-items already
26
+ center the value. */
27
+ padding-block: 0;
23
28
 
24
29
  &::picker(select) {
25
30
  appearance: base-select;
@@ -8,6 +8,7 @@
8
8
  * .center centered content column
9
9
  * .frame fixed-ratio media frame
10
10
  * .app-shell full-height application shell
11
+ * .sidebar-shell persistent side region + main, each scrolling; drawer below 64rem
11
12
  * .app-layout topbar + scrolling main + bottom/side app navigation
12
13
  * .media fixed media + flexible content
13
14
  * .switcher peer regions: all horizontal or all stacked
@@ -31,6 +32,7 @@
31
32
  @import "./center.css";
32
33
  @import "./frame.css";
33
34
  @import "./app-shell.css";
35
+ @import "./sidebar-shell.css";
34
36
  @import "./app-layout.css";
35
37
  @import "./media.css";
36
38
  @import "./switcher.css";
@@ -0,0 +1,67 @@
1
+ /*
2
+ * Sidebar shell — a persistent side region beside the main one on a wide
3
+ * viewport, each scrolling on its own; below 64rem the side region hides and
4
+ * the document scrolls. The page mirrors the navigation into a dialog.drawer.
5
+ *
6
+ * Docs: docs/pages/layout/sidebar-shell.md
7
+ * Design note: docs/design-notes/app-ui.md#sidebar-shell
8
+ *
9
+ * Structure: two direct children, an `aside` (side) and one other element
10
+ * (main). The breakpoint is a literal; a custom property cannot sit in a
11
+ * media condition.
12
+ *
13
+ * Public hooks:
14
+ * --sidebar-shell-size
15
+ */
16
+ .sidebar-shell {
17
+ --sidebar-shell-size: 16rem;
18
+ }
19
+
20
+ /* Hidden below, never shown above: the aside keeps the author's display (an
21
+ aside.stack). Where range syntax is unsupported the rule drops and the
22
+ sidebar stacks above the content, still reachable. Screen only: a printed
23
+ page is narrower than 64rem, and print never hides framework content. */
24
+ @media screen and (width < 64rem) {
25
+ .sidebar-shell > aside {
26
+ display: none;
27
+ }
28
+ }
29
+
30
+ @media (width >= 64rem) {
31
+ .sidebar-shell {
32
+ display: grid;
33
+ grid-template-columns: var(--sidebar-shell-size) minmax(0, 1fr);
34
+ block-size: var(--viewport-block);
35
+ }
36
+
37
+ /* Each region is its own scroller, so the sidebar stays put. min-block-size
38
+ lets the grid row hold them to the viewport instead of their content. */
39
+ .sidebar-shell > * {
40
+ min-block-size: 0;
41
+ overflow: auto;
42
+ overscroll-behavior: contain;
43
+ }
44
+
45
+ .sidebar-shell > aside {
46
+ grid-column: 1;
47
+ grid-row: 1;
48
+ }
49
+
50
+ .sidebar-shell > :not(aside) {
51
+ grid-column: 2;
52
+ grid-row: 1;
53
+ }
54
+ }
55
+
56
+ /* Paper is one flow, side then main, nothing clipped by a scroller. Leaving
57
+ the sidebar off the page is the application's print stylesheet. */
58
+ @media print {
59
+ .sidebar-shell {
60
+ display: block;
61
+ block-size: auto;
62
+ }
63
+
64
+ .sidebar-shell > * {
65
+ overflow: visible;
66
+ }
67
+ }
package/src/js/ajax.js ADDED
@@ -0,0 +1,148 @@
1
+ /*
2
+ * Ajax — optional fetch transport for HTML forms.
3
+ *
4
+ * Opt in with data-enhance="ajax". A submission the module can reproduce
5
+ * faithfully is sent with fetch; anything else is left to the browser:
6
+ * method="dialog", enctype="text/plain", a target other than the page itself,
7
+ * or a cross-origin action. Refusing beats approximating, and the native path
8
+ * always works.
9
+ *
10
+ * Transport: one request at a time per form, aria-busy on the form and the
11
+ * submitter, the request aborted when the form leaves the page, redirects
12
+ * followed by navigation like a native submission.
13
+ *
14
+ * Display, kept apart: with data-ajax-target, an HTML response (2xx or 422)
15
+ * replaces the target's content. Everything else only reaches the events.
16
+ * The module never decides that a response means "saved".
17
+ */
18
+
19
+ import { registerEnhancement } from "./enhance.js";
20
+ import { EVENTS } from "./events.js";
21
+ import { submissionSetting, submissionTarget } from "./form-submission.js";
22
+
23
+ const BUSY = "aria-busy";
24
+ const ENCODINGS = new Set(["application/x-www-form-urlencoded", "multipart/form-data"]);
25
+
26
+ function isFormElement(el) {
27
+ return typeof HTMLFormElement !== "undefined" && el instanceof HTMLFormElement;
28
+ }
29
+
30
+ // URL encoding as a native submission does it: CRLF newlines, and a file
31
+ // sent as its name. URLSearchParams alone would send "[object File]".
32
+ function urlEncoded(data) {
33
+ const params = new URLSearchParams();
34
+ const crlf = (value) => value.replace(/\r\n?|\n/g, "\r\n");
35
+ for (const [name, value] of data) {
36
+ params.append(crlf(name), crlf(typeof value === "string" ? value : value.name));
37
+ }
38
+ return params;
39
+ }
40
+
41
+ /** Builds the request, or returns null for a submission left to the browser. */
42
+ function requestFor(form, submitter) {
43
+ const method = submissionSetting(form, submitter, "method");
44
+ const enctype = submissionSetting(form, submitter, "enctype");
45
+ const target = submissionTarget(form, submitter).toLowerCase();
46
+ if (method !== "get" && method !== "post") return null;
47
+ if (target !== "" && target !== "_self") return null;
48
+ if (method === "post" && !ENCODINGS.has(enctype)) return null;
49
+ const url = new URL(submissionSetting(form, submitter, "action"));
50
+ // Cross-origin would need CORS and send no cookies: the native submission
51
+ // works where fetch would fail. (file: pages compare "null" to "null".)
52
+ if (url.origin !== form.ownerDocument.location.origin) return null;
53
+
54
+ const data = new FormData(form, submitter);
55
+ // De facto marker servers use to answer with a fragment instead of a page.
56
+ const init = { method, headers: { Accept: "text/html", "X-Requested-With": "XMLHttpRequest" } };
57
+ if (method === "get") url.search = urlEncoded(data).toString();
58
+ else init.body = enctype === "multipart/form-data" ? data : urlEncoded(data);
59
+ return { url, init };
60
+ }
61
+
62
+ function targetElement(root, selector) {
63
+ try {
64
+ return root.querySelector(selector);
65
+ } catch {
66
+ // A configuration error, not a failed request: keep it out of ajax-error.
67
+ console.warn(`data-ajax-target is not a valid selector: "${selector}"`);
68
+ return null;
69
+ }
70
+ }
71
+
72
+ function display(form, root, response) {
73
+ const selector = form.dataset.ajaxTarget;
74
+ if (!selector || !(response.ok || response.status === 422)) return null;
75
+ const type = response.headers.get("Content-Type")?.toLowerCase() ?? "";
76
+ if (!type.includes("text/html")) return null;
77
+ const target = targetElement(root, selector);
78
+ if (!target) return null;
79
+ // The clone leaves the original body readable by event listeners.
80
+ return response
81
+ .clone()
82
+ .text()
83
+ .then((html) => {
84
+ target.innerHTML = html;
85
+ });
86
+ }
87
+
88
+ function connectForm(form) {
89
+ const root = form.getRootNode();
90
+ const lifetime = new AbortController();
91
+ let pending = false;
92
+
93
+ // A target that contains the form (the server re-renders the whole form)
94
+ // detaches it; the root still reaches document listeners.
95
+ const emit = (name, detail) => {
96
+ const origin = form.isConnected ? form : root;
97
+ origin.dispatchEvent(new CustomEvent(name, { bubbles: true, detail: { form, ...detail } }));
98
+ };
99
+
100
+ const send = async (submitter, { url, init }) => {
101
+ pending = true;
102
+ // Restored afterwards, not removed: an authored aria-busy="false" is what
103
+ // keeps a last-child .spinner hidden at rest (busy.css).
104
+ const busy = [form, submitter].filter(Boolean).map((el) => [el, el.getAttribute(BUSY)]);
105
+ for (const [el] of busy) el.setAttribute(BUSY, "true");
106
+ emit(EVENTS.ajaxStart, { submitter });
107
+ try {
108
+ const response = await fetch(url, { ...init, signal: lifetime.signal });
109
+ if (response.redirected) {
110
+ emit(EVENTS.ajaxResponse, { submitter, response });
111
+ location.assign(response.url);
112
+ return;
113
+ }
114
+ await display(form, root, response);
115
+ emit(EVENTS.ajaxResponse, { submitter, response });
116
+ } catch (error) {
117
+ // An abort means the form left the page: nobody is listening.
118
+ if (!lifetime.signal.aborted) emit(EVENTS.ajaxError, { submitter, error });
119
+ } finally {
120
+ pending = false;
121
+ for (const [el, rest] of busy) {
122
+ if (rest === null) el.removeAttribute(BUSY);
123
+ else el.setAttribute(BUSY, rest);
124
+ }
125
+ }
126
+ };
127
+
128
+ // Listen on the root, after the form's own listeners: validation (or the
129
+ // application) cancels or stops an invalid submission before it gets here,
130
+ // whatever order the enhancers started in.
131
+ root.addEventListener(
132
+ "submit",
133
+ (event) => {
134
+ if (event.target !== form || event.defaultPrevented) return;
135
+ // Decide first: a submission left to the browser (a dialog's Cancel)
136
+ // goes through even while a request runs.
137
+ const request = requestFor(form, event.submitter);
138
+ if (!request) return;
139
+ event.preventDefault();
140
+ if (!pending) send(event.submitter, request); // one request at a time
141
+ },
142
+ { signal: lifetime.signal },
143
+ );
144
+
145
+ return () => lifetime.abort();
146
+ }
147
+
148
+ registerEnhancement("ajax", (el) => (isFormElement(el) ? connectForm(el) : undefined));
package/src/js/dialog.js CHANGED
@@ -15,6 +15,8 @@
15
15
  * indicator on backdrop click. Escape and explicit close requests always
16
16
  * close, unless an application cancels the actual:dialog-cancel event, and
17
17
  * closedby="none" keeps its native meaning (no Escape, no backdrop close).
18
+ * data-dialog-open opens the dialog once the document is parsed, in its
19
+ * data-dialog-modal mode; with `open` it upgrades the no-JS rendering.
18
20
  *
19
21
  * View transitions (opt-in via data-dialog-view-transition):
20
22
  * When the browser supports document.startViewTransition and the user allows
@@ -30,9 +32,12 @@
30
32
  import { registerCommands, targetFor } from "./command.js";
31
33
  import enhance, { registerEnhancement } from "./enhance.js";
32
34
  import { EVENTS } from "./events.js";
35
+ import { submissionSetting } from "./form-submission.js";
36
+ import { afterParse } from "./parsed.js";
33
37
  import { CLASSES } from "./selectors.js";
34
38
 
35
39
  const dialogMap = new WeakMap();
40
+ const autoOpened = new WeakSet();
36
41
  const wiredDialogs = new Set();
37
42
  const delegatedDialogs = new WeakSet();
38
43
  // HTML has no non-modal dialog keyword, so non-modal opening is the custom
@@ -400,7 +405,9 @@ function handleDialogSubmit(event) {
400
405
  const form = event.target;
401
406
 
402
407
  if (!(form instanceof HTMLFormElement)) return;
403
- if (form.method.toLowerCase() !== "dialog") return;
408
+ // formmethod on the submitter wins, as natively: a Save posting from a
409
+ // method="dialog" form must not close the dialog.
410
+ if (submissionSetting(form, event.submitter, "method") !== "dialog") return;
404
411
  if (!canViewTransition(dialog, dialogMap.get(dialog)?.restoreFocusTo)) return;
405
412
 
406
413
  event.preventDefault();
@@ -440,6 +447,9 @@ function handleDialogCancel(event) {
440
447
 
441
448
  function handleDialogClose(event) {
442
449
  const dialog = event.currentTarget;
450
+ // close is queued as a task: a dialog closed then reopened in the same task
451
+ // receives it while open again, and the cleanup would undo the new opening.
452
+ if (dialog.open) return;
443
453
  const state = dialogMap.get(dialog);
444
454
 
445
455
  clearVtName(dialog);
@@ -508,9 +518,56 @@ function ensureDialogWired(dialog) {
508
518
  return state;
509
519
  }
510
520
 
521
+ /* The close() that precedes an upgrade queues a close event for a dialog
522
+ nobody closed. Window capture stops it before downstream listeners, even
523
+ though close does not bubble; earlier window capture listeners still see it. */
524
+ function swallowNextClose(dialog) {
525
+ const view = dialog.ownerDocument.defaultView;
526
+ if (!view) return;
527
+ const { controller } = ensureDialogWired(dialog);
528
+ const swallow = (event) => {
529
+ if (event.target !== dialog) return;
530
+ view.removeEventListener("close", swallow, true);
531
+ if (dialog.open) event.stopImmediatePropagation();
532
+ };
533
+ // A detached dialog's queued event no longer passes through the window.
534
+ view.addEventListener("close", swallow, { capture: true, signal: controller.signal });
535
+ }
536
+
537
+ /* data-dialog-open: open once per element, for a page the server rendered
538
+ with the dialog showing. A dialog that also carries `open` is already shown
539
+ without JavaScript, non-modally; the runtime upgrades it to its modal mode.
540
+ A reinserted node does not reopen; a new node does. */
541
+ function autoOpen(dialog) {
542
+ if (!boolData(dialog, "data-dialog-open") || autoOpened.has(dialog)) return;
543
+ if (dialog.open) {
544
+ // Already modal (a command came first), or meant to stay non-modal.
545
+ if (isModalOpen(dialog) || !isModal(dialog)) {
546
+ autoOpened.add(dialog);
547
+ return;
548
+ }
549
+ // showModal() throws on a dialog that is open non-modally.
550
+ swallowNextClose(dialog);
551
+ dialog.close();
552
+ }
553
+ openDialog(dialog);
554
+ if (dialog.open) {
555
+ // No trigger owns this opening: leave focus restoration to the browser,
556
+ // and do not morph the closing dialog into the previously active element.
557
+ dialogMap.get(dialog).restoreFocusTo = null;
558
+ autoOpened.add(dialog);
559
+ }
560
+ }
561
+
511
562
  function connectDialog(dialog) {
512
563
  ensureDialogWired(dialog);
513
- return () => disconnectDialog(dialog);
564
+ // Once parsed: the title that labels the dialog and the control that takes
565
+ // initial focus may not exist yet when its start tag connects.
566
+ const cancelOpen = afterParse(dialog, () => autoOpen(dialog));
567
+ return () => {
568
+ cancelOpen();
569
+ disconnectDialog(dialog);
570
+ };
514
571
  }
515
572
 
516
573
  function ensureDelegatedDialog(dialog) {
@@ -0,0 +1,140 @@
1
+ /*
2
+ * Dirty — optional unsaved-changes tracking for forms.
3
+ *
4
+ * Opt in with data-enhance="dirty". The form carries data-dirty while the
5
+ * data it would submit differs from its baseline, and dispatches
6
+ * actual:dirty-change ({ form, dirty }) after each transition. The event
7
+ * reports state; it cannot veto it.
8
+ *
9
+ * The module observes, it never submits and never guards navigation: the
10
+ * transport (native, fetch, htmx, a library) decides when data is saved and
11
+ * tells the module through FormDirty.markClean().
12
+ *
13
+ * Comparison runs on FormData, so it covers exactly what would be submitted:
14
+ * disabled and unnamed controls do not count, form-associated controls
15
+ * outside the <form> do. Controls marked data-dirty-ignore are left out by
16
+ * name (CSRF tokens, computed fields).
17
+ */
18
+
19
+ import { registerEnhancement } from "./enhance.js";
20
+ import { EVENTS } from "./events.js";
21
+
22
+ const ATTR = "data-dirty";
23
+ const IGNORE_ATTR = "data-dirty-ignore";
24
+
25
+ // Baselines outlive the enhancer instance on purpose: a form removed and
26
+ // reinserted keeps its baseline, so moving or re-parenting it does not
27
+ // silently mark unsaved edits as clean.
28
+ const baselines = new WeakMap();
29
+ const connected = new WeakSet();
30
+
31
+ function isFormElement(el) {
32
+ return typeof HTMLFormElement !== "undefined" && el instanceof HTMLFormElement;
33
+ }
34
+
35
+ function ignoredNames(form) {
36
+ const names = new Set();
37
+ for (const el of form.elements) {
38
+ if (el.hasAttribute(IGNORE_ATTR) && el.name) names.add(el.name);
39
+ }
40
+ return names;
41
+ }
42
+
43
+ // A file is compared by identity hints, not content: two different files with
44
+ // the same name, size and timestamp read as unchanged. An empty file input
45
+ // still yields an entry, whose lastModified is "now" — normalized so an
46
+ // untouched input stays clean.
47
+ function fileKey(file) {
48
+ if (file.name === "" && file.size === 0) return [];
49
+ return [file.name, file.size, file.lastModified];
50
+ }
51
+
52
+ /**
53
+ * Serializes the data the form would submit, in submission order.
54
+ * new FormData(form) fires the form's formdata event, so an entry a listener
55
+ * adds there counts too; a volatile one (a nonce) keeps the form dirty unless
56
+ * it shares a name with a data-dirty-ignore control.
57
+ */
58
+ function capture(form) {
59
+ if (!isFormElement(form)) throw new TypeError("FormDirty expects an HTMLFormElement.");
60
+ const ignored = ignoredNames(form);
61
+ const entries = [];
62
+ for (const [name, value] of new FormData(form)) {
63
+ if (ignored.has(name)) continue;
64
+ entries.push([name, typeof value === "string" ? value : fileKey(value)]);
65
+ }
66
+ // JSON keeps names and values unambiguous: no separator a value can forge.
67
+ return JSON.stringify(entries);
68
+ }
69
+
70
+ function refresh(form) {
71
+ if (!connected.has(form)) return;
72
+ const dirty = capture(form) !== baselines.get(form);
73
+ if (dirty === form.hasAttribute(ATTR)) return;
74
+ form.toggleAttribute(ATTR, dirty);
75
+ form.dispatchEvent(
76
+ new CustomEvent(EVENTS.dirtyChange, { bubbles: true, detail: { form, dirty } }),
77
+ );
78
+ }
79
+
80
+ function connectForm(form) {
81
+ if (!baselines.has(form)) baselines.set(form, capture(form));
82
+ connected.add(form);
83
+
84
+ const controller = new AbortController();
85
+ const options = { signal: controller.signal };
86
+ const update = () => refresh(form);
87
+ const onEdit = ({ target }) => {
88
+ // A form-associated custom element exposes no .form on its host, but it
89
+ // is listed in form.elements like any native control.
90
+ if (target.form === form || Array.prototype.includes.call(form.elements, target)) update();
91
+ };
92
+
93
+ // Listen on the root: a control associated through form="…" sits outside
94
+ // the <form>, so its events never bubble through it.
95
+ const root = form.getRootNode();
96
+ root.addEventListener("input", onEdit, options);
97
+ root.addEventListener("change", onEdit, options);
98
+ // The reset event fires before the controls revert, and microtasks would
99
+ // run between listeners of a user-initiated reset — still too early. A task
100
+ // runs after the reset algorithm completes.
101
+ form.addEventListener("reset", () => setTimeout(update), options);
102
+
103
+ refresh(form);
104
+
105
+ // Release listeners only: data-dirty and the baseline stay, like validation
106
+ // state, so a reinserted form resumes where it was.
107
+ return () => {
108
+ controller.abort();
109
+ connected.delete(form);
110
+ };
111
+ }
112
+
113
+ // biome-ignore lint/complexity/noStaticOnlyClass: Stable public namespace, like FormValidator.
114
+ export class FormDirty {
115
+ /**
116
+ * Opaque snapshot of what the form would submit. Take it at submit time
117
+ * and pass it to markClean() once that submission is saved, so edits
118
+ * made during the request stay dirty.
119
+ */
120
+ static capture(form) {
121
+ return capture(form);
122
+ }
123
+
124
+ /**
125
+ * Makes `snapshot` (default: current data) the new baseline. Also valid
126
+ * before the form is enhanced: connection keeps an existing baseline.
127
+ */
128
+ static markClean(form, snapshot) {
129
+ if (!isFormElement(form)) return;
130
+ baselines.set(form, snapshot ?? capture(form));
131
+ refresh(form);
132
+ }
133
+
134
+ /** Re-evaluates an enhanced form after programmatic edits or added controls. */
135
+ static refresh(form) {
136
+ if (isFormElement(form)) refresh(form);
137
+ }
138
+ }
139
+
140
+ registerEnhancement("dirty", (el) => (isFormElement(el) ? connectForm(el) : undefined));
package/src/js/dismiss.js CHANGED
@@ -1,13 +1,32 @@
1
1
  /*
2
2
  * Dismiss command — the generic `--dismiss` action. Hides the resolved target
3
3
  * and emits the bubbling `actual:dismiss` event.
4
+ *
5
+ * Focus contract: when focus is inside the target (the usual case, a close
6
+ * button in an alert), it moves to the next tab stop after the target, else to
7
+ * the nearest ancestor with an explicit tabindex; with neither, the browser's
8
+ * focus fixup applies. Focus outside the target is left alone, and so is focus
9
+ * a listener of `actual:dismiss` placed itself (a surface restores its opener).
4
10
  */
5
11
 
6
12
  import { registerCommands } from "./command.js";
7
13
  import { EVENTS } from "./events.js";
14
+ import { isElementVisible, nextTabStop } from "./focus.js";
15
+
16
+ function focusSuccessor(target) {
17
+ const next = nextTabStop(target);
18
+ if (next) return next;
19
+ const region = target.parentElement?.closest("[tabindex]");
20
+ return region && isElementVisible(region) && !region.closest("[inert]") ? region : null;
21
+ }
8
22
 
9
23
  registerCommands("--dismiss", {
10
24
  handle(_event, trigger, target) {
25
+ const doc = target.ownerDocument;
26
+ // Resolved before hiding: a browser may move focus as soon as the focused
27
+ // element is hidden, so a check made afterwards would miss it, and the
28
+ // successor search needs the target's descendants still visible to skip.
29
+ const successor = target.contains(doc.activeElement) ? focusSuccessor(target) : null;
11
30
  target.hidden = true;
12
31
  target.dispatchEvent(
13
32
  new CustomEvent(EVENTS.dismiss, {
@@ -15,5 +34,11 @@ registerCommands("--dismiss", {
15
34
  detail: { trigger },
16
35
  }),
17
36
  );
37
+ // Only when focus is still stranded: in the hidden target, or dropped to
38
+ // <body> by the browser. No scroll: the next Tab scrolls to the successor.
39
+ const active = doc.activeElement;
40
+ if (successor && (!active || active === doc.body || target.contains(active))) {
41
+ successor.focus({ preventScroll: true });
42
+ }
18
43
  },
19
44
  });
package/src/js/events.js CHANGED
@@ -13,6 +13,23 @@ export const EVENTS = {
13
13
  // Dispatched by a form after validation blocks submission.
14
14
  // detail: { form, firstInvalid, message }
15
15
  invalid: `${ACTUAL_EVENT_PREFIX}:invalid`,
16
+ // Dispatched by a dirty-tracked form after data-dirty flips.
17
+ // detail: { form, dirty }
18
+ dirtyChange: `${ACTUAL_EVENT_PREFIX}:dirty-change`,
19
+ // Dispatched by an ajax form when its request starts.
20
+ // detail: { form, submitter }
21
+ ajaxStart: `${ACTUAL_EVENT_PREFIX}:ajax-start`,
22
+ // Dispatched by an ajax form with any HTTP response: after display, or
23
+ // before navigating to a redirect. From the root when display replaced the
24
+ // form.
25
+ // detail: { form, submitter, response }
26
+ ajaxResponse: `${ACTUAL_EVENT_PREFIX}:ajax-response`,
27
+ // Dispatched by an ajax form when the request fails (network, CORS).
28
+ // detail: { form, submitter, error }
29
+ ajaxError: `${ACTUAL_EVENT_PREFIX}:ajax-error`,
30
+ // Dispatched by a tablist after its selection changed, never at connect.
31
+ // detail: { tab, panel, previousTab }
32
+ tabChange: `${ACTUAL_EVENT_PREFIX}:tab-change`,
16
33
  // Cancelable: dispatched by dialog.js before handling native cancel close.
17
34
  // detail: { dialog, sourceEvent }
18
35
  dialogCancel: `${ACTUAL_EVENT_PREFIX}:dialog-cancel`,
package/src/js/focus.js CHANGED
@@ -59,6 +59,18 @@ function isRadioTabStop(el) {
59
59
  );
60
60
  }
61
61
 
62
+ /* The first tab stop after `node` in document order, outside `node` itself.
63
+ Document order, not tabindex order: positive tabindex is not a supported
64
+ pattern here. */
65
+ export function nextTabStop(node) {
66
+ return getFocusable(node.ownerDocument)
67
+ .filter(isRadioTabStop)
68
+ .find(
69
+ (el) =>
70
+ !node.contains(el) && node.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING,
71
+ );
72
+ }
73
+
62
74
  export function focusFirstDescendant(root) {
63
75
  const target = getFocusable(root).filter(isRadioTabStop)[0];
64
76
  target?.focus();