Calio/tests/scanner.test.js
Elijah 0ff7279cf6
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 46s
Fix touch input highlights and barcode camera focus
Remove field focus outlines. Preserve camera constraints across light and focus changes, fall back to one-shot autofocus, and offer supported manual focus, lens selection, and camera restart. Add scanner regression coverage.
2026-10-25 11:02:36 -07:00

153 lines
7 KiB
JavaScript

import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import vm from "node:vm";
import ts from "typescript";
// Mount the real scanner with a browser-shaped camera. This exercises startup
// and the actual UI handlers without needing permission or physical hardware.
async function mount({ modes = ["continuous", "single-shot"], rejectContinuous = false, capabilities = {} } = {}) {
const calls = [];
let constraints = { width: { ideal: 1920 }, height: { ideal: 1080 } };
let settings = {};
let stops = 0;
const camera = {
getCapabilities: () => ({ focusMode: modes, torch: true, ...capabilities }),
getConstraints: () => constraints,
getSettings: () => settings,
stop: () => stops++,
async applyConstraints(next) {
calls.push(next);
const applied = Object.assign({}, next, ...(next.advanced ?? []));
const mode = applied.focusMode?.exact ?? applied.focusMode;
if (mode === "continuous" && rejectContinuous) throw new Error("Focus rejected");
constraints = next;
settings = { focusMode: mode, focusDistance: applied.focusDistance, torch: applied.torch };
},
};
const stream = { getTracks: () => [camera], getVideoTracks: () => [camera] };
const video = { play: async () => {}, videoWidth: 0, videoHeight: 0 };
const refs = [], states = [], effects = [];
let refIndex = 0, stateIndex = 0, mounted = false;
const jsx = (type, props) => ({ type, props });
const react = {
useRef(initial) {
const index = refIndex++;
return refs[index] ??= { current: index === 0 ? video : initial };
},
useState(initial) {
const index = stateIndex++;
if (!(index in states)) states[index] = initial;
return [states[index], value => { states[index] = typeof value === "function" ? value(states[index]) : value; }];
},
useEffect(effect) { if (!mounted) effects.push(effect); },
};
const cache = new Map();
function load(file) {
if (cache.has(file.href)) return cache.get(file.href);
const exports = {};
cache.set(file.href, exports);
const context = {
exports,
require(name) {
if (name === "react") return react;
if (name === "react/jsx-runtime") return { jsx, jsxs: jsx };
if (name === "lucide-react") return {};
if (name === "./components") return { Modal: "Modal" };
if (name === "./scan") return { barcodeDetector: async () => ({}), detectBarcode: async () => null };
if (name === "../shared/barcode.js") return { normalizeBarcode: () => null };
return load(new URL(name + ".ts", file));
},
navigator: { mediaDevices: { getUserMedia: async () => stream } },
document: { createElement: () => ({ getContext: () => ({}) }) },
window: { setTimeout: () => 1 }, clearTimeout() {},
};
vm.runInNewContext(ts.transpileModule(readFileSync(file, "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX },
}).outputText, context);
return exports;
}
const { BarcodeScanner } = load(new URL("../src/Scanner.tsx", import.meta.url));
const render = () => {
refIndex = stateIndex = 0;
return BarcodeScanner({ close() {}, detected() {} });
};
render();
mounted = true;
const cleanups = effects.map(effect => effect());
const settle = () => new Promise(resolve => setImmediate(resolve));
await settle();
const walk = (predicate, tree) => {
if (!tree || typeof tree !== "object") return;
if (predicate(tree)) return tree;
for (const child of [tree.props?.children].flat(Infinity)) {
const result = walk(predicate, child);
if (result) return result;
}
};
return { camera, calls, find: predicate => walk(predicate, render()), settle, cleanup: () => cleanups.forEach(fn => fn?.()), stops: () => stops };
}
test("scanner falls back to one-shot autofocus when continuous focus fails", async () => {
const app = await mount({ rejectContinuous: true });
assert.equal(app.camera.getSettings().focusMode, "single-shot");
app.find(node => node.props?.children === "Refocus").props.onClick();
await app.settle();
assert.equal(app.calls.filter(call => call.advanced?.some(entry => entry.focusMode === "single-shot")).length, 2);
app.cleanup();
});
test("switching the scanner light preserves autofocus and video constraints", async () => {
const app = await mount();
await app.find(node => node.props?.className === "scanner-torch").props.onClick();
await app.settle();
assert.equal(app.camera.getSettings().focusMode, "continuous");
assert.equal(app.camera.getSettings().torch, true);
assert.equal(app.camera.getConstraints().width.ideal, 1920);
app.cleanup();
assert.equal(app.stops(), 1);
});
test("manual focus locks the chosen distance and survives light changes", async () => {
const app = await mount({
modes: ["continuous", "manual"],
capabilities: { focusDistance: { min: 0, max: 10, step: 0.1 } },
});
const slider = () => app.find(node => node.type === "input" && node.props.type === "range");
assert.equal(slider().props.min, 0);
assert.equal(slider().props.max, 10);
// Simulate a fast drag: queued requests must retain the final position.
slider().props.onChange({ target: { value: "2" } });
slider().props.onChange({ target: { value: "3" } });
await app.settle();
assert.equal(app.camera.getSettings().focusMode, "manual");
assert.equal(app.camera.getSettings().focusDistance, 3);
assert.equal(slider().props.value, 3);
await app.find(node => node.props?.className === "scanner-torch").props.onClick();
assert.equal(app.camera.getSettings().focusMode, "manual");
assert.equal(app.camera.getSettings().focusDistance, 3);
assert.equal(app.camera.getSettings().torch, true);
app.find(node => node.props?.children === "Use autofocus").props.onClick();
await app.settle();
assert.equal(app.camera.getSettings().focusMode, "continuous");
assert.equal(app.camera.getSettings().torch, true);
app.cleanup();
});
test("scanner stays usable when the browser exposes no focus controls", async () => {
const app = await mount({ modes: [] });
assert.equal(app.calls.length, 0);
assert.equal(app.find(node => node.type === "input" && node.props.type === "range"), undefined);
assert.ok(app.find(node => node.props?.className === "scanner-view live"));
assert.ok(app.find(node => node.props?.onClick && Array.isArray(node.props.children) && node.props.children.includes("Restart camera")));
app.cleanup();
});
test("manual-only cameras offer fixed focus without an unsupported autofocus button", async () => {
const app = await mount({ modes: ["manual"], capabilities: { focusDistance: { min: 0, max: 1 } } });
app.find(node => node.type === "input" && node.props.type === "range").props.onChange({ target: { value: "0.4" } });
await app.settle();
assert.equal(app.camera.getSettings().focusMode, "manual");
assert.equal(app.find(node => node.props?.children === "Use autofocus"), undefined);
app.cleanup();
});