| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395 |
- const icons = {
- menu: '<path d="M4 7h16M4 12h11M4 17h16"/>',
- flower: Array.from(
- { length: 8 },
- (_, index) =>
- `<ellipse cx="12" cy="7.3" rx="2.15" ry="4.6" transform="rotate(${index * 45} 12 12)"/>`,
- ).join(''),
- 'arrow-right': '<path d="M5 12h14m-5-5 5 5-5 5"/>',
- 'arrow-up': '<path d="M12 19V5m-6 6 6-6 6 6"/>',
- back: '<path d="m14 5-7 7 7 7"/>',
- chevron: '<path d="m8 10 4 4 4-4"/>',
- right: '<path d="m9 6 6 6-6 6"/>',
- plus: '<path d="M12 5v14M5 12h14"/>',
- close: '<path d="m6 6 12 12M6 18 18 6"/>',
- chat: '<path d="M20 11.5a7.7 7.7 0 0 1-8 7.5 9 9 0 0 1-3-.5L4 20l1.5-4.5A7.2 7.2 0 0 1 4 11.5a8 8 0 0 1 16 0Z"/><path d="M8 10h8M8 14h5"/>',
- edit: '<path d="M12 4H4v16h16v-8M10 14l1-4L19 2l3 3-8 8Z"/>',
- search: '<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 4 4"/>',
- people:
- '<circle cx="9" cy="8" r="3"/><path d="M3 20v-3a6 6 0 0 1 12 0v3m1-15a3 3 0 0 1 0 6m2 3a5 5 0 0 1 3 4v2"/>',
- grid: '<rect x="4" y="4" width="6" height="6" rx="1.5"/><rect x="14" y="4" width="6" height="6" rx="1.5"/><rect x="4" y="14" width="6" height="6" rx="1.5"/><rect x="14" y="14" width="6" height="6" rx="1.5"/>',
- user: '<circle cx="12" cy="8" r="4"/><path d="M4 21v-2a8 8 0 0 1 16 0v2"/>',
- more: '<circle cx="5" cy="12" r=".9"/><circle cx="12" cy="12" r=".9"/><circle cx="19" cy="12" r=".9"/>',
- folder: '<path d="M3 7a2 2 0 0 1 2-2h5l2 3h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/>',
- archive: '<rect x="3" y="4" width="18" height="4" rx="1"/><path d="M5 8v12h14V8M10 12h4"/>',
- file: '<path d="M14 3H5v18h14V8Zm0 0v6h5M8 13h8M8 17h6"/>',
- clip: '<path d="m8 13 7-7a3 3 0 0 1 4 4L9 20a5 5 0 0 1-7-7L13 2"/>',
- check: '<path d="m5 12 4 4L19 6"/>',
- shield: '<path d="m12 3 8 3v6c0 5-8 9-8 9s-8-4-8-9V6Z"/><path d="m8 12 3 3 5-6"/>',
- copy: '<rect x="8" y="8" width="12" height="13" rx="2"/><path d="M15 8V3H3v13h5"/>',
- moon: '<path d="M20 14A8 8 0 0 1 10 4a8.5 8.5 0 1 0 10 10Z"/>',
- bell: '<path d="M5 17h14l-2-4V9a5 5 0 0 0-10 0v4Zm5 3h4"/>',
- key: '<circle cx="8" cy="9" r="5"/><path d="m12 13 8 8m-4-4 3-3"/>',
- eye: '<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/>',
- logout: '<path d="M10 4H4v16h6m5-12 5 4-5 4m-6-4h11"/>',
- link: '<path d="m9 15 6-6m-4-3 2-2a5 5 0 0 1 7 7l-2 2m-5 5-2 2a5 5 0 0 1-7-7l2-2"/>',
- wallet: '<rect x="3" y="5" width="18" height="15" rx="2"/><path d="M3 8h18m-5 4h5v5h-5Z"/>',
- trash: '<path d="M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7m4-7v7"/>',
- download: '<path d="M12 3v12m-5-5 5 5 5-5M4 16v5h16v-5"/>',
- spark: '<path d="m12 3 2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5Z"/>',
- wifi: '<path d="M3 8a15 15 0 0 1 18 0M6 12a10 10 0 0 1 12 0M9 16a5 5 0 0 1 6 0"/><circle cx="12" cy="20" r=".7"/>',
- signal: '<path d="M4 19v-3m5 3v-6m5 6V9m5 10V5" stroke-width="2.8"/>',
- battery:
- '<rect x="2" y="6" width="18" height="12" rx="3"/><path d="M22 10v4M5 9h12v6H5Z" fill="currentColor" stroke="none"/>',
- };
- const icon = (name, className = '') =>
- `<svg class="${className}" viewBox="0 0 24 24" aria-hidden="true">${icons[name] || icons.spark}</svg>`;
- const esc = (value) =>
- String(value).replace(
- /[&<>"']/g,
- (character) =>
- ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character],
- );
- const ib = (name, label, action, extra = '') =>
- `<button class="icon-button" aria-label="${esc(label)}" data-action="${action}" ${extra}>${icon(name)}</button>`;
- const agents = [
- {
- id: 'a1',
- name: '小禾',
- role: '研究与写作伙伴',
- tone: '',
- online: true,
- cpu: '12%',
- memory: '328 MB',
- balance: '128.60',
- task: '正在整理产品体验调研',
- symbol: 'flower',
- },
- {
- id: 'a2',
- name: '阿澈',
- role: '开发与技术伙伴',
- tone: 'clay',
- online: true,
- cpu: '8%',
- memory: '256 MB',
- balance: '86.20',
- task: '等待新的协作指令',
- symbol: 'grid',
- },
- {
- id: 'a3',
- name: '知夏',
- role: '设计与创意伙伴',
- tone: 'lilac',
- online: false,
- cpu: '—',
- memory: '—',
- balance: '42.00',
- task: '当前离线,连接恢复后继续协作',
- symbol: 'spark',
- },
- ];
- const conversations = [
- {
- id: 'c1',
- title: '把产品的第一印象做好',
- agentId: 'a1',
- preview: '我整理了三个可以落地的优化方向。',
- time: '刚刚',
- group: '今天',
- workspace: 'w1',
- unread: 2,
- archived: false,
- },
- {
- id: 'c2',
- title: '官网首页的灵感与参考',
- agentId: 'a3',
- preview: '留白、秩序,以及一点点恰好的温度。',
- time: '10:24',
- group: '今天',
- workspace: 'w1',
- unread: 0,
- archived: false,
- },
- {
- id: 'c3',
- title: '梳理一下这周的工作',
- agentId: 'a1',
- preview: '已按优先级整理好,随时可以继续。',
- time: '昨天',
- group: '昨天',
- workspace: null,
- unread: 0,
- archived: false,
- },
- {
- id: 'c4',
- title: '登录接口联调记录',
- agentId: 'a2',
- preview: '接口参数和错误处理已经检查完毕。',
- time: '昨天',
- group: '昨天',
- workspace: 'w2',
- unread: 1,
- archived: false,
- },
- {
- id: 'c5',
- title: '一些还没成形的小想法',
- agentId: 'a1',
- preview: '我们可以从一个最小的版本开始。',
- time: '周五',
- group: '更早',
- workspace: null,
- unread: 0,
- archived: false,
- },
- {
- id: 'c6',
- title: '上一版品牌文案',
- agentId: 'a1',
- preview: '品牌文案讨论已归档。',
- time: '11/08',
- group: '更早',
- workspace: 'w1',
- unread: 0,
- archived: true,
- },
- ];
- let workspaces = [
- { id: 'w1', name: '产品与灵感' },
- { id: 'w2', name: '研发协作' },
- ];
- const messages = new Map();
- const collaboration = new Map([
- ['c1', { kind: 'done', label: '体验优化建议已交付', elapsed: '刚刚完成' }],
- ['c2', { kind: 'attention', label: '连接中断,等待恢复', elapsed: '需要关注' }],
- ['c3', { kind: 'running', label: '正在整理本周的优先级', elapsed: '已进行 2 分钟' }],
- ['c4', { kind: 'running', label: '正在检查接口返回结果', elapsed: '已进行 45 秒' }],
- ['c5', { kind: 'idle', label: '等待新的想法', elapsed: '空闲' }],
- ]);
- const activityNames = { running: '进行中', attention: '待关注', done: '已完成', idle: '空闲' };
- const drafts = new Map();
- const draftKey = () => (state.page === 'chat' ? state.currentId : 'home');
- function saveDraft() {
- if (['home', 'chat'].includes(state.page))
- drafts.set(draftKey(), { text: state.draft, files: [...state.attachments] });
- }
- function restoreDraft() {
- const draft = drafts.get(draftKey());
- state.draft = draft?.text || '';
- state.attachments = [...(draft?.files || [])];
- }
- let preferences = { dark: false, palette: 'forest', font: 14 };
- try {
- preferences = {
- ...preferences,
- ...JSON.parse(localStorage.getItem('fmode_mobile_proposal_v1') || '{}'),
- };
- } catch {}
- const state = {
- page: 'home',
- currentId: 'c1',
- agentId: null,
- draft: '',
- attachments: [],
- filter: 'all',
- contactFilter: 'agents',
- agentFilter: 'all',
- keyword: '',
- expanded: new Set(),
- drawerExpanded: new Set(),
- pendingSend: false,
- newWorkspace: null,
- generating: false,
- disconnected: false,
- tokenVisible: false,
- drawerView: 'recent',
- activityFilter: 'all',
- activityKeyword: '',
- ...preferences,
- };
- const main = document.querySelector('#main'),
- header = document.querySelector('#app-header'),
- composerArea = document.querySelector('#composer-area'),
- tabbar = document.querySelector('#tabbar'),
- overlay = document.querySelector('#overlay-root'),
- app = document.querySelector('#app');
- let returnFocus, toastTimer, generationTimer;
- const getAgent = (agentId) => agents.find((agent) => agent.id === agentId) || agents[0];
- const getConversation = (identifier = state.currentId) =>
- conversations.find((conversation) => conversation.id === identifier);
- const avatar = (agent) => `<span class="avatar ${agent.tone}">${icon(agent.symbol)}</span>`;
- const activeConversations = () => conversations.filter((conversation) => !conversation.archived);
- const navItems = [
- ['messages', 'chat', '会话'],
- ['contacts', 'people', '通讯录'],
- ['workbench', 'grid', '工作台'],
- ['mine', 'user', '我的'],
- ];
- const emptyState = (title, description = '', symbol = 'search') =>
- `<div class="empty-state">${icon(symbol)}<strong>${title}</strong><p>${description}</p></div>`;
- const tabs = (items, active, action) =>
- `<div class="segmented" aria-label="筛选">${items.map(([value, label]) => `<button data-action="${action}" data-value="${value}" aria-pressed="${value === active}" class="${value === active ? 'active' : ''}">${label}</button>`).join('')}</div>`;
- const searchField = (placeholder, action = 'search', value = '') =>
- `<label class="search-field">${icon('search')}<input type="search" aria-label="${placeholder}" placeholder="${placeholder}" data-input="${action}" value="${esc(value)}" /></label>`;
- const navigation = () =>
- navItems
- .map(
- ([page, symbol, label]) =>
- `<button data-action="navigate" data-page="${page}" class="${state.page === page ? 'active' : ''}" ${state.page === page ? 'aria-current="page"' : ''}><span>${icon(symbol)}</span><span>${label}</span></button>`,
- )
- .join('');
- function applyPreferences() {
- const device = document.querySelector('#device');
- device.classList.toggle('dark', state.dark);
- const palettes = {
- forest: ['#386b52', '#eaf1e8', '#a4c59a', '#303f30'],
- blue: ['#496a96', '#eaf0f8', '#a5bde0', '#2e3c50'],
- purple: ['#806495', '#f0eaf5', '#c9acdf', '#403349'],
- amber: ['#9a7641', '#f4efdf', '#ddc195', '#443a27'],
- };
- const palette = palettes[state.palette] || palettes.forest;
- device.style.setProperty('--accent', palette[state.dark ? 2 : 0]);
- device.style.setProperty('--tint', palette[state.dark ? 3 : 1]);
- device.style.setProperty('--chat-font', `${state.font}px`);
- try {
- localStorage.setItem(
- 'fmode_mobile_proposal_v1',
- JSON.stringify({ dark: state.dark, palette: state.palette, font: state.font }),
- );
- } catch {}
- }
- function navigate(page, identifier) {
- const destination =
- page === 'chat'
- ? `#/chat/${identifier || state.currentId}`
- : page === 'agent'
- ? `#/agent/${identifier}`
- : `#/${page}`;
- if (location.hash === destination) readRoute();
- else location.hash = destination;
- }
- function readRoute() {
- saveDraft();
- const [page = 'home', identifier] = location.hash.replace(/^#\/?/, '').split('/');
- state.page = ['home', 'chat', 'messages', 'contacts', 'workbench', 'mine', 'agent'].includes(page)
- ? page
- : 'home';
- if (state.page === 'chat') {
- const conversation = getConversation(identifier);
- if (conversation) {
- state.currentId = identifier;
- conversation.unread = 0;
- } else state.page = 'messages';
- }
- if (state.page === 'agent') state.detailAgentId = identifier;
- state.keyword = '';
- restoreDraft();
- closeOverlay();
- render();
- main.scrollTop = 0;
- }
- function render() {
- const conversation = getConversation(),
- agent = getAgent(conversation?.agentId);
- if (state.page === 'chat')
- header.innerHTML = `${ib('menu', '打开会话侧栏', 'drawer')}<div class="header-center"><button class="header-title" data-action="edit-current-title" aria-label="编辑会话标题:${esc(conversation.title)}"><strong>${esc(conversation.title)}</strong>${icon('edit')}</button><small>${esc(agent.name)}<span class="subtitle-separator">/</span><span class="activity-text ${collaboration.get(conversation.id)?.kind || 'idle'}">${activityNames[collaboration.get(conversation.id)?.kind || 'idle']}</span></small></div>${ib('more', '会话详情', 'details')}`;
- else if (state.page === 'home')
- header.innerHTML = `${ib('menu', '打开会话侧栏', 'drawer')}<div class="header-brand">${icon('flower')}<strong>fmode</strong></div><button class="profile-button" data-action="navigate" data-page="mine" aria-label="我的">林</button>`;
- else if (state.page === 'agent')
- header.innerHTML = `${ib('back', '返回通讯录', 'navigate', 'data-page="contacts"')}<strong class="page-title">数字生命设置</strong>`;
- else
- header.innerHTML = `${ib('menu', '打开会话侧栏', 'drawer')}<strong class="page-title">${navItems.find(([page]) => page === state.page)?.[2]}</strong>${state.page === 'messages' ? ib('edit', '新建对话', 'new-chat') : '<span style="width:44px"></span>'}`;
- ({
- home: renderHome,
- chat: renderChat,
- messages: renderMessages,
- contacts: renderContacts,
- workbench: renderWorkbench,
- mine: renderMine,
- agent: renderAgent,
- })[state.page]();
- if (state.page === 'chat' && messages.get(state.currentId)?.length === 0) {
- main.innerHTML = `<section class="screen blank-chat"><div class="blank-chat-mark">${icon(agent.symbol)}</div><h1>新的想法,直接说。</h1><p>正在和 ${esc(agent.name)} 对话<br />${esc(workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || '日常对话')} · 不影响之前的会话</p></section>`;
- }
- if (state.page === 'mine')
- main
- .querySelector('.version-text')
- .insertAdjacentHTML(
- 'beforeend',
- '<br /><button class="text-button" data-action="preview-states">查看加载与反馈状态 · 原型专用</button>',
- );
- tabbar.innerHTML = ['messages', 'contacts', 'workbench', 'mine'].includes(state.page)
- ? navigation()
- : '';
- if (['home', 'chat'].includes(state.page)) renderComposer();
- else composerArea.innerHTML = '';
- document
- .querySelectorAll('[data-scene]')
- .forEach((button) => button.classList.toggle('active', button.dataset.scene === state.page));
- applyPreferences();
- }
- function renderHome() {
- main.innerHTML = `<section class="screen home-screen"><div class="home-hero"><div class="hero-art">${icon('flower')}</div><div class="overline">每一个想法,都值得被认真对待</div><h1>让想法,<br />再往前一步。</h1><p>写下想做的事,和你的数字生命一起完成。</p></div><div class="prompts"><button class="prompt" data-action="prompt" data-value="帮我梳理一下这周的工作安排">${icon('file')}梳理思路</button><button class="prompt" data-action="prompt" data-value="帮我写一份产品体验优化方案">${icon('edit')}写点什么</button><button class="prompt" data-action="prompt" data-value="帮我找几个官网设计的灵感方向">${icon('spark')}找点灵感</button></div><div class="recent-block"><div class="section-label"><span>接着上次的想法</span><button class="text-button" data-action="navigate" data-page="messages">全部会话 ${icon('arrow-right')}</button></div>${activeConversations()
- .slice(0, 2)
- .map(
- (conversation) =>
- `<button class="recent-row" data-action="open-chat" data-id="${conversation.id}">${icon('chat')}<span class="row-text"><strong>${esc(conversation.title)}</strong><small>${esc(getAgent(conversation.agentId).name)} · ${esc(workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || '日常对话')}</small></span><time>${conversation.time}</time></button>`,
- )
- .join('')}</div></section>`;
- }
- function renderComposer() {
- const agentId = state.page === 'chat' ? getConversation()?.agentId : state.agentId,
- agent = agentId ? getAgent(agentId) : null;
- composerArea.innerHTML = `<div class="composer"><div class="attachment-list">${state.attachments.map((file, index) => `<span class="attachment-chip">${icon('clip')}<span>${esc(file.name)}</span><button aria-label="移除附件 ${esc(file.name)}" data-action="remove-attachment" data-index="${index}">${icon('close')}</button></span>`).join('')}</div><textarea id="draft" rows="1" aria-label="输入消息" placeholder="说说你的想法…" ${state.generating ? 'disabled' : ''}>${esc(state.draft)}</textarea><div class="composer-tools">${ib('plus', '添加附件', 'attach')}<button class="agent-select" data-action="${state.page === 'home' ? 'pick-agent' : 'agent-info'}">${agent ? '<i class="dot ' + (agent.online ? '' : 'offline') + '"></i>' : icon('flower')}<span>${agent ? esc(agent.name) + ' · ' + agent.role : '选择数字生命'}</span>${state.page === 'home' ? icon('chevron') : ''}</button><button class="send-button" aria-label="${state.generating ? '发送中' : '发送消息'}" data-action="send" ${state.generating || (!state.draft.trim() && !state.attachments.length) ? 'disabled' : ''}>${state.generating ? '<span class="typing"><i></i><i></i><i></i></span>' : icon('arrow-up')}</button></div></div><div class="composer-footnote">${state.page === 'home' ? '和数字生命一起,把想法变成现实' : '内容由 AI 生成,请核实重要信息'} · 演示</div>`;
- if (state.page === 'chat') {
- const running = activeConversations().filter(
- (conversation) => collaboration.get(conversation.id)?.kind === 'running',
- ).length;
- const attention = activeConversations().filter(
- (conversation) => collaboration.get(conversation.id)?.kind === 'attention',
- ).length;
- composerArea.insertAdjacentHTML(
- 'afterbegin',
- `<div class="collaboration-rail"><button class="quick-current" data-action="quick-current" aria-label="在当前数字生命 ${esc(agent.name)} 中新建对话">${icon('edit')}<span>新对话</span><span class="quick-agent">· ${esc(agent.name)}</span></button><button class="activity-entry" data-action="activity" aria-label="切换协作,${running} 个进行中,${attention} 个待关注"><span class="activity-orbit ${running ? 'running' : ''}"></span><span>${running ? running + ' 个进行中' : '协作动态'}</span>${attention ? `<span class="attention-count">${attention}</span>` : ''}${icon('chevron')}</button></div>`,
- );
- }
- const textarea = document.querySelector('#draft');
- textarea.setAttribute('enterkeyhint', 'enter');
- textarea.style.height = 'auto';
- textarea.style.height = `${Math.min(textarea.scrollHeight, 116)}px`;
- }
- function conversationRow(conversation) {
- const agent = getAgent(conversation.agentId);
- return `<article class="conversation-row"><button class="conversation-open" data-action="open-chat" data-id="${conversation.id}">${avatar(agent)}<span class="conversation-body"><span class="conversation-top"><strong>${esc(conversation.title)}</strong><time>${conversation.time}</time></span><p>${esc(conversation.preview)}</p><span class="conversation-meta">${esc(agent.name)}${conversation.workspace ? ' · ' + esc(workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || '工作区') : ''}<span class="inline-activity ${collaboration.get(conversation.id)?.kind || 'idle'}">${activityNames[collaboration.get(conversation.id)?.kind || 'idle']}</span>${conversation.unread ? `<span class="unread">${conversation.unread}</span>` : ''}</span></span></button><button class="row-more" data-action="conversation-menu" data-id="${conversation.id}" aria-label="${esc(conversation.title)} 更多操作">${icon('more')}</button></article>`;
- }
- function renderMessages() {
- main.innerHTML = `<section class="screen"><p class="page-subtitle">每一次对话,都是想法向前的一步。</p>${searchField('搜索会话或数字生命', 'search', state.keyword)}${tabs(
- [
- ['all', '全部'],
- ['unread', '未读'],
- ['workspace', '工作区'],
- ],
- state.filter,
- 'message-filter',
- )}<div id="conversation-results">${conversationResults()}</div></section>`;
- }
- function conversationResults() {
- const keyword = state.keyword.trim().toLowerCase(),
- filtered = activeConversations().filter(
- (conversation) =>
- (state.filter !== 'unread' || conversation.unread > 0) &&
- `${conversation.title} ${getAgent(conversation.agentId).name}`
- .toLowerCase()
- .includes(keyword),
- );
- if (state.filter === 'workspace')
- return `<button class="text-button" data-action="create-workspace">${icon('plus')} 新建工作区</button>${workspaces
- .map((workspace) => {
- const rows = filtered.filter((conversation) => conversation.workspace === workspace.id);
- if (keyword && !rows.length && !workspace.name.includes(keyword)) return '';
- return `<section class="workspace"><header class="workspace-head"><button class="workspace-toggle" data-action="toggle-workspace" data-id="${workspace.id}" aria-expanded="${state.expanded.has(workspace.id)}" aria-controls="workspace-${workspace.id}">${icon(state.expanded.has(workspace.id) ? 'chevron' : 'right')}${icon('folder')} ${esc(workspace.name)}<small>${rows.length}</small></button>${ib('plus', '在 ' + workspace.name + ' 中新建对话', 'workspace-chat', `data-id="${workspace.id}"`)}${ib('more', workspace.name + ' 更多操作', 'workspace-menu', `data-id="${workspace.id}"`)}</header><div id="workspace-${workspace.id}" ${state.expanded.has(workspace.id) || keyword ? '' : 'hidden'}>${rows.length ? rows.map(conversationRow).join('') : emptyState('还没有对话', '在这里开始一个新的想法', 'chat')}</div></section>`;
- })
- .join('')}`;
- if (!filtered.length)
- return emptyState(
- state.filter === 'unread' ? '未读已清空,安心专注' : '没有找到相关对话',
- state.filter === 'unread' ? '新的消息会出现在这里。' : '换个关键词再试试。',
- );
- return ['今天', '昨天', '更早']
- .map((group) => {
- const rows = filtered.filter((conversation) => conversation.group === group);
- return rows.length
- ? `<div class="group-heading">${group}</div>${rows.map(conversationRow).join('')}`
- : '';
- })
- .join('');
- }
- const sampleAnswer =
- '<p>好的。第一印象不一定要做得更满,<br />而是让用户更快地感到:<strong>这里懂我。</strong></p><h2>先把这三件事做好</h2><ul><li><strong>让入口更清楚</strong><br />一个明确的主操作,比同时展示很多功能更有效。</li><li><strong>让阅读更轻松</strong><br />减少卡片边框,拉开段落间距,让内容成为主角。</li><li><strong>让操作有回应</strong><br />无论是发送、等待还是完成,都给出清晰、克制的反馈。</li></ul><blockquote>好的体验,是不用思考下一步该点哪里。</blockquote><p>我把具体建议整理成了一份文档,可以先从首页和对话页开始验证。</p>';
- function sampleMessages(conversation) {
- if (conversation.id === 'c1')
- return [
- { role: 'user', text: '我们来想想,怎么把产品的第一印象做得更好?' },
- { role: 'assistant', html: sampleAnswer, file: true },
- ];
- return [
- { role: 'user', text: conversation.title },
- {
- role: 'assistant',
- html: `<p>${esc(conversation.preview)}</p><p>这段对话保留在「${esc(workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || '日常对话')}」中,你可以接着补充想法。</p><blockquote>这是界面演示内容,不是真实的历史消息。</blockquote>`,
- },
- ];
- }
- function fileCard() {
- return `<button class="file-card" data-action="preview-file"><span class="file-badge">DOC</span><span><strong>产品初体验优化建议</strong><small>DOCX · 24 KB · 已上传云盘(演示)</small></span>${icon('right')}</button>`;
- }
- function renderChat() {
- const conversation = getConversation(),
- agent = getAgent(conversation.agentId);
- if (!messages.has(conversation.id)) messages.set(conversation.id, sampleMessages(conversation));
- const rows = messages.get(conversation.id);
- main.innerHTML = `<section class="screen chat-screen">${state.disconnected ? `<button class="connection-banner" data-action="reconnect">${icon('wifi')}连接已断开,点击重连 ${icon('right')}</button>` : ''}<div class="chat-date">今天 · 10:42</div>${rows.map((message, index) => (message.role === 'user' ? `<div class="user-message"><div class="user-bubble">${esc(message.text).replace(/\n/g, '<br />')}${message.files?.map((name) => `<span class="user-file">${icon('clip')} ${esc(name)}</span>`).join('') || ''}</div></div>` : `<article class="assistant-message"><div class="assistant-heading">${icon(agent.symbol)}<span>${esc(agent.name)}</span><time>演示回复</time></div><details class="process"><summary>${icon('check')} 已完成 ${message.file ? '3' : '2'} 个步骤 · ${message.file ? '12' : '3'} 秒 ${icon('chevron', 'chevron')}</summary><ol><li>理解需求与对话上下文</li><li>整理可执行的建议</li>${message.file ? '<li>生成文档并上传云盘</li>' : ''}</ol></details><div class="assistant-body">${message.html}</div>${message.file ? fileCard() : ''}<div class="message-actions"><button aria-label="复制回复" data-action="copy-message" data-index="${index}">${icon('copy')}</button>${message.file ? `<button aria-label="查看成果文件" data-action="details" data-tab="deliver">${icon('file')}</button>` : ''}<small>AI 生成 · 请核实</small></div></article>`)).join('')}${state.generating && state.generatingId === conversation.id ? '<div class="assistant-heading">' + icon(agent.symbol) + '正在整理你的想法</div><div class="typing" role="status" aria-label="正在生成演示回复"><i></i><i></i><i></i></div>' : ''}</section>`;
- }
- function renderContacts() {
- main.innerHTML = `<section class="screen">${tabs(
- [
- ['agents', '数字生命'],
- ['coworkers', '同事'],
- ],
- state.contactFilter,
- 'contact-filter',
- )}${searchField('搜索联系人', 'contact-search', state.keyword)}<div id="contact-results">${contactResults()}</div></section>`;
- }
- function contactResults() {
- if (state.contactFilter === 'coworkers') {
- const people = [
- { name: '林一', role: '产品设计 · 我', initial: '林' },
- { name: '陈序', role: '研发协作', initial: '陈' },
- ].filter((person) => person.name.includes(state.keyword));
- return people.length
- ? `<div class="contact-department">产品与研发 · ${people.length} 人</div>${people.map((person) => `<div class="contact-row"><button data-action="coworker" data-name="${person.name}"><span class="avatar person">${person.initial}</span><span><strong>${person.name}</strong><small>${person.role}</small></span></button>${icon('right')}</div>`).join('')}`
- : emptyState('没有找到联系人');
- }
- const filtered = agents.filter((agent) => `${agent.name} ${agent.role}`.includes(state.keyword));
- return filtered.length
- ? `<div class="section-label"><span>我的数字伙伴</span><span>${filtered.length} 位</span></div>${filtered.map((agent) => `<div class="contact-row"><button data-action="open-agent" data-id="${agent.id}">${avatar(agent)}<span><strong>${esc(agent.name)}</strong><small>${agent.role} · ${agent.online ? '在线' : '离线'}</small></span></button>${icon('right')}</div>`).join('')}`
- : emptyState('没有找到数字生命');
- }
- function renderWorkbench() {
- main.innerHTML = `<section class="screen"><p class="page-subtitle">伙伴们的工作状态,一眼就知道。</p><div class="overview"><div><strong>3</strong><small>数字生命</small></div><div><strong>2<span style="font-size:12px"> / 3</span></strong><small>在线</small></div><div><strong>1</strong><small>离线</small></div></div>${tabs(
- [
- ['all', '全部'],
- ['online', '在线'],
- ['offline', '离线'],
- ],
- state.agentFilter,
- 'agent-filter',
- )}${searchField('搜索数字生命', 'agent-search', state.keyword)}<div id="agent-results">${agentResults()}</div></section>`;
- }
- function agentResults() {
- const filtered = agents.filter(
- (agent) =>
- agent.name.includes(state.keyword) &&
- (state.agentFilter === 'all' || agent.online === (state.agentFilter === 'online')),
- );
- return filtered.length
- ? filtered
- .map(
- (agent) =>
- `<article class="agent-card"><div class="agent-card-head">${avatar(agent)}<div><h2>${esc(agent.name)}</h2><small>${agent.role}</small></div><span class="tag ${agent.online ? '' : 'offline'}">${agent.online ? '在线' : '离线'}</span></div><p class="agent-current">${agent.task}</p><div class="agent-metrics"><span>CPU <b>${agent.cpu}</b></span><span>内存 <b>${agent.memory}</b></span><span>余额 <b>¥${agent.balance}</b></span></div><div class="agent-actions"><button data-action="channels" data-id="${agent.id}">${icon('link')}通道</button><button data-action="recharge" data-id="${agent.id}">${icon('wallet')}充值</button><button data-action="agent-chat" data-id="${agent.id}">进入会话 ${icon('arrow-right')}</button></div></article>`,
- )
- .join('')
- : emptyState('没有匹配的数字生命');
- }
- function renderMine() {
- main.innerHTML = `<section class="screen"><div class="profile-card"><span class="avatar">林</span><div><h2>林一</h2><p>fmode 体验空间 · 演示账号</p></div></div><section class="settings-group"><h2>外观与阅读</h2><div class="palette-row">${[
- ['forest', '#386b52', '森林'],
- ['blue', '#496a96', '湖蓝'],
- ['purple', '#806495', '暮紫'],
- ['amber', '#9a7641', '暖砂'],
- ]
- .map(
- ([value, color, label]) =>
- `<button class="palette-option ${state.palette === value ? 'active' : ''}" style="--swatch:${color}" aria-label="${label}配色" aria-pressed="${state.palette === value}" data-action="palette" data-value="${value}"><span></span></button>`,
- )
- .join(
- '',
- )}</div><button class="settings-row" data-action="theme" role="switch" aria-checked="${state.dark}">${icon('moon')}深色模式<span class="toggle ${state.dark ? 'on' : ''}"></span></button><button class="settings-row" data-action="font">${icon('file')}对话正文字号<small>${state.font === 14 ? '标准' : state.font === 16 ? '较大' : '大号'}</small>${icon('right')}</button></section><section class="settings-group"><h2>账号与通知</h2><button class="settings-row" data-action="token">${icon('key')}访问 Token<small>仅演示占位</small>${icon('right')}</button><button class="settings-row" data-action="notifications">${icon('bell')}消息与任务通知<small>权限说明</small>${icon('right')}</button><button class="settings-row danger" data-action="logout">${icon('logout')}退出登录${icon('right')}</button></section><div class="version-text">fmode · 人机共生中枢<br />Mobile experience / 01 · 独立体验提案</div></section>`;
- }
- function renderAgent() {
- const agent = getAgent(state.detailAgentId);
- main.innerHTML = `<section class="screen"><div class="profile-card">${avatar(agent)}<div><h2>${esc(agent.name)}</h2><p>${agent.role}</p></div></div><section class="settings-group"><h2>容器设置</h2><button class="settings-row" data-action="rename-agent" data-id="${agent.id}">显示名称<small>${esc(agent.name)}</small>${icon('right')}</button><div class="settings-row">连接状态<small>${agent.online ? '在线' : '离线'}</small></div></section><p class="page-subtitle">沿用现有通讯录逻辑:数字生命详情只提供重命名。</p></section>`;
- }
- function openOverlay(html) {
- if (!overlay.childElementCount) returnFocus = document.activeElement;
- overlay.innerHTML = html;
- app.inert = true;
- requestAnimationFrame(() => {
- const target = overlay.querySelector('[autofocus]') || overlay.querySelector('button,input,select,summary');
- target?.focus({ preventScroll: true });
- });
- }
- function closeOverlay() {
- const wasOpen = overlay.childElementCount > 0;
- overlay.innerHTML = '';
- app.inert = false;
- state.pendingSend = false;
- if (wasOpen && returnFocus?.isConnected) returnFocus.focus({ preventScroll: true });
- }
- function sheet(title, content, extra = '') {
- openOverlay(
- `<div class="backdrop" data-action="close" aria-hidden="true"></div><section class="sheet" role="dialog" aria-modal="true" aria-labelledby="sheet-title"><div class="sheet-handle" aria-hidden="true"></div><header class="sheet-header"><h2 id="sheet-title">${title}</h2>${ib('close', '关闭面板', 'close')}</header>${extra}<div class="sheet-body">${content}</div></section>`,
- );
- }
- function drawerHistory(keyword = '') {
- if (state.drawerView === 'recent') {
- const recent = activeConversations().filter((conversation) =>
- `${conversation.title} ${getAgent(conversation.agentId).name} ${workspaces.find((workspace) => workspace.id === conversation.workspace)?.name || ''}`.includes(
- keyword,
- ),
- );
- return `<div class="group-heading">最近的协作<span>${recent.length} 段对话</span></div>${recent.map((conversation) => drawerConversation(conversation)).join('') || emptyState('没有找到对话', '换个关键词再试试。')}`;
- }
- if (state.drawerView === 'agents') {
- return (
- agents
- .map((agent) => {
- const rows = activeConversations().filter(
- (conversation) =>
- conversation.agentId === agent.id &&
- `${conversation.title} ${agent.name}`.includes(keyword),
- );
- if (!rows.length) return '';
- const running = rows.filter(
- (conversation) => collaboration.get(conversation.id)?.kind === 'running',
- ).length;
- return `<section class="drawer-agent-group"><div class="drawer-agent-head">${avatar(agent)}<span><strong>${esc(agent.name)}</strong><small>${agent.role}</small></span>${running ? `<span class="inline-activity running">${running} 进行中</span>` : `<small>${rows.length} 段对话</small>`}<button class="drawer-agent-new" data-action="agent-new" data-id="${agent.id}" aria-label="在 ${esc(agent.name)} 中新建对话">${icon('plus')}</button></div>${rows.map((conversation) => drawerConversation(conversation)).join('')}</section>`;
- })
- .join('') || emptyState('没有找到对话')
- );
- }
- const matches = (conversation) =>
- `${conversation.title} ${getAgent(conversation.agentId).name}`.includes(keyword),
- row = (conversation) =>
- `<button class="drawer-history ${state.page === 'chat' && state.currentId === conversation.id ? 'active' : ''}" data-action="open-chat" data-id="${conversation.id}">${icon('chat')}<span>${esc(conversation.title)}</span></button>`;
- return `${workspaces
- .map(
- (workspace) =>
- `<div class="workspace-head"><button class="workspace-toggle" data-action="drawer-workspace" data-id="${workspace.id}" aria-expanded="${state.drawerExpanded.has(workspace.id)}">${icon(state.drawerExpanded.has(workspace.id) ? 'chevron' : 'right')}${icon('folder')}${esc(workspace.name)}</button>${ib('more', workspace.name + ' 更多操作', 'workspace-menu', `data-id="${workspace.id}"`)}</div>${
- state.drawerExpanded.has(workspace.id) || keyword
- ? activeConversations()
- .filter(
- (conversation) =>
- conversation.workspace === workspace.id && matches(conversation),
- )
- .map(row)
- .join('')
- : ''
- }`,
- )
- .join(
- '',
- )}<button class="text-button" data-action="create-workspace">${icon('plus')} 新建工作区</button><div class="group-heading">日常对话</div>${
- activeConversations()
- .filter((conversation) => !conversation.workspace && matches(conversation))
- .map(row)
- .join('') || '<p class="sheet-description">暂无匹配对话</p>'
- }<button class="drawer-history" data-action="show-archived">${icon('archive')}已归档 <span style="margin-left:auto">${conversations.filter((conversation) => conversation.archived).length}</span></button>`;
- }
- function openDrawer() {
- openOverlay(
- `<div class="backdrop" data-action="close" aria-hidden="true"></div><aside class="drawer" role="dialog" aria-modal="true" aria-label="会话与导航"><div class="drawer-header"><div class="header-brand">${icon('flower')}<strong>fmode</strong></div>${ib('close', '关闭侧栏', 'close')}</div><button class="primary-button" data-action="new-chat">${icon('plus')}新建对话</button>${searchField('搜索历史对话', 'drawer-search')}<div class="drawer-scroll" id="drawer-results">${drawerHistory()}</div><nav class="drawer-nav" aria-label="侧栏导航">${navigation()}</nav><div class="drawer-bottom">林一 · 体验空间 / 演示</div></aside>`,
- );
- overlay.querySelector('.search-field').insertAdjacentHTML(
- 'afterend',
- tabs(
- [
- ['recent', '最近'],
- ['agents', '数字生命'],
- ['workspace', '工作区'],
- ],
- state.drawerView,
- 'drawer-view',
- ),
- );
- overlay
- .querySelector('.drawer-scroll')
- .insertAdjacentHTML(
- 'afterend',
- '<button class="drawer-archive" data-action="show-archived">' +
- icon('archive') +
- '已归档对话' +
- icon('right') +
- '</button>',
- );
- }
- function pickAgent(pending = false) {
- sheet(
- '和谁一起开始?',
- `<p class="sheet-description">选择数字生命,草稿和附件会一并保留。</p>${agents.map((agent) => `<button class="sheet-list-button" data-action="choose-agent" data-id="${agent.id}">${avatar(agent)}<span>${esc(agent.name)}<small>${agent.role} · ${agent.online ? '在线' : '离线'}</small></span>${state.agentId === agent.id ? icon('check', 'selected-check') : icon('right')}</button>`).join('')}<p class="sheet-description" style="margin-top:18px">保留「先选择数字生命,再建立会话」的现有流程。</p>`,
- );
- state.pendingSend = pending;
- }
- function details(tab = 'task') {
- const agent = getAgent(getConversation().agentId),
- content = {
- task: `<p class="sheet-description">当前会话中的任务,不新增全局任务入口。</p><div class="sheet-item"><span class="tag">已完成</span><strong>产品初体验优化建议</strong><p>分析首页与对话页的体验问题,整理可执行的改进方向。</p><p>3 / 3 步骤完成 · ${esc(agent.name)}</p></div>`,
- file: `${fileCard()}<p class="sheet-description">演示文件内容为静态预览,不会上传或读取云盘。</p>`,
- deliver: `<div class="sheet-item"><span class="tag">v1.0</span><strong>产品初体验优化建议</strong><p>今天 10:42 · ${esc(agent.name)} 已交付</p>${fileCard()}</div>`,
- state: `<div class="sheet-item"><strong>数字生命</strong><p>${esc(agent.name)} · ${agent.online ? '在线' : '离线'}</p></div><div class="sheet-item"><strong>会话连接</strong><p>${state.disconnected ? '连接中断,等待重连' : '已连接 · 当前没有待发送消息'}</p></div><p class="sheet-description" style="margin-top:18px">原型状态演示(不影响实际服务)</p><div class="state-chips"><button data-action="disconnect">模拟断线</button><button data-action="reconnect">恢复连接</button></div>`,
- };
- if (state.currentId !== 'c1' && tab !== 'state')
- content[tab] = emptyState(
- tab === 'task' ? '还没有任务' : tab === 'file' ? '还没有文件' : '还没有成果',
- '这段对话中的内容会显示在这里。',
- tab === 'task' ? 'check' : 'file',
- );
- sheet(
- '会话详情',
- content[tab] || content.task,
- tabs(
- [
- ['task', '任务'],
- ['file', '文件'],
- ['deliver', '成果'],
- ['state', '状态'],
- ],
- tab,
- 'detail-tab',
- ),
- );
- }
- function previewFile() {
- sheet(
- '文档预览',
- `<p class="sheet-description">产品初体验优化建议.docx · 演示内容</p><article class="preview-document"><div class="eyebrow">FMODE / EXPERIENCE NOTE</div><h1>把第一印象做好</h1><p>一份围绕移动端的体验优化建议<br />2026.11.16 / v1.0</p><h2>01 · 让入口更清楚</h2><p>保留熟悉的导航,用明确的主操作降低理解成本。</p><h2>02 · 让内容回到中心</h2><p>减少无效的视觉容器,用段落、留白与字重建立信息层级。</p><table><thead><tr><th>页面</th><th>体验方向</th></tr></thead><tbody><tr><td>新建对话</td><td>一个输入框,开始协作</td></tr><tr><td>会话详情</td><td>正文优先,过程折叠</td></tr><tr><td>会话列表</td><td>搜索、分组与清晰状态</td></tr></tbody></table><h2>03 · 每次操作都有回应</h2><p>发送、加载、离线和失败状态清晰可见,操作始终可恢复。</p></article><button class="primary-button" data-action="download-demo">${icon('download')}下载演示文稿(TXT)</button><button class="text-button" data-action="details" data-tab="file">${icon('back')}返回会话文件</button>`,
- );
- }
- function formSheet(title, label, value, submitAction, identifier = '') {
- sheet(
- title,
- `<form class="sheet-form" data-form="${submitAction}" data-id="${identifier}"><label for="form-value">${label}</label><input id="form-value" name="value" maxlength="60" value="${esc(value)}" autocomplete="off" autofocus required /><p class="form-error" role="alert"></p><button class="primary-button" type="submit">保存</button></form>`,
- );
- }
- function confirmation(title, description, action, identifier) {
- sheet(
- title,
- `<p class="sheet-description">${description}</p><div class="button-row"><button class="secondary-button" data-action="close">取消</button><button class="secondary-button danger" data-action="${action}" data-id="${identifier || ''}">确认${title.replace('?', '')}</button></div>`,
- );
- }
- function conversationMenu(identifier) {
- const conversation = getConversation(identifier);
- sheet(
- '管理这段对话',
- `<p class="sheet-description">${esc(conversation.title)}</p><button class="sheet-list-button" data-action="rename-conversation" data-id="${identifier}">${icon('edit')}重命名</button><button class="sheet-list-button" data-action="move-conversation" data-id="${identifier}">${icon('folder')}移动到工作区</button><button class="sheet-list-button" data-action="archive-conversation" data-id="${identifier}">${icon('archive')}${conversation.archived ? '取消归档' : '归档对话'}</button><button class="sheet-list-button danger" data-action="delete-conversation" data-id="${identifier}">${icon('trash')}删除对话</button>`,
- );
- }
- function drawerConversation(conversation) {
- const status = collaboration.get(conversation.id)?.kind || 'idle';
- const workspace =
- workspaces.find((item) => item.id === conversation.workspace)?.name || '日常对话';
- return `<button class="drawer-conversation ${state.page === 'chat' && state.currentId === conversation.id ? 'active' : ''}" data-action="open-chat" data-id="${conversation.id}"><span class="drawer-conversation-title">${esc(conversation.title)}<span class="mini-state ${status}" aria-label="${activityNames[status]}">${status === 'done' ? icon('check') : status === 'attention' ? '!' : ''}</span></span><small>${state.drawerView === 'agents' ? '' : esc(getAgent(conversation.agentId).name) + ' · '}${esc(workspace)}</small></button>`;
- }
- function activityResults() {
- const rows = activeConversations().filter((conversation) => {
- const status = collaboration.get(conversation.id)?.kind;
- return (
- status &&
- status !== 'idle' &&
- (state.activityFilter === 'all' || status === state.activityFilter) &&
- `${conversation.title} ${getAgent(conversation.agentId).name}`.includes(state.activityKeyword)
- );
- });
- return (
- ['running', 'attention', 'done']
- .map((kind) => {
- const group = rows.filter(
- (conversation) => collaboration.get(conversation.id)?.kind === kind,
- );
- if (!group.length) return '';
- return `<div class="activity-group-label"><span class="inline-activity ${kind}">${activityNames[kind]}</span><span>${group.length}</span></div>${group
- .map((conversation) => {
- const activity = collaboration.get(conversation.id);
- const agent = getAgent(conversation.agentId);
- const workspace =
- workspaces.find((item) => item.id === conversation.workspace)?.name || '日常对话';
- return `<button class="activity-card ${kind} ${conversation.id === state.currentId ? 'current' : ''}" data-action="activity-open" data-id="${conversation.id}"><span class="activity-card-avatar">${avatar(agent)}<span class="mini-state ${kind}">${kind === 'done' ? icon('check') : kind === 'attention' ? '!' : ''}</span></span><span class="activity-card-content"><strong>${esc(conversation.title)}</strong><small>${esc(agent.name)} · ${esc(workspace)}</small><span class="activity-detail">${esc(activity.label)}</span></span><span class="activity-card-end">${conversation.id === state.currentId ? '<em>当前</em>' : icon('right')}<small>${activity.elapsed}</small></span></button>`;
- })
- .join('')}`;
- })
- .join('') || emptyState('这里暂时没有协作动态', '切换筛选,看看其他会话。', 'check')
- );
- }
- function openActivity() {
- const count = (kind) =>
- activeConversations().filter(
- (conversation) => collaboration.get(conversation.id)?.kind === kind,
- ).length;
- sheet(
- '切换协作',
- `<p class="sheet-description">不用退出对话,也能知道每件事的进展。</p>${searchField('搜索正在协作的事', 'activity-search', state.activityKeyword)}${tabs(
- [
- ['all', '全部'],
- ['running', '进行中 ' + count('running')],
- ['attention', '待关注 ' + count('attention')],
- ['done', '已完成 ' + count('done')],
- ],
- state.activityFilter,
- 'activity-filter',
- )}<div id="activity-results">${activityResults()}</div><div class="activity-sheet-footer"><span>会话状态演示 · 不等于数字生命在线状态</span><button data-action="complete-demo">模拟完成提醒</button></div>`,
- );
- overlay.querySelector('.sheet').classList.add('activity-sheet');
- }
- function quickCurrent() {
- if (state.generating) {
- toast('演示回复完成后即可新建');
- return;
- }
- const previous = getConversation();
- saveDraft();
- const identifier = `c${Date.now()}`;
- conversations.unshift({
- id: identifier,
- title: '新对话',
- agentId: previous.agentId,
- preview: '等待你的第一个想法',
- time: '刚刚',
- group: '今天',
- workspace: previous.workspace,
- unread: 0,
- archived: false,
- });
- collaboration.set(identifier, { kind: 'idle', label: '等待新的想法', elapsed: '空闲' });
- messages.set(identifier, []);
- navigate('chat', identifier);
- toast('已在 ' + getAgent(previous.agentId).name + ' 中新建,原对话草稿已保留');
- }
- function editCurrentTitle() {
- const conversation = getConversation();
- formSheet(
- '给这段对话起个名字',
- '会话标题',
- conversation.title,
- 'rename-conversation',
- conversation.id,
- );
- const form = overlay.querySelector('form');
- form.insertAdjacentHTML(
- 'beforeend',
- `<button class="regenerate-title" type="button" data-action="regenerate-title">${icon('spark')}生成一个候选标题<span>演示</span></button><p class="title-protection">${icon('shield')}只有点保存才会更新。手动标题不会被自动覆盖。</p>`,
- );
- }
- function previewListState(mode) {
- saveDraft();
- state.page = 'messages';
- state.keyword = '';
- history.pushState(null, '', '#/messages');
- closeOverlay();
- render();
- const results = document.querySelector('#conversation-results');
- if (mode === 'loading') {
- results.innerHTML = `<div class="skeleton-list" role="status" aria-label="正在加载会话" aria-busy="true">${Array.from({ length: 5 }, () => '<div class="skeleton-row"><span></span><div><i></i><i></i></div></div>').join('')}</div>`;
- setTimeout(() => {
- if (results.isConnected) results.innerHTML = conversationResults();
- }, 1800);
- } else if (mode === 'error') {
- results.innerHTML =
- emptyState('暂时没连上,不是消息丢了', '网络恢复后可以重试,草稿仍然保留。', 'wifi') +
- '<button class="primary-button" data-action="retry-list">重新加载</button>';
- } else
- results.innerHTML =
- emptyState('还没有对话,从一个想法开始', '选择熟悉的数字生命,开始你的第一次协作。', 'chat') +
- '<button class="primary-button" data-action="new-chat">开始新对话</button>';
- }
- function completeDemo() {
- const conversation = getConversation('c4');
- if (!conversation) {
- toast('这条演示会话已删除,刷新可恢复');
- return;
- }
- const activity = collaboration.get(conversation.id);
- if (activity?.kind === 'done') {
- toast('该协作已完成,可在「已完成」中查看');
- return;
- }
- collaboration.set(conversation.id, {
- kind: 'done',
- label: '接口检查已完成,结果已整理',
- elapsed: '刚刚完成',
- });
- conversation.unread = 1;
- closeOverlay();
- render();
- document.querySelector('#completion-banner')?.remove();
- document
- .querySelector('#device')
- .insertAdjacentHTML(
- 'beforeend',
- `<div class="completion-banner" id="completion-banner" role="status"><span class="completion-mark">${icon('check')}</span><button data-action="completion-open" data-id="${conversation.id}"><strong>阿澈的接口检查完成了</strong><small>结果已整理好,点这里接着看 · 演示</small></button><button data-action="dismiss-completion" aria-label="关闭完成提醒">${icon('close')}</button></div>`,
- );
- }
- function send() {
- if (state.generating || (!state.draft.trim() && !state.attachments.length)) return;
- if (state.disconnected && state.page === 'chat') {
- toast('连接已断开,请先重连;草稿已保留');
- return;
- }
- if (state.page === 'home' && !state.agentId) {
- pickAgent(true);
- return;
- }
- if (state.page === 'home') {
- drafts.delete('home');
- const identifier = `c${Date.now()}`;
- conversations.unshift({
- id: identifier,
- title: state.draft.trim().slice(0, 18) || '附件对话',
- agentId: state.agentId,
- preview: '正在整理你的想法…',
- time: '刚刚',
- group: '今天',
- workspace: state.newWorkspace,
- unread: 0,
- archived: false,
- });
- messages.set(identifier, []);
- state.currentId = identifier;
- state.newWorkspace = null;
- state.page = 'chat';
- history.pushState(null, '', `#/chat/${identifier}`);
- }
- const conversation = getConversation(),
- rows = messages.get(conversation.id) || sampleMessages(conversation),
- question = state.draft.trim(),
- files = state.attachments.map((file) => file.name);
- rows.push({ role: 'user', text: question || '请查看我添加的附件', files });
- if (conversation.title === '新对话' && !conversation.manuallyNamed)
- conversation.title = (question || '附件对话').slice(0, 18);
- collaboration.set(conversation.id, {
- kind: 'running',
- label: '正在处理你的消息',
- elapsed: '刚刚开始',
- });
- messages.set(conversation.id, rows);
- state.draft = '';
- state.attachments = [];
- drafts.delete(conversation.id);
- state.generating = true;
- state.generatingId = conversation.id;
- render();
- main.scrollTop = main.scrollHeight;
- clearTimeout(generationTimer);
- generationTimer = setTimeout(() => {
- rows.push({
- role: 'assistant',
- html: `<p>收到,我们就从「<strong>${esc(question || '这份附件')}</strong>」开始。</p><p>我会先把目标、已有信息和下一步梳理清楚,再一起把它变成可执行的行动。</p><blockquote>这是一条本地模拟回复,仅用于体验发送、等待和阅读的完整流程${files.length ? ';附件只展示文件名,未读取或上传' : ''}。</blockquote>`,
- });
- conversation.preview = '已整理好思路,可以继续讨论。';
- collaboration.set(conversation.id, {
- kind: 'done',
- label: '演示回复已完成',
- elapsed: '刚刚完成',
- });
- state.generating = false;
- if (state.page === 'chat' && state.currentId === conversation.id) {
- render();
- main.scrollTop = main.scrollHeight;
- } else if (['home', 'messages'].includes(state.page)) render();
- }, 1100);
- }
- function toast(message) {
- const element = document.querySelector('#toast');
- element.textContent = message;
- element.classList.add('visible');
- clearTimeout(toastTimer);
- toastTimer = setTimeout(() => element.classList.remove('visible'), 2700);
- }
- async function copyText(text) {
- try {
- await navigator.clipboard.writeText(text);
- toast('已复制');
- } catch {
- toast('浏览器未开放剪贴板权限,请手动选择内容复制');
- }
- }
- function downloadDemo() {
- const content =
- '产品初体验优化建议(演示文稿)\n\n01 让入口更清楚\n保留现有导航与功能,突出主操作。\n\n02 让阅读更轻松\n减少厚重卡片,扩大段落留白。\n\n03 让操作有回应\n清晰呈现加载、断线与错误状态。\n\n本文件为独立 HTML 原型的演示文稿,并非真实云盘文件。',
- url = URL.createObjectURL(new Blob([content], { type: 'text/plain;charset=utf-8' })),
- link = document.createElement('a');
- link.href = url;
- link.download = '产品初体验优化建议-演示.txt';
- link.click();
- setTimeout(() => URL.revokeObjectURL(url), 1000);
- toast('演示文稿已下载,不是实际 DOCX 文件');
- }
- function showArchived() {
- sheet(
- '已归档对话',
- conversations
- .filter((conversation) => conversation.archived)
- .map(conversationRow)
- .join('') || emptyState('没有归档对话', '归档的对话会保留在这里。', 'archive'),
- );
- }
- function newChat(workspace = null, agentId = null) {
- if (state.generating) {
- toast('演示回复完成后即可新建对话');
- return;
- }
- state.agentId = agentId;
- state.newWorkspace = workspace;
- navigate('home');
- }
- const actions = {
- 'preview-states': () =>
- sheet(
- '加载与反馈状态',
- '<p class="sheet-description">仅切换演示视图,不改变真实数据或权限。</p><button class="sheet-list-button" data-action="list-state" data-value="loading">' +
- icon('more') +
- '加载骨架屏</button><button class="sheet-list-button" data-action="list-state" data-value="empty">' +
- icon('chat') +
- '首次使用空态</button><button class="sheet-list-button" data-action="list-state" data-value="error">' +
- icon('wifi') +
- '断网与重试</button>',
- ),
- 'list-state': (button) => previewListState(button.dataset.value),
- 'retry-list': renderMessages,
- activity: openActivity,
- 'activity-filter': (button) => {
- state.activityFilter = button.dataset.value;
- openActivity();
- },
- 'activity-open': (button) => {
- closeOverlay();
- navigate('chat', button.dataset.id);
- requestAnimationFrame(() => {
- main.scrollTop = main.scrollHeight;
- });
- },
- 'drawer-view': (button) => {
- state.drawerView = button.dataset.value;
- openDrawer();
- },
- 'quick-current': quickCurrent,
- 'agent-new': (button) => {
- newChat(null, button.dataset.id);
- toast('已选中 ' + getAgent(button.dataset.id).name + ',不用再次选择');
- },
- 'edit-current-title': editCurrentTitle,
- 'regenerate-title': () => {
- const conversation = getConversation();
- const rows = messages.get(conversation.id) || [];
- const question = [...rows].reverse().find((message) => message.role === 'user')?.text;
- overlay.querySelector('#form-value').value =
- conversation.id === 'c1'
- ? '移动端第一印象与体验优化'
- : (question || conversation.title).slice(0, 22);
- toast('候选标题已填入,保存后才会更新;未调用 AI');
- },
- 'complete-demo': completeDemo,
- 'dismiss-completion': () => document.querySelector('#completion-banner')?.remove(),
- 'completion-open': (button) => {
- document.querySelector('#completion-banner')?.remove();
- navigate('chat', button.dataset.id);
- requestAnimationFrame(() => {
- main.scrollTop = main.scrollHeight;
- });
- },
- navigate: (button) => navigate(button.dataset.page),
- drawer: openDrawer,
- close: closeOverlay,
- 'new-chat': () => newChat(),
- 'open-chat': (button) => navigate('chat', button.dataset.id),
- 'pick-agent': () => pickAgent(false),
- 'choose-agent': (button) => {
- const pending = state.pendingSend;
- state.agentId = button.dataset.id;
- closeOverlay();
- renderComposer();
- if (pending) send();
- },
- 'agent-info': () => {
- const agent = getAgent(getConversation().agentId);
- sheet(
- '当前数字生命',
- `<div class="profile-card">${avatar(agent)}<div><h2>${esc(agent.name)}</h2><p>${agent.role} · ${agent.online ? '在线' : '离线'}</p></div></div><p class="sheet-description">当前会话固定关联该数字生命。如需更换,请新建对话。</p>`,
- );
- },
- prompt: (button) => {
- state.draft = button.dataset.value;
- renderComposer();
- document.querySelector('#draft').focus();
- },
- send,
- attach: () => {
- if (state.generating) return;
- document.querySelector('#file-input').click();
- },
- 'remove-attachment': (button) => {
- state.attachments.splice(Number(button.dataset.index), 1);
- renderComposer();
- },
- 'message-filter': (button) => {
- state.filter = button.dataset.value;
- renderMessages();
- },
- 'contact-filter': (button) => {
- state.contactFilter = button.dataset.value;
- state.keyword = '';
- renderContacts();
- },
- 'agent-filter': (button) => {
- state.agentFilter = button.dataset.value;
- renderWorkbench();
- },
- 'toggle-workspace': (button) => {
- state.expanded.has(button.dataset.id)
- ? state.expanded.delete(button.dataset.id)
- : state.expanded.add(button.dataset.id);
- document.querySelector('#conversation-results').innerHTML = conversationResults();
- },
- 'drawer-workspace': (button) => {
- state.drawerExpanded.has(button.dataset.id)
- ? state.drawerExpanded.delete(button.dataset.id)
- : state.drawerExpanded.add(button.dataset.id);
- document.querySelector('#drawer-results').innerHTML = drawerHistory(
- document.querySelector('[data-input="drawer-search"]').value,
- );
- },
- 'workspace-chat': (button) => newChat(button.dataset.id),
- 'create-workspace': () =>
- formSheet('新建工作区', '工作区名称(最多 24 字)', '', 'create-workspace'),
- 'workspace-menu': (button) => {
- const workspace = workspaces.find((item) => item.id === button.dataset.id);
- sheet(
- esc(workspace.name),
- `<button class="sheet-list-button" data-action="rename-workspace" data-id="${workspace.id}">${icon('edit')}重命名工作区</button><button class="sheet-list-button danger" data-action="delete-workspace" data-id="${workspace.id}">${icon('trash')}删除工作区</button>`,
- );
- },
- 'rename-workspace': (button) =>
- formSheet(
- '重命名工作区',
- '工作区名称(最多 24 字)',
- workspaces.find((workspace) => workspace.id === button.dataset.id).name,
- 'rename-workspace',
- button.dataset.id,
- ),
- 'delete-workspace': (button) =>
- confirmation(
- '删除工作区?',
- '其中的会话会移到「日常对话」,不会被删除。此操作只影响演示数据。',
- 'confirm-delete-workspace',
- button.dataset.id,
- ),
- 'confirm-delete-workspace': (button) => {
- conversations.forEach((conversation) => {
- if (conversation.workspace === button.dataset.id) conversation.workspace = null;
- });
- workspaces = workspaces.filter((workspace) => workspace.id !== button.dataset.id);
- if (state.newWorkspace === button.dataset.id) state.newWorkspace = null;
- closeOverlay();
- render();
- toast('工作区已删除,会话已移到日常对话');
- },
- 'conversation-menu': (button) => conversationMenu(button.dataset.id),
- 'rename-conversation': (button) =>
- formSheet(
- '重命名对话',
- '对话名称',
- getConversation(button.dataset.id).title,
- 'rename-conversation',
- button.dataset.id,
- ),
- 'move-conversation': (button) =>
- sheet(
- '移动到工作区',
- `<button class="sheet-list-button" data-action="choose-workspace" data-id="${button.dataset.id}" data-workspace="">${icon('chat')}日常对话</button>${workspaces.map((workspace) => `<button class="sheet-list-button" data-action="choose-workspace" data-id="${button.dataset.id}" data-workspace="${workspace.id}">${icon('folder')}${esc(workspace.name)}</button>`).join('')}`,
- ),
- 'choose-workspace': (button) => {
- getConversation(button.dataset.id).workspace = button.dataset.workspace || null;
- closeOverlay();
- render();
- toast('已移动,仅影响本地演示数据');
- },
- 'archive-conversation': (button) => {
- const conversation = getConversation(button.dataset.id);
- conversation.archived = !conversation.archived;
- closeOverlay();
- if (state.page === 'chat' && conversation.archived) navigate('messages');
- else render();
- toast(conversation.archived ? '已归档,可在侧栏中找回' : '已取消归档');
- },
- 'delete-conversation': (button) =>
- confirmation(
- '删除对话?',
- '删除后这条演示对话将从当前预览中移除,刷新页面可恢复。',
- 'confirm-delete-conversation',
- button.dataset.id,
- ),
- 'confirm-delete-conversation': (button) => {
- const index = conversations.findIndex((conversation) => conversation.id === button.dataset.id);
- if (index >= 0) conversations.splice(index, 1);
- messages.delete(button.dataset.id);
- closeOverlay();
- if (state.page === 'chat') navigate('messages');
- else render();
- toast('演示对话已删除');
- },
- 'show-archived': showArchived,
- details: (button) => details(button?.dataset.tab || 'task'),
- 'detail-tab': (button) => details(button.dataset.value),
- 'preview-file': previewFile,
- 'download-demo': downloadDemo,
- 'copy-message': (button) => {
- const message = messages.get(state.currentId)[Number(button.dataset.index)],
- content = document.createElement('div');
- content.innerHTML = message.html;
- copyText(content.textContent);
- },
- disconnect: () => {
- state.disconnected = true;
- closeOverlay();
- renderChat();
- toast('已进入断线演示,草稿不会丢失');
- },
- reconnect: () => {
- state.disconnected = false;
- closeOverlay();
- renderChat();
- toast('演示连接已恢复');
- },
- 'open-agent': (button) => navigate('agent', button.dataset.id),
- 'rename-agent': (button) =>
- formSheet(
- '重命名数字生命',
- '显示名称',
- getAgent(button.dataset.id).name,
- 'rename-agent',
- button.dataset.id,
- ),
- 'agent-chat': (button) => {
- const conversation = activeConversations().find((item) => item.agentId === button.dataset.id);
- conversation ? navigate('chat', conversation.id) : newChat(null, button.dataset.id);
- },
- channels: (button) =>
- sheet(
- '消息通道',
- `<p class="sheet-description">${esc(getAgent(button.dataset.id).name)} · 演示连接信息</p><div class="sheet-item"><span class="tag">${getAgent(button.dataset.id).online ? '已连接' : '离线'}</span><strong>Matrix</strong><p>沿用现有消息通道,不在原型中建立真实连接。</p></div>`,
- ),
- recharge: (button) =>
- sheet(
- '数字生命充值',
- `<p class="sheet-description">${esc(getAgent(button.dataset.id).name)} · 当前演示余额 ¥${getAgent(button.dataset.id).balance}</p><div class="empty-state">${icon('shield')}<strong>这里只预览,不会产生支付</strong><p>正式迁移时继续使用现有充值页面与接口,金额、账单和支付流程均不改变。</p></div>`,
- ),
- coworker: (button) =>
- sheet(
- esc(button.dataset.name),
- `<p class="sheet-description">同事的数字生命 · 演示</p>${agents
- .slice(0, 2)
- .map(
- (agent) =>
- `<button class="sheet-list-button" data-action="open-agent" data-id="${agent.id}">${avatar(agent)}<span>${esc(agent.name)}<small>${agent.role}</small></span>${icon('right')}</button>`,
- )
- .join('')}`,
- ),
- theme: () => {
- state.dark = !state.dark;
- const scroll = main.scrollTop;
- renderMine();
- applyPreferences();
- main.scrollTop = scroll;
- },
- palette: (button) => {
- state.palette = button.dataset.value;
- const scroll = main.scrollTop;
- renderMine();
- applyPreferences();
- main.scrollTop = scroll;
- },
- font: () =>
- sheet(
- '舒适地阅读',
- `<p class="sheet-description">仅调整对话正文,沿用现有字号偏好功能。</p><div class="font-options">${[
- [14, '标准'],
- [16, '较大'],
- [18, '大号'],
- ]
- .map(
- ([value, label]) =>
- `<button data-action="choose-font" data-value="${value}" class="${state.font === value ? 'active' : ''}">${label}</button>`,
- )
- .join(
- '',
- )}</div><div class="assistant-body" id="font-preview" style="font-size:${state.font}px;line-height:1.9;padding:14px 0">让每一个想法,都有舒展的空间。<br />好的阅读体验,从恰好的字号开始。</div>`,
- ),
- 'choose-font': (button) => {
- state.font = Number(button.dataset.value);
- applyPreferences();
- renderMine();
- actions.font();
- },
- token: () =>
- sheet(
- '访问 Token',
- `<p class="sheet-description">演示占位,不读取或展示任何真实凭据。</p><div class="sheet-item"><strong>${state.tokenVisible ? 'DEMO-NOT-A-REAL-TOKEN' : '•••• •••• •••• ••••'}</strong></div><div class="button-row"><button class="secondary-button" data-action="toggle-token">${state.tokenVisible ? '隐藏' : '显示'}占位 Token</button><button class="secondary-button" data-action="copy-token" ${state.tokenVisible ? '' : 'disabled'}>复制占位内容</button></div>`,
- ),
- 'toggle-token': () => {
- state.tokenVisible = !state.tokenVisible;
- actions.token();
- },
- 'copy-token': () => copyText('DEMO-NOT-A-REAL-TOKEN'),
- notifications: () =>
- sheet(
- '消息与任务通知',
- `<p class="sheet-description">继续保留现有通知权限状态和系统设置入口。</p><div class="empty-state">${icon('bell')}<strong>原型不申请系统权限</strong><p>正式版本仍由现有通知服务检查权限,并引导到系统设置。</p></div>`,
- ),
- logout: () =>
- confirmation('退出登录?', '此处仅演示二次确认,不会退出真实项目账号。', 'confirm-logout'),
- 'confirm-logout': () => {
- closeOverlay();
- navigate('home');
- toast('退出交互演示完成;未操作真实账号');
- },
- };
- document.addEventListener('click', (event) => {
- const experience = event.target.closest('[data-experience]');
- if (experience) {
- const type = experience.dataset.experience;
- closeOverlay();
- if (state.page !== 'chat') {
- saveDraft();
- state.page = 'chat';
- state.currentId = 'c1';
- restoreDraft();
- history.pushState(null, '', '#/chat/c1');
- render();
- }
- if (type === 'activity') openActivity();
- if (type === 'title') editCurrentTitle();
- if (type === 'complete') completeDemo();
- return;
- }
- const scene = event.target.closest('[data-scene]');
- if (scene) {
- navigate(scene.dataset.scene, scene.dataset.scene === 'chat' ? 'c1' : undefined);
- return;
- }
- const button = event.target.closest('[data-action]');
- if (button && !button.disabled) actions[button.dataset.action]?.(button);
- });
- document.addEventListener('input', (event) => {
- const element = event.target;
- if (element.id === 'draft') {
- state.draft = element.value;
- element.style.height = 'auto';
- element.style.height = `${Math.min(element.scrollHeight, 116)}px`;
- document.querySelector('.send-button').disabled =
- state.generating || (!state.draft.trim() && !state.attachments.length);
- return;
- }
- const kind = element.dataset.input;
- if (!kind) return;
- if (kind === 'activity-search') {
- state.activityKeyword = element.value;
- document.querySelector('#activity-results').innerHTML = activityResults();
- return;
- }
- if (kind === 'drawer-search') {
- document.querySelector('#drawer-results').innerHTML = drawerHistory(element.value);
- return;
- }
- state.keyword = element.value;
- if (kind === 'search')
- document.querySelector('#conversation-results').innerHTML = conversationResults();
- if (kind === 'contact-search')
- document.querySelector('#contact-results').innerHTML = contactResults();
- if (kind === 'agent-search') document.querySelector('#agent-results').innerHTML = agentResults();
- });
- document.addEventListener('keydown', (event) => {
- if (event.key === 'Escape' && overlay.childElementCount) {
- event.preventDefault();
- closeOverlay();
- return;
- }
- if (event.key === 'Tab' && overlay.childElementCount) {
- const focusable = [
- ...overlay.querySelectorAll('button:not(:disabled),input,select,a[href],summary'),
- ].filter((element) => element.getClientRects().length),
- first = focusable[0],
- last = focusable.at(-1);
- if (event.shiftKey && document.activeElement === first) {
- event.preventDefault();
- last?.focus();
- } else if (!event.shiftKey && document.activeElement === last) {
- event.preventDefault();
- first?.focus();
- }
- }
- });
- let sheetDrag = null;
- overlay.addEventListener('pointerdown', (event) => {
- const handle = event.target.closest('.sheet-handle');
- if (!handle) return;
- sheetDrag = { start: event.clientY, distance: 0, element: handle.closest('.sheet'), handle };
- handle.setPointerCapture(event.pointerId);
- sheetDrag.element.style.transition = 'none';
- sheetDrag.element.style.animation = 'none';
- });
- overlay.addEventListener('pointermove', (event) => {
- if (!sheetDrag) return;
- sheetDrag.distance = Math.max(0, event.clientY - sheetDrag.start);
- sheetDrag.element.style.transform = `translateY(${sheetDrag.distance}px)`;
- });
- overlay.addEventListener('pointerup', () => {
- if (!sheetDrag) return;
- if (sheetDrag.distance > 85) closeOverlay();
- else {
- sheetDrag.element.style.transition = 'transform .2s ease';
- sheetDrag.element.style.transform = '';
- }
- sheetDrag = null;
- });
- overlay.addEventListener('pointercancel', () => {
- if (sheetDrag) sheetDrag.element.style.transform = '';
- sheetDrag = null;
- });
- document.addEventListener('submit', (event) => {
- const form = event.target.closest('[data-form]');
- if (!form) return;
- event.preventDefault();
- const value = new FormData(form).get('value').trim(),
- kind = form.dataset.form,
- identifier = form.dataset.id,
- error = form.querySelector('.form-error');
- if (!value) {
- error.textContent = '名称不能为空';
- return;
- }
- if (kind.includes('workspace')) {
- if (value.length > 24) {
- error.textContent = '工作区名称最多 24 字';
- return;
- }
- if (workspaces.some((workspace) => workspace.name === value && workspace.id !== identifier)) {
- error.textContent = '已有同名工作区,请换一个名称';
- return;
- }
- }
- if (kind === 'create-workspace') workspaces.push({ id: `w${Date.now()}`, name: value });
- if (kind === 'rename-workspace')
- workspaces.find((workspace) => workspace.id === identifier).name = value;
- if (kind === 'rename-conversation') {
- getConversation(identifier).title = value;
- getConversation(identifier).manuallyNamed = true;
- }
- if (kind === 'rename-agent') getAgent(identifier).name = value;
- closeOverlay();
- render();
- toast('已保存,仅影响本地演示数据');
- });
- document.querySelector('#file-input').addEventListener('change', (event) => {
- state.attachments.push(...Array.from(event.target.files));
- event.target.value = '';
- renderComposer();
- toast('附件仅暂存在本页,不会读取或上传');
- });
- window.addEventListener('hashchange', readRoute);
- function syncVisualViewport() {
- if (window.innerWidth <= 520 && window.visualViewport?.scale === 1) {
- document
- .querySelector('#device')
- .style.setProperty('--visual-height', `${window.visualViewport.height}px`);
- } else document.querySelector('#device').style.removeProperty('--visual-height');
- }
- window.visualViewport?.addEventListener('resize', syncVisualViewport);
- window.addEventListener('resize', syncVisualViewport);
- syncVisualViewport();
- document
- .querySelectorAll('[data-icon]')
- .forEach((element) => (element.innerHTML = icon(element.dataset.icon)));
- readRoute();
|