@monster-orange/den-ui 0.6.6 → 0.7.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.
@@ -8,6 +8,8 @@
8
8
  * compareNav(actual, reference, { hostSlots, themeTokens, tolerance })
9
9
  * → NavDiff[] (empty: the same nav)
10
10
  * formatNavDiffs(diffs) → string, one line per difference
11
+ * pinNavFonts(context, { fontsDir }?) → Promise<void>: the same glyphs
12
+ * on every machine (see below)
11
13
  *
12
14
  * `page` is a Playwright Page (anything with `evaluate(fn, arg)` works),
13
15
  * already on a page that draws the kit's shell.
@@ -38,6 +40,13 @@
38
40
  * sides.
39
41
  */
40
42
 
43
+ import { readFileSync, existsSync } from "node:fs";
44
+ import * as path from "node:path";
45
+ // The kit's own src/fonts, found from the kit's files themselves: an ES
46
+ // module reads it from import.meta.url, CommonJS from __dirname (the
47
+ // package's "imports" picks the side).
48
+ import { FONTS_DIR } from "#den-ui-fonts-dir";
49
+
41
50
  /** The computed styles kept for each element. */
42
51
  export const STYLE_PROPS = [
43
52
  "display",
@@ -199,7 +208,9 @@ export async function collectNav(page, opts = {}) {
199
208
  // `pathKey`: the DOM parent's key (an element with no box of its own,
200
209
  // display: contents, still names its children); `boxParent`: the
201
210
  // nearest ancestor with a box, the one the snapshot lists.
202
- const walk = (el, pathKey, boxParent, slot) => {
211
+ // `host`: the nearest element (this one or an ancestor) with a
212
+ // data-nav-role: host content ({ role, key }), else null.
213
+ const walk = (el, pathKey, boxParent, slot, hostIn) => {
203
214
  if (el.hidden) return slot;
204
215
  const cs = getComputedStyle(el);
205
216
  if (cs.display === "none") return slot;
@@ -208,7 +219,29 @@ export async function collectNav(page, opts = {}) {
208
219
  const n = (used.get(key) || 0) + 1;
209
220
  used.set(key, n);
210
221
  if (n > 1) key += `{${n}}`;
222
+ const navRole = el.getAttribute("data-nav-role");
223
+ const host = navRole
224
+ ? { role: navRole, key }
225
+ : hostIn
226
+ ? { role: hostIn.role, key: hostIn.key }
227
+ : null;
211
228
  const boxed = el.getClientRects().length > 0;
229
+ // A host root's own width: its contents' plus its padding and
230
+ // border (a field that fills the bar is wider than its words).
231
+ if (navRole && boxed) {
232
+ const rg = document.createRange();
233
+ rg.selectNodeContents(el);
234
+ const px = (p) => parseFloat(cs.getPropertyValue(p)) || 0;
235
+ const edge =
236
+ px("padding-left") +
237
+ px("padding-right") +
238
+ px("border-left-width") +
239
+ px("border-right-width");
240
+ const w = el.getBoundingClientRect().width;
241
+ host.fit = round(
242
+ Math.min(w, rg.getBoundingClientRect().width + edge),
243
+ );
244
+ }
212
245
  if (boxed) {
213
246
  const r = el.getBoundingClientRect();
214
247
  const style = {};
@@ -228,20 +261,25 @@ export async function collectNav(page, opts = {}) {
228
261
  h: round(r.height),
229
262
  },
230
263
  style,
264
+ ...(host ? { host } : {}),
265
+ // Its name is the host's words (the search's label, say).
266
+ ...(el.getAttribute("data-nav-name") === "host"
267
+ ? { hostName: true }
268
+ : {}),
231
269
  });
232
270
  }
233
271
  if (el.tagName.toLowerCase() === "svg") return mySlot;
234
272
  let kidSlot = mySlot;
235
273
  for (const k of Array.from(el.children)) {
236
274
  // Everything after the rail's spacer is the rail's foot.
237
- kidSlot = walk(k, key, boxed ? key : boxParent, kidSlot);
275
+ kidSlot = walk(k, key, boxed ? key : boxParent, kidSlot, host);
238
276
  }
239
277
  return kidSlot === "foot" ? "foot" : mySlot;
240
278
  };
241
279
  const top = document.querySelector("header.den-top");
242
280
  const rail = document.querySelector("nav.den-rail, .den-rail");
243
- if (top) walk(top, null, null, "top");
244
- if (rail) walk(rail, null, null, "rail");
281
+ if (top) walk(top, null, null, "top", null);
282
+ if (rail) walk(rail, null, null, "rail", null);
245
283
 
246
284
  // The theme tokens: each colour seen → the --tokens that make it.
247
285
  const names = new Set();
@@ -313,8 +351,10 @@ export async function collectNav(page, opts = {}) {
313
351
  "sans-serif",
314
352
  "serif",
315
353
  "monospace",
316
- rootCs.getPropertyValue("--sans").trim(),
317
- rootCs.getPropertyValue("--mono").trim(),
354
+ // One line, single-spaced: a token written over lines (tokens.css
355
+ // wraps long values) is the same family (navFamily, below).
356
+ rootCs.getPropertyValue("--sans").replace(/\s+/g, " ").trim(),
357
+ rootCs.getPropertyValue("--mono").replace(/\s+/g, " ").trim(),
318
358
  ])
319
359
  if (fam)
320
360
  for (const wt of ["400", "500"]) faceKeys.add(`${wt} 14px ${fam}`);
@@ -353,11 +393,22 @@ export function fingerprint(snap) {
353
393
  return JSON.stringify([
354
394
  env.userAgent || "",
355
395
  Object.keys(faces)
356
- .sort()
357
- .map((k) => [k, faces[k]]),
396
+ .map((k) => [navFamily(k), faces[k]])
397
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)),
358
398
  ]);
