// The GM token panel's pure half (T11/#74, #78): local validation of the vision controls and the // fields the panel sends for `token.create` / `token.update` (DESIGN 6.1, 8). No DOM, no socket. // // `flags` is free-form (DESIGN 8): an edit writes only the `vision` key and copies every other key // from the current GM `token` frame, so future GM flags survive a save. A new token keeps the // DESIGN 8 default (`flags: '{}'`): vision off means no `flags` field is sent at all. // // `vision_radius` is also the player's move step cap (DESIGN 5.5), so the panel validates it like // the token radius: blank = scene default (`null`), anything else must be > 0 and finite. /** The vision part of a `token.create` / `token.update` payload. */ export interface VisionFields { /** Present only when the panel writes a flag (create with vision on, or any edit). */ flags?: Record vision_radius: number | null } export type VisionFieldsResult = | { ok: true; fields: VisionFields } | { ok: false; error: string } export type VisionUpdateResult = | { ok: true; fields: { id: string; flags: Record; vision_radius: number | null } } | { ok: false; error: string } type RadiusResult = { ok: true; value: number | null } | { ok: false; error: string } /** Blank is the scene default; non-finite and non-positive values are refused before the wire. */ export function parseVisionRadius(raw: string): RadiusResult { const text = raw.trim() if (text === '') return { ok: true, value: null } const value = Number(text) if (!Number.isFinite(value) || value <= 0) { return { ok: false, error: 'Vision radius must be a positive number or blank for the scene default.', } } return { ok: true, value } } /** Copy `flags` and set only `vision`; every other GM flag survives (DESIGN 8). */ export function withVisionFlag( flags: Record, vision: boolean, ): Record { return { ...flags, vision } } /** * `token.create` vision fields. Vision off sends no `flags`, so the server keeps its DESIGN 8 * default (`{}`); vision on carries only the one key. */ export function createVisionFields(vision: boolean, rawRadius: string): VisionFieldsResult { const radius = parseVisionRadius(rawRadius) if (!radius.ok) return radius return { ok: true, fields: vision ? { flags: { vision: true }, vision_radius: radius.value } : { vision_radius: radius.value }, } } /** `token.update` vision fields: the stored flags are the base, never a rebuilt object. */ export function updateVisionFields( id: string, flags: Record, vision: boolean, rawRadius: string, ): VisionUpdateResult { const radius = parseVisionRadius(rawRadius) if (!radius.ok) return radius return { ok: true, fields: { id, flags: withVisionFlag(flags, vision), vision_radius: radius.value }, } }