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
thread.py · 7.2 KB · 142 lines
1"""Comment thread widget, served at /thread as window.dbbasicThread.
2
3The missing piece of app-thread: the `thread_comments` schema and the
4`thread` block reference landed early (see the schema's own note), with the
5final polymorphic shape (parent_collection + parent_id) so no data
6migration is ever needed once the widget arrives. This is that widget.
7
8Sibling to /list, /form, /detail: a public static script, no server state.
9`window.dbbasicThread.mount(el, {parent_collection, parent_id, viewer_id?})`
10renders the comment thread for one record -- the comments filtered to that
11(collection, id) pair, a compose box for signed-in visitors, owner-only
12delete, relative timestamps, and the same change-log realtime every other
13surface uses. It is what a collection's `capabilities.comments` flag mounts
14under a detail page (see app-views/objects/site/view_render.py), so any
15collection gets comments by declaring one key -- no per-app comment table
16(the task_comments/interactions/profile_comments duplication this replaces).
17"""
18
19_JS = r"""
20(function () {
21 const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g,
22 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
23 const qs = (m) => typeof m === "string" ? document.querySelector(m) : m;
24
25 function relDate(iso) {
26 if (!iso) return "";
27 const d = new Date(iso); if (isNaN(d)) return "";
28 const ms = Date.now() - d.getTime();
29 if (ms < 3600000) { const m = Math.floor(ms / 60000); return m < 1 ? "just now" : m + "m"; }
30 if (ms < 86400000) return Math.floor(ms / 3600000) + "h";
31 if (ms < 7 * 86400000) return Math.floor(ms / 86400000) + "d";
32 return d.toLocaleDateString(undefined, {month: "short", day: "numeric"});
33 }
34
35 async function api(method, path, body) {
36 const res = await fetch(path, {method, credentials: "same-origin",
37 headers: {"content-type": "application/json", accept: "application/json"},
38 body: body === undefined ? undefined : JSON.stringify(body)});
39 let data = null; try { data = await res.json(); } catch (e) {}
40 return [res.ok, data];
41 }
42
43 window.dbbasicThread = {
44 mount: async function (mountEl, opts) {
45 mountEl = qs(mountEl); opts = opts || {};
46 const pc = opts.parent_collection, pid = opts.parent_id;
47 // The signed-in viewer -- passed by the caller (view_render embeds
48 // VIEWER_ID). Enables the compose box and marks a comment deletable
49 // by its author. Empty => read-only thread with a sign-in prompt.
50 const viewer = opts.viewer_id
51 || (typeof VIEWER_ID !== "undefined" ? VIEWER_ID : "") || "";
52 if (!mountEl) return;
53 if (!pc || !pid) {
54 mountEl.innerHTML = '<div class="viewblock-error">comments need a parent_collection and parent_id</div>';
55 return;
56 }
57
58 mountEl.innerHTML =
59 '<div class="thread"><h3 class="threadhead">Comments</h3>'
60 + '<div class="threadlist"><div class="state">loading&hellip;</div></div>'
61 + (viewer
62 ? '<form class="threadcompose"><textarea name="body" rows="2" placeholder="Add a comment&hellip;" required></textarea>'
63 + '<div class="threadcomposeactions"><button type="submit" class="btn primary">Comment</button>'
64 + '<span class="error" data-err></span></div></form>'
65 : '<div class="state"><a href="/login">Sign in</a> to comment.</div>')
66 + '</div>';
67 const listEl = mountEl.querySelector(".threadlist");
68 const form = mountEl.querySelector(".threadcompose");
69
70 function bubble(c) {
71 const who = c.author_name || c.owner_id || "someone";
72 const av = String(who).trim().charAt(0).toUpperCase() || "?";
73 const mine = viewer && c.owner_id && c.owner_id === viewer;
74 const del = mine
75 ? '<button class="rowbtn danger" data-del="' + esc(c.id) + '" title="Delete">✕</button>' : "";
76 return '<div class="comment"><div class="av">' + esc(av) + '</div>'
77 + '<div class="commentbody"><div class="commentmeta">'
78 + '<span class="commentwho">' + esc(who) + '</span>'
79 + (c.created_at ? '<span class="when">' + esc(relDate(c.created_at)) + '</span>' : "")
80 + del + '</div>'
81 + '<div class="commenttext">' + esc(c.body).replace(/\n/g, "<br>") + '</div></div></div>';
82 }
83
84 async function load() {
85 // Query narrows to THIS record's thread server-side (58 field=value),
86 // so even a read-all permission only returns this record's comments.
87 const [ok, body] = await api("GET", "/collections/thread_comments/records?limit=500"
88 + "&parent_collection=" + encodeURIComponent(pc) + "&parent_id=" + encodeURIComponent(pid));
89 if (!ok) { listEl.innerHTML = '<div class="state">Could not load comments.</div>'; return; }
90 let rows = (body.records || []).filter((c) => c.parent_collection === pc && c.parent_id === pid);
91 // Moderated comments are hidden from everyone but their author.
92 rows = rows.filter((c) => {
93 const st = c.status || "published";
94 return st === "published" || (viewer && c.owner_id === viewer);
95 });
96 rows.sort((a, b) => String(a.created_at || "").localeCompare(String(b.created_at || "")));
97 listEl.innerHTML = rows.length ? rows.map(bubble).join("") : '<div class="state">No comments yet.</div>';
98 }
99
100 if (form) {
101 form.addEventListener("submit", async (e) => {
102 e.preventDefault();
103 const ta = form.elements["body"], text = String(ta.value || "").trim();
104 const errEl = form.querySelector("[data-err]"); if (errEl) errEl.textContent = "";
105 if (!text) return;
106 // Minimal payload: the server owns created_at (read-only) and
107 // defaults status to "published"; parent_* pin the thread.
108 const rec = {
109 id: (window.crypto && crypto.randomUUID) ? crypto.randomUUID() : String(Date.now()),
110 parent_collection: pc, parent_id: pid, body: text,
111 };
112 // Do NOT send owner_id: it carries a `public: hidden` policy and is
113 // server-owned (set from the session on create; a client value is
114 // rejected as not-editable). author_name IS a normal display field --
115 // stamp it, because owner_id is redacted from other readers, so
116 // without it every other person's comment would read as "someone".
117 if (viewer) rec.author_name = viewer;
118 const [ok, resp] = await api("POST", "/collections/thread_comments/records", rec);
119 if (!ok) { if (errEl) errEl.textContent = (resp && resp.error) || "Could not post comment"; return; }
120 ta.value = ""; load();
121 });
122 }
123 listEl.addEventListener("click", async (e) => {
124 const del = e.target.closest("[data-del]"); if (!del) return;
125 if (!window.confirm("Delete this comment?")) return;
126 await api("DELETE", "/collections/thread_comments/records/" + encodeURIComponent(del.getAttribute("data-del")));
127 load();
128 });
129
130 (function sub() {
131 if (window.dbbasicSubscribe) window.dbbasicSubscribe("thread_comments", load);
132 else setTimeout(sub, 400);
133 })();
134 load();
135 },
136 };
137})();
138"""
139
140
141def GET(request):
142 return {"content_type": "application/javascript; charset=utf-8", "body": _JS}