359
399
  }
360
400
 
401
+ /**
402
+ * A font family (or a face key) as one line: every run of whitespace one
403
+ * space, the ends trimmed. "a,\n b" is "a, b": a token's value keeps
404
+ * the line breaks it was written with, and must still name one face.
405
+ */
406
+ export function navFamily(s) {
407
+ return String(s ?? "")
408
+ .replace(/\s+/g, " ")
409
+ .trim();
410
+ }
411
+
361
412
  /** Where a snapshot was taken, in words: its image (if named) and browser. */
362
413
  function envWords(snap) {
363
414
  const env = snap.env || {};
@@ -388,7 +439,7 @@ function kept(snap, hostSlots) {
388
439
  * moves or stretches its neighbours by just that much: each host slot's
389
440
  * change in width, per nav slot, and every sum of them.
390
441
  */
391
- function slotShifts(actual, reference, hostSlots) {
442
+ function slotShifts(actual, reference, hostSlots, extra = {}) {
392
443
  const roots = (snap) => {
393
444
  const byKey = new Map(snap.elements.map((e) => [e.key, e]));
394
445
  const out = new Map();
@@ -418,6 +469,8 @@ function slotShifts(actual, reference, hostSlots) {
418
469
  const d = x && y ? x.w - y.w : x ? x.w + x.gap : -(y.w + y.gap);
419
470
  if (d) (deltas[slot] = deltas[slot] || []).push(d);
420
471
  }
472
+ for (const [slot, ds] of Object.entries(extra))
473
+ for (const d of ds) if (d) (deltas[slot] = deltas[slot] || []).push(d);
421
474
  const sums = {};
422
475
  for (const [slot, ds] of Object.entries(deltas)) {
423
476
  let set = [0];
@@ -470,6 +523,67 @@ function lcs(a, b) {
470
523
  * stretch sideways by exactly that change (or a sum of such changes, with
471
524
  * the flex gap of a slot there on one side only), never by anything else.
472
525
  */
526
+ /** The rail's column: its slots stack top to bottom. */
527
+ const COLUMN = ["rail", "foot"];
528
+
529
+ /**
530
+ * Host content's size, by role: for each role, the sum of its roots'
531
+ * widths (in a row) or heights (in the rail's column), each with its
532
+ * parent's gap. `row`: { slot: { role: n } }; `column`: { role: n }.
533
+ */
534
+ function hostExtent(snap) {
535
+ const byKey = new Map(snap.elements.map((e) => [e.key, e]));
536
+ const row = {};
537
+ const column = {};
538
+ for (const e of snap.elements) {
539
+ if (!e.host || e.host.key !== e.key) continue;
540
+ const parent = e.parent && byKey.get(e.parent);
541
+ const r = e.host.role;
542
+ if (COLUMN.includes(e.slot)) {
543
+ const gap = parseFloat(parent ? parent.style["row-gap"] : "") || 0;
544
+ column[r] = (column[r] || 0) + e.box.h + gap;
545
+ } else {
546
+ const gap = parseFloat(parent ? parent.style["column-gap"] : "") || 0;
547
+ row[e.slot] = row[e.slot] || {};
548
+ const w = e.host.fit == null ? e.box.w : e.host.fit;
549
+ row[e.slot][r] = (row[e.slot][r] || 0) + w + gap;
550
+ }
551
+ }
552
+ return { row, column };
553
+ }
554
+
555
+ /** Every subset's sum of up to 8 deltas, with either sign. */
556
+ function subsetSums(ds) {
557
+ let set = [0];
558
+ for (const d of ds.filter(Boolean).slice(0, 8))
559
+ set = [...set, ...set.map((v) => v + d)];
560
+ return set.flatMap((v) => [v, -v]);
561
+ }
562
+
563
+ /**
564
+ * Host content (an element with a data-nav-role, and what it holds): the
565
+ * first of each role on each side, and what it holds by its key's tail,
566
+ * as [role, tail, element] for each.
567
+ */
568
+ function firstOfRoles(els) {
569
+ const roots = new Map();
570
+ for (const e of els)
571
+ if (e.host && !roots.has(e.host.role)) roots.set(e.host.role, e.host.key);
572
+ const out = new Map();
573
+ for (const e of els) {
574
+ if (!e.host || roots.get(e.host.role) !== e.host.key) continue;
575
+ const root = e.host.key;
576
+ const tail =
577
+ e.key === root
578
+ ? ""
579
+ : e.key.startsWith(root)
580
+ ? e.key.slice(root.length)
581
+ : null;
582
+ if (tail != null) out.set(`${e.host.role}|${tail}`, e);
583
+ }
584
+ return out;
585
+ }
586
+
473
587
  export function compareNav(actual, reference, opts = {}) {
474
588
  const hostSlots = opts.hostSlots || [];
475
589
  const themeTokens = new Set(opts.themeTokens || []);
@@ -519,8 +633,27 @@ export function compareNav(actual, reference, opts = {}) {
519
633
  actual: `running in theme ${themeWords(actual)}`,
520
634
  },
521
635
  ];
522
- const want = kept(reference, hostSlots);
523
- const got = kept(actual, hostSlots);
636
+ const allWant = kept(reference, hostSlots);
637
+ const allGot = kept(actual, hostSlots);
638
+ // Host content is never keyed: its count, keys, ids and text are the
639
+ // host's. The kit's chrome around it is.
640
+ const want = allWant.filter((e) => !e.host);
641
+ const got = allGot.filter((e) => !e.host);
642
+ // A kit element that holds host content: its name is the host's words.
643
+ const holders = (snap) => {
644
+ const byKey = new Map(snap.elements.map((e) => [e.key, e]));
645
+ const out = new Set();
646
+ for (const e of snap.elements)
647
+ if (e.host)
648
+ for (
649
+ let x = e.parent && byKey.get(e.parent);
650
+ x;
651
+ x = x.parent && byKey.get(x.parent)
652
+ )
653
+ out.add(x.key);
654
+ return out;
655
+ };
656
+ const holdsHost = new Set([...holders(reference), ...holders(actual)]);
524
657
  const wantBy = new Map(want.map((e) => [e.key, e]));
525
658
  const gotBy = new Map(got.map((e) => [e.key, e]));
526
659
  for (const e of want)
@@ -539,12 +672,36 @@ export function compareNav(actual, reference, opts = {}) {
539
672
  `#${b.indexOf(k) + 1} of ${b.length}`,
540
673
  );
541
674
  const tokenOf = (snap, c) => (snap.tokens && snap.tokens[c]) || [];
542
- const shifts = slotShifts(actual, reference, hostSlots);
675
+ // Host content's size moves what follows it: in a row by its width's
676
+ // change, in the rail's column by its height's.
677
+ const ea = hostExtent(actual);
678
+ const er = hostExtent(reference);
679
+ const rowDeltas = {};
680
+ for (const slot of new Set([
681
+ ...Object.keys(ea.row),
682
+ ...Object.keys(er.row),
683
+ ])) {
684
+ const a = ea.row[slot] || {};
685
+ const r = er.row[slot] || {};
686
+ rowDeltas[slot] = [...new Set([...Object.keys(a), ...Object.keys(r)])].map(
687
+ (k) => (a[k] || 0) - (r[k] || 0),
688
+ );
689
+ }
690
+ const shifts = slotShifts(actual, reference, hostSlots, rowDeltas);
691
+ const drops = subsetSums(
692
+ [...new Set([...Object.keys(ea.column), ...Object.keys(er.column)])].map(
693
+ (k) => (ea.column[k] || 0) - (er.column[k] || 0),
694
+ ),
695
+ );
543
696
  for (const w of want) {
544
697
  const g = gotBy.get(w.key);
545
698
  if (!g) continue;
546
699
  for (const p of ["slot", "role", "tag", "name"])
547
- if (w[p] !== g[p]) add(w, p, w[p], g[p]);
700
+ if (
701
+ w[p] !== g[p] &&
702
+ !(p === "name" && (holdsHost.has(w.key) || w.hostName || g.hostName))
703
+ )
704
+ add(w, p, w[p], g[p]);
548
705
  const wc = w.classes.join(" ");
549
706
  const gc = g.classes.join(" ");
550
707
  if (wc !== gc) add(w, "classes", wc, gc);
@@ -562,10 +719,37 @@ export function compareNav(actual, reference, opts = {}) {
562
719
  const ok =
563
720
  edge === "left" || edge === "right"
564
721
  ? moves.some((m) => Math.abs(d - m) <= tol)
565
- : Math.abs(d) <= tol;
722
+ : COLUMN.includes(w.slot)
723
+ ? drops.some((m) => Math.abs(d - m) <= tol)
724
+ : Math.abs(d) <= tol;
566
725
  if (!ok) add(w, `box.${edge}`, we[edge], ge[edge]);
567
726
  }
727
+ // The rail's spacer takes up what the rail's pages don't.
728
+ const grows =
729
+ w.classes.includes("den-rail-grow") &&
730
+ drops.some(
731
+ (m) =>
732
+ Math.abs(
733
+ parseFloat(g.style.height) - parseFloat(w.style.height) - m,
734
+ ) <= tol,
735
+ );
736
+ styles(w, g, grows ? ["height"] : []);
737
+ }
738
+ // The first of each role on each side, and what it holds, compared on
739
+ // every style and on height: never on text, width or where it sits.
740
+ const fw = firstOfRoles(allWant);
741
+ const fg = firstOfRoles(allGot);
742
+ for (const [k, w] of fw) {
743
+ const g = fg.get(k);
744
+ if (!g) continue;
745
+ if (Math.abs(g.box.h - w.box.h) > tol)
746
+ add(w, "box.height", w.box.h, g.box.h);
747
+ styles(w, g, []);
748
+ }
749
+ return diffs;
750
+ function styles(w, g, skip) {
568
751
  for (const p of STYLE_PROPS) {
752
+ if (skip.includes(p)) continue;
569
753
  const rv = w.style[p];
570
754
  const av = g.style[p];
571
755
  if (rv === av) continue;
@@ -577,7 +761,6 @@ export function compareNav(actual, reference, opts = {}) {
577
761
  add(w, `style.${p}`, rv, av);
578
762
  }
579
763
  }
580
- return diffs;
581
764
  }
582
765
 
583
766
  /** The differences, one per line: "top #den-search style.font-weight: 500 → 700". */
@@ -588,3 +771,69 @@ export function formatNavDiffs(diffs) {
588
771
  )
589
772
  .join("\n");
590
773
  }
774
+
775
+ // ── The font pin ─────────────────────────────────────────────────────────
776
+
777
+ /**
778
+ * The system faces a nav names, pinned to the kit's own font files, so
779
+ * text lays out alike on every machine: the sans faces to Rubik (400 up
780
+ * to 449, 500 from 450), the mono ones to Space Mono. The reference was
781
+ * taken with this pin.
782
+ */
783
+ const PIN_SANS = [
784
+ "-apple-system",
785
+ "BlinkMacSystemFont",
786
+ "Segoe UI",
787
+ "Noto Sans",
788
+ "Hiragino Sans",
789
+ "Noto Sans JP",
790
+ "Helvetica",
791
+ "Arial",
792
+ "Times New Roman",
793
+ ];
794
+ const PIN_MONO = ["ui-monospace", "SFMono-Regular", "Menlo", "Consolas"];
795
+ export const PIN_FONTS_CSS = [
796
+ ...PIN_SANS.flatMap((f) => [
797
+ `@font-face{font-family:"${f}";font-weight:100 449;src:url(/__pin-fonts/rubik-latin-400-normal.woff2) format("woff2")}`,
798
+ `@font-face{font-family:"${f}";font-weight:450 900;src:url(/__pin-fonts/rubik-latin-500-normal.woff2) format("woff2")}`,
799
+ ]),
800
+ ...PIN_MONO.map(
801
+ (f) =>
802
+ `@font-face{font-family:"${f}";src:url(/__pin-fonts/space-mono-latin-400-normal.woff2) format("woff2")}`,
803
+ ),
804
+ ].join("\n");
805
+
806
+ /**
807
+ * Pins a Playwright BrowserContext's fonts for the inventory (call it
808
+ * before the context opens a page): every page gets the pin stylesheet
809
+ * first in its <head>, and /__pin-fonts/* answers with the kit's own woff2
810
+ * files. `opts.fontsDir`: where they are, if not this package's.
811
+ */
812
+ export async function pinNavFonts(context, opts = {}) {
813
+ const dir = opts.fontsDir || FONTS_DIR;
814
+ await context.route("**/__pin-fonts/**", (route) => {
815
+ const name = decodeURIComponent(
816
+ new URL(route.request().url()).pathname.split("/").pop() || "",
817
+ );
818
+ if (name === "pin.css")
819
+ return route.fulfill({ contentType: "text/css", body: PIN_FONTS_CSS });
820
+ // Only a font file of the kit's: no path in the name.
821
+ const file = path.join(dir, path.basename(name));
822
+ if (!/^[\w.-]+\.woff2$/.test(name) || !existsSync(file))
823
+ return route.fulfill({ status: 404, body: "" });
824
+ return route.fulfill({
825
+ contentType: "font/woff2",
826
+ body: readFileSync(file),
827
+ });
828
+ });
829
+ await context.addInitScript(() => {
830
+ const add = () => {
831
+ const l = document.createElement("link");
832
+ l.rel = "stylesheet";
833
+ l.href = "/__pin-fonts/pin.css";
834
+ document.head.prepend(l);
835
+ };
836
+ if (document.head) add();
837
+ else document.addEventListener("DOMContentLoaded", add);
838
+ });
839
+ }