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
nav.py · 20.1 KB · 413 lines
1"""The app shell / navigation bar, served as one script at /nav.
2
3Every page includes <script src="/nav"></script> and gets a persistent
4top bar: brand + app switcher, global search (Cmd/Ctrl-K) over
5/api/search, an Ask-AI link to the shell, a notification bell reading
6the notifications collection, and a user menu (appearance, sign out).
7
8The bell polls today; it is written so a websocket message can call the
9same renderNotes() to make it live the moment realtime push lands —
10auto-update on events is the thing the old stack could not do cleanly.
11"""
12
13_JS = r"""
14(function () {
15 if (document.getElementById("dbbasic-appbar")) return;
16
17 // Fallback only. The switcher is a fold over the nav registry
18 // (action_nav_entries -> the nav_entries collection every package
19 // writes on install); this array is what gets drawn if that call
20 // fails. It is deliberately NOT maintained -- a second maintained list
21 // is the exact drift this registry was built to end -- but a nav that
22 // vanishes on a fetch error is worse than one that is slightly stale,
23 // so a stale door beats no door.
24 const APPS = [
25 ["/shell", "Shell"], ["/talk", "Talk"], ["/notes", "Notes"], ["/tasks", "Tasks"], ["/templates", "Templates"],
26 ["/projects", "Projects"], ["/contacts", "Contacts"], ["/articles", "Articles"],
27 ["/links", "Links"], ["/calendar", "Calendar"], ["/files", "Files"],
28 ["/invoices", "Invoices"], ["/products", "Products"], ["/orders", "Orders"],
29 ["/stock", "Stock"], ["/locations", "Locations"],
30 ["/accounts", "Accounts"], ["/journals", "Journals"], ["/trial-balance", "Trial Balance"],
31 ["/activity", "Activity"], ["/forum", "Forum"], ["/profile/edit", "Profile"], ["/inbox", "Inbox"],
32 ["/dashboard", "Dashboard"], ["/appearance", "Appearance"],
33 ];
34 // The third hand-maintained list, still hand-maintained: a search hit
35 // needs a URL for a RECORD, which the nav registry does not model (it
36 // registers doors, not permalinks). Deliberately left alone rather
37 // than half-folded into something that does not fit.
38 const HIT_URL = {
39 notes: (id) => "/notes/" + encodeURIComponent(id),
40 articles: (id) => "/articles/" + encodeURIComponent(id),
41 files: (id) => "/api/files/" + encodeURIComponent(id),
42 views: (id) => "/views/" + encodeURIComponent(id),
43 tasks: () => "/tasks", projects: () => "/projects", contacts: () => "/contacts",
44 organizations: () => "/contacts", interactions: () => "/contacts",
45 links: () => "/links", events: () => "/calendar",
46 invoices: () => "/invoices", templates: () => "/templates", products: (id) => "/products/" + encodeURIComponent(id), orders: (id) => "/orders/" + encodeURIComponent(id),
47 forum_categories: () => "/forum", forum_topics: (id) => "/forum/topics/" + encodeURIComponent(id), profiles: (id) => "/u/" + encodeURIComponent(id), message_threads: (id) => "/inbox/" + encodeURIComponent(id), fin_accounts: () => "/accounts", fin_journals: (id) => "/journals/" + encodeURIComponent(id), locations: () => "/locations",
48 };
49 const esc = (s) => String(s ?? "").replace(/[&<>"']/g,
50 (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
51 const api = (path) => fetch(path, { credentials: "same-origin", headers: { accept: "application/json" } });
52
53 // 65 multi-entity: the "current entity" (set of books) is a client-held
54 // value in localStorage, read here and by the list/form generators to
55 // scope every entity-scoped collection. A convenience getter -- the
56 // generators read the same localStorage key directly, so they never depend
57 // on the nav having loaded first. Empty string = "All entities" (no scope).
58 var ENTITY_KEY = "dbbasic_entity";
59 window.dbbasicEntity = function () {
60 try { return localStorage.getItem(ENTITY_KEY) || ""; } catch (e) { return ""; }
61 };
62
63 const bar = document.createElement("div");
64 bar.className = "appbar";
65 bar.id = "dbbasic-appbar";
66 bar.innerHTML =
67 '<a class="brand" href="/">DBBASIC</a>' +
68 '<button class="navbtn" id="nav-apps">Apps ▾</button>' +
69 '<button class="navbtn" id="nav-books" style="display:none"></button>' +
70 '<div class="search"><input id="nav-search" placeholder="Search everything…" autocomplete="off">' +
71 '<span class="kbd">⌘K</span></div>' +
72 '<span class="spacer"></span>' +
73 '<a class="navbtn accent" href="/shell">Ask AI</a>' +
74 '<button class="navbtn" id="nav-bell" title="Notifications">◉<span class="count" id="nav-count" style="display:none">0</span></button>' +
75 '<button class="navbtn" id="nav-user">…</button>';
76 document.body.insertBefore(bar, document.body.firstChild);
77 document.body.classList.add("has-appbar");
78
79 const menus = {};
80 function menu(id) {
81 if (menus[id]) return menus[id];
82 const m = document.createElement("div");
83 m.className = "navmenu";
84 m.id = id;
85 document.body.appendChild(m);
86 menus[id] = m;
87 return m;
88 }
89 function place(m, anchor, right) {
90 const r = anchor.getBoundingClientRect();
91 m.style.left = right ? "auto" : r.left + "px";
92 m.style.right = right ? (window.innerWidth - r.right) + "px" : "auto";
93 }
94 function closeAll(except) {
95 Object.values(menus).forEach((m) => { if (m !== except) m.classList.remove("open"); });
96 }
97 document.addEventListener("click", (e) => {
98 if (!e.target.closest(".navmenu") && !e.target.closest(".appbar .navbtn")) closeAll();
99 });
100
101 // App switcher. Drawn from the fallback immediately so the menu is
102 // never empty, then replaced by the registry as soon as it answers:
103 // action_nav_entries returns the doors THIS caller may see, already
104 // grouped and sorted, so the switcher restates no visibility rule of
105 // its own.
106 const appsBtn = document.getElementById("nav-apps");
107 const appsMenu = menu("nav-apps-menu");
108 // Two async loaders write this menu, so each owns a piece and a single
109 // render joins them -- appending straight into innerHTML made whichever
110 // one answered second wipe the other.
111 let appsHtml = APPS.map(([u, n]) => '<a href="' + u + '">' + esc(n) + "</a>").join("");
112 let pinnedHtml = "";
113 const renderApps = () => { appsMenu.innerHTML = appsHtml + pinnedHtml; };
114 renderApps();
115 appsBtn.addEventListener("click", () => {
116 const open = appsMenu.classList.contains("open"); closeAll();
117 if (!open) { place(appsMenu, appsBtn); appsMenu.classList.add("open"); }
118 });
119 (async function loadApps() {
120 try {
121 const res = await api("/objects/action_nav_entries");
122 if (!res.ok) return; // keep the fallback
123 const groups = (await res.json()).groups || [];
124 if (!groups.length) return; // empty registry: keep the fallback
125 appsHtml = groups.map((g) =>
126 '<div class="head">' + esc(g.group) + "</div>" +
127 // The count rides along on the entry when a package's attention
128 // provider says that door has a queue. Rendered as text rather
129 // than a styled pill deliberately: the switcher is drawn by this
130 // script and styled by /style, and a class this stylesheet does
131 // not know about would ship as an invisible promise. A zero never
132 // arrives -- action_nav_entries drops empty queues -- so there is
133 // no "0" case to suppress here.
134 (g.entries || []).map((e) =>
135 '<a href="' + esc(e.path) + '">' + esc(e.label) +
136 (e.count ? " · " + esc(e.count) : "") + "</a>").join("")
137 ).join("");
138 renderApps();
139 } catch (e) { /* registry unreachable -- the fallback list is already drawn */ }
140 })();
141
142 // Pinned views (app-views, optional): append any pinned view record to
143 // the Apps switcher. The nav ships in every install, app-views does not,
144 // so a missing collection or a failed fetch must stay silent -- the
145 // switcher already works without it.
146 (async function loadPinnedViews() {
147 try {
148 const res = await api("/collections/views/records?limit=200");
149 if (!res.ok) return;
150 const body = await res.json();
151 const pinned = (body.records || []).filter((v) => v.pinned === "true");
152 if (!pinned.length) return;
153 pinnedHtml = '<div class="head">pinned</div>' + pinned.map((v) =>
154 '<a href="' + esc(v.route || ("/views/" + v.id)) + '">' + esc(v.title || "View") + "</a>").join("");
155 renderApps();
156 } catch (e) { /* app-views not installed -- the switcher still works without it */ }
157 })();
158
159 // Entity switcher (65 multi-entity): a "Books" picker listing the signed-in
160 // user's entities. Selecting one stores its id in localStorage; the list/
161 // form generators read that key and scope every entity-scoped collection to
162 // it (filter on read, FK-lock on new writes). "All entities" clears the
163 // scope. Hidden entirely when the user has no entities (nothing to switch),
164 // so a fresh/unused install shows no extra chrome -- same silent-degrade
165 // posture as the pinned-views loader above.
166 const booksBtn = document.getElementById("nav-books");
167 const booksMenu = menu("nav-books-menu");
168 (async function loadEntities() {
169 try {
170 const res = await api("/collections/entities/records?limit=200");
171 if (!res.ok) return;
172 const entities = ((await res.json()).records) || [];
173 if (!entities.length) return; // no books -> no switcher
174 const current = window.dbbasicEntity();
175 const currentName = (entities.find((e) => e.id === current) || {}).name;
176 booksBtn.textContent = "Books: " + (currentName || "All") + " ▾";
177 booksBtn.style.display = "";
178 const setEntity = (id) => {
179 try { id ? localStorage.setItem(ENTITY_KEY, id) : localStorage.removeItem(ENTITY_KEY); } catch (e) {}
180 location.reload();
181 };
182 booksMenu.innerHTML =
183 '<div class="head">books</div>' +
184 '<a href="#" data-eid="">All entities</a>' +
185 entities.map((e) => '<a href="#" data-eid="' + esc(e.id) + '">' + esc(e.name || e.id) + "</a>").join("") +
186 '<div class="head"><a href="/entities">Manage entities…</a></div>';
187 booksMenu.querySelectorAll("a[data-eid]").forEach((a) =>
188 a.addEventListener("click", (ev) => { ev.preventDefault(); setEntity(a.dataset.eid); }));
189 booksBtn.addEventListener("click", () => {
190 const open = booksMenu.classList.contains("open"); closeAll();
191 if (!open) { place(booksMenu, booksBtn); booksMenu.classList.add("open"); }
192 });
193 } catch (e) { /* entities collection not installed -- no switcher, nav still works */ }
194 })();
195
196 // Global search
197 const search = document.getElementById("nav-search");
198 const resMenu = menu("nav-results"); resMenu.classList.add("results");
199 let timer = null;
200 async function runSearch() {
201 const q = search.value.trim();
202 if (!q) { resMenu.classList.remove("open"); return; }
203 const res = await api("/api/search?q=" + encodeURIComponent(q) + "&limit=6");
204 if (!res.ok) return;
205 const body = await res.json();
206 const groups = Object.entries(body.results || {}).filter(([, hits]) => hits.length);
207 if (!groups.length) { resMenu.innerHTML = '<div class="head">no matches</div>'; }
208 else {
209 resMenu.innerHTML = groups.map(([col, hits]) =>
210 '<div class="head">' + esc(col) + "</div>" +
211 hits.map((h) => {
212 const label = esc(h.title || h.name || h.number || h.subject || h.body
213 || h.content || h.comment || h.description || h.first_name || "(untitled)").slice(0, 80);
214 const url = (HIT_URL[col] ? HIT_URL[col](h.id) : null);
215 return url ? '<a class="hit item" href="' + url + '">' + label + "</a>"
216 : '<div class="hit item">' + label + "</div>";
217 }).join("")
218 ).join("");
219 }
220 place(resMenu, search); resMenu.classList.add("open");
221 }
222 search.addEventListener("input", () => { clearTimeout(timer); timer = setTimeout(runSearch, 200); });
223 document.addEventListener("keydown", (e) => {
224 if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); search.focus(); }
225 if (e.key === "Escape") closeAll();
226 });
227
228 // Notifications (poll now; a websocket can call renderNotes() later)
229 const bell = document.getElementById("nav-bell");
230 const count = document.getElementById("nav-count");
231 const notesMenu = menu("nav-notes");
232 function renderNotes(records) {
233 const unread = records.filter((n) => n.is_read !== "true");
234 if (unread.length) { count.textContent = unread.length > 9 ? "9+" : unread.length; count.style.display = ""; }
235 else count.style.display = "none";
236 notesMenu.innerHTML = '<div class="head">notifications</div>' +
237 (records.length ? records.slice(-8).reverse().map((n) =>
238 '<div class="item">' + esc(n.body || "") + "</div>").join("")
239 : '<div class="item" style="color:var(--muted)">nothing yet</div>');
240 }
241 async function refreshNotes() {
242 const res = await api("/collections/notifications/records?limit=50");
243 if (res.ok) { const b = await res.json(); renderNotes(b.records || []); }
244 }
245 window.dbbasicRenderNotes = renderNotes;
246
247 // Realtime: live push over a websocket, with the 20s poll as fallback.
248 const subs = {}; // collection -> [handlers]
249 let ws = null, retry = 1000;
250 function subscribe(collection, handler) {
251 (subs[collection] = subs[collection] || []).push(handler);
252 if (ws && ws.readyState === 1) ws.send(JSON.stringify({ action: "subscribe", collections: [collection] }));
253 }
254 window.dbbasicSubscribe = subscribe; // pages can follow their own collection
255 function connectRealtime() {
256 try {
257 const proto = location.protocol === "https:" ? "wss" : "ws";
258 ws = new WebSocket(proto + "://" + location.host + "/ws");
259 } catch (e) { return; }
260 ws.onopen = () => {
261 retry = 1000;
262 const cols = Object.keys(subs);
263 if (cols.length) ws.send(JSON.stringify({ action: "subscribe", collections: cols }));
264 };
265 ws.onmessage = (ev) => {
266 let m; try { m = JSON.parse(ev.data); } catch (e) { return; }
267 if (m.type === "record" && subs[m.collection]) subs[m.collection].forEach((h) => h(m));
268 };
269 ws.onclose = () => { ws = null; setTimeout(connectRealtime, retry); retry = Math.min(retry * 2, 30000); };
270 ws.onerror = () => { try { ws.close(); } catch (e) {} };
271 }
272
273 bell.addEventListener("click", () => {
274 const open = notesMenu.classList.contains("open"); closeAll();
275 if (!open) { place(notesMenu, bell, true); notesMenu.classList.add("open"); }
276 });
277
278 // User menu
279 const userBtn = document.getElementById("nav-user");
280 const userMenu = menu("nav-user-menu");
281 async function loadUser() {
282 let name = null;
283 try {
284 const res = await api("/identity/session");
285 if (res.ok) { const b = await res.json(); name = (b.session || b).user_id || b.user_id; }
286 } catch (e) {}
287 if (name) {
288 userBtn.textContent = name + " ▾";
289 userMenu.innerHTML =
290 '<div class="head">' + esc(name) + "</div>" +
291 '<a href="/appearance">Appearance</a>' +
292 '<button class="item" id="nav-signout">Sign out</button>';
293 userMenu.querySelector("#nav-signout").addEventListener("click", async () => {
294 await fetch("/logout", { method: "POST", credentials: "same-origin" });
295 location.href = "/";
296 });
297 refreshNotes();
298 setInterval(refreshNotes, 20000); // fallback poll
299 subscribe("notifications", refreshNotes); // live push updates the bell instantly
300 connectRealtime();
301 } else {
302 userBtn.textContent = "Sign in";
303 userBtn.onclick = () => { location.href = "/login?next=" + encodeURIComponent(location.pathname); };
304 bell.style.display = "none";
305 }
306 }
307 userBtn.addEventListener("click", () => {
308 if (userBtn.textContent === "Sign in") return;
309 const open = userMenu.classList.contains("open"); closeAll();
310 if (!open) { place(userMenu, userBtn, true); userMenu.classList.add("open"); }
311 });
312 loadUser();
313})();
314
315// === local time ============================================================
316//
317// Every timestamp this server STORES is UTC, which is correct and is not
318// negotiable -- a stamp without a zone is a bug waiting for the clocks to
319// change. Every timestamp a person READS should be in their own zone,
320// which is a rendering question and belongs here rather than in each page.
321//
322// The generative renderer already got this right by accident of being
323// client-side: `new Date(iso)` parses UTC and `toLocaleString` prints
324// local. Server-rendered pages did not, because a Python f-string has no
325// idea who is reading it. So the convention is one element:
326//
327// <time datetime="2026-07-27T03:12:44Z">2026-07-27T03:12:44Z</time>
328//
329// and this converts the text while leaving the machine-readable attribute
330// exactly as the server wrote it. No JavaScript, or an unparseable stamp,
331// leaves the UTC text in place -- which is honest rather than blank.
332//
333// THE BROWSER IS THE DEFAULT, NOT A PREFERENCE, because it is right more
334// often: it follows the reader across daylight saving and across a plane,
335// and it needs nobody to have set anything. A stored preference OVERRIDES
336// it (display.timezone in user_prefs) for the real case the browser gets
337// wrong -- a business whose books are kept in one zone regardless of where
338// the person reading them happens to be sitting.
339//
340// AND THE BROWSER'S ZONE IS NEVER SENT TO THE SERVER. It is available
341// (Intl.DateTimeFormat().resolvedOptions().timeZone returns the IANA
342// name) and it is deliberately used only in this process. A timezone is a
343// real fingerprinting signal -- one of the higher-entropy bits in the
344// standard browser fingerprint -- so silently posting it back to store as
345// a preference would be collecting an identifying attribute nobody asked
346// us to collect, and /privacy is a fold over exactly that. Reading it to
347// format text costs nothing and discloses nothing. If a user wants a
348// fixed zone, they set the pref themselves and it is their statement
349// rather than our observation.
350(function () {
351 const ISO = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
352 let zone = null; // null = browser default
353
354 function fmt(iso, opts) {
355 if (!iso || !ISO.test(String(iso).trim())) return null;
356 // A bare stamp with no zone marker is UTC by this server's contract.
357 let text = String(iso).trim().replace(" ", "T");
358 if (!/[Zz]|[+-]\d{2}:?\d{2}$/.test(text)) text += "Z";
359 const d = new Date(text);
360 if (isNaN(d)) return null;
361 const o = Object.assign({dateStyle: "medium", timeStyle: "short"}, opts || {});
362 if (o.timeStyle === undefined) delete o.timeStyle; // date-only, cleanly
363 if (zone) o.timeZone = zone;
364 try { return d.toLocaleString(undefined, o); }
365 catch (e) { return d.toLocaleString(); } // a bad pref must not blank the page
366 }
367
368 function apply(root) {
369 (root || document).querySelectorAll("time[datetime]").forEach((el) => {
370 if (el.dataset.localized === "1") return;
371 const out = fmt(el.getAttribute("datetime"),
372 el.dataset.timeStyle === "date" ? {timeStyle: undefined} : null);
373 if (!out) return; // unparseable: leave UTC showing
374 if (!el.title) el.title = el.getAttribute("datetime") + " (UTC)";
375 el.textContent = out;
376 el.dataset.localized = "1";
377 });
378 }
379
380 window.dbbasicTime = {format: fmt, apply: apply,
381 zone: () => zone || Intl.DateTimeFormat().resolvedOptions().timeZone};
382
383 function start() {
384 apply(document);
385 // Anything rendered after load -- the generative list, a form panel,
386 // a realtime push -- gets converted as it arrives, so a page does not
387 // have to remember to call apply().
388 if (window.MutationObserver) {
389 new MutationObserver((muts) => {
390 for (const m of muts) if (m.addedNodes.length) { apply(document); break; }
391 }).observe(document.body, {childList: true, subtree: true});
392 }
393 }
394
395 fetch("/prefs", {credentials: "same-origin"})
396 .then((r) => (r.ok ? r.json() : null))
397 .then((p) => {
398 const prefs = (p && (p.prefs || p.records || p)) || {};
399 const tz = prefs["display.timezone"] || prefs.display_timezone;
400 if (tz && String(tz).trim()) zone = String(tz).trim();
401 })
402 .catch(() => {})
403 .finally(() => {
404 if (document.readyState === "loading") {
405 document.addEventListener("DOMContentLoaded", start);
406 } else { start(); }
407 });
408})();
409"""
410
411
412def GET(request):
413 return {"content_type": "application/javascript; charset=utf-8", "body": _JS}