@senad-d/drawme 0.1.11 → 0.2.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/src/fitcanvas.ts CHANGED
@@ -5,8 +5,9 @@
5
5
  * oversized ones without touching element sizes or relative positions. No
6
6
  * draw.io CLI involved.
7
7
  */
8
- import { readFile, writeFile } from "node:fs/promises";
8
+ import { writeFile } from "node:fs/promises";
9
9
  import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
10
+ import { readDiagramXml, withDiagramFiles } from "./diagram-files";
10
11
  import { type DomEl, attr, childrenByTag, directText, firstByTag } from "./dom";
11
12
  import { type ById, collectCellsWithIds, contentBounds, geometryIsRelative, pyFloat } from "./geometry";
12
13
 
@@ -144,29 +145,32 @@ function fitPage(diagram: DomEl, margin: number): FitPageResult {
144
145
  export async function fitCanvasFile(options: FitCanvasOptions): Promise<FitCanvasResult> {
145
146
  const margin = options.margin ?? DEFAULT_FIT_MARGIN;
146
147
  if (!Number.isFinite(margin) || margin < 0) throw new Error(`invalid margin ${String(options.margin)}`);
147
- const output = options.output ?? options.input;
148
- const xml = await readFile(options.input, "utf8");
149
- const doc = new DOMParser().parseFromString(xml, "text/xml");
150
- const root = doc.documentElement as unknown as DomEl | null;
151
- if (!root) throw new Error("no root element (malformed XML)");
152
-
153
- const diagrams = childrenByTag(root, "diagram");
154
- let pages: FitPageResult[];
155
- if (diagrams.length > 0) {
156
- pages = diagrams.map((diagram) => fitPage(diagram, margin));
157
- } else if (root.tagName === "mxGraphModel") {
158
- pages = [fitModel("?", root, margin)];
159
- } else {
160
- pages = [{ page: "?", status: "skipped", reason: "no <diagram> pages and root is not <mxGraphModel>" }];
161
- }
148
+ const { input } = options;
149
+ const output = options.output ?? input;
150
+ return withDiagramFiles([input, output], undefined, async () => {
151
+ const xml = await readDiagramXml(input);
152
+ const doc = new DOMParser().parseFromString(xml, "text/xml");
153
+ const root = doc.documentElement as unknown as DomEl | null;
154
+ if (!root) throw new Error("no root element (malformed XML)");
155
+
156
+ const diagrams = childrenByTag(root, "diagram");
157
+ let pages: FitPageResult[];
158
+ if (diagrams.length > 0) {
159
+ pages = diagrams.map((diagram) => fitPage(diagram, margin));
160
+ } else if (root.tagName === "mxGraphModel") {
161
+ pages = [fitModel("?", root, margin)];
162
+ } else {
163
+ pages = [{ page: "?", status: "skipped", reason: "no <diagram> pages and root is not <mxGraphModel>" }];
164
+ }
162
165
 
163
- const changed = pages.some((page) => page.status === "fitted");
164
- if (changed || output !== options.input) {
165
- let serialized = new XMLSerializer().serializeToString(doc as never);
166
- const declaration = /^<\?xml[^>]*\?>/.exec(xml)?.[0];
167
- if (declaration && !serialized.startsWith("<?xml")) serialized = `${declaration}\n${serialized}`;
168
- if (xml.endsWith("\n") && !serialized.endsWith("\n")) serialized += "\n";
169
- await writeFile(output, serialized, "utf8");
170
- }
171
- return { input: options.input, output, margin, changed, pages };
166
+ const changed = pages.some((page) => page.status === "fitted");
167
+ if (changed || output !== input) {
168
+ let serialized = new XMLSerializer().serializeToString(doc as never);
169
+ const declaration = /^<\?xml[^>]*\?>/.exec(xml)?.[0];
170
+ if (declaration && !serialized.startsWith("<?xml")) serialized = `${declaration}\n${serialized}`;
171
+ if (xml.endsWith("\n") && !serialized.endsWith("\n")) serialized += "\n";
172
+ await writeFile(output, serialized, "utf8");
173
+ }
174
+ return { input, output, margin, changed, pages };
175
+ });
172
176
  }
package/src/geometry.ts CHANGED
@@ -139,33 +139,67 @@ export function edgeRoute(edge: DomEl, byId: ById): Point[] | null {
139
139
  return [source, ...waypoints.map(([x, y]): Point => [x + ox, y + oy]), target];
140
140
  }
141
141
 
142
- /** Point at `fraction` (0..1) of the route's arc length. */
143
- export function routePointAt(points: Point[], fraction: number): Point {
142
+ function pointAlongRoute(points: Point[], fraction: number, normal: number): Point | null {
144
143
  const lengths: number[] = [];
145
144
  let total = 0;
145
+ let lastSegment = -1;
146
146
  for (let i = 0; i < points.length - 1; i++) {
147
147
  const length = Math.hypot(points[i + 1][0] - points[i][0], points[i + 1][1] - points[i][1]);
148
148
  lengths.push(length);
149
149
  total += length;
150
+ if (length > 0) lastSegment = i;
150
151
  }
152
+ if (!Number.isFinite(total)) return null;
153
+
151
154
  let remaining = total * fraction;
152
- for (let i = 0; i < lengths.length; i++) {
153
- if (remaining <= lengths[i]) {
154
- const fraction = lengths[i] === 0 ? 0 : remaining / lengths[i];
155
- return [
156
- points[i][0] + fraction * (points[i + 1][0] - points[i][0]),
157
- points[i][1] + fraction * (points[i + 1][1] - points[i][1]),
158
- ];
155
+ for (const [i, length] of lengths.entries()) {
156
+ if (length === 0) continue;
157
+ // At a bend use the outgoing direction; at the end use the last nonzero segment.
158
+ if (remaining < length || i === lastSegment) {
159
+ const [x, y] = points[i];
160
+ const dx = points[i + 1][0] - x;
161
+ const dy = points[i + 1][1] - y;
162
+ const progress = Math.min(1, remaining / length);
163
+ return [x + progress * dx + normal * (dy / length), y + progress * dy - normal * (dx / length)];
159
164
  }
160
- remaining -= lengths[i];
165
+ remaining -= length;
161
166
  }
162
- return points.at(-1) ?? [0, 0];
167
+ return points.at(-1) ?? null;
168
+ }
169
+
170
+ /** Point at `fraction` (0..1) of the route's arc length. */
171
+ export function routePointAt(points: Point[], fraction: number): Point {
172
+ return pointAlongRoute(points, fraction, 0) ?? [0, 0];
163
173
  }
164
174
 
165
175
  export function routeMidpoint(points: Point[]): Point {
166
176
  return routePointAt(points, 0.5);
167
177
  }
168
178
 
179
+ function geometryPoint(geometry: DomEl | null, kind: string): DomEl | undefined {
180
+ return geometry ? childrenByTag(geometry, "mxPoint").find((point) => attr(point, "as") === kind) : undefined;
181
+ }
182
+
183
+ function pointCoordinates(point: DomEl): Point | null {
184
+ const x = pyFloat(attr(point, "x") ?? "0");
185
+ const y = pyFloat(attr(point, "y") ?? "0");
186
+ return x === undefined || y === undefined || hasInvalidNumber([x, y]) ? null : [x, y];
187
+ }
188
+
189
+ /** Label anchor: x runs from -1 to 1 along the route, y follows its signed normal, then offset is absolute. */
190
+ export function routeLabelPoint(cell: DomEl, route: Point[]): Point | null {
191
+ const geometry = firstByTag(cell, "mxGeometry");
192
+ const x = geometry ? pyFloat(attr(geometry, "x") ?? "0") : 0;
193
+ const y = geometry ? pyFloat(attr(geometry, "y") ?? "0") : 0;
194
+ if (x === undefined || y === undefined || hasInvalidNumber([x, y])) return null;
195
+ const offsetNode = geometryPoint(geometry, "offset");
196
+ const offset: Point | null = offsetNode ? pointCoordinates(offsetNode) : [0, 0];
197
+ const anchor = pointAlongRoute(route, (Math.min(1, Math.max(-1, x)) + 1) / 2, y);
198
+ if (!offset || !anchor) return null;
199
+ const point: Point = [anchor[0] + offset[0], anchor[1] + offset[1]];
200
+ return hasInvalidNumber(point) ? null : point;
201
+ }
202
+
169
203
  /** Conservative box for a separately sized label on an explicitly routed edge. */
170
204
  export function explicitEdgeLabelRect(cell: DomEl, byId: ById): Rect | null {
171
205
  if (!isEdgeLabel(cell)) return null;
@@ -174,21 +208,13 @@ export function explicitEdgeLabelRect(cell: DomEl, byId: ById): Rect | null {
174
208
  const edge = parent ? byId.get(parent) : undefined;
175
209
  if (!local || hasInvalidNumber(local) || edge?.getAttribute("edge") !== "1") return null;
176
210
  const route = edgeRoute(edge, byId);
177
- if (!route) return null;
178
- const [midX, midY] = routeMidpoint(route);
179
- const geometry = firstByTag(cell, "mxGeometry");
180
- const offset = geometry
181
- ? childrenByTag(geometry, "mxPoint").find((point) => attr(point, "as") === "offset")
182
- : undefined;
183
- const offsetX = offset ? pyFloat(attr(offset, "x") ?? "0") : 0;
184
- const offsetY = offset ? pyFloat(attr(offset, "y") ?? "0") : 0;
185
- if (offsetX === undefined || offsetY === undefined || !Number.isFinite(offsetX) || !Number.isFinite(offsetY)) {
186
- return null;
187
- }
188
- return [midX + offsetX - local[2] / 2, midY + offsetY - local[3] / 2, local[2], local[3]];
211
+ const center = route ? routeLabelPoint(cell, route) : null;
212
+ if (!center) return null;
213
+ const [, , width, height] = local;
214
+ return [center[0] - width / 2, center[1] - height / 2, width, height];
189
215
  }
190
216
 
191
- /** Fold UserObject/object wrappers into their inner mxCell so wrapper ids resolve. */
217
+ /** Analysis only: materialize effective wrapper ids and labels on their inner mxCells. */
192
218
  export function collectCells(root: DomEl | null): DomEl[] {
193
219
  const cells: DomEl[] = [];
194
220
  for (const child of root ? elemChildren(root) : []) {
@@ -197,6 +223,8 @@ export function collectCells(root: DomEl | null): DomEl[] {
197
223
  const inner = firstByTag(child, "mxCell");
198
224
  if (inner) {
199
225
  inner.setAttribute("id", attr(child, "id") ?? "");
226
+ const value = attr(child, "label") ?? attr(child, "value");
227
+ if (value !== null) inner.setAttribute("value", value);
200
228
  cells.push(inner);
201
229
  }
202
230
  }
@@ -258,17 +286,28 @@ export function contentWaypoints(cell: DomEl): Point[] {
258
286
  return cell.getAttribute("edge") === "1" ? edgeWaypoints(cell) : [];
259
287
  }
260
288
 
261
- /** Visible vertices/containers, practical edge-label boxes, and explicit waypoints. */
289
+ /** Visible vertices/containers, practical edge-label boxes, waypoints, and floating terminals. */
262
290
  export function contentBounds(cells: DomEl[], ids: ById): ContentBounds | null {
263
291
  let bounds: ContentBounds | null = null;
264
292
  for (const cell of cells) {
265
293
  if (!isVisible(cell, ids)) continue;
266
294
  const box = contentRect(cell, ids);
267
295
  if (box && !hasInvalidNumber(box)) bounds = addRectToBounds(bounds, box);
268
- const waypoints = contentWaypoints(cell);
269
- if (waypoints.length > 0) {
270
- const [ox, oy] = parentOrigin(cell, ids);
271
- for (const [x, y] of waypoints) bounds = addPointToBounds(bounds, [x + ox, y + oy]);
296
+ if (attr(cell, "edge") !== "1") continue;
297
+
298
+ const points = contentWaypoints(cell);
299
+ const geometry = firstByTag(cell, "mxGeometry");
300
+ for (const end of ["source", "target"]) {
301
+ if (attr(cell, end) !== null) continue; // An attached end's stored point is not rendered.
302
+ const terminal = geometryPoint(geometry, `${end}Point`);
303
+ const point = terminal ? pointCoordinates(terminal) : null;
304
+ if (point) points.push(point);
305
+ }
306
+ if (points.length === 0) continue;
307
+ const [ox, oy] = parentOrigin(cell, ids);
308
+ for (const [x, y] of points) {
309
+ const point: Point = [x + ox, y + oy];
310
+ if (!hasInvalidNumber(point)) bounds = addPointToBounds(bounds, point);
272
311
  }
273
312
  }
274
313
  return bounds;