cornfield 0.40.0 → 0.41.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: {},
@@ -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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.40.0",
3
+ "version": "0.41.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)",