cornfield 0.39.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,156 @@
1
+ /**
2
+ * @module explorer/search-model
3
+ *
4
+ * What a search finds, in what order, and how it reads (spec 0008 D3 and D4). Pure: no DOM, no state. Nodes in, matches out.
5
+ *
6
+ * - It reads a node's label, its id, its file path, its type (as a word: "service", and as its layer's name: "Services")
7
+ * and its finer kind ("webhook"). Case does not matter. Not descriptions: on a big map a common word in one would match
8
+ * hundreds of nodes and bury the one that was named.
9
+ * - It ranks: a label that starts with the term (0), then a word of the label that does (1), then the label containing it
10
+ * (2), then the id or the file (3), then the type or the kind (4). Within a rank, by label, then id: the order does not
11
+ * depend on the camera or on how the nodes happen to be listed.
12
+ * - It groups by type, under the layer's name with a count, groups in the order of their best match, and puts the matches
13
+ * in layers that are off last, under their own heading.
14
+ *
15
+ * Substring matching only: no fuzzy matching, so a reviewer can always see why a node matched.
16
+ */
17
+
18
+ /** The heading of the matches in layers that are off */
19
+ export const OFF_GROUP = 'In layers that are off';
20
+
21
+ /** Rows the list shows before "and N more" */
22
+ export const MAX_ROWS = 50;
23
+
24
+ /** The ranks, best first */
25
+ export const RANK = Object.freeze({ labelStart: 0, wordStart: 1, label: 2, idOrFile: 3, typeOrKind: 4 });
26
+
27
+ /**
28
+ * The layer's name for each node type, as the Layers menu says it (layers.js `LAYER_DEFS`; a test keeps the two together).
29
+ * A type not here is its own name with a capital.
30
+ */
31
+ export const TYPE_NAMES = Object.freeze({
32
+ root: 'Root', app: 'Apps', pkg: 'Packages', page: 'Pages & Routes', atom: 'Atoms', molecule: 'Molecules', token: 'Design Tokens',
33
+ tool: 'Dev Tools', core: 'Core', store: 'Stores', table: 'Tables', rom: 'ROM', service: 'Services', external: 'Cloud', stack: 'Infra',
34
+ machine: 'Machines', container: 'Containers', device: 'Devices', floor: 'House', room: 'House', persona: 'People',
35
+ });
36
+
37
+ const capital = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);
38
+
39
+ /** The name of the group a node is listed under: its layer's name */
40
+ export const groupName = (node) => TYPE_NAMES[node.type] || capital(String(node.type || ''));
41
+
42
+ const lower = (s) => (typeof s === 'string' ? s.toLowerCase() : '');
43
+ const WORD_BREAK = /[^\p{L}\p{N}]+/u;
44
+
45
+ /**
46
+ * How well `query` (trimmed) matches a node, as a RANK, or -1 for no match
47
+ * @param {{label?: string, id?: string, file?: string, type?: string, kind?: string}} node
48
+ * @param {string} query
49
+ */
50
+ export function rankOf(node, query) {
51
+ const term = String(query || '').toLowerCase();
52
+ if (!term) return -1;
53
+ const label = lower(node.label);
54
+ if (label.startsWith(term)) return RANK.labelStart;
55
+ if (label.split(WORD_BREAK).some((w) => w && w.startsWith(term))) return RANK.wordStart;
56
+ if (label.includes(term)) return RANK.label;
57
+ if (lower(node.id).includes(term) || lower(node.file).includes(term)) return RANK.idOrFile;
58
+ if (lower(node.type).includes(term) || lower(groupName(node)).includes(term) || lower(node.kind).includes(term)) return RANK.typeOrKind;
59
+ return -1;
60
+ }
61
+
62
+ /**
63
+ * Every node the query finds, in the order the list shows them.
64
+ * @param {object[]} nodes the topology nodes
65
+ * @param {string} query as typed (it is trimmed, and case does not matter)
66
+ * @param {{visible?: (node: object) => boolean, parentLabel?: (node: object) => string}} [opts]
67
+ * `visible`: whether the node is drawn (its layer is on); the others come last. `parentLabel`: who the row names after its label.
68
+ * @returns {{
69
+ * query: string,
70
+ * matches: {node: object, rank: number, on: boolean, group: string, parent: string}[],
71
+ * groups: {name: string, off: boolean, count: number, rows: object[]}[],
72
+ * total: number, onMap: number, off: number,
73
+ * rows: number, more: number
74
+ * }}
75
+ * `matches` is every match in list order (the order Enter and N walk), `groups` the same in groups with at most MAX_ROWS rows
76
+ * in all, `more` how many are past that.
77
+ */
78
+ export function searchNodes(nodes, query, opts = {}) {
79
+ const term = String(query || '').trim().toLowerCase();
80
+ const visible = opts.visible || (() => true);
81
+ const parentLabel = opts.parentLabel || (() => '');
82
+ const out = { query: String(query || '').trim(), matches: [], groups: [], total: 0, onMap: 0, off: 0, rows: 0, more: 0 };
83
+ if (!term) return out;
84
+
85
+ const found = [];
86
+ for (const node of nodes) {
87
+ const rank = rankOf(node, term);
88
+ if (rank < 0) continue;
89
+ found.push({ node, rank, on: !!visible(node), group: groupName(node), parent: parentLabel(node) });
90
+ }
91
+ const byRank = (a, b) => a.rank - b.rank || String(a.node.label).localeCompare(String(b.node.label)) || String(a.node.id).localeCompare(String(b.node.id));
92
+ found.sort(byRank);
93
+
94
+ // The groups: by type, in the order of each one's best match (then its name); what is on the map before what is off it
95
+ const lists = new Map();
96
+ for (const m of found) {
97
+ const key = m.on ? `on|${m.group}` : 'off'; // what a layer that is off hides is one group, whatever its types
98
+ if (!lists.has(key)) lists.set(key, { name: m.on ? m.group : OFF_GROUP, off: !m.on, rows: [] });
99
+ lists.get(key).rows.push(m);
100
+ }
101
+ const groups = [...lists.values()].sort((a, b) => Number(a.off) - Number(b.off) || a.rows[0].rank - b.rows[0].rank || a.name.localeCompare(b.name));
102
+ out.matches = groups.flatMap((g) => g.rows);
103
+ out.total = out.matches.length;
104
+ out.onMap = found.filter((m) => m.on).length;
105
+ out.off = out.total - out.onMap;
106
+
107
+ // The list: the first MAX_ROWS rows in that order, in their groups; the groups keep their full counts
108
+ let room = MAX_ROWS;
109
+ for (const g of groups) {
110
+ if (room <= 0) break;
111
+ out.groups.push({ name: g.name, off: g.off, count: g.rows.length, rows: g.rows.slice(0, room) });
112
+ room -= g.rows.length;
113
+ }
114
+ out.rows = Math.min(MAX_ROWS, out.total);
115
+ out.more = Math.max(0, out.total - MAX_ROWS);
116
+ return out;
117
+ }
118
+
119
+ /** The ids a query matches (what the map halos): a Set, empty for no query */
120
+ export function matchIds(nodes, query) {
121
+ const term = String(query || '').trim().toLowerCase();
122
+ const ids = new Set();
123
+ if (!term) return ids;
124
+ for (const node of nodes) if (rankOf(node, term) >= 0) ids.add(node.id);
125
+ return ids;
126
+ }
127
+
128
+ /**
129
+ * The match `by` steps (+1 or -1) from the one with id `currentId`, wrapping round; the first (or, going back, the last) when
130
+ * there is no current one or it is not among them.
131
+ * @param {{node: {id: string}}[]} matches in list order
132
+ * @param {string|null|undefined} currentId
133
+ * @param {number} by
134
+ * @returns {number} an index into `matches`, -1 for none
135
+ */
136
+ export function stepIndex(matches, currentId, by) {
137
+ if (!matches.length) return -1;
138
+ const at = matches.findIndex((m) => m.node.id === currentId);
139
+ if (at < 0) return by < 0 ? matches.length - 1 : 0;
140
+ return (at + (by < 0 ? -1 : 1) + matches.length) % matches.length;
141
+ }
142
+
143
+ /** What the field's count says: "No match", "33 matches", or "3 of 33" once one is chosen; '' for no query */
144
+ export function countText(result, currentId) {
145
+ if (!result.query) return '';
146
+ if (!result.total) return 'No match';
147
+ const at = result.matches.findIndex((m) => m.node.id === currentId);
148
+ if (at >= 0) return `${at + 1} of ${result.total}`;
149
+ return result.total === 1 ? '1 match' : `${result.total} matches`;
150
+ }
151
+
152
+ /** The list's words for a query that found nothing (the query goes in as text, never as HTML) */
153
+ export const noMatchLine = (query) => `No node matches “${query}”. Search reads names, files, types and kinds.`;
154
+
155
+ /** "and 12 more: type more to narrow" */
156
+ export const moreLine = (n) => `and ${n} more: type more to narrow`;
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * @module explorer/search-status
3
3
  *
