@floless/app 0.157.0 → 0.158.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,351 @@
1
+ // Knowledge categories and the knowledge map (#2491 R6.9): the pure half. Turns the categories file the server keeps
2
+ // (`knowledge/categories.json`, or the company library's `taxonomy.json`) into what the References tree, the Move to…
3
+ // menu and the map show — the tree in order, counts, name paths, the change a reorder needs, multi-selection, and the
4
+ // map's membership, colours and filters — with no DOM. web/workspaces.js mounts it; server/kb-categories-ui.test.ts
5
+ // drives it in Node through module.exports.
6
+ //
7
+ // Rules owned here:
8
+ // - categories are a VIEW of the documents: nothing here changes a document, and the map is recoloured from the
9
+ // current categories without asking the server again;
10
+ // - colour is never the only cue: a category beyond the eighth colour is hatched, and documents and pages differ in
11
+ // shape, not only in colour.
12
+
13
+ /* The map's category colours, existing theme tokens only, by a category's position at the top level. */
14
+ const KBC_COLORS = ['--accent', '--ok', '--info', '--part-ws', '--part-wf', '--part-ag', '--star', '--warn'];
15
+ /* How many nodes the map draws at once after filtering; the rest are counted and offered by category. */
16
+ const KBC_RENDER_CAP = 1500;
17
+
18
+ function kbcCats(file) {
19
+ return file && Array.isArray(file.categories) ? file.categories : [];
20
+ }
21
+
22
+ /** Children of `parentId` (null = top level), in the order the person set, then by name. */
23
+ function kbcChildren(file, parentId) {
24
+ return kbcCats(file).filter((c) => (c.parentId || null) === (parentId || null))
25
+ // One fixed collation, the same as the server's settleTies, so a tie reads the same in every browser language.
26
+ .sort((a, b) => (a.order - b.order) || a.name.localeCompare(b.name, 'en'));
27
+ }
28
+
29
+ function kbcById(file) {
30
+ return new Map(kbcCats(file).map((c) => [c.id, c]));
31
+ }
32
+
33
+ /** The category's name path, top level first, or null when it does not exist. */
34
+ function kbcPath(file, id) {
35
+ if (!id) return null;
36
+ const byId = kbcById(file);
37
+ const out = [];
38
+ for (let at = byId.get(id), n = 0; at && n < 16; at = at.parentId ? byId.get(at.parentId) : null, n += 1) out.unshift(at.name);
39
+ return out.length ? out : null;
40
+ }
41
+ function kbcLabel(file, id) {
42
+ const p = kbcPath(file, id);
43
+ return p ? p.join(' / ') : 'Uncategorized';
44
+ }
45
+
46
+ /** The top-level ancestor of a category (itself when it is top level), or null. */
47
+ function kbcTop(file, id) {
48
+ const byId = kbcById(file);
49
+ let at = id ? byId.get(id) : null;
50
+ for (let n = 0; at && at.parentId && n < 16; n += 1) at = byId.get(at.parentId) || null;
51
+ return at ? at.id : null;
52
+ }
53
+
54
+ /** Where a document sits now: a category that exists, or null (Uncategorized). */
55
+ function kbcPlacement(file, sourceId) {
56
+ const c = file && file.placements ? file.placements[sourceId] : null;
57
+ return c && kbcById(file).has(c) ? c : null;
58
+ }
59
+
60
+ /** Each category's id and every id below it. */
61
+ function kbcSubtree(file, id) {
62
+ const out = [id];
63
+ for (let i = 0; i < out.length; i += 1) for (const c of kbcChildren(file, out[i])) out.push(c.id);
64
+ return out;
65
+ }
66
+
67
+ /** How many of `rows` sit in each category, its subcategories included; `null` keys the Uncategorized count. */
68
+ function kbcCounts(file, rows) {
69
+ const direct = new Map();
70
+ for (const r of rows || []) {
71
+ const c = kbcPlacement(file, r.sourceId);
72
+ direct.set(c, (direct.get(c) || 0) + 1);
73
+ }
74
+ const total = new Map([[null, direct.get(null) || 0]]);
75
+ for (const c of kbcCats(file)) total.set(c.id, kbcSubtree(file, c.id).reduce((n, id) => n + (direct.get(id) || 0), 0));
76
+ return total;
77
+ }
78
+
79
+ /**
80
+ * The References tree as a flat list in reading order: a category row, then (when expanded) its documents and its
81
+ * subcategories; Uncategorized last. Each item: { kind: 'category' | 'uncategorized' | 'row', depth, ... }.
82
+ * `expanded` is a Set of category ids (and 'uncategorized'); a category not in it is folded.
83
+ */
84
+ function kbcTreeItems(file, rows, expanded) {
85
+ const items = [];
86
+ const counts = kbcCounts(file, rows);
87
+ const byCat = new Map();
88
+ for (const r of rows || []) {
89
+ const c = kbcPlacement(file, r.sourceId);
90
+ if (!byCat.has(c)) byCat.set(c, []);
91
+ byCat.get(c).push(r);
92
+ }
93
+ const walk = (parentId, depth) => {
94
+ for (const c of kbcChildren(file, parentId)) {
95
+ const open = !!(expanded && expanded.has(c.id));
96
+ const kids = kbcChildren(file, c.id);
97
+ const own = byCat.get(c.id) || [];
98
+ items.push({ kind: 'category', id: c.id, name: c.name, depth, count: counts.get(c.id) || 0, open, empty: !kids.length && !own.length });
99
+ if (!open) continue;
100
+ for (const r of own) items.push({ kind: 'row', row: r, depth: depth + 1, categoryId: c.id });
101
+ walk(c.id, depth + 1);
102
+ }
103
+ };
104
+ walk(null, 0);
105
+ const loose = byCat.get(null) || [];
106
+ const openU = !expanded || expanded.has('uncategorized');
107
+ items.push({ kind: 'uncategorized', id: null, name: 'Uncategorized', depth: 0, count: loose.length, open: openU, empty: !loose.length });
108
+ if (openU) for (const r of loose) items.push({ kind: 'row', row: r, depth: 1, categoryId: null });
109
+ return items;
110
+ }
111
+
112
+ /** The ancestors of a category, nearest last — to expand them so a moved item stays in view. */
113
+ function kbcAncestors(file, id) {
114
+ const byId = kbcById(file);
115
+ const out = [];
116
+ for (let at = id ? byId.get(id) : null, n = 0; at && at.parentId && n < 16; n += 1) { out.unshift(at.parentId); at = byId.get(at.parentId); }
117
+ return out;
118
+ }
119
+
120
+ /** The Move to… menu's choices: Uncategorized, then every category indented, with whether it can take `movingCat`. */
121
+ function kbcMenuChoices(file, movingCat) {
122
+ const banned = movingCat ? new Set(kbcSubtree(file, movingCat)) : new Set();
123
+ const out = [{ id: null, name: 'Uncategorized', depth: 0, allowed: true }];
124
+ const walk = (parentId, depth) => {
125
+ for (const c of kbcChildren(file, parentId)) {
126
+ // A category cannot go inside itself or below 4 levels (its own height counted).
127
+ const height = movingCat ? kbcHeight(file, movingCat) : 0;
128
+ out.push({ id: c.id, name: c.name, depth, allowed: !banned.has(c.id) && depth + 1 + height <= 4 });
129
+ walk(c.id, depth + 1);
130
+ }
131
+ };
132
+ walk(null, 0);
133
+ if (movingCat) out[0] = { id: null, name: 'Top level', depth: 0, allowed: true };
134
+ return out;
135
+ }
136
+ function kbcHeight(file, id) {
137
+ const kids = kbcChildren(file, id);
138
+ return 1 + (kids.length ? Math.max(...kids.map((k) => kbcHeight(file, k.id))) : 0);
139
+ }
140
+
141
+ /** The changes that move a category one place up (-1) or down (+1) among its siblings, or null at an end. */
142
+ function kbcReorderOps(file, id, dir) {
143
+ const c = kbcById(file).get(id);
144
+ if (!c) return null;
145
+ const parentId = c.parentId || null;
146
+ const sibs = kbcChildren(file, parentId);
147
+ const at = sibs.findIndex((s) => s.id === id);
148
+ if (!sibs[at + dir]) return null;
149
+ // The list as it should read: the two neighbours swapped, everything else where it was.
150
+ const want = sibs.slice();
151
+ [want[at], want[at + dir]] = [want[at + dir], want[at]];
152
+ const lo = Math.min(at, at + dir), n = want.length;
153
+ // Give new orders only to a window around the swap whose outer neighbours leave room for it: everything outside keeps
154
+ // its order (so ties and gaps elsewhere stay as they are). For each left edge the narrowest window that fits is taken,
155
+ // and of those the one that changes the fewest categories, which keeps a move inside the server's batch. Orders may
156
+ // go below zero. Proven against the server's own reducer in server/kb-categories-ui.test.ts.
157
+ let best = null;
158
+ for (let i = lo; i >= 0; i--) {
159
+ const below = i > 0 ? want[i - 1].order : -Infinity;
160
+ for (let j = lo + 1; j < n; j++) {
161
+ const above = j < n - 1 ? want[j + 1].order : Infinity;
162
+ const size = j - i + 1;
163
+ if (above - below - 1 < size) continue;
164
+ const first = below !== -Infinity ? below + 1 : above !== Infinity ? above - size : Math.min(0, want[i].order);
165
+ // Only whole, safe numbers: next to the edge of the safe range a window is skipped (the whole list from 0 always fits).
166
+ if (!Number.isSafeInteger(first) || !Number.isSafeInteger(first + size - 1)) continue;
167
+ let cost = 0;
168
+ for (let k = i; k <= j; k++) if (want[k].order !== first + (k - i)) cost++;
169
+ if (!best || cost < best.cost) best = { i, j, first, cost };
170
+ break; // a wider window to the right only adds categories to renumber
171
+ }
172
+ }
173
+ const ops = [];
174
+ for (let k = best.i; k <= best.j; k++) {
175
+ const order = best.first + (k - best.i);
176
+ if (want[k].order !== order) ops.push({ op: 'move', id: want[k].id, parentId, order });
177
+ }
178
+ return ops;
179
+ }
180
+
181
+ /**
182
+ * Click selection over `order` (the visible rows' ids): a plain click selects one, Ctrl/Cmd toggles, Shift extends from
183
+ * the anchor. Returns { selected: Set, anchor }.
184
+ */
185
+ function kbcSelect(prev, id, mods, order) {
186
+ const sel = new Set(prev && prev.selected ? prev.selected : []);
187
+ let anchor = prev && prev.anchor;
188
+ if (mods && mods.shift && anchor && order.includes(anchor) && order.includes(id)) {
189
+ const a = order.indexOf(anchor), b = order.indexOf(id);
190
+ const range = order.slice(Math.min(a, b), Math.max(a, b) + 1);
191
+ const out = mods.toggle ? sel : new Set();
192
+ for (const x of range) out.add(x);
193
+ return { selected: out, anchor };
194
+ }
195
+ if (mods && mods.toggle) {
196
+ if (sel.has(id)) sel.delete(id); else sel.add(id);
197
+ return { selected: sel, anchor: id };
198
+ }
199
+ return { selected: new Set([id]), anchor: id };
200
+ }
201
+ /** Ctrl/Cmd+A: every row in `order` (the visible rows) is selected; the anchor stays when it is still among them. */
202
+ function kbcSelectAll(prev, order) {
203
+ const anchor = prev && order.includes(prev.anchor) ? prev.anchor : (order[0] ?? null);
204
+ return { selected: new Set(order), anchor };
205
+ }
206
+ /** Keep only ids still present (a reference removed elsewhere leaves the selection). */
207
+ function kbcPrune(prev, ids) {
208
+ const live = new Set(ids);
209
+ const selected = new Set([...(prev && prev.selected ? prev.selected : [])].filter((x) => live.has(x)));
210
+ return { selected, anchor: prev && live.has(prev.anchor) ? prev.anchor : null };
211
+ }
212
+
213
+ // ── The map ─────────────────────────────────────────────────────────────────────────────────────────
214
+
215
+ /** A new, empty map being streamed in. */
216
+ function kbgCreate(generationId) {
217
+ return { generationId, nodes: new Map(), links: [], index: null, total: 0, done: false, grouped: false, truncated: false };
218
+ }
219
+ /** Merge one chunk the server sent. Documents arrive once per page that cites them; the first one stays. */
220
+ function kbgMerge(model, chunk) {
221
+ if (!chunk || chunk.generationId !== model.generationId) return model;
222
+ for (const n of chunk.nodes || []) if (n && n.id && !model.nodes.has(n.id)) model.nodes.set(n.id, n);
223
+ for (const e of chunk.edges || []) if (e && e.a && e.b) model.links.push([e.a, e.b]);
224
+ if (chunk.index && (!model.index || chunk.index.slug === 'index')) model.index = chunk.index;
225
+ model.total = chunk.total || model.total;
226
+ model.grouped = !!chunk.grouped;
227
+ model.truncated = model.truncated || !!chunk.truncated;
228
+ model.done = chunk.next === null || chunk.next === undefined;
229
+ return model;
230
+ }
231
+
232
+ /**
233
+ * Each node's top-level categories from the CURRENT categories: a document's own placement, a page's the union of the
234
+ * documents it was written from. Returns Map(id → { cats: string[] (top-level ids, or ['uncategorized']),
235
+ * grouped: boolean }). A page that does not list its documents is "not yet grouped".
236
+ */
237
+ function kbgMembership(model, file) {
238
+ const out = new Map();
239
+ const docTop = (sourceId) => kbcTop(file, kbcPlacement(file, sourceId)) || 'uncategorized';
240
+ for (const n of model.nodes.values()) {
241
+ if (n.kind === 'document') { out.set(n.id, { cats: [docTop(n.sourceId)], grouped: true }); continue; }
242
+ if (!model.grouped || !Array.isArray(n.sourceIds)) { out.set(n.id, { cats: [], grouped: false }); continue; }
243
+ const cats = [...new Set(n.sourceIds.filter((s) => model.nodes.has(`doc:${s}`)).map(docTop))];
244
+ out.set(n.id, { cats: cats.length ? cats : ['uncategorized'], grouped: true });
245
+ }
246
+ return out;
247
+ }
248
+
249
+ /** The colour of a top-level category: { token, hatch } — hatched past the eighth so colour is never the only cue. */
250
+ function kbgColour(file, topId) {
251
+ if (!topId || topId === 'uncategorized') return { token: '--text-muted', hatch: false };
252
+ const i = kbcChildren(file, null).findIndex((c) => c.id === topId);
253
+ if (i < 0) return { token: '--text-muted', hatch: false };
254
+ return { token: KBC_COLORS[i % KBC_COLORS.length], hatch: i >= KBC_COLORS.length };
255
+ }
256
+
257
+ /**
258
+ * What the map draws now: the nodes that pass the filters (hidden categories, hidden page types, the neighbourhood of
259
+ * one node), at most KBC_RENDER_CAP of them, and the links between drawn nodes. A link whose other end has not
260
+ * arrived yet is pending, never dropped. `search` marks matches; it does not hide anything.
261
+ */
262
+ function kbgView(model, file, opts) {
263
+ const o = opts || {};
264
+ const hiddenCats = o.hiddenCats || new Set();
265
+ const hiddenTypes = o.hiddenTypes || new Set();
266
+ const member = kbgMembership(model, file);
267
+ const adj = new Map();
268
+ let pending = 0;
269
+ for (const [a, b] of model.links) {
270
+ if (!model.nodes.has(a) || !model.nodes.has(b)) { pending += 1; continue; }
271
+ if (a === b) continue;
272
+ if (!adj.has(a)) adj.set(a, new Set());
273
+ if (!adj.has(b)) adj.set(b, new Set());
274
+ adj.get(a).add(b); adj.get(b).add(a);
275
+ }
276
+ const passes = (n) => {
277
+ const m = member.get(n.id);
278
+ if (n.kind === 'page' && hiddenTypes.has(n.type)) return false;
279
+ if (!m.grouped) return !hiddenCats.has('ungrouped');
280
+ return m.cats.some((c) => !hiddenCats.has(c));
281
+ };
282
+ let ids = [...model.nodes.values()].filter(passes).map((n) => n.id);
283
+ if (o.neighbourOf && model.nodes.has(o.neighbourOf)) {
284
+ const near = new Set([o.neighbourOf, ...(adj.get(o.neighbourOf) || [])]);
285
+ ids = ids.filter((id) => near.has(id));
286
+ if (!ids.includes(o.neighbourOf)) ids.unshift(o.neighbourOf);
287
+ }
288
+ const shownTotal = ids.length;
289
+ ids.sort();
290
+ const drawn = ids.slice(0, KBC_RENDER_CAP);
291
+ const drawnSet = new Set(drawn);
292
+ const edges = [];
293
+ const seen = new Set();
294
+ for (const [a, set] of adj) {
295
+ if (!drawnSet.has(a)) continue;
296
+ for (const b of set) {
297
+ if (!drawnSet.has(b) || a >= b) continue;
298
+ const k = `${a}\u0000${b}`;
299
+ if (seen.has(k)) continue;
300
+ seen.add(k); edges.push([a, b]);
301
+ }
302
+ }
303
+ const q = typeof o.search === 'string' ? o.search.trim().toLowerCase() : '';
304
+ const matches = q ? drawn.filter((id) => {
305
+ const n = model.nodes.get(id);
306
+ return String(n.title || n.filename || '').toLowerCase().includes(q);
307
+ }) : [];
308
+ return { nodes: drawn.map((id) => model.nodes.get(id)), edges, member, adj, matches, pending,
309
+ capped: shownTotal > drawn.length ? { shown: drawn.length, total: shownTotal } : null };
310
+ }
311
+
312
+ /** The map's legend: one chip per top-level category that has something on the map, then Uncategorized and Not yet grouped. */
313
+ function kbgLegend(model, file) {
314
+ const member = kbgMembership(model, file);
315
+ const count = new Map();
316
+ for (const m of member.values()) {
317
+ if (!m.grouped) { count.set('ungrouped', (count.get('ungrouped') || 0) + 1); continue; }
318
+ for (const c of m.cats) count.set(c, (count.get(c) || 0) + 1);
319
+ }
320
+ const chips = kbcChildren(file, null).filter((c) => count.get(c.id)).map((c) => ({ id: c.id, name: c.name, n: count.get(c.id), ...kbgColour(file, c.id) }));
321
+ if (count.get('uncategorized')) chips.push({ id: 'uncategorized', name: 'Uncategorized', n: count.get('uncategorized'), token: '--text-muted', hatch: false });
322
+ if (count.get('ungrouped')) chips.push({ id: 'ungrouped', name: 'Not yet grouped', n: count.get('ungrouped'), token: '--text-muted', hatch: false, dashed: true });
323
+ return chips;
324
+ }
325
+
326
+ /** From the focused node, the nearest drawn neighbour in a direction (for the arrow keys). */
327
+ function kbgNearest(pos, from, dir, candidates) {
328
+ const p = pos.get(from);
329
+ if (!p) return null;
330
+ let best = null; let bestScore = Infinity;
331
+ for (const id of candidates) {
332
+ if (id === from) continue;
333
+ const q = pos.get(id);
334
+ if (!q) continue;
335
+ const dx = q.x - p.x, dy = q.y - p.y;
336
+ const along = dir === 'ArrowRight' ? dx : dir === 'ArrowLeft' ? -dx : dir === 'ArrowDown' ? dy : -dy;
337
+ const across = dir === 'ArrowRight' || dir === 'ArrowLeft' ? Math.abs(dy) : Math.abs(dx);
338
+ if (along <= 0) continue;
339
+ const score = along + across * 2;
340
+ if (score < bestScore) { bestScore = score; best = id; }
341
+ }
342
+ return best;
343
+ }
344
+
345
+ if (typeof module !== 'undefined' && module.exports) {
346
+ module.exports = {
347
+ KBC_COLORS, KBC_RENDER_CAP, kbcChildren, kbcPath, kbcLabel, kbcTop, kbcPlacement, kbcSubtree, kbcCounts, kbcTreeItems,
348
+ kbcAncestors, kbcMenuChoices, kbcReorderOps, kbcSelect, kbcSelectAll, kbcPrune,
349
+ kbgCreate, kbgMerge, kbgMembership, kbgColour, kbgView, kbgLegend, kbgNearest,
350
+ };
351
+ }
@@ -0,0 +1,73 @@
1
+ // The knowledge map's layout, off the main thread (#2491 R6.9, spec §5.2). A seeded force layout: the same map
2
+ // always lands the same way. Repulsion is grid-accelerated (each node only pushes nodes in its own and the eight
3
+ // neighbouring cells), so a step costs about O(N) and a 1,500-node map lays out in well under a second.
4
+ //
5
+ // Message in: { epoch, n, edges: Int32Array [a0, b0, a1, b1, …], seeds: Uint32Array (one per node) }
6
+ // Message out: { epoch, x: Float32Array, y: Float32Array, w, h }
7
+ // The page drops any answer whose epoch is not the latest, and terminates this worker when it asks again or closes.
8
+
9
+ function kbgLayout(n, edges, seeds) {
10
+ const W = Math.max(600, Math.sqrt(n) * 70), H = W * 0.72;
11
+ const K = Math.max(40, Math.min(140, W / Math.sqrt(Math.max(1, n)) * 0.9));
12
+ const x = new Float32Array(n), y = new Float32Array(n);
13
+ const R = Math.min(W, H) / 2 - 30;
14
+ for (let i = 0; i < n; i++) {
15
+ const s = seeds[i] >>> 0;
16
+ const ang = i * 2.399963 + (s % 628) / 100;
17
+ const rad = 18 + (n > 1 ? (i / (n - 1)) * R : 0);
18
+ x[i] = W / 2 + Math.cos(ang) * rad; y[i] = H / 2 + Math.sin(ang) * rad;
19
+ }
20
+ const iters = n <= 200 ? 300 : n <= 800 ? 200 : 120;
21
+ const cell = K * 2;
22
+ const cols = Math.max(1, Math.ceil(W / cell)), rows = Math.max(1, Math.ceil(H / cell));
23
+ const head = new Int32Array(cols * rows), next = new Int32Array(n);
24
+ const fx = new Float32Array(n), fy = new Float32Array(n);
25
+ const rep = K * K * 0.5;
26
+ let pairs = 0; // node pairs compared for repulsion: the work the grid saves, reported so a test can count it
27
+ for (let it = 0; it < iters; it++) {
28
+ const cool = 1 - it / iters;
29
+ fx.fill(0); fy.fill(0); head.fill(-1);
30
+ for (let i = 0; i < n; i++) {
31
+ const c = Math.min(cols - 1, Math.max(0, (x[i] / cell) | 0)) + Math.min(rows - 1, Math.max(0, (y[i] / cell) | 0)) * cols;
32
+ next[i] = head[c]; head[c] = i;
33
+ }
34
+ for (let i = 0; i < n; i++) {
35
+ const cx = Math.min(cols - 1, Math.max(0, (x[i] / cell) | 0)), cy = Math.min(rows - 1, Math.max(0, (y[i] / cell) | 0));
36
+ for (let oy = -1; oy <= 1; oy++) for (let ox = -1; ox <= 1; ox++) {
37
+ const gx = cx + ox, gy = cy + oy;
38
+ if (gx < 0 || gy < 0 || gx >= cols || gy >= rows) continue;
39
+ for (let j = head[gx + gy * cols]; j !== -1; j = next[j]) {
40
+ if (j <= i) continue;
41
+ pairs++;
42
+ const dx = x[i] - x[j], dy = y[i] - y[j];
43
+ const d2 = dx * dx + dy * dy || 0.01, d = Math.sqrt(d2), f = rep / d2;
44
+ fx[i] += dx / d * f; fy[i] += dy / d * f; fx[j] -= dx / d * f; fy[j] -= dy / d * f;
45
+ }
46
+ }
47
+ }
48
+ for (let e = 0; e + 1 < edges.length; e += 2) {
49
+ const i = edges[e], j = edges[e + 1];
50
+ if (i < 0 || j < 0 || i >= n || j >= n) continue;
51
+ const dx = x[j] - x[i], dy = y[j] - y[i];
52
+ const d = Math.sqrt(dx * dx + dy * dy) || 0.01, s = (d - K) * 0.03;
53
+ fx[i] += dx / d * s; fy[i] += dy / d * s; fx[j] -= dx / d * s; fy[j] -= dy / d * s;
54
+ }
55
+ const step = 4 + 18 * cool;
56
+ for (let i = 0; i < n; i++) {
57
+ fx[i] += (W / 2 - x[i]) * 0.006; fy[i] += (H / 2 - y[i]) * 0.006;
58
+ x[i] = Math.max(20, Math.min(W - 20, x[i] + Math.max(-step, Math.min(step, fx[i]))));
59
+ y[i] = Math.max(20, Math.min(H - 20, y[i] + Math.max(-step, Math.min(step, fy[i]))));
60
+ }
61
+ }
62
+ return { x, y, w: W, h: H, pairs, iters };
63
+ }
64
+
65
+ if (typeof self !== 'undefined' && typeof self.postMessage === 'function' && typeof module === 'undefined') {
66
+ self.onmessage = (ev) => {
67
+ const m = ev.data || {};
68
+ const out = kbgLayout(m.n | 0, m.edges || new Int32Array(0), m.seeds || new Uint32Array(m.n | 0));
69
+ self.postMessage({ epoch: m.epoch, x: out.x, y: out.y, w: out.w, h: out.h }, [out.x.buffer, out.y.buffer]);
70
+ };
71
+ }
72
+
73
+ if (typeof module !== 'undefined' && module.exports) module.exports = { kbgLayout };
package/dist/web/pages.js CHANGED
@@ -88,7 +88,7 @@
88
88
 
