`;
});
$("msgs").innerHTML = h;
+ // (Diagrams in the answers: drawn by the brain once they are on the page.)
+ if ($("msgs").querySelector(".chart[data-mermaid]")) loadCharts();
renderSendBtn();
loadFiles();
seenWatch();
@@ -3465,7 +3467,7 @@ async function listSchedule(el) {
S.sched = v;
drawSchedule(el);
}
-function dayLabel(d, today) {
+function schedDay(d, today) {
const [y, m, dd] = d.split("-").map(Number), t = new Date(y, m - 1, dd), [ty, tm, td] = today.split("-").map(Number);
const diff = Math.round((t - new Date(ty, tm - 1, td)) / 864e5);
const wd = "日一二三四五六"[t.getDay()];
@@ -3475,7 +3477,7 @@ function drawSchedule(el) {
const v = S.sched || {}, items = v.items || [], today = v.today || "";
const row = (i, showDay) => {
const b = bot(i.bot) || {}, [cls, icon, word] = SCH_MARK[i.status] || ["", "clock", ""];
- const right = showDay ? (i.day === today ? "今天 " : dayLabel(i.day, today).replace(/(.)$/, "") + " ") + i.clock : word;
+ const right = showDay ? (i.day === today ? "今天 " : schedDay(i.day, today).replace(/(.)$/, "") + " ") + i.clock : word;
return ``;
};
let h = group("即將執行", (v.coming || []).map((i) => row(i, true)).join("") || `
接下來兩週沒有排定的事
`);
@@ -3485,7 +3487,7 @@ function drawSchedule(el) {
for (const d of days) {
const list = items.filter((i) => i.day === d);
if (!list.length && d !== today) continue;
- h += group(dayLabel(d, today), list.map((i) => row(i, false)).join("") || `
`;
const sc = el.scrollTop;
@@ -4233,13 +4235,27 @@ function saveFile(path, name, att, bot) {
$("b-filesave").innerHTML = ic("download", 20);
$("b-filesave").onclick = () => { if (S.file) saveFile(S.file.path, S.file.name, S.file.att, S.file.bot); };
const isDark = () => document.documentElement.dataset.theme === "dark" || (!document.documentElement.dataset.theme && matchMedia("(prefers-color-scheme: dark)").matches);
+// A drawn chart as a picture: an SVG kept as an SVG image — only ever shown in an , where it
+// runs nothing (safeBlob turns SVG into a download, so the picture showed broken).
+async function chartUrl(r) {
+ if (/^image\/svg\+xml/i.test(r.headers.get("Content-Type") || "")) return URL.createObjectURL(new Blob([await r.text()], {type: "image/svg+xml"}));
+ return URL.createObjectURL(await safeBlob(r));
+}
async function loadCharts() {
+ for (const el of document.querySelectorAll(".chart[data-mermaid]")) {
+ const src = el.dataset.mermaid; el.removeAttribute("data-mermaid");
+ try {
+ const r = await api(base() + "api/diagram", {json: {src, dark: isDark()}, raw: true});
+ if (!r.ok) throw new Error();
+ el.innerHTML = ``;
+ } catch (_) { el.innerHTML = `
${esc(src)}
`; }
+ }
for (const el of document.querySelectorAll(".chart[data-src]")) {
const src = el.dataset.src; el.removeAttribute("data-src");
try {
const r = await api(base() + src + (src.includes("?") ? "&" : "?") + "dark=" + (isDark() ? 1 : 0), {raw: true});
if (!r.ok) throw new Error();
- el.innerHTML = ``;
+ el.innerHTML = ``;
} catch (_) { el.innerHTML = `
這張圖畫不出來
`; }
}
}
@@ -4509,6 +4525,8 @@ function pageMd(text, id, rev) {
while (i < L.length && !L[i].trim().startsWith("```")) body.push(L[i++]);
i++;
if (lang === "mermaid" && id) { out.push(`
圖表載入中…
`); continue; }
+ // (A diagram in a chat: drawn by the brain from its words, as the computer draws it.)
+ if (lang === "mermaid") { out.push(`
圖表載入中…
`); continue; }
// ```details : folded under one quiet line (細節 without a title); the inside is the page's Markdown.
if (lang === "details") { const title = t.replace(/^```\s*details/i, "").trim() || "細節"; out.push(`${esc(title)}
${pageMd(body.join("\n"), id, rev)}
`); continue; }
if (lang === "chart") { const html = chartMd(body); if (html) { out.push(html); continue; } }
diff --git a/src/remote.rs b/src/remote.rs
index 54ae730..13f18e0 100644
--- a/src/remote.rs
+++ b/src/remote.rs
@@ -776,6 +776,19 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
out["latest"] = json!(cur.revision);
Resp::json(&out)
}
+ // A Mermaid diagram in a chat (a page's have their own path above): drawn here, the same
+ // way, from the words the phone holds (nothing else is read).
+ ("POST", ["api", "diagram"]) => {
+ let v = req.json();
+ let src = v["src"].as_str().unwrap_or("");
+ if src.trim().is_empty() || src.len() > 20_000 {
+ return Resp::error(400, "這張圖太大或是空的");
+ }
+ match crate::diagram::svg(src, v["dark"].as_bool().unwrap_or(false)) {
+ Ok(svg) => Resp::bytes("image/svg+xml", svg.into_bytes()),
+ Err(e) => Resp::error(422, &e),
+ }
+ }
("GET", ["api", "pages", id, "chart", n]) => {
let id: u64 = id.parse().unwrap_or(0);
let n: usize = n.parse().unwrap_or(0);
@@ -1364,7 +1377,7 @@ pub fn role_allows(role: &str, method: &str, path: &[&str]) -> bool {
// 大腦: the owner's other AnyBots showing this one's bots.
"mirror" => sync,
"owner" | "admin" => !device && !sync,
- "member" => matches!((method, path), ("GET", ["api", "state"]) | ("GET", ["api", "bots", _]) | ("GET", ["api", "pages", ..]) | ("GET", ["api", "file"]) | ("GET", ["api", "preview", ..]) | ("POST", ["api", "bots", _, "send" | "read" | "seen" | "upload"]) | ("POST", ["api", "voice", "transcribe" | "speech"])),
+ "member" => matches!((method, path), ("GET", ["api", "state"]) | ("GET", ["api", "bots", _]) | ("GET", ["api", "pages", ..]) | ("GET", ["api", "file"]) | ("GET", ["api", "preview", ..]) | ("POST", ["api", "bots", _, "send" | "read" | "seen" | "upload"]) | ("POST", ["api", "voice", "transcribe" | "speech"]) | ("POST", ["api", "diagram"])),
_ => false,
}
}
@@ -3620,6 +3633,29 @@ pub fn page(req: &Req) -> Resp {
#[cfg(test)]
mod tests {
+ /// The phone page is one file of plain scripts sharing one global scope: a function or a
+ /// top-level name declared twice silently replaces the first (a second `dayLabel`, for the
+ /// 日程, once replaced the chat's — every chat on the phone drew empty). Each name once.
+ #[test]
+ fn the_phone_page_names_each_thing_once() {
+ let mut seen: HashMap = HashMap::new();
+ for line in PAGE.lines() {
+ let l = line.strip_prefix("async ").unwrap_or(line);
+ let name = if let Some(r) = l.strip_prefix("function ") {
+ r.split('(').next()
+ } else if let Some(r) = l.strip_prefix("const ").or_else(|| l.strip_prefix("let ")) {
+ r.split([' ', '=']).next()
+ } else {
+ None
+ };
+ if let Some(n) = name.map(str::trim).filter(|n| !n.is_empty() && n.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')) {
+ *seen.entry(n.to_string()).or_default() += 1;
+ }
+ }
+ let twice: Vec<&String> = seen.iter().filter(|(_, n)| **n > 1).map(|(k, _)| k).collect();
+ assert!(twice.is_empty(), "declared more than once in mobile/index.html: {twice:?}");
+ }
+
/// 虛擬觸控板 (mobile/trackpad.js): a tap clicks, one finger moves the pointer, two fingers
/// scroll or right-click, double tap and slide drags, a long press right-clicks; the key
/// bar's modifiers hold for one key or lock. Run in node when it is there (the gestures are