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

9 downloads

Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
view_render.py · 43.6 KB · 876 lines
1"""The universal view renderer: one object that draws any `views` record.
2
3Served through a site route like /views/{view_id:uuid}. The browser fetches
4the view record with the visitor's own session cookie, so the permission
5policy decides visibility (owner + is_public, same as every other record) --
6the renderer adds no data path of its own. Each block then re-fetches its
7own data the same way, so a public view over a private collection renders
8its frame plus an empty/denied block for anonymous visitors: it can never
9show what the engine would not otherwise serve.
10
11Blocks are DATA, not code: a closed v1 vocabulary of eight kinds --
12list, form, detail, related, thread, count, markdown, reader -- read from
13the record's `blocks` JSON and rendered through the existing generators
14(window.dbbasicList, window.dbbasicForm, window.dbbasicDetail,
15window.dbbasicThread) or small renderers here. An unknown kind, a
16malformed block, or invalid blocks JSON never becomes a blank page or raw
17markup: it becomes a visible placeholder card, and the rest of the view
18still renders.
19
20`reader` ({kind:'reader', url}) is client-side like every other block
21here: it POSTs the url to /api/read (object_server's flag-gated,
22signed-in-only fetch -- see DBBASIC_ENABLE_READER and object_reader's SSRF
23gate) and renders the stripped title/text/links it gets back. A disabled
24flag, a signed-out visitor, or a refused/failed fetch all come back as a
25normal JSON error body, which renders as the same placeholder card as any
26other broken block -- no separate error path needed here.
27
28`detail` (`59-detail-related-spec.md`) renders ONE record, read-only,
29composed -- it does not re-derive field layout itself, it mounts
30window.dbbasicDetail (served at /detail), which in turn reuses /form's
31own field-rendering pipeline in forced-read-only mode
32(window.dbbasicForm.readOnly). `related` renders a CHILD collection
33filtered by a foreign key back to the record the page's `detail` block is
34showing -- it is exactly a 58 filtered read (`{"kind":"list","filters":
35{fk_field: match}}`), compiled here to a plain window.dbbasicList mount
36with a `where` option (see list.py); no bespoke fetch. `thread` is sugar
37over 22's comment widget (window.dbbasicThread) for the one shape
38`related`'s single `fk_field` cannot express: `thread_comments`'
39polymorphic `parent_collection`/`parent_id` pair. All three lean on
40`$record_id`, a template token (mirroring `22`'s `$user_id` permission
41row-filter convention) that resolves at render time to the id captured by
42this view's own parameterized route -- see resolveRecordId and the
43Python GET() below for how that capture is found.
44
45**Scope boundary (per `plan/parity-completion-plan.md`'s document-
46modeling rubric):** `related` is for TRUE CHILDREN with independent
47identity and lifecycle -- interactions, comments, followers/following,
48task<->files. It is NOT for document-composition items (order/invoice
49lines): those embed as a JSON array field on the parent (a `line-items`
50block, `66-line-items-spec.md`, not this one) and have no `collection` +
51`fk_field` of their own for a `related` block to point at.
52
53Two of the block options ask more of the generators than they currently
54offer:
55 - `list`'s `filters` and `limit` have no equivalent in window.dbbasicList
56 (it always fetches its own /collections/{c}/records?limit=500 with no
57 filter hook). Blocks that set either fall back to a small client-side
58 fetch + filter + sort + slice here instead of pretending the option
59 works -- see renderFilteredList. Filter-less, limit-less list blocks
60 use the real window.dbbasicList and get its full feature set (search
61 box, live edit/delete, row styling) for free. `related` never takes
62 this path -- it always compiles to window.dbbasicList's `where` option
63 (58's real, server-side filter), never the client-side fallback.
64
65 A list block that needs a STANDING narrowing rather than a one-off
66 client-side slice says `where` instead of `filters`, and gets exactly
67 what `related` gets: cfg.where, one query param per pair, applied by
68 the server after its own permission row filter. The difference is not
69 cosmetic. `filters` drops the page into renderFilteredList, which can
70 only draw bare rows titled `title || name || id` -- fine for a
71 collection that has a title, useless for one that does not, where
72 every row reads as a raw id. `where` keeps the real generator, so the
73 schema's own list_mode/list_fields table, its filter bar, search,
74 sort, the row cap and realtime all still apply, and the operator can
75 narrow FURTHER from the filter bar (a picked value layers on top of
76 the block's `where` rather than replacing the base scope). This is
77 what an index page over one slice of a shared collection needs:
78 app-returns' returns bench is every shipment with direction=inbound,
79 which is a permanent property of that page and not a filter anybody
80 should have to re-pick. Values are literals -- `where` is deliberately
81 NOT run through $record_id resolution, because a parent-scoped child
82 list is what `related` is for and two spellings of one thing is how
83 block vocabularies rot.
84 - `form`'s optional `form` key (an alternate form name) has no
85 equivalent either -- window.dbbasicForm always renders
86 schema.forms.default. Only `record_id` is honored.
87
88The page subscribes to its own view record (dbbasicSubscribe("views", ...))
89and reloads on change, so editing a view's blocks re-renders it live --
90the same "surface changed, re-render" signal every other live list gets,
91with zero new protocol.
92"""
93
94# Page-unique layout only; shared component styling comes from /style.
95_STYLE = """
96.blocks.layout-single { display: grid; gap: var(--gap); }
97.blocks.layout-two_column { display: grid; gap: var(--gap); grid-template-columns: 1fr 1fr; }
98.blocks.layout-grid { display: grid; gap: var(--gap); grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); }
99@media (max-width: 720px) { .blocks.layout-two_column { grid-template-columns: 1fr; } }
100.viewblock { min-width: 0; }
101.viewblock-error { background: var(--panel); border: 1px solid var(--danger); color: var(--danger);
102 border-radius: var(--radius-md); padding: 0.75rem 1rem; font-size: 0.85rem; }
103.blocktitle { margin: 0 0 0.5rem; font-size: 1rem; }
104.countcard { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-md);
105 padding: 1rem; text-align: center; }
106.countcard.danger { border-color: var(--danger); color: var(--danger); }
107.countnum { font-size: 2.25rem; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; }
108.countlabel { color: var(--muted); font-size: 0.85rem; margin-top: 0.25rem; }
109/* aggregate block: a row of stat cards (sums) + an optional balance badge */
110.aggregaterow { display: flex; gap: var(--gap, 0.75rem); flex-wrap: wrap; }
111.aggregaterow .countcard { flex: 1 1 8rem; }
112/* .detailcard/.detailrow/.detaillabel/.detailvalue: global now, in /style
113 (app-theme/objects/site/style.py) -- window.dbbasicForm.readOnly (via
114 window.dbbasicDetail) can be mounted outside this page too, so those
115 rules moved out of this page-local stylesheet. */
116.markdownblock { line-height: 1.6; }
117.readertitle { margin: 0 0 0.5rem; font-size: 1.3rem; }
118.readertext p { line-height: 1.6; margin: 0 0 0.85rem; }
119.readerlinks { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius-md);
120 padding: 0.75rem 1rem 0.75rem 2rem; margin-top: 0.75rem; font-size: 0.9rem; }
121.readerlinks li { margin: 0.25rem 0; }
122"""
123
124_SCRIPT = r"""
125const esc = (s) => String(s ?? "").replace(/[&<>"']/g,
126 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
127const human = (n) => String(n || "").replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
128const el = (id) => document.getElementById(id);
129
130const KNOWN_KINDS = ["list", "form", "detail", "related", "thread", "count", "aggregate", "markdown", "reader", "object"];
131
132// "notes" -> "Note", "value_accounts" -> "Value Account". Only used for a
133// button label, so a naive de-pluralisation is fine -- a block can always
134// pass add_label to say exactly what it wants.
135function singular(collection) {
136 const words = String(collection || "record").split("_");
137 return words.map((w) => {
138 const one = w.endsWith("ies") ? w.slice(0, -3) + "y" : (w.endsWith("s") ? w.slice(0, -1) : w);
139 return one.charAt(0).toUpperCase() + one.slice(1);
140 }).join(" ");
141}
142
143function unsupportedCard(msg) {
144 return '<div class="viewblock-error">' + esc(msg || "unsupported block") + "</div>";
145}
146
147// 59's $record_id template token: a block field may hold the literal
148// string "$record_id", resolved here to RECORD_ID -- the id GET() below
149// captured from this view's own parameterized route (mirroring 22's
150// $user_id permission row-filter convention, at render time instead of
151// query time). Anything else (a literal id, e.g. an admin dashboard block
152// pinned to one record) passes through unchanged. Returns null when the
153// token can't resolve (no RECORD_ID for this render -- zero or multiple
154// route captures, or the view was reached without going through its
155// registered route) so callers can show the same visible error state
156// "target collection missing" already uses, never a runtime crash on an
157// empty filter/record id.
158function resolveRecordId(value) {
159 if (value !== "$record_id") return value || null;
160 return RECORD_ID || null;
161}
162
163function matchesFilters(record, filters) {
164 if (!filters) return true;
165 return Object.entries(filters).every(([k, v]) => String(record[k] ?? "") === String(v));
166}
167
168// Fallback for list blocks that need filters/limit -- options window.dbbasicList
169// does not expose. Fetches the collection itself, filters/sorts/slices
170// client-side, and renders plain rows styled with the shared .listrow classes.
171// What to show for one row when the block picked no fields. NEVER the id:
172// a UUID answers no question a person brings to a list, and "show me my
173// notes" rendering seven UUIDs was a real bug on a real iPad -- every
174// untitled record fell through `title || name || id` to the id. The
175// fallback walks the record for the first human-shaped string instead
176// (body, description, whatever the collection calls it), because a note
177// IS its body, and an id-shaped or date-shaped value is skipped by SHAPE
178// so this needs no per-collection knowledge.
179function rowLabel(r) {
180 const direct = r.title || r.name || r.label || r.subject;
181 if (direct) return String(direct).slice(0, 120);
182 const idish = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
183 const dateish = /^\d{4}-\d{2}-\d{2}/;
184 for (const [key, value] of Object.entries(r)) {
185 if (key === "id" || key.endsWith("_id") || key === "owner_id") continue;
186 if (typeof value !== "string" || !value.trim()) continue;
187 if (idish.test(value.trim()) || dateish.test(value.trim())) continue;
188 const text = value.trim().replace(/\s+/g, " ");
189 return text.length > 120 ? text.slice(0, 117) + "\u2026" : text;
190 }
191 return "(untitled)";
192}
193
194function renderFilteredList(block, mount) {
195 async function load() {
196 const res = await fetch("/collections/" + encodeURIComponent(block.collection) + "/records?limit=500",
197 {credentials: "same-origin", headers: {accept: "application/json"}});
198 if (!res.ok) { mount.innerHTML = unsupportedCard("could not load " + block.collection); return; }
199 const body = await res.json();
200 let list = (body.records || []).filter((r) => matchesFilters(r, block.filters));
201 list = list.slice().sort((a, b) => String(a.created_at || "").localeCompare(String(b.created_at || "")));
202 if (!(block.sort === "oldest" || block.sort === "asc")) list.reverse();
203 if (block.limit != null) list = list.slice(0, Number(block.limit) || 0);
204 mount.innerHTML = list.length
205 ? list.map((r) => '<div class="listrow"><div class="body"><div class="rowtitle">'
206 + esc(rowLabel(r)) + "</div></div></div>").join("")
207 : '<div class="state">Nothing yet.</div>';
208 }
209 (function sub() {
210 if (window.dbbasicSubscribe) window.dbbasicSubscribe(block.collection, load);
211 else setTimeout(sub, 400);
212 })();
213 load();
214}
215
216function renderList(block, mount) {
217 if (!block.collection) { mount.innerHTML = unsupportedCard("list block needs a collection"); return; }
218 const heading = block.title ? '<h3 class="blocktitle">' + esc(block.title) + "</h3>" : "";
219 mount.innerHTML = heading + '<div class="listmount"></div>';
220 const listMount = mount.querySelector(".listmount");
221 const hasFilters = block.filters && Object.keys(block.filters).length;
222 const hasLimit = block.limit != null;
223 if (hasFilters || hasLimit || !window.dbbasicList) {
224 renderFilteredList(block, listMount);
225 return;
226 }
227 const cfg = {mount: listMount};
228 // `where`: the block's standing scope, compiled to the SAME server-side
229 // filter `related` uses (one field=value param per pair, applied after the
230 // permission row filter, so it can only ever narrow what the viewer may
231 // already see). Unlike `filters` this keeps the real generator -- table
232 // mode, the schema's filter bar, search, sort, realtime -- which is what an
233 // index over one slice of a shared collection (inbound shipments) needs.
234 // The filter bar layers the operator's picks on top of this base scope.
235 if (block.where && typeof block.where === "object" && Object.keys(block.where).length) {
236 cfg.where = block.where;
237 }
238 // `search`/`sort`/`add` turn a bare list into the full working page every
239 // collection used to hand-write: a search box, a newest/oldest select, an
240 // Add button, and an inline create/edit panel. Sixteen page objects were
241 // ~55 lines of identical chrome around exactly this, which is why it now
242 // lives in the block instead of in each of them.
243 const toolbarBits = [];
244 if (block.search) toolbarBits.push('<input class="search grow" data-vsearch placeholder="Search&hellip;" autocomplete="off">');
245 if (block.sort) toolbarBits.push('<select data-vsort><option value="newest">Newest</option><option value="oldest">Oldest</option></select>');
246 if (toolbarBits.length) {
247 const bar = document.createElement("div");
248 bar.className = "toolbar";
249 bar.innerHTML = toolbarBits.join("");
250 mount.insertBefore(bar, listMount);
251 if (block.search) cfg.search = bar.querySelector("[data-vsearch]");
252 if (block.sort) cfg.sort = bar.querySelector("[data-vsort]");
253 }
254 // Owner scoping is opt-in per block rather than assumed: a private
255 // collection (notes, tasks) lists only the viewer's rows, while a shared
256 // one (forum topics) must not. The permission engine is still the actual
257 // gate -- this only decides what the page ASKS for.
258 if (block.owner_scoped && typeof VIEWER_ID !== "undefined" && VIEWER_ID) cfg.owner = VIEWER_ID;
259 if (block.add && window.dbbasicForm) {
260 const panel = document.createElement("div");
261 panel.className = "formpanel";
262 panel.style.display = "none";
263 panel.innerHTML = '<h3 class="blocktitle" data-vformtitle></h3><div data-vformmount></div>';
264 mount.insertBefore(panel, listMount);
265 const addBtn = document.createElement("button");
266 addBtn.className = "btn primary";
267 addBtn.textContent = block.add_label || ("+ New " + singular(block.collection));
268 mount.insertBefore(addBtn, panel);
269 const openForm = (record) => {
270 panel.querySelector("[data-vformtitle]").textContent =
271 (record ? "Edit " : "New ") + singular(block.collection);
272 panel.style.display = "block";
273 window.dbbasicForm(block.collection, {
274 mount: panel.querySelector("[data-vformmount]"),
275 record: record || undefined,
276 owner: (typeof VIEWER_ID !== "undefined" ? VIEWER_ID : "") || undefined,
277 onSaved: () => { panel.style.display = "none"; },
278 onCancel: () => { panel.style.display = "none"; },
279 });
280 };
281 addBtn.addEventListener("click", () => openForm(null));
282 cfg.onEdit = openForm;
283 }
284 // A collection without a `title`/`name` field (e.g. a rollup target keyed by
285 // path/ip/status) would otherwise render each row as its raw id. `title_field`
286 // / `subtitle_field` point the row label at real columns -- so an analytics
287 // rollup, or any data-shaped collection, lists meaningfully with zero JS.
288 if (block.title_field) {
289 const tf = block.title_field;
290 cfg.title = (r) => (r[tf] == null || r[tf] === "" ? "(none)" : String(r[tf]));
291 }
292 if (block.subtitle_field) {
293 const sf = block.subtitle_field;
294 const lbl = block.subtitle_label ? String(block.subtitle_label) + ": " : "";
295 // A blank value draws no line (never a bare "Pinned:"), and a boolean field
296 // reads Yes/No; list.py fills cfg.fieldTypes from the schema before rows draw.
297 cfg.subtitle = (r) => {
298 const v = r[sf];
299 if (v == null || String(v).trim() === "") return "";
300 const isBool = cfg.fieldTypes && cfg.fieldTypes[sf] === "boolean";
301 return lbl + (isBool ? (String(v) === "true" ? "Yes" : "No") : String(v));
302 };
303 }
304 // `href_template` points row titles at the collection's REAL detail page
305 // when it differs from the naive /{collection}/{id} default -- fin_journals
306 // renders at /journals/{id}, and guessing would 404. `href_field` makes the
307 // row title open the value of a field (a bookmarked URL): the row IS the
308 // link, so it opens in a new tab and never pretends to be a detail page.
309 if (block.href_template) {
310 const tpl = String(block.href_template);
311 cfg.href = (r) => tpl.replace(/\{(\w+)\}/g, (_, name) => encodeURIComponent(String(r[name] == null ? "" : r[name])));
312 } else if (block.href_field) {
313 const hf = String(block.href_field);
314 cfg.href = (r) => (r[hf] ? String(r[hf]) : "");
315 }
316 // (dbbasicList already opens any custom href in a new tab -- true of the
317 // bespoke pages these blocks replaced, so behaviour is unchanged.)
318 // `row_actions: false` -> a read-only list (a log, a report, a rollup target):
319 // no per-row edit/delete buttons, and no detail link either (a rollup target
320 // has no detail page). Normal data lists keep the owner-based actions and get
321 // the default /{collection}/{id} detail link.
322 if (block.row_actions === false) { cfg.rowActions = false; cfg.link = false; }
323 if (block.link === false) cfg.link = false;
324 // `row_limit` overrides the list's default display cap (50); `sort_by`
325 // (+ `sort_dir` asc|desc) sorts by a real field -- so a report renders as a
326 // bounded top-N (e.g. top IPs by hits, desc) instead of every row.
327 if (block.row_limit != null) cfg.limit = block.row_limit;
328 if (block.sort_by) cfg.sortBy = {field: block.sort_by, dir: (block.sort_dir === "asc" ? "asc" : "desc")};
329 if (block.sort === "oldest" || block.sort === "asc") {
330 // dbbasicList's real sort option is a bound <select> element, not a
331 // value -- synthesize a hidden one already set to "oldest" so the
332 // real option still applies instead of inventing a new one.
333 const sel = document.createElement("select");
334 sel.style.display = "none";
335 sel.innerHTML = '<option value="oldest" selected>oldest</option>';
336 mount.appendChild(sel);
337 cfg.sort = sel;
338 }
339 window.dbbasicList(block.collection, cfg);
340}
341
342function renderForm(block, mount) {
343 if (!block.collection) { mount.innerHTML = unsupportedCard("form block needs a collection"); return; }
344 if (!window.dbbasicForm) { mount.innerHTML = unsupportedCard("form generator unavailable"); return; }
345 const viewerId = (typeof VIEWER_ID !== "undefined" ? VIEWER_ID : "") || undefined;
346 // `fixed`: lock fields to a context value for parent->child compose --
347 // {"topic_id": "$record_id"} prefills+hides topic_id to the page's record.
348 // Values run through the same $record_id resolution the detail/related
349 // blocks use; the generic form renderer (opts.fixed) does the rest.
350 const fixed = {};
351 if (block.fixed && typeof block.fixed === "object") {
352 for (const k in block.fixed) {
353 const rv = resolveRecordId(block.fixed[k]);
354 if (rv) fixed[k] = rv;
355 }
356 }
357 const base = {mount: mount, owner: viewerId};
358 if (Object.keys(fixed).length) base.fixed = fixed;
359 // A compose form (no record_id) resets to empty after each save so another
360 // child can be posted; a sibling `related` block re-renders on the record
361 // event. An edit form (record_id) keeps the default post-save behavior.
362 const go = (record) => window.dbbasicForm(block.collection, Object.assign({}, base, {
363 record: record,
364 onSaved: block.record_id ? undefined : function () { go(null); },
365 }));
366 if (block.record_id) {
367 fetch("/collections/" + encodeURIComponent(block.collection) + "/records/" + encodeURIComponent(block.record_id),
368 {credentials: "same-origin", headers: {accept: "application/json"}})
369 .then((res) => (res.ok ? res.json() : null))
370 .then((body) => go(body && (body.record || body)))
371 .catch(() => go(null));
372 } else {
373 go(null);
374 }
375}
376
377// 59's detail mode: renders ONE record, read-only, composed -- not a
378// second field-renderer. This block is a thin mount wrapper; every
379// field-layout/formatting decision lives in window.dbbasicDetail (served
380// at /detail), which itself reuses /form's own pipeline
381// (window.dbbasicForm.readOnly) in forced-read-only mode.
382//
383// Owner-aware edit/delete (Stage 6): a block may declare `editable` and/or
384// `deletable` (and optionally `delete_redirect`, `owner_field`); the detail
385// generator shows Edit/Delete only when the viewer owns the record. VIEWER_ID
386// (embedded server-side above) is passed through so the generator can make
387// that owner check -- it never widens the underlying permission gate, it only
388// decides whether to render the affordances.
389function renderDetail(block, mount) {
390 if (!block.collection) { mount.innerHTML = unsupportedCard("detail block needs a collection"); return; }
391 const recordId = resolveRecordId(block.record_id);
392 if (!recordId) { mount.innerHTML = unsupportedCard("detail block needs a record_id"); return; }
393 if (!window.dbbasicDetail) { mount.innerHTML = unsupportedCard("detail generator unavailable"); return; }
394 const viewerId = (typeof VIEWER_ID !== "undefined" ? VIEWER_ID : "") || null;
395 // Detail on top, an auto-comments thread below it (see maybeMountComments).
396 mount.innerHTML = '<div class="detailmount"></div><div class="detailcomments"></div>';
397 const detailMount = mount.querySelector(".detailmount");
398 const commentsMount = mount.querySelector(".detailcomments");
399 const load = () => window.dbbasicDetail.mount(detailMount, {
400 collection: block.collection,
401 record_id: recordId,
402 // Owner-editable by DEFAULT (opt out with editable/deletable:false). The
403 // detail generator only shows Edit/Delete to the record's owner, so this is
404 // safe -- and it fixes the inconsistency where some detail views were
405 // converted with editable:true and others weren't. delete_redirect defaults
406 // to the collection index.
407 editable: block.editable !== false,
408 deletable: block.deletable !== false,
409 delete_redirect: block.delete_redirect || ("/" + block.collection),
410 owner_field: block.owner_field || null,
411 viewer_id: viewerId,
412 });
413 (function sub() {
414 if (window.dbbasicSubscribe) window.dbbasicSubscribe(block.collection, load);
415 else setTimeout(sub, 400);
416 })();
417 load();
418 maybeMountCapabilities(block.collection, recordId, commentsMount, viewerId);
419}
420
421// Capability wiring: a collection's schema declares generic behaviors under
422// `capabilities`, and the detail page mounts the matching widget automatically
423// -- no per-view block, no per-app table/FK. This is the "declare a capability,
424// the platform wires it" layer on top of the display generators. Each mounts
425// into its own sub-element under the detail; fails silent when a flag is absent
426// or a widget isn't loaded.
427async function maybeMountCapabilities(collection, recordId, mount, viewerId) {
428 if (!mount) return;
429 let schema = null;
430 try {
431 const res = await fetch("/api/schema/" + encodeURIComponent(collection),
432 {credentials: "same-origin", headers: {accept: "application/json"}});
433 if (res.ok) schema = (await res.json()).schema;
434 } catch (e) { return; }
435 const caps = (schema && schema.capabilities) || {};
436 const opts = {parent_collection: collection, parent_id: recordId, viewer_id: viewerId || ""};
437 // Sharing (owner-only, renders nothing for others), then attachments, then
438 // comments -- each in its own div so none clobbers another.
439 if (caps.shareable && window.dbbasicShare) {
440 const s = document.createElement("div"); mount.appendChild(s);
441 window.dbbasicShare.mount(s, opts);
442 }
443 if (caps.attachments && window.dbbasicAttachments) {
444 const a = document.createElement("div"); mount.appendChild(a);
445 window.dbbasicAttachments.mount(a, opts);
446 }
447 if (caps.comments && window.dbbasicThread) {
448 const t = document.createElement("div"); mount.appendChild(t);
449 window.dbbasicThread.mount(t, opts);
450 }
451}
452
453// 59's related block: a CHILD collection filtered by a foreign key back
454// to the record the page's `detail` block is showing. This compiles
455// directly to 58's filtered read -- window.dbbasicList's `where` option
456// (list.py), never the client-side renderFilteredList fallback `list`
457// itself sometimes needs -- so a related block is always the real,
458// server-side, permission-narrowed filter, one query param:
459// {fk_field: resolved match}.
460function renderRelated(block, mount) {
461 if (!block.collection || !block.fk_field) {
462 mount.innerHTML = unsupportedCard("related block needs a collection and fk_field");
463 return;
464 }
465 const match = resolveRecordId(block.match);
466 if (!match) { mount.innerHTML = unsupportedCard("related block's match did not resolve"); return; }
467 if (!window.dbbasicList) { mount.innerHTML = unsupportedCard("list generator unavailable"); return; }
468 const heading = block.title ? '<h3 class="blocktitle">' + esc(block.title) + "</h3>" : "";
469 mount.innerHTML = heading + '<div class="listmount"></div>';
470 const listMount = mount.querySelector(".listmount");
471 window.dbbasicList(block.collection, {mount: listMount, where: {[block.fk_field]: match}});
472}
473
474// 59's thread block: pure sugar over 22's comment widget for the one
475// composition shape `related`'s single fk_field cannot express
476// (thread_comments' polymorphic parent_collection/parent_id pair). 22
477// still owns every behavior behind window.dbbasicThread (moderation,
478// anon mode, realtime, markdown escaping) -- this only resolves
479// $record_id and mounts it, the same "widget any page includes and
480// mounts explicitly" shape 22's own Surfaces section documents.
481function renderThread(block, mount) {
482 if (!block.collection) { mount.innerHTML = unsupportedCard("thread block needs a collection"); return; }
483 const recordId = resolveRecordId(block.record_id);
484 if (!recordId) { mount.innerHTML = unsupportedCard("thread block needs a record_id"); return; }
485 if (!window.dbbasicThread) { mount.innerHTML = unsupportedCard("thread widget unavailable"); return; }
486 window.dbbasicThread.mount(mount, {parent_collection: block.collection, parent_id: recordId});
487}
488
489function renderCount(block, mount) {
490 if (!block.collection) { mount.innerHTML = unsupportedCard("count block needs a collection"); return; }
491 async function load() {
492 const res = await fetch("/collections/" + encodeURIComponent(block.collection) + "/records?limit=500",
493 {credentials: "same-origin", headers: {accept: "application/json"}});
494 if (!res.ok) { mount.innerHTML = unsupportedCard("could not load " + block.collection); return; }
495 const body = await res.json();
496 const n = (body.records || []).filter((r) => matchesFilters(r, block.filters)).length;
497 const warn = block.warn_over != null && n > Number(block.warn_over);
498 mount.innerHTML = '<div class="countcard' + (warn ? " danger" : "") + '"><div class="countnum">' + n
499 + '</div><div class="countlabel">' + esc(block.label || block.collection) + "</div></div>";
500 }
501 (function sub() {
502 if (window.dbbasicSubscribe) window.dbbasicSubscribe(block.collection, load);
503 else setTimeout(sub, 400);
504 })();
505 load();
506}
507
508// `aggregate` block: sum numeric fields across a set of records -- the
509// document-totals shape (a journal's debit/credit balance, an invoice's line
510// subtotal) that `related` (which only LISTS rows) and `count` (which only
511// COUNTS them) cannot express. Fetches the same 58-shaped record window a
512// `related`/`list` block does, filters to the parent by fk_field/match (like
513// `related`) or by `filters`, sums each field in `sums`, and renders a stat
514// per sum (a `_cents` field is shown in whole units, the same convention
515// /form's read-only renderer uses). `balance: [a, b]` adds a Balanced/Not
516// badge when two sums must be equal (debits == credits). Read-only + live,
517// subscribing to the source like every other block.
518function aggLabel(f) { return human(String(f).replace(/_cents$/, "")); }
519function aggValue(f, n) { return /_cents$/.test(String(f)) ? (Number(n) / 100).toFixed(2) : String(n); }
520function renderAggregate(block, mount) {
521 if (!block.collection) { mount.innerHTML = unsupportedCard("aggregate block needs a collection"); return; }
522 const sums = Array.isArray(block.sums) ? block.sums.filter((s) => typeof s === "string") : [];
523 const fk = block.fk_field;
524 const match = resolveRecordId(block.match);
525 async function load() {
526 const res = await fetch("/collections/" + encodeURIComponent(block.collection) + "/records?limit=500",
527 {credentials: "same-origin", headers: {accept: "application/json"}});
528 if (!res.ok) { mount.innerHTML = unsupportedCard("could not load " + block.collection); return; }
529 let rows = ((await res.json()).records) || [];
530 if (fk && match) rows = rows.filter((r) => r[fk] === match);
531 else if (block.filters) rows = rows.filter((r) => matchesFilters(r, block.filters));
532 const total = {};
533 for (const f of sums) total[f] = rows.reduce((a, r) => a + (Number(r[f]) || 0), 0);
534 const stats = sums.map((f) =>
535 '<div class="countcard"><div class="countnum">' + esc(aggValue(f, total[f]))
536 + '</div><div class="countlabel">' + esc(aggLabel(f)) + "</div></div>").join("");
537 let badge = "";
538 if (Array.isArray(block.balance) && block.balance.length === 2) {
539 const ok = (total[block.balance[0]] || 0) === (total[block.balance[1]] || 0);
540 badge = '<div class="countcard' + (ok ? "" : " danger") + '"><div class="countnum">' + (ok ? "✓" : "✗")
541 + '</div><div class="countlabel">' + (ok ? "Balanced" : "Not balanced") + "</div></div>";
542 }
543 const title = block.title ? '<h3 class="blocktitle">' + esc(block.title) + "</h3>" : "";
544 mount.innerHTML = title + '<div class="aggregaterow">' + (stats + badge || '<div class="state">Nothing to total.</div>') + "</div>";
545 }
546 (function sub() {
547 if (window.dbbasicSubscribe) window.dbbasicSubscribe(block.collection, load);
548 else setTimeout(sub, 400);
549 })();
550 load();
551}
552
553// Delegates to the ONE shared renderer at /markdown (window.dbbasicMarkdown,
554// see markdown.py) rather than keeping a second copy of the same escape-
555// first, safe-subset transform here. Falls back to a bare escape (never
556// raw innerHTML of untrusted block text) if a page somehow loads this
557// without /markdown -- the page wrapper always includes it (see the
558// script tags this file itself emits), but block.text is still untrusted
559// content either way, so the fallback stays safe even without the real
560// parser.
561function renderMarkdown(block, mount) {
562 const html = window.dbbasicMarkdown
563 ? window.dbbasicMarkdown(block.text)
564 : esc(block.text).replace(/\n/g, "<br>");
565 mount.innerHTML = '<div class="markdownblock">' + html + "</div>";
566}
567
568// Fetch one url through the flag-gated, signed-in-only /api/read and render
569// title + paragraphs + a numbered link list. Every failure shape (flag off,
570// signed out, SSRF-refused, non-HTML, timeout) comes back as {status:
571// "error", error} from the endpoint and renders as the same placeholder
572// card -- no separate error UI needed here.
573function renderReader(block, mount) {
574 if (!block.url) { mount.innerHTML = unsupportedCard("reader block needs a url"); return; }
575 mount.innerHTML = '<div class="state">Fetching&hellip;</div>';
576 fetch("/api/read", {
577 method: "POST",
578 credentials: "same-origin",
579 headers: {"content-type": "application/json", accept: "application/json"},
580 body: JSON.stringify({url: block.url}),
581 })
582 .then((res) => res.json().then((data) => ({ok: res.ok, data})))
583 .then(({ok, data}) => {
584 if (!ok || data.status === "error") {
585 mount.innerHTML = unsupportedCard(data.error || "could not read page");
586 return;
587 }
588 const paragraphs = String(data.text || "").split("\n\n")
589 .filter((p) => p.trim())
590 .map((p) => "<p>" + esc(p) + "</p>")
591 .join("") || '<p class="state">No readable text.</p>';
592 const links = (data.links || [])
593 .map((l) => "<li>" + esc(l.n) + ". <a href=\"" + esc(l.href)
594 + "\" target=\"_blank\" rel=\"noopener\">" + esc(l.label) + "</a></li>")
595 .join("");
596 mount.innerHTML = '<h1 class="readertitle">' + esc(data.title || block.url) + "</h1>"
597 + '<div class="readertext">' + paragraphs + "</div>"
598 + (links ? '<ol class="readerlinks">' + links + "</ol>" : "");
599 })
600 .catch(() => { mount.innerHTML = unsupportedCard("could not read page"); });
601}
602
603const RENDERERS = {list: renderList, form: renderForm, detail: renderDetail, related: renderRelated,
604 thread: renderThread, count: renderCount, aggregate: renderAggregate, markdown: renderMarkdown, reader: renderReader};
605
606// The escape hatch that keeps the generated page from being all-or-nothing.
607//
608// Every generative UI eventually meets something it cannot express, and the
609// usual answer is a cliff: the admin/scaffold works until it doesn't, then
610// you throw the whole screen away and hand-write it. Here a page is a LIST
611// of blocks, so one of them can simply be a hand-written object -- keep the
612// generated list, the generated form and the generated detail, and drop a
613// bespoke panel in the middle of them.
614//
615// The object runs through the ordinary execution path, so permissions,
616// audit, timeouts and correlation ids all still apply: this widens what a
617// page can show, never what a viewer may see.
618function renderObject(block, mount) {
619 const objectId = block.object_id;
620 if (!objectId) { mount.innerHTML = unsupportedCard("object block needs an object_id"); return; }
621 const heading = block.title ? '<h3 class="blocktitle">' + esc(block.title) + "</h3>" : "";
622 mount.innerHTML = heading + '<div class="objectmount"><div class="state">loading&hellip;</div></div>';
623 const target = mount.querySelector(".objectmount");
624 const params = new URLSearchParams(block.params && typeof block.params === "object" ? block.params : {});
625 const qs = params.toString();
626 fetch("/objects/" + encodeURIComponent(objectId) + (qs ? "?" + qs : ""), {
627 credentials: "same-origin",
628 }).then((r) => {
629 if (!r.ok) throw new Error("HTTP " + r.status);
630 return r.text();
631 }).then((body) => {
632 // Objects that return JSON (an action, a report) are shown as data
633 // rather than injected as markup -- a block that silently rendered a
634 // JSON blob as HTML would be a confusing way to find a wiring mistake.
635 const text = String(body || "");
636 if (text.trim().startsWith("{") || text.trim().startsWith("[")) {
637 target.innerHTML = "<pre>" + esc(text.slice(0, 4000)) + "</pre>";
638 } else {
639 target.innerHTML = text;
640 }
641 }).catch((err) => {
642 target.innerHTML = unsupportedCard("object " + esc(objectId) + " did not render (" + esc(String(err.message || err)) + ")");
643 });
644}
645
646function renderBlocks(view) {
647 const container = el("blocks");
648 container.className = "blocks layout-" + esc(view.layout || "single");
649 let blocks;
650 try {
651 blocks = JSON.parse(view.blocks || "[]");
652 if (!Array.isArray(blocks)) throw new Error("blocks must be a JSON array");
653 } catch (e) {
654 container.innerHTML = unsupportedCard("Invalid blocks JSON");
655 return;
656 }
657 if (!blocks.length) { container.innerHTML = '<div class="state">This view has no blocks yet.</div>'; return; }
658 container.innerHTML = "";
659 blocks.forEach((block) => {
660 const wrap = document.createElement("div");
661 wrap.className = "viewblock";
662 container.appendChild(wrap);
663 if (!block || typeof block !== "object" || KNOWN_KINDS.indexOf(block.kind) === -1) {
664 wrap.innerHTML = unsupportedCard("Unsupported block kind" + (block && block.kind ? ": " + esc(block.kind) : ""));
665 return;
666 }
667 try {
668 RENDERERS[block.kind](block, wrap);
669 } catch (e) {
670 wrap.innerHTML = unsupportedCard("Invalid block");
671 }
672 });
673}
674
675async function load() {
676 const res = await fetch("/collections/views/records/" + VIEW_ID,
677 {credentials: "same-origin", headers: {accept: "application/json"}});
678 if (!res.ok) {
679 el("blocks").innerHTML = VIEWER_ID
680 ? '<p class="hint">This view does not exist or is not shared with you.</p>'
681 : '<p class="hint"><a href="/login?next=/views/' + VIEW_ID + '">Sign in</a> to view this page.</p>';
682 return;
683 }
684 const body = await res.json();
685 const view = body.record || body;
686 document.title = view.title || "View";
687 el("viewtitle").textContent = view.title || "View";
688 renderBlocks(view);
689}
690load();
691
692// Realtime: re-render when this view record changes (edited in another
693// tab, by another user, or by an agent) -- the "surface changed" signal
694// falls out of existing realtime with zero new protocol.
695(function () {
696 let _lt = null;
697 const reload = () => { clearTimeout(_lt); _lt = setTimeout(load, 150); };
698 (function wait() {
699 if (window.dbbasicSubscribe) window.dbbasicSubscribe("views", reload);
700 else setTimeout(wait, 300);
701 })();
702})();
703"""
704
705
706import os
707import re
708
709import object_records
710import object_site_routes
711
712_RECORD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$")
713_DATA_DIR_ENV = "DBBASIC_DATA_DIR"
714
715# Request keys that are never a route capture, whatever a package's route
716# pattern happens to name its one param -- see _resolve_view_and_record.
717_RESERVED_REQUEST_KEYS = {"_identity", "embed", "view_id", "_path"}
718
719
720def _data_dir():
721 # Mirrors app-catalog's stock.py: standalone, reads the env var
722 # object_server.py sets for every execution rather than depending on
723 # it directly.
724 return os.environ.get(_DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
725
726
727def _views_records(base_dir):
728 try:
729 # access: route resolution only: reads each view's route, never returns a view; the browser fetches it through the records API
730 return object_records.read_collection_records("views", base_dir=base_dir)
731 except (LookupError, OSError, ValueError):
732 return []
733
734
735def _route_capture_name(route):
736 """Return the one {name} capture in a views.route pattern, or None.
737
738 Reuses object_site_routes' own pattern parser -- docs/site-routing.md's
739 {name}/{name:uuid} syntax, no second pattern language (59's Route-
740 Seeding). None covers "no route", "no capture" (a plain path like
741 /stuck), and "more than one capture" alike: 59 pins $record_id
742 resolution to routes with EXACTLY one capture, so none of those three
743 cases can ever supply a record id -- same degrade, no need to tell
744 them apart here.
745 """
746 if not route:
747 return None
748 parsed = object_site_routes._parse_pattern(route)
749 if not parsed:
750 return None
751 params = [name for kind, name, _constraint in parsed if kind == "param"]
752 if len(params) != 1:
753 return None
754 return params[0]
755
756
757def _resolve_view_and_record(request, base_dir):
758 """Return (view_id, record_id) for this request.
759
760 Direct case: request["view_id"] is set -- the plain
761 /views/{view_id:uuid} convention (55) a site_routes row maps straight
762 to this object. record_id still resolves the same way below (a view
763 reached this way carries no captures of its own unless the caller
764 also supplied one, e.g. hit directly with an extra query param -- rare
765 but harmless, since every read past this point is permission-gated
766 the same as any other route).
767
768 Routed-detail case (59): no "view_id" key, but package-seeded routes
769 like /contacts/{contact_id:uuid} land a DIFFERENT captured key
770 (docs/site-routing.md's request[name] convention). Resolved by
771 scanning the (small, one-row-per-collection) `views` collection for
772 the record whose own `route` field declares a single capture matching
773 one of the keys actually present -- the views record stays the single
774 source of truth for which route maps to which view; no second route
775 table, no new site_routes column.
776 """
777 view_id = str(request.get("view_id") or "").strip()
778 candidates = {
779 key: str(value).strip()
780 for key, value in request.items()
781 if key not in _RESERVED_REQUEST_KEYS
782 and isinstance(value, str)
783 and value.strip()
784 }
785
786 records = _views_records(base_dir)
787 if view_id:
788 record_id = ""
789 for record in records:
790 if record.get("id") == view_id:
791 capture = _route_capture_name(record.get("route"))
792 if capture and capture in candidates:
793 record_id = candidates[capture]
794 break
795 return view_id, record_id
796
797 for record in records:
798 capture = _route_capture_name(record.get("route"))
799 if capture and capture in candidates:
800 return str(record.get("id") or ""), candidates[capture]
801
802 # Capture-LESS route (an index/list view like /entities, whose views.route
803 # is a plain literal path with no {param}): the request carries no capture
804 # to match on, so resolve by the raw matched path against the view's own
805 # `route` field. The path (request["_path"], set by object_server for every
806 # routed object) stays the single source of truth -- no second route table.
807 path = str(request.get("_path") or "").strip()
808 if path:
809 for record in records:
810 route = record.get("route")
811 if route and _route_capture_name(route) is None and route == path:
812 return str(record.get("id") or ""), ""
813 return "", ""
814
815
816def GET(request):
817 base_dir = _data_dir()
818 view_id, record_id = _resolve_view_and_record(request, base_dir)
819 if view_id and not _RECORD_ID_RE.fullmatch(view_id):
820 view_id = ""
821 record_id = ""
822 if record_id and not _RECORD_ID_RE.fullmatch(record_id):
823 record_id = ""
824 identity = request.get("_identity", {})
825 user_id = identity.get("user_id")
826 _logger.info("site_view_render served", view_id=view_id or "missing",
827 record_id=record_id or "none", user_id=user_id or "anonymous")
828
829 if not view_id:
830 return {
831 "content_type": "text/html; charset=utf-8",
832 "body": "<p>View not found.</p>",
833 "status": 404,
834 }
835
836 who = (
837 f"signed in as <strong>{user_id}</strong>"
838 if user_id
839 else f'<a href="/login?next=/views/{view_id}">sign in</a>'
840 )
841 # ?embed=1: chromeless rendition for stages/iframes (Talk, shell embeds,
842 # someday in-world screens) -- same page, no app bar, no who-row.
843 embed = str(request.get("embed") or "").strip() not in ("", "0", "false")
844 header_html = (
845 f'<header class="app"><h1 id="viewtitle">Loading&hellip;</h1>'
846 f'<div class="who">{who}</div></header>'
847 if not embed
848 else '<h1 id="viewtitle" class="embed-title">Loading&hellip;</h1>'
849 )
850 nav_html = "" if embed else '<script src="/nav"></script>'
851 html = f"""<!doctype html>
852<html lang="en">
853<head>
854<meta charset="utf-8">
855<meta name="viewport" content="width=device-width, initial-scale=1">
856<title>View</title>
857<link rel="stylesheet" href="/style">
858<style>{_STYLE}</style>
859</head>
860<body>
861<div class="wrap">
862{header_html}
863<div class="blocks" id="blocks"><div class="state">loading&hellip;</div></div>
864</div>
865<script src="/markdown"></script>
866<script src="/list"></script>
867<script src="/form"></script>
868<script src="/detail"></script>
869<script src="/thread"></script>
870<script src="/attachments"></script>
871<script src="/share"></script>
872<script>const VIEW_ID = {view_id!r}; const VIEWER_ID = {(user_id or "")!r}; const RECORD_ID = {record_id!r};{_SCRIPT}</script>
873{nav_html}
874</body>
875</html>"""
876 return {"content_type": "text/html; charset=utf-8", "body": html}