89
89
  // #2262 slice 4: a list row says where its link stands — never "Shared" for a link that isn't open yet or is going.
90
90
  const LIST_CHIP = { live: 'Shared', 'pending-publish': 'Publishing…', 'pending-revoke': 'Revoke waiting' };
91
- function rowHtml(home, p) {
91
+ function rowHtml(home, p, view = {}) {
92
92
  if (p.damaged) {
93
93
  // Delete is offered only where deleting loses nothing good: a broken or record-less Page. A Page saved
94
94
  // by a newer FloLess is fine (update to open it), and a shortcut folder points somewhere else.
@@ -103,7 +103,7 @@
103
103
  ${canDelete ? `<button type="button" class="ghost pg-row-delete" data-command-id="shell.page-delete-unreadable#${esc(p.id)}" data-home="${esc(home)}" data-page="${esc(p.id)}">Delete</button>` : ''}
104
104
  </div>`;
105
105
  }
106
- const meta = [sourceText(p.source), versionsText(p.versionCount), p.sequence ? 'Has an order' : '', `Updated ${ago(p.updatedAt)}`].filter(Boolean).join(' · ');
106
+ const meta = [...(view.lead || [sourceText(p.source)]), versionsText(p.versionCount), p.sequence ? 'Has an order' : '', `Updated ${ago(p.updatedAt)}`].filter(Boolean).join(' · ');
107
107
  // Only an order FloLess did not read is flagged on the row; a read one is the plain "Has an order".
108
108
  const seqChip = p.sequence && (p.sequence !== 'read' || p.sequencePartial) ? `<span class="pg-seq-chip is-warn">${esc(seqLabel({ order: p.sequence, partial: p.sequencePartial }))}</span>` : '';
109
109
  return `<div class="pg-row" role="listitem">
@@ -120,7 +120,7 @@
120
120
  if (w.page && typeof w.home === 'string') return rowHtml(w.home, w.page);
121
121
  return `<div class="pg-row pg-row-damaged" role="listitem">
122
122
  <div class="pg-row-text"><span class="pg-row-title">${esc(w.workflowName)}: its Page can’t be opened</span>
123
- <span class="pg-row-meta">${esc(w.note || 'FloLess couldn’t read this workflow’s Page.')}</span></div>
123
+ <span class="pg-row-meta">${esc(w.note || 'FloLess couldn’t read this workflow’s Page.')} Run the workflow again to save a new version; if this keeps happening, use Report an issue.</span></div>
124
124
  </div>`;
125
125
  }
126
126
 
@@ -174,6 +174,106 @@
174
174
  }
175
175
  }
