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

0 downloads

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

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

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
form.py · 19.3 KB · 355 lines
1"""Schema-driven form generator, served at /form as window.dbbasicForm.
2
3The metadata builds the UI: given a collection, it fetches the schema
4(GET /api/schema/{c}) and renders a form from it — field order from
5forms.default.fields, controls from field semantics (enum -> select,
6relation -> record picker, boolean -> checkbox, date -> date input,
7textarea, number, text), labels/help/required/max-length from the schema.
8Create (POST) and edit (PUT) modes; id, owner_id, and created_at are set
9automatically; computed/read_only fields are never written. One generator,
10every collection — the web counterpart of Scroll's schema_form.
11
12`window.dbbasicForm.readOnly(collection, opts)` is the same pipeline run
13in forced-read-only mode over one record for `59-detail-related-spec.md`'s
14detail generator (served at /detail): same schema fetch, same field
15order/labels, same relation display-field resolution and type-aware value
16formatting (`control()` below, shared by both modes) — just a plain
17`<div>` of label/value rows instead of editable controls, and no submit.
18This is the "delete a layer, don't add one" move: a second field-renderer
19in detail.py would be a second place to keep that formatting logic
20correct, so /detail calls back into this one instead.
21
22Defined once here, so no page hand-writes a form again.
23"""
24
25_JS = r"""
26(function () {
27 const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g,
28 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
29 const human = (n) => n.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
30
31 // Real markdown for read-only textarea fields (a note, an article, any
32 // long-form field) -- delegates to the ONE shared renderer at /markdown
33 // (window.dbbasicMarkdown, see markdown.py) rather than keeping a
34 // second copy here. This file used to carry its own light regex
35 // subset; without it a multi-line value collapsed into one
36 // run-together line (plain text in a <span>, no paragraph breaks) and
37 // literal "**bold**" syntax showed as literal asterisks -- found while
38 // trying to publish a real article. Falls back to a bare escape (never
39 // raw innerHTML of untrusted text) if a page loads /form without
40 // /markdown, same "fails silent when a widget isn't loaded" posture
41 // detail.py already uses for window.dbbasicForm itself.
42 function textareaHtml(text) {
43 if (window.dbbasicMarkdown) return window.dbbasicMarkdown(text);
44 return esc(text).replace(/\n/g, "<br>");
45 }
46 const qs = (m) => typeof m === "string" ? document.querySelector(m) : m;
47
48 async function api(method, path, body) {
49 const res = await fetch(path, {method, credentials: "same-origin",
50 headers: {"content-type": "application/json", accept: "application/json"},
51 body: body === undefined ? undefined : JSON.stringify(body)});
52 let data = null; try { data = await res.json(); } catch (e) {}
53 return [res.ok, data];
54 }
55
56 function skip(f) {
57 const t = String(f.type || "").toLowerCase();
58 return f.name === "id" || f.name === "owner_id" || f.name === "created_at"
59 || t === "computed" || f.computed || f.read_only || f.readonly || f.readOnly;
60 }
61
62 // Type-aware read-only text, shared by every non-relation field kind.
63 // Kept next to control()'s edit-mode branches so a new field type only
64 // ever needs one new `if` here, not a second renderer to keep in sync.
65 function readOnlyText(t, v) {
66 if (!v) return "—";
67 if (t === "boolean") return v === "true" ? "Yes" : "No";
68 if (t === "date") return v.slice(0, 10);
69 // A stored datetime is UTC (this server's contract). Slicing the
70 // string showed UTC digits to a reader who does not live there --
71 // "2026-07-27 09:39" for something that happened at 4:39am. Hand it
72 // to the shared formatter, which knows the reader's zone; fall back
73 // to the old slice only if that script has not loaded, because a
74 // wrong-but-present time beats a blank field.
75 if (t === "datetime" || t === "timestamp") {
76 const local = window.dbbasicTime && window.dbbasicTime.format(v);
77 return local || v.slice(0, 16).replace("T", " ");
78 }
79 return v;
80 }
81
82 // <input type="datetime-local"> is LOCAL BY DEFINITION -- the browser
83 // reads and writes wall-clock time in the viewer's zone with no offset
84 // attached. Feeding it a UTC slice therefore did two wrong things at
85 // once: it displayed 09:39 for a 4:39am event, and on save it handed
86 // back that same wall-clock string which was then stored AS UTC. Every
87 // edit shifted the value by the reader's offset, compounding on each
88 // round trip. Nine editable datetime fields across seven collections
89 // (events, stock_moves, pickup_slots, time_logs, ...) were reachable.
90 //
91 // So the input is fed LOCAL and its answer is converted back to UTC.
92 function utcToLocalInput(v) {
93 if (!v) return "";
94 let text = String(v).trim().replace(" ", "T");
95 if (!/[Zz]|[+-]\d{2}:?\d{2}$/.test(text)) text += "Z";
96 const d = new Date(text);
97 if (isNaN(d)) return String(v).slice(0, 16);
98 const pad = (n) => String(n).padStart(2, "0");
99 return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate())
100 + "T" + pad(d.getHours()) + ":" + pad(d.getMinutes());
101 }
102
103 function localInputToUtc(v) {
104 if (!v) return "";
105 const d = new Date(String(v)); // no zone marker -> parsed LOCAL
106 if (isNaN(d)) return String(v);
107 return d.toISOString().replace(/\.\d{3}Z$/, "Z");
108 }
109
110 // Money is stored as an integer number of cents under a `_cents` field
111 // name -- the codebase's universal doctrine (price_cents, total_cents,
112 // debit_cents, ...). Every hand-written *_view page re-implemented the
113 // same cents->whole-units formatter; hoisting it here formats money on
114 // EVERY detail page (and, via readOnly, wherever this renderer is reused)
115 // with zero schema changes. Display only: the stored value stays integer
116 // cents, and edit mode keeps the raw integer input (a dollars-input with
117 // round-trip conversion is a separate, riskier change, not done here).
118 function isMoneyField(f) {
119 const t = String(f.type || "").toLowerCase();
120 return /_cents$/.test(f.name || "") && ["integer", "int", "number", "currency"].indexOf(t) >= 0;
121 }
122 function moneyText(v) {
123 if (v === "" || v == null) return "—";
124 const n = Number(v);
125 return isFinite(n) ? (n / 100).toFixed(2) : String(v);
126 }
127 // A `_cents` field's label conventionally ends with "(cents)"; drop it
128 // since the value is now shown in whole units ("Total (cents)" -> "Total").
129 function moneyLabel(f) {
130 return String(f.label || human(f.name)).replace(/\s*\(cents\)\s*$/i, "");
131 }
132
133 // Conditional field visibility. A field may declare
134 // visible_when = {field, equals} or {field, in:[...]} and renders only when
135 // the record's value for that other field matches -- e.g. a product's asset
136 // fields visible only when product_type == "asset". Every hand-written
137 // *_view page did this with bespoke show/hide CSS+JS; as a field-level
138 // declaration it applies on every generated surface for free. Unknown or
139 // absent condition => always visible (fail OPEN, never hide by accident).
140 // A hidden field is simply not rendered, so in edit mode it is not
141 // submitted and its stored value is preserved untouched.
142 function fieldVisible(f, record) {
143 const cond = f.visible_when;
144 if (!cond || typeof cond !== "object") return true;
145 const actual = String((record && record[cond.field] != null) ? record[cond.field] : "");
146 if ("equals" in cond) return actual === String(cond.equals);
147 if (Array.isArray(cond.in)) return cond.in.map(String).indexOf(actual) >= 0;
148 return true;
149 }
150
151 // `readOnly`: 59's detail mode. Same schema-driven branches as edit mode
152 // (relation lookup, enum, boolean, date/datetime, plain text) but
153 // returns a label/value span instead of an editable control -- the one
154 // place relation display-field resolution and type formatting live for
155 // both modes.
156 async function control(f, value, readOnly) {
157 const t = String(f.type || "text").toLowerCase();
158 const name = esc(f.name);
159 const req = f.required ? " required" : "";
160 const ml = (f.validation && f.validation.max_length) ? ' maxlength="' + f.validation.max_length + '"' : "";
161 const ph = f.placeholder ? ' placeholder="' + esc(f.placeholder) + '"' : "";
162 const v = value == null ? "" : String(value);
163 if (f.relation) {
164 const col = typeof f.relation === "string" ? f.relation : f.relation.collection;
165 const disp = (typeof f.relation === "object" && f.relation.display_field) || "name";
166 let opts = '<option value="">—</option>';
167 let displayText = v;
168 const [ok, body] = await api("GET", "/collections/" + col + "/records?limit=500");
169 if (ok) for (const r of (body.records || [])) {
170 opts += '<option value="' + esc(r.id) + '"' + (r.id === v ? " selected" : "") + '>' + esc(r[disp] || r.id) + '</option>';
171 if (r.id === v) displayText = r[disp] || r.id;
172 }
173 if (readOnly) return v
174 ? '<span class="detailvalue">' + esc(displayText) + '</span>'
175 : '<span class="detailvalue empty">—</span>';
176 return '<select name="' + name + '"' + req + '>' + opts + '</select>';
177 }
178 if (readOnly) {
179 if (t === "textarea") {
180 return v ? '<div class="detailvalue textareavalue">' + textareaHtml(v) + '</div>'
181 : '<span class="detailvalue empty">—</span>';
182 }
183 const text = isMoneyField(f) ? moneyText(v) : readOnlyText(t, v);
184 return '<span class="detailvalue' + (isMoneyField(f) ? ' money' : '') + '">' + esc(text) + '</span>';
185 }
186 if (f.enum || t === "enum") {
187 let opts = f.required ? "" : '<option value="">—</option>';
188 for (const o of (f.enum || [])) opts += '<option value="' + esc(o) + '"' + (String(o) === v ? " selected" : "") + '>' + esc(o) + '</option>';
189 return '<select name="' + name + '"' + req + '>' + opts + '</select>';
190 }
191 if (t === "boolean") return '<label class="switch"><input type="checkbox" name="' + name + '"' + (v === "true" ? " checked" : "") + '> ' + esc(f.label || human(f.name)) + '</label>';
192 if (t === "textarea") return '<textarea name="' + name + '" rows="3"' + req + ml + ph + '>' + esc(v) + '</textarea>';
193 if (t === "date") return '<input type="date" name="' + name + '" value="' + esc(v.slice(0, 10)) + '"' + req + '>';
194 if (t === "datetime" || t === "timestamp") return '<input type="datetime-local" name="' + name + '" value="' + esc(utcToLocalInput(v)) + '"' + req + '>';
195 if (["integer", "int", "number", "float", "currency"].indexOf(t) >= 0) return '<input type="number" name="' + name + '" value="' + esc(v) + '"' + req + ph + '>';
196 return '<input type="text" name="' + name + '" value="' + esc(v) + '"' + req + ml + ph + '>';
197 }
198
199 window.dbbasicForm = async function (collection, opts) {
200 opts = opts || {};
201 const mount = qs(opts.mount);
202 const record = opts.record || null;
203 // Fixed fields: a caller (e.g. a `form` block composing a child under a
204 // parent) locks certain fields to a context value -- the classic
205 // "prefill topic_id/invoice_id/order_id to the page's record and hide it"
206 // shape every parent->child compose needs. Locked fields are neither
207 // rendered nor collected from the DOM; their value is injected on submit.
208 // A shared capability of the generic renderer, not a bespoke per-page form.
209 const fixed = (opts.fixed && typeof opts.fixed === "object") ? Object.assign({}, opts.fixed) : {};
210 const [ok, meta] = await api("GET", "/api/schema/" + collection);
211 if (!ok || !meta.schema) { mount.innerHTML = '<p class="error">Could not load form.</p>'; return; }
212 const schema = meta.schema;
213 const byName = {}; (schema.fields || []).forEach((f) => byName[f.name] = f);
214 // 65 multi-entity: a NEW record in an entity-scoped collection is auto-
215 // scoped to the current entity (the nav switcher's client-held selection),
216 // by locking entity_id the same way a caller-supplied fixed FK is -- unless
217 // the caller already fixed it. Only on create (an edit keeps the row's own
218 // entity), only when an entity is actually selected, and only when the
219 // collection has an entity_id field. So every generator create form writes
220 // into the current set of books with no per-form wiring.
221 if (!record && byName["entity_id"] && !("entity_id" in fixed)) {
222 const cur = (window.dbbasicEntity && window.dbbasicEntity()) || "";
223 if (cur) fixed["entity_id"] = cur;
224 }
225 const order = (schema.forms && schema.forms.default && schema.forms.default.fields)
226 || (schema.fields || []).map((f) => f.name);
227 // Create mode (no record) shows every field -- there's no value to test
228 // visible_when against yet; edit mode honors it against the record. Fixed
229 // fields are excluded from the UI entirely (locked to their context value).
230 const ordered = order.map((n) => byName[n]).filter((f) => f && !skip(f) && !(f.name in fixed) && (!record || fieldVisible(f, record)));
231
232 const slotHtml = (name, ctx) => {
233 let out = "";
234 const local = opts.slots && opts.slots[name];
235 if (local) { try { const h = local(ctx); if (h) out += h; } catch (e) {} }
236 if (window.dbbasicSlots) out += window.dbbasicSlots.render(collection, name, ctx);
237 return out;
238 };
239 const slotCtx = {collection: collection, record: record};
240
241 const rows = [];
242 for (const f of ordered) {
243 const ctrl = await control(f, record ? record[f.name] : f.default);
244 if (String(f.type || "").toLowerCase() === "boolean")
245 rows.push('<div class="field">' + ctrl + '</div>');
246 else
247 rows.push('<div class="field"><label>' + esc(f.label || human(f.name)) +
248 (f.required ? ' <span class="req">*</span>' : "") + '</label>' + ctrl +
249 (f.help ? '<div class="help">' + esc(f.help) + '</div>' : "") +
250 '<div class="err" data-for="' + esc(f.name) + '"></div></div>');
251 }
252 mount.innerHTML = '<form class="genform stack">' +
253 slotHtml("before_fields", slotCtx) + rows.join("") + slotHtml("after_fields", slotCtx) +
254 '<div class="formactions"><button type="submit" class="btn primary">' +
255 (record ? "Save Changes" : (opts.submitLabel || "Save")) + '</button>' +
256 (opts.onCancel ? '<button type="button" class="btn" data-cancel>Cancel</button>' : "") +
257 '<span class="error" data-formerror></span></div></form>';
258
259 const form = mount.querySelector("form");
260 if (opts.onCancel) form.querySelector("[data-cancel]").addEventListener("click", opts.onCancel);
261 form.addEventListener("submit", async (e) => {
262 e.preventDefault();
263 const rec = {};
264 for (const f of ordered) {
265 const el = form.elements[f.name];
266 if (!el) continue;
267 const ft = String(f.type || "").toLowerCase();
268 if (ft === "boolean") { rec[f.name] = el.checked ? "true" : "false"; continue; }
269 // The datetime-local control answers in the viewer's wall clock;
270 // storage is UTC. Converting here rather than server-side is the
271 // only place that knows the offset.
272 rec[f.name] = (ft === "datetime" || ft === "timestamp")
273 ? localInputToUtc(el.value) : el.value;
274 }
275 let bad = false;
276 form.querySelectorAll(".err").forEach((el) => el.textContent = "");
277 for (const f of ordered) {
278 if (f.required && !String(rec[f.name] || "").trim()) {
279 const errEl = form.querySelector('.err[data-for="' + f.name + '"]');
280 if (errEl) errEl.textContent = "Required";
281 bad = true;
282 }
283 }
284 if (bad) return;
285 // Inject the context-locked values (they were never in the DOM).
286 for (const k in fixed) rec[k] = fixed[k];
287 let ok2, body2;
288 if (record) {
289 [ok2, body2] = await api("PUT", "/collections/" + collection + "/records/" + encodeURIComponent(record.id), rec);
290 } else {
291 rec.id = crypto.randomUUID();
292 if (opts.owner !== undefined) rec.owner_id = opts.owner;
293 [ok2, body2] = await api("POST", "/collections/" + collection + "/records", rec);
294 }
295 const fe = form.querySelector("[data-formerror]");
296 if (!ok2) { if (fe) fe.textContent = (body2 && body2.error) || "Save failed"; return; }
297 if (opts.onSaved) opts.onSaved((body2 && body2.record) || rec);
298 });
299 };
300
301 // 59's detail mode: one record, read-only, every readable field labeled
302 // and laid out -- no submit control, no second field-renderer. Field
303 // order is `views.detail_fields` when the schema declares it (the same
304 // schema-key convention `views.list_fields`/`views.filter_fields`
305 // already establish), else plain schema declaration order -- NOT
306 // forms.default.fields (that's edit mode's own convention) and no
307 // skip(): detail mode shows every field the record has, id included,
308 // unless the schema opts out via detail_fields. "Visible = readable"
309 // falls out for free -- a field the viewer can't read is already
310 // missing from `opts.record` (the platform's own redaction strips the
311 // key on the way out), so this never needs its own permission check.
312 window.dbbasicForm.readOnly = async function (collection, opts) {
313 opts = opts || {};
314 const mount = qs(opts.mount);
315 const record = opts.record || null;
316 if (!record) { mount.innerHTML = '<div class="state">Not found.</div>'; return; }
317 const [ok, meta] = await api("GET", "/api/schema/" + collection);
318 if (!ok || !meta.schema) { mount.innerHTML = '<div class="viewblock-error">Could not load record.</div>'; return; }
319 const schema = meta.schema;
320 const byName = {}; (schema.fields || []).forEach((f) => byName[f.name] = f);
321 const order = (schema.views && schema.views.detail_fields)
322 || (schema.fields || []).map((f) => f.name);
323 // The raw `id` (a UUID) is noise on a detail page; drop it by default.
324 // Timestamps/owner stay -- they're informative here. A schema that
325 // explicitly lists detail_fields is honored verbatim (id included if listed).
326 const explicit = !!(schema.views && schema.views.detail_fields);
327 const ordered = order.map((n) => byName[n]).filter((f) => f && (explicit || f.name !== "id"));
328 // Record metadata (when was this created/updated) is baseline info every
329 // record carries -- detail_fields curates the MAIN fields, it shouldn't
330 // suppress the timestamps. Append them if the schema has them and the
331 // curated list didn't already include them, so "Created" shows on every
332 // detail page the way it does in the list row meta (matching decision:
333 // detail is a superset of the list, not a subset). Skipped automatically
334 // for a record with no value (readOnly skips fields absent from record).
335 for (const meta of ["created_at", "updated_at"]) {
336 if (byName[meta] && !ordered.some((f) => f.name === meta)) ordered.push(byName[meta]);
337 }
338
339 const rows = [];
340 for (const f of ordered) {
341 if (!(f.name in record)) continue;
342 if (!fieldVisible(f, record)) continue;
343 const value = await control(f, record[f.name], true);
344 const label = isMoneyField(f) ? moneyLabel(f) : (f.label || human(f.name));
345 rows.push('<div class="detailrow"><div class="detaillabel">' + esc(label)
346 + '</div><div class="detailvaluewrap">' + value + '</div></div>');
347 }
348 mount.innerHTML = '<div class="detailcard">' + (rows.join("") || '<div class="state">No fields.</div>') + '</div>';
349 };
350})();
351"""
352
353
354def GET(request):
355 return {"content_type": "application/javascript; charset=utf-8", "body": _JS}