diff --git a/FEATURES.md b/FEATURES.md index c3bb010..f629fff 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -1564,7 +1564,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) ### 頁面(Bot 做、Bot 持續更新的報告) - 你請 Bot 追蹤、整理、比較一件之後還會回來看的事(例如「幫我追蹤一下台灣 FSD 狀況」),它用 `write_page` 做成一頁:先寫現況,再寫細節和來源(附日期)。回答裡用「[標題](page:ID)」連到它,回答下面出現頁面卡片(標題、開頭幾行、頁面圖示、「頁面 · 更新時間」、最近一次更新了什麼),點一下打開。 -- 頁面可以放表格、Mermaid 圖表(圓餅、長條、折線、時間軸…白底卡節點、細灰連線),以及頁面專用的區塊:```stats 數字卡片(數字大字;值和備註開頭 ↑/+ 綠色、↓/− 紅色)、```steps 進度(✓ 完成、◉ 進行中、○ 還沒到)、```chart 原生圖表(bar 長條、line 折線、pie 圓餅;只畫淡水平參考線,長條自動由大到小排序——月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名;懸停看數值、拖曳平移、右鍵框選放大、雙擊還原,圖下自動附數據表,不會破版;多系列用 `| 1月 | 2月` 當表頭;手機看同一頁也畫同樣樣式的原生 SVG 圖)、`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]` 提示框。這些區塊在聊天裡也能用。所有圖表(含 Mermaid 圓餅)共用同一套低飽和六色色板,深淺兩主題各一組。 +- 頁面可以放表格、Mermaid 圖表(圓餅、長條、折線、時間軸…白底卡節點、細灰連線),以及頁面專用的區塊:```stats 數字卡片(數字大字,超過 10 個字的值縮成小一號;值和備註開頭 ↑/+ 綠色、↓/−/- 紅色,「+」「-」後面要緊接著東西才算,單獨一個「-」當作沒資料;電腦和手機同一套規則)、```steps 進度(✓ 完成、◉ 進行中、○ 還沒到)、```chart 原生圖表(bar 長條、line 折線、pie 圓餅;只畫淡水平參考線,長條自動由大到小排序——月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上、不畫 y 軸;多條線在線尾標系列名;懸停看數值、拖曳平移、右鍵框選放大、雙擊還原,圖下自動附數據表,不會破版;多系列用 `| 1月 | 2月` 當表頭;第一行可以是「圖型 標題」、只寫圖型(bar/line/pie 或 長條/折線/圓餅)或只寫標題,`#` 開頭的行是註解,`|---|` 分隔列略過,少填的格子當 0——電腦和手機同一套讀法;手機看同一頁也畫同樣樣式的原生 SVG 圖:照手機寬度畫、字不會縮小,折線和多系列長條有 y 軸數字,圖下同樣附數據表,只有一項的圓餅畫成整圓,圖例項目再多也都畫得到,負數的數字不會壓到下面的標籤)、`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]` 提示框。這些區塊在聊天裡也能用。所有圖表(含 Mermaid 圓餅)共用同一套低飽和六色色板,深淺兩主題各一組。 - 頁面是「閱讀排版」:內文排在置中的 720 像素欄位裡,行高 1.55 倍、段落有呼吸空間,不會貼著視窗邊緣;聊天室保持原本的緊湊排版。頁面上的數字表格(2–3 欄、資料不超過 8 列)在寬度夠時會自動左表右圖併排。 - 標題超過 4 個的頁面,頂部有「目錄」卡:每條標題可點,點了直接跳到那一節;上面的搜尋框可以篩標題(⌘F 光標進搜尋框,Esc 離開)。 - 寫頁面時 Bot 會選一種「種類」(data 數據分析/compare 比較評測/decision 決策備忘/howto 教學步驟/timeline 時間線/prose 長文/notes 筆記),第一屏跟著內容走:data 頁頂部放 2–4 張 KPI 數字卡(附漲跌,漲綠跌紅),compare/decision 頁先給一行「結論」卡;種類顯示在頁面標題和聊天卡片的列中。字段全部可省略——沒有數字就不硬湊卡片。 @@ -2041,7 +2041,7 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開) - 「這台 Mac」要先在設定裡打開才會出現。 - 操作方式:點一下是左鍵;長按是右鍵;點兩下是雙擊;「右鍵:開」之後每次點都是右鍵。 - 「⌨︎ 打字」可以打中文,會打進目前的視窗;還有 Enter、Esc、Tab、⌫ 和捲動按鈕。 -- 右上角頭像:傳送到其他裝置(只有擁有者有,見下面「傳送到其他裝置」)、開啟通知(只有用帳號登入時才有;iPhone 要先加入主畫面)、切換到別台 AnyBot、登出這支手機。 +- 右上角頭像:傳送到其他裝置(只有擁有者有,見下面「傳送到其他裝置」)、通知(開關、要通知哪幾種、送一則測試通知;開關顯示的是帳號伺服器上這支手機的狀態,按下去就照它顯示的開或關——帳號伺服器已經沒有這支手機的訂閱時顯示「關閉中」,打開會重新訂閱;連不上帳號伺服器時照這支手機上的設定,種類和測試等連上再改;直接連線的手機會說明收不到推播;iPhone 要先加入主畫面)、安裝成 App(還沒裝時才有)、切換到別台 AnyBot、登出這支手機。 - 手機做的事都交給電腦版原本的功能處理(同一套規則、同一份資料),不是另外寫一套。 - 團隊(用帳號伺服器分享時)權限跟以前一樣: - 成員只能聊天和附檔; diff --git a/docs/feature-map/pages.md b/docs/feature-map/pages.md index 23f754c..ffe96b4 100644 --- a/docs/feature-map/pages.md +++ b/docs/feature-map/pages.md @@ -4,7 +4,7 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 ## 子功能 -- 寫頁面:標題和整頁 Markdown(標題、表格、連結、Mermaid 圖),加上頁面區塊:```stats 數字卡(數字大字顯示;值和備註開頭是 ↑/+ 綠色、↓/− 紅色)、```steps 進度([x] 完成、[>] 進行中、[ ] 還沒到)、```chart 圖表(bar/line/pie,可以多系列;長條圖自動由大到小排序,月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上不畫 y 軸;多條線在線尾標系列名;手機也畫原生圖,樣式相同)、`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]` 提示框。 +- 寫頁面:標題和整頁 Markdown(標題、表格、連結、Mermaid 圖),加上頁面區塊:```stats 數字卡(數字大字顯示;值和備註開頭是 ↑/+ 綠色、↓/−/- 紅色,+ − - 後面要緊接著字才算,單獨一個「-」是沒資料、不上色;電腦和手機同一條規則)、```steps 進度([x] 完成、[>] 進行中、[ ] 還沒到)、```chart 圖表(bar/line/pie,可以多系列;長條圖自動由大到小排序,月份/年份等自有順序的標籤不排;單系列把數字直接標在圖上不畫 y 軸;多條線在線尾標系列名;圖下附數據表;第一行可以是「圖型 標題」、只寫圖型(bar/line/pie 或 長條/折線/圓餅)或只寫標題,`#` 開頭是註解,`|---|` 分隔列略過,少填的格子當 0;手機也畫原生圖,讀法和樣式相同:照手機寬度畫、字不縮小,折線和多系列長條有 y 軸數字,只有一項的圓餅是整圓,圖例再多項都畫得到)、`> [!NOTE]`/`[!TIP]`/`[!WARNING]`/`[!IMPORTANT]` 提示框。 - 種類(kind):data 數據分析、compare 比較評測、decision 決策備忘、howto 教學步驟、timeline 時間線、prose 長文、notes 筆記。種類決定第一屏:data 頁上面放 2–4 個 KPI 數字(kpis),compare/decision 頁先給一行「結論」(verdict)。沒給種類就是一般頁面。 - 更新:帶 id(或同一個標題)就換掉內容,上一版留著,最多留 10 版;note 寫這次改了什麼,頁面上顯示「這一版更新了:…」。內容一模一樣就不更新。 - 一直留著:跨聊天、跨例行任務都在。例行任務每一輪從新的開始,要接著上次做就先讀頁面。 @@ -21,7 +21,7 @@ Bot 把要追蹤、整理、比較的事寫成一頁,之後一直更新同一 ## 怎麼操作 - Bot:使用者要你追蹤、整理、比較、研究一件之後還會回來看的事,用 `write_page`(title、content;summary 一行現況;kind;kpis、verdict 只放真的資料;更新時帶 id 和 note),回覆裡用 [標題](page:ID) 連過去。更新前先 `read_page`(id 或 title)看現在的內容。要查的事同事可能已經在追,先 `list_pages`、`read_page` 讀它的,不要重查一遍。要定期追蹤就配一條例行任務([routines](routines.md)):每次讀頁面、查新消息,有實質進展才更新,沒有就說「沒有新消息」。這三個工具屬於「頁面」能力。 -- 驗證:請 Bot「幫我追蹤某件事,整理成一頁」,回覆下面要出現頁面卡片,右側面板 資料庫 › 頁面 要列出它;再請它更新,卡片寫「已更新」,打開頁面的「版本紀錄」有上一版。請另一個 Bot 改這一頁,要被擋下並說是誰的頁面。頁裡的 ```chart:長條要按大小排序(月份圖不排)、單系列數字在條上;手機同頁看同一張圖要是同一套樣式。自動測試:`cargo test pages::`、`cargo test appctl::`。 +- 驗證:請 Bot「幫我追蹤某件事,整理成一頁」,回覆下面要出現頁面卡片,右側面板 資料庫 › 頁面 要列出它;再請它更新,卡片寫「已更新」,打開頁面的「版本紀錄」有上一版。請另一個 Bot 改這一頁,要被擋下並說是誰的頁面。頁裡的 ```chart:長條要按大小排序(月份圖不排)、單系列數字在條上;手機同頁看同一張圖要是同一套樣式——字跟內文差不多大、折線有 y 軸數字、圖下有數據表、只寫 `pie` 當第一行也畫得出來、只有一項的圓餅是整圓。自動測試:`cargo test pages::`、`cargo test appctl::`。 ## 陷阱 diff --git a/docs/feature-map/phone.md b/docs/feature-map/phone.md index d02e55f..732a705 100644 --- a/docs/feature-map/phone.md +++ b/docs/feature-map/phone.md @@ -12,7 +12,7 @@ - 直接連線的裝置:用手機密碼登入過的手機和瀏覽器、最近使用時間,可以逐台「登出」。 - 手機可以做什麼:聊天、核准、看 Bot 的電腦一律可以;「從手機看這台電腦的螢幕並操作」和「裝置連結」預設關閉。 - 分享給團隊(登入後):把這台的 Bot 分享給帳號伺服器上的其他帳號,選成員或管理員([team](team.md))。 -- 手機頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止)、允許請求卡片(「一律允許」「允許一次」或「允許」、「拒絕」、「全部允許,之後直接操作」;卡片太高時卡在內面自己捲,輸入框不会被顶出螢幕)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定、傳送到其他裝置。 +- 手機頁面:Bot 清單(分區、工作中/等你)、聊天(附檔、拍照、語音輸入、插話、停止)、允許請求卡片(「一律允許」「允許一次」或「允許」、「拒絕」、「全部允許,之後直接操作」;卡片太高時卡在內面自己捲,輸入框不會被頂出螢幕)、問題卡、「需要處理」與接管、Bot 設定、例行任務(詳細頁有最近幾次執行和送出證據)、頁面、記憶、檔案預覽、Bot 的電腦畫面、設定、傳送到其他裝置。 - 通知:需要你允許、問你、需要你處理,你不在時做完事,例行任務暫停,收到傳來的檔案——推播到開了通知的手機,點了直接打開那個 Bot。每支手機自己選要哪幾種(需要你/做完了/例行任務暫停/收到傳來的檔案),可以送一則測試通知。通知的圖示是 AnyBot 的貓,Android 狀態列是貓的單色剪影;App 圖示上的數字是正在等你的 Bot。 - 像 App 一樣:加入主畫面後全螢幕、沒有網址列(瀏海、動態島、底部手勢條、橫放都避開);首頁會提示「把 AnyBot 裝成 App」(Android 直接安裝,iPhone 教你加入主畫面,可以關掉);換畫面會左右滑動;iPhone 主畫面 App 從左邊緣往右滑回上一頁。 @@ -32,6 +32,7 @@ - 推播只有用帳號登入的手機收得到,直接連線的沒有(帳戶選單 ›「通知」會這樣說);iPhone 要先「加入主畫面」、從主畫面打開才開得了通知。 - 「要通知我的事」全部關掉,這支手機就收不到 Bot 的通知(測試通知照樣會到);通知被手機系統擋下時,開關是灰的,要到手機的設定 › 通知打開。 +- 通知開關顯示的是帳號伺服器上這支手機的狀態,按下去就照它顯示的開或關:帳號伺服器已經沒有這支手機的訂閱(一個帳號最多 16 支,或推播服務退回)時顯示「關閉中」,打開會重新訂閱;暫時連不上帳號伺服器時,開關照這支手機上的設定,「要通知我的事」和測試通知等連上再用。 - App 圖示上的數字要手機支援(iPhone 主畫面 App、Android Chrome 安裝的 App);在瀏覽器分頁裡看不到。 - 電腦上的「Bot 做完或等你時通知」關掉,手機也收不到「需要你允許」「做完了」(例行任務暫停照樣推);而且只在你不在電腦前(視窗不在最前面,或 90 秒沒動)才推。 - 直接連線的連接埠預設 8793,被占用會往後找;照設定頁列出的網址打開。不要把它開放到網際網路,從外面連用帳號或 Tailscale。 diff --git a/mobile/index.html b/mobile/index.html index 94224fa..30981ef 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -455,9 +455,18 @@ textarea.field{min-height:96px;line-height:1.5} .page .chart img{width:100%;display:block} .page .chart .wait{padding:18px;font-size:13px;color:var(--text3)} /* ```chart 原生 SVG 卡(與桌面版圖表卡同款) */ -.page .chartcard{margin:12px 0;border:.5px solid var(--line);border-radius:12px;background:var(--elev);padding:12px 12px 8px} -.page .chartcard .ct2{font-size:14px;font-weight:600;margin:2px 2px 6px} -.page .chartcard svg{width:100%;height:auto;display:block} +.chartcard{margin:12px 0;border:.5px solid var(--line);border-radius:12px;background:var(--elev);padding:12px 12px 8px;max-width:100%} +.bub .chartcard,.talk .chartcard{margin:6px 0;padding:8px 8px 6px} +.chartcard .ct2{font-size:14px;font-weight:600;line-height:1.4;margin:2px 2px 6px} +.chartcard svg{width:100%;height:auto;display:block;margin:0 auto} +/* The numbers under the chart (desktop: the same table). */ +.chartcard .ctab{overflow-x:auto;margin:8px 0 2px} +.chartcard .ctab table{border-collapse:collapse;width:100%;font-size:12.5px;line-height:1.45} +.chartcard .ctab th{font-weight:400;font-size:11.5px;color:var(--text3);background:none;border:0;border-bottom:.5px solid var(--line);padding:3px 6px;text-align:right;white-space:nowrap} +.chartcard .ctab td{border:0;padding:3px 6px;text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;color:var(--text)} +.chartcard .ctab th:first-child,.chartcard .ctab td:first-child{text-align:left} +.chartcard .ctab td:first-child{color:var(--text2);white-space:normal;overflow-wrap:anywhere} +.chartcard .ctab tbody tr:nth-child(even) td{background:var(--hover)} .page li.task{list-style:none;margin-left:-18px} /* ---- this Mac's screen ---- */ @@ -2619,101 +2628,217 @@ function inl(s) { const CALL = {note: "說明", tip: "提示", warning: "注意", important: "重要"}; // Markdown as the desktop draws it (pages and chat replies): headings, lists and tasks, tables, // quotes and call-outs, code, Mermaid charts (pages: drawn by AnyBot), ```stats and ```steps. -/* ```chart 頁面板塊 → 原生 SVG,和桌面版同一套規則:長條依大小排序(標籤本身有順序 - (月/季/年/數字)時不排);單系列把數字直接標在條上(不畫 y 軸);多線把系列名放在 - 線尾;只留淡水平參考線;色板用 --cat1..6(同桌面版 theme.rs)。 */ -function chartMd(lines) { - const cells = (l) => l.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim()); - const num = (v) => Math.abs(v) >= 10000 ? Math.round(v).toLocaleString("en-US") : String(Math.round(v * 100) / 100); - const clean = (s) => Number(String(s).replace(/[,\s]/g, "").replace(/[%元個次人台]$/, "")); - const rows = lines.map((l) => l.trim()).filter(Boolean); - if (!rows.length) return ""; - let kind = "bar", title = "", body = rows; - const m = rows[0].match(/^(bar|line|pie)\s+(.*)$/i); - if (m) { kind = m[1].toLowerCase(); title = m[2]; body = rows.slice(1); } - let labels = [], series = []; - if (body[0] && body[0].trim().startsWith("|")) { - labels = cells(body[0]); - for (const r of body.slice(1)) { const c = cells(r); const v = c.slice(1).map(clean); if (!c[0] || v.length !== labels.length || v.some((x) => !isFinite(x))) return ""; series.push([c[0], v]); } - } else { - const vals = []; - for (const r of body) { const c = cells(r); const v = clean(c[1]); if (c.length < 2 || !c[0] || !isFinite(v)) return ""; labels.push(c[0]); vals.push(v); } - series = [["", vals]]; +/* ```chart → 原生 SVG,和桌面版同一套規則(解析照 src/pages.rs chart(),畫法照 + src/app/markdown_ui.rs md_chart_card):長條依大小排序(標籤本身有順序(月/季/年/數字) + 時不排);單系列長條把數字直接標在條上、不畫 y 軸,折線和多系列長條有 y 軸;多條線在 + 線尾標系列名;只留淡水平參考線;圖下附數據表;色板用 --cat1..6(同 theme.rs)。 + 圖照手機畫面的寬度畫:圖裡寫 13 px 的字,螢幕上就是 13 px(不會縮成 6 px)。 */ +const CHART_KINDS = {bar: "bar", long: "bar", "長條": "bar", line: "line", "折線": "line", pie: "pie", "圓餅": "pie"}; +const CHART_TEMPORAL = ["月", "年", "週", "周", "季", "Q1", "Q2", "Q3", "Q4", "q1", "q2", "q3", "q4", "W1", "W2", "W3", "W4", "今", "上週", "上季", "去年", "今年", "明年"]; +// A cell's words: a link becomes its text; ** ` __ go (pages.rs plain()). +const chartPlain = (s) => String(s).replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").split("**").join("").split("`").join("").split("__").join(""); +// A number with spaces, thousands commas, % and trailing units stripped (pages.rs num()); null when it is not one. +function chartValue(s) { + const t = String(s).replace(/[ \t\n\r\f,]/g, "").replace(/[%元個次人台]+$/, ""); + return /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(t) && isFinite(+t) ? +t : null; +} +// ```chart's text → {kind, title, labels, series: [[name, values]]}, or null (pages.rs chart()). +function chartParse(lines) { + let kind = "bar", title = "", labels = [], series = [], header = false; + for (const line of lines.map((l) => String(l).trim()).filter((l) => l && !l.startsWith("#"))) { + // The first line, before any data: [kind] [title] — or only a kind, or only a title. + if (!title && !labels.length && !series.length && !line.includes("|")) { + const sp = line.search(/\s/), k = CHART_KINDS[(sp < 0 ? line : line.slice(0, sp)).toLowerCase()]; + if (k) { kind = k; title = sp < 0 ? "" : line.slice(sp + 1).trim(); } else title = line; + continue; + } + const cells = line.split("|").map((c) => chartPlain(c.trim())); + if (cells.length > 1 && line.endsWith("|")) cells.pop(); // (a closing | adds no empty column) + // `| 1月 | 2月` (first cell empty): the labels of a multi-series chart. + if (!cells[0] && !labels.length) { labels = cells.slice(1); header = true; continue; } + // A row: its name and the cells that are numbers (|---| and words are skipped). + const vals = cells.slice(1).map(chartValue); + if (cells[0] && vals.some((v) => v !== null)) series.push([cells[0], vals.filter((v) => v !== null)]); } - const n = labels.length, ns = series.length, single = ns === 1; - if (!n || !ns || labels.length * (kind === "pie" ? 1 : 1) === 0) return ""; - const W = 620, H = 240, L = 10, R0 = 10; - const nat = labels.every((l) => /月|年|周|週|日|季|Q[1-4]|q[1-4]|W[1-4]|今|去年|今年|明年/.test(l) || /^\d/.test(l.trim())); - const tot = (i) => series.reduce((a, s) => a + (s[1][i] || 0), 0); - const idx = labels.map((_, i) => i); - if (kind === "bar" && n > 1 && !nat) idx.sort((a, b) => tot(b) - tot(a) || a - b); - const esc2 = (s) => esc(String(s)); - const cut7 = (s) => (String(s).length > 7 ? String(s).slice(0, 7) + "…" : String(s)); - const cat = (i) => `var(--cat${i % 6 + 1})`; - const svg = []; - if (kind === "pie") { - const multi = ns > 1; - const pl = multi ? series.map((s) => s[0]) : labels; - const pv = multi ? series.map((s) => Math.max(0, s[1][0] || 0)) : series[0][1].map((v) => Math.max(0, v)); - const order = pl.map((_, i) => i).sort((a, b) => pv[b] - pv[a]); - const total = pv.reduce((a, b) => a + b, 0); - if (total <= 0) return ""; - const cx = 92, cy = H / 2, Rr = 84; - let a0 = -Math.PI / 2; - order.forEach((i, k) => { - const sweep = pv[i] / total * Math.PI * 2; - if (sweep > 0) { - const a1 = a0 + sweep, big = sweep > Math.PI ? 1 : 0; - svg.push(`${esc2(pl[i])} · ${num(pv[i])} (${Math.round(pv[i] / total * 100)}%)`); - } - a0 += sweep; + // The plain 標籤 | 數值 form: each row became a one-value series — fold them into one. + if (!labels.length && series.length && series.every((s) => s[1].length === 1) && kind !== "pie") { + labels = series.map((s) => s[0]); + series = [["", series.map((s) => s[1][0])]]; + } + const n = Math.max(labels.length, ...series.map((s) => s[1].length)); + if (!series.length || !n) return null; + labels = Array.from({length: n}, (_, i) => labels[i] || String(i + 1)); + // A missing cell is 0; a series of only zeros is left out. + series = series.map(([s, v]) => [s, Array.from({length: n}, (_, i) => v[i] ?? 0)]).filter((s) => s[1].some((x) => x !== 0)); + if (!series.length) return null; + // A pie of one plain row is that row's slice (not a slice called 「1」). + if (kind === "pie" && !header && series.length === 1 && n === 1) labels = [series[0][0]]; + return {kind, title, labels, series}; +} +const chartNum = (v) => Math.abs(v) >= 10000 ? Math.round(v).toLocaleString("en-US") : String(Math.round(v * 100) / 100); +// About how wide a text is (CJK and full-width ≈ 1 em, the rest ≈ 0.6 em). +const chartTextW = (s, fs) => [...String(s)].reduce((a, ch) => a + (ch.codePointAt(0) >= 0x2e80 ? fs : fs * 0.6), 0); +const chartCut7 = (s) => { const cs = [...String(s)]; return cs.length > 7 ? cs.slice(0, 7).join("") + "…" : String(s); }; +// A text cut with … to fit a width. +function chartFit(s, w, fs) { + if (chartTextW(s, fs) <= w) return String(s); + const cs = [...String(s)]; + while (cs.length > 1 && chartTextW(cs.join("") + "…", fs) > w) cs.pop(); + return cs.join("") + "…"; +} +const chartCol = (i) => `var(--cat${i % 6 + 1})`; +// Round steps for the value axis, 0 always inside: 0 · 50 · 100 · 150. +function chartTicks(lo, hi) { + const raw = (hi - lo) / 4 || 1, mag = 10 ** Math.floor(Math.log10(raw)); + const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw * (1 - 1e-9)); + const out = []; + for (let k = Math.floor(lo / step + 1e-9); k <= Math.ceil(hi / step - 1e-9) && out.length < 12; k++) out.push(+(k * step).toPrecision(12)); + return out.length >= 2 && isFinite(step) ? out : [lo, hi]; +} +// Bar and line. +function chartPlot(c, W) { + const FS = 13, line = c.kind === "line", single = c.series.length === 1, labelBars = single && !line; + const n = c.labels.length, ns = c.series.length, svg = []; + // A bar chart shows ranking, so bars go big → small — unless the labels carry their own order. + const temporal = (s) => CHART_TEMPORAL.some((k) => s.includes(k)) || /^\d/.test(s.trim()); + const order = c.labels.map((_, i) => i); + if (!line && n >= 2 && !c.labels.every(temporal)) { + const tot = (k) => c.series.reduce((a, s) => a + (s[1][k] || 0), 0); + order.sort((a, b) => tot(b) - tot(a) || a - b); + } + const all = c.series.flatMap((s) => s[1]); + const vmin = Math.min(0, ...all), vmax = Math.max(0, ...all); + const ticks = chartTicks(vmin, vmax), lo = ticks[0], hi = ticks[ticks.length - 1]; + // The value axis on the left — except a single series of bars, which carries its own numbers. + const L = labelBars ? 4 : Math.ceil(Math.max(...ticks.map((t) => chartTextW(chartNum(t), FS - 1)))) + 10; + // Several lines say their names at their ends: room on the right for them. + const ends = line && !single; + const R = ends ? Math.min(Math.ceil(Math.max(...c.series.map((s) => chartTextW(chartCut7(s[0]), FS)))) + 12, Math.round(W * 0.3)) : 6; + // Several series of bars: a legend on top (wrapping). + let legendH = 0; + if (!single && !line) { + let x = 4, y = FS + 1; + c.series.forEach((s, si) => { + const name = chartFit(s[0], W * 0.45, FS), w = Math.ceil(13 + chartTextW(name, FS) + 14); + if (x > 4 && x + w > W) { x = 4; y += FS + 6; } + svg.push(`${esc(name)}`); + x += w; }); - const rows2 = order.map((i, k) => `${esc2(cut7(pl[i]))} · ${num(pv[i])} (${Math.round(pv[i] / total * 100)}%)`).join(""); - svg.push(rows2); - } else { - const valsAll = series.flatMap((s) => s[1]); - const vmax = Math.max(0, ...valsAll), vmin = Math.min(0, ...valsAll), span = (vmax - vmin) || 1; - const padT = (single ? 26 : 40), padB = 30; - const R = kind === "line" && !single ? 130 : 12; - const Y = (v) => padT + (H - padT - padB) * (1 - (v - vmin) / span); - const Xc = (k) => L + (W - L - R) * (n === 1 ? 0.5 : k / (n - 1)); - // 只留淡水平參考線(max、mid、0),不畫框不畫直格線。 - const marks = [vmax, vmin + (vmax - vmin) / 2, 0].filter((v, i, a) => a.findIndex((u) => Math.abs(u - v) < 1e-9) === i); - for (const v of marks) if (!(v === vmin && vmin < 0)) svg.push(``); - if (kind === "bar") { - const gw = (W - L - R) / n, bw = Math.min(56, gw * 0.66 / ns); - idx.forEach((i, k) => { - series.forEach((s, si) => { - const v = s[1][i], cx = L + gw * (k + 0.5) + (si - (ns - 1) / 2) * (bw + 2); - const y0 = Y(0), yv = Y(v); - svg.push(`${esc2(labels[i])}${s[0] ? " · " + esc2(s[0]) : ""} · ${num(v)}`); - }); - svg.push(`${esc2(cut7(labels[i]))}`); - }); - if (single) idx.forEach((i, k) => { - const v = series[0][1][i]; - const cx = L + gw * (k + 0.5), yv = Y(v); - svg.push(`${num(v)}`); - }); - if (!single) series.forEach((s, si) => { - const lx = L + si * 110; - svg.push(`${esc2(cut7(s[0]))}`); - }); - } else { - idx.forEach((i, k) => svg.push(`${esc2(cut7(labels[i]))}`)); - series.forEach((s, si) => { - const pts = idx.map((i, k) => [Xc(k), Y(s[1][i])]); - svg.push(``); - pts.forEach((p, k) => svg.push(`${esc2(labels[idx[k]])}${s[0] ? " · " + esc2(s[0]) : ""} · ${num(s[1][idx[k]])}`)); - if (!single && s[0]) { - const last = pts[pts.length - 1]; - svg.push(`${esc2(cut7(s[0]))}`); - } + legendH = y + 6; + } + const top = Math.max(labelBars ? FS + 10 : 10, legendH + 10); + const bot = top + Math.round(Math.min(200, Math.max(140, W * 0.5))); + // A negative bar's number goes under it: room for that above the labels underneath. + const negRoom = labelBars && vmin < 0 ? FS + 6 : 0; + const H = bot + negRoom + FS + 16; + const Y = (v) => top + (bot - top) * (hi - v) / (hi - lo); + for (const t of ticks) { + const y = Y(t).toFixed(1); + svg.push(``); + if (!labelBars) svg.push(`${chartNum(t)}`); + } + const x0 = L + (line ? 10 : 0), x1 = W - R - (line ? 10 : 0), gw = (x1 - x0) / n; + const X = (k) => line ? (n === 1 ? (x0 + x1) / 2 : x0 + (x1 - x0) * k / (n - 1)) : x0 + gw * (k + 0.5); + const slot = line ? (n === 1 ? x1 - x0 : (x1 - x0) / (n - 1)) : gw; + // A text centred on x, kept inside the picture (the first and last labels were cut in half). + const inside = (x, w) => Math.min(Math.max(x, w / 2 + 2), W - w / 2 - 2).toFixed(1); + // The labels underneath: every one that fits (crowded: every 2nd, 3rd…) — counting the ones + // pulled in from the edges, so no two touch. + const xl = order.map((i) => chartCut7(c.labels[i])), xw = xl.map((s) => chartTextW(s, FS)), xx = xl.map((_, k) => +inside(X(k), xw[k])); + const clash = (e) => { for (let k = e; k < n; k += e) if (xx[k] - xw[k] / 2 < xx[k - e] + xw[k - e] / 2 + 6) return true; return false; }; + let every = Math.max(1, Math.ceil((Math.max(...xw) + 8) / slot)); + while (every < n && clash(every)) every++; + xl.forEach((s, k) => { + if (!(k % every)) svg.push(`${esc(s)}`); + }); + if (!line) { + const bw = Math.max(2, Math.min(single ? 44 : 28, (gw * 0.7 - 2 * (ns - 1)) / ns)), y0 = Y(0); + order.forEach((i, k) => c.series.forEach((s, si) => { + const v = s[1][i], cx = X(k) + (si - (ns - 1) / 2) * (bw + 2), yv = Y(v); + svg.push(`${esc(c.labels[i])}${s[0] ? " · " + esc(s[0]) : ""} · ${chartNum(v)}`); + })); + if (labelBars) { + const vs = order.map((i) => chartNum(c.series[0][1][i])); + const vevery = Math.max(1, Math.ceil((Math.max(...vs.map((s) => chartTextW(s, FS))) + 4) / gw)); + order.forEach((i, k) => { + if (k % vevery) return; + const v = c.series[0][1][i], yv = Y(v); + svg.push(`${vs[k]}`); }); } + } else { + const names = []; + c.series.forEach((s, si) => { + const pts = order.map((i, k) => [X(k), Y(s[1][i])]); + svg.push(``); + pts.forEach((p, k) => svg.push(`${esc(c.labels[order[k]])}${s[0] ? " · " + esc(s[0]) : ""} · ${chartNum(s[1][order[k]])}`)); + const last = pts[pts.length - 1]; + if (ends && s[0].trim()) names.push({si, x: last[0] + 7, y: last[1] + 4}); + }); + // Names at the line ends, pushed apart when two lines end close together. + names.sort((a, b) => a.y - b.y); + for (let j = 1; j < names.length; j++) names[j].y = Math.max(names[j].y, names[j - 1].y + FS + 2); + const over = names.length ? Math.max(0, names[names.length - 1].y - (bot + 4)) : 0; + names.forEach((e) => svg.push(`${esc(chartFit(chartCut7(c.series[e.si][0]), W - e.x - 2, FS))}`)); } - return `
${title ? `
${esc2(title)}
` : ""}${svg.join("")}
`; + return {svg: svg.join(""), H}; } +// Pie: slices of the positive values in their own order; the legend says value and share. +function chartPie(c, W) { + const FS = 13, one = c.series.length === 1; + const names = one ? c.labels : c.series.map((s) => s[0]); + const vals = (one ? c.series[0][1] : c.series.map((s) => s[1][0])).map((v) => Math.max(0, v)); + const total = vals.reduce((a, b) => a + b, 0); + if (total <= 0) return {svg: "", H: 0}; + const shown = vals.map((_, i) => i).filter((i) => vals[i] > 0); + const share = (i) => Math.round(vals[i] / total * 100); + const legend = shown.map((i) => `${chartCut7(names[i])} · ${chartNum(vals[i])} (${share(i)}%)`); + // (A legend row: the colour, a gap, the words, a little room on the right.) + const legW = Math.max(...legend.map((s) => chartTextW(s, FS))) + 20, rowH = FS + 9; + // The legend beside the pie when both fit; under it on a narrow phone. Every row is inside. + const side = W >= 144 + legW; + const r = Math.floor(side ? Math.max(60, Math.min(84, (W - legW - 24) / 2)) : Math.min(84, (W - 16) / 2)); + const H = Math.ceil(side ? Math.max(2 * r + 16, shown.length * rowH + 16) : 2 * r + 24 + shown.length * rowH + 4); + const cx = side ? r + 8 : W / 2, cy = side ? H / 2 : r + 8, svg = []; + const pt = (a) => `${(cx + r * Math.cos(a)).toFixed(2)},${(cy + r * Math.sin(a)).toFixed(2)}`; + let a0 = -Math.PI / 2; + for (const i of shown) { + const sweep = vals[i] / total * Math.PI * 2, tip = `${esc(names[i])} · ${chartNum(vals[i])} (${share(i)}%)`; + // One slice (nearly) all the way round is a circle: an arc that ends where it starts draws nothing. + if (sweep > Math.PI * 2 - 1e-3) svg.push(`${tip}`); + else svg.push(`${tip}`); + a0 += sweep; + } + const lx = side ? Math.round(2 * r + 24) : 8, ly = side ? cy - (shown.length - 1) * rowH / 2 : 2 * r + 24; + shown.forEach((i, k) => { + const y = ly + k * rowH; + svg.push(`${esc(chartFit(legend[k], W - lx - 18, FS))}`); + }); + return {svg: svg.join(""), H}; +} +// The numbers behind the chart, under it (desktop: the same table) — readable without hovering. +function chartTable(c) { + const pie = c.kind === "pie", one = c.series.length === 1; + const labels = !pie || one ? c.labels : c.series.map((s) => s[0]); + const vals = !pie || one ? c.series[0][1] : c.series.map((s) => s[1][0]); + const total = Math.max(1e-9, vals.reduce((a, b) => a + b, 0)); + const cols = pie ? ["項目", "數值", "佔比"] : one ? ["項目", c.series[0][0].trim() || "數值"] : ["項目", ...c.series.map((s) => s[0])]; + const cell = (i, ci) => pie && ci === 2 ? Math.round(vals[i] / total * 100) + "%" : chartNum(pie || one ? vals[i] : c.series[ci - 1][1][i]); + return `
${cols.map((h) => ``).join("")}${labels.map((l, i) => `${cols.slice(1).map((_, k) => ``).join("")}`).join("")}
${esc(h)}
${esc(l)}${cell(i, k + 1)}
`; +} +function chartMd(lines) { + const c = chartParse(lines); + if (!c) return ""; + // Drawn at this phone's width (and grows at most a third when the phone turns sideways). + const vw = typeof innerWidth === "number" && innerWidth > 0 ? innerWidth : 390; + const W = Math.round(Math.min(700, Math.max(296, vw - 64))); + const {svg, H} = c.kind === "pie" ? chartPie(c, W) : chartPlot(c, W); + const pic = H ? `${svg}` : ""; + return `
${c.title ? `
${esc(c.title)}
` : ""}${pic}${chartTable(c)}
`; +} +// ```stats: ↑/+ green, ↓/− red. The same rule as src/pages.rs stat_trend: + − - count only with +// something right after them (「-12%」 is down; a lone 「-」 is "no data", 「- 待補」 is neutral). +const trend = (t) => /^\s*(↑|\+(?=\S))/.test(t) ? " up" : /^\s*(↓|[−-](?=\S))/.test(t) ? " dn" : ""; function pageMd(text, id, rev) { const L = String(text || "").replace(/\r/g, "").split("\n"); const out = []; let i = 0, chart = 0; @@ -2729,7 +2854,7 @@ function pageMd(text, id, rev) { if (lang === "mermaid" && id) { out.push(`
圖表載入中…
`); continue; } if (lang === "chart") { const html = chartMd(body); if (html) { out.push(html); continue; } } if (lang === "stats") { - const tiles = body.map(cells).filter((c) => c.length >= 2 && c[0]).map((c) => { const dir = (t) => /^[↑+]/.test(t) ? " up" : /^[↓−-]/.test(t) ? " dn" : ""; return `
${inl(c[0])}
${inl(c[1])}
${c[2] ? `
${inl(c[2])}
` : ""}
`; }); + const tiles = body.map(cells).filter((c) => c.length >= 2 && c[0]).map((c) => `
${inl(c[0])}
${inl(c[1])}
${c[2] ? `
${inl(c[2])}
` : ""}
`); if (tiles.length) { out.push(`
${tiles.join("")}
`); continue; } } if (lang === "steps") { @@ -3001,41 +3126,56 @@ async function notifySheet() { const why = !S.relay ? "直接連線(同一個網路)收不到推播:用 AnyBot 帳號登入的手機才收得到。" : navigator.standalone === false ? "iPhone 要先按分享 › 加入主畫面,從主畫面打開 AnyBot 才能開通知。" : "這個瀏覽器不支援通知。"; sheet("通知", [], `
${why}
`); return; } + // The switch shows what the account server has for this phone, and pressing it does what it + // shows: a subscription the phone kept but the server dropped (too many phones, an address the + // push service gave up on) reads 「關閉中」, and pressing it subscribes again. Server not + // reachable: the phone's own subscription, and the kinds and the test wait. + const all = KINDS.map((k) => k[0]); const sub = await pushSub().catch(() => null); - let st = {on: false, kinds: KINDS.map((k) => k[0])}; - if (sub) st = await api("relay/push/state", {json: {endpoint: sub.endpoint}}).catch(() => st); + let st = {on: false, kinds: all}, unknown = false; + if (sub) st = await api("relay/push/state", {json: {endpoint: sub.endpoint}}).catch(() => { unknown = true; return {on: true, kinds: all}; }); const blocked = Notification.permission === "denied"; let h = `
` + item({icon: "bell", k: "這支手機的通知", v: blocked ? "被系統擋下了:到手機的設定 › 通知 › AnyBot 打開" : st.on ? "Bot 需要你時,會跳出通知" : "關閉中", sw: st.on && !blocked, swdata: 'data-push="1"', disabled: blocked}) + `
`; - if (st.on) { + if (unknown) h += `
暫時連不上帳號伺服器:開關照這支手機上的設定;要通知哪幾種、送測試通知,等連上再試。
`; + else if (st.on) { h += `
要通知我的事
` + KINDS.map(([k, n, v]) => item({k: n, v, sw: st.kinds.includes(k), swdata: `data-kind="${k}"`})).join("") + `
`; h += `
`; } h += `
通知的圖示是 AnyBot 的貓;App 圖示上的數字是正在等你的 Bot。${navigator.standalone ? "聲音和橫幅樣式在 iPhone 的設定 › 通知 › AnyBot 調整。" : ""}
`; const el = sheet("通知", [], h); + // This phone's subscription: the account server forgets it (best effort), then the phone. + const drop = async (s) => { if (!s) return; await api("relay/push/unsubscribe", {json: {endpoint: s.endpoint}}).catch(() => {}); await s.unsubscribe().catch(() => {}); }; const on = el.querySelector("[data-push]"); if (on) on.onchange = async () => { + const want = on.checked; on.disabled = true; try { - const r = await navigator.serviceWorker.register("sw.js"); await navigator.serviceWorker.ready; - const old = await r.pushManager.getSubscription(); - if (old) { await api("relay/push/unsubscribe", {json: {endpoint: old.endpoint}}).catch(() => {}); await old.unsubscribe(); if (navigator.clearAppBadge) navigator.clearAppBadge().catch(() => {}); toast("已關閉通知"); } - else { + if (!want) { + await drop(await pushSub().catch(() => null)); + if (navigator.clearAppBadge) navigator.clearAppBadge().catch(() => {}); + toast("已關閉通知"); + } else { if (await Notification.requestPermission() !== "granted") { toast("沒有允許通知(可在手機的設定裡打開)"); notifySheet(); return; } + const r = await navigator.serviceWorker.register("sw.js"); await navigator.serviceWorker.ready; const {key} = await api("relay/push/key"); + // A subscription left on the phone (the server no longer has it, or it was made for + // another key) never rings: start a fresh one. + await drop(await r.pushManager.getSubscription()); const s2 = await r.pushManager.subscribe({userVisibleOnly: true, applicationServerKey: keyBytes(key)}); - await api("relay/push/subscribe", {json: {...s2.toJSON(), kinds: st.kinds}}); toast("已開啟通知"); + await api("relay/push/subscribe", {json: {...s2.toJSON(), kinds: all}}); toast("已開啟通知"); } } catch (e) { toast("通知設定失敗:" + e.message); } notifySheet(); }; + const mine = async () => { const s2 = await pushSub(); if (!s2) throw new Error("這支手機還沒開通知"); return s2; }; el.querySelectorAll("[data-kind]").forEach((c) => c.onchange = async () => { const kinds = [...el.querySelectorAll("[data-kind]")].filter((x) => x.checked).map((x) => x.dataset.kind); - try { const s2 = await pushSub(); await api("relay/push/kinds", {json: {endpoint: s2.endpoint, kinds}}); toast(kinds.length ? "已更新" : "這支手機現在不會收到 Bot 的通知"); } + try { const s2 = await mine(); await api("relay/push/kinds", {json: {endpoint: s2.endpoint, kinds}}); toast(kinds.length ? "已更新" : "這支手機現在不會收到 Bot 的通知"); } catch (e) { toast("沒有存到:" + e.message); c.checked = !c.checked; } }); const test = el.querySelector("#push-test"); if (test) test.onclick = async () => { - try { const s2 = await pushSub(); await api("relay/push/test", {json: {endpoint: s2.endpoint}}); toast("送出了,幾秒內會跳出來"); } + try { const s2 = await mine(); await api("relay/push/test", {json: {endpoint: s2.endpoint}}); toast("送出了,幾秒內會跳出來"); } catch (e) { toast("沒有送出:" + e.message); } }; } @@ -3052,7 +3192,8 @@ window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); S.in window.addEventListener("appinstalled", () => { S.installPrompt = null; installHint(); toast("已安裝,之後從主畫面打開 AnyBot"); }); async function installApp() { if (S.installPrompt) { const p = S.installPrompt; S.installPrompt = null; p.prompt(); await p.userChoice.catch(() => {}); installHint(); return; } - sheet("加入主畫面", [], `
1. 按 Safari 下方的分享按鈕 ${ic("share", 15)}\n2. 選「加入主畫面」\n3. 之後從主畫面的 AnyBot 打開:全螢幕、沒有網址列,也能開通知。
`); + // (.note is a flex row: the steps are one block inside it, so the share icon stays in its line.) + sheet("加入主畫面", [], `
1. 按 Safari 下方的分享按鈕 ${ic("share", 15)}\n2. 選「加入主畫面」\n3. 之後從主畫面的 AnyBot 打開:全螢幕、沒有網址列,也能開通知。
`); } function installHint() { const el = $("install"); if (!el) return; diff --git a/mobile/manifest.webmanifest b/mobile/manifest.webmanifest index 056d96c..d81b8b6 100644 --- a/mobile/manifest.webmanifest +++ b/mobile/manifest.webmanifest @@ -9,8 +9,8 @@ "scope": "./", "display": "standalone", "orientation": "any", - "background_color": "#121212", - "theme_color": "#121212", + "background_color": "#faf9f6", + "theme_color": "#faf9f6", "categories": ["productivity", "utilities"], "icons": [ {"src": "icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any"},