askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
view_render.py · 43.1 KB · 868 lines
| 1 | """The universal view renderer: one object that draws any `views` record. |
| 2 | |
| 3 | Served through a site route like /views/{view_id:uuid}. The browser fetches |
| 4 | the view record with the visitor's own session cookie, so the permission |
| 5 | policy decides visibility (owner + is_public, same as every other record) -- |
| 6 | the renderer adds no data path of its own. Each block then re-fetches its |
| 7 | own data the same way, so a public view over a private collection renders |
| 8 | its frame plus an empty/denied block for anonymous visitors: it can never |
| 9 | show what the engine would not otherwise serve. |
| 10 | |
| 11 | Blocks are DATA, not code: a closed v1 vocabulary of eight kinds -- |
| 12 | list, form, detail, related, thread, count, markdown, reader -- read from |
| 13 | the record's `blocks` JSON and rendered through the existing generators |
| 14 | (window.dbbasicList, window.dbbasicForm, window.dbbasicDetail, |
| 15 | window.dbbasicThread) or small renderers here. An unknown kind, a |
| 16 | malformed block, or invalid blocks JSON never becomes a blank page or raw |
| 17 | markup: it becomes a visible placeholder card, and the rest of the view |
| 18 | still renders. |
| 19 | |
| 20 | `reader` ({kind:'reader', url}) is client-side like every other block |
| 21 | here: it POSTs the url to /api/read (object_server's flag-gated, |
| 22 | signed-in-only fetch -- see DBBASIC_ENABLE_READER and object_reader's SSRF |
| 23 | gate) and renders the stripped title/text/links it gets back. A disabled |
| 24 | flag, a signed-out visitor, or a refused/failed fetch all come back as a |
| 25 | normal JSON error body, which renders as the same placeholder card as any |
| 26 | other broken block -- no separate error path needed here. |
| 27 | |
| 28 | `detail` (`59-detail-related-spec.md`) renders ONE record, read-only, |
| 29 | composed -- it does not re-derive field layout itself, it mounts |
| 30 | window.dbbasicDetail (served at /detail), which in turn reuses /form's |
| 31 | own field-rendering pipeline in forced-read-only mode |
| 32 | (window.dbbasicForm.readOnly). `related` renders a CHILD collection |
| 33 | filtered by a foreign key back to the record the page's `detail` block is |
| 34 | showing -- it is exactly a 58 filtered read (`{"kind":"list","filters": |
| 35 | {fk_field: match}}`), compiled here to a plain window.dbbasicList mount |
| 36 | with a `where` option (see list.py); no bespoke fetch. `thread` is sugar |
| 37 | over 22's comment widget (window.dbbasicThread) for the one shape |
| 38 | `related`'s single `fk_field` cannot express: `thread_comments`' |
| 39 | polymorphic `parent_collection`/`parent_id` pair. All three lean on |
| 40 | `$record_id`, a template token (mirroring `22`'s `$user_id` permission |
| 41 | row-filter convention) that resolves at render time to the id captured by |
| 42 | this view's own parameterized route -- see resolveRecordId and the |
| 43 | Python GET() below for how that capture is found. |
| 44 | |
| 45 | **Scope boundary (per `plan/parity-completion-plan.md`'s document- |
| 46 | modeling rubric):** `related` is for TRUE CHILDREN with independent |
| 47 | identity and lifecycle -- interactions, comments, followers/following, |
| 48 | task<->files. It is NOT for document-composition items (order/invoice |
| 49 | lines): those embed as a JSON array field on the parent (a `line-items` |
| 50 | block, `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 | |
| 53 | Two of the block options ask more of the generators than they currently |
| 54 | offer: |
| 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 | |
| 88 | The page subscribes to its own view record (dbbasicSubscribe("views", ...)) |
| 89 | and reloads on change, so editing a view's blocks re-renders it live -- |
| 90 | the same "surface changed, re-render" signal every other live list gets, |
| 91 | with 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""" |
| 125 | const esc = (s) => String(s ?? "").replace(/[&<>"']/g, |
| 126 | (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); |
| 127 | const human = (n) => String(n || "").replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()); |
| 128 | const el = (id) => document.getElementById(id); |
| 129 | |
| 130 | const 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. |
| 135 | function 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 | |
| 143 | function 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. |
| 158 | function resolveRecordId(value) { |
| 159 | if (value !== "$record_id") return value || null; |
| 160 | return RECORD_ID || null; |
| 161 | } |
| 162 | |
| 163 | function 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. |
| 179 | function 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 | |
| 194 | function 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 | |
| 216 | function 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…" 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 | cfg.subtitle = (r) => (r[sf] == null ? "" : lbl + String(r[sf])); |
| 296 | } |
| 297 | // `href_template` points row titles at the collection's REAL detail page |
| 298 | // when it differs from the naive /{collection}/{id} default -- fin_journals |
| 299 | // renders at /journals/{id}, and guessing would 404. `href_field` makes the |
| 300 | // row title open the value of a field (a bookmarked URL): the row IS the |
| 301 | // link, so it opens in a new tab and never pretends to be a detail page. |
| 302 | if (block.href_template) { |
| 303 | const tpl = String(block.href_template); |
| 304 | cfg.href = (r) => tpl.replace(/\{(\w+)\}/g, (_, name) => encodeURIComponent(String(r[name] == null ? "" : r[name]))); |
| 305 | } else if (block.href_field) { |
| 306 | const hf = String(block.href_field); |
| 307 | cfg.href = (r) => (r[hf] ? String(r[hf]) : ""); |
| 308 | } |
| 309 | // (dbbasicList already opens any custom href in a new tab -- true of the |
| 310 | // bespoke pages these blocks replaced, so behaviour is unchanged.) |
| 311 | // `row_actions: false` -> a read-only list (a log, a report, a rollup target): |
| 312 | // no per-row edit/delete buttons, and no detail link either (a rollup target |
| 313 | // has no detail page). Normal data lists keep the owner-based actions and get |
| 314 | // the default /{collection}/{id} detail link. |
| 315 | if (block.row_actions === false) { cfg.rowActions = false; cfg.link = false; } |
| 316 | if (block.link === false) cfg.link = false; |
| 317 | // `row_limit` overrides the list's default display cap (50); `sort_by` |
| 318 | // (+ `sort_dir` asc|desc) sorts by a real field -- so a report renders as a |
| 319 | // bounded top-N (e.g. top IPs by hits, desc) instead of every row. |
| 320 | if (block.row_limit != null) cfg.limit = block.row_limit; |
| 321 | if (block.sort_by) cfg.sortBy = {field: block.sort_by, dir: (block.sort_dir === "asc" ? "asc" : "desc")}; |
| 322 | if (block.sort === "oldest" || block.sort === "asc") { |
| 323 | // dbbasicList's real sort option is a bound <select> element, not a |
| 324 | // value -- synthesize a hidden one already set to "oldest" so the |
| 325 | // real option still applies instead of inventing a new one. |
| 326 | const sel = document.createElement("select"); |
| 327 | sel.style.display = "none"; |
| 328 | sel.innerHTML = '<option value="oldest" selected>oldest</option>'; |
| 329 | mount.appendChild(sel); |
| 330 | cfg.sort = sel; |
| 331 | } |
| 332 | window.dbbasicList(block.collection, cfg); |
| 333 | } |
| 334 | |
| 335 | function renderForm(block, mount) { |
| 336 | if (!block.collection) { mount.innerHTML = unsupportedCard("form block needs a collection"); return; } |
| 337 | if (!window.dbbasicForm) { mount.innerHTML = unsupportedCard("form generator unavailable"); return; } |
| 338 | const viewerId = (typeof VIEWER_ID !== "undefined" ? VIEWER_ID : "") || undefined; |
| 339 | // `fixed`: lock fields to a context value for parent->child compose -- |
| 340 | // {"topic_id": "$record_id"} prefills+hides topic_id to the page's record. |
| 341 | // Values run through the same $record_id resolution the detail/related |
| 342 | // blocks use; the generic form renderer (opts.fixed) does the rest. |
| 343 | const fixed = {}; |
| 344 | if (block.fixed && typeof block.fixed === "object") { |
| 345 | for (const k in block.fixed) { |
| 346 | const rv = resolveRecordId(block.fixed[k]); |
| 347 | if (rv) fixed[k] = rv; |
| 348 | } |
| 349 | } |
| 350 | const base = {mount: mount, owner: viewerId}; |
| 351 | if (Object.keys(fixed).length) base.fixed = fixed; |
| 352 | // A compose form (no record_id) resets to empty after each save so another |
| 353 | // child can be posted; a sibling `related` block re-renders on the record |
| 354 | // event. An edit form (record_id) keeps the default post-save behavior. |
| 355 | const go = (record) => window.dbbasicForm(block.collection, Object.assign({}, base, { |
| 356 | record: record, |
| 357 | onSaved: block.record_id ? undefined : function () { go(null); }, |
| 358 | })); |
| 359 | if (block.record_id) { |
| 360 | fetch("/collections/" + encodeURIComponent(block.collection) + "/records/" + encodeURIComponent(block.record_id), |
| 361 | {credentials: "same-origin", headers: {accept: "application/json"}}) |
| 362 | .then((res) => (res.ok ? res.json() : null)) |
| 363 | .then((body) => go(body && (body.record || body))) |
| 364 | .catch(() => go(null)); |
| 365 | } else { |
| 366 | go(null); |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | // 59's detail mode: renders ONE record, read-only, composed -- not a |
| 371 | // second field-renderer. This block is a thin mount wrapper; every |
| 372 | // field-layout/formatting decision lives in window.dbbasicDetail (served |
| 373 | // at /detail), which itself reuses /form's own pipeline |
| 374 | // (window.dbbasicForm.readOnly) in forced-read-only mode. |
| 375 | // |
| 376 | // Owner-aware edit/delete (Stage 6): a block may declare `editable` and/or |
| 377 | // `deletable` (and optionally `delete_redirect`, `owner_field`); the detail |
| 378 | // generator shows Edit/Delete only when the viewer owns the record. VIEWER_ID |
| 379 | // (embedded server-side above) is passed through so the generator can make |
| 380 | // that owner check -- it never widens the underlying permission gate, it only |
| 381 | // decides whether to render the affordances. |
| 382 | function renderDetail(block, mount) { |
| 383 | if (!block.collection) { mount.innerHTML = unsupportedCard("detail block needs a collection"); return; } |
| 384 | const recordId = resolveRecordId(block.record_id); |
| 385 | if (!recordId) { mount.innerHTML = unsupportedCard("detail block needs a record_id"); return; } |
| 386 | if (!window.dbbasicDetail) { mount.innerHTML = unsupportedCard("detail generator unavailable"); return; } |
| 387 | const viewerId = (typeof VIEWER_ID !== "undefined" ? VIEWER_ID : "") || null; |
| 388 | // Detail on top, an auto-comments thread below it (see maybeMountComments). |
| 389 | mount.innerHTML = '<div class="detailmount"></div><div class="detailcomments"></div>'; |
| 390 | const detailMount = mount.querySelector(".detailmount"); |
| 391 | const commentsMount = mount.querySelector(".detailcomments"); |
| 392 | const load = () => window.dbbasicDetail.mount(detailMount, { |
| 393 | collection: block.collection, |
| 394 | record_id: recordId, |
| 395 | // Owner-editable by DEFAULT (opt out with editable/deletable:false). The |
| 396 | // detail generator only shows Edit/Delete to the record's owner, so this is |
| 397 | // safe -- and it fixes the inconsistency where some detail views were |
| 398 | // converted with editable:true and others weren't. delete_redirect defaults |
| 399 | // to the collection index. |
| 400 | editable: block.editable !== false, |
| 401 | deletable: block.deletable !== false, |
| 402 | delete_redirect: block.delete_redirect || ("/" + block.collection), |
| 403 | owner_field: block.owner_field || null, |
| 404 | viewer_id: viewerId, |
| 405 | }); |
| 406 | (function sub() { |
| 407 | if (window.dbbasicSubscribe) window.dbbasicSubscribe(block.collection, load); |
| 408 | else setTimeout(sub, 400); |
| 409 | })(); |
| 410 | load(); |
| 411 | maybeMountCapabilities(block.collection, recordId, commentsMount, viewerId); |
| 412 | } |
| 413 | |
| 414 | // Capability wiring: a collection's schema declares generic behaviors under |
| 415 | // `capabilities`, and the detail page mounts the matching widget automatically |
| 416 | // -- no per-view block, no per-app table/FK. This is the "declare a capability, |
| 417 | // the platform wires it" layer on top of the display generators. Each mounts |
| 418 | // into its own sub-element under the detail; fails silent when a flag is absent |
| 419 | // or a widget isn't loaded. |
| 420 | async function maybeMountCapabilities(collection, recordId, mount, viewerId) { |
| 421 | if (!mount) return; |
| 422 | let schema = null; |
| 423 | try { |
| 424 | const res = await fetch("/api/schema/" + encodeURIComponent(collection), |
| 425 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 426 | if (res.ok) schema = (await res.json()).schema; |
| 427 | } catch (e) { return; } |
| 428 | const caps = (schema && schema.capabilities) || {}; |
| 429 | const opts = {parent_collection: collection, parent_id: recordId, viewer_id: viewerId || ""}; |
| 430 | // Sharing (owner-only, renders nothing for others), then attachments, then |
| 431 | // comments -- each in its own div so none clobbers another. |
| 432 | if (caps.shareable && window.dbbasicShare) { |
| 433 | const s = document.createElement("div"); mount.appendChild(s); |
| 434 | window.dbbasicShare.mount(s, opts); |
| 435 | } |
| 436 | if (caps.attachments && window.dbbasicAttachments) { |
| 437 | const a = document.createElement("div"); mount.appendChild(a); |
| 438 | window.dbbasicAttachments.mount(a, opts); |
| 439 | } |
| 440 | if (caps.comments && window.dbbasicThread) { |
| 441 | const t = document.createElement("div"); mount.appendChild(t); |
| 442 | window.dbbasicThread.mount(t, opts); |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | // 59's related block: a CHILD collection filtered by a foreign key back |
| 447 | // to the record the page's `detail` block is showing. This compiles |
| 448 | // directly to 58's filtered read -- window.dbbasicList's `where` option |
| 449 | // (list.py), never the client-side renderFilteredList fallback `list` |
| 450 | // itself sometimes needs -- so a related block is always the real, |
| 451 | // server-side, permission-narrowed filter, one query param: |
| 452 | // {fk_field: resolved match}. |
| 453 | function renderRelated(block, mount) { |
| 454 | if (!block.collection || !block.fk_field) { |
| 455 | mount.innerHTML = unsupportedCard("related block needs a collection and fk_field"); |
| 456 | return; |
| 457 | } |
| 458 | const match = resolveRecordId(block.match); |
| 459 | if (!match) { mount.innerHTML = unsupportedCard("related block's match did not resolve"); return; } |
| 460 | if (!window.dbbasicList) { mount.innerHTML = unsupportedCard("list generator unavailable"); return; } |
| 461 | const heading = block.title ? '<h3 class="blocktitle">' + esc(block.title) + "</h3>" : ""; |
| 462 | mount.innerHTML = heading + '<div class="listmount"></div>'; |
| 463 | const listMount = mount.querySelector(".listmount"); |
| 464 | window.dbbasicList(block.collection, {mount: listMount, where: {[block.fk_field]: match}}); |
| 465 | } |
| 466 | |
| 467 | // 59's thread block: pure sugar over 22's comment widget for the one |
| 468 | // composition shape `related`'s single fk_field cannot express |
| 469 | // (thread_comments' polymorphic parent_collection/parent_id pair). 22 |
| 470 | // still owns every behavior behind window.dbbasicThread (moderation, |
| 471 | // anon mode, realtime, markdown escaping) -- this only resolves |
| 472 | // $record_id and mounts it, the same "widget any page includes and |
| 473 | // mounts explicitly" shape 22's own Surfaces section documents. |
| 474 | function renderThread(block, mount) { |
| 475 | if (!block.collection) { mount.innerHTML = unsupportedCard("thread block needs a collection"); return; } |
| 476 | const recordId = resolveRecordId(block.record_id); |
| 477 | if (!recordId) { mount.innerHTML = unsupportedCard("thread block needs a record_id"); return; } |
| 478 | if (!window.dbbasicThread) { mount.innerHTML = unsupportedCard("thread widget unavailable"); return; } |
| 479 | window.dbbasicThread.mount(mount, {parent_collection: block.collection, parent_id: recordId}); |
| 480 | } |
| 481 | |
| 482 | function renderCount(block, mount) { |
| 483 | if (!block.collection) { mount.innerHTML = unsupportedCard("count block needs a collection"); return; } |
| 484 | async function load() { |
| 485 | const res = await fetch("/collections/" + encodeURIComponent(block.collection) + "/records?limit=500", |
| 486 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 487 | if (!res.ok) { mount.innerHTML = unsupportedCard("could not load " + block.collection); return; } |
| 488 | const body = await res.json(); |
| 489 | const n = (body.records || []).filter((r) => matchesFilters(r, block.filters)).length; |
| 490 | const warn = block.warn_over != null && n > Number(block.warn_over); |
| 491 | mount.innerHTML = '<div class="countcard' + (warn ? " danger" : "") + '"><div class="countnum">' + n |
| 492 | + '</div><div class="countlabel">' + esc(block.label || block.collection) + "</div></div>"; |
| 493 | } |
| 494 | (function sub() { |
| 495 | if (window.dbbasicSubscribe) window.dbbasicSubscribe(block.collection, load); |
| 496 | else setTimeout(sub, 400); |
| 497 | })(); |
| 498 | load(); |
| 499 | } |
| 500 | |
| 501 | // `aggregate` block: sum numeric fields across a set of records -- the |
| 502 | // document-totals shape (a journal's debit/credit balance, an invoice's line |
| 503 | // subtotal) that `related` (which only LISTS rows) and `count` (which only |
| 504 | // COUNTS them) cannot express. Fetches the same 58-shaped record window a |
| 505 | // `related`/`list` block does, filters to the parent by fk_field/match (like |
| 506 | // `related`) or by `filters`, sums each field in `sums`, and renders a stat |
| 507 | // per sum (a `_cents` field is shown in whole units, the same convention |
| 508 | // /form's read-only renderer uses). `balance: [a, b]` adds a Balanced/Not |
| 509 | // badge when two sums must be equal (debits == credits). Read-only + live, |
| 510 | // subscribing to the source like every other block. |
| 511 | function aggLabel(f) { return human(String(f).replace(/_cents$/, "")); } |
| 512 | function aggValue(f, n) { return /_cents$/.test(String(f)) ? (Number(n) / 100).toFixed(2) : String(n); } |
| 513 | function renderAggregate(block, mount) { |
| 514 | if (!block.collection) { mount.innerHTML = unsupportedCard("aggregate block needs a collection"); return; } |
| 515 | const sums = Array.isArray(block.sums) ? block.sums.filter((s) => typeof s === "string") : []; |
| 516 | const fk = block.fk_field; |
| 517 | const match = resolveRecordId(block.match); |
| 518 | async function load() { |
| 519 | const res = await fetch("/collections/" + encodeURIComponent(block.collection) + "/records?limit=500", |
| 520 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 521 | if (!res.ok) { mount.innerHTML = unsupportedCard("could not load " + block.collection); return; } |
| 522 | let rows = ((await res.json()).records) || []; |
| 523 | if (fk && match) rows = rows.filter((r) => r[fk] === match); |
| 524 | else if (block.filters) rows = rows.filter((r) => matchesFilters(r, block.filters)); |
| 525 | const total = {}; |
| 526 | for (const f of sums) total[f] = rows.reduce((a, r) => a + (Number(r[f]) || 0), 0); |
| 527 | const stats = sums.map((f) => |
| 528 | '<div class="countcard"><div class="countnum">' + esc(aggValue(f, total[f])) |
| 529 | + '</div><div class="countlabel">' + esc(aggLabel(f)) + "</div></div>").join(""); |
| 530 | let badge = ""; |
| 531 | if (Array.isArray(block.balance) && block.balance.length === 2) { |
| 532 | const ok = (total[block.balance[0]] || 0) === (total[block.balance[1]] || 0); |
| 533 | badge = '<div class="countcard' + (ok ? "" : " danger") + '"><div class="countnum">' + (ok ? "✓" : "✗") |
| 534 | + '</div><div class="countlabel">' + (ok ? "Balanced" : "Not balanced") + "</div></div>"; |
| 535 | } |
| 536 | const title = block.title ? '<h3 class="blocktitle">' + esc(block.title) + "</h3>" : ""; |
| 537 | mount.innerHTML = title + '<div class="aggregaterow">' + (stats + badge || '<div class="state">Nothing to total.</div>') + "</div>"; |
| 538 | } |
| 539 | (function sub() { |
| 540 | if (window.dbbasicSubscribe) window.dbbasicSubscribe(block.collection, load); |
| 541 | else setTimeout(sub, 400); |
| 542 | })(); |
| 543 | load(); |
| 544 | } |
| 545 | |
| 546 | // Delegates to the ONE shared renderer at /markdown (window.dbbasicMarkdown, |
| 547 | // see markdown.py) rather than keeping a second copy of the same escape- |
| 548 | // first, safe-subset transform here. Falls back to a bare escape (never |
| 549 | // raw innerHTML of untrusted block text) if a page somehow loads this |
| 550 | // without /markdown -- the page wrapper always includes it (see the |
| 551 | // script tags this file itself emits), but block.text is still untrusted |
| 552 | // content either way, so the fallback stays safe even without the real |
| 553 | // parser. |
| 554 | function renderMarkdown(block, mount) { |
| 555 | const html = window.dbbasicMarkdown |
| 556 | ? window.dbbasicMarkdown(block.text) |
| 557 | : esc(block.text).replace(/\n/g, "<br>"); |
| 558 | mount.innerHTML = '<div class="markdownblock">' + html + "</div>"; |
| 559 | } |
| 560 | |
| 561 | // Fetch one url through the flag-gated, signed-in-only /api/read and render |
| 562 | // title + paragraphs + a numbered link list. Every failure shape (flag off, |
| 563 | // signed out, SSRF-refused, non-HTML, timeout) comes back as {status: |
| 564 | // "error", error} from the endpoint and renders as the same placeholder |
| 565 | // card -- no separate error UI needed here. |
| 566 | function renderReader(block, mount) { |
| 567 | if (!block.url) { mount.innerHTML = unsupportedCard("reader block needs a url"); return; } |
| 568 | mount.innerHTML = '<div class="state">Fetching…</div>'; |
| 569 | fetch("/api/read", { |
| 570 | method: "POST", |
| 571 | credentials: "same-origin", |
| 572 | headers: {"content-type": "application/json", accept: "application/json"}, |
| 573 | body: JSON.stringify({url: block.url}), |
| 574 | }) |
| 575 | .then((res) => res.json().then((data) => ({ok: res.ok, data}))) |
| 576 | .then(({ok, data}) => { |
| 577 | if (!ok || data.status === "error") { |
| 578 | mount.innerHTML = unsupportedCard(data.error || "could not read page"); |
| 579 | return; |
| 580 | } |
| 581 | const paragraphs = String(data.text || "").split("\n\n") |
| 582 | .filter((p) => p.trim()) |
| 583 | .map((p) => "<p>" + esc(p) + "</p>") |
| 584 | .join("") || '<p class="state">No readable text.</p>'; |
| 585 | const links = (data.links || []) |
| 586 | .map((l) => "<li>" + esc(l.n) + ". <a href=\"" + esc(l.href) |
| 587 | + "\" target=\"_blank\" rel=\"noopener\">" + esc(l.label) + "</a></li>") |
| 588 | .join(""); |
| 589 | mount.innerHTML = '<h1 class="readertitle">' + esc(data.title || block.url) + "</h1>" |
| 590 | + '<div class="readertext">' + paragraphs + "</div>" |
| 591 | + (links ? '<ol class="readerlinks">' + links + "</ol>" : ""); |
| 592 | }) |
| 593 | .catch(() => { mount.innerHTML = unsupportedCard("could not read page"); }); |
| 594 | } |
| 595 | |
| 596 | const RENDERERS = {list: renderList, form: renderForm, detail: renderDetail, related: renderRelated, |
| 597 | thread: renderThread, count: renderCount, aggregate: renderAggregate, markdown: renderMarkdown, reader: renderReader}; |
| 598 | |
| 599 | // The escape hatch that keeps the generated page from being all-or-nothing. |
| 600 | // |
| 601 | // Every generative UI eventually meets something it cannot express, and the |
| 602 | // usual answer is a cliff: the admin/scaffold works until it doesn't, then |
| 603 | // you throw the whole screen away and hand-write it. Here a page is a LIST |
| 604 | // of blocks, so one of them can simply be a hand-written object -- keep the |
| 605 | // generated list, the generated form and the generated detail, and drop a |
| 606 | // bespoke panel in the middle of them. |
| 607 | // |
| 608 | // The object runs through the ordinary execution path, so permissions, |
| 609 | // audit, timeouts and correlation ids all still apply: this widens what a |
| 610 | // page can show, never what a viewer may see. |
| 611 | function renderObject(block, mount) { |
| 612 | const objectId = block.object_id; |
| 613 | if (!objectId) { mount.innerHTML = unsupportedCard("object block needs an object_id"); return; } |
| 614 | const heading = block.title ? '<h3 class="blocktitle">' + esc(block.title) + "</h3>" : ""; |
| 615 | mount.innerHTML = heading + '<div class="objectmount"><div class="state">loading…</div></div>'; |
| 616 | const target = mount.querySelector(".objectmount"); |
| 617 | const params = new URLSearchParams(block.params && typeof block.params === "object" ? block.params : {}); |
| 618 | const qs = params.toString(); |
| 619 | fetch("/objects/" + encodeURIComponent(objectId) + (qs ? "?" + qs : ""), { |
| 620 | credentials: "same-origin", |
| 621 | }).then((r) => { |
| 622 | if (!r.ok) throw new Error("HTTP " + r.status); |
| 623 | return r.text(); |
| 624 | }).then((body) => { |
| 625 | // Objects that return JSON (an action, a report) are shown as data |
| 626 | // rather than injected as markup -- a block that silently rendered a |
| 627 | // JSON blob as HTML would be a confusing way to find a wiring mistake. |
| 628 | const text = String(body || ""); |
| 629 | if (text.trim().startsWith("{") || text.trim().startsWith("[")) { |
| 630 | target.innerHTML = "<pre>" + esc(text.slice(0, 4000)) + "</pre>"; |
| 631 | } else { |
| 632 | target.innerHTML = text; |
| 633 | } |
| 634 | }).catch((err) => { |
| 635 | target.innerHTML = unsupportedCard("object " + esc(objectId) + " did not render (" + esc(String(err.message || err)) + ")"); |
| 636 | }); |
| 637 | } |
| 638 | |
| 639 | function renderBlocks(view) { |
| 640 | const container = el("blocks"); |
| 641 | container.className = "blocks layout-" + esc(view.layout || "single"); |
| 642 | let blocks; |
| 643 | try { |
| 644 | blocks = JSON.parse(view.blocks || "[]"); |
| 645 | if (!Array.isArray(blocks)) throw new Error("blocks must be a JSON array"); |
| 646 | } catch (e) { |
| 647 | container.innerHTML = unsupportedCard("Invalid blocks JSON"); |
| 648 | return; |
| 649 | } |
| 650 | if (!blocks.length) { container.innerHTML = '<div class="state">This view has no blocks yet.</div>'; return; } |
| 651 | container.innerHTML = ""; |
| 652 | blocks.forEach((block) => { |
| 653 | const wrap = document.createElement("div"); |
| 654 | wrap.className = "viewblock"; |
| 655 | container.appendChild(wrap); |
| 656 | if (!block || typeof block !== "object" || KNOWN_KINDS.indexOf(block.kind) === -1) { |
| 657 | wrap.innerHTML = unsupportedCard("Unsupported block kind" + (block && block.kind ? ": " + esc(block.kind) : "")); |
| 658 | return; |
| 659 | } |
| 660 | try { |
| 661 | RENDERERS[block.kind](block, wrap); |
| 662 | } catch (e) { |
| 663 | wrap.innerHTML = unsupportedCard("Invalid block"); |
| 664 | } |
| 665 | }); |
| 666 | } |
| 667 | |
| 668 | async function load() { |
| 669 | const res = await fetch("/collections/views/records/" + VIEW_ID, |
| 670 | {credentials: "same-origin", headers: {accept: "application/json"}}); |
| 671 | if (!res.ok) { |
| 672 | el("blocks").innerHTML = VIEWER_ID |
| 673 | ? '<p class="hint">This view does not exist or is not shared with you.</p>' |
| 674 | : '<p class="hint"><a href="/login?next=/views/' + VIEW_ID + '">Sign in</a> to view this page.</p>'; |
| 675 | return; |
| 676 | } |
| 677 | const body = await res.json(); |
| 678 | const view = body.record || body; |
| 679 | document.title = view.title || "View"; |
| 680 | el("viewtitle").textContent = view.title || "View"; |
| 681 | renderBlocks(view); |
| 682 | } |
| 683 | load(); |
| 684 | |
| 685 | // Realtime: re-render when this view record changes (edited in another |
| 686 | // tab, by another user, or by an agent) -- the "surface changed" signal |
| 687 | // falls out of existing realtime with zero new protocol. |
| 688 | (function () { |
| 689 | let _lt = null; |
| 690 | const reload = () => { clearTimeout(_lt); _lt = setTimeout(load, 150); }; |
| 691 | (function wait() { |
| 692 | if (window.dbbasicSubscribe) window.dbbasicSubscribe("views", reload); |
| 693 | else setTimeout(wait, 300); |
| 694 | })(); |
| 695 | })(); |
| 696 | """ |
| 697 | |
| 698 | |
| 699 | import os |
| 700 | import re |
| 701 | |
| 702 | import object_records |
| 703 | import object_site_routes |
| 704 | |
| 705 | _RECORD_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$") |
| 706 | _DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 707 | |
| 708 | # Request keys that are never a route capture, whatever a package's route |
| 709 | # pattern happens to name its one param -- see _resolve_view_and_record. |
| 710 | _RESERVED_REQUEST_KEYS = {"_identity", "embed", "view_id", "_path"} |
| 711 | |
| 712 | |
| 713 | def _data_dir(): |
| 714 | # Mirrors app-catalog's stock.py: standalone, reads the env var |
| 715 | # object_server.py sets for every execution rather than depending on |
| 716 | # it directly. |
| 717 | return os.environ.get(_DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR) |
| 718 | |
| 719 | |
| 720 | def _views_records(base_dir): |
| 721 | try: |
| 722 | return object_records.read_collection_records("views", base_dir=base_dir) |
| 723 | except (LookupError, OSError, ValueError): |
| 724 | return [] |
| 725 | |
| 726 | |
| 727 | def _route_capture_name(route): |
| 728 | """Return the one {name} capture in a views.route pattern, or None. |
| 729 | |
| 730 | Reuses object_site_routes' own pattern parser -- docs/site-routing.md's |
| 731 | {name}/{name:uuid} syntax, no second pattern language (59's Route- |
| 732 | Seeding). None covers "no route", "no capture" (a plain path like |
| 733 | /stuck), and "more than one capture" alike: 59 pins $record_id |
| 734 | resolution to routes with EXACTLY one capture, so none of those three |
| 735 | cases can ever supply a record id -- same degrade, no need to tell |
| 736 | them apart here. |
| 737 | """ |
| 738 | if not route: |
| 739 | return None |
| 740 | parsed = object_site_routes._parse_pattern(route) |
| 741 | if not parsed: |
| 742 | return None |
| 743 | params = [name for kind, name, _constraint in parsed if kind == "param"] |
| 744 | if len(params) != 1: |
| 745 | return None |
| 746 | return params[0] |
| 747 | |
| 748 | |
| 749 | def _resolve_view_and_record(request, base_dir): |
| 750 | """Return (view_id, record_id) for this request. |
| 751 | |
| 752 | Direct case: request["view_id"] is set -- the plain |
| 753 | /views/{view_id:uuid} convention (55) a site_routes row maps straight |
| 754 | to this object. record_id still resolves the same way below (a view |
| 755 | reached this way carries no captures of its own unless the caller |
| 756 | also supplied one, e.g. hit directly with an extra query param -- rare |
| 757 | but harmless, since every read past this point is permission-gated |
| 758 | the same as any other route). |
| 759 | |
| 760 | Routed-detail case (59): no "view_id" key, but package-seeded routes |
| 761 | like /contacts/{contact_id:uuid} land a DIFFERENT captured key |
| 762 | (docs/site-routing.md's request[name] convention). Resolved by |
| 763 | scanning the (small, one-row-per-collection) `views` collection for |
| 764 | the record whose own `route` field declares a single capture matching |
| 765 | one of the keys actually present -- the views record stays the single |
| 766 | source of truth for which route maps to which view; no second route |
| 767 | table, no new site_routes column. |
| 768 | """ |
| 769 | view_id = str(request.get("view_id") or "").strip() |
| 770 | candidates = { |
| 771 | key: str(value).strip() |
| 772 | for key, value in request.items() |
| 773 | if key not in _RESERVED_REQUEST_KEYS |
| 774 | and isinstance(value, str) |
| 775 | and value.strip() |
| 776 | } |
| 777 | |
| 778 | records = _views_records(base_dir) |
| 779 | if view_id: |
| 780 | record_id = "" |
| 781 | for record in records: |
| 782 | if record.get("id") == view_id: |
| 783 | capture = _route_capture_name(record.get("route")) |
| 784 | if capture and capture in candidates: |
| 785 | record_id = candidates[capture] |
| 786 | break |
| 787 | return view_id, record_id |
| 788 | |
| 789 | for record in records: |
| 790 | capture = _route_capture_name(record.get("route")) |
| 791 | if capture and capture in candidates: |
| 792 | return str(record.get("id") or ""), candidates[capture] |
| 793 | |
| 794 | # Capture-LESS route (an index/list view like /entities, whose views.route |
| 795 | # is a plain literal path with no {param}): the request carries no capture |
| 796 | # to match on, so resolve by the raw matched path against the view's own |
| 797 | # `route` field. The path (request["_path"], set by object_server for every |
| 798 | # routed object) stays the single source of truth -- no second route table. |
| 799 | path = str(request.get("_path") or "").strip() |
| 800 | if path: |
| 801 | for record in records: |
| 802 | route = record.get("route") |
| 803 | if route and _route_capture_name(route) is None and route == path: |
| 804 | return str(record.get("id") or ""), "" |
| 805 | return "", "" |
| 806 | |
| 807 | |
| 808 | def GET(request): |
| 809 | base_dir = _data_dir() |
| 810 | view_id, record_id = _resolve_view_and_record(request, base_dir) |
| 811 | if view_id and not _RECORD_ID_RE.fullmatch(view_id): |
| 812 | view_id = "" |
| 813 | record_id = "" |
| 814 | if record_id and not _RECORD_ID_RE.fullmatch(record_id): |
| 815 | record_id = "" |
| 816 | identity = request.get("_identity", {}) |
| 817 | user_id = identity.get("user_id") |
| 818 | _logger.info("site_view_render served", view_id=view_id or "missing", |
| 819 | record_id=record_id or "none", user_id=user_id or "anonymous") |
| 820 | |
| 821 | if not view_id: |
| 822 | return { |
| 823 | "content_type": "text/html; charset=utf-8", |
| 824 | "body": "<p>View not found.</p>", |
| 825 | "status": 404, |
| 826 | } |
| 827 | |
| 828 | who = ( |
| 829 | f"signed in as <strong>{user_id}</strong>" |
| 830 | if user_id |
| 831 | else f'<a href="/login?next=/views/{view_id}">sign in</a>' |
| 832 | ) |
| 833 | # ?embed=1: chromeless rendition for stages/iframes (Talk, shell embeds, |
| 834 | # someday in-world screens) -- same page, no app bar, no who-row. |
| 835 | embed = str(request.get("embed") or "").strip() not in ("", "0", "false") |
| 836 | header_html = ( |
| 837 | f'<header class="app"><h1 id="viewtitle">Loading…</h1>' |
| 838 | f'<div class="who">{who}</div></header>' |
| 839 | if not embed |
| 840 | else '<h1 id="viewtitle" class="embed-title">Loading…</h1>' |
| 841 | ) |
| 842 | nav_html = "" if embed else '<script src="/nav"></script>' |
| 843 | html = f"""<!doctype html> |
| 844 | <html lang="en"> |
| 845 | <head> |
| 846 | <meta charset="utf-8"> |
| 847 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 848 | <title>View</title> |
| 849 | <link rel="stylesheet" href="/style"> |
| 850 | <style>{_STYLE}</style> |
| 851 | </head> |
| 852 | <body> |
| 853 | <div class="wrap"> |
| 854 | {header_html} |
| 855 | <div class="blocks" id="blocks"><div class="state">loading…</div></div> |
| 856 | </div> |
| 857 | <script src="/markdown"></script> |
| 858 | <script src="/list"></script> |
| 859 | <script src="/form"></script> |
| 860 | <script src="/detail"></script> |
| 861 | <script src="/thread"></script> |
| 862 | <script src="/attachments"></script> |
| 863 | <script src="/share"></script> |
| 864 | <script>const VIEW_ID = {view_id!r}; const VIEWER_ID = {(user_id or "")!r}; const RECORD_ID = {record_id!r};{_SCRIPT}</script> |
| 865 | {nav_html} |
| 866 | </body> |
| 867 | </html>""" |
| 868 | return {"content_type": "text/html; charset=utf-8", "body": html} |