@popcorn245/cornfield 0.50.1 → 0.51.1

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.
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @module explorer/camera-frame
3
+ *
4
+ * Where a review's camera goes, as pure functions on `{ x, y, zoom }` (camera.js's): the zoom a step or a picked change is read at
5
+ * (`READ_ZOOM`), the lowest a change is framed at (`FRAME_ZOOM_MIN`) and the most of it that fits there (`largestGroup`), whether a set is all in
6
+ * view (`allInside`), and the pan that brings a node out from under a panel (`panIntoView`). The proposal bar, the scenario player and the node
7
+ * panel use them; a map alone does not (the components' size budget, spec 0011 D11). No DOM, no state.
8
+ *
9
+ * @typedef {import('./camera.js').Camera} Camera
10
+ */
11
+
12
+ import { boxOf, padFor } from './camera.js';
13
+
14
+ /** The zoom at which a node's label is about 11px on screen (a label is never drawn under 11px, labels.js): where a step or a picked change is shown */
15
+ export const READ_ZOOM = 1.0;
16
+ /**
17
+ * The lowest zoom a change is framed at when it opens (proposal.js `fitToChange`): below it node discs and marks run together, so a change
18
+ * wider than this shows is framed where most of it is (`largestGroup`), not shrunk to a speck; the rest is a row of the change list away.
19
+ * The map's own floor (render.js `getMinZoom()`, low enough for the whole map) is what hand zoom and Fit go down to.
20
+ */
21
+ export const FRAME_ZOOM_MIN = 0.18;
22
+
23
+ /** Whether every one of `items` is inside `rect` (with `margin` px to spare) under `camera` */
24
+ export function allInside(items, camera, rect, margin = 0) {
25
+ return items.every((n) => {
26
+ const sx = camera.x + n.x * camera.zoom;
27
+ const sy = camera.y + n.y * camera.zoom;
28
+ return sx >= rect.x + margin && sx <= rect.x + rect.width - margin && sy >= rect.y + margin && sy <= rect.y + rect.height - margin;
29
+ });
30
+ }
31
+
32
+ /**
33
+ * The most of `items` that fit in `rect` together at `minZoom`: all of them when they fit, else the biggest group a window of that size
34
+ * holds (so a change spread wider than the lowest zoom shows is framed where most of it is, not on the empty ground between).
35
+ * @param {{ x: number, y: number, r?: number }[]} items
36
+ * @param {{ x: number, y: number, width: number, height: number }} rect
37
+ * @param {{ padding?: number, minZoom?: number }} [opts]
38
+ */
39
+ export function largestGroup(items, rect, { padding = 40, minZoom = FRAME_ZOOM_MIN } = {}) {
40
+ if (items.length < 2) return items;
41
+ const pad = padFor(padding, rect);
42
+ const w = (rect.width - pad * 2) / minZoom;
43
+ const h = (rect.height - pad * 2) / minZoom;
44
+ const boxes = items.map(boxOf);
45
+ const holds = (left, top) => items.filter((_, i) => boxes[i].left >= left && boxes[i].right <= left + w && boxes[i].top >= top && boxes[i].bottom <= top + h);
46
+ // Every window worth trying has its left edge on some node's box and its top edge on some node's (a big change: only each node's own corner)
47
+ const lefts = boxes.map((b) => b.left);
48
+ const tops = boxes.map((b) => b.top);
49
+ let best = [];
50
+ const pairs = items.length <= 120 ? lefts.flatMap((l) => tops.map((t) => [l, t])) : boxes.map((b) => [b.left, b.top]);
51
+ for (const [l, t] of pairs) {
52
+ if (best.length === items.length) break;
53
+ const got = holds(l, t);
54
+ if (got.length > best.length) best = got;
55
+ }
56
+ return best.length ? best : [items[0]];
57
+ }
58
+
59
+ /**
60
+ * The camera panned (never zoomed) so a world point is inside `box` (screen px), or null when it already is. A point
61
+ * outside is put in the middle of the box, on the axis it is outside of. `pad` is the room it needs from the edge
62
+ * (its disc and a little more); a box smaller than twice that is the centre only.
63
+ * @param {Camera} camera
64
+ * @param {{ x: number, y: number }} point world position
65
+ * @param {{ left: number, top: number, right: number, bottom: number }} box the part of the screen that shows the map
66
+ * @param {number} [pad]
67
+ * @returns {Camera|null}
68
+ */
69
+ export function panIntoView(camera, point, box, pad = 0) {
70
+ const sx = camera.x + point.x * camera.zoom;
71
+ const sy = camera.y + point.y * camera.zoom;
72
+ const px = Math.min(pad, (box.right - box.left) / 2);
73
+ const py = Math.min(pad, (box.bottom - box.top) / 2);
74
+ const outX = sx < box.left + px || sx > box.right - px;
75
+ const outY = sy < box.top + py || sy > box.bottom - py;
76
+ if (!outX && !outY) return null;
77
+ return {
78
+ x: outX ? (box.left + box.right) / 2 - point.x * camera.zoom : camera.x,
79
+ y: outY ? (box.top + box.bottom) / 2 - point.y * camera.zoom : camera.y,
80
+ zoom: camera.zoom,
81
+ };
82
+ }
@@ -7,6 +7,9 @@
7
7
  * The rule for zooming by hand: the world point under the pointer (or between two fingers) stays
8
8
  * where it is on screen, so you zoom into what you are pointing at.
9
9
  *
10
+ * Where a review's camera goes (a change opened, a scenario's step, a panel's node: `READ_ZOOM`, `largestGroup`, `allInside`, `panIntoView`) is
11
+ * camera-frame.js's: a map alone does not carry it (the components' size budget, spec 0011 D11).
12
+ *
10
13
  * @typedef {{ x: number, y: number, zoom: number }} Camera
