- @vitejs/plugin-legacy: browsers without import.meta.resolve (older than Chrome 105 / Firefox 106 / Safari 16.4) load a second copy built for Chrome 79 / Firefox 78 / Safari 13 with polyfills. The modern targets and the stylesheet stay on Vite's own defaults, so modern chunks are byte-identical to before (only plugin-legacy's 230-byte guard in the entry). - terminal/src/compat.js (legacy copy only): swaps in <name>.compat.css (lightningcss for the older targets), sets container-size variables for signage slides, emulates flex gap. - @xenia/signage cq()/CQ_BOX: container units as before where supported, calc(var()) fallback otherwise; EmbeddedSlide no longer uses inline `inset`. - Shared Notice (@xenia/ui); "Devices that work" in Pair a device and Signage -> Screens (EN/EL). - tests/e2e/compat.mjs: modern browser loads nothing extra; a simulated older TV runs the legacy copy and the layer, pairs, and plays a slide at the same sizes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
355 lines
18 KiB
React
355 lines
18 KiB
React
// Devices page (plan step 2.6d, APPS_PLATFORM D-8, §6.3): screens and terminals paired
|
|
// with the venue, each running one app. Backend: /api/devices (step 1.8, core.devices.manage).
|
|
// - Pair: the device shows a 6-character code (POST /api/devices/pair-request on its side);
|
|
// the manager enters it here with the app, a name, how staff sign in on it and an optional
|
|
// linked device → POST /api/devices. The license limit per app is shown and enforced
|
|
// (license.limit_reached).
|
|
// - Edit (name, sign-in mode, link) → PATCH; change app → POST /reassign (signs out whoever
|
|
// is on it); remove → POST /revoke (the device goes back to its pairing screen).
|
|
// - Per-app settings (3.1a): each app's device_app.config fields are rendered by
|
|
// DeviceConfigFields in the pair and edit dialogs and sent as `config`.
|
|
import { useCallback, useEffect, useMemo, useState } from 'react'
|
|
import { useSearchParams } from 'react-router-dom'
|
|
import toast from 'react-hot-toast'
|
|
import { MonitorSmartphone, Plus } from 'lucide-react'
|
|
import { DeviceSupport } from './DeviceSupport'
|
|
import { errorMessage, parseError } from '@xenia/api'
|
|
import { useTranslation, useFormat } from '@xenia/i18n'
|
|
import { Button, Dialog, EmptyState, Field, Input, Page, Select, Spinner } from '@xenia/ui'
|
|
import client from '../../api/client'
|
|
import DeviceConfigFields from './DeviceConfigFields'
|
|
import { configInitial, deviceStatus, deviceUsage, hasRoom, linkTargets, normalizeCode } from './devicesLogic'
|
|
|
|
const STATUS_TONE = {
|
|
online: 'bg-success-soft text-success-ink',
|
|
offline: 'bg-surface-2 text-ink-2',
|
|
waiting: 'bg-info-soft text-info-ink',
|
|
app_off: 'bg-warning-soft text-warning-ink',
|
|
removed: 'bg-surface-2 text-ink-3',
|
|
}
|
|
|
|
export default function DevicesPage() {
|
|
const { t } = useTranslation('manager')
|
|
const f = useFormat()
|
|
const [devices, setDevices] = useState(null)
|
|
const [modules, setModules] = useState(null)
|
|
const [showRemoved, setShowRemoved] = useState(false)
|
|
const [error, setError] = useState(null)
|
|
const [dialog, setDialog] = useState(null) // { kind: 'pair' | 'edit' | 'app' | 'remove', device? }
|
|
|
|
const load = useCallback(async () => {
|
|
try {
|
|
const [d, m] = await Promise.all([
|
|
client.get('/api/devices', { params: { include_revoked: showRemoved } }),
|
|
client.get('/api/platform/modules'),
|
|
])
|
|
setDevices(d.data)
|
|
setModules(m.data.modules)
|
|
setError(null)
|
|
} catch (err) {
|
|
setError(errorMessage(err, t))
|
|
}
|
|
}, [showRemoved, t])
|
|
|
|
useEffect(() => { load() }, [load])
|
|
|
|
const apps = useMemo(() => (modules || []).filter(m => m.device_app), [modules])
|
|
|
|
// /devices?pair=<app> (Apps → "Set up a screen", 3.2d): open the pair dialog on that app
|
|
const [params, setParams] = useSearchParams()
|
|
const pairApp = params.get('pair')
|
|
useEffect(() => {
|
|
if (!pairApp || !modules) return
|
|
setDialog({ kind: 'pair', app: pairApp })
|
|
setParams({}, { replace: true })
|
|
}, [pairApp, modules, setParams])
|
|
const appOn = key => !!apps.find(a => a.key === key)?.effective
|
|
const usage = useMemo(() => (devices && modules ? deviceUsage(devices, modules) : {}), [devices, modules])
|
|
const appName = key => t(`modules:${key}.name`, { defaultValue: key })
|
|
const limitLabel = key => t(`modules:${key}.limits.devices`, { defaultValue: appName(key) })
|
|
const byId = id => devices?.find(d => d.id === id)
|
|
|
|
/** A refusal for one more device of `app`: say it with the app's own words. */
|
|
const explain = useCallback(err => {
|
|
const x = parseError(err)
|
|
if (x.code === 'license.limit_reached') return t('devices.limitReached', { label: limitLabel(x.params.module), max: x.params.max })
|
|
return errorMessage(err, t)
|
|
}, [t]) // eslint-disable-line react-hooks/exhaustive-deps
|
|
|
|
async function act(fn, okText) {
|
|
try {
|
|
await fn()
|
|
setDialog(null)
|
|
if (okText) toast.success(okText)
|
|
await load()
|
|
return null
|
|
} catch (err) {
|
|
return explain(err)
|
|
}
|
|
}
|
|
|
|
if (error) return <div className="p-8"><EmptyState title={error} action={<Button variant="secondary" onClick={load}>{t('common:actions.retry')}</Button>} /></div>
|
|
if (!devices || !modules) return <div className="p-8 flex justify-center"><Spinner /></div>
|
|
|
|
const live = devices.filter(d => !d.revoked_at)
|
|
const signInLabel = d => {
|
|
const modes = apps.find(a => a.key === d.app_key)?.device_app?.login_modes || []
|
|
if (d.login_mode || modes.length < 2) return t(`devices.signIn.${d.effective_login_mode}`) // its own choice, or the only one the app has
|
|
return t('devices.signIn.default', { mode: t(`devices.signIn.${d.effective_login_mode}`) })
|
|
}
|
|
const statusText = d => {
|
|
const s = deviceStatus(d, { appOn: appOn(d.app_key) })
|
|
if (s === 'offline') return d.last_seen_at ? t('devices.status.offline', { when: f.formatRelative(d.last_seen_at) }) : t('devices.status.offlineNever')
|
|
if (s === 'removed') return t('devices.status.removed', { when: f.formatRelative(d.revoked_at) })
|
|
return t(`devices.status.${s}`)
|
|
}
|
|
|
|
return (
|
|
<Page>
|
|
<div className="flex flex-wrap items-start gap-4 justify-between">
|
|
<p className="text-body text-ink-2 max-w-2xl">{t('devices.intro')}</p>
|
|
<Button icon={<Plus size={16} />} onClick={() => setDialog({ kind: 'pair' })}>{t('devices.pair')}</Button>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap gap-2" data-testid="device-usage">
|
|
{apps.filter(a => a.effective).map(a => {
|
|
const u = usage[a.key] || { used: 0, max: null }
|
|
return (
|
|
<span key={a.key} className={`rounded-full px-3 py-1 text-label ${u.max != null && u.used >= u.max ? 'bg-warning-soft text-warning-ink' : 'bg-surface-2 text-ink-2'}`}>
|
|
{u.max == null
|
|
? t('devices.usageUnlimited', { label: limitLabel(a.key), used: u.used })
|
|
: t('devices.usage', { label: limitLabel(a.key), used: u.used, max: u.max })}
|
|
</span>
|
|
)
|
|
})}
|
|
</div>
|
|
|
|
{devices.length === 0
|
|
? <EmptyState icon={<MonitorSmartphone />} title={t('devices.empty')} description={t('devices.emptyBody')} />
|
|
: (
|
|
<div className="bg-surface border border-line rounded-card shadow-raised overflow-x-auto">
|
|
<table className="w-full text-body" data-testid="devices-table">
|
|
<thead>
|
|
<tr className="text-left text-label text-ink-3 border-b border-line">
|
|
{['device', 'app', 'status', 'signIn', 'linked', 'actions'].map(c => <th key={c} className="px-4 py-2.5 font-medium">{t(`devices.columns.${c}`)}</th>)}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{devices.map(d => {
|
|
const s = deviceStatus(d, { appOn: appOn(d.app_key) })
|
|
return (
|
|
<tr key={d.id} className="border-b border-line last:border-0" data-testid={`device-${d.id}`} data-status={s}>
|
|
<td className="px-4 py-3">
|
|
<div className="font-medium text-ink">{d.name}</div>
|
|
<div className="text-caption text-ink-3">{f.formatDate(d.paired_at, 'dateMedium')}</div>
|
|
</td>
|
|
<td className="px-4 py-3 text-ink-2">{appName(d.app_key)}</td>
|
|
<td className="px-4 py-3"><span className={`rounded-full px-2.5 py-0.5 text-caption font-medium ${STATUS_TONE[s]}`}>{statusText(d)}</span></td>
|
|
<td className="px-4 py-3 text-ink-2">{d.revoked_at ? '—' : signInLabel(d)}</td>
|
|
<td className="px-4 py-3 text-ink-2">{byId(d.linked_device_id)?.name || '—'}</td>
|
|
<td className="px-4 py-3 whitespace-nowrap text-right">
|
|
{!d.revoked_at && (
|
|
<div className="inline-flex gap-1">
|
|
<Button size="sm" variant="ghost" onClick={() => setDialog({ kind: 'edit', device: d })}>{t('devices.actions.edit')}</Button>
|
|
<Button size="sm" variant="ghost" onClick={() => setDialog({ kind: 'app', device: d })}>{t('devices.actions.changeApp')}</Button>
|
|
<Button size="sm" variant="ghost" className="text-danger-ink" onClick={() => setDialog({ kind: 'remove', device: d })}>{t('devices.actions.remove')}</Button>
|
|
</div>
|
|
)}
|
|
</td>
|
|
</tr>
|
|
)
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
|
|
<label className="inline-flex items-center gap-2 text-label text-ink-2 cursor-pointer w-fit">
|
|
<input type="checkbox" checked={showRemoved} onChange={e => setShowRemoved(e.target.checked)} />
|
|
{t('devices.showRemoved')}
|
|
</label>
|
|
|
|
{dialog?.kind === 'pair' && (
|
|
<PairDialog apps={apps} usage={usage} devices={live} appName={appName} limitLabel={limitLabel} initialApp={dialog.app}
|
|
onClose={() => setDialog(null)}
|
|
onPair={body => act(() => client.post('/api/devices', body), t('devices.paired', { name: body.name }))} />
|
|
)}
|
|
{dialog?.kind === 'edit' && (
|
|
<EditDialog device={dialog.device} apps={apps} devices={live}
|
|
onClose={() => setDialog(null)}
|
|
onSave={body => act(() => client.patch(`/api/devices/${dialog.device.id}`, body), t('devices.saved'))} />
|
|
)}
|
|
{dialog?.kind === 'app' && (
|
|
<ChangeAppDialog device={dialog.device} apps={apps} usage={usage} appName={appName}
|
|
onClose={() => setDialog(null)}
|
|
onSave={appKey => act(() => client.post(`/api/devices/${dialog.device.id}/reassign`, { app_key: appKey }), t('devices.saved'))} />
|
|
)}
|
|
{dialog?.kind === 'remove' && (
|
|
<RemoveDialog device={dialog.device} onClose={() => setDialog(null)}
|
|
onRemove={() => act(() => client.post(`/api/devices/${dialog.device.id}/revoke`))} />
|
|
)}
|
|
</Page>
|
|
)
|
|
}
|
|
|
|
function loginModeOptions(app, t) {
|
|
const modes = app?.device_app?.login_modes || []
|
|
if (modes.length < 2) return null
|
|
return [{ value: '', label: t('devices.signIn.defaultPlain') }, ...modes.map(m => ({ value: m, label: t(`devices.signIn.${m}`) }))]
|
|
}
|
|
|
|
function useSubmit(fn) {
|
|
const [busy, setBusy] = useState(false)
|
|
const [error, setError] = useState('')
|
|
const run = async (...args) => {
|
|
setBusy(true)
|
|
setError('')
|
|
const err = await fn(...args)
|
|
setBusy(false)
|
|
if (err) setError(err)
|
|
}
|
|
return { busy, error, run }
|
|
}
|
|
|
|
function PairDialog({ apps, usage, devices, appName, limitLabel, initialApp, onClose, onPair }) {
|
|
const { t } = useTranslation('manager')
|
|
const usable = apps.filter(a => a.effective)
|
|
const [code, setCode] = useState('')
|
|
const [appKey, setAppKey] = useState(usable.find(a => a.key === initialApp)?.key || usable.find(a => hasRoom(usage, a.key))?.key || usable[0]?.key || '')
|
|
const [name, setName] = useState('')
|
|
const [mode, setMode] = useState('')
|
|
const [link, setLink] = useState('')
|
|
const app = apps.find(a => a.key === appKey)
|
|
const fields = app?.device_app?.config || []
|
|
const [config, setConfig] = useState(() => configInitial(fields))
|
|
const { busy, error, run } = useSubmit(onPair)
|
|
const full = appKey && !hasRoom(usage, appKey)
|
|
const modes = loginModeOptions(app, t)
|
|
const ready = code.length === 6 && appKey && name.trim() && !full
|
|
|
|
const submit = e => {
|
|
e.preventDefault()
|
|
if (!ready || busy) return
|
|
run({ code, app_key: appKey, name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null,
|
|
config: fields.length ? config : null })
|
|
}
|
|
|
|
return (
|
|
<Dialog open onClose={onClose} title={t('devices.pair')}
|
|
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button type="submit" form="pair-form" loading={busy} disabled={!ready}>{t('devices.pair')}</Button></>}>
|
|
{usable.length === 0
|
|
? <p>{t('devices.form.noApps')}</p>
|
|
: (
|
|
<form id="pair-form" onSubmit={submit} className="grid gap-4">
|
|
<Field label={t('devices.form.code')} hint={t('devices.form.codeHint')}>
|
|
<Input value={code} onChange={e => setCode(normalizeCode(e.target.value))} autoComplete="off" spellCheck={false}
|
|
className="font-mono tracking-[0.3em] text-center uppercase" autoFocus />
|
|
</Field>
|
|
<DeviceSupport />
|
|
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: limitLabel(appKey), max: usage[appKey].max }) : undefined}>
|
|
<Select value={appKey} onChange={e => {
|
|
const next = e.target.value
|
|
setAppKey(next); setMode('')
|
|
setConfig(configInitial(apps.find(a => a.key === next)?.device_app?.config))
|
|
}}
|
|
options={usable.map(a => ({ value: a.key, label: appName(a.key) }))} />
|
|
</Field>
|
|
<Field label={t('devices.form.name')}>
|
|
<Input value={name} onChange={e => setName(e.target.value)} placeholder={t('devices.form.namePlaceholder')} maxLength={60} />
|
|
</Field>
|
|
{modes && (
|
|
<Field label={t('devices.form.signIn')}>
|
|
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
|
|
</Field>
|
|
)}
|
|
{devices.length > 0 && (
|
|
<Field label={t('devices.form.link')} hint={t('devices.form.linkHint')}>
|
|
<Select value={link} onChange={e => setLink(e.target.value)}
|
|
options={[{ value: '', label: t('devices.form.noLink') }, ...linkTargets(devices).map(d => ({ value: String(d.id), label: d.name }))]} />
|
|
</Field>
|
|
)}
|
|
<DeviceConfigFields appKey={appKey} fields={fields} value={config} onChange={setConfig} devices={devices} />
|
|
{error && <p className="text-label text-danger-ink" role="alert" data-testid="pair-error">{error}</p>}
|
|
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
|
|
</form>
|
|
)}
|
|
</Dialog>
|
|
)
|
|
}
|
|
|
|
function EditDialog({ device, apps, devices, onClose, onSave }) {
|
|
const { t } = useTranslation('manager')
|
|
const [name, setName] = useState(device.name)
|
|
const [mode, setMode] = useState(device.login_mode || '')
|
|
const [link, setLink] = useState(device.linked_device_id ? String(device.linked_device_id) : '')
|
|
const app = apps.find(a => a.key === device.app_key)
|
|
const fields = app?.device_app?.config || []
|
|
const [config, setConfig] = useState(() => configInitial(fields, device.config))
|
|
const { busy, error, run } = useSubmit(onSave)
|
|
const modes = loginModeOptions(app, t)
|
|
const targets = linkTargets(devices, device.id)
|
|
|
|
const submit = e => {
|
|
e.preventDefault()
|
|
if (!name.trim() || busy) return
|
|
run({ name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null,
|
|
...(fields.length ? { config } : {}) })
|
|
}
|
|
|
|
return (
|
|
<Dialog open onClose={onClose} title={device.name}
|
|
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button type="submit" form="edit-form" loading={busy}>{t('devices.actions.save')}</Button></>}>
|
|
<form id="edit-form" onSubmit={submit} className="grid gap-4">
|
|
<Field label={t('devices.form.name')}>
|
|
<Input value={name} onChange={e => setName(e.target.value)} maxLength={60} />
|
|
</Field>
|
|
{modes && (
|
|
<Field label={t('devices.form.signIn')}>
|
|
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
|
|
</Field>
|
|
)}
|
|
{targets.length > 0 && (
|
|
<Field label={t('devices.form.link')} hint={t('devices.form.linkHint')}>
|
|
<Select value={link} onChange={e => setLink(e.target.value)}
|
|
options={[{ value: '', label: t('devices.form.noLink') }, ...targets.map(d => ({ value: String(d.id), label: d.name }))]} />
|
|
</Field>
|
|
)}
|
|
<DeviceConfigFields appKey={device.app_key} fields={fields} value={config} onChange={setConfig} devices={devices} selfId={device.id} />
|
|
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
|
|
<button type="submit" hidden aria-hidden="true" tabIndex={-1} />
|
|
</form>
|
|
</Dialog>
|
|
)
|
|
}
|
|
|
|
function ChangeAppDialog({ device, apps, usage, appName, onClose, onSave }) {
|
|
const { t } = useTranslation('manager')
|
|
const usable = apps.filter(a => a.effective)
|
|
const [appKey, setAppKey] = useState(device.app_key)
|
|
const { busy, error, run } = useSubmit(onSave)
|
|
const full = appKey !== device.app_key && !hasRoom(usage, appKey)
|
|
|
|
return (
|
|
<Dialog open onClose={onClose} title={`${t('devices.actions.changeApp')}: ${device.name}`} description={t('devices.changeAppBody')}
|
|
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button loading={busy} disabled={appKey === device.app_key || full} onClick={() => run(appKey)}>{t('devices.actions.save')}</Button></>}>
|
|
<div className="grid gap-4">
|
|
<Field label={t('devices.form.app')} error={full ? t('devices.form.full', { label: t(`modules:${appKey}.limits.devices`), max: usage[appKey].max }) : undefined}>
|
|
<Select value={appKey} onChange={e => setAppKey(e.target.value)} options={usable.map(a => ({ value: a.key, label: appName(a.key) }))} />
|
|
</Field>
|
|
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
|
|
</div>
|
|
</Dialog>
|
|
)
|
|
}
|
|
|
|
function RemoveDialog({ device, onClose, onRemove }) {
|
|
const { t } = useTranslation('manager')
|
|
const { busy, error, run } = useSubmit(onRemove)
|
|
return (
|
|
<Dialog open size="sm" onClose={onClose} title={t('devices.removeTitle', { name: device.name })} description={t('devices.removeBody')}
|
|
footer={<><Button variant="secondary" onClick={onClose}>{t('common:actions.cancel')}</Button><Button variant="danger" loading={busy} onClick={() => run()}>{t('devices.actions.remove')}</Button></>}>
|
|
{error && <p className="text-label text-danger-ink" role="alert">{error}</p>}
|
|
</Dialog>
|
|
)
|
|
}
|