@grethel-labs/excaliplant 0.4.0 → 0.5.2
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 +42 -0
- package/README.md +20 -8
- package/SECURITY.md +2 -1
- package/THIRD_PARTY_NOTICES.md +5 -4
- package/assets/fonts/Excalifont-Regular.ttf +0 -0
- package/assets/fonts/LICENSE.txt +1 -1
- package/bin/excaliplant.mjs +9 -0
- package/index.mjs +10 -0
- package/package.json +6 -6
- package/src/layout/sizing.mjs +32 -10
- package/src/model/diagram.mjs +9 -0
- package/src/render/canvas_svg.mjs +14 -2
- package/src/render/excalidraw.mjs +35 -18
- package/src/render/png.mjs +7 -7
- package/src/render/svg.mjs +29 -14
- package/src/style/font.mjs +17 -5
- package/src/style/style.mjs +316 -0
- package/src/style/text.mjs +71 -36
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- New `src/style/style.mjs` module with a single source of truth for
|
|
12
|
+
renderer styling. `getStyle()` / `setStyle()` / `resetStyle()` /
|
|
13
|
+
`loadStyleFromFile()` are exported from the package root, the CLI
|
|
14
|
+
exposes `excaliplant --style <file>`, and the `./style` subpath is
|
|
15
|
+
importable directly. The loader supports JSON and a small YAML
|
|
16
|
+
subset (nested maps, scalars, comments) so style overrides can live
|
|
17
|
+
in either format. Example presets ship as
|
|
18
|
+
[`style.example.json`](style.example.json) and
|
|
19
|
+
[`style.example.yaml`](style.example.yaml).
|
|
20
|
+
- Auto-shrink for box titles and descriptions: long unbreakable
|
|
21
|
+
identifiers now reduce their font size (down to `text.minFontSize`)
|
|
22
|
+
rather than overflowing. Disable via `text.autoShrink: false`. New
|
|
23
|
+
helper `measureFitted` is exported from `src/style/text.mjs`.
|
|
24
|
+
- Edge-label chips now carry `customData.role` markers
|
|
25
|
+
(`edgeLabelChip` / `edgeLabelText`) so renderers, tests, and
|
|
26
|
+
third-party tools can identify them reliably.
|
|
27
|
+
- Auto-generated single-page API reference at
|
|
28
|
+
[`docs/API.md`](docs/API.md). It replaces the previous TypeDoc HTML
|
|
29
|
+
site under `docs/api/` and is rendered from JSDoc by
|
|
30
|
+
[`docs/scripts/extract-api.mjs`](docs/scripts/extract-api.mjs) +
|
|
31
|
+
[`docs/API.template.md.njk`](docs/API.template.md.njk) on every
|
|
32
|
+
`npm run build:docs` run, so it can never drift from the README.
|
|
33
|
+
The TypeDoc devDependency was removed.
|
|
34
|
+
|
|
35
|
+
### Changed
|
|
36
|
+
|
|
37
|
+
- Edge labels render as a compact tag in the connection's stroke
|
|
38
|
+
colour with white text by default (`edgeLabel.useLineColor`,
|
|
39
|
+
`edgeLabel.textColor`, `edgeLabel.maxWidth`, …). The chip itself is
|
|
40
|
+
emitted with `roughness: 0` and no rounded corners so it reads as a
|
|
41
|
+
clean badge sitting on the line; default font size dropped to 10 px.
|
|
42
|
+
- The `svg.mjs` renderer now honours the per-element `roughness`
|
|
43
|
+
field, so connection arrows / lines and edge-label chips appear
|
|
44
|
+
perfectly straight in the exported SVG / PNG (matching the existing
|
|
45
|
+
`roughness: 0` Excalidraw JSON output).
|
|
46
|
+
- `FONT` from `src/style/text.mjs` is now a live view of the active
|
|
47
|
+
style document. Existing reads (`FONT.sizeTitle`, `FONT.family`,
|
|
48
|
+
…) keep working; calls to `setStyle()` / `loadStyleFromFile()`
|
|
49
|
+
immediately propagate to sizing and rendering.
|
|
50
|
+
|
|
9
51
|
## [0.3.7] - 2026-05-04
|
|
10
52
|
|
|
11
53
|
### Added
|
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
[](https://nodejs.org)
|
|
8
8
|
[](./LICENSE)
|
|
9
9
|
|
|
10
|
-
> PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser. · **v0.
|
|
10
|
+
> PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser. · **v0.5.2** · 116 tests · MIT
|
|
11
11
|
|
|
12
12
|
`@grethel-labs/excaliplant` takes PlantUML source, runs it through a plugin-based
|
|
13
13
|
parser, lays it out with [ELK](https://github.com/kieler/elkjs), and
|
|
@@ -103,13 +103,17 @@ Lower-level entry points are also exported:
|
|
|
103
103
|
| `excalidrawJsonToCanvasSvg(…)` | …same, letter-boxed onto a fixed-aspect canvas |
|
|
104
104
|
| `svgToPng(svg)` | Rasterise SVG to PNG (`@resvg/resvg-js`) |
|
|
105
105
|
|
|
106
|
+
The complete list of exported symbols, with parameter tables and
|
|
107
|
+
return types, lives in [`docs/API.md`](./docs/API.md). It is
|
|
108
|
+
regenerated from JSDoc on every `npm run build:docs` run.
|
|
109
|
+
|
|
106
110
|
### Run the tests
|
|
107
111
|
|
|
108
112
|
```sh
|
|
109
113
|
npm test
|
|
110
114
|
```
|
|
111
115
|
|
|
112
|
-
Ships with **
|
|
116
|
+
Ships with **116 tests** across functional, edge-case,
|
|
113
117
|
security (XSS / ReDoS / prototype-pollution), and self-introspection
|
|
114
118
|
suites.
|
|
115
119
|
|
|
@@ -190,6 +194,7 @@ PlantUML text
|
|
|
190
194
|
excaliplant
|
|
191
195
|
├── assets
|
|
192
196
|
│ └── fonts
|
|
197
|
+
│ ├── Excalifont-Regular.ttf
|
|
193
198
|
│ ├── Excalifont-Regular.woff2
|
|
194
199
|
│ └── LICENSE.txt
|
|
195
200
|
├── bin
|
|
@@ -200,9 +205,12 @@ excaliplant
|
|
|
200
205
|
│ │ ├── build-docs.mjs
|
|
201
206
|
│ │ ├── check-build-manifest.mjs
|
|
202
207
|
│ │ ├── config.mjs
|
|
208
|
+
│ │ ├── extract-api.mjs
|
|
203
209
|
│ │ ├── extract-docs.mjs
|
|
204
210
|
│ │ ├── file-tree.mjs
|
|
205
211
|
│ │ └── self-diagrams.mjs
|
|
212
|
+
│ ├── API.md
|
|
213
|
+
│ ├── API.template.md.njk
|
|
206
214
|
│ └── README.template.md.njk
|
|
207
215
|
├── scripts
|
|
208
216
|
│ ├── auto-patch-deps.mjs
|
|
@@ -238,6 +246,7 @@ excaliplant
|
|
|
238
246
|
│ └── style
|
|
239
247
|
│ ├── colors.mjs
|
|
240
248
|
│ ├── font.mjs
|
|
249
|
+
│ ├── style.mjs
|
|
241
250
|
│ └── text.mjs
|
|
242
251
|
├── tests
|
|
243
252
|
│ ├── edge_cases.test.mjs
|
|
@@ -245,7 +254,8 @@ excaliplant
|
|
|
245
254
|
│ ├── merge_driver.test.mjs
|
|
246
255
|
│ ├── plantuml.test.mjs
|
|
247
256
|
│ ├── security.test.mjs
|
|
248
|
-
│
|
|
257
|
+
│ ├── self_introspection.test.mjs
|
|
258
|
+
│ └── style.test.mjs
|
|
249
259
|
├── AGENTS.md
|
|
250
260
|
├── CHANGELOG.md
|
|
251
261
|
├── CLAUDE.md
|
|
@@ -257,13 +267,15 @@ excaliplant
|
|
|
257
267
|
├── THIRD_PARTY_NOTICES.md
|
|
258
268
|
├── index.mjs
|
|
259
269
|
├── package.json
|
|
260
|
-
├──
|
|
261
|
-
|
|
270
|
+
├── style.example.json
|
|
271
|
+
├── style.example.yaml
|
|
272
|
+
└── tsconfig.json
|
|
262
273
|
```
|
|
263
274
|
|
|
264
|
-
Generated artefacts (`docs/ressources/generated
|
|
265
|
-
|
|
266
|
-
`
|
|
275
|
+
Generated artefacts (`docs/ressources/generated/`) live in
|
|
276
|
+
`.gitignore` — they are rebuilt by `npm run build:docs`. The
|
|
277
|
+
single-page API reference at [`docs/API.md`](./docs/API.md) is
|
|
278
|
+
generated by the same command from JSDoc.
|
|
267
279
|
|
|
268
280
|
## Module documentation
|
|
269
281
|
|
package/SECURITY.md
CHANGED
|
@@ -37,7 +37,8 @@ patched release within 30 days for confirmed high/critical issues.
|
|
|
37
37
|
- Treat `renderPlantUml(input)` like any other untrusted-input parser.
|
|
38
38
|
Run it inside a worker / isolated process if your input source is
|
|
39
39
|
hostile.
|
|
40
|
-
- The SVG output **inlines the Excalifont woff2** as a `data:` URL
|
|
40
|
+
- The SVG output **inlines the Excalifont woff2** as a `data:` URL;
|
|
41
|
+
PNG rasterisation loads the bundled TrueType copy through `resvg`.
|
|
41
42
|
Some sandboxing environments restrict data URLs in fonts; if that
|
|
42
43
|
applies, post-process the SVG to drop the `<style>` block.
|
|
43
44
|
- The PNG path uses `@resvg/resvg-js` which executes as native code
|
package/THIRD_PARTY_NOTICES.md
CHANGED
|
@@ -4,17 +4,18 @@ This package bundles or depends on the following third-party works.
|
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
## Excalifont (Latin subset, woff2)
|
|
7
|
+
## Excalifont (Latin subset, woff2 + TrueType)
|
|
8
8
|
|
|
9
9
|
- Path: [`assets/fonts/Excalifont-Regular.woff2`](assets/fonts/Excalifont-Regular.woff2)
|
|
10
|
+
- Path: [`assets/fonts/Excalifont-Regular.ttf`](assets/fonts/Excalifont-Regular.ttf)
|
|
10
11
|
- Upstream: <https://github.com/excalidraw/excalidraw>
|
|
11
12
|
- License: SIL Open Font License 1.1 (OFL-1.1)
|
|
12
13
|
- Reproduction of the OFL notice is bundled alongside the binary at
|
|
13
14
|
[`assets/fonts/LICENSE.txt`](assets/fonts/LICENSE.txt).
|
|
14
15
|
|
|
15
|
-
The
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
The woff2 file is embedded into exported SVG documents as a `data:` URL.
|
|
17
|
+
The TrueType copy is loaded by `@resvg/resvg-js` for PNG rasterisation,
|
|
18
|
+
because resvg's `fontFiles` loader does not load woff2 files.
|
|
18
19
|
|
|
19
20
|
---
|
|
20
21
|
|
|
Binary file
|
package/assets/fonts/LICENSE.txt
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Excalifont
|
|
2
2
|
==========
|
|
3
3
|
|
|
4
|
-
The Excalifont woff2 font
|
|
4
|
+
The Excalifont woff2 and decompressed TrueType font files in this directory are bundled into
|
|
5
5
|
@grethel-labs/excaliplant so SVG and PNG exports render text in the
|
|
6
6
|
same hand-drawn typeface that Excalidraw uses on screen.
|
|
7
7
|
|
package/bin/excaliplant.mjs
CHANGED
|
@@ -37,6 +37,7 @@ Options:
|
|
|
37
37
|
--label <s> Source label written to appState.name.
|
|
38
38
|
--no-canvas For --svg: emit a tightly-cropped SVG without the 4:3 letterbox.
|
|
39
39
|
--rng-seed <n> Override the deterministic seed (use --rng-seed=random for non-determinism).
|
|
40
|
+
--style <file> Load a JSON or YAML style override (see style.example.json).
|
|
40
41
|
--max-input-bytes <N>
|
|
41
42
|
Reject stdin/file input larger than N bytes
|
|
42
43
|
(default ${DEFAULT_MAX_INPUT_BYTES}, ceiling ${MAX_INPUT_BYTES_CEILING}).
|
|
@@ -121,6 +122,9 @@ function parseArgs(argv) {
|
|
|
121
122
|
case "--rng-seed":
|
|
122
123
|
opts.rngSeed = argv[++i];
|
|
123
124
|
break;
|
|
125
|
+
case "--style":
|
|
126
|
+
opts.styleFile = argv[++i];
|
|
127
|
+
break;
|
|
124
128
|
case "--max-input-bytes": {
|
|
125
129
|
const n = parsePositiveInt(argv[++i], "--max-input-bytes");
|
|
126
130
|
if (n > MAX_INPUT_BYTES_CEILING) {
|
|
@@ -215,6 +219,11 @@ async function main() {
|
|
|
215
219
|
die(1, e?.message || String(e));
|
|
216
220
|
}
|
|
217
221
|
|
|
222
|
+
if (opts.styleFile) {
|
|
223
|
+
const { loadStyleFromFile } = await import("../src/style/style.mjs");
|
|
224
|
+
loadStyleFromFile(opts.styleFile);
|
|
225
|
+
}
|
|
226
|
+
|
|
218
227
|
// Build deterministic / overridable RNG.
|
|
219
228
|
let rng;
|
|
220
229
|
if (opts.rngSeed === "random") {
|
package/index.mjs
CHANGED
|
@@ -65,6 +65,16 @@ export {
|
|
|
65
65
|
export { svgToPng } from "./src/render/png.mjs";
|
|
66
66
|
export { EXCALIDRAW_SCHEMA, ROUNDNESS } from "./src/render/schema.mjs";
|
|
67
67
|
export { createSeededRng, stableHash32 } from "./src/render/rng.mjs";
|
|
68
|
+
export {
|
|
69
|
+
DEFAULT_STYLE,
|
|
70
|
+
EXCALIDRAW_FONT_FAMILY,
|
|
71
|
+
getStyle,
|
|
72
|
+
setStyle,
|
|
73
|
+
resetStyle,
|
|
74
|
+
loadStyleFromFile,
|
|
75
|
+
resolveFontFamilyId,
|
|
76
|
+
parseSimpleYaml,
|
|
77
|
+
} from "./src/style/style.mjs";
|
|
68
78
|
export {
|
|
69
79
|
Box,
|
|
70
80
|
Connection,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@grethel-labs/excaliplant",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"description": "PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.mjs",
|
|
@@ -30,14 +30,15 @@
|
|
|
30
30
|
"./render/png": "./src/render/png.mjs",
|
|
31
31
|
"./render/schema": "./src/render/schema.mjs",
|
|
32
32
|
"./render/rng": "./src/render/rng.mjs",
|
|
33
|
-
"./model": "./src/model/diagram.mjs"
|
|
33
|
+
"./model": "./src/model/diagram.mjs",
|
|
34
|
+
"./style": "./src/style/style.mjs"
|
|
34
35
|
},
|
|
35
36
|
"scripts": {
|
|
36
|
-
"test": "node --test tests/edge_cases.test.mjs tests/functional_more.test.mjs tests/merge_driver.test.mjs tests/plantuml.test.mjs tests/security.test.mjs tests/self_introspection.test.mjs",
|
|
37
|
+
"test": "node --test tests/edge_cases.test.mjs tests/functional_more.test.mjs tests/merge_driver.test.mjs tests/plantuml.test.mjs tests/security.test.mjs tests/self_introspection.test.mjs tests/style.test.mjs",
|
|
37
38
|
"typecheck": "tsc -p tsconfig.json",
|
|
38
39
|
"build:docs": "node docs/scripts/build-docs.mjs",
|
|
39
|
-
"build:api": "
|
|
40
|
-
"build": "npm run build:docs
|
|
40
|
+
"build:api": "node docs/scripts/build-docs.mjs",
|
|
41
|
+
"build": "npm run build:docs",
|
|
41
42
|
"format": "prettier --write .",
|
|
42
43
|
"format:check": "prettier --check .",
|
|
43
44
|
"prepare": "husky && node scripts/setup-merge-drivers.mjs",
|
|
@@ -83,7 +84,6 @@
|
|
|
83
84
|
"nunjucks": "^3.2.4",
|
|
84
85
|
"prettier": "^3.8.3",
|
|
85
86
|
"tree-node-cli": "^3.0.0",
|
|
86
|
-
"typedoc": "^0.28.19",
|
|
87
87
|
"typescript": "^6.0.3"
|
|
88
88
|
}
|
|
89
89
|
}
|
package/src/layout/sizing.mjs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// of a container share the same content width so titles align.
|
|
8
8
|
|
|
9
9
|
import { Box, Plane, Subplane } from "../model/diagram.mjs";
|
|
10
|
-
import { FONT, measureLine, measureWrapped } from "../style/text.mjs";
|
|
10
|
+
import { FONT, measureLine, measureWrapped, measureFitted } from "../style/text.mjs";
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Default padding / spacing constants used by {@link sizeDiagram}.
|
|
@@ -110,23 +110,45 @@ function sizeBox(box, width) {
|
|
|
110
110
|
const innerWidth = Math.max(20, width - SIZING.boxPaddingX * 2);
|
|
111
111
|
// Auto-wrap the title so long labels stay inside the box. Manual
|
|
112
112
|
// line breaks ("\n") are preserved by wrapping each segment
|
|
113
|
-
// independently.
|
|
113
|
+
// independently. `measureFitted` shrinks the font size when a
|
|
114
|
+
// single token would still overflow the inner width at the
|
|
115
|
+
// configured base size — long unbreakable identifiers (e.g.
|
|
116
|
+
// "AVeryLongClassName") then visibly shrink instead of overflowing.
|
|
114
117
|
const titleSegments = String(box.title || "").split("\n");
|
|
115
118
|
/** @type {string[]} */
|
|
116
119
|
const wrappedTitleLines = [];
|
|
120
|
+
let titleFontSize = FONT.sizeTitle;
|
|
117
121
|
for (const seg of titleSegments) {
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
122
|
+
const fitted = measureFitted(seg, FONT.sizeTitle, innerWidth);
|
|
123
|
+
titleFontSize = Math.min(titleFontSize, fitted.fontSize);
|
|
124
|
+
if (fitted.lines.length === 0) wrappedTitleLines.push("");
|
|
125
|
+
else wrappedTitleLines.push(...fitted.lines);
|
|
126
|
+
}
|
|
127
|
+
// Re-wrap every segment at the chosen size so all title lines share
|
|
128
|
+
// one font size (mixed-size titles look broken).
|
|
129
|
+
if (titleFontSize !== FONT.sizeTitle) {
|
|
130
|
+
wrappedTitleLines.length = 0;
|
|
131
|
+
for (const seg of titleSegments) {
|
|
132
|
+
const w = measureWrapped(seg, titleFontSize, innerWidth);
|
|
133
|
+
if (w.lines.length === 0) wrappedTitleLines.push("");
|
|
134
|
+
else wrappedTitleLines.push(...w.lines);
|
|
135
|
+
}
|
|
121
136
|
}
|
|
122
137
|
// Cache the wrapped title so the renderer can emit the exact same
|
|
123
138
|
// line breaks the sizing pass measured.
|
|
124
139
|
box._wrappedTitle = wrappedTitleLines.join("\n");
|
|
125
|
-
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
140
|
+
box._wrappedTitleFontSize = titleFontSize;
|
|
141
|
+
const titleHeight = wrappedTitleLines.length * titleFontSize * FONT.lineHeight;
|
|
142
|
+
let descriptionFontSize = FONT.sizeDescription;
|
|
143
|
+
/** @type {{height:number, lines:string[]}} */
|
|
144
|
+
let description = { height: 0, lines: [] };
|
|
145
|
+
if (box.description) {
|
|
146
|
+
const fittedDesc = measureFitted(box.description, FONT.sizeDescription, innerWidth);
|
|
147
|
+
descriptionFontSize = fittedDesc.fontSize;
|
|
148
|
+
description = { height: fittedDesc.height, lines: fittedDesc.lines };
|
|
149
|
+
box._wrappedDescription = description.lines.join("\n");
|
|
150
|
+
box._wrappedDescriptionFontSize = descriptionFontSize;
|
|
151
|
+
}
|
|
130
152
|
let textHeight = SIZING.boxPaddingY + titleHeight;
|
|
131
153
|
if (box.stereotype) textHeight += FONT.sizeDescription * FONT.lineHeight;
|
|
132
154
|
if (description.height) textHeight += SIZING.boxTitleGap + description.height;
|
package/src/model/diagram.mjs
CHANGED
|
@@ -83,6 +83,15 @@ export class Box {
|
|
|
83
83
|
this._wrappedTitle = undefined;
|
|
84
84
|
/** @type {string|undefined} */
|
|
85
85
|
this._wrappedDescription = undefined;
|
|
86
|
+
/**
|
|
87
|
+
* Auto-shrunk font sizes computed by the sizing pass when a long
|
|
88
|
+
* unbreakable token would otherwise overflow the box. Defaults to
|
|
89
|
+
* the active style's `font.sizeTitle` / `font.sizeDescription`.
|
|
90
|
+
* @type {number|undefined}
|
|
91
|
+
*/
|
|
92
|
+
this._wrappedTitleFontSize = undefined;
|
|
93
|
+
/** @type {number|undefined} */
|
|
94
|
+
this._wrappedDescriptionFontSize = undefined;
|
|
86
95
|
}
|
|
87
96
|
/** @returns {Plane | null} The owning plane (direct or via a {@link Subplane} parent). */
|
|
88
97
|
get plane() {
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
// (`./png.mjs`) needs `@resvg/resvg-js` to be installed.
|
|
10
10
|
|
|
11
11
|
import { excalidrawToSvg, escapeAttr } from "./svg.mjs";
|
|
12
|
+
import { EXCALIFONT_FONT_STACK } from "../style/font.mjs";
|
|
12
13
|
|
|
13
14
|
export const DEFAULT_CANVAS_WIDTH = 1200;
|
|
14
15
|
export const MIN_CANVAS_WIDTH = 16;
|
|
@@ -51,14 +52,25 @@ export function excalidrawJsonToCanvasSvg(doc, opts = {}) {
|
|
|
51
52
|
|
|
52
53
|
const innerBody = inner.replace(/^<svg[^>]*>/, "").replace(/<\/svg>\s*$/, "");
|
|
53
54
|
|
|
55
|
+
// The inner SVG starts with a root-level <defs> block (font-face + arrowhead
|
|
56
|
+
// markers). After we strip the <svg> wrapper that <defs> would otherwise end
|
|
57
|
+
// up inside the canvas <g transform>, which prevents Safari and resvg from
|
|
58
|
+
// resolving marker IDs and font-face rules reliably. Hoist it to the canvas
|
|
59
|
+
// root so it stays a direct child of the outer <svg>.
|
|
60
|
+
const defsMatch = innerBody.match(/^(\s*)(<defs>[\s\S]*?<\/defs>)([\s\S]*)$/);
|
|
61
|
+
const rootDefs = defsMatch ? defsMatch[2] : "";
|
|
62
|
+
const bodyWithoutDefs = defsMatch ? defsMatch[3] : innerBody;
|
|
63
|
+
|
|
54
64
|
return [
|
|
55
65
|
`<svg xmlns="http://www.w3.org/2000/svg" ` +
|
|
56
66
|
`width="${width}" height="${height}" ` +
|
|
57
|
-
`viewBox="0 0 ${width} ${height}"
|
|
67
|
+
`viewBox="0 0 ${width} ${height}" ` +
|
|
68
|
+
`font-family='${EXCALIFONT_FONT_STACK}'>`,
|
|
58
69
|
`<rect width="${width}" height="${height}" fill="${safeBackground}"/>`,
|
|
70
|
+
rootDefs,
|
|
59
71
|
`<g transform="translate(${offsetX} ${offsetY}) scale(${scale}) ` +
|
|
60
72
|
`translate(${-innerVb.x} ${-innerVb.y})">`,
|
|
61
|
-
|
|
73
|
+
bodyWithoutDefs,
|
|
62
74
|
`</g>`,
|
|
63
75
|
`</svg>`,
|
|
64
76
|
].join("");
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
import { Box, Plane, Subplane, SequenceDiagram } from "../model/diagram.mjs";
|
|
20
20
|
import { FONT, measureWrapped } from "../style/text.mjs";
|
|
21
|
+
import { getStyle } from "../style/style.mjs";
|
|
21
22
|
import { SIZING } from "../layout/sizing.mjs";
|
|
22
23
|
import { boxColor } from "../style/colors.mjs";
|
|
23
24
|
import { EXCALIDRAW_SCHEMA, ROUNDNESS } from "./schema.mjs";
|
|
@@ -721,8 +722,9 @@ function renderBoxText(box, color, elements, { titleColor } = {}) {
|
|
|
721
722
|
// text never overflows the box width). Falls back to the raw title
|
|
722
723
|
// for callers that bypass sizing.
|
|
723
724
|
const titleValue = box._wrappedTitle ?? String(box.title || "");
|
|
725
|
+
const titleFontSize = box._wrappedTitleFontSize ?? FONT.sizeTitle;
|
|
724
726
|
const titleLines = titleValue.split("\n").length;
|
|
725
|
-
const titleHeight =
|
|
727
|
+
const titleHeight = titleFontSize * FONT.lineHeight * titleLines;
|
|
726
728
|
if (box.stereotype) {
|
|
727
729
|
elements.push(
|
|
728
730
|
text({
|
|
@@ -744,13 +746,14 @@ function renderBoxText(box, color, elements, { titleColor } = {}) {
|
|
|
744
746
|
width: box.width - SIZING.boxPaddingX * 2,
|
|
745
747
|
height: titleHeight,
|
|
746
748
|
value: titleValue,
|
|
747
|
-
fontSize:
|
|
749
|
+
fontSize: titleFontSize,
|
|
748
750
|
color: titleColor || color.stroke,
|
|
749
751
|
align: "center",
|
|
750
752
|
}),
|
|
751
753
|
);
|
|
752
754
|
if (box.description) {
|
|
753
755
|
const descValue = box._wrappedDescription ?? String(box.description);
|
|
756
|
+
const descFontSize = box._wrappedDescriptionFontSize ?? FONT.sizeDescription;
|
|
754
757
|
elements.push(
|
|
755
758
|
text({
|
|
756
759
|
x: tx,
|
|
@@ -762,7 +765,7 @@ function renderBoxText(box, color, elements, { titleColor } = {}) {
|
|
|
762
765
|
width: box.width - SIZING.boxPaddingX * 2,
|
|
763
766
|
height: box.height - SIZING.boxPaddingY * 2 - titleHeight,
|
|
764
767
|
value: descValue,
|
|
765
|
-
fontSize:
|
|
768
|
+
fontSize: descFontSize,
|
|
766
769
|
color: "#444",
|
|
767
770
|
}),
|
|
768
771
|
);
|
|
@@ -1243,36 +1246,49 @@ function renderEdgeLabel(conn) {
|
|
|
1243
1246
|
const cy = (a.y + b.y) / 2;
|
|
1244
1247
|
|
|
1245
1248
|
// Segment angle, normalised to [-π/2, π/2] so text always reads
|
|
1246
|
-
// upright (never upside down).
|
|
1249
|
+
// upright (never upside down). The chip + text are rotated by this
|
|
1250
|
+
// angle so the label visually rides on top of the connection.
|
|
1247
1251
|
let angle = Math.atan2(b.y - a.y, b.x - a.x);
|
|
1248
1252
|
if (angle > Math.PI / 2) angle -= Math.PI;
|
|
1249
1253
|
else if (angle < -Math.PI / 2) angle += Math.PI;
|
|
1250
1254
|
|
|
1255
|
+
const style = /** @type {any} */ (getStyle()).edgeLabel || {};
|
|
1256
|
+
const lineColor = conn.from.plane?.color?.stroke || "#444";
|
|
1257
|
+
const bgColor = style.useLineColor === false ? style.backgroundColor || "#444" : lineColor;
|
|
1258
|
+
const strokeColor = style.strokeColor || bgColor;
|
|
1259
|
+
const textColor = style.textColor || "#ffffff";
|
|
1260
|
+
const padX = typeof style.paddingX === "number" ? style.paddingX : 6;
|
|
1261
|
+
const padY = typeof style.paddingY === "number" ? style.paddingY : 2;
|
|
1262
|
+
const segMargin = typeof style.segmentMargin === "number" ? style.segmentMargin : 24;
|
|
1263
|
+
const maxWidthCap = typeof style.maxWidth === "number" ? style.maxWidth : 160;
|
|
1264
|
+
|
|
1251
1265
|
const fontSize = FONT.sizeEdgeLabel;
|
|
1252
|
-
// Clamp the chip width to the segment length (minus a
|
|
1253
|
-
//
|
|
1254
|
-
const segCap = Math.max(40, bestLen -
|
|
1255
|
-
const maxChipWidth = Math.min(
|
|
1256
|
-
const wrapped = measureWrapped(String(conn.label), fontSize, maxChipWidth -
|
|
1257
|
-
const
|
|
1258
|
-
const
|
|
1259
|
-
const w = Math.min(maxChipWidth, wrapped.width + padX * 2);
|
|
1260
|
-
const h = wrapped.height + padY * 2;
|
|
1266
|
+
// Clamp the chip width to the segment length (minus a margin so
|
|
1267
|
+
// arrowheads stay clear) and cap at the configured absolute max.
|
|
1268
|
+
const segCap = Math.max(40, bestLen - segMargin);
|
|
1269
|
+
const maxChipWidth = Math.min(maxWidthCap, segCap);
|
|
1270
|
+
const wrapped = measureWrapped(String(conn.label), fontSize, maxChipWidth - padX * 2);
|
|
1271
|
+
const w = Math.min(maxChipWidth, Math.max(20, wrapped.width + padX * 2));
|
|
1272
|
+
const h = Math.max(fontSize * FONT.lineHeight, wrapped.height) + padY * 2;
|
|
1261
1273
|
const x = cx - w / 2;
|
|
1262
1274
|
const y = cy - h / 2;
|
|
1263
1275
|
const value = wrapped.lines.join("\n");
|
|
1264
1276
|
|
|
1277
|
+
// Chip: line-coloured pill, no wobble, no rounded corners, so the
|
|
1278
|
+
// label reads as a clean tag riding on the connection.
|
|
1265
1279
|
const chip = rect({
|
|
1266
1280
|
x,
|
|
1267
1281
|
y,
|
|
1268
1282
|
width: w,
|
|
1269
1283
|
height: h,
|
|
1270
|
-
strokeColor
|
|
1271
|
-
backgroundColor:
|
|
1284
|
+
strokeColor,
|
|
1285
|
+
backgroundColor: bgColor,
|
|
1272
1286
|
});
|
|
1273
1287
|
chip.angle = angle;
|
|
1274
|
-
|
|
1275
|
-
|
|
1288
|
+
chip.roughness = 0;
|
|
1289
|
+
chip.roundness = null;
|
|
1290
|
+
chip.strokeWidth = 1;
|
|
1291
|
+
chip.customData = { role: "edgeLabelChip" };
|
|
1276
1292
|
|
|
1277
1293
|
const label = text({
|
|
1278
1294
|
x: x + padX,
|
|
@@ -1281,11 +1297,12 @@ function renderEdgeLabel(conn) {
|
|
|
1281
1297
|
height: h - padY * 2,
|
|
1282
1298
|
value,
|
|
1283
1299
|
fontSize,
|
|
1284
|
-
color:
|
|
1300
|
+
color: textColor,
|
|
1285
1301
|
align: "center",
|
|
1286
1302
|
vAlign: "middle",
|
|
1287
1303
|
});
|
|
1288
1304
|
label.angle = angle;
|
|
1305
|
+
label.customData = { role: "edgeLabelText" };
|
|
1289
1306
|
return [chip, label];
|
|
1290
1307
|
}
|
|
1291
1308
|
|
package/src/render/png.mjs
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
import { Resvg } from "@resvg/resvg-js";
|
|
8
8
|
|
|
9
|
-
import {
|
|
9
|
+
import { EXCALIFONT_FAMILY, EXCALIFONT_RASTER_FONT_PATH } from "../style/font.mjs";
|
|
10
10
|
|
|
11
11
|
const DEFAULT_PNG_WIDTH = 4800; // 4× the default 1200 SVG canvas.
|
|
12
12
|
const MIN_PNG_WIDTH = 16;
|
|
@@ -32,14 +32,14 @@ export function svgToPng(svgText, opts = {}) {
|
|
|
32
32
|
const resvg = new Resvg(svgText, {
|
|
33
33
|
fitTo: { mode: "width", value: width },
|
|
34
34
|
background: opts.background ?? "#ffffff",
|
|
35
|
-
// resvg ignores @font-face / data-URL fonts in the SVG
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
// the Excalidraw
|
|
35
|
+
// resvg ignores @font-face / data-URL fonts in the SVG and does not
|
|
36
|
+
// load woff2 files via `fontFiles`, so point it at the decompressed
|
|
37
|
+
// TrueType copy of the bundled Excalifont instead. Otherwise PNG text
|
|
38
|
+
// falls back to a system font and loses the Excalidraw handwriting.
|
|
39
39
|
font: {
|
|
40
40
|
loadSystemFonts: true,
|
|
41
|
-
fontFiles: [
|
|
42
|
-
defaultFontFamily:
|
|
41
|
+
fontFiles: [EXCALIFONT_RASTER_FONT_PATH],
|
|
42
|
+
defaultFontFamily: EXCALIFONT_FAMILY,
|
|
43
43
|
},
|
|
44
44
|
});
|
|
45
45
|
return resvg.render().asPng();
|
package/src/render/svg.mjs
CHANGED
|
@@ -44,13 +44,16 @@ export function excalidrawToSvg(doc, opts = {}) {
|
|
|
44
44
|
out.push(
|
|
45
45
|
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" font-family='${FONT_FAMILY}'>`,
|
|
46
46
|
);
|
|
47
|
-
//
|
|
48
|
-
//
|
|
49
|
-
//
|
|
50
|
-
|
|
47
|
+
// Root-level <defs>: font-face + arrowhead markers. Keeping both here
|
|
48
|
+
// (rather than inside the translate <g>) ensures every SVG renderer
|
|
49
|
+
// finds the markers, as some implementations (Safari, resvg, some
|
|
50
|
+
// Markdown sanitisers) only resolve <marker> IDs when the <defs>
|
|
51
|
+
// is a direct child of the root <svg> element.
|
|
52
|
+
out.push(
|
|
53
|
+
`<defs><style type="text/css"><![CDATA[${getExcalifontFontFace()}]]></style>${arrowheadMarkers()}</defs>`,
|
|
54
|
+
);
|
|
51
55
|
out.push(`<rect width="100%" height="100%" fill="${escapeAttr(bg)}"/>`);
|
|
52
56
|
out.push(`<g transform="translate(${tx} ${ty})">`);
|
|
53
|
-
out.push(arrowheadDefs());
|
|
54
57
|
|
|
55
58
|
for (const el of elements) {
|
|
56
59
|
const node = renderOne(el);
|
|
@@ -147,16 +150,21 @@ function seedFor(el) {
|
|
|
147
150
|
* @returns {any} roughjs options.
|
|
148
151
|
*/
|
|
149
152
|
function roughOpts(el) {
|
|
153
|
+
// Honour the per-element roughness Excalidraw stores: arrows /
|
|
154
|
+
// connection lines are emitted with `roughness: 0` so their SVG
|
|
155
|
+
// representation must be perfectly straight too. Falling back to
|
|
156
|
+
// the default (1) keeps Excalidraw's hand-drawn look for boxes.
|
|
157
|
+
const r = typeof el.roughness === "number" ? el.roughness : ROUGHNESS;
|
|
150
158
|
return {
|
|
151
159
|
seed: seedFor(el),
|
|
152
|
-
roughness:
|
|
153
|
-
bowing: BOWING,
|
|
160
|
+
roughness: r,
|
|
161
|
+
bowing: r === 0 ? 0 : BOWING,
|
|
154
162
|
stroke: el.strokeColor || "#000",
|
|
155
163
|
strokeWidth: el.strokeWidth || 1.5,
|
|
156
164
|
fill: /** @type {string|undefined} */ (undefined),
|
|
157
165
|
fillStyle: "solid",
|
|
158
166
|
fillWeight: FILL_WEIGHT,
|
|
159
|
-
disableMultiStroke:
|
|
167
|
+
disableMultiStroke: r === 0,
|
|
160
168
|
};
|
|
161
169
|
}
|
|
162
170
|
|
|
@@ -295,7 +303,13 @@ function roughPolyline(el, withArrow) {
|
|
|
295
303
|
? ` marker-start="url(#m_${el.startArrowhead}_start)"`
|
|
296
304
|
: "";
|
|
297
305
|
const endMarker = el.endArrowhead ? ` marker-end="url(#m_${el.endArrowhead}_end)"` : "";
|
|
298
|
-
|
|
306
|
+
// Marker rendering rules vary across renderers:
|
|
307
|
+
// - stroke-width="0" : Safari and resvg skip markers (degenerate stroke)
|
|
308
|
+
// - stroke="none" : some renderers also skip markers
|
|
309
|
+
// Safest combination: a real, non-zero stroke width in a fully
|
|
310
|
+
// transparent colour. The polyline contributes no visible pixels
|
|
311
|
+
// but markers still attach at the vertices everywhere.
|
|
312
|
+
body += `<polyline points="${polyPts}" fill="none" stroke="rgba(0,0,0,0)" stroke-width="1"${startMarker}${endMarker}/>`;
|
|
299
313
|
}
|
|
300
314
|
return body;
|
|
301
315
|
}
|
|
@@ -324,9 +338,11 @@ function svgText(el) {
|
|
|
324
338
|
|
|
325
339
|
// ── arrowheads ────────────────────────────────────────────────────────────
|
|
326
340
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
341
|
+
// Returns only the <marker> elements (no wrapping <defs>). The caller
|
|
342
|
+
// merges them into the root <defs> block so SVG renderers that only
|
|
343
|
+
// resolve marker IDs from root-level <defs> (Safari, resvg) work.
|
|
344
|
+
function arrowheadMarkers() {
|
|
345
|
+
return `<marker id="m_arrow_end" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#000"/></marker>
|
|
330
346
|
<marker id="m_arrow_start" viewBox="0 0 10 10" refX="1" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#000"/></marker>
|
|
331
347
|
<marker id="m_triangle_end" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="9" markerHeight="9" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#000"/></marker>
|
|
332
348
|
<marker id="m_triangle_start" viewBox="0 0 10 10" refX="1" refY="5" markerWidth="9" markerHeight="9" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#000"/></marker>
|
|
@@ -335,8 +351,7 @@ function arrowheadDefs() {
|
|
|
335
351
|
<marker id="m_diamond_end" viewBox="0 0 12 10" refX="11" refY="5" markerWidth="10" markerHeight="8" orient="auto"><path d="M0,5 L6,0 L12,5 L6,10 z" fill="#000"/></marker>
|
|
336
352
|
<marker id="m_diamond_start" viewBox="0 0 12 10" refX="1" refY="5" markerWidth="10" markerHeight="8" orient="auto-start-reverse"><path d="M0,5 L6,0 L12,5 L6,10 z" fill="#000"/></marker>
|
|
337
353
|
<marker id="m_diamond_outline_end" viewBox="0 0 12 10" refX="11" refY="5" markerWidth="10" markerHeight="8" orient="auto"><path d="M0,5 L6,0 L12,5 L6,10 z" fill="#fff" stroke="#000"/></marker>
|
|
338
|
-
<marker id="m_diamond_outline_start" viewBox="0 0 12 10" refX="1" refY="5" markerWidth="10" markerHeight="8" orient="auto-start-reverse"><path d="M0,5 L6,0 L12,5 L6,10 z" fill="#fff" stroke="#000"/></marker
|
|
339
|
-
</defs>`;
|
|
354
|
+
<marker id="m_diamond_outline_start" viewBox="0 0 12 10" refX="1" refY="5" markerWidth="10" markerHeight="8" orient="auto-start-reverse"><path d="M0,5 L6,0 L12,5 L6,10 z" fill="#fff" stroke="#000"/></marker>`;
|
|
340
355
|
}
|
|
341
356
|
|
|
342
357
|
// ── misc ──────────────────────────────────────────────────────────────────
|
package/src/style/font.mjs
CHANGED
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
// hand-drawn typeface that Excalidraw uses on screen.
|
|
3
3
|
//
|
|
4
4
|
// Excalidraw ships Excalifont as a multi-subset family. We bundle the
|
|
5
|
-
// Latin subset (U+20-7E plus common punctuation)
|
|
6
|
-
//
|
|
5
|
+
// Latin subset (U+20-7E plus common punctuation). SVG output embeds the
|
|
6
|
+
// compact woff2 as a data URL, while PNG output points resvg at the
|
|
7
|
+
// decompressed TrueType copy because resvg/fontdb does not load woff2
|
|
8
|
+
// files from `fontFiles`.
|
|
7
9
|
//
|
|
8
10
|
// The font is OFL-licensed; the upstream copy lives at
|
|
9
11
|
// excalidraw/excalidraw on GitHub. The OFL notice is preserved in
|
|
@@ -14,12 +16,22 @@ import { fileURLToPath } from "node:url";
|
|
|
14
16
|
import path from "node:path";
|
|
15
17
|
|
|
16
18
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
17
|
-
const
|
|
19
|
+
const WOFF2_FONT_PATH = path.resolve(
|
|
20
|
+
here,
|
|
21
|
+
"..",
|
|
22
|
+
"..",
|
|
23
|
+
"assets",
|
|
24
|
+
"fonts",
|
|
25
|
+
"Excalifont-Regular.woff2",
|
|
26
|
+
);
|
|
27
|
+
const TTF_FONT_PATH = path.resolve(here, "..", "..", "assets", "fonts", "Excalifont-Regular.ttf");
|
|
18
28
|
|
|
19
29
|
/** Family name used inside the SVG `font-family` attribute. */
|
|
20
30
|
export const EXCALIFONT_FAMILY = "Excalifont";
|
|
21
31
|
/** Absolute filesystem path to the bundled woff2. */
|
|
22
|
-
export const EXCALIFONT_FONT_PATH =
|
|
32
|
+
export const EXCALIFONT_FONT_PATH = WOFF2_FONT_PATH;
|
|
33
|
+
/** Absolute filesystem path to the bundled TrueType copy used by resvg. */
|
|
34
|
+
export const EXCALIFONT_RASTER_FONT_PATH = TTF_FONT_PATH;
|
|
23
35
|
|
|
24
36
|
/** @type {Buffer | null} */
|
|
25
37
|
let _woff2 = null;
|
|
@@ -31,7 +43,7 @@ let _woff2 = null;
|
|
|
31
43
|
* @public
|
|
32
44
|
*/
|
|
33
45
|
export function getExcalifontWoff2() {
|
|
34
|
-
if (!_woff2) _woff2 = readFileSync(
|
|
46
|
+
if (!_woff2) _woff2 = readFileSync(WOFF2_FONT_PATH);
|
|
35
47
|
return _woff2;
|
|
36
48
|
}
|
|
37
49
|
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
// Renderer style configuration.
|
|
2
|
+
//
|
|
3
|
+
// Exposes a single mutable `STYLE` document and helpers to load it
|
|
4
|
+
// from a JSON or YAML file. All other style-related modules read from
|
|
5
|
+
// `getStyle()` (or the live-view `FONT` proxy in `text.mjs`) so a
|
|
6
|
+
// caller can override the look once and have parser/sizing/renderer
|
|
7
|
+
// all pick up the new values.
|
|
8
|
+
//
|
|
9
|
+
// The shape is intentionally small and flat. Fields are validated /
|
|
10
|
+
// merged on load: unknown keys are ignored, malformed values fall
|
|
11
|
+
// back to defaults, and the loader never throws on missing files —
|
|
12
|
+
// the caller decides how strict to be.
|
|
13
|
+
//
|
|
14
|
+
// YAML support is intentionally a tiny embedded subset (key/value,
|
|
15
|
+
// nested maps via 2-space indentation, comments, scalars). Diagrams
|
|
16
|
+
// don't need full YAML; bringing in a YAML dependency for that would
|
|
17
|
+
// be over-engineering.
|
|
18
|
+
|
|
19
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Excalidraw `fontFamily` enum mirror, kept here so `style.mjs` is
|
|
24
|
+
* importable without pulling in `text.mjs` (which now depends on
|
|
25
|
+
* this file).
|
|
26
|
+
*
|
|
27
|
+
* @public
|
|
28
|
+
*/
|
|
29
|
+
export const EXCALIDRAW_FONT_FAMILY = Object.freeze({
|
|
30
|
+
Virgil: 1,
|
|
31
|
+
Helvetica: 2,
|
|
32
|
+
Cascadia: 3,
|
|
33
|
+
LocalFont: 4,
|
|
34
|
+
Excalifont: 5,
|
|
35
|
+
Nunito: 6,
|
|
36
|
+
LilitaOne: 7,
|
|
37
|
+
ComicShanns: 8,
|
|
38
|
+
LiberationSans: 9,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Default renderer style. Cloned on every `setStyle` call so the
|
|
43
|
+
* exported reference stays immutable.
|
|
44
|
+
*
|
|
45
|
+
* @public
|
|
46
|
+
*/
|
|
47
|
+
export const DEFAULT_STYLE = deepFreeze({
|
|
48
|
+
font: {
|
|
49
|
+
/** Excalidraw font enum id, family name (e.g. "Excalifont"), or numeric id. */
|
|
50
|
+
family: "Excalifont",
|
|
51
|
+
sizeTitle: 18,
|
|
52
|
+
sizeDescription: 13,
|
|
53
|
+
sizeEdgeLabel: 10,
|
|
54
|
+
sizePlaneTitle: 22,
|
|
55
|
+
sizeSubplaneTitle: 16,
|
|
56
|
+
/** Average glyph width / fontSize, calibrated for Excalifont. */
|
|
57
|
+
glyphRatio: 0.51,
|
|
58
|
+
lineHeight: 1.25,
|
|
59
|
+
/** Lower bound used by the auto-shrink pass in `sizing.mjs`. */
|
|
60
|
+
minSize: 8,
|
|
61
|
+
},
|
|
62
|
+
shape: {
|
|
63
|
+
/** Roughness for boxes / ellipses / planes (Excalidraw default look). */
|
|
64
|
+
roughness: 1,
|
|
65
|
+
/** Roughness for connection lines and arrows. 0 == perfectly straight. */
|
|
66
|
+
connectionRoughness: 0,
|
|
67
|
+
/** Roughness for the edge-label chip rectangle. */
|
|
68
|
+
edgeLabelRoughness: 0,
|
|
69
|
+
fillStyle: "solid",
|
|
70
|
+
strokeWidth: 2,
|
|
71
|
+
},
|
|
72
|
+
edgeLabel: {
|
|
73
|
+
/** When true, the chip background uses the connection's stroke colour. */
|
|
74
|
+
useLineColor: true,
|
|
75
|
+
/** Override colour when `useLineColor` is false (or as fallback). */
|
|
76
|
+
backgroundColor: "#444444",
|
|
77
|
+
/** Text colour drawn on top of the chip. */
|
|
78
|
+
textColor: "#ffffff",
|
|
79
|
+
/** Stroke colour for the chip outline. Empty string == match background. */
|
|
80
|
+
strokeColor: "",
|
|
81
|
+
paddingX: 6,
|
|
82
|
+
paddingY: 2,
|
|
83
|
+
/** Hard cap on chip width in px. */
|
|
84
|
+
maxWidth: 160,
|
|
85
|
+
/** Minimum gap to leave around arrowheads at the segment ends. */
|
|
86
|
+
segmentMargin: 24,
|
|
87
|
+
},
|
|
88
|
+
text: {
|
|
89
|
+
/** Auto-shrink long titles/descriptions until they fit. */
|
|
90
|
+
autoShrink: true,
|
|
91
|
+
/** Lower bound for the auto-shrink pass. */
|
|
92
|
+
minFontSize: 8,
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
/** @type {any} */
|
|
97
|
+
let _activeStyle = clone(DEFAULT_STYLE);
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Returns the active style document. Always returns the same live
|
|
101
|
+
* object; callers should not mutate it directly — use `setStyle`.
|
|
102
|
+
*
|
|
103
|
+
* @returns {typeof DEFAULT_STYLE}
|
|
104
|
+
* @public
|
|
105
|
+
*/
|
|
106
|
+
export function getStyle() {
|
|
107
|
+
return _activeStyle;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Replace the active style with a deep-merged copy of the defaults +
|
|
112
|
+
* the supplied partial. Returns the new active style.
|
|
113
|
+
*
|
|
114
|
+
* @param {Record<string, any>} partial Partial style overrides.
|
|
115
|
+
* @returns {typeof DEFAULT_STYLE}
|
|
116
|
+
* @public
|
|
117
|
+
*/
|
|
118
|
+
export function setStyle(partial) {
|
|
119
|
+
_activeStyle = mergeDeep(clone(DEFAULT_STYLE), partial || {});
|
|
120
|
+
return _activeStyle;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Reset to the built-in defaults.
|
|
125
|
+
*
|
|
126
|
+
* @returns {typeof DEFAULT_STYLE}
|
|
127
|
+
* @public
|
|
128
|
+
*/
|
|
129
|
+
export function resetStyle() {
|
|
130
|
+
_activeStyle = clone(DEFAULT_STYLE);
|
|
131
|
+
return _activeStyle;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Load a style document from JSON or YAML on disk and apply it.
|
|
136
|
+
*
|
|
137
|
+
* The file extension decides the parser: `.json`, `.yaml` or `.yml`.
|
|
138
|
+
* Returns the active style after merge. Returns the unchanged active
|
|
139
|
+
* style and emits a console warning when the file is missing or
|
|
140
|
+
* cannot be parsed (so a missing user override never breaks rendering).
|
|
141
|
+
*
|
|
142
|
+
* @param {string} filePath Absolute or workspace-relative path.
|
|
143
|
+
* @returns {typeof DEFAULT_STYLE}
|
|
144
|
+
* @public
|
|
145
|
+
*/
|
|
146
|
+
export function loadStyleFromFile(filePath) {
|
|
147
|
+
if (!filePath || !existsSync(filePath)) {
|
|
148
|
+
return _activeStyle;
|
|
149
|
+
}
|
|
150
|
+
let parsed;
|
|
151
|
+
try {
|
|
152
|
+
const raw = readFileSync(filePath, "utf8");
|
|
153
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
154
|
+
if (ext === ".yaml" || ext === ".yml") parsed = parseSimpleYaml(raw);
|
|
155
|
+
else parsed = JSON.parse(raw);
|
|
156
|
+
} catch (err) {
|
|
157
|
+
// eslint-disable-next-line no-console
|
|
158
|
+
console.warn(`[style] failed to load ${filePath}: ${/** @type {Error} */ (err).message}`);
|
|
159
|
+
return _activeStyle;
|
|
160
|
+
}
|
|
161
|
+
return setStyle(parsed);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Resolve the configured `font.family` to the numeric Excalidraw id
|
|
166
|
+
* required by the JSON document.
|
|
167
|
+
*
|
|
168
|
+
* @param {string|number} family Family name or numeric id.
|
|
169
|
+
* @returns {number}
|
|
170
|
+
* @public
|
|
171
|
+
*/
|
|
172
|
+
export function resolveFontFamilyId(family) {
|
|
173
|
+
if (typeof family === "number" && Number.isFinite(family)) return family;
|
|
174
|
+
if (typeof family === "string") {
|
|
175
|
+
const id = /** @type {Record<string, number>} */ (EXCALIDRAW_FONT_FAMILY)[family];
|
|
176
|
+
if (typeof id === "number") return id;
|
|
177
|
+
}
|
|
178
|
+
return EXCALIDRAW_FONT_FAMILY.Excalifont;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ── helpers ───────────────────────────────────────────────────────────────
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* @param {any} obj
|
|
185
|
+
* @returns {any}
|
|
186
|
+
*/
|
|
187
|
+
function clone(obj) {
|
|
188
|
+
if (obj === null || typeof obj !== "object") return obj;
|
|
189
|
+
if (Array.isArray(obj)) return obj.map(clone);
|
|
190
|
+
const out = /** @type {Record<string, any>} */ ({});
|
|
191
|
+
for (const k of Object.keys(obj)) out[k] = clone(obj[k]);
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* @param {any} target
|
|
197
|
+
* @param {any} source
|
|
198
|
+
* @returns {any}
|
|
199
|
+
*/
|
|
200
|
+
function mergeDeep(target, source) {
|
|
201
|
+
if (source === null || typeof source !== "object" || Array.isArray(source)) return target;
|
|
202
|
+
for (const k of Object.keys(source)) {
|
|
203
|
+
// Defend against prototype pollution: only merge own, non-magic keys.
|
|
204
|
+
if (k === "__proto__" || k === "prototype" || k === "constructor") continue;
|
|
205
|
+
const sv = source[k];
|
|
206
|
+
if (sv && typeof sv === "object" && !Array.isArray(sv)) {
|
|
207
|
+
if (!target[k] || typeof target[k] !== "object") target[k] = {};
|
|
208
|
+
mergeDeep(target[k], sv);
|
|
209
|
+
} else {
|
|
210
|
+
target[k] = sv;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return target;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* @param {any} obj
|
|
218
|
+
* @returns {any}
|
|
219
|
+
*/
|
|
220
|
+
function deepFreeze(obj) {
|
|
221
|
+
if (obj === null || typeof obj !== "object") return obj;
|
|
222
|
+
for (const k of Object.keys(obj)) deepFreeze(obj[k]);
|
|
223
|
+
return Object.freeze(obj);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ── tiny YAML subset ──────────────────────────────────────────────────────
|
|
227
|
+
//
|
|
228
|
+
// Supports:
|
|
229
|
+
// - `# comments` (full-line and end-of-line outside quoted scalars)
|
|
230
|
+
// - `key: value` pairs
|
|
231
|
+
// - Nested mappings via consistent indentation (any width, but the
|
|
232
|
+
// same width across siblings)
|
|
233
|
+
// - Scalar values: numbers, true/false/null, single- or double-quoted
|
|
234
|
+
// strings, or bare strings.
|
|
235
|
+
// Sequences (`- item`) are intentionally not supported — style configs
|
|
236
|
+
// don't need them, and a line-by-line parser keeps the surface tiny
|
|
237
|
+
// and ReDoS-free.
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* @param {string} text
|
|
241
|
+
* @returns {Record<string, any>}
|
|
242
|
+
*/
|
|
243
|
+
export function parseSimpleYaml(text) {
|
|
244
|
+
const lines = String(text).replace(/\r\n?/g, "\n").split("\n");
|
|
245
|
+
const root = /** @type {Record<string, any>} */ ({});
|
|
246
|
+
/** @type {{indent:number,obj:Record<string,any>}[]} */
|
|
247
|
+
const stack = [{ indent: -1, obj: root }];
|
|
248
|
+
|
|
249
|
+
for (let raw of lines) {
|
|
250
|
+
// Strip comments outside quotes.
|
|
251
|
+
raw = stripYamlComment(raw);
|
|
252
|
+
if (!raw.trim()) continue;
|
|
253
|
+
const indent = raw.length - raw.trimStart().length;
|
|
254
|
+
const body = raw.trim();
|
|
255
|
+
const idx = body.indexOf(":");
|
|
256
|
+
if (idx < 0) continue; // sequences not supported, skip
|
|
257
|
+
const key = body.slice(0, idx).trim();
|
|
258
|
+
const value = body.slice(idx + 1).trim();
|
|
259
|
+
if (!isValidYamlKey(key)) continue;
|
|
260
|
+
|
|
261
|
+
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
|
|
262
|
+
const parent = stack[stack.length - 1].obj;
|
|
263
|
+
|
|
264
|
+
if (value === "") {
|
|
265
|
+
const child = /** @type {Record<string, any>} */ ({});
|
|
266
|
+
parent[key] = child;
|
|
267
|
+
stack.push({ indent, obj: child });
|
|
268
|
+
} else {
|
|
269
|
+
parent[key] = parseYamlScalar(value);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return root;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* @param {string} line
|
|
277
|
+
* @returns {string}
|
|
278
|
+
*/
|
|
279
|
+
function stripYamlComment(line) {
|
|
280
|
+
let out = "";
|
|
281
|
+
let inSingle = false;
|
|
282
|
+
let inDouble = false;
|
|
283
|
+
for (let i = 0; i < line.length; i++) {
|
|
284
|
+
const c = line[i];
|
|
285
|
+
if (c === "'" && !inDouble) inSingle = !inSingle;
|
|
286
|
+
else if (c === '"' && !inSingle) inDouble = !inDouble;
|
|
287
|
+
else if (c === "#" && !inSingle && !inDouble) break;
|
|
288
|
+
out += c;
|
|
289
|
+
}
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* @param {string} k
|
|
295
|
+
* @returns {boolean}
|
|
296
|
+
*/
|
|
297
|
+
function isValidYamlKey(k) {
|
|
298
|
+
if (!k) return false;
|
|
299
|
+
if (k === "__proto__" || k === "prototype" || k === "constructor") return false;
|
|
300
|
+
return /^[A-Za-z_][A-Za-z0-9_-]*$/.test(k);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* @param {string} raw
|
|
305
|
+
* @returns {any}
|
|
306
|
+
*/
|
|
307
|
+
function parseYamlScalar(raw) {
|
|
308
|
+
if (raw === "null" || raw === "~") return null;
|
|
309
|
+
if (raw === "true") return true;
|
|
310
|
+
if (raw === "false") return false;
|
|
311
|
+
if (/^-?\d+(?:\.\d+)?$/.test(raw)) return Number(raw);
|
|
312
|
+
if ((raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'"))) {
|
|
313
|
+
return raw.slice(1, -1);
|
|
314
|
+
}
|
|
315
|
+
return raw;
|
|
316
|
+
}
|
package/src/style/text.mjs
CHANGED
|
@@ -7,47 +7,42 @@
|
|
|
7
7
|
// glyph ratio empirically tuned for Excalifont. The exporter writes
|
|
8
8
|
// the same `fontSize` Excalidraw will use, so visible labels stay
|
|
9
9
|
// inside the boxes computed here.
|
|
10
|
+
//
|
|
11
|
+
// Font sizes are sourced from the live style document
|
|
12
|
+
// (`src/style/style.mjs`), so loading a custom style.json / style.yaml
|
|
13
|
+
// changes wrapping, sizing, and rendering in one place.
|
|
10
14
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
* numeric ids end up verbatim inside the exported `.excalidraw`
|
|
15
|
-
* documents and decide which bundled font Excalidraw will display
|
|
16
|
-
* when the file is opened.
|
|
17
|
-
*
|
|
18
|
-
* @public
|
|
19
|
-
*/
|
|
20
|
-
export const EXCALIDRAW_FONT_FAMILY = Object.freeze({
|
|
21
|
-
Virgil: 1,
|
|
22
|
-
Helvetica: 2,
|
|
23
|
-
Cascadia: 3,
|
|
24
|
-
LocalFont: 4,
|
|
25
|
-
Excalifont: 5,
|
|
26
|
-
Nunito: 6,
|
|
27
|
-
LilitaOne: 7,
|
|
28
|
-
ComicShanns: 8,
|
|
29
|
-
LiberationSans: 9,
|
|
30
|
-
});
|
|
15
|
+
import { EXCALIDRAW_FONT_FAMILY, getStyle, resolveFontFamilyId } from "./style.mjs";
|
|
16
|
+
|
|
17
|
+
export { EXCALIDRAW_FONT_FAMILY };
|
|
31
18
|
|
|
32
19
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* exports and re-opening the JSON in Excalidraw all show the same
|
|
38
|
-
* glyphs).
|
|
20
|
+
* Live view of the active font configuration. Reading e.g.
|
|
21
|
+
* `FONT.sizeTitle` always returns the current value from the active
|
|
22
|
+
* style; `FONT.family` returns the resolved Excalidraw numeric id.
|
|
23
|
+
*
|
|
39
24
|
* @public
|
|
25
|
+
* @type {any}
|
|
40
26
|
*/
|
|
41
|
-
export const FONT =
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
};
|
|
27
|
+
export const FONT = new Proxy(
|
|
28
|
+
{},
|
|
29
|
+
{
|
|
30
|
+
get(_t, key) {
|
|
31
|
+
const f = /** @type {any} */ (getStyle()).font;
|
|
32
|
+
if (key === "family") return resolveFontFamilyId(f.family);
|
|
33
|
+
return /** @type {any} */ (f)[key];
|
|
34
|
+
},
|
|
35
|
+
has(_t, key) {
|
|
36
|
+
return key === "family" || key in /** @type {any} */ (getStyle()).font;
|
|
37
|
+
},
|
|
38
|
+
ownKeys() {
|
|
39
|
+
return Object.keys(/** @type {any} */ (getStyle()).font);
|
|
40
|
+
},
|
|
41
|
+
getOwnPropertyDescriptor() {
|
|
42
|
+
return { enumerable: true, configurable: true };
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
);
|
|
51
46
|
|
|
52
47
|
/**
|
|
53
48
|
* Measure a single-line label.
|
|
@@ -102,3 +97,43 @@ export function measureWrapped(text, fontSize, maxWidth) {
|
|
|
102
97
|
lines,
|
|
103
98
|
};
|
|
104
99
|
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Word-wrap `text` and shrink the font size when a single token would
|
|
103
|
+
* still exceed `maxWidth` at the requested size. Returns the chosen
|
|
104
|
+
* font size alongside the wrapped lines so the renderer can emit the
|
|
105
|
+
* same size the sizing pass measured.
|
|
106
|
+
*
|
|
107
|
+
* Auto-shrink is governed by the active style: when `text.autoShrink`
|
|
108
|
+
* is `false` the function falls back to the regular `measureWrapped`
|
|
109
|
+
* result without shrinking.
|
|
110
|
+
*
|
|
111
|
+
* @param {string} text
|
|
112
|
+
* @param {number} fontSize
|
|
113
|
+
* @param {number} maxWidth
|
|
114
|
+
* @param {object} [opts]
|
|
115
|
+
* @param {number} [opts.minFontSize] Lower bound; defaults to the active style.
|
|
116
|
+
* @returns {{ fontSize:number, width:number, height:number, lines:string[] }}
|
|
117
|
+
* @public
|
|
118
|
+
*/
|
|
119
|
+
export function measureFitted(text, fontSize, maxWidth, opts = {}) {
|
|
120
|
+
const style = /** @type {any} */ (getStyle());
|
|
121
|
+
const enabled = style.text?.autoShrink !== false;
|
|
122
|
+
const minSize = Math.max(
|
|
123
|
+
1,
|
|
124
|
+
opts.minFontSize ?? style.text?.minFontSize ?? style.font?.minSize ?? 8,
|
|
125
|
+
);
|
|
126
|
+
let fs = fontSize;
|
|
127
|
+
let wrapped = measureWrapped(text, fs, maxWidth);
|
|
128
|
+
if (!enabled || !text) return { fontSize: fs, ...wrapped };
|
|
129
|
+
// `measureWrapped` clamps its reported width to `maxWidth`. To
|
|
130
|
+
// detect a single token that still overflows we re-measure the raw
|
|
131
|
+
// line widths and compare them against `maxWidth`.
|
|
132
|
+
const rawMaxLineWidth = (/** @type {string[]} */ lines, /** @type {number} */ sz) =>
|
|
133
|
+
Math.max(0, ...lines.map((/** @type {string} */ l) => l.length * sz * FONT.glyphRatio));
|
|
134
|
+
while (fs > minSize && rawMaxLineWidth(wrapped.lines, fs) > maxWidth + 0.5) {
|
|
135
|
+
fs -= 1;
|
|
136
|
+
wrapped = measureWrapped(text, fs, maxWidth);
|
|
137
|
+
}
|
|
138
|
+
return { fontSize: fs, ...wrapped };
|
|
139
|
+
}
|