@crux-diagram/core 0.0.0-stage → 0.1.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/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +45 -2
- package/dist/cjs/angle.d.ts +8 -0
- package/dist/cjs/angle.js +23 -0
- package/dist/cjs/color.d.ts +9 -0
- package/dist/cjs/color.js +42 -0
- package/dist/cjs/geometry/anchor-snapping.d.ts +34 -0
- package/dist/cjs/geometry/anchor-snapping.js +66 -0
- package/dist/cjs/geometry/anchors.d.ts +15 -0
- package/dist/cjs/geometry/anchors.js +42 -0
- package/dist/cjs/geometry/bounds.d.ts +10 -0
- package/dist/cjs/geometry/bounds.js +37 -0
- package/dist/cjs/geometry/grid.d.ts +56 -0
- package/dist/cjs/geometry/grid.js +109 -0
- package/dist/cjs/geometry/hit-testing.d.ts +5 -0
- package/dist/cjs/geometry/hit-testing.js +26 -0
- package/dist/cjs/geometry/joints.d.ts +25 -0
- package/dist/cjs/geometry/joints.js +66 -0
- package/dist/cjs/geometry/placement.d.ts +15 -0
- package/dist/cjs/geometry/placement.js +37 -0
- package/dist/cjs/geometry/resize.d.ts +46 -0
- package/dist/cjs/geometry/resize.js +130 -0
- package/dist/cjs/geometry/rotation.d.ts +19 -0
- package/dist/cjs/geometry/rotation.js +40 -0
- package/dist/cjs/geometry/round.d.ts +9 -0
- package/dist/cjs/geometry/round.js +22 -0
- package/dist/cjs/geometry/transforms.d.ts +10 -0
- package/dist/cjs/geometry/transforms.js +30 -0
- package/dist/cjs/geometry/viewport.d.ts +48 -0
- package/dist/cjs/geometry/viewport.js +79 -0
- package/dist/cjs/ids.d.ts +4 -0
- package/dist/cjs/ids.js +22 -0
- package/dist/cjs/index.d.ts +21 -0
- package/dist/cjs/index.js +52 -0
- package/dist/cjs/io.d.ts +28 -0
- package/dist/cjs/io.js +69 -0
- package/dist/cjs/measure.d.ts +38 -0
- package/dist/cjs/measure.js +48 -0
- package/dist/cjs/names.d.ts +7 -0
- package/dist/cjs/names.js +42 -0
- package/dist/cjs/ops.d.ts +99 -0
- package/dist/cjs/ops.js +407 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/style.d.ts +26 -0
- package/dist/cjs/style.js +26 -0
- package/dist/cjs/types.d.ts +75 -0
- package/dist/cjs/types.js +9 -0
- package/dist/cjs/validate.d.ts +20 -0
- package/dist/cjs/validate.js +356 -0
- package/dist/esm/angle.d.ts +8 -0
- package/dist/esm/angle.js +17 -0
- package/dist/esm/color.d.ts +9 -0
- package/dist/esm/color.js +37 -0
- package/dist/esm/geometry/anchor-snapping.d.ts +34 -0
- package/dist/esm/geometry/anchor-snapping.js +61 -0
- package/dist/esm/geometry/anchors.d.ts +15 -0
- package/dist/esm/geometry/anchors.js +37 -0
- package/dist/esm/geometry/bounds.d.ts +10 -0
- package/dist/esm/geometry/bounds.js +33 -0
- package/dist/esm/geometry/grid.d.ts +56 -0
- package/dist/esm/geometry/grid.js +99 -0
- package/dist/esm/geometry/hit-testing.d.ts +5 -0
- package/dist/esm/geometry/hit-testing.js +22 -0
- package/dist/esm/geometry/joints.d.ts +25 -0
- package/dist/esm/geometry/joints.js +58 -0
- package/dist/esm/geometry/placement.d.ts +15 -0
- package/dist/esm/geometry/placement.js +34 -0
- package/dist/esm/geometry/resize.d.ts +46 -0
- package/dist/esm/geometry/resize.js +121 -0
- package/dist/esm/geometry/rotation.d.ts +19 -0
- package/dist/esm/geometry/rotation.js +35 -0
- package/dist/esm/geometry/round.d.ts +9 -0
- package/dist/esm/geometry/round.js +17 -0
- package/dist/esm/geometry/transforms.d.ts +10 -0
- package/dist/esm/geometry/transforms.js +23 -0
- package/dist/esm/geometry/viewport.d.ts +48 -0
- package/dist/esm/geometry/viewport.js +68 -0
- package/dist/esm/ids.d.ts +4 -0
- package/dist/esm/ids.js +18 -0
- package/dist/esm/index.d.ts +21 -0
- package/dist/esm/index.js +23 -0
- package/dist/esm/io.d.ts +28 -0
- package/dist/esm/io.js +62 -0
- package/dist/esm/measure.d.ts +38 -0
- package/dist/esm/measure.js +43 -0
- package/dist/esm/names.d.ts +7 -0
- package/dist/esm/names.js +38 -0
- package/dist/esm/ops.d.ts +99 -0
- package/dist/esm/ops.js +385 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/style.d.ts +26 -0
- package/dist/esm/style.js +21 -0
- package/dist/esm/types.d.ts +75 -0
- package/dist/esm/types.js +6 -0
- package/dist/esm/validate.d.ts +20 -0
- package/dist/esm/validate.js +351 -0
- package/package.json +58 -4
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daniel Garrido
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @crux-diagram/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Read, validate, edit and write drawings in the crux_diagram JSON format (v1).
|
|
4
|
+
|
|
5
|
+
- Zero runtime dependencies. Runs in Node (22+) and in browsers.
|
|
6
|
+
- ESM and CommonJS builds, with TypeScript types.
|
|
7
|
+
- Reads and writes the same JSON as the Flutter package [`crux_diagram`](https://pub.dev/packages/crux_diagram), checked against shared fixtures.
|
|
8
|
+
- Works without React: use it in a Node backend, a CLI, or any frontend framework. For the React editor, see [`@crux-diagram/react`](https://www.npmjs.com/package/@crux-diagram/react).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @crux-diagram/core
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { parse, safeParse, validate, moveShape, serialize } from '@crux-diagram/core';
|
|
20
|
+
|
|
21
|
+
// Read a drawing. `parse` throws a DrawingFormatError with the path of each problem.
|
|
22
|
+
const doc = parse(jsonFromBackend);
|
|
23
|
+
|
|
24
|
+
// Or check it without throwing.
|
|
25
|
+
const result = safeParse(jsonFromBackend);
|
|
26
|
+
if (!result.ok) console.error(result.error.errors);
|
|
27
|
+
|
|
28
|
+
// List the problems of an untrusted value.
|
|
29
|
+
const errors = validate(JSON.parse(body));
|
|
30
|
+
|
|
31
|
+
// Edit. Operations never mutate: they return a new document.
|
|
32
|
+
const moved = moveShape(doc, 's_01', { dx: 20, dy: 0 });
|
|
33
|
+
|
|
34
|
+
// Write compact JSON, ready to store.
|
|
35
|
+
const json = serialize(moved);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Placing joint labels needs a text measurer. In browsers use `CanvasTextMeasurer`; in Node, where there is no canvas, use `ApproximateTextMeasurer`.
|
|
39
|
+
|
|
40
|
+
## Format
|
|
41
|
+
|
|
42
|
+
The format is specified in [`spec/02-spec-formato-json.md`](https://github.com/DanM10/crux_diagram/blob/main/spec/02-spec-formato-json.md). Only `schemaVersion: 1` is read and written.
|
|
43
|
+
|
|
44
|
+
## License
|
|
45
|
+
|
|
46
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A full turn in radians. */
|
|
2
|
+
export declare const FULL_TURN: number;
|
|
3
|
+
/** Normalizes `radians` to [0, 2π). JS `%` keeps the dividend's sign, hence the double modulo. */
|
|
4
|
+
export declare function normalizeAngle(radians: number): number;
|
|
5
|
+
/** Radians to degrees, for libraries that use degrees (Konva). */
|
|
6
|
+
export declare function toDegrees(radians: number): number;
|
|
7
|
+
/** Degrees to radians. */
|
|
8
|
+
export declare function toRadians(degrees: number): number;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Angles (FMT-003, REC-040, REC-041). The document always stores radians.
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.FULL_TURN = void 0;
|
|
5
|
+
exports.normalizeAngle = normalizeAngle;
|
|
6
|
+
exports.toDegrees = toDegrees;
|
|
7
|
+
exports.toRadians = toRadians;
|
|
8
|
+
/** A full turn in radians. */
|
|
9
|
+
exports.FULL_TURN = 2 * Math.PI;
|
|
10
|
+
/** Normalizes `radians` to [0, 2π). JS `%` keeps the dividend's sign, hence the double modulo. */
|
|
11
|
+
function normalizeAngle(radians) {
|
|
12
|
+
const normalized = ((radians % exports.FULL_TURN) + exports.FULL_TURN) % exports.FULL_TURN;
|
|
13
|
+
// Same guard as Flutter: a value that rounds up to a full turn becomes 0.
|
|
14
|
+
return normalized >= exports.FULL_TURN ? 0 : normalized;
|
|
15
|
+
}
|
|
16
|
+
/** Radians to degrees, for libraries that use degrees (Konva). */
|
|
17
|
+
function toDegrees(radians) {
|
|
18
|
+
return (radians * 180) / Math.PI;
|
|
19
|
+
}
|
|
20
|
+
/** Degrees to radians. */
|
|
21
|
+
function toRadians(degrees) {
|
|
22
|
+
return (degrees * Math.PI) / 180;
|
|
23
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** True when `value` is an integer in [0, 4294967295]. */
|
|
2
|
+
export declare function isArgb(value: unknown): value is number;
|
|
3
|
+
/** Converts `0xAARRGGBB` to `rgba(R, G, B, A/255)`. Throws `RangeError` for a non-color. */
|
|
4
|
+
export declare function argbToCss(value: number): string;
|
|
5
|
+
/**
|
|
6
|
+
* Converts `rgba(R, G, B, A)` or `rgb(R, G, B)` back to `0xAARRGGBB`.
|
|
7
|
+
* Alpha is rounded to the nearest 1/255. Throws `RangeError` for anything else.
|
|
8
|
+
*/
|
|
9
|
+
export declare function cssToArgb(css: string): number;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ARGB <-> CSS conversion (FMT-004, REC-030, REC-031).
|
|
3
|
+
// Colors are unsigned 32-bit integers 0xAARRGGBB; bit operations go through `>>> 0`.
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.isArgb = isArgb;
|
|
6
|
+
exports.argbToCss = argbToCss;
|
|
7
|
+
exports.cssToArgb = cssToArgb;
|
|
8
|
+
const MAX_COLOR = 0xffffffff;
|
|
9
|
+
const CHANNEL = '(\\d{1,3})';
|
|
10
|
+
const ALPHA = '(\\d*\\.?\\d+)';
|
|
11
|
+
const RGBA = new RegExp(`^rgba\\(\\s*${CHANNEL}\\s*,\\s*${CHANNEL}\\s*,\\s*${CHANNEL}\\s*,\\s*${ALPHA}\\s*\\)$`);
|
|
12
|
+
const RGB = new RegExp(`^rgb\\(\\s*${CHANNEL}\\s*,\\s*${CHANNEL}\\s*,\\s*${CHANNEL}\\s*\\)$`);
|
|
13
|
+
/** True when `value` is an integer in [0, 4294967295]. */
|
|
14
|
+
function isArgb(value) {
|
|
15
|
+
return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= MAX_COLOR;
|
|
16
|
+
}
|
|
17
|
+
/** Converts `0xAARRGGBB` to `rgba(R, G, B, A/255)`. Throws `RangeError` for a non-color. */
|
|
18
|
+
function argbToCss(value) {
|
|
19
|
+
if (!isArgb(value))
|
|
20
|
+
throw new RangeError(`Not an ARGB color: ${value}`);
|
|
21
|
+
const a = (value >>> 24) & 0xff;
|
|
22
|
+
const r = (value >>> 16) & 0xff;
|
|
23
|
+
const g = (value >>> 8) & 0xff;
|
|
24
|
+
const b = value & 0xff;
|
|
25
|
+
return `rgba(${r}, ${g}, ${b}, ${a / 255})`;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Converts `rgba(R, G, B, A)` or `rgb(R, G, B)` back to `0xAARRGGBB`.
|
|
29
|
+
* Alpha is rounded to the nearest 1/255. Throws `RangeError` for anything else.
|
|
30
|
+
*/
|
|
31
|
+
function cssToArgb(css) {
|
|
32
|
+
const text = css.trim();
|
|
33
|
+
const match = RGBA.exec(text) ?? RGB.exec(text);
|
|
34
|
+
if (!match)
|
|
35
|
+
throw new RangeError(`Unsupported CSS color: ${css}`);
|
|
36
|
+
const [r, g, b] = [match[1], match[2], match[3]].map(Number);
|
|
37
|
+
const alpha = match[4] === undefined ? 1 : Number(match[4]);
|
|
38
|
+
if (r > 255 || g > 255 || b > 255 || alpha > 1)
|
|
39
|
+
throw new RangeError(`CSS color out of range: ${css}`);
|
|
40
|
+
const a = Math.round(alpha * 255);
|
|
41
|
+
return ((a << 24) | (r << 16) | (g << 8) | b) >>> 0;
|
|
42
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Point, Shape, Vector } from '../types.js';
|
|
2
|
+
import { type Anchor } from './anchors.js';
|
|
3
|
+
import type { ResizeHandle } from './resize.js';
|
|
4
|
+
/** A snap that moves anchor position `from` onto anchor position `to`. */
|
|
5
|
+
export interface AnchorSnap {
|
|
6
|
+
readonly from: Point;
|
|
7
|
+
readonly to: Point;
|
|
8
|
+
/** Index of the snapped-to anchor in the targets list. */
|
|
9
|
+
readonly targetIndex: number;
|
|
10
|
+
/** Translation that makes the two anchors coincide. */
|
|
11
|
+
readonly delta: Vector;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The nearest pair between `moving` and `targets` at most `threshold` apart, or null.
|
|
15
|
+
* On equal distances the first pair in `moving` order wins.
|
|
16
|
+
*/
|
|
17
|
+
export declare function nearestAnchorSnap(moving: readonly Anchor[], targets: readonly Anchor[], { threshold }: {
|
|
18
|
+
threshold: number;
|
|
19
|
+
}): AnchorSnap | null;
|
|
20
|
+
/** The anchor id under `handle`. Circles have no anchor under their corner handles. */
|
|
21
|
+
export declare function anchorIdForHandle(handle: ResizeHandle): string;
|
|
22
|
+
/** The anchor {@link pickAnchor} found. */
|
|
23
|
+
export interface AnchorHit {
|
|
24
|
+
readonly shapeId: string;
|
|
25
|
+
readonly anchorId: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The anchor under `point`: the nearest one within `radius`; when several shapes' anchors are
|
|
29
|
+
* within `tieTolerance` of that distance, the topmost shape wins. `shapes` are back to front.
|
|
30
|
+
*/
|
|
31
|
+
export declare function pickAnchor(shapes: readonly Shape[], point: Point, { radius, tieTolerance }: {
|
|
32
|
+
radius: number;
|
|
33
|
+
tieTolerance: number;
|
|
34
|
+
}): AnchorHit | null;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Snapping between anchors and picking an anchor (REC-077, port of Flutter's
|
|
3
|
+
// anchor_snapping and joint_geometry's pickAnchor).
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.nearestAnchorSnap = nearestAnchorSnap;
|
|
6
|
+
exports.anchorIdForHandle = anchorIdForHandle;
|
|
7
|
+
exports.pickAnchor = pickAnchor;
|
|
8
|
+
const anchors_js_1 = require("./anchors.js");
|
|
9
|
+
const round_js_1 = require("./round.js");
|
|
10
|
+
/**
|
|
11
|
+
* The nearest pair between `moving` and `targets` at most `threshold` apart, or null.
|
|
12
|
+
* On equal distances the first pair in `moving` order wins.
|
|
13
|
+
*/
|
|
14
|
+
function nearestAnchorSnap(moving, targets, { threshold }) {
|
|
15
|
+
let best = null;
|
|
16
|
+
let bestDistance = Infinity;
|
|
17
|
+
for (const from of moving) {
|
|
18
|
+
targets.forEach((to, i) => {
|
|
19
|
+
const d = (0, round_js_1.distance)(to.position.x - from.position.x, to.position.y - from.position.y);
|
|
20
|
+
if (d <= threshold && d < bestDistance) {
|
|
21
|
+
best = {
|
|
22
|
+
from: from.position,
|
|
23
|
+
to: to.position,
|
|
24
|
+
targetIndex: i,
|
|
25
|
+
delta: { dx: to.position.x - from.position.x, dy: to.position.y - from.position.y },
|
|
26
|
+
};
|
|
27
|
+
bestDistance = d;
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return best;
|
|
32
|
+
}
|
|
33
|
+
const HANDLE_ANCHORS = {
|
|
34
|
+
topLeft: 'tl',
|
|
35
|
+
top: 'tc',
|
|
36
|
+
topRight: 'tr',
|
|
37
|
+
right: 'rc',
|
|
38
|
+
bottomRight: 'br',
|
|
39
|
+
bottom: 'bc',
|
|
40
|
+
bottomLeft: 'bl',
|
|
41
|
+
left: 'lc',
|
|
42
|
+
};
|
|
43
|
+
/** The anchor id under `handle`. Circles have no anchor under their corner handles. */
|
|
44
|
+
function anchorIdForHandle(handle) {
|
|
45
|
+
return HANDLE_ANCHORS[handle];
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The anchor under `point`: the nearest one within `radius`; when several shapes' anchors are
|
|
49
|
+
* within `tieTolerance` of that distance, the topmost shape wins. `shapes` are back to front.
|
|
50
|
+
*/
|
|
51
|
+
function pickAnchor(shapes, point, { radius, tieTolerance }) {
|
|
52
|
+
const hits = [];
|
|
53
|
+
shapes.forEach((shape, z) => {
|
|
54
|
+
for (const anchor of (0, anchors_js_1.anchorsOf)(shape)) {
|
|
55
|
+
const d = (0, round_js_1.distance)(anchor.position.x - point.x, anchor.position.y - point.y);
|
|
56
|
+
if (d <= radius)
|
|
57
|
+
hits.push({ z, shapeId: shape.id, anchorId: anchor.id, distance: d });
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
if (hits.length === 0)
|
|
61
|
+
return null;
|
|
62
|
+
const nearest = Math.min(...hits.map((hit) => hit.distance));
|
|
63
|
+
const tied = hits.filter((hit) => hit.distance - nearest < tieTolerance);
|
|
64
|
+
const topmost = tied.reduce((a, b) => (b.z > a.z || (b.z === a.z && b.distance < a.distance) ? b : a));
|
|
65
|
+
return { shapeId: topmost.shapeId, anchorId: topmost.anchorId };
|
|
66
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Point, Shape, ShapeType } from '../types.js';
|
|
2
|
+
/** What kind of point an anchor marks on its shape. */
|
|
3
|
+
export type AnchorKind = 'vertex' | 'edgeMidpoint' | 'cardinal';
|
|
4
|
+
/** A well-known point of a shape, in canvas coordinates. `id` refers to the local frame. */
|
|
5
|
+
export interface Anchor {
|
|
6
|
+
readonly id: string;
|
|
7
|
+
readonly kind: AnchorKind;
|
|
8
|
+
readonly position: Point;
|
|
9
|
+
}
|
|
10
|
+
/** Anchor ids valid for `type`, in spec order. */
|
|
11
|
+
export declare function anchorIdsFor(type: ShapeType): readonly string[];
|
|
12
|
+
/** The anchors of `shape` in canvas coordinates, in spec order. The center is not an anchor. */
|
|
13
|
+
export declare function anchorsOf(shape: Shape): Anchor[];
|
|
14
|
+
/** Canvas position of `anchorId` on `shape`, or `null` when the type has no such anchor. */
|
|
15
|
+
export declare function anchorPositionOf(shape: Shape, anchorId: string): Point | null;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Anchors of a shape (spec 02, section 10; REC-050).
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.anchorIdsFor = anchorIdsFor;
|
|
5
|
+
exports.anchorsOf = anchorsOf;
|
|
6
|
+
exports.anchorPositionOf = anchorPositionOf;
|
|
7
|
+
const transforms_js_1 = require("./transforms.js");
|
|
8
|
+
const BOX_ANCHORS = [
|
|
9
|
+
{ id: 'tl', kind: 'vertex', local: (s) => ({ x: -s.width / 2, y: -s.height / 2 }) },
|
|
10
|
+
{ id: 'tr', kind: 'vertex', local: (s) => ({ x: s.width / 2, y: -s.height / 2 }) },
|
|
11
|
+
{ id: 'br', kind: 'vertex', local: (s) => ({ x: s.width / 2, y: s.height / 2 }) },
|
|
12
|
+
{ id: 'bl', kind: 'vertex', local: (s) => ({ x: -s.width / 2, y: s.height / 2 }) },
|
|
13
|
+
{ id: 'tc', kind: 'edgeMidpoint', local: (s) => ({ x: 0, y: -s.height / 2 }) },
|
|
14
|
+
{ id: 'rc', kind: 'edgeMidpoint', local: (s) => ({ x: s.width / 2, y: 0 }) },
|
|
15
|
+
{ id: 'bc', kind: 'edgeMidpoint', local: (s) => ({ x: 0, y: s.height / 2 }) },
|
|
16
|
+
{ id: 'lc', kind: 'edgeMidpoint', local: (s) => ({ x: -s.width / 2, y: 0 }) },
|
|
17
|
+
];
|
|
18
|
+
// A circle uses r = width / 2 for every cardinal point.
|
|
19
|
+
const CIRCLE_ANCHORS = [
|
|
20
|
+
{ id: 'tc', kind: 'cardinal', local: (s) => ({ x: 0, y: -s.width / 2 }) },
|
|
21
|
+
{ id: 'rc', kind: 'cardinal', local: (s) => ({ x: s.width / 2, y: 0 }) },
|
|
22
|
+
{ id: 'bc', kind: 'cardinal', local: (s) => ({ x: 0, y: s.width / 2 }) },
|
|
23
|
+
{ id: 'lc', kind: 'cardinal', local: (s) => ({ x: -s.width / 2, y: 0 }) },
|
|
24
|
+
];
|
|
25
|
+
const specsFor = (type) => (type === 'circle' ? CIRCLE_ANCHORS : BOX_ANCHORS);
|
|
26
|
+
/** Anchor ids valid for `type`, in spec order. */
|
|
27
|
+
function anchorIdsFor(type) {
|
|
28
|
+
return specsFor(type).map((s) => s.id);
|
|
29
|
+
}
|
|
30
|
+
/** The anchors of `shape` in canvas coordinates, in spec order. The center is not an anchor. */
|
|
31
|
+
function anchorsOf(shape) {
|
|
32
|
+
return specsFor(shape.type).map((spec) => ({
|
|
33
|
+
id: spec.id,
|
|
34
|
+
kind: spec.kind,
|
|
35
|
+
position: (0, transforms_js_1.worldFromLocal)(shape.center, shape.rotation, spec.local(shape.size)),
|
|
36
|
+
}));
|
|
37
|
+
}
|
|
38
|
+
/** Canvas position of `anchorId` on `shape`, or `null` when the type has no such anchor. */
|
|
39
|
+
function anchorPositionOf(shape, anchorId) {
|
|
40
|
+
const spec = specsFor(shape.type).find((s) => s.id === anchorId);
|
|
41
|
+
return spec ? (0, transforms_js_1.worldFromLocal)(shape.center, shape.rotation, spec.local(shape.size)) : null;
|
|
42
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Shape } from '../types.js';
|
|
2
|
+
import type { Rect } from './joints.js';
|
|
3
|
+
/**
|
|
4
|
+
* The axis-aligned box of `shape` in canvas units, rotation included (Flutter `shapeBounds`).
|
|
5
|
+
* Squares and rectangles use their rotated corners; circles use the rotated ellipse, so a
|
|
6
|
+
* turned circle keeps a tight box.
|
|
7
|
+
*/
|
|
8
|
+
export declare function shapeBounds(shape: Shape): Rect;
|
|
9
|
+
/** The union of the `shapeBounds` of `shapes`; the zero rect `(0, 0, 0, 0)` when empty (Flutter `boundsOfShapes`). */
|
|
10
|
+
export declare function boundsOfShapes(shapes: Iterable<Shape>): Rect;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Axis-aligned bounding boxes, ported from Flutter `transforms.dart` (REC-078).
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.shapeBounds = shapeBounds;
|
|
5
|
+
exports.boundsOfShapes = boundsOfShapes;
|
|
6
|
+
/**
|
|
7
|
+
* The axis-aligned box of `shape` in canvas units, rotation included (Flutter `shapeBounds`).
|
|
8
|
+
* Squares and rectangles use their rotated corners; circles use the rotated ellipse, so a
|
|
9
|
+
* turned circle keeps a tight box.
|
|
10
|
+
*/
|
|
11
|
+
function shapeBounds(shape) {
|
|
12
|
+
const a = shape.size.width / 2;
|
|
13
|
+
const b = shape.size.height / 2;
|
|
14
|
+
const cos = Math.abs(Math.cos(shape.rotation));
|
|
15
|
+
const sin = Math.abs(Math.sin(shape.rotation));
|
|
16
|
+
const circle = shape.type === 'circle';
|
|
17
|
+
const halfX = circle ? Math.sqrt(a * a * cos * cos + b * b * sin * sin) : a * cos + b * sin;
|
|
18
|
+
const halfY = circle ? Math.sqrt(a * a * sin * sin + b * b * cos * cos) : a * sin + b * cos;
|
|
19
|
+
return { left: shape.center.x - halfX, top: shape.center.y - halfY, width: 2 * halfX, height: 2 * halfY };
|
|
20
|
+
}
|
|
21
|
+
/** The union of the `shapeBounds` of `shapes`; the zero rect `(0, 0, 0, 0)` when empty (Flutter `boundsOfShapes`). */
|
|
22
|
+
function boundsOfShapes(shapes) {
|
|
23
|
+
let left = Infinity;
|
|
24
|
+
let top = Infinity;
|
|
25
|
+
let right = -Infinity;
|
|
26
|
+
let bottom = -Infinity;
|
|
27
|
+
for (const shape of shapes) {
|
|
28
|
+
const box = shapeBounds(shape);
|
|
29
|
+
left = Math.min(left, box.left);
|
|
30
|
+
top = Math.min(top, box.top);
|
|
31
|
+
right = Math.max(right, box.left + box.width);
|
|
32
|
+
bottom = Math.max(bottom, box.top + box.height);
|
|
33
|
+
}
|
|
34
|
+
if (left === Infinity)
|
|
35
|
+
return { left: 0, top: 0, width: 0, height: 0 };
|
|
36
|
+
return { left, top, width: right - left, height: bottom - top };
|
|
37
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Point, Size, Vector } from '../types.js';
|
|
2
|
+
import type { Rect } from './joints.js';
|
|
3
|
+
/** Rounds `value` to the nearest multiple of `step`; halves round away from zero, like Dart. */
|
|
4
|
+
export declare function snapToMultiple(value: number, step: number): number;
|
|
5
|
+
/** Snaps both coordinates of `point` to multiples of `gridSize`. */
|
|
6
|
+
export declare function snapPointToGrid(point: Point, gridSize: number): Point;
|
|
7
|
+
/** Smallest on-screen spacing, in screen units, at which a grid level is drawn. */
|
|
8
|
+
export declare const MIN_GRID_SPACING = 8;
|
|
9
|
+
/** Tolerance of the {@link MIN_GRID_SPACING} comparison, in screen units. */
|
|
10
|
+
export declare const GRID_SPACING_TOLERANCE = 0.000001;
|
|
11
|
+
/** Grid settings at a given zoom: `scale` is screen units per canvas unit. */
|
|
12
|
+
export interface GridScale {
|
|
13
|
+
readonly gridSize: number;
|
|
14
|
+
readonly majorEvery: number;
|
|
15
|
+
readonly scale: number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Spacing, in canvas units, of the finest grid lines drawn: `gridSize` when minor lines
|
|
19
|
+
* are readable, `gridSize × majorEvery` when only major lines are, null when none is.
|
|
20
|
+
*/
|
|
21
|
+
export declare function visibleGridStep({ gridSize, majorEvery, scale }: GridScale): number | null;
|
|
22
|
+
/** One grid line along an axis. */
|
|
23
|
+
export interface GridLine {
|
|
24
|
+
readonly at: number;
|
|
25
|
+
readonly major: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Grid lines to draw along an axis of `extent` canvas units. A position on a major line
|
|
29
|
+
* is reported once, as major. Positions are `i × step`, so they do not drift.
|
|
30
|
+
* Throws `RangeError` for a non-finite `extent` or a `majorEvery` that is not a positive integer.
|
|
31
|
+
*/
|
|
32
|
+
export declare function gridLinesAlong(extent: number, grid: GridScale): GridLine[];
|
|
33
|
+
/** Tolerance, in quarter turns, of {@link isQuarterTurn}. */
|
|
34
|
+
export declare const QUARTER_TURN_TOLERANCE = 1e-9;
|
|
35
|
+
/** Whether `radians` is a multiple of 90°, within {@link QUARTER_TURN_TOLERANCE} quarter turns. */
|
|
36
|
+
export declare function isQuarterTurn(radians: number): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Snapped center of a shape of `size` and `rotation` moved so its center is at `center`.
|
|
39
|
+
* At a multiple of 90° the bounding box edge nearest to a grid line lands on it on each axis
|
|
40
|
+
* (the lower edge on a tie); at other rotations the center snaps to multiples of `step`.
|
|
41
|
+
*/
|
|
42
|
+
export declare function snapMoveToGrid(center: Point, { size, rotation, step }: {
|
|
43
|
+
size: Size;
|
|
44
|
+
rotation: number;
|
|
45
|
+
step: number;
|
|
46
|
+
}): Point;
|
|
47
|
+
/**
|
|
48
|
+
* Translation that moves `box` by about `delta` and snaps it to grid lines every `step` units.
|
|
49
|
+
* With `edges`, the box edge nearest to a line lands on it on each axis (the lower edge on a tie);
|
|
50
|
+
* otherwise the box center snaps. Measured from the snapped target, so a box already on lines
|
|
51
|
+
* moves by an exact multiple of `step`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function snapBoxShiftToGrid(box: Rect, delta: Vector, { step, edges }: {
|
|
54
|
+
step: number;
|
|
55
|
+
edges: boolean;
|
|
56
|
+
}): Vector;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Grid snapping and visible grid lines (REC-077, port of Flutter's grid).
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.QUARTER_TURN_TOLERANCE = exports.GRID_SPACING_TOLERANCE = exports.MIN_GRID_SPACING = void 0;
|
|
5
|
+
exports.snapToMultiple = snapToMultiple;
|
|
6
|
+
exports.snapPointToGrid = snapPointToGrid;
|
|
7
|
+
exports.visibleGridStep = visibleGridStep;
|
|
8
|
+
exports.gridLinesAlong = gridLinesAlong;
|
|
9
|
+
exports.isQuarterTurn = isQuarterTurn;
|
|
10
|
+
exports.snapMoveToGrid = snapMoveToGrid;
|
|
11
|
+
exports.snapBoxShiftToGrid = snapBoxShiftToGrid;
|
|
12
|
+
const round_js_1 = require("./round.js");
|
|
13
|
+
/** Rounds `value` to the nearest multiple of `step`; halves round away from zero, like Dart. */
|
|
14
|
+
function snapToMultiple(value, step) {
|
|
15
|
+
return (0, round_js_1.roundHalfAwayFromZero)(value / step) * step;
|
|
16
|
+
}
|
|
17
|
+
/** Snaps both coordinates of `point` to multiples of `gridSize`. */
|
|
18
|
+
function snapPointToGrid(point, gridSize) {
|
|
19
|
+
return { x: snapToMultiple(point.x, gridSize), y: snapToMultiple(point.y, gridSize) };
|
|
20
|
+
}
|
|
21
|
+
/** Smallest on-screen spacing, in screen units, at which a grid level is drawn. */
|
|
22
|
+
exports.MIN_GRID_SPACING = 8;
|
|
23
|
+
/** Tolerance of the {@link MIN_GRID_SPACING} comparison, in screen units. */
|
|
24
|
+
exports.GRID_SPACING_TOLERANCE = 1e-6;
|
|
25
|
+
/**
|
|
26
|
+
* Spacing, in canvas units, of the finest grid lines drawn: `gridSize` when minor lines
|
|
27
|
+
* are readable, `gridSize × majorEvery` when only major lines are, null when none is.
|
|
28
|
+
*/
|
|
29
|
+
function visibleGridStep({ gridSize, majorEvery, scale }) {
|
|
30
|
+
const readable = (spacing) => spacing * scale >= exports.MIN_GRID_SPACING - exports.GRID_SPACING_TOLERANCE;
|
|
31
|
+
if (readable(gridSize))
|
|
32
|
+
return gridSize;
|
|
33
|
+
const majorSpacing = gridSize * majorEvery;
|
|
34
|
+
return readable(majorSpacing) ? majorSpacing : null;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Grid lines to draw along an axis of `extent` canvas units. A position on a major line
|
|
38
|
+
* is reported once, as major. Positions are `i × step`, so they do not drift.
|
|
39
|
+
* Throws `RangeError` for a non-finite `extent` or a `majorEvery` that is not a positive integer.
|
|
40
|
+
*/
|
|
41
|
+
function gridLinesAlong(extent, grid) {
|
|
42
|
+
// Dart throws on both (a non-finite floor, an integer modulo by zero); without the guard
|
|
43
|
+
// an infinite extent would loop forever here.
|
|
44
|
+
if (!Number.isFinite(extent))
|
|
45
|
+
throw new RangeError('extent must be finite');
|
|
46
|
+
if (!Number.isInteger(grid.majorEvery) || grid.majorEvery < 1)
|
|
47
|
+
throw new RangeError('majorEvery must be a positive integer');
|
|
48
|
+
const step = visibleGridStep(grid);
|
|
49
|
+
if (step === null)
|
|
50
|
+
return [];
|
|
51
|
+
const minor = step === grid.gridSize;
|
|
52
|
+
// The small slack keeps a line that lands on the far edge.
|
|
53
|
+
const count = Math.floor(extent / step + 1e-9);
|
|
54
|
+
const lines = [];
|
|
55
|
+
for (let i = 0; i <= count; i++) {
|
|
56
|
+
lines.push({ at: i * step, major: !minor || i % grid.majorEvery === 0 });
|
|
57
|
+
}
|
|
58
|
+
return lines;
|
|
59
|
+
}
|
|
60
|
+
/** Tolerance, in quarter turns, of {@link isQuarterTurn}. */
|
|
61
|
+
exports.QUARTER_TURN_TOLERANCE = 1e-9;
|
|
62
|
+
/** Whether `radians` is a multiple of 90°, within {@link QUARTER_TURN_TOLERANCE} quarter turns. */
|
|
63
|
+
function isQuarterTurn(radians) {
|
|
64
|
+
const quarters = radians / (Math.PI / 2);
|
|
65
|
+
return Math.abs(quarters - (0, round_js_1.roundHalfAwayFromZero)(quarters)) < exports.QUARTER_TURN_TOLERANCE;
|
|
66
|
+
}
|
|
67
|
+
/** Whether a shape at `rotation` has its width along the canvas y axis (odd quarter turns). */
|
|
68
|
+
function swapsAxes(rotation) {
|
|
69
|
+
return (0, round_js_1.isOdd)((0, round_js_1.roundHalfAwayFromZero)(rotation / (Math.PI / 2)));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Snapped center of a shape of `size` and `rotation` moved so its center is at `center`.
|
|
73
|
+
* At a multiple of 90° the bounding box edge nearest to a grid line lands on it on each axis
|
|
74
|
+
* (the lower edge on a tie); at other rotations the center snaps to multiples of `step`.
|
|
75
|
+
*/
|
|
76
|
+
function snapMoveToGrid(center, { size, rotation, step }) {
|
|
77
|
+
if (!isQuarterTurn(rotation))
|
|
78
|
+
return snapPointToGrid(center, step);
|
|
79
|
+
const swap = swapsAxes(rotation);
|
|
80
|
+
const halfX = (swap ? size.height : size.width) / 2;
|
|
81
|
+
const halfY = (swap ? size.width : size.height) / 2;
|
|
82
|
+
const axis = (c, half) => {
|
|
83
|
+
const low = snapToMultiple(c - half, step) - (c - half);
|
|
84
|
+
const high = snapToMultiple(c + half, step) - (c + half);
|
|
85
|
+
return c + (Math.abs(high) < Math.abs(low) ? high : low);
|
|
86
|
+
};
|
|
87
|
+
return { x: axis(center.x, halfX), y: axis(center.y, halfY) };
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Translation that moves `box` by about `delta` and snaps it to grid lines every `step` units.
|
|
91
|
+
* With `edges`, the box edge nearest to a line lands on it on each axis (the lower edge on a tie);
|
|
92
|
+
* otherwise the box center snaps. Measured from the snapped target, so a box already on lines
|
|
93
|
+
* moves by an exact multiple of `step`.
|
|
94
|
+
*/
|
|
95
|
+
function snapBoxShiftToGrid(box, delta, { step, edges }) {
|
|
96
|
+
const axis = (low, high, d) => {
|
|
97
|
+
if (!edges) {
|
|
98
|
+
const center = (low + high) / 2;
|
|
99
|
+
return snapToMultiple(center + d, step) - center;
|
|
100
|
+
}
|
|
101
|
+
const toLow = snapToMultiple(low + d, step) - low;
|
|
102
|
+
const toHigh = snapToMultiple(high + d, step) - high;
|
|
103
|
+
return Math.abs(toHigh - d) < Math.abs(toLow - d) ? toHigh : toLow;
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
dx: axis(box.left, box.left + box.width, delta.dx),
|
|
107
|
+
dy: axis(box.top, box.top + box.height, delta.dy),
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Point, Shape } from '../types.js';
|
|
2
|
+
/** Whether `shape`'s area contains canvas point `point` (rotation-aware, edges inclusive). Fill does not matter. */
|
|
3
|
+
export declare function shapeContains(shape: Shape, point: Point): boolean;
|
|
4
|
+
/** The topmost shape (last in z-order) containing `point`, or null. */
|
|
5
|
+
export declare function topmostShapeAt(shapes: readonly Shape[], point: Point): Shape | null;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Selection by point (REC-077, port of Flutter's hit_testing).
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.shapeContains = shapeContains;
|
|
5
|
+
exports.topmostShapeAt = topmostShapeAt;
|
|
6
|
+
const transforms_js_1 = require("./transforms.js");
|
|
7
|
+
/** Whether `shape`'s area contains canvas point `point` (rotation-aware, edges inclusive). Fill does not matter. */
|
|
8
|
+
function shapeContains(shape, point) {
|
|
9
|
+
const local = (0, transforms_js_1.localFromWorld)(shape.center, shape.rotation, point);
|
|
10
|
+
const halfWidth = shape.size.width / 2;
|
|
11
|
+
const halfHeight = shape.size.height / 2;
|
|
12
|
+
if (shape.type === 'circle') {
|
|
13
|
+
const nx = local.x / halfWidth;
|
|
14
|
+
const ny = local.y / halfHeight;
|
|
15
|
+
return nx * nx + ny * ny <= 1;
|
|
16
|
+
}
|
|
17
|
+
return Math.abs(local.x) <= halfWidth && Math.abs(local.y) <= halfHeight;
|
|
18
|
+
}
|
|
19
|
+
/** The topmost shape (last in z-order) containing `point`, or null. */
|
|
20
|
+
function topmostShapeAt(shapes, point) {
|
|
21
|
+
for (let i = shapes.length - 1; i >= 0; i--) {
|
|
22
|
+
if (shapeContains(shapes[i], point))
|
|
23
|
+
return shapes[i];
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Point, Size, Vector } from '../types.js';
|
|
2
|
+
/** An axis-aligned rectangle: top-left corner plus size. */
|
|
3
|
+
export interface Rect {
|
|
4
|
+
readonly left: number;
|
|
5
|
+
readonly top: number;
|
|
6
|
+
readonly width: number;
|
|
7
|
+
readonly height: number;
|
|
8
|
+
}
|
|
9
|
+
/** Distance from the anchor to a new joint's label center (FMT-040). */
|
|
10
|
+
export declare const DEFAULT_LABEL_DISTANCE = 64;
|
|
11
|
+
/** Unit vector from the shape center to the anchor, times 64; `(0, −64)` when they coincide (FMT-040). */
|
|
12
|
+
export declare function defaultLabelOffset(center: Point, anchor: Point): Vector;
|
|
13
|
+
/** The offset that keeps the label center `anchor + offset` inside the canvas (FMT-041). */
|
|
14
|
+
export declare function clampLabelOffset(anchor: Point, offset: Vector, canvas: Size): Vector;
|
|
15
|
+
/** Half-open containment, like Flutter's `Rect.contains`: right and bottom edges are outside. */
|
|
16
|
+
export declare function rectContains(rect: Rect, point: Point): boolean;
|
|
17
|
+
/** Where the segment from the label center to `anchor` leaves `labelRect`; `null` when the anchor is inside (FMT-043). */
|
|
18
|
+
export declare function leaderLineStart(labelRect: Rect, anchor: Point): Point | null;
|
|
19
|
+
/** The arrowhead triangle `[tip, base + normal, base − normal]` for a line from `from` to `tip` (FMT-044). */
|
|
20
|
+
export declare function arrowheadPoints(args: {
|
|
21
|
+
from: Point;
|
|
22
|
+
tip: Point;
|
|
23
|
+
length: number;
|
|
24
|
+
width: number;
|
|
25
|
+
}): [Point, Point, Point];
|