176
176
 
177
+ // ── The Workflows landing's Pages tab (#2568): every workflow's Page, wherever it is kept ─────────────────────────
178
+
179
+ /** The last list read, so a landing repaint shows it at once while the fresh one loads — for this workspace only. */
180
+ let wfRowsCache = null;
181
+ let wfNote = '';
182
+ let wfRoot = null;
183
+ // A change of workspace (the first word about it included) drops what was read and redraws each open list ONCE; an
184
+ // answer still out for the workspace that was open before is simply dropped (see renderWorkflowsList), never re-asked.
185
+ window.addEventListener('floless:workspace-root-state', (event) => {
186
+ const root = event.detail && event.detail.root;
187
+ const id = root ? `${root.rootId}#${root.generation}` : null;
188
+ if (id === wfRoot) return;
189
+ wfRoot = id;
190
+ wfRowsCache = null; wfNote = '';
191
+ for (const e of [...lists]) {
192
+ if (e.kind !== 'workflows') continue;
193
+ if (!e.container.isConnected) { lists.delete(e); continue; }
194
+ void renderWorkflowsList(e.container, e.opts);
195
+ }
196
+ });
197
+ const cachedRows = () => wfRowsCache;
198
+ const ownerText = (w) => (w.owner?.kind === 'project' ? (w.owner.name || 'A project') : 'Workspace');
199
+
200
+ function workflowPageRowHtml(w) {
201
+ if (!(w.page && typeof w.home === 'string')) return workflowRowHtml(w);
202
+ // A workflow's Page is titled after the workflow, so its name is repeated only when the two differ.
203
+ const named = w.page?.title && w.page.title.trim() === String(w.workflowName).trim() ? [] : [w.workflowName];
204
+ return rowHtml(w.home, w.page, { lead: [...named, ownerText(w), ...(w.archived ? ['Archived'] : [])] });
205
+ }
206
+
207
+ function wfMatches(w, terms) {
208
+ const hay = `${w.workflowName} ${w.page?.title || ''} ${ownerText(w)}`.toLowerCase();
209
+ return terms.every((t) => hay.includes(t));
210
+ }
211
+
212
+ function paintWorkflowsList(container, rows, opts) {
213
+ const query = String(opts?.getQuery?.() ?? '').trim();
214
+ const focused = container.contains(document.activeElement) ? document.activeElement?.getAttribute('data-command-id') : null;
215
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
216
+ const shown = rows.filter((w) => wfMatches(w, terms));
217
+ container.dataset.pgwfState = 'ready';
218
+ if (!rows.length) {
219
+ container.innerHTML = `<div class="pg-empty"><p>No workflow has a Page yet. Every successful run of a workflow that makes a report adds a version to its Page.</p>
220
+ <p><button type="button" class="ghost pg-wf-act" data-act="show-workflows" data-command-id="shell.workflows-landing-pages-show-workflows">Show workflows</button></p></div>`;
221
+ } else if (!shown.length) {
222
+ container.innerHTML = '<div class="pg-empty" role="status"><p class="pg-wf-nomatch"></p><p><button type="button" class="ghost pg-wf-act" data-act="clear-search" data-command-id="shell.workflows-landing-pages-clear-search">Clear search</button></p></div>';
223
+ container.querySelector('.pg-wf-nomatch').textContent = `No Page matches “${query}”.`; // text, never markup: it echoes what was typed
224
+ } else {
225
+ container.innerHTML = `<div class="pg-list" role="list" aria-label="Pages from workflows">${shown.map(workflowPageRowHtml).join('')}</div>`;
226
+ }
227
+ if (wfNote) {
228
+ const note = document.createElement('p');
229
+ note.className = 'pg-wf-note';
230
+ note.setAttribute('role', 'status');
231
+ note.textContent = wfNote;
232
+ container.prepend(note);
233
+ }
234
+ if (focused && document.activeElement === document.body && container.isConnected) {
235
+ [...container.querySelectorAll('[data-command-id]')].find((el) => el.getAttribute('data-command-id') === focused)?.focus({ preventScroll: true });
236
+ }
237
+ }
238
+
239
+ /** Draw the list again from what was last read (a search, a tab switch back): nothing is fetched. */
240
+ function repaintWorkflowsList(container) {
241
+ const entry = [...lists].find((e) => e.kind === 'workflows' && e.container === container);
242
+ if (entry && cachedRows() && container.dataset.pgwfState === 'ready') paintWorkflowsList(container, cachedRows(), entry.opts);
243
+ }
244
+
245
+ /**
246
+ * Render every workflow's Page into `container`. `opts.getQuery()` is the landing's search text; `opts.onAction(act)`
247
+ * hears the buttons that leave this list ('show-workflows', 'clear-search'). Registered with the live lists, so a
248
+ * Page that changes re-reads it.
249
+ */
250
+ async function renderWorkflowsList(container, opts = {}) {
251
+ if (!container) return;
252
+ const entry = { container, kind: 'workflows', opts };
253
+ for (const e of [...lists]) if (e.container === container) lists.delete(e);
254
+ lists.add(entry);
255
+ const token = (container.dataset.pagesToken = String(Math.random()));
256
+ if (cachedRows()) paintWorkflowsList(container, cachedRows(), opts);
257
+ else { container.dataset.pgwfState = 'loading'; container.innerHTML = '<p class="pg-loading-line">Loading Pages…</p>'; }
258
+ // An answer is used only by the request still current for this list, while the list is on screen. A workspace change
259
+ // redraws every open list (a new token), so an answer read for the workspace that was open before is dropped here.
260
+ const current = () => container.dataset.pagesToken === token && container.isConnected;
261
+ let body;
262
+ try { body = await api('/api/pages/workflows'); } catch (err) {
263
+ if (!current()) return;
264
+ console.warn('The workflows’ Pages could not be read', err);
265
+ wfRowsCache = null; wfNote = '';
266
+ container.dataset.pgwfState = 'error';
267
+ container.innerHTML = `<div class="pg-empty" role="alert"><p>FloLess couldn’t load the workflows’ Pages. Check that FloLess is running, then try again.</p>
268
+ <p><button type="button" class="ghost pg-wf-act" data-act="retry" data-command-id="shell.workflows-landing-pages-retry">Try again</button></p></div>`;
269
+ return;
270
+ }
271
+ if (!current()) return;
272
+ wfRowsCache = (Array.isArray(body.workflowPages) ? body.workflowPages : []).filter((w) => w && typeof w.workflowName === 'string');
273
+ wfNote = typeof body.note === 'string' ? body.note : '';
274
+ paintWorkflowsList(container, wfRowsCache, opts);
275
+ }
276
+
177
277
  /** Tell the rest of the window a Page is gone, so nothing keeps offering to open it (the report viewer's links). */
