Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
list.py · 53.8 KB · 1067 lines
1"""Shared list generator, served at /list as window.dbbasicList.
2
3Renders a collection as rich rows (avatar, title/link, subtitle, relative
4date, tag pills, per-row edit + delete), with a search box (over
5/api/search) and a newest/oldest sort. It subscribes to the collection
6over the /ws websocket, so the list auto-refreshes when a record changes
7in another tab, by another user, or by an agent — a thing the old stack's
8lists did not do. Display accessors come from a small config; search and
9live updates are automatic.
10
11`cfg.where` (optional, `{field: value}`) narrows the fetch to
12`58-query-filter-spec.md`'s `field=value` (implicit `eq`) query encoding —
13the same server-side filter `/collections/{c}/records` already applies
14after its own permission row filter, so a `where`'d list can only narrow
15what the caller could already see, never widen it. This is what
16`59-detail-related-spec.md`'s `related` block compiles to: one `where`
17entry, `{fk_field: parent_record_id}`, no bespoke fetch. Plain lists
18(no `where`) are unaffected.
19
20`60-list-modes-spec.md`: board / tree / calendar.
21
22`window.dbbasicList(collection, cfg)` is schema-driven for THREE more
23`views.list_mode` values beyond the plain row list above (`table`/`cards`/
24`feed`, which all render as the row list -- this generator has never
25distinguished them). On mount it fetches `/api/schema/{collection}` (the
26same public, structure-only endpoint window.dbbasicForm already reads) and,
27when `schema.views.list_mode` is `board`/`tree`/`calendar`, delegates to
28one of the render functions below instead of the row list -- no new route,
29no per-page code, the same "1 -> 12" property every generator improvement
30already has. A collection with `list_mode` left at `table`/`cards`/`feed`/
31unset never pays for this beyond the one extra schema fetch.
32
33- **board** (kanban AND the CRM lead pipeline -- ONE mode, not two: a
34 collection gets `views.list_mode: "board"` with a grouping field, never
35 a separate "kanban block"). Buckets one flat 58 fetch by an enum field
36 into columns (`groupByColumn`), in the enum's own declared order, plus
37 an "(unset)" column first for an empty/stray value -- never a dropped
38 card. `group_field` defaults per `defaultGroupField`'s chain (schema
39 `flow.field`, else the first `transitions`-guarded enum, else the first
40 plain enum) so `tasks` and a bare `contacts.lead_status` both get a
41 working board from the same fallback with no divergent config. A drag
42 issues `PUT /collections/{c}/records/{id}` with the target column as the
43 new field value -- THE SAME write any row-action or generated-form edit
44 already issues. `object_records.update_collection_record` runs
45 `_validate_field_transitions` on every such write, guard map or not; this
46 file adds no client-side legality check and no second write path. If the
47 group field carries no `transitions` map (`contacts.lead_status` today --
48 no map declared, see `packages/app-contacts/schemas/contacts.json`), the
49 drag is an ORDINARY unguarded write, exactly as permissive as editing
50 that field through the generated form already is -- not a regression, not
51 a silently-invented guard. Adding a `transitions` (and optionally `flow`)
52 map to `contacts.json` to make the pipeline board a *guarded* workflow is
53 Stage-6 schema wiring, not done here (open question, carried forward
54 below). A rejected drop (`res.ok` false -- illegal `to`, or a failed
55 `when` guard) reverts the card to its origin column by simply re-drawing
56 from the last successfully loaded set; the record was never mutated
57 client-side before the server confirmed it.
58 **Open question carried forward verbatim from `31-wizard-kanban-stub.md`
59 via `60-list-modes-spec.md` (unresolved here too):** when one user drags
60 a card to another column while a second user's client is mid-scroll or
61 has independently reordered the same column's presentational order, does
62 the card resolve to its DOM position or its semantic (column) position
63 once both realtime updates land? v1 has no persisted within-column rank
64 (a reload always re-sorts by the collection's default sort), so there is
65 no "position" to preserve beyond column membership -- semantic/column
66 position wins by construction -- but this is stated, not proven under two
67 concurrent clients; needs a concrete look once this ships.
68- **tree** (account hierarchy, location hierarchy -- any self-relation).
69 Nests one flat 58 fetch by a `parent_field` self-relation
70 (`buildTree`), read-only in v1 (re-parenting stays a plain form edit).
71 **Cycle guard**: neither `fin_accounts.parent_id` nor `locations.
72 parent_id` has platform-level acyclicity enforcement (both schemas say so
73 in their own text) -- `buildTree` tracks a `visited` id set across the
74 whole render pass; a node already rendered is never re-descended into, so
75 a malformed loop renders once and stops instead of hanging the page. Logs
76 once (`console.warn`) when a render pass hits this, so an operator can
77 find the bad `parent_id`. **Depth cap** (`max_depth`, default 10) is a
78 second, independent guard alongside the cycle guard, not a restatement of
79 it: it bounds a legitimately deep (but acyclic) tree's render cost. A
80 node at the cap gets a `truncated: true` flag on its data (spec's own
81 open question -- "silent stop" vs. an affordance -- is left unresolved;
82 the flag exists so a future UI decision doesn't need a second data pass).
83 One implementation note NOT in the spec's own cost model: this renderer
84 does a single flat fetch (`/collections/{c}/records?limit=500`, exactly
85 the row list's own shape, plus `cfg.where`) and nests client-side, rather
86 than one 58 filter call per expanded level. Reason: this platform's query
87 parser drops a blank query value (`?parent_id=` for "root" -- Python's
88 `urllib.parse.parse_qsl` without `keep_blank_values=True`,
89 `object_server._parse_query`), so the spec's literal `{parent_field: ""}`
90 root filter can't be expressed as a query string today. One bounded fetch
91 (same `limit=500` ceiling every other list already accepts) sidesteps
92 that gap entirely and is still exactly a 58 filtered fetch, bucketed
93 client-side -- the same pattern board's own Storage section already
94 uses, just bucketing by `parent_field` instead of one enum.
95- **calendar** (month grid over a date/datetime field). One 58 range fetch
96 per visible month (`date_field.gte`/`date_field.lte`, 58's own operators,
97 nothing new), bucketed client-side by day (`bucketByDate`). A record with
98 no `date_field` value is never dropped: it renders once in an "Undated"
99 row above the grid. Read-only in v1 (dragging a card to reschedule is
100 future work); prev/next re-issues the range fetch, nothing prefetched.
101
102All three inherit 58's Permissions Posture with zero new access machinery:
103every card/node/cell comes from the exact `/collections/{c}/records`
104fetch the row list already issues (permission row-filter first, field
105filter second, same as any other read through this generator) -- a viewer
106who can't read a record never sees its card/node/cell, and a `group_field`/
107`parent_field`/`date_field` this file picks is always a real schema field
108(the same structure-only `/api/schema/{c}` endpoint window.dbbasicForm
109already reads), never a hidden one singled out.
110
111`list_modes_enabled` (default ON -- an absent or non-"off"/"false" value
112counts as on, since nothing in this codebase pre-seeds a `feature_flags`
113row) gates all three; off, or a mode whose field can't be derived (no enum
114for board, no self-relation for tree, no writable date for calendar, and no
115explicit `views.board`/`views.tree`/`views.calendar` override), falls back
116to the plain row list with a visible, correctable notice -- never a silent
117empty page, matching every other block's degrade-to-safe posture.
118
119Defined once here — every list page reuses it instead of hand-writing rows.
120"""
121
122_JS = r"""
123(function () {
124 const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g,
125 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
126 const qs = (m) => typeof m === "string" ? document.querySelector(m) : m;
127 const humanize = (n) => String(n || "").replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
128
129 function relDate(iso) {
130 if (!iso) return "";
131 const d = new Date(iso); if (isNaN(d)) return "";
132 const ms = Date.now() - d.getTime();
133 if (ms < 3600000) { const m = Math.floor(ms / 60000); return m < 1 ? "just now" : m + "m"; }
134 if (ms < 86400000) return Math.floor(ms / 3600000) + "h";
135 if (ms < 7 * 86400000) return Math.floor(ms / 86400000) + "d";
136 return d.toLocaleDateString(undefined, {month: "short", day: "numeric"});
137 }
138 function pills(v) {
139 return String(v || "").split(",").map((t) => t.trim()).filter(Boolean)
140 .map((t) => '<span class="pill">' + esc(t) + '</span>').join("");
141 }
142 // A single enum/status value renders as a colored badge -- the same
143 // treatment the bespoke Projects table gives "active". Tone is inferred
144 // from the value's meaning so the whole product agrees (a "done"/"paid"
145 // is green everywhere, a "blocked"/"overdue" red) without each schema
146 // having to declare colors. Unknown values get a neutral badge.
147 function badgeTone(val) {
148 const s = String(val || "").toLowerCase().replace(/[\s-]+/g, "_");
149 if (/^(active|done|complete|completed|paid|approved|published|resolved|won|live|success|ready|enabled|open)$/.test(s)) return "positive";
150 if (/^(blocked|overdue|failed|cancelled|canceled|rejected|lost|error|archived|expired|disabled|closed)$/.test(s)) return "danger";
151 if (/^(pending|in_progress|review|in_review|on_hold|draft|todo|new|waiting|queued|processing|backlog)$/.test(s)) return "warning";
152 return "";
153 }
154 function enumBadge(val) {
155 const tone = badgeTone(val);
156 return '<span class="badge' + (tone ? " " + tone : "") + '">' + esc(String(val)) + '</span>';
157 }
158
159 // 58's field=value encoding (implicit eq) -- one query param per `where`
160 // entry, ANDed by the server after its own permission row filter. `extra`
161 // layers on any additional dotted-operator params (calendar's own
162 // `date_field.gte`/`date_field.lte` range) with the same encoding. Shared
163 // by the plain row list and all three 60 modes below -- every mode's
164 // fetch is this SAME query builder, just with the mode's own grouping
165 // dimension bucketed client-side on top (see each render function).
166 function whereQueryString(where, extra) {
167 const parts = [];
168 if (where) for (const [k, v] of Object.entries(where)) parts.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
169 if (extra) for (const [k, v] of Object.entries(extra)) parts.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
170 return parts.length ? "&" + parts.join("&") : "";
171 }
172
173 function isEnumField(field) {
174 return !!field && (field.type === "enum" || Array.isArray(field.enum));
175 }
176
177 function isDateField(field) {
178 return !!field && (field.type === "date" || field.type === "datetime");
179 }
180
181 function fieldsByName(schema) {
182 const byName = {};
183 (schema.fields || []).forEach((f) => { byName[f.name] = f; });
184 return byName;
185 }
186
187 // ---- board: group by an enum field, columns in enum order --------------
188
189 // 60's default chain: the schema's `flow.field` (10-flow-spec.md's
190 // annotation of an existing transitions map -- inert today, no shipped
191 // schema declares `flow` yet, but honored the moment one does) else the
192 // first transitions-guarded enum (tasks.status) else the first plain enum
193 // (a bare lead_status-shaped field) else none (Degradation: falls back
194 // to table).
195 function defaultGroupField(schema) {
196 const fields = schema.fields || [];
197 const byName = fieldsByName(schema);
198 if (schema.flow && schema.flow.field && byName[schema.flow.field]) return schema.flow.field;
199 const guarded = fields.find((f) => isEnumField(f) && f.transitions && Object.keys(f.transitions).length > 0);
200 if (guarded) return guarded.name;
201 const anyEnum = fields.find(isEnumField);
202 return anyEnum ? anyEnum.name : null;
203 }
204
205 // "(unset)" column first (mirrors flow's own "an empty existing value may
206 // move anywhere" rule), then the enum's own declared order -- nothing
207 // re-sorted, re-derived, or alphabetized.
208 function boardColumns(field) {
209 return [""].concat((field && field.enum) || []);
210 }
211
212 // Buckets a flat record list by `groupField`'s value into `columns`. A
213 // value that isn't one of the field's declared enum options (stray data,
214 // not a spec'd case) folds into the "(unset)" bucket rather than either
215 // vanishing or inventing a new column on the fly -- never a dropped card.
216 function groupByColumn(records, groupField, columns) {
217 const known = new Set(columns);
218 const buckets = {};
219 columns.forEach((c) => { buckets[c] = []; });
220 for (const r of records) {
221 const v = known.has(String(r[groupField] || "")) ? String(r[groupField] || "") : "";
222 buckets[v].push(r);
223 }
224 return buckets;
225 }
226
227 function resolveBoardConfig(schema) {
228 const block = (schema.views && schema.views.board) || {};
229 const groupField = block.group_field || defaultGroupField(schema);
230 const field = groupField ? fieldsByName(schema)[groupField] : null;
231 if (!isEnumField(field)) {
232 return {error: "board mode needs an enum field -- none found; showing table"};
233 }
234 const cardFields = block.card_fields || (schema.views && schema.views.list_fields) || [];
235 return {config: {groupField: groupField, columns: boardColumns(field),
236 cardFields: cardFields, byName: fieldsByName(schema)}};
237 }
238
239 // ---- tree: nest by a self-relation, cycle-guarded + depth-capped -------
240
241 function isSelfRelation(schema, field) {
242 if (!field || !field.relation) return false;
243 const target = typeof field.relation === "string" ? field.relation : field.relation.collection;
244 return target === schema.name;
245 }
246
247 function resolveTreeConfig(schema) {
248 const block = (schema.views && schema.views.tree) || {};
249 const parentField = block.parent_field || "parent_id";
250 const field = fieldsByName(schema)[parentField];
251 if (!isSelfRelation(schema, field)) {
252 return {error: "tree mode needs a self-relation field ('" + parentField + "' is not one); showing table"};
253 }
254 const maxDepth = block.max_depth == null ? 10 : Number(block.max_depth);
255 return {config: {parentField: parentField, maxDepth: maxDepth}};
256 }
257
258 // Pure nest-and-guard over an already-fetched flat record list -- no DOM,
259 // no fetch, so this is what the test suite runs directly under node.
260 // `visited` is one Set for the whole render pass: a record already
261 // rendered once (reached from a first parent) is skipped, never
262 // re-descended, when some OTHER row's `parentField` also points at it --
263 // the guard 60's Storage section calls for against a malformed/cyclic
264 // `parent_id` chain. `maxDepth` is the independent second guard: a node
265 // at the cap still renders (never silently missing) but does not descend
266 // further, and carries `truncated: true` when it actually has children
267 // being cut off, so a future UI affordance has something to key off.
268 function buildTree(records, opts) {
269 opts = opts || {};
270 const parentField = opts.parentField || "parent_id";
271 const maxDepth = opts.maxDepth == null ? 10 : opts.maxDepth;
272 const startParentId = opts.startParentId || "";
273
274 const byParent = new Map();
275 for (const r of records) {
276 const p = String(r[parentField] || "");
277 if (!byParent.has(p)) byParent.set(p, []);
278 byParent.get(p).push(r);
279 }
280
281 const visited = new Set();
282 let cycleDetected = false;
283
284 function descend(parentId, depth) {
285 const kids = byParent.get(parentId) || [];
286 const out = [];
287 for (const child of kids) {
288 if (visited.has(child.id)) { cycleDetected = true; continue; }
289 visited.add(child.id);
290 const grandkids = byParent.get(child.id) || [];
291 const canDescend = depth + 1 < maxDepth;
292 out.push({
293 record: child,
294 depth: depth,
295 truncated: !canDescend && grandkids.length > 0,
296 children: canDescend ? descend(child.id, depth + 1) : [],
297 });
298 }
299 return out;
300 }
301
302 return {nodes: descend(startParentId, 0), cycleDetected: cycleDetected};
303 }
304
305 // ---- calendar: month grid over a date/datetime field --------------------
306
307 function defaultDateField(schema) {
308 const f = (schema.fields || []).find((f) => isDateField(f) && !f.read_only);
309 return f ? f.name : null;
310 }
311
312 function resolveCalendarConfig(schema) {
313 const block = (schema.views && schema.views.calendar) || {};
314 const dateField = block.date_field || defaultDateField(schema);
315 const field = dateField ? fieldsByName(schema)[dateField] : null;
316 if (!isDateField(field)) {
317 return {error: "calendar mode needs a date field -- none found; showing table"};
318 }
319 return {config: {dateField: dateField, defaultView: block.default_view || "month"}};
320 }
321
322 function monthRange(year, month) {
323 const start = new Date(Date.UTC(year, month, 1));
324 const end = new Date(Date.UTC(year, month + 1, 0));
325 return {start: start.toISOString().slice(0, 10), end: end.toISOString().slice(0, 10)};
326 }
327
328 // 42 cells (6 weeks); leading/trailing days from adjacent months are
329 // dimmed (inMonth: false) and never fetched -- purely a grid-shape filler.
330 function monthGridDays(year, month) {
331 const first = new Date(Date.UTC(year, month, 1));
332 const startOffset = first.getUTCDay();
333 const cells = [];
334 for (let i = 0; i < 42; i++) {
335 const d = new Date(Date.UTC(year, month, 1 - startOffset + i));
336 cells.push({date: d.toISOString().slice(0, 10), inMonth: d.getUTCMonth() === month});
337 }
338 return cells;
339 }
340
341 // A record with no `dateField` value lands in `undated`, never dropped --
342 // "visible gap, not silent loss", the same posture 58 commits to for an
343 // unfiltered fallback.
344 function bucketByDate(records, dateField) {
345 const byDay = {};
346 const undated = [];
347 for (const r of records) {
348 const v = r[dateField];
349 if (!v) { undated.push(r); continue; }
350 const day = String(v).slice(0, 10);
351 if (!byDay[day]) byDay[day] = [];
352 byDay[day].push(r);
353 }
354 return {byDay: byDay, undated: undated};
355 }
356
357 // ---- feature flag + schema-driven mode resolution ------------------------
358
359 // Default ON: nothing pre-seeds a `feature_flags` row for this flag, so
360 // "unknown" must read as "on" (an absent value would otherwise read as
361 // off through window.dbbasicFlags.on, which is default-false) -- only an
362 // explicit "off"/"false" value turns the three modes off.
363 async function listModesEnabled() {
364 if (!window.dbbasicFlags) return true;
365 try {
366 await window.dbbasicFlags.load();
367 const v = window.dbbasicFlags("list_modes_enabled");
368 return v !== "off" && v !== "false";
369 } catch (e) {
370 return true;
371 }
372 }
373
374 // Table config from a schema: columns from list_fields (curated) else every
375 // field, never the raw id. Returns null when there's nothing to show as
376 // columns. Hoisted out of resolveListMode so the board<->table switcher can
377 // build a table for a board-declared collection too (it has list_fields).
378 function buildTableConfig(schema) {
379 if (!schema) return null;
380 const byName = {}; (schema.fields || []).forEach((f) => byName[f.name] = f);
381 const fields = ((schema.views && schema.views.list_fields) || (schema.fields || []).map((f) => f.name))
382 .filter((n) => byName[n] && n !== "id");
383 return fields.length ? {fields: fields, byName: byName} : null;
384 }
385
386 // Filter controls from schema.views.filter_fields. Each named field becomes
387 // a control: an enum -> a select of its options, a boolean -> Yes/No. The
388 // chosen values are ANDed into the same server-side `where` fetch the board
389 // already uses (field=value, applied after the permission row filter), so a
390 // filtered list can only ever narrow what the viewer may already see. Types
391 // other than enum/boolean are skipped for now (text is covered by the search
392 // box; a date-range control is a follow-on that needs the dotted-operator
393 // `extra` query path). One declaration, filters on every mode.
394 function buildFilters(schema) {
395 const ff = schema && schema.views && schema.views.filter_fields;
396 if (!Array.isArray(ff) || !ff.length) return [];
397 const byName = {}; (schema.fields || []).forEach((f) => byName[f.name] = f);
398 const out = [];
399 for (const name of ff) {
400 const f = byName[name]; if (!f) continue;
401 const t = String(f.type || "").toLowerCase();
402 if (t === "enum" || Array.isArray(f.enum)) {
403 out.push({name: name, label: f.label || humanize(name), type: "enum", options: f.enum || []});
404 } else if (t === "boolean") {
405 out.push({name: name, label: f.label || humanize(name), type: "boolean"});
406 }
407 }
408 return out;
409 }
410
411 // Resolve relation fields to a human label instead of a raw FK id. A field
412 // with `relation: {collection, display_field}` stores an id (o-acme); the
413 // table/board should show the target's name ("Acme"), the way the detail
414 // page already does. Fetch each referenced collection once, build an
415 // id->display map. Done once per render surface (not per realtime reload) --
416 // relation targets are comparatively stable, and a stale label just corrects
417 // on the next full load. Fails soft: a field with no map falls back to the id.
418 async function loadRelationMaps(byName, fields) {
419 const maps = {};
420 await Promise.all((fields || []).map(async (n) => {
421 const f = byName && byName[n];
422 if (!f || !f.relation) return;
423 const col = typeof f.relation === "string" ? f.relation : f.relation.collection;
424 const disp = (typeof f.relation === "object" && f.relation.display_field) || "name";
425 try {
426 const res = await fetch("/collections/" + encodeURIComponent(col) + "/records?limit=500",
427 {credentials: "same-origin", headers: {accept: "application/json"}});
428 if (!res.ok) return;
429 const body = await res.json();
430 const m = {};
431 for (const r of (body.records || [])) m[r.id] = r[disp] || r.id;
432 maps[n] = m;
433 } catch (e) { /* leave unmapped -> falls back to the id */ }
434 }));
435 return maps;
436 }
437 function relLabel(fname, value, byName, relMaps) {
438 const f = byName && byName[fname];
439 if (f && f.relation && relMaps && relMaps[fname] && (value in relMaps[fname])) return relMaps[fname][value];
440 return value;
441 }
442
443 async function resolveListMode(collection) {
444 if (!(await listModesEnabled())) return {kind: null, notice: null, schema: null};
445
446 let schema = null;
447 try {
448 const res = await fetch("/api/schema/" + encodeURIComponent(collection),
449 {credentials: "same-origin", headers: {accept: "application/json"}});
450 if (res.ok) { const body = await res.json(); schema = body.schema || null; }
451 } catch (e) { schema = null; }
452 if (!schema) return {kind: null, notice: null, schema: null};
453
454 const wanted = schema.views && schema.views.list_mode;
455 if (wanted === "board") {
456 const r = resolveBoardConfig(schema);
457 return r.config ? {kind: "board", config: r.config, schema: schema} : {kind: null, notice: r.error, schema: schema};
458 }
459 if (wanted === "tree") {
460 const r = resolveTreeConfig(schema);
461 return r.config ? {kind: "tree", config: r.config, schema: schema} : {kind: null, notice: r.error, schema: schema};
462 }
463 if (wanted === "calendar") {
464 const r = resolveCalendarConfig(schema);
465 return r.config ? {kind: "calendar", config: r.config, schema: schema} : {kind: null, notice: r.error, schema: schema};
466 }
467 if (wanted === "table") {
468 const cfg = buildTableConfig(schema);
469 return cfg ? {kind: "table", config: cfg, schema: schema} : {kind: null, notice: null, schema: schema};
470 }
471 return {kind: null, notice: null, schema: schema};
472 }
473
474 // ---- board/tree/calendar renderers (impure: fetch + DOM + realtime) ----
475
476 function cardTitle(cfg, r) {
477 // Label a record by a human field, trying common text fields before the raw
478 // id -- so a comment / note / message / interaction (no title/name field)
479 // shows its actual text instead of a UUID (and the avatar gets a real
480 // letter). cfg.title overrides everything.
481 const auto = r.title || r.name || r.label || r.subject || r.body || r.text
482 || r.content || r.message || r.description || r.email || r.id;
483 return (cfg.title ? cfg.title(r) : auto) || "(untitled)";
484 }
485
486 function renderBoard(collection, cfg, mount, boardCfg) {
487 let all = [];
488 let relMaps = {};
489
490 function cardHtml(r) {
491 const title = cardTitle(cfg, r);
492 // Skip the group field, empties, and any field whose value is already
493 // part of the title (first_name/last_name when the title is the full
494 // name) -- otherwise the card repeats "Grace" / "Hopper" under "Grace
495 // Hopper". Relation fields show the resolved label, not the raw FK id.
496 const extra = boardCfg.cardFields.filter((f) => f !== boardCfg.groupField && r[f])
497 .map((f) => relLabel(f, String(r[f]), boardCfg.byName, relMaps))
498 .filter((label) => label && String(title).indexOf(label) === -1)
499 .map((label) => '<div class="boardcardfield">' + esc(label) + '</div>').join("");
500 return '<div class="boardcard" draggable="true" data-id="' + esc(r.id) + '">'
501 + '<div class="boardcardtitle">' + esc(title) + '</div>' + extra + '</div>';
502 }
503
504 function draw() {
505 const buckets = groupByColumn(all, boardCfg.groupField, boardCfg.columns);
506 mount.innerHTML = '<div class="board">' + boardCfg.columns.map((col) =>
507 '<div class="boardcol">'
508 + '<div class="boardcolhead">' + esc(col || "(unset)")
509 + '<span class="boardcolcount">' + buckets[col].length + '</span></div>'
510 + '<div class="boardcolbody" data-drop="' + esc(col) + '">' + buckets[col].map(cardHtml).join("") + '</div>'
511 + '</div>'
512 ).join("") + '</div>';
513 wireDrag();
514 }
515
516 function wireDrag() {
517 mount.querySelectorAll(".boardcard").forEach((card) => {
518 card.addEventListener("dragstart", (e) => {
519 e.dataTransfer.setData("text/plain", card.dataset.id);
520 e.dataTransfer.effectAllowed = "move";
521 });
522 // A board card opens its detail on click. HTML5 drag-and-drop does not
523 // emit a click, so a plain click is unambiguous -- no drag-guard flag
524 // (an earlier guard could get stuck and swallow a card's click).
525 if (cfg.link !== false) {
526 card.style.cursor = "pointer";
527 card.addEventListener("click", () => {
528 const id = card.dataset.id;
529 const record = all.find((x) => x.id === id) || {id: id};
530 window.location.href = cfg.href ? cfg.href(record) : "/" + collection + "/" + encodeURIComponent(id);
531 });
532 }
533 });
534 mount.querySelectorAll(".boardcolbody").forEach((body) => {
535 body.addEventListener("dragover", (e) => { e.preventDefault(); e.dataTransfer.dropEffect = "move"; });
536 body.addEventListener("drop", async (e) => {
537 e.preventDefault();
538 const id = e.dataTransfer.getData("text/plain");
539 const toCol = body.dataset.drop;
540 const record = all.find((r) => r.id === id);
541 if (!record || String(record[boardCfg.groupField] || "") === toCol) return;
542 // 10-flow: this is the ordinary record-update write path -- the
543 // exact PUT any row action or generated-form edit already issues.
544 // object_records.update_collection_record runs
545 // _validate_field_transitions on it unconditionally; a `to` not
546 // present in the source value's transitions list, or a failing
547 // `when` guard, comes back non-2xx here. Nothing is applied
548 // client-side before that response, so a rejected move needs no
549 // undo -- re-drawing from `all` (unchanged) is the revert.
550 const res = await fetch("/collections/" + collection + "/records/" + encodeURIComponent(id), {
551 method: "PUT",
552 credentials: "same-origin",
553 headers: {"content-type": "application/json", accept: "application/json"},
554 body: JSON.stringify({[boardCfg.groupField]: toCol}),
555 });
556 if (!res.ok) {
557 let message = "Move rejected";
558 try { const body = await res.json(); message = body.error || message; } catch (e2) {}
559 draw();
560 if (cfg.onError) cfg.onError(message); else alert(message);
561 return;
562 }
563 load();
564 });
565 });
566 }
567
568 async function load() {
569 const res = await fetch("/collections/" + collection + "/records?limit=500" + whereQueryString(cfg.where),
570 {credentials: "same-origin", headers: {accept: "application/json"}});
571 if (!res.ok) { mount.innerHTML = '<div class="state denied">Not available.</div>'; return; }
572 const body = await res.json();
573 all = body.records || [];
574 draw();
575 }
576
577 (function sub() {
578 if (window.dbbasicSubscribe) window.dbbasicSubscribe(collection, load);
579 else setTimeout(sub, 400);
580 })();
581 // Resolve card relation labels once (org id -> name) before first draw.
582 loadRelationMaps(boardCfg.byName, boardCfg.cardFields).then((m) => { relMaps = m; load(); });
583 return load;
584 }
585
586 function renderTree(collection, cfg, mount, treeCfg) {
587 function nodeHtml(node) {
588 const kidsHtml = node.children.length
589 ? '<div class="treekids">' + node.children.map(nodeHtml).join("") + '</div>'
590 : "";
591 const toggle = node.children.length
592 ? '<button type="button" class="treetoggle" data-act="toggle">&#9662;</button>'
593 : '<span class="treeleaf"></span>';
594 const cap = node.truncated ? '<span class="pill" title="More levels not shown">&hellip;</span>' : "";
595 return '<div class="treenode" style="--depth:' + node.depth + '">'
596 + '<div class="treerow">' + toggle + '<span class="treetitle">' + esc(cardTitle(cfg, node.record)) + '</span>' + cap + '</div>'
597 + kidsHtml + '</div>';
598 }
599
600 function draw(built) {
601 if (built.cycleDetected) {
602 console.warn("[dbbasicList tree] a parent_id cycle was detected in '" + collection
603 + "' -- each affected node renders once and is not re-descended.");
604 }
605 mount.innerHTML = built.nodes.length
606 ? '<div class="tree">' + built.nodes.map(nodeHtml).join("") + '</div>'
607 : '<div class="state">Nothing yet.</div>';
608 mount.querySelectorAll("button.treetoggle").forEach((btn) => {
609 btn.addEventListener("click", () => {
610 const kids = btn.closest(".treenode").querySelector(".treekids");
611 if (kids) kids.classList.toggle("collapsed");
612 });
613 });
614 }
615
616 async function load() {
617 const res = await fetch("/collections/" + collection + "/records?limit=500" + whereQueryString(cfg.where),
618 {credentials: "same-origin", headers: {accept: "application/json"}});
619 if (!res.ok) { mount.innerHTML = '<div class="state denied">Not available.</div>'; return; }
620 const body = await res.json();
621 draw(buildTree(body.records || [], {parentField: treeCfg.parentField, maxDepth: treeCfg.maxDepth}));
622 }
623
624 (function sub() {
625 if (window.dbbasicSubscribe) window.dbbasicSubscribe(collection, load);
626 else setTimeout(sub, 400);
627 })();
628 load();
629 return load;
630 }
631
632 function renderCalendar(collection, cfg, mount, calCfg) {
633 const today = new Date();
634 let year = today.getUTCFullYear();
635 let month = today.getUTCMonth();
636
637 function eventHtml(r) {
638 const title = cardTitle(cfg, r);
639 return '<div class="calevent" title="' + esc(title) + '">' + esc(title) + '</div>';
640 }
641
642 function draw(bucketed) {
643 const cells = monthGridDays(year, month);
644 const undatedHtml = bucketed.undated.length
645 ? '<div class="calundated"><span class="calundatedlabel">Undated (' + bucketed.undated.length + ')</span>'
646 + bucketed.undated.map(eventHtml).join("") + '</div>'
647 : "";
648 const gridHtml = cells.map((c) => {
649 const evs = bucketed.byDay[c.date] || [];
650 return '<div class="calcell' + (c.inMonth ? "" : " dim") + '"><div class="caldate">'
651 + Number(c.date.slice(8, 10)) + '</div>' + evs.map(eventHtml).join("") + '</div>';
652 }).join("");
653 const label = new Date(Date.UTC(year, month, 1)).toLocaleDateString(undefined, {month: "long", year: "numeric"});
654 mount.innerHTML = '<div class="calheader"><button type="button" class="btn sm" data-act="prev">&lsaquo;</button>'
655 + '<span class="calmonth">' + esc(label) + '</span>'
656 + '<button type="button" class="btn sm" data-act="next">&rsaquo;</button></div>'
657 + undatedHtml + '<div class="calgrid">' + gridHtml + '</div>';
658 mount.querySelector('[data-act="prev"]').addEventListener("click", () => {
659 month--; if (month < 0) { month = 11; year--; } load();
660 });
661 mount.querySelector('[data-act="next"]').addEventListener("click", () => {
662 month++; if (month > 11) { month = 0; year++; } load();
663 });
664 }
665
666 async function load() {
667 const range = monthRange(year, month);
668 const extra = {};
669 extra[calCfg.dateField + ".gte"] = range.start;
670 extra[calCfg.dateField + ".lte"] = range.end;
671 const res = await fetch("/collections/" + collection + "/records?limit=500" + whereQueryString(cfg.where, extra),
672 {credentials: "same-origin", headers: {accept: "application/json"}});
673 if (!res.ok) { mount.innerHTML = '<div class="state denied">Not available.</div>'; return; }
674 const body = await res.json();
675 draw(bucketByDate(body.records || [], calCfg.dateField));
676 }
677
678 (function sub() {
679 if (window.dbbasicSubscribe) window.dbbasicSubscribe(collection, load);
680 else setTimeout(sub, 400);
681 })();
682 load();
683 return load;
684 }
685
686 // ---- the plain row list (table/cards/feed -- unchanged behavior) -------
687
688 window.dbbasicList = function (collection, cfg) {
689 cfg = Object.assign({}, cfg || {}); // own a copy -- 65 may add cfg.where below
690 const mount = qs(cfg.mount);
691 const searchEl = cfg.search ? qs(cfg.search) : null;
692 const sortEl = cfg.sort ? qs(cfg.sort) : null;
693 let all = [];
694 let activeReload = null;
695
696 // Page hooks: cfg.slots[name] (per page) + window.dbbasicSlots (cross-page,
697 // operator-registered). Both return HTML; the generator injects it at the
698 // named hook. No-op when neither is present.
699 function slotHtml(name, ctx) {
700 let out = "";
701 const local = cfg.slots && cfg.slots[name];
702 if (local) { try { const h = local(ctx); if (h) out += h; } catch (e) {} }
703 if (window.dbbasicSlots) out += window.dbbasicSlots.render(collection, name, ctx);
704 return out;
705 }
706
707 function startRowList(notice, table) {
708 // Relation columns (organization_id -> "Acme") resolved once for the table.
709 let relMaps = {};
710 // Edit/delete only for a row the viewer actually owns. BOTH ids must be
711 // present and equal -- a log/report/rollup row has no owner_id, and a
712 // report view has no cfg.owner, so `undefined === undefined` must not
713 // wrongly offer actions. `cfg.rowActions:false` is the explicit off
714 // switch. Shared by the row list and the table so both modes offer the
715 // SAME actions -- flipping between them never silently drops edit/delete.
716 function isMine(r) { return !!(cfg.owner && r.owner_id && r.owner_id === cfg.owner); }
717 function rowActionsHtml(r) {
718 const acts = (cfg.rowActions !== false && isMine(r))
719 ? '<button class="rowbtn" data-act="edit" data-id="' + esc(r.id) + '" title="Edit">✎</button>'
720 + '<button class="rowbtn danger" data-act="delete" data-id="' + esc(r.id) + '" title="Delete">✕</button>'
721 : "";
722 return acts + slotHtml("row_actions", r);
723 }
724 function row(r) {
725 const title = cardTitle(cfg, r);
726 const av = String(title).trim().charAt(0) || "?";
727 // Every row links to its detail view -- reachability, "everything has a
728 // url". The detail route is `/{collection}/{id}` by convention; cfg.href
729 // overrides it (and is treated as an external/new-tab link), and
730 // cfg.link === false opts a report/log (no detail page) out entirely.
731 const href = (cfg.link === false) ? "" : (cfg.href ? cfg.href(r) : "/" + collection + "/" + encodeURIComponent(r.id));
732 const linkAttrs = cfg.href ? ' target="_blank" rel="noopener"' : "";
733 const titleHtml = href
734 ? '<a href="' + esc(href) + '"' + linkAttrs + '>' + esc(title) + '</a>'
735 : esc(title);
736 const sub = cfg.subtitle ? cfg.subtitle(r) : "";
737 const tags = cfg.tags ? cfg.tags(r) : "";
738 const created = cfg.created ? cfg.created(r) : r.created_at;
739 // Edit/delete only for a row the viewer actually owns. BOTH ids must be
740 // present and equal -- a log/report/rollup row has no owner_id, and a
741 // report view has no cfg.owner, so the old `undefined === undefined`
742 // wrongly offered edit/delete on generated data. `cfg.rowActions:false`
743 // is the explicit off switch (a list block over a log/report sets it).
744 return '<div class="listrow"><div class="av">' + esc(av) + '</div><div class="body">'
745 + '<div class="rowtitle">' + titleHtml + '</div>'
746 + (sub ? '<div class="rowsub">' + esc(sub) + '</div>' : "")
747 + '<div class="rowmeta">' + (created ? '<span class="when">' + esc(relDate(created)) + '</span>' : "")
748 + pills(tags) + '</div></div><div class="rowactions">' + rowActionsHtml(r) + '</div></div>';
749 }
750 // A list over a collection with real volume (a rollup report, a busy log)
751 // must never render every row -- that produces a 50,000px page. Cap the
752 // rendered rows (cfg.limit, default 50) with a Show-all toggle; the data
753 // is already fetched, so expanding is free. Universal: every list surface
754 // in every app inherits the cap, no per-view opt-in.
755 const DEFAULT_ROW_CAP = 50;
756 let expanded = false;
757 let lastList = [];
758 function sortList(list) {
759 // A report can sort by a real field+direction (cfg.sortBy) -- e.g. top
760 // IPs by hits, descending -- otherwise fall back to the created_at
761 // newest/oldest default the sort <select> drives.
762 if (cfg.sortBy && cfg.sortBy.field) {
763 const f = cfg.sortBy.field, dir = (cfg.sortBy.dir === "asc") ? 1 : -1;
764 return list.slice().sort((a, b) => {
765 const an = parseFloat(a[f]), bn = parseFloat(b[f]);
766 const cmp = (!isNaN(an) && !isNaN(bn))
767 ? (an - bn)
768 : String(a[f] == null ? "" : a[f]).localeCompare(String(b[f] == null ? "" : b[f]));
769 return cmp * dir;
770 });
771 }
772 const s = list.slice().sort((a, b) => String(a.created_at || "").localeCompare(String(b.created_at || "")));
773 return (sortEl && sortEl.value === "oldest") ? s : s.reverse();
774 }
775 // ---- table list_mode: a real <table> over the SAME fetch/sort/cap/
776 // subscribe pipeline as the row list, so it inherits filtering, the
777 // render cap, detail links, and LIVE UPDATES for free. `table` is
778 // {fields, byName} from the schema (list_fields + field metadata); cells
779 // are formatted by field semantics; headers sort; rows link to detail.
780 function humanName(n) { return String(n || "").replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()); }
781 function fmtCell(fname, r) {
782 const f = (table && table.byName[fname]) || {};
783 const t = String(f.type || "").toLowerCase();
784 const v = r[fname];
785 if (v == null || v === "") return "—";
786 if (/_cents$/.test(fname) && (t === "integer" || t === "number")) {
787 const n = parseFloat(v); if (!isNaN(n)) return "$" + (n / 100).toFixed(2);
788 }
789 if (t === "boolean") return v === "true" ? "Yes" : "No";
790 if (t === "datetime" || t === "date") return esc(relDate(v));
791 if (f.relation) return esc(relLabel(fname, String(v), table.byName, relMaps));
792 if (isEnumField(f)) return enumBadge(v);
793 if (/(^|_)tags?$/.test(fname) || t === "array" || t === "list") return pills(v) || "—";
794 return esc(String(v));
795 }
796 function tableBody(shown) {
797 const sf = cfg.sortBy && cfg.sortBy.field;
798 // Peer with the row list: an owned row gets the same edit/delete (+ any
799 // row_actions slot) in a trailing column. Only add the column when a
800 // shown row actually has actions, so a read-only/report table stays a
801 // clean grid with no empty trailing column.
802 const showActs = shown.some((r) => rowActionsHtml(r) !== "");
803 const th = table.fields.map((n) => {
804 const f = table.byName[n] || {};
805 const arrow = (sf === n) ? (cfg.sortBy.dir === "asc" ? " ▲" : " ▼") : "";
806 return '<th data-sort="' + esc(n) + '">' + esc(f.label || humanName(n)) + arrow + '</th>';
807 }).join("") + (showActs ? '<th class="dtactions" aria-label="Actions"></th>' : "");
808 const trs = shown.map((r) => {
809 const tds = table.fields.map((n) => '<td>' + fmtCell(n, r) + '</td>').join("")
810 + (showActs ? '<td class="dtactions">' + rowActionsHtml(r) + '</td>' : "");
811 return '<tr data-id="' + esc(r.id) + '"' + (cfg.link !== false ? ' class="clickrow"' : "") + '>' + tds + '</tr>';
812 }).join("");
813 return '<div class="dtablewrap"><table class="dtable"><thead><tr>' + th
814 + '</tr></thead><tbody>' + trs + '</tbody></table></div>';
815 }
816 function render(list) {
817 lastList = list;
818 const sorted = sortList(list);
819 const cap = (cfg.limit != null) ? cfg.limit : DEFAULT_ROW_CAP;
820 const shown = expanded ? sorted : sorted.slice(0, cap);
821 const ctx = {collection: collection, count: list.length};
822 const body = shown.length
823 ? (table ? tableBody(shown) : shown.map(row).join(""))
824 : (slotHtml("empty", ctx) || '<div class="state">Nothing yet.</div>');
825 const noticeHtml = notice ? '<div class="state notice">' + esc(notice) + '</div>' : "";
826 let more = "";
827 if (sorted.length > cap) {
828 more = expanded
829 ? '<button class="listmore" data-act="collapse">Show fewer</button>'
830 : '<button class="listmore" data-act="showall">Show all ' + sorted.length + '</button>';
831 }
832 mount.innerHTML = noticeHtml + slotHtml("before_list", ctx) + body + more + slotHtml("after_list", ctx);
833 }
834 async function load() {
835 const res = await fetch("/collections/" + collection + "/records?limit=500" + whereQueryString(cfg.where),
836 {credentials: "same-origin", headers: {accept: "application/json"}});
837 if (!res.ok) { render([]); return; }
838 const body = await res.json(); all = body.records || []; render(all);
839 }
840 // Last-request-wins: each keystroke bumps a sequence token so a slow
841 // in-flight /api/search response can't land AFTER a newer input (or a
842 // backspace-to-empty) and overwrite the current view with stale
843 // filtered results -- the "clear the box but it still shows filtered"
844 // bug. Both the empty path and every await checkpoint honor the token.
845 let searchSeq = 0;
846 async function search(q) {
847 const seq = ++searchSeq;
848 if (!q) { render(all); return; }
849 const res = await fetch("/api/search?q=" + encodeURIComponent(q) + "&collections=" + collection + "&limit=50",
850 {credentials: "same-origin", headers: {accept: "application/json"}});
851 if (seq !== searchSeq || !res.ok) return;
852 const body = await res.json();
853 if (seq !== searchSeq) return;
854 render((body.results || {})[collection] || []);
855 }
856
857 if (searchEl) searchEl.addEventListener("input", (e) => search(e.target.value.trim()));
858 if (sortEl) sortEl.addEventListener("change", () => render(all));
859 mount.addEventListener("click", async (e) => {
860 const more = e.target.closest("button.listmore");
861 if (more) { expanded = (more.dataset.act === "showall"); render(lastList); return; }
862 // table: click a header to sort by that column (toggle desc/asc); click
863 // a row to open its detail (same reachability as the row list / cards).
864 const thSort = e.target.closest("th[data-sort]");
865 if (thSort) {
866 const f = thSort.dataset.sort, cur = cfg.sortBy || {};
867 cfg.sortBy = {field: f, dir: (cur.field === f && cur.dir !== "asc") ? "asc" : "desc"};
868 render(lastList); return;
869 }
870 // A row click opens detail -- UNLESS the click landed on an action
871 // button or a link inside the row (the actions column, or a linked
872 // cell), which have their own behavior.
873 const clickrow = e.target.closest("tr.clickrow");
874 if (clickrow && !e.target.closest("button, a")) {
875 const id = clickrow.dataset.id, rec = all.find((x) => x.id === id) || {id: id};
876 window.location.href = cfg.href ? cfg.href(rec) : "/" + collection + "/" + encodeURIComponent(id);
877 return;
878 }
879 const btn = e.target.closest("button.rowbtn"); if (!btn) return;
880 const id = btn.dataset.id;
881 if (btn.dataset.act === "delete") {
882 if (!confirm("Delete this?")) return;
883 await fetch("/collections/" + collection + "/records/" + encodeURIComponent(id),
884 {method: "DELETE", credentials: "same-origin", headers: {accept: "application/json"}});
885 load();
886 } else if (btn.dataset.act === "edit" && cfg.onEdit) {
887 const r = all.find((x) => x.id === id); if (r) cfg.onEdit(r);
888 }
889 });
890 (function sub() {
891 if (window.dbbasicSubscribe) window.dbbasicSubscribe(collection, load);
892 else setTimeout(sub, 400);
893 })();
894 // In table mode, resolve relation labels once before the first render so
895 // columns show names not FK ids; the plain row list has no such columns.
896 if (table) {
897 loadRelationMaps(table.byName, table.fields).then((m) => { relMaps = m; load(); });
898 } else {
899 load();
900 }
901 return load;
902 }
903
904 // 60: resolve list_mode from the schema once, then delegate to
905 // board/tree/calendar -- or fall through to the plain row list above,
906 // completely unchanged, when the mode is table/cards/feed/absent, the
907 // flag is off, or the mode's field can't be derived (Degradation: falls
908 // back to table with a visible notice, never a silent empty page).
909 // 65 multi-entity: auto-scope a TOP-LEVEL browse list to the nav
910 // switcher's current entity. Only when there is no existing cfg.where --
911 // a `related` child list (a journal's postings, matched by journal_id) or
912 // an explicitly filtered list already carries the scope it needs, and
913 // adding the current entity there would wrongly hide a parent's children
914 // when a different entity is selected. Gated on an entity actually being
915 // selected AND the collection having an entity_id field, so non-entity
916 // lists and the "All entities" state are untouched (the same never-hide-
917 // by-default posture 58 takes for its own filters).
918 async function scopeToCurrentEntity() {
919 const cur = (window.dbbasicEntity && window.dbbasicEntity()) || "";
920 if (!cur || cfg.where) return;
921 try {
922 const res = await fetch("/api/schema/" + encodeURIComponent(collection),
923 {credentials: "same-origin", headers: {accept: "application/json"}});
924 if (!res.ok) return;
925 const schema = (await res.json()).schema;
926 if (schema && (schema.fields || []).some((f) => f.name === "entity_id")) {
927 cfg.where = {entity_id: cur};
928 }
929 } catch (e) { /* schema fetch failed -- leave the list unscoped, never blank */ }
930 }
931
932 // A grouped mode (board/tree/calendar) hides the row list's search + sort
933 // box -- those controls only drive the row list. Table and plain-list keep
934 // them.
935 function setGroupedControls(hidden) {
936 if (sortEl) sortEl.style.display = hidden ? "none" : "";
937 if (searchEl) searchEl.style.display = hidden ? "none" : "";
938 }
939
940 // board <-> table switcher. Persist the choice and reload rather than
941 // swap in place: window.dbbasicSubscribe has no unsubscribe, so an
942 // in-place swap would leave the previous mode's change-log handler live
943 // and double-render. One page load = one subscription. The choice is
944 // per-collection and survives navigation.
945 const modeStoreKey = "dbb_listmode_" + collection;
946 function storedMode() {
947 try { return window.localStorage.getItem(modeStoreKey); } catch (e) { return null; }
948 }
949 function storeMode(m) {
950 try { window.localStorage.setItem(modeStoreKey, m); } catch (e) {}
951 }
952 function renderSwitcher(current, modes) {
953 if (!mount || !mount.parentNode) return;
954 const bar = document.createElement("div");
955 bar.className = "listmodes";
956 bar.setAttribute("role", "tablist");
957 bar.innerHTML = modes.map((m) =>
958 '<button type="button" class="modebtn' + (m.key === current ? " active" : "")
959 + '" data-mode="' + m.key + '" aria-selected="' + (m.key === current) + '">'
960 + esc(m.label) + "</button>").join("");
961 mount.parentNode.insertBefore(bar, mount);
962 bar.addEventListener("click", (e) => {
963 const btn = e.target.closest("[data-mode]");
964 if (!btn) return;
965 const mk = btn.getAttribute("data-mode");
966 if (mk === current) return;
967 storeMode(mk);
968 window.location.reload();
969 });
970 }
971
972 // Filter bar: a row of selects above the list, one per filter field. A
973 // change ANDs the picked value into cfg.where and reloads the active mode
974 // -- server-side narrowing that composes with the caller's own where
975 // (entity scope, a parent FK) and with the client-side search box. Shown
976 // in every mode. Insert before mount so a mode re-render (which replaces
977 // mount's contents) never disturbs it.
978 function renderFilters(filters, onChange) {
979 if (!filters.length || !mount || !mount.parentNode) return;
980 const bar = document.createElement("div");
981 bar.className = "listfilters";
982 bar.innerHTML = filters.map((f) => {
983 let opts = '<option value="">All ' + esc(f.label) + '</option>';
984 if (f.type === "enum") for (const o of f.options) opts += '<option value="' + esc(o) + '">' + esc(o) + '</option>';
985 else if (f.type === "boolean") opts += '<option value="true">Yes</option><option value="false">No</option>';
986 return '<select class="filterctl" data-filter="' + esc(f.name) + '" aria-label="Filter by ' + esc(f.label) + '">' + opts + '</select>';
987 }).join("") + '<button type="button" class="filterclear" data-filterclear hidden>Clear</button>';
988 mount.parentNode.insertBefore(bar, mount);
989 const clearBtn = bar.querySelector("[data-filterclear]");
990 function sync() {
991 const any = [].some.call(bar.querySelectorAll("select[data-filter]"), (s) => s.value);
992 if (clearBtn) clearBtn.hidden = !any;
993 }
994 bar.addEventListener("change", (e) => {
995 const sel = e.target.closest("select[data-filter]");
996 if (!sel) return;
997 onChange(sel.getAttribute("data-filter"), sel.value);
998 sync();
999 });
1000 if (clearBtn) clearBtn.addEventListener("click", () => {
1001 bar.querySelectorAll("select[data-filter]").forEach((s) => { s.value = ""; });
1002 onChange(null, null);
1003 sync();
1004 });
1005 }
1006
1007 (async function boot() {
1008 await scopeToCurrentEntity();
1009 // Capture the caller/entity scope AFTER scopeToCurrentEntity so user
1010 // filters layer on top of it rather than replacing it.
1011 const baseWhere = cfg.where ? Object.assign({}, cfg.where) : null;
1012 const resolved = await resolveListMode(collection);
1013
1014 // Wire filters (enum/boolean) once, before dispatching a mode -- they
1015 // apply to whichever renderer becomes active.
1016 const filterState = {};
1017 function applyFilterWhere() {
1018 const merged = Object.assign({}, baseWhere || {});
1019 for (const k in filterState) if (filterState[k] != null && filterState[k] !== "") merged[k] = filterState[k];
1020 cfg.where = Object.keys(merged).length ? merged : null;
1021 }
1022 function onFilterChange(field, value) {
1023 if (field === null) { for (const k in filterState) delete filterState[k]; }
1024 else if (value == null || value === "") delete filterState[field];
1025 else filterState[field] = value;
1026 applyFilterWhere();
1027 if (activeReload) activeReload();
1028 }
1029 renderFilters(buildFilters(resolved.schema), onFilterChange);
1030
1031 // A board-declared collection that also has list_fields can render as a
1032 // table too, so offer a switcher (the classic kanban<->list toggle). The
1033 // user's pick (localStorage) wins over the schema default.
1034 const tableConfig = buildTableConfig(resolved.schema);
1035 const canBoard = resolved.kind === "board";
1036 if (canBoard && tableConfig) {
1037 const pick = storedMode() === "table" ? "table" : "board";
1038 renderSwitcher(pick, [{key: "board", label: "Board"}, {key: "table", label: "Table"}]);
1039 if (pick === "table") {
1040 setGroupedControls(false);
1041 activeReload = startRowList(null, tableConfig);
1042 } else {
1043 setGroupedControls(true);
1044 activeReload = renderBoard(collection, cfg, mount, resolved.config);
1045 }
1046 return;
1047 }
1048 if (resolved.kind === "board" || resolved.kind === "tree" || resolved.kind === "calendar") {
1049 setGroupedControls(true);
1050 if (resolved.kind === "board") { activeReload = renderBoard(collection, cfg, mount, resolved.config); return; }
1051 if (resolved.kind === "tree") { activeReload = renderTree(collection, cfg, mount, resolved.config); return; }
1052 activeReload = renderCalendar(collection, cfg, mount, resolved.config); return;
1053 }
1054 // table keeps the search box + sort control (unlike the grouped modes) --
1055 // it's the row list rendered as a <table>, so those controls still apply.
1056 if (resolved.kind === "table") { activeReload = startRowList(resolved.notice, resolved.config); return; }
1057 activeReload = startRowList(resolved.notice);
1058 })();
1059
1060 return {reload: () => { if (activeReload) activeReload(); }};
1061 };
1062})();
1063"""
1064
1065
1066def GET(request):
1067 return {"content_type": "application/javascript; charset=utf-8", "body": _JS}