70160
Ce
cel-tui / files
cel-tui / packages / core / src / state-identity.ts
2.8 KB
1import type { Node, StateKey } from "@cel-tui/types"; 2import type { LayoutNode } from "./layout.js"; 3 4export type StatefulNodeKind = "vstack" | "hstack" | "textinput"; 5 6export interface MountedStateNode { 7 key: StateKey; 8 kind: StatefulNodeKind; 9 identity: string; 10 layerIndex: number; 11 layoutNode: LayoutNode; 12} 13 14export interface MountedStateSnapshot { 15 byKey: Map<StateKey, MountedStateNode>; 16 textInputKeys: Set<StateKey>; 17 stateIdentities: Set<string>; 18 containerIdentities: Set<string>; 19 layerIdentities: Set<string>; 20} 21 22function encodeStateKey(key: StateKey): string { 23 if (typeof key === "string") return `s:${JSON.stringify(key)}`; 24 return `n:${String(Object.is(key, -0) ? 0 : key)}`; 25} 26 27export function explicitStateIdentity(node: Node): string | null { 28 if (node.type === "text" || node.props.stateKey === undefined) return null; 29 return `K:${node.type}:${encodeStateKey(node.props.stateKey)}`; 30} 31 32export function layerIdentity(root: LayoutNode, index: number): string { 33 const explicit = explicitStateIdentity(root.node); 34 return explicit === null ? `L:${index}` : `L:${explicit}`; 35} 36 37function keyDescription(key: StateKey): string { 38 if (typeof key === "string") return JSON.stringify(key); 39 return String(key); 40} 41 42/** Inspect and validate every explicit state identity in laid-out layers. */ 43export function inspectMountedStateKeys( 44 layouts: readonly LayoutNode[], 45): MountedStateSnapshot { 46 const byKey = new Map<StateKey, MountedStateNode>(); 47 const textInputKeys = new Set<StateKey>(); 48 const stateIdentities = new Set<string>(); 49 const containerIdentities = new Set<string>(); 50 const layerIdentities = new Set<string>(); 51 52 const visit = (layoutNode: LayoutNode, layerIndex: number): void => { 53 const { node } = layoutNode; 54 const identity = explicitStateIdentity(node); 55 if (identity !== null && node.type !== "text") { 56 const key = node.props.stateKey as StateKey; 57 if (byKey.has(key)) { 58 throw new Error( 59 `Duplicate stateKey ${keyDescription(key)} in viewport`, 60 ); 61 } 62 63 const mounted: MountedStateNode = { 64 key, 65 kind: node.type, 66 identity, 67 layerIndex, 68 layoutNode, 69 }; 70 byKey.set(key, mounted); 71 stateIdentities.add(identity); 72 if (node.type === "textinput") { 73 textInputKeys.add(key); 74 } else { 75 containerIdentities.add(identity); 76 } 77 } 78 79 for (const child of layoutNode.children) visit(child, layerIndex); 80 }; 81 82 for (let i = 0; i < layouts.length; i++) { 83 const root = layouts[i]; 84 if (!root) throw new Error(`Missing layout root at index ${i}`); 85 layerIdentities.add(layerIdentity(root, i)); 86 visit(root, i); 87 } 88 89 return { 90 byKey, 91 textInputKeys, 92 stateIdentities, 93 containerIdentities, 94 layerIdentities, 95 }; 96}