HEL-822: land HEL-821 A1+A2 source onto PR#4 base (db571ba)

- 13 modified / 8 added / 1 deleted per CHANGES.json (author package 76bc120b)
- docs/requirements v1.10 + prototypes/hel-799 + PROVENANCE from bundle, verified byte-identical to 63799f0
- AGENTS.md + scripts/check_requirements.py restored from governance commit 63799f0

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
白栖知
2026-10-24 06:10:53 +08:00
co-authored by multica-agent
parent db571ba204
commit 003d8c2cae
78 changed files with 11055 additions and 433 deletions
+23 -11
View File
@@ -8,9 +8,10 @@ import { CreationWizard } from '../manage/CreationWizard';
import { ManagePanel } from '../manage/ManagePanel';
import { LifePanel } from '../life/LifePanel';
import { ChatPanel } from '../chat/ChatPanel';
import { Background } from '../stage/Background';
import { FallbackPresenter } from '../stage/Presenter';
import { Presenter } from '../stage/Presenter';
import { Button, Icon, Status } from '../shared/ui';
import { snap } from '../shared/motion';
import { spaceFor, useSpace } from '../shared/space';
const demo = new URLSearchParams(location.search).get('demo') === '1';
export function App() {
const [initial] = useState(loadState), [state, setState] = useState<DemoState | null>(initial.state), [creating, setCreating] = useState(!initial.state), [area, setArea] = useState('now'), [theme, setThemeValue] = useState<Theme>(() => { try {
@@ -18,7 +19,7 @@ export function App() {
}
catch {
return 'moon';
} }), [toast, setToast] = useState(''), [controls, setControls] = useState(false), [fail, setFail] = useState(false), [offline, setOffline] = useState(false), [reconnecting, setReconnecting] = useState(false), [welcome, setWelcome] = useState(!!initial.state && Date.now() - initial.state.lastVisit > 86400000), [reach, setReach] = useState(false), [unread, setUnread] = useState(false), [log, setLog] = useState(false), [focusLife, setFocusLife] = useState(''), [returnTo, setReturnTo] = useState('now'), [presence, setPresence] = useState('在你面前'), [voice, setVoice] = useState(false), [observation, setObservation] = useState('');
} }), [toast, setToast] = useState(''), [controls, setControls] = useState(false), [fail, setFail] = useState(false), [offline, setOffline] = useState(false), [reconnecting, setReconnecting] = useState(false), [welcome, setWelcome] = useState(!!initial.state && Date.now() - initial.state.lastVisit > 86400000), [reach, setReach] = useState(false), [unread, setUnread] = useState(false), [log, setLog] = useState(false), [focusLife, setFocusLife] = useState(''), [returnTo, setReturnTo] = useState('now'), [presence, setPresence] = useState('在你面前'), [voice, setVoice] = useState(false), [observation, setObservation] = useState(''), [record, setRecord] = useState(false), [instant, setInstant] = useState(0);
const latest = useRef(state);
latest.current = state;
const toastTimer = useRef<ReturnType<typeof setTimeout> | null>(null), reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -47,10 +48,12 @@ export function App() {
setLog(false);
setVoice(false);
} }); }, []);
const space = spaceFor(area, record || log, creating);
useSpace(area, space);
useEffect(() => { document.documentElement.dataset.theme = theme; }, [theme]);
useEffect(() => { document.body.className = [creating && demo ? 'creating' : '', area === 'talk' ? 'talk' : '', !creating && ['days', 'settings'].includes(area) ? 'paned' : '', voice ? 'voice' : '', log ? 'log' : '', offline ? 'offline' : '', welcome ? 'welcoming' : '', state?.events.length === 0 ? 'data-empty' : ''].join(' '); }, [area, creating, voice, log, offline, welcome, state]);
useEffect(() => { document.documentElement.classList.toggle('reduced', !!state?.settings.reduced); }, [state?.settings.reduced]);
useEffect(() => { const visibility = () => { document.documentElement.classList.toggle('paused', document.hidden); if (document.hidden && latest.current) {
useEffect(() => { const visibility = () => { if (document.hidden && latest.current) {
try {
persistState({ ...latest.current, lastVisit: Date.now() });
}
@@ -58,6 +61,9 @@ export function App() {
} }; document.addEventListener('visibilitychange', visibility); return () => { document.removeEventListener('visibilitychange', visibility); if (toastTimer.current)
clearTimeout(toastTimer.current); if (reconnectTimer.current)
clearTimeout(reconnectTimer.current); }; }, []);
function openEventChat(id: string) { setFocusLife(id); setReturnTo('days'); setLog(true); setArea('talk'); }
const closeTalk = useCallback(() => { setArea(returnTo); setLog(false); setVoice(false); }, [returnTo]);
// Esc peels one layer at a time: demo menu, welcome, record; then you are back across the room at once.
useEffect(() => { const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || creating)
return; if (controls) {
setControls(false);
@@ -68,9 +74,12 @@ export function App() {
} if (log) {
setLog(false);
return;
} navigate('now'); }; window.addEventListener('keydown', key); return () => window.removeEventListener('keydown', key); }, [controls, welcome, log, creating, navigate]);
function openEventChat(id: string) { setFocusLife(id); setReturnTo('days'); setLog(true); setArea('talk'); }
function closeTalk() { setArea(returnTo); setLog(false); setVoice(false); }
} if (area === 'talk') {
snap();
setInstant(i => i + 1);
closeTalk();
return;
} if (area !== 'now') navigate('now'); }; window.addEventListener('keydown', key); return () => window.removeEventListener('keydown', key); }, [controls, welcome, log, creating, navigate, area, closeTalk]);
function loadSamples(long = false) { if (!state)
return; try {
save(sampleDays(state, long));
@@ -95,15 +104,18 @@ export function App() {
notify('暂时还没连上,再试一次。');
return;
} setOffline(false); notify('模拟恢复完成,已重新同步。草稿仍在,可自行发送。'); }, 700); }
const scene = { mode: area === 'talk' ? 'talk' as const : 'daily' as const, activity: view?.events.find(e => e.kind === 'now') ? '在窗边读书' : '刚搬进来,安静待着', time_band: 'evening', weather: 'demo', outfit: 'home' };
return <><Background /><header className="topbar"><div className="who"><i className="dot"/><span className="name">{state?.identity.name || 'CyberGril'}</span><span className="state">{demo ? '本机演示 · 无真实后台' : '服务尚未接通'}</span></div><div className="env"><span className="chip glass place"><Icon name="pin"/>{state?.settings.city || '杭州'}</span><span className="chip glass weather"><Icon name="cloud"/>雨后 · 模拟</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i /><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span></div></header>
// The reference still is not her new daily life (reading is no longer the default, 01a166aa): say only where she is.
const scene = { mode: area === 'talk' ? 'talk' as const : 'daily' as const, activity: view?.events.length ? '在窗边待着' : '刚搬进来,安静待着', time_band: 'evening', weather: 'demo', outfit: 'home' };
const talking = area === 'talk';
return <><Presenter scene={scene} space={space} theme={theme} instant={instant} observation={observation} onApproach={() => navigate('talk')}/>
<header className="topbar"><div className="who"><i className="dot"/><span className="name" title={state?.identity.name}>{state?.identity.name || 'CyberGril'}</span>{state && !creating && <span className="presence">{talking ? presence : scene.activity}</span>}<span className="state">{demo ? '本机演示 · 无真实后台' : '服务尚未接通'}</span></div><div className="env"><span className="chip glass place"><Icon name="pin"/>{state?.settings.city || '杭州'}</span><span className="chip glass weather"><Icon name="cloud"/>雨后 · 模拟</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i /><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span>{talking && state && <button className="end-talk" onClick={closeTalk}><Icon name="x"/><span>{returnTo === 'days' ? '结束交谈 · 回到日子' : '结束交谈'}</span></button>}</div></header>
{!demo ? <main className="entry"><div className="card glass"><h1>一扇亮着的窗。</h1><p>真实服务还在准备,当前没有连接对话、生活、记忆或备份后台。你可以先体验完整的本机演示。</p><a className="btn-primary" href="?demo=1">进入本机演示</a></div></main> : initial.error ? <main className="entry"><div className="card"><h1>资料暂时读不出来</h1><Status text={initial.error} error/><p>请先检查浏览器存储权限,或备份浏览器中的原始资料后再处理。不会自动清空或覆盖。</p></div></main> : <>
{creating && <CreationWizard fail={fail} onCreate={save} onEnter={() => setCreating(false)}/>}
{!creating && state && view && <><FallbackPresenter scene={scene} presence={presence} observation={observation} onClose={area === 'talk' ? closeTalk : () => navigate('now')} closeLabel={returnTo === 'days' ? '返回日子' : '回到此刻'}/>
{!creating && state && view && <>
{area === 'now' && !welcome && <main className="home"><div className="eyebrow">夜色里 · 一扇亮着的窗</div><h1 className="whisper">{state.events.length ? '夜深了,慢慢说。' : '刚住进来,一切都慢慢来。'}</h1><div className="meta"><span><Icon name="moon"/>心情平静 · 演示</span><span><Icon name="heart"/>{state.identity.relation} · 慢慢熟悉</span></div>{view.messages.filter(m => m.role === 'companion').length > 0 && <button className="letter glass" onClick={() => { navigate('talk'); setLog(true); }}><span className="lh"><b>她留给你的</b><span>演示留言</span></span><p>{[...view.messages].reverse().find(m => m.role === 'companion')?.text}</p></button>}<button className="away" onClick={() => navigate('days')}>你不在时 · 看她已经分享的日子 <Icon name="next"/></button><div className="cta"><Button primary small={false} onClick={() => navigate('talk')}><Icon name="chat"/>和她说话</Button><button className="btn-round glass" aria-label="进入模拟语音" onClick={() => { navigate('talk'); notify('点输入框右侧麦克风,可开启无收音的语音模拟。'); }}><Icon name="mic"/></button></div><p className="first-note">{state.identity.name}今晚刚住进来。这里还没有共同的日子。</p><p className="demo-label">本机演示 · 没有真实后台生活</p></main>}
{welcome && area === 'now' && <section className="welcome glass"><div className="eyebrow">回来坐一会儿</div><h2>你不在的这两天</h2><p className="sub">固定演示摘要 · 只展示已分享记录</p><ul>{view.events.filter(e => e.kind !== 'plan').slice(0, 3).map(e => <li key={e.id}><time>{e.time}</time><span>{e.title}</span></li>)}</ul><p className="note">演示中网页关闭不会产生新的生活,服务器后台尚未接通。</p><div className="acts"><Button primary onClick={() => { navigate('talk'); setLog(true); }}>看她留的话</Button><Button onClick={() => navigate('days')}>看她的日子</Button><button className="btn-text" onClick={() => setWelcome(false)}>先待一会儿</button></div></section>}
<LifePanel state={state} open={area === 'days'} onClose={() => navigate('now')} onChat={openEventChat}/><ManagePanel state={state} open={area === 'settings'} onClose={() => navigate('now')} onSave={save} fail={fail} theme={theme} setTheme={setTheme}/>
{area === 'talk' && <ChatPanel state={state} onChange={changeMessages} onPresence={setPresence} onVoice={setVoice} onObservation={setObservation} onClose={closeTalk} offline={offline} fail={fail} log={log} setLog={setLog} focusLife={focusLife}/>}
{talking && <ChatPanel state={state} onChange={changeMessages} onPresence={setPresence} onVoice={setVoice} onObservation={setObservation} onRecord={setRecord} offline={offline} fail={fail} log={log} setLog={setLog} focusLife={focusLife}/>}
{offline && <div className={`netbar show glass ${reconnecting ? '' : 'failed'}`} role="status"><span>{reconnecting ? '信号不太好,正在重新连上…' : '模拟断线,草稿还在'}</span><button className="btn-ghost" onClick={reconnect}>再试一次</button></div>}
{reach && <aside className="reach glass show"><div className="rh"><b>{state.identity.name}</b>主动说的 · 模拟</div><p>窗外的雨停了,想跟你说一声。</p><div className="basis">来自已分享的「听了一下午的雨」</div><div className="acts"><Button primary onClick={() => { setReach(false); setUnread(false); setReturnTo(area); setArea('talk'); setFocusLife('rain'); setLog(true); }}>回她</Button><Button onClick={() => setReach(false)}>稍后再看</Button></div></aside>}
<nav className="nav glass" aria-label="主导航">{[['now', 'moon', '此刻'], ['talk', 'chat', '交谈'], ['days', 'book', '日子'], ['settings', 'gear', '设置']].map(([id, icon, label]) => <button className={`nav-item ${id === 'talk' && unread ? 'unread' : ''}`} key={id} aria-current={area === id ? 'page' : undefined} onClick={() => navigate(id)}><Icon name={icon}/>{label}<i className="badge"/></button>)}</nav></>}
+13 -7
View File
@@ -1,17 +1,18 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { api, loadReal, type Health } from '../adapters/real';
import type { DemoState, Message, Theme } from '../domain/model';
import { Background } from '../stage/Background';
import { FallbackPresenter } from '../stage/Presenter';
import { Presenter } from '../stage/Presenter';
import { CreationWizard } from '../manage/CreationWizard';
import { LifePanel } from '../life/LifePanel';
import { leaveSettingsThen } from '../shared/navigation';
import { ManagePanel } from '../manage/ManagePanel';
import { ChatPanel } from '../chat/ChatPanel';
import { Button, Icon, Status } from '../shared/ui';
import { snap } from '../shared/motion';
import { spaceFor, useSpace } from '../shared/space';
export function RealApp() {
const [state, setState] = useState<DemoState | null>(null), [ready, setReady] = useState(false), [creating, setCreating] = useState(false), [error, setError] = useState(''), [health, setHealth] = useState<Health>(), [area, setArea] = useState('now'), [log, setLog] = useState(false), [presence, setPresence] = useState('文字已接通');
const [state, setState] = useState<DemoState | null>(null), [ready, setReady] = useState(false), [creating, setCreating] = useState(false), [error, setError] = useState(''), [health, setHealth] = useState<Health>(), [area, setArea] = useState('now'), [log, setLog] = useState(false), [presence, setPresence] = useState('文字已接通'), [record, setRecord] = useState(false), [instant, setInstant] = useState(0);
const [theme, setTheme] = useState<Theme>(() => { try { return localStorage.getItem('cg.theme') === 'fog' ? 'fog' : 'moon'; } catch { return 'moon'; } });
const latest = useRef(state); latest.current = state;
const initialize = useCallback(async () => {
@@ -20,20 +21,25 @@ export function RealApp() {
catch (e) { setError((e as Error).message || '暂时连不上真实服务。'); }
}, []);
useEffect(() => { void initialize(); }, [initialize]);
const space = spaceFor(area, record || log, creating || !ready);
useSpace(area, space);
useEffect(() => { document.documentElement.dataset.theme = theme; try { localStorage.setItem('cg.theme', theme); } catch { /* Preference stays in memory. */ } }, [theme]);
useEffect(() => { document.body.className = [creating ? 'creating' : '', area === 'talk' ? 'talk' : '', ['days', 'settings'].includes(area) ? 'paned' : '', log ? 'log' : ''].join(' '); }, [area, creating, log]);
useEffect(() => { document.documentElement.classList.toggle('reduced', !!state?.settings.reduced); }, [state?.settings.reduced]);
const changeMessages = useCallback((messages: Message[]) => { if (latest.current) { const next = { ...latest.current, messages }; latest.current = next; setState(next); } }, []);
const ignoreVoice = useCallback(() => {}, []);
const navigate = useCallback((next: string) => { leaveSettingsThen(() => { setArea(next); setLog(false); }); }, []);
useEffect(() => { const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || creating) return; if (log) setLog(false); else navigate('now'); }; window.addEventListener('keydown', key); return () => window.removeEventListener('keydown', key); }, [creating, log, navigate]);
// Esc peels one layer at a time: the record first, then you are back across the room at once.
useEffect(() => { const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || creating) return; if (log) { setLog(false); return; } if (area === 'talk') { snap(); setInstant(i => i + 1); setArea('now'); return; } if (area !== 'now') navigate('now'); }; window.addEventListener('keydown', key); return () => window.removeEventListener('keydown', key); }, [creating, log, navigate, area]);
const lastReply = state ? [...state.messages].reverse().find(m => m.role === 'companion') : undefined;
return <><Background/><header className="topbar"><div className="who"><i className="dot"/><span className="name">{state?.identity.name || 'CyberGril'}</span><span className="state">{ready ? '真实档案 · 文字对话' : '连接真实服务'}</span></div><div className="env"><span className="chip glass weather">天气尚未接通</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i/><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span></div></header>
const talking = area === 'talk' && !!state && !creating;
return <><Presenter real scene={{ mode: area === 'talk' ? 'talk' : 'daily', activity: '文字已接通', time_band: '', weather: '', outfit: '' }} space={space} theme={theme} instant={instant} observation="" onApproach={() => navigate('talk')}/>
<header className="topbar"><div className="who"><i className="dot"/><span className="name" title={state?.identity.name}>{state?.identity.name || 'CyberGril'}</span>{talking && <span className="presence">{presence}</span>}<span className="state">{ready ? '真实档案 · 文字对话' : '连接真实服务'}</span></div><div className="env"><span className="chip glass weather">天气尚未接通</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i/><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span>{talking && <button className="end-talk" onClick={() => navigate('now')}><Icon name="x"/><span>结束交谈</span></button>}</div></header>
{!ready ? <main className="entry"><div className="card glass"><h1>一扇亮着的窗。</h1><Status text={error || '正在读取服务器档案…'} error={!!error}/>{error && <><p>请检查真实服务是否可达。资料仍在服务器保存。</p><Button primary onClick={() => void initialize()}>重新连接</Button></>}</div></main> : <>
{creating && <CreationWizard real fail={false} onCreate={setState} onEnter={() => setCreating(false)}/>}
{!creating && state && <><FallbackPresenter real scene={{ mode: area === 'talk' ? 'talk' : 'daily', activity: '文字已接通 · 生活尚未接通', time_band: '', weather: '', outfit: '' }} presence={presence} observation="" onClose={() => navigate('now')} closeLabel="回到此刻"/>
{!creating && state && <>
{area === 'now' && <main className="home"><div className="eyebrow">一扇亮着的窗</div><h1 className="whisper">慢慢说,我在这里。</h1><div className="meta"><span><Icon name="heart"/>{state.identity.relation} · 慢慢熟悉</span></div><button className="away" onClick={() => navigate('days')}>日子与回忆 · 后台待接入 <Icon name="next"/></button>{lastReply && <button className="letter glass" onClick={() => { navigate('talk'); setLog(true); }}><span className="lh"><b>最近说过的话</b><span>打开完整记录</span></span><p>{lastReply.text}</p></button>}<div className="cta"><Button primary small={false} onClick={() => navigate('talk')}><Icon name="chat"/>和她说话</Button></div><p className="first-note">资料与聊天已保存在服务器。生活、长期记忆与语音尚未接通。</p>{health && !health.llm.ok && <Status error text="模型暂时不可达,档案和历史仍可查看。"/>}</main>}
{area === 'talk' && <ChatPanel real state={state} onChange={changeMessages} onPresence={setPresence} onVoice={ignoreVoice} onObservation={ignoreVoice} onClose={() => navigate('now')} offline={false} fail={false} log={log} setLog={setLog} focusLife=""/>}
{area === 'talk' && <ChatPanel real state={state} onChange={changeMessages} onPresence={setPresence} onVoice={ignoreVoice} onObservation={ignoreVoice} onRecord={setRecord} offline={false} fail={false} log={log} setLog={setLog} focusLife=""/>}
<LifePanel real state={state} open={area === 'days'} onClose={() => navigate('now')} onChat={() => { navigate('talk'); setLog(true); }}/>
<ManagePanel real state={state} open={area === 'settings'} onClose={() => navigate('now')} onSave={setState} fail={false} theme={theme} setTheme={setTheme}/>
<nav className="nav glass" aria-label="主导航">{[['now','moon','此刻'],['talk','chat','交谈'],['days','book','日子'],['settings','gear','设置']].map(([id, icon, label]) => <button key={id} className="nav-item" aria-current={area === id ? 'page' : undefined} onClick={() => navigate(id)}><Icon name={icon}/>{label}</button>)}</nav></>}
+215 -95
View File
@@ -1,124 +1,244 @@
import { SoftText } from '../shared/SoftText';
import { newId } from '../domain/id';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import type { DemoState, Message } from '../domain/model';
import { RealChatAdapter } from '../adapters/real';
import { DemoAdapter, TurnGate } from '../adapters/demo';
import { publicView } from '../domain/privacy';
import { Icon, Modal } from '../shared/ui';
export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onClose, offline, fail, log, setLog, focusLife, real = false }: {
import { snap } from '../shared/motion';
import { motionOff } from '../stage/roomScene';
import { LineStage, type PresentHow } from './lineStage';
import { anchorOf, cursorAt, dwellFor, groupTurns, pagesOf, type Anchor, type Metrics, type ShownMessage } from './reading';
const START: Anchor = { mi: 0, offset: 0 };
const metricsFor = (width: number): Metrics => { const compact = document.documentElement.classList.contains('compact'); return { width, font: compact ? 16 : innerWidth <= 720 ? 18 : 23, compact }; };
const typingTarget = (el: Element | null) => !!el && (el.matches('textarea,input,select,[contenteditable="true"]'));
export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onRecord, offline, fail, log, setLog, focusLife, real = false }: {
real?: boolean;
state: DemoState;
onChange: (messages: Message[]) => void;
onPresence: (p: string) => void;
onVoice: (v: boolean) => void;
onObservation: (s: string) => void;
onClose: () => void;
// A reading sheet (full text or the whole record) is open: she stays across the table, the room dims a little.
onRecord: (open: boolean) => void;
offline: boolean;
fail: boolean;
log: boolean;
setLog: (b: boolean) => void;
focusLife: string;
}) {
const [draft, setDraft] = useState(() => { try {
return sessionStorage.getItem(real ? 'cg.real.draft' : 'cg.draft') || '';
}
catch {
return '';
} }), [reply, setReply] = useState(''), [busy, setBusy] = useState(false), [voice, setVoice] = useState(false), [permission, setPermission] = useState<'' | 'mic' | 'vision'>(''), [notice, setNotice] = useState(''), [denied, setDenied] = useState(false), [vision, setVision] = useState(false);
const draftKey = real ? 'cg.real.draft' : 'cg.draft', readKey = real ? 'cg.real.reading' : 'cg.reading';
const [draft, setDraft] = useState(() => { try { return sessionStorage.getItem(draftKey) || ''; } catch { return ''; } }), [reply, setReply] = useState(''), [busy, setBusy] = useState(false), [voice, setVoice] = useState(false), [permission, setPermission] = useState<'' | 'mic' | 'vision'>(''), [notice, setNotice] = useState(''), [flash, setFlash] = useState(''), [denied, setDenied] = useState(false), [vision, setVision] = useState(false);
const gate = useRef(new TurnGate()), adapter = useRef(real ? new RealChatAdapter(epoch => { gate.current.epoch = epoch; }) : new DemoAdapter()), live = useRef(state.messages), logRef = useRef<HTMLDivElement>(null), voiceController = useRef<AbortController | null>(null);
const [activeTurn, setActiveTurn] = useState(''), [interrupted, setInterrupted] = useState<{ text: string; turn: string } | null>(null);
const replyLive = useRef(''), turnLive = useRef(''), dialogue = useRef<HTMLDivElement>(null), following = useRef(true);
const replyLive = useRef(''), turnLive = useRef(''), sentTurn = useRef('');
live.current = state.messages;
const view = publicView(state), lastUser = [...view.messages].reverse().find(m => m.role === 'user'), lastHer = [...view.messages].reverse().find(m => m.role === 'companion');
const name = state.identity.name;
const change = (messages: Message[]) => { live.current = messages; onChange(messages); };
// ── What the stage shows: the newest turn of the (already privacy-filtered) record, plus the live reply. ──
const view = useMemo(() => publicView(state), [state]);
// The cut-off part of a stopped reply stays with its own turn (it is shown, never stored).
const shown = useMemo<ShownMessage[]>(() => {
const list: ShownMessage[] = [...view.messages];
if (reply) list.push({ id: 'live-reply', role: 'companion', text: reply, lifeIds: [], turnId: activeTurn, live: 'generating' });
else if (interrupted) {
const at = list.map(m => m.turnId).lastIndexOf(interrupted.turn);
list.splice(at < 0 ? list.length : at + 1, 0, { id: 'cut-reply', role: 'companion', text: interrupted.text, lifeIds: [], turnId: interrupted.turn, live: 'cancelled' });
}
return list;
}, [view.messages, reply, activeTurn, interrupted]);
const turn = useMemo(() => groupTurns(shown).at(-1), [shown]);
const stageRef = useRef<HTMLDivElement>(null), lines = useRef<LineStage | null>(null), meter = useRef<HTMLElement>(null);
const [metrics, setMetrics] = useState<Metrics>(() => metricsFor(Math.min(900, innerWidth * .88)));
const pages = useMemo(() => pagesOf(turn, metrics), [turn, metrics]);
// Reading position is kept as a place in the text (not a line number), so re-chunking never loses it.
const restored = useRef<{ turn: string; anchor: Anchor; flow: boolean } | null>((() => { try { return JSON.parse(sessionStorage.getItem(readKey) || 'null'); } catch { return null; } })());
const resume = restored.current && turn && restored.current.turn === turn.key ? restored.current : null;
const [anchor, setAnchor] = useState<Anchor>(resume?.anchor || START), [flow, setFlowState] = useState(resume ? resume.flow : true), [full, setFull] = useState(false);
const head = useRef<Anchor>(resume?.anchor || START), how = useRef<PresentHow>('jump'), turnKey = useRef(turn?.key || '');
const cursor = cursorAt(pages, anchor), page = pages[cursor], atEnd = cursor >= pages.length - 1;
const headIndex = cursorAt(pages, head.current);
if (cursor > headIndex) head.current = anchor;
const held = useRef(new Set<string>()), clock = useRef({ key: '', dwell: 0, total: 0 });
const reading = useRef({ pages, cursor, flow }); reading.current = { pages, cursor, flow };
function stop() { gate.current.cancel(); if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnLive.current }); replyLive.current = ''; setBusy(false); setReply(''); onPresence('停下来了'); change(live.current.map(m => m.status === 'pending' ? { ...m, status: 'cancelled' } : m)); }
function endVoice() { stop(); voiceController.current?.abort(); setVoice(false); onVoice(false); onPresence('在你面前'); }
useEffect(() => { const current = gate.current; return () => { current.cancel(); if (real) onChange(live.current.map(m => m.status === 'pending' ? { ...m, status: 'cancelled' } : m)); voiceController.current?.abort(); onVoice(false); onObservation(''); }; }, [onVoice, onObservation, onChange, real]);
useEffect(() => { try {
sessionStorage.setItem(real ? 'cg.real.draft' : 'cg.draft', draft);
}
catch { /* Draft remains in memory. */ } }, [draft, real]);
useEffect(() => { if (offline) {
gate.current.resync();
setBusy(false);
setReply('');
setVoice(false);
onVoice(false);
voiceController.current?.abort();
} }, [offline, onVoice]);
useEffect(() => { if (!vision)
return; onObservation('模拟 · 刚刚看到,未采集影像'); const t = setTimeout(() => onObservation('模拟 · 已过期,不再当作眼前'), 30000); return () => clearTimeout(t); }, [vision, onObservation]);
useEffect(() => { if (log) {
const el = focusLife ? logRef.current?.querySelector(`[data-life="${CSS.escape(focusLife)}"]`) : null;
if (el)
el.scrollIntoView({ block: 'center' });
else if (logRef.current)
logRef.current.scrollTop = logRef.current.scrollHeight;
} }, [log, focusLife, view.messages.length]);
useLayoutEffect(() => { if (following.current && dialogue.current) dialogue.current.scrollTop = dialogue.current.scrollHeight; }, [reply, state.messages, interrupted]);
async function send(retry?: Message) { if (!retry && real) retry = [...live.current].reverse().find(m => m.role === 'user' && m.status === 'failed' && m.text === draft.trim()); const text = retry?.text || draft.trim(); if (!text || offline)
return; stop(); const turnId = retry?.turnId || newId(), signal = gate.current.begin(turnId); const msg: Message = { id: retry?.id || newId(), role: 'user', text, lifeIds: [], turnId, status: 'pending' }; change(retry ? live.current.map(m => m.id === retry.id ? msg : m) : [...live.current, msg]); if (!retry)
setDraft(''); setActiveTurn(turnId); turnLive.current = turnId; following.current = true; setBusy(true); onPresence('在想'); setNotice(''); try {
await adapter.current.send(text, turnId, gate.current.epoch, signal, event => { if (!gate.current.accepts(event))
return; if (event.t === 'chat.delta') {
replyLive.current += event.delta; setInterrupted(null); setReply(replyLive.current);
onPresence('在说话');
useEffect(() => { try { sessionStorage.setItem(draftKey, draft); } catch { /* Draft remains in memory. */ } }, [draft, draftKey]);
useEffect(() => { try { if (turn) sessionStorage.setItem(readKey, JSON.stringify({ turn: turn.key, anchor, flow })); } catch { /* Position remains in memory. */ } }, [turn, anchor, flow, readKey]);
useEffect(() => { if (offline) { gate.current.resync(); setBusy(false); setReply(''); setVoice(false); onVoice(false); voiceController.current?.abort(); } }, [offline, onVoice]);
useEffect(() => { if (!vision) return; onObservation('模拟 · 刚刚看到,未采集影像'); const t = setTimeout(() => onObservation('模拟 · 已过期,不再当作眼前'), 30000); return () => clearTimeout(t); }, [vision, onObservation]);
useEffect(() => { if (!flash) return; const t = setTimeout(() => setFlash(''), 2600); return () => clearTimeout(t); }, [flash]);
useEffect(() => { onRecord(log || full); }, [log, full, onRecord]);
useEffect(() => () => onRecord(false), [onRecord]);
useEffect(() => { if (log) { const el = focusLife ? logRef.current?.querySelector(`[data-life="${CSS.escape(focusLife)}"]`) : null; if (el) el.scrollIntoView({ block: 'center' }); else if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; } }, [log, focusLife, view.messages.length]);
// ── Stage ──
useLayoutEffect(() => { if (stageRef.current) lines.current = new LineStage(stageRef.current); return () => { lines.current = null; }; }, []);
useLayoutEffect(() => {
const el = stageRef.current; if (!el) return;
const measure = () => setMetrics(m => { const next = metricsFor(el.clientWidth || m.width); if (next.width === m.width && next.font === m.font && next.compact === m.compact) return m; how.current = 'jump'; return next; });
const ro = new ResizeObserver(measure), vv = window.visualViewport; ro.observe(el); addEventListener('resize', measure); vv?.addEventListener('resize', measure); measure();
return () => { ro.disconnect(); removeEventListener('resize', measure); vv?.removeEventListener('resize', measure); };
}, []);
// A new turn (you sent something, or she spoke on her own) starts at its first line.
useLayoutEffect(() => {
const key = turn?.key || '';
if (key === turnKey.current) return;
turnKey.current = key; how.current = 'jump'; head.current = START; setAnchor(START);
if (key && key === sentTurn.current) setFlowState(true);
}, [turn?.key]);
const signature = pages.map(p => p.key).join('|');
useLayoutEffect(() => {
lines.current?.present(pages, cursor, how.current, name, !motionOff());
how.current = 'advance';
// eslint-disable-next-line react-hooks/exhaustive-deps -- re-present only when the visible lines change
}, [signature, cursor]);
useLayoutEffect(() => {
if (!page) return;
const mine = page.message, cancelled = mine.live === 'cancelled' || (mine.status === 'cancelled' && mine.role === 'companion');
const text = cancelled && page.last ? '未完成 · 已取消' : mine.role === 'user' && mine.status === 'failed' ? '没发出去' : mine.role === 'user' && mine.status === 'cancelled' && atEnd ? '本轮已取消' : atEnd && busy && mine.role === 'companion' ? '还在说' : '';
lines.current?.mark({ text, waiting: atEnd && busy && mine.role === 'companion' });
});
useEffect(() => { lines.current?.rename(name); }, [name]);
// ── Reading clock. Holds (hover, selection, open sheets, hidden page) freeze it without changing your choice. ──
useEffect(() => {
let raf = 0, last = 0;
const tick = (now: number) => {
const dt = last ? Math.min(100, now - last) : 0; last = now;
const { pages: list, cursor: at, flow: on } = reading.current, cur = list[at], c = clock.current;
if (cur && cur.key !== c.key) { c.key = cur.key; c.dwell = 0; c.total = dwellFor(cur); }
if (cur && on && !held.current.size && !document.hidden) {
if (c.dwell < c.total) c.dwell += dt;
if (c.dwell >= c.total && at < list.length - 1) { how.current = 'advance'; setAnchor(anchorOf(list, at + 1) || START); }
}
if (meter.current) meter.current.style.transform = `scaleX(${c.total ? Math.min(1, c.dwell / c.total) : 0})`;
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, []);
const [holding, setHolding] = useState(false);
const hold = useCallback((why: string, on: boolean) => { if (on) held.current.add(why); else held.current.delete(why); setHolding(held.current.size > 0); }, []);
useEffect(() => { hold('sheet', log || full); }, [log, full, hold]);
useEffect(() => {
const selection = () => { const s = getSelection(); hold('select', !!(s && String(s).length && stageRef.current?.contains(s.anchorNode))); };
document.addEventListener('selectionchange', selection);
return () => document.removeEventListener('selectionchange', selection);
}, [hold]);
const goTo = (index: number, mode: PresentHow) => { const to = Math.max(0, Math.min(index, pages.length - 1)); if (to === cursor) return; how.current = mode; clock.current.key = ''; setAnchor(anchorOf(pages, to) || START); };
const setFlow = (on: boolean, quiet = false) => { setFlowState(on); clock.current.dwell = 0; if (!quiet) setFlash(on ? '继续自动呈现' : '已暂停 · 可以慢慢回看'); };
const back = (instant = false) => { if (flow) setFlow(false, true); goTo(cursor - 1, instant ? 'instant' : 'jump'); };
const forward = (instant = false) => goTo(cursor + 1, instant ? 'instant' : 'advance');
const toLatest = () => { how.current = 'jump'; setAnchor(head.current); setFlow(true, true); };
// Keyboard review lands at once (no slide, no replayed ink). Sheets and dialogs own their keys.
const keys = useRef({ back, forward, toggle: () => setFlow(!flow) }); keys.current = { back, forward, toggle: () => setFlow(!flow) };
useEffect(() => {
const key = (e: KeyboardEvent) => {
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || typingTarget(document.activeElement) || document.querySelector('.modal.open') || document.documentElement.dataset.mode !== 'talk') return;
if (e.key === 'ArrowLeft') { snap(); keys.current.back(true); }
else if (e.key === 'ArrowRight') { snap(); keys.current.forward(true); }
else if (e.key === ' ' && (document.activeElement === document.body || !document.activeElement)) { e.preventDefault(); keys.current.toggle(); }
};
addEventListener('keydown', key);
return () => removeEventListener('keydown', key);
}, []);
// Esc closes the full-text sheet first (one layer at a time) and returns focus to the button that opened it.
const fullButton = useRef<HTMLButtonElement>(null), historyButton = useRef<HTMLButtonElement>(null), fullClose = useRef<HTMLButtonElement>(null), logClose = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (!full) return;
fullClose.current?.focus({ preventScroll: true });
const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || document.querySelector('.modal.open')) return; e.stopImmediatePropagation(); e.preventDefault(); setFull(false); };
document.addEventListener('keydown', key, true);
return () => { document.removeEventListener('keydown', key, true); const back = fullButton.current; if (back && !back.closest('[inert]')) back.focus({ preventScroll: true }); };
}, [full]);
const logWasOpen = useRef(log);
useEffect(() => {
if (log) logClose.current?.focus({ preventScroll: true });
else if (logWasOpen.current && document.activeElement && (document.activeElement === document.body || document.activeElement.closest('.record'))) historyButton.current?.focus({ preventScroll: true });
logWasOpen.current = log;
}, [log]);
async function send(retry?: Message) {
if (!retry && real) retry = [...live.current].reverse().find(m => m.role === 'user' && m.status === 'failed' && m.text === draft.trim());
const text = retry?.text || draft.trim(); if (!text || offline) return;
stop();
const turnId = retry?.turnId || newId(), signal = gate.current.begin(turnId);
const msg: Message = { id: retry?.id || newId(), role: 'user', text, lifeIds: [], turnId, status: 'pending' };
sentTurn.current = turnId;
change(retry ? live.current.map(m => m.id === retry.id ? msg : m) : [...live.current, msg]);
if (!retry) setDraft('');
setActiveTurn(turnId); turnLive.current = turnId; setBusy(true); onPresence('在想'); setNotice('');
if (!flow) setFlash('新的一轮会自动呈现,随时可以暂停');
try {
await adapter.current.send(text, turnId, gate.current.epoch, signal, event => {
if (!gate.current.accepts(event)) return;
if (event.t === 'chat.delta') { replyLive.current += event.delta; setInterrupted(null); setReply(replyLive.current); onPresence('在说话'); }
else if (event.t === 'chat.final') {
change([...live.current.map(m => m.id === msg.id ? { ...m, status: 'sent' as const } : m), { id: newId(), role: 'companion', text: event.utterance.text, lifeIds: [], turnId }]);
replyLive.current = ''; setInterrupted(null); setReply('');
if (real) setDraft(current => current === text ? '' : current);
setBusy(false);
onPresence(voice ? '在听你说(模拟)' : '在你面前');
}
}, fail);
}
else if (event.t === 'chat.final') {
change([...live.current.map(m => m.id === msg.id ? { ...m, status: 'sent' as const } : m), { id: newId(), role: 'companion', text: event.utterance.text, lifeIds: [], turnId }]);
replyLive.current = ''; setInterrupted(null); setReply('');
if (real) setDraft(current => current === text ? '' : current);
catch (e) {
if (signal.aborted) return;
change(live.current.map(m => m.id === msg.id ? { ...m, status: 'failed' } : m));
setBusy(false);
onPresence(voice ? '在听你说(模拟)' : '在你面前');
} }, fail);
}
catch (e) {
if (signal.aborted)
return;
change(live.current.map(m => m.id === msg.id ? { ...m, status: 'failed' } : m));
setBusy(false);
if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnId }); replyLive.current = ''; setReply('');
setDraft(text);
setNotice(real && (e instanceof TypeError || e instanceof SyntaxError) ? '连接中断了,你写的话还在,可以重试。' : (e as Error).message);
onPresence('在你面前');
} }
const setVoiceMode = () => { if (real) { setNotice('语音尚未接通,文字仍可使用。'); return; } if (voice) {
endVoice();
return;
} setPermission('mic'); };
const herText = reply || interrupted?.text || lastHer?.text || '我在。你想说什么?';
const herTurn = reply ? activeTurn : interrupted ? interrupted.turn : lastHer?.turnId || lastHer?.id || 'greeting';
return <><div className="chat-layout"><div className="talk-scene-space" aria-hidden="true"/><div className="dialog"><div className="dialog-scroll" ref={dialogue} tabIndex={0} aria-label="当前对话,可滚动阅读全文" onScroll={() => { const el = dialogue.current; if (el) following.current = el.scrollHeight - el.clientHeight - el.scrollTop < 40; }}>
{lastUser && <div className="you"><div className="speaker">你</div><SoftText identity={lastUser.turnId || lastUser.id} text={lastUser.text}/>{lastUser.status === 'failed' && <div className="failed">没发出去 <button className="retry" onClick={() => void send(lastUser)}>重试</button></div>}{lastUser.status === 'cancelled' && <small>本轮已取消</small>}</div>}
<div className={`her ${interrupted ? 'cut' : ''}`}><div className="speaker">{state.identity.name}</div><SoftText identity={herTurn} text={herText}/>{reply && <span className="caret"/>}{interrupted && <small className="partial-note">这段未完成,未存入聊天记录</small>}</div>
</div><div className="hint"><span role="status">{state.identity.name} · {notice || (busy ? reply ? '正在回应…' : `${state.identity.name}在想…` : real ? '文字已接通 · 完整内容可滚动阅读' : '演示回复 · 未连接真实模型')}</span>{busy && <button className="btn-text" onClick={stop}>取消本轮回复</button>}</div></div>
{voice && <div className="voicebar glass"><span className="live"><i /></span><span className="vstate">{busy ? '她在想(模拟)' : '在听你说(模拟,无收音)'}</span><button className="btn-ghost" onClick={() => { stop(); setNotice(fail?'刚才没听清,你再说一遍?(模拟识别失败)':'她停下来了,在等你。'); }}>打断她</button><button className="end" onClick={endVoice}>结束语音</button></div>}
<div className="composer glass"><button className={`btn-round cam ${vision ? 'on' : ''}`} aria-label="视觉观察" onClick={() => { if (real) { setNotice('视觉尚未接通,不采集影像。'); return; } if (vision) {
setVision(false);
onObservation('窗户关上了');
}
else
setPermission('vision'); }}><Icon name="eye"/></button><textarea aria-label="想和她说的话" rows={1} maxLength={4000} value={draft} placeholder="想和她说点什么…" onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) {
e.preventDefault();
void send();
} }}/><button className="btn-round send" disabled={!draft.trim() || offline} aria-label="发送" onClick={() => void send()}><Icon name="up"/></button><button className={`btn-round log-btn ${log ? 'on' : ''}`} aria-label="完整记录" onClick={() => setLog(!log)}><Icon name="chat"/></button><button className={`mic ${denied ? 'denied' : ''}`} aria-label={real ? '语音尚未接通' : voice ? '停止语音' : '开始模拟语音'} disabled={offline} onClick={setVoiceMode}><Icon name={voice ? 'stop' : 'mic'}/></button></div>
</div><aside className="log-panel glass read" hidden={!log}><header><h2>你们说过的话</h2><button className="btn-round sm" aria-label="关闭记录" onClick={() => setLog(false)}><Icon name="x"/></button></header><div className="scroll" ref={logRef}><div className="day">{real ? '服务器聊天记录' : '本机演示记录'}</div>{view.messages.map(m => <div key={m.id} data-life={m.lifeIds[0]} className={`msg ${m.role === 'user' ? 'me' : ''} ${m.status === 'failed' ? 'fail' : ''} ${focusLife && m.lifeIds.includes(focusLife) ? 'hl' : ''}`}><div className="who-l">{m.role === 'user' ? '你' : state.identity.name}{m.proactive && <span className="tagm proactive">她主动说的</span>}</div><p>{m.text}</p>{m.status === 'failed' && <button className="btn-text" onClick={() => void send(m)}>没发出去 · 重试</button>}{m.status === 'cancelled' && <small>已取消</small>}</div>)}</div></aside>
{permission && <Modal title={permission === 'mic' ? '开启模拟语音?' : '打开模拟视觉窗?'} onClose={() => { setPermission(''); setDenied(true); setNotice('没有开启。真实服务尚未接通,文字仍可使用。'); }} confirm="开始模拟" onConfirm={() => { if (permission === 'mic') {
setDenied(false);
setVoice(true);
onVoice(true);
voiceController.current = new AbortController();
onPresence('在听你说(模拟)');
setNotice('模拟语音没有收音,可继续用文字输入。');
}
else {
if (fail) {
onObservation('模拟 · 看不清,视觉服务未接通');
setNotice('模拟观察失败,文字仍可使用。');
if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnId });
replyLive.current = ''; setReply('');
setDraft(text);
setNotice(real && (e instanceof TypeError || e instanceof SyntaxError) ? '连接中断了,你写的话还在,可以重试。' : (e as Error).message);
onPresence('在你面前');
}
else
setVision(true);
} setPermission(''); }}>本次仅模拟界面状态,不申请麦克风或摄像头权限,不采集声音或影像,也不向外接服务发送请求。</Modal>}
<button hidden className="sr" onClick={onClose}>退出交流</button></>;
}
const setVoiceMode = () => { if (real) { setNotice('语音尚未接通,文字仍可使用。'); return; } if (voice) { endVoice(); return; } setPermission('mic'); };
const lastUser = [...view.messages].reverse().find(m => m.role === 'user');
const status = notice || flash || (busy ? (reply ? `${name}正在回应…` : `${name}在想…`) : !pages.length ? '你们还没有说过话。' : real ? '' : '演示回复 · 未连接真实模型');
const unread = pages.length - 1 - cursor, single = pages.length <= 1 && !busy, fullMessage = page?.message;
const textarea = useRef<HTMLTextAreaElement>(null);
useLayoutEffect(() => { const t = textarea.current; if (!t) return; t.style.height = 'auto'; t.style.height = Math.min(t.scrollHeight, 88) + 'px'; }, [draft]);
const typing = (on: boolean) => document.documentElement.classList.toggle('typing', on);
useEffect(() => () => { document.documentElement.classList.remove('typing'); }, []);
const record = reply ? shown.filter(m => !m.live) : shown;
// While a reading sheet is open the table words are out of reach (the sheet holds them all); layout effect so the
// focus hand-back after closing never lands on an inert button.
const conversation = useRef<HTMLElement>(null);
useLayoutEffect(() => { conversation.current?.toggleAttribute('inert', log || full); }, [log, full]);
return <><section ref={conversation} className={`conversation ${single ? 'single-page' : ''} ${flow ? '' : 'reading-paused'} ${holding && flow ? 'reading-held' : ''}`} aria-label="当前对话">
{voice && <div className="voice-row"><span className="voice-wave" aria-hidden="true"><i/><i/><i/><i/></span><span>{busy ? '她在想(模拟)' : '在听你说(模拟,无收音)'}</span><button onClick={() => { stop(); setNotice(fail ? '刚才没听清,你再说一遍?(模拟识别失败)' : '她停下来了,在等你。'); }}>打断她</button><button onClick={endVoice}>结束语音</button></div>}
<div className="stage" ref={stageRef} aria-hidden="true" onPointerEnter={e => { if (e.pointerType === 'mouse') hold('hover', true); }} onPointerLeave={() => hold('hover', false)}/>
<p className="sr" aria-live="polite" aria-atomic="true">{page ? `${page.message.role === 'user' ? '你' : name}:${page.text}` : ''}</p>
{status && <div className="talk-status" role="status"><span>{status}</span>{lastUser?.status === 'failed' && !busy && <button className="retry" onClick={() => void send(lastUser)}>重试</button>}</div>}
<div className="reader-bar">
<button className="flow" aria-pressed={flow} onClick={() => setFlow(!flow)}><Icon name={flow ? 'pause' : 'play'}/><span>{flow ? '暂停' : '继续'}</span></button>
<button className="icon" aria-label="上一句" disabled={cursor <= 0} onClick={() => back()}><Icon name="back"/></button>
<span className="count" aria-label={pages.length ? `第 ${cursor + 1} 句,共 ${pages.length} 句${busy ? ',还在说' : ''}` : '还没有对话'}><span>{pages.length ? `${cursor + 1} / ${pages.length}${busy ? '…' : ''}` : '0 / 0'}</span><i ref={meter}/></span>
<button className="icon" aria-label="下一句" disabled={atEnd} onClick={() => forward()}><Icon name="next"/></button>
<button className="read-all" ref={fullButton} disabled={!page} onClick={() => setFull(true)}>全文</button>
{busy && <button className="stop" onClick={stop}>停止回复</button>}
{!flow && cursor < cursorAt(pages, head.current) && <button className="latest" onClick={toLatest}><Icon name="down"/><span>{unread > 0 ? `回到读到的地方 · 后面还有 ${unread} 句` : '回到读到的地方'}</span></button>}
</div>
<div className="composer"><button className={`round log-btn ${log ? 'on' : ''}`} ref={historyButton} aria-label="完整记录" aria-expanded={log} onClick={() => setLog(!log)}><Icon name="lines"/></button>
<textarea ref={textarea} aria-label="想和她说的话" rows={1} maxLength={4000} value={draft} placeholder="想和她说点什么…" onFocus={() => typing(true)} onBlur={() => typing(false)} onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) { e.preventDefault(); void send(); } }}/>
<button className={`round cam ${vision ? 'on' : ''}`} aria-label={real ? '视觉观察尚未接通' : '视觉观察(模拟)'} onClick={() => { if (real) { setNotice('视觉尚未接通,不采集影像。'); return; } if (vision) { setVision(false); onObservation('窗户关上了'); } else setPermission('vision'); }}><Icon name="eye"/></button>
<button className="round send" disabled={!draft.trim() || offline} aria-label="发送" onClick={() => void send()}><Icon name="up"/></button>
<button className={`voice-button ${denied ? 'denied' : ''}`} aria-label={real ? '语音尚未接通' : voice ? '停止语音' : '开始模拟语音'} disabled={offline} onClick={setVoiceMode}><Icon name={voice ? 'stop' : 'mic'}/></button>
</div>
</section>
<aside className="record log-panel glass read" hidden={!log} role="dialog" aria-modal="false" aria-labelledby="record-title"><header><div><p className="eyebrow">{real ? '服务器聊天记录' : '完整记录 · 本机演示'}</p><h2 id="record-title">你们说过的话</h2></div><button className="btn-round sm" ref={logClose} aria-label="关闭记录" onClick={() => setLog(false)}><Icon name="x"/></button></header>
<div className="scroll" ref={logRef}><p className="guide">内容完整保留;关闭后回到刚才那一句,自动呈现会接着走。</p>{record.map(m => <article key={m.id} data-life={m.lifeIds[0]} data-role={m.role} className={`message ${m.status === 'failed' ? 'fail' : ''} ${focusLife && m.lifeIds.includes(focusLife) ? 'hl' : ''}`}><div className="author"><i/>{m.role === 'user' ? '你' : name}{m.proactive && <span className="tagm">她主动说的</span>}</div><p>{m.text}</p>{m.status === 'failed' && <button className="btn-text" onClick={() => void send(m)}>没发出去 · 重试</button>}{m.status === 'cancelled' && <span className="incomplete">已取消</span>}{m.live === 'cancelled' && <span className="incomplete">已停止 · 这是未完成片段,未存入聊天记录</span>}</article>)}{reply && <article className="message" data-role="companion"><div className="author"><i/>{name}</div><p>{reply}</p><span className="incomplete">还在说…</span></article>}</div></aside>
{full && fullMessage && <aside className="record full glass read" role="dialog" aria-modal="false" aria-labelledby="full-title"><header><div><p className="eyebrow">{fullMessage.role === 'user' ? '你' : name} · 全文</p><h2 id="full-title">这一段,慢慢看</h2></div><button className="btn-round sm" ref={fullClose} aria-label="关闭全文" onClick={() => setFull(false)}><Icon name="x"/></button></header>
<div className="scroll"><p className="guide">整段完整可读。关闭后回到刚才那一句。</p><article className="message" data-role={fullMessage.role}><div className="author"><i/>{fullMessage.role === 'user' ? '你' : name}</div><p>{fullMessage.text}</p>{fullMessage.live === 'generating' && <span className="incomplete">还在说…</span>}{fullMessage.live === 'cancelled' && <span className="incomplete">这段回复已停止,内容未完成,未存入聊天记录。</span>}</article></div></aside>}
{permission && <Modal title={permission === 'mic' ? '开启模拟语音?' : '打开模拟视觉窗?'} onClose={() => { setPermission(''); setDenied(true); setNotice('没有开启。真实服务尚未接通,文字仍可使用。'); }} confirm="开始模拟" onConfirm={() => { if (permission === 'mic') { setDenied(false); setVoice(true); onVoice(true); voiceController.current = new AbortController(); onPresence('在听你说(模拟)'); setNotice('模拟语音没有收音,可继续用文字输入。'); } else { if (fail) { onObservation('模拟 · 看不清,视觉服务未接通'); setNotice('模拟观察失败,文字仍可使用。'); } else setVision(true); } setPermission(''); }}>本次仅模拟界面状态,不申请麦克风或摄像头权限,不采集声音或影像,也不向外接服务发送请求。</Modal>}
</>;
}
+92
View File
@@ -0,0 +1,92 @@
import { graphemes, type Page } from './reading';
// The lines on your side of the table (HEL-799 talk.js present/pin/leave). React owns the element; this class owns
// its children so finished lines are never re-rendered, re-typeset or re-animated. Text is always textContent.
const EASE = 'cubic-bezier(.22,1,.36,1)';
export type PresentHow = 'advance' | 'jump' | 'instant';
export interface LineState { text: string; waiting: boolean }
export class LineStage {
constructor(private stage: HTMLElement) {}
// A line inks in only the first time it is read; review, returns and resizes show it as it is.
private inked = new Set<string>();
private line(page: Page, current: boolean, name: string, ink: boolean) {
if (ink) this.inked.add(page.key);
const el = document.createElement('div');
el.className = 'line' + (current ? ' is-current' : ' is-prev');
el.dataset.role = page.message.role; el.dataset.key = page.key;
const who = document.createElement('span'); who.className = 'by';
const dot = document.createElement('i'), label = document.createElement('b'), state = document.createElement('em');
label.textContent = page.message.role === 'user' ? '你' : name; label.title = label.textContent; state.className = 'state';
who.append(dot, label, state);
const p = document.createElement('p');
if (ink) {
// Her current line inks in once, character by character (capped so long lines don't drag).
p.className = 'ink';
graphemes(page.text).forEach((c, i) => { const s = document.createElement('span'); s.style.setProperty('--i', String(Math.min(i, 48))); s.textContent = c; p.append(s); });
} else p.textContent = page.text;
el.append(who, p);
return el;
}
// Take a line out of the flow at its current place, so the remaining lines lay out once at their final size.
private pin(node: HTMLElement, rect: DOMRect, stageRect: DOMRect) {
node.classList.add('leaving');
Object.assign(node.style, { position: 'absolute', left: rect.left - stageRect.left + 'px', top: rect.top - stageRect.top + 'px', width: rect.width + 'px', transformOrigin: '50% 0' });
}
private leave(node: HTMLElement, rect: DOMRect, stageRect: DOMRect, quick = false, lift = quick ? -4 : -14, shrink = 1) {
this.pin(node, rect, stageRect);
node.animate([{ opacity: getComputedStyle(node).opacity, transform: 'none', filter: 'blur(0)' }, { opacity: 0, transform: `translateY(${lift}px) scale(${shrink})`, filter: 'blur(5px)' }],
{ duration: quick ? 240 : 520, easing: EASE, fill: 'forwards' }).finished.then(() => node.remove()).catch(() => node.remove());
}
clear() { this.stage.replaceChildren(); }
// Shows the current page with the one before it. Returns early when the same lines are already on screen, so
// a growing stream, a status change or a re-render never replays anything.
present(pages: Page[], cursor: number, how: PresentHow, name: string, animate: boolean) {
const stage = this.stage, page = pages[cursor];
if (!page) { stage.replaceChildren(); return; }
const prev = pages[cursor - 1], want = [prev, page].filter((p): p is Page => !!p);
const have = [...stage.querySelectorAll<HTMLElement>('.line:not(.leaving)')], keys = have.map(n => n.dataset.key);
const inkFor = (p: Page) => p === page && animate && p.message.role === 'companion' && !this.inked.has(p.key);
if (how === 'instant' || !animate) {
// Keyboard review and reduced motion: show the target lines as they are — no slide, no re-played ink.
if (keys.join() === want.map(p => p.key).join() && how !== 'instant') return;
for (const n of stage.querySelectorAll('.line.leaving')) n.remove();
stage.replaceChildren(...want.map(p => this.line(p, p === page, name, false)));
return;
}
if (keys.join() === want.map(p => p.key).join()) return;
const stageRect = stage.getBoundingClientRect();
// Forward by one: the finished line lifts toward the "previous" slot while a small copy settles there; the
// oldest drifts away. Both copies keep a fixed font size; only transform/opacity/filter move.
if (how === 'advance' && prev && keys[keys.length - 1] === prev.key) {
const first = new Map(have.map(n => [n, n.getBoundingClientRect()]));
for (const n of have) if (n.dataset.key !== prev.key) this.leave(n, first.get(n)!, stageRect);
const keep = have.find(n => n.dataset.key === prev.key)!, was = first.get(keep)!;
const settled = this.line(prev, false, name, false), fresh = this.line(page, true, name, inkFor(page));
this.pin(keep, was, stageRect);
stage.append(settled, fresh);
const to = settled.getBoundingClientRect();
if (to.height) {
const shrink = parseFloat(getComputedStyle(settled.querySelector('p')!).fontSize) / parseFloat(getComputedStyle(keep.querySelector('p')!).fontSize);
this.leave(keep, was, stageRect, false, to.top - was.top, shrink);
settled.animate([{ opacity: 0, transform: `translateY(${Math.round((was.top - to.top) * .35)}px)` }, { opacity: getComputedStyle(settled).opacity, transform: 'none' }], { duration: 620, easing: EASE });
} else this.leave(keep, was, stageRect); // compact screens hide the previous line
fresh.animate([{ opacity: 0, transform: 'translateY(16px)', filter: 'blur(8px)' }, { opacity: 1, transform: 'none', filter: 'blur(0)' }], { duration: 680, easing: EASE });
return;
}
// Jumps (review, new turn, resize) crossfade instead of sliding, so direction never lies.
for (const n of have) this.leave(n, n.getBoundingClientRect(), stageRect, true);
for (const p of want) {
const el = this.line(p, p === page, name, inkFor(p)); stage.append(el);
el.animate([{ opacity: 0, filter: 'blur(6px)' }, { opacity: 1, filter: 'blur(0)' }], { duration: 520, delay: 90, easing: EASE, fill: 'backwards' });
}
}
// Status words beside the current speaker ("还在说", "未完成 · 已取消"); changing them never touches the text.
mark(state: LineState) {
const cur = this.stage.querySelector('.line.is-current:not(.leaving)'); if (!cur) return;
const s = cur.querySelector('.state'); if (s && s.textContent !== state.text) s.textContent = state.text;
cur.classList.toggle('waiting', state.waiting);
}
rename(name: string) {
for (const n of this.stage.querySelectorAll<HTMLElement>('.line[data-role="companion"] .by b')) { n.textContent = name; n.title = name; }
}
}
+85
View File
@@ -0,0 +1,85 @@
import type { Message } from '../domain/model';
// Reading logic carried over from the verified HEL-793/795 prototype (PR#8) and HEL-799 (approved 01a16810), moved
// onto the real message flow: replies are shown one or two lines at a time and flow on by themselves.
// A message as the stage sees it: stored messages plus, at most, the reply still being written or cut off.
export interface ShownMessage extends Message { live?: 'generating' | 'cancelled' }
export interface Turn { key: string; items: ShownMessage[] }
export interface Page { key: string; text: string; index: number; last: boolean; mi: number; message: ShownMessage }
export interface Metrics { width: number; font: number; compact: boolean }
export const graphemes = (text: string): string[] => typeof Intl.Segmenter === 'function' ? [...new Intl.Segmenter('zh', { granularity: 'grapheme' }).segment(text)].map(s => s.segment) : Array.from(text);
// A turn starts with your message (or with something she says on her own). Server turn ids keep a reply with the
// message it answers; older local records without ids fall back to their order.
export function groupTurns(messages: ShownMessage[]): Turn[] {
const turns: Turn[] = [];
for (const m of messages) {
const cur = turns[turns.length - 1], head = cur?.items[0];
const fresh = !cur || m.role === 'user' || !!m.proactive || (!!m.turnId && !!head?.turnId && m.turnId !== head.turnId);
if (fresh || !cur) turns.push({ key: m.turnId || m.id, items: [m] }); else cur.items.push(m);
}
return turns;
}
export function chunks(text: string, { width, font, compact }: Metrics): string[] {
const perLine = Math.floor(Math.max(220, Math.min(width, 900) - 24) / font), max = Math.max(14, Math.min(60, Math.floor(perLine * (compact ? 1.6 : 2))));
const out: string[] = []; let line = '', n = 0;
for (const ch of graphemes(text)) {
if (ch === '\n') { if (line.trim()) { out.push(line); line = ''; n = 0; } continue; }
// Keep closing punctuation with its sentence; never produce an empty line.
if (!line && out.length && /[。!?!?,、;:,;:」』))”]/u.test(ch)) { out[out.length - 1] += ch; continue; }
line += ch; n++;
// Short sentences travel together (as in the approved still); a line ends at a sentence once it has some weight.
if (/[。!?!?]/u.test(ch) && n >= Math.min(22, max * .45)) { out.push(line); line = ''; n = 0; }
else if (n >= max) {
// Long text without punctuation still breaks, so nothing ever overflows the stage.
const cut = Math.max(line.lastIndexOf(','), line.lastIndexOf('、'), line.lastIndexOf(';'));
if (cut > max * .55) { out.push(line.slice(0, cut + 1)); line = line.slice(cut + 1); n = graphemes(line).length; } else { out.push(line); line = ''; n = 0; }
}
}
if (line.trim()) out.push(line);
return out;
}
export function pagesOf(turn: Turn | undefined, metrics: Metrics): Page[] {
const list: Page[] = [];
if (!turn) return list;
turn.items.forEach((message, mi) => {
const parts = chunks(message.text, metrics);
// The newest chunk of a reply still being written is held back (it may still grow or merge with the next
// sentence), so a line never changes or re-animates after it has appeared.
const held = message.live === 'generating' && parts.length ? 1 : 0;
// Keys follow the turn and position, not the message id, so a streamed reply keeps its lines when it is stored.
for (let index = 0; index < parts.length - held; index++) list.push({ key: `${turn.key}:${mi}:${index}`, text: parts[index], index, last: index === parts.length - 1, mi, message });
});
return list;
}
// Each line stays on screen in proportion to its length (about 2.4–8 s for her, shorter for yours).
export function dwellFor(page: Page) {
const n = graphemes(page.text).length;
return page.message.role === 'user' ? Math.min(3000, Math.max(1400, 900 + n * 60)) : Math.min(8000, Math.max(2400, 1500 + n * 150));
}
// Reading position as a character offset inside one message, so a re-chunk (resize, keyboard) keeps your place.
export interface Anchor { mi: number; offset: number }
export function anchorOf(pages: Page[], cursor: number): Anchor | null {
const page = pages[cursor];
if (!page) return null;
let offset = 0;
for (const p of pages) { if (p === page) break; if (p.mi === page.mi) offset += p.text.length; }
return { mi: page.mi, offset };
}
export function cursorAt(pages: Page[], anchor: Anchor | null): number {
if (!anchor) return 0;
let used = 0, best = -1;
for (let i = 0; i < pages.length; i++) {
if (pages[i].mi < anchor.mi) { best = i; continue; }
if (pages[i].mi > anchor.mi) break;
best = i;
if (used + pages[i].text.length > anchor.offset) return i;
used += pages[i].text.length;
}
return Math.max(0, best);
}
-31
View File
@@ -1,31 +0,0 @@
import { useLayoutEffect, useRef, useState } from 'react';
// Identity is a turn, not a token or a database id. Finalizing a stream keeps
// its DOM and animation. Only a replacement retains/fades out the old sentence.
export function SoftText({ identity, text }: { identity: string; text: string }) {
const current = useRef<HTMLSpanElement>(null), outgoing = useRef<HTMLSpanElement>(null);
const previous = useRef({ identity, text });
const [leaving, setLeaving] = useState<{ identity: string; text: string } | null>(null);
useLayoutEffect(() => {
if (previous.current.identity !== identity && previous.current.text) setLeaving(previous.current);
previous.current = { identity, text };
}, [identity, text]);
useLayoutEffect(() => {
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches || document.documentElement.classList.contains('reduced');
const easing = getComputedStyle(document.documentElement).getPropertyValue('--ease-out').trim();
const animation = current.current?.animate([
{ opacity: 0, transform: reduced ? 'none' : 'translateY(3px)' },
{ opacity: 1, transform: 'none' },
], { duration: reduced ? 120 : 200, easing });
return () => animation?.cancel();
}, [identity]);
useLayoutEffect(() => {
if (!leaving || !outgoing.current) return;
const animation = outgoing.current.animate([{ opacity: 1 }, { opacity: 0 }], {
duration: 160, easing: getComputedStyle(document.documentElement).getPropertyValue('--ease-out').trim(), fill: 'forwards',
});
void animation.finished.then(() => setLeaving(null)).catch(() => {});
return () => animation.cancel();
}, [leaving]);
return <span className="soft-text"><span key={identity} ref={current} className="current-text">{text}</span>{leaving && <span ref={outgoing} className="outgoing-text" aria-hidden="true">{leaving.text}</span>}</span>;
}
+11 -5
View File
@@ -2,23 +2,29 @@ import { useLayoutEffect, type ReactNode } from 'react';
export function Viewport({ children }: { children: ReactNode }) {
useLayoutEffect(() => {
const viewport = window.visualViewport, style = document.documentElement.style;
const viewport = window.visualViewport, html = document.documentElement, style = html.style;
let settle: ReturnType<typeof setTimeout>;
const update = () => {
// Keyboard/browser-bar geometry must follow the viewport immediately;
// a decorative stage transition would cover the dialogue in between.
document.documentElement.classList.add('viewport-resizing');
html.classList.add('viewport-resizing');
clearTimeout(settle);
settle = setTimeout(() => document.documentElement.classList.remove('viewport-resizing'), 200);
settle = setTimeout(() => html.classList.remove('viewport-resizing'), 200);
const height = viewport?.height ?? innerHeight, top = viewport?.offsetTop ?? 0;
style.setProperty('--view-h', `${height}px`);
style.setProperty('--view-top', `${top}px`);
style.setProperty('--view-bottom', `${Math.max(0, innerHeight - height - top)}px`);
// Short visual viewport = keyboard open or a squat window. Her face yields first, the words never do.
html.classList.toggle('compact', height < 610);
html.classList.toggle('micro', height < 420);
};
update();
// Hidden page: ambient loops and the reading clock pause; they resume where they were.
const visibility = () => html.classList.toggle('paused', document.hidden);
update(); visibility();
viewport?.addEventListener('resize', update); viewport?.addEventListener('scroll', update);
window.addEventListener('resize', update);
return () => { clearTimeout(settle); viewport?.removeEventListener('resize', update); viewport?.removeEventListener('scroll', update); window.removeEventListener('resize', update); };
document.addEventListener('visibilitychange', visibility);
return () => { clearTimeout(settle); viewport?.removeEventListener('resize', update); viewport?.removeEventListener('scroll', update); window.removeEventListener('resize', update); document.removeEventListener('visibilitychange', visibility); };
}, []);
return children;
}
+8
View File
@@ -0,0 +1,8 @@
// Keyboard shortcuts are frequent, deliberate jumps: land on the target state at once. CSS transitions are
// suspended for two frames and any finite animation already under way jumps to its end; ambient loops keep running.
export function snap() {
const html = document.documentElement;
html.classList.add('snap');
for (const a of document.getAnimations()) if (a.effect && a.effect.getTiming().iterations !== Infinity) a.finish();
requestAnimationFrame(() => requestAnimationFrame(() => html.classList.remove('snap')));
}
+33
View File
@@ -0,0 +1,33 @@
import { useLayoutEffect, useRef } from 'react';
import type { SpaceMode } from '../stage/roomScene';
// Which place in the shared room an app area belongs to. Panels (days/settings/creation) step the room back.
export function spaceFor(area: string, record: boolean, creating: boolean): SpaceMode {
if (creating) return 'pane';
if (area === 'talk') return record ? 'record' : 'talk';
return area === 'now' ? 'home' : 'pane';
}
// Publishes the space on <html data-mode> for CSS and keyboard handlers, and keeps focus where a keyboard user
// expects it: into a panel when it opens, back to whatever opened it when you return to the room.
export function useSpace(area: string, space: SpaceMode) {
const trigger = useRef<HTMLElement | null>(null), previous = useRef(area);
useLayoutEffect(() => { document.documentElement.dataset.mode = space; }, [space]);
useLayoutEffect(() => () => { delete document.documentElement.dataset.mode; }, []);
useLayoutEffect(() => {
const from = previous.current; previous.current = area;
if (from === area) return;
const active = document.activeElement as HTMLElement | null;
if (from === 'now' && active && active !== document.body) trigger.current = active;
if (area === 'days' || area === 'settings') {
// Opened from the navigation: stay on the navigation so the next area is one key away.
if (active?.closest('.nav')) return;
requestAnimationFrame(() => document.querySelector<HTMLElement>('.pane.open > header button[aria-label^="关闭"]')?.focus({ preventScroll: true }));
} else if (area === 'now') {
const lost = !active || active === document.body || !active.isConnected || !!active.closest('.pane,.conversation,.record');
if (!lost) return;
const t = trigger.current, usable = t && t.isConnected && !t.closest('[hidden],[inert]') && !(t as HTMLButtonElement).disabled;
requestAnimationFrame(() => (usable ? t : document.querySelector<HTMLElement>('.home .cta .btn-primary'))?.focus({ preventScroll: true }));
}
}, [area]);
}
+72 -9
View File
@@ -1,16 +1,79 @@
import { useState } from 'react';
import type { SceneDesc } from '../domain/model';
import { Icon } from '../shared/ui';
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from 'react';
import type { SceneDesc, Theme } from '../domain/model';
import { Background } from './Background';
import { RoomScene, type SpaceMode } from './roomScene';
export interface PresenterProps {
scene: SceneDesc;
space: SpaceMode;
theme: Theme;
// Bumped by keyboard shortcuts (Esc): the camera lands at once instead of travelling.
instant: number;
real?: boolean;
onClose: () => void;
closeLabel: string;
presence: string;
observation: string;
onApproach: () => void;
}
// Only consumes scene. No life writes, no synthesis, no microphone/camera APIs.
export function FallbackPresenter({ scene, onClose, closeLabel, presence, observation, real = false }: PresenterProps) {
// One shared room (HEL-799, approved 01a16810): far = her room and the rainy city, middle = her, near = your table.
// Only consumes scene. No life writes, no synthesis, no microphone/camera APIs. The two stills are reference frames,
// not her real daily video; the camera move is the approved push-in, not body motion.
export function Presenter({ scene, space, theme, instant, real = false, observation, onApproach }: PresenterProps) {
const [failed, setFailed] = useState(false);
return <><section className="portal" aria-label="她的视窗"><div className="life">{!failed && <><img className="img-room" src="/assets/her-room.jpg" alt="卧室窗边的人物参考静帧" onError={() => setFailed(true)}/><img className="img-talk" src="/assets/her-talk.jpg" alt="同一人物的交谈近景参考静帧" onError={() => setFailed(true)}/></>}</div>{failed && <div className="empty">画面暂时没打开,文字仍可使用。</div>}<div className="tint"/><div className="doing"><span className="chip glass"><Icon name="book"/>{scene.activity}</span><span className="tag-demo">{real ? '生活尚未接通' : '演示状态'}</span></div><div className="topleft"><span className="chip">{presence}</span>{observation && <span className="chip observe show">{observation}</span>}</div><button className="close" onClick={onClose}><Icon name="back"/>{closeLabel}</button><span className="mark">示意画面 · 参考静帧</span></section><div className="mini-cap"><b>她此刻 · {scene.activity}</b>{real ? '生活尚未接通' : '来自演示生活状态'}<br />画面为示意静帧<button className="btn-text" onClick={onClose}>回到她身边</button></div></>;
const cam = useRef<HTMLDivElement>(null), room = useRef<HTMLDivElement>(null), talk = useRef<HTMLDivElement>(null), moon = useRef<HTMLElement>(null), near = useRef<HTMLDivElement>(null), hit = useRef<HTMLButtonElement>(null), rainRoom = useRef<HTMLCanvasElement>(null), rainTalk = useRef<HTMLCanvasElement>(null);
const controller = useRef<RoomScene | null>(null), first = useRef(true), lastInstant = useRef(instant);
useLayoutEffect(() => {
if (!cam.current || !room.current || !talk.current || !moon.current || !near.current || !hit.current || !rainRoom.current || !rainTalk.current) return;
const scene = new RoomScene({ cam: cam.current, room: room.current, talk: talk.current, moon: moon.current, near: near.current, hit: hit.current, rainRoom: rainRoom.current, rainTalk: rainTalk.current });
controller.current = scene;
(window as unknown as { __room?: () => unknown }).__room = () => scene.info();
return () => { scene.destroy(); controller.current = null; };
}, []);
useLayoutEffect(() => {
// First paint and keyboard jumps land directly; every other change travels on the spring.
const jump = first.current || lastInstant.current !== instant;
first.current = false; lastInstant.current = instant;
controller.current?.go(space, jump);
}, [space, instant]);
const firstTheme = useRef(true);
useLayoutEffect(() => { controller.current?.setTheme(theme, firstTheme.current); firstTheme.current = false; }, [theme]);
// The reduced-motion preference changes the camera from travelling to crossfading; redraw at rest.
useEffect(() => { const q = matchMedia('(prefers-reduced-motion: reduce)'), redo = () => controller.current?.resize(); q.addEventListener('change', redo); return () => q.removeEventListener('change', redo); }, []);
const fail = () => setFailed(true);
return <>
{failed && <Background/>}
<div className={`room ${failed ? 'failed' : ''}`} aria-hidden="true">
<div className="r-cam" ref={cam}>
<div className="plate plate-room" ref={room}><div className="po">
{!failed && <img className="photo" src="/assets/her-room.jpg" alt="" draggable={false} onError={fail}/>}
<div className="r-tint moon"><i className="night"/><i className="night2"/></div>
<div className="r-tint fog"><i className="night"/><i className="night2"/></div>
<canvas className="r-rain" ref={rainRoom}/>
<i className="r-mist m1"/><i className="r-mist m2"/>
<i className="flame-glow" style={{ left: 931, top: 500 }}/>
<i className="spill"/>
</div></div>
<div className="plate plate-talk" ref={talk}><div className="po">
{!failed && <img className="photo" src="/assets/her-talk.jpg" alt="" draggable={false} onError={fail}/>}
<div className="r-tint moon"><i className="night"/><i className="night2"/><i className="beam"/></div>
<div className="r-tint fog"><i className="night"/><i className="night2"/><i className="beam"/></div>
<canvas className="r-rain" ref={rainTalk}/>
<i className="r-mist m1"/><i className="r-mist m2"/>
<i className="flame-glow" style={{ left: 89, top: 738 }}/><i className="flame-glow" style={{ left: -12, top: 704 }}/>
<i className="spill"/>
{[[1180, 330, 17, -3], [1290, 240, 21, -9], [1400, 420, 19, -14], [1230, 520, 24, -6]].map(([x, y, d, dl]) => <i key={x} className="mote" style={{ '--x': `${x}px`, '--y': `${y}px`, '--d': `${d}s`, '--dl': `${dl}s` } as CSSProperties}/>)}
</div></div>
<i className="r-moon" ref={moon}/>
</div>
<div className="r-near" ref={near}>
<canvas className="near-c" data-theme-layer="moon"/><canvas className="near-c" data-theme-layer="fog"/>
<i className="steam s1"/><i className="steam s2"/><i className="candle"/>
</div>
<div className="r-vignette"/><div className="r-veil"/>
</div>
<button className="her-hit" ref={hit} aria-label="走近她,开始交谈" tabIndex={space === 'home' ? 0 : -1} disabled={space !== 'home'} onClick={onApproach}><span>和她说话</span></button>
<div className="room-labels">
{failed && <span className="chip glass">画面暂时没打开,文字仍可使用。</span>}
{observation && <span className="chip glass observe show">{observation}</span>}
</div>
<p className="ref-note" data-activity={scene.activity}>{real ? '生活尚未接通' : '演示状态'} · 人物为旧参考静帧 · 不代表新日常 · 未接入真实动态</p>
</>;
}
+171
View File
@@ -0,0 +1,171 @@
import type { Theme } from '../domain/model';
// Ambient life of the room (HEL-799 ambient.js): drawn, never taken from her photo, never a weather claim.
// Rain falls only inside each still's window panes; city windows blink; a few drops slide down the glass.
const COLORS: Record<Theme, number[]> = { moon: [190, 210, 255], fog: [228, 204, 255] };
// Plate px. clip: the glass; city: where lit windows may blink.
const CFG = {
room: { clip: [655, 0, 545, 545], city: [660, 215, 530, 320], n: 110, seed: 11 },
talk: { clip: [0, 0, 640, 600], city: [0, 200, 640, 360], n: 150, seed: 7 },
} as const;
type PlateKey = keyof typeof CFG;
interface Streak { x: number; y: number; len: number; spd: number; a: number }
interface Light { x: number; y: number; p: number; f: number; warm: boolean }
interface Slide { x: number; y: number; spd: number; r: number }
interface Layer { ctx: CanvasRenderingContext2D; streaks: Streak[]; lights: Light[]; slides: Slide[]; drops: HTMLCanvasElement; scale: number }
const rng = (seed: number) => () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const sstep = (k: number) => k * k * (3 - 2 * k);
export class Rain {
private layers: Partial<Record<PlateKey, Layer>> = {};
private mix = 0; private mixFrom = 0; private mixTo = 0; private mixStart = 0;
private visible: Record<PlateKey, boolean> = { room: true, talk: false };
private dirty = true; private lastDraw = 0; private res = 0;
constructor(private canvases: Record<PlateKey, HTMLCanvasElement>) {}
private build(name: PlateKey, scale: number) {
const c = CFG[name], cv = this.canvases[name], r = rng(c.seed), ctx = cv.getContext('2d');
if (!ctx) return;
cv.width = 1600 * scale; cv.height = 1000 * scale;
const [x, y, w, h] = c.clip;
const streaks = Array.from({ length: c.n }, () => ({ x: x + r() * (w + 60), y: y + r() * h, len: 10 + r() * 24, spd: 520 + r() * 420, a: .07 + r() * .17 }));
const lights = Array.from({ length: 30 }, () => ({ x: c.city[0] + r() * c.city[2], y: c.city[1] + r() * c.city[3], p: r() * 6.28, f: .25 + r() * .7, warm: r() > .35 }));
const slides = Array.from({ length: 4 }, () => ({ x: x + r() * w, y: y + r() * h, spd: 6 + r() * 14, r: 1.6 + r() * 1.4 }));
// Static droplets on the glass, rendered once.
const drops = document.createElement('canvas'); drops.width = cv.width; drops.height = cv.height;
const d = drops.getContext('2d');
if (d) {
d.scale(scale, scale);
for (let i = 0; i < 70; i++) {
const px = x + r() * w, py = y + r() * h, rr = 1 + r() * 2.4, g = d.createRadialGradient(px - rr * .3, py - rr * .3, 0, px, py, rr);
g.addColorStop(0, 'rgba(230,240,255,.45)'); g.addColorStop(1, 'rgba(160,190,255,0)');
d.fillStyle = g; d.beginPath(); d.arc(px, py, rr, 0, 7); d.fill();
}
}
this.layers[name] = { ctx, streaks, lights, slides, drops, scale };
}
private paint(name: PlateKey, dt: number, now: number) {
const s = this.layers[name]; if (!s) return;
const { ctx, scale } = s, [x, y, w, h] = CFG[name].clip;
const col = COLORS.moon.map((m, i) => Math.round(m + (COLORS.fog[i] - m) * this.mix));
ctx.setTransform(scale, 0, 0, scale, 0, 0);
ctx.clearRect(x - 2, y - 2, w + 4, h + 4);
ctx.save(); ctx.beginPath(); ctx.rect(x, y, w, h); ctx.clip();
for (const l of s.lights) {
const a = Math.max(0, Math.sin(l.p + now / 1000 * l.f)) * .55;
if (a < .02) continue;
ctx.fillStyle = l.warm ? `rgba(255,214,150,${a.toFixed(3)})` : `rgba(${col[0]},${col[1]},${col[2]},${(a * .8).toFixed(3)})`;
ctx.fillRect(l.x, l.y, 2.2, 2.6);
}
ctx.lineWidth = .8; ctx.lineCap = 'round';
for (const k of s.streaks) {
k.y += k.spd * dt; k.x -= k.spd * dt * .18;
if (k.y > y + h) { k.y = y - k.len; k.x = x + Math.random() * (w + 60); }
ctx.strokeStyle = `rgba(${col[0]},${col[1]},${col[2]},${k.a.toFixed(3)})`;
ctx.beginPath(); ctx.moveTo(k.x, k.y); ctx.lineTo(k.x - k.len * .18, k.y + k.len); ctx.stroke();
}
ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(s.drops, 0, 0); ctx.setTransform(scale, 0, 0, scale, 0, 0);
for (const q of s.slides) {
q.y += q.spd * dt; if (q.y > y + h) { q.y = y; q.x = x + Math.random() * w; }
ctx.fillStyle = 'rgba(225,236,255,.35)'; ctx.beginPath(); ctx.arc(q.x, q.y, q.r, 0, 7); ctx.fill();
ctx.fillStyle = 'rgba(225,236,255,.08)'; ctx.fillRect(q.x - .5, q.y - 26, 1, 26);
}
ctx.restore();
}
draw(now: number, tier: number, still: boolean, hidden: boolean) {
const want = tier > 0 ? .5 : 1;
if (want !== this.res) { this.res = want; this.build('room', want); this.build('talk', want); this.dirty = true; }
if (this.mixStart) { const k = Math.min(1, (now - this.mixStart) / 1000); this.mix = this.mixFrom + (this.mixTo - this.mixFrom) * sstep(k); if (k >= 1) this.mixStart = 0; this.dirty = true; }
// Reduced motion: the rain stays one still frame.
if (still) { if (!this.dirty) return; this.dirty = false; this.paint('room', 0, 0); this.paint('talk', 0, 0); return; }
if (hidden) return;
if (tier > 1 && now - this.lastDraw < 32) return; // ~30fps on slow devices
const dt = this.lastDraw ? Math.min(.05, (now - this.lastDraw) / 1000) : 0; this.lastDraw = now;
if (this.visible.room) this.paint('room', dt, now);
if (this.visible.talk) this.paint('talk', dt, now);
}
view(talkOpacity: number) { this.visible.room = talkOpacity < .998; this.visible.talk = talkOpacity > .002; this.dirty = true; }
setTheme(theme: Theme, instant: boolean) {
this.mixTo = theme === 'fog' ? 1 : 0;
if (instant) { this.mix = this.mixTo; this.mixStart = 0; this.dirty = true; return; }
this.mixFrom = this.mix; this.mixStart = performance.now();
}
resume() { this.lastDraw = 0; }
}
// Your side of the table: drawn per theme at the viewport's own size, so the cup and candle never stretch.
const PAL = {
moon: { top: ['#3b2c30', '#221a24', '#0b0a14'], cool: '150,180,255', warm: '255,190,130', grain: ['#c9b8ff', '#ffd9b0'], rim: ['170,200,255', '240,230,255', '255,205,150'], cup: ['#5a6aa0', '#d9def2', '#9ea6c8', '#3a3f66'], handle: '#aeb6d8', bokeh: ['160,190,255', '255,200,140'] },
fog: { top: ['#3a2a3e', '#231a30', '#0e0a18'], cool: '200,170,255', warm: '255,180,175', grain: ['#e2c4ff', '#ffd2d8'], rim: ['205,180,255', '246,226,255', '255,192,176'], cup: ['#7a62a8', '#e6dcf2', '#b0a2c8', '#4a3a66'], handle: '#c2b4d8', bokeh: ['205,170,255', '255,186,200'] },
};
type Palette = typeof PAL.moon;
function anchors(W: number, H: number) {
const sx = W / 1600, sy = H / 1000, u = Math.min(1.35, Math.max(.42, Math.min(sx, sy))), phone = W <= 720 || W / H < .9;
return { sx, sy, u, cup: phone ? [34, H - 8] : [210 * sx, 985 * sy], candle: phone ? [W - 26, H - 30] : [1400 * sx, 966 * sy] };
}
function paintNear(cv: HTMLCanvasElement, pal: Palette, W: number, H: number, dpr: number) {
cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
const A = anchors(W, H), c = cv.getContext('2d');
if (!c) return A;
const { sx, sy, u } = A, px = (n: number) => n * dpr;
c.setTransform(dpr, 0, 0, dpr, 0, 0);
const ex = W / 2, ey = 1585 * sy, rx = 1300 * Math.max(sx, .32), ry = 775 * sy;
// Table top: one arc of a large round table, the part nearest to you.
c.save(); c.filter = `blur(${px(2.5 * u)}px)`;
c.beginPath(); c.ellipse(ex, ey, rx, ry, 0, Math.PI, 2 * Math.PI); c.lineTo(W + 100, H + 100); c.lineTo(-100, H + 100); c.closePath();
const top = c.createLinearGradient(0, ey - ry - 30 * sy, 0, H);
top.addColorStop(0, pal.top[0]); top.addColorStop(.3, pal.top[1]); top.addColorStop(1, pal.top[2]);
c.fillStyle = top; c.fill(); c.clip();
let g = c.createRadialGradient(300 * sx, 860 * sy, 0, 300 * sx, 860 * sy, 520 * u);
g.addColorStop(0, `rgba(${pal.cool},.22)`); g.addColorStop(1, `rgba(${pal.cool},0)`); c.fillStyle = g; c.fillRect(0, 0, W, H);
g = c.createRadialGradient(1260 * sx, 840 * sy, 0, 1260 * sx, 840 * sy, 560 * u);
g.addColorStop(0, `rgba(${pal.warm},.26)`); g.addColorStop(1, `rgba(${pal.warm},0)`); c.fillStyle = g; c.fillRect(0, 0, W, H);
c.globalAlpha = .06;
for (let i = 0; i < 26; i++) {
c.strokeStyle = pal.grain[i % 2]; c.lineWidth = 1;
c.beginPath(); c.ellipse(ex, ey, Math.max(10, rx - i * 9 * sx), Math.max(10, ry - (i * 6 + 14) * sy), 0, Math.PI * 1.08, Math.PI * 1.92); c.stroke();
}
c.restore();
c.save(); c.filter = `blur(${px(1)}px)`;
const rim = c.createLinearGradient(0, 0, W, 0);
rim.addColorStop(0, `rgba(${pal.rim[0]},.05)`); rim.addColorStop(.25, `rgba(${pal.rim[0]},.45)`);
rim.addColorStop(.55, `rgba(${pal.rim[1]},.3)`); rim.addColorStop(.8, `rgba(${pal.rim[2]},.55)`); rim.addColorStop(1, `rgba(${pal.rim[2]},.08)`);
c.strokeStyle = rim; c.lineWidth = 2;
c.beginPath(); c.ellipse(ex, ey, rx, ry, 0, Math.PI * 1.03, Math.PI * 1.97); c.stroke();
c.restore();
// Your cup (nearest, most out of focus). Drawn in HEL-798 units around its base.
c.save(); c.translate(A.cup[0], A.cup[1]); c.scale(u, u); c.translate(-210, -985); c.filter = `blur(${px(5 * u)}px)`;
c.fillStyle = '#0d0c18'; c.beginPath(); c.ellipse(205, 985, 150, 34, 0, 0, 7); c.fill();
const cup = c.createLinearGradient(100, 0, 320, 0);
cup.addColorStop(0, pal.cup[0]); cup.addColorStop(.35, pal.cup[1]); cup.addColorStop(.7, pal.cup[2]); cup.addColorStop(1, pal.cup[3]);
c.fillStyle = cup; c.beginPath(); c.moveTo(108, 830); c.bezierCurveTo(108, 950, 140, 985, 210, 985); c.bezierCurveTo(280, 985, 312, 950, 312, 830); c.closePath(); c.fill();
c.strokeStyle = pal.handle; c.lineWidth = 16; c.beginPath(); c.arc(320, 885, 34, -Math.PI / 2.2, Math.PI / 2.2); c.stroke();
c.fillStyle = '#3a2416'; c.beginPath(); c.ellipse(210, 830, 102, 18, 0, 0, 7); c.fill();
c.fillStyle = 'rgba(255,200,140,.35)'; c.beginPath(); c.ellipse(240, 828, 46, 7, 0, 0, 7); c.fill();
c.restore();
// Your small candle, answering the one beside her.
c.save(); c.translate(A.candle[0], A.candle[1]); c.scale(u, u); c.translate(-1400, -966); c.filter = `blur(${px(3.5 * u)}px)`;
const glass = c.createLinearGradient(1350, 0, 1450, 0);
glass.addColorStop(0, 'rgba(255,190,130,.25)'); glass.addColorStop(.5, 'rgba(255,225,180,.55)'); glass.addColorStop(1, 'rgba(255,170,110,.22)');
c.fillStyle = glass; c.beginPath(); c.moveTo(1356, 850); c.lineTo(1444, 850); c.lineTo(1440, 952); c.quadraticCurveTo(1400, 966, 1360, 952); c.closePath(); c.fill();
c.fillStyle = 'rgba(255,240,215,.35)'; c.beginPath(); c.ellipse(1400, 850, 44, 9, 0, 0, 7); c.fill();
c.restore();
// Near bokeh (depth of field).
c.save(); c.globalCompositeOperation = 'screen';
const bok: [number, number, number, number, number][] = [[60, 120, 70, 0, .1], [1530, 300, 90, 1, .09], [1480, 980, 120, 1, .1], [560, 990, 80, 0, .08], [30, 560, 60, 0, .08]];
for (const [x, y, r0, k, a] of bok) {
const r = r0 * u, X = x * sx, Y = y * sy, col = pal.bokeh[k];
g = c.createRadialGradient(X, Y, r * .6, X, Y, r);
g.addColorStop(0, `rgba(${col},${a})`); g.addColorStop(.9, `rgba(${col},${a * .8})`); g.addColorStop(1, `rgba(${col},0)`);
c.fillStyle = g; c.beginPath(); c.arc(X, Y, r, 0, 7); c.fill();
}
c.restore();
return A;
}
export function drawNear(host: HTMLElement, W: number, H: number, tier: number) {
const dpr = Math.min(tier > 0 ? 1 : 2, window.devicePixelRatio || 1);
let A: ReturnType<typeof anchors> | undefined;
for (const cv of host.querySelectorAll<HTMLCanvasElement>('canvas[data-theme-layer]')) A = paintNear(cv, PAL[cv.dataset.themeLayer as Theme], W, H, dpr);
if (!A) return;
host.style.setProperty('--u', A.u.toFixed(3));
host.style.setProperty('--steam-x', (A.cup[0] + 5 * A.u).toFixed(1) + 'px'); host.style.setProperty('--steam-y', (A.cup[1] - 330 * A.u).toFixed(1) + 'px');
host.style.setProperty('--candle-x', A.candle[0].toFixed(1) + 'px'); host.style.setProperty('--candle-y', (A.candle[1] - 116 * A.u).toFixed(1) + 'px');
}
+76
View File
@@ -0,0 +1,76 @@
// One room, one camera (HEL-799 scene.js, approved 01a16810). Pure geometry, no DOM.
// Two approved reference stills of the same person, room and clothes are aligned on her face, so the camera can
// move continuously from "sitting across the room" (room still) to "sitting across the table" (talk still, = the
// approved HEL-798 composition). Only transform and opacity move per frame; the face itself is never warped.
export type PlateName = 'room' | 'talk';
export interface Placement { s: number; o: [number, number] }
export interface CameraPose { room: Placement; talk: Placement }
// Plate px of the 1600×1000 design. FACE: centre of her face in each still. K: her face is K× larger on the talk
// plate than on the room plate (measured from eye spacing and hair width on the two stills: 3.8 native × 1.12 / 1.4).
export const FACE: Record<PlateName, [number, number]> = { room: [1275, 347], talk: [856, 315] };
export const K = 3.04;
// Picture bounds of each plate in design px (the room still is shown at 2240×1260, the talk still at 1792×1008).
export const BOUNDS: Record<PlateName, [number, number, number, number]> = { room: [-640, -112, 1600, 1148], talk: [-118, -10, 1674, 998] };
export const MOON: Record<PlateName, [number, number, number]> = { room: [1082, 98, 30], talk: [404, 92, 44] };
// Her figure on the room plate, for the tap target.
export const HER: [number, number, number, number] = [1195, 235, 1445, 700];
export const smoothstep = (a: number, b: number, x: number) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
export const isPhone = (vw: number, vh: number) => vw <= 720 || vw / vh < .9;
export class Camera {
// Overscan kept for pointer parallax.
constructor(public vw: number, public vh: number, public overscan = 12) {}
private shot(kind: PlateName) {
const phone = isPhone(this.vw, this.vh);
if (kind === 'room') return { ax: phone ? .6 : 1275 / 1600, ay: phone ? .25 : .347 };
return { ax: phone ? .5 : 856 / 1600, ay: phone ? .27 : .315 };
}
// How far a plate must shift so its picture still covers the viewport (plus parallax overscan).
private cover(s: number, o: [number, number], p: PlateName): [number, number] {
const [x0, y0, x1, y1] = BOUNDS[p], c: [number, number] = [0, 0], M = this.overscan;
const fit = (pos: number, a0: number, a1: number, size: number, i: 0 | 1) => {
const min = size + M - s * a1, max = -M - s * a0;
if (min > max) { c[i] = (min + max) / 2 - pos; return; }
if (pos < min) c[i] = min - pos; else if (pos > max) c[i] = max - pos;
};
fit(o[0], x0, x1, this.vw, 0); fit(o[1], y0, y1, this.vh, 1);
return c;
}
rest(kind: PlateName): Placement {
const sh = this.shot(kind), base = Math.max(this.vw / 1600, this.vh / 1000), f = FACE[kind];
const o: [number, number] = [sh.ax * this.vw - base * f[0], sh.ay * this.vh - base * f[1]];
const c = this.cover(base, o, kind);
return { s: base, o: [o[0] + c[0], o[1] + c[1]] };
}
// Camera at parameter x: zoom in log-space, face travels in a straight line on screen.
at(x: number): CameraPose {
const A = this.rest('room'), B = this.rest('talk');
const sRB = B.s * K;
const phA = [A.o[0] + A.s * FACE.room[0], A.o[1] + A.s * FACE.room[1]];
const phB = [B.o[0] + B.s * FACE.talk[0], B.o[1] + B.s * FACE.talk[1]];
const sR = A.s * Math.pow(sRB / A.s, x), sT = sR / K;
const ph = [lerp(phA[0], phB[0], x), lerp(phA[1], phB[1], x)];
const oR: [number, number] = [ph[0] - sR * FACE.room[0], ph[1] - sR * FACE.room[1]];
const oT: [number, number] = [ph[0] - sT * FACE.talk[0], ph[1] - sT * FACE.talk[1]];
const cR = this.cover(sR, oR, 'room'), cT = this.cover(sT, oT, 'talk'), w = smoothstep(.35, .8, x);
const c = [lerp(cR[0], cT[0], w), lerp(cR[1], cT[1], w)];
return { room: { s: sR, o: [oR[0] + c[0], oR[1] + c[1]] }, talk: { s: sT, o: [oT[0] + c[0], oT[1] + c[1]] } };
}
}
export const mapPoint = (tr: Placement, p: readonly [number, number]): [number, number] => [tr.o[0] + tr.s * p[0], tr.o[1] + tr.s * p[1]];
// Critically damped spring: interruptible, keeps its velocity when the target changes mid-way (≈0.85s to settle).
export const SPRING_W = 7.2;
export function springStep(t: number, v: number, target: number, dt: number) {
// Fixed small sub-steps keep the spring in real time even when frames arrive late.
for (let left = dt; left > 0; left -= 1 / 240) {
const h = Math.min(left, 1 / 240), a = SPRING_W * SPRING_W * (target - t) - 2 * SPRING_W * v;
v += a * h; t += v * h;
}
const settled = Math.abs(target - t) < 4e-4 && Math.abs(v) < 4e-3;
return settled ? { t: target, v: 0, settled } : { t, v, settled };
}
+126
View File
@@ -0,0 +1,126 @@
import type { Theme } from '../domain/model';
import { Camera, FACE, HER, MOON, lerp, mapPoint, smoothstep, springStep, type CameraPose, type Placement } from './camera';
import { Rain, drawNear } from './ambient';
// Where you are in the shared space. home: across the room; talk/record: across the table; pane: the room steps back.
export type SpaceMode = 'home' | 'talk' | 'record' | 'pane';
export interface RoomElements {
cam: HTMLElement; room: HTMLElement; talk: HTMLElement; moon: HTMLElement; near: HTMLElement; hit: HTMLElement;
rainRoom: HTMLCanvasElement; rainTalk: HTMLCanvasElement;
}
const reducedQuery = () => matchMedia('(prefers-reduced-motion: reduce)');
export const motionOff = () => reducedQuery().matches || document.documentElement.classList.contains('reduced');
const put = (el: HTMLElement, tr: Placement) => { el.style.transform = `translate3d(${tr.o[0].toFixed(2)}px,${tr.o[1].toFixed(2)}px,0) scale(${tr.s.toFixed(5)})`; };
// Imperative per-frame controller; React owns the DOM, this only writes transform/opacity/visibility on it.
export class RoomScene {
private camera = new Camera(innerWidth, innerHeight);
private rain: Rain;
// t: camera (0 = across the room, 1 = across the table). b: how much of the close still shows (reduced motion).
private t = 0; private v = 0; private target = 0; private b = 0; private bFrom = 0; private bStart = 0; private settled = true;
private maskOn: boolean | null = null; private tier = 0; private forced = false; private samples: number[] = [];
private last = 0; private raf = 0; private alive = true;
private fine = matchMedia('(hover: hover) and (pointer: fine)');
constructor(private el: RoomElements) {
this.rain = new Rain({ room: el.rainRoom, talk: el.rainTalk });
addEventListener('pointermove', this.pointer, { passive: true });
addEventListener('resize', this.resize);
document.addEventListener('visibilitychange', this.visibility);
const tier = new URLSearchParams(location.search).get('tier');
if (tier && /^[0-2]$/.test(tier)) this.setTier(+tier, true);
this.resize();
this.raf = requestAnimationFrame(this.frame);
}
destroy() {
this.alive = false; cancelAnimationFrame(this.raf);
removeEventListener('pointermove', this.pointer); removeEventListener('resize', this.resize);
document.removeEventListener('visibilitychange', this.visibility);
}
go(mode: SpaceMode, instant = false) {
const nt = mode === 'talk' || mode === 'record' ? 1 : 0;
if (instant) { this.t = this.target = this.b = nt; this.v = 0; this.settled = true; this.apply(); return; }
if (nt === this.target && this.settled) return;
this.bFrom = this.b; this.bStart = performance.now();
this.target = nt; this.settled = false;
}
setTheme(theme: Theme, instant: boolean) { this.rain.setTheme(theme, instant || motionOff()); }
resize = () => {
this.camera.vw = innerWidth; this.camera.vh = innerHeight;
drawNear(this.el.near, innerWidth, innerHeight, this.tier); this.apply();
};
// Review hook (same as the prototype's __proto.scene): exposes where her face is and how far the move has got.
info() {
const pose = motionOff() ? { talk: this.camera.rest('talk') } : this.camera.at(this.t), s = pose.talk.s;
const cx = pose.talk.o[0] + s * FACE.talk[0], cy = pose.talk.o[1] + s * FACE.talk[1];
return { t: +this.t.toFixed(4), target: this.target, settled: this.settled, tier: this.tier, face: { x: +cx.toFixed(1), y: +cy.toFixed(1) }, head: { left: cx - 200 * s, right: cx + 200 * s, top: cy - 300 * s, bottom: cy + 140 * s }, talkOpacity: +this.el.talk.style.opacity };
}
private visibility = () => { this.last = 0; this.samples = []; this.rain.resume(); };
// Pointer parallax (fine pointers only): far things move a little, your table the other way.
private pointer = (e: PointerEvent) => {
if (!this.fine.matches || motionOff() || e.pointerType !== 'mouse') return;
const px = e.clientX / innerWidth - .5, py = e.clientY / innerHeight - .5;
this.el.cam.style.transform = `translate3d(${(-px * 16).toFixed(1)}px,${(-py * 10).toFixed(1)}px,0)`;
this.el.near.style.setProperty('translate', `${(px * 22).toFixed(1)}px ${(py * 10).toFixed(1)}px`);
};
private step(dt: number) {
if (motionOff()) {
this.t = this.target; this.v = 0;
const k = Math.min(1, (performance.now() - this.bStart) / 200);
this.b = lerp(this.bFrom, this.target, k); this.settled = k >= 1;
return;
}
const next = springStep(this.t, this.v, this.target, dt);
this.t = next.t; this.v = next.v; this.settled = next.settled; this.b = this.t;
}
private apply() {
const off = motionOff(), el = this.el;
// Reduced motion: both stills stay at rest and simply crossfade.
const pose: CameraPose = off ? { room: this.camera.rest('room'), talk: this.camera.rest('talk') } : this.camera.at(this.t);
put(el.room, pose.room); put(el.talk, pose.talk);
const blend = off ? this.b : this.t, useMask = !off && this.tier < 2;
const op = useMask ? smoothstep(.08, .45, blend) : smoothstep(off ? 0 : .3, off ? 1 : .8, blend);
el.talk.style.opacity = op.toFixed(3);
el.talk.style.visibility = op < .002 ? 'hidden' : 'visible';
el.room.style.visibility = blend > .999 ? 'hidden' : 'visible';
// The close still opens out from her face: a soft-edged circle that grows until it reaches the corners,
// intersected with soft picture edges that tighten to nothing as the picture reaches the screen edges.
// (Mask coordinates are in the plate box, which starts at the picture's corner: face + (118, 10).)
const wantMask = useMask && blend < .985 && op > .002, s = el.talk.style;
if (wantMask) {
const r = 150 + 1450 * smoothstep(.1, .97, blend), e = (260 * (1 - smoothstep(.7, .985, blend))).toFixed(0);
const edge = (d: string) => `linear-gradient(${d},transparent 0,#000 ${e}px,#000 calc(100% - ${e}px),transparent 100%)`;
const m = `radial-gradient(circle at ${FACE.talk[0] + 118}px ${FACE.talk[1] + 10}px,#000 ${r.toFixed(0)}px,transparent ${(r + 520).toFixed(0)}px),${edge('90deg')},${edge('180deg')}`;
s.setProperty('-webkit-mask-image', m); s.setProperty('mask-image', m);
if (!this.maskOn) { s.setProperty('-webkit-mask-composite', 'source-in, source-in'); s.setProperty('mask-composite', 'intersect'); }
this.maskOn = true;
} else if (this.maskOn !== false) { s.setProperty('-webkit-mask-image', 'none'); s.setProperty('mask-image', 'none'); this.maskOn = false; }
// The moon is far away: it drifts less than the room and hands over between the two windows.
const mw = off ? (this.b > .5 ? 1 : 0) : smoothstep(.2, .8, this.t);
const mr = mapPoint(pose.room, [MOON.room[0], MOON.room[1]]), mt = mapPoint(pose.talk, [MOON.talk[0], MOON.talk[1]]);
const size = lerp(MOON.room[2] * pose.room.s, MOON.talk[2] * pose.talk.s, mw);
el.moon.style.transform = `translate3d(${lerp(mr[0], mt[0], mw).toFixed(1)}px,${lerp(mr[1], mt[1], mw).toFixed(1)}px,0) scale(${(size / 44).toFixed(4)})`;
// Tap target over her (only reachable while you are across the room).
const a = mapPoint(pose.room, [HER[0], HER[1]]), z = mapPoint(pose.room, [HER[2], HER[3]]);
Object.assign(el.hit.style, { left: a[0] + 'px', top: a[1] + 'px', width: (z[0] - a[0]) + 'px', height: (z[1] - a[1]) + 'px' });
this.rain.view(op);
}
// Frame loop + automatic quality tiers (average frame interval while settled).
private frame = (now: number) => {
if (!this.alive) return;
const dt = this.last ? Math.min(.12, (now - this.last) / 1000) : 0; this.last = now;
if (!this.settled) { this.step(dt); this.apply(); }
this.rain.draw(now, this.tier, motionOff(), document.hidden);
if (!this.forced && this.settled && dt && !document.hidden) {
this.samples.push(dt); if (this.samples.length > 120) this.samples.shift();
if (this.samples.length === 120) {
const avg = this.samples.reduce((x, y) => x + y) / 120;
if (avg > .026 && this.tier < 2) { this.setTier(this.tier + 1); this.samples = []; }
}
}
this.raf = requestAnimationFrame(this.frame);
};
private setTier(n: number, force = false) {
this.tier = n; this.forced = this.forced || force; document.documentElement.dataset.tier = String(n);
drawNear(this.el.near, innerWidth, innerHeight, n); this.apply();
}
}
+245 -191
View File
@@ -153,7 +153,12 @@ html[data-theme="fog"] .glass{box-shadow:inset 0 1px 0 var(--glass-hi),inset 0 0
.topbar{position:fixed;top:calc(var(--view-top) + 22px);left:32px;right:32px;display:flex;align-items:center;justify-content:space-between;z-index:30;pointer-events:none;transition:opacity var(--dur-panel)}
.topbar > *{pointer-events:auto}
.who{display:flex;align-items:center;gap:12px}
.who .name{font-size:19px;font-weight:400;letter-spacing:.14em}
.who .name{font-size:19px;font-weight:400;letter-spacing:.14em;max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.who .presence{font-size:var(--fs-meta);color:var(--text-2);letter-spacing:.04em;white-space:nowrap;text-shadow:0 1px 12px var(--pool)}
.end-talk{display:inline-flex;align-items:center;gap:7px;height:30px;padding:0 13px;border-radius:15px;background:var(--glass);border:1px solid var(--glass-line);color:var(--text-1);font-size:12px;white-space:nowrap;-webkit-backdrop-filter:blur(18px);backdrop-filter:blur(18px);transition:transform 160ms var(--ease-out);animation:chip-in 420ms var(--ease-out) 200ms both}
.end-talk:active{transform:scale(.97)}
.end-talk svg{width:14px;height:14px}
@keyframes chip-in{from{opacity:0;transform:translateY(-4px)}}
.dot{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 10px 2px var(--accent-glow);animation:dotPulse 3.6s var(--ease-drift) infinite}
body.offline .dot{background:var(--text-3);box-shadow:none;animation:none}
@keyframes dotPulse{0%,100%{opacity:.65}50%{opacity:1}}
@@ -181,69 +186,102 @@ body.creating .topbar .who,body.creating .topbar .env > :not(.theme-switch){opac
.netbar small{color:var(--text-3);font-size:12px}
/* ============================================================
她的视窗(舞台)
共同空间:一间房、一台镜头(HEL-799 对坐动态小样,获认可 01a16810)
远:她的房间与雨夜城市;中:她;近:你这一侧的桌沿、茶杯与烛灯。
两张参考静帧按她的脸对齐,镜头在两者之间推近/退回;人物不变形,也不是人物视频。
动效预算:界面反馈 160ms · 文字 420–680ms · 镜头弹簧约 0.85s · 环境循环 6–47s
============================================================ */
.portal{position:fixed;z-index:10;overflow:hidden;
--pw:clamp(300px,27vw,430px); --ph:calc(var(--pw) * 1.3);
--pl:calc(100vw - var(--pw) - 14vw); --pt:calc((100vh - var(--ph)) / 2 - 8px);
--pr:calc(var(--pw) / 2) calc(var(--pw) / 2) 26px 26px;
left:var(--pl);top:var(--pt);width:var(--pw);height:var(--ph);border-radius:var(--pr);
box-shadow:0 0 0 1px var(--glass-line),0 0 0 8px rgba(255,255,255,.025),0 40px 90px -30px rgba(0,0,10,.8),0 0 80px -20px var(--window-glow);
transition:left var(--dur-stage) var(--ease-out),top var(--dur-stage) var(--ease-out),width var(--dur-stage) var(--ease-out),height var(--dur-stage) var(--ease-out),border-radius var(--dur-stage) var(--ease-out),box-shadow var(--dur-theme),opacity var(--dur-panel),filter var(--dur-panel)}
.portal img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;transition:opacity 620ms var(--ease-in-out) 120ms,transform var(--dur-stage) var(--ease-out)}
.portal .img-room{object-position:88% 42%;transform:scale(1.16);transform-origin:80% 42%}
html.viewport-resizing .portal{transition:none}
.portal .img-talk{object-position:54% 28%;opacity:0;transform:scale(1.08);transform-origin:54% 30%}
.portal .life{position:absolute;inset:0;animation:kenburns 26s var(--ease-drift) infinite alternate}
@keyframes kenburns{from{transform:scale(1) translate3d(0,0,0)}to{transform:scale(1.045) translate3d(-1.2%,-.6%,0)}}
.portal .tint{position:absolute;inset:0;pointer-events:none;transition:background var(--dur-theme)}
html[data-theme="moon"] .portal .tint{background:linear-gradient(180deg,rgba(40,70,150,.20) 0%,rgba(10,20,50,0) 35%,rgba(8,14,40,.55) 100%)}
html[data-theme="fog"] .portal .tint{background:linear-gradient(180deg,rgba(140,90,220,.24) 0%,rgba(40,20,80,0) 40%,rgba(30,14,60,.55) 100%)}
.portal .rain{position:absolute;inset:0;pointer-events:none;opacity:.22;background-image:repeating-linear-gradient(104deg,rgba(255,255,255,.0) 0 9px,rgba(255,255,255,.35) 9px 10px,rgba(255,255,255,0) 10px 22px);background-size:220px 220px;animation:rain 1.6s linear infinite;mix-blend-mode:screen;mask-image:linear-gradient(180deg,#000 0%,rgba(0,0,0,.2) 60%,transparent 80%)}
@keyframes rain{to{background-position:-60px 220px}}
.portal .doing{position:absolute;left:18px;right:18px;bottom:16px;display:flex;align-items:center;justify-content:space-between;gap:8px;transition:opacity var(--dur-ui)}
.portal .doing .chip{background:rgba(8,10,28,.38);color:var(--text-1);border-color:rgba(255,255,255,.14)}
.portal .mark{position:absolute;right:18px;bottom:58px;font-size:10.5px;color:rgba(255,255,255,.55);letter-spacing:.06em;transition:opacity var(--dur-ui)}
.portal .close{position:absolute;top:16px;right:16px;height:36px;padding:0 14px 0 12px;border-radius:var(--radius-pill);display:flex;align-items:center;gap:6px;font-size:13px;color:var(--text-1);background:rgba(8,10,28,.36);border:1px solid rgba(255,255,255,.16);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);opacity:0;pointer-events:none;transform:translateY(-6px);transition:opacity var(--dur-ui),transform var(--dur-ui) var(--ease-out)}
.portal .close svg{width:16px;height:16px}
.portal .topleft{position:absolute;left:18px;top:16px;display:flex;flex-direction:column;align-items:flex-start;gap:8px;opacity:0;transition:opacity var(--dur-ui)}
.portal .topleft .chip{background:rgba(8,10,28,.42);color:var(--text-1);border:1px solid rgba(255,255,255,.12);-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}
.room{position:fixed;inset:0;overflow:hidden;background:#04060f;z-index:0}
.room.failed{background:transparent}
.r-cam{position:absolute;inset:0;transition:transform 1.4s var(--ease-out)}
/* Each plate box covers its whole picture (so a mask never clips it to 1600×1000); .po is the 1600×1000 design origin. */
.plate{position:absolute;will-change:transform;contain:layout style}
.plate-room{left:-640px;top:-112px;width:2240px;height:1260px;transform-origin:640px 112px}
.plate-talk{left:-118px;top:-10px;width:1792px;height:1008px;transform-origin:118px 10px;visibility:hidden}
.plate-room .po{left:640px;top:112px}.plate-talk .po{left:118px;top:10px}
.po{position:absolute;width:1600px;height:1000px}
.plate .photo{position:absolute;max-width:none;user-select:none;-webkit-user-drag:none}
.plate-room .photo{left:-640px;top:-112px;width:2240px;height:1260px;filter:saturate(.9) brightness(.8) contrast(1.05)}
.plate-talk .photo{left:-118px;top:-10px;width:1792px;height:1008px;filter:saturate(.92) brightness(.9) contrast(1.04)}
.r-tint{position:absolute;inset:0;transition:opacity .9s var(--ease-in-out)}
.r-tint i,.po>i{position:absolute;pointer-events:none;display:block}
html[data-theme="moon"] .r-tint.fog,html[data-theme="fog"] .r-tint.moon{opacity:0}
/* Her side, close: the HEL-798 still, unchanged (stage px = plate px). */
.plate-talk .r-tint .night{inset:0;mix-blend-mode:multiply}
.plate-talk .r-tint .night::before{content:"";position:absolute;left:-118px;top:-10px;width:118px;bottom:0}
.plate-talk .r-tint .night2{inset:-10px 0 0;mix-blend-mode:color;-webkit-mask:linear-gradient(90deg,#000 0 40%,transparent 56%);mask:linear-gradient(90deg,#000 0 40%,transparent 56%)}
.plate-talk .r-tint .beam{left:120px;top:40px;width:560px;height:1040px;transform:skewX(18deg);filter:blur(30px);mix-blend-mode:screen}
.plate-talk .moon .night{background:linear-gradient(100deg,#1c2f7fcc 0%,#1b2c78aa 28%,#1a2a7044 46%,transparent 60%)}
.plate-talk .moon .night::before{background:#1c2f7fcc}
.plate-talk .moon .night2{background:linear-gradient(180deg,#24357ccc 0%,#24357c66 18%,transparent 34%)}
.plate-talk .moon .beam{background:linear-gradient(180deg,#a9c8ff22,#a9c8ff10 55%,transparent)}
.plate-talk .fog .night{background:linear-gradient(100deg,#3b2a7ccc 0%,#3a2874aa 28%,#38266a44 46%,transparent 60%)}
.plate-talk .fog .night::before{background:#3b2a7ccc}
.plate-talk .fog .night2{background:linear-gradient(180deg,#5a3a92cc 0%,#5a3a9266 18%,transparent 34%)}
.plate-talk .fog .beam{background:linear-gradient(180deg,#e6c4ff1c,#e6c4ff0c 55%,transparent);transform:skewX(-8deg)}
/* Her side, far: the room still turned to the same rainy night. Coordinates are plate px. */
.plate-room .r-tint{inset:auto;left:-640px;top:-112px;width:2240px;height:1260px}
.plate-room .r-tint .night{inset:0;mix-blend-mode:multiply}
.plate-room .r-tint .night2{inset:0;mix-blend-mode:color;-webkit-mask:radial-gradient(ellipse 150px 210px at 1915px 459px,transparent 70%,#000 100%),linear-gradient(180deg,#000 0 27%,transparent 40%);mask:radial-gradient(ellipse 150px 210px at 1915px 459px,transparent 70%,#000 100%),linear-gradient(180deg,#000 0 27%,transparent 40%);-webkit-mask-composite:source-in;mask-composite:intersect}
.plate-room .moon .night{background:radial-gradient(ellipse 330px 420px at 1930px 560px,#ffffff 0 30%,#ffffff00 100%),linear-gradient(97deg,#16225cf2 0%,#1a2768e0 30%,#1c2c74b0 50%,#2a3a8a70 62%,#ffffff00 80%),linear-gradient(180deg,#00000000 50%,#1a204c66 100%)}
.plate-room .moon .night2{background:linear-gradient(180deg,#24357ce6 0%,#24357ccc 22%,#24357c55 40%)}
.plate-room .fog .night{background:radial-gradient(ellipse 330px 420px at 1930px 560px,#ffffff 0 30%,#ffffff00 100%),linear-gradient(97deg,#2c1f5ef2 0%,#32246ae0 30%,#3a2a78b0 50%,#4a3a8a70 62%,#ffffff00 80%),linear-gradient(180deg,#00000000 50%,#2a1c4c66 100%)}
.plate-room .fog .night2{background:linear-gradient(180deg,#5a3a92e6 0%,#5a3a92cc 22%,#5a3a9255 40%)}
.plate canvas.r-rain{position:absolute;left:0;top:0;width:1600px;height:1000px;pointer-events:none}
/* Weather in the window: a slow cloud veil (moon) or folding violet mist (fog). Atmosphere, not a weather report. */
.r-mist{border-radius:50%;filter:blur(38px);mix-blend-mode:screen;opacity:0;transition:opacity 1.2s var(--ease-in-out);animation:r-mist 34s var(--ease-in-out) infinite alternate}
.r-mist.m2{animation-duration:47s;animation-delay:-20s}
.plate-talk .r-mist{left:-60px;top:120px;width:560px;height:120px}.plate-talk .r-mist.m2{top:250px;left:120px;width:460px}
.plate-room .r-mist{left:660px;top:20px;width:420px;height:90px}.plate-room .r-mist.m2{top:120px;left:760px;width:360px}
html[data-theme="moon"] .r-mist{background:#b9c8ff;opacity:.07}
html[data-theme="fog"] .r-mist{background:linear-gradient(90deg,#c69cff,#ff9fd8 60%,#9cc0ff);opacity:.32}
@keyframes r-mist{from{transform:translateX(-60px) scaleY(.8)}to{transform:translateX(90px) scaleY(1.25)}}
.spill{inset:0;mix-blend-mode:screen;animation:breathe-light 9s var(--ease-in-out) infinite alternate}
.plate-talk .spill{background:radial-gradient(ellipse 520px 380px at 1290px 40px,#ffcf8a30,transparent 70%),radial-gradient(ellipse 760px 260px at 1180px 900px,#ffb97a2a,transparent 70%)}
.plate-room .spill{background:radial-gradient(ellipse 360px 300px at 1420px 150px,#ffcf8a38,transparent 70%),radial-gradient(ellipse 600px 240px at 1250px 760px,#ffb97a22,transparent 70%)}
html[data-theme="fog"] .spill{filter:hue-rotate(-28deg) saturate(1.1)}
@keyframes breathe-light{from{opacity:.75}to{opacity:1}}
.flame-glow{width:90px;height:90px;margin:-45px 0 0 -45px;border-radius:50%;background:radial-gradient(circle,#ffd9a0aa,#ffb46a44 35%,transparent 70%);mix-blend-mode:screen;animation:flicker 3.2s steps(1,end) infinite,flame 2.4s var(--ease-in-out) infinite alternate}
.flame-glow+.flame-glow{animation-delay:-1.1s,-.7s}
@keyframes flicker{0%,100%{opacity:.9}17%{opacity:.72}18%{opacity:.95}46%{opacity:.8}47%{opacity:1}79%{opacity:.78}}
@keyframes flame{to{transform:scale(1.12) translateY(-3px)}}
.mote{left:var(--x);top:var(--y);width:4px;height:4px;border-radius:50%;background:#ffe2b8;box-shadow:0 0 8px 2px #ffd59a88;opacity:0;animation:mote var(--d) linear var(--dl) infinite}
@keyframes mote{0%{transform:translate(0,0);opacity:0}15%{opacity:.7}80%{opacity:.5}100%{transform:translate(-40px,-160px);opacity:0}}
.r-moon{position:absolute;left:0;top:0;width:44px;height:44px;margin:-22px 0 0 -22px;border-radius:50%;background:radial-gradient(circle at 42% 40%,#fbfdff 0%,#e4ecff 55%,#c9d6f5 100%);filter:blur(.6px);box-shadow:0 0 22px 6px #cfe0ff88,0 0 90px 40px #8fb0ff33,0 0 220px 120px #5f7fe022;transform-origin:50% 50%;will-change:transform;transition:opacity 1s var(--ease-in-out)}
html[data-theme="fog"] .r-moon{opacity:0}
.r-vignette{position:absolute;inset:0;pointer-events:none;background:radial-gradient(ellipse 62% 74% at 54% 42%,transparent 52%,#050918aa 100%),linear-gradient(180deg,#050918aa 0%,transparent 13%)}
html[data-theme="fog"] .r-vignette{background:radial-gradient(ellipse 62% 74% at 54% 42%,transparent 52%,#0e0820aa 100%),linear-gradient(180deg,#0e0820aa 0%,transparent 13%)}
/* Your side: the table edge, a cup and a small candle. Drawn for the viewport, never stretched. */
.r-near{position:absolute;inset:0;pointer-events:none;--near-y:0px;transform:translate3d(0,var(--near-y),0);transition:transform var(--dur-space) var(--ease-space),translate 1.4s var(--ease-out),opacity var(--dur-space) var(--ease-out)}
.near-c{position:absolute;inset:0;width:100%;height:100%;transition:opacity .9s var(--ease-in-out)}
html[data-theme="moon"] .near-c[data-theme-layer="fog"],html[data-theme="fog"] .near-c[data-theme-layer="moon"]{opacity:0}
.steam{position:absolute;left:var(--steam-x);top:var(--steam-y);width:calc(var(--u) * 40px);height:calc(var(--u) * 170px);margin-left:calc(var(--u) * -20px);border-radius:50%;background:radial-gradient(ellipse at 50% 80%,#d2e1ff33,transparent 70%);filter:blur(calc(var(--u) * 9px));transform-origin:50% 100%;animation:steam 7s var(--ease-in-out) infinite}
.steam.s2{margin-left:calc(var(--u) * 14px);animation-duration:9s;animation-delay:-4s}
@keyframes steam{0%{transform:translateY(20%) scaleX(.7) skewX(0);opacity:0}30%{opacity:.9}70%{opacity:.5}100%{transform:translateY(-30%) scaleX(1.3) skewX(-14deg);opacity:0}}
.candle{position:absolute;left:var(--candle-x);top:var(--candle-y);width:calc(var(--u) * 380px);height:calc(var(--u) * 380px);margin:calc(var(--u) * -190px) 0 0 calc(var(--u) * -190px);border-radius:50%;background:radial-gradient(circle,#ffdca0cc 0,#ffbe7866 12%,#ffaa6420 40%,transparent 70%);mix-blend-mode:screen;animation:flicker 2.8s steps(1,end) infinite,flame 2s var(--ease-in-out) infinite alternate}
.r-veil{position:absolute;inset:0;background:radial-gradient(ellipse at 50% 40%,#02061433,#020614cc 90%);opacity:0;pointer-events:none;transition:opacity var(--dur-space) var(--ease-out)}
html[data-mode="pane"] .r-veil{opacity:.75}html[data-mode="record"] .r-veil{opacity:.35}
html[data-mode="home"] .r-near{--near-y:3.5vh}
html[data-mode="pane"] .r-near,html[data-mode="record"] .r-near{--near-y:7vh;opacity:.7}
/* Tap target over her, only while you are across the room. */
.her-hit{position:fixed;z-index:5;left:0;top:0;width:10px;height:10px;border-radius:40% 40% 30% 30%;display:flex;align-items:flex-start;justify-content:center}
.her-hit span{margin-top:-34px;padding:5px 12px;border-radius:14px;font-size:12px;background:var(--glass);border:1px solid var(--glass-line);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);opacity:0;transform:translateY(4px);transition:opacity var(--dur-ui) var(--ease-out),transform var(--dur-ui) var(--ease-out);pointer-events:none;white-space:nowrap}
.her-hit:focus-visible span{opacity:1;transform:none}
html:not([data-mode="home"]) .her-hit{visibility:hidden}
.room-labels{position:fixed;z-index:6;left:32px;top:calc(var(--view-top) + 72px);display:flex;flex-direction:column;align-items:flex-start;gap:8px;pointer-events:none}
.room-labels .chip{color:var(--text-1)}
.observe{display:none;max-width:min(420px,60vw);white-space:normal;height:auto !important;min-height:32px;padding:6px 14px !important;line-height:1.5}
.observe.show{display:inline-flex}
.observe .eye{width:8px;height:8px;border-radius:50%;background:var(--ok);box-shadow:0 0 8px var(--ok);flex:none}
.observe.stale{opacity:.7}
.observe.stale .eye{background:var(--warn);box-shadow:none}
.observe.fail .eye{background:var(--danger);box-shadow:none}
.observe.asking .eye{background:var(--text-3);box-shadow:none}
body.talk .portal{--pw:min(64vw, calc(var(--talk-stage-h) * 1.72)); --ph:var(--talk-stage-h); --pl:calc(50vw - var(--pw) / 2 + var(--shift)); --pt:calc(var(--view-top) + 72px); --pr:var(--radius-stage) var(--radius-stage) var(--radius-stage) var(--radius-stage)}
body.talk.voice{--talk-stage-h:clamp(64px,calc(var(--view-h) - 472px),488px)}
body{--shift:0px}
body.talk.log{--shift:-200px}
body.talk .portal .img-room{opacity:0;transform:scale(2.1);transform-origin:84% 38%}
body.talk .portal .img-talk{opacity:1;transform:scale(1)}
body.talk .portal .doing{opacity:0}
body.talk .portal .mark{bottom:18px}
body.talk .portal .close{opacity:1;pointer-events:auto;transform:none;transition-delay:280ms}
body.talk .portal .topleft{opacity:1}
body.offline .portal{filter:saturate(.55) brightness(.7)}
/* 日子 / 设置时:窗缩小留在右侧,她仍在同一个空间里 */
body.paned .portal{--pw:var(--mini-pw); --ph:calc(var(--pw) * 1.3); --pl:calc(var(--pane-l) + var(--pane-w) + (100vw - var(--pane-l) - var(--pane-w) - var(--pw)) / 2); --pt:calc(var(--pane-t) + 28px)}
body.paned .portal .doing{left:10px;right:10px;bottom:10px}
body.paned .portal .doing .tag-demo,body.paned .portal .mark{display:none}
body.paned .portal .doing .chip{height:28px;padding:0 10px;font-size:12px}
.mini-cap{position:fixed;z-index:11;left:calc(var(--pane-l) + var(--pane-w) + (100vw - var(--pane-l) - var(--pane-w) - var(--mini-pw)) / 2);top:calc(var(--pane-t) + 28px + var(--mini-pw) * 1.3 + 16px);width:var(--mini-pw);text-align:center;font-size:12.5px;color:var(--text-3);line-height:1.6;opacity:0;pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out)}
body.paned .mini-cap{opacity:1;pointer-events:auto;transition-delay:240ms}
.mini-cap b{display:block;font-weight:400;color:var(--text-2);font-size:13px}
.mini-cap button{margin-top:8px}
body.creating .portal,body.creating .window-glow{opacity:0;pointer-events:none}
.ref-note{position:fixed;z-index:6;right:40px;bottom:calc(var(--view-bottom) + 14px + var(--safe-bottom));font-size:11px;color:var(--text-3);opacity:.8;letter-spacing:.04em;pointer-events:none;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:calc(50vw - 200px);text-shadow:0 1px 8px var(--pool)}
html[data-mode="pane"] .ref-note{opacity:0}
/* ============================================================
首页
============================================================ */
.home{position:fixed;left:9vw;top:50%;width:min(440px,34vw);transform:translateY(-50%);z-index:12;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-stage) var(--ease-out),filter var(--dur-panel)}
body.talk .home,body.paned .home,body.creating .home{opacity:0;transform:translate(-40px,-50%) scale(.96);filter:blur(6px);pointer-events:none}
.home{position:fixed;left:6.5vw;top:50%;width:min(420px,32vw);transform:translateY(-44%);z-index:12;text-shadow:0 2px 18px var(--pool);animation:home-in 520ms var(--ease-out) 200ms both}
/* Back across the room: the words come back after the camera has started to retreat. */
@keyframes home-in{from{opacity:0;transform:translate(-24px,-44%);filter:blur(6px)}}
.home .letter,.home .btn-primary,.home .btn-round{text-shadow:none}
.home .eyebrow{font-size:var(--fs-meta);color:var(--text-3);letter-spacing:.2em;margin-bottom:14px}
.home .whisper{font-size:var(--fs-whisper);font-weight:300;line-height:1.5;letter-spacing:.04em;color:var(--text-1);text-wrap:balance}
.home .meta{margin-top:14px;color:var(--text-2);font-size:14px;display:flex;flex-wrap:wrap;gap:8px 14px;align-items:center}
@@ -280,9 +318,8 @@ body.welcoming .home{opacity:0;pointer-events:none;filter:blur(4px)}
.welcome .acts{display:flex;gap:10px;flex-wrap:wrap}
/* 主动消息(首页 / 区域页 中的轻提醒) */
.reach{position:fixed;z-index:24;width:min(340px,80vw);border-radius:20px 20px 20px 6px;padding:14px 16px 12px;opacity:0;transform:translateY(10px) scale(.98);pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-panel) var(--ease-out);
left:calc(100vw - clamp(300px,27vw,430px) - 14vw + 16px);width:calc(clamp(300px,27vw,430px) - 32px);bottom:calc((100vh - clamp(300px,27vw,430px) * 1.3) / 2 + 64px)}
body.paned .reach{left:auto;right:28px;bottom:104px;width:340px;border-radius:20px}
.reach{position:fixed;z-index:24;right:6vw;bottom:calc(var(--view-bottom) + 120px + var(--safe-bottom));width:min(340px,80vw);border-radius:20px 20px 6px 20px;padding:14px 16px 12px;opacity:0;transform:translateY(10px) scale(.98);pointer-events:none;transition:opacity 240ms var(--ease-out),transform 240ms var(--ease-out)}
body.paned .reach{right:28px;bottom:calc(var(--view-bottom) + 72px + var(--safe-bottom));border-radius:20px}
.reach.show{opacity:1;transform:none;pointer-events:auto}
.reach .rh{display:flex;align-items:center;gap:8px;font-size:12.5px;color:var(--text-3)}
.reach .rh b{font-weight:500;color:var(--accent)}
@@ -294,102 +331,104 @@ body.paned .reach{left:auto;right:28px;bottom:104px;width:340px;border-radius:20
.reach .acts .btn-ghost{height:36px;padding:0 14px;font-size:13px}
/* ============================================================
交流
交流:话落在你这一侧的桌面,在她的目光下方(HEL-799 / HEL-793 阅读方式)
当前一两句;长回复自动续读,可暂停、前后回看、回到读到的地方、看全文与完整记录
============================================================ */
.chat-layout{position:fixed;top:calc(var(--view-top) + 72px);height:calc(var(--view-h) - 166px - var(--safe-bottom));left:calc(50vw + var(--shift));transform:translateX(-50%);width:min(760px,74vw);z-index:12;display:flex;flex-direction:column;gap:12px;pointer-events:none}
.talk-scene-space{height:var(--talk-stage-h);flex:none}
.dialog{min-height:0;flex:1;display:flex;flex-direction:column;pointer-events:auto}
.dialog-scroll{min-height:0;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable;padding:4px 12px;overflow-anchor:none}
.dialog .you{font-size:15px;color:var(--text-2);margin:0 0 14px 12%;text-align:right}
.dialog .her{font-size:var(--fs-line);line-height:1.65;font-weight:400;color:var(--text-1);text-shadow:0 2px 18px rgba(0,0,10,.6);margin-right:8%;min-height:1.65em}
.speaker{display:block;font-size:13px;font-weight:500;letter-spacing:.1em;color:var(--accent);margin-bottom:4px}
.dialog .you .speaker{color:var(--text-2)}
.dialog .failed{color:var(--danger);font-size:13px}
.dialog .retry{color:var(--accent);font-size:13px;margin-left:6px;text-decoration:underline;text-underline-offset:3px}
.dialog .her.cut{opacity:.65}
.soft-text{display:block;position:relative;white-space:pre-wrap;overflow-wrap:anywhere}
.current-text{display:block}
.outgoing-text{position:absolute;inset:0;pointer-events:none}
.partial-note{display:block;font-size:12px;color:var(--warn);margin-top:6px}
.dialog .her .caret{display:inline-block;width:2px;height:1em;background:var(--accent);margin-left:3px;vertical-align:-2px;animation:caret 1s steps(1) infinite}
.dialog .her .dots{display:inline-flex;gap:5px;vertical-align:middle}
.dialog .her .dots i{width:6px;height:6px;border-radius:50%;background:var(--text-2);animation:dots 1.2s var(--ease-drift) infinite}
.dialog .her .dots i:nth-child(2){animation-delay:.15s}.dialog .her .dots i:nth-child(3){animation-delay:.3s}
@keyframes dots{0%,100%{opacity:.25;transform:translateY(0)}50%{opacity:1;transform:translateY(-3px)}}
@keyframes caret{50%{opacity:0}}
.dialog .hint{display:flex;align-items:center;justify-content:space-between;gap:8px;flex:none;padding:4px 12px;font-size:12px;color:var(--text-2);min-height:26px}
.dialog .hint .btn-text{white-space:nowrap;color:var(--accent)}
.composer{position:relative;flex:none;width:100%;min-height:60px;border-radius:var(--radius-pill);pointer-events:auto;display:flex;align-items:center;gap:4px;padding:0 6px}
.composer .btn-round{width:46px;height:46px}
.composer textarea{flex:1;height:46px;max-height:90px;resize:none;border:0;background:none;outline:none;padding:10px 8px;font-size:15px;color:var(--text-1);min-width:0}
.conversation{position:fixed;z-index:14;left:50%;bottom:calc(var(--view-bottom) + var(--nav-space) + var(--safe-bottom));width:min(940px,88vw);transform:translateX(-50%);display:flex;flex-direction:column;align-items:center;transition:opacity 220ms var(--ease-out);animation:talk-in 620ms var(--ease-out) 300ms both}
@keyframes talk-in{from{opacity:0;transform:translate(-50%,14px)}}
/* While a reading sheet is open she stays across the table; the table words step aside (the sheet has them all). */
html[data-mode="record"] .conversation{opacity:0;pointer-events:none}
.stage{position:relative;width:100%;height:var(--stage-h);display:flex;flex-direction:column;justify-content:flex-end;align-items:center;gap:6px;text-align:center}
.stage::before{content:"";position:absolute;left:4%;right:4%;top:0;bottom:-40%;background:radial-gradient(ellipse 50% 55% at 50% 64%,color-mix(in srgb,var(--pool) 62%,transparent),transparent 100%);pointer-events:none;z-index:-1}
.line{width:100%;display:flex;flex-direction:column;align-items:center;gap:3px}
.line .by{display:inline-flex;align-items:center;gap:7px;font-size:12px;letter-spacing:.08em;color:var(--text-2);max-width:100%}
.line .by b{font-weight:400;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:16em}
/* Identity never rests on position or colour alone: her name with a lit dot, "你" with an open ring. */
.line .by i{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 8px var(--accent);flex:none}
.line[data-role="user"] .by i{background:transparent;box-shadow:none;border:1px solid var(--user)}
.line .state{font-style:normal;color:var(--text-3);font-size:11px;letter-spacing:0}
.line p{font-size:23px;font-weight:350;line-height:1.5;letter-spacing:.02em;max-width:900px;overflow-wrap:anywhere;text-shadow:0 2px 18px var(--pool),0 0 2px color-mix(in srgb,var(--pool) 60%,transparent);color:var(--text-1)}
.line[data-role="user"] p{color:var(--user);font-size:20px;font-weight:300}
/* Previous line: tag and words on one row, quiet (HEL-798). Fixed size; the hand-off is a crossfade of two copies. */
.line.is-prev{flex-direction:row;justify-content:center;gap:10px;opacity:.6;margin-bottom:4px}
.line.is-prev p{font-size:15px;font-weight:300;color:var(--user);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:min(680px,72vw)}
.line.is-prev[data-role="companion"] p{color:var(--text-2)}
.ink span{display:inline;animation:ink 460ms var(--ease-out) both;animation-delay:calc(var(--i) * 14ms)}
@keyframes ink{from{opacity:0;filter:blur(3px)}}
.line.waiting .state::after{content:"";display:inline-block;width:18px;height:6px;margin-left:5px;background:radial-gradient(circle,var(--accent) 1.5px,transparent 2px) 0 50%/6px 6px repeat-x;animation:r-dots 1.4s linear infinite;vertical-align:middle;opacity:.8}
@keyframes r-dots{50%{opacity:.25}}
.talk-status{display:flex;align-items:center;justify-content:center;gap:10px;min-height:20px;margin-top:4px;font-size:12px;color:var(--text-2);text-shadow:0 1px 10px var(--pool);text-align:center}
.talk-status .retry{color:var(--accent);text-decoration:underline;text-underline-offset:3px}
.reader-bar{display:flex;align-items:center;justify-content:center;gap:4px;height:30px;margin:4px 0 6px;font-size:12px;color:var(--text-3)}
.reader-bar>button{height:28px;padding:0 9px;border-radius:14px;white-space:nowrap;display:inline-flex;align-items:center;gap:5px;color:var(--text-2);transition:background-color 160ms var(--ease-out),color 160ms var(--ease-out),transform 160ms var(--ease-out)}
.reader-bar>button:active:not(:disabled){transform:scale(.97)}
.reader-bar .icon{width:28px;padding:0;justify-content:center}.reader-bar svg{width:14px;height:14px}
.reader-bar .count{position:relative;min-width:72px;height:28px;display:inline-flex;align-items:center;justify-content:center;font-variant-numeric:tabular-nums;font-size:11px;color:var(--text-3)}
/* The dwell meter lives under the count: one quiet line, as in the approved still. */
.reader-bar .count::after{content:"";position:absolute;left:0;right:0;bottom:3px;height:2px;border-radius:1px;background:#ffffff1c}
.reader-bar .count i{position:absolute;left:0;right:0;bottom:3px;height:2px;border-radius:1px;background:var(--accent);box-shadow:0 0 6px var(--accent);transform-origin:left;transform:scaleX(0);z-index:1}
.reading-paused .reader-bar .count i{opacity:.3}.reading-held .reader-bar .count i{opacity:.5}
.reader-bar .flow[aria-pressed="false"]{color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent-glow)}
.reader-bar .stop{color:var(--accent)}
.reader-bar .latest{color:var(--on-accent);background:var(--accent);box-shadow:0 0 16px var(--accent-glow)}
.single-page .reader-bar .icon,.single-page .reader-bar .count span{visibility:hidden}
.composer{width:min(640px,100%);min-height:50px;border-radius:25px;display:flex;align-items:center;gap:6px;padding:0 6px 0 8px;background:linear-gradient(90deg,var(--input-a),var(--input-b) 70%,var(--input-c));border:1px solid var(--glass-line);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);box-shadow:0 10px 40px #02051466,inset 0 1px 0 #ffffff12;transition:border-color var(--dur-ui) var(--ease-out),box-shadow var(--dur-ui) var(--ease-out)}
.composer .round{width:38px;height:38px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;flex:none;color:var(--text-2);transition:transform 160ms var(--ease-out),color 160ms var(--ease-out),background-color 160ms var(--ease-out)}
.composer .round:active:not(:disabled),.composer .voice-button:active:not(:disabled){transform:scale(.97)}
.composer .round svg,.composer .voice-button svg{width:18px;height:18px}
.composer textarea{flex:1;min-width:0;resize:none;height:38px;max-height:88px;border:0;background:transparent;line-height:1.6;padding:8px 4px;outline:none;color:var(--text-1);font-size:15px}
.composer textarea::placeholder{color:var(--text-3)}
.composer .send{color:var(--text-2)}
.composer .send.ready{color:var(--accent)}
.composer .cam.on{color:var(--accent);background:var(--accent-soft)}
.composer:focus-within{border-color:var(--accent-glow);box-shadow:0 0 0 1px var(--accent-soft),0 0 30px var(--accent-soft)}
.composer .send:not(:disabled){color:var(--accent)}
.composer .cam.on,.composer .log-btn.on{color:var(--accent);background:var(--accent-soft)}
body.offline .composer .send{opacity:.4;pointer-events:none}
.mic{position:relative;width:46px;height:46px;border-radius:50%;display:grid;place-items:center;flex:none;background:var(--accent);color:var(--on-accent);box-shadow:0 0 22px -4px var(--accent-glow);transition:transform var(--dur-fast) var(--ease-out),background-color var(--dur-theme)}
.mic svg{width:20px;height:20px}
.mic .ic-stop{display:none}
.mic::after{content:"";position:absolute;inset:-6px;border-radius:50%;border:1.5px solid var(--accent);opacity:0}
body.voice .mic .ic-mic{display:none}
body.voice .mic .ic-stop{display:block}
body.v-listen .mic::after{animation:ring 1.4s var(--ease-out) infinite}
.mic.denied{background:rgba(255,255,255,.08);color:var(--text-3);box-shadow:none}
.mic .slash{position:absolute;width:26px;height:2px;background:var(--danger);transform:rotate(-45deg);display:none;border-radius:1px}
.mic.denied .slash{display:block}
@keyframes ring{from{opacity:.8;transform:scale(.9)}to{opacity:0;transform:scale(1.35)}}
.wave{display:flex;align-items:center;gap:3px;height:20px}
.wave i{width:3px;height:10px;border-radius:2px;background:currentColor;animation:wave 1s var(--ease-drift) infinite}
.wave i:nth-child(2){animation-delay:.15s}.wave i:nth-child(3){animation-delay:.3s}.wave i:nth-child(4){animation-delay:.45s}
@keyframes wave{0%,100%{height:5px}50%{height:18px}}
.wave.still i{animation:none;height:4px}
.voice-button{width:38px;height:38px;border-radius:50%;display:grid;place-items:center;background:var(--accent);color:var(--on-accent);box-shadow:0 0 18px var(--accent-glow);flex:none;transition:transform 160ms var(--ease-out),background-color var(--dur-theme)}
.voice-button.denied{background:rgba(255,255,255,.08);color:var(--text-3);box-shadow:none}
.voice-row{display:flex;align-items:center;justify-content:center;gap:12px;font-size:12px;color:var(--text-2);margin-bottom:6px;text-shadow:0 1px 10px var(--pool)}.voice-row button{color:var(--accent);padding:4px 2px}
.voice-wave{display:inline-flex;gap:3px;align-items:center;height:14px}.voice-wave i{width:2px;height:100%;background:var(--accent);border-radius:2px;animation:r-wave 1.1s var(--ease-in-out) infinite}.voice-wave i:nth-child(2){animation-delay:.15s}.voice-wave i:nth-child(3){animation-delay:.3s}.voice-wave i:nth-child(4){animation-delay:.45s}
@keyframes r-wave{50%{transform:scaleY(.3)}}
/* 语音会话条:会话中始终可见「结束语音」 */
.voicebar{position:relative;flex:none;min-height:48px;padding:0 6px 0 16px;border-radius:var(--radius-pill);display:flex;align-items:center;gap:12px;font-size:13.5px;pointer-events:auto}
.voicebar .live{display:flex;align-items:center;gap:8px;color:var(--text-2);font-family:var(--font-num)}
.voicebar .live i{width:8px;height:8px;border-radius:50%;background:var(--danger);box-shadow:0 0 8px var(--danger);animation:dotPulse 1.6s infinite}
.voicebar .vstate{display:flex;align-items:center;gap:8px;color:var(--text-1);min-width:120px}
.voicebar .vstate .wave{color:var(--accent);height:16px}
.voicebar .btn-ghost{height:36px;padding:0 14px;font-size:13px}
.voicebar .end{height:36px;padding:0 16px;border-radius:var(--radius-pill);background:rgba(255,159,179,.14);color:var(--danger);font-size:13px;display:inline-flex;align-items:center;gap:6px}
.voicebar .end svg{width:12px;height:12px}
/* 完整聊天记录 */
.log-panel{position:fixed;right:24px;top:calc(var(--view-top) + 72px);bottom:calc(var(--view-bottom) + 98px + var(--safe-bottom));width:380px;border-radius:24px;z-index:20;display:flex;flex-direction:column;opacity:0;transform:translateX(36px);pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-panel) var(--ease-out),background-color var(--dur-theme)}
body.log .log-panel{opacity:1;transform:none;pointer-events:auto}
.log-panel header{display:flex;align-items:center;justify-content:space-between;padding:18px 18px 10px 22px}
.log-panel header h2{font-size:16px;font-weight:500;letter-spacing:.08em}
.log-panel .scroll{flex:1;overflow:auto;padding:4px 22px 20px;scrollbar-width:thin}
.day{font-size:var(--fs-tiny);color:var(--text-3);text-align:center;margin:12px 0 8px;letter-spacing:.12em}
.msg{margin:10px 0;max-width:88%;scroll-margin:80px}
.msg .who-l{font-size:var(--fs-tiny);color:var(--text-3);margin-bottom:3px}
.msg p{white-space:pre-wrap;font-size:14.5px;line-height:1.7;padding:9px 14px;border-radius:16px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.06);transition:box-shadow var(--dur-panel),border-color var(--dur-panel)}
.msg.me{margin-left:auto;text-align:right}
.msg.me p{background:var(--accent-soft);border-color:transparent;text-align:left;display:inline-block}
.msg.fail p{border:1px dashed var(--danger);background:transparent}
.msg .tagm{font-size:10.5px;color:var(--text-3);margin-left:6px}
.msg .tagm.proactive{color:var(--accent)}
.msg.hl p{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-soft)}
.msg .basis{font-size:11px;color:var(--text-3);margin-top:4px}
.log-btn.on{color:var(--accent);background:var(--accent-soft)}
/* 完整记录与全文:房间里的阅读面,她仍在桌对面;不是模态框,导航始终可以直接切换 */
.record{position:fixed;z-index:20;top:calc(var(--view-top) + 84px);left:4vw;width:min(470px,36vw);height:calc(var(--view-h) - 150px - var(--safe-bottom));border-radius:26px;display:flex;flex-direction:column;overflow:hidden;box-shadow:0 25px 100px #02041270,inset 0 1px 0 #ffffff10;animation:sheet-in 240ms var(--ease-out)}
.record.full{z-index:21}
@keyframes sheet-in{from{opacity:0;transform:translateY(12px) scale(.985)}}
.record header{display:flex;justify-content:space-between;align-items:center;gap:20px;padding:20px 22px 14px 26px;border-bottom:1px solid var(--glass-line);flex:none}
.record header .eyebrow{font-size:11px;letter-spacing:.18em;color:var(--text-3);margin-bottom:3px}
.record header h2{font-size:20px;font-weight:350;letter-spacing:.04em}
.record .scroll{flex:1;min-height:0;overflow:auto;overscroll-behavior:contain;padding:18px 26px 32px;scrollbar-gutter:stable;line-height:1.9}
.record .guide{font-size:13px;color:var(--text-2);margin-bottom:8px}
.record .message{padding:14px 0;border-bottom:1px solid var(--glass-line);scroll-margin:80px}
.record .message .author{display:flex;align-items:center;gap:7px;color:var(--accent);font-size:12px;margin-bottom:6px;overflow-wrap:anywhere}
.record .message .author i{width:7px;height:7px;border-radius:50%;background:var(--accent);box-shadow:0 0 8px var(--accent);flex:none}
.record .message[data-role="user"] .author{color:var(--text-2)}.record .message[data-role="user"] .author i{background:none;box-shadow:none;border:1px solid var(--user)}
.record .message p{font-size:15px;white-space:pre-wrap;overflow-wrap:anywhere}
.record .message .incomplete{display:block;font-size:12px;color:var(--warn)}
.record .message .tagm{font-size:10.5px;color:var(--accent);margin-left:6px}
.record .message.fail p{color:var(--text-2)}
.record .message.hl{box-shadow:inset 3px 0 0 var(--accent);padding-left:12px}
/* ============================================================
底部导航
底部导航:小巧、透光,选中处亮起微光(HEL-799)
============================================================ */
.nav{position:fixed;left:50%;bottom:calc(var(--view-bottom) + 22px + var(--safe-bottom));transform:translateX(-50%);height:60px;padding:6px;border-radius:var(--radius-pill);display:flex;gap:2px;z-index:25;transition:opacity var(--dur-panel),transform var(--dur-panel) var(--ease-out)}
.nav{position:fixed;left:50%;bottom:calc(var(--view-bottom) + 6px + var(--safe-bottom));transform:translateX(-50%);display:flex;gap:4px;padding:3px;border-radius:17px;z-index:25;background:color-mix(in srgb,var(--surface) 40%,transparent);transition:transform 420ms var(--ease-out),opacity 280ms var(--ease-out)}
body.creating .nav{opacity:0;pointer-events:none;transform:translate(-50%,20px)}
.nav-item{position:relative;width:76px;height:48px;border-radius:var(--radius-pill);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px;font-size:11.5px;color:var(--text-2);letter-spacing:.08em;transition:color var(--dur-ui),background-color var(--dur-ui),transform var(--dur-fast) var(--ease-out)}
.nav-item svg{width:19px;height:19px}
.nav-item[aria-current="page"]{color:var(--text-1);background:var(--accent-soft)}
.nav-item[aria-current="page"] svg{color:var(--accent);filter:drop-shadow(0 0 6px var(--accent-glow))}
.nav-item .badge{position:absolute;top:6px;right:20px;width:6px;height:6px;border-radius:50%;background:var(--accent);box-shadow:0 0 8px var(--accent-glow);display:none}
.nav-item{position:relative;width:64px;height:26px;border-radius:13px;display:inline-flex;align-items:center;justify-content:center;gap:6px;font-size:12px;letter-spacing:.04em;color:var(--text-3);transition:color 160ms var(--ease-out),background-color 160ms var(--ease-out),box-shadow 160ms var(--ease-out),transform 160ms var(--ease-out)}
.nav-item svg{width:14px;height:14px}
.nav-item[aria-current="page"]{color:var(--text-1);background:var(--accent-soft);box-shadow:0 0 14px var(--accent-glow)}
.nav-item[aria-current="page"] svg{color:var(--accent)}
.nav-item .badge{position:absolute;top:3px;right:8px;width:6px;height:6px;border-radius:50%;background:var(--accent);box-shadow:0 0 8px var(--accent-glow);display:none}
.nav-item.unread .badge{display:block}
@media(hover:hover) and (pointer:fine){.nav-item:hover:not([aria-current="page"]),.reader-bar>button:hover:not(:disabled){background:#ffffff0d;color:var(--text-1)}.her-hit{cursor:pointer}.her-hit:hover span{opacity:1;transform:none}}
/* ============================================================
区域面板:日子 / 设置(同一主题空间里升起的阅读面)
============================================================ */
.pane{position:fixed;z-index:16;left:var(--pane-l);top:calc(var(--view-top) + var(--pane-t));bottom:calc(var(--view-bottom) + var(--pane-b) + var(--safe-bottom));width:var(--pane-w);border-radius:28px;display:flex;flex-direction:column;overflow:hidden;opacity:0;transform:translateY(24px) scale(.985);pointer-events:none;transition:opacity var(--dur-panel) var(--ease-out),transform var(--dur-panel) var(--ease-out),background-color var(--dur-theme)}
.pane.open{opacity:1;transform:none;pointer-events:auto;transition-delay:80ms}
.pane{position:fixed;z-index:16;left:var(--pane-l);top:calc(var(--view-top) + var(--pane-t));bottom:calc(var(--view-bottom) + var(--pane-b) + var(--safe-bottom));width:var(--pane-w);border-radius:28px;display:flex;flex-direction:column;overflow:hidden;opacity:0;pointer-events:none;transition:background-color var(--dur-theme)}
/* Ordinary panels switch quickly; only the room itself keeps the slow spatial move. */
.pane.open{opacity:1;pointer-events:auto;animation:pane-in 240ms var(--ease-out)}
@keyframes pane-in{from{opacity:0;transform:translateY(12px) scale(.99)}}
.pane > header{display:flex;align-items:center;gap:16px;padding:18px 18px 14px 28px;border-bottom:1px solid rgba(255,255,255,.06);flex:none}
.pane > header h2{font-size:var(--fs-title);font-weight:400;letter-spacing:.1em;white-space:nowrap}
.pane > header .grow{flex:1}
@@ -630,59 +669,50 @@ body.creating .create{opacity:1;pointer-events:auto}
.netbar{top:56px;max-width:calc(100vw - 24px);font-size:12.5px}
.netbar small{display:none}
body{--home-pw:min(74vw,330px,max(120px,calc((var(--view-h) - 340px) / 1.22)))}
.portal{--pw:var(--home-pw); --ph:calc(var(--pw) * 1.22); --pl:calc(50vw - var(--pw) / 2); --pt:70px}
body.talk{--talk-stage-h:clamp(64px,calc((var(--view-h) - 360px) * .55),300px)}
body.talk .portal{--pw:calc(100vw - 24px); --ph:var(--talk-stage-h); --pl:12px; --pt:calc(var(--view-top) + 58px)}
body.talk.voice{--talk-stage-h:clamp(48px,calc((var(--view-h) - 412px) * .5),250px)}
body.talk.log{--shift:0px}
body.paned .portal{opacity:0;pointer-events:none;--pw:min(74vw,330px); --ph:calc(var(--pw) * 1.22); --pl:calc(50vw - var(--pw) / 2); --pt:70px}
.mini-cap{display:none}
.portal .doing{left:12px;right:12px;bottom:12px}
.portal .doing .tag-demo{display:none}
.portal .mark{right:14px;bottom:50px}
.observe{max-width:calc(100vw - 80px)}
:root{--stage-h:132px;--nav-space:60px}
.r-vignette,html[data-theme="fog"] .r-vignette{background:radial-gradient(ellipse 95% 70% at 55% 38%,transparent 55%,color-mix(in srgb,var(--bg-0) 66%,transparent) 100%),linear-gradient(180deg,color-mix(in srgb,var(--bg-0) 66%,transparent) 0%,transparent 10%)}
.who .presence{display:none}
.who .name{max-width:96px}
.end-talk{width:28px;height:28px;padding:0;justify-content:center}
.end-talk span{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}
.room-labels{left:14px;top:calc(var(--view-top) + 52px)}
.ref-note{top:calc(var(--view-top) + 50px);right:14px;bottom:auto;font-size:10px;opacity:.65;max-width:calc(100vw - 28px)}
.home{left:22px;right:22px;width:auto;top:calc(var(--view-top) + 70px + var(--home-pw) * 1.22 + 22px);max-height:calc(var(--view-h) - 70px - var(--home-pw) * 1.22 - 106px - var(--safe-bottom));overflow:auto;transform:none}
body.talk .home,body.paned .home,body.creating .home{transform:translateY(20px) scale(.97)}
.home .eyebrow,.home .meta{display:none}
.letter{margin-top:14px;padding:14px 16px 12px}
.letter p{font-size:14px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.away{margin-top:8px;font-size:13px}
.cta{position:static;margin-top:16px}
.cta .btn-primary{flex:1;height:50px}
.cta .btn-round{width:50px;height:50px}
.first-note{font-size:13px}
.home{left:20px;right:20px;top:auto;bottom:calc(var(--view-bottom) + var(--nav-space) + 6px + var(--safe-bottom));width:auto;transform:none;max-height:calc(var(--view-h) - 140px);overflow:auto;animation-name:home-in-phone}
@keyframes home-in-phone{from{opacity:0;transform:translateY(16px)}}
.home .eyebrow{margin-bottom:8px}
.home .whisper{line-height:1.55}
.home .meta{display:none}
.letter{margin-top:14px;padding:12px 15px 10px;border-radius:18px}
.letter p{font-size:13px;line-height:1.7}
.away{margin-top:8px;font-size:12px}
.cta{position:static;margin-top:10px}
.cta .btn-primary{flex:1;height:46px}
.cta .btn-round{width:46px;height:46px}
.first-note{font-size:13px;margin-top:12px}
.welcome{left:12px;right:12px;width:auto;top:auto;bottom:90px;transform:translateY(20px);max-height:calc(100vh - 160px);overflow:auto;padding:22px 20px 18px;background:var(--glass-solid)}
body.welcoming .welcome{transform:none}
.welcome li{grid-template-columns:64px 1fr}
.reach{left:12px;right:12px;width:auto;bottom:164px;border-radius:20px}
body.paned .reach{left:12px;right:12px;bottom:96px}
.reach{left:12px;right:12px;width:auto;bottom:calc(var(--view-bottom) + 300px + var(--safe-bottom));border-radius:20px}
body.paned .reach{left:12px;right:12px;bottom:calc(var(--view-bottom) + 72px + var(--safe-bottom))}
.chat-layout{left:50vw;top:calc(var(--view-top) + 58px);height:calc(var(--view-h) - 142px - var(--safe-bottom));width:calc(100vw - 24px);gap:8px}
.dialog .her{font-size:17px}
.composer{min-height:56px}
.composer .btn-round{width:40px;height:40px}
.composer .btn-round svg{width:19px;height:19px}
.mic{width:42px;height:42px}
.voicebar{gap:8px;padding:0 6px 0 12px}
.voicebar .vstate{min-width:0;flex:1;font-size:13px}
.voicebar .live span,.voicebar .vstate .wave{display:none}
.voicebar .vstate{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block}
.conversation{width:calc(100% - 20px)}
.line p{font-size:18px;line-height:1.55}.line[data-role="user"] p{font-size:16px}.line.is-prev p{font-size:13px;max-width:70vw}
.reader-bar{gap:0;margin:2px 0 6px;font-size:11px}.reader-bar>button{padding:0 7px;height:34px}.reader-bar .icon{width:34px}.reader-bar .count{min-width:56px}
.reader-bar .latest span{max-width:9em;overflow:hidden;text-overflow:ellipsis}
.composer{min-height:48px;padding:0 4px}.composer textarea{font-size:16px}
.composer .round{width:36px;height:36px}
.nav{bottom:calc(var(--view-bottom) + 16px + var(--safe-bottom));height:58px;width:calc(100vw - 24px);justify-content:space-between}
.nav-item{flex:1;width:auto}
.nav-item .badge{right:calc(50% - 18px)}
.nav{padding:3px}
.nav-item{width:70px;height:40px}
.log-panel{left:0;right:0;top:calc(var(--view-top) + 54px);bottom:calc(var(--view-bottom) + 84px + var(--safe-bottom));width:auto;height:auto;border-radius:26px 26px 0 0;z-index:45;transform:translateY(100%);opacity:1}
body.log .log-panel{transform:none}
.log-panel,.pane,.wiz,.modal{background:var(--glass-solid)}
.window-glow{display:none}
body.talk .moon-disc,body.talk .moon-halo{opacity:0}
.record,.record.full{left:10px;right:10px;width:auto;top:calc(var(--view-top) + 60px);height:calc(var(--view-h) - 128px - var(--safe-bottom));border-radius:22px;background:var(--glass-solid)}
.record header{padding:14px 18px 12px}.record .scroll{padding:14px 18px 26px}
.pane,.wiz,.modal{background:var(--glass-solid)}
/* 区域面板 → 全屏层;列表与详情改为推入 */
.pane{left:8px;right:8px;width:auto;top:calc(var(--view-top) + 54px);bottom:calc(var(--view-bottom) + 84px + var(--safe-bottom));border-radius:24px}
.pane{left:8px;right:8px;width:auto;top:calc(var(--view-top) + 54px);bottom:calc(var(--view-bottom) + 60px + var(--safe-bottom));border-radius:24px}
.pane > header{flex-wrap:wrap;gap:10px;padding:14px 14px 12px 18px}
.pane > header h2{font-size:18px}
.pane > header .tabs{order:3;width:100%;margin:0;display:flex}
@@ -728,22 +758,46 @@ body.creating .create{opacity:1;pointer-events:auto}
}
@media (max-width:1100px) and (min-width:721px){
:root{--pane-w:calc(100vw - 10vw); --mini-pw:0px}
body.paned .portal{opacity:0;pointer-events:none}
.mini-cap{display:none}
.pane .presence{display:flex}
.pane .cols{grid-template-columns:340px 1fr}
.pane-manage .cols{grid-template-columns:200px 1fr}
.home{width:min(400px,40vw)}
.env .weather{display:none}
.ref-note{top:calc(var(--view-top) + 64px);right:32px;bottom:auto;max-width:calc(100vw - 64px)}
.record,.record.full{width:min(440px,52vw)}
}
/* ============================================================
减少动效 / 隐藏页暂停
============================================================ */
html.reduced *, html.reduced *::before, html.reduced *::after{animation:none !important}
html.reduced .portal, html.reduced .portal img, html.reduced .space, html.reduced .home, html.reduced .dialog, html.reduced .composer, html.reduced .log-panel, html.reduced .pane, html.reduced .pane .detail, html.reduced .welcome, html.reduced .reach, html.reduced .modal, html.reduced .voicebar, html.reduced .create{transition-duration:200ms !important;transition-delay:0ms !important}
html.reduced .space, html.reduced .home, html.reduced .conversation, html.reduced .record, html.reduced .pane, html.reduced .pane .detail, html.reduced .welcome, html.reduced .reach, html.reduced .modal, html.reduced .create, html.reduced .nav{transition-duration:200ms !important;transition-delay:0ms !important}
/* Reduced motion: the camera no longer travels; the two stills crossfade at rest and the rain stays one frame. */
html.reduced .r-cam, html.reduced .r-near, html.reduced .r-veil, html.reduced .r-tint, html.reduced .near-c, html.reduced .r-moon{transition:opacity 200ms linear !important}
html.reduced body.talk .space, html.reduced body.paned .space{transform:none}
html.reduced .k.now{box-shadow:0 0 10px var(--accent-glow)}
html.reduced .wave i{height:8px}
html.paused *, html.paused *::before, html.paused *::after{animation-play-state:paused !important}
/* Keyboard shortcuts (snap): land on the target state with no transition; ambient loops keep running. */
html.snap *, html.snap *::before, html.snap *::after{transition:none !important}
/* Short visual viewport = keyboard open or a squat window. Her face yields first, the words never do. */
html.compact{--stage-h:78px;--nav-space:54px}
html.compact .topbar{top:calc(var(--view-top) + 10px)}
html.compact .ref-note,html.compact .who .presence,html.compact .env .weather{display:none}
html.compact .line.is-prev{display:none}
html.compact .line p{font-size:16px;line-height:1.55}
html.compact .reader-bar{margin:0 0 4px}
html.compact .nav-item{height:36px}
html.compact .record{top:calc(var(--view-top) + 48px);height:calc(var(--view-h) - 104px - var(--safe-bottom))}
html.compact.typing{--nav-space:6px}
html.compact.typing[data-mode="talk"] .nav{transform:translate(-50%,150%);opacity:0;pointer-events:none}
html.compact .home .eyebrow,html.compact .home .meta,html.compact .home .away,html.compact .home .letter p,html.compact .home .first-note,html.compact .home .demo-label{display:none}
html.compact .home .whisper{font-size:18px}
html.compact .letter{margin-top:6px;padding:7px 12px}
html.micro .reader-bar .count,html.micro .reader-bar .read-all,html.micro .talk-status{display:none}
html.micro .home .letter{display:none}
/* Tier 2 (slow device, measured): no backdrop blur, the most expensive compositor effect; no per-frame mask. */
html[data-tier="2"] .glass,html[data-tier="2"] .composer,html[data-tier="2"] .nav,html[data-tier="2"] .record{-webkit-backdrop-filter:none;backdrop-filter:none;background:var(--glass-read)}
html[data-tier="2"] .mote,html[data-tier="2"] .r-mist{display:none}
[hidden]{display:none!important}
p,button,h1,h2,h3,dd{overflow-wrap:anywhere}
@@ -762,4 +816,4 @@ body:has(textarea:focus) .space *{animation-play-state:paused!important}
.color-sections h4{color:var(--text-1);margin-bottom:8px}
.birth-help, .color-sections details{font-size:13px;color:var(--text-2);margin-top:10px}
.birth-help summary, .color-sections summary{cursor:pointer;color:var(--accent)}
@media(max-height:480px){body.talk{--talk-stage-h:40px}body.talk .portal .mark,body.talk .portal .topleft{display:none}.create .story p,.create .story .single{display:none}.create .story{padding-bottom:4px}.create .story h1{font-size:18px}}
@media(max-height:480px){.create .story p,.create .story .single{display:none}.create .story{padding-bottom:4px}.create .story h1{font-size:18px}}
+8 -2
View File
@@ -7,7 +7,8 @@
:root{
--view-h:100vh; --view-top:0px; --view-bottom:0px;
--safe-bottom:env(safe-area-inset-bottom,0px);
--talk-stage-h:clamp(64px,calc(var(--view-h) - 420px),540px);
/* HEL-799 shared room (approved 01a16810): words on your side of the table, small navigation under everything. */
--stage-h:128px; --nav-space:52px;
--font-sans: "PingFang SC","HarmonyOS Sans SC","MiSans","Microsoft YaHei UI","Microsoft YaHei","Noto Sans SC",system-ui,sans-serif;
--font-num: "SF Pro Display","Segoe UI Variable Display","Segoe UI",var(--font-sans);
@@ -18,10 +19,13 @@
--ease-out: cubic-bezier(.22,1,.36,1);
--ease-in-out: cubic-bezier(.65,0,.35,1);
--ease-drift: cubic-bezier(.45,.05,.55,.95);
--ease-space: cubic-bezier(.65,0,.25,1);
--dur-fast: 160ms; --dur-ui: 280ms; --dur-panel: 420ms; --dur-stage: 720ms; --dur-theme: 1100ms;
/* Camera spring settles in ≈0.85s (roomScene.ts SPRING_W); near layer and veil follow it. */
--dur-space: 850ms;
/* 区域面板(日子 / 设置)几何:电脑 */
--pane-l: 5vw; --pane-w: min(1000px, 66vw); --pane-t: 84px; --pane-b: 104px;
--pane-l: 5vw; --pane-w: min(1000px, 66vw); --pane-t: 84px; --pane-b: 56px;
--mini-pw: clamp(170px, 14vw, 230px);
}
html[data-theme="moon"]{
@@ -34,6 +38,7 @@ html[data-theme="moon"]{
--window-glow:rgba(255,196,140,.20);
--scroll-track:#0d1838; --scroll-thumb:#51678d; --scroll-hover:#a9dcff;
--ok:#9fe8cf; --warn:#ffd79c; --danger:#ff9fb3;
--pool:#050918; --user:#d7e2ff; --input-a:#16244e70; --input-b:#1c264c70; --input-c:#3a2c3a60;
}
html[data-theme="fog"]{
--bg-0:#110b26; --bg-1:#22174a; --bg-2:#43307a;
@@ -45,4 +50,5 @@ html[data-theme="fog"]{
--window-glow:rgba(255,170,190,.22);
--scroll-track:#22174a; --scroll-thumb:#806298; --scroll-hover:#ebbcff;
--ok:#a8f0d8; --warn:#ffdcae; --danger:#ffa8c8;
--pool:#0e0820; --user:#f1e2ff; --input-a:#3a245e70; --input-b:#3a265470; --input-c:#5a2c5260;
}