SPB Git

Repository Public

Viewer.tsx 26.8 KB 415 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : apps/navigator-web/src/viewer/Viewer.tsx9 * Module           : viewer10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Screen B — interactive view of the real remote Chromium.43// Watching is always possible; inputs leave this page only while this user holds the control lease.44import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent, type MouseEvent } from 'react';45import { get, post, type Me } from '../../../shared/api.ts';46import { hasKey, tCode, useLang, useT, type Key } from '../i18n.ts';47import { IcoBack, IcoClose, IcoExitFullscreen, IcoFit, IcoForward, IcoFullscreen, IcoGo, IcoKeyboard, IcoMinus, IcoMore, IcoPanel, IcoPlus, IcoReload, IcoResetZoom } from '../icons.tsx';48import { saveFit, storedFit } from '../prefs.ts';49import { EmergencyBanner, EmergencyControl } from '../screens/Emergency.tsx';50import type { NavPolicy, RemoteTab, ServerMsg, SessionList, SessionRow, SessionState, ViewerMsg } from '../types.ts';51import { ErrorLine, IconBtn, StateBadge, usePoll } from '../ui.tsx';52import { Stage, type StageHandle } from './Canvas.tsx';53import { NavConnection, type ConnState } from './connection.ts';54import { IDENTITY, InputController, type View } from './input.ts';55import { AssistPanel, ConfirmPanel } from './Panels.tsx';5657type Vars = Record<string, string | number>;58type Notice = { id: number; tone: 'info' | 'warn' | 'error'; sig: string; n: number } & ({ key: Key; vars?: Vars } | { error: unknown });59type Lease = { mine: boolean; holderKind: string | null; reason?: string };60type Mode = 'emergency' | 'control' | 'challenge' | 'agent' | 'readonly';61const PRIVACY_STATES: SessionState[] = ['LOGIN_REQUIRED', 'MANUAL_CONTROL', 'SECURITY_CHALLENGE'];62const FIXED = { w: 1280, h: 800 };63const clampInt = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, Math.round(v)));64const hostOf = (u: string) => { try { return new URL(u).host; } catch { return u; } };6566export function Viewer({ sessionId, me, navigate, refreshMe }: { sessionId: string; me: Me; navigate: (to: string) => void; refreshMe: () => Promise<void> }) {67  const t = useT(); const { lang, setLang } = useLang();6869  /* ── What the gateway told us ── */70  const [conn, setConn] = useState<{ s: ConnState; retry?: number }>({ s: 'connecting' });71  const [state, setState] = useState<SessionState | null>(null);72  const [lease, setLease] = useState<Lease>({ mine: false, holderKind: null });73  const [workerOnline, setWorkerOnline] = useState<boolean | null>(null);74  const [emergency, setEmergency] = useState(me.emergency.emergency_stop);75  const [policy, setPolicy] = useState<NavPolicy>({ clipboard: false, insertApprovedText: false });76  const [tabs, setTabs] = useState<RemoteTab[]>([]);77  const [loc, setLoc] = useState({ url: '', title: '' });78  const [chooser, setChooser] = useState({ open: false, multiple: false });79  const [cursor, setCursor] = useState('default');80  const [rtt, setRtt] = useState<number | null>(null);81  const [frame, setFrame] = useState<{ w: number; h: number } | null>(null);82  /* ── What the API told us (the gateway is not told about every state change) ── */83  const [session, setSession] = useState<SessionRow | null | undefined>(undefined);84  /* ── Local UI ── */85  const [notices, setNotices] = useState<Notice[]>([]);86  const [view, setView] = useState<View>(IDENTITY);87  const [kb, setKb] = useState(false);88  const [fit, setFit] = useState(storedFit);89  const [fs, setFs] = useState(false);90  const [immersive, setImmersive] = useState(false);91  const [side, setSide] = useState(false);92  const [more, setMore] = useState(false);93  const [zoom, setZoom] = useState(1);94  const [addr, setAddr] = useState('');95  const [busy, setBusy] = useState<string | null>(null);96  const [denied, setDenied] = useState(0);97  const [stageSize, setStageSize] = useState({ w: 0, h: 0 });98  const [selectedJob, setSelectedJob] = useState<string | null>(null);99  const [jobIds, setJobIds] = useState<string[]>([]);100  const [assistKey, setAssistKey] = useState(0);101102  // Read synchronously by the input handlers: React state would lag one render behind a lost lease.103  const live = useRef({ mine: false, open: false, emergency: me.emergency.emergency_stop, clipboard: false, frame: null as { w: number; h: number } | null, wsStateAt: 0 });104  const connRef = useRef<NavConnection | null>(null);105  const stageRef = useRef<StageHandle>(null);106  const inputRef = useRef<InputController | null>(null);107  const rootRef = useRef<HTMLDivElement>(null);108  const takeRef = useRef<HTMLButtonElement>(null);109  const lastResize = useRef('');110  const seq = useRef(0);111112  const notify = useCallback((tone: Notice['tone'], what: { key: Key; vars?: Vars } | { error: unknown }) => {113    const sig = 'key' in what ? `${what.key}|${JSON.stringify(what.vars ?? {})}` : `e|${what.error instanceof Error ? what.error.message : String(what.error)}`;114    setNotices((list) => {115      const hit = list.find((x) => x.sig === sig);116      if (hit) return list.map((x) => (x === hit ? { ...x, n: x.n + 1 } : x));117      return [...list.slice(-3), { id: ++seq.current, tone, sig, n: 1, ...what }];118    });119  }, []);120  const dismiss = (id: number) => setNotices((l) => l.filter((x) => x.id !== id));121122  const applyLease = useCallback((l: Lease) => {123    live.current.mine = l.mine;124    if (!l.mine) { inputRef.current?.dropAll(); lastResize.current = ''; }125    setLease(l);126  }, []);127128  const onMessage = (m: ServerMsg) => {129    switch (m.t) {130      case 'hello':131        live.current.wsStateAt = Date.now(); live.current.emergency = m.emergencyStop; live.current.clipboard = !!m.policy?.clipboard;132        setState(m.state); setWorkerOnline(m.workerOnline); setEmergency(m.emergencyStop);133        setPolicy({ clipboard: !!m.policy?.clipboard, insertApprovedText: !!m.policy?.insertApprovedText });134        { const mine = !!m.lease?.mine; live.current.mine = mine; if (!mine) inputRef.current?.dropAll(); lastResize.current = ''; setLease((p) => ({ mine, holderKind: m.lease?.holderKind ?? null, reason: mine ? undefined : p.reason })); }135        break;136      case 'state': live.current.wsStateAt = Date.now(); setState(m.state); setAssistKey((k) => k + 1); break;137      case 'lease': applyLease({ mine: !!m.mine, holderKind: m.holderKind ?? null, reason: m.mine ? undefined : m.reason ?? (live.current.mine ? (m.holderKind ? 'taken' : 'released') : undefined) }); break;138      case 'tabs': setTabs(Array.isArray(m.tabs) ? m.tabs : []); break;139      case 'url': setLoc({ url: String(m.url ?? ''), title: String(m.title ?? '') }); break;140      case 'chooser': setChooser({ open: !!m.open, multiple: !!m.multiple }); if (m.open) setSide(true); break;141      case 'blocked': notify('warn', { key: hasKey(`blocked.${m.reason}`) ? (`blocked.${m.reason}` as Key) : 'blocked._', vars: { code: m.reason, url: m.url ? hostOf(m.url) : '' } }); break;142      case 'cursor': setCursor(String(m.css ?? 'default')); break;143      case 'status': setWorkerOnline(!!m.workerOnline); if (!m.workerOnline) { live.current.frame = null; setFrame(null); } break;144      case 'notice': notify('info', { key: hasKey(`notice.${m.code}`) ? (`notice.${m.code}` as Key) : 'notice._', vars: { code: m.code, message: m.message ?? '' } }); break;145      case 'emergency': live.current.emergency = !!m.engaged; setEmergency(!!m.engaged); if (m.engaged) inputRef.current?.dropAll(); void refreshMe(); break;146      case 'job': setAssistKey((k) => k + 1); break;147      case 'assisted': notify('info', { key: m.kind === 'text' ? 'assisted.text' : m.kind === 'media' ? 'assisted.media' : 'assisted._', vars: { kind: m.kind } }); break;148      case 'error':149        if (m.code === 'no_control' && live.current.mine) applyLease({ mine: false, holderKind: null, reason: 'no_control' });150        notify('error', { key: hasKey(`wserr.${m.code}`) ? (`wserr.${m.code}` as Key) : 'wserr._', vars: { code: m.code } });151        break;152      case 'pong': break;153      default: notify('warn', { key: 'wserr.unknown_message', vars: { code: String((m as { t: string }).t) } });154    }155  };156  const onMessageRef = useRef(onMessage); onMessageRef.current = onMessage;157158  useEffect(() => {159    const c = new NavConnection(sessionId, {160      onMessage: (m) => onMessageRef.current(m),161      onFrame: (f) => {162        stageRef.current?.draw(f.bitmap);163        const cur = live.current.frame;164        if (!cur || cur.w !== f.w || cur.h !== f.h) { live.current.frame = { w: f.w, h: f.h }; setFrame(live.current.frame); }165      },166      onState: (s, retry) => {167        live.current.open = s === 'open';168        if (s !== 'open') {169          // Nothing shown may pretend to be live, and control is never assumed across a reconnect.170          live.current.frame = null; setFrame(null); setRtt(null); setChooser({ open: false, multiple: false });171          const had = live.current.mine; live.current.mine = false; lastResize.current = ''; inputRef.current?.dropAll();172          setLease((l) => (had ? { mine: false, holderKind: null, reason: 'disconnected' } : l.mine ? { ...l, mine: false } : l));173        }174        setConn({ s, retry });175      },176      onRtt: setRtt,177      onProblem: (p) => notify('error', { key: `problem.${p}` }),178    });179    connRef.current = c; c.start();180    return () => { c.stop(); connRef.current = null; };181  }, [sessionId, notify]);182183  /* ── Input capture ── */184  const canControl = lease.mine && conn.s === 'open' && !emergency;185  useEffect(() => {186    const h = stageRef.current; if (!h?.stage || !h.canvas || !h.textarea) return;187    const ic = new InputController({188      send: (m) => { connRef.current?.send(m); },189      canControl: () => live.current.mine && live.current.open && !live.current.emergency,190      frame: () => live.current.frame,191      clipboardAllowed: () => live.current.clipboard,192      onClipboardBlocked: () => notify('info', { key: 'viewer.clipboard_off' }),193      onDenied: () => setDenied((n) => n + 1),194      onView: setView,195      onKeyboardFocus: setKb,196      onExitKeyboard: () => takeRef.current?.focus(),197    });198    ic.attach(h.stage, h.canvas, h.textarea);199    inputRef.current = ic;200    return () => { ic.detach(); inputRef.current = null; };201  }, [notify]);202  /** For toolbar and panel actions: explains instead of silently doing nothing. */203  const act = useCallback((m: ViewerMsg): boolean => {204    if (!(live.current.mine && live.current.open && !live.current.emergency)) { notify('warn', { key: 'viewer.need_control' }); return false; }205    if (!connRef.current?.send(m)) { notify('error', { key: 'problem.send_failed' }); return false; }206    return true;207  }, [notify]);208209  /* ── Session row from the API: label, worker, and the state changes the gateway is not told about ── */210  const loadSession = useCallback(async () => {211    const asked = Date.now();212    try {213      const r = await get<SessionList>('/v1/navigator/sessions');214      const row = r.sessions.find((x) => x.id === sessionId) ?? r.revoked.find((x) => x.id === sessionId) ?? null;215      setSession(row);216      if (row && live.current.wsStateAt < asked) setState(row.state);217    } catch (e) { notify('error', { error: e }); }218  }, [sessionId, notify]);219  usePoll(loadSession, 4000);220221  /* ── Remote viewport size: only the controller resizes the real browser ── */222  const sizeKey = `${stageSize.w}x${stageSize.h}`;223  useEffect(() => {224    if (!canControl || (kb && window.matchMedia('(pointer: coarse)').matches)) return; // the on-screen keyboard must not reflow the remote page225    const id = window.setTimeout(() => {226      const coarse = window.matchMedia('(pointer: coarse)').matches;227      const msg: ViewerMsg = fit228        ? { t: 'resize', w: clampInt(stageSize.w, 320, 2560), h: clampInt(stageSize.h, 320, 1600), dpr: Math.min(2, Math.max(1, window.devicePixelRatio || 1)), mobile: coarse && Math.min(window.innerWidth, stageSize.w) < 700 }229        : { t: 'resize', w: FIXED.w, h: FIXED.h, dpr: 1, mobile: false };230      if (fit && (stageSize.w < 50 || stageSize.h < 50)) return;231      const sig = JSON.stringify(msg);232      if (sig === lastResize.current) return;233      if (connRef.current?.send(msg)) lastResize.current = sig;234    }, 250);235    return () => window.clearTimeout(id);236  }, [canControl, fit, sizeKey, kb]); // eslint-disable-line react-hooks/exhaustive-deps237238  /* ── Fullscreen (API where it exists, CSS immersive mode on iPhone) ── */239  useEffect(() => { const on = () => setFs(document.fullscreenElement === rootRef.current); document.addEventListener('fullscreenchange', on); return () => document.removeEventListener('fullscreenchange', on); }, []);240  const hidden = fs || immersive;241  const toggleFullscreen = async () => {242    const el = rootRef.current; if (!el) return;243    try {244      if (document.fullscreenElement) { await document.exitFullscreen(); return; }245      if (immersive) { setImmersive(false); return; }246      if (document.fullscreenEnabled && typeof el.requestFullscreen === 'function') await el.requestFullscreen({ navigationUI: 'hide' });247      else setImmersive(true);248    } catch { setImmersive(true); } // refused by the browser: fall back to the CSS mode rather than fail silently249  };250  // iOS keeps the layout viewport under the on-screen keyboard: follow the visible part instead.251  useEffect(() => {252    const vv = window.visualViewport; const el = rootRef.current; if (!vv || !el) return;253    const fitVV = () => { el.style.height = `${Math.round(vv.height)}px`; el.style.top = `${Math.round(vv.offsetTop)}px`; };254    fitVV(); vv.addEventListener('resize', fitVV); vv.addEventListener('scroll', fitVV);255    return () => { vv.removeEventListener('resize', fitVV); vv.removeEventListener('scroll', fitVV); };256  }, []);257258  /* ── Actions ── */259  const api = async (name: 'takeover' | 'release') => {260    setBusy(name);261    try { await post(`/v1/navigator/sessions/${sessionId}/${name}`); await loadSession(); }262    catch (e) { notify('error', { error: e }); } finally { setBusy(null); }263  };264  const go = (e: FormEvent) => {265    e.preventDefault();266    const raw = addr.trim(); if (!raw) return;267    const full = /^[a-z][a-z0-9+.-]*:/i.test(raw) ? raw : `https://${raw}`;268    let ok = false; try { ok = !!new URL(full).host && full.length <= 2000; } catch { ok = false; }269    if (!ok) { notify('warn', { key: 'blocked.invalid_url', vars: { code: 'invalid_url', url: '' } }); return; }270    if (act({ t: 'nav', op: 'goto', url: full })) setAddr('');271  };272  const setRemoteZoom = (f: number) => { const z = Math.round(Math.min(3, Math.max(0.5, f)) * 10) / 10; if (act({ t: 'zoom', factor: z })) setZoom(z); };273  const toggleFit = () => { const n = !fit; setFit(n); saveFit(n); };274  const toggleKeyboard = () => { if (kb) inputRef.current?.blurKeyboard(); else inputRef.current?.focusKeyboard(); };275276  /* ── Derived display ── */277  const shown: SessionState | null = state ?? session?.state ?? null;278  const mode: Mode = emergency ? 'emergency' : lease.mine ? 'control' : shown === 'SECURITY_CHALLENGE' ? 'challenge' : shown === 'BUSY' || lease.holderKind === 'agent' ? 'agent' : 'readonly';279  const why = !lease.mine && lease.reason ? tCode(t, 'lost', lease.reason) : !lease.mine && lease.holderKind === 'human' ? t('lost.other_human') : '';280  const stopped = session?.wanted === 'stopped' || shown === 'REVOKED';281  const placeholder = useMemo(() => {282    if (conn.s === 'unauthorized') return { key: 'ph.unauthorized' as Key };283    if (conn.s === 'connecting') return { key: 'ph.connecting' as Key };284    if (conn.s === 'waiting' || conn.s === 'stopped') return { key: 'ph.reconnecting' as Key };285    if (session === null) return { key: 'ph.not_found' as Key };286    if (workerOnline === false) return { key: 'ph.worker_offline' as Key };287    if (stopped) return { key: 'ph.browser_closed' as Key };288    if (emergency) return { key: 'ph.emergency' as Key };289    return { key: 'ph.first_frame' as Key };290  }, [conn.s, session, workerOnline, stopped, emergency]);291  const connLabel = conn.s === 'open' ? t('conn.open') : conn.s === 'connecting' ? t('conn.connecting') : conn.s === 'unauthorized' ? t('conn.unauthorized') : conn.s === 'waiting' ? t('conn.waiting', { s: Math.round((conn.retry ?? 0) / 1000) }) : t('conn.stopped');292  const privacy = shown !== null && PRIVACY_STATES.includes(shown);293  const showConfirm = lease.mine && shown === 'MANUAL_CONTROL';294  const jobForChooser = selectedJob && jobIds.includes(selectedJob) ? selectedJob : null;295  const toList = (e: MouseEvent) => { if (e.metaKey || e.ctrlKey || e.shiftKey) return; e.preventDefault(); navigate('/'); };296297  return (298    <div ref={rootRef} className={`viewer mode-${mode}${hidden ? ' immersive' : ''}${side ? ' side-open' : ''}${more ? ' more-open' : ''}`}>299      <header className="v-top">300        <a className="btn quiet v-back" href="/" onClick={toList}><IcoBack /><span>{t('viewer.sessions')}</span></a>301        <div className="v-id">302          <span className="v-label">{session?.label ?? (session === null ? t('ph.not_found') : '…')}</span>303          {shown && <StateBadge state={shown} />}304        </div>305        <span className="spacer" />306        <span className={`conn conn-${conn.s}`} role="status">307          <span aria-hidden="true">{conn.s === 'open' ? '●' : conn.s === 'connecting' ? '◌' : '○'}</span> {connLabel}308          {conn.s === 'waiting' && <> <button type="button" className="link" onClick={() => connRef.current?.retryNow()}>{t('conn.retry_now')}</button></>}309          {conn.s === 'unauthorized' && <> <button type="button" className="link" onClick={() => void refreshMe()}>{t('conn.signin')}</button></>}310        </span>311        <span className="rtt num" title={t('viewer.latency')}><span className="sr-only">{t('viewer.latency')} </span>{rtt === null ? '— ms' : `${rtt} ms`}</span>312        <button type="button" className="btn quiet v-lang" onClick={() => setLang(lang === 'fr' ? 'en' : 'fr')} lang={lang === 'fr' ? 'en' : 'fr'} aria-label={t('prefs.lang')}>{lang === 'fr' ? 'EN' : 'FR'}</button>313        <EmergencyControl me={me} engaged={emergency} refreshMe={refreshMe} compact />314      </header>315316      <div className="v-mode" aria-live="assertive">317        <span key={denied} className={`mode-chip${denied ? ' pulse' : ''}`}>318          <span className="mode-mark" aria-hidden="true">{mode === 'control' ? '■' : mode === 'agent' ? '»' : mode === 'challenge' ? '▲' : mode === 'emergency' ? '⬣' : '□'}</span>319          <strong>{t(`mode.${mode}`)}</strong>320        </span>321        {why && <span className="mode-why">{why}</span>}322        {mode === 'readonly' && !why && <span className="mode-why">{t('mode.readonly_x')}</span>}323        {kb && canControl && <span className="mode-why kb-hint">{t('viewer.kb_captured')}</span>}324        <span className="spacer" />325        {lease.mine326          ? <button ref={takeRef} type="button" className="btn" disabled={busy !== null} onClick={() => void api('release')}>{busy === 'release' ? t('common.working') : t('act.release')}</button>327          : <button ref={takeRef} type="button" className="btn primary" disabled={busy !== null || emergency || shown === 'REVOKED' || conn.s !== 'open'} onClick={() => void api('takeover')}>{busy === 'takeover' ? t('common.working') : t('act.take')}</button>}328      </div>329330      <EmergencyBanner me={me} engaged={emergency} />331      {privacy && (332        <div className="banner privacy" role="note">333          <p><strong>{t('privacy.title')}</strong> {t('privacy.body')}</p>334        </div>335      )}336      {chooser.open && (337        <div className="banner chooser" role="alert">338          <p><strong>{t('chooser.title')}</strong> {jobForChooser ? t('chooser.with_job') : t('chooser.no_job')}</p>339          <div className="row">340            {jobForChooser && <button type="button" className="btn primary" disabled={!canControl} onClick={() => act({ t: 'chooseMedia', jobId: jobForChooser })}>{t('assist.attach')}</button>}341            {!jobForChooser && jobIds.length > 0 && <button type="button" className="btn" onClick={() => setSide(true)}>{t('chooser.pick')}</button>}342            <button type="button" className="btn" disabled={!canControl} onClick={() => act({ t: 'cancelChooser' })}>{t('assist.cancel_chooser')}</button>343          </div>344        </div>345      )}346      <div className="notices" aria-live="polite">347        {notices.map((n) => (348          <div key={n.id} className={`notice tone-${n.tone}`}>349            {'key' in n ? <p>{t(n.key, n.vars)}{n.n > 1 && <span className="num"> ×{n.n}</span>}</p> : <ErrorLine error={n.error} />}350            <IconBtn label={t('common.dismiss')} icon={<IcoClose size={16} />} onClick={() => dismiss(n.id)} className="small" />351          </div>352        ))}353      </div>354355      {tabs.length > 0 && (356        <nav className="v-tabs" aria-label={t('viewer.tabs')}>357          <ul>358            {tabs.map((tb) => (359              <li key={tb.id} className={tb.active ? 'active' : undefined}>360                <button type="button" className="tab" aria-current={tb.active ? 'page' : undefined} disabled={!canControl && !tb.active} onClick={() => { if (!tb.active) act({ t: 'tab', op: 'activate', tabId: tb.id }); }}>361                  <span className="tab-title">{tb.title || hostOf(tb.url) || t('viewer.tab_untitled')}</span>362                </button>363                {tabs.length > 1 && <IconBtn label={t('viewer.tab_close', { title: tb.title || hostOf(tb.url) })} icon={<IcoClose size={14} />} className="small" disabled={!canControl} onClick={() => act({ t: 'tab', op: 'close', tabId: tb.id })} />}364              </li>365            ))}366          </ul>367        </nav>368      )}369      <p className="v-loc" aria-label={t('viewer.location')}>370        {loc.url ? <><span className="loc-title">{loc.title || t('viewer.tab_untitled')}</span> <span className="loc-url mono">{loc.url}</span></> : <span className="muted">{t('viewer.no_location')}</span>}371      </p>372373      <div className="v-body">374        <Stage ref={stageRef} frame={frame} view={view} cursor={cursor} interactive={canControl} keyboardFocused={kb && canControl}375          onSize={(w, h) => setStageSize((s) => (s.w === w && s.h === h ? s : { w, h }))}376          placeholder={<>377            <p className="ph-title">{t(placeholder.key)}</p>378            <p className="ph-sub">{t(`${placeholder.key}.x` as Key, { s: Math.round((conn.retry ?? 0) / 1000) })}</p>379          </>}380          frozen={stopped ? t('ph.frozen_closed') : null}>381          {hidden && <div className="float-mode"><span className="mode-chip"><strong>{t(`mode.${mode}`)}</strong></span></div>}382          {view.z !== 1 && <button type="button" className="btn float-reset" onClick={() => inputRef.current?.resetView()}><IcoResetZoom /><span>{t('viewer.reset_zoom')} · {Math.round(view.z * 100)} %</span></button>}383        </Stage>384        <aside className="side" aria-label={t('viewer.side')} hidden={!side}>385          <div className="side-head"><h2>{t('viewer.side')}</h2><IconBtn label={t('viewer.side_close')} icon={<IcoClose />} onClick={() => setSide(false)} /></div>386          {showConfirm && <ConfirmPanel sessionId={sessionId} onConfirmed={() => { void loadSession(); setAssistKey((k) => k + 1); }} />}387          {!showConfirm && <section className="panel"><h2>{t('confirm.title')}</h2><p className="hint">{t('confirm.unavailable')}</p></section>}388          <AssistPanel sessionId={sessionId} canControl={canControl} policy={policy} chooserOpen={chooser.open} refreshKey={assistKey} selected={selectedJob} onSelect={setSelectedJob} onJobs={setJobIds} act={act} />389        </aside>390      </div>391392      <div className="v-nav" role="toolbar" aria-label={t('viewer.toolbar')}>393        <IconBtn label={t('nav.back')} icon={<IcoBack />} disabled={!canControl} onClick={() => act({ t: 'nav', op: 'back' })} />394        <IconBtn label={t('nav.forward')} icon={<IcoForward />} disabled={!canControl} onClick={() => act({ t: 'nav', op: 'forward' })} />395        <IconBtn label={t('nav.reload')} icon={<IcoReload />} disabled={!canControl} onClick={() => act({ t: 'nav', op: 'reload' })} />396        <form className="addr" onSubmit={go}>397          <label htmlFor="addr" className="sr-only">{t('nav.address')}</label>398          <input id="addr" type="text" inputMode="url" value={addr} onChange={(e) => setAddr(e.target.value)} placeholder={t('nav.address_ph')} maxLength={2000} autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck={false} disabled={!canControl} enterKeyHint="go" />399          <IconBtn type="submit" label={t('nav.go')} icon={<IcoGo />} disabled={!canControl || !addr.trim()} />400        </form>401        <div className="grp extra" role="group" aria-label={t('nav.zoom')}>402          <IconBtn label={t('nav.zoom_out')} icon={<IcoMinus />} disabled={!canControl || zoom <= 0.5} onClick={() => setRemoteZoom(zoom - 0.1)} />403          <span className="num zoom-val" aria-live="polite">{Math.round(zoom * 100)} %</span>404          <IconBtn label={t('nav.zoom_in')} icon={<IcoPlus />} disabled={!canControl || zoom >= 3} onClick={() => setRemoteZoom(zoom + 0.1)} />405        </div>406        <IconBtn className="extra" label={fit ? t('nav.fit_on') : t('nav.fit_off')} icon={<IcoFit />} text={fit ? t('nav.fit_short') : '1280×800'} pressed={fit} onClick={toggleFit} />407        <IconBtn label={kb ? t('nav.kb_hide') : t('nav.kb_show')} icon={<IcoKeyboard />} pressed={kb} onPointerDown={(e) => e.preventDefault()} onClick={toggleKeyboard} />408        <IconBtn label={hidden ? t('nav.fs_exit') : t('nav.fs_enter')} icon={hidden ? <IcoExitFullscreen /> : <IcoFullscreen />} pressed={hidden} onClick={() => void toggleFullscreen()} />409        <IconBtn label={side ? t('viewer.side_close') : t('viewer.side_open')} icon={<IcoPanel />} pressed={side} onClick={() => setSide((v) => !v)} />410        <IconBtn className="more-btn" label={t('nav.more')} icon={<IcoMore />} pressed={more} onClick={() => setMore((v) => !v)} />411      </div>412    </div>413  );414}415
Files main
Menu

Theme