@popcorn245/cornfield 0.44.0 → 0.46.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/config.js CHANGED
@@ -30,6 +30,7 @@
30
30
  * brand: {}, // { logo, wordmark, favicon, appName, color, background }: a repo's own logo and name, images from the repo (docs/config.md#brand)
31
31
  * layers: {}, // { add: [{ key, label, desc?, match }], off: [keys], order: [keys] }: a repo's own layers in the Layers menu, as data (docs/config.md#layers)
32
32
  * strings: {}, // { approve: 'Ship it', … }: a repo's own words for the visible labels, plain text (core/strings.js, docs/theming.md#words)
33
+ * embed: { origins: [] }, // exact origins of sibling apps that may read, and decide a review, as the signed-in maintainer (docs/embedding.md)
33
34
  * proxy: {}, // { '/api/': 'http://127.0.0.1:3245' }: same-origin paths for a live source
34
35
  * importMap: {}, // bare imports a repo-local browser module needs: { name: '/repo/path.js' }
35
36
  * dataDir: null, // where cornfield keeps its own state (reviews; the SQLite file in v1)
@@ -176,6 +177,7 @@ export const DEFAULTS = Object.freeze({
176
177
  brand: { logo: null, wordmark: null, favicon: null, appName: null, color: null, background: null },
177
178
  strings: {},
178
179
  layers: { add: [], off: [], order: [] },
180
+ embed: { origins: [] },
179
181
  proxy: {},
180
182
  importMap: {},
181
183
  dataDir: null,
@@ -208,6 +210,58 @@ const isForgeOrigin = (url) => {
208
210
  } catch { return false; }
209
211
  };
210
212
 
213
+ /** The names a plain `http` origin may have: this machine's own (`localhost`, any `*.localhost`, `127.0.0.1`, `[::1]`) */
214
+ const isLoopbackName = (host) => host === 'localhost' || host.endsWith('.localhost') || host === '127.0.0.1' || host === '[::1]';
215
+ const EMBED_ORIGIN = /^(https?):\/\/([A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*|\[[0-9A-Fa-f:.]+\])(?::(\d{1,5}))?$/i;
216
+ /** The most origins `embed.origins` may list: each one is trusted with the maintainer's session, so the list is short on purpose */
217
+ export const MAX_EMBED_ORIGINS = 20;
218
+
219
+ /**
220
+ * An `embed.origins` entry as one canonical origin (`https://tasks.example.com`, `http://localhost:5173`), or what is wrong with it, in words.
221
+ * Exact only: a scheme, a host and an optional port; no path (not even a trailing slash), query, fragment or user name, and no wildcard.
222
+ * `https` only, except `http` for this machine's own names. The scheme and host are lowercased and a default port is dropped, so the same origin
223
+ * written two ways is one entry. A host the URL parser would rewrite (`https://2130706433`, `https://0x7f.1`) is refused.
224
+ * @param {unknown} value
225
+ * @returns {{ origin: string } | { problem: string }}
226
+ */
227
+ export function embedOrigin(value) {
228
+ if (typeof value !== 'string' || value === '') return { problem: 'is an origin like https://tasks.example.com, as text.' };
229
+ if (value.includes('*')) return { problem: `"${value}" has a wildcard: list each origin exactly, like https://tasks.example.com.` };
230
+ if (/\s/.test(value) || value.length > 300) return { problem: `"${value.slice(0, 80)}" is not an origin: no spaces, and at most 300 characters.` };
231
+ if (value.includes('\\')) return { problem: `"${value}" has a backslash: write the origin with forward slashes, like https://tasks.example.com.` };
232
+ if (value.includes('@')) return { problem: `"${value}" has a user name: an origin is a scheme, a host and a port, like https://tasks.example.com.` };
233
+ if (!/^https?:\/\//i.test(value)) return { problem: `"${value}" has no https:// in front: write the whole origin, like https://tasks.example.com.` };
234
+ if (/^https?:\/\/[^/?#]*[/?#]/i.test(value)) return { problem: `"${value}" has a path, query or fragment (a trailing slash counts): list the origin only, like https://tasks.example.com.` };
235
+ const m = EMBED_ORIGIN.exec(value);
236
+ if (!m) return { problem: `"${value}" is not an origin: a scheme, a host name (or a bracketed IPv6 address) and an optional port, like https://tasks.example.com.` };
237
+ const [, scheme, host, port] = m;
238
+ if (port !== undefined && (String(Number(port)) !== port || Number(port) < 1 || Number(port) > 65535)) return { problem: `"${value}" has a port that is not a number from 1 to 65535.` };
239
+ let u;
240
+ try { u = new URL(value.toLowerCase()); } catch { return { problem: `"${value}" is not a URL the browser would read as written.` }; }
241
+ if (u.hostname !== host.toLowerCase()) return { problem: `"${value}" would be read as ${u.hostname}: write the host the way a browser shows it.` };
242
+ if (scheme.toLowerCase() === 'http' && !isLoopbackName(u.hostname)) return { problem: `"${value}" is plain http: only https, or http for localhost, a *.localhost name, 127.0.0.1 or [::1], because the maintainer's session would otherwise be offered to a page that travels in the clear.` };
243
+ return { origin: u.origin };
244
+ }
245
+
246
+ /** What is wrong with `embed`, in words: only `origins`, a short list of exact origins, none twice */
247
+ function embedProblems(e) {
248
+ const out = [];
249
+ if (e === undefined || e === null) return out;
250
+ if (!isObject(e)) return ['"embed" is { origins: ["https://tasks.example.com"] }.'];
251
+ for (const k of Object.keys(e)) if (k !== 'origins') out.push(`embed.${k}: the only key is origins.`);
252
+ if (e.origins === undefined) return out;
253
+ if (!Array.isArray(e.origins)) return [...out, 'embed.origins is a list of origins, like ["https://tasks.example.com"].'];
254
+ if (e.origins.length > MAX_EMBED_ORIGINS) out.push(`embed.origins lists ${e.origins.length} origins; at most ${MAX_EMBED_ORIGINS}: each one is trusted with the maintainer's session.`);
255
+ const seen = new Set();
256
+ e.origins.forEach((o, i) => {
257
+ const r = embedOrigin(o);
258
+ if ('problem' in r) out.push(`embed.origins[${i}] ${r.problem}`);
259
+ else if (seen.has(r.origin)) out.push(`embed.origins[${i}] "${o}" is listed twice.`);
260
+ else seen.add(r.origin);
261
+ });
262
+ return out;
263
+ }
264
+
211
265
  /**
212
266
  * What is wrong with a config object (as the file exports it, before defaults).
213
267
  * @param {any} c
@@ -369,6 +423,7 @@ export function configProblems(c) {
369
423
  out.push(...brandProblems(c.brand));
370
424
  out.push(...stringsProblems(c.strings));
371
425
  out.push(...layersProblems(c.layers));
426
+ out.push(...embedProblems(c.embed));
372
427
  if (c.proxy !== undefined) {
373
428
  if (!isObject(c.proxy)) out.push('"proxy" is { "/path/": "http://upstream" }.');
374
429
  else for (const [p, t] of Object.entries(c.proxy)) {
@@ -559,6 +614,8 @@ export async function loadConfig(root, { env = process.env, file } = {}) {
559
614
  config.brand = { ...DEFAULTS.brand, ...(raw.brand || {}) };
560
615
  config.strings = { ...(raw.strings || {}) };
561
616
  config.layers = clientLayers(raw.layers); // checked above: only the known keys, as plain data
617
+ // The origins that may embed this server, as canonical origins (checked above): [] unless the file lists some
618
+ config.embed = { origins: (Array.isArray(raw.embed?.origins) ? raw.embed.origins : []).map((o) => /** @type {{ origin: string }} */ (embedOrigin(o)).origin) };
562
619
  // `threads: false` stays false; an object is read over the default
563
620
  config.threads = raw.threads === false ? false : { ...DEFAULTS.threads, ...(raw.threads || {}) };
564
621
  // `hookPoll: false` is `{ specs: false }`; an object is read over the default
package/core/contrast.js CHANGED
@@ -26,7 +26,7 @@ import { MAX_THEME_BYTES, cssProblems, withoutComments } from './theme.js';
26
26
  import { MIN_SHAPE_DELTA_E, NODE_SHAPES, NODE_THEMES } from './schema.js';
27
27
  import { deltaE2000 } from './delta-e.js';
28
28
  import { LAYER_KEY_RE, MAX_KEY, mapFillNames, parseKindToken } from './layers.js';
29
- import { DIFF_MARK_COLORS, DIFF_LABEL_ALPHA, markOpacity } from '../explorer/diff-marks.js';
29
+ import { DIFF_MARK_COLORS, DIFF_LABEL_ALPHA, GREY_ALPHA, GREY_LABEL_ALPHA, GREY_MIN_RATIO, markOpacity } from '../explorer/diff-marks.js';
30
30
  import { lightColor } from '../explorer/theme-model.js';
31
31
 
32
32
  /** WCAG 2.1 AA: text, and large text and user-interface parts */
@@ -586,6 +586,15 @@ function mapFindings(props, theme, mode, grounds, extra = []) {
586
586
  out.push({ ...base, fg: '--corn-map-stroke', bg: weakest.on, min: MAP_FILL_MIN, kind: 'ui', use: `the outline that carries ${what}, which is ${fmt(f.ratio)} on its own`, fgValue: onGround.fgValue, bgValue: weakest.value, ratio: weakest.r });
587
587
  }
588
588
  // Labels are text: the colour against the ground, and against the halo under it (the halo is the ground's own colour at `auto`)
589
+ // What a review greys, when the theme sets the colour (issue #232): readable as a colour, and at its faded strength still told from the ground. `auto` is each tone with its hue taken away (a test holds it)
590
+ const grey = mapToken(props, '--corn-map-grey');
591
+ if (grey.problem) out.push({ ...base, fg: '--corn-map-grey', bg: GROUND, min: GREY_MIN_RATIO, kind: 'ui', use: 'a node the review greys', problem: grey.problem });
592
+ else if (grey.color) {
593
+ const alphaText = props.has('--corn-map-grey-alpha') ? substitute(props.get('--corn-map-grey-alpha'), props).trim() : '';
594
+ const a = /^\d*\.?\d+$/.test(alphaText) && +alphaText >= 0.1 && +alphaText <= 1 ? +alphaText : GREY_ALPHA;
595
+ const w = worstOnGrounds([grey.color[0], grey.color[1], grey.color[2], grey.color[3] * a], grounds);
596
+ out.push({ ...base, fg: '--corn-map-grey', bg: GROUND, min: GREY_MIN_RATIO, kind: 'ui', use: `a node the review greys, left at ${Math.round(a * 100)}% opacity`, fgValue: w.fgValue, bgValue: w.bgValue, ratio: w.ratio, ...(w.image ? { groundImage: true } : {}) });
597
+ }
589
598
  const label = mapToken(props, '--corn-map-label');
590
599
  const haloTok = mapToken(props, '--corn-map-label-halo');
591
600
  const labelColor = label.color || (label.problem ? null : readColor(mode === 'light' ? lightColor('#f8fafc') : '#f8fafc'));
@@ -670,6 +679,8 @@ function mapGrounds(grounds, base, props) {
670
679
  const DIFF_MAP_PAIRS = (mode) => [
671
680
  ...['added', 'changed', 'removed', 'edit'].map((m) => [`--corn-map-${m}`, DIFF_MARK_COLORS[mode][m], markOpacity(m), `the ${m} mark on the map, drawn at ${Math.round(markOpacity(m) * 100)}% opacity`]),
672
681
  ['--corn-map-label', mode === 'light' ? lightColor('#f8fafc', 'text') : '#f8fafc', DIFF_LABEL_ALPHA, `a label the diff dims, drawn at ${Math.round(DIFF_LABEL_ALPHA * 100)}% opacity`],
682
+ // a label a review greys (issue #232), where it is fainter than a dimmed one (the dark ground)
683
+ ...(GREY_LABEL_ALPHA[mode] !== DIFF_LABEL_ALPHA ? [['--corn-map-label', mode === 'light' ? lightColor('#f8fafc', 'text') : '#f8fafc', GREY_LABEL_ALPHA[mode], `a label a review greys, drawn at ${Math.round(GREY_LABEL_ALPHA[mode] * 100)}% opacity`]] : []),
673
684
  ];
674
685
 
675
686
  function diffMapFindings(props, theme, mode, grounds, base) {
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * @module core/map-tokens
3
3
  *
4
- * The map's non-colour tokens, as `cornfield validate` reads them: `--corn-map-font`, `--corn-map-edge-width`, `--corn-map-glow` and `--corn-map-label-min`. The
4
+ * The map's non-colour tokens, as `cornfield validate` reads them: `--corn-map-font`, `--corn-map-edge-width`, `--corn-map-glow`, `--corn-map-label-min` and `--corn-map-grey-alpha`. The
5
5
  * map reads each with the same parser (explorer/map-style.js `readMapTokens`), and one it cannot read is drawn as if it were `auto`; this
6
6
  * says so before the theme ships, as a warning naming the token, the theme, the level and what it may hold (docs/theming.md, The map).
7
7
  */
@@ -10,12 +10,13 @@ import { declaredProps, expand, projectGroupOf, resolveProps, themesToCheck } fr
10
10
  import { iconKeyShape, parseKindToken } from './layers.js';
11
11
  import { readColor } from './color.js';
12
12
  import { MAX_NODE_COLOR_CHARS } from '../explorer/css-color.js';
13
- import { EDGE_WIDTH_TOKEN, FONT_TOKEN, GLOW_TOKEN, LABEL_MIN_TOKEN, MAX_EDGE_WIDTH, MAX_GLOW, MAX_LABEL_MIN, readMapTokens } from '../explorer/map-style.js';
13
+ import { EDGE_WIDTH_TOKEN, FONT_TOKEN, GLOW_TOKEN, GREY_ALPHA_TOKEN, LABEL_MIN_TOKEN, MAX_EDGE_WIDTH, MAX_GLOW, MAX_LABEL_MIN, readMapTokens } from '../explorer/map-style.js';
14
14
 
15
15
  const WANTS = {
16
16
  [FONT_TOKEN]: ['font', 'a list of font families (quoted names or plain words, at most 8; no url(), and no punctuation but commas and quotes)'],
17
17
  [EDGE_WIDTH_TOKEN]: ['edgeWidth', `a width in px over 0 and at most ${MAX_EDGE_WIDTH}`],
18
18
  [GLOW_TOKEN]: ['glow', `a factor from 0 (no glow) to ${MAX_GLOW}`],
19
+ [GREY_ALPHA_TOKEN]: ['greyAlpha', 'a number from 0.1 to 1 (0.45 is the default; a greyed node under 0.1 would vanish)'],
19
20
  [LABEL_MIN_TOKEN]: ['labelMin', `a size in px from 9 to ${MAX_LABEL_MIN} (11px is the default and the least it draws at; under 9px is ignored)`],
20
21
  };
21
22
 
package/core/strings.js CHANGED
@@ -39,6 +39,9 @@ export const STRINGS = Object.freeze({
39
39
  undo: 'Undo',
40
40
  approved: 'Approved',
41
41
  myEdits: 'My edits',
42
+ showWholeMap: 'Show the whole map',
43
+ wholeMap: 'Whole map',
44
+ hiddenWhileReviewing: 'hidden while reviewing',
42
45
  yourEdits: 'Your edits',
43
46
  cancelLanding: 'Cancel landing',
44
47
  queueIt: 'Queue it',
package/explorer/check.js CHANGED
@@ -23,7 +23,8 @@
23
23
  */
24
24
 
25
25
  import { state, escHtml } from './state.js';
26
- import { toggleLayer } from './layers.js';
26
+ import { setLayer } from './layers.js';
27
+ import { layersOf } from './layer-model.js';
27
28
  import { mapIndex, personaLabel, planChecks, runChecks, stepVerdict, verdictWords } from './check-model.js';
28
29
  import { cornState } from './corn-state.js';
29
30
 
@@ -53,7 +54,7 @@ export function openChecks(scenario, onChange = () => {}) {
53
54
  if (current && current.scenario && scenario && current.scenario.id === scenario.id) { current.onChange = onChange; replan(scenario); return; }
54
55
  closeChecks();
55
56
  current = { scenario: null, as: null, nodes: null, plan: null, answer: { status: 'idle' }, controller: null, onChange };
56
- if (namesActor(scenario) && state.activeLayers.persona !== true) toggleLayer('persona');
57
+ if (namesActor(scenario) && layersOf(state).persona !== true) setLayer('persona', true, { scenario: true });
57
58
  replan(scenario);
58
59
  }
59
60
 
@@ -26,6 +26,18 @@ export const markOpacity = (mark) => EDGE_MIN_ALPHA * (mark === 'removed' || mar
26
26
  /** The opacity of the label of a node a diff dims (the node itself is at PROPOSAL_DIM_ALPHA) */
27
27
  export const DIFF_LABEL_ALPHA = 0.6;
28
28
 
29
+ /**
30
+ * How much of a node a review greys (issue #232) is left (`--corn-map-grey-alpha: auto`), and the least a greyed disc may differ from the ground it sits on
31
+ * (core/contrast.js checks a theme's `--corn-map-grey` against it): faded, but the map still reads as a map. Its label is at GREY_LABEL_ALPHA (below).
32
+ */
33
+ export const GREY_ALPHA = 0.45;
34
+ export const GREY_MIN_RATIO = 1.5;
35
+ /**
36
+ * The opacity of a greyed node's label, by ground: near the dimmed-label floor (4.4:1 on the default light ground, 5.2:1 on the dark, 4.75:1 on retro's navy),
37
+ * so the change's labels are the strongest text on the map. On the dark ground DIFF_LABEL_ALPHA would leave it near 7:1. core/contrast.js checks both.
38
+ */
39
+ export const GREY_LABEL_ALPHA = Object.freeze({ light: DIFF_LABEL_ALPHA, dark: 0.5 });
40
+
29
41
  /** How a mark differs without colour: the ring's dash (`null` is solid) and whether it is struck through. Four marks, four styles. */
30
42
  export const MARK_SHAPES = Object.freeze({
31
43
  added: Object.freeze({ ringDash: Object.freeze([5, 4]), edgeDash: Object.freeze([7, 5]), strike: false }), // a dashed ring
@@ -1462,7 +1462,7 @@ a.hx-proposal-source:focus-visible { outline: var(--corn-focus-width) solid var(
1462
1462
  @media (prefers-reduced-motion: reduce) { .hx-hold { display: none; } .hx-hold-fill { animation: none; } } /* only the words count down */
1463
1463
  .hx-rc-sub { margin: var(--corn-space-2) 0 var(--corn-space-1); font-size: var(--corn-text-sm); font-weight: 600; color: var(--corn-text); }
1464
1464
  .hx-proposal-yours { display: inline-flex; align-items: center; gap: var(--corn-space-1); color: var(--corn-text-2); }
1465
- .hx-proposal-tools [aria-pressed="false"] { opacity: 0.8; }
1465
+ .hx-proposal-tools [aria-pressed="false"]:not([data-corn="whole-map"]) { opacity: 0.8; } /* My edits off; "Whole map" off is the review's own view, not a faded choice */
1466
1466
  .hx-whatif-row [aria-disabled="true"] { opacity: 0.55; cursor: default; }
1467
1467
  .hx-runner-dot { display: inline-block; width: 8px; height: 8px; margin-left: var(--corn-space-1); border-radius: 50%; background: var(--corn-warn); vertical-align: middle; }
1468
1468
  .hx-runner-dot[hidden] { display: none; }
@@ -1499,3 +1499,14 @@ a.hx-proposal-source:focus-visible { outline: var(--corn-focus-width) solid var(
1499
1499
  /* (the waiting line's Answer is in the proposal bar too, so it is the bar's height; it is a strip's action elsewhere, at its own size) */
1500
1500
  :where(.hx-forge-head, .hx-player-controls, .hx-player-as, .hx-proposal-bar .hx-waiting-line) .hx-btn, :where(.hx-header) .hx-live-chip { height: var(--hx-control-h); }
1501
1501
  /* ==== end of the panel head and control height ============================================================================================ */
1502
+
1503
+ /* ---- The review narrows the map to the change (issue #232) ---- */
1504
+ /* A Layers row the review hid: its name with "hidden while reviewing" under it */
1505
+ .hx-toggle-text { display: flex; flex-direction: column; align-items: flex-start; min-width: 0; }
1506
+ /* On a desk "Whole map" sits on the title's row, beside the source, so the row of counts, Compare, Edit and More keeps the one line it had: at the
1507
+ control height, drawn over the row's own 24px (the source's; --corn-space-6) so the bar is no taller. On a phone it stays with Edit, 44px */
1508
+ @media (min-width: 768px) {
1509
+ .hx-proposal-tools { display: contents; }
1510
+ .hx-proposal-name, .hx-proposal-source { order: -2; }
1511
+ :where(.hx-proposal-head) [data-corn="whole-map"] { order: -1; margin-block: calc((var(--corn-space-6) - var(--hx-control-h)) / 2); } /* the row is 24px (--corn-space-6 by default), the source's height */
1512
+ }
package/explorer/flows.js CHANGED
@@ -15,6 +15,7 @@
15
15
  import { state, nameOf, escHtml } from './state.js';
16
16
  import { themed } from './theme-model.js';
17
17
  import { capped } from './capped.js';
18
+ import { layersOf } from './layer-model.js';
18
19
 
19
20
  export const FLOW_STYLES = {
20
21
  outbox: { color: '#f59e0b', label: 'Outbox → API (writes)' },
@@ -132,7 +133,7 @@ export function buildDataFlow(nodes, edges) {
132
133
  export function renderFlowLegend() {
133
134
  const el = document.getElementById('flow-legend');
134
135
  if (!el) return;
135
- const { activeLayers } = state;
136
+ const activeLayers = layersOf(state);
136
137
  if (activeLayers.flow === false && activeLayers.table === false) { el.innerHTML = ''; el.hidden = true; return; }
137
138
  el.hidden = false;
138
139
  const row = (swatch, text) => `<div class="hx-legend-row"><span class="hx-legend-swatch">${swatch}</span><span>${text}</span></div>`;
@@ -74,6 +74,7 @@ import { trapTab } from './focusables.js';
74
74
  import { isPhone, registerSheet, expandSheet, collapseSheet, showSheet, refreshStubs } from './sheets.js';
75
75
  import { relativeTime } from './review-model.js';
76
76
  import { LAYER_DEFS, toggleLayer } from './layers.js';
77
+ import { layerOn } from './layer-model.js';
77
78
  import { WORK_URL, groupWork, filterGroups, groupWords, workStatus, markWords } from './agents-model.js';
78
79
  import {
79
80
  RUNS_URL, runsUrl, stopUrl, runOnThread, threadRunWords, runOnPull, pullRunWords, canRetry, retryRefs, retryWords, limitsFromFields, defaultLimits, LIMIT_KEYS, briefUrl, answerUrl, answerBody, answerWordsFor, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, runnerState, runnerWords, triggerNotice, totalsLines, handLines, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
@@ -494,7 +495,7 @@ export function selectDeploy(id) {
494
495
  const turnedOn = [];
495
496
  for (const n of litForDeploy(found, state.nodes).nodes) {
496
497
  const layer = LAYER_DEFS.find((l) => l.key === n.type);
497
- if (layer && state.activeLayers[layer.key] === false) { toggleLayer(layer.key); turnedOn.push(layer.label); }
498
+ if (layer && !layerOn(state, layer.key)) { toggleLayer(layer.key); turnedOn.push(layer.label); }
498
499
  }
499
500
  relight();
500
501
  $('forge-panel').querySelector('.hx-forge-body').scrollTop = 0; // the deploy's nodes are what was asked for, not the row that was tapped
@@ -216,6 +216,9 @@
216
216
  </div>
217
217
  <div class="hx-proposal-tools">
218
218
  <!-- Shown only while there are what-if edits: off, the map is the proposal as written; the edits are kept and still go with a review (whatif.js) -->
219
+ <!-- The review narrows the map to the change; this puts the whole map back, as Diff always was (layers.js setWholeMap). Off at every opening -->
220
+ <!-- Its words are "Whole map", which read right pressed or not; its name and tooltip are the full "Show the whole map". On a desk it sits beside the title, so the bar keeps its rows (explorer.css) -->
221
+ <button data-corn="whole-map" data-corn-kind="secondary" type="button" id="proposal-whole" class="hx-btn" data-action="proposal-whole" aria-pressed="false" aria-label="Show the whole map" title="Show the whole map" data-peek-ok data-corn-string="wholeMap" data-corn-string-aria-label="showWholeMap">Whole map</button>
219
222
  <button data-corn-kind="secondary" type="button" id="proposal-myedits" class="hx-btn" aria-pressed="true" data-peek-ok data-corn-string="myEdits" hidden>My edits</button>
220
223
  <button data-corn-kind="secondary" type="button" id="proposal-edit" class="hx-btn" aria-expanded="false" aria-controls="whatif" title="Try a change: add a node or an edge, reword a scenario">Edit</button>
221
224
  </div>
@@ -69,8 +69,10 @@ const REF = 100;
69
69
  /** The grid the placing looks for neighbours in (px) */
70
70
  const CELL = 64;
71
71
 
72
- /** Priority tiers, best first */
73
- const TIER = { selected: 0, current: 1, match: 2, lit: 3, marked: 4, hub: 5, rest: 6 };
72
+ /** Priority tiers, best first. `greyed`: a node a review greys (issue #232), after everything else, a hub's title included */
73
+ const TIER = { selected: 0, current: 1, match: 2, lit: 3, marked: 4, hub: 5, rest: 6, greyed: 7 };
74
+ /** A greyed node's label keeps this many of its own heights clear on every side: the change's labels stand out, and the greyed map is named sparsely */
75
+ export const GREYED_ROOM = 1.5;
74
76
 
75
77
  /**
76
78
  * The smallest label size on screen (px) for a theme's `--corn-map-label-min` (a number, or null for `auto`): a theme may raise the 11 px,
@@ -82,14 +84,16 @@ export const labelMinPx = (value) => (Number.isFinite(value) && value >= LABEL_M
82
84
  /** The smallest label size on screen (px) for a scene: the theme's `--corn-map-label-min`, never under 11 */
83
85
  export const labelMinOf = (scene) => labelMinPx(scene.labelMin);
84
86
 
85
- const isHub = (node) => LANDMARK_TYPES.includes(node.type);
87
+ /** A cluster's title: bigger and bold, unless a review greys it (then it is a plain label, placed last) */
88
+ const isHub = (node) => LANDMARK_TYPES.includes(node.type) && !node.greyed;
86
89
 
87
90
  const tierOf = (node, focused) => (node.selected ? TIER.selected
88
91
  : node.current ? TIER.current
89
92
  : node.match ? TIER.match
90
93
  : focused && node.connected ? TIER.lit
91
94
  : (node.mark && node.mark !== 'none') || (node.labelKeep && !isHub(node)) ? TIER.marked
92
- : isHub(node) ? TIER.hub : TIER.rest);
95
+ : node.greyed ? TIER.greyed
96
+ : isHub(node) ? TIER.hub : TIER.rest);
93
97
 
94
98
  /**
95
99
  * Which node labels fit at `zoom`, and where. The whole map, not the view: a box is in zoom-scaled world coordinates (`x * zoom`, no
@@ -118,15 +122,16 @@ export function placeLabels(scene, zoom, opts = {}) {
118
122
  const gap = Math.max(GAP_PX, GAP_PX * zoom);
119
123
  for (const { node, index, tier } of cands) {
120
124
  const hub = isHub(node);
121
- const bold = !!node.labelBold || hub;
125
+ const bold = !node.greyed && (!!node.labelBold || hub); // a greyed node's label is plain, whatever asked for bold
122
126
  const px = Math.max(hub ? min + HUB_LABEL_EXTRA_PX : min, node.labelSize * zoom);
123
127
  const w = measure ? (measure(node.label, REF, bold) * px) / REF : node.label.length * px * GLYPH;
124
128
  const cx = node.x * zoom;
125
129
  const baseline = node.y * zoom + node.r * zoom + gap + px;
126
130
  const l = cx - w / 2, r = cx + w / 2, t = baseline - px * ASCENT, b = baseline + px * DESCENT;
127
- // Touching a placed box, give or take LABEL_PAD: skipped
128
- const i0 = Math.floor((l - LABEL_PAD) / CELL), i1 = Math.floor((r + LABEL_PAD) / CELL);
129
- const j0 = Math.floor((t - LABEL_PAD) / CELL), j1 = Math.floor((b + LABEL_PAD) / CELL);
131
+ // Touching a placed box, give or take LABEL_PAD (a greyed node's: GREYED_ROOM of its heights): skipped
132
+ const pad = tier === TIER.greyed ? LABEL_PAD + px * GREYED_ROOM : LABEL_PAD;
133
+ const i0 = Math.floor((l - pad) / CELL), i1 = Math.floor((r + pad) / CELL);
134
+ const j0 = Math.floor((t - pad) / CELL), j1 = Math.floor((b + pad) / CELL);
130
135
  let hit = false;
131
136
  for (let i = i0; i <= i1 && !hit; i++) {
132
137
  for (let j = j0; j <= j1 && !hit; j++) {
@@ -134,7 +139,7 @@ export function placeLabels(scene, zoom, opts = {}) {
134
139
  if (!cell) continue;
135
140
  for (let k = 0; k < cell.length; k++) {
136
141
  const o = cell[k];
137
- if (l - LABEL_PAD < o.r && r + LABEL_PAD > o.l && t - LABEL_PAD < o.b && b + LABEL_PAD > o.t) { hit = true; break; }
142
+ if (l - pad < o.r && r + pad > o.l && t - pad < o.b && b + pad > o.t) { hit = true; break; }
138
143
  }
139
144
  }
140
145
  }
@@ -9,10 +9,13 @@
9
9
  * - `shownByProposal(state, node)`: a node the open proposal touches is always drawn, whatever its layer says, so a review never hides its
10
10
  * own change.
11
11
  *
12
+ * - `touchedLayerKeys`, `reviewLayers`, `layersOf`, `layerOn`, `reviewHides` (issue #232): while a proposal is under review the map is narrowed to the
13
+ * change. The layers the proposal does not touch are off for the review; the viewer's own state (`state.activeLayers`) is never written.
14
+ *
12
15
  * The matching itself is core/layers.js (data only); this file only hands it the map's ownership line.
13
16
  */
14
17
 
15
- import { kindLetters, layerKeyOf, parentIndex, projectLayerOf } from '../core/layers.js';
18
+ import { STARTING_LAYERS, kindLetters, layerKeyOf, parentIndex, projectLayerOf } from '../core/layers.js';
16
19
  import { touchedIds } from './proposal-model.js';
17
20
 
18
21
  /** Asks the ownership line of the map the state holds, only when a layer matches by `parent` */
@@ -57,3 +60,90 @@ export function lettersOf(state, node) {
57
60
  const t = hit.map.get(node.type);
58
61
  return (t && t.get(node.kind)) || '';
59
62
  }
63
+
64
+ // ---------------------------------------------------------------------------
65
+ // The review narrows the map to the change (issue #232)
66
+ // ---------------------------------------------------------------------------
67
+
68
+ /** Layers a touched layer cannot show without (scene.js `layerShows`): Core needs Packages, Stores and ROM need Data Flow */
69
+ const NEEDS = Object.freeze({ core: ['pkg'], store: ['flow'], rom: ['flow'] });
70
+ const marked = (item) => !!item && !!item.mark && item.mark !== 'none';
71
+
72
+ /**
73
+ * The keys of the layers a proposal touches: the layer of every node it marks (added, changed, removed, or a what-if edit) and of both ends of an
74
+ * edge it marks, the Data Flow overlay when a marked edge is a flow, the Runs overlay when a touched node has a run in flight, and what a touched
75
+ * layer cannot be drawn without (`NEEDS`). The root has no layer. Pure: the map, what the layers are, the runs.
76
+ * @param {{ nodes: {id: string, mark?: string}[], edges: {from: string, to: string, kind?: string, mark?: string}[], rowOf: (node: object) => string | null, flight?: { has(id: string): boolean } | null }} map
77
+ * @returns {Set<string>}
78
+ */
79
+ export function touchedLayerKeys({ nodes, edges, rowOf, flight = null }) {
80
+ const { touched } = touchedIds(nodes, edges);
81
+ const keys = new Set();
82
+ for (const n of nodes) {
83
+ if (!touched.has(n.id)) continue;
84
+ const key = rowOf(n);
85
+ if (key) { keys.add(key); for (const need of NEEDS[key] || []) keys.add(need); }
86
+ if (flight && flight.has(n.id)) keys.add('runs');
87
+ }
88
+ for (const e of edges) if (marked(e) && e.kind === 'flow') keys.add('flow');
89
+ return keys;
90
+ }
91
+
92
+ /**
93
+ * The layers a review shows, from the viewer's own (`active`), as a new map. Untouched layers are off and touched ones on (a layer the viewer had
94
+ * off comes on for the review); then what the reviewer did by hand (`manual`) and what a playing scenario turned on (`step`). With `whole` the map
95
+ * is the viewer's as it always was, with only the hand and the scenario laid over it. `universe`: every layer key the menu knows.
96
+ * @param {{ active: Record<string, boolean>, touched: Set<string>, universe: Iterable<string>, review: { whole?: boolean, manual?: Record<string, boolean>, step?: Record<string, boolean> } }} a
97
+ * @returns {Record<string, boolean>}
98
+ */
99
+ export function reviewLayers({ active, touched, universe, review }) {
100
+ const out = { ...active };
101
+ if (!review.whole && touched.size) for (const key of universe) out[key] = touched.has(key); // a proposal that touches no layer has nothing to narrow the map to: it is left whole
102
+ Object.assign(out, review.manual || {}, review.step || {});
103
+ return out;
104
+ }
105
+
106
+ const layerKeysMemo = new WeakMap();
107
+ /** The touched layer keys of the open proposal's map: kept while the map, the runs and the layers' ownership are the same */
108
+ function touchedLayers(state) {
109
+ const nodes = state.nodes;
110
+ const edges = state.edges || [];
111
+ const flight = state.runsMap ? state.runsMap.flight : null;
112
+ const hit = layerKeysMemo.get(nodes);
113
+ if (hit && hit.edges === edges && hit.n === nodes.length && hit.e === edges.length && hit.flight === flight && hit.project === state.projectLayers) return hit;
114
+ const touched = touchedLayerKeys({ nodes, edges, rowOf: (n) => rowKeyOf(state, n), flight });
115
+ const universe = new Set([...STARTING_LAYERS.map((l) => l.key), ...(state.projectLayers || []).map((l) => l.key), ...nodes.map((n) => rowKeyOf(state, n)).filter(Boolean)]);
116
+ const made = { edges, n: nodes.length, e: edges.length, flight, project: state.projectLayers, touched, universe };
117
+ layerKeysMemo.set(nodes, made);
118
+ return made;
119
+ }
120
+
121
+ const layersMemo = new WeakMap();
122
+ /**
123
+ * The layers the map is drawn with: `state.activeLayers` itself with no review open, else the review's (`reviewLayers`). Every reader of a layer's
124
+ * state for what is drawn goes through this, so the review's hiding is decided in one place.
125
+ */
126
+ export function layersOf(state) {
127
+ const review = state.review;
128
+ if (!review || !state.proposal) return state.activeLayers;
129
+ const hit = layersMemo.get(review);
130
+ if (hit && hit.rev === review.rev && hit.version === state.sceneVersion && hit.active === state.activeLayers && hit.nodes === state.nodes) return hit.out;
131
+ const { touched, universe } = touchedLayers(state);
132
+ const out = reviewLayers({ active: state.activeLayers, touched, universe, review });
133
+ layersMemo.set(review, { rev: review.rev, version: state.sceneVersion, active: state.activeLayers, nodes: state.nodes, out });
134
+ return out;
135
+ }
136
+
137
+ /** Whether a layer is on for what is drawn (a layer with no entry is on, as the menu shows it) */
138
+ export const layerOn = (state, key) => layersOf(state)[key] !== false;
139
+
140
+ /** Whether the review hid this layer, which the viewer has on: the row says so, and the reviewer may turn it on for the review */
141
+ export function reviewHides(state, key) {
142
+ const r = state.review;
143
+ if (!r || !state.proposal || r.whole) return false;
144
+ if (state.activeLayers[key] === false || Object.hasOwn(r.manual || {}, key) || Object.hasOwn(r.step || {}, key)) return false;
145
+ return layersOf(state)[key] === false;
146
+ }
147
+
148
+ /** Whether the greying is on: a review is open, the whole map is not asked for, and the proposal involves something (a proposal that changes nothing greys nothing: scene.js, map-style.js) */
149
+ export const greying = (state) => !!state.review && !!state.proposal && !state.review.whole && touchedBy(state).size > 0;
@@ -15,7 +15,7 @@ import { themed } from './theme-model.js';
15
15
  import { onThemeChange } from './theme.js';
16
16
  import { NODE_THEMES } from '../core/schema.js';
17
17
  import { STARTING_LAYERS, clientLayers, kindLetters, orderRows, startingLayerOf } from '../core/layers.js';
18
- import { rowKeyOf, shownByProposal } from './layer-model.js';
18
+ import { layerOn, reviewHides, rowKeyOf, shownByProposal } from './layer-model.js';
19
19
  import { fillOfNode, groupOf, layerShows } from './scene.js';
20
20
  import { STROKE_TOKEN, cssColor, fillOf, getMapStyle, kindToken, onMapStyleChange, pageReader, setMapSubjects } from './map-style.js';
21
21
  import { over, parseColor, contrast } from '../core/color.js';
@@ -79,7 +79,8 @@ export function clickWithLegendMenu(target, act) {
79
79
 
80
80
  /** What a layer is when the viewer has not touched it: the config's `off`, else a starting layer's own default, else on */
81
81
  const defaultOf = (key) => (Object.hasOwn(state.layerDefaults, key) ? state.layerDefaults[key] : !STARTS_OFF.has(key));
82
- const isOn = (key) => state.activeLayers[key] !== false;
82
+ /** Whether a layer is on for what is drawn: the viewer's, or the review's while a proposal is under review (layer-model.js) */
83
+ const isOn = (key) => layerOn(state, key);
83
84
 
84
85
  const NO_COLOR = '#94a3b8';
85
86
  /** A colour as the dot's style may hold it: a hex or an rgb()/rgba() of numbers, else the plain grey. A node's colour is the map's data
@@ -299,11 +300,14 @@ export function renderLayerToggles() {
299
300
  const row = (layer) => {
300
301
  const on = isOn(layer.key);
301
302
  const shown = byProposal[layer.key] ? `<span class="hx-faint hx-layer-note" data-corn="layer-note">+${byProposal[layer.key]} shown by the proposal</span>` : '';
303
+ // A row the review hid says so under its name (there is no room beside it): it can still be turned on, for the review
304
+ const hid = !shown && counts[layer.key] && reviewHides(state, layer.key) ? `<span class="hx-faint hx-layer-note" data-corn="layer-note">${escHtml(t('hiddenWhileReviewing'))}</span>` : '';
305
+ const name = `<span class="hx-toggle-name">${escHtml(layer.label)}</span>`;
302
306
  return `
303
307
  <button type="button" class="hx-toggle-row${on ? '' : ' is-off'}" data-action="toggle-layer" data-layer="${escHtml(layer.key)}" aria-pressed="${on}" title="${escHtml(layer.desc)}" data-corn="row">
304
308
  <span class="hx-toggle-label">
305
309
  ${dot(swatch(layer.color), on, surface)}
306
- <span class="hx-toggle-name">${escHtml(layer.label)}</span>${layer.live ? '<span class="hx-live-tag" data-corn="live-tag">live</span>' : ''}
310
+ ${hid ? `<span class="hx-toggle-text">${name}${hid}</span>` : name}${layer.live ? '<span class="hx-live-tag" data-corn="live-tag">live</span>' : ''}
307
311
  </span>
308
312
  <span class="hx-toggle-meta">${shown}
309
313
  <span class="hx-count" data-corn="count">${(UNIT[layer.key] || String)(counts[layer.key] || 0)}</span>
@@ -336,7 +340,7 @@ export function renderEdgeKey() {
336
340
  export function renderCloudLegend() {
337
341
  const el = document.getElementById('cloud-legend');
338
342
  if (!el) return;
339
- if (state.activeLayers.cloud === false) { el.innerHTML = ''; el.hidden = true; return; }
343
+ if (!layerOn(state, 'cloud')) { el.innerHTML = ''; el.hidden = true; return; }
340
344
  el.hidden = false;
341
345
  el.innerHTML = `
342
346
  <div class="hx-menu-title" data-corn="menu-title"><span>Cloud: when an outage bites</span></div>
@@ -361,35 +365,98 @@ function say(text) {
361
365
  }
362
366
 
363
367
  /**
364
- * Turns a layer on or off. `viewer`: the person chose it in the menu, so it is kept in their browser; a layer another part of the app
365
- * turns on (a deploy that lights a stack) is not a choice of theirs and is not kept.
368
+ * Sets a layer on or off. `viewer`: the person chose it in the menu, so it is kept in their browser; a layer another part of the app
369
+ * turns on (a deploy that lights a stack) is not a choice of theirs and is not kept. While a proposal is under review the choice is the review's:
370
+ * kept for the review only (`state.review.manual`, or `.step` when a playing scenario needs the layer: `scenario`), never in `activeLayers` or the browser.
366
371
  */
367
- export function toggleLayer(key, { viewer = false } = {}) {
368
- const on = state.activeLayers[key] === false; // a layer with no entry yet is on, as the toggles show it
369
- state.activeLayers[key] = on;
370
- if (viewer) { keep(key, on); writeChanges(); }
372
+ export function setLayer(key, on, { viewer = false, scenario = false } = {}) {
373
+ const review = state.review && state.proposal ? state.review : null;
374
+ if (review) {
375
+ (scenario ? review.step : review.manual)[key] = on;
376
+ review.rev++;
377
+ } else {
378
+ state.activeLayers[key] = on;
379
+ if (viewer) { keep(key, on); writeChanges(); }
380
+ }
371
381
  changed();
372
382
  if (viewer) {
373
383
  const { layers, overlays } = layerRows();
374
384
  const layer = [...layers, ...overlays].find((l) => l.key === key);
375
385
  const n = state.nodes.filter((x) => isNodeVisible(x)).length;
376
- say(`${layer ? layer.label : key} ${on ? 'on' : 'off'}. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
386
+ say(`${layer ? layer.label : key} ${on ? 'on' : 'off'}${review ? ' for this review' : ''}. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
377
387
  }
378
388
  }
379
389
 
380
- /** All / None: every layer on or off, never an overlay; the root stays drawn */
390
+ /** Flips a layer (what a click on its row does); see `setLayer` */
391
+ export function toggleLayer(key, opts = {}) {
392
+ setLayer(key, !layerOn(state, key), opts);
393
+ }
394
+
395
+ /** All / None: every layer on or off, never an overlay; the root stays drawn. During a review it is the review's state that changes, not the viewer's */
381
396
  export function toggleAllLayers(on, { viewer = false } = {}) {
382
397
  const { layers } = layerRows();
383
398
  const keys = new Set([...LAYER_DEFS.filter((l) => !l.overlay).map((l) => l.key), ...state.projectLayers.map((l) => l.key), ...layers.map((l) => l.key)]);
384
- keys.forEach((k) => { state.activeLayers[k] = on; if (viewer) keep(k, on); });
385
- if (viewer) writeChanges();
399
+ const review = state.review && state.proposal ? state.review : null;
400
+ if (review) { keys.forEach((k) => { review.manual[k] = on; }); review.rev++; } else {
401
+ keys.forEach((k) => { state.activeLayers[k] = on; if (viewer) keep(k, on); });
402
+ if (viewer) writeChanges();
403
+ }
386
404
  changed();
387
405
  if (viewer) {
388
406
  const n = state.nodes.filter((x) => isNodeVisible(x)).length;
389
- say(`${on ? 'All' : 'No'} layers on. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
407
+ say(`${on ? 'All' : 'No'} layers on${review ? ' for this review' : ''}. ${n} ${n === 1 ? 'node' : 'nodes'} shown.`);
390
408
  }
391
409
  }
392
410
 
411
+ // ---------------------------------------------------------------------------
412
+ // The review narrows the map to the change (issue #232)
413
+ // The hiding is the review's, never the viewer's: `state.review` holds it (layer-model.js `layersOf` reads it), `activeLayers` and the saved choices are not touched.
414
+ // ---------------------------------------------------------------------------
415
+
416
+ /** A proposal is opened: a fresh review ("Show the whole map" off, nothing turned on by hand yet), also when one was already open */
417
+ export function beginReview() {
418
+ state.review = { whole: false, manual: {}, step: {}, rev: 0 }; // the map and the menu are drawn by the caller, once the proposal is on the map (proposal.js rebuildProposalMap)
419
+ }
420
+
421
+ /** The proposal is closed: the viewer's own layers are what is drawn again, exactly as they were */
422
+ export function endReview() {
423
+ if (!state.review) return;
424
+ state.review = null;
425
+ touchScene();
426
+ renderLayerToggles();
427
+ }
428
+
429
+ /** What a screen reader hears when a review opens and hid layers: "Showing 4 of 22 layers: the ones this proposal changes." Nothing when no layer was hidden */
430
+ export function reviewLayersLine() {
431
+ if (!state.review || !state.proposal || state.review.whole) return '';
432
+ const { layers } = layerRows();
433
+ const held = new Set(state.nodes.map((n) => rowKeyOf(state, n))); // a layer that holds no node has nothing to hide
434
+ if (!layers.some((l) => held.has(l.key) && reviewHides(state, l.key))) return '';
435
+ const on = layers.filter((l) => isOn(l.key)).length;
436
+ return `Showing ${on} of ${layers.length} layers: the ones this proposal changes.`;
437
+ }
438
+
439
+ /** "Show the whole map": on brings back every layer the viewer has on and the proposal's dimming of the rest (Diff as it always was); off narrows to the change again. Said once, here */
440
+ export function setWholeMap(on) {
441
+ const review = state.review && state.proposal ? state.review : null;
442
+ if (!review || review.whole === on) return;
443
+ review.whole = on;
444
+ review.rev++;
445
+ changed();
446
+ say(on ? 'Showing the whole map.' : (reviewLayersLine() || 'Showing the change: the rest of the map is greyed.'));
447
+ }
448
+
449
+ /** A scenario ended: the layers it turned on for the review go off again (the focused view comes back). True when there were any */
450
+ export function clearStepLayers() {
451
+ const review = state.review;
452
+ if (!review || !Object.keys(review.step).length) return false;
453
+ review.step = {};
454
+ review.rev++;
455
+ touchScene();
456
+ renderLayerToggles();
457
+ return true;
458
+ }
459
+
393
460
  /** Opens or closes the kinds of one row ("5 kinds"); the focus stays on its button */
394
461
  export function toggleLayerKinds(key) {
395
462
  if (openKinds.has(key)) openKinds.delete(key); else openKinds.add(key);