@popcorn245/cornfield 0.34.0 → 0.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core/strings.js CHANGED
@@ -19,6 +19,7 @@ export const STRINGS = Object.freeze({
19
19
  proposals: 'Proposals',
20
20
  issuesAndPrs: 'Work',
21
21
  searchPlaceholder: 'Search...',
22
+ searchNoMatch: 'No match for',
22
23
  signOut: 'Sign out',
23
24
  poweredBy: 'powered by cornfield',
24
25
  // The proposal bar and the review
@@ -10,19 +10,27 @@
10
10
  * @typedef {{ x: number, y: number, zoom: number }} Camera
11
11
  */
12
12
 
13
+ /** The floor of a map that fits above it; a bigger map (or a smaller screen) needs a lower one: render.js `getMinZoom()` */
13
14
  export const ZOOM_MIN = 0.25;
14
15
  export const ZOOM_MAX = 3.0;
16
+ /** Whatever the map, never below this (a bounding box of nothing, a map of a million px) */
17
+ export const ZOOM_FLOOR = 0.005;
15
18
 
16
- export const clampZoom = (zoom) => Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, zoom));
19
+ /** `min` is the floor for this map and screen (`getMinZoom()`); it never rises above the default floor */
20
+ export const clampZoom = (zoom, min = ZOOM_MIN) => Math.max(Math.max(ZOOM_FLOOR, Math.min(min, ZOOM_MIN)), Math.min(ZOOM_MAX, zoom));
21
+
22
+ /** Zooming out is never zooming in: below the floor already (the layers changed), a step out stays where it is */
23
+ const stepZoom = (from, to, min) => (to < from ? Math.min(from, clampZoom(to, min)) : clampZoom(to, min));
17
24
 
18
25
  /**
19
26
  * The camera after zooming by `factor` with the screen point (px, py) held still.
20
27
  * @param {Camera} camera
21
28
  * @param {number} factor
29
+ * @param {number} [min] the floor for this map
22
30
  * @returns {Camera}
23
31
  */
