@popcorn245/cornfield 0.40.0 → 0.42.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.
@@ -0,0 +1,335 @@
1
+ /**
2
+ * @module explorer/search
3
+ *
4
+ * Search on the page (spec 0008 D3 and D4); search-model.js decides what is found and in what order, this shows it:
5
+ *
6
+ * - the count in the field ("33 matches", "3 of 33", "No match") and, under the field, a list of what was found: up to 50 rows,
7
+ * grouped by type (the Layers name, with a count) in rank order, each row the label and its parent's; "Frame all 33" first;
8
+ * what a layer that is off hides last, under "In layers that are off", and choosing one turns its layer on;
9
+ * - stepping: Enter and Shift+Enter in the field, the arrow keys in the list, N and P on the map (keyboard.js) and the field's
10
+ * ^ and v buttons. Each step selects the match and flies the camera to it, at zoom 1 or closer;
11
+ * - on the map the matches keep their halo and win a label (scene.js, labels.js), the rest dims.
12
+ *
13
+ * The desktop field and the phone's bar are two inputs on one search: the query, the matches and the current match are shared, each
14
+ * field has its own count, buttons and list. A polite live region says what changed (search-status.js). Everything the user typed or
15
+ * the map holds goes into the markup as text.
16
+ */
17
+
18
+ import { state, touchScene, escHtml } from './state.js';
19
+ import { render, fitGraphToViewport, fitPadding, isNodeVisible } from './render.js';
20
+ import { toggleLayer, onLayersChange } from './layers.js';
21
+ import { selectNode } from './panels.js';
22
+ import { isPhone, visibleMapRect } from './sheets.js';
23
+ import { announce } from './keyboard.js';
24
+ import { flyTo } from './fly.js';
25
+ import { groupOf } from './scene.js';
26
+ import { projectLayerKey } from './layer-model.js';
27
+ import { noMatchText, showSearchStatus, updateSearchStatus } from './search-status.js';
28
+ import { countText, moreLine, noMatchLine, searchNodes, stepIndex } from './search-model.js';
29
+
30
+ const $ = (id) => document.getElementById(id);
31
+
32
+ /** The two fields: the desktop's and the phone's bar. Each has its input, count, list and the live region it shares with the other */
33
+ const FIELDS = [
34
+ { input: 'node-search', count: 'search-count', results: 'search-results', steps: 'search-steps' },
35
+ { input: 'mobile-node-search', count: 'mobile-search-count', results: 'mobile-search-results', steps: 'mobile-search-steps' },
36
+ ];
37
+
38
+ /** The zoom a chosen match is shown at, at least */
39
+ export const MATCH_ZOOM = 1;
40
+
41
+ let memo = null; // { key, result }
42
+
43
+ /** The parent's label, for the row: the node the first ownership edge into it comes from */
44
+ function parentLabeller() {
45
+ const byId = new Map(state.nodes.map((n) => [n.id, n]));
46
+ const parentOf = new Map();
47
+ for (const e of state.edges) if (!e.kind && !e.dashed && !parentOf.has(e.to)) parentOf.set(e.to, e.from);
48
+ return (node) => { const p = byId.get(parentOf.get(node.id)); return p ? String(p.label || '') : ''; };
49
+ }
50
+
51
+ /** What the current query finds (kept until the query, the nodes or the scene change) */
52
+ export function currentResult() {
53
+ const key = `${state.searchQuery}|${state.sceneVersion}|${state.nodes.length}`;
54
+ if (memo && memo.key === key && memo.nodes === state.nodes) return memo.result;
55
+ const result = searchNodes(state.nodes, state.searchQuery, { visible: (n) => isNodeVisible(n), parentLabel: parentLabeller() });
56
+ memo = { key, nodes: state.nodes, result };
57
+ return result;
58
+ }
59
+
60
+ /** Whether a search is on and found something: N and P step through its matches then */
61
+ export const searchActive = () => !!state.searchQuery && currentResult().total > 0;
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Drawing the count and the list
65
+ // ---------------------------------------------------------------------------
66
+
67
+ const listOf = (field) => $(field.results);
68
+
69
+ const FRAME_STOP = Symbol('frame all');
70
+
71
+ function rowHtml(m, off, stop = false) {
72
+ const type = off ? ` · ${escHtml(m.group)}` : '';
73
+ const parent = m.parent ? escHtml(m.parent) : '';
74
+ const current = state.searchCurrent === m.node.id;
75
+ return `<button type="button" role="option" class="hx-search-row" data-corn="search-result" data-search-id="${escHtml(m.node.id)}" tabindex="${stop ? 0 : -1}" aria-selected="${current}"${current ? ' aria-current="true"' : ''}><span class="hx-search-row-label">${escHtml(m.node.label)}</span><span class="hx-search-row-parent">${parent}${type}</span></button>`;
76
+ }
77
+
78
+ /**
79
+ * The list's markup for a result: a listbox (the combobox's popup) of Frame all and the groups of rows, then the "and N more" line; or the
80
+ * no-match words alone. The focus moves into the listbox, from option to option (each row is a button with the option role).
81
+ * @param {ReturnType<typeof searchNodes>} result
82
+ * @param {string} [listId] the listbox's id
83
+ */
84
+ export function resultsHtml(result, listId = 'search-listbox') {
85
+ if (!result.query) return '';
86
+ if (!result.total) return `<p class="hx-search-empty" data-corn="search-empty">${escHtml(noMatchLine(result.query))}</p>`;
87
+ // A roving tab stop: one option (the chosen match when it is listed, else the first) is in the tab order, so Tab reaches the list that scrolls
88
+ const listed = result.groups.flatMap((g) => g.rows);
89
+ const stop = listed.some((m) => m.node.id === state.searchCurrent) ? state.searchCurrent : result.onMap ? FRAME_STOP : listed[0].node.id;
90
+ const frame = result.onMap ? `<button type="button" role="option" aria-selected="false" class="hx-search-row hx-search-frame" data-corn="search-result" data-search-frame tabindex="${stop === FRAME_STOP ? 0 : -1}">Frame all ${result.onMap}</button>` : '';
91
+ const groups = result.groups.map((g) => `<div class="hx-search-group" role="group" aria-label="${escHtml(g.name)}, ${g.count}" data-corn="search-group"><div class="hx-search-group-title" aria-hidden="true">${escHtml(g.name)} <span class="hx-search-group-count">${g.count}</span></div>${g.rows.map((m) => rowHtml(m, g.off, m.node.id === stop)).join('')}</div>`).join('');
92
+ const more = result.more ? `<p class="hx-search-more">${escHtml(moreLine(result.more))}</p>` : '';
93
+ return `<div role="listbox" id="${escHtml(listId)}" aria-label="Search results">${frame}${groups}</div>${more}`;
94
+ }
95
+
96
+ /** Paints the count, the step buttons and the list of both fields from the current result */
97
+ export function paintSearch({ keepOpen = true } = {}) {
98
+ const result = currentResult();
99
+ const text = countText(result, state.searchCurrent);
100
+ for (const field of FIELDS) {
101
+ const count = $(field.count);
102
+ if (count) { count.textContent = text; count.dataset.empty = result.query && !result.total ? 'true' : 'false'; }
103
+ const steps = $(field.steps);
104
+ if (steps) {
105
+ steps.hidden = !result.query;
106
+ for (const b of steps.querySelectorAll('[data-action="search-prev"], [data-action="search-next"]')) b.disabled = !result.total; // nothing to step to
107
+ }
108
+ const list = listOf(field);
109
+ if (!list) continue;
110
+ const input = $(field.input);
111
+ const open = !!result.query && keepOpen && (document.activeElement === input || list.contains(document.activeElement) || list.dataset.open === 'true');
112
+ // A row that has the focus is repainted: the focus goes to the same row again, so a keyboard user keeps their place
113
+ const held = list.contains(document.activeElement) ? document.activeElement : null;
114
+ const heldId = held ? held.dataset.searchId || (held.hasAttribute('data-search-frame') ? '' : null) : null;
115
+ const listId = `${field.results}-listbox`;
116
+ list.innerHTML = open ? resultsHtml(result, listId) : '';
117
+ if (held && open && heldId !== null) {
118
+ const again = rowsOf(list).find((r) => (heldId === '' ? r.hasAttribute('data-search-frame') : r.dataset.searchId === heldId));
119
+ if (again) again.focus();
120
+ }
121
+ list.hidden = !open;
122
+ list.dataset.open = open ? 'true' : 'false';
123
+ if (input) {
124
+ const options = open && result.total > 0; // the popup is the listbox: with no match there is none, only the words (and the live region says them)
125
+ input.setAttribute('aria-expanded', String(options));
126
+ input.setAttribute('aria-controls', options ? listId : field.results);
127
+ }
128
+ }
129
+ }
130
+
131
+ /** The list of a field, closed (Escape, or the focus left it) */
132
+ function closeList(field) {
133
+ const list = listOf(field);
134
+ if (!list) return;
135
+ list.hidden = true;
136
+ list.dataset.open = 'false';
137
+ list.innerHTML = '';
138
+ const input = $(field.input);
139
+ if (input) input.setAttribute('aria-expanded', 'false');
140
+ }
141
+
142
+ // ---------------------------------------------------------------------------
143
+ // The query
144
+ // ---------------------------------------------------------------------------
145
+
146
+ /** What the live region says for a result, once the typing pauses: the count, or for none the no-match words (search-status.js) */
147
+ function announceResult(result) {
148
+ updateSearchStatus(result.query, result.total > 0, countText(result, state.searchCurrent)); // once the typing pauses, not on every key
149
+ }
150
+
151
+ /** Sets the query (typed in either field, or cleared): the map redraws, the count and the list follow */
152
+ export function setQuery(value) {
153
+ const query = String(value || '').trim();
154
+ const changed = query !== state.searchQuery;
155
+ state.searchQuery = query;
156
+ if (changed) state.searchCurrent = null; // a new question has no current answer yet
157
+ touchScene();
158
+ for (const field of FIELDS) {
159
+ const input = $(field.input);
160
+ if (input && input.value !== value) input.value = value || '';
161
+ const list = listOf(field);
162
+ if (list && input && (document.activeElement === input)) list.dataset.open = 'true';
163
+ }
164
+ paintSearch();
165
+ announceResult(currentResult());
166
+ render();
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Choosing a match
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /** Turns on the layer that hides `node`, so it can be shown (the matches in layers that are off) */
174
+ function showLayerOf(node) {
175
+ // A project layer that takes the node decides alone (spec 0009); else its starting layer, and what that one needs on with it
176
+ const tries = [projectLayerKey(state, node), groupOf(node), node.type === 'store' || node.type === 'rom' ? 'flow' : null, node.type === 'core' ? 'pkg' : null, node.type === 'core' ? 'core' : null];
177
+ for (const key of tries) {
178
+ if (isNodeVisible(node)) return;
179
+ if (key && state.activeLayers[key] === false) toggleLayer(key);
180
+ }
181
+ }
182
+
183
+ /** The camera that puts `node` in the middle of the part of the map nothing covers (the panels, the proposal bar, the review column, a phone's sheets: sheets.js) */
184
+ export function matchTarget(node, zoom) {
185
+ const r = visibleMapRect();
186
+ return { x: r.x + r.width / 2 - node.x * zoom, y: r.y + r.height / 2 - node.y * zoom, zoom };
187
+ }
188
+
189
+ /** Selects a match and flies the camera to it (zoom 1 or closer): what Enter, a row and N do */
190
+ let chosen = 0;
191
+ export async function chooseMatch(match, { say = true } = {}) {
192
+ const node = match.node;
193
+ const mine = ++chosen;
194
+ if (!isNodeVisible(node)) showLayerOf(node);
195
+ state.searchCurrent = node.id;
196
+ touchScene();
197
+ const result = currentResult();
198
+ const at = result.matches.findIndex((m) => m.node.id === node.id);
199
+ await selectNode(node);
200
+ if (mine !== chosen || state.searchCurrent !== node.id) return; // a later choice, or a new query, has taken over while the panel was filling
201
+ flyTo(matchTarget(node, Math.max(state.camera.zoom, MATCH_ZOOM)));
202
+ paintSearch();
203
+ const words = `${at + 1} of ${result.total}: ${node.label}${match.parent ? `, in ${match.parent}` : ''}`;
204
+ showSearchStatus(''); // said once, by the map's announcer: two live regions with the same words are read out twice
205
+ if (say) announce(words);
206
+ }
207
+
208
+ /** The match `by` (+1, -1) from the current one: the first (or last) with none; false when there is nothing to step to */
209
+ export function stepMatch(by) {
210
+ const result = currentResult();
211
+ if (!state.searchQuery || !result.total) return false;
212
+ const at = stepIndex(result.matches, state.searchCurrent, by);
213
+ if (at < 0) return false;
214
+ chooseMatch(result.matches[at]);
215
+ return true;
216
+ }
217
+
218
+ /** Fits the camera to every match on the map ("Frame all") */
219
+ export function frameAll() {
220
+ const result = currentResult();
221
+ const ids = new Set(result.matches.filter((m) => m.on).map((m) => m.node.id));
222
+ if (!ids.size) return;
223
+ fitGraphToViewport(fitPadding(), ids);
224
+ showSearchStatus('');
225
+ announce(`Framed ${ids.size} ${ids.size === 1 ? 'match' : 'matches'}`);
226
+ }
227
+
228
+ // ---------------------------------------------------------------------------
229
+ // Keys and clicks
230
+ // ---------------------------------------------------------------------------
231
+
232
+ const rowsOf = (list) => [...list.querySelectorAll('[data-corn="search-result"]')];
233
+
234
+ function onFieldKey(e, field) {
235
+ const input = e.currentTarget;
236
+ if (e.key === 'Enter') {
237
+ if (e.isComposing) return;
238
+ e.preventDefault();
239
+ const typed = input.value.trim();
240
+ if (typed !== state.searchQuery) setQuery(input.value);
241
+ if (!typed) return;
242
+ const result = currentResult();
243
+ if (!result.total) { announce(`No node matches ${typed}`); return; }
244
+ stepMatch(e.shiftKey ? -1 : 1);
245
+ } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
246
+ const list = listOf(field);
247
+ if (!list || list.hidden) { if (e.key === 'ArrowDown' && state.searchQuery) { e.preventDefault(); list.dataset.open = 'true'; paintSearch(); } return; }
248
+ const rows = rowsOf(list);
249
+ if (!rows.length) return;
250
+ e.preventDefault();
251
+ (e.key === 'ArrowDown' ? rows[0] : rows[rows.length - 1]).focus();
252
+ } else if (e.key === 'Escape') {
253
+ const list = listOf(field);
254
+ if (list && !list.hidden) { e.preventDefault(); closeList(field); return; }
255
+ if (state.searchQuery) { e.preventDefault(); setQuery(''); announce('Search cleared'); }
256
+ }
257
+ }
258
+
259
+ function onListKey(e, field) {
260
+ const list = listOf(field);
261
+ const rows = rowsOf(list);
262
+ const at = rows.indexOf(document.activeElement);
263
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
264
+ e.preventDefault();
265
+ const next = at + (e.key === 'ArrowDown' ? 1 : -1);
266
+ if (next < 0) $(field.input).focus(); else rows[Math.min(rows.length - 1, next)].focus();
267
+ } else if (e.key === 'Home' || e.key === 'End') {
268
+ e.preventDefault();
269
+ rows[e.key === 'Home' ? 0 : rows.length - 1].focus();
270
+ } else if (e.key === 'Escape') {
271
+ e.preventDefault();
272
+ $(field.input).focus(); // back in the field, the list still there: a second Escape shuts it
273
+ }
274
+ }
275
+
276
+ function onListClick(e) {
277
+ const row = e.target.closest && e.target.closest('[data-corn="search-result"]');
278
+ if (!row) return;
279
+ if (row.hasAttribute('data-search-frame')) { frameAll(); return; }
280
+ const result = currentResult();
281
+ const match = result.matches.find((m) => m.node.id === row.dataset.searchId);
282
+ if (!match) return;
283
+ chooseMatch(match);
284
+ // On a phone the list would cover the match: it shuts, and the focus goes to the next-match button, which stays
285
+ const field = FIELDS.find((f) => listOf(f) === e.currentTarget);
286
+ if (field && field.input === 'mobile-node-search' && isPhone()) {
287
+ closeList(field);
288
+ const next = $(field.steps) && $(field.steps).querySelector('[data-action="search-next"]');
289
+ if (next) next.focus();
290
+ }
291
+ }
292
+
293
+ /** The list closes when the focus leaves the field and its list (a click on the map, Tab away) */
294
+ function onFocusOut(e, field) {
295
+ const next = e.relatedTarget;
296
+ const box = $(field.input).closest('[data-corn="search"], [data-corn="mobile-search"]');
297
+ if (next && box && box.contains(next)) return;
298
+ if (!next && e.target && e.target.matches && e.target.matches('[data-corn="search-result"]')) return; // a row that left the DOM (the list repainted)
299
+ closeList(field);
300
+ }
301
+
302
+ /** Wires both fields, their list, and the step and clear buttons (main.js, once the page is up) */
303
+ export function initSearch() {
304
+ for (const field of FIELDS) {
305
+ const input = $(field.input);
306
+ if (!input || input.dataset.searchBound) continue;
307
+ input.dataset.searchBound = '1';
308
+ // A combobox whose popup is a listbox: its options (Frame all, then the rows) in labelled groups, reached with the down arrow and
309
+ // walked with the arrows (the focus moves from option to option), so a screen reader hears each row and its group
310
+ input.setAttribute('role', 'combobox');
311
+ input.setAttribute('aria-haspopup', 'listbox');
312
+ input.setAttribute('aria-autocomplete', 'none');
313
+ input.setAttribute('aria-expanded', 'false');
314
+ input.setAttribute('aria-controls', field.results);
315
+ input.addEventListener('input', (e) => setQuery(e.target.value));
316
+ input.addEventListener('keydown', (e) => onFieldKey(e, field));
317
+ input.addEventListener('focus', () => { const list = listOf(field); if (list && state.searchQuery) { list.dataset.open = 'true'; paintSearch(); } });
318
+ const box = input.closest('[data-corn="search"], [data-corn="mobile-search"]');
319
+ if (box) box.addEventListener('focusout', (e) => onFocusOut(e, field));
320
+ const list = listOf(field);
321
+ if (list) {
322
+ // A press on a row keeps the focus where it is (some browsers do not focus a button they press): the field would lose it and shut the list before the click
323
+ list.addEventListener('mousedown', (e) => { if (e.target.closest && e.target.closest('[data-corn="search-result"]')) e.preventDefault(); });
324
+ list.addEventListener('click', onListClick);
325
+ list.addEventListener('keydown', (e) => onListKey(e, field));
326
+ }
327
+ }
328
+ // A layer going on or off moves matches between the list and "In layers that are off"
329
+ onLayersChange(() => { if (state.searchQuery) paintSearch(); });
330
+ }
331
+
332
+ /** For tests: forget what was found */
333
+ export function resetSearchForTests() { memo = null; chosen++; state.searchQuery = ''; state.searchCurrent = null; }
334
+
335
+ export { noMatchText };
package/explorer/state.js CHANGED
@@ -39,6 +39,10 @@ export const state = {
39
39
  /** The config's `forge` (`{ type, url, repo, baseBranch? }`), or null: where a node's file is opened (file-url.js) */
40
40
  forge: null,
41
41
  searchQuery: '',
42
+ /** The id of the search match the stepping is on (search.js), or null: the map draws its halo and places its label first of the matches */
43
+ searchCurrent: null,
44
+ /** The id of the node the pointer is on (input.js): a node with no label is named by a chip while it is */
45
+ hoverNodeId: null,
42
46
 
43
47
  isFreeform: false,
44
48
  freeformPositions: {},
@@ -103,6 +107,8 @@ export const state = {
103
107
  proposal: null,
104
108
  proposalView: 'diff',
105
109
  proposalSource: null,
110
+ /** The open proposal's file as the server sent it, its SHA-256 (X-Proposal-Sha256), or null: a review names it, so a push since is refused (spec 0007) */
111
+ proposalSha256: null,
106
112
  proposalSlug: null,
107
113
  proposalErrors: [],
108
114
  /** Where each of the open proposal's mockups stands with the review, by position: 'approved' | 'changed' | 'unreviewed' | 'missing' (mockups.js; none read yet is empty) */
@@ -114,6 +120,8 @@ export const state = {
114
120
  effectiveProposal: null,
115
121
  /** The maintainer's what-if edits to the open proposal, and what Undo took back (whatif-model.js): `{ edits, undone }` */
116
122
  whatIf: { edits: [], undone: [] },
123
+ /** The My edits toggle is off: the map is drawn from the proposal as written, the edits are kept and still go with a review (whatif.js, spec 0007 D5) */
124
+ whatIfOff: false,
117
125
  /** A marked edge picked on the map (nodes are `selectedNode`): the panel shows it, the scene does not change */
118
126
  selectedEdge: null,
119
127
 
@@ -137,6 +137,8 @@
137
137
  --corn-map-font: auto;
138
138
  --corn-map-edge-width: auto;
139
139
  --corn-map-glow: auto;
140
+ /* The smallest a map label is drawn on screen (spec 0008): auto is 11px; a theme may raise it, not lower it. A hub's title is 2px more */
141
+ --corn-map-label-min: auto;
140
142
  /* Diff, selection and focus */
141
143
  --corn-map-added: auto;
142
144
  --corn-map-changed: auto;
@@ -22,7 +22,8 @@
22
22
 
23
23
  import { state, touchScene, onSceneTouch, nameOf, nodeById, escHtml } from './state.js';
24
24
  import { render, isNodeVisible } from './render.js';
25
- import { hooks, rebuildProposalMap, closeProposal } from './proposal.js';
25
+ import { hooks, rebuildProposalMap, closeProposal, focusChange } from './proposal.js';
26
+ import { t } from './strings.js';
26
27
  import { getPlayer, playScenario, stopScenario, tickScenario } from './scenario-ui.js';
27
28
  import { kindOfMark } from './proposal-model.js';
28
29
  import { announce } from './keyboard.js';
@@ -78,9 +79,33 @@ export function onEditsChange(fn) {
78
79
  return () => listeners.delete(fn);
79
80
  }
80
81
 
82
+ /**
83
+ * The what-if form that is open with something in it, for the decision to ask about before it drops it (spec 0007 D2): `{ name }` or null. The add-node
84
+ * form counts once it has a label or a description, the edge form while it is open (it holds the pair), a new step once it has words.
85
+ */
86
+ export function openFormInfo() {
87
+ if (!state.proposal || !root) return null;
88
+ if (ui.form && ui.form.kind === 'node') {
89
+ const f = q('[data-form="node"]');
90
+ const typed = f && f.elements ? [f.elements.namedItem('label'), f.elements.namedItem('desc')].some((el) => el && String(el.value).trim()) : false;
91
+ return typed ? { name: 'Add a node' } : null;
92
+ }
93
+ if (ui.form && ui.form.kind === 'edge') return { name: 'Draw an edge' };
94
+ if (ui.panel === 'steps' && (ui.stepDraft.trim() || ui.titleDraft.trim())) return { name: 'New step' };
95
+ return null;
96
+ }
97
+
98
+ /** One line for each applied edit, as "Your edits" words them (what a send back keeps readable, spec 0007 D4) */
99
+ export function describeEditsNow() {
100
+ const proposal = state.effectiveProposal || state.proposal;
101
+ const words = { nameOf, scenarioTitle: (id) => (scenariosOf(proposal).find((x) => x.id === id) || { title: id }).title };
102
+ return state.whatIf.edits.map((edit) => M.describeEdit(edit, words));
103
+ }
104
+
81
105
  /** Empties the list and the stored copy (once the edits were sent) and draws the proposal as the robot wrote it */
82
106
  export function clearEdits() {
83
107
  if (!state.proposal) return;
108
+ state.whatIfOff = false; // no edits left to hide
84
109
  apply({ whatIf: M.emptyWhatIf(), effective: state.proposal });
85
110
  }
86
111
 
@@ -88,6 +113,7 @@ function load(proposal) {
88
113
  const key = keyOf();
89
114
  loadedFor = proposal;
90
115
  loadedKey = key;
116
+ state.whatIfOff = false;
91
117
  resetUi();
92
118
  let stored = M.emptyWhatIf();
93
119
  const store = storage();
@@ -105,7 +131,7 @@ function load(proposal) {
105
131
  /** hooks.effective: the proposal the map is drawn from. Loads this proposal's stored edits the first time it is asked about it. */
106
132
  function effectiveFor(proposal) {
107
133
  if (proposal !== loadedFor || keyOf() !== loadedKey) load(proposal);
108
- return M.evaluate(base(), proposal, state.whatIf.edits).effective;
134
+ return state.whatIfOff ? proposal : M.evaluate(base(), proposal, state.whatIf.edits).effective;
109
135
  }
110
136
 
111
137
  hooks.effective = effectiveFor;
@@ -118,6 +144,7 @@ hooks.beforeClose = () => {
118
144
  };
119
145
  hooks.closed = () => {
120
146
  state.whatIf = M.emptyWhatIf();
147
+ state.whatIfOff = false;
121
148
  loadedFor = null;
122
149
  loadedKey = null;
123
150
  resetUi();
@@ -164,8 +191,9 @@ function apply({ whatIf, effective }) {
164
191
  const before = scenariosOf(state.effectiveProposal);
165
192
  state.whatIf = whatIf;
166
193
  save();
167
- rebuildProposalMap(effective);
168
- const sync = M.scenarioSync(state.scenario ? state.scenario.id : null, before, scenariosOf(effective));
194
+ const shown = state.whatIfOff ? state.proposal : effective; // My edits off: the proposal as written, the edits kept
195
+ rebuildProposalMap(shown);
196
+ const sync = M.scenarioSync(state.scenario ? state.scenario.id : null, before, scenariosOf(shown));
169
197
  if (sync.action === 'update') {
170
198
  const player = getPlayer();
171
199
  if (player) { player.setScenario(sync.scenario); tickScenario(performance.now()); }
@@ -185,6 +213,7 @@ const clearMessages = () => { ui.messages = {}; };
185
213
  /** An intent from a control, as an edit: refused with a message next to the control, or applied */
186
214
  function doIntent(intent, where) {
187
215
  if (!state.proposal) return false;
216
+ if (state.whatIfOff) return refuse(where, turnOnWords());
188
217
  const effective = state.effectiveProposal || state.proposal;
189
218
  const taken = new Set([...state.baseNodes.map((n) => n.id), ...asList(effective?.nodes?.add).map((n) => n.id)]);
190
219
  const edit = M.editFromIntent(intent, { takenIds: taken, scenarios: scenariosOf(effective), now: now() });
@@ -193,16 +222,45 @@ function doIntent(intent, where) {
193
222
  if (!result.ok) return refuse(where, result.message);
194
223
  clearMessages();
195
224
  apply(result);
225
+ bringIntoView(edit);
226
+ return true;
227
+ }
228
+
229
+ /** "Turn My edits on to edit.": the tools do nothing while the map is the proposal as written */
230
+ const turnOnWords = () => `Turn ${t('myEdits')} on to edit.`;
231
+
232
+ /**
233
+ * An edit that adds a node or an edge brings it into view, in the part of the map the review column and the panels leave free, and says it once
234
+ * (a new node used to land off screen, issue #166). Other edits move nothing.
235
+ */
236
+ function bringIntoView(edit) {
237
+ if (!edit) return;
238
+ if (edit.op === 'add-node') focusChange('node', edit.id, { select: false });
239
+ else if (edit.op === 'add-edge') focusChange('edge', edgeKey(edit), { select: false });
240
+ }
241
+
242
+ /** The My edits toggle: off draws the proposal as written (the edits are kept, and still go with Approve and Send back); on draws them again */
243
+ export function setMyEdits(on) {
244
+ if (!state.proposal || !M.hasEdits(state.whatIf)) return false;
245
+ state.whatIfOff = !on;
246
+ if (!on) { setDrawing(false); ui.form = null; }
247
+ rebuildProposalMap(on ? M.evaluate(base(), state.proposal, state.whatIf.edits).effective : state.proposal);
248
+ touchScene();
249
+ render();
250
+ renderUi();
251
+ emit();
252
+ const n = state.whatIf.edits.length;
253
+ announce(on ? `${t('myEdits')} on: your ${n === 1 ? 'edit is' : `${n} edits are`} on the map.` : `${t('myEdits')} off: the map shows the proposal as written. Your ${n === 1 ? 'edit is' : `${n} edits are`} kept, and still go with Approve and Send back.`);
196
254
  return true;
197
255
  }
198
256
 
199
257
  export function undoEdit() {
200
- if (!state.proposal || !M.canUndo(state.whatIf)) return false;
258
+ if (!state.proposal || state.whatIfOff || !M.canUndo(state.whatIf)) return false;
201
259
  const edit = state.whatIf.edits[state.whatIf.edits.length - 1];
202
260
  return step(M.undo(state.whatIf), edit, 'Undid');
203
261
  }
204
262
  export function redoEdit() {
205
- if (!state.proposal || !M.canRedo(state.whatIf)) return false;
263
+ if (!state.proposal || state.whatIfOff || !M.canRedo(state.whatIf)) return false;
206
264
  const edit = state.whatIf.undone[state.whatIf.undone.length - 1];
207
265
  return step(M.redo(state.whatIf), edit, 'Redid');
208
266
  }
@@ -217,6 +275,7 @@ function step(whatIf, edit, verb) {
217
275
  }
218
276
 
219
277
  function removeEditAt(index) {
278
+ if (state.whatIfOff) return refuse('edits', turnOnWords());
220
279
  const result = M.tryRemoveEdit(base(), state.proposal, state.whatIf, index);
221
280
  if (!result.ok) return refuse('edits', result.message);
222
281
  clearMessages();
@@ -257,6 +316,8 @@ function mount() {
257
316
  body.appendChild(root);
258
317
  const edit = $('proposal-edit');
259
318
  if (edit) edit.addEventListener('click', () => setEditing(!ui.editing));
319
+ const mine = $('proposal-myedits');
320
+ if (mine) mine.addEventListener('click', () => setMyEdits(!!state.whatIfOff));
260
321
  root.addEventListener('click', onClick);
261
322
  root.addEventListener('submit', onSubmit);
262
323
  root.addEventListener('change', onChange);
@@ -278,6 +339,13 @@ function renderUi() {
278
339
  edit.classList.toggle('hx-btn--active', ui.editing);
279
340
  edit.textContent = state.whatIf.edits.length ? `Edit · ${state.whatIf.edits.length}` : 'Edit';
280
341
  }
342
+ const mine = $('proposal-myedits');
343
+ if (mine) {
344
+ mine.hidden = !open || !M.hasEdits(state.whatIf);
345
+ mine.setAttribute('aria-pressed', String(!state.whatIfOff));
346
+ mine.classList.toggle('hx-btn--active', !state.whatIfOff);
347
+ mine.textContent = t('myEdits');
348
+ }
281
349
  if (!open) { paintDrawer(); return; }
282
350
 
283
351
  const wi = state.whatIf;
@@ -295,6 +363,10 @@ function renderUi() {
295
363
  q('[data-whatif="edits"]').textContent = M.editsLabel(wi.edits.length);
296
364
  const addNode = q('[data-whatif="add-node"]');
297
365
  addNode.classList.toggle('hx-btn--active', ui.form?.kind === 'node');
366
+ // My edits off: the tools say why they do nothing
367
+ for (const btn of q('[data-whatif="add-node"]').parentElement.querySelectorAll('button')) {
368
+ if (state.whatIfOff) btn.setAttribute('aria-disabled', 'true'); else btn.removeAttribute('aria-disabled');
369
+ }
298
370
 
299
371
  const notice = q('[data-notice]');
300
372
  notice.hidden = !ui.notice;
@@ -319,7 +391,7 @@ function setEditing(on) {
319
391
  function paintMessages() {
320
392
  if (!root) return;
321
393
  for (const el of root.querySelectorAll('[data-msg]')) {
322
- const text = ui.messages[el.dataset.msg] || '';
394
+ const text = ui.messages[el.dataset.msg] || (el.dataset.msg === 'toolbar' && state.whatIfOff ? turnOnWords() : '');
323
395
  el.hidden = !text;
324
396
  el.textContent = text;
325
397
  }
@@ -680,10 +752,14 @@ const ACTIONS = {
680
752
  },
681
753
  };
682
754
 
755
+ /** What changes the edits: with My edits off these do nothing and say why */
756
+ const EDITING = new Set(['add-node', 'draw-edge', 'undo', 'redo', 'steps', 'edge-to', 'remove-node', 'remove-edge', 'bring-back', 'remove-edit', 'step-up', 'step-down', 'step-delete']);
757
+
683
758
  function onClick(e) {
684
759
  const el = e.target.closest ? e.target.closest('[data-whatif]') : null;
685
760
  const action = el && ACTIONS[el.dataset.whatif];
686
761
  if (!action || el.disabled) return;
762
+ if (state.whatIfOff && EDITING.has(el.dataset.whatif)) { refuse('toolbar', turnOnWords()); return; }
687
763
  action(el);
688
764
  }
689
765
 
@@ -944,4 +1020,5 @@ export function resetWhatIfForTests() {
944
1020
  listeners.clear();
945
1021
  Object.assign(ui, { editing: false, panel: null, form: null, drawing: false, confirm: false, closing: false, scenarioId: null, stepDraft: '', titleDraft: '', notice: '', messages: {}, recentParents: [], lastSelected: null });
946
1022
  state.whatIf = M.emptyWhatIf();
1023
+ state.whatIfOff = false;
947
1024
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.40.0",
3
+ "version": "0.42.0",
4
4
  "description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
5
5
  "license": "MIT",
6
6
  "author": "popcorn245 (https://github.com/popcorn245)",