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
appearance.py · 7.7 KB · 178 lines
1"""Appearance: the theme chooser.
2
3Reads the available themes from /style?info=true and, for an admin,
4switches the instance theme with POST /style {theme}. The change is
5instance-wide and reskins every page that links /style — which is all of
6them. Non-admins see the current theme read-only.
7"""
8
9# Page-unique: the swatch preview grid. Colors come from the fetched
10# theme previews (inline styles), everything else from /style tokens.
11_STYLE = """
12.themes { display: grid; gap: var(--gap); grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
13 margin-top: var(--gap); }
14.theme { border: 1px solid var(--line); border-radius: var(--radius-md); overflow: hidden;
15 background: var(--panel); cursor: pointer; text-align: left; padding: 0; font: inherit; color: inherit; }
16.theme[aria-disabled="true"] { cursor: default; }
17.theme.active { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent); }
18.theme .swatch { display: flex; height: 64px; }
19.theme .swatch span { flex: 1; }
20.theme .label { padding: 0.55rem 0.75rem; display: flex; align-items: center; gap: 0.5rem; }
21.theme .label .dot { width: 0.8rem; height: 0.8rem; border-radius: 999px; border: 1px solid var(--line); }
22.theme .label .on { margin-left: auto; color: var(--accent); font-size: 0.75rem; }
23"""
24
25_SCRIPT = """
26const esc = (s) => String(s ?? "").replace(/[&<>"']/g,
27 (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
28const grid = document.getElementById("themes");
29
30function card(name, p, active) {
31 const swatch = [p.bg, p.panel, p.accent, p.text]
32 .map((c) => `<span style="background:${esc(c)}"></span>`).join("");
33 return `<button class="theme${active ? " active" : ""}" data-theme="${esc(name)}"` +
34 `${ADMIN ? "" : ' aria-disabled="true"'}>` +
35 `<div class="swatch">${swatch}</div>` +
36 `<div class="label"><span class="dot" style="background:${esc(p.accent)}"></span>` +
37 `${esc(name)}${active ? '<span class="on">active</span>' : ""}</div></button>`;
38}
39
40async function load() {
41 const res = await fetch("/style?info=true", {credentials: "same-origin",
42 headers: {accept: "application/json"}});
43 const info = await res.json();
44 grid.innerHTML = info.available
45 .map((n) => card(n, (info.previews || {})[n] || {}, n === info.active)).join("");
46}
47
48grid.addEventListener("click", async (event) => {
49 const btn = event.target.closest("button.theme");
50 if (!btn || !ADMIN) return;
51 const res = await fetch("/style", {
52 method: "POST", credentials: "same-origin",
53 headers: {"content-type": "application/json", accept: "application/json"},
54 body: JSON.stringify({theme: btn.dataset.theme}),
55 });
56 const body = await res.json();
57 document.getElementById("msg").textContent =
58 res.ok ? `Theme set to ${body.active}. Reloading…` : (body.error || "Failed");
59 if (res.ok) setTimeout(() => location.reload(), 500);
60});
61load();
62"""
63
64
65_TZ_SCRIPT = r"""
66// The timezone picker. The pref is display.timezone in user_prefs and has
67// been writable over PUT /prefs/... since the formatter shipped -- it just
68// had nowhere a person would ever find it, which is the same as not
69// existing. Blank means "use the browser", which stays the default because
70// it is right more often and requires nobody to decide anything.
71(function () {
72 const sel = document.getElementById("tz");
73 const msg = document.getElementById("tzmsg");
74 if (!sel) return;
75 const browserTz = Intl.DateTimeFormat().resolvedOptions().timeZone || "unknown";
76 const label = document.getElementById("browsertz");
77 if (label) label.textContent = browserTz;
78
79 // Intl.supportedValuesOf is the standard list where it exists; the
80 // fallback is short and deliberate rather than a bundled tz database --
81 // anybody needing an exotic zone can PUT the pref directly, and shipping
82 // 400 names to render a dropdown nobody scrolls is not worth the bytes.
83 let zones = [];
84 try { zones = Intl.supportedValuesOf("timeZone"); } catch (e) {
85 zones = ["UTC", "America/New_York", "America/Chicago", "America/Denver",
86 "America/Los_Angeles", "Europe/London", "Europe/Paris",
87 "Europe/Berlin", "Asia/Tokyo", "Asia/Kolkata", "Australia/Sydney"];
88 }
89 if (browserTz && zones.indexOf(browserTz) < 0) zones.unshift(browserTz);
90 for (const z of zones) {
91 const o = document.createElement("option");
92 o.value = z; o.textContent = z;
93 sel.appendChild(o);
94 }
95
96 fetch("/prefs", {credentials: "same-origin"})
97 .then((r) => (r.ok ? r.json() : null))
98 .then((p) => { sel.value = ((p && p.prefs) || {})["display.timezone"] || ""; })
99 .catch(() => {});
100
101 sel.addEventListener("change", () => {
102 msg.textContent = "saving…";
103 fetch("/prefs/display.timezone", {
104 method: "PUT", credentials: "same-origin",
105 headers: {"Content-Type": "application/json"},
106 body: JSON.stringify({value: sel.value}),
107 }).then((r) => {
108 if (!r.ok) throw new Error(r.status);
109 msg.textContent = sel.value
110 ? "saved — times now show in " + sel.value
111 : "saved — using your browser's zone";
112 // Re-render what is already on screen rather than asking for a reload.
113 if (window.dbbasicTime) {
114 document.querySelectorAll("time[datetime]").forEach((el) => {
115 delete el.dataset.localized;
116 });
117 }
118 setTimeout(() => location.reload(), 700);
119 }).catch(() => { msg.textContent = "could not save"; });
120 });
121})();
122"""
123
124def GET(request):
125 identity = request.get("_identity", {})
126 user_id = identity.get("user_id")
127 is_admin = "admin" in (identity.get("roles") or [])
128 _logger.info("site_appearance served", user_id=user_id or "anonymous", admin=is_admin)
129
130 note = (
131 "Click a theme to reskin the whole instance. Changes are instance-wide and live."
132 if is_admin
133 else "This is the current instance theme. Switching requires an admin session."
134 )
135 who = (
136 f"signed in as <strong>{user_id}</strong>"
137 if user_id
138 else '<a href="/login?next=/appearance">sign in</a>'
139 )
140 html = f"""<!doctype html>
141<html lang="en">
142<head>
143<meta charset="utf-8">
144<meta name="viewport" content="width=device-width, initial-scale=1">
145<title>Appearance</title>
146<link rel="stylesheet" href="/style">
147<style>{_STYLE}</style>
148</head>
149<body>
150<div class="wrap narrow">
151<header class="app"><h1><a href="/">Home</a> / appearance</h1><div class="who">{who}</div></header>
152<p class="muted">{note}</p>
153<div class="themes" id="themes"><p class="hint">loading&hellip;</p></div>
154<p class="error" id="msg"></p>
155
156<h2 style="margin-top:2rem">Time</h2>
157<p class="muted">Timestamps are stored in UTC and shown in <strong>your
158browser's timezone</strong> — <span id="browsertz">detecting&hellip;</span>.
159Nothing is sent to the server to work that out, and nothing about your
160timezone is stored unless you choose one below.</p>
161<p>
162<label for="tz">Show times in</label>
163<select id="tz" style="max-width:22rem"><option value="">Whatever my browser says (recommended)</option></select>
164<span class="hint" id="tzmsg"></span>
165</p>
166<p class="muted" style="font-size:0.8rem">Pick a fixed zone only if you want
167times to read the same wherever you happen to be — books kept in one place,
168a rota everyone reads in the shop's own hours. Otherwise leave it on the
169browser, which follows you across daylight saving and across a plane.</p>
170
171<p class="muted" style="margin-top:1.5rem;font-size:0.8rem">A theme is a set of values for the
172design system's token roles. Themes also install as packages — see docs/design-system.md.</p>
173</div>
174<script>const ADMIN = {"true" if is_admin else "false"};{_SCRIPT}{_TZ_SCRIPT}</script>
175<script src="/nav"></script>
176</body>
177</html>"""
178 return {"content_type": "text/html; charset=utf-8", "body": html}