Files
dsh-lan-share/client.js
T

1147 lines
51 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Client half of LAN Share.
*
* On the host computer it contributes a Share control to the conversation
* header and a management page to Settings. On a paired tablet it contributes
* no controls, opens the Session recorded with the device, and remembers the
* Session the user navigates to so a reload returns there.
*
* The QR matrix is produced by the Host half; this file only renders it. That
* keeps the browser bundle small and lets the encoder be tested in Node.
*/
window.__ModuleLoader__.load({
id: '@local/dsh-lan-share',
factory(require) {
const React = require('react');
const ReactDOM = require('react-dom');
const { createSnapshotStore } = require('@deepseek-ai/dsh-client-store');
const h = React.createElement;
const NS = 'lanShare';
const PLUGIN_ID = '@local/dsh-lan-share';
const CSS_ID = PLUGIN_ID + '/lan-share.css';
const API = '/api/lan-share';
const en = {
'share.label': 'Share',
'share.tooltip': 'Share this session over the local network',
'section.title': 'LAN access',
'section.icon': 'LAN access',
'dialog.title': 'Share this session',
'dialog.subtitle': 'Scan the code with a tablet camera on the same Wi-Fi network.',
'dialog.expires': 'One-time code. It works once and expires in {time}.',
'dialog.expired': 'This code has expired. Refresh it to pair another device.',
'dialog.urlLabel': 'Or open this address',
'dialog.copy': 'Copy link',
'dialog.copied': 'Copied',
'dialog.refresh': 'New code',
'dialog.close': 'Close',
'dialog.pair': 'Pair a device',
'dialog.pairHint': 'Create a one-time code for a tablet on the same network.',
'dialog.showQr': 'Tap to show the QR code',
'dialog.showHint': 'The one-time code stays valid for one minute.',
'dialog.loading': 'Creating code…',
'pending.title': 'A device wants to connect',
'pending.device': 'Device: {label} · {ip}',
'pending.expires': 'Confirm the connection within {time}.',
'pending.approve': 'Confirm',
'pending.deny': 'Deny',
'pending.unknownDevice': 'Unknown device',
'devices.title': 'Paired devices',
'devices.empty': 'No devices are paired yet.',
'devices.online': 'online',
'devices.offline': 'offline',
'devices.session': 'session {id}',
'devices.revoke': 'Disconnect',
'devices.revokeAll': 'Disconnect all',
'devices.confirmRevoke': 'Disconnect this device?',
'devices.confirmRevokeAll': 'Disconnect every paired device?',
'status.listening': 'Listening on {origin}',
'status.notListening': 'Not listening: {reason}',
'status.fallback': 'The default port was busy, so this run uses {port}.',
'status.mintError': 'The host session could not be authenticated: {detail}',
'relay.connected': 'Internet relay: {origin}',
'relay.offline': 'Internet relay is offline: {error}',
'relay.disabled': 'Internet relay is not configured.',
'relay.publicOrigin': 'Public address: {origin}',
'relay.error.websocket': 'WSS connection failed. Check relay.url, the certificate, and that relay.token matches the relay AGENT_TOKEN.',
'relay.error.unavailable': 'This runtime has no WebSocket client, so the relay cannot connect.',
'warning.fullAccess': 'A paired device gets full owner control of this DSH instance, including tools and approvals.',
'warning.http': 'Traffic is plain HTTP on the local network. Pair only on a network you trust.',
'error.ticket': 'Could not create a pairing code.',
'error.deviceLimit': 'The device limit is reached. Disconnect an old device first.',
'error.unknownSession': 'This session is no longer available.',
'error.notRunning': 'The LAN listener is not running.',
'error.noLan': 'No LAN address was found. Set the host in the plugin configuration.',
'error.generic': 'Could not reach the host.',
'error.relayOffline': 'The relay is not connected. Check the internet connection on the host computer.',
'error.unavailable': 'LAN access is unavailable in this composition.',
'remote.title': 'Connected to a host',
'remote.body': 'This browser is paired with the DSH desktop at {origin}. Manage pairings on the host computer.',
'remote.device': 'This device: {label}',
'remote.disconnect': 'Disconnect this tablet',
'remote.confirm': 'Disconnect this tablet from the host?',
'remote.disconnected': 'Disconnected.',
'qr.aria': 'Pairing QR code',
'loading': 'Loading…',
};
const ru = {
'share.label': 'Поделиться',
'share.tooltip': 'Открыть этот сеанс в локальной сети',
'section.title': 'Общий доступ по сети',
'section.icon': 'Общий доступ по сети',
'dialog.title': 'Поделиться сеансом',
'dialog.subtitle': 'Отсканируйте код камерой планшета в той же сети Wi-Fi.',
'dialog.expires': 'Одноразовый код. Он сработает один раз и истечёт через {time}.',
'dialog.expired': 'Код истёк. Обновите его, чтобы подключить другое устройство.',
'dialog.urlLabel': 'Или откройте этот адрес',
'dialog.copy': 'Скопировать ссылку',
'dialog.copied': 'Скопировано',
'dialog.refresh': 'Новый код',
'dialog.close': 'Закрыть',
'dialog.pair': 'Подключить устройство',
'dialog.pairHint': 'Создайте одноразовый код для планшета в этой же сети.',
'dialog.showQr': 'Нажмите, чтобы показать QR-код',
'dialog.showHint': 'Одноразовый код будет действовать одну минуту.',
'dialog.loading': 'Создаём код…',
'pending.title': 'Устройство хочет подключиться',
'pending.device': 'Устройство: {label} · {ip}',
'pending.expires': 'Подтвердите подключение в течение {time}.',
'pending.approve': 'Подтвердить',
'pending.deny': 'Отклонить',
'pending.unknownDevice': 'Неизвестное устройство',
'devices.title': 'Подключённые устройства',
'devices.empty': 'Пока нет подключённых устройств.',
'devices.online': 'в сети',
'devices.offline': 'не в сети',
'devices.session': 'сеанс {id}',
'devices.revoke': 'Отключить',
'devices.revokeAll': 'Отключить все',
'devices.confirmRevoke': 'Отключить это устройство?',
'devices.confirmRevokeAll': 'Отключить все подключённые устройства?',
'status.listening': 'Слушает {origin}',
'status.notListening': 'Не запущено: {reason}',
'status.fallback': 'Порт по умолчанию занят, поэтому используется {port}.',
'status.mintError': 'Не удалось подтвердить сеанс на host: {detail}',
'relay.connected': 'Интернет-релей: {origin}',
'relay.offline': 'Интернет-релей не подключён: {error}',
'relay.disabled': 'Интернет-релей не настроен.',
'relay.publicOrigin': 'Публичный адрес: {origin}',
'relay.error.websocket': 'Не удалось открыть WSS. Проверьте relay.url, сертификат и совпадение relay.token с AGENT_TOKEN релея.',
'relay.error.unavailable': 'В этой среде нет WebSocket-клиента, поэтому релей не может подключиться.',
'warning.fullAccess': 'Подключённое устройство получает полный доступ владельца к этому DSH, включая инструменты и подтверждения.',
'warning.http': 'Трафик идёт по обычному HTTP в локальной сети. Подключайте устройства только в доверенной сети.',
'error.ticket': 'Не удалось создать код подключения.',
'error.deviceLimit': 'Достигнут лимит устройств. Сначала отключите старое.',
'error.unknownSession': 'Этот сеанс больше недоступен.',
'error.notRunning': 'LAN-листенер не запущен.',
'error.noLan': 'Не найден LAN-адрес. Укажите host в конфигурации плагина.',
'error.generic': 'Не удалось связаться с host.',
'error.relayOffline': 'Релей недоступен. Проверьте интернет на компьютере.',
'error.unavailable': 'Общий доступ по сети недоступен в этой конфигурации.',
'remote.title': 'Подключено к host',
'remote.body': 'Этот браузер подключён к DSH Desktop по адресу {origin}. Управление привязками — на компьютере.',
'remote.device': 'Это устройство: {label}',
'remote.disconnect': 'Отключить этот планшет',
'remote.confirm': 'Отключить этот планшет от host?',
'remote.disconnected': 'Отключено.',
'qr.aria': 'QR-код для подключения',
'loading': 'Загрузка…',
};
const DICTIONARIES = { en, ru };
/** Copy for one key with simple {name} interpolation. */
function format(template, params) {
if (params === undefined) return template;
return template.replace(/\{(\w+)\}/g, (match, name) => String(params[name] ?? ''));
}
/** Milliseconds as m:ss, or h:mm:ss for long waits. */
function clock(ms) {
const total = Math.max(0, Math.ceil(ms / 1000));
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const seconds = total % 60;
if (hours > 0) return hours + ':' + String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
return String(minutes) + ':' + String(seconds).padStart(2, '0');
}
/** A live "now" that re-renders every interval. */
function useNow(interval) {
const [now, setNow] = React.useState(() => Date.now());
React.useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), interval);
return () => clearInterval(timer);
}, [interval]);
return now;
}
/** Copy text with a clipboard fallback for insecure origins. */
async function copyText(text) {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return true;
}
} catch {
/* fall through to the legacy path */
}
try {
const area = document.createElement('textarea');
area.value = text;
area.style.position = 'fixed';
area.style.opacity = '0';
area.style.pointerEvents = 'none';
document.body.appendChild(area);
area.select();
const ok = document.execCommand('copy');
area.remove();
return ok;
} catch {
return false;
}
}
/** Read one JSON API response, tolerating a non-JSON error page. */
async function readJson(response) {
try {
return await response.json();
} catch {
return null;
}
}
/** Error copy for a control-API refusal. */
function errorFor(t, code) {
switch (code) {
case 'DEVICE_LIMIT':
case 'device-limit':
return t('error.deviceLimit');
case 'unknown-session':
return t('error.unknownSession');
case 'NOT_RUNNING':
case 'not-running':
return t('error.notRunning');
case 'no-lan-address':
return t('error.noLan');
case 'relay-offline':
return t('error.relayOffline');
default:
return t('error.ticket');
}
}
/** A small QR glyph for the tap-to-reveal placeholder. */
function QrGlyph() {
return h(
'svg',
{ className: 'dshLanShare_qrGlyph', viewBox: '0 0 24 24', fill: 'none', 'aria-hidden': 'true' },
h('rect', { x: 3, y: 3, width: 7, height: 7, rx: 1, stroke: 'currentColor', strokeWidth: 1.5 }),
h('rect', { x: 14, y: 3, width: 7, height: 7, rx: 1, stroke: 'currentColor', strokeWidth: 1.5 }),
h('rect', { x: 3, y: 14, width: 7, height: 7, rx: 1, stroke: 'currentColor', strokeWidth: 1.5 }),
h('rect', { x: 5.5, y: 5.5, width: 2, height: 2, fill: 'currentColor' }),
h('rect', { x: 16.5, y: 5.5, width: 2, height: 2, fill: 'currentColor' }),
h('rect', { x: 5.5, y: 16.5, width: 2, height: 2, fill: 'currentColor' }),
h('path', { d: 'M14 14h3v3h-3zM18 14h3v3h-3zM14 18h3v3h-3zM19 19h2v2h-2z', fill: 'currentColor' }),
);
}
/** A QR symbol rendered from the Host-produced matrix on a white tile. */
function QrCode({ rows, size, label }) {
const count = Array.isArray(rows) ? rows.length : 0;
if (count === 0) return null;
let path = '';
for (let y = 0; y < count; y++) {
const row = rows[y];
for (let x = 0; x < count; x++) {
if (row[x] === '1') path += 'M' + String(x) + ' ' + String(y) + 'h1v1h-1z';
}
}
const quiet = 4;
return h(
'svg',
{
className: 'dshLanShare_qr',
viewBox: String(-quiet) + ' ' + String(-quiet) + ' ' + String(count + quiet * 2) + ' ' + String(count + quiet * 2),
width: size,
height: size,
role: 'img',
'aria-label': label,
shapeRendering: 'crispEdges',
},
h('rect', { x: -quiet, y: -quiet, width: count + quiet * 2, height: count + quiet * 2, fill: '#fff' }),
h('path', { d: path, fill: '#0b0b0c' }),
);
}
/** A small share glyph. */
function ShareIcon() {
return h(
'svg',
{ viewBox: '0 0 16 16', width: 15, height: 15, fill: 'none', 'aria-hidden': 'true' },
h('path', {
d: 'M8 1.8v7.4M8 1.8 5.2 4.6M8 1.8l2.8 2.8M3.2 8.4v4.4c0 .8.6 1.4 1.4 1.4h6.8c.8 0 1.4-.6 1.4-1.4V8.4',
stroke: 'currentColor',
strokeWidth: 1.3,
strokeLinecap: 'round',
strokeLinejoin: 'round',
}),
);
}
/** A small LAN glyph for the Settings navigation. */
function LanIcon(props) {
const size = typeof props.size === 'number' ? props.size : 16;
return h(
'svg',
{ viewBox: '0 0 16 16', width: size, height: size, fill: 'none', 'aria-hidden': 'true' },
h('path', {
d: 'M2.5 10.8a5.5 5.5 0 0 1 11 0M5 10.8a3 3 0 0 1 6 0M7.2 11.6a.8.8 0 1 0 1.6 0 .8.8 0 0 0-1.6 0Z',
stroke: 'currentColor',
strokeWidth: 1.2,
strokeLinecap: 'round',
}),
);
}
/**
* One status line for the listener.
* @param {{ state: any, t: Function }} props panel props.
*/
function ListenerStatus({ state, t }) {
if (state === null || state === undefined) return h('p', { className: 'dshLanShare_hint' }, t('loading'));
if (state.running === true) {
return h(
'div',
{ className: 'dshLanShare_status' },
h('span', { className: 'dshLanShare_dot dshLanShare_dotOn', 'aria-hidden': 'true' }),
h('span', null, format(t('status.listening'), { origin: state.origin ?? '' })),
);
}
const reason = state.error === 'no-lan-address' ? t('error.noLan') : String(state.error ?? 'unknown');
return h(
'div',
{ className: 'dshLanShare_status dshLanShare_statusWarn' },
h('span', { className: 'dshLanShare_dot', 'aria-hidden': 'true' }),
h('span', null, format(t('status.notListening'), { reason })),
);
}
/** Human copy for a relay error code. */
function relayErrorText(t, error) {
if (error === 'websocket-error' || error === 'connect-failed') return t('relay.error.websocket');
if (error === 'websocket-unavailable') return t('relay.error.unavailable');
return String(error ?? 'unknown');
}
/** Internet-relay status line; absent when no relay is configured. */
function RelayStatus({ state, t }) {
const relay = state?.relay;
if (relay === null || relay === undefined || relay.enabled !== true) return null;
if (relay.connected === true) {
return h(
'div',
{ className: 'dshLanShare_status' },
h('span', { className: 'dshLanShare_dot dshLanShare_dotOn', 'aria-hidden': 'true' }),
h('span', null, format(t('relay.connected'), { origin: relay.publicOrigin ?? '' })),
);
}
return h(
'div',
{ className: 'dshLanShare_status dshLanShare_statusWarn' },
h('span', { className: 'dshLanShare_dot', 'aria-hidden': 'true' }),
h('span', null, format(t('relay.offline'), { error: relayErrorText(t, relay.error) })),
);
}
/** The device list shared by the dialog and the Settings page. */
function DeviceList({ devices, t, onRevoke, onRevokeAll, busy }) {
if (!Array.isArray(devices) || devices.length === 0) {
return h('p', { className: 'dshLanShare_hint' }, t('devices.empty'));
}
return h(
'div',
{ className: 'dshLanShare_devices' },
h(
'div',
{ className: 'dshLanShare_devicesHead' },
h('span', null, t('devices.title')),
h(
'button',
{ type: 'button', className: 'dshLanShare_link', onClick: onRevokeAll, disabled: busy },
t('devices.revokeAll'),
),
),
...devices.map((device) =>
h(
'div',
{ key: device.id, className: 'dshLanShare_device' },
h('span', {
className: 'dshLanShare_dot' + (device.online === true ? ' dshLanShare_dotOn' : ''),
'aria-hidden': 'true',
}),
h(
'div',
{ className: 'dshLanShare_deviceBody' },
h('span', { className: 'dshLanShare_deviceLabel' }, device.label),
h(
'span',
{ className: 'dshLanShare_deviceMeta' },
(device.online === true ? t('devices.online') : t('devices.offline'))
+ ' · ' + String(device.ip ?? '')
+ (typeof device.sessionId === 'string' ? ' · ' + format(t('devices.session'), { id: device.sessionId.slice(0, 8) }) : ''),
),
),
h(
'button',
{ type: 'button', className: 'dshLanShare_button', onClick: () => onRevoke(device), disabled: busy },
t('devices.revoke'),
),
),
),
);
}
/** Copy-to-clipboard glyph for the URL row. */
function CopyIcon() {
return h(
'svg',
{ viewBox: '0 0 16 16', width: 14, height: 14, fill: 'none', 'aria-hidden': 'true' },
h('rect', { x: 5.5, y: 5.5, width: 8, height: 8, rx: 1.5, stroke: 'currentColor', strokeWidth: 1.3 }),
h('path', { d: 'M10.5 5.5V4A1.5 1.5 0 0 0 9 2.5H4A1.5 1.5 0 0 0 2.5 4v5A1.5 1.5 0 0 0 4 10.5h1.5', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round' }),
);
}
/** Confirmation check after the URL was copied. */
function CheckIcon() {
return h(
'svg',
{ viewBox: '0 0 16 16', width: 14, height: 14, fill: 'none', 'aria-hidden': 'true' },
h('path', { d: 'M3 8.5l3 3 7-7', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' }),
);
}
/** One scanned QR waiting for the owner's decision. */
function PendingCard({ pending, t, now, busy, onApprove, onDeny }) {
const remaining = Math.max(0, Number(pending.expiresAt ?? 0) - now);
const label = typeof pending.label === 'string' && pending.label !== '' ? pending.label : t('pending.unknownDevice');
return h(
'div',
{ className: 'dshLanShare_pending' },
h(
'div',
{ className: 'dshLanShare_pendingHead' },
h('span', { className: 'dshLanShare_pendingDot', 'aria-hidden': 'true' }),
h('span', null, t('pending.title')),
),
h('p', { className: 'dshLanShare_pendingDevice' }, format(t('pending.device'), { label, ip: String(pending.ip ?? '—') })),
typeof pending.userAgent === 'string' && pending.userAgent !== ''
? h('p', { className: 'dshLanShare_pendingMeta', title: pending.userAgent }, pending.userAgent)
: null,
h('p', { className: 'dshLanShare_hint' }, format(t('pending.expires'), { time: clock(remaining) })),
h(
'div',
{ className: 'dshLanShare_pendingActions' },
h('button', { type: 'button', className: 'dshLanShare_primary', onClick: onApprove, disabled: busy }, t('pending.approve')),
h('button', { type: 'button', className: 'dshLanShare_button', onClick: onDeny, disabled: busy }, t('pending.deny')),
),
);
}
/**
* The pairing panel: status, QR, URL and devices. Used inside the dialog
* and embedded in Settings.
*/
function SharePanel({ sessionId, t, embedded }) {
const [ticket, setTicket] = React.useState(null);
const [revealed, setRevealed] = React.useState(false);
const [state, setState] = React.useState(null);
const [error, setError] = React.useState('');
const [busy, setBusy] = React.useState(false);
const [copied, setCopied] = React.useState(false);
const alive = React.useRef(true);
const now = useNow(1000);
const pending = state !== null && Array.isArray(state.pending) && state.pending.length > 0
? state.pending[0]
: null;
const pendingId = pending === null ? null : pending.id;
React.useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
};
}, []);
/** Read listener status and devices. */
const refreshState = React.useCallback(async () => {
try {
const response = await fetch(API + '/state', { headers: { accept: 'application/json' }, cache: 'no-store' });
if (!response.ok) return;
const data = await readJson(response);
if (alive.current && data !== null) setState(data);
} catch {
/* keep the previous status */
}
}, []);
/**
* Mint one ticket bound to this Session.
* @param {{ reveal?: boolean }} [options] reveal immediately (true) or
* keep the fresh code behind the tap placeholder (false).
*/
const mint = React.useCallback(async (options = {}) => {
if (busy) return;
const shouldReveal = options.reveal !== false;
setBusy(true);
setError('');
setCopied(false);
try {
const response = await fetch(API + '/ticket', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify(typeof sessionId === 'string' && sessionId !== '' ? { sessionId } : {}),
});
const data = await readJson(response);
if (alive.current === false) return;
if (!response.ok || data === null || data.ok !== true) {
setTicket(null);
setRevealed(false);
setError(errorFor(t, data?.code ?? (response.status === 404 ? 'unknown-session' : null)));
return;
}
setTicket(data);
setRevealed(shouldReveal);
refreshState();
} catch {
if (alive.current) {
setTicket(null);
setRevealed(false);
setError(t('error.generic'));
}
} finally {
if (alive.current) setBusy(false);
}
}, [busy, refreshState, sessionId, t]);
React.useEffect(() => {
refreshState();
const timer = setInterval(refreshState, 2500);
return () => clearInterval(timer);
}, [refreshState]);
/** Reveal the waiting code, or mint a fresh one when it went stale. */
const reveal = React.useCallback(() => {
if (busy) return;
/* Background refresh keeps a hidden code ready. Show it only while it
* still has most of its minute; otherwise mint one with a full timer. */
if (ticket !== null && Number(ticket.expiresAt) - Date.now() > 55_000) {
setRevealed(true);
return;
}
void mint();
}, [busy, mint, ticket]);
/* The hidden code is refreshed in the background every minute, so the
* next tap always reveals a usable QR. A scanned code pauses this loop:
* the pending request card takes over until the owner decides. */
React.useEffect(() => {
if (pendingId !== null) return;
if (ticket === null) return;
if (Number(ticket.expiresAt) > now) return;
if (revealed) setRevealed(false);
void mint({ reveal: false });
}, [now, revealed, ticket, pendingId, mint]);
React.useEffect(() => {
if (pendingId === null) return;
setRevealed(false);
setTicket(null);
setCopied(false);
}, [pendingId]);
/** Revoke one device after a confirmation. */
const revoke = async (device) => {
if (!window.confirm(t('devices.confirmRevoke'))) return;
setBusy(true);
try {
await fetch(API + '/revoke', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ deviceId: device.id }),
});
await refreshState();
} catch {
setError(t('error.generic'));
} finally {
if (alive.current) setBusy(false);
}
};
/** Revoke every device after a confirmation. */
const revokeAll = async () => {
if (!window.confirm(t('devices.confirmRevokeAll'))) return;
setBusy(true);
try {
await fetch(API + '/revoke', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ all: true }),
});
await refreshState();
} catch {
setError(t('error.generic'));
} finally {
if (alive.current) setBusy(false);
}
};
/** Approve or deny the device that scanned the QR. */
const decide = async (action) => {
if (busy || pending === null) return;
setBusy(true);
setError('');
try {
const response = await fetch(API + '/' + action, {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ id: pending.id }),
});
const data = await readJson(response);
if (!response.ok || data === null || data.ok !== true) {
setError(errorFor(t, data?.code ?? null));
}
await refreshState();
} catch {
if (alive.current) setError(t('error.generic'));
} finally {
if (alive.current) setBusy(false);
}
};
const remaining = revealed && ticket !== null ? Number(ticket.expiresAt) - now : 0;
const showQr = revealed && ticket !== null && remaining > 0;
return h(
'div',
{ className: 'dshLanShare_panel' + (embedded ? ' dshLanShare_panelEmbedded' : '') },
h(ListenerStatus, { state, t }),
h(RelayStatus, { state, t }),
state !== null && state.running === true && state.fallbackPort === true
? h('p', { className: 'dshLanShare_hint' }, format(t('status.fallback'), { port: String(state.port ?? '') }))
: null,
state !== null && typeof state.mintError === 'string' && state.mintError !== ''
? h('p', { className: 'dshLanShare_warn' }, format(t('status.mintError'), { detail: state.mintError }))
: null,
pending !== null
? h(PendingCard, {
pending,
t,
now,
busy,
onApprove: () => void decide('approve'),
onDeny: () => void decide('deny'),
})
: !showQr
? h(
'div',
{ className: 'dshLanShare_pairEmpty' },
h(
'button',
{
type: 'button',
className: 'dshLanShare_qrPlaceholder',
onClick: reveal,
disabled: busy,
'aria-label': t('dialog.showQr'),
},
h(QrGlyph, null),
h('span', null, busy ? t('dialog.loading') : t('dialog.showQr')),
),
h('p', { className: 'dshLanShare_hint' }, t('dialog.showHint')),
)
: h(
'div',
{ className: 'dshLanShare_pair' },
h('div', { className: 'dshLanShare_qrCard' }, h(QrCode, { rows: ticket.qr?.rows ?? [], size: 240, label: t('qr.aria') })),
h(
'div',
{ className: 'dshLanShare_pairBody' },
h('p', { className: 'dshLanShare_hint' }, t('dialog.subtitle')),
h(
'p',
{ className: 'dshLanShare_countdown' },
format(t('dialog.expires'), { time: clock(remaining) }),
),
h(
'div',
{ className: 'dshLanShare_urlRow' },
h('span', { className: 'dshLanShare_url', title: ticket.url }, ticket.url),
h(
'button',
{
type: 'button',
className: 'dshLanShare_button dshLanShare_copyButton',
title: copied ? t('dialog.copied') : t('dialog.copy'),
'aria-label': copied ? t('dialog.copied') : t('dialog.copy'),
onClick: async () => {
if (await copyText(ticket.url)) {
setCopied(true);
setTimeout(() => { if (alive.current) setCopied(false); }, 1500);
}
},
},
copied ? h(CheckIcon, null) : h(CopyIcon, null),
),
),
),
),
error !== '' ? h('p', { className: 'dshLanShare_warn' }, error) : null,
h(DeviceList, {
devices: state?.devices ?? [],
t,
onRevoke: revoke,
onRevokeAll: revokeAll,
busy,
}),
h('p', { className: 'dshLanShare_warn' }, t('warning.fullAccess')),
state !== null && state.protocol === 'http:'
? h('p', { className: 'dshLanShare_hint' }, t('warning.http'))
: null,
);
}
/** A modal portal shared by the header control. */
function ShareDialog({ sessionId, t, onClose }) {
const panelRef = React.useRef(null);
React.useEffect(() => {
const previous = document.activeElement;
const { overflow } = document.body.style;
document.body.style.overflow = 'hidden';
panelRef.current?.focus();
const onKey = (event) => {
if (event.key === 'Escape') {
event.preventDefault();
onClose();
}
};
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('keydown', onKey);
document.body.style.overflow = overflow;
if (previous instanceof HTMLElement) previous.focus();
};
}, [onClose]);
return ReactDOM.createPortal(
h(
'div',
{ className: 'dshLanShare_overlay', onMouseDown: (event) => { if (event.target === event.currentTarget) onClose(); } },
h(
'div',
{
className: 'dshLanShare_dialog',
role: 'dialog',
'aria-modal': 'true',
'aria-label': t('dialog.title'),
tabIndex: -1,
ref: panelRef,
},
h(
'div',
{ className: 'dshLanShare_dialogHead' },
h('div', null,
h('h2', { className: 'dshLanShare_title' }, t('dialog.title')),
h('p', { className: 'dshLanShare_subtitle' }, t('dialog.subtitle')),
),
h(
'button',
{ type: 'button', className: 'dshLanShare_close', onClick: onClose, 'aria-label': t('dialog.close') },
'×',
),
),
h(SharePanel, { sessionId, t }),
),
),
document.body,
);
}
/** The header control: opens the Share dialog. */
function ShareAction({ sessionId, t, useBootstrap }) {
const remote = useBootstrap((snapshot) => snapshot.remote);
const [open, setOpen] = React.useState(false);
if (remote !== false) return null;
return h(
React.Fragment,
null,
h(
'button',
{
type: 'button',
className: 'dshLanShare_action',
onClick: () => setOpen(true),
title: t('share.tooltip'),
'aria-label': t('share.tooltip'),
},
h(ShareIcon, null),
h('span', { className: 'dshLanShare_actionLabel' }, t('share.label')),
),
open ? h(ShareDialog, { sessionId, t, onClose: () => setOpen(false) }) : null,
);
}
/** Settings → LAN access: host controls, or this tablet's pairing facts. */
function SettingsSection({ t, useBootstrap, currentSessionId }) {
const bootstrap = useBootstrap((snapshot) => snapshot);
const [disconnecting, setDisconnecting] = React.useState(false);
if (bootstrap.phase === 'loading') return h('p', { className: 'dshLanShare_hint' }, t('loading'));
if (bootstrap.phase === 'off') return h('p', { className: 'dshLanShare_hint' }, t('error.unavailable'));
if (bootstrap.remote === true) {
const publicOrigin = typeof window !== 'undefined' && window.location?.origin
? window.location.origin
: String(bootstrap.origin ?? '');
return h(
'div',
{ className: 'dshLanShare_panel dshLanShare_panelEmbedded' },
h('h3', { className: 'dshLanShare_title' }, t('remote.title')),
h('p', { className: 'dshLanShare_hint' }, format(t('remote.body'), { origin: publicOrigin })),
typeof bootstrap.label === 'string'
? h('p', { className: 'dshLanShare_hint' }, format(t('remote.device'), { label: bootstrap.label }))
: null,
h(
'button',
{
type: 'button',
className: 'dshLanShare_button',
disabled: disconnecting,
onClick: async () => {
if (!window.confirm(t('remote.confirm'))) return;
setDisconnecting(true);
try {
await fetch(API + '/forget-self', { method: 'POST', headers: { accept: 'application/json' } });
} catch {
/* the reload still shows the pairing page */
}
window.location.reload();
},
},
t('remote.disconnect'),
),
);
}
return h(SharePanel, {
sessionId: typeof currentSessionId === 'function' ? currentSessionId() : undefined,
t,
embedded: true,
});
}
/**
* On a tablet: open the Session recorded at pairing, then remember every
* Session the user navigates to. The opener waits for the startup
* restoration so it does not race the host's own selection.
* @param {any} ctx client context.
* @param {any} store bootstrap store.
* @param {{ sessionId: string | null }} bootstrap initial value.
* @returns {() => void} cleanup.
*/
function installRemoteSessionSync(ctx, store, bootstrap) {
const started = Date.now();
let done = typeof bootstrap.sessionId !== 'string';
let attempts = 0;
let lastSent = null;
const workspace = ctx.uiWorkspace;
const openBound = () => {
if (done) return;
const snapshot = store.getSnapshot();
if (snapshot.remote !== true) return;
const target = snapshot.sessionId;
if (typeof target !== 'string') {
done = true;
return;
}
const sessions = ctx.sessions?.list?.getSnapshot?.();
if (sessions === undefined || sessions.phase !== 'ready') return;
const workspaces = workspace?.workspaces?.list?.getSnapshot?.();
if (workspaces !== undefined && workspaces.phase !== 'ready') return;
if (sessions.byId === undefined || sessions.byId[target] === undefined) {
done = true;
return;
}
const current = workspace?.mainReference?.sessionId;
if (current === target) {
done = true;
return;
}
if (current === undefined && Date.now() - started < 2000) return;
if (attempts >= 3) {
done = true;
return;
}
attempts += 1;
try {
workspace.openSession(target);
} catch (error) {
console.warn('lan-share: could not open the paired Session', error);
done = true;
}
};
const remember = () => {
const current = workspace?.mainReference?.sessionId;
if (typeof current !== 'string' || current === lastSent) return;
lastSent = current;
fetch(API + '/session', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ sessionId: current }),
keepalive: true,
}).catch(() => {});
};
const timers = new Set();
const tick = () => {
openBound();
if (done) {
for (const timer of timers) clearInterval(timer);
timers.clear();
}
};
const fast = setInterval(tick, 400);
timers.add(fast);
const safety = setTimeout(() => {
if (!done) {
attempts = Math.max(attempts, 2);
openBound();
}
}, 5000);
timers.add(safety);
const unsubscribeSelection = workspace?.selection?.subscribe?.(() => {
openBound();
remember();
}) ?? (() => {});
const unsubscribeSessions = ctx.sessions?.list?.subscribe?.(openBound) ?? (() => {});
const unsubscribeConnection = ctx.get?.('connection')?.state?.subscribe?.(() => {
openBound();
}) ?? (() => {});
return () => {
for (const timer of timers) {
clearInterval(timer);
clearTimeout(timer);
}
timers.clear();
unsubscribeSelection();
unsubscribeSessions();
unsubscribeConnection();
};
}
/** Styles for the action, dialog and Settings page. */
const CSS = [
'.dshLanShare_action{box-sizing:border-box;height:24px;flex:none;display:inline-flex;align-items:center;gap:6px;',
'border-radius:9px;border:none;background:0 0;color:var(--dsw-alias-label-secondary);',
'font:inherit;font-size:12px;line-height:1;padding:0 8px;cursor:pointer;white-space:nowrap}',
'@media (hover:hover){.dshLanShare_action:hover{background:var(--dsw-alias-interactive-bg-hover);',
'color:var(--dsw-alias-label-primary)}}',
'.dshLanShare_action:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:1px}',
'.dshLanShare_actionLabel{max-width:90px;overflow:hidden;text-overflow:ellipsis}',
'.dshLanShare_overlay{position:fixed;inset:0;z-index:1200;display:flex;align-items:center;justify-content:center;',
'background:color-mix(in srgb,#000 42%,transparent);padding:20px;overscroll-behavior:contain}',
'.dshLanShare_dialog{box-sizing:border-box;width:min(680px,100%);max-height:min(86vh,900px);overflow:auto;',
'border-radius:16px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);',
'box-shadow:0 18px 60px rgb(0 0 0 / .32);padding:20px;outline:none}',
'.dshLanShare_dialogHead{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:12px}',
'.dshLanShare_title{margin:0;font-size:17px;font-weight:600;line-height:1.3;color:var(--dsw-alias-label-primary)}',
'.dshLanShare_subtitle{margin:4px 0 0;font-size:13px;color:var(--dsw-alias-label-tertiary);line-height:1.45}',
'.dshLanShare_close{flex:none;width:32px;height:32px;border:none;border-radius:9px;background:0 0;',
'color:var(--dsw-alias-label-secondary);font-size:22px;line-height:1;cursor:pointer}',
'@media (hover:hover){.dshLanShare_close:hover{background:var(--dsw-alias-interactive-bg-hover)}}',
'.dshLanShare_panel{display:flex;flex-direction:column;gap:12px;min-width:0}',
'.dshLanShare_panelEmbedded{max-width:720px}',
'.dshLanShare_status{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--dsw-alias-label-secondary);min-width:0}',
'.dshLanShare_status>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
'.dshLanShare_statusWarn{color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary))}',
'.dshLanShare_dot{width:7px;height:7px;border-radius:50%;flex:none;background:var(--dsw-alias-label-tertiary);opacity:.55}',
'.dshLanShare_dotOn{background:var(--dsw-alias-state-success-primary, #2e9e5b);opacity:1}',
'.dshLanShare_hint{margin:0;font-size:12.5px;line-height:1.5;color:var(--dsw-alias-label-tertiary)}',
'.dshLanShare_warn{margin:0;font-size:12.5px;line-height:1.5;color:var(--dsw-alias-state-warn-label,var(--dsw-alias-state-warn-primary))}',
'.dshLanShare_pair{display:grid;grid-template-columns:auto minmax(0,1fr);gap:18px;align-items:start}',
'.dshLanShare_qrCard{flex:none;display:inline-flex;padding:10px;border-radius:14px;background:#fff;',
'border:1px solid color-mix(in srgb,#000 10%,transparent)}',
'.dshLanShare_qrPlaceholder{box-sizing:border-box;width:240px;height:240px;flex:none;display:flex;',
'flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:16px;',
'border-radius:14px;border:1px dashed var(--dsw-alias-border-l2);',
'background:color-mix(in srgb,var(--dsw-alias-label-primary) 4%,transparent);',
'color:var(--dsw-alias-label-secondary);font:inherit;font-size:13px;line-height:1.4;',
'text-align:center;cursor:pointer}',
'@media (hover:hover){.dshLanShare_qrPlaceholder:hover{background:color-mix(in srgb,var(--dsw-alias-label-primary) 7%,transparent);',
'color:var(--dsw-alias-label-primary)}}',
'.dshLanShare_qrPlaceholder:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px}',
'.dshLanShare_qrPlaceholder:disabled{opacity:.55;cursor:default}',
'.dshLanShare_qrGlyph{width:44px;height:44px;color:var(--dsw-alias-label-tertiary)}',
'.dshLanShare_copyButton{width:30px;height:30px;padding:0;flex:none;justify-content:center}',
'.dshLanShare_pending{box-sizing:border-box;width:100%;max-width:560px;display:flex;flex-direction:column;gap:8px;',
'padding:14px;border-radius:14px;border:1px solid color-mix(in srgb,var(--dsw-alias-state-warn-primary) 35%,transparent);',
'background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 6%,transparent)}',
'.dshLanShare_pendingHead{display:flex;align-items:center;gap:8px;font-size:13.5px;font-weight:600;',
'color:var(--dsw-alias-label-primary)}',
'.dshLanShare_pendingDot{width:8px;height:8px;flex:none;border-radius:50%;',
'background:var(--dsw-alias-state-warn-primary);box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-state-warn-primary) 20%,transparent)}',
'.dshLanShare_pendingDevice{margin:0;font-size:13px;line-height:1.4;color:var(--dsw-alias-label-secondary)}',
'.dshLanShare_pendingMeta{margin:0;font-size:11.5px;line-height:1.4;color:var(--dsw-alias-label-tertiary);',
'white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
'.dshLanShare_pendingActions{display:flex;flex-wrap:wrap;gap:8px;margin-top:2px}',
'.dshLanShare_qr{display:block;border-radius:6px}',
'.dshLanShare_pairBody{display:flex;flex-direction:column;gap:10px;min-width:0}',
'.dshLanShare_countdown{margin:0;font-size:13px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}',
'.dshLanShare_countdownOff{color:var(--dsw-alias-state-warn-primary)}',
'.dshLanShare_urlRow{display:flex;align-items:center;gap:8px;min-width:0}',
'.dshLanShare_url{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;',
'font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px;color:var(--dsw-alias-label-secondary);',
'background:color-mix(in srgb,var(--dsw-alias-label-primary) 6%,transparent);padding:7px 9px;border-radius:8px}',
'.dshLanShare_button,.dshLanShare_primary{box-sizing:border-box;min-height:32px;display:inline-flex;align-items:center;',
'justify-content:center;padding:0 12px;border-radius:9px;font:inherit;font-size:12.5px;line-height:1;cursor:pointer;',
'border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary)}',
'.dshLanShare_primary{border-color:transparent;color:#fff;',
'background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,var(--dsw-alias-state-business-primary))}',
'@media (hover:hover){.dshLanShare_button:hover{background:var(--dsw-alias-interactive-bg-hover)}',
'.dshLanShare_primary:hover{filter:brightness(1.06)}}',
'.dshLanShare_button:disabled,.dshLanShare_primary:disabled{opacity:.5;cursor:default}',
'.dshLanShare_link{border:none;background:0 0;color:var(--dsw-alias-state-business-primary);font:inherit;',
'font-size:12px;cursor:pointer;padding:0}',
'.dshLanShare_link:disabled{opacity:.5;cursor:default}',
'.dshLanShare_devices{display:flex;flex-direction:column;gap:2px;margin-top:4px;',
'border-top:1px solid var(--dsw-alias-border-l1);padding-top:10px}',
'.dshLanShare_devicesHead{display:flex;align-items:center;justify-content:space-between;gap:12px;',
'font-size:12px;color:var(--dsw-alias-label-tertiary);margin-bottom:4px}',
'.dshLanShare_device{display:flex;align-items:center;gap:9px;padding:6px 0;min-width:0}',
'.dshLanShare_deviceBody{display:flex;flex-direction:column;gap:1px;min-width:0;flex:1 1 auto}',
'.dshLanShare_deviceLabel{font-size:13px;color:var(--dsw-alias-label-primary);overflow:hidden;',
'text-overflow:ellipsis;white-space:nowrap}',
'.dshLanShare_deviceMeta{font-size:11.5px;color:var(--dsw-alias-label-tertiary);overflow:hidden;',
'text-overflow:ellipsis;white-space:nowrap;font-variant-numeric:tabular-nums}',
'.dshLanShare_pairEmpty{display:flex;flex-direction:column;gap:10px;align-items:flex-start}',
'@media (max-width:640px){.dshLanShare_overlay{padding:0;align-items:stretch}',
'.dshLanShare_dialog{width:100%;max-height:100%;border-radius:0;border:none;padding:18px 16px}',
'.dshLanShare_pair{grid-template-columns:1fr;justify-items:center}',
'.dshLanShare_pairBody{width:100%}.dshLanShare_actionLabel{display:none}}',
'@media (pointer:coarse){.dshLanShare_button,.dshLanShare_primary,.dshLanShare_close{min-height:42px}',
'.dshLanShare_action{min-height:36px}.dshLanShare_device{padding:9px 0}}',
].join('');
/** Services the Client half requires. */
const inject = ['slots', 'locale', 'sessions', 'uiWorkspace'];
/**
* Register the surfaces and, on a paired tablet, install Session sync.
* @param {any} ctx client plugin context.
*/
function apply(ctx) {
const store = createSnapshotStore({ phase: 'loading', remote: null, sessionId: null, deviceId: null, label: null, origin: null, error: null });
const tSettings = ctx.locale.bind(NS);
let cleanupRemote = null;
ctx.effect(() => ctx.locale.register(NS, DICTIONARIES), 'lan-share: dictionaries');
ctx.effect(() => {
const tag = document.createElement('style');
tag.dataset.plugin = PLUGIN_ID;
tag.dataset.pluginCss = CSS_ID;
tag.textContent = CSS;
document.head.appendChild(tag);
return () => tag.remove();
}, 'lan-share: styles');
ctx.effect(() => {
const controller = new AbortController();
(async () => {
try {
const response = await fetch(API + '/bootstrap', {
headers: { accept: 'application/json' },
cache: 'no-store',
signal: controller.signal,
});
if (!response.ok) {
store.set({ phase: 'off', remote: null });
return;
}
const data = await readJson(response);
if (controller.signal.aborted) return;
if (data === null) {
store.set({ phase: 'off', remote: null });
return;
}
store.set({
phase: 'ready',
remote: data.remote === true,
sessionId: typeof data.sessionId === 'string' ? data.sessionId : null,
deviceId: typeof data.deviceId === 'string' ? data.deviceId : null,
label: typeof data.label === 'string' ? data.label : null,
origin: typeof data.origin === 'string' ? data.origin : null,
error: typeof data.error === 'string' ? data.error : null,
});
if (data.remote === true) cleanupRemote = installRemoteSessionSync(ctx, store, data);
} catch (error) {
if (!controller.signal.aborted) store.set({ phase: 'off', remote: null });
}
})();
return () => {
controller.abort();
if (cleanupRemote !== null) {
cleanupRemote();
cleanupRemote = null;
}
};
}, 'lan-share: bootstrap');
ctx.slots.inject('conversation.session.header.actions', () =>
ctx.slots.register(
{
name: 'conversation.session.header.actions',
id: 'lan-share',
order: 30,
locale: NS,
inject: () => ({ hooks: { bootstrap: store } }),
},
ShareAction,
),
);
ctx.slots.inject('settings.section', () =>
ctx.slots.register(
{
name: 'settings.section',
id: 'lan-share',
order: 55,
label: () => tSettings('section.title'),
locale: NS,
inject: () => ({
hooks: { bootstrap: store },
currentSessionId: () => ctx.uiWorkspace?.mainReference?.sessionId ?? undefined,
}),
},
SettingsSection,
),
);
ctx.slots.inject('settings.section.icon', () =>
ctx.slots.register(
{ name: 'settings.section.icon', id: 'lan-share', locale: NS },
LanIcon,
),
);
}
return { inject, apply };
},
});