@tonycodes-ui/mortar 0.25.0 → 0.27.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":
@@ -663,6 +665,239 @@ function replacements(data) {
663
665
  map.set(element, [...(map.get(element) ?? []), c.export]);
664
666
  return map;
665
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
+
666
901
  // Inputs with no Mortar equivalent (hidden values, file pickers, sliders).
667
902
  const NATIVE_ONLY = new Set(["hidden", "file", "range", "color", "image"]);
668
903
  const TEXT_LIKE = new Set([
@@ -975,6 +1210,9 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
975
1210
  // tool's mapping; every component it names has existed since 0.1.
976
1211
  let rawElements = replacements(data);
977
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);
978
1216
  // Phrasing-only slots (rendered inside a <p>). Older catalogues fall back
979
1217
  // to this tool's map so Banner/AuthLayout stay checked after upgrade of the
980
1218
  // CLI alone.
@@ -985,6 +1223,10 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
985
1223
  // Raw elements are collected from every JSX file and reported once the
986
1224
  // whole app is known to use Mortar.
987
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 = [];
988
1230
 
989
1231
  const files = walk(root);
990
1232
  const hashes = data.agent.sourceHashes ?? {};
@@ -1048,6 +1290,7 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1048
1290
  for (const m of css.matchAll(/([^{};]+)\{/g)) {
1049
1291
  const selector = m[1].trim();
1050
1292
  if (!selector || selector.startsWith("@")) continue;
1293
+ const selAt = m.index + m[0].length - m[1].trimStart().length - 1;
1051
1294
  const hits = [
1052
1295
  ...[...selector.matchAll(/\.(m-[a-z][a-z0-9-]*)/g)]
1053
1296
  .map((x) => x[1])
@@ -1062,10 +1305,20 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1062
1305
  "css-override",
1063
1306
  "error",
1064
1307
  file,
1065
- line(m.index + m[0].length - m[1].trimStart().length - 1),
1308
+ line(selAt),
1066
1309
  `Overrides Mortar markup (${[...new Set(hits)].join(", ")}).`,
1067
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.",
1068
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
+ }
1069
1322
  }
1070
1323
  continue;
1071
1324
  }
@@ -1256,6 +1509,10 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1256
1509
  }
1257
1510
  if (!imported) continue;
1258
1511
 
1512
+ if (JSX.has(ext) && !emailFile && byExport.size)
1513
+ for (const p of findMortarPlacements(src, locals, namespaces, byExport))
1514
+ mortarPlacements.push(p);
1515
+
1259
1516
  // className tokens on the app's own markup and arbitrary variants.
1260
1517
  for (const m of src.matchAll(
1261
1518
  /\bclass(?:Name)?\s*=\s*(?:\{\s*)?(["'`])([^"'`]*)\1/g,
@@ -1502,6 +1759,24 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1502
1759
  );
1503
1760
  }
1504
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
+
1505
1780
  // Package-level rules.
1506
1781
  let pkgJson;
1507
1782
  const pkgFile = join(root, "package.json");
package/cli/search.mjs CHANGED
@@ -216,6 +216,7 @@ export function searchComponents(
216
216
  category: p.categoryTitle ?? null,
217
217
  description: c.description,
218
218
  capabilities: c.capabilities,
219
+ ...(c.platforms ? { platforms: c.platforms } : {}),
219
220
  score: Math.round(total * 10) / 10,
220
221
  matched,
221
222
  });