3486 lines
279 KiB
HTML
3486 lines
279 KiB
HTML
<!doctype html>
|
||
<html lang="zh-Hant">
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content">
|
||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||
<meta name="mobile-web-app-capable" content="yes">
|
||
<meta name="color-scheme" content="light dark">
|
||
<meta name="format-detection" content="telephone=no">
|
||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||
<meta name="apple-mobile-web-app-title" content="AnyBot">
|
||
<meta name="theme-color" content="#1e1d1b" media="(prefers-color-scheme: dark)">
|
||
<meta name="theme-color" content="#faf9f6" media="(prefers-color-scheme: light)">
|
||
<link rel="manifest" href="manifest.webmanifest">
|
||
<link rel="icon" href="icon.svg" type="image/svg+xml">
|
||
<link rel="icon" href="icon-192.png" type="image/png" sizes="192x192">
|
||
<link rel="apple-touch-icon" href="icon-180.png">
|
||
<title>AnyBot</title>
|
||
<style>
|
||
/* The desktop app's colours (src/theme.rs, from the original's stylesheet), as on a phone: the
|
||
sidebar is the home, the chat is pushed on top, 對話詳細資訊 and 設定 are pushed on that. */
|
||
:root{
|
||
--pane:#faf9f6;--chrome:#f7f6f2;--side:#f2f0eb;--elev:#fff;--hover:#25221f0d;--active:#25221f15;
|
||
--primary:#25221f;--on-primary:#fefcfa;--text:#25221f;--text2:#25221fb0;--text3:#25221f85;--text4:#25221f66;
|
||
--line:#25221f1a;--line2:#25221f14;--focus:#c06244;--accent:#c06244;--accent-ink:#a84f33;
|
||
--danger:#b42a2a;--ok:#2e7d3f;--warn:#b07f2e;
|
||
--bubble-user:#25221f;--bubble-user-ink:#fefcfa;--bubble-bot:#25221f0d;--card:#fff;--attention:#d9a441;--attention-bg:#f6ecd9;
|
||
--spec:#ffffff59;--shadow:0 2px 8px -1px #241f1a0d,0 1px 2px #241f1a08,0 0 0 1px #e0ddd40a;
|
||
/* 圖表色板(與桌面版 theme.rs chart_cat 同序): 一個暖家族轉色相,低飽和 */
|
||
--cat1:#c06244;--cat2:#4f6f92;--cat3:#3e7c77;--cat4:#8a7a33;--cat5:#8a5a78;--cat6:#7a746c;
|
||
--grid:#25221f10;--up:#2e7d3f;
|
||
--font:-apple-system,BlinkMacSystemFont,"SF Pro Text","PingFang TC","Noto Sans TC","Segoe UI",system-ui,sans-serif;
|
||
--mono:ui-monospace,SFMono-Regular,Menlo,monospace;
|
||
--safe-b:env(safe-area-inset-bottom);--safe-t:env(safe-area-inset-top);
|
||
/* One design spec for desktop and phone (src/theme.rs has the same names and numbers). */
|
||
--fs-caption:12px;--fs-small:13px;--fs-ui:14px;--fs-read:16px;--fs-h3:18px;--fs-h2:22px;--fs-h1:28px;
|
||
--lh-read:1.7;
|
||
--sp-1:4px;--sp-2:8px;--sp-3:12px;--sp-4:16px;--sp-5:24px;--sp-6:32px;
|
||
--r-s:6px;--r-m:10px;--r-l:14px;
|
||
--font-read:"Noto Serif TC","Songti TC","Source Han Serif TC","Noto Serif CJK TC",serif;
|
||
/* Floating shadows, the sheet's backdrop, the black stage under a screen, words on a strong fill. */
|
||
--shade:#00000024;--scrim:#00000066;--stage:#000;--on-stage:#ffffff99;--on-color:#fff;
|
||
}
|
||
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
|
||
--pane:#1e1d1b;--chrome:#1b1a18;--side:#191817;--elev:#262422;--hover:#f2f0eb0f;--active:#f2f0eb14;
|
||
--primary:#f2f0eb;--on-primary:#1e1d1b;--text:#f2f0eb;--text2:#f2f0eba8;--text3:#f2f0eb8a;--text4:#f2f0eb66;
|
||
--line:#f2f0eb1a;--line2:#f2f0eb14;--focus:#d88366;--accent:#d88366;--accent-ink:#e2977d;
|
||
--danger:#e26e6e;--bubble-user:#f2f0eb2e;--bubble-user-ink:#f2f0eb;--bubble-bot:#f2f0eb0a;--card:#262422;--attention:#d9a441;--attention-bg:#38311f;
|
||
--spec:#ffffff0d;--shadow:none;
|
||
--cat1:#d88366;--cat2:#7f9dc0;--cat3:#6fae9c;--cat4:#c2b060;--cat5:#b78aa4;--cat6:#a09a92;--grid:#f2f0eb14;--up:#6fb97d;
|
||
--shade:#00000073;--scrim:#0000008c;--stage:#000;--on-stage:#ffffff99;--on-color:#fff;
|
||
}}
|
||
:root[data-theme="dark"]{
|
||
--pane:#1e1d1b;--chrome:#1b1a18;--side:#191817;--elev:#262422;--hover:#f2f0eb0f;--active:#f2f0eb14;
|
||
--primary:#f2f0eb;--on-primary:#1e1d1b;--text:#f2f0eb;--text2:#f2f0eba8;--text3:#f2f0eb8a;--text4:#f2f0eb66;
|
||
--line:#f2f0eb1a;--line2:#f2f0eb14;--focus:#d88366;--accent:#d88366;--accent-ink:#e2977d;
|
||
--danger:#e26e6e;--bubble-user:#f2f0eb2e;--bubble-user-ink:#f2f0eb;--bubble-bot:#f2f0eb0a;--card:#262422;--attention:#d9a441;--attention-bg:#38311f;
|
||
--spec:#ffffff0d;--shadow:none;
|
||
--cat1:#d88366;--cat2:#7f9dc0;--cat3:#6fae9c;--cat4:#c2b060;--cat5:#b78aa4;--cat6:#a09a92;--grid:#f2f0eb14;--up:#6fb97d;
|
||
--shade:#00000073;--scrim:#0000008c;--stage:#000;--on-stage:#ffffff99;--on-color:#fff;
|
||
}
|
||
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
|
||
html,body{margin:0;height:100%;background:var(--pane);color:var(--text);font:var(--fs-ui)/1.47 var(--font);-webkit-font-smoothing:antialiased;overscroll-behavior:none}
|
||
button{font:inherit;color:inherit;background:none;border:0;padding:0;cursor:pointer}
|
||
input,textarea,select{font:inherit;color:var(--text)}
|
||
a{color:var(--accent-ink)}
|
||
.ic{flex:none;vertical-align:-3px}
|
||
.app{height:100dvh;display:flex;flex-direction:column;overflow:hidden}
|
||
.view{flex:1;display:none;flex-direction:column;min-height:0;background:var(--pane)}
|
||
.view.on{display:flex}
|
||
/* A message that just arrived slides up into place (screens slide in with in-fwd / in-back). */
|
||
@keyframes msgIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
|
||
.m.fresh{animation:msgIn .18s ease-out}
|
||
@media (prefers-reduced-motion:reduce){.m.fresh{animation:none}}
|
||
.scroll{flex:1;overflow-y:auto;-webkit-overflow-scrolling:touch;min-height:0}
|
||
|
||
/* ---- bars ---- */
|
||
.bar{display:flex;align-items:center;gap:4px;padding:calc(var(--safe-t) + 4px) 6px 4px;min-height:52px;background:var(--pane);flex:none}
|
||
.bar h1{font-size:var(--fs-h3);font-weight:600;margin:0;flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.bar h1 small{font-size:var(--fs-caption);font-weight:400;color:var(--text3);margin-left:6px}
|
||
.ib{width:44px;height:44px;border-radius:var(--r-m);display:grid;place-items:center;color:var(--text2);flex:none}
|
||
.ib:active,.ib.on{background:var(--hover)}
|
||
.ib .ic{vertical-align:0}
|
||
.island{flex:1;min-width:0;display:flex;align-items:center;gap:9px;height:40px;padding:0 10px 0 4px;border-radius:var(--r-m)}
|
||
.island:active{background:var(--hover)}
|
||
.island .t{min-width:0;flex:1;text-align:left}
|
||
.island .n{font-size:var(--fs-ui);font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:flex;align-items:center;gap:4px}
|
||
.island .s{font-size:var(--fs-caption);color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.island .s.busy{color:var(--ok)}
|
||
.island .s.wait{color:var(--warn)}
|
||
|
||
/* ---- avatars ---- */
|
||
.av{width:36px;height:36px;flex:none;position:relative;display:grid;place-items:center}
|
||
.av svg{width:100%;height:100%}
|
||
.av.lg{width:64px;height:64px}
|
||
.av.sm{width:30px;height:30px}
|
||
.av .dot{position:absolute;right:-1px;bottom:-1px;width:11px;height:11px;border-radius:50%;border:2px solid var(--side)}
|
||
.dot.busy{background:var(--ok)}.dot.wait{background:var(--warn)}.dot.unread{background:var(--accent)}.dot.err{background:var(--danger)}
|
||
|
||
/* ---- home = the sidebar ---- */
|
||
#v-home{background:var(--side)}
|
||
#v-home .bar{background:var(--side);border-bottom:0}
|
||
.me{width:32px;height:32px;border-radius:50%;background:var(--active);display:grid;place-items:center;font-size:var(--fs-small);font-weight:600;color:var(--text2);flex:none}
|
||
.searchbox{margin:0 12px 6px;display:none;align-items:center;gap:8px;background:var(--hover);border-radius:var(--r-m);padding:0 10px;height:36px}
|
||
.searchbox.on{display:flex}
|
||
.searchbox .ib{width:36px;height:36px}
|
||
.searchbox input{flex:1;border:0;background:none;outline:0;font-size:var(--fs-ui);min-width:0}
|
||
.quick{display:flex;gap:8px;padding:2px 12px 8px;overflow-x:auto;scrollbar-width:none}
|
||
.quick::-webkit-scrollbar{display:none}
|
||
.quick button{flex:none;display:flex;align-items:center;gap:6px;height:36px;padding:0 14px;border-radius:999px;background:var(--elev);font-size:var(--fs-small);color:var(--text2)}
|
||
.quick button b{font-weight:600;color:var(--text)}
|
||
.quick button .st{width:7px;height:7px;border-radius:50%}
|
||
.sec{display:flex;align-items:center;gap:6px;padding:14px 18px 4px;font-size:var(--fs-caption);font-weight:600;color:var(--text3)}
|
||
.sec .ic{color:var(--text3)}
|
||
.sec .n{font-weight:400}
|
||
.sec button{margin-left:auto;color:var(--text3);font-size:var(--fs-caption);font-weight:400;display:flex;align-items:center;gap:2px}
|
||
.rows{padding:0 8px}
|
||
.row{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:var(--r-m);min-height:56px;position:relative}
|
||
.row:active,.row.sel{background:var(--active)}
|
||
.row .mid{flex:1;min-width:0}
|
||
.row .nm{font-size:var(--fs-ui);font-weight:500;display:flex;align-items:center;gap:6px;min-width:0}
|
||
.row .nm span.t{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.row .pv{font-size:var(--fs-small);color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.row .pv.busy{color:var(--ok)}.row .pv.wait{color:var(--warn)}
|
||
.row .tm{font-size:var(--fs-caption);color:var(--text4);align-self:flex-start;margin-top:4px;flex:none}
|
||
.row .more{width:44px;height:44px;margin-right:-8px;border-radius:var(--r-m);display:grid;place-items:center;color:var(--text3);flex:none}
|
||
.pill{font-size:var(--fs-caption);font-weight:500;padding:1px 7px;border-radius:999px;background:var(--active);color:var(--text2);flex:none}
|
||
.pill.acc{background:color-mix(in srgb,var(--accent) 16%,transparent);color:var(--accent-ink)}
|
||
.pill.ok{background:color-mix(in srgb,var(--ok) 16%,transparent);color:var(--ok)}
|
||
.pill.warn{background:color-mix(in srgb,var(--warn) 18%,transparent);color:var(--warn)}
|
||
.empty{padding:40px 24px;text-align:center;color:var(--text3);font-size:var(--fs-ui);line-height:1.6}
|
||
|
||
/* ---- chat ---- */
|
||
#v-chat{position:relative}
|
||
.msgs{padding:12px 14px 8px;display:flex;flex-direction:column;gap:2px;max-width:760px;margin:0 auto;width:100%}
|
||
.dsep{align-self:center;font-size:var(--fs-caption);color:var(--text3);padding:12px 0 6px}
|
||
.m{display:flex;flex-direction:column;max-width:100%;margin:3px 0;position:relative}
|
||
.m.user{align-items:flex-end}
|
||
.m.bot{align-items:flex-start}
|
||
.bub{max-width:min(86%,560px);padding:7px 12px;border-radius:var(--r-l);font-size:var(--fs-read);line-height:1.5;word-wrap:break-word;overflow-wrap:anywhere;
|
||
background-image:linear-gradient(to bottom,var(--spec),transparent);box-shadow:inset 0 .5px 0 var(--spec),inset 0 0 0 .5px var(--line2)}
|
||
/* The chat takes its bot's colour (--bot, set when the chat opens; a black bot keeps the plain bubble). */
|
||
.m.user .bub{background-color:var(--bot,var(--bubble-user));color:var(--bot-ink,var(--bubble-user-ink));white-space:pre-wrap;border-radius:var(--r-l) var(--r-l) var(--r-s) var(--r-l)}
|
||
.quiet .m.user .bub{background-color:var(--hover);color:var(--text)}
|
||
details.dt{margin:var(--sp-3) 0}details.dt>summary{font-size:var(--fs-small);color:var(--text2);cursor:pointer;list-style:none}
|
||
details.dt>summary::-webkit-details-marker{display:none}details.dt>summary::before{content:"▸ "}details.dt[open]>summary::before{content:"▾ "}
|
||
details.dt>.dt-in{padding-left:var(--sp-4);margin-top:var(--sp-2)}
|
||
/* The bot's words sit on the page like a document; only an error gets a bubble. */
|
||
.m.bot .bub{background-color:transparent;padding:0;max-width:100%;border-radius:0;box-shadow:none;background-image:none}
|
||
.m.bot.err .bub{color:var(--danger);background-color:var(--bubble-bot);padding:7px 12px;border-radius:var(--r-l);font-family:var(--font);font-size:var(--fs-ui);line-height:1.5}
|
||
/* ---- Reading: the bot's answers and pages read like a document (Claude's warmth, Notion's
|
||
clarity) — serif text, quiet blocks. The person's own messages and the interface stay sans. ---- */
|
||
.m.bot .bub,.page{font-family:var(--font-read);font-size:var(--fs-read);line-height:var(--lh-read)}
|
||
:is(.bub,.page,.tk-a)>:first-child{margin-top:0}
|
||
:is(.bub,.page,.tk-a) p{margin:0 0 .75em}
|
||
:is(.bub,.page,.tk-a) :is(ul,ol){margin:0 0 .75em;padding-left:1.4em}
|
||
:is(.bub,.page,.tk-a) li{margin:0 0 6px}
|
||
:is(.bub,.page,.tk-a) li:last-child{margin-bottom:0}
|
||
:is(.bub,.page,.tk-a) li.task{list-style:none;margin-left:-1.2em}
|
||
:is(.bub,.page) :is(h2,h3,h4){font-family:var(--font-read);font-weight:700;line-height:1.35;color:var(--text)}
|
||
.bub h2{font-size:var(--fs-h3);margin:1.2em 0 .4em}
|
||
.bub :is(h3,h4){font-size:var(--fs-read);margin:1.1em 0 .3em}
|
||
.tk-a :is(h2,h3,h4){font-size:var(--fs-ui);margin:.8em 0 .3em}
|
||
:is(.bub,.page,.tk-a) code{font-family:var(--mono);font-size:var(--fs-small);background:var(--hover);padding:1px 5px;border-radius:var(--r-s)}
|
||
:is(.bub,.page,.tk-a) pre{margin:0 0 .75em;padding:var(--sp-3) var(--sp-4);border-radius:var(--r-m);background:var(--hover);overflow-x:auto;font:var(--fs-small)/1.55 var(--mono)}
|
||
:is(.bub,.page,.tk-a) pre code{background:none;padding:0;border-radius:0;font:inherit}
|
||
:is(.bub,.page,.tk-a) blockquote{margin:0 0 .75em;padding-left:var(--sp-3);border-left:2px solid var(--line);color:var(--text2)}
|
||
:is(.bub,.page,.tk-a) hr{border:0;border-top:1px solid var(--line);margin:var(--sp-5) 0}
|
||
/* Tables: no vertical lines, no stripes — a hairline under the header and under each row;
|
||
numbers line up on the right. */
|
||
:is(.bub,.page,.tk-a) .tw{overflow-x:auto;margin:0 0 .75em}
|
||
:is(.bub,.page,.tk-a) table{border-collapse:collapse;font-family:var(--font);font-size:var(--fs-ui);line-height:1.5}
|
||
:is(.bub,.page,.tk-a) :is(th,td){border:0;border-bottom:1px solid var(--line2);padding:var(--sp-2) var(--sp-3);text-align:left;vertical-align:top}
|
||
:is(.bub,.page,.tk-a) th{font-size:var(--fs-small);font-weight:600;color:var(--text2);background:none;border-bottom-color:var(--line)}
|
||
:is(.bub,.page,.tk-a) :is(th,td).num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
|
||
/* Call-outs ([!NOTE]…, the page's 結論): one quiet tint for every kind; only the icon says which. */
|
||
:is(.bub,.page,.tk-a) .call{margin:0 0 .75em;padding:var(--sp-3) var(--sp-4);border-radius:var(--r-m);background:var(--hover)}
|
||
.call .ct{display:flex;align-items:center;gap:6px;font-family:var(--font);font-size:var(--fs-small);font-weight:600;color:var(--text2);margin-bottom:var(--sp-1)}
|
||
/* (k-…: a plain "note" class would also pick up the app's .note look.) */
|
||
.call.k-note .ct .ic{color:var(--cat2)}.call.k-tip .ct .ic{color:var(--ok)}.call.k-warning .ct .ic{color:var(--warn)}
|
||
.call.k-important .ct .ic,.call.k-verdict .ct .ic{color:var(--accent)}
|
||
:is(.bub,.page,.tk-a) :is(p,ul,ol,pre,blockquote,.tw,.call,hr,.stats,.chartcard):last-child{margin-bottom:0}
|
||
.m.user .bub a{color:inherit;text-decoration:underline}
|
||
.who{font-size:var(--fs-caption);color:var(--text3);margin:6px 0 2px 4px}
|
||
.tag{font-size:var(--fs-caption);color:var(--text3);margin:4px 4px 2px;display:flex;align-items:center;gap:4px}
|
||
.meta{font-size:var(--fs-caption);color:var(--text4);margin:3px 6px 0;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
|
||
.meta button{color:var(--text3);display:grid;place-items:center;width:36px;height:36px;border-radius:var(--r-m)}
|
||
.meta button:active{background:var(--hover)}
|
||
.reacts{display:flex;gap:4px;flex-wrap:wrap;margin:3px 4px 0}
|
||
.reacts button{font-size:var(--fs-small);padding:1px 8px;min-height:28px;border-radius:999px;background:var(--hover)}
|
||
.quote{font-size:var(--fs-small);color:var(--text2);border-left:2px solid var(--line);padding-left:8px;margin:0 0 4px;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;white-space:normal}
|
||
/* steps (the desktop's outline rows) */
|
||
.steps{display:flex;flex-direction:column;gap:4px;margin:4px 0;max-width:min(92%,560px);width:100%}
|
||
.step,.fold{border-radius:var(--r-m);background:var(--hover);font-size:var(--fs-small);overflow:hidden}
|
||
.step>.h,.fold{display:flex;align-items:center;gap:7px;padding:7px 10px;min-height:34px;width:100%;text-align:left}
|
||
.step .l{font-weight:600;flex:none;max-width:45%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.step .d{color:var(--text3);flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.step .chev{color:var(--text4);transition:transform .15s}
|
||
.step.open .chev{transform:rotate(90deg)}
|
||
.step .body{display:none;padding:0 10px 9px;border-top:.5px solid var(--line2)}
|
||
.step.open .body{display:block}
|
||
.step .body pre{margin:8px 0 0;white-space:pre-wrap;word-break:break-word;font:var(--fs-caption)/1.5 var(--mono);color:var(--text2);max-height:260px;overflow:auto}
|
||
.step .body .k{font-size:var(--fs-caption);color:var(--text3);margin-top:8px}
|
||
.st-i{display:grid;place-items:center;width:16px;color:var(--text3)}
|
||
.step.done .st-i{color:var(--ok)}.step.failed .st-i{color:var(--danger)}.step.waiting .st-i{color:var(--warn)}.step.running .st-i{color:var(--accent)}
|
||
.step.running .st-i svg{animation:spin 1.2s linear infinite}
|
||
@keyframes spin{to{transform:rotate(360deg)}}
|
||
.fold{color:var(--text2)}
|
||
.fold .ic:last-child{margin-left:auto;color:var(--text4)}
|
||
.typing{display:flex;gap:4px;padding:11px 14px;border-radius:var(--r-l);background:var(--bubble-bot);width:fit-content}
|
||
.typing i{width:5px;height:5px;border-radius:50%;background:var(--text3);animation:blink 1.2s infinite}
|
||
.typing i:nth-child(2){animation-delay:.2s}.typing i:nth-child(3){animation-delay:.4s}
|
||
@keyframes blink{0%,80%,100%{opacity:.3}40%{opacity:1}}
|
||
.working{display:flex;align-items:center;gap:8px;margin:6px 0;max-width:100%}
|
||
.presence{font-size:var(--fs-small);color:var(--text3);margin:6px 4px;min-width:0;overflow-wrap:anywhere;background:linear-gradient(90deg,var(--text3) 30%,var(--text) 50%,var(--text3) 70%);background-size:200% 100%;-webkit-background-clip:text;background-clip:text;color:transparent;animation:shimmer 2s linear infinite}
|
||
@keyframes shimmer{to{background-position:-200% 0}}
|
||
.summary{align-self:stretch;margin:8px 0;padding:10px 12px;border-radius:var(--r-m);background:var(--hover);font-size:var(--fs-small);color:var(--text2)}
|
||
.summary b{display:flex;align-items:center;gap:6px;color:var(--text);font-weight:500}
|
||
.summary .tx{display:none;margin-top:6px;white-space:pre-wrap;overflow-wrap:anywhere}
|
||
.summary.open .tx{display:block}
|
||
/* cards in the chat */
|
||
.m.sending .bub{opacity:.55}.m.sending .sn{font-size:var(--fs-caption);color:var(--text3);align-self:flex-end;margin-top:2px}.m.sending.failed .sn{color:var(--danger)}
|
||
.talk{border-radius:var(--r-l);background:none;box-shadow:inset 0 0 0 .5px var(--line);max-width:min(92%,560px);width:100%;margin:4px 0;padding:10px 12px;font-size:var(--fs-small);overflow:hidden}
|
||
.talk .tk-h{display:flex;align-items:center;gap:5px;flex-wrap:wrap}.talk .tk-h span{color:var(--text3);font-size:var(--fs-caption);margin-left:2px}
|
||
.talk .tk-h b{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||
.talk .av.xs{width:18px;height:18px;display:inline-flex}.talk .av.xs svg{width:18px;height:18px}
|
||
.talk .tk-q{color:var(--text2);margin-top:4px;white-space:pre-wrap;overflow-wrap:anywhere}
|
||
.talk .tk-st{display:flex;gap:5px;align-items:center;color:var(--text2);font-size:var(--fs-small);margin-top:6px;min-width:0;overflow-wrap:anywhere}.talk .tk-st.err{color:var(--danger)}
|
||
.talk .tk-ok{display:flex;gap:5px;align-items:center;color:var(--ok);font-size:var(--fs-small);margin-top:6px}.talk .tk-a{margin-top:2px;min-width:0;max-width:100%;overflow-wrap:anywhere}
|
||
/* Answers in these cards are markdown: code and tables scroll inside, never past the card. */
|
||
.talk .tk-go{color:var(--text3);font-size:var(--fs-caption);margin-top:6px;padding:0}
|
||
.talk.branch .tk-h span{margin:0 2px 0 0}.br-log{margin-top:6px;color:var(--text3);font-size:var(--fs-caption)}.br-log summary{cursor:pointer}
|
||
.card,.pcard,.filec{border-radius:var(--r-l);background:none;box-shadow:inset 0 0 0 .5px var(--line);max-width:min(92%,420px);width:100%;margin:4px 0;overflow:hidden}
|
||
.card{padding:10px 12px;font-size:var(--fs-small)}
|
||
.card .t{font-weight:600;font-size:var(--fs-ui)}.card .s{color:var(--text3);margin-bottom:4px}
|
||
.card .r{display:flex;justify-content:space-between;gap:10px;padding:3px 0;border-top:.5px solid var(--line2)}
|
||
.card .r span:first-child{color:var(--text3)}
|
||
.pcard .top{padding:12px 14px 6px}
|
||
.pcard .top .t{font-weight:600;margin-bottom:4px}
|
||
.pcard .top .l{font-size:var(--fs-small);color:var(--text2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.pcard .foot{display:flex;align-items:center;gap:10px;padding:9px 14px;border-top:.5px solid var(--line2)}
|
||
.pcard .foot .n{font-size:var(--fs-small);font-weight:500}.pcard .foot .x{font-size:var(--fs-caption);color:var(--text3)}
|
||
.filec{display:flex;align-items:center;gap:8px;padding:8px 10px;min-width:180px;width:auto;text-decoration:none;color:var(--text)}
|
||
.filec .fn{font-size:var(--fs-small);font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.attimg{max-width:min(78%,320px);margin:4px 0;border-radius:var(--r-l);overflow:hidden;box-shadow:inset 0 0 0 .5px var(--line)}
|
||
.attimg img{display:block;width:100%;max-height:320px;object-fit:cover}
|
||
.attimg .wait{padding:20px;font-size:var(--fs-caption);color:var(--text3)}
|
||
.plink{cursor:pointer;color:var(--accent-ink);text-decoration:underline;text-decoration-color:color-mix(in srgb,var(--accent-ink) 40%,transparent)}
|
||
/* empty chat */
|
||
.intro{display:flex;flex-direction:column;align-items:center;text-align:center;padding:36px 16px 10px;gap:6px}
|
||
.intro .hi{font-size:var(--fs-h2);font-weight:600;margin-top:8px}
|
||
.intro .sub{font-size:var(--fs-ui);color:var(--text3)}
|
||
.sugs{display:flex;flex-direction:column;gap:6px;padding:14px 16px;max-width:520px;margin:0 auto;width:100%}
|
||
.sug{display:flex;align-items:center;gap:12px;padding:11px 12px;min-height:52px;border-radius:var(--r-m);background:var(--elev);text-align:left}
|
||
.sug .ic{color:var(--text2)}
|
||
.sug .tt{font-size:var(--fs-ui);font-weight:500}.sug .dd{font-size:var(--fs-caption);color:var(--text3)}
|
||
/* the dock: approvals, queued steering, attachments, the composer */
|
||
/* --kb: the iOS keyboard floats over the page; the script measures it and lifts the composer. */
|
||
.dock{flex:none;padding:6px 10px calc(var(--safe-b) + 8px + var(--kb,0px));background:linear-gradient(to bottom,transparent,var(--chrome) 40%)}
|
||
/* 需要你: yellow is the one colour for what waits for the person. */
|
||
/* Tall cards (long reasons, many choices) scroll inside the card: the composer stays on screen. */
|
||
.ask{max-width:560px;margin:0 auto 8px;padding:14px 16px;border-radius:var(--r-l);background:var(--attention-bg);box-shadow:inset 0 0 0 1px var(--attention);max-height:min(48dvh,420px);overflow-y:auto;overscroll-behavior:contain}
|
||
.ask .q{font-weight:600;font-size:var(--fs-ui)}
|
||
.ask .why{font-size:var(--fs-small);color:var(--text2);margin:4px 0 10px;white-space:pre-wrap;overflow-wrap:anywhere}
|
||
.ask .thumb{width:100%;border-radius:var(--r-m);margin:2px 0 10px;display:block;background:var(--hover);min-height:60px}
|
||
.ask .btns{display:flex;flex-wrap:wrap;gap:8px}
|
||
.ask .all{display:block;margin-top:10px;font-size:var(--fs-small);color:var(--accent-ink)}
|
||
/* 問題卡: one question at a time — choices to tap, a field for your own answer */
|
||
.ask .asknum{font-size:var(--fs-caption);color:var(--text2);margin-bottom:2px}
|
||
.ask .opt{display:flex;align-items:center;gap:10px;width:100%;min-height:44px;margin:0 0 6px;padding:8px 12px;border:0;border-radius:var(--r-m);background:var(--elev);box-shadow:inset 0 0 0 1px var(--line);color:var(--text);font:inherit;font-size:var(--fs-ui);text-align:left}
|
||
.ask .opt.on{box-shadow:inset 0 0 0 2px var(--text)}
|
||
.ask .opt i{flex:none;width:18px;height:18px;border-radius:50%;box-shadow:inset 0 0 0 1.5px var(--text3)}
|
||
.ask .opt.many i{border-radius:var(--r-s)}
|
||
.ask .opt.on i{background:var(--text);box-shadow:none;position:relative}
|
||
.ask .opt.on i::after{content:"";position:absolute;left:6px;top:2.5px;width:4px;height:9px;border:solid var(--elev);border-width:0 2px 2px 0;transform:rotate(45deg)}
|
||
.ask .own{display:block;width:100%;box-sizing:border-box;min-height:44px;margin:0 0 10px;padding:8px 12px;border:0;border-radius:var(--r-m);background:var(--elev);box-shadow:inset 0 0 0 1px var(--line);color:var(--text);font:inherit;font-size:var(--fs-read)}
|
||
.ask .btn[disabled]{opacity:.45}
|
||
.btn{height:40px;padding:0 16px;border-radius:999px;background:var(--hover);font-weight:500;font-size:var(--fs-ui);display:inline-flex;align-items:center;justify-content:center;gap:6px}
|
||
.btn.main{background:var(--primary);color:var(--on-primary)}
|
||
.btn.no{color:var(--danger)}
|
||
.btn.sm{height:34px;padding:0 12px;font-size:var(--fs-small);border-radius:999px}
|
||
.btn:disabled{opacity:.45}
|
||
/* 目標 and 計畫 while they are on: one row of small chips (no line each); a tap opens that one's line below. */
|
||
.modes{max-width:560px;margin:0 auto 6px;display:flex;gap:6px}
|
||
.modes:empty{display:none}
|
||
.mode{position:relative;display:inline-flex;align-items:center;gap:4px;height:28px;padding:0 9px;border-radius:999px;background:var(--hover);font-size:var(--fs-small);color:var(--text2)}
|
||
/* (28 px to look at, 44 px to tap.) */
|
||
.mode::after{content:"";position:absolute;inset:-8px -2px}
|
||
.mode.on .ic{color:var(--accent)}
|
||
.mode.open{box-shadow:inset 0 0 0 1px var(--text3)}
|
||
/* 問題卡: in the chat, after the newest message (it scrolls with it), as tall as its content. */
|
||
#askq{padding:0 14px}
|
||
#askq .ask{max-height:none;overflow:visible;margin:4px auto 14px}
|
||
.goalbar{max-width:560px;margin:0 auto 6px;display:flex;align-items:center;gap:8px;font-size:var(--fs-small);color:var(--text2);background:var(--hover);border-radius:var(--r-m);padding:5px 6px 5px 11px}
|
||
.goalbar .t{flex:1;min-width:0;display:flex;align-items:center;gap:6px}
|
||
.goalbar .t span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||
.goalbar.on .t .ic{color:var(--accent)}
|
||
.goalbar button{flex:none;font-size:var(--fs-small);color:var(--text2);padding:4px 8px;border-radius:var(--r-s)}
|
||
/* 計畫 (/plan): the plan handed in, as a card — waiting on you (accent edge), followed (its steps tick), or past. */
|
||
.card.plan .t{display:flex;align-items:center;gap:6px}.card.plan .t .st{margin-left:auto;font-weight:400;font-size:var(--fs-small);color:var(--text3)}
|
||
.card.plan.wait{box-shadow:inset 0 0 0 1px var(--accent)}.card.plan.wait .t .st{color:var(--accent)}
|
||
.card.plan .sum{margin:4px 0 2px;color:var(--text)}.card.plan.past .sum{color:var(--text2)}
|
||
.card.plan ol{margin:6px 0 0;padding-left:22px}.card.plan li{padding:2px 0}.card.plan li::marker{color:var(--text3)}
|
||
.card.plan li .d{display:block;color:var(--text3);font-size:var(--fs-small)}.card.plan li.done{color:var(--text3);list-style-type:"✓ "}.card.plan li.now{list-style-type:"▸ "}.card.plan li.now::marker{color:var(--accent)}.card.plan li.skip{color:var(--text3);text-decoration:line-through;list-style-type:"– "}
|
||
.card.plan .x{margin-top:6px;color:var(--text2);font-size:var(--fs-small)}
|
||
.msgs .note{align-self:center;display:flex;gap:6px;max-width:min(560px,100%);margin:6px 0;padding:7px 12px;border-radius:var(--r-m);background:var(--hover);color:var(--text2)}
|
||
.msgs .note .ic{flex:none;margin-top:2px;color:var(--text3)}
|
||
.queued{max-width:560px;margin:0 auto 6px;font-size:var(--fs-small);color:var(--text2);background:var(--hover);border-radius:var(--r-m);padding:7px 11px;overflow-wrap:anywhere}
|
||
.chips{display:flex;gap:6px;flex-wrap:wrap;max-width:760px;margin:0 auto}
|
||
.chip{display:inline-flex;align-items:center;gap:5px;font-size:var(--fs-small);padding:4px 6px 4px 10px;border-radius:999px;background:var(--elev);margin-bottom:6px;max-width:100%}
|
||
.chip span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:180px}
|
||
.chip button{display:grid;place-items:center;width:28px;height:28px;margin:-4px -2px;border-radius:50%;color:var(--text3)}
|
||
/* 記憶: the composer's suggestions, the tag under a message, the memory tab */
|
||
.memchips{display:flex;gap:6px;flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none;align-items:center;max-width:760px;margin:0 auto}
|
||
.memchips::-webkit-scrollbar{display:none}
|
||
.memchips>*{flex:none}
|
||
.memchips:not(:empty){margin-bottom:6px}
|
||
.memchips .lbl{font-size:var(--fs-caption);color:var(--text3);display:inline-flex;gap:4px;align-items:center}
|
||
.mchip{font-size:var(--fs-small);padding:4px 10px;border-radius:999px;box-shadow:inset 0 0 0 .5px var(--line);color:var(--text2);max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.mchip.on{background:color-mix(in srgb,var(--accent) 14%,transparent);box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 55%,transparent);color:var(--text)}
|
||
.slash{max-width:760px;margin:0 auto 6px;padding:4px;max-height:min(272px,38vh);overflow-y:auto;border-radius:var(--r-l);background:var(--elev);box-shadow:0 6px 24px -6px var(--shade)}
|
||
.slash:empty{display:none}
|
||
.slash .hd{font-size:var(--fs-caption);color:var(--text3);padding:6px 10px 4px}
|
||
.slash button{display:flex;align-items:center;gap:8px;width:100%;min-height:44px;padding:6px 10px;border-radius:var(--r-m);text-align:left}
|
||
.slash button.on{background:var(--active)}
|
||
.slash b{flex:none;max-width:62%;font-size:var(--fs-ui);font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.slash span{min-width:0;font-size:var(--fs-small);color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.memtok{font-size:var(--fs-caption);color:var(--text3)}
|
||
.carried{font-size:var(--fs-caption);color:var(--text3);margin:3px 6px 0;display:inline-flex;gap:4px;align-items:center}
|
||
.carried-list{font-size:var(--fs-small);color:var(--text2);background:var(--hover);border-radius:var(--r-m);padding:8px 12px;margin:4px 4px 0;max-width:85%;line-height:1.5;white-space:pre-wrap;word-break:break-word}
|
||
.memhead{padding:10px 18px 0;font-size:var(--fs-small);color:var(--text3);line-height:1.7}
|
||
.memhead b{color:var(--text);font-weight:600;margin:0 12px 0 3px}
|
||
.memhead .sub{font-size:var(--fs-caption)}
|
||
.memsearch{display:flex;gap:8px;padding:10px 12px 6px}
|
||
.memsearch input{flex:1;min-width:0;height:40px;border-radius:999px;padding:0 14px;background:var(--elev);font-size:var(--fs-read);color:var(--text);border:0;outline:none}
|
||
.memsearch button{flex:none;height:40px;padding:0 14px;border-radius:999px;background:var(--elev);font-size:var(--fs-ui);color:var(--accent-ink);display:inline-flex;gap:4px;align-items:center}
|
||
.memfilters{display:flex;gap:6px;padding:4px 12px 10px;overflow-x:auto;scrollbar-width:none}
|
||
.memfilters::-webkit-scrollbar{display:none}
|
||
.memfilters button{flex:none;height:30px;padding:0 12px;border-radius:999px;font-size:var(--fs-small);color:var(--text2);box-shadow:inset 0 0 0 .5px var(--line)}
|
||
.memfilters button.on{background:var(--active);color:var(--text);font-weight:500;box-shadow:none}
|
||
.mcard{margin:0 12px 8px;padding:11px 14px 8px;border-radius:var(--r-l);background:var(--elev)}
|
||
.mcard.pin{box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 45%,transparent)}
|
||
.mcard .mt{font-size:var(--fs-ui);white-space:pre-wrap;word-break:break-word;line-height:1.5}
|
||
.mcard .mm{font-size:var(--fs-caption);color:var(--text3);margin-top:6px;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
|
||
.mcard .mm .pinned{color:var(--accent-ink);display:inline-flex;gap:3px;align-items:center}
|
||
.mcard .ma{display:flex;gap:2px;justify-content:flex-end;margin-top:4px}
|
||
.mcard .ma button{height:30px;padding:0 10px;border-radius:999px;font-size:var(--fs-small);color:var(--text2)}
|
||
.mcard .ma button:active{background:var(--hover)}
|
||
.msugg{margin:0 12px 10px;padding:12px 14px;border-radius:var(--r-l);background:var(--hover);font-size:var(--fs-small);color:var(--text2);line-height:1.5}
|
||
.msugg .h{font-weight:600;color:var(--text);display:flex;gap:6px;align-items:center}
|
||
.msugg .sr{margin-top:10px;word-break:break-word}
|
||
.msugg .acts{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap}
|
||
.msugg .acts button{height:30px;padding:0 12px;border-radius:999px;font-size:var(--fs-small);color:var(--accent-ink);background:var(--elev)}
|
||
.memmore{display:flex;justify-content:space-between;align-items:center;padding:4px 18px 12px;font-size:var(--fs-caption);color:var(--text3)}
|
||
.memmore button{color:var(--accent-ink);font-size:var(--fs-small)}
|
||
.quoting{max-width:760px;margin:0 auto 6px;display:flex;align-items:center;gap:8px;font-size:var(--fs-small);color:var(--text2);border-left:3px solid var(--line);padding-left:8px}
|
||
.quoting span{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.composer{max-width:760px;margin:0 auto;display:flex;align-items:flex-end;gap:4px;background:var(--elev);border-radius:var(--r-l);padding:6px;box-shadow:inset 0 0 0 1px var(--line),0 2px 10px -2px var(--shade)}
|
||
.composer:focus-within{box-shadow:inset 0 0 0 1px var(--text4),0 2px 10px -2px var(--shade)}
|
||
.composer.tall{border-radius:var(--r-l)}
|
||
.composer textarea{flex:1;border:0;outline:0;background:none;resize:none;font-size:var(--fs-read);line-height:22px;max-height:140px;min-height:28px;padding:3px 4px}
|
||
.cbtn{width:36px;height:36px;border-radius:var(--r-m);display:grid;place-items:center;flex:none;color:var(--text2)}
|
||
.cbtn.plus{background:none}
|
||
.cbtn.go{background:var(--bot,var(--primary));color:var(--bot-ink,var(--on-primary))}
|
||
.cbtn.go:disabled{opacity:.35}
|
||
.cbtn.rec{color:var(--danger)}
|
||
.cbtn .ic{vertical-align:0}
|
||
.down{position:absolute;right:16px;bottom:96px;width:36px;height:36px;border-radius:50%;background:var(--elev);box-shadow:inset 0 0 0 .5px var(--line),0 4px 12px var(--shade);display:none;place-items:center;color:var(--text2);z-index:2}
|
||
.down.on{display:grid}
|
||
|
||
/* ---- details, editor, lists ---- */
|
||
.hero{display:flex;flex-direction:column;align-items:center;gap:6px;padding:18px 16px 6px;text-align:center}
|
||
.hero .n{font-size:var(--fs-h2);font-weight:600}
|
||
.hero .d{font-size:var(--fs-small);color:var(--text3);max-width:320px}
|
||
.tabs{display:flex;gap:4px;padding:8px 12px;overflow-x:auto;scrollbar-width:none;flex:none;position:sticky;top:0;background:var(--pane);z-index:1}
|
||
.tabs::-webkit-scrollbar{display:none}
|
||
.tabs button{flex:none;height:32px;padding:0 13px;border-radius:999px;font-size:var(--fs-ui);color:var(--text2)}
|
||
.tabs button.on{background:var(--active);color:var(--text);font-weight:500}
|
||
.group{margin:8px 12px 14px;border-radius:var(--r-l);background:var(--elev);overflow:hidden}
|
||
.gt{font-size:var(--fs-caption);font-weight:600;color:var(--text3);padding:12px 18px 4px;display:flex;align-items:center;gap:6px}
|
||
.gt button{margin-left:auto;font-weight:500;color:var(--accent-ink);font-size:var(--fs-small)}
|
||
.item{display:flex;align-items:center;gap:12px;padding:11px 14px;min-height:48px;border-top:.5px solid var(--line2);width:100%;text-align:left}
|
||
.item:first-child{border-top:0}
|
||
button.item:active,.item.tap:active{background:var(--hover)}
|
||
.item .ic{color:var(--text2)}
|
||
.item .mid{flex:1;min-width:0}
|
||
.item .k{font-size:var(--fs-ui)}
|
||
.item .v{font-size:var(--fs-small);color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.item .r{font-size:var(--fs-ui);color:var(--text3);flex:none;max-width:45%;text-align:right;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.item.danger .k,.item.danger .ic{color:var(--danger)}
|
||
.item .chev{color:var(--text4)}
|
||
.note{font-size:var(--fs-small);color:var(--text3);padding:6px 18px 10px;line-height:1.55;white-space:pre-wrap;overflow-wrap:anywhere}
|
||
.sw{position:relative;width:46px;height:28px;flex:none}
|
||
.sw input{opacity:0;position:absolute;inset:0;margin:0}
|
||
.sw i{position:absolute;inset:0;border-radius:999px;background:var(--active);transition:.15s}
|
||
.sw i::after{content:"";position:absolute;left:3px;top:3px;width:22px;height:22px;border-radius:50%;background:var(--on-color);box-shadow:0 1px 3px var(--shade);transition:.15s}
|
||
.sw input:checked+i{background:var(--primary)}
|
||
.sw input:checked+i::after{background:var(--on-primary)}
|
||
.sw input:checked+i::after{transform:translateX(18px)}
|
||
.sw input:disabled+i{opacity:.4}
|
||
.field{display:block;width:100%;border:0;outline:0;background:var(--hover);border-radius:var(--r-m);padding:10px 12px;font-size:var(--fs-read);resize:vertical}
|
||
.field:focus{box-shadow:0 0 0 2px color-mix(in srgb,var(--focus) 45%,transparent)}
|
||
textarea.field{min-height:96px;line-height:1.5}
|
||
.form{padding:10px 14px;display:flex;flex-direction:column;gap:8px}
|
||
.form label{font-size:var(--fs-small);color:var(--text3);margin-top:4px}
|
||
.row2{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
|
||
.shapes{display:grid;grid-template-columns:repeat(6,1fr);gap:8px;padding:10px 14px}
|
||
.shapes button{aspect-ratio:1;border-radius:var(--r-m);padding:6px;background:var(--hover);min-width:0}
|
||
.shapes button svg{display:block;width:100%;height:100%}
|
||
.btnrow{display:flex;flex-wrap:wrap;gap:8px;padding:12px 14px}
|
||
.shapes button.on{box-shadow:0 0 0 2px var(--focus)}
|
||
.colors{display:flex;gap:10px;flex-wrap:wrap;padding:4px 14px 14px}
|
||
.colors button{width:30px;height:30px;border-radius:50%;box-shadow:inset 0 0 0 1px var(--line)}
|
||
.colors button.on{box-shadow:0 0 0 2px var(--pane),0 0 0 4px var(--focus)}
|
||
.thumbbox{margin:12px 14px 4px;border-radius:var(--r-l);overflow:hidden;background:var(--stage);aspect-ratio:16/10;display:grid;place-items:center;color:var(--on-stage);font-size:var(--fs-small)}
|
||
.thumbbox img{width:100%;height:100%;object-fit:contain;display:block}
|
||
.files{display:grid;grid-template-columns:repeat(3,1fr);gap:4px;padding:6px 12px}
|
||
.files .f{aspect-ratio:1;border-radius:var(--r-s);overflow:hidden;background:var(--hover);display:grid;place-items:center;font-size:var(--fs-caption);color:var(--text3);padding:6px;text-align:center;word-break:break-all}
|
||
.files .f img{width:100%;height:100%;object-fit:cover}
|
||
.log{font:var(--fs-caption)/1.5 var(--mono);color:var(--text2);white-space:pre-wrap;padding:10px 14px;max-height:280px;overflow:auto}
|
||
.kv{display:flex;justify-content:space-between;gap:10px;padding:4px 0}
|
||
|
||
/* ---- sheets ---- */
|
||
.sheet-bg{position:fixed;inset:0;background:var(--scrim);display:none;align-items:flex-end;justify-content:center;z-index:20}
|
||
.sheet-bg.on{display:flex}
|
||
.sheet{width:100%;max-width:560px;max-height:88dvh;overflow-y:auto;background:var(--pane);border-radius:var(--r-l) var(--r-l) 0 0;padding:6px 0 calc(var(--safe-b) + 10px);animation:up .18s ease-out}
|
||
@keyframes up{from{transform:translateY(30px);opacity:.6}}
|
||
.sheet .grab{width:36px;height:5px;border-radius:999px;background:var(--active);margin:4px auto 6px}
|
||
.sheet .st{font-size:var(--fs-small);color:var(--text3);text-align:center;padding:4px 16px 8px}
|
||
.sheet .opt{display:flex;align-items:center;gap:12px;width:100%;padding:13px 20px;font-size:var(--fs-ui);text-align:left}
|
||
.sheet .opt:active{background:var(--hover)}
|
||
.sheet .opt .ic{color:var(--text2)}
|
||
.sheet .opt.danger,.sheet .opt.danger .ic{color:var(--danger)}
|
||
.sheet .opt .ck{margin-left:auto;color:var(--accent)}
|
||
.sheet .sep{height:1px;background:var(--line2);margin:var(--sp-1) 20px}
|
||
.sheet .opt .x{margin-left:auto;font-size:var(--fs-small);color:var(--text3)}
|
||
.drop-to{display:flex;gap:6px;flex-wrap:wrap}
|
||
.drop-to button{height:32px;padding:0 12px;border-radius:999px;font-size:var(--fs-small);box-shadow:inset 0 0 0 .5px var(--line);color:var(--text2)}
|
||
.drop-to button.on{background:var(--primary);color:var(--on-primary);box-shadow:none}
|
||
.drop-to button.off{color:var(--text3)}
|
||
.drop-row{display:flex;align-items:center;gap:10px;padding:9px 18px}
|
||
.drop-row .ic{flex:none;color:var(--text3)}
|
||
.drop-row .dw{flex:1;min-width:0}
|
||
.drop-row .dn{font-size:var(--fs-ui);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.drop-row .ds{font-size:var(--fs-caption);color:var(--text3);line-height:1.4}
|
||
.drop-row .ds.bad{color:var(--danger)}
|
||
.drop-row .btn{flex:none}
|
||
.drop-bar{height:4px;border-radius:999px;background:var(--line);overflow:hidden;margin-top:4px}
|
||
.drop-bar i{display:block;height:100%;background:var(--primary)}
|
||
.sheet .grp{font-size:var(--fs-caption);font-weight:600;color:var(--text3);padding:12px 20px 4px}
|
||
.emojis{display:grid;grid-template-columns:repeat(8,1fr);gap:6px;padding:6px 16px 10px}
|
||
.emojis button{font-size:var(--fs-h2);height:44px;min-width:0;border-radius:var(--r-m);background:var(--hover)}
|
||
.toast{position:fixed;left:50%;top:calc(var(--safe-t) + 60px);transform:translate(-50%,-12px);background:var(--primary);color:var(--on-primary);padding:9px 16px;border-radius:999px;font-size:var(--fs-ui);opacity:0;pointer-events:none;transition:.2s;z-index:40;max-width:86vw;text-align:center}
|
||
.toast.on{opacity:1;transform:translate(-50%,0)}
|
||
|
||
/* ---- sign in ---- */
|
||
.login{max-width:360px;margin:auto;padding:24px;display:flex;flex-direction:column;gap:10px;width:100%}
|
||
.login .logo{width:72px;height:72px;margin:0 auto 8px;display:block}
|
||
.login h2{text-align:center;margin:0;font-size:var(--fs-h2)}
|
||
.login p{text-align:center;color:var(--text3);margin:0 0 8px;font-size:var(--fs-ui)}
|
||
.login .err{color:var(--danger);font-size:var(--fs-small);text-align:center;min-height:18px}
|
||
.link{color:var(--accent-ink);font-size:var(--fs-ui);text-align:center;padding:6px}
|
||
|
||
/* ---- page viewer ---- */
|
||
.page{padding:var(--sp-2) 18px 40px;max-width:760px;margin:0 auto}
|
||
.page h1.pt{font-family:var(--font-read);font-weight:700;font-size:var(--fs-h1);line-height:1.3;margin:var(--sp-3) 0 var(--sp-1)}
|
||
.page .mt{font-family:var(--font);font-size:var(--fs-caption);color:var(--text3);margin-bottom:var(--sp-4)}
|
||
.page h2{font-size:var(--fs-h2);margin:1.6em 0 .5em}
|
||
.page h3{font-size:var(--fs-h3);margin:1.4em 0 .4em}
|
||
.page h4{font-size:var(--fs-read);margin:1.2em 0 .3em}
|
||
.page :is(h2,h3,h4){scroll-margin-top:var(--sp-3)}
|
||
/* The one-line conclusion: a lead paragraph, no box. */
|
||
.page .sum{font-size:var(--fs-read);line-height:1.8;color:var(--text);margin:0 0 1em}
|
||
.page .old,.page .chg{font-family:var(--font);font-size:var(--fs-small);color:var(--text2);background:var(--hover);padding:var(--sp-2) var(--sp-3);border-radius:var(--r-m);margin:0 0 var(--sp-4)}
|
||
/* 目錄: one quiet line that opens to a plain list (only with 3+ headings). */
|
||
.toc{margin:0 0 var(--sp-4);font-family:var(--font)}
|
||
.toc summary{cursor:pointer;list-style:none;display:inline-flex;align-items:center;gap:var(--sp-1);padding:var(--sp-1) 0;font-size:var(--fs-small);color:var(--text3)}
|
||
.toc summary::-webkit-details-marker{display:none}
|
||
.toc summary .ic{transition:transform .15s}
|
||
.toc[open] summary .ic{transform:rotate(90deg)}
|
||
.toc ol{list-style:none;margin:var(--sp-1) 0 0;padding:0}
|
||
.toc li{margin:0}
|
||
.toc button{display:block;width:100%;text-align:left;padding:6px 0;font-size:var(--fs-ui);line-height:1.45;color:var(--text2)}
|
||
.toc li.sub button{padding-left:var(--sp-4);color:var(--text3)}
|
||
/* ---- 檔案: a chat file shown as the desktop shows it, and the takeover screen over all ---- */
|
||
.fimg{padding:16px 12px 40px;text-align:center}
|
||
.fimg img{max-width:100%;border-radius:var(--r-m)}
|
||
.ftext{padding:14px 16px 40px;font:var(--fs-small)/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;word-break:break-word;color:var(--text2)}
|
||
.fmedia{padding:28px 18px;display:grid;gap:12px;place-items:center}
|
||
.fmedia audio,.fmedia video{width:100%;max-width:560px;border-radius:var(--r-m)}
|
||
.fdl{display:grid;place-items:center;gap:14px;padding:64px 24px;color:var(--text2);text-align:center;line-height:1.6}
|
||
.pager{display:flex;align-items:center;justify-content:center;gap:14px;padding:8px 12px;padding-bottom:max(8px,env(safe-area-inset-bottom));border-top:1px solid var(--line);background:var(--pane);flex:none}
|
||
.pager span{font-size:var(--fs-small);color:var(--text2);min-width:72px;text-align:center}
|
||
.boxwrap{position:fixed;inset:0;z-index:50;background:var(--stage);display:none}
|
||
.boxwrap iframe{width:100%;height:100%;border:0;display:block}
|
||
.page .stats{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:8px;margin:12px 0}
|
||
.page .stat{border:.5px solid var(--line);border-radius:var(--r-l);background:none;padding:11px 13px;font-family:var(--font)}
|
||
.page .stat .k{font-size:var(--fs-caption);color:var(--text3)}.page .stat .v{font-size:var(--fs-h2);font-weight:650;line-height:1.2}.page .stat .v.long{font-size:var(--fs-read);font-weight:600}.page .stat .s{font-size:var(--fs-caption);color:var(--text2)}
|
||
.page .stat .v.up,.page .stat .s.up{color:var(--up)}.page .stat .v.dn,.page .stat .s.dn{color:var(--danger)}
|
||
.page ul.steps{list-style:none;padding:0}
|
||
.page ul.steps li{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:6px 0}
|
||
.page ul.steps .dot{width:18px;height:18px;border-radius:50%;border:2px solid var(--line);display:grid;place-items:center;font-size:var(--fs-caption)}
|
||
.page ul.steps li.done .dot{background:var(--ok);border-color:var(--ok);color:var(--on-color)}
|
||
.page ul.steps li.now .dot{border-color:var(--accent)}
|
||
.page ul.steps .nt{flex-basis:100%;padding-left:26px;font-size:var(--fs-small);color:var(--text3)}
|
||
.page .chart{margin:12px 0;border:.5px solid var(--line);border-radius:var(--r-l);overflow:hidden;background:var(--elev)}
|
||
.page .chart img{width:100%;display:block}
|
||
.page .chart .wait{padding:18px;font-size:var(--fs-small);color:var(--text3)}
|
||
/* ```chart 原生 SVG 卡(與桌面版圖表卡同款) */
|
||
.chartcard{margin:12px 0 .75em;border:.5px solid var(--line);border-radius:var(--r-l);background:none;padding:12px 12px 8px;max-width:100%;font-family:var(--font);line-height:1.45}
|
||
.bub .chartcard,.talk .chartcard{margin:6px 0;padding:8px 8px 6px}
|
||
.chartcard .ct2{font-size:var(--fs-ui);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:var(--fs-small);line-height:1.45}
|
||
.chartcard .ctab th{font-weight:600;font-size:var(--fs-small);color:var(--text2);background:none;border:0;border-bottom:1px solid var(--line);padding:6px var(--sp-3);text-align:right;white-space:nowrap}
|
||
.chartcard .ctab td{border:0;border-bottom:1px solid var(--line2);padding:6px var(--sp-3);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}
|
||
|
||
/* ---- this Mac's screen ---- */
|
||
.stage{flex:1;position:relative;background:var(--stage);display:flex;align-items:center;justify-content:center;overflow:hidden;touch-action:none}
|
||
.stage img{max-width:100%;max-height:100%;user-select:none;-webkit-user-select:none}
|
||
.stage .msg{color:var(--on-stage);font-size:var(--fs-ui);padding:20px;text-align:center}
|
||
.stage .tapdot{position:absolute;width:26px;height:26px;margin:-13px 0 0 -13px;border-radius:50%;background:color-mix(in srgb,var(--accent) 53%,transparent);pointer-events:none;animation:fade .6s forwards}
|
||
@keyframes fade{to{opacity:0;transform:scale(1.8)}}
|
||
.tools{display:flex;gap:6px;padding:8px 10px calc(var(--safe-b) + 8px);overflow-x:auto;flex:none;background:var(--chrome)}
|
||
.tools .btn{flex:none}
|
||
.typebar{display:none;gap:6px;padding:8px 10px 0;background:var(--chrome)}
|
||
.typebar.on{display:flex}
|
||
.typebar input{flex:1}
|
||
.live{display:inline-block;width:7px;height:7px;border-radius:50%;background:var(--ok);margin-right:5px}
|
||
.pair-code{font:600 var(--fs-h1)/1.2 var(--mono);text-align:center;letter-spacing:4px;padding:10px}
|
||
.pair-line{display:block;font:var(--fs-caption)/1.5 var(--mono);background:var(--hover);padding:10px;border-radius:var(--r-m);margin:6px 16px;word-break:break-all}
|
||
/* ---- feels installed (a PWA on every phone) ---- */
|
||
:root{--safe-l:env(safe-area-inset-left,0px);--safe-r:env(safe-area-inset-right,0px)}
|
||
/* No font inflation when the phone turns sideways. */
|
||
html{-webkit-text-size-adjust:100%;text-size-adjust:100%}
|
||
/* A phone on its side with a notch: every screen paints edge to edge, its content stays clear of it. */
|
||
.view{padding-left:var(--safe-l);padding-right:var(--safe-r)}
|
||
.sheet{padding-left:var(--safe-l);padding-right:var(--safe-r)}
|
||
.boxwrap{padding:0 var(--safe-r) 0 var(--safe-l)}
|
||
/* Lists bounce on their own; the page behind them never moves. */
|
||
.scroll,.sheet{overscroll-behavior:contain}
|
||
/* Controls are not text: a long press doesn't select a button's label, and a tap answers at once. */
|
||
button,.row,.ib,.island,.opt,.chip,.tab,label.sw,[role="button"]{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;touch-action:manipulation}
|
||
/* (Under 16 px, iPhone zooms the page into the field and leaves it there.) */
|
||
.searchbox input{font-size:var(--fs-read)}
|
||
/* Screens slide like an app's: a new one comes in from the right, going back comes from the left. */
|
||
@media (prefers-reduced-motion: no-preference){
|
||
.view.in-fwd{animation:in-fwd .28s cubic-bezier(.22,.8,.24,1)}
|
||
.view.in-back{animation:in-back .28s cubic-bezier(.22,.8,.24,1)}
|
||
}
|
||
@keyframes in-fwd{from{transform:translateX(32%);opacity:.35}}
|
||
@keyframes in-back{from{transform:translateX(-14%);opacity:.6}}
|
||
/* The iPhone home-screen app has no browser to swipe back with: the edge swipe moves the screen. */
|
||
.view.dragging{transition:none!important;box-shadow:-12px 0 24px var(--shade)}
|
||
/* Put AnyBot on the home screen (shown once, until installed or dismissed). */
|
||
.install{margin:2px 12px 8px;padding:12px 14px;border-radius:var(--r-l);background:var(--elev);display:none;gap:12px;align-items:center}
|
||
.install.on{display:flex}
|
||
.install img{width:44px;height:44px;border-radius:var(--r-m);flex:none}
|
||
.install .mid{flex:1;min-width:0}
|
||
.install b{display:block;font-size:var(--fs-ui);font-weight:600}
|
||
.install span{display:block;font-size:var(--fs-small);color:var(--text3);line-height:1.45;margin-top:2px}
|
||
.install .x{width:30px;height:30px;border-radius:50%;display:grid;place-items:center;color:var(--text3);flex:none}
|
||
.install .btn{flex:none}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<div class="app">
|
||
<!-- sign in -->
|
||
<section class="view" id="v-login">
|
||
<div class="scroll" style="display:flex">
|
||
<div class="login">
|
||
<img class="logo" src="icon-192.png" alt="AnyBot">
|
||
<h2 id="login-title">登入 AnyBot</h2>
|
||
<p id="login-desc">用手機和你的 Bot 聊天、核准它要做的事,也能看著它的電腦。</p>
|
||
<input class="field" id="f-user" placeholder="帳號" autocomplete="username" autocapitalize="off">
|
||
<input class="field" id="f-pass" type="password" placeholder="密碼" autocomplete="current-password">
|
||
<input class="field" id="f-invite" placeholder="邀請碼(伺服器有設定才需要)" autocapitalize="off" style="display:none">
|
||
<button class="btn main" id="b-login" style="height:44px;border-radius:var(--r-m)">登入</button>
|
||
<div class="err" id="login-err"></div>
|
||
<button class="link" id="b-mode" style="display:none">還沒有帳號?建立一個</button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- which AnyBot (an account with several) -->
|
||
<section class="view" id="v-hosts">
|
||
<div class="bar"><h1>選擇要連的 AnyBot</h1><button class="ib" id="b-out1" title="登出"></button></div>
|
||
<div class="scroll"><div class="rows" id="hosts" style="padding-top:8px"></div></div>
|
||
</section>
|
||
|
||
<!-- home: the sidebar -->
|
||
<section class="view" id="v-home">
|
||
<div class="bar">
|
||
<button class="me" id="b-me" title="帳戶選單">A</button>
|
||
<h1>AnyBot<small id="host-name"></small></h1>
|
||
<button class="ib" id="b-search" title="搜尋"></button>
|
||
<button class="ib" id="b-newbot" title="新 Bot"></button>
|
||
</div>
|
||
<div class="searchbox" id="searchbox"><span id="search-ic"></span><input id="search" placeholder="搜尋 Bot" enterkeyhint="search"><button class="ib" id="b-search-x"></button></div>
|
||
<div class="install" id="install"></div>
|
||
<div class="quick" id="quick"></div>
|
||
<div class="scroll" id="home"></div>
|
||
</section>
|
||
|
||
<!-- one chat -->
|
||
<section class="view" id="v-chat">
|
||
<div class="bar">
|
||
<button class="ib" data-back title="返回"></button>
|
||
<button class="island" id="island" title="查看對話詳細資訊"><div class="av sm" id="isl-av"></div><div class="t"><div class="n"><span id="isl-name"></span><span id="isl-chev"></span></div><div class="s" id="isl-sub"></div></div></button>
|
||
<button class="ib" id="b-newchat" title="開始新對話"></button>
|
||
<button class="ib" id="b-chatmore" title="更多"></button>
|
||
</div>
|
||
<div class="scroll" id="scroller"><div class="msgs" id="msgs"></div><div id="askq"></div></div>
|
||
<button class="down" id="b-down" title="到最新的訊息"></button>
|
||
<div class="dock">
|
||
<div id="ask"></div>
|
||
<div class="modes" id="modes"></div>
|
||
<div id="goalbar"></div>
|
||
<div id="planbar"></div>
|
||
<div id="queued"></div>
|
||
<div class="quoting" id="quoting" style="display:none"></div>
|
||
<div class="chips" id="chips"></div>
|
||
<div class="memchips" id="memchips"></div>
|
||
<div class="slash" id="slash"></div>
|
||
<div class="composer" id="composer">
|
||
<button class="cbtn plus" id="b-plus" title="輸入框操作"></button>
|
||
<input type="file" id="file" multiple hidden>
|
||
<input type="file" id="camera" accept="image/*" capture="environment" hidden>
|
||
<textarea id="input" rows="1" placeholder="傳訊息…" enterkeyhint="send"></textarea>
|
||
<button class="cbtn" id="b-mic" title="開始語音輸入"></button>
|
||
<button class="cbtn go" id="b-send" title="傳送訊息"></button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- 對話詳細資訊 -->
|
||
<section class="view" id="v-details">
|
||
<div class="bar">
|
||
<button class="ib" data-back title="關閉"></button>
|
||
<h1>對話詳細資訊</h1>
|
||
<button class="ib" id="b-botset" title="Bot 設定"></button>
|
||
</div>
|
||
<div class="scroll" id="details"></div>
|
||
</section>
|
||
|
||
<!-- Bot 設定 -->
|
||
<section class="view" id="v-botset">
|
||
<div class="bar"><button class="ib" data-back title="返回"></button><h1 id="botset-title">Bot 設定</h1></div>
|
||
<div class="scroll" id="botset"></div>
|
||
</section>
|
||
|
||
<!-- a list screen: 例行任務 / 頁面 / 電腦 / 設定 and its sections -->
|
||
<section class="view" id="v-list">
|
||
<div class="bar"><button class="ib" data-back title="返回"></button><h1 id="list-title"></h1><span id="list-act"></span></div>
|
||
<div class="scroll" id="list"></div>
|
||
</section>
|
||
|
||
<!-- a page -->
|
||
<section class="view" id="v-page">
|
||
<div class="bar">
|
||
<button class="ib" data-back title="返回"></button>
|
||
<h1 id="page-name">頁面</h1>
|
||
<button class="ib" id="b-pagemore" title="更多"></button>
|
||
</div>
|
||
<div class="scroll" id="pscroll"><div class="page" id="page"></div></div>
|
||
</section>
|
||
|
||
<!-- 檔案: a chat file's preview (image / PDF pages / text / sheet / media) -->
|
||
<section class="view" id="v-file">
|
||
<div class="bar">
|
||
<button class="ib" data-back title="返回"></button>
|
||
<h1 id="file-name">檔案</h1>
|
||
<button class="ib" id="b-filesave" title="儲存"></button>
|
||
</div>
|
||
<div class="scroll" id="filebody"><div class="empty">載入中…</div></div>
|
||
<div class="pager" id="filepager" style="display:none">
|
||
<button class="btn sm" id="f-prev">‹ 上一頁</button><span id="f-at"></span><button class="btn sm" id="f-next">下一頁 ›</button>
|
||
</div>
|
||
</section>
|
||
|
||
<!-- this Mac's screen -->
|
||
<section class="view" id="v-screen">
|
||
<div class="bar"><button class="ib" data-back title="返回"></button><h1>這台 Mac</h1><span class="pill" id="screen-live"></span></div>
|
||
<div class="stage" id="stage"><div class="msg">載入中…</div></div>
|
||
<div class="typebar" id="typebar"><input class="field" id="typein" placeholder="要打的字(會打進目前的視窗)" enterkeyhint="send"><button class="btn main" id="b-type">送出</button></div>
|
||
<div class="tools">
|
||
<button class="btn sm" id="k-type">打字</button>
|
||
<button class="btn sm" data-key="Return">Enter</button>
|
||
<button class="btn sm" data-key="Escape">Esc</button>
|
||
<button class="btn sm" data-key="Tab">Tab</button>
|
||
<button class="btn sm" data-key="BackSpace">刪除</button>
|
||
<button class="btn sm" data-scroll="up">↑ 捲動</button>
|
||
<button class="btn sm" data-scroll="down">↓ 捲動</button>
|
||
<button class="btn sm" id="k-right">右鍵:關</button>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
<div class="toast" id="toast"></div>
|
||
<!-- one sheet for every menu and picker -->
|
||
<div class="sheet-bg" id="sheet"><div class="sheet" id="sheet-in"></div></div>
|
||
<!-- 接管: the bot's computer, screen.html embedded over the app (its ✕ posts a close) -->
|
||
<div class="boxwrap" id="boxwrap"><iframe id="boxframe" title="Bot 的電腦" allow="clipboard-write"></iframe></div>
|
||
<script>
|
||
"use strict";
|
||
// Lucide icons (ISC licence), the set the desktop app uses.
|
||
const LUCIDE = {
|
||
"send": '<path d="M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"/><path d="m21.854 2.147-10.94 10.939"/>',
|
||
"image": '<rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>',
|
||
"file": '<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"/><path d="M14 2v5a1 1 0 0 0 1 1h5"/>',
|
||
"file-text": '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/>',
|
||
"circle-check": '<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>',
|
||
"circle-alert": '<circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/>',
|
||
"circle-x": '<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>',
|
||
"loader": '<path d="M12 2v4"/><path d="m16.2 7.8 2.9-2.9"/><path d="M18 12h4"/><path d="m16.2 16.2 2.9 2.9"/><path d="M12 18v4"/><path d="m4.9 19.1 2.9-2.9"/><path d="M2 12h4"/><path d="m4.9 4.9 2.9 2.9"/>',
|
||
"minus": '<path d="M5 12h14"/>',
|
||
"x": '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
|
||
"plus": '<path d="M5 12h14"/><path d="M12 5v14"/>',
|
||
"check": '<path d="M20 6 9 17l-5-5"/>',
|
||
"search": '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>',
|
||
"chevron-left": '<path d="m15 18-6-6 6-6"/>',
|
||
"chevron-right": '<path d="m9 18 6-6-6-6"/>',
|
||
"chevron-down": '<path d="m6 9 6 6 6-6"/>',
|
||
"chevron-up": '<path d="m18 15-6-6-6 6"/>',
|
||
"ellipsis": '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
|
||
"settings": '<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',
|
||
"star": '<path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"/>',
|
||
"pin": '<path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/>',
|
||
"folder": '<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/>',
|
||
"trash": '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>',
|
||
"reply": '<polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/>',
|
||
"smile-plus": '<path d="M22 11v1a10 10 0 1 1-9-10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" x2="9.01" y1="9" y2="9"/><line x1="15" x2="15.01" y1="9" y2="9"/><path d="M16 5h6"/><path d="M19 2v6"/>',
|
||
"audio-lines": '<path d="M2 10v3"/><path d="M6 6v11"/><path d="M10 3v18"/><path d="M14 8v7"/><path d="M18 5v13"/><path d="M22 10v3"/>',
|
||
"mic": '<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" x2="12" y1="19" y2="22"/>',
|
||
"arrow-up": '<path d="m5 12 7-7 7 7"/><path d="M12 19V5"/>',
|
||
"arrow-down": '<path d="M12 5v14"/><path d="m19 12-7 7-7-7"/>',
|
||
"stop": '<rect width="10" height="10" x="7" y="7" rx="1.5" fill="currentColor" stroke="none"/>',
|
||
"play": '<polygon points="6 3 20 12 6 21 6 3"/>',
|
||
"pause": '<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>',
|
||
"pen": '<path d="M12 20h9"/><path d="M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z"/>',
|
||
"copy": '<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
|
||
"refresh": '<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>',
|
||
"history": '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>',
|
||
"monitor": '<rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/>',
|
||
"laptop": '<path d="M18 5a2 2 0 0 1 2 2v8.526a2 2 0 0 0 .212.897l1.068 2.127a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45l1.068-2.127A2 2 0 0 0 4 15.526V7a2 2 0 0 1 2-2z"/><path d="M20.054 15.987H3.946"/>',
|
||
"cloud": '<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z"/>',
|
||
"server": '<rect width="20" height="8" x="2" y="2" rx="2" ry="2"/><rect width="20" height="8" x="2" y="14" rx="2" ry="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/>',
|
||
"target": '<circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>',
|
||
"alarm-clock": '<circle cx="12" cy="13" r="8"/><path d="M12 9v4l2 2"/><path d="M5 3 2 6"/><path d="m22 6-3-3"/><path d="M6.38 18.7 4 21"/><path d="M17.64 18.67 20 21"/>',
|
||
"sparkles": '<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/>',
|
||
"list-checks": '<path d="m3 17 2 2 4-4"/><path d="m3 7 2 2 4-4"/><path d="M13 6h8"/><path d="M13 12h8"/><path d="M13 18h8"/>',
|
||
"camera": '<path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/>',
|
||
"paperclip": '<path d="m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"/>',
|
||
"log-out": '<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" x2="9" y1="12" y2="12"/>',
|
||
"bell": '<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/>',
|
||
"moon": '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>',
|
||
"shield": '<path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/>',
|
||
"plug": '<path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/>',
|
||
"users": '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
|
||
"bookmark": '<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/>',
|
||
"power": '<path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>',
|
||
"share": '<path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" x2="12" y1="2" y2="15"/>',
|
||
"download": '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',
|
||
"globe": '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
|
||
"key": '<circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/>',
|
||
"lock": '<rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>',
|
||
"message": '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
|
||
"hand": '<path d="M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2"/><path d="M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2"/><path d="M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8"/><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/>',
|
||
"zap": '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',
|
||
"lightbulb": '<path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/>',
|
||
"activity": '<path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/>',
|
||
"eye": '<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/>',
|
||
"hard-drive": '<line x1="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/>',
|
||
"info": '<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>',
|
||
"smartphone": '<rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/>',
|
||
"terminal": '<polyline points="4 17 10 11 4 5"/><line x1="12" x2="20" y1="19" y2="19"/>',
|
||
"brain": '<path d="M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"/><path d="M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"/><path d="M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"/>',
|
||
"keyboard": '<path d="M10 8h.01"/><path d="M12 12h.01"/><path d="M14 8h.01"/><path d="M16 12h.01"/><path d="M18 8h.01"/><path d="M6 8h.01"/><path d="M7 16h10"/><path d="M8 12h.01"/><rect width="20" height="16" x="2" y="4" rx="2"/>',
|
||
"bot": '<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>',
|
||
};
|
||
function ic(name, size = 18) { return `<svg class="ic" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${LUCIDE[name] || ""}</svg>`; }
|
||
const $ = (id) => document.getElementById(id);
|
||
function esc(s) { return String(s ?? "").replace(/[&<>"']/g, (c) => ({"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}[c])); }
|
||
function toast(t) { const e = $("toast"); e.textContent = t; e.classList.add("on"); clearTimeout(toast.t); toast.t = setTimeout(() => e.classList.remove("on"), 2600); }
|
||
const nap = (ms) => new Promise((r) => setTimeout(r, ms));
|
||
// Times as the desktop's sidebar shows them: 剛剛 / 5 分鐘 / 3 小時 / 昨天 / 4 天 / 11/5.
|
||
function ago(ms) {
|
||
if (!ms) return "";
|
||
const s = (Date.now() - ms) / 1000;
|
||
if (s < 60) return "剛剛";
|
||
if (s < 3600) return Math.floor(s / 60) + " 分鐘";
|
||
const d = new Date(ms), now = new Date();
|
||
if (d.toDateString() === now.toDateString()) return Math.floor(s / 3600) + " 小時";
|
||
const y = new Date(now); y.setDate(now.getDate() - 1);
|
||
if (d.toDateString() === y.toDateString()) return "昨天";
|
||
if (s < 7 * 86400) return Math.ceil(s / 86400) + " 天";
|
||
return `${d.getMonth() + 1}/${d.getDate()}`;
|
||
}
|
||
function clock(ms) { return ms ? new Date(ms).toLocaleTimeString("zh-TW", {hour: "numeric", minute: "2-digit"}) : ""; }
|
||
// "2026-11-11 13:52" in this phone's time zone (the brain may be a server running in UTC).
|
||
function stamp(ms) {
|
||
if (typeof ms !== "number") return String(ms ?? "");
|
||
const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
|
||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
||
}
|
||
function dayLabel(ms) {
|
||
const d = new Date(ms), now = new Date(), y = new Date(now); y.setDate(now.getDate() - 1);
|
||
if (d.toDateString() === now.toDateString()) return "今天";
|
||
if (d.toDateString() === y.toDateString()) return "昨天";
|
||
return d.getFullYear() === now.getFullYear() ? `${d.getMonth() + 1} 月 ${d.getDate()} 日` : `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;
|
||
}
|
||
// Plain words of a message for a one-line preview (no Markdown marks).
|
||
function plain(t) { return String(t || "").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/[*_`#>]/g, "").replace(/\s+/g, " ").trim(); }
|
||
|
||
// 外觀 of this phone: follow it, or light or dark by hand.
|
||
// 外觀 of this phone: the computer's (設定 › 一般 › 外觀 › 主題, the default), the phone's own, or light
|
||
// or dark by hand.
|
||
const THEMES = [["", "跟著電腦"], ["system", "跟著手機"], ["light", "淺色"], ["dark", "深色"]];
|
||
// What the computer said last (kept, so the next start wears it before the brain answers).
|
||
const DESK = {theme: ""};
|
||
function phoneTheme() { try { return localStorage.getItem("anybot.theme") || ""; } catch (_) { return ""; } }
|
||
function applyTheme() {
|
||
const pick = phoneTheme();
|
||
const t = pick === "light" || pick === "dark" ? pick : pick === "system" ? "" : ["light", "dark"].includes(DESK.theme) ? DESK.theme : "";
|
||
if (t) document.documentElement.dataset.theme = t; else delete document.documentElement.dataset.theme;
|
||
if (typeof barColor === "function") barColor();
|
||
}
|
||
// The computer's colours (底色, 強調色, 對比 — theme::shell, light and dark) as this page's CSS
|
||
// variables. Only names and #hex colours go in; an older brain sends none and the built-in 紙 stays.
|
||
function paletteCss(p) {
|
||
if (!p || typeof p !== "object") return "";
|
||
const block = (o) => Object.entries(o && typeof o === "object" ? o : {}).filter(([k, v]) => /^[a-z0-9-]{2,20}$/.test(k) && /^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(String(v))).map(([k, v]) => `--${k}:${v}`).join(";");
|
||
const l = block(p.light), d = block(p.dark);
|
||
if (!l || !d) return "";
|
||
return `:root{${l}}:root[data-theme="light"]{${l}}@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){${d}}}:root[data-theme="dark"]{${d}}`;
|
||
}
|
||
function applyPalette(p) {
|
||
const css = paletteCss(p);
|
||
let el = document.getElementById("desk-palette");
|
||
if (!el) { el = document.createElement("style"); el.id = "desk-palette"; document.head.appendChild(el); }
|
||
if (el.textContent === css) return;
|
||
el.textContent = css;
|
||
try { if (css) localStorage.setItem("anybot.palette", JSON.stringify(p)); else localStorage.removeItem("anybot.palette"); } catch (_) {}
|
||
if (typeof barColor === "function") barColor();
|
||
}
|
||
try { DESK.theme = localStorage.getItem("anybot.desk-theme") || ""; applyPalette(JSON.parse(localStorage.getItem("anybot.palette") || "null")); } catch (_) {}
|
||
applyTheme();
|
||
// The phone switching light/dark while open: the status bar follows.
|
||
try { matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => barColor()); } catch (_) {}
|
||
|
||
const S = { sending: [], voice: {},
|
||
relay: false, token: localStorage.getItem("anybot.token") || "", host: localStorage.getItem("anybot.host") || "",
|
||
version: 0, bots: [], approvals: [], pages: [], models: [], hostName: "", mac: false, box: "", boxOn: false, role: "owner",
|
||
prevShown: 0, prevFirst: "", answer: null, sc: "",
|
||
open: 0, msgs: [], pending: [], quote: null, unfold: {}, openSteps: {}, detail: {}, audit: {}, settings: null, polling: false,
|
||
chatSig: "", file: null,
|
||
search: "", size: [0, 0], right: false,
|
||
};
|
||
const owner = () => S.role !== "member";
|
||
const isOwner = () => S.role === "owner";
|
||
const bot = (id) => S.bots.find((b) => b.id === id);
|
||
function base() { return S.relay ? "h/" + encodeURIComponent(S.host) + "/" : ""; }
|
||
|
||
async function api(path, opts = {}) {
|
||
const headers = Object.assign({}, opts.headers || {});
|
||
if (S.token) headers.Authorization = "Bearer " + S.token;
|
||
if (opts.json !== undefined) { headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(opts.json); }
|
||
const r = await fetch(path, {method: opts.method || (opts.body ? "POST" : "GET"), headers, body: opts.body});
|
||
const signingIn = /(^|\/)(login|signup)$/.test(path);
|
||
if (r.status === 401 && !signingIn) { signOut(true); throw new Error("請重新登入"); }
|
||
if (opts.raw) return r;
|
||
const t = await r.text();
|
||
let v = {}; try { v = t ? JSON.parse(t) : {}; } catch (_) {}
|
||
if (!r.ok) throw new Error(v.error || ("HTTP " + r.status));
|
||
return v;
|
||
}
|
||
// One of the desktop's actions (api/act/<what>), with its answer as a toast.
|
||
async function act(what, body, ok) {
|
||
try {
|
||
const v = await api(base() + "api/act/" + what, {json: body || {}});
|
||
if (ok !== false) toast(ok || v.text || "好了");
|
||
return v;
|
||
} catch (e) { toast(e.message); return null; }
|
||
}
|
||
const app = (name, args, b, ok) => act("app", {bot: b || S.open || 0, name, args}, ok);
|
||
|
||
// A bot's face as in the app (src/avatar.rs): its shape in its colour, two slanted oval eyes.
|
||
const color = (c) => (/^#[0-9a-f]{6}$/i.test(String(c || "")) ? c : "#1c1c1c");
|
||
function avatarSvg(shape, hex) {
|
||
const col = color(hex), P = Math.PI, f = (n) => n.toFixed(3);
|
||
const pts = (a) => `<polygon points="${a.map(([x, y]) => f(x) + "," + f(y)).join(" ")}"/>`;
|
||
const circ = (x, y, r) => `<circle cx="${f(x)}" cy="${f(y)}" r="${f(r)}"/>`;
|
||
const range = (n) => [...Array(n).keys()];
|
||
let body;
|
||
switch (shape) {
|
||
case "squircle": body = `<rect x="-0.92" y="-0.92" width="1.84" height="1.84" rx="0.42"/>`; break;
|
||
case "capsule": body = `<rect x="-0.675" y="-1" width="1.35" height="2" rx="0.66"/>`; break;
|
||
case "egg": body = pts(range(48).map((i) => { const t = i / 48 * 2 * P; return [0.8 * Math.cos(t), 0.08 + (Math.sin(t) < 0 ? 1 : 0.86) * Math.sin(t)]; })); break;
|
||
case "hex": body = pts(range(6).map((i) => { const a = i / 6 * 2 * P + P / 6; return [Math.cos(a), Math.sin(a)]; })); break;
|
||
case "gem": body = pts([[-0.55, -0.8], [0.55, -0.8], [1, -0.2], [0, 1], [-1, -0.2]]); break;
|
||
case "arch": body = pts(range(25).map((i) => { const a = P + i / 24 * P; return [0.85 * Math.cos(a), -0.15 + 0.85 * Math.sin(a)]; }).concat([[0.85, 1], [-0.85, 1]])); break;
|
||
case "shield": body = pts([[-0.85, -0.9], [0.85, -0.9], [0.85, 0.05], [0.5, 0.65], [0, 1], [-0.5, 0.65], [-0.85, 0.05]]); break;
|
||
case "pebble": body = `<ellipse rx="1" ry="0.78" transform="rotate(-14.3)"/>`; break;
|
||
case "cloud": body = circ(-0.45, 0.15, 0.55) + circ(0.45, 0.15, 0.55) + circ(0, -0.2, 0.65) + circ(0, 0.35, 0.55); break;
|
||
case "heart": body = circ(-0.45, -0.25, 0.55) + circ(0.45, -0.25, 0.55) + pts([[-0.97, -0.1], [0.97, -0.1], [0, 1]]); break;
|
||
case "star": body = pts(range(10).map((i) => { const a = -P / 2 + i * P / 5, r = i % 2 ? 0.48 : 1.05; return [r * Math.cos(a), 0.08 + r * Math.sin(a)]; })); break;
|
||
case "blob": body = pts(range(40).map((i) => { const a = i / 40 * 2 * P, r = 0.92 + 0.08 * Math.sin(3 * a); return [r * Math.cos(a), r * Math.sin(a)]; })); break;
|
||
default: body = circ(0, 0, 0.95);
|
||
}
|
||
const rgb = [1, 3, 5].map((i) => parseInt(col.slice(i, i + 2), 16));
|
||
const eye = rgb[0] + rgb[1] + rgb[2] > 600 ? "#1c1c1c" : "#fcfcfc";
|
||
const eyes = [-0.27, 0.27].map((x) => `<ellipse cx="${x}" cy="0.02" rx="0.11" ry="0.22" transform="rotate(-20 ${x} 0.02)"/>`).join("");
|
||
// A near-black bot gets a hairline edge: in dark it was only two eyes floating on the page.
|
||
const edge = rgb[0] + rgb[1] + rgb[2] < 150 ? ` style="stroke:var(--line)" stroke-width="0.08"` : "";
|
||
return `<svg viewBox="-1.1 -1.1 2.2 2.2" aria-hidden="true"><g fill="${col}"${edge}>${body}</g><g fill="${eye}">${eyes}</g></svg>`;
|
||
}
|
||
const face = (b, cls = "") => `<div class="av ${cls}">${avatarSvg(b.shape, b.color)}</div>`;
|
||
|
||
// ---------- the one sheet: menus, pickers, forms ----------
|
||
// opts: [{icon, label, x (right text), check, danger, on: fn}] or html; a tap runs on() and closes.
|
||
function sheet(title, items, html) {
|
||
const el = $("sheet-in");
|
||
el.innerHTML = `<div class="grab"></div>${title ? `<div class="st">${esc(title)}</div>` : ""}` + (html || "") +
|
||
(items || []).map((o, i) => o.sep ? `<div class="sep"></div>` : o.group ? `<div class="grp">${esc(o.group)}</div>` : `<button class="opt ${o.danger ? "danger" : ""}" data-i="${i}">${o.icon ? ic(o.icon, 20) : ""}<span>${esc(o.label)}</span>${o.check ? `<span class="ck">${ic("check", 18)}</span>` : o.x ? `<span class="x">${esc(o.x)}</span>` : ""}</button>`).join("");
|
||
el.querySelectorAll(".opt[data-i]").forEach((b) => b.onclick = () => { const o = items[+b.dataset.i]; if (!o.keep) closeSheet(); o.on && o.on(); });
|
||
$("sheet").classList.add("on");
|
||
return el;
|
||
}
|
||
function closeSheet() { $("sheet").classList.remove("on"); }
|
||
$("sheet").onclick = (e) => { if (e.target.id === "sheet") closeSheet(); };
|
||
// A question with a text answer (prompt() looks out of place on a phone).
|
||
function ask(title, value = "", placeholder = "", multi = false) {
|
||
return new Promise((done) => {
|
||
const el = sheet(title, [], `<div class="form">${multi ? `<textarea class="field" id="ask-in" placeholder="${esc(placeholder)}">${esc(value)}</textarea>` : `<input class="field" id="ask-in" value="${esc(value)}" placeholder="${esc(placeholder)}">`}<div class="row2" style="justify-content:flex-end;margin-top:6px"><button class="btn" id="ask-no">取消</button><button class="btn main" id="ask-ok">好</button></div></div>`);
|
||
const input = el.querySelector("#ask-in"); setTimeout(() => input.focus(), 50);
|
||
el.querySelector("#ask-no").onclick = () => { closeSheet(); done(null); };
|
||
el.querySelector("#ask-ok").onclick = () => { closeSheet(); done(input.value.trim()); };
|
||
if (!multi) input.onkeydown = (e) => { if (e.key === "Enter" && !e.isComposing) el.querySelector("#ask-ok").click(); };
|
||
});
|
||
}
|
||
function confirmSheet(title, note, yes, danger = true) {
|
||
return new Promise((done) => {
|
||
sheet(title, [{label: yes, danger, icon: danger ? "trash" : "check", on: () => done(true)}, {label: "取消", on: () => done(false)}], note ? `<div class="note" style="text-align:center">${esc(note)}</div>` : "");
|
||
});
|
||
}
|
||
|
||
// ---------- screens: a stack, the phone's back gesture goes back ----------
|
||
const NAV = [];
|
||
function show(v) {
|
||
const was = S.view;
|
||
document.querySelectorAll(".view").forEach((x) => x.classList.toggle("on", x.id === "v-" + v));
|
||
S.view = v; if (v !== "screen") stopFrames(); if (v !== "list") stopListTimer();
|
||
// A new screen slides in (forward from the right, back from the left); redrawing the same one doesn't.
|
||
const el = $("v-" + v), dir = S.dir; S.dir = "";
|
||
if (el && dir && was && was !== v) { el.classList.remove("in-fwd", "in-back"); void el.offsetWidth; el.classList.add(dir); el.addEventListener("animationend", () => el.classList.remove(dir), {once: true}); }
|
||
barColor();
|
||
}
|
||
// Android's status bar (and the browser's own bar) in the colour of the top of the screen showing.
|
||
function barColor() {
|
||
const top = document.querySelector(".view.on .bar") || document.querySelector(".view.on") || document.body;
|
||
const c = getComputedStyle(top).backgroundColor;
|
||
if (!c || c === "rgba(0, 0, 0, 0)") return;
|
||
document.querySelectorAll('meta[name="theme-color"]').forEach((m) => m.setAttribute("content", c));
|
||
}
|
||
function go(v, arg = {}, replace = false) {
|
||
S.dir = replace ? "" : "in-fwd";
|
||
if (replace && NAV.length) NAV[NAV.length - 1] = {v, arg}; else NAV.push({v, arg});
|
||
if (replace) history.replaceState({n: NAV.length}, ""); else history.pushState({n: NAV.length}, "");
|
||
draw(v, arg);
|
||
}
|
||
function back() { if (NAV.length > 1) history.back(); else go("home", {}, true); }
|
||
window.addEventListener("popstate", () => {
|
||
if (!S.token) return;
|
||
if (boxOpen) { closeBox(); return; } // the takeover overlay sits above the stack; back closes it
|
||
NAV.pop();
|
||
if (!NAV.length) { NAV.push({v: "home", arg: {}}); history.pushState({n: 1}, ""); }
|
||
const t = NAV[NAV.length - 1];
|
||
S.dir = S.swiped ? "" : "in-back"; S.swiped = false;
|
||
closeSheet();
|
||
draw(t.v, t.arg);
|
||
});
|
||
document.querySelectorAll("[data-back]").forEach((b) => { b.innerHTML = ic("chevron-left", 24); b.onclick = back; });
|
||
function draw(v, arg) {
|
||
show(v);
|
||
if (v === "home") renderHome();
|
||
else if (v === "chat") openChat(arg.bot);
|
||
else if (v === "details") renderDetails(arg.bot, arg.tab);
|
||
else if (v === "botset") renderBotset(arg.bot);
|
||
else if (v === "list") renderList(arg);
|
||
else if (v === "page") openPage(arg.id, arg.rev);
|
||
else if (v === "screen") startFrames();
|
||
}
|
||
const cur = () => NAV[NAV.length - 1] || {v: "home", arg: {}};
|
||
|
||
// ---------- sign in ----------
|
||
async function hello() {
|
||
try { const r = await fetch("api/hello"); const v = await r.json(); S.relay = v.app === "anybot-relay"; } catch (_) { S.relay = false; }
|
||
$("f-user").style.display = S.relay ? "" : "none";
|
||
$("b-mode").style.display = S.relay ? "" : "none";
|
||
$("login-desc").textContent = S.relay ? "用你的 AnyBot 帳號登入。在哪裡都能用,電腦不用開任何連接埠。" : "輸入這台 AnyBot 的手機密碼(在 AnyBot 設定 › 手機與帳號 設定)。";
|
||
if (!S.token) return show("login");
|
||
if (S.relay) return pickHost();
|
||
start();
|
||
}
|
||
let signingUp = false;
|
||
$("b-mode").onclick = () => {
|
||
signingUp = !signingUp;
|
||
$("f-invite").style.display = signingUp ? "" : "none";
|
||
$("b-login").textContent = signingUp ? "建立帳號並登入" : "登入";
|
||
$("b-mode").textContent = signingUp ? "已經有帳號?登入" : "還沒有帳號?建立一個";
|
||
$("login-title").textContent = signingUp ? "建立 AnyBot 帳號" : "登入 AnyBot";
|
||
$("f-pass").placeholder = signingUp ? "密碼(至少 8 個字)" : "密碼";
|
||
};
|
||
$("b-login").onclick = async () => {
|
||
const b = $("b-login"); b.disabled = true; $("login-err").textContent = "";
|
||
const device = (navigator.userAgent.match(/iPhone|iPad|Android|Mac|Windows/) || ["手機"])[0];
|
||
try {
|
||
if (S.relay && signingUp) await api("relay/signup", {json: {user: $("f-user").value.trim(), password: $("f-pass").value, invite: $("f-invite").value.trim()}});
|
||
const v = await api(S.relay ? "relay/login" : "api/login", {json: {user: $("f-user").value.trim(), password: $("f-pass").value, device}});
|
||
if (v.need_2fa) {
|
||
// 開了两步验证:密码只是第一步,验证器 App 上的六位数(或一张恢复码)才换来通行证。
|
||
const code = (prompt("Two-step 验证:输入 App 上的六位验证码(没有 App 可用一张恢复码)") || "").trim();
|
||
if (!code) throw new Error("已取消");
|
||
const v2 = await api("relay/2fa/verify", {json: {challenge: v.challenge, code}});
|
||
v.token = v2.token;
|
||
}
|
||
S.token = v.token; localStorage.setItem("anybot.token", S.token); $("f-pass").value = "";
|
||
if (S.relay) await pickHost(); else start();
|
||
} catch (e) { $("login-err").textContent = e.message; }
|
||
b.disabled = false;
|
||
};
|
||
$("f-pass").addEventListener("keydown", (e) => { if (e.key === "Enter") $("b-login").click(); });
|
||
function signOut(expired) {
|
||
if (S.token && !expired) api(S.relay ? "relay/logout" : "api/logout", {json: {}}).catch(() => {});
|
||
S.token = ""; localStorage.removeItem("anybot.token"); S.version = 0; NAV.length = 0; show("login");
|
||
if (expired) $("login-err").textContent = "登入已失效,請重新登入";
|
||
}
|
||
$("b-out1").innerHTML = ic("log-out", 20);
|
||
$("b-out1").onclick = () => signOut();
|
||
|
||
// The list waits for a brain that is restarting (or a computer that woke up): it looks again
|
||
// every few seconds and goes in by itself.
|
||
let hostRetry = null;
|
||
async function pickHost() {
|
||
clearTimeout(hostRetry);
|
||
let me;
|
||
try { me = await api("relay/me"); } catch (e) { toast(e.message); if (S.token) hostRetry = setTimeout(pickHost, 3000); return; }
|
||
const all = me.hosts || [];
|
||
const byId = Object.fromEntries(all.map((h) => [h.id, h]));
|
||
// A link or an old choice that isn't one of this account's AnyBots is forgotten.
|
||
if (S.host && !byId[S.host]) { S.host = ""; localStorage.removeItem("anybot.host"); }
|
||
// 團隊邀請: someone shared their AnyBot with this account — nothing is opened until yes.
|
||
for (const inv of me.invites || []) {
|
||
const yes = await confirmSheet(`「${inv.owner}」邀請你使用他的 AnyBot「${inv.name}」`, `角色:${inv.role === "admin" ? "管理員" : "成員"}。接受後它會出現在你的清單裡。只接受你認識的人:對方的 AnyBot 回傳的內容會顯示在這裡。`, "接受", false);
|
||
try { await api("relay/invites", {json: {host: inv.host, accept: !!yes}}); } catch (e) { toast(e.message); }
|
||
if (yes) return pickHost();
|
||
}
|
||
const target = (id) => (byId[id] && byId[id].uses && byId[byId[id].uses]) ? byId[id].uses : id;
|
||
const hosts = all.filter((h) => !(h.uses && byId[h.uses]));
|
||
const sharers = (id) => all.filter((h) => h.uses === id).map((h) => h.name);
|
||
const live = hosts.filter((h) => h.online);
|
||
const used = live.filter((h) => sharers(h.id).length);
|
||
if (!S.host && used.length === 1) S.host = used[0].id;
|
||
if (S.host) {
|
||
const t = target(S.host);
|
||
if (byId[t] && byId[t].online) { S.host = t; localStorage.setItem("anybot.host", t); return start(); }
|
||
}
|
||
if (live.length === 1) { S.host = live[0].id; localStorage.setItem("anybot.host", S.host); return start(); }
|
||
const note = (h) => { const n = sharers(h.id); return n.length ? " · " + esc(n.join("、")) + " 也用這個大腦" : ""; };
|
||
const wanted = (S.host && byId[target(S.host)]) || (all.find((h) => sharers(h.id).length)) || hosts[0];
|
||
const waiting = hosts.length && !live.length && wanted ? `<div class="empty">「${esc(wanted.name)}」暫時沒有連線(可能正在重新啟動,或那台電腦睡著了)。<br>連上後會自動進入,不用重新整理。</div>` : "";
|
||
$("hosts").innerHTML = waiting + (hosts.length ? hosts.map((h) => `<div class="row" data-h="${esc(h.id)}"><div class="av" style="border-radius:var(--r-m);background:var(--active)">${ic(h.online ? "monitor" : "power", 18)}</div><div class="mid"><div class="nm"><span class="t">${esc(h.name)}</span></div><div class="pv ${h.online ? "busy" : ""}">${h.online ? "在線上" : "離線(" + esc(h.last_seen_text || "很久沒連線") + ")"}${note(h)}</div></div></div>`).join("")
|
||
: `<div class="empty">這個帳號還沒有連上任何 AnyBot。<br>在電腦上打開 AnyBot › 設定 › 手機與帳號,登入同一個帳號。</div>`);
|
||
document.querySelectorAll("#hosts .row").forEach((r) => r.onclick = () => { clearTimeout(hostRetry); S.host = r.dataset.h; localStorage.setItem("anybot.host", S.host); start(); });
|
||
show("hosts");
|
||
if (S.token && !live.length) hostRetry = setTimeout(pickHost, 3000);
|
||
}
|
||
|
||
// ---------- live state ----------
|
||
const TZ = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ""; } catch (_) { return ""; } })();
|
||
async function start() {
|
||
if (!NAV.length) {
|
||
NAV.push({v: "home", arg: {}}); history.replaceState({n: 1}, "");
|
||
if (S.open) go("chat", {bot: S.open}); else draw("home", {});
|
||
} else { const t = cur(); draw(t.v, t.arg); }
|
||
if (S.polling) return;
|
||
S.polling = true;
|
||
while (S.token) {
|
||
try {
|
||
// 單趟同步: when a chat is open, the state poll carries its messages too — sent only
|
||
// when their signature changed (api/state?bot=…&chat_sig=…).
|
||
const open = S.view === "chat" && S.open ? "&bot=" + S.open + "&chat_sig=" + encodeURIComponent(S.chatSig) : "";
|
||
const v = await api(base() + "api/state?since=" + S.version + "&tz=" + encodeURIComponent(TZ) + open);
|
||
if (v.version !== S.version) { S.version = v.version; apply(v); }
|
||
} catch (e) {
|
||
if (!S.token) break;
|
||
if (S.relay && /離線|offline|not connected/i.test(e.message)) toast("那台 AnyBot 目前沒有連線");
|
||
await nap(2500);
|
||
}
|
||
}
|
||
S.polling = false;
|
||
}
|
||
function apply(v) {
|
||
S.bots = v.bots || []; S.approvals = v.approvals || []; S.hostName = v.host || ""; S.mac = !!v.mac;
|
||
// An approval answered from a notification banner, and a home-screen shortcut (主要 Bot, 未讀).
|
||
if (S.answer && S.token) {
|
||
const a = S.answer; S.answer = null;
|
||
api(base() + `api/bots/${a.bot}/answer`, {json: {answer: a.answer, call: a.call}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message));
|
||
}
|
||
if (S.sc && !S.open) {
|
||
const want = S.sc === "unread" ? S.bots.find((b) => b.unread) : (S.bots.find((b) => b.primary) || S.bots[0]);
|
||
S.sc = "";
|
||
if (want) { S.open = want.id; go("chat", {bot: want.id}); }
|
||
}
|
||
S.box = v.box || ""; S.boxOn = !!v.box_available; S.pages = v.pages || []; S.models = v.models || []; S.sections = v.sections || null; S.role = v.role || "owner";
|
||
S.voice = v.voice || {}; micShown(); appBadge();
|
||
// The computer's 外觀 (an older brain sends neither: the built-in look stays).
|
||
if (v.palettes) applyPalette(v.palettes);
|
||
if (typeof v.theme === "string" && v.theme !== DESK.theme) { DESK.theme = v.theme; try { localStorage.setItem("anybot.desk-theme", v.theme); } catch (_) {} applyTheme(); }
|
||
const t = cur();
|
||
if (t.v === "home") renderHome();
|
||
else if (t.v === "chat") {
|
||
chatHead(); renderDock();
|
||
const c = v.chat;
|
||
// (A poll that left before the person switched chats carries the old chat: ignore it.)
|
||
if (c && c.bot === S.open && c.unchanged) { /* the chat did not change — nothing to draw */ }
|
||
else if (c && c.bot === S.open && c.messages) applyChat(c.messages, c.sig);
|
||
else loadChat();
|
||
}
|
||
else if (t.v === "details" && S.tab !== "memory" && Date.now() - (S.detailAt || 0) > 1500) renderDetails(t.arg.bot, S.tab, true);
|
||
}
|
||
|
||
// ---------- home: the sidebar ----------
|
||
$("b-search").innerHTML = ic("search", 20); $("b-newbot").innerHTML = ic("plus", 22); $("search-ic").innerHTML = ic("search", 16); $("b-search-x").innerHTML = ic("x", 16);
|
||
$("b-search").onclick = () => { $("searchbox").classList.add("on"); $("search").focus(); };
|
||
$("b-search-x").onclick = () => { $("search").value = ""; S.search = ""; $("searchbox").classList.remove("on"); renderHome(); };
|
||
$("search").oninput = () => { S.search = $("search").value.trim().toLowerCase(); renderHome(); };
|
||
function botState(b) {
|
||
const waiting = S.approvals.find((a) => a.bot === b.id);
|
||
if (waiting) return {cls: "wait", dot: "wait", text: waiting.kind === "question" ? "等你回答:" + waiting.reason : "等你處理:" + (waiting.kind === "handoff" ? waiting.reason : waiting.title)};
|
||
if (b.busy) return {cls: "busy", dot: "busy", text: b.status || "工作中…"};
|
||
return {cls: "", dot: b.unread ? "unread" : "", text: plain(b.last) || b.description || "還沒有訊息"};
|
||
}
|
||
function botRow(b) {
|
||
const st = botState(b);
|
||
return `<div class="row" data-bot="${b.id}">${`<div class="av">${avatarSvg(b.shape, b.color)}${st.dot ? `<span class="dot ${st.dot}"></span>` : ""}</div>`}<div class="mid"><div class="nm"><span class="t">${esc(b.name)}</span>${b.members ? '<span class="pill">群組</span>' : ""}</div><div class="pv ${st.cls}">${esc(st.text)}</div></div><div class="tm">${ago(b.time)}</div><button class="more" data-botmenu="${b.id}" title="更多">${ic("ellipsis", 18)}</button></div>`;
|
||
}
|
||
function renderHome() {
|
||
installHint();
|
||
$("host-name").textContent = S.hostName ? "· " + S.hostName : "";
|
||
$("b-me").textContent = (S.hostName || "A").slice(0, 1).toUpperCase();
|
||
const q = S.search;
|
||
const match = (b) => !q || (b.name + " " + (b.description || "")).toLowerCase().includes(q);
|
||
const bots = S.bots.filter(match);
|
||
// Shortcuts the desktop keeps beside the chat: routines, pages, computers.
|
||
const routines = S.bots.reduce((n, b) => n + (b.routines || []).length, 0);
|
||
const main = S.bots.find((b) => b.primary) || S.bots[0];
|
||
const comps = (main && main.computers) || [];
|
||
const on = comps.filter((c) => c.online).length;
|
||
$("quick").innerHTML = owner() ? [
|
||
`<button data-q="routines">${ic("alarm-clock", 15)} 例行任務 <b>${routines}</b></button>`,
|
||
`<button data-q="pages">${ic("file-text", 15)} 頁面 <b>${S.pages.length}</b></button>`,
|
||
`<button data-q="computers"><span class="st" style="background:${on ? "var(--ok)" : "var(--text4)"}"></span> 電腦 <b>${on}/${comps.length}</b></button>`,
|
||
isOwner() ? `<button data-q="settings">${ic("settings", 15)} 設定</button>` : "",
|
||
].join("") : "";
|
||
$("b-newbot").style.display = isOwner() ? "" : "none";
|
||
$("quick").querySelectorAll("[data-q]").forEach((b) => b.onclick = () => go("list", {kind: b.dataset.q}));
|
||
if (!S.bots.length) { $("home").innerHTML = `<div class="empty">還沒有 Bot。按右上角的 + 建立第一個。</div>`; return; }
|
||
if (!bots.length) { $("home").innerHTML = `<div class="empty">沒有相符的 Bot</div>`; return; }
|
||
// The sidebar's sections: 主要 Bot, 已釘選的 Bot, the person's own sections, then Bot.
|
||
const primary = bots.filter((b) => b.primary);
|
||
const pinned = bots.filter((b) => !b.primary && b.pinned);
|
||
const rest = bots.filter((b) => !b.primary && !b.pinned);
|
||
// The desktop's 分區 in its order (null = 未分區), empty ones too.
|
||
const order = S.sections || [...new Set(rest.map((b) => b.folder).filter(Boolean)), null];
|
||
const folders = order.filter((f) => f != null);
|
||
let folded = {}; try { folded = JSON.parse(localStorage.getItem("anybot.folded") || "{}"); } catch (_) {}
|
||
const sec = (title, icon, list, key, extra = "", keep = false) => list.length || keep ? `<div class="sec" data-fold="${esc(key)}">${icon ? ic(icon, 13) : ""}${esc(title)} <span class="n">${list.length}</span>${extra}${key ? `<button ${extra ? 'style="margin-left:6px"' : ""}>${ic(folded[key] ? "chevron-right" : "chevron-down", 14)}</button>` : ""}</div>${folded[key] ? "" : `<div class="rows">${list.map(botRow).join("")}</div>`}` : "";
|
||
let h = sec("主要 Bot", "star", primary, "") + sec("已釘選的 Bot", "pin", pinned, "");
|
||
for (const f of order) {
|
||
if (f == null) h += sec(folders.length ? "未分區" : "Bot", "", rest.filter((b) => !folders.includes(b.folder)), folders.length ? "loose" : "");
|
||
else h += sec(f, "folder", rest.filter((b) => b.folder === f), "f:" + f, isOwner() ? `<button data-fmenu="${esc(f)}" style="margin-left:auto">${ic("ellipsis", 15)}</button>` : "", !q);
|
||
}
|
||
$("home").innerHTML = h + `<div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
$("home").querySelectorAll(".row[data-bot]").forEach((r) => {
|
||
r.onclick = (e) => { if (e.target.closest("[data-botmenu]")) return; go("chat", {bot: +r.dataset.bot}); };
|
||
let t = null; r.addEventListener("touchstart", () => { t = setTimeout(() => { t = "long"; botMenu(+r.dataset.bot); }, 520); }, {passive: true});
|
||
r.addEventListener("touchend", (e) => { if (t === "long") e.preventDefault(); clearTimeout(t); }); r.addEventListener("touchmove", () => clearTimeout(t), {passive: true});
|
||
});
|
||
$("home").querySelectorAll("[data-botmenu]").forEach((b) => b.onclick = (e) => { e.stopPropagation(); botMenu(+b.dataset.botmenu); });
|
||
// 分區's menu: rename it, or delete it (its bots go back to 未分區; nothing is deleted).
|
||
$("home").querySelectorAll("[data-fmenu]").forEach((b) => b.onclick = (e) => {
|
||
e.stopPropagation();
|
||
const f = b.dataset.fmenu;
|
||
sheet(f, [
|
||
{icon: "pen", label: "重新命名分區", on: async () => { const n = await ask("分區名稱", f); if (n && n !== f) app("rename_group", {group: f, new_name: n}); }},
|
||
{icon: "trash", label: "刪除分區", danger: true, on: async () => { if (await confirmSheet(`刪除分區「${f}」?`, "裡面的 Bot 會移到未分區,不會刪除任何 Bot。", "刪除分區")) app("delete_group", {group: f}); }},
|
||
]);
|
||
});
|
||
$("home").querySelectorAll(".sec[data-fold]").forEach((s) => { if (!s.dataset.fold) return; s.onclick = () => { folded[s.dataset.fold] = !folded[s.dataset.fold]; try { localStorage.setItem("anybot.folded", JSON.stringify(folded)); } catch (_) {} renderHome(); }; });
|
||
}
|
||
// The sidebar row's menu, as on the desktop.
|
||
function botMenu(id) {
|
||
const b = bot(id); if (!b || !owner()) return;
|
||
// What is used often first; the rest under 「更多…」 (a tap on the row already opens the chat).
|
||
const items = [{icon: "info", label: "對話詳細資訊", on: () => go("details", {bot: id})}];
|
||
const more = [{icon: b.unread ? "check" : "bell", label: b.unread ? "標示為已讀" : "標示為未讀", on: () => b.unread ? api(base() + `api/bots/${id}/read`, {json: {}}).then(() => toast("已標示為已讀")).catch((e) => toast(e.message)) : act("bot", {bot: id, key: "unread", value: true}, "已標示為未讀")}];
|
||
// (Changing bots is the owner's; an admin opens, reads and restarts them.)
|
||
if (isOwner()) items.push({icon: "pin", label: b.pinned ? "取消釘選" : "釘選", on: () => act("bot", {bot: id, key: "pinned", value: !b.pinned}, b.pinned ? "已取消釘選" : "已釘選")}, {icon: "folder", label: "移至分區", on: () => moveToFolder(b)});
|
||
// 團隊: whether teammates may use this bot (they see its chat, pages and files).
|
||
if (isOwner() && !b.members) more.push({icon: "users", label: b.team ? "不再分享給團隊成員" : "分享給團隊成員", on: () => act("bot", {bot: id, key: "team", value: !b.team}, b.team ? "團隊成員看不到這個 Bot 了" : "團隊成員現在可以使用這個 Bot")});
|
||
if (!b.primary && isOwner()) more.push({icon: "star", label: "設為主要 Bot", on: () => act("bot", {bot: id, key: "primary", value: true}, "已設為主要 Bot")});
|
||
more.push({icon: "refresh", label: "重新啟動這個 Bot", on: () => act("restart_bot", {bot: id})});
|
||
items.push({icon: "ellipsis", label: "更多…", on: () => sheet(b.name, more)});
|
||
if (isOwner()) items.push({sep: true}, {icon: "trash", label: "刪除 Bot", danger: true, on: () => deleteBot(b)});
|
||
sheet(b.name, items);
|
||
}
|
||
async function moveToFolder(b) {
|
||
if (!S.sections && !S.settings) await loadSettings();
|
||
const folders = S.sections ? S.sections.filter((f) => f != null) : (S.settings && S.settings.folders) || [];
|
||
sheet("移至分區", [
|
||
...folders.map((f) => ({icon: "folder", label: f, check: b.folder === f, on: () => app("move_to_group", {group: f, bots: [b.name]}, b.id)})),
|
||
{icon: "minus", label: "未分區", check: !b.folder, on: () => app("move_to_group", {group: "", bots: [b.name]}, b.id)},
|
||
{icon: "plus", label: "新增分區…", on: async () => { const n = await ask("新增分區", "", "例如:文宣組"); if (n) app("move_to_group", {group: n, bots: [b.name]}, b.id); }},
|
||
]);
|
||
}
|
||
async function deleteBot(b) {
|
||
if (!await confirmSheet(`刪除「${b.name}」?`, "這會刪除它和它的聊天記錄。此操作無法復原。", "刪除")) return;
|
||
if (await act("delete_bot", {bot: b.id}, `已刪除「${b.name}」`)) { if (S.open === b.id) { S.open = 0; go("home", {}, true); } }
|
||
}
|
||
// 新 Bot: 建立 Bot / 從範本建立 / 建立群組聊天 / 新增分區.
|
||
$("b-newbot").onclick = async () => {
|
||
if (!isOwner()) return;
|
||
if (!S.settings) loadSettings();
|
||
sheet("新 Bot", [
|
||
{icon: "bot", label: "建立 Bot", on: async () => { const n = await ask("新 Bot 的名字", "", "例如:研究助理"); if (n) newBotDone(await app("create_bot", {name: n})); }},
|
||
{icon: "sparkles", label: "從範本建立", on: templates},
|
||
{icon: "users", label: "建立群組聊天", on: groupChat},
|
||
{icon: "folder", label: "新增分區", on: async () => { const n = await ask("新增分區", "", "例如:文宣組"); if (n) app("create_group", {name: n}); }},
|
||
]);
|
||
};
|
||
function newBotDone(v) { if (v && v.bot) setTimeout(() => go("chat", {bot: v.bot}), 400); }
|
||
async function templates() {
|
||
if (!S.settings) await loadSettings();
|
||
const t = (S.settings && S.settings.templates) || [];
|
||
const el = sheet("從範本建立", [], t.map((x, i) => `<button class="opt" data-t="${i}"><div class="av sm">${avatarSvg(x.shape, x.color)}</div><span style="min-width:0"><div>${esc(x.name)}</div><div style="font-size:var(--fs-small);color:var(--text3)">${esc(x.description)}</div></span></button>`).join(""));
|
||
el.querySelectorAll("[data-t]").forEach((b) => b.onclick = async () => { closeSheet(); newBotDone(await app("create_bot", {template: t[+b.dataset.t].name})); });
|
||
}
|
||
function groupChat() {
|
||
const cands = S.bots.filter((b) => !b.members);
|
||
const pick = new Set(cands.slice(0, 3).map((b) => b.id));
|
||
const draw = () => {
|
||
const el = sheet("建立群組聊天", [], `<div class="note">選幾個 Bot,它們會依序回答同一則訊息;打「@名字」可以只叫某幾個回答。</div>` + cands.map((b) => `<button class="opt" data-m="${b.id}"><div class="av sm">${avatarSvg(b.shape, b.color)}</div><span>${esc(b.name)}</span>${pick.has(b.id) ? `<span class="ck">${ic("check", 18)}</span>` : ""}</button>`).join("") + `<div class="form"><button class="btn main" id="gc-ok" ${pick.size ? "" : "disabled"}>建立</button></div>`);
|
||
el.querySelectorAll("[data-m]").forEach((b) => b.onclick = () => { const id = +b.dataset.m; pick.has(id) ? pick.delete(id) : pick.add(id); draw(); });
|
||
el.querySelector("#gc-ok").onclick = async () => { closeSheet(); newBotDone(await act("group_chat", {members: [...pick]}, "已建立群組聊天")); };
|
||
};
|
||
draw();
|
||
}
|
||
// 帳戶選單 (the desktop's account menu): 設定, this phone's look and notifications, more.
|
||
$("b-me").onclick = () => {
|
||
const items = [];
|
||
if (isOwner()) items.push({icon: "settings", label: "設定", on: () => go("list", {kind: "settings"})});
|
||
items.push({icon: "moon", label: "這支手機的外觀", x: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], on: () => {
|
||
sheet("這支手機的外觀", THEMES.map(([k, n]) => ({label: n, check: phoneTheme() === k, on: () => { try { localStorage.setItem("anybot.theme", k); } catch (_) {} applyTheme(); }})));
|
||
}});
|
||
if (isOwner()) items.push({icon: "send", label: "傳送到其他裝置", on: dropsSheet});
|
||
items.push({icon: "bell", label: "通知", on: notifySheet});
|
||
if (!installed() && (S.installPrompt || navigator.standalone === false)) items.push({icon: "download", label: "安裝成 App", on: installApp});
|
||
if (S.mac) items.push({icon: "monitor", label: "看這台 Mac 的螢幕", on: () => go("screen")});
|
||
if (S.relay && owner()) items.push({icon: "plus", label: "加一台電腦(Linux、伺服器)", on: pair});
|
||
if (S.relay) items.push({icon: "refresh", label: "切換到別台 AnyBot", on: () => { S.host = ""; localStorage.removeItem("anybot.host"); S.version = 0; NAV.length = 0; pickHost(); }});
|
||
items.push({icon: "log-out", label: "登出這支手機", danger: true, on: async () => { if (await confirmSheet("要登出這支手機嗎?", "", "登出", true)) signOut(); }});
|
||
sheet(S.hostName || "AnyBot", items);
|
||
};
|
||
</script>
|
||
<script>
|
||
"use strict";
|
||
// ---------- chat ----------
|
||
$("isl-chev").innerHTML = ic("chevron-right", 14);
|
||
$("b-newchat").innerHTML = ic("pen", 19); $("b-chatmore").innerHTML = ic("ellipsis", 20);
|
||
$("b-plus").innerHTML = ic("plus", 16); $("b-mic").innerHTML = ic("mic", 18); $("b-down").innerHTML = ic("arrow-down", 18);
|
||
const ST = {waiting: "circle-alert", running: "loader", done: "circle-check", denied: "minus", failed: "circle-x"};
|
||
// What the bot is doing, in the words the desktop uses (its status line, or a waiting question).
|
||
function chatSub(b) {
|
||
const a = S.approvals.find((x) => x.bot === b.id);
|
||
if (a) return ["wait", a.kind === "handoff" ? "需要你的輸入" : a.kind === "question" ? "等你回答" : "需要你核准"];
|
||
if (b.busy) return ["busy", b.status || "工作中…"];
|
||
return ["", b.model || ""];
|
||
}
|
||
function chatHead() {
|
||
const b = bot(S.open); if (!b) return;
|
||
$("isl-av").innerHTML = avatarSvg(b.shape, b.color);
|
||
$("isl-name").textContent = b.name;
|
||
const [cls, text] = chatSub(b);
|
||
$("isl-sub").className = "s " + cls; $("isl-sub").textContent = text;
|
||
$("input").placeholder = "傳訊息給 " + b.name;
|
||
$("b-newchat").style.display = owner() ? "" : "none";
|
||
}
|
||
$("island").onclick = () => go("details", {bot: S.open});
|
||
function openChat(id) {
|
||
if (S.open !== id) { S.msgs = []; S.pending = []; S.quote = null; S.unfold = {}; S.openSteps = {}; S.chatSig = ""; S.prevShown = 0; S.prevFirst = ""; MODE_OPEN = ""; $("msgs").innerHTML = ""; }
|
||
S.open = id;
|
||
// Your bubbles as 聊天的顏色 on the computer says (ob.bubble): "quiet" a light grey with the
|
||
// page's ink (the default), "bot" the bot's colour, "black". (An older AnyBot sends no field: its colour.)
|
||
const ob = bot(id) || {}, chat = $("v-chat");
|
||
const bubble = ob.bubble || "bot";
|
||
chat.classList.toggle("quiet", bubble === "quiet");
|
||
if (bubble === "bot" && ob.color && ob.color_key !== "black") { chat.style.setProperty("--bot", ob.color); chat.style.setProperty("--bot-ink", "var(--on-color)"); }
|
||
else { chat.style.removeProperty("--bot"); chat.style.removeProperty("--bot-ink"); }
|
||
chatHead(); renderChips(); renderQuote(); loadChat(true); renderDock();
|
||
api(base() + `api/bots/${id}/read`, {json: {}}).catch(() => {});
|
||
}
|
||
let loading = false, again = false;
|
||
async function loadChat(jump) {
|
||
if (!S.open) return;
|
||
if (loading) { again = true; return; }
|
||
loading = true;
|
||
try {
|
||
const v = await api(base() + "api/bots/" + S.open);
|
||
const sc = $("scroller"); const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140;
|
||
S.msgs = v.messages || []; S.chatSig = v.sig || ""; renderMsgs();
|
||
if (jump || near) sc.scrollTop = sc.scrollHeight;
|
||
} catch (e) { toast(e.message); }
|
||
loading = false;
|
||
if (again) { again = false; loadChat(); }
|
||
}
|
||
// The state poll carried the open chat's messages along (single trip): take them as-is.
|
||
function applyChat(msgs, sig) {
|
||
S.chatSig = sig || "";
|
||
const sc = $("scroller");
|
||
const near = sc.scrollHeight - sc.scrollTop - sc.clientHeight < 140;
|
||
S.msgs = msgs;
|
||
renderMsgs();
|
||
if (near) sc.scrollTop = sc.scrollHeight;
|
||
}
|
||
// What a new chat offers (the desktop's 建議): the everyday jobs, one tap to start writing them.
|
||
const SUGGEST = [
|
||
["search", "海巡 Threads", "整理熱門討論和互動數", "幫我在 Threads 海巡「」最近的熱門討論,整理互動最多的 5 則(誰發的、在講什麼、讚數、連結)。"],
|
||
["pen", "寫一則貼文", "用你平常的語氣先寫草稿", "用我 Threads 帳號平常的語氣,幫我寫一則關於「」的貼文草稿,先給我看,不要發。"],
|
||
["monitor", "看我電腦的畫面", "截一張現在的畫面給你", "截一張我電腦現在的畫面給我看。"],
|
||
["list-checks", "幫我研究一件事", "查清楚現況和來源,整理成一頁", "幫我研究「」:查清楚現況和來源,整理成一頁。"],
|
||
["alarm-clock", "建立例行任務", "每天、每週自動做", "幫我建立一個例行任務:每天早上 9 點"],
|
||
];
|
||
function stepHtml(t, key) {
|
||
const open = S.openSteps[key];
|
||
const body = `<div class="body">${t.detail ? `<div class="k">內容</div><pre>${esc(t.detail)}</pre>` : ""}${t.result ? `<div class="k">結果</div><pre>${esc(t.result)}</pre>` : ""}${!t.detail && !t.result ? `<div class="k">(沒有更多內容)</div>` : ""}</div>`;
|
||
return `<div class="step ${t.status} ${open ? "open" : ""}" data-step="${esc(key)}"><button class="h"><span class="st-i">${ic(ST[t.status] || "minus", 14)}</span><span class="l">${esc(t.label)}</span><span class="d">${esc(t.detail || "")}</span><span class="chev">${ic("chevron-right", 13)}</span></button>${body}</div>`;
|
||
}
|
||
function thinkHtml(m) {
|
||
const key = "t" + m.index, open = S.openSteps[key];
|
||
return `<div class="steps"><div class="step done ${open ? "open" : ""}" data-step="${key}"><button class="h"><span class="st-i">${ic("brain", 14)}</span><span class="l">思考過程</span><span class="d">${esc(plain(m.thinking).slice(0, 80))}</span><span class="chev">${ic("chevron-right", 13)}</span></button><div class="body"><pre>${esc(m.thinking)}</pre></div></div></div>`;
|
||
}
|
||
function attHtml(a) {
|
||
if (!a.path) return `<div class="filec">${ic(a.image ? "image" : "file", 16)}<span class="fn">${esc(a.name)}</span></div>`;
|
||
if (a.image) return `<div class="attimg" data-file="${esc(a.path)}" data-name="${esc(a.name)}">${FILES[a.path] ? `<img alt="${esc(a.name)}" src="${FILES[a.path]}">` : `<div class="wait">${ic("image", 14)} ${esc(a.name)}</div>`}</div>`;
|
||
return `<a class="filec" data-file="${esc(a.path)}" data-name="${esc(a.name)}">${ic("file", 18)}<span style="min-width:0"><div class="fn">${esc(a.name)}</div><div style="font-size:var(--fs-caption);color:var(--text3)">${esc(a.kind || "檔案")}${a.bytes ? " · " + kb(a.bytes) : ""} · 點一下開啟</div></span></a>`;
|
||
}
|
||
const kb = (n) => n >= 1048576 ? (n / 1048576).toFixed(1) + " MB" : Math.max(1, Math.round(n / 1024)) + " KB";
|
||
function safeHttpUrl(u) {
|
||
const s = String(u || "").trim();
|
||
return /^https?:\/\//i.test(s) ? s : "";
|
||
}
|
||
/** 支線 (/btw): what it was asked, how it stands, its steps; a stop button while it works. */
|
||
function branchCard(r) {
|
||
const st = {checking: `${ic("loader", 13)} 先看看會不會跟主線正在做的事衝突…`, waiting: `等主線這一輪做完再開始:${esc(r.note || "")}`, running: `${ic("loader", 13)} ${esc(r.doing || "正在做…")}${r.steps ? `(${r.steps} 步)` : ""}`, done: `${ic("circle-check", 13)} 做完了`, failed: `沒有做完:${esc(r.note || "")}`, stopped: "已停止"}[r.state] || "";
|
||
const log = (r.log || []).length ? `<details class="br-log"><summary>看過程(${r.log.length})</summary>${r.log.map((l) => `<div>${esc(l)}</div>`).join("")}</details>` : "";
|
||
const stop = r.state === "running" && owner() ? `<button class="tk-go" data-brstop="${r.id}">停止支線</button>` : "";
|
||
return `<div class="talk branch"><div class="tk-h">${ic("activity", 13)}<span>支線</span><b>${esc(r.task)}</b></div><div class="tk-st ${r.state === "failed" ? "err" : ""}">${st}</div>${r.state === "done" && r.result ? `<div class="tk-a">${pageMd(r.result, 0)}</div>` : ""}${log}${stop}</div>`;
|
||
}
|
||
/** 同事之間: who asked whom (or handed what), and the answer once it is back — here, in the chat
|
||
* that asked. The colleague's own chat keeps the whole of it. */
|
||
function talkCard(t, status, from) {
|
||
const to = S.bots.find((b) => b.name === t.to);
|
||
const av = (b) => b ? `<span class="av xs">${avatarSvg(b.shape, b.color)}</span>` : "";
|
||
const me = S.bots.find((b) => b.name === from);
|
||
const q = (t.text || "").length > 400 ? t.text.slice(0, 400) + "…" : (t.text || "");
|
||
let tail;
|
||
if (status === "running" || status === "waiting") tail = `<div class="tk-st">${ic("loader", 13)} 「${esc(t.to)}」${to && to.busy && to.status ? ":" + esc(to.status) : "正在處理…"}</div>`;
|
||
else if (status === "done" && t.ask && t.answer) { const body = t.answer.includes("\n") ? t.answer.slice(t.answer.indexOf("\n") + 1) : t.answer; tail = `<div class="tk-ok">${ic("circle-check", 13)} 「${esc(t.to)}」的回答</div><div class="tk-a">${pageMd(body, 0)}</div>`; }
|
||
else if (status === "done") tail = `<div class="tk-st">${esc(t.answer || "已交給它,做完會回報到這裡")}</div>`;
|
||
else tail = `<div class="tk-st err">${esc(t.answer || "沒有完成")}</div>`;
|
||
return `<div class="talk"><div class="tk-h">${av(me)}<b>${esc(from)}</b>${ic("chevron-right", 12)}${av(to)}<b>${esc(t.to)}</b><span>${t.ask ? "問" : "交辦"}</span></div>${q ? `<div class="tk-q">${esc(q)}</div>` : ""}${tail}${to ? `<button class="tk-go" data-bot="${to.id}">「${esc(t.to)}」那邊的紀錄 ›</button>` : ""}</div>`;
|
||
}
|
||
/** 計畫: the plan a bot handed in (`state`: waiting, approved, changed, not_now; `live`: its steps as followed now). */
|
||
function planCard(p) {
|
||
if (!p || !p.summary) return "";
|
||
const st = {waiting: "等你決定", approved: p.live ? `照著做 · ${p.live.filter((s) => s.status === "done" || s.status === "skipped").length}/${p.live.length}` : "已核准", changed: "已修改,見下面新版", not_now: "沒有採用"}[p.state] || "";
|
||
const whole = p.state === "waiting" || p.state === "approved";
|
||
const cls = p.state === "waiting" ? " wait" : whole ? "" : " past";
|
||
let h = `<div class="card plan${cls}"><div class="t">${ic("list-checks", 15)}<span>計畫</span><span class="st">${esc(st)}</span></div><div class="sum">${esc(p.summary)}</div>`;
|
||
if (whole) {
|
||
const rows = p.live ? p.live.map((s) => ({title: s.title, detail: "", status: s.status})) : (p.steps || []);
|
||
h += "<ol>" + rows.map((s) => `<li class="${{done: "done", in_progress: "now", skipped: "skip"}[s.status] || ""}">${esc(s.title)}${s.detail && s.status !== "done" ? `<span class="d">${esc(s.detail)}</span>` : ""}</li>`).join("") + "</ol>";
|
||
if (p.check) h += `<div class="x">怎麼確認做對了:${esc(p.check)}</div>`;
|
||
if (p.notes) h += `<div class="x">注意:${esc(p.notes)}</div>`;
|
||
if (p.state === "waiting") h += `<div class="x">在下面的卡片選「開始照計畫做」,或寫下要改哪裡</div>`;
|
||
}
|
||
return h + "</div>";
|
||
}
|
||
function card(c) {
|
||
if (!c) return "";
|
||
const rows = (c.rows || []).map((r) => `<div class="r"><span>${esc(r.label)}</span><span>${esc(r.value)}</span></div>`).join("");
|
||
const link = safeHttpUrl(c.link);
|
||
return `<div class="card"><div class="t">${esc(c.title)}</div>${c.subtitle ? `<div class="s">${esc(c.subtitle)}</div>` : ""}${rows}${link ? `<div class="r"><a href="${esc(link)}" target="_blank" rel="noopener">來源</a><span></span></div>` : ""}</div>`;
|
||
}
|
||
const GLYPH = (h = 34) => `<svg width="${Math.round(h * .8)}" height="${h}" viewBox="0 0 24 30" style="flex:none"><rect x=".5" y=".5" width="23" height="29" rx="4" style="fill:var(--hover);stroke:var(--line)"/><path d="M5 7h9M5 11h6" style="stroke:var(--text3)" stroke-width="2" stroke-linecap="round"/><rect x="5" y="20" width="2.6" height="5" rx=".6" style="fill:var(--cat3)"/><rect x="9" y="18" width="2.6" height="7" rx=".6" style="fill:var(--cat4)"/><rect x="13" y="16" width="2.6" height="9" rx=".6" style="fill:var(--cat1)"/><rect x="17" y="14" width="2.6" height="11" rx=".6" style="fill:var(--cat2)"/></svg>`;
|
||
function pageCard(p) {
|
||
const lines = (p.preview || []).slice(0, 3).map((l, i, a) => `<div class="l" style="opacity:${1 - (i / Math.max(a.length, 1)) * .6}">${esc(l)}</div>`).join("");
|
||
// (The title once: the foot only says what it is and when.)
|
||
return `<div class="pcard" data-page="${p.id}"><div class="top"><div class="t">${esc(p.title)}</div>${lines}</div><div class="foot">${GLYPH(22)}<div class="x">頁面 · ${esc(p.updated)}${p.revision > 1 ? " · 已更新" : ""}</div></div></div>`;
|
||
}
|
||
function renderMsgs() {
|
||
const b = bot(S.open) || {};
|
||
const busy = b.busy;
|
||
// A turn: the bot's messages between two of the person's. Its steps fold into one line once it
|
||
// is done; while it works, the newest three stay in view.
|
||
const turns = []; let curT = null;
|
||
S.msgs.forEach((m, i) => {
|
||
if (m.role === "user" || m.summary || m.interrupted || m.note) { curT = null; return; }
|
||
if (!curT) { curT = {first: i, last: i, key: String(m.at || i), steps: 0}; turns.push(curT); }
|
||
curT.last = i; curT.steps += (m.tools || []).filter((t) => !t.page && !t.card && !t.plan && !t.plan_update).length;
|
||
});
|
||
const turnOf = {}; turns.forEach((t) => { for (let i = t.first; i <= t.last; i++) turnOf[i] = t; });
|
||
const lastTurn = turns[turns.length - 1];
|
||
const lastBot = [...S.msgs].reverse().find((m) => m.role !== "user" && m.text && !m.note);
|
||
const lastMsg = S.msgs[S.msgs.length - 1];
|
||
const shown = {}; let day = "";
|
||
let h = "";
|
||
// A message that arrived since the last draw slides up into place; the whole history on
|
||
// opening a chat draws plain (no animation on every old message).
|
||
// (Another conversation of the same bot — its first message differs — draws plain too.)
|
||
const first = S.msgs.length ? String(S.msgs[0].at || "") + (S.msgs[0].text || "").slice(0, 40) : "";
|
||
const same = first === S.prevFirst; S.prevFirst = first;
|
||
const freshFrom = same && S.prevShown > 0 && S.msgs.length > S.prevShown ? S.prevShown : S.msgs.length;
|
||
S.prevShown = S.msgs.length;
|
||
const fr = (i) => (i >= freshFrom ? " fresh" : "");
|
||
S.msgs.forEach((m, i) => {
|
||
if (m.at) { const d = dayLabel(m.at); if (d !== day) { day = d; h += `<div class="dsep">${esc(d)}</div>`; } }
|
||
const reacts = (m.reactions || []).length ? `<div class="reacts">${m.reactions.map((e) => `<button data-react="${esc(e)}" data-i="${m.index}">${esc(e)}</button>`).join("")}</div>` : "";
|
||
if (m.summary) {
|
||
h += `<div class="summary" data-sum="1"><b>${ic("history", 15)} 較早的對話已整理成摘要 ${ic("chevron-down", 14)}</b><div class="tx">${esc(m.text)}</div></div>`;
|
||
return;
|
||
}
|
||
// Where AnyBot stopping cut a turn off: what it was doing, what may have run, and 「繼續」
|
||
// while it is the newest thing in the chat.
|
||
if (m.interrupted) {
|
||
const go = m === lastMsg && !busy && owner() ? `<button class="btn main sm" style="margin-top:8px" data-resume="1">繼續</button>` : "";
|
||
h += `<div class="summary open"><div class="tx">${esc(m.text)}</div>${go}</div>`;
|
||
return;
|
||
}
|
||
// 支線: its card where it was asked; its report handed to the running turn is one line.
|
||
if (m.branch && m.note) { h += branchCard(m.branch); return; }
|
||
if (m.branch && m.role === "user") { h += `<div class="note">${ic("activity", 13)}<span>支線的結果已交給正在做事的主線</span></div>`; return; }
|
||
// 目標: AnyBot's own line about the goal (met, paused…), not the bot's words.
|
||
if (m.note) {
|
||
h += `<div class="note">${ic("target", 13)}<span>${esc(m.text)}</span></div>`;
|
||
return;
|
||
}
|
||
if (m.role === "user") {
|
||
const goal = m.wake && String(m.text || "").startsWith(GOAL_TAG);
|
||
const tag = goal ? `<div class="tag">${ic("target", 12)} 目標</div>` : m.wake ? `<div class="tag">${ic("alarm-clock", 12)} ${esc(m.via || "例行任務")}</div>` : "";
|
||
if (goal) m = {...m, text: m.text.slice(GOAL_TAG.length)};
|
||
const q = String(m.text || "").match(/^((?:>.*\n?)+)\n*([\s\S]*)$/);
|
||
const text = q ? q[2] : m.text;
|
||
const quote = q ? `<div class="quote">${esc(plain(q[1].replace(/^> ?/gm, "")).replace(/\|/g, " ").replace(/\s+/g, " ").trim())}</div>` : "";
|
||
const mems = m.memories || [];
|
||
const open = S.carried.has(String(m.at || i));
|
||
const carried = mems.length ? `<button class="carried" data-carried="${esc(String(m.at || i))}">${ic("bookmark", 12)} 帶了 ${mems.length} 條記憶 ${ic(open ? "chevron-up" : "chevron-down", 12)}</button>${open ? `<div class="carried-list">${mems.map((x) => "• " + esc(x)).join("<br>")}</div>` : ""}` : "";
|
||
h += `<div class="m user${fr(i)}" data-msg="${i}">${tag}${m.text ? `<div class="bub">${quote}${esc(text)}</div>` : ""}${(m.attachments || []).map(attHtml).join("")}${reacts}${carried}</div>`;
|
||
return;
|
||
}
|
||
const t = turnOf[i];
|
||
const running = busy && t === lastTurn;
|
||
const unfolded = t && (S.unfold[t.key] || t.steps <= 2);
|
||
let steps = "", extra = "";
|
||
(m.tools || []).forEach((x, k) => {
|
||
if (x.page) { extra += pageCard(x.page); return; }
|
||
if (x.card) { extra += card(x.card); return; }
|
||
if (x.plan) { extra += planCard(x.plan); return; }
|
||
if (x.plan_update) return;
|
||
if (x.talk) { extra += talkCard(x.talk, x.status, m.author || (bot(S.open) || {}).name || ""); return; }
|
||
const n = (shown[t.key] = (shown[t.key] || 0) + 1);
|
||
if (unfolded) { steps += stepHtml(x, m.index + ":" + k); return; }
|
||
if (n === 1) steps += `<button class="fold" data-turn="${esc(t.key)}">${ic(running ? "loader" : "circle-check", 14)} ${running ? "已做了" : "已完成"} ${t.steps} 個步驟 ${ic("chevron-right", 13)}</button>`;
|
||
if (running && n > t.steps - 3) steps += stepHtml(x, m.index + ":" + k);
|
||
});
|
||
const end = t && i === t.last && !running;
|
||
const who = m.author ? `<div class="who">${esc(m.author)}</div>` : "";
|
||
const think = m.thinking ? thinkHtml(m) : "";
|
||
const bub = m.text ? `<div class="bub">${pageMd(m.text, 0)}</div>` : "";
|
||
const atts = (m.attachments || []).map(attHtml).join("");
|
||
const meta = end && m.text ? `<div class="meta">${m.at ? esc(clock(m.at)) : ""}<button data-copy="${i}" title="複製">${ic("copy", 14)}</button>${owner() && m === lastBot && t === lastTurn ? `<button data-regen="1" title="重新產生">${ic("refresh", 14)}</button>` : ""}<button data-more="${i}" title="更多">${ic("ellipsis", 14)}</button></div>` : "";
|
||
h += `<div class="m bot${fr(i)} ${m.error ? "err" : ""}" data-msg="${i}">${who}${think}${bub}${steps ? `<div class="steps">${steps}</div>` : ""}${extra}${atts}${reacts}${meta}</div>`;
|
||
});
|
||
// Still working: what it is doing now; a message nobody answered yet can be sent again.
|
||
if (busy) h += (lastMsg && lastMsg.role !== "user" && !lastMsg.text && !(lastMsg.tools || []).length) || lastMsg?.role === "user" ? `<div class="m bot"><div class="typing"><i></i><i></i><i></i></div></div>` : "";
|
||
if (busy && b.status) h += `<div class="working">${face(b, "sm")}<div class="presence">${esc(b.status)}</div></div>`;
|
||
if (!busy && lastMsg && lastMsg.role === "user" && !lastMsg.wake && owner()) h += `<div class="meta" style="align-self:flex-end">還沒有回覆 <button data-resend="1">${ic("refresh", 14)} 重新傳送</button></div>`;
|
||
if (!S.msgs.length) {
|
||
h = `<div class="intro">${face(b, "lg")}<div class="hi">嗨,我是${esc(b.name || "Bot")}</div><div class="sub">${esc(b.description || "想做什麼?點一個開始,或直接打字。")}</div></div><div class="sugs">${SUGGEST.map((x, k) => `<button class="sug" data-sugg="${k}">${ic(x[0], 20)}<span><div class="tt">${esc(x[1])}</div><div class="dd">${esc(x[2])}</div></span></button>`).join("")}</div>`;
|
||
}
|
||
// 先顯示: words sent while it works, until the chat has them (or they failed: tap to take back).
|
||
const tail = S.msgs.slice(-16).map((m) => String(m.text || "").trim());
|
||
S.sending = S.sending.filter((x) => x.failed || (!tail.some((t) => t === x.text || t.endsWith(x.text)) && Date.now() - x.at < (busy ? 600000 : 8000)));
|
||
S.sending.filter((x) => x.bot === S.open).forEach((x, k) => {
|
||
h += `<div class="m user sending${x.failed ? " failed" : ""}" data-unsent="${k}"><div class="bub">${esc(x.text)}</div><div class="sn">${x.failed ? "沒送出,點一下拿回來重送" : Date.now() - x.at < 1200 ? "傳送中…" : "已排入,它下一步會看到"}</div></div>`;
|
||
});
|
||
$("msgs").innerHTML = h;
|
||
renderSendBtn();
|
||
loadFiles();
|
||
}
|
||
// Taps in the chat: steps, folds, summaries, copy, regenerate, resend, reactions, suggestions, pages.
|
||
$("msgs").addEventListener("click", async (e) => {
|
||
const st = e.target.closest(".step .h");
|
||
if (st) { const k = st.parentElement.dataset.step; S.openSteps[k] = !S.openSteps[k]; st.parentElement.classList.toggle("open"); return; }
|
||
const f = e.target.closest(".fold"); if (f) { S.unfold[f.dataset.turn] = true; renderMsgs(); return; }
|
||
const bs = e.target.closest("[data-brstop]"); if (bs) { try { await api(base() + `api/bots/${+bs.dataset.brstop}/stop`, {json: {}}); toast("已停止支線"); } catch (err) { toast(err.message); } return; }
|
||
const un = e.target.closest(".sending.failed"); if (un) { const mine = S.sending.filter((x) => x.bot === S.open); const x = mine[+un.dataset.unsent]; if (x) { S.sending = S.sending.filter((y) => y !== x); input.value = x.text; input.dispatchEvent(new Event("input")); renderMsgs(); input.focus(); } return; }
|
||
const tg = e.target.closest(".tk-go"); if (tg && tg.dataset.bot) { go("chat", {bot: +tg.dataset.bot}); return; }
|
||
const sm = e.target.closest("[data-sum]"); if (sm) { sm.classList.toggle("open"); return; }
|
||
const c = e.target.closest("[data-copy]"); if (c) { copyText(S.msgs[+c.dataset.copy].text); return; }
|
||
if (e.target.closest("[data-regen]")) { regen(); return; }
|
||
if (e.target.closest("[data-resend]")) { act("reply", {bot: S.open}); return; }
|
||
if (e.target.closest("[data-resume]")) { act("resume", {bot: S.open}, "繼續中…"); return; }
|
||
const mo = e.target.closest("[data-more]"); if (mo) { msgMenu(+mo.dataset.more); return; }
|
||
const r = e.target.closest("[data-react]"); if (r) { act("react", {bot: S.open, index: +r.dataset.i, emoji: r.dataset.react}, false).then(() => loadChat()); return; }
|
||
const sg = e.target.closest("[data-sugg]");
|
||
if (sg) {
|
||
const text = SUGGEST[+sg.dataset.sugg][3];
|
||
const input = $("input"); input.value = text; input.focus();
|
||
const at = text.indexOf("「」"); if (at >= 0) input.setSelectionRange(at + 1, at + 1);
|
||
input.dispatchEvent(new Event("input"));
|
||
}
|
||
});
|
||
// Long-press a message: its menu (the desktop's hover row).
|
||
(() => {
|
||
let t = null, at = null;
|
||
$("msgs").addEventListener("touchstart", (e) => {
|
||
const m = e.target.closest(".m[data-msg]"); if (!m || e.target.closest("button,a,.step,.pcard")) return;
|
||
at = +m.dataset.msg; t = setTimeout(() => { t = "long"; msgMenu(at); }, 480);
|
||
}, {passive: true});
|
||
$("msgs").addEventListener("touchend", (e) => { if (t === "long") e.preventDefault(); clearTimeout(t); t = null; });
|
||
$("msgs").addEventListener("touchmove", () => { clearTimeout(t); t = null; }, {passive: true});
|
||
$("msgs").addEventListener("contextmenu", (e) => { const m = e.target.closest(".m[data-msg]"); if (m) { e.preventDefault(); msgMenu(+m.dataset.msg); } });
|
||
})();
|
||
async function copyText(t) { try { await navigator.clipboard.writeText(t || ""); toast("已複製"); } catch (_) { toast("這支手機不讓網頁複製"); } }
|
||
const QUICK = ["👍", "❤️", "😂", "🎉", "👀", "🙏", "👌", "🔥"];
|
||
function msgMenu(i) {
|
||
const m = S.msgs[i]; if (!m) return;
|
||
const items = [];
|
||
if (m.text) items.push({icon: "copy", label: "複製", on: () => copyText(m.text)});
|
||
if (m.text && m.role !== "user" && S.voice.speak) items.push({icon: "audio-lines", label: "唸出來", on: () => speakText(m.text)});
|
||
if (m.text && owner()) items.push({icon: "reply", label: "引用回覆", on: () => { S.quote = {text: plain(m.text).slice(0, 300), raw: m.text}; renderQuote(); $("input").focus(); }});
|
||
if (m.text && owner() && m.role === "user") items.push({icon: "sparkles", label: "教我做(學這一回合)", on: async () => { if (await app("skillify", {prompt: plain(m.text).slice(0, 200)}, 0, "已存成技能,下次說名字就會照做")) again(); }});
|
||
const lastBot = [...S.msgs].reverse().find((x) => x.role !== "user" && x.text);
|
||
if (m === lastBot && owner()) items.push({icon: "refresh", label: "重新產生這個回答", on: regen});
|
||
// 重新產生 kept what it replaced (on the brain): put it back.
|
||
if (m === lastBot && owner() && (bot(S.open) || {}).can_restore && !(bot(S.open) || {}).busy) items.push({icon: "history", label: "還原上一個答案", on: async () => { try { await api(base() + `api/bots/${S.open}/restore_answer`, {json: {}}); toast("還原了"); } catch (e) { toast(e.message); } }});
|
||
if (m.role === "user" && i === S.msgs.length - 1 && owner()) items.push({icon: "refresh", label: "重新傳送", on: () => act("reply", {bot: S.open})});
|
||
const emojis = m.index != null && owner() ? `<div class="emojis">${QUICK.map((e) => `<button data-e="${e}">${e}</button>`).join("")}</div>` : "";
|
||
const el = sheet("", items, emojis);
|
||
el.querySelectorAll("[data-e]").forEach((b) => b.onclick = () => { closeSheet(); act("react", {bot: S.open, index: m.index, emoji: b.dataset.e}, false).then(() => loadChat()); });
|
||
}
|
||
async function regen() { try { await api(base() + `api/bots/${S.open}/regenerate`, {json: {}}); toast("重新產生中…"); } catch (e) { toast(e.message); } }
|
||
// The dock: what needs the person (允許 / 需要處理), what is queued, then the composer.
|
||
let thumbTimer = null;
|
||
function renderDock() {
|
||
const b = bot(S.open) || {};
|
||
const a = S.approvals.find((x) => x.bot === S.open);
|
||
clearInterval(thumbTimer);
|
||
if (a && a.kind === "question" && owner()) { $("ask").innerHTML = ""; renderQuestion(a); renderDockRest(b); return; }
|
||
ASKF = null;
|
||
$("askq").innerHTML = "";
|
||
if (!a) $("ask").innerHTML = "";
|
||
else if (!owner()) $("ask").innerHTML = `<div class="ask"><div class="q">${esc(a.title)}</div><div class="why">等擁有者或管理員決定</div></div>`;
|
||
else if (a.kind === "handoff") {
|
||
const own = /的電腦$/.test(a.computer || "") && S.boxOn;
|
||
$("ask").innerHTML = `<div class="ask"><div class="q">${ic("hand", 16)} 需要處理 · ${esc(a.computer || "")}</div><div class="why">${esc(a.reason)}</div>${own ? `<img class="thumb" id="hand-thumb" alt="">` : ""}<div class="btns"><button class="btn" data-screen="1">${ic("monitor", 15)} 接管</button><button class="btn main" data-a="once">我完成了</button><button class="btn" data-a="reject">跳過</button></div></div>`;
|
||
$("ask").querySelector("[data-screen]").onclick = () => openBox(true);
|
||
if (own) { const load = () => boxThumb($("hand-thumb")); load(); thumbTimer = setInterval(load, 3000); }
|
||
} else {
|
||
$("ask").innerHTML = `<div class="ask"><div class="q">${esc(a.title)}</div><div class="why">${esc(a.reason)}</div><div class="btns">${a.can_always ? `<button class="btn main" data-a="always">一律允許</button><button class="btn" data-a="once">允許一次</button>` : `<button class="btn main" data-a="once">允許</button>`}<button class="btn" data-a="reject">拒絕</button></div>${isOwner() ? `<a class="all" data-direct="1">${ic("zap", 13)} 全部允許,之後直接操作</a>` : ""}</div>`;
|
||
}
|
||
$("ask").querySelectorAll("button[data-a]").forEach((x) => x.onclick = async () => {
|
||
if (navigator.vibrate) navigator.vibrate(8);
|
||
$("ask").innerHTML = "";
|
||
try { await api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: {answer: x.dataset.a}}); } catch (e) { toast(e.message); }
|
||
});
|
||
const d = $("ask").querySelector("[data-direct]");
|
||
if (d) d.onclick = async () => {
|
||
if (!await confirmSheet("打開「直接操作」?", "Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。", "打開", false)) return;
|
||
if (await act("setting", {key: "direct_mode", value: true}, "已打開直接操作")) api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: {answer: a.can_always ? "always" : "once"}}).catch(() => {});
|
||
};
|
||
renderDockRest(b);
|
||
}
|
||
// 問題卡: the bot's questions, one at a time. A choice is one tap (it moves on; on the last
|
||
// question it sends); several choices and typed answers have 下一題/送出.
|
||
let ASKF = null;
|
||
function askAnswer(q, i) {
|
||
const typed = (ASKF.typed[i] || "").trim();
|
||
const parts = (q.multiple || !typed) ? ASKF.picks[i].slice().sort((x, y) => x - y).map((k) => q.options[k]) : [];
|
||
if (typed) parts.push(typed);
|
||
return parts.join("、");
|
||
}
|
||
function renderQuestion(a, force) {
|
||
const qs = a.questions || [];
|
||
if (!qs.length) return;
|
||
if (!ASKF || ASKF.id !== a.call_id) {
|
||
ASKF = {id: a.call_id, step: 0, drawn: -1, picks: qs.map((q) => { const k = (q.options || []).indexOf(q.default); return k >= 0 && q.default ? [k] : []; }), typed: qs.map((q) => (q.options || []).length ? "" : (q.default || ""))};
|
||
}
|
||
// Drawn already: leave it, or what is being typed would be lost on every refresh.
|
||
if (!force && ASKF.drawn === ASKF.step && $("askq").querySelector(".own")) return;
|
||
const i = ASKF.step, q = qs[i], opts = q.options || [], last = i + 1 === qs.length;
|
||
ASKF.drawn = i;
|
||
const own = !!(ASKF.typed[i] || "").trim();
|
||
$("askq").innerHTML = `<div class="ask"><div class="asknum">${esc(a.title)}${qs.length > 1 ? ` · ${i + 1}/${qs.length}` : ""}</div><div class="q">${esc(q.question)}</div><div class="why">${q.multiple ? "可以選好幾個" : ""}</div>${opts.map((o, k) => `<button class="opt ${q.multiple ? "many" : ""} ${ASKF.picks[i].includes(k) && (q.multiple || !own) ? "on" : ""}" data-k="${k}"><i></i><span>${esc(o)}</span></button>`).join("")}<input class="own" enterkeyhint="${last ? "send" : "next"}" placeholder="${opts.length ? "自己回答" : "輸入回答"}" value="${esc(ASKF.typed[i])}"><div class="btns"><button class="btn main" data-go="next">${last ? "送出" : "下一題"}</button>${i > 0 ? `<button class="btn" data-go="back">上一題</button>` : ""}<button class="btn" data-go="skip">略過</button></div></div>`;
|
||
const box = $("askq"), field = box.querySelector(".own"), go = box.querySelector('[data-go="next"]');
|
||
// The chat comes to the card when it appears and at each next question.
|
||
// (Once laid out; a card taller than the screen shows its question, not its buttons.)
|
||
requestAnimationFrame(() => {
|
||
const sc = $("scroller"), top = box.getBoundingClientRect().top - sc.getBoundingClientRect().top + sc.scrollTop;
|
||
sc.scrollTo({top: box.offsetHeight > sc.clientHeight ? top : sc.scrollHeight, behavior: "smooth"});
|
||
});
|
||
const ready = () => { go.disabled = !askAnswer(q, i); };
|
||
ready();
|
||
const send = async (body) => { ASKF = null; box.innerHTML = ""; try { await api(base() + `api/bots/${(a && a.target) || S.open}/answer`, {json: body}); } catch (e) { toast(e.message); } };
|
||
const next = () => {
|
||
if (!askAnswer(q, i)) return;
|
||
if (!last) { ASKF.step = i + 1; return renderQuestion(a, true); }
|
||
// Every question has its answer, or it goes back to the first without one.
|
||
const miss = qs.findIndex((x, k) => !askAnswer(x, k));
|
||
if (miss >= 0) { ASKF.step = miss; return renderQuestion(a, true); }
|
||
send({answer: "answered", text: JSON.stringify(qs.map((x, k) => askAnswer(x, k)))});
|
||
};
|
||
field.oninput = () => { ASKF.typed[i] = field.value; if (!q.multiple) box.querySelectorAll(".opt").forEach((x) => x.classList.toggle("on", !field.value.trim() && ASKF.picks[i].includes(+x.dataset.k))); ready(); };
|
||
field.onkeydown = (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); next(); } };
|
||
box.querySelectorAll(".opt").forEach((x) => x.onclick = () => {
|
||
const k = +x.dataset.k, picks = ASKF.picks[i];
|
||
if (q.multiple) { const at = picks.indexOf(k); if (at >= 0) picks.splice(at, 1); else picks.push(k); x.classList.toggle("on"); ready(); }
|
||
else { ASKF.picks[i] = [k]; ASKF.typed[i] = ""; next(); }
|
||
});
|
||
go.onclick = next;
|
||
const back = box.querySelector('[data-go="back"]');
|
||
if (back) back.onclick = () => { ASKF.step = i - 1; renderQuestion(a, true); };
|
||
box.querySelector('[data-go="skip"]').onclick = () => send({answer: "reject"});
|
||
}
|
||
// Which mode's line is open above the input ("goal", "plan" or none).
|
||
var MODE_OPEN = ""; // (var: openChat, above, clears it.)
|
||
function renderDockRest(b) {
|
||
// 目標 and 計畫: a chip each in one row (what it is on hover; the plan's 2/5 beside its icon).
|
||
// A tap opens that one's line: how it stands, and 清除目標/取消計畫 (sent as 「/goal clear」,
|
||
// 「/plan clear」, the brain's own commands).
|
||
const g = b.goal, pl = b.plan;
|
||
if (MODE_OPEN && !(MODE_OPEN === "goal" ? g : pl)) MODE_OPEN = "";
|
||
const gTip = g ? g.line + "\n\n目標:" + g.condition + (g.reason ? "\n最近一次檢查:" + g.reason : "") : "";
|
||
const pTip = pl ? pl.line + "\n\n要做的事:" + pl.task + (pl.steps ? "\n\n" + pl.steps : "") : "";
|
||
const count = pl ? (/\d+/\d+/.exec(pl.line) || [""])[0] : "";
|
||
const chip = (m, on, icon, tip, label, n) => `<button class="mode ${on ? "on" : ""} ${MODE_OPEN === m ? "open" : ""}" data-m="${m}" title="${esc(tip)}" aria-label="${label}" aria-expanded="${MODE_OPEN === m}">${ic(icon, 14)}${n ? `<span>${esc(n)}</span>` : ""}</button>`;
|
||
$("modes").innerHTML = (g ? chip("goal", g.active, "target", gTip, "目標", "") : "") + (pl ? chip("plan", true, "list-checks", pTip, "計畫", count) : "");
|
||
$("modes").querySelectorAll(".mode").forEach((x) => x.onclick = () => { MODE_OPEN = MODE_OPEN === x.dataset.m ? "" : x.dataset.m; renderDockRest(b); });
|
||
$("goalbar").innerHTML = g && MODE_OPEN === "goal" ? `<div class="goalbar ${g.active ? "on" : ""}"><div class="t" title="${esc(gTip)}">${ic("target", 14)}<span>${esc(g.line)}</span></div>${owner() ? `<button id="goal-x">清除目標</button>` : ""}</div>` : "";
|
||
if ($("goal-x")) $("goal-x").onclick = async () => {
|
||
try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/goal clear", attachments: []}}); toast("已清除目標"); loadChat(); } catch (e) { toast(e.message); }
|
||
};
|
||
$("planbar").innerHTML = pl && MODE_OPEN === "plan" ? `<div class="goalbar on"><div class="t" title="${esc(pTip)}">${ic("list-checks", 14)}<span>${esc(pl.line)}</span></div>${owner() ? `<button id="plan-x">取消計畫</button>` : ""}</div>` : "";
|
||
if ($("plan-x")) $("plan-x").onclick = async () => {
|
||
try { await api(base() + `api/bots/${S.open}/send`, {json: {text: "/plan clear", attachments: []}}); toast("已取消計畫"); loadChat(); } catch (e) { toast(e.message); }
|
||
};
|
||
const q = b.queued || [];
|
||
$("queued").innerHTML = q.length ? `<div class="queued">${ic("history", 13)} 已排入:「${esc(q.join("」「"))}」,${esc(b.name)} 會在下一步看到</div>` : "";
|
||
renderSendBtn();
|
||
}
|
||
const BOXIMG = {};
|
||
async function boxThumb(img) {
|
||
if (!img) return;
|
||
try {
|
||
const r = await api(base() + "api/box/thumb", {raw: true});
|
||
if (!r.ok) throw new Error();
|
||
const u = URL.createObjectURL(await safeBlob(r));
|
||
if (BOXIMG.last) URL.revokeObjectURL(BOXIMG.last);
|
||
BOXIMG.last = u; img.src = u;
|
||
} catch (_) { img.alt = "看不到畫面"; }
|
||
}
|
||
function renderQuote() {
|
||
const q = S.quote;
|
||
$("quoting").style.display = q ? "" : "none";
|
||
$("quoting").innerHTML = q ? `${ic("reply", 14)}<span>${esc(q.text)}</span><button class="cbtn" id="q-x">${ic("x", 14)}</button>` : "";
|
||
if (q) $("q-x").onclick = () => { S.quote = null; renderQuote(); };
|
||
}
|
||
const input = $("input");
|
||
input.addEventListener("input", () => {
|
||
input.style.height = "auto"; input.style.height = Math.min(input.scrollHeight, 140) + "px";
|
||
$("composer").classList.toggle("tall", input.scrollHeight > 40); renderSendBtn();
|
||
memSuggestSoon(); renderMemChips(); renderSlash();
|
||
});
|
||
// 技能: a / at the start of the input lists them — tap one, or ↑↓ and Enter/Tab on a keyboard;
|
||
// Esc closes the list until the / is gone. (First here: Enter picks instead of sending.)
|
||
input.addEventListener("keydown", (e) => {
|
||
const n = SL.hits.length;
|
||
if (!n || e.isComposing) return;
|
||
const k = e.key, stop = () => { e.preventDefault(); e.stopImmediatePropagation(); };
|
||
if (k === "ArrowDown" || k === "ArrowUp") { stop(); SL.lit = (SL.lit + (k === "ArrowDown" ? 1 : n - 1)) % n; SL.moved = true; renderSlash(); }
|
||
else if ((k === "Enter" && !e.shiftKey) || k === "Tab") { stop(); slashPick(SL.lit); }
|
||
else if (k === "Escape") { stop(); SL.closed = true; renderSlash(); }
|
||
});
|
||
input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey && !e.isComposing && matchMedia("(pointer:fine)").matches) { e.preventDefault(); send(); } });
|
||
const SL = {hits: [], lit: 0, q: null, moved: false, closed: false, loading: false, fresh: false, at: false};
|
||
/** AnyBot's own / commands (goal.rs on the brain). */
|
||
const COMMANDS = [{name: "goal", description: "設一個目標,一直做到達成為止(/goal clear 清除)"}, {name: "plan", description: "先規劃再動手:它先查清楚、寫出計畫給你核准,核准後才照計畫做(/plan clear 取消)"}, {name: "always-approve", description: "一律放行:Bot 做事不再一個個問你(/always-approve off 關閉)"}, {name: "usage", description: "用量:最近一天和一週,各 Bot、各模型用了多少 token"}, {name: "doctor", description: "診斷:檢查大腦的連線、模型服務、Bot 的電腦、連接器、磁碟"}, {name: "context", description: "這個對話用了模型可讀的多少"}, {name: "compact", description: "現在就把較早的對話整理成摘要"}, {name: "fork", description: "分岔:這段對話存一份到過去的對話,之後各走各的"}, {name: "rewind", description: "退回:把 Bot 改的檔案和對話退回之前說的某一句"}, {name: "btw", description: "開一條支線:帶著這段對話和記憶,同時去做另一件事,做完回報到這裡"}];
|
||
const GOAL_TAG = "[目標]";
|
||
/** The skills a draft like 「/pp」 asks for, as the brain ranks them: name starts with it, name
|
||
* contains it, then description. None once a space ends the name, or while the bot works. */
|
||
function slashHits() {
|
||
const v = input.value;
|
||
// @點名: in a group chat an @ being typed at the end lists the members instead.
|
||
const at = atHits(v);
|
||
SL.at = at !== null;
|
||
if (at !== null) return SL.closed ? [] : at;
|
||
if (!v.startsWith("/")) { SL.closed = false; SL.fresh = false; return []; }
|
||
if (SL.closed || /\s/.test(v.slice(1))) return [];
|
||
// AnyBot's own commands first (the brain acts on them itself), then the skills. While it works
|
||
// only /btw (anything else typed then joins the running turn).
|
||
const working = !!(bot(S.open) || {}).busy;
|
||
const cmds = COMMANDS.filter((c) => c.name.startsWith(v.slice(1).toLowerCase()) && (!working || c.name === "btw"));
|
||
if (working) return cmds;
|
||
// Each new / asks the brain once more, so a skill added since (on the computer, from the
|
||
// market, or one a bot just learned) is there; what was known shows in the meantime.
|
||
if (!SL.fresh && owner() && !SL.loading) {
|
||
SL.fresh = SL.loading = true;
|
||
api(base() + "api/settings").then((st) => { S.settings = st; }).catch(() => {}).finally(() => { SL.loading = false; renderSlash(); });
|
||
}
|
||
// A bare 「/」: the commands only. A word after it also finds this bot's skills by it (a few).
|
||
if (!S.settings || v.length < 2) return cmds;
|
||
const q = v.slice(1).toLowerCase();
|
||
const mine = (bot(S.open) || {}).skills;
|
||
const rank = (k) => { const n = k.name.toLowerCase(); return n.startsWith(q) ? 0 : n.includes(q) ? 1 : (k.description || "").toLowerCase().includes(q) ? 2 : 3; };
|
||
return cmds.concat((S.settings.skills || []).filter((k) => k.enabled !== false && k.name && !COMMANDS.some((c) => c.name === k.name) && (!Array.isArray(mine) || mine.includes(k.name))).map((k) => [rank(k), k]).filter(([r]) => r < 3).sort((a, b) => a[0] - b[0]).slice(0, 6).map(([, k]) => k));
|
||
}
|
||
/** What is typed after an @ at the end of the input (names may hold spaces), or null: a new
|
||
* line or a long run of words ends it, and an @ glued to letters is an address. */
|
||
function atTyping(v) {
|
||
const i = Math.max(v.lastIndexOf("@"), v.lastIndexOf("@"));
|
||
if (i < 0 || (i > 0 && /[A-Za-z0-9]/.test(v[i - 1]))) return null;
|
||
const q = v.slice(i + 1);
|
||
return q.includes("\n") || [...q].length > 24 ? null : q;
|
||
}
|
||
/** Who fits the @ being typed (name starts with it, then contains it): a group's members, or in a
|
||
* bot's own chat the other bots. null when no @ is being typed (or it is working). */
|
||
function atHits(v) {
|
||
const b = bot(S.open) || {};
|
||
if (b.busy) return null;
|
||
const q = atTyping(v);
|
||
if (q === null) return null;
|
||
const s = q.trimStart().toLowerCase();
|
||
const names = b.members ? (b.member_names || []) : S.bots.filter((x) => !x.members && x.id !== b.id).map((x) => x.name);
|
||
return names.map((n) => [n.toLowerCase().startsWith(s) ? 0 : n.toLowerCase().includes(s) ? 1 : 2, n]).filter(([r]) => r < 2).sort((x, y) => x[0] - y[0])
|
||
.map(([, n]) => ({name: n, description: (S.bots.find((x) => x.name === n) || {}).description || ""}));
|
||
}
|
||
function renderSlash() {
|
||
const el = $("slash");
|
||
SL.hits = slashHits();
|
||
if (input.value !== SL.q) { SL.q = input.value; SL.lit = 0; }
|
||
if (!SL.hits.length) { el.innerHTML = ""; return; }
|
||
SL.lit = Math.min(SL.lit, SL.hits.length - 1);
|
||
const mark = SL.at ? "@" : "/";
|
||
el.innerHTML = `<div class="hd">${SL.at ? ((bot(S.open) || {}).members ? "點名成員" : "找其他 Bot 一起來") : "指令和技能"}</div>` + SL.hits.map((k, i) => `<button class="${i === SL.lit ? "on" : ""}" data-sl="${i}"><b>${mark}${esc(k.name)}</b><span>${esc(k.description || "")}</span></button>`).join("");
|
||
el.querySelectorAll("[data-sl]").forEach((x) => {
|
||
// Keep the caret (and the phone's keyboard) in the input while a row is pressed.
|
||
x.onpointerdown = x.onmousedown = (e) => e.preventDefault();
|
||
x.onclick = () => slashPick(+x.dataset.sl);
|
||
});
|
||
if (SL.moved) { SL.moved = false; const on = el.querySelector(".on"); if (on) on.scrollIntoView({block: "nearest"}); }
|
||
}
|
||
function slashPick(i) {
|
||
const k = SL.hits[i];
|
||
if (!k) return;
|
||
if (SL.at) {
|
||
// The name being typed is completed, whatever came before it stays.
|
||
const v = input.value, i = Math.max(v.lastIndexOf("@"), v.lastIndexOf("@"));
|
||
input.value = v.slice(0, i + 1) + k.name + " ";
|
||
} else input.value = "/" + k.name + " ";
|
||
input.focus(); input.setSelectionRange(input.value.length, input.value.length);
|
||
input.dispatchEvent(new Event("input"));
|
||
}
|
||
function renderSendBtn() {
|
||
const b = bot(S.open) || {};
|
||
const empty = !input.value.trim() && !S.pending.length;
|
||
const stop = empty && b.busy && owner();
|
||
$("b-send").innerHTML = ic(stop ? "stop" : "arrow-up", 16);
|
||
$("b-send").title = stop ? "停止" : "傳送訊息";
|
||
$("b-send").disabled = empty && !stop;
|
||
}
|
||
$("b-send").onclick = send;
|
||
async function send() {
|
||
let text = input.value.trim();
|
||
const b = bot(S.open) || {};
|
||
if (!text && !S.pending.length) {
|
||
if (b.busy && owner()) { try { await api(base() + `api/bots/${S.open}/stop`, {json: {}}); toast("已停止"); } catch (e) { toast(e.message); } }
|
||
return;
|
||
}
|
||
if (S.quote) { text = S.quote.raw.split("\n").map((l) => "> " + l).join("\n") + "\n\n" + text; S.quote = null; renderQuote(); }
|
||
const attachments = S.pending.map((p) => p.path);
|
||
// 記憶 ticked above the composer (none of it if the shelf never answered: the brain chooses).
|
||
const memories = b.busy ? undefined : memPicks();
|
||
memReset();
|
||
input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash();
|
||
const quiet = /^\/(goal|plan)(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text) || /^\/(always-approve|yolo)(\s|$)/i.test(text) || /^\/(usage|doctor|context|compact)\s*$/i.test(text) || /^\/(fork|rewind)(\s|$)/.test(text);
|
||
if (!b.busy && !quiet) { if (navigator.vibrate) navigator.vibrate(8); S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; }
|
||
// 先顯示: while it works the words aren't in the chat yet — shown at once all the same.
|
||
const sent = b.busy && text ? {bot: S.open, text, at: Date.now(), failed: false} : null;
|
||
if (sent) { S.sending.push(sent); renderMsgs(); $("scroller").scrollTop = 1e9; }
|
||
const body = {text, attachments}; if (memories) body.memories = memories;
|
||
try { await api(base() + `api/bots/${S.open}/send`, {json: body}); if (quiet) loadChat(); } catch (e) { toast(e.message); if (sent) { sent.failed = true; renderMsgs(); } else input.value = text; }
|
||
}
|
||
$("b-plus").onclick = () => sheet("", [
|
||
{icon: "image", label: "照片與檔案", on: () => $("file").click()},
|
||
{icon: "camera", label: "拍照", on: () => $("camera").click()},
|
||
{icon: "alarm-clock", label: "建立例行任務", on: () => { input.value = "幫我建立一個例行任務:"; input.focus(); input.dispatchEvent(new Event("input")); }},
|
||
]);
|
||
async function upload(files) {
|
||
for (const f of files) {
|
||
toast("上傳 " + f.name + "…");
|
||
try {
|
||
const r = await api(base() + `api/bots/${S.open}/upload?name=` + encodeURIComponent(f.name), {method: "POST", body: f, headers: {"Content-Type": "application/octet-stream"}});
|
||
S.pending.push(r); renderChips();
|
||
} catch (err) { toast(err.message); }
|
||
}
|
||
}
|
||
$("file").onchange = (e) => { upload([...e.target.files]); e.target.value = ""; };
|
||
$("camera").onchange = (e) => { upload([...e.target.files]); e.target.value = ""; };
|
||
function renderChips() {
|
||
$("chips").innerHTML = S.pending.map((p, i) => `<span class="chip">${ic(p.image ? "image" : "file", 14)}<span>${esc(p.name)}</span><button data-i="${i}">${ic("x", 12)}</button></span>`).join("");
|
||
$("chips").querySelectorAll("button").forEach((b) => b.onclick = () => { S.pending.splice(+b.dataset.i, 1); renderChips(); });
|
||
renderSendBtn();
|
||
}
|
||
// 語音輸入: record here; the brain's voice service (設定 › 語音) turns it into text, the same as
|
||
// on every screen. The mic shows only when the brain says it can hear.
|
||
const CAN_REC = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia && window.MediaRecorder);
|
||
// The brain writes Mandarin in Traditional characters for a Traditional Chinese phone.
|
||
const UI_LANG = /^zh-(tw|hk|mo|hant)/i.test(navigator.language || "") ? "zh-TW" : (navigator.language || "");
|
||
let rec = null;
|
||
function micShown() { $("b-mic").style.display = S.voice.listen && CAN_REC ? "" : "none"; }
|
||
micShown();
|
||
$("b-mic").onclick = async () => {
|
||
if (rec) { rec.stop(); return; }
|
||
let stream;
|
||
try { stream = await navigator.mediaDevices.getUserMedia({audio: true}); } catch (_) { toast("沒有允許使用麥克風"); return; }
|
||
const type = ["audio/webm;codecs=opus", "audio/mp4", "audio/webm", "audio/ogg"].find((t) => MediaRecorder.isTypeSupported && MediaRecorder.isTypeSupported(t)) || "";
|
||
const r = new MediaRecorder(stream, type ? {mimeType: type} : {});
|
||
const chunks = [];
|
||
r.ondataavailable = (e) => { if (e.data && e.data.size) chunks.push(e.data); };
|
||
r.onstop = async () => {
|
||
stream.getTracks().forEach((t) => t.stop());
|
||
rec = null; $("b-mic").classList.remove("rec"); $("b-mic").title = "開始語音輸入";
|
||
const mime = r.mimeType || type || "audio/webm";
|
||
const ext = mime.includes("mp4") ? "m4a" : mime.includes("ogg") ? "ogg" : "webm";
|
||
const blob = new Blob(chunks, {type: mime});
|
||
if (blob.size < 1000) { toast("沒有錄到聲音"); return; }
|
||
toast("轉成文字中…");
|
||
try {
|
||
const v = await api(base() + "api/voice/transcribe?name=voice." + ext + "&ui=" + encodeURIComponent(UI_LANG), {method: "POST", body: blob, headers: {"Content-Type": "application/octet-stream"}});
|
||
if (!v.text) { toast("沒有聽到說話"); return; }
|
||
input.value = (input.value ? input.value + " " : "") + v.text; input.dispatchEvent(new Event("input"));
|
||
} catch (err) { toast(err.message); }
|
||
};
|
||
r.start(); rec = r;
|
||
$("b-mic").classList.add("rec"); $("b-mic").title = "停止並轉成文字"; toast("正在錄音…再按一次結束");
|
||
};
|
||
// 朗讀: the brain's voice service reads a message; the phone only plays it.
|
||
let player = null;
|
||
async function speakText(text) {
|
||
if (player) { player.pause(); player = null; }
|
||
// Made while the tap still counts, so the phone lets it play once the sound arrives.
|
||
const a = new Audio(); a.play().catch(() => {}); player = a;
|
||
toast("準備朗讀…");
|
||
try {
|
||
const r = await api(base() + "api/voice/speech", {json: {text}, raw: true});
|
||
if (!r.ok) { let e = ""; try { e = (await r.json()).error || ""; } catch (_) {} throw new Error(e || "HTTP " + r.status); }
|
||
const url = URL.createObjectURL(await safeBlob(r));
|
||
if (player !== a) { URL.revokeObjectURL(url); return; }
|
||
a.onended = () => URL.revokeObjectURL(url);
|
||
a.src = url; await a.play();
|
||
} catch (err) { toast(err.message || "朗讀失敗"); }
|
||
}
|
||
$("b-newchat").onclick = async () => {
|
||
if (!await confirmSheet("開始新對話?", "目前的對話會留在「過去的對話」裡。", "開始新對話", false)) return;
|
||
try { await api(base() + `api/bots/${S.open}/new`, {json: {}}); S.unfold = {}; toast("已開始新對話"); setTimeout(() => loadChat(true), 500); } catch (e) { toast(e.message); }
|
||
};
|
||
$("b-chatmore").onclick = () => {
|
||
const b = bot(S.open); if (!b) return;
|
||
const items = [
|
||
{icon: "info", label: "對話詳細資訊", on: () => go("details", {bot: b.id})},
|
||
{icon: "history", label: "過去的對話", x: String((b.threads || []).length || ""), on: () => threads(b)},
|
||
{icon: "copy", label: "複製整段對話", on: () => copyText(S.msgs.filter((m) => m.text && !m.summary).map((m) => (m.role === "user" ? "我:" : b.name + ":") + m.text).join("\n\n"))},
|
||
];
|
||
if (owner()) items.splice(1, 0, {icon: "refresh", label: "重新產生上一個回答", on: regen});
|
||
if (isOwner()) items.push({icon: "settings", label: "Bot 設定", on: () => go("botset", {bot: b.id})});
|
||
if (isOwner()) items.push({icon: "trash", label: "清除聊天記錄", danger: true, on: async () => { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) { await act("clear", {bot: b.id}); setTimeout(() => loadChat(true), 500); } }});
|
||
sheet(b.name, items);
|
||
};
|
||
function threads(b) {
|
||
const list = b.threads || [];
|
||
if (!list.length) { toast("還沒有過去的對話"); return; }
|
||
sheet("過去的對話", list.map((t) => ({icon: "message", label: t.title || "對話", x: ago(t.at), on: async () => {
|
||
if (!await confirmSheet("回到這段對話?", "現在的對話會留在「過去的對話」裡。", "回到這段對話", false)) return;
|
||
try { await api(base() + `api/bots/${b.id}/restore`, {json: {index: t.index}}); toast("已回到那段對話"); S.unfold = {}; setTimeout(() => loadChat(true), 700); } catch (e) { toast(e.message); }
|
||
}})));
|
||
}
|
||
$("scroller").addEventListener("scroll", () => { const sc = $("scroller"); $("b-down").classList.toggle("on", sc.scrollHeight - sc.scrollTop - sc.clientHeight > 400); });
|
||
$("b-down").onclick = () => { const sc = $("scroller"); sc.scrollTo({top: sc.scrollHeight, behavior: "smooth"}); };
|
||
</script>
|
||
<script>
|
||
"use strict";
|
||
// ---------- 對話詳細資訊 (the desktop's panel beside the chat) ----------
|
||
$("b-botset").innerHTML = ic("settings", 20);
|
||
$("b-botset").onclick = () => go("botset", {bot: cur().arg.bot});
|
||
async function loadDetail(id) {
|
||
if (!owner()) return null;
|
||
try { S.detail[id] = await api(base() + `api/bots/${id}/detail`); S.detailAt = Date.now(); } catch (e) { toast(e.message); }
|
||
return S.detail[id];
|
||
}
|
||
const item = (o) => `<${o.tap ? "button" : "div"} class="item ${o.danger ? "danger" : ""}" ${o.data || ""}>${o.icon ? ic(o.icon, 19) : ""}<div class="mid"><div class="k">${esc(o.k)}</div>${o.v ? `<div class="v">${esc(o.v)}</div>` : ""}</div>${o.r != null ? `<div class="r">${esc(o.r)}</div>` : ""}${o.sw != null ? `<label class="sw"><input type="checkbox" ${o.sw ? "checked" : ""} ${o.swdata || ""} ${o.disabled ? "disabled" : ""}><i></i></label>` : ""}${o.tap && o.chev !== false ? `<span class="chev">${ic("chevron-right", 16)}</span>` : ""}</${o.tap ? "button" : "div"}>`;
|
||
const group = (title, inner, extra = "") => `${title ? `<div class="gt">${esc(title)}${extra}</div>` : ""}<div class="group">${inner}</div>`;
|
||
async function loadAudit(id) {
|
||
try { S.audit[id] = await api(base() + `api/bots/${id}/audit`); } catch (e) { S.audit[id] = {turns: []}; }
|
||
if (cur().v === "details" && S.tab === "audit") renderDetails(id, "audit", true);
|
||
}
|
||
|
||
async function renderDetails(id, tab, quiet) {
|
||
const b = bot(id); if (!b) { back(); return; }
|
||
S.tab = tab || S.tab || "activity";
|
||
if (!quiet || !S.detail[id]) { if (!S.detail[id]) $("details").innerHTML = `<div class="empty">載入中…</div>`; await loadDetail(id); }
|
||
if (cur().v !== "details") return;
|
||
$("b-botset").style.display = isOwner() ? "" : "none";
|
||
const d = S.detail[id] || {};
|
||
const tabs = [["activity", "動態"], ...(isOwner() ? [["memory", "記憶"]] : []), ["routines", "例行任務"], ["library", "資料庫"], ["computer", "電腦"], ["audit", "稽核"]];
|
||
if (b.members) tabs.push(["members", "成員"]);
|
||
let h = `<div class="hero">${face(b, "lg")}<div class="n">${esc(b.name)}</div>${b.description ? `<div class="d">${esc(b.description)}</div>` : ""}</div>`;
|
||
h += `<div class="tabs">${tabs.map(([k, n]) => `<button data-tab="${k}" class="${S.tab === k ? "on" : ""}">${n}</button>`).join("")}</div>`;
|
||
h += `<div id="tab">${tabBody(b, d)}</div><div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
const sc = $("details").scrollTop;
|
||
$("details").innerHTML = h;
|
||
if (quiet) $("details").scrollTop = sc;
|
||
$("details").querySelectorAll("[data-tab]").forEach((x) => x.onclick = () => { S.tab = x.dataset.tab; renderDetails(id, S.tab, true); });
|
||
wireDetails(b, d);
|
||
}
|
||
function tabBody(b, d) {
|
||
const a = S.approvals.find((x) => x.bot === b.id);
|
||
if (S.tab === "memory") { setTimeout(() => memTab(b.id), 0); return `<div id="memtab"><div class="note" style="padding:14px 18px">載入中…</div></div>`; }
|
||
if (S.tab === "activity") {
|
||
let h = "";
|
||
if (b.busy || a) h += group("進行中", (a ? item({icon: "hand", k: a.kind === "handoff" ? "需要你處理" : a.kind === "question" ? "等你回答" : "需要你核准", v: a.title, tap: 1, data: 'data-d="chat"'}) : "") + (b.busy ? item({icon: "loader", k: b.status || "工作中…", r: "", tap: 0}) + `<div class="form"><button class="btn no" data-d="stop">${ic("stop", 14)} 停止</button></div>` : ""));
|
||
h += group("建議", SUGGEST.slice(0, 3).map((x, k) => item({icon: x[0], k: x[1], v: x[2], tap: 1, data: `data-sg="${k}"`})).join(""));
|
||
if (isOwner()) h += group("記憶", item({icon: "bookmark", k: "記得的事和做過的事", v: (d.memories || []).length ? `記得 ${(d.memories || []).length} 件事 · 搜尋、釘選、整理` : "還沒有記得的事。在聊天裡說「記住…」", tap: 1, data: 'data-tab="memory"'}));
|
||
if (owner()) h += group("這個 Bot", item({icon: "sparkles", k: "模型", r: b.model || "", tap: 1, data: 'data-d="model"'}) + item({icon: "file-text", k: "指示", v: d.instructions ? d.instructions.slice(0, 120) + (d.instructions.length > 120 ? "…" : "") : "還沒有寫", tap: isOwner() ? 1 : 0, data: isOwner() ? 'data-d="instr"' : ""}) + item({icon: "history", k: "過去的對話", r: String((d.threads || []).length), tap: 1, data: 'data-d="threads"'}));
|
||
return h;
|
||
}
|
||
if (S.tab === "audit") {
|
||
const a = S.audit[b.id];
|
||
if (a === undefined) { loadAudit(b.id); return `<div class="note" style="padding:14px 16px">載入中…</div>`; }
|
||
if (!a.turns.length) return `<div class="empty">最近 30 天沒有工作紀錄。</div>`;
|
||
const OUT = {completed: "已結束", aborted: "被你停止", failed: "失敗"};
|
||
const ST = {done: "完成", running: "進行中…", waiting: "等核准", denied: "沒有完成(拒絕或停止)", failed: "失敗"};
|
||
const TI = {computer: "zap", menu_click: "zap", fill_form: "zap", wait_for: "clock", run_cmd: "zap", web_fetch: "globe", browser: "globe"};
|
||
let h = "";
|
||
for (const t of [...a.turns].reverse()) {
|
||
const steps = t.steps.map((x) => {
|
||
if (x.type === "model") return item({icon: "sparkles", k: x.step === "assistant" ? "問模型" : x.step === "compaction" ? "整理長對話" : x.step, v: x.attempts > 1 ? `試了 ${x.attempts} 次(有重試)` : ""});
|
||
if (x.type === "tool") return item({icon: TI[x.name] || "zap", k: x.name, v: (x.args || "").slice(0, 200), r: ST[x.status] || x.status});
|
||
if (x.type === "queue") return item({icon: "message", k: "你插進來的話", v: x.text, r: x.state === "waiting" ? "排隊中" : x.state === "consumed" ? "已送達" : "已取消"});
|
||
return item({icon: "stop", k: "你按了停止"});
|
||
}).join("");
|
||
h += group(`${plain(t.prompt || "(無訊息的回合)").slice(0, 24)} · ${ago(t.at)} · ${OUT[t.outcome] || "進行中…"}`, steps); // (group() escapes the title itself)
|
||
}
|
||
return h;
|
||
}
|
||
if (S.tab === "routines") {
|
||
const rs = d.routines || [];
|
||
const list = rs.map((r) => item({icon: r.paused ? "pause" : "alarm-clock", k: r.title, v: (r.trigger ? "事件觸發:" + r.trigger : r.repeat) + " · " + r.when + (r.status ? "\n" + r.status : ""), tap: 1, data: `data-rt="${r.id}"`})).join("");
|
||
return group("", list || `<div class="note" style="padding:14px 16px">例行任務是這個 Bot 依排程重複執行的任務。按下面的新增,或在聊天中請它設定一個。</div>`) + (isOwner() ? `<div class="form"><button class="btn main" data-d="newrt">${ic("plus", 15)} 新增例行任務</button></div>` : "");
|
||
}
|
||
if (S.tab === "library") {
|
||
const pages = S.pages.filter((p) => p.bot === b.name);
|
||
const files = d.files || [];
|
||
const imgs = files.filter((f) => f.image), docs = files.filter((f) => !f.image);
|
||
let h = "";
|
||
if (pages.length) h += group("頁面", pages.map((p) => item({icon: "file-text", k: p.title, v: p.updated, tap: 1, data: `data-page="${p.id}"`})).join(""));
|
||
if (imgs.length) h += `<div class="gt">圖片 <span style="font-weight:400">${imgs.length}</span></div><div class="files">${imgs.map((f) => `<div class="f" data-file="${esc(f.path)}" data-img="1">${FILES[f.path] ? `<img src="${FILES[f.path]}">` : ic("image", 18)}</div>`).join("")}</div>`;
|
||
if (docs.length) h += group("檔案", docs.map((f) => `<a class="item tap" data-file="${esc(f.path)}" data-name="${esc(f.name)}">${ic("file", 19)}<div class="mid"><div class="k" style="font-size:var(--fs-ui);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(f.name)}</div><div class="v">${f.mine ? "你傳的" : "Bot 傳的"} · ${ago(f.at)}</div></div>${ic("download", 16)}</a>`).join(""));
|
||
return h || `<div class="empty">這段對話還沒有頁面或檔案</div>`;
|
||
}
|
||
if (S.tab === "computer") {
|
||
const comps = b.computers || [];
|
||
const own = comps.find((c) => c.kind === "own");
|
||
let h = "";
|
||
if (own) h += `<div class="gt">${esc(own.name)} <span class="pill ${S.boxOn && !/睡|暫停|關/.test(S.box) ? "ok" : ""}" style="margin-left:4px">${esc(S.boxOn ? S.box || "可以用" : "沒有 Docker")}</span></div><div class="group"><div class="thumbbox" style="margin:0;border-radius:0">${S.boxOn ? `<img id="box-thumb" alt="">` : "沒有畫面"}</div><div class="btnrow"><button class="btn main" data-d="openbox">${ic("monitor", 15)} 開啟電腦</button><button class="btn" data-d="takeover">${ic("hand", 15)} 接管</button><button class="btn" data-d="wake">${ic("power", 15)} 喚醒</button></div></div>`;
|
||
h += group("做事的電腦", item({icon: "monitor", k: "預設在這台做事", r: b.computer || "", tap: 1, data: 'data-d="pickcomp"'}));
|
||
h += group("電腦", comps.map((c) => { const k = {own: "cloud", this: "monitor", device: "laptop", ssh: "server"}[c.kind] || "monitor"; return item({icon: k, k: c.name, v: (c.online ? "在線上" : "離線") + (c.person ? " · 你正在用的" : "") + (c.name === b.computer ? " · 預設" : ""), tap: c.kind === "this" && S.mac ? 1 : 0, data: c.kind === "this" && S.mac ? 'data-d="mac"' : ""}); }).join(""));
|
||
return h;
|
||
}
|
||
if (S.tab === "members") {
|
||
const ids = (d.members || []).map((m) => m.id);
|
||
return group("成員", S.bots.filter((x) => !x.members && x.id !== b.id).map((x) => `<button class="item" data-mem="${x.id}"><div class="av sm">${avatarSvg(x.shape, x.color)}</div><div class="mid"><div class="k">${esc(x.name)}</div></div>${ids.includes(x.id) ? `<span style="color:var(--accent)">${ic("check", 18)}</span>` : ""}</button>`).join("")) + `<div class="note">成員依序回答你的訊息,只回答自己擅長的部分;用「@名字」點名就只有被點到的回答,成員也會 @ 彼此接著說。</div>`;
|
||
}
|
||
return "";
|
||
}
|
||
function wireDetails(b, d) {
|
||
const el = $("details");
|
||
const on = (sel, fn) => el.querySelectorAll(sel).forEach((x) => x.onclick = (e) => fn(x, e));
|
||
on("[data-d]", async (x) => {
|
||
const k = x.dataset.d;
|
||
if (k === "chat") back();
|
||
else if (k === "stop") { try { await api(base() + `api/bots/${b.id}/stop`, {json: {}}); toast("已停止"); } catch (e) { toast(e.message); } }
|
||
else if (k === "remember") { const t = await ask("要它記住什麼?", "", "例如:之後的貼文都用輕鬆的語氣"); if (t && await app("remember", {fact: t}, b.id)) renderDetails(b.id, S.tab); }
|
||
else if (k === "model") modelSheet(b);
|
||
else if (k === "instr") editInstructions(b, d);
|
||
else if (k === "threads") threads(b);
|
||
else if (k === "newrt") routineForm(b, null);
|
||
else if (k === "openbox") openBox(false);
|
||
else if (k === "takeover") openBox(true);
|
||
else if (k === "wake") act("box", {op: "wake"}, "正在喚醒…");
|
||
else if (k === "pickcomp") pickComputer(b, d);
|
||
else if (k === "mac") go("screen");
|
||
});
|
||
on("[data-forget]", async (x) => { if (await app("forget", {what: x.dataset.forget}, b.id)) renderDetails(b.id, S.tab); });
|
||
on("[data-sg]", (x) => { const s = SUGGEST[+x.dataset.sg]; back(); setTimeout(() => { input.value = s[3]; input.focus(); input.dispatchEvent(new Event("input")); }, 60); });
|
||
on("[data-rt]", (x) => routineSheet(b, (d.routines || []).find((r) => r.id === +x.dataset.rt)));
|
||
on("[data-mem]", async (x) => {
|
||
if (!isOwner()) return;
|
||
const ids = new Set((d.members || []).map((m) => m.id)); const id = +x.dataset.mem;
|
||
ids.has(id) ? ids.delete(id) : ids.add(id);
|
||
if (await act("bot", {bot: b.id, key: "members", value: [...ids]}, "已更新成員")) renderDetails(b.id, S.tab);
|
||
});
|
||
const t = $("box-thumb"); if (t) boxThumb(t);
|
||
el.querySelectorAll(".files [data-img]").forEach(async (f) => { if (f.querySelector("img")) return; try { const u = await fileUrl(f.dataset.file); f.innerHTML = `<img src="${u}">`; } catch (_) {} });
|
||
el.querySelectorAll(".files [data-img]").forEach((f) => f.onclick = async () => { try { window.open(await fileUrl(f.dataset.file), "_blank"); } catch (e) { toast(e.message); } });
|
||
}
|
||
// ---------- 記憶 ----------
|
||
// The memories live on the brain: the composer asks which ones a draft may want (300 ms after
|
||
// typing stops; the strong ones come ticked), and the memory tab lists, searches and tidies them.
|
||
const memApi = (body) => api(base() + "api/memory", {json: body});
|
||
const KIND = {fact: "記得的事", event: "做過的事", rollup: "整理過的"};
|
||
const memDay = (ms) => ms ? new Date(ms).toLocaleDateString("zh-TW") : "";
|
||
S.carried = new Set();
|
||
S.memSug = {bot: 0, asked: "", hits: [], toggled: {}, timer: null};
|
||
function memOn(h) { const t = S.memSug.toggled[h.id]; return t === undefined ? !!h.pick : t; }
|
||
function memPicks() { const s = S.memSug; return s.bot === S.open && s.asked ? s.hits.filter(memOn).map((h) => h.text) : undefined; }
|
||
function memReset() { clearTimeout(S.memSug.timer); S.memSug = {bot: 0, asked: "", hits: [], toggled: {}, timer: null}; renderMemChips(); }
|
||
function renderMemChips() {
|
||
const s = S.memSug, el = $("memchips");
|
||
// (Not while the bot works: what is sent then joins the running turn, which carries none.)
|
||
const busy = (S.bots.find((x) => x.id === S.open) || {}).busy;
|
||
if (!isOwner() || busy || s.bot !== S.open || !s.hits.length || !input.value.trim()) { el.innerHTML = ""; return; }
|
||
const on = s.hits.filter(memOn), tok = on.reduce((a, h) => a + (h.tokens || 0), 0);
|
||
el.innerHTML = `<span class="lbl">${ic("bookmark", 13)} 帶入記憶</span>` + s.hits.map((h) => `<button class="mchip ${memOn(h) ? "on" : ""}" data-mc="${h.id}" title="${esc(h.text)}">${memOn(h) ? "✓ " : ""}${esc(h.text)}</button>`).join("") + `<span class="memtok">${on.length ? `帶 ${on.length} 條,約 ${tok} token` : "這次不帶"}</span>`;
|
||
el.querySelectorAll("[data-mc]").forEach((x) => x.onclick = () => { const h = s.hits.find((y) => y.id === +x.dataset.mc); if (h) { s.toggled[h.id] = !memOn(h); renderMemChips(); } });
|
||
}
|
||
function memSuggestSoon() {
|
||
const s = S.memSug; clearTimeout(s.timer);
|
||
if (!isOwner() || !S.open) return;
|
||
s.timer = setTimeout(async () => {
|
||
const q = input.value.trim(), bot = S.open;
|
||
if (q.length < 2) { Object.assign(s, {bot, asked: "", hits: [], toggled: {}}); renderMemChips(); return; }
|
||
if (q === s.asked && bot === s.bot) return;
|
||
try {
|
||
const v = await memApi({op: "suggest", bot, q});
|
||
if (S.open !== bot) return;
|
||
const keep = {}; (v.hits || []).forEach((h) => { if (s.bot === bot && s.toggled[h.id] !== undefined) keep[h.id] = s.toggled[h.id]; });
|
||
Object.assign(s, {bot, asked: q, hits: v.hits || [], toggled: keep});
|
||
renderMemChips();
|
||
} catch (_) {}
|
||
}, 300);
|
||
}
|
||
$("msgs").addEventListener("click", (e) => {
|
||
const c = e.target.closest("[data-carried]"); if (!c) return;
|
||
const k = c.dataset.carried; S.carried.has(k) ? S.carried.delete(k) : S.carried.add(k); renderMsgs();
|
||
});
|
||
// The memory tab.
|
||
const MEM_FILTERS = [["all", "全部"], ["fact", "記得的事"], ["event", "做過的事"], ["pinned", "釘選"], ["trash", "最近刪除"]];
|
||
/** `shelf`: the bot's own memories (its id) or 關於你 (0, what every bot knows about the person);
|
||
* left out, the one already open for this bot. */
|
||
function memTab(id, shelf) {
|
||
const el = $("memtab"); if (!el) return;
|
||
const want = shelf === undefined ? (S.mem && S.mem.owner === id ? S.mem.bot : id) : shelf;
|
||
if (!S.mem || S.mem.owner !== id || S.mem.bot !== want) S.mem = {bot: want, owner: id, filter: "all", q: "", limit: 60, items: [], total: 0, ov: null, kept: [], staleOpen: false};
|
||
const m = S.mem;
|
||
const shelves = [[id, "這個 Bot 自己的"], [0, "關於你(所有 Bot 共用)"]];
|
||
el.innerHTML = `<div class="memfilters">${shelves.map(([b, n]) => `<button class="${m.bot === b ? "on" : ""}" data-shelf="${b}">${n}</button>`).join("")}</div>`
|
||
+ (m.bot === 0 ? `<div class="note" style="padding:2px 18px 8px">每個 Bot 每次聊天都帶著這裡的事(最新的 40 條);Bot 記下關於你本人的事(名字、家人、住哪、喜好)時會放在這裡。</div>` : "")
|
||
+ `<div class="memhead" id="mem-head"></div><div class="memsearch"><input id="mem-q" type="search" placeholder="搜尋記憶(打字就找)" value="${esc(m.q)}"><button id="mem-add">${ic("plus", 15)} 新增</button></div><div class="memfilters" id="mem-filters"></div><div id="mem-sugg"></div><div id="mem-list"></div>`;
|
||
let t = null;
|
||
$("mem-q").oninput = () => { clearTimeout(t); t = setTimeout(() => { m.q = $("mem-q").value.trim(); m.limit = 60; memList(); memSugg(); }, 300); };
|
||
$("mem-add").onclick = async () => { const x = await ask(m.bot === 0 ? "所有 Bot 都要知道你什麼?" : "要它記住什麼?", "", m.bot === 0 ? "例如:我住台南,平日早上九點上班" : "例如:之後的貼文都用輕鬆的語氣"); if (x) memWrite({op: "add", text: x}); };
|
||
el.querySelectorAll("[data-shelf]").forEach((x) => x.onclick = () => memTab(id, +x.dataset.shelf));
|
||
memFilters(); memList(); memOverview();
|
||
}
|
||
function memFilters() {
|
||
const m = S.mem, el = $("mem-filters"); if (!el) return;
|
||
el.innerHTML = MEM_FILTERS.filter(([k]) => m.bot !== 0 || (k !== "event" && k !== "pinned")).map(([k, n]) => `<button class="${m.filter === k ? "on" : ""}" data-mf="${k}">${n}</button>`).join("");
|
||
el.querySelectorAll("[data-mf]").forEach((x) => x.onclick = () => { m.filter = x.dataset.mf; m.limit = 60; memFilters(); memList(); memSugg(); });
|
||
}
|
||
async function memOverview() {
|
||
const m = S.mem;
|
||
try { m.ov = await memApi({op: "overview", bot: m.bot}); } catch (e) { toast(e.message); return; }
|
||
const st = m.ov.stats || {}, n = (k) => st[k] || 0;
|
||
const files = (m.ov.files || []).map((f) => `${f.name} ${f.bytes > 1048576 ? (f.bytes / 1048576).toFixed(1) + " MB" : Math.max(1, Math.round(f.bytes / 1024)) + " KB"}`).join(" · ");
|
||
const head = $("mem-head");
|
||
if (head) head.innerHTML = m.bot === 0 ? `記得的事<b>${n("facts")}</b>最近刪除<b>${n("trash")}</b>` : `記得的事<b>${n("facts")}</b>做過的事<b>${n("events") + n("rollups")}</b>釘選<b>${n("pinned")}</b>最近刪除<b>${n("trash")}</b><div class="sub">釘選的每次都帶,其他的相關時才帶</div>`;
|
||
memSugg();
|
||
}
|
||
function memSugg() {
|
||
const m = S.mem, el = $("mem-sugg"); if (!el) return;
|
||
const s = (m.ov && m.ov.suggestions) || {};
|
||
const dupes = (s.dupes || []).filter((d) => !m.kept.includes(d[0].id + ":" + d[1].id)), stale = s.stale || [];
|
||
if (m.filter === "trash" || m.q || (!dupes.length && !stale.length && !s.old_events && !s.old_weeks)) { el.innerHTML = ""; return; }
|
||
let h = `<div class="msugg"><div class="h">${ic("sparkles", 15)} 整理建議</div>`;
|
||
dupes.forEach((d, i) => { h += `<div class="sr">這兩條很像:「${esc(d[0].text)}」/「${esc(d[1].text)}」<div class="acts"><button data-merge="${i}">合併(留下較新的)</button><button data-keep="${i}">兩條都留著</button></div></div>`; });
|
||
if (stale.length) h += `<div class="sr">${stale.length} 條記得的事半年沒被帶入過,可能過時了<div class="acts"><button data-stale="1">${m.staleOpen ? "收起" : "看看是哪些"}</button><button data-staleall="1">全部忘記</button></div>${m.staleOpen ? stale.map((x) => `<div class="sr" style="margin-top:6px">• ${esc(x.text)} <button class="plink" data-forget1="${x.id}">忘記</button></div>`).join("") : ""}</div>`;
|
||
if (s.old_events || s.old_weeks) h += `<div class="sr">${s.old_events ? `${s.old_events} 條做過的事超過 30 天,可以壓成每週一行` : ""}${s.old_events && s.old_weeks ? ";" : ""}${s.old_weeks ? `${s.old_weeks} 行每週的整理可以壓成每月一行` : ""}<div class="acts"><button data-tidy="1">現在整理</button></div><div style="font-size:var(--fs-caption);color:var(--text3);margin-top:4px">每晚也會自動整理;壓掉的原文在「最近刪除」放 30 天。</div></div>`;
|
||
el.innerHTML = h + "</div>";
|
||
el.querySelectorAll("[data-merge]").forEach((x) => x.onclick = () => { const d = dupes[+x.dataset.merge]; const [keep, drop] = d[0].created >= d[1].created ? [d[0], d[1]] : [d[1], d[0]]; memWrite({op: "merge", keep: keep.id, drop: [drop.id]}); });
|
||
el.querySelectorAll("[data-keep]").forEach((x) => x.onclick = () => { const d = dupes[+x.dataset.keep]; m.kept.push(d[0].id + ":" + d[1].id); memSugg(); });
|
||
el.querySelectorAll("[data-stale]").forEach((x) => x.onclick = () => { m.staleOpen = !m.staleOpen; memSugg(); });
|
||
el.querySelectorAll("[data-staleall]").forEach((x) => x.onclick = async () => { if (await confirmSheet(`忘記這 ${stale.length} 條?`, "30 天內可以在「最近刪除」還原。", "全部忘記")) memWrite({op: "forget", ids: stale.map((y) => y.id)}); });
|
||
el.querySelectorAll("[data-forget1]").forEach((x) => x.onclick = () => memWrite({op: "forget", id: +x.dataset.forget1}));
|
||
el.querySelectorAll("[data-tidy]").forEach((x) => x.onclick = () => memWrite({op: "tidy"}));
|
||
}
|
||
async function memList() {
|
||
const m = S.mem, el = $("mem-list"); if (!el) return;
|
||
const want = {op: "list", bot: m.bot, filter: m.filter, q: m.q, limit: m.limit};
|
||
let v; try { v = await memApi(want); } catch (e) { toast(e.message); return; }
|
||
if (S.mem !== m || m.q !== want.q || m.filter !== want.filter) return;
|
||
m.items = v.items || []; m.total = v.total || 0;
|
||
const trash = m.filter === "trash";
|
||
if (!m.items.length) {
|
||
el.innerHTML = `<div class="note" style="padding:14px 18px">${m.q ? "沒有找到相關的記憶。" : trash ? "最近刪除是空的。忘記、合併、壓縮掉的記憶會在這裡放 30 天。" : "還沒有記憶。在聊天裡說「記住…」,或按上面的新增。"}</div>`;
|
||
return;
|
||
}
|
||
el.innerHTML = m.items.map((x) => {
|
||
const meta = [x.pinned ? `<span class="pinned">${ic("pin", 12)} 釘選</span>` : "", KIND[x.kind] || "", memDay(x.created),
|
||
trash ? `${ago(x.deleted)}刪除${x.superseded_by ? "(被新的取代或壓縮)" : ""}` : m.bot === 0 ? "每個 Bot 都帶著" : (x.uses ? `帶過 ${x.uses} 次 · 上次 ${ago(x.last_used)}` : "還沒被帶入過")].filter(Boolean).join(" · ");
|
||
const acts = trash ? `<button data-restore="${x.id}">還原</button>` : `${m.bot === 0 ? "" : `<button data-pin="${x.id}">${x.pinned ? "取消釘選" : "釘選"}</button>`}<button data-edit="${x.id}">編輯</button><button data-forget="${x.id}">忘記</button>`;
|
||
return `<div class="mcard ${x.pinned ? "pin" : ""}"><div class="mt">${esc(x.text)}</div><div class="mm">${meta}</div><div class="ma">${acts}</div></div>`;
|
||
}).join("") + `<div class="memmore"><span>共 ${m.total} 條${m.q && v.ms != null ? `(搜尋 ${v.ms} 毫秒)` : ""}</span>${m.total > m.items.length ? `<button data-more="1">再顯示 ${Math.min(60, m.total - m.items.length)} 條</button>` : trash && m.total ? `<button data-empty="1">清空最近刪除</button>` : ""}</div>`;
|
||
const find = (id) => m.items.find((y) => y.id === +id);
|
||
el.querySelectorAll("[data-pin]").forEach((x) => x.onclick = () => { const y = find(x.dataset.pin); memWrite({op: "pin", id: y.id, on: !y.pinned}); });
|
||
el.querySelectorAll("[data-edit]").forEach((x) => x.onclick = async () => { const y = find(x.dataset.edit); const t = await ask("編輯記憶", y.text, "", true); if (t && t.trim() && t.trim() !== y.text) memWrite({op: "edit", id: y.id, text: t.trim()}); });
|
||
el.querySelectorAll("[data-forget]").forEach((x) => x.onclick = () => memWrite({op: "forget", id: +x.dataset.forget}));
|
||
el.querySelectorAll("[data-restore]").forEach((x) => x.onclick = () => memWrite({op: "restore", id: +x.dataset.restore}));
|
||
el.querySelectorAll("[data-more]").forEach((x) => x.onclick = () => { m.limit += 60; memList(); });
|
||
el.querySelectorAll("[data-empty]").forEach((x) => x.onclick = async () => { if (await confirmSheet("清空最近刪除?", "清掉以後就不能還原了。", "清空")) memWrite({op: "empty_trash"}); });
|
||
}
|
||
async function memWrite(body) {
|
||
const m = S.mem;
|
||
try { const v = await memApi(Object.assign({bot: m.bot}, body)); toast(v.text || "好了"); } catch (e) { toast(e.message); }
|
||
delete S.detail[m.owner];
|
||
memList(); memOverview();
|
||
}
|
||
|
||
// The model, as the desktop's composer picker: each ready provider's chat models, or any name.
|
||
function modelSheet(b) {
|
||
const items = [];
|
||
for (const p of S.models || []) {
|
||
items.push({group: p.label});
|
||
for (const m of p.models || []) items.push({label: m, check: p.provider === b.provider && m === b.model, on: () => setBot(b, {provider: p.provider, model: m}, "之後用 " + m + " 回答")});
|
||
}
|
||
items.push({icon: "pen", label: "其他模型…", on: async () => { const m = await ask("模型名稱", b.model || "", "例如:grok-4.7"); if (m) setBot(b, {provider: b.provider, model: m}, "之後用 " + m + " 回答"); }});
|
||
sheet("模型", items);
|
||
}
|
||
async function setBot(b, body, ok) {
|
||
try { await api(base() + `api/bots/${b.id}/set`, {json: body}); toast(ok); delete S.detail[b.id]; } catch (e) { toast(e.message); }
|
||
}
|
||
function pickComputer(b, d) {
|
||
const list = (d.computers || []).map((c) => c.name);
|
||
sheet("做事的電腦", list.map((n) => ({icon: "monitor", label: n, check: n === b.computer, on: () => setBot(b, {computer: n}, "之後預設在「" + n + "」做事")})));
|
||
}
|
||
async function editInstructions(b, d) {
|
||
const t = await ask("指示(它的工作、口吻、界線)", d.instructions || "", "例如:你負責幫我經營 Threads…", true);
|
||
if (t != null && t !== d.instructions && await app("update_bot", {instructions: t}, b.id, "已更新指示")) { delete S.detail[b.id]; if (cur().v === "details") renderDetails(b.id, S.tab); else if (cur().v === "botset") renderBotset(b.id); }
|
||
}
|
||
// ---------- 例行任務 ----------
|
||
function routineSheet(b, r) {
|
||
if (!r) return;
|
||
const html = `<div class="form"><div style="font-size:var(--fs-h3);font-weight:600">${esc(r.title)}</div><div class="v" style="color:var(--text3);font-size:var(--fs-small)">${esc(r.trigger ? "事件觸發:" + r.trigger : r.repeat)} · ${esc(r.when)}${r.last ? " · 上次 " + esc(r.last) : ""}</div>${r.status ? `<div class="note" style="padding:0">${esc(r.status)}</div>` : ""}${r.target ? `<div class="v" style="color:var(--text2);font-size:var(--fs-small)">${esc(r.target)}</div>` : ""}${r.paused_why ? `<div class="note" style="padding:0;color:var(--attention)">${esc(r.paused_why)}</div>` : ""}${(r.runs || []).length ? `<label>最近執行</label>${r.runs.map((x) => `<div style="font-size:var(--fs-small);line-height:1.5;color:${x.bad ? "var(--attention)" : "var(--text3)"}">${esc(x.line)}</div>${(x.sends || []).map((l) => `<div style="font-size:var(--fs-caption);line-height:1.5;color:var(--text3);padding-left:12px;overflow-wrap:anywhere">· ${esc(l)}</div>`).join("")}`).join("")}` : ""}<label>每次要做的事</label><div style="white-space:pre-wrap;font-size:var(--fs-ui);background:var(--hover);border-radius:var(--r-m);padding:10px 12px">${esc(r.prompt)}</div></div>`;
|
||
sheet("", !isOwner() ? [] : [
|
||
{icon: "play", label: "立即執行", on: () => app("run_routine_now", {id: r.id}, b.id, "已開始執行")},
|
||
{icon: r.paused ? "play" : "pause", label: r.paused ? "繼續" : "暫停", on: async () => { if (await app("update_routine", {id: r.id, paused: !r.paused}, b.id, r.paused ? "已繼續" : "已暫停")) refreshAfter(b); }},
|
||
{icon: "pen", label: "編輯", on: () => routineForm(b, r)},
|
||
{icon: "trash", label: "刪除", danger: true, on: async () => { if (await confirmSheet(`刪除「${r.title}」?`, "這會停止它之後的執行,無法復原。", "刪除") && await app("delete_routine", {id: r.id}, b.id, "已刪除例行任務")) refreshAfter(b); }},
|
||
], html);
|
||
}
|
||
function refreshAfter(b) { delete S.detail[b.id]; setTimeout(() => { const t = cur(); if (t.v === "details") renderDetails(b.id, S.tab); else if (t.v === "list") renderList(t.arg); }, 300); }
|
||
const FREQ = [["daily", "每天"], ["workdays", "每個工作日"], ["weekly", "每週"], ["hourly", "每小時"], ["monthly", "每月"], ["once", "僅一次"]];
|
||
const DAYS = [["MO", "一"], ["TU", "二"], ["WE", "三"], ["TH", "四"], ["FR", "五"], ["SA", "六"], ["SU", "日"]];
|
||
function routineForm(b, r) {
|
||
const sc = (r && r.schedule) || {};
|
||
let freq = sc.once ? "once" : sc.frequency || "daily";
|
||
const dow = new Set(sc.daysOfWeek || sc.days_of_week || []);
|
||
if (freq === "weekly" && dow.size === 5 && !dow.has("SA") && !dow.has("SU")) freq = "workdays";
|
||
const el = sheet(r ? "編輯例行任務" : "新增例行任務", [], `<div class="form">
|
||
<label>名稱</label><input class="field" id="rt-title" value="${esc(r ? r.title : "")}" placeholder="例如:每天早上海巡">
|
||
<label>每次要做的事</label><textarea class="field" id="rt-prompt" placeholder="例如:海巡 Threads 上 AI 工具的熱門討論,整理 5 則">${esc(r ? r.prompt : "")}</textarea>
|
||
<label>多久一次</label><select class="field" id="rt-freq">${FREQ.map(([k, n]) => `<option value="${k}" ${k === freq ? "selected" : ""}>${n}</option>`).join("")}</select>
|
||
<div id="rt-days" class="row2" style="display:${freq === "weekly" ? "flex" : "none"}">${DAYS.map(([k, n]) => `<button class="btn sm ${dow.has(k) ? "main" : ""}" data-day="${k}">${n}</button>`).join("")}</div>
|
||
<div id="rt-mday" style="display:${freq === "monthly" ? "block" : "none"}"><label>每月幾號</label><input class="field" id="rt-md" type="number" min="1" max="31" value="${sc.monthDay || sc.month_day || 1}"></div>
|
||
<label>時間</label><input class="field" id="rt-time" type="time" value="${esc(sc.time || "09:00")}">
|
||
<div class="row2" style="justify-content:flex-end;margin-top:8px"><button class="btn" id="rt-no">取消</button><button class="btn main" id="rt-ok">${r ? "儲存" : "建立"}</button></div></div>`);
|
||
const days = new Set(dow);
|
||
el.querySelector("#rt-freq").onchange = (e) => { el.querySelector("#rt-days").style.display = e.target.value === "weekly" ? "flex" : "none"; el.querySelector("#rt-mday").style.display = e.target.value === "monthly" ? "block" : "none"; };
|
||
el.querySelectorAll("[data-day]").forEach((x) => x.onclick = () => { const k = x.dataset.day; days.has(k) ? days.delete(k) : days.add(k); x.classList.toggle("main"); });
|
||
el.querySelector("#rt-no").onclick = closeSheet;
|
||
el.querySelector("#rt-ok").onclick = async () => {
|
||
const title = el.querySelector("#rt-title").value.trim(), prompt = el.querySelector("#rt-prompt").value.trim();
|
||
const f = el.querySelector("#rt-freq").value, time = el.querySelector("#rt-time").value || "09:00";
|
||
if (!title || !prompt) { toast("名稱和要做的事都要填"); return; }
|
||
const schedule = {frequency: f === "workdays" ? "weekly" : f === "once" ? "daily" : f, time};
|
||
if (f === "workdays") schedule.daysOfWeek = ["MO", "TU", "WE", "TH", "FR"];
|
||
if (f === "weekly") { if (!days.size) { toast("選至少一天"); return; } schedule.daysOfWeek = DAYS.map((d) => d[0]).filter((k) => days.has(k)); }
|
||
if (f === "monthly") schedule.monthDay = Math.max(1, Math.min(31, +el.querySelector("#rt-md").value || 1));
|
||
if (f === "once") schedule.once = true;
|
||
closeSheet();
|
||
const ok = r ? await app("update_routine", {id: r.id, title, prompt, schedule}, b.id) : await app("create_routine", {title, prompt, schedule}, b.id);
|
||
if (ok) refreshAfter(b);
|
||
};
|
||
}
|
||
|
||
// ---------- Bot 設定 (the desktop's bot editor) ----------
|
||
async function renderBotset(id) {
|
||
const b = bot(id); if (!b) { back(); return; }
|
||
$("botset-title").textContent = "設定 " + b.name;
|
||
if (!S.settings) loadSettings().then(() => { if (cur().v === "botset") renderBotset(id); });
|
||
const d = S.detail[id] || await loadDetail(id) || {};
|
||
if (cur().v !== "botset") return;
|
||
const st = S.settings || {};
|
||
const CTX = [[32000, "32K"], [64000, "64K"], [128000, "128K"], [200000, "200K"], [1000000, "1M"]];
|
||
let h = `<div class="hero">${face(b, "lg")}<div class="n">${esc(b.name)}</div></div>`;
|
||
h += group("基本", item({k: "名稱", r: b.name, tap: 1, data: 'data-e="name"'}) + item({k: "描述", v: d.description || "還沒有寫", tap: 1, data: 'data-e="desc"'}) + item({k: "指示", v: d.instructions ? d.instructions.slice(0, 160) + (d.instructions.length > 160 ? "…" : "") : "還沒有寫", tap: 1, data: 'data-e="instr"'}));
|
||
if (isOwner()) {
|
||
h += group("個人檔案", item({k: "擅長", v: d.strengths || "還沒有寫(同事會看到,知道什麼事找它)", tap: 1, data: 'data-e="strengths"'}) + item({k: "不找它做的事", v: d.not_for || "還沒有寫", tap: 1, data: 'data-e="not_for"'}));
|
||
const ticks = (title, key, list, note) => (list || []).length ? group(title, list.map((x) => item({k: x.name, v: x.note || "", sw: !!x.on, swdata: `data-tick="${key}" data-key="${esc(x.key)}"`, disabled: !!x.fixed})).join("") + (note ? `<div class="note" style="padding:8px 16px">${note}</div>` : "")) : "";
|
||
h += ticks("能力", "abilities", d.abilities, "沒勾的工具不會給它,也不佔它每一輪的字數。");
|
||
h += ticks("會的技能", "skills", d.skills, "");
|
||
h += ticks("可以用的電腦", "may_use", (d.may_use || []).length > 1 ? d.may_use : [], "它自己的電腦一定可以用。");
|
||
}
|
||
h += `<div class="gt">頭像</div><div class="group"><div class="shapes">${(st.shapes || []).map((s) => `<button data-shape="${s}" class="${s === d.shape ? "on" : ""}">${avatarSvg(s, b.color)}</button>`).join("")}</div><div class="colors">${(st.colors || []).map((c) => `<button data-color="${c.key}" title="${esc(c.name)}" class="${c.key === d.color ? "on" : ""}" style="background:${c.hex}"></button>`).join("")}</div></div>`;
|
||
h += group("AI 與電腦", item({icon: "sparkles", k: "模型", r: b.via || b.model, tap: 1, data: 'data-e="model"'}) + item({icon: "monitor", k: "做事的電腦", r: b.computer || "", tap: 1, data: 'data-e="comp"'}) + item({icon: "terminal", k: "電腦操作", v: "關掉時,用電腦前會先問你", sw: d.tools_enabled !== false, swdata: 'data-sw="tools"', disabled: !isOwner()}) + item({icon: "brain", k: "模型可讀長度", r: (CTX.find((c) => c[0] === d.context_tokens) || [0, Math.round((d.context_tokens || 0) / 1000) + "K"])[1], tap: 1, data: 'data-e="ctx"'}));
|
||
if (isOwner()) h += group("已設定「一律允許」", (d.allow_rules || []).map((r) => `<div class="item">${ic("shield", 17)}<div class="mid"><div class="v" style="color:var(--text);font-size:var(--fs-ui)">${esc(r)}</div></div><button class="btn sm no" data-rule="${esc(r)}">移除</button></div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有。在核准時選「一律允許」就會記在這裡。</div>`);
|
||
h += group("整理", item({icon: "pin", k: "釘選", sw: !!d.pinned, swdata: 'data-sw="pinned"'}) + item({icon: "star", k: "主要 Bot", v: d.primary ? "這是主要 Bot" : "", sw: !!d.primary, swdata: 'data-sw="primary"', disabled: !!d.primary}) + item({icon: "folder", k: "分區", r: d.folder || "未分區", tap: 1, data: 'data-e="folder"'}));
|
||
if ((d.demos || []).length) h += group("示範教學", d.demos.map((x) => item({icon: "eye", k: x.name, v: `${x.steps} 個步驟 · ${x.created}`})).join("") + `<div class="note" style="padding:8px 16px">示範要在那台電腦上錄;Bot 在對話裡會照著做。</div>`);
|
||
h += group("", item({icon: "refresh", k: "重新啟動這個 Bot", v: "卡住時用:停止它正在做的事和背景指令", tap: 1, data: 'data-e="restart"', chev: false}) + item({icon: "trash", k: "清除聊天記錄", tap: 1, data: 'data-e="clear"', danger: true, chev: false}) + (isOwner() ? item({icon: "trash", k: "刪除 Bot", tap: 1, data: 'data-e="delete"', danger: true, chev: false}) : ""));
|
||
$("botset").innerHTML = h + `<div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
const el = $("botset");
|
||
const refresh = () => { delete S.detail[id]; setTimeout(() => cur().v === "botset" && renderBotset(id), 300); };
|
||
el.querySelectorAll("[data-shape]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "shape", value: x.dataset.shape}, false)) refresh(); });
|
||
el.querySelectorAll("[data-color]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "color", value: x.dataset.color}, false)) refresh(); });
|
||
el.querySelectorAll("[data-rule]").forEach((x) => x.onclick = async () => { if (await act("bot", {bot: id, key: "allow_remove", value: x.dataset.rule}, "已移除")) refresh(); });
|
||
el.querySelectorAll("[data-tick]").forEach((x) => x.onchange = async () => {
|
||
// (The whole ticked list goes: the app keeps "all of them" as no list at all.)
|
||
const k = x.dataset.tick;
|
||
const on = [...el.querySelectorAll(`[data-tick="${k}"]`)].filter((y) => y.checked).map((y) => y.dataset.key);
|
||
if (!await act("bot", {bot: id, key: k, value: on}, false)) x.checked = !x.checked; else delete S.detail[id];
|
||
});
|
||
el.querySelectorAll("[data-sw]").forEach((x) => x.onchange = async () => {
|
||
const k = x.dataset.sw;
|
||
if (k === "primary") { if (await act("bot", {bot: id, key: "primary", value: true}, "已設為主要 Bot")) refresh(); return; }
|
||
if (!await act("bot", {bot: id, key: k, value: x.checked}, false)) x.checked = !x.checked; else refresh();
|
||
});
|
||
el.querySelectorAll("[data-e]").forEach((x) => x.onclick = async () => {
|
||
const k = x.dataset.e;
|
||
if (k === "name") { const n = await ask("名稱", b.name); if (n && n !== b.name && await app("update_bot", {name: n}, id, "已改名")) refresh(); }
|
||
else if (k === "desc") { const n = await ask("描述(一句話說它做什麼)", d.description || ""); if (n != null && await app("update_bot", {description: n}, id, "已更新描述")) refresh(); }
|
||
else if (k === "instr") editInstructions(b, d);
|
||
else if (k === "strengths") { const n = await ask("擅長(什麼事找它)", d.strengths || "", "例如:查資料、寫摘要、追 Threads 上的討論", true); if (n != null && n !== (d.strengths || "") && await act("bot", {bot: id, key: "strengths", value: n}, "已更新")) refresh(); }
|
||
else if (k === "not_for") { const n = await ask("不找它做的事", d.not_for || "", "例如:不寫程式、不碰帳務", true); if (n != null && n !== (d.not_for || "") && await act("bot", {bot: id, key: "not_for", value: n}, "已更新")) refresh(); }
|
||
else if (k === "model") modelSheet(b);
|
||
else if (k === "comp") pickComputer(b, d);
|
||
else if (k === "ctx") sheet("模型可讀長度", CTX.map(([n, l]) => ({label: l + " 個 token", check: n === d.context_tokens, on: async () => { if (await act("bot", {bot: id, key: "context", value: n}, "已更新")) refresh(); }})));
|
||
else if (k === "folder") moveToFolder(b);
|
||
else if (k === "restart") act("restart_bot", {bot: id});
|
||
else if (k === "clear") { if (await confirmSheet("清除聊天記錄?", "這段對話的訊息會全部刪除,無法復原。", "清除")) act("clear", {bot: id}); }
|
||
else if (k === "delete") deleteBot(b);
|
||
});
|
||
}
|
||
</script>
|
||
<script>
|
||
"use strict";
|
||
// ---------- 設定 and the other lists ----------
|
||
async function loadSettings() {
|
||
if (!owner()) return null;
|
||
try { S.settings = await api(base() + "api/settings"); } catch (e) { toast(e.message); }
|
||
return S.settings;
|
||
}
|
||
let listTimer = null;
|
||
function stopListTimer() { clearInterval(listTimer); listTimer = null; }
|
||
const TITLES = {routines: "例行任務", pages: "頁面", computers: "電腦", settings: "設定", general: "一般", models: "模型", perms: "權限", integrations: "整合", vault: "保險庫", account: "手機與帳號", updates: "更新"};
|
||
async function renderList(arg) {
|
||
const kind = arg.kind;
|
||
$("list-title").textContent = TITLES[kind] || "";
|
||
$("list-act").innerHTML = "";
|
||
const el = $("list");
|
||
stopListTimer();
|
||
if (kind === "routines") return listRoutines(el);
|
||
if (kind === "pages") return listPages(el);
|
||
if (["computers", "settings", "general", "models", "perms", "integrations", "vault", "account", "updates"].includes(kind)) {
|
||
if (!S.settings) { el.innerHTML = `<div class="empty">載入中…</div>`; await loadSettings(); }
|
||
if (cur().v !== "list" || cur().arg.kind !== kind) return;
|
||
drawSettings(kind);
|
||
// Things that change on their own (Bot 的電腦 updating, a channel connecting): look again.
|
||
if (["computers", "integrations"].includes(kind)) listTimer = setInterval(async () => { await loadSettings(); if (cur().v === "list" && cur().arg.kind === kind) drawSettings(kind, true); }, 4000);
|
||
}
|
||
}
|
||
async function listRoutines(el) {
|
||
el.innerHTML = `<div class="empty">載入中…</div>`;
|
||
for (const b of S.bots) if (!S.detail[b.id]) await loadDetail(b.id);
|
||
if (cur().arg.kind !== "routines") return;
|
||
let h = "";
|
||
for (const b of S.bots) {
|
||
const rs = (S.detail[b.id] || {}).routines || [];
|
||
if (!rs.length) continue;
|
||
h += `<div class="gt"><div class="av sm" style="width:20px;height:20px">${avatarSvg(b.shape, b.color)}</div>${esc(b.name)}</div><div class="group">${rs.map((r) => item({icon: r.paused ? "pause" : "alarm-clock", k: r.title, v: (r.trigger ? "事件觸發:" + r.trigger : r.repeat) + " · " + r.when, tap: 1, data: `data-rt="${b.id}:${r.id}"`})).join("")}</div>`;
|
||
}
|
||
el.innerHTML = (h || `<div class="empty">還沒有例行任務。<br>例行任務是 Bot 依排程重複執行的任務。</div>`) + (isOwner() ? `<div class="form"><button class="btn main" id="rt-new">${ic("plus", 15)} 新增例行任務</button></div>` : "");
|
||
el.querySelectorAll("[data-rt]").forEach((x) => x.onclick = () => { const [bid, rid] = x.dataset.rt.split(":").map(Number); const b = bot(bid); routineSheet(b, ((S.detail[bid] || {}).routines || []).find((r) => r.id === rid)); });
|
||
if ($("rt-new")) $("rt-new").onclick = () => {
|
||
const pick = (b) => routineForm(b, null);
|
||
if (S.bots.length === 1) pick(S.bots[0]);
|
||
else sheet("交給哪個 Bot?", S.bots.filter((b) => !b.members).map((b) => ({label: b.name, on: () => setTimeout(() => pick(b), 60)})));
|
||
};
|
||
}
|
||
async function listPages(el) {
|
||
el.innerHTML = `<div class="empty">載入中…</div>`;
|
||
let pages = S.pages;
|
||
try { pages = (await act("pages", {}, false) || {}).pages || pages; } catch (_) {}
|
||
if (cur().arg.kind !== "pages") return;
|
||
el.innerHTML = pages.length ? group("", pages.map((p) => item({icon: "file-text", k: p.title, v: (p.bot ? p.bot + " · " : "") + (p.updated || ""), tap: 1, data: `data-page="${p.id}"`})).join("")) : `<div class="empty">還沒有頁面。請 Bot 研究一件事並「整理成一頁」,頁面會出現在這裡。</div>`;
|
||
}
|
||
function rulesGroup(title, list, kind) {
|
||
return group(title, (list || []).map((r) => `<div class="item">${ic(kind === "ask" ? "hand" : "shield", 17)}<div class="mid"><div class="v" style="color:var(--text);font-size:var(--fs-ui)">${esc(r)}</div></div>${isOwner() ? `<button class="btn sm no" data-rmrule="${kind}" data-r="${esc(r)}">移除</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有規則</div>`, isOwner() ? `<button data-addrule="${kind}">${ic("plus", 14)} 新增</button>` : "");
|
||
}
|
||
function drawSettings(kind, quiet) {
|
||
const st = S.settings || {};
|
||
const el = $("list");
|
||
const sc = el.scrollTop;
|
||
let h = "";
|
||
if (kind === "settings") {
|
||
h += group("", [
|
||
["general", "settings", "一般", "外觀、時區、通知"], ["models", "sparkles", "模型", "可以用的 AI 服務"], ["perms", "shield", "權限", st.direct_mode ? "直接操作:開" : "Bot 做事前的規則"],
|
||
["integrations", "plug", "整合", "訊息管道、連接器、技能"], ["computers", "monitor", "電腦", "Bot 的電腦和你帳號裡的電腦"], ["vault", "lock", "保險庫", "密碼和卡號"],
|
||
["account", "smartphone", "手機與帳號", "登入的手機、通知"], ["updates", "download", "更新", st.version || ""],
|
||
].map(([k, i, n, v]) => item({icon: i, k: n, r: k === "updates" ? v : "", tap: 1, data: `data-go="${k}"`})).join(""));
|
||
}
|
||
if (kind === "general") {
|
||
st.accent = ({Quiet: "quiet", BotColor: "bot_color", Black: "black"})[st.accent] || st.accent;
|
||
const theme = {system: "跟隨系統", light: "淺色", dark: "深色"}[st.theme] || "";
|
||
h += group("電腦上的 AnyBot", item({icon: "moon", k: "主題", r: theme, tap: 1, data: 'data-s="theme"'}) + item({icon: "sparkles", k: "聊天的顏色", r: ({quiet: "安靜", black: "只用黑色", bot_color: "跟著 Bot"})[st.accent] || "安靜", tap: 1, data: 'data-s="accent"'}));
|
||
h += group("", item({icon: "globe", k: "時區", r: st.timezone || "", tap: 1, data: 'data-s="tz"'}) + item({icon: "bell", k: "通知", sw: !!st.notify, swdata: 'data-sset="notify"', disabled: !isOwner()}));
|
||
h += group("這支手機", item({icon: "smartphone", k: "外觀", r: (THEMES.find((t) => t[0] === phoneTheme()) || THEMES[0])[1], tap: 1, data: 'data-s="phonetheme"'}));
|
||
}
|
||
if (kind === "models") {
|
||
h += group("AI 服務", (st.providers || []).map((p, i) => item({k: p.label, v: p.ready && p.default_model ? p.default_model : "", r: p.ready ? "可以用" : "未設定", tap: isOwner() ? 1 : 0, data: `data-prov="${i}"`})).join(""));
|
||
h += `<div class="note">金鑰只存在這台 AnyBot,手機寫得進去、看不到。</div>`;
|
||
}
|
||
if (kind === "perms") {
|
||
h += group("", item({icon: "zap", k: "直接操作", v: st.direct_locked ? "已由管理員關閉" : "Bot 直接做事,只有危險操作和「一律詢問」規則會先問你", sw: !!st.direct_mode, swdata: 'data-sset="direct_mode"', disabled: !isOwner() || st.direct_locked}) + item({icon: "shield", k: "自動審核", v: "照下面的規則自動允許或先問你", sw: !!st.auto_review, swdata: 'data-sset="auto_review"', disabled: !isOwner()}));
|
||
h += rulesGroup("一律詢問(優先)", st.ask_rules, "ask") + rulesGroup("無需詢問直接允許", st.allow_rules, "allow");
|
||
h += `<div class="note">用一般的話寫,例如「付款前先問我」。兩邊都符合時先問。</div>`;
|
||
}
|
||
if (kind === "integrations") {
|
||
const dot = (ok, on) => `<span style="width:8px;height:8px;border-radius:50%;flex:none;background:${!on ? "var(--text4)" : ok ? "var(--ok)" : "var(--warn)"}"></span>`;
|
||
h += group("訊息管道", (st.channels || []).map((c) => `<div class="item">${dot(c.ok, c.enabled)}<div class="mid"><div class="k">${esc(c.kind)} · ${esc(c.name)}</div><div class="v">由「${esc(c.bot)}」回覆${c.note ? " · " + esc(c.note) : ""}</div></div>${isOwner() ? `<label class="sw"><input type="checkbox" ${c.enabled ? "checked" : ""} data-ch="${c.id}"><i></i></label><button class="ib" data-chrm="${c.id}" title="移除">${ic("trash", 16)}</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有。Telegram、Slack、Discord… 要在電腦上的 AnyBot 新增(需要輸入 Token)。</div>`);
|
||
h += group("連接器(MCP)", ((st.mcp || []).map((m) => `<div class="item">${dot(m.tools != null, m.enabled)}<div class="mid"><div class="k">${esc(m.name)}</div><div class="v">${!m.enabled ? "已關閉" : m.tools != null ? `已連上,${m.tools} 個工具` : m.error ? esc(m.error) : "連線中…"}</div></div>${isOwner() ? `${m.enabled ? `<button class="ib" data-mcpre="${esc(m.name)}" title="重新連線">${ic("refresh", 16)}</button>` : ""}<label class="sw"><input type="checkbox" ${m.enabled ? "checked" : ""} data-mcp="${esc(m.name)}"><i></i></label><button class="ib" data-mcprm="${esc(m.name)}" title="移除">${ic("trash", 16)}</button>` : ""}</div>`).join("") || `<div class="note" style="padding:12px 16px">還沒有連接器</div>`) + (isOwner() ? item({icon: "plus", k: "從公用市集加入", v: "搜尋官方 MCP Registry 裡用網址連的連接器", tap: 1, data: 'data-mcpmarket="1"'}) : ""));
|
||
const skRows = (st.skills || []).map((k, i) => {
|
||
const tags = [...(k.resources && k.resources.length ? [`${k.resources.length} 檔`] : []), ...(k.steps ? [`可重播 ${k.steps} 步`] : [])].join(" · ");
|
||
return `<div class="item"><div class="mid" data-skill="${i}" style="cursor:pointer"><div class="k">${esc(k.name)}${tags ? ` <span class="pill" style="margin-left:4px">${esc(tags)}</span>` : ""}</div><div class="v">${esc(k.description)}</div></div>${isOwner() ? `<label class="sw"><input type="checkbox" ${k.enabled !== false ? "checked" : ""} data-sksw="${esc(k.name)}"><i></i></label>` : ""}</div>`;
|
||
}).join("");
|
||
const skActions = isOwner()
|
||
? item({icon: "sparkles", k: "從技能市集加入", v: "內建繁中核心技能包與 Anthropic 官方開源技能", tap: 1, data: 'data-skillmarket="1"'}) +
|
||
item({icon: "plus", k: "從 GitHub 或網址安裝技能", v: "支援 anthropics/skills 網址、owner/repo/path 或 SKILL.md 連結", tap: 1, data: 'data-skilladd="1"', chev: false})
|
||
: "";
|
||
h += group("技能", (skRows || `<div class="note" style="padding:12px 16px">還沒有技能。可從下方「技能市集」一鍵加入,或在聊天裡請 Bot 幫你建立。</div>`) + skActions);
|
||
}
|
||
if (kind === "computers") h += computersHtml(st);
|
||
if (kind === "vault") h += `<div class="empty">${ic("lock", 28)}<br><br>保險庫裡的密碼、卡號和聯絡資訊,只在電腦上的 AnyBot 管理。<br>Bot 用到時由 AnyBot 直接填進網頁,不會交給模型,也不會經過手機。</div>`;
|
||
if (kind === "account") {
|
||
h += group("這台 AnyBot", item({icon: "monitor", k: "名稱", r: st.host || S.hostName}) + item({icon: "info", k: "你的角色", r: isOwner() ? "擁有者" : "管理員"}));
|
||
if (st.devices) h += group("直接連線的手機", st.devices.map((d, i) => item({icon: "smartphone", k: d.name, v: d.last_seen ? "上次使用 " + ago(d.last_seen * 1000) : "登入於 " + ago(d.created * 1000), tap: 1, data: `data-dev="${i}"`})).join("") || `<div class="note" style="padding:12px 16px">沒有</div>`);
|
||
const acts = [];
|
||
if (S.relay) acts.push(item({icon: "bell", k: "通知", v: "Bot 需要你允許、或做完事時,手機跳通知", tap: 1, data: 'data-s="push"'}));
|
||
if (S.relay) acts.push(item({icon: "shield", k: "兩步驗證", v: "登入要密碼+驗證器 App 的六位碼", tap: 1, data: 'data-s="2fa"'}));
|
||
if (S.relay) acts.push(item({icon: "smartphone", k: "登入的裝置", v: "看看有哪些裝置登著,可逐台踢掉", tap: 1, data: 'data-s="devices"'}));
|
||
if (S.relay && owner()) acts.push(item({icon: "plus", k: "加一台電腦", v: "Linux、伺服器當 Bot 的手腳", tap: 1, data: 'data-s="pair"'}));
|
||
if (S.relay) acts.push(item({icon: "refresh", k: "切換到別台 AnyBot", tap: 1, data: 'data-s="host"'}));
|
||
acts.push(item({icon: "log-out", k: "登出這支手機", tap: 1, data: 'data-s="out"', danger: true, chev: false}));
|
||
h += group("這支手機", acts.join(""));
|
||
}
|
||
if (kind === "updates") {
|
||
h += group("", item({icon: "info", k: "版本", v: st.built ? `${stamp(st.built)} 建置` : "", r: st.version || ""}) + (st.newer ? item({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : item({icon: "circle-check", k: "已是最新版"})));
|
||
h += `<div class="note">Bot 的電腦的更新在「電腦」裡。</div>`;
|
||
}
|
||
el.innerHTML = h + `<div style="height:calc(var(--safe-b) + 24px)"></div>`;
|
||
if (quiet) el.scrollTop = sc;
|
||
wireSettings(kind, st);
|
||
}
|
||
function computersHtml(st) {
|
||
const box = st.box || {}, f = box.facts || {};
|
||
const main = S.bots.find((b) => b.primary) || S.bots[0] || {};
|
||
const comps = main.computers || [];
|
||
const own = comps.find((c) => c.kind === "own");
|
||
const running = box.available && /運作中|可以用|執行中|已開/.test(box.state || "") || (box.available && !/睡|暫停|關|沒有|失敗|建立中|喚醒中|更新/.test(box.state || ""));
|
||
let h = `<div class="gt">${esc(own ? own.name : "Bot 的電腦")} <span class="pill ${running ? "ok" : ""}" style="margin-left:4px">${esc(box.state || "")}</span></div><div class="group">`;
|
||
if (box.available) h += `<div class="thumbbox" style="margin:0;border-radius:0">${running ? `<img id="box-thumb" alt="">` : esc(box.state || "")}</div>`;
|
||
h += `<div class="btnrow"><button class="btn main" data-bx="open">${ic("monitor", 15)} 開啟電腦</button><button class="btn" data-bx="take">${ic("hand", 15)} 接管</button><button class="btn" data-bx="wake">${ic("power", 15)} 喚醒</button>${isOwner() ? `<button class="btn" data-bx="snapshot">${ic("hard-drive", 15)} 儲存快照</button>` : ""}<button class="btn" data-bx="disk">檢查用量</button></div>`;
|
||
if (box.note) h += `<div class="note" style="padding:0 16px 12px">${esc(box.note)}</div>`;
|
||
h += `</div>`;
|
||
if (box.disk) h += group("用量", `<div class="log">${esc(box.disk)}</div>`);
|
||
const rt = box.runtime === "runsc" ? "強隔離(gVisor)" : "標準";
|
||
const running_rt = f.running ? (f.running === "runsc" ? "強隔離" : "標準") : "";
|
||
const steps = f.steps && f.steps.n ? `平均每步 ${Math.round(f.steps.total_ms / f.steps.n)} ms(${f.steps.n} 步)` : "";
|
||
h += group("", item({icon: "download", k: "更新 Bot 的電腦", v: f.update == null ? "檢查中…" : f.update ? `有新版(v${box.version})。檔案和登入都會留著` : `已是 v${box.version}`, tap: isOwner() && f.update ? 1 : 0, data: 'data-bx="update"'}) +
|
||
item({icon: "alarm-clock", k: "自動更新", r: box.auto_update || "關", tap: isOwner() ? 1 : 0, data: 'data-bx="auto"'}) +
|
||
item({icon: "shield", k: "容器隔離", v: running_rt && running_rt !== rt.slice(0, 2) ? `目前是${running_rt};按更新後改成${rt}` : (f.gvisor === false && box.runtime !== "runsc" ? "這台 Docker 主機沒有 gVisor" : ""), r: rt, tap: isOwner() && (f.gvisor || box.runtime === "runsc") ? 1 : 0, data: 'data-bx="runtime"'}) +
|
||
item({icon: "hard-drive", k: "上次快照", r: box.snapshot || "還沒有"}) +
|
||
(steps ? item({icon: "activity", k: "速度", r: steps}) : "") +
|
||
(st.docker_host ? item({icon: "server", k: "Docker 主機", v: st.docker_host}) : ""));
|
||
h += group("", item({icon: "sparkles", k: "請 Bot 提出清理方案", v: "先列出用量最大的地方,不會直接刪除", tap: 1, data: 'data-bx="clean"'}) +
|
||
(isOwner() ? item({icon: "refresh", k: box.snapshot ? "從快照復原" : "重設電腦", v: box.snapshot ? `回到 ${box.snapshot} 的快照(目前的內容會先存起來)` : "換一台全新的電腦(檔案和登入會清除)", tap: 1, data: 'data-bx="reset"', danger: true, chev: false}) : ""));
|
||
if ((box.log || []).length) h += `<div class="gt">紀錄</div><div class="group"><div class="log">${esc(box.log.slice(-25).join("\n"))}</div></div>`;
|
||
const others = comps.filter((c) => c.kind !== "own");
|
||
if (others.length) h += group("帳號裡的電腦", others.map((c) => item({icon: {this: "monitor", device: "laptop", ssh: "server"}[c.kind] || "monitor", k: c.name, v: (c.online ? "在線上" : "離線") + (c.person ? " · 你正在用的" : ""), tap: c.kind === "this" && S.mac ? 1 : 0, data: c.kind === "this" && S.mac ? 'data-bx="mac"' : ""})).join(""));
|
||
return h;
|
||
}
|
||
async function devicesSheet() {
|
||
let me;
|
||
try { me = await api("relay/me"); } catch (e) { toast(e.message); return; }
|
||
const ss = me.sessions || [];
|
||
const html = ss.map((d) => item({icon: "smartphone", k: d.device || "裝置", v: "上次使用 " + ago(d.last * 1000), r: d.id})).join("") || `<div class="note" style="padding:12px 16px">只有這支手機</div>`;
|
||
sheet("登入的裝置 (" + ss.length + ")", [
|
||
{icon: "log-out", label: "全部登出", danger: true, on: async () => {
|
||
if (!await confirmSheet("全部登出?", "包含這支手機。其他裝置要重新用密碼(和驗證碼)登入。", "全部登出")) return;
|
||
await api("relay/sessions/logout", {json: {}}); signOut();
|
||
}},
|
||
], html + `<div class="note">踢掉某一台:按它的「裝置代號」。不知道是哪台就全部登出。</div>`);
|
||
// Tapping a device's id (the .r span) kicks just it.
|
||
sheet.devices = ss;
|
||
$("sheet-in").querySelectorAll(".item .r").forEach((el, i) => { el.style.textDecoration = "underline"; el.onclick = async (e) => {
|
||
e.stopPropagation();
|
||
const d = (sheet.devices || [])[i]; if (!d) return;
|
||
if (!await confirmSheet(`登出「${d.device || "裝置"}」?`, "那台手機要重新登入才能用。", "登出這台")) return;
|
||
const v = await api("relay/sessions/drop", {json: {id: d.id}});
|
||
if (v.was_self) { signOut(); return; }
|
||
toast("已登出"); devicesSheet();
|
||
}; });
|
||
}
|
||
async function twoFaSheet() {
|
||
let me;
|
||
try { me = await api("relay/me"); } catch (e) { toast(e.message); return; }
|
||
if (!me.two_factor) {
|
||
if (!await confirmSheet("打開兩步驗證?", "之後登入要密碼,加驗證器 App(Google Authenticator、Authy、Apple 密碼…)的六位碼。會給你 8 個恢復碼——收好,遺失驗證器時用。", "開始設定", false)) return;
|
||
let v;
|
||
try { v = await api("relay/2fa/enroll", {json: {}}); } catch (e) { toast(e.message); return; }
|
||
const el = sheet("在驗證器 App 加入這組金鑰", [],
|
||
`<div class="form"><div class="note">金鑰(在 App 選「輸入設定金鑰」貼上)</div><input class="field" readonly value="${esc(v.secret)}">
|
||
<div class="note">恢復碼——只顯示這一次,先抄下來</div><textarea class="field" readonly rows="3" style="font-family:var(--mono)">${v.recovery_codes.join(" ")}</textarea>
|
||
<div class="note">App 加好金鑰後,輸入它現在顯示的六位碼</div><input class="field" id="2fa-in" inputmode="numeric" placeholder="123456" autocomplete="one-time-code">
|
||
<button class="btn main" id="2fa-ok">開啟兩步驗證</button></div>`);
|
||
el.querySelector("#2fa-ok").onclick = async () => {
|
||
const b = el.querySelector("#2fa-ok"); b.disabled = true;
|
||
try { await api("relay/2fa/verify", {json: {code: el.querySelector("#2fa-in").value.trim()}}); closeSheet(); toast("兩步驗證已開啟,恢復碼收好"); }
|
||
catch (e) { toast(e.message); b.disabled = false; }
|
||
};
|
||
return;
|
||
}
|
||
const code = await ask("關閉兩步驗證", "", "先輸入一個六位碼證明是你");
|
||
if (!code) return;
|
||
try { await api("relay/2fa/disable", {json: {code}}); toast("兩步驗證已關閉"); } catch (e) { toast(e.message); }
|
||
}
|
||
|
||
function wireSettings(kind, st) {
|
||
const el = $("list");
|
||
const on = (sel, ev, fn) => el.querySelectorAll(sel).forEach((x) => x[ev] = () => fn(x));
|
||
const again = async () => { await loadSettings(); if (cur().v === "list") drawSettings(cur().arg.kind, true); };
|
||
on("[data-go]", "onclick", (x) => go("list", {kind: x.dataset.go}));
|
||
on("[data-sset]", "onchange", async (x) => {
|
||
const k = x.dataset.sset;
|
||
if (k === "direct_mode" && x.checked && !await confirmSheet("打開「直接操作」?", "Bot 會直接做事,只有危險操作和你的「一律詢問」規則會停下來問你。", "打開", false)) { x.checked = false; return; }
|
||
if (!await act("setting", {key: k, value: x.checked})) x.checked = !x.checked; else again();
|
||
});
|
||
on("[data-addrule]", "onclick", async (x) => { const t = await ask(x.dataset.addrule === "ask" ? "一律詢問的規則" : "無需詢問的規則", "", x.dataset.addrule === "ask" ? "例如:發文、寄信、付款前先問我" : "例如:讀取網頁和檔案"); if (t && await act("setting", {key: "rule_add", list: x.dataset.addrule, value: t}, "已新增")) again(); });
|
||
on("[data-rmrule]", "onclick", async (x) => { if (await act("setting", {key: "rule_remove", list: x.dataset.rmrule, value: x.dataset.r}, "已移除")) again(); });
|
||
on("[data-ch]", "onchange", async (x) => { if (!await act("channel", {id: +x.dataset.ch, enabled: x.checked})) x.checked = !x.checked; else again(); });
|
||
on("[data-chrm]", "onclick", async (x) => { if (await confirmSheet("移除這個管道?", "", "移除") && await act("channel", {id: +x.dataset.chrm, remove: true}, "已移除")) again(); });
|
||
on("[data-mcp]", "onchange", async (x) => { if (!await act("mcp", {name: x.dataset.mcp, enabled: x.checked})) x.checked = !x.checked; else again(); });
|
||
on("[data-mcpre]", "onclick", async (x) => { if (await act("mcp", {name: x.dataset.mcpre, reconnect: true}, "重新連線中…")) { again(); setTimeout(again, 4000); } });
|
||
on("[data-mcprm]", "onclick", async (x) => { if (await confirmSheet("移除這個連接器?", "", "移除") && await act("mcp", {name: x.dataset.mcprm, remove: true}, "已移除")) again(); });
|
||
on("[data-prov]", "onclick", (x) => {
|
||
const p = st.providers[+x.dataset.prov];
|
||
sheet(p.label, [
|
||
...(p.needs_key || p.key === "Custom" ? [{icon: "key", label: p.ready && p.needs_key ? "換一把 API 金鑰…" : "設定 API 金鑰…", on: async () => { const k = await ask(p.label + " 的 API 金鑰", "", "貼上金鑰(存在這台 AnyBot,手機看不到)"); if (k && await act("provider", {provider: p.key, key: k}, "已設定金鑰")) again(); }}] : []),
|
||
// ChatGPT 方案: an account on the brain, not a key. The sign-in page opens here; the page it
|
||
// comes back to (127.0.0.1 on the brain) won't load on the phone, so its address is pasted back.
|
||
...(p.account ? [{icon: "key", label: p.ready ? "重新用 ChatGPT 登入…" : "使用 ChatGPT 繼續…", on: async () => {
|
||
// (Opened now, while the tap still counts: a window opened after waiting is blocked.)
|
||
const w = window.open("", "_blank");
|
||
if (!w) { toast("請允許這個網頁開新視窗,再按一次"); return; }
|
||
const v = await act("chatgpt", {action: "login"}, false);
|
||
if (!v || !v.url || !String(v.url).startsWith("https://auth.openai.com/")) { w.close(); if (v && v.text) toast(v.text); return; }
|
||
w.location = v.url;
|
||
const cb = await ask("登入並同意後,那一頁打不開的話,把它的網址整個貼在這裡", "", "http://127.0.0.1:1455/auth/callback?code=…");
|
||
if (!cb) return;
|
||
const r = await act("chatgpt", {action: "login", callback: cb}, false);
|
||
if (r) { toast(r.text || (r.ok ? "已登入" : "沒有登入成功")); again(); }
|
||
}}, ...(p.ready ? [{icon: "trash", label: "登出 ChatGPT", danger: true, on: async () => { if (await confirmSheet("登出 ChatGPT?", "用 ChatGPT 方案的 Bot 會沒辦法回答,直到再登入。", "登出") && await act("chatgpt", {action: "logout"})) again(); }}] : [])] : []),
|
||
{icon: "sparkles", label: "新 Bot 預設模型…", x: p.default_model || "", on: async () => { const m = await ask("新 Bot 預設用的模型", p.default_model || ""); if (m != null && await act("provider", {provider: p.key, default_model: m}, "已更新")) again(); }},
|
||
...(p.ready && p.needs_key ? [{icon: "trash", label: "清除金鑰", danger: true, on: async () => { if (await confirmSheet(`清除 ${p.label} 的金鑰?`, "用這個服務的 Bot 會沒辦法回答,直到再設定一把。", "清除") && await act("provider", {provider: p.key, key: ""}, "已清除")) again(); }}] : []),
|
||
]);
|
||
});
|
||
on("[data-dev]", "onclick", async (x) => {
|
||
const d = st.devices[+x.dataset.dev];
|
||
if (await confirmSheet(`登出「${d.name}」?`, "那支手機要重新輸入密碼才能再連。如果是你現在用的這支,也會被登出。", "登出") && await act("device_remove", {name: d.name, created: d.created}, "已登出那支手機")) again();
|
||
});
|
||
on("[data-sksw]", "onchange", async (x) => { if (!await act("skill", {name: x.dataset.sksw, enabled: x.checked})) x.checked = !x.checked; else again(); });
|
||
// 公用市集: the brain searches the official MCP Registry; a pick asks for what it needs (the
|
||
// key, an address part) and the brain adds it.
|
||
on("[data-mcpmarket]", "onclick", async () => {
|
||
const q = await ask("搜尋公用市集", "", "例如 notion、search、docs");
|
||
if (!q) return;
|
||
toast("搜尋中…");
|
||
let found;
|
||
try { found = (await api(base() + "api/mcp/registry?q=" + encodeURIComponent(q))).servers || []; } catch (e) { toast(e.message); return; }
|
||
if (!found.length) { toast("沒有找到,換個關鍵字試試(英文的比較多)"); return; }
|
||
const have = new Set((st.mcp || []).map((m) => m.what));
|
||
sheet(`公用市集:${q}`, found.map((e) => ({
|
||
icon: "plug",
|
||
label: e.title + (e.description ? " — " + e.description : ""),
|
||
x: e.note ? "還不支援" : have.has(e.url) ? "已加入" : e.header ? "要金鑰" : "",
|
||
on: async () => {
|
||
if (e.note) { toast(e.note); return; }
|
||
if (have.has(e.url)) { toast("已經加入過了"); return; }
|
||
let url = e.url, header = "";
|
||
for (const v of e.variables || []) {
|
||
const val = await ask(`網址裡的 ${v.name}`, (v.choices || [])[0] || "", v.description || "");
|
||
if (!val) return;
|
||
url = url.split("{" + v.name + "}").join(val);
|
||
}
|
||
if (e.header) {
|
||
const key = await ask(`${e.title} 的金鑰`, "", e.header.description || e.header.value);
|
||
if (!key) return;
|
||
header = `${e.header.name}: ${e.header.value.replace(/\{[^}]*\}/, key)}`;
|
||
}
|
||
if (await act("mcp", {add: {name: e.title, url, header}})) again();
|
||
},
|
||
})), `<div class="note" style="text-align:center">官方 MCP Registry 裡用網址連的連接器。要登入帳號(OAuth)的 AnyBot 還不支援,加入後連線時會說。</div>`);
|
||
});
|
||
on("[data-skillmarket]", "onclick", () => {
|
||
const installed = new Set((st.skills || []).map((s) => s.name));
|
||
const list = (st.skill_market || []).map((m) => ({
|
||
icon: m.remote ? "download" : "sparkles",
|
||
label: `${m.name}${m.title && m.title !== m.name ? " · " + m.title : ""}`,
|
||
x: installed.has(m.name) ? "已加入" : (m.remote ? "GitHub" : "內建"),
|
||
on: async () => {
|
||
if (installed.has(m.name)) { toast("已經加入過了"); return; }
|
||
if (m.remote) {
|
||
toast("正在從 GitHub 下載技能…");
|
||
if (await app("skill_install", {url: m.source}, 0, `已安裝技能「${m.name}」`)) again();
|
||
} else {
|
||
if (await act("skill", {builtin: m.name}, `已加入技能「${m.name}」`)) again();
|
||
}
|
||
},
|
||
}));
|
||
sheet("技能市集", list, `<div class="note" style="text-align:center">點一下即可安裝,所有 Bot 都能使用</div>`);
|
||
});
|
||
on("[data-skilladd]", "onclick", async () => {
|
||
const url = await ask("安裝技能", "", "GitHub 網址、owner/repo/path 或 SKILL.md 網址");
|
||
if (url && await app("skill_install", {url}, 0, "已安裝技能")) again();
|
||
});
|
||
on("[data-skill]", "onclick", (x) => {
|
||
const k = st.skills[+x.dataset.skill];
|
||
const filesHtml = (k.resources && k.resources.length) ? `<div style="font-size:var(--fs-caption);color:var(--text3)">隨附檔案:<code>${esc(k.resources.join("、"))}</code></div>` : "";
|
||
sheet("", isOwner() ? [{icon: "trash", label: "刪除技能", danger: true, on: async () => { if (await confirmSheet(`刪除技能「${k.name}」?`, "", "刪除") && await act("skill", {name: k.name, remove: true}, "已刪除技能")) again(); }}] : [],
|
||
`<div class="form"><div style="font-size:var(--fs-h3);font-weight:600">${esc(k.name)}</div><div style="color:var(--text3);font-size:var(--fs-small)">${esc(k.description)}</div>${filesHtml}<div style="white-space:pre-wrap;font-size:var(--fs-small);background:var(--hover);border-radius:var(--r-m);padding:10px 12px;max-height:50vh;overflow:auto">${esc(k.instructions)}</div></div>`);
|
||
});
|
||
on("[data-s]", "onclick", async (x) => {
|
||
const k = x.dataset.s;
|
||
if (k === "theme") sheet("主題", [["system", "跟隨系統"], ["light", "淺色"], ["dark", "深色"]].map(([v, n]) => ({label: n, check: st.theme === v, on: async () => { if (await app("update_settings", {theme: v})) again(); }})));
|
||
else if (k === "accent") sheet("聊天的顏色", [["quiet", "安靜(淡灰泡泡)"], ["bot_color", "跟著 Bot"], ["black", "只用黑色"]].map(([v, n]) => ({label: n, check: (st.accent || "quiet") === v, on: async () => { if (await app("update_settings", {accent: v})) again(); }})));
|
||
else if (k === "tz") {
|
||
const zones = [...new Set([TZ, "Asia/Taipei", "Asia/Tokyo", "Asia/Shanghai", "Asia/Hong_Kong", "Asia/Singapore", "Europe/London", "America/New_York", "America/Los_Angeles", "UTC"].filter(Boolean))];
|
||
sheet("時區", zones.map((z) => ({label: z + (z === TZ ? "(這支手機)" : ""), check: st.timezone === z, on: async () => { if (await app("update_settings", {timezone: z})) again(); }})));
|
||
}
|
||
else if (k === "phonetheme") sheet("這支手機的外觀", THEMES.map(([v, n]) => ({label: n, check: phoneTheme() === v, on: () => { try { localStorage.setItem("anybot.theme", v); } catch (_) {} applyTheme(); drawSettings(kind, true); }})));
|
||
else if (k === "push") notifySheet();
|
||
else if (k === "2fa") twoFaSheet();
|
||
else if (k === "devices") devicesSheet();
|
||
else if (k === "pair") pair();
|
||
else if (k === "host") { S.host = ""; localStorage.removeItem("anybot.host"); S.version = 0; NAV.length = 0; pickHost(); }
|
||
else if (k === "out") { if (await confirmSheet("要登出這支手機嗎?", "", "登出")) signOut(); }
|
||
});
|
||
on("[data-bx]", "onclick", async (x) => {
|
||
const k = x.dataset.bx, box = st.box || {};
|
||
if (k === "open") openBox(false);
|
||
else if (k === "take") openBox(true);
|
||
else if (k === "mac") go("screen");
|
||
else if (k === "wake") { await act("box", {op: "wake"}, "正在喚醒…"); again(); }
|
||
else if (k === "snapshot") { await act("box", {op: "snapshot"}, "正在儲存快照…"); again(); }
|
||
else if (k === "disk") { await act("box", {op: "disk"}, "檢查中…"); setTimeout(again, 2500); }
|
||
else if (k === "update") { if (await confirmSheet("更新 Bot 的電腦?", "正在做的事會先停下來;檔案和登入都會留著,要幾分鐘。", "更新", false)) { await act("box", {op: "update"}, "更新已開始"); again(); } }
|
||
else if (k === "auto") sheet("自動更新", [{label: "關", check: !box.auto_update, on: async () => { if (await act("box", {op: "auto_update", value: ""})) again(); }}, {label: "每天在這個時間更新…", on: async () => { const t = await ask("每天幾點更新(有新版時)", box.auto_update || "03:00", "HH:MM"); if (t && await act("box", {op: "auto_update", value: t})) again(); }}]);
|
||
else if (k === "clean") {
|
||
const main = S.bots.find((b) => b.primary) || S.bots[0]; if (!main) return;
|
||
go("chat", {bot: main.id});
|
||
setTimeout(() => { input.value = "檢查「Bot 的電腦」的磁碟使用情況,並提出安全的清理方案供我核准。先列出用量最大的地方,不要直接刪除任何東西。"; input.dispatchEvent(new Event("input")); input.focus(); }, 300);
|
||
}
|
||
else if (k === "reset") {
|
||
const restore = !!box.snapshot;
|
||
if (await confirmSheet(restore ? "從快照復原?" : "重設電腦?", restore ? "會關閉目前的電腦,從上次的快照以最新版本開一台新的。目前電腦的內容會先存成快照,事後可以找回。正在做的事會先停下來。" : "還沒有快照:會換一台全新的電腦,裡面的檔案和登入資訊都會清除。正在做的事會先停下來。", restore ? "復原" : "重設")) { await act("box", {op: "reset"}, "已開始"); again(); }
|
||
}
|
||
else if (k === "runtime") sheet("容器隔離", [["runc", "標準", "容器和主機共用核心"], ["runsc", "強隔離(gVisor)", "電腦有自己的虛擬核心,Chromium 的沙盒打開"]].map(([v, n, d]) => ({label: n, x: d, check: (box.runtime || "runc") === v, on: async () => { if (await act("box", {op: "runtime", value: v}, "已設定;按「更新」重建後生效")) again(); }})));
|
||
});
|
||
const t = $("box-thumb"); if (t) boxThumb(t);
|
||
}
|
||
|
||
// ---------- 頁面 ----------
|
||
$("b-pagemore").innerHTML = ic("ellipsis", 20);
|
||
document.addEventListener("click", (e) => {
|
||
const el = e.target.closest && e.target.closest("[data-page]");
|
||
if (el && !e.defaultPrevented) { e.preventDefault(); go("page", {id: +el.dataset.page}); }
|
||
});
|
||
async function openPage(id, rev) {
|
||
S.page = id; $("pscroll").scrollTop = 0;
|
||
if (!rev) $("page").innerHTML = `<div class="empty">載入中…</div>`;
|
||
try {
|
||
const v = await api(base() + "api/pages/" + id + (rev ? "?rev=" + rev : ""));
|
||
S.pageData = v;
|
||
$("page-name").textContent = v.title;
|
||
const old = v.revision !== v.latest;
|
||
let head = `<h1 class="pt">${esc(v.title)}</h1><div class="mt">${esc(v.bot)} · 更新於 ${esc(v.updated)}${v.latest > 1 ? ` · 第 ${v.revision} 版` : ""}</div>`;
|
||
if (old) head += `<div class="old">你在看舊的版本。<a class="plink" data-page="${id}">回到最新版</a></div>`;
|
||
else if (v.summary) head += `<p class="sum">${esc(v.summary)}</p>`;
|
||
if (v.note && v.revision > 1) head += `<div class="chg">這一版更新了:${esc(v.note)}</div>`;
|
||
if ((v.kpis || []).length) head += `<div class="stats">${v.kpis.map((k) => `<div class="stat"><div class="k">${esc(k.label)}</div><div class="v${String(k.value || "").length > 10 ? " long" : ""}">${esc(k.value)}</div>${k.delta ? `<div class="s${trend(k.delta)}">${esc(k.delta)}</div>` : ""}</div>`).join("")}</div>`;
|
||
if (v.verdict) head += `<div class="call k-verdict"><div class="ct">${ic("circle-check", 15)}結論</div><p>${inl(v.verdict)}</p></div>`;
|
||
$("page").innerHTML = head + `<div class="toc-at"></div>` + pageMd(v.body, id, old ? v.revision : 0);
|
||
pageToc($("page"));
|
||
loadCharts();
|
||
} catch (e) { $("page").innerHTML = `<div class="empty">${esc(e.message)}</div>`; }
|
||
}
|
||
// 目錄: with 3+ headings, one quiet line 「目錄 · N 節」 that opens to the headings; a tap scrolls there.
|
||
function pageToc(root) {
|
||
const at = root.querySelector(".toc-at"); if (!at) return;
|
||
const all = [...root.children].filter((x) => /^H[2-4]$/.test(x.tagName)), lv = (h) => +h.tagName[1];
|
||
const top = Math.min(...all.map(lv)), hs = all.filter((h) => lv(h) <= top + 1);
|
||
if (hs.length < 3) { at.remove(); return; }
|
||
const toc = document.createElement("details");
|
||
toc.className = "toc";
|
||
toc.innerHTML = `<summary>${ic("chevron-right", 14)}目錄 · ${hs.length} 節</summary><ol>${hs.map((h, i) => `<li class="${lv(h) > top ? "sub" : ""}"><button data-toc="${i}">${esc(h.textContent)}</button></li>`).join("")}</ol>`;
|
||
toc.querySelectorAll("[data-toc]").forEach((b) => b.onclick = () => hs[+b.dataset.toc].scrollIntoView({block: "start", behavior: "smooth"}));
|
||
at.replaceWith(toc);
|
||
}
|
||
$("b-pagemore").onclick = () => {
|
||
const v = S.pageData; if (!v) return;
|
||
const items = [{icon: "copy", label: "複製 Markdown", on: () => copyText(v.body)}];
|
||
if ((v.versions || []).length) items.push({icon: "history", label: "其他版本", on: () => sheet("版本", [{label: `第 ${v.latest} 版(最新)`, check: v.revision === v.latest, on: () => openPage(v.id)}, ...v.versions.map((x) => ({label: `第 ${x.revision} 版`, x: x.at, check: v.revision === x.revision, on: () => openPage(v.id, x.revision)}))])});
|
||
if (isOwner()) items.push({sep: true}, {icon: "trash", label: "刪除頁面", danger: true, on: async () => { if (await confirmSheet(`刪除「${v.title}」?`, "", "刪除") && await act("delete_page", {id: v.id}, "已刪除頁面")) back(); }});
|
||
sheet(v.title, items);
|
||
};
|
||
// Files in a chat: pictures shown in place, every file opened as a preview (as the desktop
|
||
// shows it) — api/preview says what it is, api/preview/image decodes it, api/preview/pdf
|
||
// renders one page at a time. Saving is a button in the preview's own bar.
|
||
/** A fetched answer as a blob that can never run as a page of this site: a picture (no SVG),
|
||
* sound, video or PDF keeps its type; anything else (HTML, SVG, unknown) is plain bytes. The
|
||
* brain names the type, and a brain may be someone else's (a team). */
|
||
async function safeBlob(r) {
|
||
const b = await r.blob();
|
||
const t = String(b.type || "").split(";")[0].trim().toLowerCase();
|
||
const ok = /^(image\/(png|jpeg|gif|webp|bmp|avif|heic|x-icon)|audio\/[\w.+-]+|video\/[\w.+-]+|application\/pdf)$/.test(t);
|
||
return ok ? b : new Blob([b], {type: "application/octet-stream"});
|
||
}
|
||
/** Keep a fetched file's blob URL, and let the oldest go past 40 of them: a tab left open for
|
||
* days used to hold every picture, PDF page and recording it had ever shown. */
|
||
function keepBlob(map, key, url) {
|
||
map[key] = url;
|
||
const keys = Object.keys(map);
|
||
for (const old of keys.slice(0, Math.max(0, keys.length - 40))) { URL.revokeObjectURL(map[old]); delete map[old]; }
|
||
}
|
||
const FILES = {};
|
||
async function fileUrl(path) {
|
||
if (!FILES[path]) {
|
||
const r = await api(base() + "api/file?path=" + encodeURIComponent(path), {raw: true});
|
||
if (!r.ok) throw new Error("找不到這個檔案");
|
||
keepBlob(FILES, path, URL.createObjectURL(await safeBlob(r)));
|
||
}
|
||
return FILES[path];
|
||
}
|
||
// Raw GETs fetched with the login, kept as blob URLs (decoded images, PDF pages, media).
|
||
const BLOBS = {};
|
||
async function blobUrl(url, key) {
|
||
if (!BLOBS[key]) {
|
||
const r = await api(url, {raw: true});
|
||
if (!r.ok) { let m = "找不到這個檔案"; try { m = (await r.json()).error || m; } catch (_) {} throw new Error(m); }
|
||
keepBlob(BLOBS, key, URL.createObjectURL(await safeBlob(r)));
|
||
}
|
||
return BLOBS[key];
|
||
}
|
||
async function loadFiles() {
|
||
for (const el of document.querySelectorAll(".attimg[data-file]")) {
|
||
if (el.querySelector("img")) continue;
|
||
// 預覽圖走 api/preview/image: it decodes TIFF/HEIC too, not only web formats.
|
||
const p = el.dataset.file;
|
||
try { const u = await blobUrl(base() + "api/preview/image?path=" + encodeURIComponent(p), "img:" + p); el.innerHTML = `<img alt="" src="${u}">`; } catch (_) { el.innerHTML = `<div class="wait">這張圖讀不到</div>`; }
|
||
}
|
||
}
|
||
document.addEventListener("click", async (e) => {
|
||
const img = e.target.closest && e.target.closest(".attimg[data-file]");
|
||
if (img) { e.preventDefault(); openFile(img.dataset.file, img.dataset.name); return; }
|
||
const f = e.target.closest && e.target.closest("a[data-file]");
|
||
if (!f) return;
|
||
e.preventDefault();
|
||
openFile(f.dataset.file, f.dataset.name);
|
||
});
|
||
async function openFile(path, name) {
|
||
const f = {path, name: name || "檔案", page: 0, pages: 0, kind: "", data: null};
|
||
S.file = f;
|
||
$("file-name").textContent = f.name;
|
||
$("filebody").innerHTML = `<div class="empty">載入中…</div>`;
|
||
$("filepager").style.display = "none";
|
||
go("file", {});
|
||
try {
|
||
const v = await api(base() + "api/preview?path=" + encodeURIComponent(path));
|
||
if (S.file !== f) return; // the person left while it loaded
|
||
Object.assign(f, {kind: v.kind, pages: v.pages || 0, data: v});
|
||
drawFile(f);
|
||
} catch (e) {
|
||
if (S.file === f) $("filebody").innerHTML = `<div class="empty">${esc(e.message)}</div>`;
|
||
}
|
||
}
|
||
function drawFile(f) {
|
||
const v = f.data, body = $("filebody");
|
||
if (f.kind === "image") {
|
||
body.innerHTML = `<div class="fimg"><div class="empty">讀取中…</div></div>`;
|
||
blobUrl(base() + "api/preview/image?path=" + encodeURIComponent(f.path), "img:" + f.path)
|
||
.then((u) => { if (S.file === f) body.innerHTML = `<div class="fimg"><img alt="" src="${u}"></div>`; })
|
||
.catch((e) => { if (S.file === f) body.innerHTML = `<div class="empty">${esc(e.message)}</div>`; });
|
||
} else if (f.kind === "pdf") {
|
||
$("filepager").style.display = f.pages > 1 ? "flex" : "none";
|
||
pdfPage(f, 0);
|
||
} else if (f.kind === "markdown" || f.kind === "html") {
|
||
body.innerHTML = `<div class="page">${pageMd(v.text || "", 0, 0)}</div>`;
|
||
} else if (f.kind === "text") {
|
||
body.innerHTML = `<pre class="ftext">${esc(v.text || "")}</pre>`;
|
||
} else if (f.kind === "sheet") {
|
||
body.innerHTML = `<div class="page">` + (v.sheets || []).map((s) =>
|
||
`<h2>${esc(s.name)}</h2><div class="tw"><table><tbody>` +
|
||
(s.rows || []).map((r, i) => `<tr>${(r || []).map((c) => i === 0 ? `<th>${esc(c)}</th>` : `<td>${esc(c)}</td>`).join("")}</tr>`).join("") +
|
||
`</tbody></table></div>`).join("") + `</div>`;
|
||
} else if (f.kind === "audio" || f.kind === "video") {
|
||
body.innerHTML = `<div class="fmedia"><div class="empty">讀取中…</div></div>`;
|
||
blobUrl(base() + "api/file?path=" + encodeURIComponent(f.path), "file:" + f.path)
|
||
.then((u) => { if (S.file === f) body.innerHTML = `<div class="fmedia">${f.kind === "audio" ? `<audio controls src="${u}"></audio>` : `<video controls src="${u}"></video>`}</div>`; })
|
||
.catch((e) => { if (S.file === f) body.innerHTML = `<div class="empty">${esc(e.message)}</div>`; });
|
||
} else {
|
||
body.innerHTML = `<div class="fdl">${ic("file", 40)}<div>${esc(v.message || "這個檔案沒有預覽")}<br>${esc(f.name)}${v.bytes ? " · " + kb(v.bytes) : ""}</div><button class="btn main" id="f-get">儲存到手機</button></div>`;
|
||
$("f-get").onclick = () => saveFile(f.path, f.name);
|
||
}
|
||
}
|
||
async function pdfPage(f, n) {
|
||
f.page = Math.max(0, Math.min(n, Math.max(0, f.pages - 1)));
|
||
$("f-at").textContent = (f.page + 1) + " / " + f.pages;
|
||
$("filebody").innerHTML = `<div class="empty">讀第 ${f.page + 1} 頁…</div>`;
|
||
try {
|
||
const u = await blobUrl(base() + "api/preview/pdf?path=" + encodeURIComponent(f.path) + "&page=" + f.page, f.path + "#" + f.page);
|
||
if (S.file === f) $("filebody").innerHTML = `<div class="fimg"><img alt="" src="${u}"></div>`;
|
||
} catch (e) { if (S.file === f) $("filebody").innerHTML = `<div class="empty">${esc(e.message)}</div>`; }
|
||
}
|
||
$("f-prev").onclick = () => { if (S.file) pdfPage(S.file, (S.file.page || 0) - 1); };
|
||
$("f-next").onclick = () => { if (S.file) pdfPage(S.file, (S.file.page || 0) + 1); };
|
||
// Saving a chat file (from the preview's bar): fetched with the login, handed to the phone.
|
||
function saveFile(path, name) {
|
||
fileUrl(path).then((u) => { const a = document.createElement("a"); a.href = u; a.download = name || "檔案"; document.body.appendChild(a); a.click(); a.remove(); }).catch((e) => toast(e.message));
|
||
}
|
||
$("b-filesave").innerHTML = ic("download", 20);
|
||
$("b-filesave").onclick = () => { if (S.file) saveFile(S.file.path, S.file.name); };
|
||
const isDark = () => document.documentElement.dataset.theme === "dark" || (!document.documentElement.dataset.theme && matchMedia("(prefers-color-scheme: dark)").matches);
|
||
async function loadCharts() {
|
||
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 = `<img alt="圖表" src="${URL.createObjectURL(await safeBlob(r))}">`;
|
||
} catch (_) { el.innerHTML = `<div class="wait">這張圖畫不出來</div>`; }
|
||
}
|
||
}
|
||
// Inline Markdown: code, bold, italics, strike, links (page:N opens the page).
|
||
function inl(s) {
|
||
return esc(s)
|
||
.replace(/`([^`]+)`/g, "<code>$1</code>")
|
||
.replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>")
|
||
.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, "$1<i>$2</i>")
|
||
.replace(/~~([^~]+)~~/g, "<s>$1</s>")
|
||
.replace(/\[([^\]]+)\]\(page:(\d+)\)/g, (_, t, id) => `<a class="plink" data-page="${id}">${t}</a>`)
|
||
.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>')
|
||
.replace(/(^|[\s((::,、「])(https?:\/\/[^\s<))」,。]+)/g, '$1<a href="$2" target="_blank" rel="noopener">$2</a>');
|
||
}
|
||
const CALL = {note: "說明", tip: "提示", warning: "注意", important: "重要"};
|
||
// A call-out's icon: the one coloured thing in it (the tint is the same for every kind).
|
||
const CALL_IC = {note: "info", tip: "lightbulb", warning: "circle-alert", important: "zap"};
|
||
// A table column of numbers (amounts, %, counts) lines up on the right; a label column doesn't.
|
||
const NUM_CELL = /^[+\-−~≈約]?\s?[$€£¥]?\s?\d[\d,]*(\.\d+)?\s?(%|[萬億千元個次人台倍件kKMB×x])?$/;
|
||
function numCols(head, rows) {
|
||
return head.map((_, j) => {
|
||
if (!j) return false;
|
||
const vals = rows.map((r) => String(r[j] ?? "").replace(/[*`]/g, "").trim()).filter((v) => v && !/^[-—–]$|^N\/A$/i.test(v));
|
||
return vals.length > 0 && vals.every((v) => NUM_CELL.test(v));
|
||
});
|
||
}
|
||
// 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,和桌面版同一套規則(解析照 src/pages.rs chart(),畫法照
|
||
src/app/markdown_ui.rs md_chart_card):長條依大小排序(標籤本身有順序(月/季/年/數字)
|
||
時不排);單系列長條把數字直接標在條上、不畫 y 軸,折線和多系列長條有 y 軸;多條線在
|
||
線尾標系列名;只留淡水平參考線;圖下附數據表;色板用 --cat1..6(同 theme.rs)。
|
||
圖照手機畫面的寬度畫:字是 --fs-caption(12 px),螢幕上就是 12 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)]);
|
||
}
|
||
// 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];
|
||
}
|
||
// Whether the value axis starts at 0 (src/pages.rs chart_from_zero): bars always; a line only when 0
|
||
// is within reach of its data (its lowest value is 0 or less, or no bigger than its spread) — a
|
||
// reading of 1,649–1,796 W drawn from 0 was a flat line pressed against the top.
|
||
function chartFromZero(c) {
|
||
if (c.kind !== "line") return true;
|
||
const all = c.series.flatMap((s) => s[1]).filter((v) => isFinite(v));
|
||
if (!all.length) return true;
|
||
const lo = Math.min(...all), hi = Math.max(...all);
|
||
return lo <= 0 || lo <= hi - lo;
|
||
}
|
||
// Bar and line.
|
||
function chartPlot(c, W) {
|
||
const FS = 12, 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]);
|
||
// Bars from 0; a line far from 0 fits its data (chartFromZero).
|
||
const z = chartFromZero(c) ? [0] : [];
|
||
const vmin = Math.min(...z, ...all), vmax = Math.max(...z, ...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)))) + 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(`<rect x="${x}" y="${y - 10}" width="9" height="9" rx="2" style="fill:${chartCol(si)}"/><text x="${x + 13}" y="${y}" style="font-size:var(--fs-caption);fill:var(--text2)">${esc(name)}</text>`);
|
||
x += w;
|
||
});
|
||
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(`<line x1="${L}" y1="${y}" x2="${W - R}" y2="${y}" style="stroke:var(--grid)" stroke-width="1"/>`);
|
||
if (!labelBars) svg.push(`<text x="${L - 6}" y="${(Y(t) + 4).toFixed(1)}" text-anchor="end" style="font-size:var(--fs-caption);fill:var(--text3)">${chartNum(t)}</text>`);
|
||
}
|
||
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(`<text x="${xx[k].toFixed(1)}" y="${H - 8}" text-anchor="middle" style="font-size:var(--fs-caption);fill:var(--text3)">${esc(s)}</text>`);
|
||
});
|
||
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(`<rect x="${(cx - bw / 2).toFixed(1)}" y="${Math.min(y0, yv).toFixed(1)}" width="${bw.toFixed(1)}" height="${Math.max(1, Math.abs(y0 - yv)).toFixed(1)}" rx="${Math.min(4, bw / 3).toFixed(1)}" style="fill:${chartCol(si)}"><title>${esc(c.labels[i])}${s[0] ? " · " + esc(s[0]) : ""} · ${chartNum(v)}</title></rect>`);
|
||
}));
|
||
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(`<text x="${inside(X(k), chartTextW(vs[k], FS))}" y="${(v >= 0 ? yv - 5 : yv + FS + 2).toFixed(1)}" text-anchor="middle" style="font-size:var(--fs-caption);fill:var(--text2)">${vs[k]}</text>`);
|
||
});
|
||
}
|
||
} else {
|
||
const names = [];
|
||
c.series.forEach((s, si) => {
|
||
const pts = order.map((i, k) => [X(k), Y(s[1][i])]);
|
||
svg.push(`<polyline points="${pts.map((p) => p[0].toFixed(1) + "," + p[1].toFixed(1)).join(" ")}" fill="none" style="stroke:${chartCol(si)}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>`);
|
||
pts.forEach((p, k) => svg.push(`<circle cx="${p[0].toFixed(1)}" cy="${p[1].toFixed(1)}" r="3" style="fill:${chartCol(si)}"><title>${esc(c.labels[order[k]])}${s[0] ? " · " + esc(s[0]) : ""} · ${chartNum(s[1][order[k]])}</title></circle>`));
|
||
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(`<text x="${e.x.toFixed(1)}" y="${Math.max(FS, e.y - over).toFixed(1)}" font-weight="600" style="font-size:var(--fs-caption);fill:${chartCol(e.si)}">${esc(chartFit(chartCut7(c.series[e.si][0]), W - e.x - 2, FS))}</text>`));
|
||
}
|
||
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 = 12, 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 = `<title>${esc(names[i])} · ${chartNum(vals[i])} (${share(i)}%)</title>`;
|
||
// 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(`<circle cx="${cx}" cy="${cy}" r="${r}" style="fill:${chartCol(i)}">${tip}</circle>`);
|
||
else svg.push(`<path d="M${cx},${cy} L${pt(a0)} A${r},${r} 0 ${sweep > Math.PI ? 1 : 0} 1 ${pt(a0 + sweep)} Z" style="fill:${chartCol(i)};stroke:var(--elev)" stroke-width="2" stroke-linejoin="round">${tip}</path>`);
|
||
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(`<rect x="${lx}" y="${(y - 5).toFixed(1)}" width="9" height="9" rx="2" style="fill:${chartCol(i)}"/><text x="${lx + 14}" y="${(y + 4).toFixed(1)}" style="font-size:var(--fs-caption);fill:var(--text2)">${esc(chartFit(legend[k], W - lx - 18, FS))}</text>`);
|
||
});
|
||
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]);
|
||
const tbl = `<div class="ctab"><table><thead><tr>${cols.map((h) => `<th>${esc(h)}</th>`).join("")}</tr></thead><tbody>${labels.map((l, i) => `<tr><td>${esc(l)}</td>${cols.slice(1).map((_, k) => `<td>${cell(i, k + 1)}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`;
|
||
// Longer than CHART_TABLE_FOLD rows: folded into 「▸ 數據 · N 筆」 (the chart already shows them).
|
||
return labels.length > CHART_TABLE_FOLD ? `<details class="dt"><summary>數據 · ${labels.length} 筆</summary>${tbl}</details>` : tbl;
|
||
}
|
||
const CHART_TABLE_FOLD = 6;
|
||
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 viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" style="max-width:${Math.round(W * 1.3)}px" role="img" aria-label="${esc(c.title || "圖表")}">${svg}</svg>` : "";
|
||
return `<div class="chartcard">${c.title ? `<div class="ct2">${esc(c.title)}</div>` : ""}${pic}${chartTable(c)}</div>`;
|
||
}
|
||
// ```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;
|
||
const cells = (l) => l.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
|
||
while (i < L.length) {
|
||
const l = L[i], t = l.trim();
|
||
if (!t) { i++; continue; }
|
||
const fence = t.match(/^```\s*([\w-]*)/);
|
||
if (fence) {
|
||
const lang = fence[1].toLowerCase(); const body = []; i++;
|
||
while (i < L.length && !L[i].trim().startsWith("```")) body.push(L[i++]);
|
||
i++;
|
||
if (lang === "mermaid" && id) { out.push(`<div class="chart" data-src="api/pages/${id}/chart/${chart++}${rev ? "?rev=" + rev : ""}"><div class="wait">圖表載入中…</div></div>`); continue; }
|
||
// ```details <title>: 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(`<details class="dt"><summary>${esc(title)}</summary><div class="dt-in">${pageMd(body.join("\n"), id, rev)}</div></details>`); 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) => `<div class="stat"><div class="k">${inl(c[0])}</div><div class="v${trend(c[1])}${c[1].length > 10 ? " long" : ""}">${inl(c[1])}</div>${c[2] ? `<div class="s${trend(c[2])}">${inl(c[2])}</div>` : ""}</div>`);
|
||
if (tiles.length) { out.push(`<div class="stats">${tiles.join("")}</div>`); continue; }
|
||
}
|
||
if (lang === "steps") {
|
||
const items = body.map((b) => b.trim().replace(/^[-*]\s*/, "").match(/^\[(x|X|✓|>|~|-| )\]\s*(.*)$/)).filter(Boolean).map((m) => {
|
||
const st = /[xX✓]/.test(m[1]) ? "done" : /[>~-]/.test(m[1]) ? "now" : "todo";
|
||
const [nm, nt] = m[2].split(/\s*\|\s*/, 2);
|
||
return `<li class="${st}"><span class="dot">${st === "done" ? "✓" : ""}</span><div class="nm">${inl(nm)}</div>${nt ? `<div class="nt">${inl(nt)}</div>` : ""}</li>`;
|
||
});
|
||
if (items.length) { out.push(`<ul class="steps">${items.join("")}</ul>`); continue; }
|
||
}
|
||
out.push(`<pre><code>${esc(body.join("\n"))}</code></pre>`); continue;
|
||
}
|
||
const h = t.match(/^(#{1,6})\s+(.*)$/);
|
||
if (h) { const n = Math.min(h[1].length + 1, 4); out.push(`<h${n}>${inl(h[2])}</h${n}>`); i++; continue; }
|
||
if (/^(-{3,}|\*{3,}|_{3,})$/.test(t)) { out.push("<hr>"); i++; continue; }
|
||
if (t.startsWith("|") && i + 1 < L.length && /^\|?\s*:?-{2,}/.test(L[i + 1].trim())) {
|
||
const head = cells(t); i += 2; const rows = [];
|
||
while (i < L.length && L[i].trim().startsWith("|")) rows.push(cells(L[i++]));
|
||
const num = numCols(head, rows), cls = (j) => num[j] ? ' class="num"' : "";
|
||
out.push(`<div class="tw"><table><thead><tr>${head.map((c, j) => `<th${cls(j)}>${inl(c)}</th>`).join("")}</tr></thead><tbody>${rows.map((r) => `<tr>${r.map((c, j) => `<td${cls(j)}>${inl(c)}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`);
|
||
continue;
|
||
}
|
||
if (t.startsWith(">")) {
|
||
const q = []; while (i < L.length && L[i].trim().startsWith(">")) q.push(L[i++].trim().replace(/^>\s?/, ""));
|
||
const c = (q[0] || "").match(/^\[!(NOTE|INFO|TIP|WARNING|CAUTION|IMPORTANT)\]\s*(.*)$/i);
|
||
if (c) {
|
||
const k = {info: "note", caution: "warning"}[c[1].toLowerCase()] || c[1].toLowerCase();
|
||
q[0] = c[2];
|
||
out.push(`<div class="call k-${k}"><div class="ct">${ic(CALL_IC[k], 15)}${CALL[k]}</div>${pageMd(q.join("\n"), id, rev)}</div>`);
|
||
} else out.push(`<blockquote>${pageMd(q.join("\n"), id, rev)}</blockquote>`);
|
||
continue;
|
||
}
|
||
if (/^([-*+•]|\d+[.)])\s+/.test(t)) {
|
||
const ordered = /^\d/.test(t); const items = [];
|
||
while (i < L.length && /^\s*([-*+•]|\d+[.)])\s+/.test(L[i])) {
|
||
const it = L[i++].trim().replace(/^([-*+•]|\d+[.)])\s+/, "");
|
||
const task = it.match(/^\[( |x|X)\]\s+(.*)$/);
|
||
items.push(task ? `<li class="task">${task[1] === " " ? "☐" : "☑"} ${inl(task[2])}</li>` : `<li>${inl(it)}</li>`);
|
||
}
|
||
out.push(ordered ? `<ol>${items.join("")}</ol>` : `<ul>${items.join("")}</ul>`); continue;
|
||
}
|
||
const para = [];
|
||
while (i < L.length && L[i].trim() && !/^(#{1,6}\s|```|>|\||([-*+•]|\d+[.)])\s)/.test(L[i].trim())) para.push(L[i++].trim());
|
||
if (!para.length) { para.push(t); i++; }
|
||
out.push(`<p>${para.map(inl).join("<br>")}</p>`);
|
||
}
|
||
return out.join("");
|
||
}
|
||
|
||
// ---------- screens ----------
|
||
// The bots' computer: its live screen shown over the app (screen.html embedded), where you
|
||
// can also take over. Its ✕ posts a close; a back gesture closes it too.
|
||
let boxOpen = false;
|
||
function openBox(control) {
|
||
const b = bot(S.open) || S.bots.find((x) => x.primary) || {};
|
||
const own = (b.computers || []).find((c) => c.kind === "own");
|
||
const at = S.relay ? "host=" + encodeURIComponent(S.host) : "lan=1";
|
||
boxOpen = true;
|
||
history.pushState({box: 1}, "");
|
||
$("boxframe").src = "screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (b.id ? "&bot=" + b.id : "") + (control ? "&control=1" : "") + "&embed=1";
|
||
$("boxwrap").style.display = "block";
|
||
}
|
||
function closeBox() {
|
||
boxOpen = false;
|
||
$("boxwrap").style.display = "none";
|
||
$("boxframe").src = "about:blank";
|
||
}
|
||
window.addEventListener("message", (e) => {
|
||
if (e.origin !== location.origin || !e.data) return;
|
||
if (e.data.anybotScreen === "close" && boxOpen) history.back();
|
||
});
|
||
// This Mac's screen: a picture at a time; taps click, long press right-clicks.
|
||
let lastUrl = null;
|
||
function startFrames() { stopFrames(); const run = S.frameRun = {}; frames(run); }
|
||
function stopFrames() { S.frameRun = null; }
|
||
async function frames(run) {
|
||
while (S.frameRun === run) {
|
||
if (document.hidden) { await nap(800); continue; }
|
||
try {
|
||
const r = await api(base() + "api/screen/mac", {raw: true});
|
||
if (S.frameRun !== run) return;
|
||
if (!r.ok) { const v = await r.json().catch(() => ({})); $("stage").innerHTML = `<div class="msg">${esc(v.error || "看不到畫面")}</div>`; $("screen-live").textContent = ""; await nap(1500); continue; }
|
||
S.size = (r.headers.get("X-Size") || "0x0").split("x").map(Number);
|
||
const url = URL.createObjectURL(await safeBlob(r));
|
||
let img = $("stage").querySelector("img");
|
||
if (!img) { $("stage").innerHTML = ""; img = document.createElement("img"); img.draggable = false; $("stage").appendChild(img); bindStage(img); }
|
||
img.src = url; if (lastUrl) URL.revokeObjectURL(lastUrl); lastUrl = url;
|
||
$("screen-live").innerHTML = `<span class="live"></span>即時`;
|
||
await nap(700);
|
||
} catch (e) { $("screen-live").textContent = ""; await nap(1500); }
|
||
}
|
||
}
|
||
function point(img, e) {
|
||
const r = img.getBoundingClientRect();
|
||
const w = S.size[0] || img.naturalWidth, h = S.size[1] || img.naturalHeight;
|
||
return {x: Math.round((e.clientX - r.left) / r.width * w), y: Math.round((e.clientY - r.top) / r.height * h), cx: e.clientX - $("stage").getBoundingClientRect().left, cy: e.clientY - $("stage").getBoundingClientRect().top};
|
||
}
|
||
function bindStage(img) {
|
||
let pressTimer = null, long = false;
|
||
img.addEventListener("pointerdown", (e) => { long = false; pressTimer = setTimeout(() => { long = true; tap(img, e, "right"); }, 550); });
|
||
img.addEventListener("pointerup", (e) => { clearTimeout(pressTimer); if (!long) tap(img, e, S.right ? "right" : "left"); });
|
||
img.addEventListener("pointercancel", () => clearTimeout(pressTimer));
|
||
img.addEventListener("dblclick", (e) => { const p = point(img, e); screenInput({kind: "click", x: p.x, y: p.y, count: 2}); });
|
||
}
|
||
function tap(img, e, button) {
|
||
const p = point(img, e);
|
||
const d = document.createElement("div"); d.className = "tapdot"; d.style.left = p.cx + "px"; d.style.top = p.cy + "px"; $("stage").appendChild(d); setTimeout(() => d.remove(), 600);
|
||
screenInput({kind: "click", x: p.x, y: p.y, button});
|
||
}
|
||
async function screenInput(body) { try { await api(base() + "api/screen/mac", {json: body}); } catch (e) { toast(e.message); } }
|
||
document.querySelectorAll("[data-key]").forEach((b) => b.onclick = () => screenInput({kind: "key", key: b.dataset.key}));
|
||
document.querySelectorAll("[data-scroll]").forEach((b) => b.onclick = () => screenInput({kind: "scroll", x: Math.round(S.size[0] / 2), y: Math.round(S.size[1] / 2), direction: b.dataset.scroll, amount: 5}));
|
||
$("k-type").onclick = () => { $("typebar").classList.toggle("on"); if ($("typebar").classList.contains("on")) $("typein").focus(); };
|
||
$("b-type").onclick = () => { const t = $("typein").value; if (!t) return; $("typein").value = ""; screenInput({kind: "type", text: t}); };
|
||
$("typein").addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.isComposing) { e.preventDefault(); $("b-type").click(); } });
|
||
$("k-right").onclick = () => { S.right = !S.right; $("k-right").textContent = "右鍵:" + (S.right ? "開" : "關"); };
|
||
|
||
// ---------- 傳送: a file or a few words to another device of the account ----------
|
||
// The brain carries it (src/drops.rs): to a computer it lands in 下載/AnyBot (words: on its
|
||
// clipboard); what was sent to the phone waits at the brain and is downloaded here.
|
||
const DROP = {to: "", targets: [], items: [], jobs: [], timer: 0};
|
||
const dropApi = (what, opts) => api(base() + "api/drop/" + what, opts);
|
||
const dropSize = (n) => n < 1024 ? n + " B" : n < 1048576 ? Math.round(n / 1024) + " KB" : n < 1073741824 ? (n / 1048576).toFixed(1) + " MB" : (n / 1073741824).toFixed(2) + " GB";
|
||
function dropAgo(ms) { const d = Math.max(0, (Date.now() - ms) / 1000); return d < 60 ? "剛剛" : d < 3600 ? Math.floor(d / 60) + " 分鐘前" : d < 86400 ? Math.floor(d / 3600) + " 小時前" : Math.floor(d / 86400) + " 天前"; }
|
||
function dropState(p) {
|
||
const pct = Math.min(100, Math.floor((p.sent || 0) * 100 / Math.max(1, p.bytes)));
|
||
switch (p.state) {
|
||
case "uploading": return ["正在交給大腦 " + pct + "%"];
|
||
case "waiting": return [/更新/.test(p.note || "") ? p.note : `等「${p.to_name}」開機上線,會自動送達`];
|
||
case "sending": return ["傳送中 " + pct + "%"];
|
||
case "ready": return [p.text ? "給手機的文字" : "可以下載(保留 7 天)"];
|
||
case "done": return [(p.to === "phone" && !p.text ? "已下載 · " : "已送達 · ") + dropAgo(p.at)];
|
||
default: return ["沒有送達:" + (p.note || "不知道原因"), true];
|
||
}
|
||
}
|
||
function dropDraw() {
|
||
const box = document.getElementById("drops"); if (!box) return false;
|
||
box.querySelector("#drop-to").innerHTML = DROP.targets.length ? DROP.targets.map((t) => `<button data-id="${esc(t.id)}" class="${t.id === DROP.to ? "on" : t.online ? "" : "off"}">${esc(t.name)}${t.online ? "" : " · 離線"}</button>`).join("") : `<span class="ds" style="color:var(--text3);font-size:var(--fs-small)">正在找帳號裡的裝置…</span>`;
|
||
box.querySelectorAll("#drop-to button").forEach((b) => b.onclick = () => { DROP.to = b.dataset.id; try { localStorage.setItem("anybot.dropto", DROP.to); } catch (_) {} dropDraw(); });
|
||
box.querySelector("#drop-jobs").innerHTML = DROP.jobs.map((j) => `<div class="drop-row"><div class="dw"><div class="dn">${esc(j.name)}</div><div class="ds">${dropSize(j.sent)} / ${dropSize(j.total)}</div><div class="drop-bar"><i style="width:${j.total ? Math.floor(j.sent * 100 / j.total) : 0}%"></i></div></div></div>`).join("");
|
||
box.querySelector("#drop-list").innerHTML = (DROP.items.length ? `<div class="grp">最近 7 天</div>` : "") + DROP.items.slice(0, 40).map((p, i) => {
|
||
const [st, bad] = dropState(p), mine = p.to === "phone";
|
||
const btns = (p.text ? `<button class="btn sm" data-copy="${i}">複製</button>` : mine && (p.state === "ready" || p.state === "done") ? `<button class="btn sm ${p.state === "ready" ? "main" : ""}" data-get="${i}">下載</button>` : "") + (bad ? `<button class="btn sm" data-retry="${i}">再試</button>` : "") + `<button class="btn sm" data-rm="${i}">${ic("x", 14)}</button>`;
|
||
return `<div class="drop-row">${ic(p.text ? "copy" : "file", 20)}<div class="dw"><div class="dn">${esc(p.name)}</div><div class="ds ${bad ? "bad" : ""}">${p.text ? "" : dropSize(p.bytes) + " · "}${esc(p.from)} → ${esc(p.to_name)} · ${esc(st)}</div></div>${btns}</div>`;
|
||
}).join("");
|
||
const at = (b, k) => DROP.items[+b.dataset[k]];
|
||
box.querySelectorAll("[data-copy]").forEach((b) => b.onclick = () => copyText(at(b, "copy").text));
|
||
box.querySelectorAll("[data-get]").forEach((b) => b.onclick = () => dropDownload(at(b, "get"), b));
|
||
box.querySelectorAll("[data-retry]").forEach((b) => b.onclick = async () => { try { await dropApi("retry", {json: {id: at(b, "retry").id}}); } catch (e) { toast(e.message); } dropRefresh(); });
|
||
box.querySelectorAll("[data-rm]").forEach((b) => b.onclick = async () => { const p = at(b, "rm"); DROP.items = DROP.items.filter((x) => x !== p); dropDraw(); try { await dropApi("remove", {json: {id: p.id}}); } catch (e) { toast(e.message); } });
|
||
return true;
|
||
}
|
||
async function dropRefresh() {
|
||
try {
|
||
const v = await dropApi("list");
|
||
DROP.items = v.items || [];
|
||
} catch (_) {}
|
||
clearTimeout(DROP.timer);
|
||
if (!dropDraw()) return;
|
||
const moving = DROP.jobs.length || DROP.items.some((p) => ["uploading", "sending", "waiting"].includes(p.state));
|
||
DROP.timer = setTimeout(dropRefresh, moving ? 1500 : 6000);
|
||
}
|
||
async function dropsSheet() {
|
||
sheet("傳送到其他裝置", [], `<div id="drops"><div class="form"><div class="drop-to" id="drop-to"></div><button class="btn main" id="drop-pick">${ic("arrow-up", 16)}選擇檔案或照片</button><textarea class="field" id="drop-text" style="min-height:56px" placeholder="或貼上一段文字、網址(電腦收到就在剪貼簿裡)"></textarea><button class="btn" id="drop-say">傳送文字</button></div><div id="drop-jobs"></div><div id="drop-list"></div><input type="file" id="drop-file" multiple hidden></div>`);
|
||
const box = document.getElementById("drops");
|
||
const need = () => { if (!DROP.to) { toast("先選要傳到哪一台"); return false; } return true; };
|
||
box.querySelector("#drop-pick").onclick = () => { if (need()) box.querySelector("#drop-file").click(); };
|
||
box.querySelector("#drop-file").onchange = (e) => { [...e.target.files].forEach(dropUpload); e.target.value = ""; };
|
||
box.querySelector("#drop-say").onclick = async () => {
|
||
const ta = box.querySelector("#drop-text"), text = ta.value.trim();
|
||
if (!text || !need()) return;
|
||
try { await dropApi("new", {json: {text, to: DROP.to}}); ta.value = ""; toast("已傳送"); } catch (e) { toast(e.message); }
|
||
dropRefresh();
|
||
};
|
||
dropDraw(); dropRefresh();
|
||
try {
|
||
const v = await dropApi("targets");
|
||
// (The phone itself isn't somewhere to send to from the phone.)
|
||
DROP.targets = (v.targets || []).filter((t) => t.id !== v.you);
|
||
let last = ""; try { last = localStorage.getItem("anybot.dropto") || ""; } catch (_) {}
|
||
if (!DROP.targets.some((t) => t.id === DROP.to)) DROP.to = (DROP.targets.find((t) => t.id === last) || DROP.targets.find((t) => t.online) || {id: ""}).id;
|
||
dropDraw();
|
||
} catch (e) { toast(e.message); }
|
||
}
|
||
// One file, handed to the brain in pieces (a piece that didn't get through is sent again from
|
||
// where the brain says it is).
|
||
async function dropUpload(f) {
|
||
const job = {name: f.name, total: f.size, sent: 0};
|
||
DROP.jobs.push(job); dropDraw();
|
||
let id = "";
|
||
try {
|
||
const v = await dropApi("new", {json: {name: f.name, bytes: f.size, to: DROP.to}});
|
||
id = v.id;
|
||
const step = v.chunk || 2097152;
|
||
let at = 0, stuck = 0;
|
||
while (at < f.size) {
|
||
let r = null;
|
||
try { r = await api(base() + `api/drop/chunk?id=${id}&at=${at}`, {method: "POST", body: f.slice(at, at + step), headers: {"Content-Type": "application/octet-stream"}, raw: true}); } catch (_) {}
|
||
if (r && r.ok) {
|
||
const have = (await r.json()).have;
|
||
stuck = have > at ? 0 : stuck + 1;
|
||
at = have;
|
||
} else if (r && r.status < 500) {
|
||
let m = ""; try { m = (await r.json()).error; } catch (_) {}
|
||
throw new Error(m || "大腦沒有收下");
|
||
} else { stuck++; await new Promise((ok) => setTimeout(ok, 2000)); }
|
||
if (stuck > 5) throw new Error("傳不過去:連線一直斷");
|
||
job.sent = at; dropDraw();
|
||
}
|
||
await dropApi("done", {json: {id}});
|
||
toast("「" + f.name + "」已交給大腦");
|
||
} catch (e) {
|
||
toast(e.message);
|
||
if (id) dropApi("remove", {json: {id}}).catch(() => {});
|
||
}
|
||
DROP.jobs.splice(DROP.jobs.indexOf(job), 1);
|
||
dropRefresh();
|
||
}
|
||
// What was sent to the phone: read from the brain in pieces, then saved (or shared, on a phone
|
||
// that can hand a file to another app).
|
||
async function dropDownload(p, btn) {
|
||
if (btn.disabled) return;
|
||
btn.disabled = true;
|
||
try {
|
||
const parts = [];
|
||
let at = 0;
|
||
while (at < p.bytes) {
|
||
const r = await api(base() + `api/drop/file?id=${p.id}&at=${at}&len=4194304`, {raw: true});
|
||
if (!r.ok) { let m = ""; try { m = (await r.json()).error; } catch (_) {} throw new Error(m || "下載不了"); }
|
||
const b = await r.arrayBuffer();
|
||
if (!b.byteLength) throw new Error("下載到一半斷了");
|
||
parts.push(b); at += b.byteLength;
|
||
btn.textContent = Math.floor(at * 100 / p.bytes) + "%";
|
||
}
|
||
const file = new File(parts, p.name, {type: "application/octet-stream"});
|
||
const u = URL.createObjectURL(file);
|
||
const a = document.createElement("a"); a.href = u; a.download = p.name; document.body.appendChild(a); a.click(); a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(u), 120000);
|
||
} catch (e) { toast(e.message); }
|
||
dropRefresh();
|
||
}
|
||
|
||
// ---------- 加一台電腦, notifications ----------
|
||
// A code for a new computer (ten minutes, once), as hands for this AnyBot.
|
||
async function pair() {
|
||
const el = sheet("加一台電腦", [], `<div class="note">Mac、任何 Linux(含沒有螢幕的)貼終端機那一行;Windows 貼 PowerShell 那一行。還沒裝會先裝好,並完成第一次配對,變成「${esc(S.hostName || "這台 AnyBot")}」的手腳。不用帳號密碼。</div><div class="pair-code" id="pair-code">······</div><code class="pair-line" id="pair-line" style="white-space:pre-wrap">正在產生…</code><div class="form"><button class="btn main" id="pair-copy">複製全部</button></div><div class="note" id="pair-left" style="text-align:center"></div>`);
|
||
try {
|
||
const v = await api("relay/pair", {json: {for: S.host}});
|
||
const line = `Windows PowerShell:\n$env:ANYBOT_NONINTERACTIVE='1'; $env:ANYBOT_MODE='hands'; $env:ANYBOT_PAIR_URL='${location.origin}'; $env:ANYBOT_PAIR_CODE='${v.code}'; irm https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.ps1 | iex\n\nMac / Linux(任何發行版,沒有螢幕也可以):\ncurl -fsSL https://code.30cm.net/daniel.w/AnyBot/raw/branch/main/install.sh | sh -s -- hands ${location.origin} ${v.code}`;
|
||
el.querySelector("#pair-code").textContent = v.code.slice(0, 3) + " " + v.code.slice(3);
|
||
el.querySelector("#pair-line").textContent = line;
|
||
el.querySelector("#pair-copy").onclick = () => copyText(line);
|
||
const end = Date.now() + (v.expires_in || 600) * 1000;
|
||
clearInterval(S.pairTimer);
|
||
S.pairTimer = setInterval(() => {
|
||
const left = Math.max(0, Math.round((end - Date.now()) / 1000));
|
||
const e2 = document.getElementById("pair-left"); if (!e2) { clearInterval(S.pairTimer); return; }
|
||
e2.textContent = left ? `還有 ${Math.floor(left / 60)} 分 ${String(left % 60).padStart(2, "0")} 秒,只能用一次` : "過期了,關掉再按一次「加一台電腦」";
|
||
if (!left) clearInterval(S.pairTimer);
|
||
}, 1000);
|
||
} catch (e) { el.querySelector("#pair-line").textContent = "沒有拿到配對碼:" + e.message; }
|
||
}
|
||
const pushOK = () => S.relay && "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
|
||
function keyBytes(b64) { const s = atob(b64.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((b64.length + 3) % 4)); return Uint8Array.from(s, (c) => c.charCodeAt(0)); }
|
||
// What this phone is told about (the account server keeps the choice with this phone's subscription).
|
||
const KINDS = [["need", "需要你", "要你允許、回答問題,或接手一個步驟"], ["done", "做完了", "你不在電腦前時,Bot 做完一件事或達成目標"], ["routine", "例行任務暫停", "例行任務連續失敗、自己停下來了"], ["file", "收到傳來的檔案", "從其他裝置傳到這裡的檔案或文字"]];
|
||
async function pushSub() { const r = await navigator.serviceWorker.getRegistration(); return r && await r.pushManager.getSubscription(); }
|
||
async function notifySheet() {
|
||
if (!pushOK()) {
|
||
const why = !S.relay ? "直接連線(同一個網路)收不到推播:用 AnyBot 帳號登入的手機才收得到。" : navigator.standalone === false ? "iPhone 要先按分享 › 加入主畫面,從主畫面打開 AnyBot 才能開通知。" : "這個瀏覽器不支援通知。";
|
||
sheet("通知", [], `<div class="note">${why}</div>`); 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: 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 = `<div class="group">` + item({icon: "bell", k: "這支手機的通知", v: blocked ? "被系統擋下了:到手機的設定 › 通知 › AnyBot 打開" : st.on ? "Bot 需要你時,會跳出通知" : "關閉中", sw: st.on && !blocked, swdata: 'data-push="1"', disabled: blocked}) + `</div>`;
|
||
if (unknown) h += `<div class="note">暫時連不上帳號伺服器:開關照這支手機上的設定;要通知哪幾種、送測試通知,等連上再試。</div>`;
|
||
else if (st.on) {
|
||
h += `<div class="grp">要通知我的事</div><div class="group">` + KINDS.map(([k, n, v]) => item({k: n, v, sw: st.kinds.includes(k), swdata: `data-kind="${k}"`})).join("") + `</div>`;
|
||
h += `<div class="form"><button class="btn" id="push-test">${ic("send", 16)}送一則測試通知</button></div>`;
|
||
}
|
||
h += `<div class="note">通知的圖示是 AnyBot 的貓;App 圖示上的數字是正在等你的 Bot。${navigator.standalone ? "聲音和橫幅樣式在 iPhone 的設定 › 通知 › AnyBot 調整。" : ""}</div>`;
|
||
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 {
|
||
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: 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 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 mine(); await api("relay/push/test", {json: {endpoint: s2.endpoint}}); toast("送出了,幾秒內會跳出來"); }
|
||
catch (e) { toast("沒有送出:" + e.message); }
|
||
};
|
||
}
|
||
// The number on the app's icon: bots waiting for you (允許、問題、需要你處理). The notifications set
|
||
// it while the app is closed; here it follows what the app shows.
|
||
function appBadge() {
|
||
if (!navigator.setAppBadge) return;
|
||
const n = new Set((S.approvals || []).map((a) => a.bot)).size;
|
||
(n ? navigator.setAppBadge(n) : navigator.clearAppBadge()).catch(() => {});
|
||
}
|
||
// ---------- installed like an app ----------
|
||
const installed = () => matchMedia("(display-mode: standalone)").matches || navigator.standalone === true;
|
||
window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); S.installPrompt = e; installHint(); });
|
||
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; }
|
||
// (.note is a flex row: the steps are one block inside it, so the share icon stays in its line.)
|
||
sheet("加入主畫面", [], `<div class="note"><div>1. 按 Safari 下方的分享按鈕 ${ic("share", 15)}\n2. 選「加入主畫面」\n3. 之後從主畫面的 AnyBot 打開:全螢幕、沒有網址列,也能開通知。</div></div>`);
|
||
}
|
||
function installHint() {
|
||
const el = $("install"); if (!el) return;
|
||
let gone = false; try { gone = localStorage.getItem("anybot.install-hint") === "no"; } catch (_) {}
|
||
const can = !installed() && !gone && S.token && (S.installPrompt || navigator.standalone === false);
|
||
el.classList.toggle("on", !!can);
|
||
if (!can) { el.innerHTML = ""; return; }
|
||
el.innerHTML = `<img src="icon-180.png" alt=""><div class="mid"><b>把 AnyBot 裝成 App</b><span>全螢幕、從主畫面打開,Bot 需要你時會跳通知。</span></div><button class="btn main" id="install-go">${S.installPrompt ? "安裝" : "怎麼做"}</button><button class="x" id="install-no" title="不用了">${ic("x", 16)}</button>`;
|
||
$("install-go").onclick = installApp;
|
||
$("install-no").onclick = () => { try { localStorage.setItem("anybot.install-hint", "no"); } catch (_) {} installHint(); };
|
||
}
|
||
// The iPhone home-screen app has no browser around it, so no swipe from the left edge to go back:
|
||
// AnyBot does that itself (Android has its own back gesture; Safari in the browser has its own).
|
||
if (navigator.standalone === true) {
|
||
let el = null, sx = 0, sy = 0, dx = 0, t0 = 0;
|
||
document.addEventListener("touchstart", (e) => {
|
||
const t = e.touches[0];
|
||
el = null;
|
||
if (e.touches.length !== 1 || t.clientX > 22 || NAV.length < 2 || boxOpen || $("sheet").classList.contains("on")) return;
|
||
el = document.querySelector(".view.on"); sx = t.clientX; sy = t.clientY; dx = 0; t0 = performance.now();
|
||
}, {passive: true});
|
||
document.addEventListener("touchmove", (e) => {
|
||
if (!el) return;
|
||
const t = e.touches[0]; dx = Math.max(0, t.clientX - sx);
|
||
if (dx < 12 && Math.abs(t.clientY - sy) > 12) { el.classList.remove("dragging"); el.style.transform = ""; el = null; return; } // scrolling, not going back
|
||
el.classList.add("dragging"); el.style.transform = `translateX(${dx}px)`;
|
||
}, {passive: true});
|
||
const end = () => {
|
||
if (!el) return;
|
||
const v = el, goBack = dx > innerWidth * 0.33 || dx / Math.max(1, performance.now() - t0) > 0.45;
|
||
el = null;
|
||
v.classList.remove("dragging"); v.style.transition = "transform .2s cubic-bezier(.22,.8,.24,1)";
|
||
v.style.transform = goBack ? `translateX(${innerWidth}px)` : "";
|
||
setTimeout(() => { v.style.transition = ""; v.style.transform = ""; if (goBack) { S.swiped = true; back(); } }, 200);
|
||
};
|
||
document.addEventListener("touchend", end);
|
||
document.addEventListener("touchcancel", end);
|
||
}
|
||
if (pushOK()) navigator.serviceWorker.register("sw.js").catch(() => {});
|
||
// A tapped notification opens that chat.
|
||
function openFromHash() {
|
||
const h = new URLSearchParams(location.hash.slice(1));
|
||
// (Only an id's shape; pickHost goes in only when it is one of this account's own.)
|
||
if (/^[A-Za-z0-9_-]{1,64}$/.test(h.get("host") || "")) { S.host = h.get("host"); localStorage.setItem("anybot.host", S.host); }
|
||
const b = +h.get("bot");
|
||
if (b) S.open = b;
|
||
// Tapping 允許/拒絕 on a notification: answer it once the token is in place.
|
||
const ans = h.get("answer");
|
||
// (With the request it was about: one that changed since is not answered by an old banner.)
|
||
// (A link with no key answers nothing: only a banner's own buttons carry one.)
|
||
if (ans && b && h.get("call") && (ans === "once" || ans === "reject")) S.answer = {bot: b, answer: ans, call: h.get("call")};
|
||
const sc = new URLSearchParams(location.search).get("sc");
|
||
if (sc) S.sc = sc;
|
||
if (location.hash || location.search) history.replaceState(null, "", location.pathname);
|
||
}
|
||
openFromHash();
|
||
if ("serviceWorker" in navigator) navigator.serviceWorker.addEventListener("message", (e) => {
|
||
const d = e.data && e.data.open; if (!d) return;
|
||
if (d.host && d.host !== S.host && S.relay) { S.host = d.host; localStorage.setItem("anybot.host", S.host); S.version = 0; }
|
||
if (d.answer && d.ask && d.bot) {
|
||
// (Not signed in yet: kept, and sent once the phone is — apply.)
|
||
if (S.token) api(base() + `api/bots/${d.bot}/answer`, {json: {answer: d.answer, call: d.ask}}).then(() => toast("已從通知回覆")).catch((e) => toast(e.message));
|
||
else S.answer = {bot: +d.bot, answer: d.answer, call: d.ask};
|
||
}
|
||
if (d.bot && S.token) go("chat", {bot: +d.bot}); else if (d.bot) S.open = +d.bot;
|
||
});
|
||
// iOS: the keyboard floats over the page instead of shrinking it; measure it and lift the composer.
|
||
if (window.visualViewport) {
|
||
const kb = () => {
|
||
// (Zoomed in with two fingers the visible part is smaller too: that isn't a keyboard.)
|
||
const k = visualViewport.scale > 1.01 ? 0 : Math.max(0, Math.round(innerHeight - visualViewport.height - visualViewport.offsetTop));
|
||
document.documentElement.style.setProperty("--kb", k + "px");
|
||
};
|
||
visualViewport.addEventListener("resize", kb);
|
||
visualViewport.addEventListener("scroll", kb);
|
||
}
|
||
document.addEventListener("visibilitychange", () => { if (!document.hidden && S.view === "screen") startFrames(); });
|
||
hello();
|
||
</script>
|
||
</body>
|
||
</html>
|