@tonycodes-ui/mortar 0.28.1 → 0.29.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
@@ -1375,7 +1375,7 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1375
1375
  "error",
1376
1376
  file,
1377
1377
  line(m.index),
1378
- `Reaches into ${m[0]}; only "${PKG}", "${PKG}/styles.css", "${PKG}/brand" and "${PKG}/email" are public.`,
1378
+ `Reaches into ${m[0]}; only "${PKG}", "${PKG}/styles.css", "${PKG}/brand", "${PKG}/email" and "${PKG}/data-grid" are public.`,
1379
1379
  `Import from "${PKG}" instead, and remove any alias to the package's source.`,
1380
1380
  );
1381
1381
  }
@@ -1442,7 +1442,11 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1442
1442
  }
1443
1443
  continue;
1444
1444
  }
1445
- if (spec !== PKG) {
1445
+ // A component subpath (such as /data-grid) the installed version ships.
1446
+ const entry =
1447
+ spec.startsWith(`${PKG}/`) &&
1448
+ data.agent.entryExports?.[spec.slice(PKG.length)];
1449
+ if (spec !== PKG && !entry) {
1446
1450
  if (spec !== `${PKG}/brand` && spec !== `${PKG}/styles.css`)
1447
1451
  if (!/\/(src|dist)\b/.test(spec))
1448
1452
  add(
@@ -1467,6 +1471,9 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1467
1471
  const named = clause.match(/\{([\s\S]*)\}/);
1468
1472
  if (!named) continue;
1469
1473
  const offset = m.index + m[0].indexOf("{");
1474
+ const known = entry
1475
+ ? new Set([...entry.values, ...entry.types])
1476
+ : exportNames;
1470
1477
  for (const raw of named[1].split(",")) {
1471
1478
  const item = raw.trim();
1472
1479
  if (!item) continue;
@@ -1476,18 +1483,26 @@ export async function auditApp(path = ".", { data: bundled } = {}) {
1476
1483
  .map((s) => s.trim());
1477
1484
  const isType = !!typeOnly || /^type\s/.test(item);
1478
1485
  const at = offset + named[0].indexOf(raw.trimStart() || raw);
1479
- if (!exportNames.has(name)) {
1480
- const removed = REMOVED_EXPORTS[name];
1481
- const guess = removed?.replacement ?? closest(name, exportNames, 3);
1486
+ if (!known.has(name)) {
1487
+ const removed = entry ? undefined : REMOVED_EXPORTS[name];
1488
+ // The name exists, but in another entry point (e.g. DataGrid in /data-grid).
1489
+ const elsewhere = Object.entries(data.agent.entryExports ?? {}).find(
1490
+ ([subpath, list]) =>
1491
+ `${PKG}${subpath}` !== spec &&
1492
+ (list.values.includes(name) || list.types.includes(name)),
1493
+ )?.[0];
1494
+ const guess = removed?.replacement ?? closest(name, known, 3);
1482
1495
  add(
1483
1496
  "unknown-export",
1484
1497
  "error",
1485
1498
  file,
1486
1499
  line(at),
1487
- `${PKG} ${data.version} has no export "${name}".${removed ? " " + removed.note : ""}`,
1488
- guess
1489
- ? `Import ${guess} instead.`
1490
- : "Search the catalogue (mortar search) for the current component.",
1500
+ `${spec} ${data.version} has no export "${name}".${removed ? " " + removed.note : ""}`,
1501
+ elsewhere
1502
+ ? `Import ${name} from "${PKG}${elsewhere}".`
1503
+ : guess
1504
+ ? `Import ${guess} instead.`
1505
+ : "Search the catalogue (mortar search) for the current component.",
1491
1506
  );
1492
1507
  continue;
1493
1508
  }
package/cli/data.mjs CHANGED
@@ -40,6 +40,11 @@ export const GUIDES = {
40
40
  summary:
41
41
  "Transactional email from @tonycodes-ui/mortar/email: emailTheme, the Email components, the templates (verify email, magic link, password reset, invite, receipt, notification) and renderEmail.",
42
42
  },
43
+ "data-grid": {
44
+ file: "docs/data-grid.md",
45
+ summary:
46
+ "DataGrid from @tonycodes-ui/mortar/data-grid: when to use it over DataTable, installing the TanStack peers, client and server mode, controlled state, sorting, filters, search, selection, paging, virtualization and pinned columns.",
47
+ },
43
48
  native: {
44
49
  file: "docs/native.md",
45
50
  summary:
package/cli/packet.mjs CHANGED
@@ -11,8 +11,38 @@ export const THEME_SETUP = `import { ThemeProvider } from "@tonycodes-ui/mortar"
11
11
  <App />
12
12
  </ThemeProvider>`;
13
13
 
14
- const importLine = (data, names) =>
15
- `import { ${[...new Set(names)].sort().join(", ")} } from "${data.packageName}";`;
14
+ /** The package a component is imported from: the root or a subpath entry. */
15
+ const packageOf = (data, name) =>
16
+ data.components.find((c) => c.export === name)?.package ?? data.packageName;
17
+
18
+ /** Import lines for the named components, one per package, the root first. */
19
+ const importLine = (data, names) => {
20
+ const byPackage = new Map();
21
+ for (const name of new Set(names)) {
22
+ const specifier = packageOf(data, name);
23
+ byPackage.set(specifier, [...(byPackage.get(specifier) ?? []), name]);
24
+ }
25
+ return [...byPackage]
26
+ .sort(([a], [b]) =>
27
+ a === data.packageName
28
+ ? -1
29
+ : b === data.packageName
30
+ ? 1
31
+ : a.localeCompare(b),
32
+ )
33
+ .map(
34
+ ([specifier, list]) =>
35
+ `import { ${list.sort().join(", ")} } from "${specifier}";`,
36
+ )
37
+ .join("\n");
38
+ };
39
+
40
+ /** Optional peer dependencies a subpath entry point needs. */
41
+ const ENTRY_PEERS = {
42
+ "/data-grid": ["@tanstack/react-table", "@tanstack/react-virtual"],
43
+ };
44
+ const peersOf = (data, specifier) =>
45
+ ENTRY_PEERS[specifier.slice(data.packageName.length)] ?? [];
16
46
 
17
47
  // The native libraries (docs/native.md): a Swift package and an Android
18
48
  // library, built from the same tokens.
@@ -252,6 +282,7 @@ export function buildPacket(data, { components: names = [], brief } = {}) {
252
282
  if (emails) guides.push("email");
253
283
  const native = !!brief && NATIVE_WORDS.test(brief);
254
284
  if (native) guides.push("native");
285
+ if (selection.some((c) => c.export === "DataGrid")) guides.push("data-grid");
255
286
  return {
256
287
  package: data.packageName,
257
288
  version: data.version,
@@ -266,7 +297,12 @@ export function buildPacket(data, { components: names = [], brief } = {}) {
266
297
  })),
267
298
  }
268
299
  : {}),
269
- install: `npm install ${data.packageName} react react-dom tailwindcss`,
300
+ install: [
301
+ `npm install ${data.packageName} react react-dom tailwindcss`,
302
+ ...new Set(
303
+ selection.flatMap((c) => peersOf(data, c.package ?? data.packageName)),
304
+ ),
305
+ ].join(" "),
270
306
  css: {
271
307
  where: "Your app's Tailwind CSS entry (for example src/index.css).",
272
308
  code: CSS_SETUP,
package/cli/render.mjs ADDED
@@ -0,0 +1,315 @@
1
+ // A rendered audit of a running application that uses Mortar. It opens each
2
+ // URL in a headless browser at a phone and a desktop width, in light and dark,
3
+ // and checks what actually rendered: problems a source scan cannot see, such as
4
+ // controls in one row with different heights or a label that inherits a
5
+ // parent's alignment. It only reads the page; it never clicks or types.
6
+ //
7
+ // Playwright is not a dependency of the kit. The audit loads it from the
8
+ // application (or the kit's own install) and explains how to add it if absent.
9
+ import { createRequire } from "node:module";
10
+ import { resolve } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+
13
+ export const RENDER_RULES = {
14
+ "render-error":
15
+ "The page logs a console error or throws while rendering, in light or dark.",
16
+ "render-missing-styles":
17
+ "Mortar components render without Mortar's stylesheet (no --m-* tokens).",
18
+ "render-box-sizing":
19
+ "Mortar controls render with content-box sizing, usually because Tailwind is not imported before Mortar's styles.",
20
+ "render-row-height":
21
+ "Mortar controls side by side in one row render at different heights.",
22
+ "render-label-align":
23
+ "A Mortar field label is not aligned to the start of its field, usually inherited from a parent's text-align.",
24
+ "render-overflow": "The page scrolls sideways at a phone width (390px).",
25
+ };
26
+
27
+ const WIDTHS = [390, 1280];
28
+
29
+ /** The URLs in a comma-separated list, trimmed, empty entries dropped. */
30
+ export const parseUrls = (text) =>
31
+ String(text ?? "")
32
+ .split(",")
33
+ .map((url) => url.trim())
34
+ .filter(Boolean);
35
+ const SCHEMES = ["light", "dark"];
36
+
37
+ /** Load Playwright from the application first, then from the kit's install. */
38
+ async function loadPlaywright(appRoot) {
39
+ const require = createRequire(resolve(appRoot, "package.json"));
40
+ for (const name of ["playwright", "@playwright/test"]) {
41
+ try {
42
+ return await import(pathToFileURL(require.resolve(name)).href);
43
+ } catch {}
44
+ try {
45
+ return await import(name);
46
+ } catch {}
47
+ }
48
+ throw Error(
49
+ "audit --render needs Playwright: npm install -D playwright && npx playwright install chromium",
50
+ );
51
+ }
52
+
53
+ // Runs in the page. Returns raw observations; the node side turns them into
54
+ // findings so rules and wording live in one place.
55
+ function inspect() {
56
+ const name = (el) => {
57
+ const marker = el.closest("[data-m-component]");
58
+ const label =
59
+ el.querySelector?.("label")?.textContent?.trim() ||
60
+ el.getAttribute?.("aria-label") ||
61
+ el.textContent?.trim().slice(0, 40) ||
62
+ "";
63
+ return `${marker?.dataset.mComponent ?? el.tagName.toLowerCase()}${label ? ` "${label}"` : ""}`;
64
+ };
65
+ const tokens = getComputedStyle(document.documentElement)
66
+ .getPropertyValue("--m-control")
67
+ .trim();
68
+ const components = document.querySelectorAll("[data-m-component]").length;
69
+
70
+ // The visible control of each Mortar field, and default-size buttons.
71
+ const controls = [];
72
+ // Single-line fields only: a TextArea is meant to be taller than its neighbours.
73
+ for (const field of document.querySelectorAll(
74
+ ".m-field[data-m-component]:not(:has(textarea))",
75
+ )) {
76
+ const box = [...field.children].find(
77
+ (child) =>
78
+ child.tagName !== "LABEL" &&
79
+ !child.matches("p, [role=alert], .m-field-feedback") &&
80
+ child.getBoundingClientRect().height > 0,
81
+ );
82
+ if (box) controls.push({ el: box, owner: field });
83
+ }
84
+ for (const button of document.querySelectorAll(
85
+ "button[data-m-component=Button]:not([data-size])",
86
+ ))
87
+ controls.push({ el: button, owner: button });
88
+
89
+ // Group controls by the nearest row container (a horizontal flex or a grid)
90
+ // and by the line they sit on when the row wraps.
91
+ const rowOf = (el) => {
92
+ for (let node = el.parentElement; node; node = node.parentElement) {
93
+ const cs = getComputedStyle(node);
94
+ if (
95
+ (cs.display.endsWith("flex") && cs.flexDirection.startsWith("row")) ||
96
+ cs.display.endsWith("grid")
97
+ )
98
+ return node;
99
+ }
100
+ return null;
101
+ };
102
+ const rows = new Map();
103
+ for (const control of controls) {
104
+ const row = rowOf(control.owner);
105
+ const rect = control.el.getBoundingClientRect();
106
+ if (!row || !rect.width) continue;
107
+ const list = rows.get(row) ?? [];
108
+ list.push({ ...control, rect });
109
+ rows.set(row, list);
110
+ }
111
+ const mismatched = [];
112
+ for (const list of rows.values()) {
113
+ const lines = [];
114
+ for (const item of list) {
115
+ const line = lines.find((l) =>
116
+ l.some(
117
+ (other) =>
118
+ item.rect.top < other.rect.bottom &&
119
+ other.rect.top < item.rect.bottom,
120
+ ),
121
+ );
122
+ if (line) line.push(item);
123
+ else lines.push([item]);
124
+ }
125
+ for (const line of lines) {
126
+ if (line.length < 2) continue;
127
+ const heights = line.map((i) => Math.round(i.rect.height));
128
+ if (Math.max(...heights) - Math.min(...heights) > 1)
129
+ mismatched.push(
130
+ line.map((i) => `${name(i.owner)} ${Math.round(i.rect.height)}px`),
131
+ );
132
+ }
133
+ }
134
+
135
+ const contentBox = [];
136
+ for (const { el, owner } of controls) {
137
+ const input = el.matches("input, select, button")
138
+ ? el
139
+ : el.querySelector("input, select, button");
140
+ if (input && getComputedStyle(input).boxSizing === "content-box")
141
+ contentBox.push(name(owner));
142
+ }
143
+
144
+ const misaligned = [];
145
+ for (const label of document.querySelectorAll(
146
+ ".m-field[data-m-component] > label",
147
+ )) {
148
+ const cs = getComputedStyle(label);
149
+ const rtl = cs.direction === "rtl";
150
+ const start = rtl ? ["right", "start"] : ["left", "start"];
151
+ if (!start.includes(cs.textAlign))
152
+ misaligned.push(
153
+ `${name(label.parentElement)} (text-align: ${cs.textAlign})`,
154
+ );
155
+ }
156
+
157
+ return {
158
+ components,
159
+ tokens: tokens !== "",
160
+ mismatched,
161
+ contentBox,
162
+ misaligned,
163
+ overflow:
164
+ document.documentElement.scrollWidth -
165
+ document.documentElement.clientWidth,
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Audit the rendered pages. Returns findings in the static audit's shape, with
171
+ * the URL in place of a file and no line.
172
+ */
173
+ export async function renderAudit(
174
+ urls,
175
+ { appRoot = ".", executablePath } = {},
176
+ ) {
177
+ const playwright = await loadPlaywright(appRoot);
178
+ // An ES import of the CommonJS package puts its exports on default.
179
+ const chromium = playwright.chromium ?? playwright.default?.chromium;
180
+ const browser = await chromium.launch(
181
+ executablePath || process.env.MORTAR_CHROME
182
+ ? { executablePath: executablePath || process.env.MORTAR_CHROME }
183
+ : {},
184
+ );
185
+ // One finding per problem; the widths and appearances it showed in are
186
+ // listed together instead of repeating it.
187
+ const found = new Map();
188
+ const add = (rule, severity, url, message, fix, where) => {
189
+ const key = `${rule}|${url}|${message}`;
190
+ const entry = found.get(key) ?? {
191
+ rule,
192
+ severity,
193
+ file: url,
194
+ line: null,
195
+ message,
196
+ fix,
197
+ where: [],
198
+ };
199
+ if (where && !entry.where.includes(where)) entry.where.push(where);
200
+ found.set(key, entry);
201
+ };
202
+ const views = SCHEMES.length * WIDTHS.length;
203
+ try {
204
+ for (const url of urls)
205
+ for (const scheme of SCHEMES)
206
+ for (const width of WIDTHS) {
207
+ const page = await browser.newPage({
208
+ viewport: { width, height: 900 },
209
+ colorScheme: scheme,
210
+ });
211
+ const errors = [];
212
+ page.on("pageerror", (e) => errors.push(e.message));
213
+ page.on("console", (m) => {
214
+ if (m.type() !== "error") return;
215
+ // Name the resource a failed load refers to; the browser's own
216
+ // favicon request is not the app's error.
217
+ const resource = m.location()?.url;
218
+ if (/^Failed to load resource/.test(m.text()) && resource) {
219
+ if (!/\/favicon\.ico$/.test(resource))
220
+ errors.push(`${m.text()}: ${resource}`);
221
+ } else errors.push(m.text());
222
+ });
223
+ try {
224
+ // Wait for load, not network idle: long polling, streams and
225
+ // other requests that never finish would keep it from settling.
226
+ await page.goto(url, { waitUntil: "load", timeout: 30_000 });
227
+ } catch (error) {
228
+ add(
229
+ "render-error",
230
+ "error",
231
+ url,
232
+ `Could not load the page: ${error.message.split("\n")[0]}`,
233
+ "Start the app and pass the URL it serves.",
234
+ );
235
+ await page.close();
236
+ continue;
237
+ }
238
+ // Client-rendered apps mount after load: give Mortar's components a
239
+ // moment to appear before checking, without failing pages that
240
+ // have none.
241
+ await page
242
+ .locator("[data-m-component]")
243
+ .first()
244
+ .waitFor({ timeout: 5_000 })
245
+ .catch(() => {});
246
+ await page.evaluate(() => document.fonts?.ready);
247
+ const seenAt = `${scheme} ${width}px`;
248
+ const r = await page.evaluate(inspect);
249
+ for (const message of errors)
250
+ add(
251
+ "render-error",
252
+ "error",
253
+ url,
254
+ message,
255
+ "Fix the error the page reports; it may hide other problems.",
256
+ seenAt,
257
+ );
258
+ if (r.components && !r.tokens)
259
+ add(
260
+ "render-missing-styles",
261
+ "error",
262
+ url,
263
+ `${r.components} Mortar components render without Mortar's tokens.`,
264
+ 'Import "@tonycodes-ui/mortar/styles.css" after Tailwind in your CSS entry.',
265
+ seenAt,
266
+ );
267
+ for (const control of r.contentBox)
268
+ add(
269
+ "render-box-sizing",
270
+ "error",
271
+ url,
272
+ `${control} uses content-box sizing, so it renders taller than its neighbours.`,
273
+ 'Import Tailwind before Mortar (@import "tailwindcss"; then @import "@tonycodes-ui/mortar/styles.css").',
274
+ seenAt,
275
+ );
276
+ for (const line of r.mismatched)
277
+ add(
278
+ "render-row-height",
279
+ "warning",
280
+ url,
281
+ `Controls in one row have different heights: ${line.join(", ")}.`,
282
+ "Use the same control kind and size in a row, and do not set heights on Mortar controls. If every control is a Mortar default, report it to the kit.",
283
+ seenAt,
284
+ );
285
+ for (const label of r.misaligned)
286
+ add(
287
+ "render-label-align",
288
+ "warning",
289
+ url,
290
+ `${label} is not start-aligned.`,
291
+ "Remove text-align from the field's container and set alignment on your own text. If the container is a Mortar component, report it to the kit.",
292
+ seenAt,
293
+ );
294
+ if (width === 390 && r.overflow > 1)
295
+ add(
296
+ "render-overflow",
297
+ "warning",
298
+ url,
299
+ `The page is ${r.overflow}px wider than a 390px screen.`,
300
+ "Find the element wider than the screen; let it wrap, scroll inside its own container, or use responsive props.",
301
+ seenAt,
302
+ );
303
+ await page.close();
304
+ }
305
+ } finally {
306
+ await browser.close();
307
+ }
308
+ return [...found.values()].map(({ where, ...finding }) => ({
309
+ ...finding,
310
+ message:
311
+ where.length && where.length < views
312
+ ? `${finding.message} Seen in ${where.join(", ")}.`
313
+ : finding.message,
314
+ }));
315
+ }
package/cli/tools.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // The MCP tools. Each handler takes validated arguments and returns a plain
2
2
  // object (serialised as JSON text) or a string (returned as text).
3
+ import { parseUrls, renderAudit, RENDER_RULES } from "./render.mjs";
3
4
  import { GUIDES } from "./data.mjs";
4
5
  import { searchComponents } from "./search.mjs";
5
6
  import { componentDetail, buildPacket } from "./packet.mjs";
@@ -191,11 +192,32 @@ export const TOOLS = [
191
192
  description:
192
193
  "The application directory (where its package.json is). Relative paths resolve from the server's working directory. Defaults to it.",
193
194
  },
195
+ render: {
196
+ type: "string",
197
+ description: `Comma-separated URLs of the running app's pages. When set, each page is also opened in a headless browser at 390px and 1280px, light and dark, and checked for: ${Object.entries(
198
+ RENDER_RULES,
199
+ )
200
+ .map(([k, v]) => `${k} (${v.replace(/\.$/, "")})`)
201
+ .join(
202
+ "; ",
203
+ )}. Needs Playwright installed in the app; it only reads the pages.`,
204
+ },
194
205
  },
195
206
  additionalProperties: false,
196
207
  },
197
- annotations: { readOnlyHint: true, openWorldHint: false },
198
- run: (data, { path = "." }) => auditApp(path, { data }),
208
+ // With render, it opens the given URLs in a headless browser.
209
+ annotations: { readOnlyHint: true, openWorldHint: true },
210
+ run: async (data, { path = ".", render }) => {
211
+ const report = await auditApp(path, { data });
212
+ if (render) {
213
+ const urls = parseUrls(render);
214
+ const rendered = await renderAudit(urls, { appRoot: report.root });
215
+ report.findings.push(...rendered);
216
+ for (const f of rendered) report.summary[f.severity]++;
217
+ report.rendered = urls;
218
+ }
219
+ return report;
220
+ },
199
221
  },
200
222
  ];
201
223