@popcorn245/cornfield 0.25.0 → 0.27.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/core/color.js +177 -0
- package/core/config.js +2 -2
- package/core/contrast.js +600 -0
- package/core/theme.js +88 -5
- package/core/validate.js +9 -3
- package/explorer/explorer.css +15 -11
- package/explorer/labels.js +13 -6
- package/explorer/main.js +4 -1
- package/explorer/map-style.js +428 -0
- package/explorer/proposal.js +4 -1
- package/explorer/renderer-canvas2d.js +26 -5
- package/explorer/renderer-webgl.js +182 -38
- package/explorer/scene.js +13 -2
- package/explorer/shaders.js +27 -0
- package/explorer/theme-model.js +6 -23
- package/explorer/theme.js +4 -1
- package/explorer/tokens.css +85 -9
- package/package.json +1 -1
- package/server/server.js +1 -1
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module explorer/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
|
+
*
|
|
17
|
+
* `auto` (the default of every one of them but the width and the collision) means "keep what the map draws without a theme": the
|
|
18
|
+
* node's own colour from the topology, deepened for the light ground by theme-model.js, and every other colour as scene.js has
|
|
19
|
+
* 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
|
|
20
|
+
* for the light ground under :root[data-theme="light"]). A kind's token wins over its group's.
|
|
21
|
+
*
|
|
22
|
+
* How it reaches the pixels. scene.js stays pure: it describes the picture with the colours it always had. A renderer (and the label
|
|
23
|
+
* layer) asks `styledScene(scene, style)` for the same picture in the theme's colours, and `looksWith(looks, style)` for the halos and
|
|
24
|
+
* the mark rings; the style is `getMapStyle()`, which `refreshMapStyle()` reads from the page's computed style. With nothing set,
|
|
25
|
+
* `styledScene` hands the scene back untouched. A node or an edge a painter gave a colour (an outage, a check's verdict, a pull
|
|
26
|
+
* request: `scene.painted`) keeps it: those colours mean something.
|
|
27
|
+
*
|
|
28
|
+
* Icons (`theme.icons`) are loaded here, one image per node kind (`createIconStore`); a kind whose file is missing or will not load
|
|
29
|
+
* simply has no icon. `pixelated` (`theme.pixelated`) is the renderers' cue to sample without smoothing.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { NODE_THEMES } from '../core/schema.js';
|
|
33
|
+
import { parseColor } from './theme-model.js';
|
|
34
|
+
import { looksFor } from './scene.js';
|
|
35
|
+
|
|
36
|
+
/** The node kinds (topology types) and the groups (layers a node can belong to) the tokens exist for */
|
|
37
|
+
export const MAP_KINDS = Object.freeze(Object.keys(NODE_THEMES));
|
|
38
|
+
export const MAP_GROUPS = Object.freeze(['app', 'pkg', 'page', 'atom', 'molecule', 'token', 'tool', 'table', 'rom', 'service', 'cloud', 'web', 'stack', 'machine', 'container', 'device', 'house', 'persona']);
|
|
39
|
+
/** The kinds of edge scene.js draws */
|
|
40
|
+
export const MAP_EDGE_KINDS = Object.freeze(['ownership', 'usage', 'flow', 'reads', 'writes', 'calls', 'triggers', 'delivers', 'runs-on', 'uses', 'extends']);
|
|
41
|
+
/** The diff marks, and the other states the map colours */
|
|
42
|
+
export const MAP_MARKS = Object.freeze(['added', 'changed', 'removed', 'edit']);
|
|
43
|
+
export const MAP_STATES = Object.freeze(['selected', 'match', 'lit']);
|
|
44
|
+
export const STROKE_TOKEN = '--corn-map-stroke';
|
|
45
|
+
export const STROKE_WIDTH_TOKEN = '--corn-map-stroke-width';
|
|
46
|
+
export const LABEL_TOKEN = '--corn-map-label';
|
|
47
|
+
export const LABEL_HALO_TOKEN = '--corn-map-label-halo';
|
|
48
|
+
export const COLLISION_TOKEN = '--corn-map-collision';
|
|
49
|
+
/** The width of an outline when the token is not a length (px, world units) */
|
|
50
|
+
export const DEFAULT_STROKE_WIDTH = 1.5;
|
|
51
|
+
/** An icon is drawn this many radii across (a square, so it fits inside the circle) */
|
|
52
|
+
export const ICON_RATIO = 1.2;
|
|
53
|
+
/** Where the server serves the images beside a theme (core/theme.js THEME_ASSET_PREFIX); an icon is fetched from nowhere else */
|
|
54
|
+
export const ICON_URL_PREFIX = '/cornfield/theme/assets/';
|
|
55
|
+
|
|
56
|
+
export const nodeToken = (kind) => `--corn-map-node-${kind}`;
|
|
57
|
+
export const groupToken = (group) => `--corn-map-group-${group}`;
|
|
58
|
+
export const edgeToken = (kind) => `--corn-map-edge-${kind}`;
|
|
59
|
+
export const stateToken = (name) => `--corn-map-${name}`;
|
|
60
|
+
|
|
61
|
+
/** The colour tokens script reads: all of them but the width and the collision mark (which CSS reads) */
|
|
62
|
+
export const MAP_COLOR_TOKENS = Object.freeze([
|
|
63
|
+
...MAP_KINDS.map(nodeToken),
|
|
64
|
+
...MAP_GROUPS.map(groupToken),
|
|
65
|
+
STROKE_TOKEN,
|
|
66
|
+
LABEL_TOKEN,
|
|
67
|
+
LABEL_HALO_TOKEN,
|
|
68
|
+
...MAP_EDGE_KINDS.map(edgeToken),
|
|
69
|
+
...MAP_MARKS.map(stateToken),
|
|
70
|
+
...MAP_STATES.map(stateToken),
|
|
71
|
+
]);
|
|
72
|
+
/** Every map token */
|
|
73
|
+
export const mapTokenNames = () => [...MAP_COLOR_TOKENS, STROKE_WIDTH_TOKEN, COLLISION_TOKEN];
|
|
74
|
+
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
// Reading a token
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
let probe;
|
|
80
|
+
const normalised = new Map();
|
|
81
|
+
|
|
82
|
+
/** A canvas context to normalise a colour the way the browser reads it (`hsl()`, a name, `color-mix()`), or null where there is none */
|
|
83
|
+
function probeContext() {
|
|
84
|
+
if (probe !== undefined) return probe;
|
|
85
|
+
probe = null;
|
|
86
|
+
try { if (typeof document !== 'undefined') probe = document.createElement('canvas').getContext('2d', { willReadFrequently: true }) || null; } catch { probe = null; }
|
|
87
|
+
return probe;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* A token's value as a colour the renderers can use (`#rrggbb`, `rgb()`, `rgba()`), or null for `auto`, empty, or anything that is not a colour.
|
|
92
|
+
* @param {string} value
|
|
93
|
+
* @returns {string | null}
|
|
94
|
+
*/
|
|
95
|
+
export function cssColor(value) {
|
|
96
|
+
const s = typeof value === 'string' ? value.trim() : '';
|
|
97
|
+
if (!s || s.toLowerCase() === 'auto') return null;
|
|
98
|
+
if (inRange(s)) return s;
|
|
99
|
+
if (/^transparent$/i.test(s)) return 'rgba(0, 0, 0, 0)';
|
|
100
|
+
if (normalised.has(s)) return normalised.get(s);
|
|
101
|
+
let out = null;
|
|
102
|
+
const ctx = isColor(s) && !/currentcolor/i.test(s) ? probeContext() : null; // a canvas has no current colour: it would read as black
|
|
103
|
+
if (ctx) {
|
|
104
|
+
try {
|
|
105
|
+
// The browser's own reading: a value it refuses leaves fillStyle as it was, so two different starting colours tell a refusal
|
|
106
|
+
// from a colour that happens to equal the first one
|
|
107
|
+
const read = (from) => { ctx.fillStyle = from; ctx.fillStyle = s; return String(ctx.fillStyle); };
|
|
108
|
+
const a = read('#010203');
|
|
109
|
+
const got = a !== '#010203' ? a : read('#040506') !== '#040506' ? a : null;
|
|
110
|
+
// A colour the browser keeps in another space (`oklch()`, `color(display-p3 ...)`) is read back as the sRGB pixel it paints
|
|
111
|
+
out = got === null ? null : parseable(got) ? got : pixelOf(ctx, s);
|
|
112
|
+
} catch { out = null; }
|
|
113
|
+
}
|
|
114
|
+
normalised.set(s, out);
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Whether CSS itself reads `s` as a colour (a canvas is more lenient: it takes `rgb(1.2.3, 0, 0)`); true where the page cannot say */
|
|
119
|
+
function isColor(s) {
|
|
120
|
+
try { return typeof CSS === 'undefined' || typeof CSS.supports !== 'function' || CSS.supports('color', s); } catch { return false; }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** `#rgb`, `#rrggbb`, `rgb()` or `rgba()` with every channel in range: what both renderers read as written */
|
|
124
|
+
function inRange(s) {
|
|
125
|
+
if (!parseable(s)) return false;
|
|
126
|
+
// The numbers as written: parseColor clamps them, and an out-of-range channel must go to the browser to be read
|
|
127
|
+
const nums = /^rgba?\(/i.test(s.trim()) ? s.slice(s.indexOf('(') + 1, s.lastIndexOf(')')).split(',').map(Number) : null;
|
|
128
|
+
if (nums && (nums.slice(0, 3).some((c) => !(c >= 0 && c <= 255)) || (nums.length > 3 && !(nums[3] > 0 && nums[3] <= 1)))) return false;
|
|
129
|
+
const [r, g, b, a] = parseColor(s);
|
|
130
|
+
return [r, g, b].every((c) => Number.isFinite(c) && c >= 0 && c <= 255) && Number.isFinite(a) && a > 0 && a <= 1;
|
|
131
|
+
}
|
|
132
|
+
/** The forms parseColor (theme-model.js) reads; anything else is normalised by the browser first */
|
|
133
|
+
const COLOR_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$|^rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*(?:,\s*[\d.]+\s*)?\)$/i;
|
|
134
|
+
const parseable = (s) => COLOR_RE.test(s.trim());
|
|
135
|
+
|
|
136
|
+
/** The sRGB pixel `css` paints, as `rgba()` (or null when the context cannot be read) */
|
|
137
|
+
function pixelOf(ctx, css) {
|
|
138
|
+
if (!ctx.getImageData || !ctx.fillRect) return null;
|
|
139
|
+
ctx.clearRect(0, 0, 1, 1);
|
|
140
|
+
ctx.fillStyle = css;
|
|
141
|
+
ctx.fillRect(0, 0, 1, 1);
|
|
142
|
+
const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
|
|
143
|
+
return rgbaText(r, g, b, a / 255);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const rgbaText = (r, g, b, a) => `rgba(${r}, ${g}, ${b}, ${+a.toFixed(3)})`;
|
|
147
|
+
|
|
148
|
+
/** `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) */
|
|
149
|
+
export function withAlphaOf(token, original) {
|
|
150
|
+
const [r, g, b, a] = parseColor(token);
|
|
151
|
+
const oa = parseColor(original)[3];
|
|
152
|
+
if (oa >= 1) return token;
|
|
153
|
+
return rgbaText(r, g, b, a * oa);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* The tokens as the page computes them.
|
|
158
|
+
* @param {(name: string) => string} read the value of a custom property
|
|
159
|
+
* @returns {{values: Record<string, string>, strokeWidth: number}} `values` holds only the tokens that are a colour (not `auto`)
|
|
160
|
+
*/
|
|
161
|
+
export function readMapTokens(read) {
|
|
162
|
+
const values = {};
|
|
163
|
+
for (const name of MAP_COLOR_TOKENS) {
|
|
164
|
+
const c = cssColor(read(name));
|
|
165
|
+
if (c) values[name] = c;
|
|
166
|
+
}
|
|
167
|
+
const w = parseFloat(String(read(STROKE_WIDTH_TOKEN) ?? ''));
|
|
168
|
+
return { values, strokeWidth: Number.isFinite(w) && w >= 0 ? w : DEFAULT_STROKE_WIDTH };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** A reader of the page's computed custom properties, or null where there is no page */
|
|
172
|
+
export function pageReader(doc = typeof document !== 'undefined' ? document : null) {
|
|
173
|
+
const win = doc && doc.defaultView;
|
|
174
|
+
if (!doc || !doc.documentElement || !win || !win.getComputedStyle) return null;
|
|
175
|
+
const style = win.getComputedStyle(doc.documentElement);
|
|
176
|
+
return (name) => style.getPropertyValue(name);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
// Icons
|
|
181
|
+
// ---------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
function loadImage(url) {
|
|
184
|
+
return new Promise((resolve, reject) => {
|
|
185
|
+
if (typeof Image === 'undefined') { reject(new Error('no Image')); return; }
|
|
186
|
+
const img = new Image();
|
|
187
|
+
img.onload = () => (img.naturalWidth > 0 && img.naturalHeight > 0 ? resolve(img) : reject(new Error(`${url} has no size`)));
|
|
188
|
+
img.onerror = () => reject(new Error(`${url} did not load`));
|
|
189
|
+
img.src = url;
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* 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
|
|
195
|
+
* one whose file is missing or is not an image are the same to the map (no icon), and one failure never touches another.
|
|
196
|
+
* @param {Record<string, string>} urls kind to served path (only paths under ICON_URL_PREFIX, for a kind that is a node kind)
|
|
197
|
+
* @param {{load?: (url: string) => Promise<unknown>, onChange?: () => void, warn?: (message: string) => void}} [opts]
|
|
198
|
+
*/
|
|
199
|
+
export function createIconStore(urls, { load = loadImage, onChange = () => {}, warn = (m) => console.warn(m) } = {}) {
|
|
200
|
+
const entries = new Map();
|
|
201
|
+
let ready = 0;
|
|
202
|
+
for (const [kind, url] of Object.entries(urls || {})) {
|
|
203
|
+
if (!MAP_KINDS.includes(kind) || typeof url !== 'string' || !url.startsWith(ICON_URL_PREFIX) || url.includes('..')) continue;
|
|
204
|
+
const entry = { status: 'loading', image: null };
|
|
205
|
+
entries.set(kind, entry);
|
|
206
|
+
Promise.resolve().then(() => load(url)).then((image) => {
|
|
207
|
+
entry.status = 'ready';
|
|
208
|
+
entry.image = image;
|
|
209
|
+
ready++;
|
|
210
|
+
onChange();
|
|
211
|
+
}, (err) => {
|
|
212
|
+
entry.status = 'failed';
|
|
213
|
+
warn(`Map icon for "${kind}" not drawn: ${err && err.message ? err.message : err}`);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
kinds: [...entries.keys()],
|
|
218
|
+
get: (kind) => { const e = entries.get(kind); return e && e.status === 'ready' ? e.image : null; },
|
|
219
|
+
status: (kind) => (entries.has(kind) ? entries.get(kind).status : 'none'),
|
|
220
|
+
anyReady: () => ready > 0,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ---------------------------------------------------------------------------
|
|
225
|
+
// The style in force
|
|
226
|
+
// ---------------------------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* @typedef {object} MapStyle
|
|
230
|
+
* @property {number} version changes whenever anything below does: a renderer draws again when it differs from the one it drew
|
|
231
|
+
* @property {Record<string, string>} values the tokens that are a colour, by name (those at `auto` are absent)
|
|
232
|
+
* @property {number} strokeWidth px, world units
|
|
233
|
+
* @property {ReturnType<typeof createIconStore> | null} icons
|
|
234
|
+
* @property {boolean} pixelated sample icons without smoothing
|
|
235
|
+
* @property {boolean} plain nothing to apply: no colour set, no icon loaded (the scene is drawn as it is)
|
|
236
|
+
*/
|
|
237
|
+
|
|
238
|
+
let tokens = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH };
|
|
239
|
+
let icons = null;
|
|
240
|
+
let pixelated = false;
|
|
241
|
+
let version = 0;
|
|
242
|
+
let current = compose();
|
|
243
|
+
const listeners = new Set();
|
|
244
|
+
|
|
245
|
+
function compose() {
|
|
246
|
+
const plain = !Object.keys(tokens.values).length && !(icons && icons.anyReady());
|
|
247
|
+
return Object.freeze({ version, values: tokens.values, strokeWidth: tokens.strokeWidth, icons, pixelated, plain });
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function changed() {
|
|
251
|
+
version++;
|
|
252
|
+
current = compose();
|
|
253
|
+
listeners.forEach((fn) => fn(current));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** @returns {MapStyle} */
|
|
257
|
+
export const getMapStyle = () => current;
|
|
258
|
+
|
|
259
|
+
/** Calls `fn(style)` when the style changes (a token, an icon arriving); returns how to stop */
|
|
260
|
+
export function onMapStyleChange(fn) {
|
|
261
|
+
listeners.add(fn);
|
|
262
|
+
return () => listeners.delete(fn);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Reads the tokens again; true when something differed (and the listeners were told). Run on load and whenever the theme changes.
|
|
267
|
+
* @param {(name: string) => string} [read] default: the page's computed style
|
|
268
|
+
*/
|
|
269
|
+
export function refreshMapStyle(read = pageReader()) {
|
|
270
|
+
if (!read) return false;
|
|
271
|
+
const next = readMapTokens(read);
|
|
272
|
+
const same = next.strokeWidth === tokens.strokeWidth
|
|
273
|
+
&& Object.keys(next.values).length === Object.keys(tokens.values).length
|
|
274
|
+
&& Object.entries(next.values).every(([k, v]) => tokens.values[k] === v);
|
|
275
|
+
if (same) return false;
|
|
276
|
+
tokens = next;
|
|
277
|
+
changed();
|
|
278
|
+
return true;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Starts loading the config's icons (`theme.icons`, as the browser is told them: kind to served path) and sets the pixelated flag.
|
|
283
|
+
* @param {{icons?: Record<string, string>, pixelated?: boolean} | null | undefined} theme
|
|
284
|
+
* @param {Parameters<typeof createIconStore>[1]} [opts]
|
|
285
|
+
*/
|
|
286
|
+
export function setMapIcons(theme, opts = {}) {
|
|
287
|
+
const urls = theme && theme.icons && typeof theme.icons === 'object' ? theme.icons : {};
|
|
288
|
+
pixelated = !!(theme && theme.pixelated === true);
|
|
289
|
+
icons = Object.keys(urls).length ? createIconStore(urls, { ...opts, onChange: () => { changed(); if (opts.onChange) opts.onChange(); } }) : null;
|
|
290
|
+
changed();
|
|
291
|
+
return icons;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* The config's part of the map theme once the page has it: loads the icons, sets the pixelated flag, and marks <html data-pixelated> so a
|
|
296
|
+
* stylesheet can sample any DOM image without smoothing too (`image-rendering: pixelated`, explorer.css).
|
|
297
|
+
* @param {Document} doc
|
|
298
|
+
* @param {{icons?: Record<string, string>, pixelated?: boolean} | null | undefined} theme `config.theme` of /cornfield/config.json
|
|
299
|
+
*/
|
|
300
|
+
export function applyMapTheme(doc, theme, opts = {}) {
|
|
301
|
+
if (theme && theme.pixelated === true) doc.documentElement.setAttribute('data-pixelated', ''); else doc.documentElement.removeAttribute('data-pixelated');
|
|
302
|
+
return setMapIcons(theme, opts);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Back to nothing set (for tests) */
|
|
306
|
+
export function resetMapStyle() {
|
|
307
|
+
tokens = { values: {}, strokeWidth: DEFAULT_STROKE_WIDTH };
|
|
308
|
+
icons = null;
|
|
309
|
+
pixelated = false;
|
|
310
|
+
changed();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Keeps the style right as the page changes its theme: `data-theme` or `data-theme-name` on <html> changing, a stylesheet finishing loading
|
|
315
|
+
* (a named theme's, or the theme file's), and `prefers-color-scheme` flipping. Returns how to stop.
|
|
316
|
+
* @param {Document} doc
|
|
317
|
+
*/
|
|
318
|
+
export function watchMapStyle(doc) {
|
|
319
|
+
const refresh = () => { refreshMapStyle(pageReader(doc)); };
|
|
320
|
+
const stops = [];
|
|
321
|
+
const win = doc.defaultView;
|
|
322
|
+
if (win && win.MutationObserver) {
|
|
323
|
+
const obs = new win.MutationObserver(refresh);
|
|
324
|
+
obs.observe(doc.documentElement, { attributes: true, attributeFilter: ['data-theme', 'data-theme-name', 'class'] });
|
|
325
|
+
stops.push(() => obs.disconnect());
|
|
326
|
+
}
|
|
327
|
+
const onLoad = (event) => { if (event.target && event.target.tagName === 'LINK') refresh(); }; // load does not bubble: captured
|
|
328
|
+
doc.addEventListener('load', onLoad, true);
|
|
329
|
+
stops.push(() => doc.removeEventListener('load', onLoad, true));
|
|
330
|
+
const media = win && win.matchMedia ? win.matchMedia('(prefers-color-scheme: light)') : null;
|
|
331
|
+
if (media) {
|
|
332
|
+
if (media.addEventListener) { media.addEventListener('change', refresh); stops.push(() => media.removeEventListener('change', refresh)); }
|
|
333
|
+
else if (media.addListener) { media.addListener(refresh); stops.push(() => media.removeListener(refresh)); }
|
|
334
|
+
}
|
|
335
|
+
refresh();
|
|
336
|
+
return () => stops.forEach((fn) => fn());
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ---------------------------------------------------------------------------
|
|
340
|
+
// Applying it
|
|
341
|
+
// ---------------------------------------------------------------------------
|
|
342
|
+
|
|
343
|
+
const firstOf = (values, names) => { for (const n of names) if (values[n]) return values[n]; return null; };
|
|
344
|
+
|
|
345
|
+
function styleEdge(e, values, painted) {
|
|
346
|
+
if (e.mark && e.mark !== 'none') {
|
|
347
|
+
const c = values[stateToken(e.mark)];
|
|
348
|
+
if (!c) return e;
|
|
349
|
+
return { ...e, color: c, glowColor: e.glowColor ? c : e.glowColor };
|
|
350
|
+
}
|
|
351
|
+
if (painted.has(e.key)) return e;
|
|
352
|
+
const lit = !e.curve && e.glow > 0 && !e.arrow; // a straight link the focus lights
|
|
353
|
+
const c = (lit && values[stateToken('lit')]) || values[edgeToken(e.kind)];
|
|
354
|
+
if (!c) return e;
|
|
355
|
+
const out = { ...e, color: withAlphaOf(c, e.color) };
|
|
356
|
+
if (e.glowColor) out.glowColor = withAlphaOf(c, e.glowColor);
|
|
357
|
+
if (e.packet) out.packet = { ...e.packet, glowColor: withAlphaOf(c, e.packet.glowColor) };
|
|
358
|
+
return out;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function compute(scene, style) {
|
|
362
|
+
const { values } = style;
|
|
363
|
+
const label = values[LABEL_TOKEN];
|
|
364
|
+
const stroke = values[STROKE_TOKEN];
|
|
365
|
+
const painted = scene.painted || { nodes: new Set(), edges: new Set() };
|
|
366
|
+
const nodes = scene.nodes.map((n) => {
|
|
367
|
+
const fill = !painted.nodes.has(n.id) && firstOf(values, [nodeToken(n.type), groupToken(n.group || n.type)]);
|
|
368
|
+
const icon = style.icons && style.icons.get(n.type) ? n.type : null;
|
|
369
|
+
if (!fill && !label && !stroke && !icon) return n;
|
|
370
|
+
const out = { ...n };
|
|
371
|
+
if (fill) out.color = fill;
|
|
372
|
+
if (label) out.labelColor = withAlphaOf(label, n.labelColor);
|
|
373
|
+
if (stroke && style.strokeWidth > 0) out.stroke = { color: stroke, width: style.strokeWidth };
|
|
374
|
+
if (icon) out.icon = icon;
|
|
375
|
+
return out;
|
|
376
|
+
});
|
|
377
|
+
const out = { ...scene, nodes, edges: scene.edges.map((e) => styleEdge(e, values, painted.edges)) };
|
|
378
|
+
const halo = values[LABEL_HALO_TOKEN];
|
|
379
|
+
if (halo) { // the outline under the labels, at the widths it has (labels.js reads `scene.labelOutline` before the ground's own)
|
|
380
|
+
const { node, edge } = looksFor(scene.theme).labelOutline;
|
|
381
|
+
out.labelOutline = { node: { ...node, color: halo }, edge: { ...edge, color: halo } };
|
|
382
|
+
}
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const sceneMemo = new WeakMap();
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* `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
|
|
390
|
+
* the same result for the same scene and style version, so a renderer's cache of what it packed holds.
|
|
391
|
+
* @param {import('./scene.js').Scene} scene
|
|
392
|
+
* @param {MapStyle} [style]
|
|
393
|
+
*/
|
|
394
|
+
export function styledScene(scene, style = current) {
|
|
395
|
+
if (!style || style.plain) return scene;
|
|
396
|
+
const hit = sceneMemo.get(scene);
|
|
397
|
+
if (hit && hit.version === style.version) return hit.out;
|
|
398
|
+
const out = compute(scene, style);
|
|
399
|
+
sceneMemo.set(scene, { version: style.version, out });
|
|
400
|
+
return out;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const looksMemo = new WeakMap();
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* 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.
|
|
407
|
+
* @param {ReturnType<typeof import('./scene.js').looksFor>} looks
|
|
408
|
+
* @param {MapStyle} [style]
|
|
409
|
+
*/
|
|
410
|
+
export function looksWith(looks, style = current) {
|
|
411
|
+
if (!style || style.plain) return looks;
|
|
412
|
+
const hit = looksMemo.get(looks);
|
|
413
|
+
if (hit && hit.version === style.version) return hit.out;
|
|
414
|
+
const { values } = style;
|
|
415
|
+
const halo = { ...looks.halo };
|
|
416
|
+
for (const name of ['selected', 'match']) {
|
|
417
|
+
const c = values[stateToken(name)];
|
|
418
|
+
if (c) halo[name] = { ...halo[name], ring: c, fill: halo[name].fill ? withAlphaOf(c, halo[name].fill) : halo[name].fill };
|
|
419
|
+
}
|
|
420
|
+
const mark = { ...looks.mark };
|
|
421
|
+
for (const name of MAP_MARKS) {
|
|
422
|
+
const c = values[stateToken(name)];
|
|
423
|
+
if (c) mark[name] = { ...mark[name], color: c };
|
|
424
|
+
}
|
|
425
|
+
const out = { ...looks, halo, mark };
|
|
426
|
+
looksMemo.set(looks, { version: style.version, out });
|
|
427
|
+
return out;
|
|
428
|
+
}
|
package/explorer/proposal.js
CHANGED
|
@@ -24,6 +24,7 @@ import { setMap } from './view.js';
|
|
|
24
24
|
import { closeDrawer, selectNode } from './panels.js';
|
|
25
25
|
import { edgePoint, looksFor } from './scene.js';
|
|
26
26
|
import { onThemeChange } from './theme.js';
|
|
27
|
+
import { looksWith, onMapStyleChange } from './map-style.js';
|
|
27
28
|
import {
|
|
28
29
|
PROPOSAL_VIEWS, MARKS, MARK_WORDS, chipText, parseProposalQuery, proposalPanelHtml, touchedIds,
|
|
29
30
|
} from './proposal-model.js';
|
|
@@ -471,10 +472,11 @@ function onKey(e) {
|
|
|
471
472
|
/** The marks' colours for the legend and the panel (the --hx-mark-* variables), the same the map draws on this ground */
|
|
472
473
|
function setMarkColours(theme) {
|
|
473
474
|
const root = document.documentElement.style;
|
|
474
|
-
const { mark: looks } = looksFor(theme);
|
|
475
|
+
const { mark: looks } = looksWith(looksFor(theme)); // the theme's --corn-map-added|changed|removed|edit, when it sets them
|
|
475
476
|
for (const mark of Object.keys(looks)) root.setProperty(`--hx-mark-${mark}`, looks[mark].color);
|
|
476
477
|
}
|
|
477
478
|
let stopMarkColours = null;
|
|
479
|
+
let stopMarkStyle = null;
|
|
478
480
|
|
|
479
481
|
/**
|
|
480
482
|
* Starts the overlay: the mark colours the legend and the panel use, the buttons, picking an
|
|
@@ -485,6 +487,7 @@ let stopMarkColours = null;
|
|
|
485
487
|
export async function initProposals() {
|
|
486
488
|
setMarkColours(state.theme);
|
|
487
489
|
if (!stopMarkColours) stopMarkColours = onThemeChange(setMarkColours);
|
|
490
|
+
if (!stopMarkStyle) stopMarkStyle = onMapStyleChange(() => setMarkColours(state.theme)); // a theme stylesheet that finishes loading later
|
|
488
491
|
|
|
489
492
|
// Once, however many times this runs
|
|
490
493
|
document.removeEventListener('click', onClick);
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { CORE_RATIO, ARROW, MARK_MIN_PX, looksFor, packetPoint } from './scene.js';
|
|
12
|
+
import { ICON_RATIO, getMapStyle, looksWith, styledScene } from './map-style.js';
|
|
12
13
|
|
|
13
14
|
const TAU = Math.PI * 2;
|
|
14
15
|
const circle = (ctx, x, y, r) => { ctx.beginPath(); ctx.arc(x, y, r, 0, TAU); };
|
|
@@ -109,7 +110,7 @@ function drawEdge(ctx, edge, timeMs, zoom) {
|
|
|
109
110
|
// ---------------------------------------------------------------------------
|
|
110
111
|
// Nodes
|
|
111
112
|
// ---------------------------------------------------------------------------
|
|
112
|
-
function drawNode(ctx, node, zoom, looks) {
|
|
113
|
+
function drawNode(ctx, node, zoom, looks, style) {
|
|
113
114
|
ctx.save();
|
|
114
115
|
ctx.globalAlpha = node.alpha;
|
|
115
116
|
|
|
@@ -152,6 +153,22 @@ function drawNode(ctx, node, zoom, looks) {
|
|
|
152
153
|
circle(ctx, node.x, node.y, node.r * CORE_RATIO);
|
|
153
154
|
ctx.fillStyle = looks.core;
|
|
154
155
|
ctx.fill();
|
|
156
|
+
|
|
157
|
+
// The theme's outline (--corn-map-stroke), just inside the edge of the circle
|
|
158
|
+
if (node.stroke) {
|
|
159
|
+
circle(ctx, node.x, node.y, Math.max(0, node.r - node.stroke.width / 2));
|
|
160
|
+
ctx.strokeStyle = node.stroke.color;
|
|
161
|
+
ctx.lineWidth = node.stroke.width;
|
|
162
|
+
ctx.stroke();
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// The theme's icon for this kind (theme.icons), inside the circle; crisp when the theme is pixelated
|
|
166
|
+
const image = node.icon && style.icons ? style.icons.get(node.icon) : null;
|
|
167
|
+
if (image) {
|
|
168
|
+
const side = node.r * ICON_RATIO;
|
|
169
|
+
ctx.imageSmoothingEnabled = !style.pixelated;
|
|
170
|
+
ctx.drawImage(image, node.x - side / 2, node.y - side / 2, side, side);
|
|
171
|
+
}
|
|
155
172
|
ctx.restore();
|
|
156
173
|
}
|
|
157
174
|
|
|
@@ -161,9 +178,11 @@ function drawNode(ctx, node, zoom, looks) {
|
|
|
161
178
|
|
|
162
179
|
/**
|
|
163
180
|
* @param {HTMLCanvasElement} canvas the canvas to draw on
|
|
181
|
+
* @param {{mapStyle?: () => import('./map-style.js').MapStyle}} [opts] `mapStyle`: where the theme's map tokens come from (default: the page's, map-style.js `getMapStyle`)
|
|
164
182
|
* @returns {import('./scene.js').Renderer}
|
|
165
183
|
*/
|
|
166
|
-
export function createCanvas2dRenderer(canvas) {
|
|
184
|
+
export function createCanvas2dRenderer(canvas, opts = {}) {
|
|
185
|
+
const styleOf = opts.mapStyle || getMapStyle;
|
|
167
186
|
const ctx = canvas.getContext('2d');
|
|
168
187
|
let width = 0;
|
|
169
188
|
let height = 0;
|
|
@@ -179,7 +198,9 @@ export function createCanvas2dRenderer(canvas) {
|
|
|
179
198
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
180
199
|
},
|
|
181
200
|
|
|
182
|
-
draw(
|
|
201
|
+
draw(drawn, camera, timeMs) {
|
|
202
|
+
const style = styleOf();
|
|
203
|
+
const scene = styledScene(drawn, style); // the map in the theme's colours (map-style.js); the scene itself when nothing is set
|
|
183
204
|
ctx.clearRect(0, 0, width, height);
|
|
184
205
|
ctx.save();
|
|
185
206
|
ctx.translate(camera.x, camera.y);
|
|
@@ -191,8 +212,8 @@ export function createCanvas2dRenderer(canvas) {
|
|
|
191
212
|
if (decor.rings.length) drawRings(ctx, decor.rings);
|
|
192
213
|
|
|
193
214
|
scene.edges.forEach((edge) => drawEdge(ctx, edge, timeMs, camera.zoom));
|
|
194
|
-
const looks = looksFor(scene.theme); // the halos, mark rings and core for the scene's ground
|
|
195
|
-
scene.nodes.forEach((node) => drawNode(ctx, node, camera.zoom, looks));
|
|
215
|
+
const looks = looksWith(looksFor(scene.theme), style); // the halos, mark rings and core for the scene's ground, in the theme's colours
|
|
216
|
+
scene.nodes.forEach((node) => drawNode(ctx, node, camera.zoom, looks, style));
|
|
196
217
|
// No text here: every label (and the strike through a removed one) is drawn by the label layer (labels.js) over this canvas
|
|
197
218
|
|
|
198
219
|
ctx.restore();
|