Files
booksorter/src/web/camera.ts
T

35 lines
1.2 KiB
TypeScript

import { useEffect, useState } from 'preact/hooks';
/** What the Scan screen's camera tells the settings panel: which cameras exist, which is chosen, the stream size. */
export interface CameraInfo { devices: { id: string; label: string }[]; deviceId: string; resolution: string }
const CAMERA_KEY = 'camera';
const readFlag = (k: string) => { try { return localStorage.getItem(k); } catch { return null; } };
export const writeFlag = (k: string, v: string | null) => {
try { if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* ignore */ }
};
export { readFlag };
let info: CameraInfo = { devices: [], deviceId: readFlag(CAMERA_KEY) ?? '', resolution: '' };
const listeners = new Set<() => void>();
export const getCamera = () => info;
export function updateCamera(patch: Partial<CameraInfo>): void {
info = { ...info, ...patch };
listeners.forEach(l => l());
}
export function chooseCamera(deviceId: string): void {
writeFlag(CAMERA_KEY, deviceId || null);
updateCamera({ deviceId });
}
export function useCamera(): CameraInfo {
const [, force] = useState(0);
useEffect(() => {
const l = () => force(n => n + 1);
listeners.add(l);
return () => { listeners.delete(l); };
}, []);
return info;
}