@senad-d/drawme 0.1.6 → 0.1.8

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/src/validate.ts CHANGED
@@ -16,12 +16,16 @@ import {
16
16
  collectCells,
17
17
  contentBounds,
18
18
  edgeRoute,
19
+ edgeWaypoints,
20
+ endpoint,
19
21
  geometryIsRelative,
20
22
  hasInvalidNumber,
23
+ explicitEdgeLabelRect,
21
24
  isEdgeLabel,
22
25
  isVisible,
23
26
  pyFloat,
24
27
  rect,
28
+ routePointAt,
25
29
  styleNum,
26
30
  } from "./geometry";
27
31
 
@@ -36,7 +40,7 @@ export interface ValidateResult {
36
40
  /** Informational limitations/settings that do not require a source correction. */
37
41
  observations: string[];
38
42
  /** Readability score (lower is better); comparable only across variants of the same graph. */
39
- score: { total: number; through: number; crossings: number; overlaps: number };
43
+ score: { total: number; through: number; crossings: number; overlaps: number; anchors: number };
40
44
  }
41
45
 
42
46
  /** Quote an optional attribute consistently in diagnostic messages. */
@@ -155,10 +159,219 @@ function routeCrossWarnings(routed: RoutedEdge[]): string[] {
155
159
  return warnings;
156
160
  }
157
161
 
