cornfield 0.46.1 → 0.46.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/explorer/capped.js +3 -2
- package/explorer/engine/feedback.js +49 -0
- package/explorer/engine/flow-ui.js +39 -0
- package/explorer/engine/fly.js +54 -0
- package/explorer/engine/hint.js +97 -0
- package/explorer/engine/keyboard.js +156 -0
- package/explorer/engine/layers.js +280 -0
- package/explorer/engine/layout.js +378 -0
- package/explorer/engine/map-style.js +547 -0
- package/explorer/engine/piece.js +142 -0
- package/explorer/engine/render.js +331 -0
- package/explorer/engine/search-status.js +59 -0
- package/explorer/engine/selection.js +42 -0
- package/explorer/engine/sheets.js +417 -0
- package/explorer/engine/strings.js +63 -0
- package/explorer/feedback.js +11 -45
- package/explorer/flow-style.js +28 -0
- package/explorer/flows.js +10 -51
- package/explorer/fly.js +11 -43
- package/explorer/hint.js +15 -88
- package/explorer/index.html +38 -75
- package/explorer/input.js +190 -177
- package/explorer/instance-state.js +172 -0
- package/explorer/instance.js +267 -0
- package/explorer/keyboard.js +14 -206
- package/explorer/labels.js +3 -3
- package/explorer/layers.js +34 -445
- package/explorer/layout.js +14 -372
- package/explorer/main.js +4 -226
- package/explorer/map-style.js +27 -525
- package/explorer/mockups-model.js +3 -3
- package/explorer/page-pieces.js +61 -0
- package/explorer/page.js +232 -0
- package/explorer/panels.js +29 -409
- package/explorer/pieces/layers.js +325 -0
- package/explorer/pieces/node-panel.js +536 -0
- package/explorer/pieces/search.js +454 -0
- package/explorer/proposal-model.js +1 -1
- package/explorer/proposal.js +1 -0
- package/explorer/render.js +37 -267
- package/explorer/renderer-canvas2d.js +4 -4
- package/explorer/renderer-webgl.js +21 -8
- package/explorer/renderer.js +11 -9
- package/explorer/scene.js +3 -2
- package/explorer/search-status.js +8 -47
- package/explorer/search.js +26 -324
- package/explorer/selection-view.js +17 -19
- package/explorer/sheets.js +31 -379
- package/explorer/state.js +38 -173
- package/explorer/strings.js +17 -60
- package/explorer/view.js +4 -5
- package/package.json +1 -1
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module explorer/engine/map-style
|
|
3
|
+
*
|
|
4
|
+
* The map's styling from the theme (docs/theming.md, "The map"). The map canvas reads its colours from `--corn-map-*` custom
|
|
5
|
+
* properties (tokens.css) on load and again whenever the theme changes, then draws again:
|
|
6
|
+
*
|
|
7
|
+
* --corn-map-node-<kind> a node kind's fill (kind: a node type, `app`, `page`, `table` ...)
|
|
8
|
+
* --corn-map-group-<group> the same by group, the node's layer in the Layers menu (`cloud`, `web`, `house`, `app` ...)
|
|
9
|
+
* --corn-map-stroke, --corn-map-stroke-width every node's outline: its colour (none at `auto`) and its width, in world px
|
|
10
|
+
* --corn-map-label, --corn-map-label-halo a node label's colour, and the outline under every label that keeps it readable over the lines
|
|
11
|
+
* --corn-map-edge-<kind> an edge kind's colour (`ownership`, `usage`, `flow`, `reads`, `writes`, `calls` ...)
|
|
12
|
+
* --corn-map-added|changed|removed|edit the diff: a proposal's marks on nodes and edges
|
|
13
|
+
* --corn-map-selected|match the halo of the selected node, and of a search hit
|
|
14
|
+
* --corn-map-lit the lines of the focus: the links the selection (or a walk's step) lights
|
|
15
|
+
* --corn-map-collision the collision mark of two runs on one node (a DOM mark: explorer.css reads it)
|
|
16
|
+
* --corn-map-font the font list of every label on the map (a list of families, `auto` for the map's own)
|
|
17
|
+
* --corn-map-edge-width the width of an ordinary line, in map px (`auto` keeps each line's own; the focus's and the marks' keep their proportion)
|
|
18
|
+
* --corn-map-label-min the smallest a label is drawn on screen, in px (11 by default; below 9px it is ignored; a hub's title is 2 more)
|
|
19
|
+
* --corn-map-grey what a review greys (the nodes and lines a proposal does not involve) is drawn in: a colour, or `auto` for each one's own tone with its hue taken away
|
|
20
|
+
* --corn-map-grey-alpha how much of a greyed node is left: a number from 0.1 to 1 (`auto` is 0.45); its lines are faded in the same proportion
|
|
21
|
+
* --corn-map-glow the soft glow round nodes, lines and packets: a factor (`0` none, `1` as drawn, `auto` as drawn)
|
|
22
|
+
*
|
|
23
|
+
* `auto` (the default of every one of them but the width and the collision) means "keep what the map draws without a theme": the
|
|
24
|
+
* node's own colour from the topology, deepened for the light ground by theme-model.js, and every other colour as scene.js has
|
|
25
|
+
* it. So with no theme the map is exactly what it was. A colour overrides it as written, in both themes (a theme sets its own
|
|
26
|
+
* for the light ground under :root[data-theme="light"]). A kind's token wins over its group's.
|
|
27
|
+
*
|
|
28
|
+
* How it reaches the pixels. scene.js stays pure: it describes the picture with the colours it always had. A renderer (and the label
|
|
29
|
+
* layer) asks `styledScene(scene, style)` for the same picture in the theme's colours, and `looksWith(looks, style)` for the halos and
|
|
30
|
+
* the mark rings; the style is the instance's (`mapStyleOf(inst).get()`), which `refresh()` reads from the computed style at the instance's root. With nothing set,
|
|
31
|
+
* `styledScene` hands the scene back untouched. A node or an edge a painter gave a colour (an outage, a check's verdict, a pull
|
|
32
|
+
* request: `scene.painted`) keeps it: those colours mean something.
|
|
33
|
+
*
|
|
34
|
+
* Icons (`theme.icons`) are loaded here, one image per node kind (`createIconStore`); a kind whose file is missing or will not load
|
|
35
|
+
* simply has no icon. `pixelated` (`theme.pixelated`) is the renderers' cue to sample without smoothing.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { NODE_THEMES } from '../../core/schema.js';
|
|
39
|
+
import { parseColor } from '../theme-model.js';
|
|
40
|
+
import { cssColor, rgbaText } from '../css-color.js';
|
|
41
|
+
export { cssColor };
|
|
42
|
+
import { GREY_ALPHA, LABEL_MIN_FLOOR, looksFor } from '../scene.js';
|
|
43
|
+
import { iconKeyShape, iconKeysFor, mapFillNames, mapGroupToken, mapKindToken } from '../../core/layers.js';
|
|
44
|
+
|
|
45
|
+
/** The node kinds (topology types) and the groups (layers a node can belong to) the tokens exist for */
|
|
46
|
+
export const MAP_KINDS = Object.freeze(Object.keys(NODE_THEMES));
|
|
47
|
+
export const MAP_GROUPS = Object.freeze(['app', 'pkg', 'page', 'atom', 'molecule', 'token', 'tool', 'table', 'rom', 'service', 'cloud', 'web', 'stack', 'machine', 'container', 'device', 'house', 'persona']);
|
|
48
|
+
/** The kinds of edge scene.js draws */
|
|
49
|
+
export const MAP_EDGE_KINDS = Object.freeze(['ownership', 'usage', 'flow', 'reads', 'writes', 'calls', 'triggers', 'delivers', 'runs-on', 'uses', 'extends']);
|
|
50
|
+
/** The diff marks, and the other states the map colours */
|
|
51
|
+
export const MAP_MARKS = Object.freeze(['added', 'changed', 'removed', 'edit']);
|
|
52
|
+
export const MAP_STATES = Object.freeze(['selected', 'match', 'lit']);
|
|
53
|
+
export const STROKE_TOKEN = '--corn-map-stroke';
|
|
54
|
+
export const STROKE_WIDTH_TOKEN = '--corn-map-stroke-width';
|
|
55
|
+
export const LABEL_TOKEN = '--corn-map-label';
|
|
56
|
+
export const LABEL_HALO_TOKEN = '--corn-map-label-halo';
|
|
57
|
+
export const COLLISION_TOKEN = '--corn-map-collision';
|
|
58
|
+
export const FONT_TOKEN = '--corn-map-font';
|
|
59
|
+
export const EDGE_WIDTH_TOKEN = '--corn-map-edge-width';
|
|
60
|
+
export const GLOW_TOKEN = '--corn-map-glow';
|
|
61
|
+
export const LABEL_MIN_TOKEN = '--corn-map-label-min';
|
|
62
|
+
export const GREY_TOKEN = '--corn-map-grey';
|
|
63
|
+
export const GREY_ALPHA_TOKEN = '--corn-map-grey-alpha';
|
|
64
|
+
/** The least a greyed node may be left at: under it the map would vanish (a value below is read as `auto`) */
|
|
65
|
+
export const MIN_GREY_ALPHA = 0.1;
|
|
66
|
+
/** The ink of a node's glyph and of a finer kind's letters (spec 0008 D8); `auto` is the white or the dark that reads on the node's fill (glyphs.js) */
|
|
67
|
+
export const GLYPH_TOKEN = '--corn-map-glyph';
|
|
68
|
+
/** The largest label minimum a theme may ask for: bigger text would leave no room for another label */
|
|
69
|
+
export const MAX_LABEL_MIN = 24;
|
|
70
|
+
/** The width an ordinary line has with no theme (scene.js `flowEdge`): the `--corn-map-edge-width` scales every line by its ratio to this */
|
|
71
|
+
export const BASE_EDGE_WIDTH = 1.6;
|
|
72
|
+
/** The most a font list may hold: the families, and the characters */
|
|
73
|
+
export const MAX_FONT_FAMILIES = 8;
|
|
74
|
+
export const MAX_FONT_CHARS = 200;
|
|
75
|
+
/** The widest a line may be set, and the largest glow factor: a typo cannot draw a map of paint */
|
|
76
|
+
export const MAX_EDGE_WIDTH = 12;
|
|
77
|
+
export const MAX_GLOW = 4;
|
|
78
|
+
/** The width of an outline when the token is not a length (px, world units) */
|
|
79
|
+
export const DEFAULT_STROKE_WIDTH = 1.5;
|
|
80
|
+
/** An icon is drawn this many radii across (a square, so it fits inside the circle) */
|
|
81
|
+
export const ICON_RATIO = 1.2;
|
|
82
|
+
/** Where the server serves the images beside a theme (core/theme.js THEME_ASSET_PREFIX); an icon is fetched from nowhere else */
|
|
83
|
+
export const ICON_URL_PREFIX = '/cornfield/theme/assets/';
|
|
84
|
+
|
|
85
|
+
export const nodeToken = (kind) => `--corn-map-node-${kind}`;
|
|
86
|
+
export const groupToken = (group) => `--corn-map-group-${group}`;
|
|
87
|
+
/** The fill token of a finer kind: `--corn-map-kind-service-timer`, or null for a kind that cannot be a part of a name (core/layers.js) */
|
|
88
|
+
export const kindToken = (type, kind) => mapKindToken(type, kind);
|
|
89
|
+
export const edgeToken = (kind) => `--corn-map-edge-${kind}`;
|
|
90
|
+
export const stateToken = (name) => `--corn-map-${name}`;
|
|
91
|
+
|
|
92
|
+
/** The colour tokens script reads: all of them but the width and the collision mark (which CSS reads) */
|
|
93
|
+
export const MAP_COLOR_TOKENS = Object.freeze([
|
|
94
|
+
...MAP_KINDS.map(nodeToken),
|
|
95
|
+
...MAP_GROUPS.map(groupToken),
|
|
96
|
+
STROKE_TOKEN,
|
|
97
|
+
LABEL_TOKEN,
|
|
98
|
+
LABEL_HALO_TOKEN,
|
|
99
|
+
GLYPH_TOKEN,
|
|
100
|
+
GREY_TOKEN,
|
|
101
|
+
...MAP_EDGE_KINDS.map(edgeToken),
|
|
102
|
+
...MAP_MARKS.map(stateToken),
|
|
103
|
+
...MAP_STATES.map(stateToken),
|
|
104
|
+
]);
|
|
105
|
+
/** Every map token */
|
|
106
|
+
export const mapTokenNames = () => [...MAP_COLOR_TOKENS, STROKE_WIDTH_TOKEN, COLLISION_TOKEN, FONT_TOKEN, EDGE_WIDTH_TOKEN, GLOW_TOKEN, LABEL_MIN_TOKEN, GREY_ALPHA_TOKEN];
|
|
107
|
+
|
|
108
|
+
// ---------------------------------------------------------------------------
|
|
109
|
+
// Reading a token
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
/** `token` as the colour of something that was `original`: the token's colour, with the original's own alpha kept (a faint line stays faint) */
|
|
113
|
+
export function withAlphaOf(token, original) {
|
|
114
|
+
const [r, g, b, a] = parseColor(token);
|
|
115
|
+
const oa = parseColor(original)[3];
|
|
116
|
+
if (oa >= 1) return token;
|
|
117
|
+
return rgbaText(r, g, b, a * oa);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const GENERIC_FAMILY = /^(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|ui-serif|ui-sans-serif|ui-monospace|ui-rounded|emoji|math|fangsong)$/i;
|
|
121
|
+
const SYSTEM_FONT_KEYWORD = /^(?:-apple-system|BlinkMacSystemFont)$/;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A font list the canvas may be given, or null (`auto`, empty, or anything that is not a plain list of families). Each family is a name in
|
|
125
|
+
* quotes, or bare words (`Nunito`, `ui-rounded`, `sans-serif`); nothing that can carry a URL or script (no parentheses, slashes, colons,
|
|
126
|
+
* semicolons, braces, angle brackets, `@`, backslashes, `url`, `var`, `expression`) and no more than MAX_FONT_FAMILIES of them.
|
|
127
|
+
* Returned with each name quoted, so a name with a space is one family.
|
|
128
|
+
* @param {unknown} value
|
|
129
|
+
* @returns {string | null}
|
|
130
|
+
*/
|
|
131
|
+
export function cssFontList(value) {
|
|
132
|
+
const s = typeof value === 'string' ? value.trim() : '';
|
|
133
|
+
if (!s || s.length > MAX_FONT_CHARS || s.toLowerCase() === 'auto') return null;
|
|
134
|
+
if (/[();:{}<>@\\/\u0000-\u001f\u007f]|\burl\b|\bvar\b|\bexpression\b|\bimport\b/i.test(s)) return null;
|
|
135
|
+
const parts = s.split(',').map((p) => p.trim());
|
|
136
|
+
if (parts.length > MAX_FONT_FAMILIES) return null;
|
|
137
|
+
const out = [];
|
|
138
|
+
for (const part of parts) {
|
|
139
|
+
const quoted = /^"([A-Za-z0-9 ._+-]{1,60})"$|^'([A-Za-z0-9 ._+-]{1,60})'$/.exec(part);
|
|
140
|
+
// A bare name may start with one hyphen (`-apple-system`, in cornfield's own --corn-font), never two (a custom property's name)
|
|
141
|
+
const name = quoted ? (quoted[1] ?? quoted[2]).trim() : /^-?[A-Za-z][A-Za-z0-9 _-]{0,59}$/.test(part) ? part.replace(/\s+/g, ' ') : null;
|
|
142
|
+
if (!name) return null;
|
|
143
|
+
// Generic families and the two system-font keywords stay bare (quoted, they would name a font called that); every other name is quoted
|
|
144
|
+
out.push(GENERIC_FAMILY.test(name) ? name.toLowerCase() : SYSTEM_FONT_KEYWORD.test(name) ? name : `"${name}"`);
|
|
145
|
+
}
|
|
146
|
+
return out.join(', ');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A length in px (`2px`, `2`) over 0 and at most max, or null for `auto` and anything else (a canvas ignores a line width of 0) */
|
|
150
|
+
function pxOf(value, max) {
|
|
151
|
+
const m = /^\s*(\d*\.?\d+)(?:px)?\s*$/i.exec(String(value ?? ''));
|
|
152
|
+
const n = m ? parseFloat(m[1]) : NaN;
|
|
153
|
+
return Number.isFinite(n) && n > 0 && n <= max ? n : null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The label minimum: a length in px from LABEL_MIN_FLOOR to MAX_LABEL_MIN, or null for `auto` and anything else (under the floor is ignored, so a theme cannot make labels unreadable) */
|
|
157
|
+
function labelMinOf(value) {
|
|
158
|
+
const n = pxOf(value, MAX_LABEL_MIN);
|
|
159
|
+
return n !== null && n >= LABEL_MIN_FLOOR ? n : null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The glow factor: a number (`0` for none, `1` as drawn, up to MAX_GLOW; `0px` reads as 0), or null for `auto` and anything else */
|
|
163
|
+
function factorOf(value) {
|
|
164
|
+
const m = /^\s*(\d*\.?\d+)(px)?\s*$/i.exec(String(value ?? ''));
|
|
165
|
+
if (!m) return null;
|
|
166
|
+
const n = parseFloat(m[1]);
|
|
167
|
+
if (m[2] && n !== 0) return null; // a length is not a factor, only zero is the same in both
|
|
168
|
+
return Number.isFinite(n) && n >= 0 && n <= MAX_GLOW ? n : null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The greyed node's opacity: a number from MIN_GREY_ALPHA to 1, or null for `auto` and anything else */
|
|
172
|
+
function greyAlphaOf(value) {
|
|
173
|
+
const m = /^\s*(\d*\.?\d+)\s*$/.exec(String(value ?? ''));
|
|
174
|
+
const n = m ? parseFloat(m[1]) : NaN;
|
|
175
|
+
return Number.isFinite(n) && n >= MIN_GREY_ALPHA && n <= 1 ? n : null;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The tokens as the page computes them.
|
|
180
|
+
* @param {(name: string) => string} read the value of a custom property
|
|
181
|
+
* @param {string[]} [extra] more colour tokens to read: those of the finer kinds and project layers on the map (`setMapSubjects`)
|
|
182
|
+
* @returns {{values: Record<string, string>, strokeWidth: number, font: string | null, edgeWidth: number | null, glow: number | null, labelMin: number | null, greyAlpha: number | null}}
|
|
183
|
+
* `values` holds only the tokens that are a colour (not `auto`); `font`, `edgeWidth`, `glow`, `labelMin` and `greyAlpha` are null at `auto` or when the value is not one
|
|
184
|
+
*/
|
|
185
|
+
export function readMapTokens(read, extra = []) {
|
|
186
|
+
const values = {};
|
|
187
|
+
for (const name of [...MAP_COLOR_TOKENS, ...extra]) {
|
|
188
|
+
const c = cssColor(read(name));
|
|
189
|
+
if (c) values[name] = c;
|
|
190
|
+
}
|
|
191
|
+
const w = parseFloat(String(read(STROKE_WIDTH_TOKEN) ?? ''));
|
|
192
|
+
return {
|
|
193
|
+
values,
|
|
194
|
+
strokeWidth: Number.isFinite(w) && w >= 0 ? w : DEFAULT_STROKE_WIDTH,
|
|
195
|
+
font: cssFontList(read(FONT_TOKEN)),
|
|
196
|
+
edgeWidth: pxOf(read(EDGE_WIDTH_TOKEN), MAX_EDGE_WIDTH),
|
|
197
|
+
glow: factorOf(read(GLOW_TOKEN)),
|
|
198
|
+
labelMin: labelMinOf(read(LABEL_MIN_TOKEN)),
|
|
199
|
+
greyAlpha: greyAlphaOf(read(GREY_ALPHA_TOKEN)),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ---------------------------------------------------------------------------
|
|
204
|
+
// Icons
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
|
|
207
|
+
function loadImage(url) {
|
|
208
|
+
return new Promise((resolve, reject) => {
|
|
209
|
+
if (typeof Image === 'undefined') { reject(new Error('no Image')); return; }
|
|
210
|
+
const img = new Image();
|
|
211
|
+
img.onload = () => (img.naturalWidth > 0 && img.naturalHeight > 0 ? resolve(img) : reject(new Error(`${url} has no size`)));
|
|
212
|
+
img.onerror = () => reject(new Error(`${url} did not load`));
|
|
213
|
+
img.src = url;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* One image per node kind, loaded once. `get(kind)` is the image when it has loaded, else null: a kind with no icon, one still loading, and
|
|
219
|
+
* one whose file is missing or is not an image are the same to the map (no icon), and one failure never touches another.
|
|
220
|
+
* @param {Record<string, string>} urls kind to served path (only paths under ICON_URL_PREFIX, for a kind that is a node kind)
|
|
221
|
+
* @param {{load?: (url: string) => Promise<unknown>, onChange?: () => void, warn?: (message: string) => void}} [opts]
|
|
222
|
+
*/
|
|
223
|
+
export function createIconStore(urls, { load = loadImage, onChange = () => {}, warn = (m) => console.warn(m) } = {}) {
|
|
224
|
+
const entries = new Map();
|
|
225
|
+
let ready = 0;
|
|
226
|
+
for (const [kind, url] of Object.entries(urls || {})) {
|
|
227
|
+
if (!iconKeyShape(kind) || typeof url !== 'string' || !url.startsWith(ICON_URL_PREFIX) || url.includes('..')) continue;
|
|
228
|
+
const entry = { status: 'loading', image: null };
|
|
229
|
+
entries.set(kind, entry);
|
|
230
|
+
Promise.resolve().then(() => load(url)).then((image) => {
|
|
231
|
+
entry.status = 'ready';
|
|
232
|
+
entry.image = image;
|
|
233
|
+
ready++;
|
|
234
|
+
onChange();
|
|
235
|
+
}, (err) => {
|
|
236
|
+
entry.status = 'failed';
|
|
237
|
+
warn(`Map icon for "${kind}" not drawn: ${err && err.message ? err.message : err}`);
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
kinds: [...entries.keys()],
|
|
242
|
+
get: (kind) => { const e = entries.get(kind); return e && e.status === 'ready' ? e.image : null; },
|
|
243
|
+
status: (kind) => (entries.has(kind) ? entries.get(kind).status : 'none'),
|
|
244
|
+
anyReady: () => ready > 0,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ---------------------------------------------------------------------------
|
|
249
|
+
// The style in force
|
|
250
|
+
// ---------------------------------------------------------------------------
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* @typedef {object} MapStyle
|
|
254
|
+
* @property {number} version changes whenever anything below does: a renderer draws again when it differs from the one it drew
|
|
255
|
+
* @property {Record<string, string>} values the tokens that are a colour, by name (those at `auto` are absent)
|
|
256
|
+
* @property {number} strokeWidth px, world units
|
|
257
|
+
* @property {string | null} font the label font list (`--corn-map-font`), null at `auto`
|
|
258
|
+
* @property {number | null} edgeWidth an ordinary line's width in px (`--corn-map-edge-width`), null at `auto`
|
|
259
|
+
* @property {number | null} glow the glow factor (`--corn-map-glow`), null at `auto`
|
|
260
|
+
* @property {number | null} labelMin the smallest label size in px (`--corn-map-label-min`), null at `auto` or under 9px
|
|
261
|
+
* @property {number | null} greyAlpha how much of a greyed node is left (`--corn-map-grey-alpha`), null at `auto` or when it is not a number from 0.1 to 1
|
|
262
|
+
* @property {ReturnType<typeof createIconStore> | null} icons
|
|
263
|
+
* @property {boolean} pixelated sample icons without smoothing
|
|
264
|
+
* @property {boolean} plain nothing to apply: no colour set, no icon loaded (the scene is drawn as it is)
|
|
265
|
+
*/
|
|
266
|
+
|
|
267
|
+
const NO_TOKENS = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH, font: null, edgeWidth: null, glow: null, labelMin: null, greyAlpha: null };
|
|
268
|
+
/** The style with nothing set: what a renderer or a label layer made without an instance draws with (the scene as it is) */
|
|
269
|
+
export const PLAIN_STYLE = Object.freeze({ version: 0, values: Object.freeze({}), strokeWidth: DEFAULT_STROKE_WIDTH, font: null, edgeWidth: null, glow: null, labelMin: null, greyAlpha: null, icons: null, pixelated: false, plain: true });
|
|
270
|
+
const MAX_SUBJECT_TOKENS = 500;
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The map style of one instance: the tokens read from its root, the icons, and who is told when either changes. One per instance
|
|
274
|
+
* (`mapStyleOf(inst)`), so two maps on a page each read their own root's tokens and draw their own.
|
|
275
|
+
* @param {ReturnType<typeof import('../instance.js').createInstance>} inst
|
|
276
|
+
*/
|
|
277
|
+
export function createMapStyle(inst) {
|
|
278
|
+
let tokens = NO_TOKENS;
|
|
279
|
+
let icons = null;
|
|
280
|
+
let pixelated = false;
|
|
281
|
+
let version = 0;
|
|
282
|
+
/** The tokens of the finer kinds and project layers on the map, read besides the fixed list (their names come from the map and the config, through core/layers.js, which refuses a name that is not a plain one) */
|
|
283
|
+
let subjectTokens = [];
|
|
284
|
+
const listeners = new Set();
|
|
285
|
+
|
|
286
|
+
const compose = () => {
|
|
287
|
+
const plain = !Object.keys(tokens.values).length && !(icons && icons.anyReady()) && tokens.font === null && tokens.edgeWidth === null && tokens.glow === null && tokens.labelMin === null && tokens.greyAlpha === null;
|
|
288
|
+
return Object.freeze({ version, values: tokens.values, strokeWidth: tokens.strokeWidth, font: tokens.font, edgeWidth: tokens.edgeWidth, glow: tokens.glow, labelMin: tokens.labelMin, greyAlpha: tokens.greyAlpha, icons, pixelated, plain });
|
|
289
|
+
};
|
|
290
|
+
let current = compose();
|
|
291
|
+
|
|
292
|
+
let ended = false;
|
|
293
|
+
inst.own(() => { ended = true; listeners.clear(); }); // the instance's end: an icon that arrives later tells nobody
|
|
294
|
+
|
|
295
|
+
const changed = () => {
|
|
296
|
+
if (ended) return;
|
|
297
|
+
version++;
|
|
298
|
+
current = compose();
|
|
299
|
+
listeners.forEach((fn) => fn(current));
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
const store = {
|
|
303
|
+
/** @returns {MapStyle} */
|
|
304
|
+
get: () => current,
|
|
305
|
+
|
|
306
|
+
/** Calls `fn(style)` when the style changes (a token, an icon arriving); returns how to stop */
|
|
307
|
+
onChange(fn) {
|
|
308
|
+
listeners.add(fn);
|
|
309
|
+
return () => listeners.delete(fn);
|
|
310
|
+
},
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Tells the style which finer kinds (`[type, kind]`) and project layers (keys) are on the map, so the tokens that colour them
|
|
314
|
+
* (`--corn-map-kind-<type>-<kind>`, `--corn-map-group-<key>`) are read. True when the set changed and a token differed.
|
|
315
|
+
* @param {{kinds?: [string, string][], layers?: string[]}} [subjects]
|
|
316
|
+
*/
|
|
317
|
+
setSubjects({ kinds = [], layers = [] } = {}) {
|
|
318
|
+
const names = [...new Set([...kinds.map(([t, k]) => mapKindToken(t, k)), ...layers.map((l) => mapGroupToken(l))].filter(Boolean))].sort().slice(0, MAX_SUBJECT_TOKENS);
|
|
319
|
+
if (names.length === subjectTokens.length && names.every((n, i) => n === subjectTokens[i])) return false;
|
|
320
|
+
subjectTokens = names;
|
|
321
|
+
return store.refresh();
|
|
322
|
+
},
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Reads the tokens again; true when something differed (and the listeners were told). Run on load and whenever the theme changes.
|
|
326
|
+
* @param {(name: string) => string} [read] default: the computed style at the instance's root
|
|
327
|
+
*/
|
|
328
|
+
refresh(read = inst.tokenReader()) {
|
|
329
|
+
if (!read) return false;
|
|
330
|
+
const next = readMapTokens(read, subjectTokens);
|
|
331
|
+
const same = next.strokeWidth === tokens.strokeWidth && next.font === tokens.font && next.edgeWidth === tokens.edgeWidth && next.glow === tokens.glow && next.labelMin === tokens.labelMin
|
|
332
|
+
&& Object.keys(next.values).length === Object.keys(tokens.values).length
|
|
333
|
+
&& Object.entries(next.values).every(([k, v]) => tokens.values[k] === v);
|
|
334
|
+
if (same) return false;
|
|
335
|
+
tokens = next;
|
|
336
|
+
changed();
|
|
337
|
+
// A web font the labels name is fetched when something asks for it, and a canvas does not wait for one: ask now, and draw again when it is in
|
|
338
|
+
try { const fonts = inst.doc && inst.doc.fonts; if (next.font && fonts && fonts.load) fonts.load(`12px ${next.font}`).catch(() => {}); } catch { /* no font loading here */ }
|
|
339
|
+
return true;
|
|
340
|
+
},
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Starts loading the config's icons (`theme.icons`, as the browser is told them: kind to served path) and sets the pixelated flag.
|
|
344
|
+
* The images are fetched from the instance's base.
|
|
345
|
+
* @param {{icons?: Record<string, string>, pixelated?: boolean} | null | undefined} theme
|
|
346
|
+
* @param {Parameters<typeof createIconStore>[1]} [opts]
|
|
347
|
+
*/
|
|
348
|
+
setIcons(theme, opts = {}) {
|
|
349
|
+
const urls = theme && theme.icons && typeof theme.icons === 'object' ? theme.icons : {};
|
|
350
|
+
pixelated = !!(theme && theme.pixelated === true);
|
|
351
|
+
const load = opts.load || ((url) => loadImage(inst.url(url)));
|
|
352
|
+
icons = Object.keys(urls).length ? createIconStore(urls, { ...opts, load, onChange: () => { changed(); if (opts.onChange) opts.onChange(); } }) : null;
|
|
353
|
+
changed();
|
|
354
|
+
return icons;
|
|
355
|
+
},
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* The config's part of the map theme once the page has it: loads the icons, sets the pixelated flag, and marks the root element
|
|
359
|
+
* `data-pixelated` (for the page, <html>) so a stylesheet can sample any DOM image without smoothing too (`image-rendering: pixelated`, explorer.css).
|
|
360
|
+
* @param {{icons?: Record<string, string>, pixelated?: boolean} | null | undefined} theme `config.theme` of /cornfield/config.json
|
|
361
|
+
*/
|
|
362
|
+
applyTheme(theme, opts = {}) {
|
|
363
|
+
const el = inst.tokenElement();
|
|
364
|
+
if (el && el.setAttribute) { if (theme && theme.pixelated === true) el.setAttribute('data-pixelated', ''); else el.removeAttribute('data-pixelated'); }
|
|
365
|
+
return store.setIcons(theme, opts);
|
|
366
|
+
},
|
|
367
|
+
|
|
368
|
+
/** Back to nothing set (for tests) */
|
|
369
|
+
reset() {
|
|
370
|
+
tokens = NO_TOKENS;
|
|
371
|
+
icons = null;
|
|
372
|
+
pixelated = false;
|
|
373
|
+
subjectTokens = [];
|
|
374
|
+
changed();
|
|
375
|
+
},
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Keeps the style right as the theme changes: `data-theme` or `data-theme-name` on the root element changing, a stylesheet finishing loading
|
|
379
|
+
* (a named theme's, or the theme file's: `load` captured at the root), and `prefers-color-scheme` flipping. Everything is removed by `inst.destroy()`;
|
|
380
|
+
* the returned function stops it earlier.
|
|
381
|
+
*/
|
|
382
|
+
watch() {
|
|
383
|
+
const refresh = () => { store.refresh(); };
|
|
384
|
+
const stops = [];
|
|
385
|
+
const el = inst.tokenElement();
|
|
386
|
+
if (el && inst.win && inst.win.MutationObserver) {
|
|
387
|
+
const obs = new inst.win.MutationObserver(refresh);
|
|
388
|
+
obs.observe(el, { attributes: true, attributeFilter: ['data-theme', 'data-theme-name', 'class'] });
|
|
389
|
+
stops.push(() => obs.disconnect());
|
|
390
|
+
}
|
|
391
|
+
if (inst.root) {
|
|
392
|
+
const onLoad = (event) => { if (event.target && event.target.tagName === 'LINK') refresh(); }; // load does not bubble: captured
|
|
393
|
+
stops.push(inst.listen(inst.root, 'load', onLoad, true));
|
|
394
|
+
}
|
|
395
|
+
const media = inst.win && inst.win.matchMedia ? inst.win.matchMedia('(prefers-color-scheme: light)') : null;
|
|
396
|
+
if (media) {
|
|
397
|
+
if (media.addEventListener) { media.addEventListener('change', refresh); stops.push(() => media.removeEventListener('change', refresh)); }
|
|
398
|
+
else if (media.addListener) { media.addListener(refresh); stops.push(() => media.removeListener(refresh)); }
|
|
399
|
+
}
|
|
400
|
+
const fonts = inst.doc && inst.doc.fonts;
|
|
401
|
+
if (fonts && fonts.addEventListener) {
|
|
402
|
+
const again = () => { if (tokens.font) changed(); }; // the label font arrived: the canvas draws again with it
|
|
403
|
+
fonts.addEventListener('loadingdone', again);
|
|
404
|
+
stops.push(() => fonts.removeEventListener('loadingdone', again));
|
|
405
|
+
}
|
|
406
|
+
refresh();
|
|
407
|
+
const stop = () => { while (stops.length) stops.pop()(); };
|
|
408
|
+
inst.own(stop);
|
|
409
|
+
return stop;
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
return store;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** The instance's map style (made on first use) */
|
|
416
|
+
export const mapStyleOf = (inst) => inst.slot('map-style', createMapStyle);
|
|
417
|
+
|
|
418
|
+
// ---------------------------------------------------------------------------
|
|
419
|
+
// Applying it
|
|
420
|
+
// ---------------------------------------------------------------------------
|
|
421
|
+
|
|
422
|
+
const firstOf = (values, names) => { for (const n of names) if (values[n]) return values[n]; return null; };
|
|
423
|
+
|
|
424
|
+
/** The tokens that can fill a node, most specific first (core/layers.js `mapFillNames`, the one place the order is written) */
|
|
425
|
+
export const fillNames = mapFillNames;
|
|
426
|
+
|
|
427
|
+
/** The theme's fill for a node of that kind, layer, type and group (`values` of a style), or null: the node then draws its own colour (`auto`) */
|
|
428
|
+
export const fillOf = (values, node) => firstOf(values, fillNames(node));
|
|
429
|
+
|
|
430
|
+
/** A line's shape in the theme: its width scaled to `--corn-map-edge-width`, its glow and its packet's by `--corn-map-glow` (nothing at `auto`) */
|
|
431
|
+
function shapeEdge(e, style) {
|
|
432
|
+
const scale = style.edgeWidth == null ? 1 : style.edgeWidth / BASE_EDGE_WIDTH;
|
|
433
|
+
const glow = style.glow == null ? 1 : style.glow;
|
|
434
|
+
if (scale === 1 && glow === 1) return e;
|
|
435
|
+
const out = { ...e, width: e.width * scale, glow: e.glow * glow };
|
|
436
|
+
if (e.packet) out.packet = { ...e.packet, glow: e.packet.glow * glow };
|
|
437
|
+
return out;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function styleEdge(e, style, painted) {
|
|
441
|
+
const { values } = style;
|
|
442
|
+
if (e.mark && e.mark !== 'none') {
|
|
443
|
+
const c = values[stateToken(e.mark)];
|
|
444
|
+
return shapeEdge(c ? { ...e, color: c, glowColor: e.glowColor ? c : e.glowColor } : e, style);
|
|
445
|
+
}
|
|
446
|
+
if (painted.has(e.key)) return shapeEdge(e, style);
|
|
447
|
+
const lit = !e.curve && e.glow > 0 && !e.arrow; // a straight link the focus lights
|
|
448
|
+
const c = (lit && values[stateToken('lit')]) || values[edgeToken(e.kind)];
|
|
449
|
+
if (!c) return shapeEdge(e, style);
|
|
450
|
+
const out = { ...e, color: withAlphaOf(c, e.color) };
|
|
451
|
+
if (e.glowColor) out.glowColor = withAlphaOf(c, e.glowColor);
|
|
452
|
+
if (e.packet) out.packet = { ...e.packet, glowColor: withAlphaOf(c, e.packet.glowColor) };
|
|
453
|
+
return shapeEdge(out, style);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** A colour with its hue taken away: the grey of the same lightness, alpha kept. Both renderers read the same `rgb()` */
|
|
457
|
+
export function greyOf(color) {
|
|
458
|
+
const [r, g, b, a] = parseColor(color);
|
|
459
|
+
const l = Math.round(0.2126 * r + 0.7152 * g + 0.0722 * b);
|
|
460
|
+
return a >= 1 ? `rgb(${l}, ${l}, ${l})` : rgbaText(l, l, l, a);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function compute(scene, style) {
|
|
464
|
+
const { values } = style;
|
|
465
|
+
const greyToken = values[GREY_TOKEN];
|
|
466
|
+
const fade = style.greyAlpha == null ? 1 : style.greyAlpha / GREY_ALPHA;
|
|
467
|
+
const toGrey = (c) => (greyToken ? withAlphaOf(greyToken, c) : greyOf(c));
|
|
468
|
+
const label = values[LABEL_TOKEN];
|
|
469
|
+
const stroke = values[STROKE_TOKEN];
|
|
470
|
+
const painted = scene.painted || { nodes: new Set(), edges: new Set() };
|
|
471
|
+
const nodes = scene.nodes.map((n) => {
|
|
472
|
+
// Which fill wins, most specific first (spec 0009 D6): the finer kind, the project layer, the type, the starting layer
|
|
473
|
+
const fill = !painted.nodes.has(n.id) && fillOf(values, n);
|
|
474
|
+
const icon = style.icons ? iconKeysFor(n.type, n.kind, n.layer).find((k) => style.icons.get(k)) || null : null; // the same order: kind, layer, type
|
|
475
|
+
const glows = style.glow != null && style.glow !== 1 && n.glow > 0;
|
|
476
|
+
const grey = !!n.greyed && !painted.nodes.has(n.id); // a review greys what the change does not involve; a colour a painter gave means something and stays
|
|
477
|
+
if (!fill && !label && !stroke && !icon && !glows && !grey) return n;
|
|
478
|
+
const out = { ...n };
|
|
479
|
+
if (glows) out.glow = n.glow * style.glow;
|
|
480
|
+
if (fill) out.color = fill;
|
|
481
|
+
if (label) out.labelColor = withAlphaOf(label, n.labelColor);
|
|
482
|
+
if (stroke && style.strokeWidth > 0) out.stroke = { color: grey ? toGrey(stroke) : stroke, width: style.strokeWidth };
|
|
483
|
+
if (icon && !grey) out.icon = icon; // a picture has its own hues: a greyed node keeps its silhouette, glyph and letters
|
|
484
|
+
if (grey) { out.color = toGrey(out.color); out.alpha = Math.min(1, n.alpha * fade); }
|
|
485
|
+
return out;
|
|
486
|
+
});
|
|
487
|
+
const edges = scene.edges.map((e) => {
|
|
488
|
+
const styled = styleEdge(e, style, painted.edges);
|
|
489
|
+
if (!e.greyed || painted.edges.has(e.key)) return styled;
|
|
490
|
+
return { ...styled, color: toGrey(styled.color), glowColor: null, alpha: Math.min(1, styled.alpha * fade) };
|
|
491
|
+
});
|
|
492
|
+
const out = { ...scene, nodes, edges };
|
|
493
|
+
if (style.font) out.labelFont = style.font; // every label's font list (labels.js reads `scene.labelFont`)
|
|
494
|
+
if (style.labelMin != null) out.labelMin = style.labelMin; // the smallest label on screen (labels.js reads `scene.labelMin`)
|
|
495
|
+
const halo = values[LABEL_HALO_TOKEN];
|
|
496
|
+
if (halo) { // the outline under the labels, at the widths it has (labels.js reads `scene.labelOutline` before the ground's own)
|
|
497
|
+
const { node, edge } = looksFor(scene.theme).labelOutline;
|
|
498
|
+
out.labelOutline = { node: { ...node, color: halo }, edge: { ...edge, color: halo } };
|
|
499
|
+
}
|
|
500
|
+
return out;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// Both memos hold the style they were made for, not its version: a style is a new frozen object at every change, and two instances' styles
|
|
504
|
+
// count their versions apart, so the same version number can be two different themes (`looksFor` hands every instance the same looks object)
|
|
505
|
+
const sceneMemo = new WeakMap();
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* `scene` in the style's colours, with the outline and icon of each node that has one: the same object when there is nothing to apply, and
|
|
509
|
+
* the same result for the same scene and style, so a renderer's cache of what it packed holds.
|
|
510
|
+
* @param {import('./scene.js').Scene} scene
|
|
511
|
+
* @param {MapStyle} [style] the instance's (`mapStyleOf(inst).get()`); none: the scene as it is
|
|
512
|
+
*/
|
|
513
|
+
export function styledScene(scene, style) {
|
|
514
|
+
if (!style || (style.plain && !scene.greying)) return scene; // a review's greying is applied even with no theme
|
|
515
|
+
const hit = sceneMemo.get(scene);
|
|
516
|
+
if (hit && hit.style === style) return hit.out;
|
|
517
|
+
const out = compute(scene, style);
|
|
518
|
+
sceneMemo.set(scene, { style, out });
|
|
519
|
+
return out;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const looksMemo = new WeakMap();
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* The halos and mark rings (scene.js `looksFor`) in the style's colours: a selected node's, a search hit's, and each diff mark's.
|
|
526
|
+
* @param {ReturnType<typeof import('./scene.js').looksFor>} looks
|
|
527
|
+
* @param {MapStyle} [style]
|
|
528
|
+
*/
|
|
529
|
+
export function looksWith(looks, style) {
|
|
530
|
+
if (!style || style.plain) return looks;
|
|
531
|
+
const hit = looksMemo.get(looks);
|
|
532
|
+
if (hit && hit.style === style) return hit.out;
|
|
533
|
+
const { values } = style;
|
|
534
|
+
const halo = { ...looks.halo };
|
|
535
|
+
for (const name of ['selected', 'match']) {
|
|
536
|
+
const c = values[stateToken(name)];
|
|
537
|
+
if (c) halo[name] = { ...halo[name], ring: c, fill: halo[name].fill ? withAlphaOf(c, halo[name].fill) : halo[name].fill };
|
|
538
|
+
}
|
|
539
|
+
const mark = { ...looks.mark };
|
|
540
|
+
for (const name of MAP_MARKS) {
|
|
541
|
+
const c = values[stateToken(name)];
|
|
542
|
+
if (c) mark[name] = { ...mark[name], color: c };
|
|
543
|
+
}
|
|
544
|
+
const out = { ...looks, halo, mark };
|
|
545
|
+
looksMemo.set(looks, { style, out });
|
|
546
|
+
return out;
|
|
547
|
+
}
|