@mark1russell7/layout-contract 0.10.2 → 0.10.3
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/README.md +3 -0
- package/build/index.d.ts +179 -0
- package/build/index.d.ts.map +1 -1
- package/build/index.js +510 -9
- package/build/index.js.map +1 -1
- package/package.json +2 -1
- package/src/index.ts +2 -0
- package/src/path.ts +300 -0
- package/src/picture.ts +277 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/layout-contract",
|
|
4
|
-
"version": "0.10.
|
|
4
|
+
"version": "0.10.3",
|
|
5
5
|
"description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"layout",
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
52
|
"@mark1russell7/cue": "^2.1.1",
|
|
53
|
+
"@mark1russell7/rigor-bench": "^0.2.47",
|
|
53
54
|
"@types/node": "^26.6.4",
|
|
54
55
|
"@vitest/coverage-v8": "^5.0.3",
|
|
55
56
|
"esbuild": "^0.28.2",
|
package/src/index.ts
CHANGED
|
@@ -13,6 +13,8 @@ export * from "./measures.ts";
|
|
|
13
13
|
export * from "./balance.ts";
|
|
14
14
|
export * from "./cell.ts";
|
|
15
15
|
export * from "./frame.ts";
|
|
16
|
+
export * from "./path.ts";
|
|
17
|
+
export * from "./picture.ts";
|
|
16
18
|
export * from "./strategy.ts";
|
|
17
19
|
export * from "./random.ts";
|
|
18
20
|
export * from "./edges.ts";
|
package/src/path.ts
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
// The paths of a picture (`docs/PICTURE.md`): a path is a list of segments that each renderer draws in the same way.
|
|
2
|
+
// The record came from the curve model of `highways`, so a curve of `highways` is a path with no change.
|
|
3
|
+
import type { Point, Rect } from "./geometry.ts";
|
|
4
|
+
|
|
5
|
+
/** The kinds of the segments of a path. */
|
|
6
|
+
export const PATH_KINDS = ["move", "line", "cubic", "arc"] as const;
|
|
7
|
+
|
|
8
|
+
/** The start of a path: the pen goes to `to` and draws nothing. */
|
|
9
|
+
export interface PathMove {
|
|
10
|
+
readonly kind: "move";
|
|
11
|
+
readonly to: Point;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** A straight line from the end of the segment before to `to`. */
|
|
15
|
+
export interface PathLine {
|
|
16
|
+
readonly kind: "line";
|
|
17
|
+
readonly to: Point;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A cubic Bezier curve from the end of the segment before to `to`, with the control points `c1` and `c2`. */
|
|
21
|
+
export interface PathCubic {
|
|
22
|
+
readonly kind: "cubic";
|
|
23
|
+
readonly c1: Point;
|
|
24
|
+
readonly c2: Point;
|
|
25
|
+
readonly to: Point;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* A circular arc from the end of the segment before to `to`. The arc has its center at `center` and the radius `radius`.
|
|
30
|
+
* It starts at the angle `start` and turns by `sweep` radians. A positive `sweep` turns from the x axis to the y axis.
|
|
31
|
+
* On a canvas, `ctx.arc(center.x, center.y, radius, start, start + sweep, sweep < 0)` draws it.
|
|
32
|
+
*/
|
|
33
|
+
export interface PathArc {
|
|
34
|
+
readonly kind: "arc";
|
|
35
|
+
readonly center: Point;
|
|
36
|
+
readonly radius: number;
|
|
37
|
+
readonly start: number;
|
|
38
|
+
readonly sweep: number;
|
|
39
|
+
readonly to: Point;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A segment of a path. A path is a list of segments: one `move` first, then lines, cubic curves and arcs.
|
|
44
|
+
* A renderer maps the list to SVG path data, to canvas commands or to the vertices of a mesh.
|
|
45
|
+
*/
|
|
46
|
+
export type PathSegment = PathMove | PathLine | PathCubic | PathArc;
|
|
47
|
+
|
|
48
|
+
/** A point of a path, with the direction of the path at that point. */
|
|
49
|
+
export interface PathTangent {
|
|
50
|
+
readonly point: Point;
|
|
51
|
+
/** A unit vector along the path, in the direction from its start to its end. A path with no length gives the vector 0, 0. */
|
|
52
|
+
readonly direction: Point;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** The largest number of points that `samplePath` gives for one segment. */
|
|
56
|
+
const MAX_STEPS = 1024;
|
|
57
|
+
|
|
58
|
+
/** This function gives the path of a polyline: a `move` to the first point, then a line to each next point. A list with no point gives an empty path. */
|
|
59
|
+
export function pathOf(points: readonly Point[]): PathSegment[] {
|
|
60
|
+
return points.map((to, i) => (i === 0 ? { kind: "move", to } : { kind: "line", to }));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* This function gives a polyline that follows the path. The distance from each part of the path to the polyline is `tolerance` or less.
|
|
65
|
+
* The polyline starts at the point of the `move` and goes through the end of each segment.
|
|
66
|
+
* Hit tests, measures and renderers that draw only lines use this polyline.
|
|
67
|
+
*/
|
|
68
|
+
export function samplePath(segments: readonly PathSegment[], tolerance = 0.5): Point[] {
|
|
69
|
+
const tol = Math.max(1e-6, tolerance);
|
|
70
|
+
const out: Point[] = [];
|
|
71
|
+
let at: Point | undefined;
|
|
72
|
+
for (const s of segments) {
|
|
73
|
+
if (s.kind === "move" || at === undefined) {
|
|
74
|
+
out.push(s.to);
|
|
75
|
+
at = s.to;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (s.kind === "cubic") {
|
|
79
|
+
// The chord of a step of 1/n of the parameter is within 3·D/(4·n²) of the curve. D is the largest second difference of the control points.
|
|
80
|
+
const d = Math.max(Math.hypot(at.x - 2 * s.c1.x + s.c2.x, at.y - 2 * s.c1.y + s.c2.y), Math.hypot(s.c1.x - 2 * s.c2.x + s.to.x, s.c1.y - 2 * s.c2.y + s.to.y));
|
|
81
|
+
const n = Math.min(MAX_STEPS, Math.max(1, Math.ceil(Math.sqrt((3 * d) / (4 * tol)))));
|
|
82
|
+
for (let k = 1; k < n; k++) out.push(cubicAt(at, s.c1, s.c2, s.to, k / n));
|
|
83
|
+
} else if (s.kind === "arc") {
|
|
84
|
+
// The chord of an angle φ is within r·(1 - cos(φ/2)) of the arc.
|
|
85
|
+
const step = s.radius <= tol ? Math.PI : 2 * Math.acos(1 - tol / s.radius);
|
|
86
|
+
const n = Math.min(MAX_STEPS, Math.max(1, Math.ceil(Math.abs(s.sweep) / step)));
|
|
87
|
+
for (let k = 1; k < n; k++) {
|
|
88
|
+
const a = s.start + (s.sweep * k) / n;
|
|
89
|
+
out.push({ x: s.center.x + s.radius * Math.cos(a), y: s.center.y + s.radius * Math.sin(a) });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
out.push(s.to);
|
|
93
|
+
at = s.to;
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** This function gives the point at the parameter `t` of the cubic Bezier curve with the control points `p0`, `p1`, `p2` and `p3`. */
|
|
99
|
+
export function cubicAt(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point {
|
|
100
|
+
const u = 1 - t;
|
|
101
|
+
const a = u * u * u;
|
|
102
|
+
const b = 3 * u * u * t;
|
|
103
|
+
const c = 3 * u * t * t;
|
|
104
|
+
const d = t * t * t;
|
|
105
|
+
return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* This function writes the segments as the data of an SVG path: the commands `M`, `L`, `C` and `A`.
|
|
110
|
+
* Each number has at most `digits` digits after the point.
|
|
111
|
+
*/
|
|
112
|
+
export function toSvgPath(segments: readonly PathSegment[], digits = 2): string {
|
|
113
|
+
const n = (v: number): string => {
|
|
114
|
+
const s = String(Number(v.toFixed(digits)));
|
|
115
|
+
return s === "-0" ? "0" : s;
|
|
116
|
+
};
|
|
117
|
+
const p = (q: Point): string => `${n(q.x)} ${n(q.y)}`;
|
|
118
|
+
const parts: string[] = [];
|
|
119
|
+
for (const s of segments) {
|
|
120
|
+
if (s.kind === "move") parts.push(`M ${p(s.to)}`);
|
|
121
|
+
else if (s.kind === "line") parts.push(`L ${p(s.to)}`);
|
|
122
|
+
else if (s.kind === "cubic") parts.push(`C ${p(s.c1)} ${p(s.c2)} ${p(s.to)}`);
|
|
123
|
+
else parts.push(`A ${n(s.radius)} ${n(s.radius)} 0 ${Math.abs(s.sweep) > Math.PI ? 1 : 0} ${s.sweep > 0 ? 1 : 0} ${p(s.to)}`);
|
|
124
|
+
}
|
|
125
|
+
return parts.join(" ");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** This function gives the parameters between 0 and 1 where `a·t² + b·t + c` is 0. The stable form of the roots keeps a small `a` correct. */
|
|
129
|
+
function unitRoots(a: number, b: number, c: number): number[] {
|
|
130
|
+
const inside = (t: number): boolean => t > 0 && t < 1;
|
|
131
|
+
if (a === 0) return b !== 0 && inside(-c / b) ? [-c / b] : [];
|
|
132
|
+
const disc = b * b - 4 * a * c;
|
|
133
|
+
if (!(disc >= 0)) return [];
|
|
134
|
+
const q = -(b + (b < 0 ? -1 : 1) * Math.sqrt(disc)) / 2;
|
|
135
|
+
const roots = q === 0 ? [0] : [q / a, c / q];
|
|
136
|
+
return roots.filter(inside);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* This function gives the exact bounding box of a path. The box of a cubic curve has the points where the curve turns back on an axis.
|
|
141
|
+
* The box of an arc has the points of its circle at each quarter turn that the arc goes through.
|
|
142
|
+
* A path with no segment gives a `RangeError`.
|
|
143
|
+
*/
|
|
144
|
+
export function pathBounds(segments: readonly PathSegment[]): Rect {
|
|
145
|
+
if (segments.length === 0) throw new RangeError("layout-path: a path with no segment has no bounds.");
|
|
146
|
+
let x0 = Infinity;
|
|
147
|
+
let y0 = Infinity;
|
|
148
|
+
let x1 = -Infinity;
|
|
149
|
+
let y1 = -Infinity;
|
|
150
|
+
const add = (p: Point): void => {
|
|
151
|
+
x0 = Math.min(x0, p.x);
|
|
152
|
+
y0 = Math.min(y0, p.y);
|
|
153
|
+
x1 = Math.max(x1, p.x);
|
|
154
|
+
y1 = Math.max(y1, p.y);
|
|
155
|
+
};
|
|
156
|
+
let at: Point | undefined;
|
|
157
|
+
for (const s of segments) {
|
|
158
|
+
add(s.to);
|
|
159
|
+
const from = at;
|
|
160
|
+
at = s.to;
|
|
161
|
+
if (from === undefined) continue;
|
|
162
|
+
if (s.kind === "cubic") {
|
|
163
|
+
// The derivative of the curve on one axis is 3·(a·t² + b·t + c).
|
|
164
|
+
for (const k of ["x", "y"] as const) {
|
|
165
|
+
const a = s.to[k] - 3 * s.c2[k] + 3 * s.c1[k] - from[k];
|
|
166
|
+
const b = 2 * (s.c2[k] - 2 * s.c1[k] + from[k]);
|
|
167
|
+
const c = s.c1[k] - from[k];
|
|
168
|
+
for (const t of unitRoots(a, b, c)) add(cubicAt(from, s.c1, s.c2, s.to, t));
|
|
169
|
+
}
|
|
170
|
+
} else if (s.kind === "arc") {
|
|
171
|
+
const quarter = Math.PI / 2;
|
|
172
|
+
const lo = Math.min(s.start, s.start + s.sweep);
|
|
173
|
+
const hi = Math.max(s.start, s.start + s.sweep);
|
|
174
|
+
if (!Number.isFinite(lo) || !Number.isFinite(hi)) continue;
|
|
175
|
+
const first = hi - lo >= 2 * Math.PI ? 0 : Math.ceil(lo / quarter);
|
|
176
|
+
const last = hi - lo >= 2 * Math.PI ? 3 : Math.floor(hi / quarter);
|
|
177
|
+
for (let k = first; k <= last; k++) {
|
|
178
|
+
// The unit vector of the angle k·π/2 has whole numbers, so the box has no error of a cosine.
|
|
179
|
+
const turn = ((k % 4) + 4) % 4;
|
|
180
|
+
const ux = turn === 0 ? 1 : turn === 2 ? -1 : 0;
|
|
181
|
+
const uy = turn === 1 ? 1 : turn === 3 ? -1 : 0;
|
|
182
|
+
add({ x: s.center.x + s.radius * ux, y: s.center.y + s.radius * uy });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** This function gives the unit vector of the vector `dx`, `dy`, or `undefined` for a vector with no length. */
|
|
190
|
+
function unit(dx: number, dy: number): Point | undefined {
|
|
191
|
+
const length = Math.hypot(dx, dy);
|
|
192
|
+
return length > 0 && Number.isFinite(length) ? { x: dx / length, y: dy / length } : undefined;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* This function gives the direction of one segment at its start or at its end. `from` is the end of the segment before.
|
|
197
|
+
* A segment with no length gives `undefined`. A cubic curve with a control point on its end uses the next control point.
|
|
198
|
+
*/
|
|
199
|
+
function directionOf(from: Point, s: PathSegment, atEnd: boolean): Point | undefined {
|
|
200
|
+
if (s.kind === "move") return undefined;
|
|
201
|
+
const chord = (): Point | undefined => unit(s.to.x - from.x, s.to.y - from.y);
|
|
202
|
+
if (s.kind === "cubic") {
|
|
203
|
+
return atEnd
|
|
204
|
+
? (unit(s.to.x - s.c2.x, s.to.y - s.c2.y) ?? unit(s.to.x - s.c1.x, s.to.y - s.c1.y) ?? chord())
|
|
205
|
+
: (unit(s.c1.x - from.x, s.c1.y - from.y) ?? unit(s.c2.x - from.x, s.c2.y - from.y) ?? chord());
|
|
206
|
+
}
|
|
207
|
+
if (s.kind === "arc" && s.radius > 0 && s.sweep !== 0) {
|
|
208
|
+
const angle = atEnd ? s.start + s.sweep : s.start;
|
|
209
|
+
const sign = s.sweep > 0 ? 1 : -1;
|
|
210
|
+
return unit(-sign * Math.sin(angle), sign * Math.cos(angle));
|
|
211
|
+
}
|
|
212
|
+
return chord();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* This function gives the first point of a path and the direction in which the path leaves it.
|
|
217
|
+
* The direction comes from the first segment that has a length. A path with no segment gives a `RangeError`.
|
|
218
|
+
*/
|
|
219
|
+
export function pathStart(segments: readonly PathSegment[]): PathTangent {
|
|
220
|
+
const first = segments[0];
|
|
221
|
+
if (first === undefined) throw new RangeError("layout-path: a path with no segment has no start.");
|
|
222
|
+
for (let i = 1; i < segments.length; i++) {
|
|
223
|
+
const direction = directionOf(segments[i - 1]!.to, segments[i]!, false);
|
|
224
|
+
if (direction !== undefined) return { point: first.to, direction };
|
|
225
|
+
}
|
|
226
|
+
return { point: first.to, direction: { x: 0, y: 0 } };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* This function gives the last point of a path and the direction in which the path comes to it. An arrow head at the end points along it.
|
|
231
|
+
* The direction comes from the last segment that has a length. A path with no segment gives a `RangeError`.
|
|
232
|
+
*/
|
|
233
|
+
export function pathEnd(segments: readonly PathSegment[]): PathTangent {
|
|
234
|
+
const last = segments[segments.length - 1];
|
|
235
|
+
if (last === undefined) throw new RangeError("layout-path: a path with no segment has no end.");
|
|
236
|
+
for (let i = segments.length - 1; i >= 1; i--) {
|
|
237
|
+
const direction = directionOf(segments[i - 1]!.to, segments[i]!, true);
|
|
238
|
+
if (direction !== undefined) return { point: last.to, direction };
|
|
239
|
+
}
|
|
240
|
+
return { point: last.to, direction: { x: 0, y: 0 } };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const isFields = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
244
|
+
|
|
245
|
+
const isPoint = (v: unknown): v is Point => isFields(v) && Number.isFinite(v["x"]) && Number.isFinite(v["y"]);
|
|
246
|
+
|
|
247
|
+
/** The fields of each kind of segment that hold a point. */
|
|
248
|
+
const POINT_FIELDS = { move: ["to"], line: ["to"], cubic: ["c1", "c2", "to"], arc: ["center", "to"] } as const;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* This function gives the problems of a path. An empty list means a good path.
|
|
252
|
+
* A good path starts with its one `move`, and each number of it is finite. An arc has a radius of 0 or more.
|
|
253
|
+
* An arc starts at the end of the segment before, and it ends at its `to`, to 1e-6 of its radius plus 1.
|
|
254
|
+
*/
|
|
255
|
+
export function checkPath(value: unknown): string[] {
|
|
256
|
+
if (!Array.isArray(value)) return ["the path is not a list"];
|
|
257
|
+
if (value.length === 0) return ["the path has no segment"];
|
|
258
|
+
const out: string[] = [];
|
|
259
|
+
let at: Point | undefined;
|
|
260
|
+
value.forEach((s: unknown, i) => {
|
|
261
|
+
const from = at;
|
|
262
|
+
at = undefined;
|
|
263
|
+
if (!isFields(s)) {
|
|
264
|
+
out.push(`segment ${i} is not an object`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const kind = PATH_KINDS.find((k) => k === s["kind"]);
|
|
268
|
+
if (kind === undefined) {
|
|
269
|
+
out.push(`segment ${i}: the kind is not one of ${PATH_KINDS.join(", ")}`);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (i === 0 && kind !== "move") out.push("segment 0 is not a move");
|
|
273
|
+
if (i > 0 && kind === "move") out.push(`segment ${i} is a second move`);
|
|
274
|
+
let good = true;
|
|
275
|
+
for (const key of POINT_FIELDS[kind]) {
|
|
276
|
+
if (isPoint(s[key])) continue;
|
|
277
|
+
out.push(`segment ${i}: ${key} is not a point of two finite numbers`);
|
|
278
|
+
good = false;
|
|
279
|
+
}
|
|
280
|
+
const to = s["to"];
|
|
281
|
+
if (isPoint(to)) at = to;
|
|
282
|
+
if (kind !== "arc") return;
|
|
283
|
+
for (const key of ["radius", "start", "sweep"] as const) {
|
|
284
|
+
if (Number.isFinite(s[key])) continue;
|
|
285
|
+
out.push(`segment ${i}: ${key} is not a finite number`);
|
|
286
|
+
good = false;
|
|
287
|
+
}
|
|
288
|
+
if (!good) return;
|
|
289
|
+
const arc = s as unknown as PathArc;
|
|
290
|
+
if (arc.radius < 0) {
|
|
291
|
+
out.push(`segment ${i}: the radius is less than 0`);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const slack = 1e-6 * (arc.radius + 1);
|
|
295
|
+
const on = (angle: number, p: Point): boolean => Math.hypot(arc.center.x + arc.radius * Math.cos(angle) - p.x, arc.center.y + arc.radius * Math.sin(angle) - p.y) <= slack;
|
|
296
|
+
if (from !== undefined && !on(arc.start, from)) out.push(`segment ${i}: the arc does not start at the end of the segment before`);
|
|
297
|
+
if (!on(arc.start + arc.sweep, arc.to)) out.push(`segment ${i}: the arc does not end at its point to`);
|
|
298
|
+
});
|
|
299
|
+
return out;
|
|
300
|
+
}
|
package/src/picture.ts
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
// The picture of a layout (`docs/PICTURE.md`): the record `layout-picture/1`. It holds the placed boxes, the route of each edge and the labels.
|
|
2
|
+
// A viewer draws a picture. Thus it shows the output of each engine, and it imports no engine.
|
|
3
|
+
import type { PlacedBox } from "./balance.ts";
|
|
4
|
+
import type { Point, Rect, Region } from "./geometry.ts";
|
|
5
|
+
import type { LayoutBox, LayoutInput } from "./input.ts";
|
|
6
|
+
import { checkPath, pathBounds, pathOf, type PathSegment } from "./path.ts";
|
|
7
|
+
|
|
8
|
+
/** The schema of a picture. */
|
|
9
|
+
export const PICTURE_SCHEMA = "layout-picture/1";
|
|
10
|
+
|
|
11
|
+
/** The places of the lines of a label in its width. */
|
|
12
|
+
export const LABEL_ALIGNS = ["left", "center", "right"] as const;
|
|
13
|
+
|
|
14
|
+
/** The place of the lines of a label in its width. */
|
|
15
|
+
export type LabelAlign = (typeof LABEL_ALIGNS)[number];
|
|
16
|
+
|
|
17
|
+
/** One box of a picture: its rectangle in the coordinates of the picture. A child does not have coordinates relative to its parent. */
|
|
18
|
+
export interface PictureBox extends PlacedBox {
|
|
19
|
+
/** The box that contains this box. A parent comes before its children in the list. */
|
|
20
|
+
readonly parent?: string;
|
|
21
|
+
/** The region of the box, relative to its top-left corner, as `LayoutBox.shape`. Without it, the box is its rectangle. */
|
|
22
|
+
readonly shape?: Region;
|
|
23
|
+
/** The free data of the box. A viewer chooses the look of the box from it. */
|
|
24
|
+
readonly data?: Readonly<Record<string, unknown>>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The route of one edge: the two boxes of the edge and the path that a renderer draws. */
|
|
28
|
+
export interface PictureRoute {
|
|
29
|
+
/** The id of the edge. */
|
|
30
|
+
readonly id: string;
|
|
31
|
+
readonly source: string;
|
|
32
|
+
readonly target: string;
|
|
33
|
+
/** The path from the source to the target. A polyline is a path of lines (`pathOf`). */
|
|
34
|
+
readonly path: readonly PathSegment[];
|
|
35
|
+
/** The free data of the edge. A viewer chooses the look of the route from it. */
|
|
36
|
+
readonly data?: Readonly<Record<string, unknown>>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* One label: the lines of a text that an engine measured, at a place. A renderer draws the lines with `font`, and it does not break them again.
|
|
41
|
+
* The rectangle is the area of the text. Line `i` is in the band that starts at `y + i * lineHeight`, and the band has the height `lineHeight`.
|
|
42
|
+
*/
|
|
43
|
+
export interface PictureLabel extends PlacedBox {
|
|
44
|
+
/** The box that the label names. A label has at most one of `box` and `route`. */
|
|
45
|
+
readonly box?: string;
|
|
46
|
+
/** The route that the label names. */
|
|
47
|
+
readonly route?: string;
|
|
48
|
+
readonly lines: readonly string[];
|
|
49
|
+
/** The height of each line. A finite number above 0. */
|
|
50
|
+
readonly lineHeight: number;
|
|
51
|
+
/** The font of the measure, as the CSS property `font`. */
|
|
52
|
+
readonly font: string;
|
|
53
|
+
/** The place of each line in the width `w`. The default is `left`. */
|
|
54
|
+
readonly align?: LabelAlign;
|
|
55
|
+
readonly data?: Readonly<Record<string, unknown>>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* A picture: the boxes, the routes and the labels of a layout, in the coordinates of the picture.
|
|
60
|
+
* Each list is in the order of the paint, so its first record is at the back. A viewer chooses the order of the three lists.
|
|
61
|
+
*/
|
|
62
|
+
export interface LayoutPicture {
|
|
63
|
+
readonly schema: typeof PICTURE_SCHEMA;
|
|
64
|
+
/** The id of the input of the picture. */
|
|
65
|
+
readonly id?: string;
|
|
66
|
+
readonly boxes: readonly PictureBox[];
|
|
67
|
+
readonly routes: readonly PictureRoute[];
|
|
68
|
+
readonly labels: readonly PictureLabel[];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* A route of a router, for `pictureOf`: the id of its edge and the points of its polyline. A `Route` of `highways` has this form.
|
|
73
|
+
* With `path`, the picture has that path, for example a curve through the points.
|
|
74
|
+
*/
|
|
75
|
+
export interface PictureRouteSource {
|
|
76
|
+
readonly edge: string;
|
|
77
|
+
readonly points: readonly Point[];
|
|
78
|
+
readonly path?: readonly PathSegment[];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The parts of a picture that an input does not hold, for `pictureOf`. */
|
|
82
|
+
export interface PictureParts {
|
|
83
|
+
readonly routes?: readonly PictureRouteSource[];
|
|
84
|
+
readonly labels?: readonly PictureLabel[];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
type Fields = Record<string, unknown>;
|
|
88
|
+
|
|
89
|
+
const isFields = (v: unknown): v is Fields => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
90
|
+
|
|
91
|
+
const REGION_KINDS: readonly unknown[] = ["rect", "polygon", "circle", "ellipse"];
|
|
92
|
+
|
|
93
|
+
/** This function gives the list `v`. A value that is not a list adds a problem and gives an empty list. */
|
|
94
|
+
function listOf(out: string[], v: unknown, name: string): readonly unknown[] {
|
|
95
|
+
if (Array.isArray(v)) return v;
|
|
96
|
+
out.push(`${name} is not a list`);
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* This function gives the fields and the name of record `i` of a list, or `undefined` for a record without a good id.
|
|
102
|
+
* The name is the kind and the id, for the text of a problem. An id two times in the list adds a problem.
|
|
103
|
+
*/
|
|
104
|
+
function recordOf(out: string[], kind: string, v: unknown, i: number, seen: Set<string>): { fields: Fields; id: string; name: string } | undefined {
|
|
105
|
+
if (!isFields(v)) {
|
|
106
|
+
out.push(`${kind} ${i} is not an object`);
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
const id = v["id"];
|
|
110
|
+
if (typeof id !== "string" || id === "") {
|
|
111
|
+
out.push(`${kind} ${i}: the id is not a string with a character`);
|
|
112
|
+
return undefined;
|
|
113
|
+
}
|
|
114
|
+
if (seen.has(id)) out.push(`${kind} ${id}: the id is not unique`);
|
|
115
|
+
return { fields: v, id, name: `${kind} ${id}` };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** This function adds the problems of the rectangle of a record: a value that is not finite, or a size less than 0. */
|
|
119
|
+
function rectProblems(out: string[], name: string, v: Fields): void {
|
|
120
|
+
for (const key of ["x", "y", "w", "h"] as const) {
|
|
121
|
+
const n = v[key];
|
|
122
|
+
if (typeof n !== "number" || !Number.isFinite(n)) out.push(`${name}: ${key} is not a finite number`);
|
|
123
|
+
else if (n < 0 && (key === "w" || key === "h")) out.push(`${name}: ${key} is less than 0`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** This function adds a problem for a field `data` that is not an object. */
|
|
128
|
+
function dataProblems(out: string[], name: string, v: Fields): void {
|
|
129
|
+
if (v["data"] !== undefined && !isFields(v["data"])) out.push(`${name}: data is not an object`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* This function gives the problems of one `layout-picture/1` value. An empty list means a good picture.
|
|
134
|
+
* Each id occurs one time in its list, each number is finite, and a size is 0 or more. A parent is a box before its child in the list.
|
|
135
|
+
* The source and the target of a route are boxes of the picture, and its path has no problem of `checkPath`.
|
|
136
|
+
*
|
|
137
|
+
* A label has lines of text, a line height above 0 and a font. Its `box` or its `route` is in the picture, and it does not have the two.
|
|
138
|
+
* The check accepts fields that the format does not know.
|
|
139
|
+
*/
|
|
140
|
+
export function checkPicture(value: unknown): string[] {
|
|
141
|
+
if (!isFields(value)) return ["the picture is not an object"];
|
|
142
|
+
const out: string[] = [];
|
|
143
|
+
if (value["schema"] !== PICTURE_SCHEMA) out.push(`schema is not ${PICTURE_SCHEMA}`);
|
|
144
|
+
if (value["id"] !== undefined && typeof value["id"] !== "string") out.push("id is not a string");
|
|
145
|
+
const boxIds = new Set<string>();
|
|
146
|
+
listOf(out, value["boxes"], "boxes").forEach((v, i) => {
|
|
147
|
+
const box = recordOf(out, "box", v, i, boxIds);
|
|
148
|
+
if (box === undefined) return;
|
|
149
|
+
rectProblems(out, box.name, box.fields);
|
|
150
|
+
const parent = box.fields["parent"];
|
|
151
|
+
if (parent !== undefined && (typeof parent !== "string" || parent === box.id || !boxIds.has(parent))) out.push(`${box.name}: the parent ${String(parent)} is not a box before it in the list`);
|
|
152
|
+
const shape = box.fields["shape"];
|
|
153
|
+
if (shape !== undefined && !(isFields(shape) && REGION_KINDS.includes(shape["kind"]))) out.push(`${box.name}: the shape is not a region`);
|
|
154
|
+
dataProblems(out, box.name, box.fields);
|
|
155
|
+
boxIds.add(box.id);
|
|
156
|
+
});
|
|
157
|
+
const routeIds = new Set<string>();
|
|
158
|
+
listOf(out, value["routes"], "routes").forEach((v, i) => {
|
|
159
|
+
const route = recordOf(out, "route", v, i, routeIds);
|
|
160
|
+
if (route === undefined) return;
|
|
161
|
+
for (const key of ["source", "target"] as const) {
|
|
162
|
+
const end = route.fields[key];
|
|
163
|
+
if (typeof end !== "string" || !boxIds.has(end)) out.push(`${route.name}: the ${key} ${String(end)} is not a box of the picture`);
|
|
164
|
+
}
|
|
165
|
+
for (const problem of checkPath(route.fields["path"])) out.push(`${route.name}: ${problem}`);
|
|
166
|
+
dataProblems(out, route.name, route.fields);
|
|
167
|
+
routeIds.add(route.id);
|
|
168
|
+
});
|
|
169
|
+
const labelIds = new Set<string>();
|
|
170
|
+
listOf(out, value["labels"], "labels").forEach((v, i) => {
|
|
171
|
+
const label = recordOf(out, "label", v, i, labelIds);
|
|
172
|
+
if (label === undefined) return;
|
|
173
|
+
const f = label.fields;
|
|
174
|
+
rectProblems(out, label.name, f);
|
|
175
|
+
if (f["box"] !== undefined && f["route"] !== undefined) out.push(`${label.name}: the label has a box and a route`);
|
|
176
|
+
if (f["box"] !== undefined && (typeof f["box"] !== "string" || !boxIds.has(f["box"]))) out.push(`${label.name}: the box ${String(f["box"])} is not a box of the picture`);
|
|
177
|
+
if (f["route"] !== undefined && (typeof f["route"] !== "string" || !routeIds.has(f["route"]))) out.push(`${label.name}: the route ${String(f["route"])} is not a route of the picture`);
|
|
178
|
+
const lines = f["lines"];
|
|
179
|
+
if (!Array.isArray(lines) || !lines.every((line) => typeof line === "string")) out.push(`${label.name}: lines is not a list of strings`);
|
|
180
|
+
const lineHeight = f["lineHeight"];
|
|
181
|
+
if (typeof lineHeight !== "number" || !Number.isFinite(lineHeight) || lineHeight <= 0) out.push(`${label.name}: lineHeight is not a finite number above 0`);
|
|
182
|
+
if (typeof f["font"] !== "string" || f["font"] === "") out.push(`${label.name}: font is not a string with a character`);
|
|
183
|
+
if (f["align"] !== undefined && !(LABEL_ALIGNS as readonly unknown[]).includes(f["align"])) out.push(`${label.name}: align is not one of ${LABEL_ALIGNS.join(", ")}`);
|
|
184
|
+
dataProblems(out, label.name, f);
|
|
185
|
+
labelIds.add(label.id);
|
|
186
|
+
});
|
|
187
|
+
return out;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* This function reads one `layout-picture/1` value, for example a parsed JSON document.
|
|
192
|
+
* It throws a `TypeError` with the problems of `checkPicture`.
|
|
193
|
+
*/
|
|
194
|
+
export function parsePicture(value: unknown): LayoutPicture {
|
|
195
|
+
const problems = checkPicture(value);
|
|
196
|
+
if (problems.length > 0) throw new TypeError(`The value is not a layout-picture/1: ${problems.join(", ")}.`);
|
|
197
|
+
return value as LayoutPicture;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** This function gives the box of a picture for a placed box of an input. */
|
|
201
|
+
function pictureBox(box: LayoutBox, x: number, y: number): PictureBox {
|
|
202
|
+
return {
|
|
203
|
+
id: box.id,
|
|
204
|
+
x,
|
|
205
|
+
y,
|
|
206
|
+
w: box.w,
|
|
207
|
+
h: box.h,
|
|
208
|
+
...(box.parent === undefined ? {} : { parent: box.parent }),
|
|
209
|
+
...(box.shape === undefined ? {} : { shape: box.shape }),
|
|
210
|
+
...(box.data === undefined ? {} : { data: box.data }),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* This function makes the picture of a placed input. Each box with `x` and `y` is in the picture, and a box with no place is not.
|
|
216
|
+
* The coordinates of each box are those of the input. The order is the order of the input, but each box comes immediately before its children.
|
|
217
|
+
*
|
|
218
|
+
* Each route gets the source, the target and the data of its edge in the input. A route with no `path` gets the polyline of its points.
|
|
219
|
+
* The labels of `parts` go into the picture with no change.
|
|
220
|
+
* A `RangeError` comes for a placed box below a box with no place, and for a loop of parents.
|
|
221
|
+
* It comes also for a route with no edge in the input, and for each problem of `checkPicture`.
|
|
222
|
+
*/
|
|
223
|
+
export function pictureOf(input: Pick<LayoutInput, "id" | "boxes" | "edges">, parts: PictureParts = {}): LayoutPicture {
|
|
224
|
+
const placed = input.boxes.filter((b) => b.x !== undefined && b.y !== undefined);
|
|
225
|
+
const ids = new Set(placed.map((b) => b.id));
|
|
226
|
+
const roots: LayoutBox[] = [];
|
|
227
|
+
const children = new Map<string, LayoutBox[]>();
|
|
228
|
+
for (const b of placed) {
|
|
229
|
+
if (b.parent === undefined) {
|
|
230
|
+
roots.push(b);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (!ids.has(b.parent)) throw new RangeError(`layout-picture: the box ${b.id} has a place, and its parent ${b.parent} has no place in the input.`);
|
|
234
|
+
const list = children.get(b.parent);
|
|
235
|
+
if (list === undefined) children.set(b.parent, [b]);
|
|
236
|
+
else list.push(b);
|
|
237
|
+
}
|
|
238
|
+
const boxes: PictureBox[] = [];
|
|
239
|
+
const stack = roots.reverse();
|
|
240
|
+
for (let b = stack.pop(); b !== undefined; b = stack.pop()) {
|
|
241
|
+
boxes.push(pictureBox(b, b.x!, b.y!));
|
|
242
|
+
const list = children.get(b.id);
|
|
243
|
+
if (list !== undefined) for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!);
|
|
244
|
+
}
|
|
245
|
+
if (boxes.length < placed.length) throw new RangeError("layout-picture: the parents of the boxes of the input make a loop.");
|
|
246
|
+
const edges = new Map((input.edges ?? []).map((e) => [e.id, e]));
|
|
247
|
+
const routes = (parts.routes ?? []).map((r): PictureRoute => {
|
|
248
|
+
const edge = edges.get(r.edge);
|
|
249
|
+
if (edge === undefined) throw new RangeError(`layout-picture: the route ${r.edge} has no edge in the input.`);
|
|
250
|
+
return { id: edge.id, source: edge.source, target: edge.target, path: r.path ?? pathOf(r.points), ...(edge.data === undefined ? {} : { data: edge.data }) };
|
|
251
|
+
});
|
|
252
|
+
const picture: LayoutPicture = { schema: PICTURE_SCHEMA, id: input.id, boxes, routes, labels: [...(parts.labels ?? [])] };
|
|
253
|
+
const problems = checkPicture(picture);
|
|
254
|
+
if (problems.length > 0) throw new RangeError(`layout-picture: ${problems.join(", ")}.`);
|
|
255
|
+
return picture;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* This function gives the bounding box of a picture: its boxes, the exact bounds of its paths and its labels.
|
|
260
|
+
* A picture with no record gives `undefined`. The picture must be good (`checkPicture`).
|
|
261
|
+
*/
|
|
262
|
+
export function pictureBounds(picture: LayoutPicture): Rect | undefined {
|
|
263
|
+
let x0 = Infinity;
|
|
264
|
+
let y0 = Infinity;
|
|
265
|
+
let x1 = -Infinity;
|
|
266
|
+
let y1 = -Infinity;
|
|
267
|
+
const add = (r: Rect): void => {
|
|
268
|
+
x0 = Math.min(x0, r.x);
|
|
269
|
+
y0 = Math.min(y0, r.y);
|
|
270
|
+
x1 = Math.max(x1, r.x + r.w);
|
|
271
|
+
y1 = Math.max(y1, r.y + r.h);
|
|
272
|
+
};
|
|
273
|
+
for (const b of picture.boxes) add(b);
|
|
274
|
+
for (const r of picture.routes) add(pathBounds(r.path));
|
|
275
|
+
for (const l of picture.labels) add(l);
|
|
276
|
+
return x0 === Infinity ? undefined : { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
|
|
277
|
+
}
|