178
278
  function announceDeleted(home, id) {
179
279
  window.dispatchEvent(new CustomEvent('floless:page-deleted', { detail: { home, id } }));
@@ -182,7 +282,8 @@
182
282
  function refreshLists() {
183
283
  for (const e of [...lists]) {
184
284
  if (!e.container.isConnected) { lists.delete(e); continue; }
185
- renderList(e.container, e.home, e.opts);
285
+ if (e.kind === 'workflows') renderWorkflowsList(e.container, e.opts);
286
+ else renderList(e.container, e.home, e.opts);
186
287
  }
187
288
  }
188
289
 
@@ -190,7 +291,12 @@
190
291
  const open = event.target.closest?.('.pg-row-open');
191
292
  if (open) { openViewer(open.dataset.home, open.dataset.page, null, open); return; }
192
293
  const del = event.target.closest?.('.pg-row-delete');
193
- if (del) deleteUnreadable(del.dataset.home, del.dataset.page, del);
294
+ if (del) { deleteUnreadable(del.dataset.home, del.dataset.page, del); return; }
295
+ const act = event.target.closest?.('.pg-wf-act');
296
+ const owner = act && [...lists].find((e) => e.kind === 'workflows' && e.container.contains(act));
297
+ if (!owner) return;
298
+ if (act.dataset.act === 'retry') void renderWorkflowsList(owner.container, owner.opts);
299
+ else owner.opts.onAction?.(act.dataset.act);
194
300
  });
195
301
 
196
302
  async function deleteUnreadable(home, id, button) {
@@ -213,7 +319,7 @@
213
319
  // ── Viewer ───────────────────────────────────────────────────────────────────────────────────────
214
320
 
215
321
  const $modal = document.getElementById('page-viewer');
216
- if (!$modal) { window.flolessPages = { renderList, open: () => {}, refresh: refreshLists }; return; }
322
+ if (!$modal) { window.flolessPages = { renderList, renderWorkflowsList, repaintWorkflowsList, open: () => {}, refresh: refreshLists }; return; }
217
323
  const $ = (id) => document.getElementById(id);
218
324
  const $title = $('pv-title');
219
325
  const $sub = $('pv-sub');
@@ -1435,6 +1541,8 @@
1435
1541
 
1436
1542
  window.flolessPages = {
1437
1543
  renderList,
1544
+ renderWorkflowsList,
1545
+ repaintWorkflowsList,
1438
1546
  openSharedLinks: (returnFocus) => openSharedLinks(returnFocus),
1439
1547
  open: (home, id, n) => openViewer(home, id, n ?? null, document.activeElement),
1440
1548
  refresh: refreshLists,