4
- * The line by the search field that says a search found nothing ("No match for “xyz”"), in a polite live region so a
5
- * screen reader says it too (F24). Spec 0008 builds the results list; this is only the no-match message.
6
- * The words are the `searchNoMatch` string; the query goes in as text, never as HTML.
4
+ * The polite live region by each search field (F24): what a screen reader hears of a search. Once the typing pauses it says the count ("7 matches")
5
+ * or "No match for “xyz”" (search.js, spec 0008); a match chosen or "Framed 7 matches" is said by the map's announcer (keyboard.js), once. The region is out of
6
+ * sight: the count in the field and the list under it say it on the screen. The no-match words are the `searchNoMatch` string; the query
7
+ * goes in as text, never as HTML.
7
8
  */
8
9
 
9
10
  import { t } from './strings.js';
@@ -14,28 +15,38 @@ const IDS = ['search-status', 'mobile-search-status'];
14
15
  /** "No match for “query”" */
15
16
  export const noMatchText = (query) => `${t('searchNoMatch')} “${query}”`;
16
17
 
17
- /** Shows `text` by the search field(s); '' clears it */
18
- export function showSearchStatus(text) {
18
+ /** Writes `text` into the region(s) at once; '' clears them */
19
+ function write(text) {
19
20
  for (const id of IDS) {
20
21
  const el = document.getElementById(id);
21
22
  if (el) el.textContent = text;
22
23
  }
23
24
  }
24
25
 
25
- /** How long the typing must pause before "No match" is shown: a live region that changed on every key would be read out on every key */
26
+ /** How long the typing must pause before what a search found is said: a live region that changed on every key would be read out on every key */
26
27
  export const NO_MATCH_DELAY_MS = 400;
27
28
  let pending = null;
28
29
 
30
+ /** Shows `text` by the search field(s) at once, ending any wait for what the typing found; '' clears it */
31
+ export function showSearchStatus(text) {
32
+ clearTimeout(pending);
33
+ pending = null;
34
+ write(text);
35
+ }
36
+
29
37
  /**
30
- * Sets the status for a search: nothing for an empty query or a match (at once), "No match for …" when the query found
31
- * no node, once the typing pauses, so a screen reader says it once and not for every letter.
38
+ * Sets the status for a search as it is typed: cleared at once (an empty query clears it for good), then, once the typing pauses, the
39
+ * count (`count`, "7 matches") for a query that found something, or "No match for …" for one that found nothing; so a screen reader
40
+ * says it once per pause, not for every letter.
32
41
  * @param {string} query the trimmed query
33
- * @param {boolean} found whether a shown node matched
42
+ * @param {boolean} found whether a node matched
43
+ * @param {string} [count] what to say when one did (nothing is said without it)
34
44
  */
35
- export function updateSearchStatus(query, found) {
45
+ export function updateSearchStatus(query, found, count = '') {
36
46
  clearTimeout(pending);
37
47
  pending = null;
38
- if (!query || found) { showSearchStatus(''); return; }
39
- const text = noMatchText(query);
40
- pending = setTimeout(() => { pending = null; showSearchStatus(text); }, NO_MATCH_DELAY_MS);
48
+ write('');
49
+ const text = !query ? '' : found ? count : noMatchText(query);
50
+ if (!text) return;
51
+ pending = setTimeout(() => { pending = null; write(text); }, NO_MATCH_DELAY_MS);
41
52
  }
@@ -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 };
@@ -545,7 +545,7 @@ flat out float v_alpha;
545
545
  void main() {
546
546
  vec2 centre = u_cam.xy + a_geom.xy * u_cam.z;
547
547
  vec2 pos = centre + a_corner * (a_geom.z * 0.5 * u_cam.z);
548
- v_uv = vec2(a_corner.x * 0.5 + 0.5, 0.5 - a_corner.y * 0.5);
548
+ v_uv = vec2(a_corner.x * 0.5 + 0.5, a_corner.y * 0.5 + 0.5); // screen y runs down and an image's first row is its top, so the corner below the centre reads the last row
549
549
  v_alpha = a_geom.w;
550
550
  gl_Position = toClip(pos);
551
551
  }
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: {},
@@ -54,6 +58,15 @@ export const state = {
54
58
  machine: false, container: false, device: false, house: false, persona: false,
55
59
  },
56
60
 
61
+ /**
62
+ * The project's own layers (spec 0009): `{ key, label, desc?, match }` in `add` order, as the config sent them (core/layers.js); a node is
63
+ * in the first one whose match it meets (explorer/layer-model.js). `layerOrder` is the config's `order`; `layerDefaults` what each layer is
64
+ * when the viewer has not touched it (layers.js `setProjectLayers`). Empty with no `layers` in the config: the menu is then the starting set.
65
+ */
66
+ projectLayers: [],
67
+ layerOrder: [],
68
+ layerDefaults: {},
69
+
57
70
  /**
58
71
  * The map as the last `setMap` (view.js) was handed it, before the live layer is laid in: the base
59
72
  * copies, or a proposal applied over them. `nodes` and `edges` are these plus the live ones.
@@ -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.39.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)",
package/server/server.js CHANGED
@@ -57,6 +57,7 @@ import { browserSources, BUILTIN_SOURCES, parseDuration, specPollMs, triggersOf,
57
57
  import { CLOUD_FILE } from '../core/cloud.js';
58
58
  import { BRAND_SVG_CSP, MANIFEST_PATH, appNameOf, brandAssetFile, brandImages, clientBrand, manifestOf } from '../core/brand.js';
59
59
  import { clientStrings } from '../core/strings.js';
60
+ import { clientLayers } from '../core/layers.js';
60
61
  import { MAX_THEME_ASSET_BYTES, MAX_THEME_BYTES, THEME_ASSET_PREFIX, THEME_NAME, THEME_SVG_CSP, clientTheme, cssProblems, cssUrls, fontOrigins, themeAssetFile, themeAssetPath, themeUrlTarget } from '../core/theme.js';
61
62
  import { decodePath, inside, notFound, sendFile } from './files.js';
62
63
  import { serveProposals } from './proposals.js';
@@ -81,7 +82,7 @@ import { compressResponse } from './compress.js';
81
82
  export const CORNFIELD_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
82
83
  const EXPLORER_DIR = path.join(CORNFIELD_DIR, 'explorer');
83
84
  /** The pure core modules the explorer imports (no Node built-ins, no files): the only ones of core/ served */
84
- export const BROWSER_CORE = ['schema.js', 'proposal.js', 'personas.js', 'cloud.js', 'text.js', 'mentions.js', 'color.js', 'strings.js'];
85
+ export const BROWSER_CORE = ['schema.js', 'proposal.js', 'personas.js', 'cloud.js', 'text.js', 'mentions.js', 'color.js', 'strings.js', 'layers.js'];
85
86
  /** The explorer files the sign-in pages load: cornfield's tokens, their own stylesheet and the script that applies Light or Dark. Served without a session. */
86
87
  const SIGN_IN_FILES = new Set(['/explorer/tokens.css', '/explorer/sign-in.css', '/explorer/theme-boot.js']);
87
88
  /** cornfield's own browser sources, by request path */
@@ -252,6 +253,8 @@ export function clientConfig(config, signIn = false) {
252
253
  brand: clientBrand(config.brand, PKG.homepage),
253
254
  // Only the labels the config overrides, as text (core/strings.js); the defaults are in the browser
254
255
  strings: clientStrings(config.strings),
256
+ // The project's own layers, as plain data of the known keys (core/layers.js; docs/config.md#layers)
257
+ layers: clientLayers(config.layers),
255
258
  forge: config.forge ? { type: config.forge.type, url: config.forge.url || (config.forge.type === 'github' ? 'https://github.com' : null), repo: config.forge.repo, mergeMethod: config.forge.mergeMethod || 'merge', ...(config.forge.baseBranch ? { baseBranch: config.forge.baseBranch } : {}), ...(config.approveLands ? { approveLands: true } : {}) } : null,
256
259
  // Threads (docs/threads.md): the idea label, or false when `threads: false` turns the Threads tab off
257
260
  threads: config.threads === false ? false : { label: ideaLabel(config) },