11
14
  */
12
15
 
@@ -64,15 +67,6 @@ export function pinchCamera(start, dist, mid, min = ZOOM_MIN) {
64
67
  // Framing: put these nodes in the part of the map nothing covers
65
68
  // ---------------------------------------------------------------------------
66
69
 
67
- /** The zoom at which a node's label is about 11px on screen (a label is never drawn under 11px, labels.js): where a step or a picked change is shown */
68
- export const READ_ZOOM = 1.0;
69
- /**
70
- * The lowest zoom a change is framed at when it opens (proposal.js `fitToChange`): below it node discs and marks run together, so a change
71
- * wider than this shows is framed where most of it is (`largestGroup`), not shrunk to a speck; the rest is a row of the change list away.
72
- * The map's own floor (render.js `getMinZoom()`, low enough for the whole map) is what hand zoom and Fit go down to.
73
- */
74
- export const FRAME_ZOOM_MIN = 0.18;
75
-
76
70
  /**
77
71
  * The part of a `width` × `height` map that nothing covers, given what covers it from each side (px).
78
72
  * Never smaller than `minSize` in either direction: when the covers leave less, they are eased until it fits.
@@ -96,16 +90,17 @@ export function freeRect(width, height, covers = {}, minSize = 120) {
96
90
  }
97
91
 
98
92
  /** The box a node needs on the map (world px): its disc, a little room round it and its label below */
99
- const boxOf = (n) => {
93
+ export const boxOf = (n) => {
100
94
  const r = n.r || 18;
101
95
  return { left: n.x - r - 25, right: n.x + r + 25, top: n.y - r - 25, bottom: n.y + r + 35 };
102
96
  };
103
- const padFor = (padding, rect) => Math.min(padding, rect.width / 4, rect.height / 4);
97
+ /** The padding round a framed set, never more than a quarter of the rect */
98
+ export const padFor = (padding, rect) => Math.min(padding, rect.width / 4, rect.height / 4);
104
99
 
105
100
  /**
106
101
  * The camera that shows `items` (nodes with `x`, `y` and maybe `r`) inside `rect`, with their labels (room below each) and `padding` px to spare.
107
102
  * The zoom is the largest that fits, between `minZoom` and `maxZoom`; when even `minZoom` does not fit, `minZoom` wins and the nodes
108
- * are centred (the fit never goes under the floor it is given; see `largestGroup` for what to frame then).
103
+ * are centred (the fit never goes under the floor it is given; see camera-frame.js `largestGroup` for what to frame then).
109
104
  * @param {{ x: number, y: number, r?: number }[]} items
110
105
  * @param {{ x: number, y: number, width: number, height: number }} rect CSS px, in the canvas's own coordinates
111
106
  * @param {{ padding?: number, maxZoom?: number, minZoom?: number }} [opts]
@@ -129,64 +124,3 @@ export function frameNodes(items, rect, { padding = 40, maxZoom = 1, minZoom = Z
129
124
  const zoom = Math.max(minZoom, Math.min(maxZoom, fit));
130
125
  return { x: rect.x + rect.width / 2 - ((minX + maxX) / 2) * zoom, y: rect.y + rect.height / 2 - ((minY + maxY) / 2) * zoom, zoom };
131
126
  }
132
-
133
- /** Whether every one of `items` is inside `rect` (with `margin` px to spare) under `camera` */
134
- export function allInside(items, camera, rect, margin = 0) {
135
- return items.every((n) => {
136
- const sx = camera.x + n.x * camera.zoom;
137
- const sy = camera.y + n.y * camera.zoom;
138
- return sx >= rect.x + margin && sx <= rect.x + rect.width - margin && sy >= rect.y + margin && sy <= rect.y + rect.height - margin;
139
- });
140
- }
141
-
142
- /**
143
- * The most of `items` that fit in `rect` together at `minZoom`: all of them when they fit, else the biggest group a window of that size
144
- * holds (so a change spread wider than the lowest zoom shows is framed where most of it is, not on the empty ground between).
145
- * @param {{ x: number, y: number, r?: number }[]} items
146
- * @param {{ x: number, y: number, width: number, height: number }} rect
147
- * @param {{ padding?: number, minZoom?: number }} [opts]
148
- */
149
- export function largestGroup(items, rect, { padding = 40, minZoom = FRAME_ZOOM_MIN } = {}) {
150
- if (items.length < 2) return items;
151
- const pad = padFor(padding, rect);
152
- const w = (rect.width - pad * 2) / minZoom;
153
- const h = (rect.height - pad * 2) / minZoom;
154
- const boxes = items.map(boxOf);
155
- const holds = (left, top) => items.filter((_, i) => boxes[i].left >= left && boxes[i].right <= left + w && boxes[i].top >= top && boxes[i].bottom <= top + h);
156
- // Every window worth trying has its left edge on some node's box and its top edge on some node's (a big change: only each node's own corner)
157
- const lefts = boxes.map((b) => b.left);
158
- const tops = boxes.map((b) => b.top);
159
- let best = [];
160
- const pairs = items.length <= 120 ? lefts.flatMap((l) => tops.map((t) => [l, t])) : boxes.map((b) => [b.left, b.top]);
161
- for (const [l, t] of pairs) {
162
- if (best.length === items.length) break;
163
- const got = holds(l, t);
164
- if (got.length > best.length) best = got;
165
- }
166
- return best.length ? best : [items[0]];
167
- }
168
-
169
- /**
170
- * The camera panned (never zoomed) so a world point is inside `box` (screen px), or null when it already is. A point
171
- * outside is put in the middle of the box, on the axis it is outside of. `pad` is the room it needs from the edge
172
- * (its disc and a little more); a box smaller than twice that is the centre only.
173
- * @param {Camera} camera
174
- * @param {{ x: number, y: number }} point world position
175
- * @param {{ left: number, top: number, right: number, bottom: number }} box the part of the screen that shows the map
176
- * @param {number} [pad]
177
- * @returns {Camera|null}
178
- */
179
- export function panIntoView(camera, point, box, pad = 0) {
180
- const sx = camera.x + point.x * camera.zoom;
181
- const sy = camera.y + point.y * camera.zoom;
182
- const px = Math.min(pad, (box.right - box.left) / 2);
183
- const py = Math.min(pad, (box.bottom - box.top) / 2);
184
- const outX = sx < box.left + px || sx > box.right - px;
185
- const outY = sy < box.top + py || sy > box.bottom - py;
186
- if (!outX && !outY) return null;
187
- return {
188
- x: outX ? (box.left + box.right) / 2 - point.x * camera.zoom : camera.x,
189
- y: outY ? (box.top + box.bottom) / 2 - point.y * camera.zoom : camera.y,
190
- zoom: camera.zoom,
191
- };
192
- }
@@ -34,18 +34,13 @@
34
34
  */
35
35
 
36
36
  import { personaNodeId } from '../core/schema.js';
37
+ import { VERDICT_COLOR, paintVerdict } from './verdict-paint.js';
38
+
39
+ export { VERDICT_COLOR, paintVerdict };
37
40
 
38
41
  /** The most checks one request holds, unless the checker says otherwise (the API's limit) */
39
42
  export const MAX_BATCH = 100;
40
43
 
41
- /**
42
- * The colours a checked step is drawn in, on its node or its edge. The red is brighter than a `writes`
43
- * edge's own (#f87171), so a refused write reads as refused, not as a write.
44
- */
45
- export const VERDICT_COLOR = { allowed: '#4ade80', refused: '#ff2d55', mismatch: '#fbbf24' };
46
- const VERDICT_GLOW = 18;
47
- const VERDICT_EDGE_WIDTH = 4.5;
48
-
49
44
  const asList = (check) => (check === undefined ? null : Array.isArray(check) ? check : [check]);
50
45
  const isOwnership = (e) => !e.kind && !e.dashed;
51
46
 
@@ -283,39 +278,3 @@ export function verdictWords(v) {
283
278
  if (v.state === 'refused') return { tone: 'refused', pill: '✕ Refused', line: `Refused: ${refusal()}`, detail };
284
279
  return { tone: 'allowed', pill: '✓ Allowed', line: 'Allowed', detail };
285
280
  }
286
-
287
- /** Whether a drawn edge is the one a step names: same ends and kind (and flow); no kind = an ownership or usage link (scene.js's rule) */
288
- function isStepEdge(drawn, step) {
289
- if (drawn.from !== step.from || drawn.to !== step.to) return false;
290
- if (!step.kind) return drawn.kind === 'ownership' || drawn.kind === 'usage';
291
- return drawn.kind === step.kind && (!step.flow || drawn.key.split('|')[2] === step.flow);
292
- }
293
-
294
- /**
295
- * Colours the current step of a playing scenario by its verdict, in a built scene (after
296
- * `emphasiseScenario`): red refused, green allowed, amber when `expect` disagrees; a step that was not
297
- * checked keeps its colours. A refused edge's packet stops halfway: the write does not go through.
298
- * Changes only `color`, `glow`, `glowColor`, `width` and the packet: never `mark`.
299
- * @param {object} scene
300
- * @param {{ done?: boolean, current: { node?: string, edge?: object }, verdict?: Verdict }} scn the player's snapshot, with the verdict check.js put on it
301
- */
302
- export function paintVerdict(scene, scn) {
303
- const v = scn && scn.verdict;
304
- if (!v || scn.done) return;
305
- const color = v.mismatch ? VERDICT_COLOR.mismatch : VERDICT_COLOR[v.state];
306
- if (!color) return;
307
- const { node, edge } = scn.current;
308
- if (node !== undefined) {
309
- const n = scene.nodes.find((x) => x.id === node);
310
- if (n) { n.color = color; n.glow = Math.max(n.glow || 0, VERDICT_GLOW); }
311
- } else if (edge) {
312
- scene.edges.forEach((e) => {
313
- if (!isStepEdge(e, edge)) return;
314
- e.color = color;
315
- e.glowColor = color;
316
- e.glow = Math.max(e.glow || 0, VERDICT_GLOW);
317
- e.width = Math.max(e.width || 0, VERDICT_EDGE_WIDTH);
318
- if (e.packet) e.packet = v.state === 'refused' && !v.mismatch ? { ...e.packet, color, glowColor: color, speed: 0, phase: 0.5 } : { ...e.packet, glowColor: color };
319
- });
320
- }
321
- }
@@ -8,16 +8,13 @@
8
8
  * (`legend`), in the panel (`title`, `color`). The one place these live: scene.js, the legend, the panel and
9
9
  * the House view's Cloud band (CLOUD-08) all read them here; the outage colours (CLOUD-07) are `color`.
10
10
  * - `externalLayer(node)`: the Layers key of an `external` node, `cloud` or `web` (the public web, spec D3).
11
- * - `planLabel`, `cloudUsedBy`: what the node panel shows of a cloud node, as data.
12
- * - `cloudPanelHtml(node, nodes, edges)`: the node panel's facts for it, as HTML (panels.js puts them under the head).
11
+ * - What the node panel shows of a cloud node (`planLabel`, `cloudUsedBy`, `nounOf`, and its facts as HTML, `cloudPanelHtml`) is cloud-panel.js's:
12
+ * only a node panel and an outage scenario say them, so a map alone does not load them.
13
13
  *
14
14
  * Nothing here reads an env var name, a token or a registry `match` list: a cloud node does not carry them, and
15
15
  * the panel shows only the node's own fields and the labels of the edges into it (the registry's words).
16
16
  */
17
17
 
18
- import { escapeHtml as esc } from '../core/text.js';
19
- import { capped } from './capped.js';
20
-
21
18
  /**
22
19
  * When an outage bites, in order of how soon. `dash` is the scene edge's dash (world units, like a proposal
23
20
  * mark's), null for solid; `color` is the panel's and an outage scenario's for that group.
@@ -39,99 +36,3 @@ export const whenTicks = (edge) => (edge && edge.kind === 'calls' ? WHEN_STYLES[
39
36
 
40
37
  /** The Layers key of an outside node: the public web (kind `web`) is its own; every other external is Cloud */
41
38
  export const externalLayer = (node) => (node && node.kind === 'web' ? 'web' : 'cloud');
42
-
43
- const TIER_WORDS = { free: 'Free', paid: 'Paid', unknown: 'Plan unknown', off: 'Off' };
44
-
45
- /** "Free", "Paid", "Plan unknown", "Off", with the plan's note after a dot; '' with no plan */
46
- export function planLabel(plan) {
47
- if (!plan || !TIER_WORDS[plan.tier]) return '';
48
- return plan.note ? `${TIER_WORDS[plan.tier]} · ${plan.note}` : TIER_WORDS[plan.tier];
49
- }
50
-
51
- /** What a user of a cloud service is called, one and many (`nounOf(type, n)`: the outage scenario's words too) */
52
- const NOUNS = {
53
- container: ['container', 'containers'], machine: ['machine', 'machines'], app: ['app', 'apps'],
54
- service: ['service', 'services'], page: ['endpoint', 'endpoints'], external: ['cloud service', 'cloud services'],
55
- };
56
- export const nounOf = (type, n) => { const w = NOUNS[type] || [type, `${type}s`]; return n === 1 ? w[0] : w[1]; };
57
-
58
- /**
59
- * Who uses a cloud node, grouped by when its outage bites them: the `calls` edges into it, one group per `when`
60
- * that has any (`run`, `deploy`, `renew`, in that order), each split by what the users are (the biggest kind
61
- * first, then by type), each user once per group with its edge labels joined, sorted by name.
62
- * @returns {{ when:string, title:string, color:string, count:number,
63
- * types: { type:string, noun:string, items: { id:string, label:string, type:string, via:string, browser:boolean }[] }[] }[]}
64
- */
65
- export function cloudUsedBy(node, nodes, edges) {
66
- const byId = new Map(nodes.map((n) => [n.id, n]));
67
- const groups = new Map(Object.keys(WHEN_STYLES).map((w) => [w, new Map()]));
68
- for (const e of edges) {
69
- if (e.kind !== 'calls' || e.to !== node.id) continue;
70
- const users = groups.get(whenOf(e));
71
- const from = byId.get(e.from) || { id: e.from, label: e.from, type: 'node' };
72
- const item = users.get(e.from) || { id: e.from, label: String(from.label || e.from), type: from.type, vias: [], browser: false };
73
- if (e.label && !item.vias.includes(e.label)) item.vias.push(e.label);
74
- if (e.side === 'browser') item.browser = true;
75
- users.set(e.from, item);
76
- }
77
- const out = [];
78
- for (const [when, users] of groups) {
79
- if (users.size === 0) continue;
80
- const byType = new Map();
81
- for (const { vias, ...item } of users.values()) {
82
- if (!byType.has(item.type)) byType.set(item.type, []);
83
- byType.get(item.type).push({ ...item, via: vias.join(', ') });
84
- }
85
- const types = [...byType].map(([type, items]) => ({ type, noun: nounOf(type, 1), items: items.sort((a, b) => a.label.localeCompare(b.label)) }))
86
- .sort((a, b) => b.items.length - a.items.length || a.type.localeCompare(b.type));
87
- const { title, color } = WHEN_STYLES[when];
88
- out.push({ when, title, color, count: users.size, types });
89
- }
90
- return out;
91
- }
92
-
93
- /** The fact names for the groups of users, short enough for the panel's key column (the long words are WHEN_STYLES `title`) */
94
- const WHEN_KEYS = { run: 'Breaks now', deploy: 'Breaks on deploy', renew: 'Breaks on renewal' };
95
-
96
- const fact = (key, rows) => (rows.length ? `<div class="hx-fact" data-corn="section"><div class="hx-fact-k">${esc(key)}</div><div class="hx-fact-v">${capped(rows)}</div></div>` : '');
97
- const line = (body) => `<div class="hx-line">${body}</div>`;
98
- const name = (label) => `<span class="hx-name">${esc(label)}</span>`;
99
-
100
- /** One user of the node: its name, (browser) when the visitor's browser makes the call, the edge's labels, and what it is when the group mixes kinds */
101
- function userRow(item, mixed) {
102
- const browser = item.browser ? ' <span class="hx-cloud-browser">(browser)</span>' : '';
103
- const bits = [mixed ? nounOf(item.type, 1) : '', item.via].filter(Boolean);
104
- return line(`<span>${name(item.label)}${browser}${bits.length ? `<span class="hx-faint"> · ${esc(bits.join(' · '))}</span>` : ''}</span>`);
105
- }
106
-
107
- /** The Play button (spec 0031 section 8, CLOUD-07): main.js plays outage-model.js `outageScenario` for the node. A quiet button under the facts. */
108
- const playButton = (node) => `<button data-corn-kind="quiet" type="button" class="hx-btn hx-btn--quiet hx-cloud-play" data-action="play-outage" data-id="${esc(node.id)}">Play: ${esc(String(node.label || node.id))} is down</button>`;
109
-
110
- /**
111
- * The node panel's facts for a cloud node (kind `cloud`) or the public web (kind `web`), in the node panel's key/value
112
- * rows (the type and the name are the panel's head): Plan, Roles, If it's down, who uses it by when its outage bites
113
- * (one fact per `when` that has any, long lists folded by capped.js), what it relies on itself (calls to other cloud
114
- * nodes), the webhooks it sends, then a quiet Play button (a cloud node only). The caller adds the File line.
115
- */
116
- export function cloudPanelHtml(node, nodes, edges) {
117
- const byId = new Map(nodes.map((n) => [n.id, n]));
118
- const label = (id) => String((byId.get(id) || { label: id }).label || id);
119
- const web = node.kind === 'web'; // the public web: no plan, no roles, no Play
120
- const roles = web ? [] : node.roles || [];
121
- const used = cloudUsedBy(node, nodes, edges).map((g) => {
122
- const mixed = g.types.length > 1;
123
- return fact(WHEN_KEYS[g.when], g.types.flatMap((t) => t.items.map((i) => userRow(i, mixed))));
124
- }).join('') || fact('Used by', [line('<span class="hx-faint">Nothing on the map uses it.</span>')]);
125
-
126
- const relies = edges.filter((e) => e.kind === 'calls' && e.from === node.id && (byId.get(e.to) || {}).type === 'external')
127
- .map((e) => line(`<span>${name(label(e.to))}${e.label ? `<span class="hx-faint"> · ${esc(e.label)}</span>` : ''}</span>`));
128
- const pushes = edges.filter((e) => e.kind === 'delivers' && e.from === node.id).map((e) => line(name(label(e.to))));
129
-
130
- return (web ? '' : fact('Plan', [line(esc(planLabel(node.plan) || TIER_WORDS.unknown))]))
131
- + fact('Roles', roles.length ? [line(esc(roles.join(', ')))] : [])
132
- + fact('If it\'s down', [line(esc(node.breaks || 'Not described yet.'))])
133
- + used
134
- + fact('Relies on', relies)
135
- + fact('Pushes to', pushes)
136
- + (web ? '' : playButton(node)); // the public web is never down as a whole (spec D3)
137
- }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * @module explorer/cloud-panel
3
+ *
4
+ * What the node panel says of a cloud node or the public web (spec 0031 sections 1 and 6, CLOUD-06): `planLabel`, `cloudUsedBy` (who uses it, by
5
+ * when its outage bites), `nounOf` (the outage scenario's words too: outage-scenario.js) and its facts as HTML, `cloudPanelHtml(node, nodes, edges)`,
6
+ * which pieces/node-panel.js puts under the panel's head. When an outage bites is cloud-model.js's (`WHEN_STYLES`, `whenOf`); this is a module of
7
+ * its own so that what draws a map alone (scene.js, the House view) does not carry the panel's words (the components' size budget, spec 0011 D11).
8
+ */
9
+
10
+ import { escapeHtml as esc } from '../core/text.js';
11
+ import { capped } from './capped.js';
12
+ import { WHEN_STYLES, whenOf } from './cloud-model.js';
13
+
14
+ const TIER_WORDS = { free: 'Free', paid: 'Paid', unknown: 'Plan unknown', off: 'Off' };
15
+
16
+ /** "Free", "Paid", "Plan unknown", "Off", with the plan's note after a dot; '' with no plan */
17
+ export function planLabel(plan) {
18
+ if (!plan || !TIER_WORDS[plan.tier]) return '';
19
+ return plan.note ? `${TIER_WORDS[plan.tier]} · ${plan.note}` : TIER_WORDS[plan.tier];
20
+ }
21
+
22
+ /** What a user of a cloud service is called, one and many (`nounOf(type, n)`: the outage scenario's words too) */
23
+ const NOUNS = {
24
+ container: ['container', 'containers'], machine: ['machine', 'machines'], app: ['app', 'apps'],
25
+ service: ['service', 'services'], page: ['endpoint', 'endpoints'], external: ['cloud service', 'cloud services'],
26
+ };
27
+ export const nounOf = (type, n) => { const w = NOUNS[type] || [type, `${type}s`]; return n === 1 ? w[0] : w[1]; };
28
+
29
+ /**
30
+ * Who uses a cloud node, grouped by when its outage bites them: the `calls` edges into it, one group per `when`
31
+ * that has any (`run`, `deploy`, `renew`, in that order), each split by what the users are (the biggest kind
32
+ * first, then by type), each user once per group with its edge labels joined, sorted by name.
33
+ * @returns {{ when:string, title:string, color:string, count:number,
34
+ * types: { type:string, noun:string, items: { id:string, label:string, type:string, via:string, browser:boolean }[] }[] }[]}
35
+ */
36
+ export function cloudUsedBy(node, nodes, edges) {
37
+ const byId = new Map(nodes.map((n) => [n.id, n]));
38
+ const groups = new Map(Object.keys(WHEN_STYLES).map((w) => [w, new Map()]));
39
+ for (const e of edges) {
40
+ if (e.kind !== 'calls' || e.to !== node.id) continue;
41
+ const users = groups.get(whenOf(e));
42
+ const from = byId.get(e.from) || { id: e.from, label: e.from, type: 'node' };
43
+ const item = users.get(e.from) || { id: e.from, label: String(from.label || e.from), type: from.type, vias: [], browser: false };
44
+ if (e.label && !item.vias.includes(e.label)) item.vias.push(e.label);
45
+ if (e.side === 'browser') item.browser = true;
46
+ users.set(e.from, item);
47
+ }
48
+ const out = [];
49
+ for (const [when, users] of groups) {
50
+ if (users.size === 0) continue;
51
+ const byType = new Map();
52
+ for (const { vias, ...item } of users.values()) {
53
+ if (!byType.has(item.type)) byType.set(item.type, []);
54
+ byType.get(item.type).push({ ...item, via: vias.join(', ') });
55
+ }
56
+ const types = [...byType].map(([type, items]) => ({ type, noun: nounOf(type, 1), items: items.sort((a, b) => a.label.localeCompare(b.label)) }))
57
+ .sort((a, b) => b.items.length - a.items.length || a.type.localeCompare(b.type));
58
+ const { title, color } = WHEN_STYLES[when];
59
+ out.push({ when, title, color, count: users.size, types });
60
+ }
61
+ return out;
62
+ }
63
+ /** The fact names for the groups of users, short enough for the panel's key column (the long words are WHEN_STYLES `title`) */
64
+ const WHEN_KEYS = { run: 'Breaks now', deploy: 'Breaks on deploy', renew: 'Breaks on renewal' };
65
+
66
+ const fact = (key, rows) => (rows.length ? `<div class="hx-fact" data-corn="section"><div class="hx-fact-k">${esc(key)}</div><div class="hx-fact-v">${capped(rows)}</div></div>` : '');
67
+ const line = (body) => `<div class="hx-line">${body}</div>`;
68
+ const name = (label) => `<span class="hx-name">${esc(label)}</span>`;
69
+
70
+ /** One user of the node: its name, (browser) when the visitor's browser makes the call, the edge's labels, and what it is when the group mixes kinds */
71
+ function userRow(item, mixed) {
72
+ const browser = item.browser ? ' <span class="hx-cloud-browser">(browser)</span>' : '';
73
+ const bits = [mixed ? nounOf(item.type, 1) : '', item.via].filter(Boolean);
74
+ return line(`<span>${name(item.label)}${browser}${bits.length ? `<span class="hx-faint"> · ${esc(bits.join(' · '))}</span>` : ''}</span>`);
75
+ }
76
+
77
+ /** The Play button (spec 0031 section 8, CLOUD-07): main.js plays outage-scenario.js `outageScenario` for the node. A quiet button under the facts. */
78
+ const playButton = (node) => `<button data-corn-kind="quiet" type="button" class="hx-btn hx-btn--quiet hx-cloud-play" data-action="play-outage" data-id="${esc(node.id)}">Play: ${esc(String(node.label || node.id))} is down</button>`;
79
+
80
+ /**
81
+ * The node panel's facts for a cloud node (kind `cloud`) or the public web (kind `web`), in the node panel's key/value
82
+ * rows (the type and the name are the panel's head): Plan, Roles, If it's down, who uses it by when its outage bites
83
+ * (one fact per `when` that has any, long lists folded by capped.js), what it relies on itself (calls to other cloud
84
+ * nodes), the webhooks it sends, then a quiet Play button (a cloud node only). The caller adds the File line.
85
+ */
86
+ export function cloudPanelHtml(node, nodes, edges) {
87
+ const byId = new Map(nodes.map((n) => [n.id, n]));
88
+ const label = (id) => String((byId.get(id) || { label: id }).label || id);
89
+ const web = node.kind === 'web'; // the public web: no plan, no roles, no Play
90
+ const roles = web ? [] : node.roles || [];
91
+ const used = cloudUsedBy(node, nodes, edges).map((g) => {
92
+ const mixed = g.types.length > 1;
93
+ return fact(WHEN_KEYS[g.when], g.types.flatMap((t) => t.items.map((i) => userRow(i, mixed))));
94
+ }).join('') || fact('Used by', [line('<span class="hx-faint">Nothing on the map uses it.</span>')]);
95
+
96
+ const relies = edges.filter((e) => e.kind === 'calls' && e.from === node.id && (byId.get(e.to) || {}).type === 'external')
97
+ .map((e) => line(`<span>${name(label(e.to))}${e.label ? `<span class="hx-faint"> · ${esc(e.label)}</span>` : ''}</span>`));
98
+ const pushes = edges.filter((e) => e.kind === 'delivers' && e.from === node.id).map((e) => line(name(label(e.to))));
99
+
100
+ return (web ? '' : fact('Plan', [line(esc(planLabel(node.plan) || TIER_WORDS.unknown))]))
101
+ + fact('Roles', roles.length ? [line(esc(roles.join(', ')))] : [])
102
+ + fact('If it\'s down', [line(esc(node.breaks || 'Not described yet.'))])
103
+ + used
104
+ + fact('Relies on', relies)
105
+ + fact('Pushes to', pushes)
106
+ + (web ? '' : playButton(node)); // the public web is never down as a whole (spec D3)
107
+ }
@@ -47,3 +47,5 @@
47
47
  set, so they cannot be told apart from the host's: a border drawn round every canvas, an indent on every paragraph */
48
48
  [data-corn="review"] canvas { border: 0; }
49
49
  [data-corn="review"] :is(p, h1, h2, h3, h4) { text-indent: 0; font-variant: normal; }
50
+ /* The load's card (pieces/status.js) and its notice lie over the dock (z-index 45) and the phone's sheets, so a sign-in link is never half under one */
51
+ [data-corn="review"] [data-corn="source-status"], [data-corn="review"] [data-corn="source-notice"] { z-index: 50; }
@@ -24,9 +24,12 @@ export function credentialed(inst) {
24
24
  * The one rule for the maintainer's session (credentialed() here, and engine/source.js's reads of the config and the map): the fetch options for
25
25
  * `path`, with `credentials: 'include'` added when the instance has a base and `path` is on the base's own origin, else `init` as it was
26
26
  * (`undefined` stays `undefined`, so a request of the page's own is unchanged). What the caller set itself wins.
27
+ *
28
+ * A request with the session never follows a redirect (`redirect: 'error'`): the browser would take it, with the cookies of wherever it is sent,
29
+ * to whatever origin the answer names, and cornfield answers none of these routes with one. It fails instead, as a request with no answer does.
27
30
  */
28
31
  export function sessionInit(inst, path, init) {
29
- return inst.base && underBase(inst, path) ? { credentials: 'include', ...init } : init;
32
+ return inst.base && underBase(inst, path) ? { credentials: 'include', redirect: 'error', ...init } : init;
30
33
  }
31
34
 
32
35
  /** Whether `path`, made absolute against the instance's base (as `inst.fetch` makes it), is on the base's origin: only those carry the maintainer's session */
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @module explorer/engine/map-rect
3
+ *
4
+ * The part of the map that nothing covers, and whether the instance is laid out as a phone (spec 0012, TOPO-18; spec 0011 D2): what a map
5
+ * frames a node into (selection-view.js) and what the sheets measure (engine/sheets.js, which re-exports all of this for the page and the
6
+ * pieces). The instance's sheets' slot is made here, so the two share it. It is a module of its own so that a map alone (`<corn-map>`) does
7
+ * not carry the sheets themselves: only a review, a node panel or the page registers one (the components' size budget, spec 0011 D11).
8
+ */
9
+
10
+ import { createSheetModel } from '../sheet-model.js';
11
+ import { freeRect } from '../camera.js';
12
+
13
+ /** The width below which the sheets apply (matches the CSS) */
14
+ export const PHONE_QUERY = '(max-width: 767px)';
15
+
16
+ /** What the instance keeps of its sheets */
17
+ export function sheetsOf(inst) {
18
+ return inst.slot('sheets', () => ({
19
+ model: createSheetModel(),
20
+ elements: new Map(), // id -> the sheet's element
21
+ options: new Map(), // id -> { stub?: () => { title: string, badge?: string, label?: string }, away?: () => void } what the sheet's owner gave it
22
+ offs: new Map(), // id -> how to remove the listeners bound on the sheet and its handle
23
+ away: new Set(), // sheets displaced by the other of their group: open on the page, hidden until opened again
24
+ listeners: new Set(),
25
+ dock: null,
26
+ box: null, // the element whose width says phone, instead of the window's (setPhoneBox)
27
+ lastCovered: 0,
28
+ observers: [],
29
+ wiredDock: null,
30
+ documentWired: false,
31
+ }));
32
+ }
33
+
34
+ /** The width of a box below which it is a phone's (the CSS's `@container corn-box (max-width: 767px)`) */
35
+ const PHONE_WIDTH = 768;
36
+
37
+ /**
38
+ * Whether the instance is laid out as a phone: the window's width on cornfield's page (PHONE_QUERY), or, where the instance has a box of its own
39
+ * (`setPhoneBox`: the one-tag review in another app's page), that box's width, which is what the stylesheets' container queries ask
40
+ */
41
+ export const isPhone = (inst) => {
42
+ const { box } = sheetsOf(inst);
43
+ if (box) return box.isConnected && box.clientWidth > 0 && box.clientWidth < PHONE_WIDTH;
44
+ return !!(inst.win && typeof inst.win.matchMedia === 'function' && inst.win.matchMedia(PHONE_QUERY).matches);
45
+ };
46
+
47
+ /** The element the dock sits in (the map's stage), or the canvas's parent */
48
+ export const stageOf = (inst, S) => (S.dock && S.dock.parentElement) || (inst.state.canvas ? inst.state.canvas.parentElement : null);
49
+
50
+ /**
51
+ * The height of the map the sheets hide, in px: the dock's height on a phone, 0 anywhere else.
52
+ * Also written to `state.coveredBottom` and to `--hx-covered` on the stage. Without a dock on the
53
+ * page it returns what `state.coveredBottom` holds.
54
+ */
55
+ export function measureCovered(inst) {
56
+ const S = sheetsOf(inst);
57
+ const { state } = inst;
58
+ if (!S.dock || !S.dock.isConnected) return state.coveredBottom || 0;
59
+ const covered = isPhone(inst) ? Math.round(S.dock.offsetHeight || 0) : 0;
60
+ state.coveredBottom = covered;
61
+ const stage = stageOf(inst, S);
62
+ if (stage) stage.style.setProperty('--hx-covered', `${covered}px`);
63
+ if (covered !== S.lastCovered) {
64
+ S.lastCovered = covered;
65
+ S.listeners.forEach((fn) => fn());
66
+ }
67
+ return covered;
68
+ }
69
+
70
+ /**
71
+ * The part of the map nothing covers, in the canvas's own CSS px: what the camera should frame a node into.
72
+ * On a phone the dock's sheets cover the bottom; from 768px the proposal bar covers the top (and the change list it grows to hold),
73
+ * the node panel the right, the Work panel and the review column the left and the scenario player the bottom. Without a layout (no page) it is the whole canvas.
74
+ * @returns {{ x: number, y: number, width: number, height: number }}
75
+ */
76
+ export function visibleMapRect(inst) {
77
+ const { state } = inst;
78
+ const covers = { top: 0, bottom: 0, left: 0, right: 0 };
79
+ const canvas = state.canvas;
80
+ const shown = (el) => !!el && !el.hidden && el.isConnected;
81
+ if (isPhone(inst)) covers.bottom = measureCovered(inst) + 8;
82
+ else if (canvas && typeof canvas.getBoundingClientRect === 'function') {
83
+ const c = canvas.getBoundingClientRect();
84
+ const bar = inst.el('proposal-bar');
85
+ if (shown(bar)) covers.top = Math.max(0, bar.getBoundingClientRect().bottom - c.top) + 8;
86
+ const drawer = inst.el('spec-drawer');
87
+ if (shown(drawer) && drawer.classList.contains('drawer-open')) covers.right = drawer.offsetWidth; // its width, not its box: it slides in
88
+ const forge = inst.el('forge-panel');
89
+ if (shown(forge) && forge.classList.contains('forge-open')) covers.left = forge.offsetWidth;
90
+ // the review column (review-column.js) is docked on the left under the bar: its right edge is what it covers, past the Work panel's when both are open
91
+ const column = inst.el('review-column');
92
+ if (shown(column)) covers.left = Math.max(covers.left, Math.max(0, column.getBoundingClientRect().right - c.left) + 8);
93
+ const player = inst.root ? inst.root.querySelector('.hx-player') : null;
94
+ if (shown(player)) covers.bottom = Math.max(0, c.bottom - player.getBoundingClientRect().top) + 8;
95
+ }
96
+ return freeRect(state.width || 0, state.height || 0, covers);
97
+ }
@@ -21,7 +21,8 @@
21
21
 
22
22
  import { escapeHtml as escHtml } from '../../core/text.js';
23
23
  import { createPlayer, cameraFor, parseSpeed, SPEED_CHOICES, SPEED_KEY } from '../scenario.js';
24
- import { blastRadius, outageLayers, outageScenario } from '../outage-model.js';
24
+ import { blastRadius } from '../outage-model.js';
25
+ import { outageLayers, outageScenario } from '../outage-scenario.js';
25
26
  import { setLayer, clearStepLayers, LAYER_DEFS } from './layers.js';
26
27
  import { externalLayer } from '../cloud-model.js';
27
28
  import { layerOn, layersOf, projectLayerKey, shownByProposal } from '../layer-model.js';