@tonycodes-ui/mortar 0.23.0 → 0.25.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
@@ -53,6 +53,12 @@ export const RULES = {
53
53
  "raw-element":
54
54
  "A raw HTML element (such as <table> or <select>) that a Mortar component replaces, in an app that uses Mortar.",
55
55
  "legacy-package": `A dependency or import of the retired ${LEGACY_PKG}; install and import @tonycodes-ui/mortar instead (see the CHANGELOG migration note).`,
56
+ "invalid-phrasing":
57
+ "A block HTML element in a phrasing-only slot that Mortar renders inside a <p>.",
58
+ "input-static-action":
59
+ "Static text passed to Input.action; use prefix or suffix instead.",
60
+ "input-absolute-adornment":
61
+ "An absolutely positioned decorative sibling of Input; use leadingIcon or trailingIcon.",
56
62
  "limited-data": "The audit could not use the installed version's own data.",
57
63
  };
58
64
 
@@ -322,6 +328,7 @@ function jsxOpening(src, i) {
322
328
  i = end + 1;
323
329
  } else if (q === "{") {
324
330
  const end = skipBraces(src, i);
331
+ attr.expression = { start: i + 1, end: end - 1 };
325
332
  const inner = src.slice(i + 1, end - 1).trim();
326
333
  const literal = inner.match(/^(["'`])([^"'`$\\]*)\1$/);
327
334
  if (literal) attr.value = literal[2];
@@ -335,10 +342,15 @@ function jsxOpening(src, i) {
335
342
 
336
343
  /**
337
344
  * The attributes of a JSX opening tag whose name ends at `i`: name, offset and,
338
- * for string literals (`a="x"` or `a={"x"}`), the value.
345
+ * for string literals (`a="x"` or `a={"x"}`), the value. Brace values also get
346
+ * `expression: { start, end }` covering the inner text. The returned array has
347
+ * `end` (index after the opening tag) and `selfClosing`.
339
348
  */
340
349
  export function jsxAttributes(src, i) {
341
- return jsxOpening(src, i).attrs;
350
+ const { attrs, end, selfClosing } = jsxOpening(src, i);
351
+ attrs.end = end;
352
+ attrs.selfClosing = selfClosing;
353
+ return attrs;
342
354
  }
343
355
 
344
356
  /**
@@ -371,6 +383,208 @@ export function jsxHasChildren(src, bodyStart, tagName) {
371
383
  return false;
372
384
  }
373
385
 
386
+ /** HTML elements that cannot nest inside a `<p>` (obvious block tags). */
387
+ export const PHRASING_BLOCK_TAGS = new Set([
388
+ "address",
389
+ "article",
390
+ "aside",
391
+ "blockquote",
392
+ "div",
393
+ "dl",
394
+ "dt",
395
+ "dd",
396
+ "fieldset",
397
+ "figcaption",
398
+ "figure",
399
+ "footer",
400
+ "form",
401
+ "h1",
402
+ "h2",
403
+ "h3",
404
+ "h4",
405
+ "h5",
406
+ "h6",
407
+ "header",
408
+ "hr",
409
+ "li",
410
+ "main",
411
+ "nav",
412
+ "ol",
413
+ "p",
414
+ "pre",
415
+ "section",
416
+ "table",
417
+ "ul",
418
+ ]);
419
+
420
+ const BLOCK_TAG = /<([a-z][a-z0-9]*)(?=[\s/>])/g;
421
+
422
+ /**
423
+ * Offsets of obvious block HTML tags in `src.slice(start, end)`.
424
+ * Strings should already be blanked so markup inside quotes is ignored.
425
+ */
426
+ export function blockTagsIn(src, start = 0, end = src.length) {
427
+ const hits = [];
428
+ BLOCK_TAG.lastIndex = start;
429
+ let m;
430
+ while ((m = BLOCK_TAG.exec(src)) && m.index < end) {
431
+ if (PHRASING_BLOCK_TAGS.has(m[1])) hits.push({ tag: m[1], index: m.index });
432
+ }
433
+ return hits;
434
+ }
435
+
436
+ /**
437
+ * The [start, end) range of JSX children for the element whose name is
438
+ * `tagName` and whose attributes start at `afterName`. Null when self-closing
439
+ * or the closing tag is missing.
440
+ */
441
+ export function jsxChildrenRange(src, tagName, afterName) {
442
+ const opening = jsxOpening(src, afterName);
443
+ if (opening.selfClosing) return null;
444
+ const start = opening.end;
445
+ const open = new RegExp(`<${escapeRegExp(tagName)}(?=[\\s/>])`, "g");
446
+ const close = new RegExp(`</${escapeRegExp(tagName)}\\s*>`, "g");
447
+ let depth = 1;
448
+ let i = start;
449
+ while (i < src.length && depth > 0) {
450
+ open.lastIndex = i;
451
+ close.lastIndex = i;
452
+ const nextOpen = open.exec(src);
453
+ const nextClose = close.exec(src);
454
+ if (!nextClose) return null;
455
+ if (nextOpen && nextOpen.index < nextClose.index) {
456
+ depth++;
457
+ i = nextOpen.index + nextOpen[0].length;
458
+ } else {
459
+ depth--;
460
+ if (depth === 0) return { start, end: nextClose.index };
461
+ i = nextClose.index + nextClose[0].length;
462
+ }
463
+ }
464
+ return null;
465
+ }
466
+
467
+ function escapeRegExp(s) {
468
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
469
+ }
470
+
471
+ /** Export name → phrasing-only prop names from each contract's `phrasingSlots`. */
472
+ function phrasingSlotMap(data) {
473
+ const map = new Map();
474
+ for (const c of data.components ?? []) {
475
+ const slots = c.contract?.phrasingSlots;
476
+ if (slots?.length) map.set(c.export, slots);
477
+ }
478
+ return map;
479
+ }
480
+
481
+ /** End index of the JSX element that opens with `tagName` at `afterName`. */
482
+ function jsxElementEnd(src, tagName, afterName, opening) {
483
+ if (opening.selfClosing) return opening.end;
484
+ const body = jsxChildrenRange(src, tagName, afterName);
485
+ if (!body) return opening.end;
486
+ const close = src
487
+ .slice(body.end)
488
+ .match(new RegExp(`^</${escapeRegExp(tagName)}\\s*>`));
489
+ return body.end + (close ? close[0].length : 0);
490
+ }
491
+
492
+ /**
493
+ * True when an `action={…}` expression is obvious static end content (a string
494
+ * or a noninteractive span/fragment), not an attached control.
495
+ */
496
+ export function isStaticInputAction(expression) {
497
+ const inner = expression.trim();
498
+ if (!inner) return false;
499
+ if (/^(["'`])([^"'`$\\]*)\1$/.test(inner)) return true;
500
+ if (/\bon[A-Z]\w*\s*=/.test(inner) || /\bhref\s*=/.test(inner)) return false;
501
+ if (/<\/?(?:button|a|input|select|textarea)\b/i.test(inner)) return false;
502
+ if (/<[A-Z][\w$]*\b/.test(inner)) return false;
503
+ if (/^<>\s*[^<{]+?\s*<\/>$/.test(inner)) return true;
504
+ if (/^<\s*span\b[^>]*>\s*[^<{]+?\s*<\/\s*span\s*>$/i.test(inner)) return true;
505
+ return false;
506
+ }
507
+
508
+ /**
509
+ * Absolutely positioned decorative siblings near a Mortar Input, typically
510
+ * left over from wrapping an unlabeled native input. Bounded: string
511
+ * `className` literals only, a nearby `relative` wrapper, and only the
512
+ * immediate sibling before or after this Input (so later Inputs in the same
513
+ * file are not flagged for an earlier icon).
514
+ */
515
+ export function absoluteAdornmentsBesideInput(src, inputStart, inputEnd) {
516
+ const windowStart = Math.max(0, inputStart - 1000);
517
+ const windowEnd = Math.min(src.length, inputEnd + 1000);
518
+ const before = src.slice(windowStart, inputStart);
519
+ const after = src.slice(inputEnd, windowEnd);
520
+ const hasRelative = (slice) =>
521
+ /\bclass(?:Name)?\s*=\s*(?:\{\s*)?(["'`])([^"'`]*\brelative\b[^"'`]*)\1/.test(
522
+ slice,
523
+ );
524
+ if (!hasRelative(before)) return [];
525
+ const hits = [];
526
+ const open =
527
+ /<(svg|img|span|i|div|em)\b(?=[^>]*\bclass(?:Name)?\s*=\s*(?:\{\s*)?(["'`])([^"'`]*\babsolute\b[^"'`]*)\2)[^>]*>/i;
528
+ const sideFrom = (cls, fallback) =>
529
+ /\b(?:right-|end-|inset-e|inset-inline-end)/.test(cls)
530
+ ? "trailing"
531
+ : /\b(?:left-|start-|inset-s|inset-inline-start)/.test(cls)
532
+ ? "leading"
533
+ : fallback;
534
+ const decorative = (tag, openText) => {
535
+ if (/\bon[A-Z]\w*\s*=/.test(openText) || /\bhref\s*=/.test(openText))
536
+ return false;
537
+ return (
538
+ tag === "svg" ||
539
+ tag === "img" ||
540
+ /\baria-hidden\b/.test(openText) ||
541
+ tag === "span" ||
542
+ tag === "i" ||
543
+ tag === "em" ||
544
+ tag === "div"
545
+ );
546
+ };
547
+ // Immediate previous sibling: the last absolute tag in `before`, with only
548
+ // whitespace (and its own closing) between it and the Input.
549
+ {
550
+ let last;
551
+ const re = new RegExp(open.source, "gi");
552
+ let m;
553
+ while ((m = re.exec(before))) last = m;
554
+ if (last) {
555
+ const tag = last[1].toLowerCase();
556
+ const cls = last[3];
557
+ const openText = last[0];
558
+ const from = last.index;
559
+ let afterOpen = from + openText.length;
560
+ if (!/\/>\s*$/.test(openText)) {
561
+ const close = before
562
+ .slice(afterOpen)
563
+ .match(new RegExp(`^[\\s\\S]*?</${tag}\\s*>`, "i"));
564
+ if (close) afterOpen += close[0].length;
565
+ }
566
+ if (/^\s*$/.test(before.slice(afterOpen)) && decorative(tag, openText))
567
+ hits.push({
568
+ index: windowStart + from,
569
+ side: sideFrom(cls, "leading"),
570
+ });
571
+ }
572
+ }
573
+ // Immediate next sibling: the first absolute tag in `after`, with only
574
+ // whitespace between the Input and it.
575
+ {
576
+ const m = after.match(new RegExp("^\\s*" + open.source, "i"));
577
+ if (m && decorative(m[1].toLowerCase(), m[0].trimStart() || m[0])) {
578
+ const absAt = m[0].indexOf("<");
579
+ hits.push({
580
+ index: inputEnd + absAt,
581
+ side: sideFrom(m[3], "trailing"),
582
+ });
583
+ }
584
+ }
585
+ return hits;
586
+ }
587
+
374
588
  /**
375
589
  * The text with string and template-literal contents blanked, so HTML inside
376
590
  * strings (an email template, say) is not read as JSX. Lengths and newlines
@@ -761,6 +975,13 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
761
975
  // tool's mapping; every component it names has existed since 0.1.
762
976
  let rawElements = replacements(data);
763
977
  if (!rawElements.size) rawElements = replacements(bundled);
978
+ // Phrasing-only slots (rendered inside a <p>). Older catalogues fall back
979
+ // to this tool's map so Banner/AuthLayout stay checked after upgrade of the
980
+ // CLI alone.
981
+ const bundledPhrasing = phrasingSlotMap(bundled);
982
+ const dataPhrasing = phrasingSlotMap(data);
983
+ const phrasingSlotsOf = (exportName) =>
984
+ dataPhrasing.get(exportName) ?? bundledPhrasing.get(exportName) ?? [];
764
985
  // Raw elements are collected from every JSX file and reported once the
765
986
  // whole app is known to use Mortar.
766
987
  const rawHits = [];
@@ -1097,6 +1318,8 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1097
1318
  });
1098
1319
 
1099
1320
  if (!JSX.has(ext)) continue;
1321
+ // Blank string contents so "<div>" inside a quote is not read as a tag.
1322
+ const jsx = blankStrings(src);
1100
1323
  // JSX opening tags of Mortar components.
1101
1324
  const tag = /<([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?)(?=[\s/>])/g;
1102
1325
  for (const m of src.matchAll(tag)) {
@@ -1121,8 +1344,10 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1121
1344
  const propTypes = component.contract.propTypes;
1122
1345
  if (!propTypes) continue;
1123
1346
  const accepts = data.accepts(component);
1124
- const opening = jsxOpening(src, m.index + m[0].length);
1125
- for (const attr of opening.attrs) {
1347
+ const afterName = m.index + m[0].length;
1348
+ const opening = jsxOpening(src, afterName);
1349
+ const attrs = opening.attrs;
1350
+ for (const attr of attrs) {
1126
1351
  const name = attr.name;
1127
1352
  if (name === "key" || /[-:]/.test(name)) continue;
1128
1353
  if (!accepts.has(name)) {
@@ -1166,6 +1391,47 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1166
1391
  guess ? `Use ${name}="${guess}".` : undefined,
1167
1392
  );
1168
1393
  }
1394
+ // Input adornments: static text in `action`, or absolute decorative
1395
+ // siblings left over from migrating an unlabeled native input.
1396
+ if (exportName === "Input") {
1397
+ const action = attrs.find((a) => a.name === "action");
1398
+ const staticAction =
1399
+ action &&
1400
+ (action.value !== undefined
1401
+ ? true
1402
+ : action.expression
1403
+ ? isStaticInputAction(
1404
+ src.slice(action.expression.start, action.expression.end),
1405
+ )
1406
+ : false);
1407
+ if (staticAction)
1408
+ add(
1409
+ "input-static-action",
1410
+ "warning",
1411
+ file,
1412
+ line(action.index),
1413
+ `<Input> action holds static text; action is for an attached control such as a Button.`,
1414
+ "Use `suffix` (or `prefix`) for end/start text adornments such as `%` or units.",
1415
+ );
1416
+ const elementEnd = jsxElementEnd(src, m[1], afterName, opening);
1417
+ // Use comment-blanked source (not string-blanked): className values
1418
+ // must stay readable so absolute/relative tokens are visible.
1419
+ for (const hit of absoluteAdornmentsBesideInput(
1420
+ src,
1421
+ m.index,
1422
+ elementEnd,
1423
+ )) {
1424
+ const prop = hit.side === "trailing" ? "trailingIcon" : "leadingIcon";
1425
+ add(
1426
+ "input-absolute-adornment",
1427
+ "warning",
1428
+ file,
1429
+ line(hit.index),
1430
+ `Absolutely positioned decorative sibling next to <Input>; it centres against the whole field (including the label).`,
1431
+ `Pass the icon as \`${prop}\` so it sits inside the text box.`,
1432
+ );
1433
+ }
1434
+ }
1169
1435
  // JSX body children on a control with no children slot (e.g. Switch).
1170
1436
  if (
1171
1437
  !opening.selfClosing &&
@@ -1186,6 +1452,38 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1186
1452
  : `See the contract: mortar component ${exportName}.`,
1187
1453
  );
1188
1454
  }
1455
+ // Phrasing-only slots: block HTML children inside a <p> are invalid.
1456
+ const slots = phrasingSlotsOf(exportName);
1457
+ if (!slots.length) continue;
1458
+ const reportBlock = (slot, hit) =>
1459
+ add(
1460
+ "invalid-phrasing",
1461
+ "error",
1462
+ file,
1463
+ line(hit.index),
1464
+ `<${exportName}> ${slot} is phrasing-only (rendered inside a <p>); <${hit.tag}> is a block element.`,
1465
+ slot === "children"
1466
+ ? "Pass text, a link or emphasis. For a full section, use Section."
1467
+ : "Pass a string or inline markup (links, emphasis), not a nested <p> or other block element.",
1468
+ );
1469
+ for (const slot of slots) {
1470
+ const attr = attrs.find((a) => a.name === slot);
1471
+ if (attr?.expression) {
1472
+ for (const hit of blockTagsIn(
1473
+ jsx,
1474
+ attr.expression.start,
1475
+ attr.expression.end,
1476
+ ))
1477
+ reportBlock(slot, hit);
1478
+ continue;
1479
+ }
1480
+ if (attr) continue; // string literal or bare boolean — no JSX blocks
1481
+ if (slot !== "children" || opening.selfClosing) continue;
1482
+ const body = jsxChildrenRange(src, m[1], afterName);
1483
+ if (!body) continue;
1484
+ for (const hit of blockTagsIn(jsx, body.start, body.end))
1485
+ reportBlock(slot, hit);
1486
+ }
1189
1487
  }
1190
1488
  }
1191
1489
 
@@ -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: {