Skip to content

Commit e5d89f7

Browse files
feat(check): flag connectors that point at nothing and stylesheets that leak into the frame (#3736)
* feat(lint): catch leftover marker heads and guessed marked shafts Dash-draw on a marked path shows the arrowhead before the shaft exists. A long marked path that misses every node in both user and screen space is the same detach as the CTM-paste bug, without the counterfactual. * feat(check): flag orphan connectors and unbalanced style tags Catch a visible shaft while fewer than two nodes are on stage (enter-early / exit-late), and extra </style> that dumps CSS onto the frame. Co-authored-by: Cursor <[email protected]> * fix(check): judge connector_orphan by the shaft's own endpoints The rule counted anchors stage-wide and skipped whenever two were on. That tier is every visible text-bearing or opaque element under 15% of the stage, so a title and a footer alone satisfied it — the check could not fire on a composition that had any chrome, which is all of them. Endpoints are now resolved per shaft, against candidates gathered by layout instead of by visibility, so a node hidden with opacity:0 still owns the endpoint that meets it and its visibility is what the rule tests. An endpoint that meets no node is left to connector_detached. * revert(lint): drop the marker rules this repo would only duplicate marker_orient_typo and marker_dash_draw_on already run in Zephyr's Python connector lint, down to the same regexes and the same message and fixHint strings. Zephyr concatenates its local findings onto this bridge's result with no dedupe, so shipping them here reports each one twice and counts it twice, and every later edit has to land in two places. The browser-check work stays: a marked shaft that meets no node, and an orphan shaft, are both runtime facts this repo can see and a source-reading rule cannot. * chore(check): drop the comments added with the orphan rewrite * fix(check): score orphan and detach on overflow-opted connector layers Allow-overflow is a clip opt-out, not a lifecycle skip. Orphan now uses the same connector names as detach so flow and arrow shafts are judged. * fix(check): see axis-aligned shafts, and script tags closed with a space connector_orphan gated on isVisibleElement, which rejects anything whose bounding box has no height or width. A straight horizontal or vertical connector is exactly that, and it is the common shape, so the rule was blind to most of what it exists to catch: across 47 production compositions it produced nothing. It now tests paint -- display, visibility and the opacity chain -- and leaves size to the 80px chord floor it already had. The same 47 compositions now yield three findings, each naming the endpoint that is still dark. unbalanced_style_tags stripped scripts with a regex that only matched `</script>`. `</script >` is valid, so the script survived the strip and a `"</style>"` string literal inside it counted toward the tag balance, reporting an error on a composition whose tags are paired. Both the strip and the closer count now tolerate whitespace before the `>`, which is also what CodeQL flagged on this branch. * fix(lint): count style tags in one pass instead of stripping scripts CodeQL reads the `source.replace(/<script.../)` as an incomplete HTML sanitizer. It was never one — the rule only needs to not count `<style` tokens that live inside a script string. A single alternation scan, where the script branch consumes the whole block, gets the same counts without a replace. * test(check): cover the two orphan guards that no fixture was crossing Neutering `shaftIsPainted`'s opacity check, or the endpoint proximity threshold, left the suite green. Both are false-positive guards: a connector staged hidden before its reveal, and a hidden element that happens to be the nearest thing to an endpoint without belonging to it. The hidden-shaft case now runs over all four ways a shaft can be invisible, so the display and visibility clauses are crossed too. * test: pin the two boundaries raised in review A closer inside an html comment is already dropped upstream by stripHtmlComments, so the rule never sees it. The test fails if that stripping regresses; adding a comment branch to the rule's own scan would have reintroduced the polynomial-redos pattern that stripper exists to avoid. A node hidden with display:none has no geometry, so nothing can place it near an endpoint and connector_orphan stays silent. connector_detached does not pick it up either, since it allows a half-attached shaft by design. That case is uncovered, and the fixture says so. * fix(check): type the hidden-shaft fixture table as a style record * fix(check): key connector_orphan by geometry and let a live node win the endpoint Two defects found in review. connector_orphan was persistence-tiered but absent from the geometry key, so several id-less shafts orphaning at one sample each collapsed into a single finding that then read as held rather than transient. On the 47 corpus compositions this recovers 9 findings across 5 compositions where 3 across 2 were reported; one composition fades its nodes and its connectors on a shared stagger, so four shafts each outlive a different node and only one of the four survived the collapse. The endpoint scan took the nearest candidate and asked whether that one was hidden, without asking whether a visible box was also in range. A staged halo sitting on the node it belongs to produced a finding naming the halo. A visible candidate within threshold now settles the endpoint. Fixtures added for both, and for the two guards a mutation sweep found unpinned: the connector-shape test and the dash-offset skip. * test(check): kill every surviving mutant in the connector_orphan path Seven guards still passed the suite when deleted: the four candidate filters, the connector layer's own visibility gate, the defs/marker skip and the chord floor. Each now has a fixture where that guard alone decides the outcome. The earlier sweep that missed them was mutating the wrong copy of a shared line — connectorAnchorRects and connectorEndpointCandidates carry the same filter text, and a first-match replace edited the detached one. Mutations are scoped by enclosing function now. * test(check): order the halo before the node it hides under The halo fixture proved nothing. Both boxes contain the endpoint, so both score gap 0, and the strict tie-break keeps whichever comes first in document order — which was the visible node. The old code picked the same winner and stayed silent too. Putting the halo first makes the tie-break hand it the slot, so only the visible-candidate check keeps the endpoint attached. --------- Co-authored-by: Cursor <[email protected]>
1 parent dc9fb67 commit e5d89f7

7 files changed

Lines changed: 702 additions & 6 deletions

File tree

‎packages/cli/src/commands/layout-audit.browser.js‎

Lines changed: 120 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1300,7 +1300,7 @@
13001300
const threshold = Math.max(32, Math.min(rootRect.width, rootRect.height) * 0.02);
13011301
const MIN_CONNECTOR_CHORD_PX = 8;
13021302
for (const svg of Array.from(root.querySelectorAll("svg"))) {
1303-
if (!isVisibleElement(svg) || hasAllowOverflowFlag(svg)) continue;
1303+
if (!isVisibleElement(svg)) continue;
13041304
for (const path of Array.from(svg.querySelectorAll("path"))) {
13051305
if (path.closest(CONNECTOR_SKIP_CONTAINERS)) continue;
13061306
if (!isConnectorPath(svg, path)) continue;
@@ -1333,7 +1333,16 @@
13331333
// Paste-into-`d` bug: both raw endpoints land on distinct anchors as screen pixels.
13341334
const userStartKey = attachmentKey(user.start);
13351335
const userEndKey = attachmentKey(user.end);
1336-
if (!userStartKey || !userEndKey || userStartKey === userEndKey) continue;
1336+
const pasteBug = Boolean(userStartKey && userEndKey && userStartKey !== userEndKey);
1337+
// Guessed marked shaft: both frames miss. Same-anchor grazes attach in user-space
1338+
// and must stay skipped. Name-only decorative flow/arrow paths stay skipped.
1339+
// 80px keeps short marker glyphs (chevrons, tips) out.
1340+
const markedMiss =
1341+
renderedChord >= 80 &&
1342+
!userStartKey &&
1343+
!userEndKey &&
1344+
(path.hasAttribute("marker-start") || path.hasAttribute("marker-end"));
1345+
if (!pasteBug && !markedMiss) continue;
13371346
const gap = Math.round(
13381347
Math.min(
13391348
Math.min(...anchors.compact.map((a) => distanceToRect(rendered.start, a.rect))),
@@ -1346,7 +1355,113 @@
13461355
time,
13471356
selector: selectorFor(path),
13481357
containerSelector: selectorFor(svg),
1349-
message: `Connector path endpoints render ${gap}px from the nearest anchorable element, but the path's user-space coordinates would attach if read as screen pixels — screen/viewport numbers were likely written into SVG \`d\` without inverting the CTM.`,
1358+
message: pasteBug
1359+
? `Connector path endpoints render ${gap}px from the nearest anchorable element, but the path's user-space coordinates would attach if read as screen pixels — screen/viewport numbers were likely written into SVG \`d\` without inverting the CTM.`
1360+
: `Connector path endpoints render ${gap}px from the nearest anchorable element — a marked shaft that meets no node.`,
1361+
rect: toRect({
1362+
left: Math.min(rendered.start.x, rendered.end.x),
1363+
top: Math.min(rendered.start.y, rendered.end.y),
1364+
right: Math.max(rendered.start.x, rendered.end.x),
1365+
bottom: Math.max(rendered.start.y, rendered.end.y),
1366+
width: Math.abs(rendered.end.x - rendered.start.x),
1367+
height: Math.abs(rendered.end.y - rendered.start.y),
1368+
}),
1369+
fixHint: pasteBug
1370+
? "Convert measured screen coordinates into the SVG's user space (subtract the SVG rect / invert getScreenCTM) before writing path `d`, and keep the SVG a direct child of the stage."
1371+
: "Measure the settled node boxes and write `d` in the SVG's user space (invert getScreenCTM), or grow a layout-owned shaft from the source node.",
1372+
});
1373+
}
1374+
}
1375+
return issues;
1376+
}
1377+
1378+
function shaftIsPainted(path) {
1379+
if (IGNORE_TAGS.has(path.tagName) || hasIgnoreFlag(path)) return false;
1380+
const style = getComputedStyle(path);
1381+
if (
1382+
style.display === "none" ||
1383+
style.visibility === "hidden" ||
1384+
style.visibility === "collapse"
1385+
) {
1386+
return false;
1387+
}
1388+
return opacityChain(path) >= 0.2;
1389+
}
1390+
1391+
function shaftDashHidden(path) {
1392+
if (typeof path.getTotalLength !== "function") return false;
1393+
let total;
1394+
try {
1395+
total = path.getTotalLength();
1396+
} catch {
1397+
return false;
1398+
}
1399+
if (!Number.isFinite(total) || total <= 0) return false;
1400+
const style = getComputedStyle(path);
1401+
const offset = Number.parseFloat(style.strokeDashoffset || "0");
1402+
const dash = Number.parseFloat(String(style.strokeDasharray || "").split(/[\s,]+/)[0] || "0");
1403+
return offset >= total * 0.9 && dash >= total * 0.9;
1404+
}
1405+
1406+
function connectorEndpointCandidates(root, rootRect) {
1407+
const candidates = [];
1408+
const rootArea = rectArea(rootRect);
1409+
for (const element of Array.from(root.querySelectorAll("*"))) {
1410+
if (element.closest("svg") || IGNORE_TAGS.has(element.tagName) || hasIgnoreFlag(element))
1411+
continue;
1412+
const style = getComputedStyle(element);
1413+
const opaque = RASTER_TAGS.has(element.tagName) || hasOpaqueBackground(style);
1414+
if (!opaque && !textContentFor(element)) continue;
1415+
const rect = toRect(element.getBoundingClientRect());
1416+
const area = rectArea(rect);
1417+
if (area < 400 || area > rootArea * 0.15) continue;
1418+
candidates.push({ rect, element });
1419+
}
1420+
return candidates;
1421+
}
1422+
1423+
function connectorOrphanIssues(root, rootRect, time) {
1424+
const issues = [];
1425+
let candidates = null;
1426+
const threshold = Math.max(32, Math.min(rootRect.width, rootRect.height) * 0.02);
1427+
for (const svg of Array.from(root.querySelectorAll("svg"))) {
1428+
if (!isVisibleElement(svg)) continue;
1429+
for (const path of Array.from(svg.querySelectorAll("path"))) {
1430+
if (path.closest(CONNECTOR_SKIP_CONTAINERS)) continue;
1431+
if (!isConnectorPath(svg, path)) continue;
1432+
if (!shaftIsPainted(path) || shaftDashHidden(path)) continue;
1433+
const user = pathUserEndpoints(path);
1434+
const rendered = pathScreenEndpoints(svg, path, user);
1435+
if (!user || !rendered) continue;
1436+
const renderedChord = Math.hypot(
1437+
rendered.end.x - rendered.start.x,
1438+
rendered.end.y - rendered.start.y,
1439+
);
1440+
if (renderedChord < 80) continue;
1441+
if (candidates === null) candidates = connectorEndpointCandidates(root, rootRect);
1442+
const dark = [];
1443+
for (const point of [rendered.start, rendered.end]) {
1444+
let best = null;
1445+
let attached = false;
1446+
for (const candidate of candidates) {
1447+
const gap = distanceToRect(point, candidate.rect);
1448+
if (gap > threshold) continue;
1449+
if (isVisibleElement(candidate.element)) {
1450+
attached = true;
1451+
break;
1452+
}
1453+
if (best === null || gap < best.gap) best = { gap, candidate };
1454+
}
1455+
if (!attached && best !== null) dark.push(best.candidate);
1456+
}
1457+
if (dark.length === 0) continue;
1458+
issues.push({
1459+
code: "connector_orphan",
1460+
severity: "warning",
1461+
time,
1462+
selector: selectorFor(path),
1463+
containerSelector: selectorFor(svg),
1464+
message: `Connector shaft is visible while ${dark.length === 2 ? "both endpoints are" : `its endpoint ${selectorFor(dark[0].element)} is`} not on stage.`,
13501465
rect: toRect({
13511466
left: Math.min(rendered.start.x, rendered.end.x),
13521467
top: Math.min(rendered.start.y, rendered.end.y),
@@ -1356,7 +1471,7 @@
13561471
height: Math.abs(rendered.end.y - rendered.start.y),
13571472
}),
13581473
fixHint:
1359-
"Convert measured screen coordinates into the SVG's user space (subtract the SVG rect / invert getScreenCTM) before writing path `d`, and keep the SVG a direct child of the stage.",
1474+
"Show the shaft only after both ends are on, and hide it with the earlier exit. Do not give the line its own clock.",
13601475
});
13611476
}
13621477
}
@@ -1467,6 +1582,7 @@
14671582
issues.push(...escaped.issues);
14681583
issues.push(...panelOutOfCanvasIssues(root, rootRect, time, tolerance, escaped.flagged));
14691584
issues.push(...connectorDetachmentIssues(root, rootRect, time));
1585+
issues.push(...connectorOrphanIssues(root, rootRect, time));
14701586
return issues;
14711587
};
14721588

0 commit comments

Comments
 (0)