24
- export function zoomAbout(camera, factor, px, py) {
25
- const zoom = clampZoom(camera.zoom * factor);
32
+ export function zoomAbout(camera, factor, px, py, min = ZOOM_MIN) {
33
+ const zoom = stepZoom(camera.zoom, camera.zoom * factor, min);
26
34
  const wx = (px - camera.x) / camera.zoom; // the world point under the pointer
27
35
  const wy = (py - camera.y) / camera.zoom;
28
36
  return { x: px - wx * zoom, y: py - wy * zoom, zoom };
@@ -45,9 +53,34 @@ export const pinchStart = (camera, dist, mid) => ({ x: camera.x, y: camera.y, zo
45
53
  * @param {{ x: number, y: number }} mid their middle now
46
54
  * @returns {Camera}
47
55
  */
48
- export function pinchCamera(start, dist, mid) {
49
- const zoom = clampZoom(start.zoom * (dist / start.dist));
56
+ export function pinchCamera(start, dist, mid, min = ZOOM_MIN) {
57
+ const zoom = stepZoom(start.zoom, start.zoom * (dist / start.dist), min);
50
58
  const wx = (start.mid.x - start.x) / start.zoom;
51
59
  const wy = (start.mid.y - start.y) / start.zoom;
52
60
  return { x: mid.x - wx * zoom, y: mid.y - wy * zoom, zoom };
53
61
  }
62
+
63
+ /**
64
+ * The camera panned (never zoomed) so a world point is inside `box` (screen px), or null when it already is. A point
65
+ * outside is put in the middle of the box, on the axis it is outside of. `pad` is the room it needs from the edge
66
+ * (its disc and a little more); a box smaller than twice that is the centre only.
67
+ * @param {Camera} camera
68
+ * @param {{ x: number, y: number }} point world position
69
+ * @param {{ left: number, top: number, right: number, bottom: number }} box the part of the screen that shows the map
70
+ * @param {number} [pad]
71
+ * @returns {Camera|null}
72
+ */
73
+ export function panIntoView(camera, point, box, pad = 0) {
74
+ const sx = camera.x + point.x * camera.zoom;
75
+ const sy = camera.y + point.y * camera.zoom;
76
+ const px = Math.min(pad, (box.right - box.left) / 2);
77
+ const py = Math.min(pad, (box.bottom - box.top) / 2);
78
+ const outX = sx < box.left + px || sx > box.right - px;
79
+ const outY = sy < box.top + py || sy > box.bottom - py;
80
+ if (!outX && !outY) return null;
81
+ return {
82
+ x: outX ? (box.left + box.right) / 2 - point.x * camera.zoom : camera.x,
83
+ y: outY ? (box.top + box.bottom) / 2 - point.y * camera.zoom : camera.y,
84
+ zoom: camera.zoom,
85
+ };
86
+ }
@@ -1004,3 +1004,12 @@ a.hx-forge-row:hover, button.hx-forge-row:hover { background: var(--corn-surface
1004
1004
  .hx-more[hidden] { display: none; }
1005
1005
  .hx-more-btn { display: block; margin-top: var(--corn-space-1); min-height: 0; padding: 0; font-size: var(--corn-text-sm); }
1006
1006
  @media (max-width: 767px) { .hx-more-btn { min-height: 44px; } }
1007
+
1008
+ /* Search with no match (F24): one line under the field, a polite live region. Empty it takes no room. */
1009
+ .hx-search { position: relative; }
1010
+ .hx-search-status { position: absolute; top: calc(100% + var(--corn-space-2)); left: 0; right: 0; z-index: 40; padding: var(--corn-space-2) var(--corn-space-3); border-radius: var(--corn-radius-sm); border: var(--corn-border) solid var(--corn-line); background: var(--corn-surface-2); color: var(--corn-text); font-size: var(--corn-text-sm); overflow-wrap: anywhere; }
1011
+ .hx-search-status:empty { display: none; }
1012
+ .hx-mobile-search .hx-search-status { top: calc(100% - var(--corn-space-1)); left: var(--corn-space-3); right: var(--corn-space-3); }
1013
+
1014
+ /* The node panel's facts break at word boundaries only (F60): "hook" is never "hoo / k". A long path or name still wraps, at its slashes and dashes, and only as a last resort anywhere. */
1015
+ .hx-fact-v { overflow-wrap: break-word; word-break: normal; }
@@ -116,6 +116,7 @@
116
116
  <svg class="hx-search-icon" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true" focusable="false"><circle cx="7" cy="7" r="4.5" /><path d="M10.5 10.5L14 14" /></svg>
117
117
  <input type="text" id="node-search" class="hx-search-input" placeholder="Search..." data-corn-string-placeholder="searchPlaceholder" aria-label="Search nodes" aria-keyshortcuts="/" data-corn="search-input" />
118
118
  <kbd class="hx-kbd" aria-hidden="true">/</kbd>
119
+ <div id="search-status" class="hx-search-status" role="status" aria-live="polite" data-corn="search-status"></div>
119
120
  </div>
120
121
 
121
122
  <!-- The Work toggle (explorer/forge-panel.js): opens the Work panel; shown only when the config names a forge -->
@@ -174,6 +175,7 @@
174
175
  <input type="text" id="mobile-node-search" class="hx-input hx-input--wide" placeholder="Search nodes, apps, components..." aria-label="Search nodes" data-corn="search-input" />
175
176
  <button type="button" class="hx-textbtn" data-action="clear-search" aria-label="Clear search" data-corn-kind="quiet">✕</button>
176
177
  <button type="button" class="hx-textbtn" data-action="close-mobile-search" data-corn-kind="quiet">Cancel</button>
178
+ <div id="mobile-search-status" class="hx-search-status" role="status" aria-live="polite" data-corn="search-status"></div>
177
179
  </div>
178
180
 
179
181
  <!-- The map -->
package/explorer/input.js CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
 
15
15
  import { state, touchScene } from './state.js';
16
- import { render, getSpatialIndex, queueFrameWork, screenToWorld } from './render.js';
16
+ import { render, getSpatialIndex, queueFrameWork, screenToWorld, getMinZoom } from './render.js';
17
17
  import { saveFreeformPositions } from './layout.js';
18
18
  import { selectNode, closeDrawer } from './panels.js';
19
19
  import { hitTestScreen } from './spatial.js';
@@ -98,7 +98,7 @@ function onPointerDown(e) {
98
98
  /** One frame's worth of pointer movement: the pinch, the node being dragged, or the pan, from the latest position */
99
99
  function applyMoves() {
100
100
  if (pendingPinch && pinch) {
101
- Object.assign(state.camera, pinchCamera(pinch, pendingPinch.dist, pendingPinch.mid));
101
+ Object.assign(state.camera, pinchCamera(pinch, pendingPinch.dist, pendingPinch.mid, getMinZoom()));
102
102
  }
103
103
  pendingPinch = null;
104
104
 
@@ -210,7 +210,7 @@ export function bindCanvasInput() {
210
210
  canvas.addEventListener('wheel', (e) => {
211
211
  e.preventDefault();
212
212
  const p = getPointerPos(e);
213
- Object.assign(state.camera, zoomAbout(state.camera, e.deltaY < 0 ? 1.12 : 0.88, p.x, p.y));
213
+ Object.assign(state.camera, zoomAbout(state.camera, e.deltaY < 0 ? 1.12 : 0.88, p.x, p.y, getMinZoom()));
214
214
  render(); // a camera change is cheap; the draw is one per frame however many wheel events arrive
215
215
  }, { passive: false });
216
216
  }
@@ -18,7 +18,7 @@
18
18
  */
19
19
 
20
20
  import { state, touchScene } from './state.js';
21
- import { render, fitGraphToViewport, fitPadding, isNodeVisible } from './render.js';
21
+ import { render, fitGraphToViewport, fitPadding, isNodeVisible, getMinZoom } from './render.js';
22
22
  import { zoomAbout } from './camera.js';
23
23
  import { selectNode, closeDrawer } from './panels.js';
24
24
  import { saveFreeformPositions } from './layout.js';
@@ -99,7 +99,7 @@ function onMapKey(e) {
99
99
  render();
100
100
  break;
101
101
  case 'zoom':
102
- Object.assign(camera, zoomAbout(camera, action.factor, width / 2, height / 2));
102
+ Object.assign(camera, zoomAbout(camera, action.factor, width / 2, height / 2, getMinZoom()));
103
103
  render();
104
104
  announce(K.zoomWords(camera.zoom));
105
105
  break;
@@ -6,7 +6,7 @@
6
6
  * two layers by their kind (spec 0031): Cloud, and the Public web; the Cloud legend says what a call's `when` looks like.
7
7
  */
8
8
 
9
- import { state, touchScene } from './state.js';
9
+ import { state, touchScene, escHtml } from './state.js';
10
10
  import { render, ensureFlowLoop } from './render.js';
11
11
  import { renderFlowLegend } from './flows.js';
12
12
  import { layerOf } from './live-model.js';
@@ -23,6 +23,8 @@ export const LAYER_DEFS = [
23
23
  { key: 'token', label: 'Design Tokens', color: '#ec4899', desc: 'Pollen CSS' },
24
24
  { key: 'tool', label: 'Dev Tools', color: '#f43f5e', desc: 'Utilities' },
25
25
  { key: 'flow', label: 'Data Flow', color: '#fb923c', desc: 'Tiers & sync' },
26
+ { key: 'core', label: 'Core', color: '#14b8a6', desc: 'The shared core: what the apps and packages are built on. Shows with Packages or Atoms' },
27
+ { key: 'store', label: 'Stores', color: '#fb923c', desc: 'Storage tiers and the ends of the data flows. Shows with Data Flow' },
26
28
  { key: 'table', label: 'Tables', color: '#fde047', desc: 'SQLite tables, reads & writes' },
27
29
  { key: 'rom', label: 'ROM', color: '#f0abfc', desc: 'Render on Mutation' },
28
30
  { key: 'service', label: 'Services', color: '#84cc16', desc: 'API jobs, webhooks and hooks' },
@@ -62,12 +64,32 @@ export function closeLegendMenu() {
62
64
  setLegendMenu(false);
63
65
  }
64
66
 
65
- /** The chip says how many layers are on: " · 13 of 20" */
67
+ /** The key of the row a node is under (the Layers menu has a row for every type on the map) */
68
+ const rowKey = (n) => (n.type === 'external' ? externalLayer(n) : layerOf(n.type));
69
+
70
+ /**
71
+ * The rows: the defined ones, and one more for any node type on this map that none of them covers (a type a plugin or
72
+ * a newer sync adds), so every type present can be turned off. `root` is always shown and has no row.
73
+ */
74
+ function layerRows() {
75
+ const known = new Set(LAYER_DEFS.map((l) => l.key));
76
+ const extra = [];
77
+ state.nodes.forEach((n) => {
78
+ const key = rowKey(n);
79
+ if (key === 'root' || known.has(key)) return;
80
+ known.add(key);
81
+ extra.push({ key, label: key.charAt(0).toUpperCase() + key.slice(1), color: '#94a3b8', desc: `Nodes of the type ${key}` });
82
+ });
83
+ return [...LAYER_DEFS, ...extra];
84
+ }
85
+
86
+ /** The chip says how many layers are on: " · 13 of 20". An overlay (Runs in flight) is not a layer: it is not counted */
66
87
  function paintCount() {
67
88
  const el = document.getElementById('layers-count');
68
89
  if (!el) return;
69
- const on = LAYER_DEFS.filter((l) => state.activeLayers[l.key] !== false).length;
70
- el.textContent = ` · ${on} of ${LAYER_DEFS.length}`;
90
+ const layers = layerRows().filter((l) => !l.overlay);
91
+ const on = layers.filter((l) => state.activeLayers[l.key] !== false).length;
92
+ el.textContent = ` · ${on} of ${layers.length}`;
71
93
  }
72
94
 
73
95
  export function renderLayerToggles() {
@@ -75,22 +97,24 @@ export function renderLayerToggles() {
75
97
  const container = document.getElementById('layer-toggles-container');
76
98
  if (!container) return;
77
99
 
100
+ // Nodes by row. Data Flow has no nodes of its own: it counts its links, and says so; Runs in flight counts runs
78
101
  const counts = {};
79
- state.nodes.forEach((n) => { const key = n.type === 'external' ? externalLayer(n) : layerOf(n.type); counts[key] = (counts[key] || 0) + 1; });
102
+ state.nodes.forEach((n) => { const key = rowKey(n); counts[key] = (counts[key] || 0) + 1; });
80
103
  counts.flow = state.edges.filter((e) => e.kind === 'flow').length;
81
104
  counts.runs = state.runsMap ? state.runsMap.flight.size : 0;
105
+ const unit = { flow: (n) => `${n} ${n === 1 ? 'link' : 'links'}`, runs: (n) => `${n} in flight` };
82
106
 
83
- container.innerHTML = LAYER_DEFS.map((layer) => {
107
+ container.innerHTML = layerRows().map((layer) => {
84
108
  const on = state.activeLayers[layer.key] !== false;
85
109
  const color = themed(layer.color, state.theme); // the dot is the colour the map draws on this ground
86
110
  return `
87
- <button type="button" class="hx-toggle-row${on ? '' : ' is-off'}" data-action="toggle-layer" data-layer="${layer.key}" aria-pressed="${on}" title="${layer.desc}" data-corn="row">
111
+ <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">
88
112
  <span class="hx-toggle-label">
89
113
  <span class="hx-dot" style="background-color: ${color}; box-shadow: ${on && state.theme !== 'light' ? `0 0 8px ${color}90` : 'none'}"></span>
90
- <span class="hx-toggle-name">${layer.label}</span>${layer.live ? '<span class="hx-live-tag">live</span>' : ''}
114
+ <span class="hx-toggle-name">${escHtml(layer.label)}</span>${layer.live ? '<span class="hx-live-tag">live</span>' : ''}
91
115
  </span>
92
116
  <span class="hx-toggle-meta">
93
- <span class="hx-count">${counts[layer.key] || 0}</span>
117
+ <span class="hx-count">${(unit[layer.key] || String)(counts[layer.key] || 0)}</span>
94
118
  <span class="hx-tick">${on ? '✓' : '—'}</span>
95
119
  </span>
96
120
  </button>`;
@@ -83,6 +83,68 @@ function ringPack(items, { first = 110, gap = 76, spacing = 90 } = {}) {
83
83
  return { offsets, radii };
84
84
  }
85
85
 
86
+ /**
87
+ * A cluster's whole pack: `children` in rings around the centre, and a child that has children of its own (a store
88
+ * owning 46 outside services) gets its own rings, placed on an outer ring of this cluster with room for them.
89
+ * `kidsOf(node)` says who hangs under a node. Returns `{ children, offsets, radii, subs, extent }`: `subs[i]` is the
90
+ * child i's own pack (or null), `extent` how far the whole thing reaches from the centre.
91
+ */
92
+ function packTree(children, kidsOf, spacingOf, byOrder, seen = new Set()) {
93
+ const withSub = [];
94
+ const plain = [];
95
+ children.forEach((c) => {
96
+ const kids = seen.has(c.id) ? [] : kidsOf(c);
97
+ if (!kids.length) { plain.push(c); return; }
98
+ seen.add(c.id);
99
+ const sub = packTree(kids.sort(byOrder), kidsOf, spacingOf, byOrder, seen);
100
+ withSub.push({ c, sub, fp: sub.extent });
101
+ });
102
+ withSub.sort((a, b) => b.fp - a.fp);
103
+ const pack = ringPack(plain, { spacing: spacingOf(children) });
104
+ const out = {
105
+ children: [...plain], offsets: [...pack.offsets], radii: pack.radii, subs: plain.map(() => null),
106
+ extent: pack.radii.length ? pack.radii[pack.radii.length - 1] + 40 : 0,
107
+ };
108
+ if (withSub.length) {
109
+ const lastR = pack.radii.length ? pack.radii[pack.radii.length - 1] : 0;
110
+ const fpMax = withSub[0].fp;
111
+ const arc = withSub.reduce((sum, w) => sum + 2 * w.fp + 30, 0);
112
+ // Each takes arc in proportion to its size; two of them are a chord apart, not an arc, so the ring is as wide as
113
+ // the closest pair needs (for three or more large ones, more than the arc says)
114
+ const mids = [];
115
+ let a = -Math.PI / 2;
116
+ withSub.forEach((w) => { const share = ((2 * w.fp + 30) / arc) * Math.PI * 2; mids.push(a + share / 2); a += share; });
117
+ let r = Math.max(110, lastR + fpMax + 40, arc / (2 * Math.PI));
118
+ for (let i = 0; i < withSub.length; i++) {
119
+ for (let j = i + 1; j < withSub.length; j++) {
120
+ const half = Math.sin(Math.abs(mids[j] - mids[i]) / 2);
121
+ if (half > 1e-6) r = Math.max(r, (withSub[i].fp + withSub[j].fp + 30) / (2 * half));
122
+ }
123
+ }
124
+ withSub.forEach((w, i) => {
125
+ out.children.push(w.c);
126
+ out.offsets.push({ x: Math.cos(mids[i]) * r, y: Math.sin(mids[i]) * r });
127
+ out.subs.push(w.sub);
128
+ });
129
+ out.bigRadius = r;
130
+ out.extent = Math.max(out.extent, r + fpMax);
131
+ }
132
+ return out;
133
+ }
134
+
135
+ /** Puts a pack's children (and theirs) around (ox, oy); a child's own rings are added to `clusters` */
136
+ function placePack(pack, ox, oy, clusters) {
137
+ pack.children.forEach((c, i) => {
138
+ c.x = ox + pack.offsets[i].x;
139
+ c.y = oy + pack.offsets[i].y;
140
+ const sub = pack.subs[i];
141
+ if (sub) {
142
+ clusters.push({ x: c.x, y: c.y, radii: sub.radii });
143
+ placePack(sub, c.x, c.y, clusters);
144
+ }
145
+ });
146
+ }
147
+
86
148
  export function computeOrbitalLayout() {
87
149
  touchScene(); // positions and rings change
88
150
  const { nodes, edges } = state;
@@ -90,9 +152,19 @@ export function computeOrbitalLayout() {
90
152
  state.rings = { rings: [], clusters: [] };
91
153
  const LAYOUT = state.rings;
92
154
 
155
+ const ids = new Set(nodes.map((n) => n.id));
93
156
  const parentMap = {};
94
157
  edges.forEach((e) => {
95
- if (!e.dashed && !e.kind && e.from && e.to && !parentMap[e.to]) parentMap[e.to] = e.from;
158
+ // A parent that is not on the map (an edge a proposal left behind) is no parent: the node would sit on the centre
159
+ if (!e.dashed && !e.kind && e.from && e.to && ids.has(e.from) && e.from !== e.to && !parentMap[e.to]) parentMap[e.to] = e.from;
160
+ });
161
+ // Nor is a parent that is its own ancestor: the first node of a loop loses its parent, so the loop hangs from it
162
+ nodes.forEach((n) => {
163
+ const path = new Set([n.id]);
164
+ for (let p = parentMap[n.id]; p; p = parentMap[p]) {
165
+ if (path.has(p)) { delete parentMap[p]; break; }
166
+ path.add(p);
167
+ }
96
168
  });
97
169
 
98
170
  // topology.json stores no positions; a node the passes below do not place starts at the centre
@@ -102,11 +174,18 @@ export function computeOrbitalLayout() {
102
174
 
103
175
  const isData = (n) => DATA_TYPES.includes(n.type);
104
176
  const hasChildren = new Set(Object.values(parentMap));
105
- // A data store with tables of its own is a cluster like an app; other data rings the root
177
+ const parentsOfNonData = new Set(nodes.filter((k) => parentMap[k.id] && !isData(k)).map((k) => parentMap[k.id]));
178
+ // A data store with children of its own (tables, outside services) is a cluster like an app; other data rings the root
179
+ // and so is any node with no parent but children of its own (its children need somewhere to go)
106
180
  const isHub = (n) => n.id !== 'root' && (isData(n)
107
- ? n.type === 'store' && hasChildren.has(n.id) && !parentMap[n.id]
108
- : parentMap[n.id] === 'root' || (!parentMap[n.id] && ['app', 'pkg', 'tool', 'external', 'stack'].includes(n.type)));
109
- const hubs = nodes.filter(isHub);
181
+ ? hasChildren.has(n.id) && (!parentMap[n.id] || parentMap[n.id] === 'root')
182
+ && (n.type === 'store' || parentsOfNonData.has(n.id))
183
+ : parentMap[n.id] === 'root' || (!parentMap[n.id] && (hasChildren.has(n.id) || ['app', 'pkg', 'tool', 'external', 'stack'].includes(n.type))));
184
+ const firstHubs = new Set(nodes.filter(isHub).map((h) => h.id));
185
+ // A data node that would ring the root (its parent is no hub) but has other nodes under it is a cluster too: the
186
+ // data ring has no room for them
187
+ const hubs = nodes.filter((n) => firstHubs.has(n.id)
188
+ || (n.id !== 'root' && isData(n) && parentsOfNonData.has(n.id) && !firstHubs.has(parentMap[n.id])));
110
189
  const hubIds = new Set(hubs.map((h) => h.id));
111
190
  const typeRank = (n) => { const i = CHILD_TYPE_ORDER.indexOf(n.type); return i < 0 ? 99 : i; };
112
191
  const byTypeThenLabel = (a, b) => typeRank(a) - typeRank(b) || String(a.label).localeCompare(String(b.label));
@@ -124,15 +203,15 @@ export function computeOrbitalLayout() {
124
203
  const coreExtent = data.length ? dataR + 50 : 60;
125
204
  if (data.length) LAYOUT.rings.push({ x: 0, y: 0, r: dataR });
126
205
 
127
- // 2. Pack each hub's children (relative to the hub)
206
+ // 2. Pack each hub's children (relative to the hub). A child with children of its own (a store that owns the
207
+ // outside services) gets rings of its own, and they count in the cluster's extent.
208
+ const kidsOf = (n) => (n.id === 'root' ? [] : nodes.filter((k) => parentMap[k.id] === n.id && !hubIds.has(k.id) && !isData(k) && k.id !== 'root'));
209
+ const spacingOf = (list) => Math.min(170, Math.max(84, ...list.map((c) => labelWidth(c) * 0.8 + 26)));
128
210
  const packs = new Map();
129
211
  hubs.forEach((hub) => {
130
212
  const children = nodes.filter((n) => parentMap[n.id] === hub.id && !hubIds.has(n.id)).sort(byTypeThenLabel);
131
213
  if (!children.length) return;
132
- const spacing = Math.min(170, Math.max(84, ...children.map((c) => labelWidth(c) * 0.8 + 26)));
133
- const pack = ringPack(children, { spacing });
134
- const extent = pack.radii[pack.radii.length - 1] + 40;
135
- packs.set(hub.id, { children, ...pack, extent });
214
+ packs.set(hub.id, packTree(children, kidsOf, spacingOf, byTypeThenLabel, new Set([hub.id])));
136
215
  });
137
216
 
138
217
  // 3. Hubs with children around the core, arc proportional to cluster size
@@ -143,19 +222,21 @@ export function computeOrbitalLayout() {
143
222
  const hubR = Math.max(coreExtent + maxExtent + GAP, need / (2 * Math.PI));
144
223
  let angle = -Math.PI / 2;
145
224
  big.forEach((hub) => {
146
- const { extent, children, offsets, radii } = packs.get(hub.id);
147
- const share = ((2 * extent + GAP) / need) * Math.PI * 2;
225
+ const pack = packs.get(hub.id);
226
+ const share = ((2 * pack.extent + GAP) / need) * Math.PI * 2;
148
227
  const a = angle + share / 2;
149
228
  hub.x = Math.cos(a) * hubR;
150
229
  hub.y = Math.sin(a) * hubR;
151
- children.forEach((c, i) => { c.x = hub.x + offsets[i].x; c.y = hub.y + offsets[i].y; });
152
- LAYOUT.clusters.push({ x: hub.x, y: hub.y, radii });
230
+ LAYOUT.clusters.push({ x: hub.x, y: hub.y, radii: pack.radii });
231
+ placePack(pack, hub.x, hub.y, LAYOUT.clusters);
153
232
  angle += share;
154
233
  });
155
234
  if (big.length) LAYOUT.rings.push({ x: 0, y: 0, r: hubR });
156
235
 
157
- // 4. Childless hubs on an outer ring
158
- const leaves = hubs.filter((h) => !packs.has(h.id)).sort(byTypeThenLabel);
236
+ // 4. Childless hubs on an outer ring, and with them any node that has no parent and is none of the above
237
+ // (it would otherwise sit on the centre, under whatever else is there)
238
+ const homeless = nodes.filter((n) => n.id !== 'root' && !parentMap[n.id] && !isData(n) && !hubIds.has(n.id));
239
+ const leaves = [...hubs.filter((h) => !packs.has(h.id)), ...homeless].sort(byTypeThenLabel);
159
240
  const leafSpacing = Math.max(120, ...leaves.map((n) => labelWidth(n) + 30));
160
241
  const leafR = Math.max(hubR + maxExtent + 90, (leaves.length * leafSpacing) / (2 * Math.PI));
161
242
  leaves.forEach((n, i) => {
@@ -165,13 +246,23 @@ export function computeOrbitalLayout() {
165
246
  });
166
247
  if (leaves.length) LAYOUT.rings.push({ x: 0, y: 0, r: leafR });
167
248
 
168
- // Anything left (a child of a non-hub) sits just outside its parent
249
+ // Anything still on the centre is a child of a node the passes above did not pack (a child of a data node on the
250
+ // core ring, say): it goes in rings around its parent, with its own children in rings around it, never on one point
251
+ const placedAt = (n) => n.id === 'root' || n.x !== 0 || n.y !== 0;
252
+ const stuckUnder = new Map();
169
253
  nodes.forEach((n) => {
170
- const p = parentMap[n.id] && nodes.find((x) => x.id === parentMap[n.id]);
171
- if (!p || hubIds.has(p.id) || p.id === 'root' || isData(n) || hubIds.has(n.id)) return;
172
- const d = Math.hypot(p.x, p.y) || 1;
173
- n.x = p.x + (p.x / d) * 70;
174
- n.y = p.y + (p.y / d) * 70;
254
+ const pid = parentMap[n.id];
255
+ if (placedAt(n) || !pid) return;
256
+ (stuckUnder.get(pid) || stuckUnder.set(pid, []).get(pid)).push(n);
257
+ });
258
+ const byId = new Map(nodes.map((n) => [n.id, n]));
259
+ stuckUnder.forEach((list, pid) => {
260
+ const p = byId.get(pid);
261
+ if (!p || !placedAt(p)) return; // its parent is stuck too: it is placed with it, in the parent's pack
262
+ if (list.every(placedAt)) return; // placed already, in a pack higher up
263
+ const pack = packTree(list.sort(byTypeThenLabel), kidsOf, spacingOf, byTypeThenLabel, new Set([pid]));
264
+ LAYOUT.clusters.push({ x: p.x, y: p.y, radii: pack.radii });
265
+ placePack(pack, p.x, p.y, LAYOUT.clusters);
175
266
  });
176
267
  }
177
268
 
package/explorer/main.js CHANGED
@@ -24,6 +24,7 @@
24
24
  */
25
25
 
26
26
  import { state, nodeById, touchScene } from './state.js';
27
+ import { updateSearchStatus } from './search-status.js';
27
28
  import { render, resize, fitGraphToViewport, fitPadding, isNodeVisible, setRenderer, getRenderer, ensureFlowLoop, renderNow, holdFrames } from './render.js';
28
29
  import { createRenderer } from './renderer.js';
29
30
  import { clearFreeformPositions, layoutOrbit, loadFreeformPositions } from './layout.js';
@@ -95,6 +96,9 @@ function handleSearch(value) {
95
96
  state.camera.x = state.width / 2 - found.x * state.camera.zoom;
96
97
  state.camera.y = state.height / 2 - found.y * state.camera.zoom;
97
98
  }
99
+ updateSearchStatus(state.searchQuery, !!found);
100
+ } else {
101
+ updateSearchStatus('', false);
98
102
  }
99
103
  render();
100
104
  }
@@ -12,7 +12,8 @@ import { flowSummary } from './flows.js';
12
12
  import { clearScenario } from './scenario-ui.js';
13
13
  import { kindOfMark, fieldRows, MARK_WORDS } from './proposal-model.js';
14
14
  import { nodeMockupsHtml } from './mockups-model.js';
15
- import { collapseSheet } from './sheets.js';
15
+ import { collapseSheet, isPhone, measureCovered, onCoveredChange } from './sheets.js';
16
+ import { panIntoView } from './camera.js';
16
17
  import { liveSection, hydrateLivePhotos } from './live.js';
17
18
  import { cloudPanelHtml } from './cloud-model.js';
18
19
  import { t } from './strings.js';
@@ -94,7 +95,9 @@ function dataSummary(node) {
94
95
  }
95
96
  if (node.type === 'service') {
96
97
  const row = (e, side) => `${nm(e[side])}${e.label && e.label !== 'imports' ? ` · ${escHtml(e.label)}` : ''}`;
97
- return section('Kind:', [line(`${code(node.kind)}${node.summary ? `<div class="hx-faint">${escHtml(node.summary)}</div>` : ''}`)])
98
+ // The summary is the first sentence of the description above: shown again only when the description does not hold it
99
+ const again = node.summary && !String(node.desc || '').includes(node.summary);
100
+ return section('Kind:', [line(`${code(node.kind)}${again ? `<div class="hx-faint">${escHtml(node.summary)}</div>` : ''}`)])
98
101
  + section('Started by:', [...(node.triggers || []).map((t) => line(escHtml(t))), ...edgesOf('triggers', 'to', node.id).map((e) => line(row(e, 'from')))])
99
102
  + section('Jobs:', (node.jobs || []).map((j) => line(`${code(j.name)} · cron ${code(j.cron)}`)))
100
103
  + section('Runs:', edgesOf('triggers', 'from', node.id).map((e) => line(row(e, 'to'))))
@@ -272,8 +275,24 @@ export async function selectNode(node) {
272
275
  $('spec-drawer').classList.add('drawer-open');
273
276
  $('spec-drawer').inert = false; // closed, it waits off screen: inert, so Tab never reaches its buttons (MAP-02)
274
277
  $('drawer-backdrop').hidden = false;
278
+ keepSelectedInView();
275
279
  }
276
280
 
281
+ /**
282
+ * On a phone the node's sheet covers the bottom of the map (sheets.js): when the selected node is under it, or
283
+ * gets covered as the sheet expands, pan the map (never zoom it) so the node is in the part still showing (F32)
284
+ */
285
+ export function keepSelectedInView() {
286
+ const node = state.selectedNode;
287
+ if (!node || !state.width || !isPhone()) return;
288
+ const covered = measureCovered();
289
+ const next = panIntoView(state.camera, node, { left: 0, top: 0, right: state.width, bottom: state.height - covered }, node.r * state.camera.zoom + 16);
290
+ if (!next) return;
291
+ Object.assign(state.camera, next);
292
+ render();
293
+ }
294
+ onCoveredChange(() => keepSelectedInView());
295
+
277
296
  /** Start a run: the Start dialog of the Work panel, on the proposal that is open */
278
297
  export function startRun() {
279
298
  if (state.proposalSlug) openProposalStart(state.proposalSlug, '#drawer-run-btn');
@@ -15,6 +15,7 @@ import { createSpatialCache } from './spatial.js';
15
15
  import { createFrameScheduler, packetsOnScreen } from './frame.js';
16
16
  import { createLabelLayer } from './labels.js';
17
17
  import { measureCovered } from './sheets.js';
18
+ import { ZOOM_MIN, ZOOM_FLOOR } from './camera.js';
18
19
 
19
20
  // ---------------------------------------------------------------------------
20
21
  // Visibility and focus (decided in scene.js, kept here under their old names)
@@ -93,15 +94,15 @@ export function resize() {
93
94
  render();
94
95
  }
95
96
 
96
- /** Zoom and pan so every visible node (and its label) is on screen; `only` (a Set of ids) narrows it to those, when any are visible */
97
- export function fitGraphToViewport(padding = 40, only = null) {
98
- const { nodes, width, height, camera } = state;
97
+ /** The box the fit shows (world px) and the zoom that makes it fill the screen, before any limit; null with nothing to show */
98
+ function fitTarget(padding, only = null) {
99
+ const { nodes, width, height } = state;
99
100
  let visible = nodes.filter(isNodeVisible);
100
101
  if (only) {
101
102
  const part = visible.filter((n) => only.has(n.id));
102
103
  if (part.length) visible = part;
103
104
  }
104
- if (visible.length === 0) return;
105
+ if (visible.length === 0) return null;
105
106
  // The phone's sheets hide the bottom of the map (sheets.js): fit into the part they leave
106
107
  const mapHeight = Math.max(160, height - measureCovered());
107
108
 
@@ -118,7 +119,34 @@ export function fitGraphToViewport(padding = 40, only = null) {
118
119
 
119
120
  const availWidth = Math.max(160, width - padding * 2);
120
121
  const availHeight = Math.max(160, mapHeight - padding * 2);
121
- const targetZoom = Math.min(1.0, Math.max(0.18, Math.min(availWidth / (maxX - minX), availHeight / (maxY - minY))));
122
+ const raw = Math.min(availWidth / (maxX - minX), availHeight / (maxY - minY));
123
+ return { minX, maxX, minY, maxY, mapHeight, raw };
124
+ }
125
+
126
+ let minZoomKey = '';
127
+ let minZoomValue = ZOOM_MIN;
128
+
129
+ /**
130
+ * The lowest zoom for this map on this screen: low enough that Fit shows all of it (at most the default floor, so a small
131
+ * map keeps its limit). Hand zoom (wheel, pinch, keys) and Fit share it.
132
+ */
133
+ export function getMinZoom() {
134
+ const key = `${state.sceneVersion}|${state.width}|${state.height}|${state.view}|${measureCovered()}`;
135
+ if (key !== minZoomKey) {
136
+ minZoomKey = key;
137
+ const t = fitTarget(fitPadding());
138
+ minZoomValue = t && t.raw > 0 && Number.isFinite(t.raw) ? Math.max(ZOOM_FLOOR, Math.min(ZOOM_MIN, t.raw)) : ZOOM_MIN;
139
+ }
140
+ return minZoomValue;
141
+ }
142
+
143
+ /** Zoom and pan so every visible node (and its label) is on screen; `only` (a Set of ids) narrows it to those, when any are visible */
144
+ export function fitGraphToViewport(padding = 40, only = null) {
145
+ const { width, camera } = state;
146
+ const t = fitTarget(padding, only);
147
+ if (!t) return;
148
+ const { minX, maxX, minY, maxY, mapHeight } = t;
149
+ const targetZoom = Math.min(1.0, Math.max(ZOOM_FLOOR, t.raw));
122
150
 
123
151
  camera.zoom = targetZoom;
124
152
  camera.x = width / 2 - ((minX + maxX) / 2) * targetZoom;
@@ -12,6 +12,8 @@ import { CORE_RATIO, ARROW, MARK_MIN_PX, looksFor, packetPoint } from './scene.j
12
12
  import { ICON_RATIO, getMapStyle, looksWith, styledScene } from './map-style.js';
13
13
 
14
14
  const TAU = Math.PI * 2;
15
+ /** A glow thinner than this on screen (px) is not drawn: zoomed out it is a fraction of a pixel, and costs a stroke or fill per edge and node */
16
+ const GLOW_MIN_PX = 1.5;
15
17
  const circle = (ctx, x, y, r) => { ctx.beginPath(); ctx.arc(x, y, r, 0, TAU); };
16
18
 
17
19
  // ---------------------------------------------------------------------------
@@ -61,7 +63,7 @@ function drawLanes(ctx, lanes) {
61
63
  // ---------------------------------------------------------------------------
62
64
  // Edges
63
65
  // ---------------------------------------------------------------------------
64
- function drawEdge(ctx, edge, timeMs, zoom) {
66
+ function drawEdge(ctx, edge, timeMs, zoom, withPacket = true) {
65
67
  ctx.save();
66
68
  ctx.globalAlpha = edge.alpha;
67
69
 
@@ -72,12 +74,18 @@ function drawEdge(ctx, edge, timeMs, zoom) {
72
74
  ctx.strokeStyle = edge.color;
73
75
  ctx.lineWidth = edge.mark && edge.mark !== 'none' ? Math.max(edge.width, MARK_MIN_PX.edge / zoom) : edge.width; // a proposal's marks stay visible zoomed out
74
76
  ctx.setLineDash(edge.dash || []);
75
- if (edge.glow) {
76
- ctx.shadowColor = edge.glowColor;
77
- ctx.shadowBlur = edge.glow;
77
+ if (edge.glow && edge.glow * zoom >= GLOW_MIN_PX) {
78
+ // The glow is a wider, fainter stroke under the line, not `shadowBlur`: a blur per edge is a full-canvas blur
79
+ // pass each, and a selected hub lights ~900 edges (F30: 8 to 10 s a tap on a phone)
80
+ const line = ctx.lineWidth;
81
+ ctx.save();
82
+ ctx.globalAlpha = edge.alpha * 0.3;
83
+ ctx.strokeStyle = edge.glowColor || edge.color;
84
+ ctx.lineWidth = line + edge.glow * 0.6;
85
+ ctx.stroke();
86
+ ctx.restore();
78
87
  }
79
88
  ctx.stroke();
80
- ctx.shadowBlur = 0;
81
89
  ctx.setLineDash([]);
82
90
 
83
91
  // Arrowhead along the curve's end tangent
@@ -95,15 +103,33 @@ function drawEdge(ctx, edge, timeMs, zoom) {
95
103
 
96
104
  // The edge's label (selection only) is the label layer's, not drawn here
97
105
 
98
- if (edge.packet) {
99
- const p = packetPoint(edge, timeMs);
106
+ if (withPacket && edge.packet) drawPacketIn(ctx, edge, timeMs, zoom);
107
+ ctx.restore();
108
+ }
109
+
110
+ /** The packet's dot: a soft disc under it for the glow (no `shadowBlur`: see drawEdge), then the dot */
111
+ function drawPacketIn(ctx, edge, timeMs, zoom) {
112
+ const p = packetPoint(edge, timeMs);
113
+ const { packet } = edge;
114
+ if (packet.glow && packet.glow * zoom >= GLOW_MIN_PX) {
100
115
  ctx.beginPath();
101
- ctx.arc(p.x, p.y, edge.packet.radius, 0, TAU);
102
- ctx.fillStyle = edge.packet.color;
103
- ctx.shadowColor = edge.packet.glowColor;
104
- ctx.shadowBlur = edge.packet.glow;
116
+ ctx.arc(p.x, p.y, packet.radius + packet.glow * 0.5, 0, TAU);
117
+ ctx.globalAlpha = edge.alpha * 0.3;
118
+ ctx.fillStyle = packet.glowColor || packet.color;
105
119
  ctx.fill();
120
+ ctx.globalAlpha = edge.alpha;
106
121
  }
122
+ ctx.beginPath();
123
+ ctx.arc(p.x, p.y, packet.radius, 0, TAU);
124
+ ctx.fillStyle = packet.color;
125
+ ctx.fill();
126
+ }
127
+
128
+ /** A packet on its own (the layer cache below draws the edges' lines once and the packets every frame) */
129
+ function drawPacket(ctx, edge, timeMs, zoom) {
130
+ ctx.save();
131
+ ctx.globalAlpha = edge.alpha;
132
+ drawPacketIn(ctx, edge, timeMs, zoom);
107
133
  ctx.restore();
108
134
  }
109
135
 
@@ -143,13 +169,18 @@ function drawNode(ctx, node, zoom, looks, style) {
143
169
 
144
170
  // The node circle, glowing, with a white core dot
145
171
  circle(ctx, node.x, node.y, node.r);
146
- ctx.fillStyle = node.color;
147
- if (node.glow) {
148
- ctx.shadowColor = node.color;
149
- ctx.shadowBlur = node.glow;
172
+ if (node.glow && node.glow * zoom >= GLOW_MIN_PX) {
173
+ // A soft disc behind the node, not `shadowBlur` (see drawEdge): one cheap fill instead of a blur pass
174
+ ctx.save();
175
+ ctx.globalAlpha = node.alpha * 0.28;
176
+ circle(ctx, node.x, node.y, node.r + node.glow * 0.7);
177
+ ctx.fillStyle = node.color;
178
+ ctx.fill();
179
+ ctx.restore();
180
+ circle(ctx, node.x, node.y, node.r);
150
181
  }
182
+ ctx.fillStyle = node.color;
151
183
  ctx.fill();
152
- ctx.shadowBlur = 0;
153
184
  circle(ctx, node.x, node.y, node.r * CORE_RATIO);
154
185
  ctx.fillStyle = looks.core;
155
186
  ctx.fill();
@@ -186,6 +217,41 @@ export function createCanvas2dRenderer(canvas, opts = {}) {
186
217
  const ctx = canvas.getContext('2d');
187
218
  let width = 0;
188
219
  let height = 0;
220
+ let ratio = 1;
221
+
222
+ // The still part of a frame (the background and every edge's line) is drawn once into `layer` and blitted while only
223
+ // the packets move: a hub's selection lights hundreds of packets, and redrawing thousands of lines on each frame is
224
+ // what made a tap take seconds on a phone (F30). Used only when the scene has packets and a canvas can be made.
225
+ let layer = null;
226
+ let layerCtx = null;
227
+ let layerFor = null; // what the layer shows: { scene, x, y, zoom, w, h }
228
+ const makeLayer = () => {
229
+ if (layer) return layer;
230
+ try {
231
+ layer = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(canvas.width || 1, canvas.height || 1)
232
+ : typeof document !== 'undefined' ? document.createElement('canvas') : null;
233
+ layerCtx = layer && layer.getContext ? layer.getContext('2d') : null;
234
+ } catch { layerCtx = null; }
235
+ if (!layerCtx) layer = null;
236
+ return layer;
237
+ };
238
+ const hasPacket = new WeakMap();
239
+ const packetsIn = (scene) => {
240
+ if (!hasPacket.has(scene)) hasPacket.set(scene, scene.edges.some((e) => e.packet));
241
+ return hasPacket.get(scene);
242
+ };
243
+
244
+ function drawStill(c, scene, camera) {
245
+ c.save();
246
+ c.translate(camera.x, camera.y);
247
+ c.scale(camera.zoom, camera.zoom);
248
+ const { decor } = scene;
249
+ if (decor.grid) drawGrid(c, decor.grid, camera, width, height);
250
+ if (decor.lanes.length) drawLanes(c, decor.lanes);
251
+ if (decor.rings.length) drawRings(c, decor.rings);
252
+ scene.edges.forEach((edge) => drawEdge(c, edge, 0, camera.zoom, false));
253
+ c.restore();
254
+ }
189
255
 
190
256
  return {
191
257
  kind: 'canvas2d',
@@ -193,15 +259,42 @@ export function createCanvas2dRenderer(canvas, opts = {}) {
193
259
  resize(w, h, dpr) {
194
260
  width = w;
195
261
  height = h;
262
+ ratio = dpr;
196
263
  canvas.width = w * dpr;
197
264
  canvas.height = h * dpr;
198
265
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
266
+ layerFor = null;
267
+ if (layer) { layer.width = canvas.width; layer.height = canvas.height; layerCtx.setTransform(dpr, 0, 0, dpr, 0, 0); }
199
268
  },
200
269
 
201
270
  draw(drawn, camera, timeMs) {
202
271
  const style = styleOf();
203
272
  const scene = styledScene(drawn, style); // the map in the theme's colours (map-style.js); the scene itself when nothing is set
204
273
  ctx.clearRect(0, 0, width, height);
274
+
275
+ const looks = looksWith(looksFor(scene.theme), style); // the halos, mark rings and core for the scene's ground, in the theme's colours
276
+ if (packetsIn(scene) && makeLayer()) {
277
+ const same = layerFor && layerFor.scene === scene && layerFor.x === camera.x && layerFor.y === camera.y && layerFor.zoom === camera.zoom && layerFor.w === canvas.width && layerFor.h === canvas.height;
278
+ if (!same) {
279
+ if (layer.width !== canvas.width || layer.height !== canvas.height) { layer.width = canvas.width; layer.height = canvas.height; }
280
+ layerCtx.setTransform(ratio, 0, 0, ratio, 0, 0);
281
+ layerCtx.clearRect(0, 0, width, height);
282
+ drawStill(layerCtx, scene, camera);
283
+ layerFor = { scene, x: camera.x, y: camera.y, zoom: camera.zoom, w: canvas.width, h: canvas.height };
284
+ }
285
+ ctx.save();
286
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
287
+ ctx.drawImage(layer, 0, 0);
288
+ ctx.restore();
289
+ ctx.save();
290
+ ctx.translate(camera.x, camera.y);
291
+ ctx.scale(camera.zoom, camera.zoom);
292
+ scene.edges.forEach((edge) => { if (edge.packet) drawPacket(ctx, edge, timeMs, camera.zoom); });
293
+ scene.nodes.forEach((node) => drawNode(ctx, node, camera.zoom, looks, style));
294
+ ctx.restore();
295
+ return;
296
+ }
297
+
205
298
  ctx.save();
206
299
  ctx.translate(camera.x, camera.y);
207
300
  ctx.scale(camera.zoom, camera.zoom);
@@ -212,13 +305,12 @@ export function createCanvas2dRenderer(canvas, opts = {}) {
212
305
  if (decor.rings.length) drawRings(ctx, decor.rings);
213
306
 
214
307
  scene.edges.forEach((edge) => drawEdge(ctx, edge, timeMs, camera.zoom));
215
- const looks = looksWith(looksFor(scene.theme), style); // the halos, mark rings and core for the scene's ground, in the theme's colours
216
308
  scene.nodes.forEach((node) => drawNode(ctx, node, camera.zoom, looks, style));
217
309
  // No text here: every label (and the strike through a removed one) is drawn by the label layer (labels.js) over this canvas
218
310
 
219
311
  ctx.restore();
220
312
  },
221
313
 
222
- destroy() { /* a 2d context holds nothing to release */ },
314
+ destroy() { layer = null; layerCtx = null; layerFor = null; },
223
315
  };
224
316
  }
package/explorer/scene.js CHANGED
@@ -242,8 +242,8 @@ export function isNodeVisible(state, node) {
242
242
  if (state.view === 'dataflow') return !!state.flow && state.flow.ids.has(node.id);
243
243
  if (state.view === 'house') return houseShowsNode(state, node); // the House view (spec 0029, PHY-11) draws its own set: house-model.js
244
244
  if (node.type === 'root') return true;
245
- if (node.type === 'core') return activeLayers.pkg || activeLayers.atom;
246
- if (node.type === 'store') return activeLayers.flow !== false;
245
+ if (node.type === 'core') return (activeLayers.pkg || activeLayers.atom) && activeLayers.core !== false; // its own row in Layers, and Packages or Atoms
246
+ if (node.type === 'store') return activeLayers.flow !== false && activeLayers.store !== false; // its own row, and Data Flow
247
247
  if (node.type === 'rom') return activeLayers.rom !== false && activeLayers.flow !== false;
248
248
  if (node.type === 'floor' || node.type === 'room') return activeLayers.house !== false; // the House layer (spec 0029)
249
249
  if (node.type === 'external') return activeLayers[externalLayer(node)] !== false; // the Cloud and Public web layers (spec 0031)
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @module explorer/search-status
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.
7
+ */
8
+
9
+ import { t } from './strings.js';
10
+
11
+ /** The two fields' status lines: the desktop box and the phone's bar */
12
+ const IDS = ['search-status', 'mobile-search-status'];
13
+
14
+ /** "No match for “query”" */
15
+ export const noMatchText = (query) => `${t('searchNoMatch')} “${query}”`;
16
+
17
+ /** Shows `text` by the search field(s); '' clears it */
18
+ export function showSearchStatus(text) {
19
+ for (const id of IDS) {
20
+ const el = document.getElementById(id);
21
+ if (el) el.textContent = text;
22
+ }
23
+ }
24
+
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
+ export const NO_MATCH_DELAY_MS = 400;
27
+ let pending = null;
28
+
29
+ /**
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.
32
+ * @param {string} query the trimmed query
33
+ * @param {boolean} found whether a shown node matched
34
+ */
35
+ export function updateSearchStatus(query, found) {
36
+ clearTimeout(pending);
37
+ pending = null;
38
+ if (!query || found) { showSearchStatus(''); return; }
39
+ const text = noMatchText(query);
40
+ pending = setTimeout(() => { pending = null; showSearchStatus(text); }, NO_MATCH_DELAY_MS);
41
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.34.0",
3
+ "version": "0.34.1",
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)",
@@ -0,0 +1,135 @@
1
+ /**
2
+ * @module server/compress
3
+ *
4
+ * Compresses the text the server sends (the page, JS, CSS, JSON, SVG) with Node's own zlib: brotli when the browser
5
+ * accepts it, gzip otherwise, never for what is already compressed (images, fonts) or streamed (event streams), and never
6
+ * on top of an answer that already carries a `Content-Encoding`, never a proxied upstream's answer or a range, and never
7
+ * an answer marked `Cache-Control: no-store` (what may hold a secret: sign-in, tokens, the agent and runner APIs; BREACH).
8
+ * Every compressible answer says `Vary: Accept-Encoding`, so a cache keeps the two apart. ETags are weak (files.js) and
9
+ * the same for every encoding, so a conditional request still gets its 304.
10
+ *
11
+ * Used by wrapping the response once, at the top of the request: `compressResponse(req, res)`.
12
+ */
13
+
14
+ import zlib from 'node:zlib';
15
+
16
+ /** Content types worth compressing: text, JSON (and `+json`), JavaScript, XML, SVG */
17
+ const COMPRESSIBLE = /^(?:text\/(?!event-stream)|application\/(?:json|javascript|ecmascript|xml|manifest\+json|[\w.+-]+\+(?:json|xml))|image\/svg\+xml)/i;
18
+ /** Below this many bytes (when the length is known) compressing costs more than it saves */
19
+ const MIN_BYTES = 512;
20
+
21
+ /**
22
+ * The encoding to answer with, from an `Accept-Encoding` header: `br`, `gzip`, or null. A `q=0` refuses one.
23
+ * @param {string|undefined} header
24
+ * @returns {'br'|'gzip'|null}
25
+ */
26
+ export function pickEncoding(header) {
27
+ if (!header) return null;
28
+ const q = new Map();
29
+ for (const part of String(header).split(',')) {
30
+ const [name, ...params] = part.trim().toLowerCase().split(';');
31
+ if (!name) continue;
32
+ const m = params.map((p) => p.trim()).find((p) => p.startsWith('q='));
33
+ q.set(name.trim(), m ? Number(m.slice(2)) : 1);
34
+ }
35
+ const weight = (e) => { const v = q.has(e) ? q.get(e) : q.has('*') ? q.get('*') : 0; return Number.isFinite(v) && v > 0 ? v : 0; };
36
+ const br = weight('br');
37
+ const gzip = Math.max(weight('gzip'), weight('x-gzip'));
38
+ if (!br && !gzip) return null;
39
+ return br >= gzip ? 'br' : 'gzip'; // the one the browser prefers; brotli on a tie
40
+ }
41
+
42
+ /** Whether a `Content-Type` is one of the compressible kinds */
43
+ export const isCompressible = (type) => typeof type === 'string' && COMPRESSIBLE.test(type.trim());
44
+
45
+ const SKIP = Symbol('cornfield.noCompress');
46
+
47
+ /**
48
+ * Leaves this answer as it is: a proxied upstream's answer (it may be a stream, or a range, and the upstream saw the
49
+ * request's Accept-Encoding itself).
50
+ * @param {import('node:http').ServerResponse} res
51
+ */
52
+ export function skipCompression(res) { /** @type {any} */ (res)[SKIP] = true; }
53
+
54
+ const hasVary = (v, name) => String(v || '').split(',').some((t) => t.trim().toLowerCase() === name.toLowerCase() || t.trim() === '*');
55
+
56
+ /**
57
+ * Wraps `res` so a compressible answer goes out compressed when the request allows it. Safe to call on every request:
58
+ * it changes nothing until `writeHead` (or the first write) shows a compressible body.
59
+ * @param {import('node:http').IncomingMessage} req
60
+ * @param {import('node:http').ServerResponse} res
61
+ */
62
+ export function compressResponse(req, res) {
63
+ const encoding = pickEncoding(req.headers['accept-encoding']);
64
+ const origWriteHead = res.writeHead.bind(res);
65
+ const origWrite = res.write.bind(res);
66
+ const origEnd = res.end.bind(res);
67
+ let decided = false;
68
+ let writeImpl = origWrite;
69
+ let endImpl = origEnd;
70
+ // Sending a body without `writeHead` first (Node adds the head itself): decide before it goes
71
+ res.write = (...a) => { if (!decided) res.writeHead(res.statusCode); return writeImpl(...a); };
72
+ res.end = (...a) => { if (!decided) res.writeHead(res.statusCode); return endImpl(...a); };
73
+
74
+ const header = (extra, name) => {
75
+ if (extra && !Array.isArray(extra)) {
76
+ const key = Object.keys(extra).find((k) => k.toLowerCase() === name.toLowerCase());
77
+ if (key !== undefined) return extra[key];
78
+ }
79
+ return res.getHeader(name);
80
+ };
81
+
82
+ res.writeHead = (status, ...rest) => {
83
+ // The caller's headers may be a constant it sends again (server.js JSON_HEADERS): change a copy, never that
84
+ const at = rest.findIndex((x) => x && typeof x === 'object');
85
+ if (at >= 0 && !Array.isArray(rest[at])) rest[at] = { ...rest[at] };
86
+ const extra = at >= 0 ? rest[at] : undefined;
87
+ if (!decided) {
88
+ decided = true;
89
+ const type = header(extra, 'content-type');
90
+ const bodyless = status < 200 || status === 204 || (status === 304 && !isCompressible(type));
91
+ if (!bodyless && isCompressible(type)) {
92
+ // The answer varies by the request's Accept-Encoding whether or not this one is compressed (a 304 too)
93
+ const vary = header(extra, 'vary');
94
+ if (!hasVary(vary, 'accept-encoding')) {
95
+ if (extra && !Array.isArray(extra)) extra.Vary = vary ? `${vary}, Accept-Encoding` : 'Accept-Encoding';
96
+ else res.setHeader('Vary', vary ? `${vary}, Accept-Encoding` : 'Accept-Encoding');
97
+ }
98
+ const length = Number(header(extra, 'content-length'));
99
+ const done = header(extra, 'content-encoding');
100
+ // `no-store` marks what the server treats as secret (sign-in pages, tokens, the agent and runner APIs): a body
101
+ // that may hold a secret beside what the request sent is never compressed (the BREACH class of attack)
102
+ const cache = String(header(extra, 'cache-control') || '');
103
+ const keep = /no-transform|no-store/i.test(cache) || /** @type {any} */ (res)[SKIP]
104
+ || status === 206 || header(extra, 'content-range') !== undefined;
105
+ if (encoding && status !== 304 && !done && !keep && !(Number.isFinite(length) && length > 0 && length < MIN_BYTES)) {
106
+ if (extra && !Array.isArray(extra)) {
107
+ Object.keys(extra).filter((k) => k.toLowerCase() === 'content-length').forEach((k) => { delete extra[k]; });
108
+ extra['Content-Encoding'] = encoding;
109
+ } else res.setHeader('Content-Encoding', encoding);
110
+ res.removeHeader('Content-Length');
111
+ if (req.method !== 'HEAD') startStream();
112
+ }
113
+ }
114
+ }
115
+ return origWriteHead(status, ...rest);
116
+ };
117
+
118
+ function startStream() {
119
+ const stream = encoding === 'br'
120
+ // Quality 4 is the cheap end: about as fast as gzip, and smaller
121
+ ? zlib.createBrotliCompress({ params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4, [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT } })
122
+ : zlib.createGzip({ level: 6 });
123
+ stream.on('data', (chunk) => origWrite(chunk));
124
+ stream.on('end', () => origEnd());
125
+ stream.on('error', () => res.destroy());
126
+ stream.on('drain', () => res.emit('drain'));
127
+ writeImpl = (chunk, enc, cb) => stream.write(chunk, enc, cb);
128
+ endImpl = (chunk, enc, cb) => {
129
+ if (typeof chunk === 'function') { cb = chunk; chunk = undefined; }
130
+ if (chunk !== undefined && chunk !== null) stream.end(chunk, typeof enc === 'string' ? enc : undefined, cb);
131
+ else stream.end(cb);
132
+ return res;
133
+ };
134
+ }
135
+ }
package/server/proxy.js CHANGED
@@ -11,6 +11,7 @@
11
11
  * The session is a bearer credential for the whole dashboard, and the upstream is someone else's server.
12
12
  */
13
13
 
14
+ import { skipCompression } from './compress.js';
14
15
  import http from 'node:http';
15
16
  import https from 'node:https';
16
17
 
@@ -40,6 +41,7 @@ export function withoutOwnSetCookies(values) {
40
41
  * @param {string} target like `http://127.0.0.1:3245`
41
42
  */
42
43
  export function proxyTo(req, res, target) {
44
+ skipCompression(res); // the upstream saw Accept-Encoding and answers as it likes: a stream or a range stays as it is
43
45
  const url = new URL(target);
44
46
  const client = url.protocol === 'https:' ? https : http;
45
47
  const port = url.port || (url.protocol === 'https:' ? '443' : '80');
package/server/server.js CHANGED
@@ -75,6 +75,7 @@ import { createLander } from './lander.js';
75
75
  import { createSpecPoll } from './spec-poll.js';
76
76
  import { createRunnerWatch } from './runner-presence.js';
77
77
  import { createTriggers } from './triggers.js';
78
+ import { compressResponse } from './compress.js';
78
79
 
79
80
  export const CORNFIELD_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
80
81
  const EXPLORER_DIR = path.join(CORNFIELD_DIR, 'explorer');
@@ -403,6 +404,7 @@ export function createCornfieldServer(config, opts = {}) {
403
404
  return server;
404
405
 
405
406
  async function answer(req, res) {
407
+ compressResponse(req, res); // text, JSON, JS, CSS and SVG go out gzipped or brotli'd when the browser accepts it
406
408
  res.setHeader('Content-Security-Policy', csp);
407
409
  res.setHeader('Referrer-Policy', 'no-referrer');
408
410
  res.setHeader('X-Frame-Options', 'DENY');