162
+ type Side = "top" | "bottom" | "left" | "right";
163
+
164
+ /** Side containing a pinned connection point, or null for an interior, corner, or unpinned point. */
165
+ function pinnedSide(style: string, end: "source" | "target"): Side | null {
166
+ const x = styleNum(style, end === "source" ? "exitX" : "entryX");
167
+ const y = styleNum(style, end === "source" ? "exitY" : "entryY");
168
+ if (x === undefined && y === undefined) return null;
169
+ const xBorder = x === 0 || x === 1;
170
+ const yBorder = y === 0 || y === 1;
171
+ if (xBorder && !yBorder) return x === 0 ? "left" : "right";
172
+ if (yBorder && !xBorder) return y === 0 ? "top" : "bottom";
173
+ return null;
174
+ }
175
+
176
+ function directionDescription(dx: number, dy: number): string {
177
+ if (Math.abs(dx) >= Math.abs(dy)) return dx > 0 ? "to the right" : "to the left";
178
+ return dy > 0 ? "below" : "above";
179
+ }
180
+
181
+ function facingSide(dx: number, dy: number): Side {
182
+ if (Math.abs(dx) >= Math.abs(dy)) return dx > 0 ? "right" : "left";
183
+ return dy > 0 ? "bottom" : "top";
184
+ }
185
+
186
+ function sideStyleHint(side: Side, end: "source" | "target"): string {
187
+ const prefix = end === "source" ? "exit" : "entry";
188
+ switch (side) {
189
+ case "top":
190
+ return `${prefix}X=0.5;${prefix}Y=0`;
191
+ case "bottom":
192
+ return `${prefix}X=0.5;${prefix}Y=1`;
193
+ case "left":
194
+ return `${prefix}X=0;${prefix}Y=0.5`;
195
+ case "right":
196
+ return `${prefix}X=1;${prefix}Y=0.5`;
197
+ }
198
+ }
199
+
200
+ function sideFacesAway(side: Side, dx: number, dy: number, tolerance: number): boolean {
201
+ return (
202
+ (side === "top" && dy > tolerance) ||
203
+ (side === "bottom" && dy < -tolerance) ||
204
+ (side === "left" && dx > tolerance) ||
205
+ (side === "right" && dx < -tolerance)
206
+ );
207
+ }
208
+
209
+ interface AnchorDirection {
210
+ end: "source" | "target";
211
+ reference: Point;
212
+ center: Point;
213
+ subject: string;
214
+ }
215
+
216
+ function rectCenter(box: Rect): Point {
217
+ return [box[0] + box[2] / 2, box[1] + box[3] / 2];
218
+ }
219
+
220
+ function anchorDirectionWarning(
221
+ cell: DomEl,
222
+ style: string,
223
+ tolerance: number,
224
+ direction: AnchorDirection,
225
+ ): string | null {
226
+ const dx = direction.reference[0] - direction.center[0];
227
+ const dy = direction.reference[1] - direction.center[1];
228
+ const side = pinnedSide(style, direction.end);
229
+ if (!side || !sideFacesAway(side, dx, dy, tolerance)) return null;
230
+ const suggested = facingSide(dx, dy);
231
+ const endLabel = direction.end === "source" ? "source exit" : "target entry";
232
+ return `edge ${repr(attr(cell, "id"))}: ${endLabel} pinned to ${side} but ${direction.subject} is ${directionDescription(dx, dy)}; re-pin to ${suggested} (${sideStyleHint(suggested, direction.end)}) to shorten the route and reduce bends`;
233
+ }
234
+
235
+ /** Warn when a pinned border anchor faces away from its adjacent waypoint, or its peer when auto-routed. */
236
+ function edgeAnchorFacingWarnings(cell: DomEl, ids: ById): string[] {
237
+ if (cell.getAttribute("edge") !== "1" || !isVisible(cell, ids)) return [];
238
+ const sourceId = attr(cell, "source");
239
+ const targetId = attr(cell, "target");
240
+ if (!sourceId || !targetId) return [];
241
+ const source = ids.get(sourceId);
242
+ const target = ids.get(targetId);
243
+ if (!source || !target || geometryIsRelative(source) || geometryIsRelative(target)) return [];
244
+ const sourceBox = absRect(source, ids);
245
+ const targetBox = absRect(target, ids);
246
+ if (!sourceBox || !targetBox) return [];
247
+
248
+ const sourceCenter = rectCenter(sourceBox);
249
+ const targetCenter = rectCenter(targetBox);
250
+ const route = edgeRoute(cell, ids);
251
+ const directions: AnchorDirection[] = [
252
+ {
253
+ end: "source",
254
+ reference: route?.[1] ?? targetCenter,
255
+ center: sourceCenter,
256
+ subject: route ? "first waypoint" : "target",
257
+ },
258
+ {
259
+ end: "target",
260
+ reference: route?.at(-2) ?? sourceCenter,
261
+ center: targetCenter,
262
+ subject: route ? "last waypoint" : "source",
263
+ },
264
+ ];
265
+ const tolerance = Math.max(sourceBox[2], sourceBox[3], targetBox[2], targetBox[3]) * 0.15;
266
+ const style = attr(cell, "style") ?? "";
267
+ return directions
268
+ .map((direction) => anchorDirectionWarning(cell, style, tolerance, direction))
269
+ .filter((warning): warning is string => warning !== null);
270
+ }
271
+
272
+ function anchorFacingWarnings(cells: DomEl[], ids: ById): string[] {
273
+ return cells.flatMap((cell) => edgeAnchorFacingWarnings(cell, ids));
274
+ }
275
+
276
+ /** A segment that enters and exits a rectangle rather than merely touching its boundary. */
277
+ function segmentPiercesRect(start: Point, end: Point, box: Rect): boolean {
278
+ const [x, y, width, height] = box;
279
+ const corners: Point[] = [
280
+ [x, y],
281
+ [x + width, y],
282
+ [x + width, y + height],
283
+ [x, y + height],
284
+ ];
285
+ const borders: [Point, Point][] = corners.map((corner, index) => [corner, corners[(index + 1) % 4]]);
286
+ let crossings = 0;
287
+ for (const [a, b] of borders) if (segmentsCross(start, end, a, b)) crossings++;
288
+ if (crossings >= 2) return true;
289
+ return crossings === 1 && (pointInRect(start, box) || pointInRect(end, box));
290
+ }
291
+
292
+ function isDescendantOf(cell: DomEl, ancestorId: string | null, ids: ById): boolean {
293
+ const seen = new Set<string>();
294
+ let parent = attr(cell, "parent");
295
+ while (parent && ids.has(parent) && !seen.has(parent)) {
296
+ if (parent === ancestorId) return true;
297
+ seen.add(parent);
298
+ parent = attr(ids.get(parent)!, "parent");
299
+ }
300
+ return false;
301
+ }
302
+
303
+ function isTextAnnotation(cell: DomEl): boolean {
304
+ return (attr(cell, "style") ?? "").split(";").some((token) => token.trim() === "text");
305
+ }
306
+
307
+ interface AutoRouteContext {
308
+ edgeId: string | null;
309
+ sourceId: string;
310
+ targetId: string;
311
+ sourcePoint: Point;
312
+ targetPoint: Point;
313
+ }
314
+
315
+ function autoRouteContext(cell: DomEl, ids: ById): AutoRouteContext | null {
316
+ if (cell.getAttribute("edge") !== "1" || !isVisible(cell, ids) || edgeWaypoints(cell).length > 0) return null;
317
+ const sourceId = attr(cell, "source");
318
+ const targetId = attr(cell, "target");
319
+ if (!sourceId || !targetId) return null;
320
+ const source = ids.get(sourceId);
321
+ const target = ids.get(targetId);
322
+ if (!source || !target || geometryIsRelative(source) || geometryIsRelative(target)) return null;
323
+ const sourcePoint = endpoint(cell, "source", ids);
324
+ const targetPoint = endpoint(cell, "target", ids);
325
+ if (!sourcePoint || !targetPoint) return null;
326
+ return { edgeId: attr(cell, "id"), sourceId, targetId, sourcePoint, targetPoint };
327
+ }
328
+
329
+ function routeThroughObservation(context: AutoRouteContext, leaf: LeafBox, ids: ById): string | null {
330
+ const [vertexId, box] = leaf;
331
+ if (vertexId === null || vertexId === context.sourceId || vertexId === context.targetId) return null;
332
+ const vertex = ids.get(vertexId);
333
+ if (!vertex || isTextAnnotation(vertex)) return null;
334
+ if (isDescendantOf(vertex, context.sourceId, ids) || isDescendantOf(vertex, context.targetId, ids)) return null;
335
+ if (!segmentPiercesRect(context.sourcePoint, context.targetPoint, box)) return null;
336
+ return `edge ${repr(context.edgeId)} may pass over vertex ${repr(vertexId)} (predicted from the direct line; verify in the preview, then add waypoints or move the shape if needed)`;
337
+ }
338
+
339
+ function edgeRouteThroughObservations(cell: DomEl, ids: ById, leaves: LeafBox[]): string[] {
340
+ const context = autoRouteContext(cell, ids);
341
+ if (!context) return [];
342
+ return leaves
343
+ .map((leaf) => routeThroughObservation(context, leaf, ids))
344
+ .filter((observation): observation is string => observation !== null);
345
+ }
346
+
347
+ /**
348
+ * Identify auto-routed edges whose direct connection line pierces an unrelated
349
+ * leaf vertex. This is only a preview-review hint because draw.io may route the
350
+ * actual orthogonal connector around the shape.
351
+ */
352
+ function predictedRouteThroughObservations(cells: DomEl[], ids: ById, leaves: LeafBox[]): string[] {
353
+ return cells.flatMap((cell) => edgeRouteThroughObservations(cell, ids, leaves));
354
+ }
355
+
158
356
  function geometryWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>): string[] {
159
357
  const routed = collectRoutedEdges(cells, ids);
160
358
  const leaves = collectLeafBoxes(cells, ids, parents);
161
- return [...routeThroughWarnings(routed, leaves), ...routeCrossWarnings(routed)];
359
+ return [...routeThroughWarnings(routed, leaves), ...routeCrossWarnings(routed), ...anchorFacingWarnings(cells, ids)];
360
+ }
361
+
362
+ /** Edges the route checks above cannot see: no explicit waypoints, so the renderer routes them blindly. */
363
+ function autoRoutedEdgeWarning(cells: DomEl[], ids: ById): string | null {
364
+ const unrouted: string[] = [];
365
+ for (const cell of cells) {
366
+ if (cell.getAttribute("edge") === "1" && isVisible(cell, ids) && edgeRoute(cell, ids) === null) {
367
+ unrouted.push(repr(attr(cell, "id")));
368
+ }
369
+ }
370
+ if (unrouted.length === 0) return null;
371
+ return (
372
+ `${unrouted.length} auto-routed edge(s) cannot be route-checked (no explicit waypoints): ${unrouted.join(", ")}; ` +
373
+ "add waypoints and pinned anchors, or verify their routing visually"
374
+ );
162
375
  }
