@tonycodes-ui/mortar 0.24.0 → 0.26.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.
package/cli/audit.mjs CHANGED
@@ -38,6 +38,8 @@ export const RULES = {
38
38
  "invalid-value": "A literal value outside the prop's declared union.",
39
39
  "css-override":
40
40
  "Consumer CSS that selects Mortar's .m-* classes or [data-m-component].",
41
+ "ancestor-override":
42
+ "Consumer CSS that uses an ancestor/native-element selector to restyle a Mortar control.",
41
43
  "class-override":
42
44
  "A Tailwind arbitrary variant in a className that targets Mortar's .m-* classes.",
43
45
  "kit-class":
@@ -55,6 +57,10 @@ export const RULES = {
55
57
  "legacy-package": `A dependency or import of the retired ${LEGACY_PKG}; install and import @tonycodes-ui/mortar instead (see the CHANGELOG migration note).`,
56
58
  "invalid-phrasing":
57
59
  "A block HTML element in a phrasing-only slot that Mortar renders inside a <p>.",
60
+ "input-static-action":
61
+ "Static text passed to Input.action; use prefix or suffix instead.",
62
+ "input-absolute-adornment":
63
+ "An absolutely positioned decorative sibling of Input; use leadingIcon or trailingIcon.",
58
64
  "limited-data": "The audit could not use the installed version's own data.",
59
65
  };
60
66
 
@@ -338,10 +344,15 @@ function jsxOpening(src, i) {
338
344
 
339
345
  /**
340
346
  * The attributes of a JSX opening tag whose name ends at `i`: name, offset and,
341
- * for string literals (`a="x"` or `a={"x"}`), the value.
347
+ * for string literals (`a="x"` or `a={"x"}`), the value. Brace values also get
348
+ * `expression: { start, end }` covering the inner text. The returned array has
349
+ * `end` (index after the opening tag) and `selfClosing`.
342
350
  */
343
351
  export function jsxAttributes(src, i) {
344
- return jsxOpening(src, i).attrs;
352
+ const { attrs, end, selfClosing } = jsxOpening(src, i);
353
+ attrs.end = end;
354
+ attrs.selfClosing = selfClosing;
355
+ return attrs;
345
356
  }
346
357
 
347
358
  /**
@@ -469,6 +480,113 @@ function phrasingSlotMap(data) {
469
480
  return map;
470
481
  }
471
482
 
483
+ /** End index of the JSX element that opens with `tagName` at `afterName`. */
484
+ function jsxElementEnd(src, tagName, afterName, opening) {
485
+ if (opening.selfClosing) return opening.end;
486
+ const body = jsxChildrenRange(src, tagName, afterName);
487
+ if (!body) return opening.end;
488
+ const close = src
489
+ .slice(body.end)
490
+ .match(new RegExp(`^</${escapeRegExp(tagName)}\\s*>`));
491
+ return body.end + (close ? close[0].length : 0);
492
+ }
493
+
494
+ /**
495
+ * True when an `action={…}` expression is obvious static end content (a string
496
+ * or a noninteractive span/fragment), not an attached control.
497
+ */
498
+ export function isStaticInputAction(expression) {
499
+ const inner = expression.trim();
500
+ if (!inner) return false;
501
+ if (/^(["'`])([^"'`$\\]*)\1$/.test(inner)) return true;
502
+ if (/\bon[A-Z]\w*\s*=/.test(inner) || /\bhref\s*=/.test(inner)) return false;
503
+ if (/<\/?(?:button|a|input|select|textarea)\b/i.test(inner)) return false;
504
+ if (/<[A-Z][\w$]*\b/.test(inner)) return false;
505
+ if (/^<>\s*[^<{]+?\s*<\/>$/.test(inner)) return true;
506
+ if (/^<\s*span\b[^>]*>\s*[^<{]+?\s*<\/\s*span\s*>$/i.test(inner)) return true;
507
+ return false;
508
+ }
509
+
510
+ /**
511
+ * Absolutely positioned decorative siblings near a Mortar Input, typically
512
+ * left over from wrapping an unlabeled native input. Bounded: string
513
+ * `className` literals only, a nearby `relative` wrapper, and only the
514
+ * immediate sibling before or after this Input (so later Inputs in the same
515
+ * file are not flagged for an earlier icon).
516
+ */
517
+ export function absoluteAdornmentsBesideInput(src, inputStart, inputEnd) {
518
+ const windowStart = Math.max(0, inputStart - 1000);
519
+ const windowEnd = Math.min(src.length, inputEnd + 1000);
520
+ const before = src.slice(windowStart, inputStart);
521
+ const after = src.slice(inputEnd, windowEnd);
522
+ const hasRelative = (slice) =>
523
+ /\bclass(?:Name)?\s*=\s*(?:\{\s*)?(["'`])([^"'`]*\brelative\b[^"'`]*)\1/.test(
524
+ slice,
525
+ );
526
+ if (!hasRelative(before)) return [];
527
+ const hits = [];
528
+ const open =
529
+ /<(svg|img|span|i|div|em)\b(?=[^>]*\bclass(?:Name)?\s*=\s*(?:\{\s*)?(["'`])([^"'`]*\babsolute\b[^"'`]*)\2)[^>]*>/i;
530
+ const sideFrom = (cls, fallback) =>
531
+ /\b(?:right-|end-|inset-e|inset-inline-end)/.test(cls)
532
+ ? "trailing"
533
+ : /\b(?:left-|start-|inset-s|inset-inline-start)/.test(cls)
534
+ ? "leading"
535
+ : fallback;
536
+ const decorative = (tag, openText) => {
537
+ if (/\bon[A-Z]\w*\s*=/.test(openText) || /\bhref\s*=/.test(openText))
538
+ return false;
539
+ return (
540
+ tag === "svg" ||
541
+ tag === "img" ||
542
+ /\baria-hidden\b/.test(openText) ||
543
+ tag === "span" ||
544
+ tag === "i" ||
545
+ tag === "em" ||
546
+ tag === "div"
547
+ );
548
+ };
549
+ // Immediate previous sibling: the last absolute tag in `before`, with only
550
+ // whitespace (and its own closing) between it and the Input.
551
+ {
552
+ let last;
553
+ const re = new RegExp(open.source, "gi");
554
+ let m;
555
+ while ((m = re.exec(before))) last = m;
556
+ if (last) {
557
+ const tag = last[1].toLowerCase();
558
+ const cls = last[3];
559
+ const openText = last[0];
560
+ const from = last.index;
561
+ let afterOpen = from + openText.length;
562
+ if (!/\/>\s*$/.test(openText)) {
563
+ const close = before
564
+ .slice(afterOpen)
565
+ .match(new RegExp(`^[\\s\\S]*?</${tag}\\s*>`, "i"));
566
+ if (close) afterOpen += close[0].length;
567
+ }
568
+ if (/^\s*$/.test(before.slice(afterOpen)) && decorative(tag, openText))
569
+ hits.push({
570
+ index: windowStart + from,
571
+ side: sideFrom(cls, "leading"),
572
+ });
573
+ }
574
+ }
575
+ // Immediate next sibling: the first absolute tag in `after`, with only
576
+ // whitespace between the Input and it.
577
+ {
578
+ const m = after.match(new RegExp("^\\s*" + open.source, "i"));
579
+ if (m && decorative(m[1].toLowerCase(), m[0].trimStart() || m[0])) {
580
+ const absAt = m[0].indexOf("<");
581
+ hits.push({
582
+ index: inputEnd + absAt,
583
+ side: sideFrom(m[3], "trailing"),
584
+ });
585
+ }
586
+ }
587
+ return hits;
588
+ }
589
+
472
590
  /**
473
591
  * The text with string and template-literal contents blanked, so HTML inside
474
592
  * strings (an email template, say) is not read as JSX. Lengths and newlines
@@ -547,6 +665,239 @@ function replacements(data) {
547
665
  map.set(element, [...(map.get(element) ?? []), c.export]);
548
666
  return map;
549
667
  }
668
+
669
+ /** Export → the native elements that component replaces. */
670
+ function replacesByExport(data) {
671
+ const map = new Map();
672
+ for (const c of data.components ?? []) {
673
+ const list = c.contract?.replaces ?? [];
674
+ if (list.length) map.set(c.export, list);
675
+ }
676
+ return map;
677
+ }
678
+
679
+ /**
680
+ * Visual properties that restyle a control. Layout (margin, display, flex,
681
+ * width, …) is ignored so composition wrappers stay quiet.
682
+ */
683
+ const VISUAL_PROP = new Set([
684
+ "background",
685
+ "background-color",
686
+ "background-image",
687
+ "border",
688
+ "border-color",
689
+ "border-style",
690
+ "border-width",
691
+ "border-top",
692
+ "border-right",
693
+ "border-bottom",
694
+ "border-left",
695
+ "border-top-color",
696
+ "border-right-color",
697
+ "border-bottom-color",
698
+ "border-left-color",
699
+ "border-top-style",
700
+ "border-right-style",
701
+ "border-bottom-style",
702
+ "border-left-style",
703
+ "border-top-width",
704
+ "border-right-width",
705
+ "border-bottom-width",
706
+ "border-left-width",
707
+ "border-radius",
708
+ "border-top-left-radius",
709
+ "border-top-right-radius",
710
+ "border-bottom-right-radius",
711
+ "border-bottom-left-radius",
712
+ "color",
713
+ "font",
714
+ "font-family",
715
+ "font-size",
716
+ "font-weight",
717
+ "font-style",
718
+ "font-variant",
719
+ "line-height",
720
+ "letter-spacing",
721
+ "text-decoration",
722
+ "text-decoration-line",
723
+ "text-decoration-color",
724
+ "text-decoration-style",
725
+ "text-transform",
726
+ "text-shadow",
727
+ ]);
728
+
729
+ /** True when a CSS rule body sets a visual property. */
730
+ export function hasVisualDeclarations(body) {
731
+ for (const m of body.matchAll(/(?:^|[{;])\s*([a-z-]+)\s*:/gi)) {
732
+ if (VISUAL_PROP.has(m[1].toLowerCase())) return true;
733
+ }
734
+ return false;
735
+ }
736
+
737
+ /**
738
+ * An obvious ancestor + native-element selector: `.toolbar button`,
739
+ * `#bar > input`, `div.panel select:hover`. Returns nothing when the selector
740
+ * is complex, targets kit classes, or has no class/id ancestor marker.
741
+ */
742
+ export function parseAncestorNativeSelector(selector) {
743
+ const parts = [];
744
+ let buf = "";
745
+ let depth = 0;
746
+ for (let i = 0; i < selector.length; i++) {
747
+ const c = selector[i];
748
+ if (c === "(" || c === "[") depth++;
749
+ else if (c === ")" || c === "]") depth = Math.max(0, depth - 1);
750
+ else if (c === "," && depth === 0) {
751
+ parts.push(buf);
752
+ buf = "";
753
+ continue;
754
+ }
755
+ buf += c;
756
+ }
757
+ parts.push(buf);
758
+
759
+ const out = [];
760
+ for (const raw of parts) {
761
+ const part = raw.trim();
762
+ if (!part || part.startsWith("@")) continue;
763
+ if (/\.m-[a-z]|\[data-m-component\b/.test(part)) continue;
764
+ const m = part.match(
765
+ /^(.+?)\s*(?:>|\s)\s*([a-z][a-z0-9]*)(\[[^\]]+\])?((?:::[a-z-]+|:[a-z-]+(?:\([^)]*\))?)*)\s*$/i,
766
+ );
767
+ if (!m) continue;
768
+ const ancestor = m[1].trim();
769
+ const subject = m[2].toLowerCase();
770
+ const attr = m[3] ?? "";
771
+ // One simple ancestor only: `.a .b button` stays manual.
772
+ if (/[\s>+~]/.test(ancestor)) continue;
773
+ // Subject must stay a bare native element (optional [type=…] / pseudos).
774
+ if (/[.#]/.test(m[4] ?? "")) continue;
775
+ const classes = [...ancestor.matchAll(/\.([A-Za-z_][\w-]*)/g)].map(
776
+ (x) => x[1],
777
+ );
778
+ const id = ancestor.match(/#([A-Za-z_][\w-]*)/)?.[1];
779
+ if (!classes.length && !id) continue;
780
+ const type = attr.match(
781
+ /^\[\s*type\s*=\s*(?:["']?)([\w-]+)(?:["']?)\s*\]$/i,
782
+ )?.[1];
783
+ if (attr && !type) continue;
784
+ out.push({
785
+ selector: part,
786
+ tag: subject,
787
+ type: type?.toLowerCase(),
788
+ classes,
789
+ id,
790
+ });
791
+ }
792
+ return out;
793
+ }
794
+
795
+ function openingEnd(src, i) {
796
+ const n = src.length;
797
+ while (i < n) {
798
+ while (i < n && /\s/.test(src[i])) i++;
799
+ if (src[i] === "/" && src[i + 1] === ">")
800
+ return { end: i + 2, selfClose: true };
801
+ if (src[i] === ">") return { end: i + 1, selfClose: false };
802
+ if (src[i] === "{") {
803
+ i = skipBraces(src, i);
804
+ continue;
805
+ }
806
+ NAME.lastIndex = i;
807
+ const m = NAME.exec(src);
808
+ if (!m) return { end: i, selfClose: false };
809
+ i += m[0].length;
810
+ while (i < n && /\s/.test(src[i])) i++;
811
+ if (src[i] !== "=") continue;
812
+ i++;
813
+ while (i < n && /\s/.test(src[i])) i++;
814
+ const q = src[i];
815
+ if (q === '"' || q === "'") {
816
+ const end = src.indexOf(q, i + 1);
817
+ if (end < 0) return { end: n, selfClose: false };
818
+ i = end + 1;
819
+ } else if (q === "{") i = skipBraces(src, i);
820
+ else return { end: i, selfClose: false };
821
+ }
822
+ return { end: n, selfClose: false };
823
+ }
824
+
825
+ function replacesMatch(replaces, tag, type) {
826
+ for (const r of replaces) {
827
+ const m = /^([a-z]+)(?:\[type=(.+)\])?$/.exec(r);
828
+ if (!m || m[1] !== tag) continue;
829
+ if (!type) return true;
830
+ if (!m[2] || m[2] === type) return true;
831
+ }
832
+ return false;
833
+ }
834
+
835
+ /**
836
+ * Mortar controls in `src` that replace a native element, with literal
837
+ * className/id markers on open host ancestors. Complex className expressions
838
+ * are ignored.
839
+ */
840
+ export function findMortarPlacements(src, locals, namespaces, byExport) {
841
+ const stack = [];
842
+ const placements = [];
843
+ const re = /<\/?([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)(?=[\s/>])/g;
844
+ let m;
845
+ while ((m = re.exec(src))) {
846
+ const at = m.index;
847
+ const name = m[1];
848
+ const isClose = src[at + 1] === "/";
849
+ const host = /^[a-z]/.test(name);
850
+ if (isClose) {
851
+ if (host) {
852
+ for (let i = stack.length - 1; i >= 0; i--) {
853
+ if (stack[i].name === name) {
854
+ stack.length = i;
855
+ break;
856
+ }
857
+ }
858
+ }
859
+ continue;
860
+ }
861
+ const attrsStart = at + m[0].length;
862
+ const { end, selfClose } = openingEnd(src, attrsStart);
863
+ const attrs = jsxAttributes(src, attrsStart);
864
+ let exportName;
865
+ const [ns, member] = name.split(".");
866
+ if (member && namespaces.has(ns)) exportName = member;
867
+ else if (!member) exportName = locals.get(name);
868
+ const replaces = exportName ? byExport.get(exportName) : undefined;
869
+ if (replaces) {
870
+ placements.push({
871
+ exportName,
872
+ replaces,
873
+ frames: stack.map((f) => ({
874
+ classes: new Set(f.classes),
875
+ id: f.id,
876
+ })),
877
+ });
878
+ }
879
+ if (host && !selfClose) {
880
+ const classAttr = attrs.find(
881
+ (a) => a.name === "className" || a.name === "class",
882
+ );
883
+ const idAttr = attrs.find((a) => a.name === "id");
884
+ const classes = (classAttr?.value ?? "").split(/\s+/).filter(Boolean);
885
+ stack.push({
886
+ name,
887
+ classes,
888
+ id: idAttr?.value,
889
+ });
890
+ }
891
+ re.lastIndex = end;
892
+ }
893
+ return placements;
894
+ }
895
+
896
+ function frameMatches(frame, classes, id) {
897
+ if (id && frame.id !== id) return false;
898
+ return classes.every((c) => frame.classes.has(c));
899
+ }
900
+
550
901
  // Inputs with no Mortar equivalent (hidden values, file pickers, sliders).
551
902
  const NATIVE_ONLY = new Set(["hidden", "file", "range", "color", "image"]);
552
903
  const TEXT_LIKE = new Set([
@@ -859,6 +1210,9 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
859
1210
  // tool's mapping; every component it names has existed since 0.1.
860
1211
  let rawElements = replacements(data);
861
1212
  if (!rawElements.size) rawElements = replacements(bundled);
1213
+ const byExport = replacesByExport(data);
1214
+ if (![...byExport.keys()].length)
1215
+ for (const [k, v] of replacesByExport(bundled)) byExport.set(k, v);
862
1216
  // Phrasing-only slots (rendered inside a <p>). Older catalogues fall back
863
1217
  // to this tool's map so Banner/AuthLayout stay checked after upgrade of the
864
1218
  // CLI alone.
@@ -869,6 +1223,10 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
869
1223
  // Raw elements are collected from every JSX file and reported once the
870
1224
  // whole app is known to use Mortar.
871
1225
  const rawHits = [];
1226
+ // Ancestor/native-element CSS rules that set visual properties, matched
1227
+ // later against Mortar controls under a matching host ancestor.
1228
+ const ancestorRules = [];
1229
+ const mortarPlacements = [];
872
1230
 
873
1231
  const files = walk(root);
874
1232
  const hashes = data.agent.sourceHashes ?? {};
@@ -932,6 +1290,7 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
932
1290
  for (const m of css.matchAll(/([^{};]+)\{/g)) {
933
1291
  const selector = m[1].trim();
934
1292
  if (!selector || selector.startsWith("@")) continue;
1293
+ const selAt = m.index + m[0].length - m[1].trimStart().length - 1;
935
1294
  const hits = [
936
1295
  ...[...selector.matchAll(/\.(m-[a-z][a-z0-9-]*)/g)]
937
1296
  .map((x) => x[1])
@@ -946,10 +1305,20 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
946
1305
  "css-override",
947
1306
  "error",
948
1307
  file,
949
- line(m.index + m[0].length - m[1].trimStart().length - 1),
1308
+ line(selAt),
950
1309
  `Overrides Mortar markup (${[...new Set(hits)].join(", ")}).`,
951
1310
  "Remove the override. Use component props, className for layout only, or theme tokens (brandTokens, --m-brand-*). If the kit is wrong, fix it centrally with a pull request.",
952
1311
  );
1312
+ const braceAt = m.index + m[0].length - 1;
1313
+ const body = css.slice(braceAt + 1, closing(css, braceAt));
1314
+ if (!hits.length && hasVisualDeclarations(body)) {
1315
+ for (const target of parseAncestorNativeSelector(selector))
1316
+ ancestorRules.push({
1317
+ file,
1318
+ line: line(selAt),
1319
+ ...target,
1320
+ });
1321
+ }
953
1322
  }
954
1323
  continue;
955
1324
  }
@@ -1140,6 +1509,10 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1140
1509
  }
1141
1510
  if (!imported) continue;
1142
1511
 
1512
+ if (JSX.has(ext) && !emailFile && byExport.size)
1513
+ for (const p of findMortarPlacements(src, locals, namespaces, byExport))
1514
+ mortarPlacements.push(p);
1515
+
1143
1516
  // className tokens on the app's own markup and arbitrary variants.
1144
1517
  for (const m of src.matchAll(
1145
1518
  /\bclass(?:Name)?\s*=\s*(?:\{\s*)?(["'`])([^"'`]*)\1/g,
@@ -1275,6 +1648,47 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1275
1648
  guess ? `Use ${name}="${guess}".` : undefined,
1276
1649
  );
1277
1650
  }
1651
+ // Input adornments: static text in `action`, or absolute decorative
1652
+ // siblings left over from migrating an unlabeled native input.
1653
+ if (exportName === "Input") {
1654
+ const action = attrs.find((a) => a.name === "action");
1655
+ const staticAction =
1656
+ action &&
1657
+ (action.value !== undefined
1658
+ ? true
1659
+ : action.expression
1660
+ ? isStaticInputAction(
1661
+ src.slice(action.expression.start, action.expression.end),
1662
+ )
1663
+ : false);
1664
+ if (staticAction)
1665
+ add(
1666
+ "input-static-action",
1667
+ "warning",
1668
+ file,
1669
+ line(action.index),
1670
+ `<Input> action holds static text; action is for an attached control such as a Button.`,
1671
+ "Use `suffix` (or `prefix`) for end/start text adornments such as `%` or units.",
1672
+ );
1673
+ const elementEnd = jsxElementEnd(src, m[1], afterName, opening);
1674
+ // Use comment-blanked source (not string-blanked): className values
1675
+ // must stay readable so absolute/relative tokens are visible.
1676
+ for (const hit of absoluteAdornmentsBesideInput(
1677
+ src,
1678
+ m.index,
1679
+ elementEnd,
1680
+ )) {
1681
+ const prop = hit.side === "trailing" ? "trailingIcon" : "leadingIcon";
1682
+ add(
1683
+ "input-absolute-adornment",
1684
+ "warning",
1685
+ file,
1686
+ line(hit.index),
1687
+ `Absolutely positioned decorative sibling next to <Input>; it centres against the whole field (including the label).`,
1688
+ `Pass the icon as \`${prop}\` so it sits inside the text box.`,
1689
+ );
1690
+ }
1691
+ }
1278
1692
  // JSX body children on a control with no children slot (e.g. Switch).
1279
1693
  if (
1280
1694
  !opening.selfClosing &&
@@ -1345,6 +1759,24 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1345
1759
  );
1346
1760
  }
1347
1761
 
1762
+ if (usesMortar)
1763
+ for (const rule of ancestorRules) {
1764
+ const hit = mortarPlacements.find(
1765
+ (p) =>
1766
+ replacesMatch(p.replaces, rule.tag, rule.type) &&
1767
+ p.frames.some((f) => frameMatches(f, rule.classes, rule.id)),
1768
+ );
1769
+ if (!hit) continue;
1770
+ add(
1771
+ "ancestor-override",
1772
+ "error",
1773
+ rule.file,
1774
+ rule.line,
1775
+ `Ancestor selector \`${rule.selector}\` restyles Mortar's <${hit.exportName}> (${rule.tag}${rule.type ? `[type=${rule.type}]` : ""}).`,
1776
+ "Remove the override. Use component props, className for layout only, or theme tokens (brandTokens, --m-brand-*). If the kit is wrong, fix it centrally with a pull request.",
1777
+ );
1778
+ }
1779
+
1348
1780
  // Package-level rules.
1349
1781
  let pkgJson;
1350
1782
  const pkgFile = join(root, "package.json");
@@ -2,6 +2,11 @@
2
2
  // CHANGELOG. The audit uses them to suggest the current name for an import, a
3
3
  // prop or a value. tests/cli.test.mjs checks every replacement exists in the
4
4
  // catalogue and every removed prop is gone.
5
+ //
6
+ // Input adornments (audit rules input-static-action / input-absolute-adornment):
7
+ // when migrating an unlabeled native <input> to Mortar's labeled Input, use
8
+ // prefix/suffix for static text and leadingIcon/trailingIcon for decorative
9
+ // icons. Do not keep absolute siblings or put static text in action.
5
10
 
6
11
  export const REMOVED_EXPORTS = {
7
12
  MarketingTone: {