163
376
 
164
377
  /** Map every cell by id (blank key for id-less cells); report duplicate ids as errors. */
@@ -410,6 +623,75 @@ function labelText(cell: DomEl): string {
410
623
  return stripLabelMarkup(attr(cell, "value") ?? "").replaceAll("&nbsp;", " ").trim();
411
624
  }
412
625
 
626
+ const DEFAULT_FONT_SIZE = 11;
627
+ const CHAR_WIDTH_FACTOR = 0.6;
628
+ const LINE_HEIGHT_FACTOR = 1.4;
629
+
630
+ function labelOffset(cell: DomEl): Point | null {
631
+ const geometry = firstByTag(cell, "mxGeometry");
632
+ const offset = geometry
633
+ ? childrenByTag(geometry, "mxPoint").find((point) => attr(point, "as") === "offset")
634
+ : undefined;
635
+ if (!offset) return null;
636
+ const x = pyFloat(attr(offset, "x") ?? "0");
637
+ const y = pyFloat(attr(offset, "y") ?? "0");
638
+ if (x === undefined || y === undefined || !Number.isFinite(x) || !Number.isFinite(y)) return null;
639
+ return [x, y];
640
+ }
641
+
642
+ /** Estimated box of an edge's inline label, centered on its explicit route like draw.io renders it. */
643
+ function inlineEdgeLabelRect(edge: DomEl, ids: ById): Rect | null {
644
+ const label = labelText(edge);
645
+ if (!label) return null;
646
+ const route = edgeRoute(edge, ids);
647
+ if (!route) return null;
648
+ const geometry = firstByTag(edge, "mxGeometry");
649
+ const along = geometry ? pyFloat(attr(geometry, "x") ?? "0") : 0;
650
+ const fraction = along !== undefined && Number.isFinite(along) ? Math.min(1, Math.max(0, (along + 1) / 2)) : 0.5;
651
+ const [centerX, centerY] = routePointAt(route, fraction);
652
+ const [offsetX, offsetY] = labelOffset(edge) ?? [0, 0];
653
+ const fontSize = styleNum(attr(edge, "style"), "fontSize") ?? DEFAULT_FONT_SIZE;
654
+ const lines = label.split("\n");
655
+ const width = Math.max(...lines.map((line) => line.length)) * fontSize * CHAR_WIDTH_FACTOR;
656
+ const height = lines.length * fontSize * LINE_HEIGHT_FACTOR;
657
+ return [centerX + offsetX - width / 2, centerY + offsetY - height / 2, width, height];
658
+ }
659
+
660
+ function edgeLabelBox(cell: DomEl, ids: ById): [string | null, Rect] | null {
661
+ if (cell.getAttribute("edge") === "1") {
662
+ const box = inlineEdgeLabelRect(cell, ids);
663
+ return box ? [attr(cell, "id"), box] : null;
664
+ }
665
+ if (isEdgeLabel(cell) && labelText(cell)) {
666
+ const box = explicitEdgeLabelRect(cell, ids);
667
+ return box ? [attr(cell, "id"), box] : null;
668
+ }
669
+ return null;
670
+ }
671
+
672
+ /** Edge-label text lying on top of a shape; sizes are estimated, so phrased as "likely". */
673
+ function labelOverlapWarnings(cells: DomEl[], ids: ById, parents: Set<string | null>): string[] {
674
+ const leaves = collectLeafBoxes(cells, ids, parents);
675
+ const warnings: string[] = [];
676
+ for (const cell of cells) {
677
+ if (!isVisible(cell, ids)) continue;
678
+ const labeled = edgeLabelBox(cell, ids);
679
+ if (!labeled || hasInvalidNumber(labeled[1])) continue;
680
+ const [id, box] = labeled;
681
+ for (const [vertexId, vertexBox] of leaves) {
682
+ if (overlap(box, vertexBox)) warnings.push(`edge label ${repr(id)} likely overlaps vertex ${repr(vertexId)}`);
683
+ }
684
+ }
685
+ return warnings;
686
+ }
687
+
688
+ function labelOnLineWarning(cell: DomEl): string | null {
689
+ if (cell.getAttribute("edge") !== "1" || !labelText(cell)) return null;
690
+ if ((attr(cell, "style") ?? "").includes("labelBackgroundColor=")) return null;
691
+ if (labelOffset(cell)) return null;
692
+ return `edge ${repr(attr(cell, "id"))} label sits directly on its line; add an offset or labelBackgroundColor`;
693
+ }
694
+
413
695
  function isCompactBorderPort(cell: DomEl, box: Rect | null): boolean {
414
696
  return (
415
697
  cell.getAttribute("vertex") === "1" &&
@@ -425,7 +707,7 @@ function isCompactBorderPort(cell: DomEl, box: Rect | null): boolean {
425
707
  function smallFontWarning(cell: DomEl, box: Rect | null): string | null {
426
708
  const fontSize = styleNum(attr(cell, "style"), "fontSize");
427
709
  const isEdgeText = cell.getAttribute("edge") === "1" || isEdgeLabel(cell);
428
- const minimum = isEdgeText ? 9 : 10;
710
+ const minimum = isEdgeText ? 10 : 11;
429
711
  if (
430
712
  isCompactBorderPort(cell, box) ||
431
713
  fontSize === undefined ||
@@ -457,7 +739,7 @@ function cellReadabilityWarnings(cell: DomEl): string[] {
457
739
  const label = labelText(cell);
458
740
  if (!label) return [];
459
741
  const box = rect(cell);
460
- return [smallFontWarning(cell, box), longLabelWarning(cell, label, box)].filter(
742
+ return [smallFontWarning(cell, box), longLabelWarning(cell, label, box), labelOnLineWarning(cell)].filter(
461
743
  (warning): warning is string => warning !== null,
462
744
  );
463
745
  }
@@ -491,9 +773,13 @@ function checkPage(diagram: DomEl): [string[], string[], string[]] {
491
773
  warnings.push(
492
774
  ...overlapWarnings(cells, ids, parents),
493
775
  ...geometryWarnings(cells, ids, parents),
776
+ ...labelOverlapWarnings(cells, ids, parents),
494
777
  ...containmentWarnings(cells, ids),
495
778
  ...readabilityWarnings(cells),
496
779
  );
780
+ observations.push(...predictedRouteThroughObservations(cells, ids, collectLeafBoxes(cells, ids, parents)));
781
+ const autoRouted = autoRoutedEdgeWarning(cells, ids);
782
+ if (autoRouted) warnings.push(autoRouted);
497
783
  const settings = pageSettings(model, warnings, observations);
498
784
  warnings.push(...canvasWarnings(contentBounds(cells, ids), settings));
499
785
  return [withPage(name, errors), withPage(name, warnings), withPage(name, observations)];
@@ -519,16 +805,17 @@ export function validateXml(xml: string): ValidateResult {
519
805
  const through = warnings.filter((warning) => warning.includes("routes through")).length;
520
806
  const crossings = warnings.filter((warning) => warning.endsWith(" cross")).length;
521
807
  const overlaps = warnings.filter((warning) => warning.endsWith(" overlap")).length;
808
+ const anchors = warnings.filter((warning) => warning.endsWith("reduce bends")).length;
522
809
  return {
523
810
  errors,
524
811
  warnings,
525
812
  observations,
526
- score: { total: 20 * through + 10 * crossings + 5 * overlaps, through, crossings, overlaps },
813
+ score: { total: 20 * through + 10 * crossings + 5 * overlaps + 8 * anchors, through, crossings, overlaps, anchors },
527
814
  };
528
815
  }
529
816
 
530
817
  function emptyScore(): ValidateResult["score"] {
531
- return { total: 0, through: 0, crossings: 0, overlaps: 0 };
818
+ return { total: 0, through: 0, crossings: 0, overlaps: 0, anchors: 0 };
532
819
  }
533
820
 
534
821
  /** Read and lint a `.drawio` file. Read/parse failures are returned as errors, never thrown. */
package/src/workflow.ts CHANGED
@@ -85,6 +85,7 @@ export function drawmeWorkflow(description: string, refDir: string, cli: DrawioI
85
85
  " 1. **Pass 1 — fit and sizing** (`<name>.review-fit.png`) answers: does the diagram fit its page, and does the canvas or any element need resizing? Hunt: content touching or crossing a page edge; one outer margin visibly thinner than the others; large empty regions or a page far larger than its content; elements too small for their labels — text touching or crossing its own shape border, clipped or mid-word truncated; a smallest label you cannot comfortably read at full-diagram scale (tighten the canvas with `drawio_fit_canvas`, split content across pages, or simplify the layout — never judge what you cannot read, and never treat \"too small to tell\" as a pass).",
86
86
  " 2. **Pass 2 — element placement** (`<name>.review-layout.png`) answers: is every element positioned correctly, and is there a visibly better arrangement? Hunt: shapes whose borders touch or overlap; two labels touching or overlapping each other; label text lying on top of any line or unrelated shape; rows/columns that drift out of alignment; uneven gaps between peers; children poking out of their container or crowding its title; related elements far apart while unrelated ones sit adjacent. Improve, not only repair: if moving an element would shorten edges, remove crossings, or make the arrangement symmetric, record that as a finding too.",
87
87
  " 3. **Pass 3 — connections** (`<name>.review-connectors.png`) answers: is every connection correct, cleanly routed, symmetric where the layout is symmetric, and anchored to the middle of the element side it faces wherever possible? Trace every edge from source to target and check it against the plan — right source, right target, right direction, right label. Hunt: an endpoint floating off its shape or plunging deep into it; an edge entering at an odd corner when a side-center anchor is available (pin `exitX`/`exitY`/`entryX`/`entryY` to the facing side's center, spreading evenly only when several edges share one side); mirrored branches routed asymmetrically; an arrowhead hidden by a shape or crushed into a bend; an edge passing through a shape it does not connect; parallel edges stacked on top of each other; an edge label sitting on its line so the text is struck through, or closer than about half a text-height to any line; crossings a reroute through a free corridor would remove.",
88
+ " Heed `drawio_validate` anchor warnings literally: re-pin an exit or entry to the suggested facing side before adding waypoints. Treat predicted route-through observations as focused preview-review hints, not proof of draw.io's rendered route; add waypoints or move a shape only when the preview confirms the obstruction.",
88
89
  " 4. **Pass 4 — typography, semantics, and regression** (`<name>.review.png`) is the holistic confirmation. Read every label word for word — a label you cannot fully read is itself a finding; check text contrast against fills; confirm every requested component and relationship is present, pointing the right way, with the right label; check hierarchy, grouping, and that legend entries match the colors actually used; apply the type's `Review:` checklist from the diagram-types reference; and re-check passes 1–3 for regressions. Retain this image (every page, for a multi-page file) for the final report.",
89
90
  " - **Image NOT attached** — the current model cannot view images. Skip the visual passes: do not describe or judge renders; review structurally instead by cross-checking `drawio_validate` findings and a `drawio_explain` read-back against the user's request. Keep the latest `<name>.review.png` on disk so the user can view it, and state plainly in the summary that rendered inspection was skipped.",
90
91
  "6. **Fix and verify before the next pass** — resolve a pass's findings with targeted source edits: after each edit, validate, then re-export the same pass preview (for a multi-page file, the page the finding is on). The superseded preview file is deleted from disk, but its image is still visible earlier in this conversation: compare the new image against it at each addressed finding's location and record a verdict — **fixed** (the defect is gone in the new render), **not fixed** (still visible), or **regressed** (the edit introduced a new defect; log it as a new numbered finding). Never mark a finding fixed because the XML changed — only because the new image shows it fixed. When elements overlap, are cramped, clipped, or short on margin, never shrink or squeeze elements to fit the page — move them apart, then run `drawio_fit_canvas` to enlarge the canvas around them. A pass is complete only when all of its findings are fixed or explicitly accepted, and every pass must be complete before final export. If the correction limit is reached mid-pass, finish the remaining passes as inspection-only and report their findings as unresolved. Each successful preview export automatically removes the previous preview file for the same source, so only the latest review image remains.",