@nick-skriabin/glyph 0.1.48 → 0.1.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/index.d.ts +37 -1
- package/dist/index.js +14 -14
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/reconciler/nodes.ts","../src/reconciler/hostConfig.ts","../src/reconciler/reconciler.ts","../src/runtime/terminal.ts","../src/runtime/input.ts","../src/paint/color.ts","../src/paint/framebuffer.ts","../src/paint/borders.ts","../src/layout/textMeasure.ts","../src/paint/painter.ts","../src/paint/diff.ts","../src/layout/yogaLayout.ts","../src/hooks/context.ts","../src/render.ts","../src/components/Box.tsx","../src/components/Text.tsx","../src/components/Input.tsx","../src/components/FocusScope.tsx","../src/components/Spacer.tsx","../src/components/Keybind.tsx","../src/components/Portal.tsx","../src/components/Button.tsx","../src/hooks/useLayout.ts","../src/hooks/useInput.ts","../src/components/ScrollView.tsx","../src/components/List.tsx","../src/components/Menu.tsx","../src/components/Progress.tsx","../src/components/Spinner.tsx","../src/components/Toast.tsx","../src/components/Select.tsx","../src/components/Checkbox.tsx","../src/components/Radio.tsx","../src/components/Dialog.tsx","../src/components/JumpNav.tsx","../src/hooks/useFocus.ts","../src/hooks/useFocusable.ts","../src/hooks/useApp.ts","../src/hooks/useFocusRegistry.ts","../src/utils/mask.ts"],"names":["nextFocusId","generateFocusId","createGlyphNode","type","props","style","appendChild","parent","child","removeChild","idx","insertBefore","beforeChild","getInheritedTextStyle","node","result","current","s","collectTextContent","DefaultEventPriority","hostConfig","_priority","_callback","_type","_props","_instance","methodName","args","_errorPrefix","_rootContainer","_hostContext","_internalHandle","text","parentInstance","textChild","t","parentHostContext","instance","_containerInfo","containerInfo","container","before","textInstance","_oldText","newText","_oldProps","newProps","reconciler","ReactReconciler","Terminal","stdout","stdin","data","x","y","color","str","handler","raw","clean","i","ch","code","match","index","r","g","b","resolve","done","timeout","query","doCleanup","handleSignal","signal","err","getKeyNameFromCode","getTildeKeyName","param","applyModifiers","key","mod","m","parseKeySequence","keys","seq","parseCsiSequence","parseSs3Sequence","letter","start","final","sequence","params","modParts","keyCode","parts","NAMED_FG","NAMED_BG","parseHex","hex","h","colorToFg","colorToBg","NAMED_RGB","NAMED_INDEX","terminalPalette","setTerminalPalette","palette","resolveNamedRgb","name","tp","colorToRgb","c","isLightColor","rgb","colorsEqual","a","getContrastCursorColor","bg","Framebuffer","_Framebuffer","width","height","cell","fg","bold","dim","italic","underline","w","row","col","fb","BORDER_CHARS","getBorderChars","measureText","maxWidth","widthMode","wrapMode","lines","MeasureMode","maxW","line","stringWidth","availWidth","wrappedLines","wrapLines","truncateLine","truncateWithEllipsis","wrapped","wordWrap","char","charWidth","truncated","currentLine","currentWidth","wordBuffer","wordBufferWidth","isEnd","isSpace","cw","paintTree","roots","options","entries","screenClip","root","collectPaintEntries","entry","nodeResult","paintNode","parentClip","parentZ","zIndex","clip","intersectClip","right","bottom","isInClip","innerX","innerY","innerWidth","innerHeight","effectiveBg","borderChars","bc","setClipped","paintText","paintInput","autoContrastFg","explicitColor","inherited","textAlign","rawLines","lineIdx","lineWidth","offsetX","cursorInfo","useNativeCursor","value","placeholder","displayText","isPlaceholder","multiline","autoFg","placeholderFg","textFg","textDim","isFocused","cursorScreenLine","cursorScreenCol","pos","logicalLine","offsetInLogicalLine","runningPos","lineLen","wrappedLinesBefore","wrappedCurrentLine","charsProcessed","subLineIdx","subLine","scrollOffset","rowIdx","lineNum","screenRow","cCol","cursorX","cursorY","existing","cursorChar","cursorFg","cursorBg","cursorCol","ESC","CSI","moveCursor","buildSGR","diffFramebuffers","prev","next","fullRedraw","out","lastX","lastY","lastSGR","nc","pc","sgr","FLEX_DIR_MAP","FlexDirection","JUSTIFY_MAP","Justify","ALIGN_MAP","Align","setDimension","setter","setPosition","edge","applyStyleToYogaNode","yogaNode","nodeType","v","Edge","hasBorder","Wrap","Gutter","PositionType","Overflow","buildYogaTree","Yoga","heightMode","collectAllText","extractLayout","parentX","parentY","yn","computedLayout","borderWidth","paddingTop","paddingRight","paddingBottom","paddingLeft","computeLayout","screenWidth","screenHeight","rootYoga","Direction","clearYogaRefs","nodes","InputContext","createContext","FocusContext","LayoutContext","AppContext","ScrollViewContext","render","element","opts","debug","terminal","nativeCursorVisible","scheduleRender","prevFb","currentFb","inputHandlers","priorityHandlers","focusedInputHandlers","inputContextValue","focusId","focusedId","focusRegistry","focusOrder","skippableIds","trapStack","focusChangeHandlers","setFocusedId","id","getActiveFocusableIds","ids","trap","nodeA","nodeB","layoutA","layoutB","focusContextValue","activeIds","nextIdx","prevIdx","skippable","layoutSubscriptions","layoutContextValue","subs","appContextValue","handle","renderScheduled","performRender","cols","rows","notifyLayoutSubscribers","focusedNode","paintResult","output","cursorColor","removeDataListener","consumed","inputHandler","removeResizeListener","handleSigcont","wrappedElement","React","onUncaughtError","error","onCaughtError","onRecoverableError","Box","forwardRef","children","focusable","ref","Text","wrap","mergedStyle","cursorToVisualLine","logicalLines","allVisualLines","logicalOffset","offsetInLogical","wrappedLine","charCount","vl","isEndOfLogicalLine","effectiveLen","lastIdx","visualLineToCursor","visualLine","visualCol","offset","targetLine","cursorToLineCol","remaining","last","lineColToCursor","Input","controlledValue","defaultValue","onChange","onKeyPress","onBeforeChange","focusedStyle","autoFocus","internalValue","setInternalValue","useState","cursorPos","setCursorPos","setInnerWidth","setIsFocused","nodeReady","setNodeReady","inputCtx","useContext","focusCtx","layoutCtx","nodeRef","useRef","focusIdRef","isControlled","useEffect","layout","rect","workingValueRef","workingCursorRef","lastSentValueRef","lastSentCursorRef","stateRef","autoFocusedRef","fid","timer","newId","ctrl","cb","onKey","onBefore","ml","val","updateValue","newVal","newCursor","finalVal","finalCursor","updateCursor","lineEnd","info","inputType","isDigit","isDecimal","isMinus","FocusScope","prevFocusRef","scopeIdsRef","useLayoutEffect","cleanup","firstId","Spacer","size","parseKeyDescriptor","descriptor","matchesKey","matcher","Keybind","keypress","onPress","whenFocused","priority","disabled","onPressRef","matcherRef","Portal","Button","DEFAULT_RECT","useLayout","ctx","setLayout","useInput","deps","ScrollView","controlledOffset","onScroll","defaultScrollOffset","scrollStep","disableKeyboard","scrollToFocus","showScrollbar","internalOffset","setInternalOffset","viewportRef","contentRef","viewportLayout","contentLayout","isSelfFocused","viewportHeight","contentHeight","maxOffset","effectiveOffset","scrollViewContextValue","useMemo","viewportY","setOffset","useCallback","clamped","findNode","found","focusedLayout","contentTopY","elementTop","elementBottom","visibleTop","visibleBottom","containsFocus","currentFocusId","halfPage","fullPage","_pad","_px","_py","_pt","_pr","_pb","_pl","styleRest","borderHeight","intrinsicHeight","outerStyle","innerStyle","isScrollable","scrollbarVisible","thumbHeight","scrollableRange","thumbPosition","scrollbarChars","scrollbarStyle","List","count","renderItem","controlledIndex","onSelectionChange","onSelect","defaultSelectedIndex","disabledIndices","internalIndex","setInternalIndex","selectedIndex","onSelectRef","lastKeyRef","setIndex","findNextEnabled","from","direction","findFirstEnabled","fromEnd","items","Menu","highlightColor","handleSelect","item","selected","focused","isDisabled","isHighlighted","indicator","Progress","indeterminate","label","showPercent","filled","empty","trackRef","trackWidth","indeterminatePos","setIndeterminatePos","p","pctText","barText","chunkSize","chars","filledCount","BRAILLE_FRAMES","Spinner","frames","intervalMs","frameIndex","setFrameIndex","ToastContext","nextToastId","useToast","VARIANT_COLORS","ToastHost","position","maxVisible","toasts","setToasts","timersRef","push","toast","full","ctxValue","isTop","isRight","portalStyle","toastElements","variant","colors","innerChildren","Select","dropdownStyle","searchable","appCtx","scrollViewCtx","onChangeRef","isOpen","setIsOpen","highlightIndex","setHighlightIndex","searchText","setSearchText","setScrollOffset","triggerLayout","screenRows","scrollViewBounds","selectedLabel","filteredItems","lower","visibleCount","visibleItems","ensureVisible","first","triggerStyle","labelColor","triggerChildren","dropdownElement","dropdownChildren","vi","itemStyle","textStyle","hasScrollUp","hasScrollDown","hasSearch","hasNoMatches","useDropdownBorder","dropdownHeight","triggerBottom","spaceBelow","spaceAbove","dropdownTop","Checkbox","checked","checkedChar","uncheckedChar","checkedRef","boxChar","boxStyle","labelStyle","Radio","focusedItemStyle","selectedItemStyle","gap","selectedChar","unselectedChar","highlightedIndex","setHighlightedIndex","selectedIdx","startIndex","containerStyle","radioItems","isSelected","isItemDisabled","radioChar","computedStyle","textColor","DialogContext","useDialog","DialogHost","dialogs","setDialogs","idCounter","alert","content","confirm","dismissDialog","dialog","d","contextValue","activeDialog","DialogOverlay","onDismiss","okButtonRef","cancelButtonRef","okFocusIdRef","cancelFocusIdRef","focusedButton","setFocusedButton","refsReady","setRefsReady","cleanups","fn","contentIsString","contentLength","getButtonStyle","button","baseStyle","defaultFocusedStyle","specificStyle","backdropStyle","generateHints","hints","charList","j","JumpNav","activationKey","hintStyle","hintBg","hintFg","hintChars","enabled","log","isActive","setIsActive","inputBuffer","setInputBuffer","elements","setElements","activationKeyParsed","keyStr","refreshElements","active","mapped","wasActiveRef","visibleElements","el","visibleHints","visibleHintMap","map","nameMatch","ctrlMatch","altMatch","shiftMatch","metaMatch","newBuffer","targetId","hintsOverlay","hint","isPartialMatch","useFocus","focus","useFocusable","onFocus","onBlur","onFocusRef","onBlurRef","onKeyPressRef","initiallyFocused","nowFocused","wasFocused","useApp","useFocusRegistry","updateRef","updateElements","unsubscribe","parseMask","mask","isValidChar","createMask","maskOrOptions","showPlaceholder","maskChars","newValue","_oldValue","inputChars","inputIndex","maskChar","masks"],"mappings":"6SA+BA,IAAIA,EAAAA,CAAc,CAAA,CACX,SAASC,EAAAA,EAA0B,CACxC,OAAO,CAAA,YAAA,EAAeD,IAAa,CAAA,CACrC,CAEO,SAASE,EAAAA,CACdC,CAAAA,CACAC,CAAAA,CACW,CACX,IAAMC,CAAAA,CAASD,CAAAA,CAAM,KAAA,EAAmB,EAAC,CACzC,OAAO,CACL,IAAA,CAAAD,CAAAA,CACA,KAAA,CAAAC,CAAAA,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AW,OAAO,CAAA,CAGvB,QAAA,CAAUA,GAAW,YAAY,CAAA,CAGjC,KAAMA,EAAAA,CAAW,iBAAiB,EAGlC,GAAA,CAAKA,EAAAA,CAAW,mBAAmB,CACrC","file":"index.js","sourcesContent":["import type { Node as YogaNode } from \"yoga-layout\";\nimport type { Style, LayoutRect, Color } from \"../types/index.js\";\n\nexport type GlyphNodeType = \"box\" | \"text\" | \"input\";\n\nexport interface GlyphNode {\n type: GlyphNodeType;\n props: Record<string, any>;\n style: Style;\n children: GlyphNode[];\n rawTextChildren: GlyphTextInstance[];\n parent: GlyphNode | null;\n yogaNode: YogaNode | null;\n text: string | null;\n layout: LayoutRect;\n focusId: string | null;\n hidden: boolean;\n}\n\nexport interface GlyphTextInstance {\n type: \"raw-text\";\n text: string;\n parent: GlyphNode | null;\n}\n\nexport interface GlyphContainer {\n type: \"root\";\n children: GlyphNode[];\n onCommit: () => void;\n}\n\nlet nextFocusId = 0;\nexport function generateFocusId(): string {\n return `glyph-focus-${nextFocusId++}`;\n}\n\nexport function createGlyphNode(\n type: GlyphNodeType,\n props: Record<string, any>,\n): GlyphNode {\n const style = (props.style as Style) ?? {};\n return {\n type,\n props,\n style,\n children: [],\n rawTextChildren: [],\n parent: null,\n yogaNode: null,\n text: null,\n layout: { x: 0, y: 0, width: 0, height: 0, innerX: 0, innerY: 0, innerWidth: 0, innerHeight: 0 },\n focusId: type === \"input\" ? generateFocusId() : (props.focusable ? generateFocusId() : null),\n hidden: false,\n };\n}\n\nexport function appendChild(parent: GlyphNode, child: GlyphNode): void {\n child.parent = parent;\n parent.children.push(child);\n}\n\nexport function removeChild(parent: GlyphNode, child: GlyphNode): void {\n const idx = parent.children.indexOf(child);\n if (idx !== -1) {\n parent.children.splice(idx, 1);\n child.parent = null;\n }\n}\n\nexport function insertBefore(\n parent: GlyphNode,\n child: GlyphNode,\n beforeChild: GlyphNode,\n): void {\n child.parent = parent;\n const idx = parent.children.indexOf(beforeChild);\n if (idx !== -1) {\n parent.children.splice(idx, 0, child);\n } else {\n parent.children.push(child);\n }\n}\n\nexport function getInheritedTextStyle(node: GlyphNode): {\n color?: Color;\n bg?: Color;\n bold?: boolean;\n dim?: boolean;\n italic?: boolean;\n underline?: boolean;\n} {\n const result: {\n color?: Color;\n bg?: Color;\n bold?: boolean;\n dim?: boolean;\n italic?: boolean;\n underline?: boolean;\n } = {};\n\n let current: GlyphNode | null = node;\n while (current) {\n const s = current.style;\n if (result.color === undefined && s.color !== undefined) result.color = s.color;\n if (result.bg === undefined && s.bg !== undefined) result.bg = s.bg;\n if (result.bold === undefined && s.bold !== undefined) result.bold = s.bold;\n if (result.dim === undefined && s.dim !== undefined) result.dim = s.dim;\n if (result.italic === undefined && s.italic !== undefined) result.italic = s.italic;\n if (result.underline === undefined && s.underline !== undefined) result.underline = s.underline;\n current = current.parent;\n }\n\n return result;\n}\n\nexport function collectTextContent(node: GlyphNode): string {\n if (node.text != null) return node.text;\n let result = \"\";\n for (const child of node.children) {\n result += collectTextContent(child);\n }\n return result;\n}\n","import type {\n GlyphNode,\n GlyphTextInstance,\n GlyphContainer,\n GlyphNodeType,\n} from \"./nodes.js\";\nimport {\n createGlyphNode,\n appendChild as glyphAppendChild,\n removeChild as glyphRemoveChild,\n insertBefore as glyphInsertBefore,\n} from \"./nodes.js\";\nimport type { Style } from \"../types/index.js\";\n\n// react-reconciler/constants\n// We import these at the module level - they're simple numeric values\nconst DefaultEventPriority = 32;\n\ntype Props = Record<string, any>;\n\nexport const hostConfig = {\n supportsMutation: true,\n supportsPersistence: false,\n supportsHydration: false,\n isPrimaryRenderer: true,\n\n // Timeouts\n scheduleTimeout: setTimeout,\n cancelTimeout: clearTimeout,\n noTimeout: -1 as const,\n supportsMicrotasks: true,\n scheduleMicrotask: queueMicrotask,\n\n // Priority & event methods required by react-reconciler v0.31\n getCurrentUpdatePriority: () => DefaultEventPriority,\n setCurrentUpdatePriority: (_priority: number) => {},\n resolveUpdatePriority: () => DefaultEventPriority,\n getCurrentEventPriority: () => DefaultEventPriority,\n resolveEventType: () => null as any,\n resolveEventTimeStamp: () => -1.1,\n shouldAttemptEagerTransition: () => false,\n\n getInstanceFromNode: () => null,\n beforeActiveInstanceBlur: () => {},\n afterActiveInstanceBlur: () => {},\n prepareScopeUpdate: () => {},\n getInstanceFromScope: () => null,\n detachDeletedInstance: () => {},\n\n requestPostPaintCallback: (_callback: any) => {},\n\n // Commit suspension stubs (required by react-reconciler v0.31)\n maySuspendCommit: (_type: string, _props: Props) => false,\n preloadInstance: (_type: string, _props: Props) => true,\n startSuspendingCommit: () => {},\n suspendInstance: (_type: string, _props: Props) => {},\n waitForCommitToBeReady: () => null,\n\n // Transition stubs\n NotPendingTransition: null as any,\n HostTransitionContext: { $$typeof: Symbol.for(\"react.context\"), _currentValue: null as any } as any,\n resetFormInstance: (_instance: any) => {},\n\n // Console binding\n bindToConsole: (methodName: string, args: any[], _errorPrefix: string) => {\n return (Function.prototype.bind as any).call(\n (console as any)[methodName],\n console,\n ...args,\n );\n },\n\n // Resource/singleton stubs\n supportsResources: false,\n isHostHoistableType: (_type: string, _props: Props) => false,\n supportsSingletons: false,\n isHostSingletonType: (_type: string) => false,\n supportsTestSelectors: false,\n\n createInstance(\n type: string,\n props: Props,\n _rootContainer: GlyphContainer,\n _hostContext: null,\n _internalHandle: any,\n ): GlyphNode {\n return createGlyphNode(type as GlyphNodeType, props);\n },\n\n createTextInstance(\n text: string,\n _rootContainer: GlyphContainer,\n _hostContext: null,\n _internalHandle: any,\n ): GlyphTextInstance {\n return { type: \"raw-text\", text, parent: null };\n },\n\n appendInitialChild(\n parentInstance: GlyphNode,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") {\n const textChild = child as GlyphTextInstance;\n textChild.parent = parentInstance;\n parentInstance.rawTextChildren.push(textChild);\n parentInstance.text = parentInstance.rawTextChildren.map((t) => t.text).join(\"\");\n } else {\n glyphAppendChild(parentInstance, child as GlyphNode);\n }\n },\n\n finalizeInitialChildren(\n _instance: GlyphNode,\n _type: string,\n _props: Props,\n _rootContainer: GlyphContainer,\n _hostContext: null,\n ): boolean {\n return false;\n },\n\n shouldSetTextContent(_type: string, _props: Props): boolean {\n return false;\n },\n\n getRootHostContext(_rootContainer: GlyphContainer): Record<string, never> {\n return {};\n },\n\n getChildHostContext(\n parentHostContext: Record<string, never>,\n _type: string,\n _rootContainer: GlyphContainer,\n ): Record<string, never> {\n return parentHostContext;\n },\n\n getPublicInstance(instance: GlyphNode | GlyphTextInstance): GlyphNode | GlyphTextInstance {\n return instance;\n },\n\n prepareForCommit(_containerInfo: GlyphContainer): null {\n return null;\n },\n\n resetAfterCommit(containerInfo: GlyphContainer): void {\n containerInfo.onCommit();\n },\n\n preparePortalMount(): void {},\n\n // Mutation methods\n appendChild(\n parentInstance: GlyphNode,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") {\n const textChild = child as GlyphTextInstance;\n textChild.parent = parentInstance;\n parentInstance.rawTextChildren.push(textChild);\n parentInstance.text = parentInstance.rawTextChildren.map((t) => t.text).join(\"\");\n } else {\n glyphAppendChild(parentInstance, child as GlyphNode);\n }\n },\n\n appendChildToContainer(\n container: GlyphContainer,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") return;\n const node = child as GlyphNode;\n node.parent = null;\n container.children.push(node);\n },\n\n insertBefore(\n parentInstance: GlyphNode,\n child: GlyphNode | GlyphTextInstance,\n beforeChild: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\" || beforeChild.type === \"raw-text\") return;\n glyphInsertBefore(parentInstance, child as GlyphNode, beforeChild as GlyphNode);\n },\n\n insertInContainerBefore(\n container: GlyphContainer,\n child: GlyphNode | GlyphTextInstance,\n beforeChild: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\" || beforeChild.type === \"raw-text\") return;\n const node = child as GlyphNode;\n const before = beforeChild as GlyphNode;\n const idx = container.children.indexOf(before);\n if (idx !== -1) {\n container.children.splice(idx, 0, node);\n } else {\n container.children.push(node);\n }\n },\n\n removeChild(\n parentInstance: GlyphNode,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") {\n const textChild = child as GlyphTextInstance;\n textChild.parent = null;\n const idx = parentInstance.rawTextChildren.indexOf(textChild);\n if (idx !== -1) parentInstance.rawTextChildren.splice(idx, 1);\n parentInstance.text = parentInstance.rawTextChildren.map((t) => t.text).join(\"\") || null;\n return;\n }\n glyphRemoveChild(parentInstance, child as GlyphNode);\n },\n\n removeChildFromContainer(\n container: GlyphContainer,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") return;\n const node = child as GlyphNode;\n const idx = container.children.indexOf(node);\n if (idx !== -1) {\n container.children.splice(idx, 1);\n }\n },\n\n commitTextUpdate(\n textInstance: GlyphTextInstance,\n _oldText: string,\n newText: string,\n ): void {\n textInstance.text = newText;\n if (textInstance.parent) {\n // Rebuild parent text from tracked raw text children\n textInstance.parent.text = textInstance.parent.rawTextChildren\n .map((t) => t.text)\n .join(\"\");\n }\n },\n\n // v0.31 signature: (instance, type, oldProps, newProps, internalHandle)\n // updatePayload was removed in this version\n commitUpdate(\n instance: GlyphNode,\n _type: string,\n _oldProps: Props,\n newProps: Props,\n _internalHandle: any,\n ): void {\n instance.props = newProps;\n instance.style = (newProps.style as Style) ?? {};\n if (newProps.focusable && !instance.focusId) {\n instance.focusId = `focus-${Math.random().toString(36).slice(2, 9)}`;\n }\n },\n\n hideInstance(instance: GlyphNode): void {\n instance.hidden = true;\n },\n\n hideTextInstance(textInstance: GlyphTextInstance): void {\n textInstance.text = \"\";\n },\n\n unhideInstance(instance: GlyphNode, _props: Props): void {\n instance.hidden = false;\n },\n\n unhideTextInstance(textInstance: GlyphTextInstance, text: string): void {\n textInstance.text = text;\n },\n\n clearContainer(container: GlyphContainer): void {\n container.children.length = 0;\n },\n\n resetTextContent(instance: GlyphNode): void {\n instance.text = null;\n },\n};\n\n","import ReactReconciler from \"react-reconciler\";\nimport { hostConfig } from \"./hostConfig.js\";\n\n// @ts-expect-error - react-reconciler types don't perfectly match runtime\nconst reconciler = ReactReconciler(hostConfig);\n\nreconciler.injectIntoDevTools({\n bundleType: process.env.NODE_ENV === \"production\" ? 0 : 1,\n version: \"0.1.0\",\n rendererPackageName: \"glyph\",\n});\n\nexport { reconciler };\n","const ESC = \"\\x1b\";\nconst CSI = `${ESC}[`;\n\nexport class Terminal {\n stdout: NodeJS.WriteStream;\n stdin: NodeJS.ReadStream;\n private wasRaw = false;\n private cleanedUp = false;\n\n // Data handler dispatch - single stdin listener, filters OSC, dispatches clean data\n private dataHandlers = new Set<(data: string) => void>();\n private stdinAttached = false;\n\n // OSC response filtering state\n private oscState: \"normal\" | \"esc\" | \"osc\" | \"osc_esc\" = \"normal\";\n private oscAccum = \"\";\n private escFlushTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Terminal palette (populated by queryPalette)\n palette = new Map<number, [number, number, number]>();\n private paletteResolve: (() => void) | null = null;\n\n constructor(\n stdout: NodeJS.WriteStream = process.stdout,\n stdin: NodeJS.ReadStream = process.stdin,\n ) {\n this.stdout = stdout;\n this.stdin = stdin;\n }\n\n get columns(): number {\n return this.stdout.columns || 80;\n }\n\n get rows(): number {\n return this.stdout.rows || 24;\n }\n\n enterRawMode(): void {\n if (this.stdin.isTTY) {\n this.wasRaw = this.stdin.isRaw;\n this.stdin.setRawMode(true);\n this.stdin.resume();\n this.stdin.setEncoding(\"utf-8\");\n }\n }\n\n exitRawMode(): void {\n if (this.stdin.isTTY && !this.wasRaw) {\n this.stdin.setRawMode(false);\n this.stdin.pause();\n }\n }\n\n write(data: string): void {\n this.stdout.write(data);\n }\n\n hideCursor(): void {\n this.write(`${CSI}?25l`);\n }\n\n showCursor(): void {\n this.write(`${CSI}?25h`);\n }\n\n /** Move cursor to (x, y) position (0-indexed) */\n moveCursor(x: number, y: number): void {\n // ANSI uses 1-indexed positions\n this.write(`${CSI}${y + 1};${x + 1}H`);\n }\n\n /** Set cursor color using OSC 12 */\n setCursorColor(color: string): void {\n // OSC 12 sets cursor color, terminated by BEL\n this.write(`${ESC}]12;${color}\\x07`);\n }\n\n /** Reset cursor color to terminal default */\n resetCursorColor(): void {\n // Empty color resets to default\n this.write(`${ESC}]112\\x07`);\n }\n\n enterAltScreen(): void {\n this.write(`${CSI}?1049h`);\n }\n\n exitAltScreen(): void {\n this.write(`${CSI}?1049l`);\n }\n\n clearScreen(): void {\n this.write(`${CSI}2J${CSI}H`);\n }\n\n resetStyles(): void {\n this.write(`${CSI}0m`);\n }\n\n /** Enable kitty keyboard protocol for enhanced key detection */\n enableKittyKeyboard(): void {\n // Push keyboard mode with flags:\n // 1 = Disambiguate escape codes\n // 2 = Report event types\n // 4 = Report alternate keys\n // 8 = Report all keys as escape codes\n // We use 1 (disambiguate) which gives us Ctrl+Enter, etc.\n this.write(`${CSI}>1u`);\n }\n\n /** Disable kitty keyboard protocol */\n disableKittyKeyboard(): void {\n // Pop keyboard mode\n this.write(`${CSI}<u`);\n }\n\n setup(): void {\n this.enterRawMode();\n this.enterAltScreen();\n this.enableKittyKeyboard(); // Enable extended keyboard protocol\n this.hideCursor();\n this.clearScreen();\n this.attachStdinListener();\n this.installCleanupHandlers();\n }\n\n cleanup(): void {\n if (this.cleanedUp) return;\n this.cleanedUp = true;\n\n if (this.escFlushTimer !== null) {\n clearTimeout(this.escFlushTimer);\n this.escFlushTimer = null;\n }\n\n this.resetStyles();\n this.resetCursorColor();\n this.disableKittyKeyboard(); // Restore normal keyboard mode\n this.showCursor();\n this.exitAltScreen();\n this.exitRawMode();\n }\n\n /** Restore terminal state for background suspension (does NOT mark as cleaned up). */\n suspend(): void {\n if (this.escFlushTimer !== null) {\n clearTimeout(this.escFlushTimer);\n this.escFlushTimer = null;\n }\n this.oscState = \"normal\";\n this.oscAccum = \"\";\n\n this.resetStyles();\n this.resetCursorColor();\n this.disableKittyKeyboard();\n this.showCursor();\n this.exitAltScreen();\n this.exitRawMode();\n }\n\n /** Re-enter raw mode and alt screen after SIGCONT resume. */\n resume(): void {\n this.enterRawMode();\n this.enterAltScreen();\n this.enableKittyKeyboard();\n this.hideCursor();\n this.clearScreen();\n }\n\n // ---- Data handling with OSC filtering ----\n\n private attachStdinListener(): void {\n if (this.stdinAttached) return;\n this.stdinAttached = true;\n\n this.stdin.on(\"data\", (data: Buffer | string) => {\n let str = typeof data === \"string\" ? data : data.toString(\"utf-8\");\n this.dispatchFiltered(str);\n });\n }\n\n onData(handler: (data: string) => void): () => void {\n this.dataHandlers.add(handler);\n return () => {\n this.dataHandlers.delete(handler);\n };\n }\n\n // ---- OSC response filtering ----\n\n private dispatchFiltered(raw: string): void {\n // Cancel any pending standalone-ESC flush since more data arrived\n if (this.escFlushTimer !== null) {\n clearTimeout(this.escFlushTimer);\n this.escFlushTimer = null;\n }\n\n const clean = this.filterOsc(raw);\n\n if (clean.length > 0) {\n for (const handler of this.dataHandlers) {\n handler(clean);\n }\n }\n\n // If filterOsc ended in \"esc\" state, a standalone ESC byte is pending.\n // Use a short timeout to disambiguate: if no more data arrives within 50ms,\n // treat it as a standalone Escape keypress and flush it.\n if (this.oscState === \"esc\") {\n this.escFlushTimer = setTimeout(() => {\n this.escFlushTimer = null;\n this.oscState = \"normal\";\n for (const handler of this.dataHandlers) {\n handler(\"\\x1b\");\n }\n }, 50);\n }\n }\n\n private filterOsc(raw: string): string {\n let clean = \"\";\n\n for (let i = 0; i < raw.length; i++) {\n const ch = raw[i]!;\n const code = raw.charCodeAt(i);\n\n switch (this.oscState) {\n case \"normal\":\n if (code === 0x1b) {\n this.oscState = \"esc\";\n } else {\n clean += ch;\n }\n break;\n\n case \"esc\":\n if (ch === \"]\") {\n // Start of OSC sequence\n this.oscState = \"osc\";\n this.oscAccum = \"\";\n } else {\n // Not OSC — pass through the ESC and current char\n clean += \"\\x1b\" + ch;\n this.oscState = \"normal\";\n }\n break;\n\n case \"osc\":\n if (code === 0x07) {\n // BEL terminator\n this.handleOscResponse(this.oscAccum);\n this.oscAccum = \"\";\n this.oscState = \"normal\";\n } else if (code === 0x1b) {\n // Possible ST (ESC \\)\n this.oscState = \"osc_esc\";\n } else {\n this.oscAccum += ch;\n }\n break;\n\n case \"osc_esc\":\n if (ch === \"\\\\\") {\n // ST terminator\n this.handleOscResponse(this.oscAccum);\n this.oscAccum = \"\";\n this.oscState = \"normal\";\n } else {\n // Not ST, accumulate\n this.oscAccum += \"\\x1b\" + ch;\n this.oscState = \"osc\";\n }\n break;\n }\n }\n\n return clean;\n }\n\n private handleOscResponse(data: string): void {\n // Parse OSC 4 response: \"4;{index};rgb:{rrrr}/{gggg}/{bbbb}\"\n const match = data.match(\n /^4;(\\d+);rgb:([0-9a-fA-F]+)\\/([0-9a-fA-F]+)\\/([0-9a-fA-F]+)/,\n );\n if (match) {\n const index = parseInt(match[1]!, 10);\n // Terminal reports 16-bit hex (e.g. \"ffff\"), take high byte for 8-bit\n const r = parseInt(match[2]!.substring(0, 2), 16);\n const g = parseInt(match[3]!.substring(0, 2), 16);\n const b = parseInt(match[4]!.substring(0, 2), 16);\n this.palette.set(index, [r, g, b]);\n if (this.palette.size >= 16 && this.paletteResolve) {\n this.paletteResolve();\n this.paletteResolve = null;\n }\n }\n }\n\n // ---- Palette querying ----\n\n queryPalette(): Promise<Map<number, [number, number, number]>> {\n return new Promise((resolve) => {\n const done = () => resolve(this.palette);\n\n // If terminal doesn't respond, resolve with whatever we have after timeout\n const timeout = setTimeout(done, 200);\n\n this.paletteResolve = () => {\n clearTimeout(timeout);\n done();\n };\n\n // Query colors 0-15 (the 16 standard ANSI colors)\n let query = \"\";\n for (let i = 0; i < 16; i++) {\n query += `\\x1b]4;${i};?\\x07`;\n }\n this.write(query);\n });\n }\n\n // ---- Event handling ----\n\n onResize(handler: () => void): () => void {\n this.stdout.on(\"resize\", handler);\n return () => {\n this.stdout.off(\"resize\", handler);\n };\n }\n\n private installCleanupHandlers(): void {\n const doCleanup = () => this.cleanup();\n\n process.on(\"exit\", doCleanup);\n\n const handleSignal = (signal: NodeJS.Signals) => {\n doCleanup();\n process.kill(process.pid, signal);\n };\n\n process.once(\"SIGINT\", () => handleSignal(\"SIGINT\"));\n process.once(\"SIGTERM\", () => handleSignal(\"SIGTERM\"));\n\n process.on(\"uncaughtException\", (err) => {\n doCleanup();\n console.error(err);\n process.exit(1);\n });\n\n process.on(\"unhandledRejection\", (err) => {\n doCleanup();\n console.error(err);\n process.exit(1);\n });\n }\n}\n","import type { Key } from \"../types/index.js\";\n\n// Map key codes to key names (for kitty protocol and xterm modifyOtherKeys)\nfunction getKeyNameFromCode(code: number): string {\n // Special keys (kitty protocol uses these codes)\n switch (code) {\n // Standard ASCII\n case 9: return \"tab\";\n case 13: return \"return\";\n case 27: return \"escape\";\n case 32: return \" \";\n case 127: return \"backspace\";\n \n // Kitty protocol special keys\n case 57358: return \"capslock\";\n case 57359: return \"scrolllock\";\n case 57360: return \"numlock\";\n case 57361: return \"printscreen\";\n case 57362: return \"pause\";\n case 57363: return \"menu\";\n \n // Function keys (kitty uses these codes)\n case 57364: return \"f13\";\n case 57365: return \"f14\";\n case 57366: return \"f15\";\n case 57367: return \"f16\";\n case 57368: return \"f17\";\n case 57369: return \"f18\";\n case 57370: return \"f19\";\n case 57371: return \"f20\";\n case 57372: return \"f21\";\n case 57373: return \"f22\";\n case 57374: return \"f23\";\n case 57375: return \"f24\";\n case 57376: return \"f25\";\n \n // Keypad keys\n case 57399: return \"kp0\";\n case 57400: return \"kp1\";\n case 57401: return \"kp2\";\n case 57402: return \"kp3\";\n case 57403: return \"kp4\";\n case 57404: return \"kp5\";\n case 57405: return \"kp6\";\n case 57406: return \"kp7\";\n case 57407: return \"kp8\";\n case 57408: return \"kp9\";\n case 57409: return \"kpdecimal\";\n case 57410: return \"kpdivide\";\n case 57411: return \"kpmultiply\";\n case 57412: return \"kpminus\";\n case 57413: return \"kpplus\";\n case 57414: return \"kpenter\";\n case 57415: return \"kpequal\";\n \n // Navigation (kitty protocol)\n case 57416: return \"kpleft\";\n case 57417: return \"kpright\";\n case 57418: return \"kpup\";\n case 57419: return \"kpdown\";\n case 57420: return \"kppageup\";\n case 57421: return \"kppagedown\";\n case 57422: return \"kphome\";\n case 57423: return \"kpend\";\n case 57424: return \"kpinsert\";\n case 57425: return \"kpdelete\";\n \n // Media keys\n case 57428: return \"mediaplaypause\";\n case 57429: return \"mediastop\";\n case 57430: return \"mediaprev\";\n case 57431: return \"medianext\";\n case 57432: return \"mediarewind\";\n case 57433: return \"mediafastforward\";\n case 57434: return \"mediamute\";\n case 57435: return \"volumedown\";\n case 57436: return \"volumeup\";\n \n default:\n // Printable ASCII\n if (code >= 32 && code <= 126) {\n return String.fromCharCode(code).toLowerCase();\n }\n return \"unknown\";\n }\n}\n\n// Map CSI ~ params to key names\nfunction getTildeKeyName(param: string): string {\n // Handle param;modifier format\n const baseParam = param.split(\";\")[0];\n switch (baseParam) {\n case \"1\": return \"home\";\n case \"2\": return \"insert\";\n case \"3\": return \"delete\";\n case \"4\": return \"end\";\n case \"5\": return \"pageup\";\n case \"6\": return \"pagedown\";\n case \"7\": return \"home\";\n case \"8\": return \"end\";\n case \"11\": return \"f1\";\n case \"12\": return \"f2\";\n case \"13\": return \"f3\";\n case \"14\": return \"f4\";\n case \"15\": return \"f5\";\n case \"17\": return \"f6\";\n case \"18\": return \"f7\";\n case \"19\": return \"f8\";\n case \"20\": return \"f9\";\n case \"21\": return \"f10\";\n case \"23\": return \"f11\";\n case \"24\": return \"f12\";\n case \"25\": return \"f13\";\n case \"26\": return \"f14\";\n case \"28\": return \"f15\";\n case \"29\": return \"f16\";\n case \"31\": return \"f17\";\n case \"32\": return \"f18\";\n case \"33\": return \"f19\";\n case \"34\": return \"f20\";\n default: return \"unknown\";\n }\n}\n\n// Parse modifier bits (shared between protocols)\nfunction applyModifiers(key: Key, mod: number): void {\n // mod is 1-indexed in the protocol, so subtract 1\n const m = mod - 1;\n if (m & 1) key.shift = true;\n if (m & 2) key.alt = true;\n if (m & 4) key.ctrl = true;\n if (m & 8) key.meta = true; // Super/Cmd key\n}\n\nexport function parseKeySequence(data: string): Key[] {\n const keys: Key[] = [];\n let i = 0;\n\n while (i < data.length) {\n const ch = data[i]!;\n const code = data.charCodeAt(i);\n\n // ESC sequences\n if (ch === \"\\x1b\") {\n // CSI sequences: ESC [\n if (data[i + 1] === \"[\") {\n const seq = parseCsiSequence(data, i);\n if (seq) {\n keys.push(seq.key);\n i = seq.end;\n continue;\n }\n }\n\n // SS3 sequences: ESC O (function keys on some terminals)\n if (data[i + 1] === \"O\") {\n const seq = parseSs3Sequence(data, i);\n if (seq) {\n keys.push(seq.key);\n i = seq.end;\n continue;\n }\n }\n\n // Alt + char: ESC followed by a printable char\n if (i + 1 < data.length && data.charCodeAt(i + 1) >= 32) {\n keys.push({\n name: data[i + 1]!.toLowerCase(),\n sequence: data.substring(i, i + 2),\n alt: true,\n });\n i += 2;\n continue;\n }\n\n // Standalone ESC\n keys.push({ name: \"escape\", sequence: \"\\x1b\" });\n i++;\n continue;\n }\n\n // Ctrl combos (0x01-0x1a except known special)\n if (code >= 1 && code <= 26) {\n const letter = String.fromCharCode(code + 96); // a-z\n if (code === 13) {\n keys.push({ name: \"return\", sequence: \"\\r\" });\n } else if (code === 9) {\n keys.push({ name: \"tab\", sequence: \"\\t\" });\n } else if (code === 8) {\n keys.push({ name: \"backspace\", sequence: \"\\b\" });\n } else {\n keys.push({ name: letter, sequence: ch, ctrl: true });\n }\n i++;\n continue;\n }\n\n // Backspace / DEL\n if (code === 127) {\n keys.push({ name: \"backspace\", sequence: ch });\n i++;\n continue;\n }\n\n // Printable characters\n keys.push({ name: ch, sequence: ch });\n i++;\n }\n\n return keys;\n}\n\ninterface SeqResult {\n key: Key;\n end: number;\n}\n\n// Parse SS3 sequences (ESC O ...)\nfunction parseSs3Sequence(data: string, start: number): SeqResult | null {\n // start points to ESC, start+1 is O\n if (start + 2 >= data.length) return null;\n \n const final = data[start + 2]!;\n const sequence = data.substring(start, start + 3);\n \n let key: Key;\n \n switch (final) {\n // Arrow keys (some terminals)\n case \"A\": key = { name: \"up\", sequence }; break;\n case \"B\": key = { name: \"down\", sequence }; break;\n case \"C\": key = { name: \"right\", sequence }; break;\n case \"D\": key = { name: \"left\", sequence }; break;\n \n // Home/End (some terminals)\n case \"H\": key = { name: \"home\", sequence }; break;\n case \"F\": key = { name: \"end\", sequence }; break;\n \n // Function keys F1-F4\n case \"P\": key = { name: \"f1\", sequence }; break;\n case \"Q\": key = { name: \"f2\", sequence }; break;\n case \"R\": key = { name: \"f3\", sequence }; break;\n case \"S\": key = { name: \"f4\", sequence }; break;\n \n // Keypad (application mode)\n case \"j\": key = { name: \"kpmultiply\", sequence }; break;\n case \"k\": key = { name: \"kpplus\", sequence }; break;\n case \"l\": key = { name: \"kpcomma\", sequence }; break;\n case \"m\": key = { name: \"kpminus\", sequence }; break;\n case \"n\": key = { name: \"kpdecimal\", sequence }; break;\n case \"o\": key = { name: \"kpdivide\", sequence }; break;\n case \"p\": key = { name: \"kp0\", sequence }; break;\n case \"q\": key = { name: \"kp1\", sequence }; break;\n case \"r\": key = { name: \"kp2\", sequence }; break;\n case \"s\": key = { name: \"kp3\", sequence }; break;\n case \"t\": key = { name: \"kp4\", sequence }; break;\n case \"u\": key = { name: \"kp5\", sequence }; break;\n case \"v\": key = { name: \"kp6\", sequence }; break;\n case \"w\": key = { name: \"kp7\", sequence }; break;\n case \"x\": key = { name: \"kp8\", sequence }; break;\n case \"y\": key = { name: \"kp9\", sequence }; break;\n case \"M\": key = { name: \"kpenter\", sequence }; break;\n \n default:\n return null;\n }\n \n return { key, end: start + 3 };\n}\n\nfunction parseCsiSequence(data: string, start: number): SeqResult | null {\n // start points to ESC, start+1 is [\n let i = start + 2;\n let params = \"\";\n\n while (i < data.length) {\n const code = data.charCodeAt(i);\n // Parameter bytes: 0x30-0x3F (digits, semicolon, etc.)\n if (code >= 0x30 && code <= 0x3f) {\n params += data[i];\n i++;\n } else {\n break;\n }\n }\n\n if (i >= data.length) return null;\n\n const final = data[i]!;\n const sequence = data.substring(start, i + 1);\n i++;\n\n let key: Key;\n\n switch (final) {\n // Arrow keys\n case \"A\":\n key = { name: \"up\", sequence };\n break;\n case \"B\":\n key = { name: \"down\", sequence };\n break;\n case \"C\":\n key = { name: \"right\", sequence };\n break;\n case \"D\":\n key = { name: \"left\", sequence };\n break;\n \n // Home/End\n case \"H\":\n key = { name: \"home\", sequence };\n break;\n case \"F\":\n key = { name: \"end\", sequence };\n break;\n \n // Shift+Tab\n case \"Z\":\n key = { name: \"tab\", sequence, shift: true };\n break;\n \n // Function keys (some terminals)\n case \"P\":\n key = { name: \"f1\", sequence };\n break;\n case \"Q\":\n key = { name: \"f2\", sequence };\n break;\n case \"R\":\n key = { name: \"f3\", sequence };\n break;\n case \"S\":\n key = { name: \"f4\", sequence };\n break;\n \n // ~ terminated sequences (VT-style)\n case \"~\": {\n // Check for xterm modifyOtherKeys format: CSI 27;mod;code ~\n if (params.startsWith(\"27;\")) {\n const modParts = params.split(\";\");\n const mod = parseInt(modParts[1] ?? \"1\", 10);\n const keyCode = parseInt(modParts[2] ?? \"0\", 10);\n key = { name: getKeyNameFromCode(keyCode), sequence };\n applyModifiers(key, mod);\n break;\n }\n \n // Standard ~ sequences with optional modifiers\n key = { name: getTildeKeyName(params), sequence };\n \n // Apply modifiers if present (e.g., 3;5~ for Ctrl+Delete)\n if (params.includes(\";\")) {\n const parts = params.split(\";\");\n const mod = parseInt(parts[1] ?? \"1\", 10);\n applyModifiers(key, mod);\n }\n break;\n }\n \n // Kitty keyboard protocol: CSI code;mod u\n case \"u\": {\n const parts = params.split(\";\");\n const keyCode = parseInt(parts[0] ?? \"0\", 10);\n const mod = parseInt(parts[1] ?? \"1\", 10);\n key = { name: getKeyNameFromCode(keyCode), sequence };\n applyModifiers(key, mod);\n break;\n }\n \n // Focus events (if terminal reports them)\n case \"I\":\n key = { name: \"focus\", sequence };\n break;\n case \"O\":\n key = { name: \"blur\", sequence };\n break;\n \n default:\n key = { name: \"unknown\", sequence };\n }\n\n // Apply modifiers from params for letter-terminated sequences (e.g., 1;2A = shift+up)\n // But skip if we already applied them (like in ~ and u handlers)\n if (params.includes(\";\") && ![\"~\", \"u\"].includes(final)) {\n const parts = params.split(\";\");\n const mod = parseInt(parts[parts.length - 1] ?? \"1\", 10);\n // Only apply if it looks like a modifier (small number)\n if (mod >= 1 && mod <= 16) {\n applyModifiers(key, mod);\n }\n }\n\n return { key, end: i };\n}\n","import type { Color, NamedColor, RGBColor } from \"../types/index.js\";\n\nconst NAMED_FG: Record<NamedColor, string> = {\n black: \"\\x1b[30m\",\n red: \"\\x1b[31m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n magenta: \"\\x1b[35m\",\n cyan: \"\\x1b[36m\",\n white: \"\\x1b[37m\",\n blackBright: \"\\x1b[90m\",\n redBright: \"\\x1b[91m\",\n greenBright: \"\\x1b[92m\",\n yellowBright: \"\\x1b[93m\",\n blueBright: \"\\x1b[94m\",\n magentaBright: \"\\x1b[95m\",\n cyanBright: \"\\x1b[96m\",\n whiteBright: \"\\x1b[97m\",\n};\n\nconst NAMED_BG: Record<NamedColor, string> = {\n black: \"\\x1b[40m\",\n red: \"\\x1b[41m\",\n green: \"\\x1b[42m\",\n yellow: \"\\x1b[43m\",\n blue: \"\\x1b[44m\",\n magenta: \"\\x1b[45m\",\n cyan: \"\\x1b[46m\",\n white: \"\\x1b[47m\",\n blackBright: \"\\x1b[100m\",\n redBright: \"\\x1b[101m\",\n greenBright: \"\\x1b[102m\",\n yellowBright: \"\\x1b[103m\",\n blueBright: \"\\x1b[104m\",\n magentaBright: \"\\x1b[105m\",\n cyanBright: \"\\x1b[106m\",\n whiteBright: \"\\x1b[107m\",\n};\n\nfunction parseHex(hex: string): RGBColor {\n const h = hex.replace(\"#\", \"\");\n const r = parseInt(h.substring(0, 2), 16);\n const g = parseInt(h.substring(2, 4), 16);\n const b = parseInt(h.substring(4, 6), 16);\n return { r, g, b };\n}\n\nexport function colorToFg(color: Color): string {\n if (typeof color === \"string\") {\n if (color.startsWith(\"#\")) {\n const { r, g, b } = parseHex(color);\n return `\\x1b[38;2;${r};${g};${b}m`;\n }\n return NAMED_FG[color as NamedColor] ?? \"\\x1b[39m\";\n }\n if (typeof color === \"number\") {\n return `\\x1b[38;5;${color}m`;\n }\n const { r, g, b } = color;\n return `\\x1b[38;2;${r};${g};${b}m`;\n}\n\nexport function colorToFgRaw(color: Color): [number, number, number] | null {\n if (typeof color === \"string\") {\n if (color.startsWith(\"#\")) {\n const c = parseHex(color);\n return [c.r, c.g, c.b];\n }\n return null;\n }\n if (typeof color === \"number\") {\n return null;\n }\n return [color.r, color.g, color.b];\n}\n\nexport function colorToBg(color: Color): string {\n if (typeof color === \"string\") {\n if (color.startsWith(\"#\")) {\n const { r, g, b } = parseHex(color);\n return `\\x1b[48;2;${r};${g};${b}m`;\n }\n return NAMED_BG[color as NamedColor] ?? \"\\x1b[49m\";\n }\n if (typeof color === \"number\") {\n return `\\x1b[48;5;${color}m`;\n }\n const { r, g, b } = color;\n return `\\x1b[48;2;${r};${g};${b}m`;\n}\n\n// Approximate RGB fallbacks for the 16 ANSI colors (used until terminal palette is queried)\nconst NAMED_RGB: Record<NamedColor, [number, number, number]> = {\n black: [0, 0, 0],\n red: [170, 0, 0],\n green: [0, 170, 0],\n yellow: [170, 170, 0],\n blue: [0, 0, 170],\n magenta: [170, 0, 170],\n cyan: [0, 170, 170],\n white: [170, 170, 170],\n blackBright: [85, 85, 85],\n redBright: [255, 85, 85],\n greenBright: [85, 255, 85],\n yellowBright: [255, 255, 85],\n blueBright: [85, 85, 255],\n magentaBright: [255, 85, 255],\n cyanBright: [85, 255, 255],\n whiteBright: [255, 255, 255],\n};\n\nconst NAMED_INDEX: NamedColor[] = [\n \"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\",\n \"blackBright\", \"redBright\", \"greenBright\", \"yellowBright\", \"blueBright\", \"magentaBright\", \"cyanBright\", \"whiteBright\",\n];\n\n// Terminal-reported palette overrides the fallback approximations\nlet terminalPalette: Map<number, [number, number, number]> | null = null;\n\nexport function setTerminalPalette(palette: Map<number, [number, number, number]>): void {\n if (palette.size > 0) {\n terminalPalette = palette;\n }\n}\n\nfunction resolveNamedRgb(name: NamedColor): [number, number, number] | null {\n // Prefer terminal-reported values if available\n if (terminalPalette) {\n const idx = NAMED_INDEX.indexOf(name);\n if (idx !== -1) {\n const tp = terminalPalette.get(idx);\n if (tp) return tp;\n }\n }\n return NAMED_RGB[name] ?? null;\n}\n\nexport function colorToRgb(color: Color): [number, number, number] | null {\n if (typeof color === \"string\") {\n if (color.startsWith(\"#\")) {\n const c = parseHex(color);\n return [c.r, c.g, c.b];\n }\n return resolveNamedRgb(color as NamedColor);\n }\n if (typeof color === \"number\") {\n if (color < 16) {\n // Use terminal palette or fallback\n if (terminalPalette) {\n const tp = terminalPalette.get(color);\n if (tp) return tp;\n }\n return NAMED_RGB[NAMED_INDEX[color]!];\n }\n if (color >= 232) {\n const g = (color - 232) * 10 + 8;\n return [g, g, g];\n }\n // 216-color cube (indices 16-231)\n const idx = color - 16;\n const b = (idx % 6) * 51;\n const g = (Math.floor(idx / 6) % 6) * 51;\n const r = Math.floor(idx / 36) * 51;\n return [r, g, b];\n }\n return [color.r, color.g, color.b];\n}\n\n/** Returns true if the color is perceptually light (should use dark text on it). */\nexport function isLightColor(color: Color): boolean {\n const rgb = colorToRgb(color);\n if (!rgb) return false;\n // W3C relative luminance formula\n const [r, g, b] = rgb.map((c) => {\n const s = c / 255;\n return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);\n });\n const luminance = 0.2126 * r! + 0.7152 * g! + 0.0722 * b!;\n return luminance > 0.4;\n}\n\nexport function colorsEqual(\n a: Color | undefined,\n b: Color | undefined,\n): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a === \"object\" && typeof b === \"object\") {\n return a.r === b.r && a.g === b.g && a.b === b.b;\n }\n return false;\n}\n\n/** Convert Color to a string suitable for OSC sequences (e.g. cursor color) */\nexport function colorToOscString(color: Color): string {\n const rgb = colorToRgb(color);\n if (rgb) {\n const [r, g, b] = rgb;\n // OSC uses \"rgb:RR/GG/BB\" format with hex values\n const rHex = r.toString(16).padStart(2, \"0\");\n const gHex = g.toString(16).padStart(2, \"0\");\n const bHex = b.toString(16).padStart(2, \"0\");\n return `rgb:${rHex}/${gHex}/${bHex}`;\n }\n // Fallback to named color string\n return String(color);\n}\n\n/** Get a contrasting cursor color for a given background */\nexport function getContrastCursorColor(bg: Color | undefined): string {\n if (!bg) return \"white\";\n return isLightColor(bg) ? \"black\" : \"white\";\n}\n","import type { Color } from \"../types/index.js\";\nimport { colorsEqual } from \"./color.js\";\n\nexport interface Cell {\n ch: string;\n fg?: Color;\n bg?: Color;\n bold?: boolean;\n dim?: boolean;\n italic?: boolean;\n underline?: boolean;\n}\n\nexport class Framebuffer {\n width: number;\n height: number;\n cells: Cell[];\n\n constructor(width: number, height: number) {\n this.width = width;\n this.height = height;\n this.cells = new Array(width * height);\n this.clear();\n }\n\n clear(): void {\n for (let i = 0; i < this.cells.length; i++) {\n this.cells[i] = { ch: \" \" };\n }\n }\n\n resize(width: number, height: number): void {\n this.width = width;\n this.height = height;\n this.cells = new Array(width * height);\n this.clear();\n }\n\n get(x: number, y: number): Cell | undefined {\n if (x < 0 || x >= this.width || y < 0 || y >= this.height) return undefined;\n return this.cells[y * this.width + x];\n }\n\n set(x: number, y: number, cell: Cell): void {\n if (x < 0 || x >= this.width || y < 0 || y >= this.height) return;\n this.cells[y * this.width + x] = cell;\n }\n\n setChar(\n x: number,\n y: number,\n ch: string,\n fg?: Color,\n bg?: Color,\n bold?: boolean,\n dim?: boolean,\n italic?: boolean,\n underline?: boolean,\n ): void {\n if (x < 0 || x >= this.width || y < 0 || y >= this.height) return;\n this.cells[y * this.width + x] = { ch, fg, bg, bold, dim, italic, underline };\n }\n\n fillRect(\n x: number,\n y: number,\n w: number,\n h: number,\n ch: string,\n fg?: Color,\n bg?: Color,\n ): void {\n for (let row = y; row < y + h; row++) {\n for (let col = x; col < x + w; col++) {\n this.setChar(col, row, ch, fg, bg);\n }\n }\n }\n\n clone(): Framebuffer {\n const fb = new Framebuffer(this.width, this.height);\n for (let i = 0; i < this.cells.length; i++) {\n const c = this.cells[i]!;\n fb.cells[i] = { ...c };\n }\n return fb;\n }\n\n cellsEqual(a: Cell, b: Cell): boolean {\n return (\n a.ch === b.ch &&\n colorsEqual(a.fg, b.fg) &&\n colorsEqual(a.bg, b.bg) &&\n (a.bold ?? false) === (b.bold ?? false) &&\n (a.dim ?? false) === (b.dim ?? false) &&\n (a.italic ?? false) === (b.italic ?? false) &&\n (a.underline ?? false) === (b.underline ?? false)\n );\n }\n}\n","import type { BorderStyle } from \"../types/index.js\";\n\nexport interface BorderChars {\n topLeft: string;\n topRight: string;\n bottomLeft: string;\n bottomRight: string;\n horizontal: string;\n vertical: string;\n}\n\nconst BORDER_CHARS: Record<Exclude<BorderStyle, \"none\">, BorderChars> = {\n single: {\n topLeft: \"┌\",\n topRight: \"┐\",\n bottomLeft: \"└\",\n bottomRight: \"┘\",\n horizontal: \"─\",\n vertical: \"│\",\n },\n double: {\n topLeft: \"╔\",\n topRight: \"╗\",\n bottomLeft: \"╚\",\n bottomRight: \"╝\",\n horizontal: \"═\",\n vertical: \"║\",\n },\n round: {\n topLeft: \"╭\",\n topRight: \"╮\",\n bottomLeft: \"╰\",\n bottomRight: \"╯\",\n horizontal: \"─\",\n vertical: \"│\",\n },\n ascii: {\n topLeft: \"+\",\n topRight: \"+\",\n bottomLeft: \"+\",\n bottomRight: \"+\",\n horizontal: \"-\",\n vertical: \"|\",\n },\n};\n\nexport function getBorderChars(\n style: BorderStyle,\n): BorderChars | null {\n if (style === \"none\") return null;\n return BORDER_CHARS[style];\n}\n","import stringWidth from \"string-width\";\nimport { MeasureMode } from \"yoga-layout\";\nimport type { WrapMode } from \"../types/index.js\";\n\nexport function measureText(\n text: string,\n maxWidth: number,\n widthMode: MeasureMode,\n wrapMode: WrapMode,\n): { width: number; height: number } {\n if (text.length === 0) {\n return { width: 0, height: 0 };\n }\n\n const lines = text.split(\"\\n\");\n\n if (widthMode === MeasureMode.Undefined || wrapMode === \"none\") {\n // No constraint: measure as-is\n let maxW = 0;\n for (const line of lines) {\n const w = stringWidth(line);\n if (w > maxW) maxW = w;\n }\n return { width: maxW, height: lines.length };\n }\n\n const availWidth = Math.max(1, Math.floor(maxWidth));\n const wrappedLines = wrapLines(lines, availWidth, wrapMode);\n\n let maxW = 0;\n for (const line of wrappedLines) {\n const w = stringWidth(line);\n if (w > maxW) maxW = w;\n }\n\n return { width: maxW, height: wrappedLines.length };\n}\n\nexport function wrapLines(\n lines: string[],\n maxWidth: number,\n wrapMode: WrapMode,\n): string[] {\n const result: string[] = [];\n\n for (const line of lines) {\n const lineWidth = stringWidth(line);\n\n if (lineWidth <= maxWidth) {\n result.push(line);\n continue;\n }\n\n if (wrapMode === \"truncate\") {\n result.push(truncateLine(line, maxWidth));\n continue;\n }\n\n if (wrapMode === \"ellipsis\") {\n result.push(truncateWithEllipsis(line, maxWidth));\n continue;\n }\n\n // wrap mode\n const wrapped = wordWrap(line, maxWidth);\n result.push(...wrapped);\n }\n\n return result;\n}\n\nfunction truncateLine(text: string, maxWidth: number): string {\n let result = \"\";\n let width = 0;\n for (const char of text) {\n const charWidth = stringWidth(char);\n if (width + charWidth > maxWidth) break;\n result += char;\n width += charWidth;\n }\n return result;\n}\n\nfunction truncateWithEllipsis(text: string, maxWidth: number): string {\n if (maxWidth <= 1) {\n return maxWidth === 1 ? \"…\" : \"\";\n }\n const truncated = truncateLine(text, maxWidth - 1);\n if (stringWidth(truncated) < stringWidth(text)) {\n return truncated + \"…\";\n }\n return text;\n}\n\nfunction wordWrap(text: string, maxWidth: number): string[] {\n const lines: string[] = [];\n let currentLine = \"\";\n let currentWidth = 0;\n let wordBuffer = \"\";\n let wordBufferWidth = 0;\n \n for (let i = 0; i <= text.length; i++) {\n const char = text[i];\n const isEnd = i === text.length;\n const isSpace = char === \" \";\n \n if (isEnd || isSpace) {\n // End of a word - try to add word buffer to current line\n if (wordBuffer.length > 0) {\n if (currentWidth + wordBufferWidth <= maxWidth) {\n // Word fits on current line\n currentLine += wordBuffer;\n currentWidth += wordBufferWidth;\n } else if (wordBufferWidth <= maxWidth) {\n // Word fits on a new line\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n currentLine = wordBuffer;\n currentWidth = wordBufferWidth;\n } else {\n // Word is too long - break it character by character\n for (const c of wordBuffer) {\n const cw = stringWidth(c);\n if (currentWidth + cw > maxWidth && currentLine.length > 0) {\n lines.push(currentLine);\n currentLine = \"\";\n currentWidth = 0;\n }\n currentLine += c;\n currentWidth += cw;\n }\n }\n wordBuffer = \"\";\n wordBufferWidth = 0;\n }\n \n // Handle the space\n if (isSpace) {\n if (currentWidth + 1 <= maxWidth) {\n // Space fits on current line\n currentLine += \" \";\n currentWidth += 1;\n } else {\n // Space doesn't fit - start new line, put space at start\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n currentLine = \" \";\n currentWidth = 1;\n }\n }\n } else if (char) {\n // Building a word\n wordBuffer += char;\n wordBufferWidth += stringWidth(char);\n }\n }\n \n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n \n return lines.length > 0 ? lines : [\"\"];\n}\n","import type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { getInheritedTextStyle, collectTextContent } from \"../reconciler/nodes.js\";\nimport type { Cell } from \"./framebuffer.js\";\nimport { Framebuffer } from \"./framebuffer.js\";\nimport { getBorderChars } from \"./borders.js\";\nimport { isLightColor } from \"./color.js\";\nimport type { Color, Style } from \"../types/index.js\";\nimport { wrapLines } from \"../layout/textMeasure.js\";\nimport stringWidth from \"string-width\";\n\ninterface ClipRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\ninterface PaintEntry {\n node: GlyphNode;\n clip: ClipRect;\n zIndex: number;\n}\n\nexport interface CursorScreenPosition {\n x: number;\n y: number;\n /** Background color at cursor position for contrast calculation */\n bg?: Color;\n}\n\nexport interface PaintOptions {\n cursorInfo?: { nodeId: string; position: number };\n /** If true, don't paint the cursor and return its screen position instead */\n useNativeCursor?: boolean;\n}\n\nexport interface PaintResult {\n /** Cursor screen position if useNativeCursor is true and an input is focused */\n cursorPosition?: CursorScreenPosition;\n}\n\nexport function paintTree(\n roots: GlyphNode[],\n fb: Framebuffer,\n options: PaintOptions = {},\n): PaintResult {\n fb.clear();\n\n const result: PaintResult = {};\n\n // Collect all nodes with their z-index for proper ordering\n const entries: PaintEntry[] = [];\n const screenClip: ClipRect = { x: 0, y: 0, width: fb.width, height: fb.height };\n\n for (const root of roots) {\n if (root.hidden) continue;\n collectPaintEntries(root, screenClip, root.style.zIndex ?? 0, entries);\n }\n\n // Sort by zIndex (stable sort preserves tree order within same z)\n entries.sort((a, b) => a.zIndex - b.zIndex);\n\n // Paint each entry\n for (const entry of entries) {\n const nodeResult = paintNode(entry.node, fb, entry.clip, options);\n // Capture cursor position from the focused input\n if (nodeResult?.cursorPosition) {\n result.cursorPosition = nodeResult.cursorPosition;\n }\n }\n\n return result;\n}\n\nfunction collectPaintEntries(\n node: GlyphNode,\n parentClip: ClipRect,\n parentZ: number,\n entries: PaintEntry[],\n): void {\n if (node.hidden) return;\n\n const zIndex = node.style.zIndex ?? parentZ;\n\n // Compute clip for this node\n const clip = node.style.clip ? intersectClip(parentClip, {\n x: node.layout.innerX,\n y: node.layout.innerY,\n width: node.layout.innerWidth,\n height: node.layout.innerHeight,\n }) : parentClip;\n\n entries.push({ node, clip: parentClip, zIndex });\n\n // Children - skip for text/input (leaf nodes for painting)\n if (node.type !== \"text\" && node.type !== \"input\") {\n for (const child of node.children) {\n collectPaintEntries(child, clip, zIndex, entries);\n }\n }\n}\n\nfunction intersectClip(a: ClipRect, b: ClipRect): ClipRect {\n const x = Math.max(a.x, b.x);\n const y = Math.max(a.y, b.y);\n const right = Math.min(a.x + a.width, b.x + b.width);\n const bottom = Math.min(a.y + a.height, b.y + b.height);\n return {\n x,\n y,\n width: Math.max(0, right - x),\n height: Math.max(0, bottom - y),\n };\n}\n\nfunction isInClip(x: number, y: number, clip: ClipRect): boolean {\n return x >= clip.x && x < clip.x + clip.width && y >= clip.y && y < clip.y + clip.height;\n}\n\nfunction paintNode(\n node: GlyphNode,\n fb: Framebuffer,\n clip: ClipRect,\n options: PaintOptions = {},\n): PaintResult | undefined {\n const { x, y, width, height, innerX, innerY, innerWidth, innerHeight } = node.layout;\n const style = node.style;\n\n if (width <= 0 || height <= 0) return;\n\n // Resolve inherited bg so borders and fills don't erase a parent's background\n const inherited = getInheritedTextStyle(node);\n const effectiveBg = inherited.bg;\n\n // 1. Background fill\n if (style.bg) {\n for (let row = y; row < y + height; row++) {\n for (let col = x; col < x + width; col++) {\n if (isInClip(col, row, clip)) {\n fb.setChar(col, row, \" \", undefined, style.bg);\n }\n }\n }\n }\n\n // 2. Border\n const borderChars = style.border ? getBorderChars(style.border) : null;\n if (borderChars && width >= 2 && height >= 2) {\n const bc = style.borderColor;\n const bg = effectiveBg;\n\n // Top border\n setClipped(fb, clip, x, y, borderChars.topLeft, bc, bg);\n for (let col = x + 1; col < x + width - 1; col++) {\n setClipped(fb, clip, col, y, borderChars.horizontal, bc, bg);\n }\n setClipped(fb, clip, x + width - 1, y, borderChars.topRight, bc, bg);\n\n // Bottom border\n setClipped(fb, clip, x, y + height - 1, borderChars.bottomLeft, bc, bg);\n for (let col = x + 1; col < x + width - 1; col++) {\n setClipped(fb, clip, col, y + height - 1, borderChars.horizontal, bc, bg);\n }\n setClipped(fb, clip, x + width - 1, y + height - 1, borderChars.bottomRight, bc, bg);\n\n // Side borders\n for (let row = y + 1; row < y + height - 1; row++) {\n setClipped(fb, clip, x, row, borderChars.vertical, bc, bg);\n setClipped(fb, clip, x + width - 1, row, borderChars.vertical, bc, bg);\n }\n }\n\n // 3. Text content\n if (node.type === \"text\") {\n paintText(node, fb, clip);\n } else if (node.type === \"input\") {\n return paintInput(node, fb, clip, options);\n }\n\n return undefined;\n}\n\nfunction setClipped(\n fb: Framebuffer,\n clip: ClipRect,\n x: number,\n y: number,\n ch: string,\n fg?: Color,\n bg?: Color,\n bold?: boolean,\n dim?: boolean,\n italic?: boolean,\n underline?: boolean,\n): void {\n if (isInClip(x, y, clip)) {\n fb.setChar(x, y, ch, fg, bg, bold, dim, italic, underline);\n }\n}\n\nfunction autoContrastFg(explicitColor: Color | undefined, bg: Color | undefined): Color | undefined {\n if (explicitColor !== undefined) return explicitColor;\n if (bg === undefined) return undefined;\n return isLightColor(bg) ? \"black\" : \"white\";\n}\n\nfunction paintText(node: GlyphNode, fb: Framebuffer, clip: ClipRect): void {\n const { innerX, innerY, innerWidth, innerHeight } = node.layout;\n const inherited = getInheritedTextStyle(node);\n const text = collectTextContent(node);\n if (!text) return;\n\n const fg = autoContrastFg(inherited.color, inherited.bg);\n const wrapMode = node.style.wrap ?? \"wrap\";\n const textAlign = node.style.textAlign ?? \"left\";\n const rawLines = text.split(\"\\n\");\n const lines = wrapLines(rawLines, innerWidth, wrapMode);\n\n for (let lineIdx = 0; lineIdx < lines.length && lineIdx < innerHeight; lineIdx++) {\n const line = lines[lineIdx]!;\n const lineWidth = stringWidth(line);\n let offsetX = 0;\n\n if (textAlign === \"center\") {\n offsetX = Math.max(0, Math.floor((innerWidth - lineWidth) / 2));\n } else if (textAlign === \"right\") {\n offsetX = Math.max(0, innerWidth - lineWidth);\n }\n\n let col = 0;\n for (const char of line) {\n const charWidth = stringWidth(char);\n if (charWidth > 0) {\n setClipped(\n fb, clip,\n innerX + offsetX + col, innerY + lineIdx,\n char,\n fg,\n inherited.bg,\n inherited.bold,\n inherited.dim,\n inherited.italic,\n inherited.underline,\n );\n }\n col += charWidth;\n }\n }\n}\n\nfunction paintInput(\n node: GlyphNode,\n fb: Framebuffer,\n clip: ClipRect,\n options: PaintOptions = {},\n): PaintResult | undefined {\n const { cursorInfo, useNativeCursor } = options;\n const { innerX, innerY, innerWidth, innerHeight } = node.layout;\n if (innerWidth <= 0 || innerHeight <= 0) return;\n\n const value: string = node.props.value ?? node.props.defaultValue ?? \"\";\n const placeholder: string = node.props.placeholder ?? \"\";\n const displayText = value || placeholder;\n const isPlaceholder = !value && !!placeholder;\n const multiline: boolean = node.props.multiline ?? false;\n const inherited = getInheritedTextStyle(node);\n\n const autoFg = autoContrastFg(inherited.color, inherited.bg);\n // For placeholder: use a dimmed contrast color based on background\n // Light bg -> dark gray placeholder, dark bg -> light gray placeholder\n const placeholderFg: Color = inherited.bg \n ? (isLightColor(inherited.bg) ? \"blackBright\" : \"whiteBright\")\n : \"blackBright\";\n const fg = isPlaceholder\n ? placeholderFg\n : (autoFg ?? inherited.color ?? node.style.color);\n const textFg = isPlaceholder ? placeholderFg : fg;\n // Force dim for placeholder text to make it visually distinct\n const textDim = isPlaceholder ? true : inherited.dim;\n\n const isFocused = cursorInfo && cursorInfo.nodeId === node.focusId;\n let result: PaintResult | undefined;\n\n if (multiline && !isPlaceholder) {\n // ── Multiline rendering with wrapping ─────────────────────\n const wrapMode = node.style.wrap ?? \"wrap\";\n const rawLines = displayText.split(\"\\n\");\n const wrappedLines = wrapLines(rawLines, innerWidth, wrapMode);\n\n // Convert flat cursor position to screen (wrappedLine, col)\n let cursorScreenLine = 0;\n let cursorScreenCol = 0;\n if (isFocused) {\n const pos = cursorInfo.position;\n \n // Find which logical line the cursor is on\n let logicalLine = 0;\n let offsetInLogicalLine = pos;\n let runningPos = 0;\n \n for (let i = 0; i < rawLines.length; i++) {\n const lineLen = rawLines[i]!.length;\n if (pos <= runningPos + lineLen) {\n logicalLine = i;\n offsetInLogicalLine = pos - runningPos;\n break;\n }\n runningPos += lineLen + 1; // +1 for newline\n }\n \n // Count wrapped lines before this logical line\n let wrappedLinesBefore = 0;\n for (let i = 0; i < logicalLine; i++) {\n wrappedLinesBefore += wrapLines([rawLines[i]!], innerWidth, wrapMode).length;\n }\n \n // Wrap the current logical line and find cursor position within it\n const wrappedCurrentLine = wrapLines([rawLines[logicalLine]!], innerWidth, wrapMode);\n let charsProcessed = 0;\n let subLineIdx = 0;\n \n for (let i = 0; i < wrappedCurrentLine.length; i++) {\n const subLine = wrappedCurrentLine[i]!;\n if (offsetInLogicalLine <= charsProcessed + subLine.length) {\n subLineIdx = i;\n break;\n }\n charsProcessed += subLine.length;\n }\n \n cursorScreenLine = wrappedLinesBefore + subLineIdx;\n cursorScreenCol = stringWidth(rawLines[logicalLine]!.slice(charsProcessed, charsProcessed + (offsetInLogicalLine - charsProcessed)));\n }\n\n // Auto-scroll to keep cursor visible\n const scrollOffset = Math.max(0, cursorScreenLine - innerHeight + 1);\n\n // Render visible wrapped lines\n for (let rowIdx = 0; rowIdx < innerHeight; rowIdx++) {\n const lineNum = scrollOffset + rowIdx;\n if (lineNum >= wrappedLines.length) break;\n const line = wrappedLines[lineNum]!;\n let col = 0;\n for (const char of line) {\n if (col >= innerWidth) break;\n const charWidth = stringWidth(char);\n if (charWidth > 0) {\n setClipped(\n fb, clip,\n innerX + col, innerY + rowIdx,\n char,\n textFg, inherited.bg,\n inherited.bold, textDim, inherited.italic, inherited.underline,\n );\n }\n col += charWidth;\n }\n }\n\n // Cursor handling\n if (isFocused) {\n const screenRow = cursorScreenLine - scrollOffset;\n if (screenRow >= 0 && screenRow < innerHeight) {\n const cCol = Math.min(cursorScreenCol, innerWidth - 1);\n const cursorX = innerX + cCol;\n const cursorY = innerY + screenRow;\n if (isInClip(cursorX, cursorY, clip) && cursorX < innerX + innerWidth) {\n if (useNativeCursor) {\n // Return cursor position for native cursor positioning\n result = { cursorPosition: { x: cursorX, y: cursorY, bg: inherited.bg } };\n } else {\n // Paint simulated cursor\n const existing = fb.get(cursorX, cursorY);\n const cursorChar = existing?.ch && existing.ch !== \" \" ? existing.ch : \"▌\";\n const cursorFg = inherited.bg ?? \"black\";\n const cursorBg = inherited.color ?? \"white\";\n fb.setChar(\n cursorX, cursorY,\n cursorChar,\n cursorFg,\n cursorBg,\n existing?.bold, existing?.dim, existing?.italic,\n false,\n );\n }\n }\n }\n }\n } else {\n // ── Single-line rendering ───────────────────────────────\n let col = 0;\n for (const char of displayText) {\n if (col >= innerWidth) break;\n const charWidth = stringWidth(char);\n if (charWidth > 0) {\n setClipped(\n fb, clip,\n innerX + col, innerY,\n char,\n textFg, inherited.bg,\n inherited.bold, textDim, inherited.italic, inherited.underline,\n );\n }\n col += charWidth;\n }\n\n // Cursor handling\n if (isFocused) {\n const cursorCol = Math.min(cursorInfo.position, innerWidth - 1);\n const cursorX = innerX + cursorCol;\n if (isInClip(cursorX, innerY, clip) && cursorX < innerX + innerWidth) {\n if (useNativeCursor) {\n // Return cursor position for native cursor positioning\n result = { cursorPosition: { x: cursorX, y: innerY, bg: inherited.bg } };\n } else {\n // Paint simulated cursor\n const existing = fb.get(cursorX, innerY);\n const cursorChar = existing?.ch && existing.ch !== \" \" ? existing.ch : \"▌\";\n const cursorFg = inherited.bg ?? \"black\";\n const cursorBg = inherited.color ?? \"white\";\n fb.setChar(\n cursorX, innerY,\n cursorChar,\n cursorFg,\n cursorBg,\n existing?.bold, existing?.dim, existing?.italic,\n false,\n );\n }\n }\n }\n }\n\n return result;\n}\n","import type { Cell } from \"./framebuffer.js\";\nimport { Framebuffer } from \"./framebuffer.js\";\nimport { colorToFg, colorToBg } from \"./color.js\";\n\nconst ESC = \"\\x1b\";\nconst CSI = `${ESC}[`;\n\nfunction moveCursor(x: number, y: number): string {\n return `${CSI}${y + 1};${x + 1}H`;\n}\n\nfunction buildSGR(cell: Cell): string {\n let seq = `${CSI}0m`;\n if (cell.bold) seq += `${CSI}1m`;\n if (cell.dim) seq += `${CSI}2m`;\n if (cell.italic) seq += `${CSI}3m`;\n if (cell.underline) seq += `${CSI}4m`;\n if (cell.fg != null) seq += colorToFg(cell.fg);\n if (cell.bg != null) seq += colorToBg(cell.bg);\n return seq;\n}\n\nexport function diffFramebuffers(\n prev: Framebuffer,\n next: Framebuffer,\n fullRedraw: boolean,\n): string {\n let out = \"\";\n let lastX = -1;\n let lastY = -1;\n let lastSGR = \"\";\n\n for (let y = 0; y < next.height; y++) {\n for (let x = 0; x < next.width; x++) {\n const nc = next.get(x, y)!;\n if (!fullRedraw) {\n const pc = prev.get(x, y);\n if (pc && next.cellsEqual(nc, pc)) continue;\n }\n\n if (lastY !== y || lastX !== x) {\n out += moveCursor(x, y);\n }\n\n const sgr = buildSGR(nc);\n if (sgr !== lastSGR) {\n out += sgr;\n lastSGR = sgr;\n }\n\n out += nc.ch;\n lastX = x + 1;\n lastY = y;\n }\n }\n\n if (out.length > 0) {\n out += `${CSI}0m`;\n }\n\n return out;\n}\n","import Yoga, {\n Align,\n Edge,\n FlexDirection,\n Gutter,\n Justify,\n PositionType,\n Wrap,\n Direction,\n Overflow,\n} from \"yoga-layout\";\nimport type { Node as YogaNode } from \"yoga-layout\";\nimport type { GlyphNode, GlyphContainer } from \"../reconciler/nodes.js\";\nimport type { Style, DimensionValue } from \"../types/index.js\";\nimport { measureText } from \"./textMeasure.js\";\n\nconst FLEX_DIR_MAP: Record<string, FlexDirection> = {\n row: FlexDirection.Row,\n column: FlexDirection.Column,\n};\n\nconst JUSTIFY_MAP: Record<string, Justify> = {\n \"flex-start\": Justify.FlexStart,\n center: Justify.Center,\n \"flex-end\": Justify.FlexEnd,\n \"space-between\": Justify.SpaceBetween,\n \"space-around\": Justify.SpaceAround,\n};\n\nconst ALIGN_MAP: Record<string, Align> = {\n \"flex-start\": Align.FlexStart,\n center: Align.Center,\n \"flex-end\": Align.FlexEnd,\n stretch: Align.Stretch,\n};\n\nfunction setDimension(\n node: YogaNode,\n setter: (v: number | `${number}%` | undefined) => void,\n value: DimensionValue | undefined,\n): void {\n if (value === undefined) return;\n if (typeof value === \"string\" && value.endsWith(\"%\")) {\n setter(value as `${number}%`);\n } else {\n setter(value as number);\n }\n}\n\nfunction setPosition(\n node: YogaNode,\n edge: Edge,\n value: DimensionValue | undefined,\n): void {\n if (value === undefined) return;\n if (typeof value === \"string\" && value.endsWith(\"%\")) {\n node.setPositionPercent(edge, parseFloat(value));\n } else {\n node.setPosition(edge, value as number);\n }\n}\n\nfunction applyStyleToYogaNode(yogaNode: YogaNode, style: Style, nodeType: string): void {\n // Dimensions\n setDimension(yogaNode, (v) => yogaNode.setWidth(v as any), style.width);\n setDimension(yogaNode, (v) => yogaNode.setHeight(v as any), style.height);\n\n if (style.minWidth !== undefined) yogaNode.setMinWidth(style.minWidth);\n if (style.minHeight !== undefined) yogaNode.setMinHeight(style.minHeight);\n if (style.maxWidth !== undefined) yogaNode.setMaxWidth(style.maxWidth);\n if (style.maxHeight !== undefined) yogaNode.setMaxHeight(style.maxHeight);\n\n // Padding\n if (style.padding !== undefined) yogaNode.setPadding(Edge.All, style.padding);\n if (style.paddingX !== undefined) yogaNode.setPadding(Edge.Horizontal, style.paddingX);\n if (style.paddingY !== undefined) yogaNode.setPadding(Edge.Vertical, style.paddingY);\n if (style.paddingTop !== undefined) yogaNode.setPadding(Edge.Top, style.paddingTop);\n if (style.paddingRight !== undefined) yogaNode.setPadding(Edge.Right, style.paddingRight);\n if (style.paddingBottom !== undefined) yogaNode.setPadding(Edge.Bottom, style.paddingBottom);\n if (style.paddingLeft !== undefined) yogaNode.setPadding(Edge.Left, style.paddingLeft);\n\n // Border thickness for layout (1 cell if border is set, 0 otherwise)\n const hasBorder = style.border != null && style.border !== \"none\";\n yogaNode.setBorder(Edge.All, hasBorder ? 1 : 0);\n\n // Flex\n if (style.flexDirection) {\n yogaNode.setFlexDirection(FLEX_DIR_MAP[style.flexDirection] ?? FlexDirection.Column);\n }\n if (style.flexWrap) {\n yogaNode.setFlexWrap(style.flexWrap === \"wrap\" ? Wrap.Wrap : Wrap.NoWrap);\n }\n if (style.justifyContent) {\n yogaNode.setJustifyContent(JUSTIFY_MAP[style.justifyContent] ?? Justify.FlexStart);\n }\n if (style.alignItems) {\n yogaNode.setAlignItems(ALIGN_MAP[style.alignItems] ?? Align.Stretch);\n }\n if (style.flexGrow !== undefined) yogaNode.setFlexGrow(style.flexGrow);\n if (style.flexShrink !== undefined) yogaNode.setFlexShrink(style.flexShrink);\n\n // Gap\n if (style.gap !== undefined) yogaNode.setGap(Gutter.All, style.gap);\n\n // Positioning\n if (style.position === \"absolute\") {\n yogaNode.setPositionType(PositionType.Absolute);\n } else {\n yogaNode.setPositionType(PositionType.Relative);\n }\n\n // Inset shorthand\n if (style.inset !== undefined) {\n setPosition(yogaNode, Edge.Top, style.inset);\n setPosition(yogaNode, Edge.Right, style.inset);\n setPosition(yogaNode, Edge.Bottom, style.inset);\n setPosition(yogaNode, Edge.Left, style.inset);\n }\n\n setPosition(yogaNode, Edge.Top, style.top);\n setPosition(yogaNode, Edge.Right, style.right);\n setPosition(yogaNode, Edge.Bottom, style.bottom);\n setPosition(yogaNode, Edge.Left, style.left);\n\n // Overflow / clip\n if (style.clip) {\n yogaNode.setOverflow(Overflow.Hidden);\n }\n}\n\nfunction buildYogaTree(node: GlyphNode): void {\n const yogaNode = Yoga.Node.create();\n node.yogaNode = yogaNode;\n\n applyStyleToYogaNode(yogaNode, node.style, node.type);\n\n if (node.type === \"text\" || node.type === \"input\") {\n yogaNode.setMeasureFunc((width, widthMode, height, heightMode) => {\n let text: string;\n if (node.type === \"input\") {\n text = node.props.value ?? node.props.defaultValue ?? node.props.placeholder ?? \"\";\n if (text.length === 0) text = \" \";\n } else {\n text = collectAllText(node);\n }\n return measureText(\n text,\n width,\n widthMode,\n node.style.wrap ?? \"wrap\",\n );\n });\n } else {\n // Build children\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i]!;\n if (child.hidden) continue;\n buildYogaTree(child);\n yogaNode.insertChild(child.yogaNode!, yogaNode.getChildCount());\n }\n }\n}\n\nfunction collectAllText(node: GlyphNode): string {\n if (node.text != null) return node.text;\n let result = \"\";\n for (const child of node.children) {\n result += collectAllText(child);\n }\n if (result === \"\" && node.props.children != null) {\n if (typeof node.props.children === \"string\") return node.props.children;\n if (typeof node.props.children === \"number\") return String(node.props.children);\n }\n return result;\n}\n\nfunction extractLayout(node: GlyphNode, parentX: number, parentY: number): void {\n const yn = node.yogaNode!;\n const computedLayout = yn.getComputedLayout();\n\n const x = parentX + computedLayout.left;\n const y = parentY + computedLayout.top;\n const width = computedLayout.width;\n const height = computedLayout.height;\n\n const borderWidth = node.style.border && node.style.border !== \"none\" ? 1 : 0;\n const paddingTop = yn.getComputedPadding(Edge.Top);\n const paddingRight = yn.getComputedPadding(Edge.Right);\n const paddingBottom = yn.getComputedPadding(Edge.Bottom);\n const paddingLeft = yn.getComputedPadding(Edge.Left);\n\n const innerX = x + borderWidth + paddingLeft;\n const innerY = y + borderWidth + paddingTop;\n const innerWidth = Math.max(0, width - borderWidth * 2 - paddingLeft - paddingRight);\n const innerHeight = Math.max(0, height - borderWidth * 2 - paddingTop - paddingBottom);\n\n node.layout = { x, y, width, height, innerX, innerY, innerWidth, innerHeight };\n\n for (const child of node.children) {\n if (child.hidden || !child.yogaNode) continue;\n extractLayout(child, x, y);\n }\n}\n\nfunction freeYogaTree(node: GlyphNode): void {\n for (const child of node.children) {\n if (child.yogaNode) freeYogaTree(child);\n }\n if (node.yogaNode) {\n node.yogaNode.freeRecursive();\n node.yogaNode = null;\n }\n}\n\nexport function computeLayout(\n roots: GlyphNode[],\n screenWidth: number,\n screenHeight: number,\n): void {\n // Create a virtual root Yoga node for the screen\n const rootYoga = Yoga.Node.create();\n rootYoga.setWidth(screenWidth);\n rootYoga.setHeight(screenHeight);\n rootYoga.setFlexDirection(FlexDirection.Column);\n\n for (const child of roots) {\n if (child.hidden) continue;\n buildYogaTree(child);\n rootYoga.insertChild(child.yogaNode!, rootYoga.getChildCount());\n }\n\n rootYoga.calculateLayout(screenWidth, screenHeight, Direction.LTR);\n\n for (const child of roots) {\n if (child.hidden || !child.yogaNode) continue;\n extractLayout(child, 0, 0);\n }\n\n // Free yoga tree\n rootYoga.freeRecursive();\n\n // Clear references (they were freed)\n clearYogaRefs(roots);\n}\n\nfunction clearYogaRefs(nodes: GlyphNode[]): void {\n for (const node of nodes) {\n node.yogaNode = null;\n clearYogaRefs(node.children);\n }\n}\n","import { createContext } from \"react\";\nimport type { Key, LayoutRect } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\n// ---- Input Context ----\nexport type InputHandler = (key: Key) => void;\n/** Returns true if the key was consumed and should not propagate further */\nexport type FocusedInputHandler = (key: Key) => boolean;\n/** Priority handler - returns true if consumed, preventing all other handlers */\nexport type PriorityInputHandler = (key: Key) => boolean;\n\nexport interface InputContextValue {\n subscribe(handler: InputHandler): () => void;\n /** Register a high-priority handler that runs BEFORE focused input handlers */\n subscribePriority(handler: PriorityInputHandler): () => void;\n registerInputHandler(focusId: string, handler: FocusedInputHandler): () => void;\n}\n\nexport const InputContext = createContext<InputContextValue | null>(null);\n\n// ---- Focus Context ----\nexport interface RegisteredElement {\n id: string;\n node: GlyphNode;\n}\n\nexport interface FocusContextValue {\n focusedId: string | null;\n register(id: string, node: GlyphNode): () => void;\n requestFocus(id: string): void;\n focusNext(): void;\n focusPrev(): void;\n /** Mark an element as skippable during Tab navigation (e.g., disabled elements) */\n setSkippable(id: string, skippable: boolean): void;\n trapIds: Set<string> | null;\n pushTrap(ids: Set<string>): () => void;\n onFocusChange(handler: (focusedId: string | null) => void): () => void;\n /** Get all registered focusable elements (for custom navigation UIs) */\n getRegisteredElements(): RegisteredElement[];\n /** Get focusable elements in the current trap scope (or all if no trap) */\n getActiveElements(): RegisteredElement[];\n}\n\nexport const FocusContext = createContext<FocusContextValue | null>(null);\n\n// ---- Layout Context ----\nexport interface LayoutContextValue {\n getLayout(node: GlyphNode): LayoutRect;\n subscribe(node: GlyphNode, handler: (rect: LayoutRect) => void): () => void;\n}\n\nexport const LayoutContext = createContext<LayoutContextValue | null>(null);\n\n// ---- App Context ----\nexport interface AppContextValue {\n registerNode(node: GlyphNode): void;\n unregisterNode(node: GlyphNode): void;\n scheduleRender(): void;\n exit(code?: number): void;\n columns: number;\n rows: number;\n}\n\nexport const AppContext = createContext<AppContextValue | null>(null);\n\n// ---- ScrollView Context ----\n/** Provides boundary information for elements inside a ScrollView */\nexport interface ScrollViewBounds {\n /** Absolute Y position of visible area top (screen coordinates) */\n visibleTop: number;\n /** Absolute Y position of visible area bottom (screen coordinates) */\n visibleBottom: number;\n /** Height of the visible viewport */\n viewportHeight: number;\n /** Current scroll offset */\n scrollOffset: number;\n}\n\nexport interface ScrollViewContextValue {\n /** Get the current visible bounds of the ScrollView */\n getBounds(): ScrollViewBounds;\n}\n\nexport const ScrollViewContext = createContext<ScrollViewContextValue | null>(null);\n","import React from \"react\";\nimport type { ReactElement } from \"react\";\nimport { reconciler } from \"./reconciler/reconciler.js\";\nimport type { GlyphContainer } from \"./reconciler/nodes.js\";\nimport type { GlyphNode } from \"./reconciler/nodes.js\";\nimport { Terminal } from \"./runtime/terminal.js\";\nimport { parseKeySequence } from \"./runtime/input.js\";\nimport { Framebuffer } from \"./paint/framebuffer.js\";\nimport { paintTree } from \"./paint/painter.js\";\nimport { diffFramebuffers } from \"./paint/diff.js\";\nimport { computeLayout } from \"./layout/yogaLayout.js\";\nimport { setTerminalPalette, getContrastCursorColor } from \"./paint/color.js\";\nimport {\n InputContext,\n FocusContext,\n LayoutContext,\n AppContext,\n} from \"./hooks/context.js\";\nimport type {\n InputHandler,\n FocusedInputHandler,\n PriorityInputHandler,\n InputContextValue,\n FocusContextValue,\n LayoutContextValue,\n AppContextValue,\n} from \"./hooks/context.js\";\nimport type { RenderOptions, AppHandle, LayoutRect } from \"./types/index.js\";\n\nexport function render(\n element: ReactElement,\n opts: RenderOptions = {},\n): AppHandle {\n const stdout = opts.stdout ?? process.stdout;\n const stdin = opts.stdin ?? process.stdin;\n const debug = opts.debug ?? false;\n const useNativeCursor = opts.useNativeCursor ?? true;\n\n const terminal = new Terminal(stdout, stdin);\n terminal.setup();\n\n // Track whether native cursor is currently visible\n let nativeCursorVisible = false;\n\n // Query terminal for actual ANSI palette colors (async, repaint when done)\n terminal.queryPalette().then((palette) => {\n setTerminalPalette(palette);\n fullRedraw = true;\n scheduleRender();\n });\n\n const prevFb = new Framebuffer(terminal.columns, terminal.rows);\n const currentFb = new Framebuffer(terminal.columns, terminal.rows);\n let fullRedraw = true;\n\n // ---- Input system ----\n const inputHandlers = new Set<InputHandler>();\n const priorityHandlers = new Set<PriorityInputHandler>(); // Run before focused handlers\n const focusedInputHandlers = new Map<string, FocusedInputHandler>();\n\n const inputContextValue: InputContextValue = {\n subscribe(handler: InputHandler) {\n inputHandlers.add(handler);\n return () => inputHandlers.delete(handler);\n },\n subscribePriority(handler: PriorityInputHandler) {\n priorityHandlers.add(handler);\n return () => priorityHandlers.delete(handler);\n },\n registerInputHandler(focusId: string, handler: FocusedInputHandler) {\n focusedInputHandlers.set(focusId, handler);\n return () => focusedInputHandlers.delete(focusId);\n },\n };\n\n // ---- Focus system ----\n let focusedId: string | null = null;\n const focusRegistry = new Map<string, GlyphNode>();\n const focusOrder: string[] = [];\n const skippableIds = new Set<string>(); // Disabled/skippable elements during Tab\n let trapStack: Array<Set<string>> = [];\n const focusChangeHandlers = new Set<(id: string | null) => void>();\n\n function setFocusedId(id: string | null): void {\n if (focusedId !== id) {\n focusedId = id;\n scheduleRender();\n for (const handler of focusChangeHandlers) {\n handler(focusedId);\n }\n }\n }\n\n function getActiveFocusableIds(): string[] {\n let ids = [...focusOrder]; // Copy to avoid mutating original\n \n // Filter by trap if active\n if (trapStack.length > 0) {\n const trap = trapStack[trapStack.length - 1]!;\n ids = ids.filter((id) => trap.has(id));\n }\n \n // Filter out skippable (disabled) elements\n ids = ids.filter((id) => !skippableIds.has(id));\n \n // Sort by visual position (top-to-bottom, left-to-right) - like web DOM order\n ids.sort((a, b) => {\n const nodeA = focusRegistry.get(a);\n const nodeB = focusRegistry.get(b);\n if (!nodeA || !nodeB) return 0;\n \n const layoutA = nodeA.layout;\n const layoutB = nodeB.layout;\n \n // Compare Y first (row), then X (column)\n if (layoutA.y !== layoutB.y) {\n return layoutA.y - layoutB.y;\n }\n return layoutA.x - layoutB.x;\n });\n \n return ids;\n }\n\n const focusContextValue: FocusContextValue = {\n get focusedId() {\n return focusedId;\n },\n register(id: string, node: GlyphNode) {\n focusRegistry.set(id, node);\n if (!focusOrder.includes(id)) {\n focusOrder.push(id);\n }\n // Auto-register in active trap\n if (trapStack.length > 0) {\n trapStack[trapStack.length - 1]!.add(id);\n }\n // Auto-focus first item if nothing focused (by visual order)\n if (focusedId === null) {\n const activeIds = getActiveFocusableIds();\n if (activeIds.length > 0) {\n setFocusedId(activeIds[0]!);\n }\n }\n return () => {\n focusRegistry.delete(id);\n const idx = focusOrder.indexOf(id);\n if (idx !== -1) focusOrder.splice(idx, 1);\n if (focusedId === id) {\n // Focus first by visual order\n const activeIds = getActiveFocusableIds();\n setFocusedId(activeIds[0] ?? null);\n }\n };\n },\n requestFocus(id: string) {\n setFocusedId(id);\n },\n focusNext() {\n const ids = getActiveFocusableIds();\n if (ids.length === 0) return;\n const currentIdx = focusedId ? ids.indexOf(focusedId) : -1;\n const nextIdx = (currentIdx + 1) % ids.length;\n setFocusedId(ids[nextIdx]!);\n },\n focusPrev() {\n const ids = getActiveFocusableIds();\n if (ids.length === 0) return;\n const currentIdx = focusedId ? ids.indexOf(focusedId) : 0;\n const prevIdx = (currentIdx - 1 + ids.length) % ids.length;\n setFocusedId(ids[prevIdx]!);\n },\n setSkippable(id: string, skippable: boolean) {\n if (skippable) {\n skippableIds.add(id);\n // If this element is currently focused and now skippable, move focus\n if (focusedId === id) {\n const ids = getActiveFocusableIds();\n if (ids.length > 0) {\n setFocusedId(ids[0]!);\n }\n }\n } else {\n skippableIds.delete(id);\n }\n },\n trapIds: null,\n pushTrap(ids: Set<string>) {\n trapStack.push(ids);\n return () => {\n const idx = trapStack.indexOf(ids);\n if (idx !== -1) trapStack.splice(idx, 1);\n };\n },\n onFocusChange(handler: (id: string | null) => void) {\n focusChangeHandlers.add(handler);\n return () => {\n focusChangeHandlers.delete(handler);\n };\n },\n getRegisteredElements() {\n // Return all non-skippable registered elements\n const result: { id: string; node: GlyphNode }[] = [];\n for (const id of focusOrder) {\n if (skippableIds.has(id)) continue;\n const node = focusRegistry.get(id);\n if (node) {\n result.push({ id, node });\n }\n }\n return result;\n },\n getActiveElements() {\n // Return elements in the current trap scope (or all if no trap)\n const activeIds = getActiveFocusableIds();\n const result: { id: string; node: GlyphNode }[] = [];\n for (const id of activeIds) {\n if (skippableIds.has(id)) continue;\n const node = focusRegistry.get(id);\n if (node) {\n result.push({ id, node });\n }\n }\n return result;\n },\n };\n\n // ---- Layout system ----\n const layoutSubscriptions = new Map<GlyphNode, Set<(rect: LayoutRect) => void>>();\n\n const layoutContextValue: LayoutContextValue = {\n getLayout(node: GlyphNode) {\n return node.layout;\n },\n subscribe(node: GlyphNode, handler: (rect: LayoutRect) => void) {\n if (!layoutSubscriptions.has(node)) {\n layoutSubscriptions.set(node, new Set());\n }\n layoutSubscriptions.get(node)!.add(handler);\n return () => {\n const subs = layoutSubscriptions.get(node);\n if (subs) {\n subs.delete(handler);\n if (subs.size === 0) layoutSubscriptions.delete(node);\n }\n };\n },\n };\n\n // ---- App context ----\n const appContextValue: AppContextValue = {\n registerNode() {},\n unregisterNode() {},\n scheduleRender,\n exit(code?: number) {\n handle.exit(code);\n },\n get columns() {\n return terminal.columns;\n },\n get rows() {\n return terminal.rows;\n },\n };\n\n // ---- Container ----\n const container: GlyphContainer = {\n type: \"root\",\n children: [],\n onCommit() {\n scheduleRender();\n },\n };\n\n // ---- Render scheduling ----\n let renderScheduled = false;\n\n function scheduleRender(): void {\n if (renderScheduled) return;\n renderScheduled = true;\n queueMicrotask(() => {\n renderScheduled = false;\n performRender();\n });\n }\n\n function performRender(): void {\n const cols = terminal.columns;\n const rows = terminal.rows;\n\n if (currentFb.width !== cols || currentFb.height !== rows) {\n currentFb.resize(cols, rows);\n prevFb.resize(cols, rows);\n fullRedraw = true;\n }\n\n // Compute layout\n computeLayout(container.children, cols, rows);\n\n // Notify layout subscribers\n notifyLayoutSubscribers(container.children);\n\n // Find cursor info for focused input\n let cursorInfo: { nodeId: string; position: number } | undefined;\n if (focusedId) {\n const focusedNode = focusRegistry.get(focusedId);\n if (focusedNode?.type === \"input\") {\n cursorInfo = {\n nodeId: focusedId,\n position: focusedNode.props.cursorPosition ?? (focusedNode.props.value?.length ?? 0),\n };\n }\n }\n\n // Paint\n const paintResult = paintTree(container.children, currentFb, {\n cursorInfo,\n useNativeCursor,\n });\n\n // Diff & flush\n const output = diffFramebuffers(prevFb, currentFb, fullRedraw);\n if (output.length > 0) {\n terminal.write(output);\n }\n\n // Handle native cursor positioning\n if (useNativeCursor) {\n if (paintResult.cursorPosition) {\n // Set cursor color to contrast with input background\n const cursorColor = getContrastCursorColor(paintResult.cursorPosition.bg);\n terminal.setCursorColor(cursorColor);\n // Position and show native cursor\n terminal.moveCursor(paintResult.cursorPosition.x, paintResult.cursorPosition.y);\n if (!nativeCursorVisible) {\n terminal.showCursor();\n nativeCursorVisible = true;\n }\n } else {\n // No focused input - hide native cursor\n if (nativeCursorVisible) {\n terminal.hideCursor();\n nativeCursorVisible = false;\n }\n }\n }\n\n // Swap buffers\n for (let i = 0; i < currentFb.cells.length; i++) {\n prevFb.cells[i] = { ...currentFb.cells[i]! };\n }\n fullRedraw = false;\n }\n\n function notifyLayoutSubscribers(nodes: GlyphNode[]): void {\n for (const node of nodes) {\n const subs = layoutSubscriptions.get(node);\n if (subs) {\n for (const handler of subs) {\n handler(node.layout);\n }\n }\n notifyLayoutSubscribers(node.children);\n }\n }\n\n // ---- Input handling ----\n const removeDataListener = terminal.onData((data: string) => {\n const keys = parseKeySequence(data);\n for (const key of keys) {\n // Global: ctrl+c exits\n if (key.ctrl && key.name === \"c\") {\n handle.exit();\n return;\n }\n\n // Global: ctrl+z suspends (background the process)\n // 1. SIGSTOP not SIGTSTP — Node.js ignores SIGTSTP by default.\n // 2. pid 0 = entire process group, so the shell sees the foreground\n // job as stopped (handles bun→tsx→node chains correctly).\n if (key.ctrl && key.name === \"z\") {\n terminal.suspend();\n process.kill(0, \"SIGSTOP\");\n return;\n }\n\n // 1. Priority handlers run first (e.g., global keybinds like Ctrl+Enter)\n let consumed = false;\n for (const handler of priorityHandlers) {\n if (handler(key)) {\n consumed = true;\n break;\n }\n }\n\n // 2. If not consumed, let focused input handler try\n if (!consumed && focusedId) {\n const inputHandler = focusedInputHandlers.get(focusedId);\n if (inputHandler) {\n consumed = inputHandler(key);\n }\n }\n\n // 3. Tab navigation (if not consumed by input handler)\n // This allows inputs to handle Tab via onKeyPress and return true to prevent focus change\n if (!consumed && key.name === \"tab\" && !key.ctrl && !key.alt) {\n if (key.shift) {\n focusContextValue.focusPrev();\n } else {\n focusContextValue.focusNext();\n }\n continue;\n }\n\n // 4. If still not consumed, run global handlers\n if (!consumed) {\n for (const handler of inputHandlers) {\n handler(key);\n }\n }\n }\n });\n\n // ---- Resize handling ----\n const removeResizeListener = terminal.onResize(() => {\n fullRedraw = true;\n scheduleRender();\n });\n\n // ---- SIGCONT: resume after Ctrl+Z suspend ----\n const handleSigcont = () => {\n terminal.resume();\n fullRedraw = true;\n scheduleRender();\n };\n process.on(\"SIGCONT\", handleSigcont);\n\n // ---- Create React tree ----\n const wrappedElement = React.createElement(\n AppContext.Provider,\n { value: appContextValue },\n React.createElement(\n InputContext.Provider,\n { value: inputContextValue },\n React.createElement(\n FocusContext.Provider,\n { value: focusContextValue },\n React.createElement(\n LayoutContext.Provider,\n { value: layoutContextValue },\n element,\n ),\n ),\n ),\n );\n\n // Error handlers for React 19 reconciler\n const onUncaughtError = (error: Error) => {\n if (debug) console.error(\"Uncaught error:\", error);\n };\n const onCaughtError = (error: Error) => {\n // Error caught by ErrorBoundary - this is expected\n if (debug) console.error(\"Error caught by boundary:\", error);\n };\n const onRecoverableError = (error: Error) => {\n if (debug) console.error(\"Recoverable error:\", error);\n };\n\n // Create fiber root\n // Cast to any - react-reconciler types don't match React 19 runtime API\n const root = (reconciler.createContainer as any)(\n container,\n 0, // LegacyRoot tag\n null, // hydrationCallbacks\n false, // isStrictMode\n null, // concurrentUpdatesByDefaultOverride\n \"\", // identifierPrefix\n onUncaughtError,\n onCaughtError,\n onRecoverableError,\n null, // transitionCallbacks\n );\n\n reconciler.updateContainer(wrappedElement, root, null, null);\n\n // ---- Handle ----\n const handle: AppHandle = {\n unmount() {\n reconciler.updateContainer(null, root, null, null);\n removeDataListener();\n removeResizeListener();\n process.off(\"SIGCONT\", handleSigcont);\n terminal.cleanup();\n },\n exit(code?: number) {\n handle.unmount();\n process.exit(code ?? 0);\n },\n };\n\n return handle;\n}\n","import React, { forwardRef } from \"react\";\nimport type { Style } from \"../types/index.js\";\nimport type { ReactNode, Ref } from \"react\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface BoxProps {\n style?: Style;\n children?: ReactNode;\n focusable?: boolean;\n}\n\nexport const Box = forwardRef<GlyphNode, BoxProps>(\n function Box({ children, style, focusable }, ref): React.JSX.Element {\n return React.createElement(\"box\" as any, { style, focusable, ref }, children);\n }\n);\n","import React, { forwardRef } from \"react\";\nimport type { Style } from \"../types/index.js\";\nimport type { ReactNode } from \"react\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface TextProps {\n style?: Style;\n children?: ReactNode;\n wrap?: Style[\"wrap\"];\n}\n\nexport const Text = forwardRef<GlyphNode, TextProps>(\n function Text({ children, style, wrap }, ref): React.JSX.Element {\n const mergedStyle = wrap ? { ...style, wrap } : style;\n return React.createElement(\"text\" as any, { style: mergedStyle, ref }, children);\n }\n);\n","import React, { useState, useContext, useEffect, useRef } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport { InputContext, FocusContext, LayoutContext } from \"../hooks/context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { wrapLines } from \"../layout/textMeasure.js\";\n\n// ── Visual line helpers (accounts for word wrapping) ──────────\n\ninterface VisualLineInfo {\n visualLine: number;\n visualCol: number;\n totalVisualLines: number;\n /** Character offset where current visual line starts in original text */\n lineStartOffset: number;\n /** Length of current visual line */\n lineLength: number;\n}\n\n/**\n * Convert flat cursor position → visual (wrapped) line/col.\n * This accounts for soft wrapping based on width.\n */\nfunction cursorToVisualLine(\n text: string,\n pos: number,\n width: number,\n): VisualLineInfo {\n if (width <= 0) {\n return { visualLine: 0, visualCol: pos, totalVisualLines: 1, lineStartOffset: 0, lineLength: text.length };\n }\n \n const logicalLines = text.split(\"\\n\");\n const allVisualLines: { text: string; logicalOffset: number }[] = [];\n \n let logicalOffset = 0;\n for (const logicalLine of logicalLines) {\n const wrapped = wrapLines([logicalLine], width, \"wrap\");\n let offsetInLogical = 0;\n for (const wrappedLine of wrapped) {\n allVisualLines.push({ \n text: wrappedLine, \n logicalOffset: logicalOffset + offsetInLogical \n });\n offsetInLogical += wrappedLine.length;\n }\n logicalOffset += logicalLine.length + 1; // +1 for newline\n }\n \n // Find which visual line contains the cursor\n let charCount = 0;\n for (let i = 0; i < allVisualLines.length; i++) {\n const vl = allVisualLines[i]!;\n const lineLen = vl.text.length;\n // Account for newline at end of logical lines (except last)\n const isEndOfLogicalLine = i + 1 < allVisualLines.length && \n allVisualLines[i + 1]!.logicalOffset !== vl.logicalOffset + lineLen;\n const effectiveLen = lineLen + (isEndOfLogicalLine ? 1 : 0);\n \n // Use < instead of <= so cursor at wrap boundary belongs to the NEXT line\n // Exception: last line always captures remaining positions\n if (pos < charCount + lineLen || i === allVisualLines.length - 1) {\n return {\n visualLine: i,\n visualCol: Math.min(pos - charCount, lineLen),\n totalVisualLines: allVisualLines.length,\n lineStartOffset: charCount,\n lineLength: lineLen,\n };\n }\n charCount += effectiveLen;\n }\n \n // Fallback\n const lastIdx = allVisualLines.length - 1;\n return {\n visualLine: lastIdx,\n visualCol: allVisualLines[lastIdx]!.text.length,\n totalVisualLines: allVisualLines.length,\n lineStartOffset: charCount - allVisualLines[lastIdx]!.text.length,\n lineLength: allVisualLines[lastIdx]!.text.length,\n };\n}\n\n/**\n * Convert visual (wrapped) line/col → flat cursor position.\n */\nfunction visualLineToCursor(\n text: string,\n visualLine: number,\n visualCol: number,\n width: number,\n): number {\n if (width <= 0) {\n return Math.min(visualCol, text.length);\n }\n \n const logicalLines = text.split(\"\\n\");\n const allVisualLines: { text: string; startOffset: number }[] = [];\n \n let offset = 0;\n for (const logicalLine of logicalLines) {\n const wrapped = wrapLines([logicalLine], width, \"wrap\");\n let offsetInLogical = 0;\n for (const wrappedLine of wrapped) {\n allVisualLines.push({ \n text: wrappedLine, \n startOffset: offset + offsetInLogical \n });\n offsetInLogical += wrappedLine.length;\n }\n offset += logicalLine.length + 1;\n }\n \n const targetLine = Math.max(0, Math.min(visualLine, allVisualLines.length - 1));\n const vl = allVisualLines[targetLine]!;\n const col = Math.min(visualCol, vl.text.length);\n \n return vl.startOffset + col;\n}\n\n// ── Logical line helpers (for Ctrl+A/E/U/K, Home/End) ─────────\n\n/** Convert flat cursor position → (line, col) within newline-separated text. */\nfunction cursorToLineCol(\n text: string,\n pos: number,\n): { line: number; col: number; lines: string[] } {\n const lines = text.split(\"\\n\");\n let remaining = pos;\n for (let i = 0; i < lines.length; i++) {\n if (remaining <= lines[i]!.length) {\n return { line: i, col: remaining, lines };\n }\n remaining -= lines[i]!.length + 1;\n }\n const last = lines.length - 1;\n return { line: last, col: lines[last]!.length, lines };\n}\n\n/** Convert (line, col) → flat cursor position. */\nfunction lineColToCursor(\n lines: string[],\n line: number,\n col: number,\n): number {\n let pos = 0;\n for (let i = 0; i < line && i < lines.length; i++) {\n pos += lines[i]!.length + 1;\n }\n return pos + Math.min(col, lines[line]?.length ?? 0);\n}\n\n// ── Component ─────────────────────────────────────────────────\n\nexport type InputType = \"text\" | \"number\";\n\nexport interface InputProps {\n value?: string;\n defaultValue?: string;\n onChange?: (value: string) => void;\n /** Called on every key press. Return `true` to prevent default handling. */\n onKeyPress?: (key: Key) => boolean | void;\n /** \n * Called before a value change is applied. Useful for input masking/validation.\n * @param newValue - The proposed new value\n * @param oldValue - The current value\n * @returns \n * - `string` to use a different value (and cursor moves to end of returned string)\n * - `false` to reject the change entirely\n * - `undefined` to accept the change as-is\n */\n onBeforeChange?: (newValue: string, oldValue: string) => string | false | void;\n placeholder?: string;\n style?: Style;\n /** Style when focused (merged with style) */\n focusedStyle?: Style;\n /** Enable multiline editing (Enter inserts newlines, Up/Down navigate lines). */\n multiline?: boolean;\n /** Automatically focus this input when mounted */\n autoFocus?: boolean;\n /** \n * Input type for validation:\n * - \"text\" (default): accepts any character\n * - \"number\": only accepts digits, decimal point, and minus sign\n */\n type?: InputType;\n}\n\nexport function Input(props: InputProps): React.JSX.Element {\n const {\n value: controlledValue,\n defaultValue = \"\",\n onChange,\n onKeyPress,\n onBeforeChange,\n placeholder,\n style,\n focusedStyle,\n multiline,\n autoFocus,\n type = \"text\",\n } = props;\n const [internalValue, setInternalValue] = useState(defaultValue);\n const [cursorPos, setCursorPos] = useState(defaultValue.length);\n const [innerWidth, setInnerWidth] = useState(0);\n const [isFocused, setIsFocused] = useState(false);\n // Track when node is mounted with a valid focusId\n const [nodeReady, setNodeReady] = useState(false);\n const inputCtx = useContext(InputContext);\n const focusCtx = useContext(FocusContext);\n const layoutCtx = useContext(LayoutContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n\n const isControlled = controlledValue !== undefined;\n const value = isControlled ? controlledValue : internalValue;\n\n // Subscribe to layout changes to get innerWidth for visual line navigation\n useEffect(() => {\n if (!layoutCtx || !nodeRef.current) return;\n const layout = layoutCtx.getLayout(nodeRef.current);\n setInnerWidth(layout.innerWidth);\n return layoutCtx.subscribe(nodeRef.current, (rect) => {\n setInnerWidth(rect.innerWidth);\n });\n }, [layoutCtx]);\n\n // Keep working value/cursor in refs that update SYNCHRONOUSLY \n // This prevents race conditions when typing faster than React renders\n const workingValueRef = useRef(value);\n const workingCursorRef = useRef(cursorPos);\n // Track what we last sent to detect external vs echoed changes\n const lastSentValueRef = useRef(value);\n const lastSentCursorRef = useRef(cursorPos);\n \n // Sync refs with React state when it updates\n // Only update if the incoming value is an EXTERNAL change (not just echoing what we sent)\n // This prevents overwriting working refs during fast typing\n useEffect(() => {\n // Only accept the incoming value if it's different from what we last sent\n // This means it's either an external change or a transformed value from the parent\n if (value !== lastSentValueRef.current) {\n workingValueRef.current = value;\n lastSentValueRef.current = value;\n // Move cursor to end of new value for programmatic changes\n workingCursorRef.current = value.length;\n lastSentCursorRef.current = value.length;\n setCursorPos(value.length);\n }\n }, [value]);\n \n // Same logic for cursor - only accept external changes\n useEffect(() => {\n if (cursorPos !== lastSentCursorRef.current) {\n workingCursorRef.current = cursorPos;\n lastSentCursorRef.current = cursorPos;\n }\n }, [cursorPos]);\n\n // Keep a ref to current values so the handler closure always reads fresh state\n const stateRef = useRef({\n isControlled,\n onChange,\n onKeyPress,\n onBeforeChange,\n multiline: multiline ?? false,\n innerWidth,\n type,\n });\n stateRef.current = {\n isControlled,\n onChange,\n onKeyPress,\n onBeforeChange,\n multiline: multiline ?? false,\n innerWidth,\n type,\n };\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, nodeReady]);\n\n // Auto-focus on mount if requested\n // Use setTimeout to ensure this runs AFTER all registrations and layout effects complete\n const autoFocusedRef = useRef(false);\n useEffect(() => {\n // Reset the flag when node is not ready (component unmounted/remounting)\n if (!nodeReady) {\n autoFocusedRef.current = false;\n return;\n }\n \n if (autoFocus && !autoFocusedRef.current && focusCtx && focusIdRef.current) {\n autoFocusedRef.current = true;\n const fid = focusIdRef.current;\n // Use setTimeout(0) instead of queueMicrotask for more reliable timing\n // This ensures registration has fully propagated through the focus system\n const timer = setTimeout(() => {\n focusCtx.requestFocus(fid);\n }, 0);\n return () => clearTimeout(timer);\n }\n }, [autoFocus, focusCtx, nodeReady]);\n\n // Subscribe to focus changes for reactive visual state\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Register focused input handler - returns true for consumed keys\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n const {\n isControlled: ctrl,\n onChange: cb,\n onKeyPress: onKey,\n onBeforeChange: onBefore,\n multiline: ml,\n } = stateRef.current;\n \n // Call onKeyPress callback first - if it returns true, prevent default handling\n if (onKey?.(key) === true) {\n return true;\n }\n \n // Read from working refs (updated synchronously) to handle fast typing\n const val = workingValueRef.current;\n const pos = workingCursorRef.current;\n\n // Escape always passes through\n if (key.name === \"escape\") return false;\n\n // Helper to update value and cursor synchronously\n // Calls onBeforeChange if provided, allowing masking/validation\n const updateValue = (newVal: string, newCursor: number) => {\n let finalVal = newVal;\n let finalCursor = newCursor;\n \n if (onBefore) {\n const result = onBefore(newVal, val);\n if (result === false) {\n // Reject the change entirely\n return;\n }\n if (typeof result === \"string\") {\n // Use the modified value, cursor goes to end\n finalVal = result;\n finalCursor = result.length;\n }\n }\n \n workingValueRef.current = finalVal;\n workingCursorRef.current = finalCursor;\n lastSentValueRef.current = finalVal; // Track what we're sending\n lastSentCursorRef.current = finalCursor;\n if (!ctrl) setInternalValue(finalVal);\n cb?.(finalVal);\n setCursorPos(finalCursor);\n };\n \n const updateCursor = (newCursor: number) => {\n workingCursorRef.current = newCursor;\n lastSentCursorRef.current = newCursor; // Track what we're sending\n setCursorPos(newCursor);\n };\n\n // Return: pass through for single-line, insert newline for multiline\n if (key.name === \"return\") {\n if (ml) {\n const newVal = val.slice(0, pos) + \"\\n\" + val.slice(pos);\n updateValue(newVal, pos + 1);\n return true;\n }\n return false;\n }\n\n // Ctrl shortcuts consumed by the input\n if (key.ctrl) {\n if (key.name === \"w\") {\n // Delete word backward (stops at newline in multiline)\n if (pos > 0) {\n let i = pos;\n while (i > 0 && val[i - 1] === \" \") i--;\n while (\n i > 0 &&\n val[i - 1] !== \" \" &&\n (!ml || val[i - 1] !== \"\\n\")\n )\n i--;\n const newVal = val.slice(0, i) + val.slice(pos);\n updateValue(newVal, i);\n }\n return true;\n }\n if (key.name === \"a\") {\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n updateCursor(lineColToCursor(lines, line, 0));\n } else {\n updateCursor(0);\n }\n return true;\n }\n if (key.name === \"e\") {\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n updateCursor(lineColToCursor(lines, line, lines[line]!.length));\n } else {\n updateCursor(val.length);\n }\n return true;\n }\n if (key.name === \"k\") {\n // Delete from cursor to end of line\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n const lineEnd = lineColToCursor(lines, line, lines[line]!.length);\n if (pos < lineEnd) {\n const newVal = val.slice(0, pos) + val.slice(lineEnd);\n updateValue(newVal, pos);\n }\n } else {\n if (pos < val.length) {\n const newVal = val.slice(0, pos);\n updateValue(newVal, pos);\n }\n }\n return true;\n }\n // All other ctrl combos pass through to useInput\n return false;\n }\n\n // ── Alt + Arrow: Word navigation ────────────────────────\n if (key.alt) {\n if (key.name === \"left\" || key.name === \"b\") {\n // Move to start of previous word\n let i = pos;\n // Skip any spaces before cursor\n while (i > 0 && val[i - 1] === \" \") i--;\n // Skip the word\n while (i > 0 && val[i - 1] !== \" \" && val[i - 1] !== \"\\n\") i--;\n updateCursor(i);\n return true;\n }\n if (key.name === \"right\" || key.name === \"f\") {\n // Move to end of next word\n let i = pos;\n // Skip current word\n while (i < val.length && val[i] !== \" \" && val[i] !== \"\\n\") i++;\n // Skip spaces after word\n while (i < val.length && val[i] === \" \") i++;\n updateCursor(i);\n return true;\n }\n if (key.name === \"backspace\" || key.name === \"d\") {\n // Delete word backward (Alt+Backspace or Alt+D for forward)\n if (key.name === \"backspace\") {\n if (pos > 0) {\n let i = pos;\n while (i > 0 && val[i - 1] === \" \") i--;\n while (i > 0 && val[i - 1] !== \" \" && val[i - 1] !== \"\\n\") i--;\n const newVal = val.slice(0, i) + val.slice(pos);\n updateValue(newVal, i);\n }\n return true;\n } else {\n // Alt+D: delete word forward\n if (pos < val.length) {\n let i = pos;\n while (i < val.length && val[i] !== \" \" && val[i] !== \"\\n\") i++;\n while (i < val.length && val[i] === \" \") i++;\n const newVal = val.slice(0, pos) + val.slice(i);\n updateValue(newVal, pos);\n }\n return true;\n }\n }\n // Pass through other alt combos\n return false;\n }\n\n // ── Navigation ──────────────────────────────────────────\n\n if (key.name === \"left\") {\n updateCursor(Math.max(0, pos - 1));\n return true;\n }\n if (key.name === \"right\") {\n updateCursor(Math.min(val.length, pos + 1));\n return true;\n }\n if (key.name === \"up\") {\n const { innerWidth: w } = stateRef.current;\n // Use visual line navigation (accounts for word wrapping)\n const info = cursorToVisualLine(val, pos, w);\n if (info.visualLine > 0) {\n updateCursor(visualLineToCursor(val, info.visualLine - 1, info.visualCol, w));\n }\n return true;\n }\n if (key.name === \"down\") {\n const { innerWidth: w } = stateRef.current;\n // Use visual line navigation (accounts for word wrapping)\n const info = cursorToVisualLine(val, pos, w);\n if (info.visualLine < info.totalVisualLines - 1) {\n updateCursor(visualLineToCursor(val, info.visualLine + 1, info.visualCol, w));\n }\n return true;\n }\n if (key.name === \"home\") {\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n updateCursor(lineColToCursor(lines, line, 0));\n } else {\n updateCursor(0);\n }\n return true;\n }\n if (key.name === \"end\") {\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n updateCursor(lineColToCursor(lines, line, lines[line]!.length));\n } else {\n updateCursor(val.length);\n }\n return true;\n }\n\n // ── Editing ─────────────────────────────────────────────\n\n if (key.name === \"backspace\") {\n if (pos > 0) {\n const newVal = val.slice(0, pos - 1) + val.slice(pos);\n updateValue(newVal, pos - 1);\n }\n return true;\n }\n if (key.name === \"delete\") {\n if (pos < val.length) {\n const newVal = val.slice(0, pos) + val.slice(pos + 1);\n updateValue(newVal, pos);\n }\n return true;\n }\n\n // Special/function keys we don't handle - pass through\n if (key.name.length > 1) return false;\n\n // Printable character - consume it\n const ch = key.sequence;\n if (ch.length === 1 && ch.charCodeAt(0) >= 32) {\n // Validate input based on type\n const { type: inputType } = stateRef.current;\n if (inputType === \"number\") {\n // Only allow digits, decimal point, minus sign (at start)\n const isDigit = /[0-9]/.test(ch);\n const isDecimal = ch === \".\" && !val.includes(\".\");\n const isMinus = ch === \"-\" && pos === 0 && !val.includes(\"-\");\n if (!isDigit && !isDecimal && !isMinus) {\n return true; // Consume but don't insert\n }\n }\n \n const newVal = val.slice(0, pos) + ch + val.slice(pos);\n updateValue(newVal, pos + 1);\n return true;\n }\n\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, nodeReady]);\n\n // Merge styles based on focus state\n const mergedStyle: Style = {\n ...style,\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n return React.createElement(\"input\" as any, {\n style: mergedStyle,\n value,\n defaultValue,\n placeholder,\n onChange,\n // Use ref (always current) instead of state (can lag during fast typing)\n cursorPosition: workingCursorRef.current,\n multiline: multiline ?? false,\n focused: isFocused,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n });\n}\n","import React, { useContext, useEffect, useLayoutEffect, useRef } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { FocusContext } from \"../hooks/context.js\";\n\nexport interface FocusScopeProps {\n trap?: boolean;\n children?: ReactNode;\n}\n\nexport function FocusScope({ trap = false, children }: FocusScopeProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const prevFocusRef = useRef<string | null>(null);\n const scopeIdsRef = useRef<Set<string>>(new Set());\n\n // Push trap during layout phase - this runs BEFORE children's useEffect,\n // so when children register in their useEffect, the trap is already active\n // and their IDs get added to scopeIdsRef.current\n useLayoutEffect(() => {\n if (!trap || !focusCtx) return;\n\n prevFocusRef.current = focusCtx.focusedId;\n const cleanup = focusCtx.pushTrap(scopeIdsRef.current);\n\n return () => {\n cleanup();\n // Restore previous focus when trap is removed\n if (prevFocusRef.current) {\n focusCtx.requestFocus(prevFocusRef.current);\n }\n };\n }, [trap, focusCtx]);\n\n // Focus first trapped item AFTER children have registered (useEffect runs after children's useEffect)\n useEffect(() => {\n if (!trap || !focusCtx) return;\n if (scopeIdsRef.current.size > 0) {\n const firstId = scopeIdsRef.current.values().next().value;\n if (firstId) focusCtx.requestFocus(firstId);\n }\n }, [trap, focusCtx]);\n\n return React.createElement(React.Fragment, null, children);\n}\n","import React from \"react\";\n\nexport interface SpacerProps {\n size?: number;\n}\n\nexport function Spacer({ size }: SpacerProps): React.JSX.Element {\n return React.createElement(\"box\" as any, {\n style: { flexGrow: size ?? 1 },\n });\n}\n","import { useContext, useEffect, useRef } from \"react\";\nimport { InputContext, FocusContext } from \"../hooks/context.js\";\nimport type { Key } from \"../types/index.js\";\n\nexport interface KeybindProps {\n /** Key descriptor, e.g. \"q\", \"escape\", \"ctrl+c\", \"ctrl+shift+a\" */\n keypress: string;\n /** Handler called when the key matches */\n onPress: () => void;\n /** Only fire when this focus ID is active */\n whenFocused?: string;\n /** Only fire when nothing is focused or the focused element doesn't consume the key */\n global?: boolean;\n /** \n * If true, this keybind runs BEFORE focused input handlers.\n * Use for keybinds that should work even when an Input is focused (e.g., Ctrl+Enter to submit).\n */\n priority?: boolean;\n /** Disabled state */\n disabled?: boolean;\n}\n\ninterface KeyMatcher {\n name: string;\n ctrl: boolean;\n alt: boolean;\n shift: boolean;\n meta: boolean;\n}\n\nfunction parseKeyDescriptor(descriptor: string): KeyMatcher {\n const parts = descriptor.toLowerCase().split(\"+\");\n const name = parts[parts.length - 1]!;\n return {\n name,\n ctrl: parts.includes(\"ctrl\"),\n alt: parts.includes(\"alt\"),\n shift: parts.includes(\"shift\"),\n meta: parts.includes(\"meta\") || parts.includes(\"cmd\") || parts.includes(\"super\") || parts.includes(\"win\"),\n };\n}\n\nfunction matchesKey(matcher: KeyMatcher, key: Key): boolean {\n if (key.name !== matcher.name) return false;\n if (matcher.ctrl !== !!key.ctrl) return false;\n if (matcher.alt !== !!key.alt) return false;\n if (matcher.shift !== !!key.shift) return false;\n if (matcher.meta !== !!key.meta) return false;\n return true;\n}\n\nexport function Keybind({\n keypress,\n onPress,\n whenFocused,\n priority,\n disabled,\n}: KeybindProps): null {\n const inputCtx = useContext(InputContext);\n const focusCtx = useContext(FocusContext);\n const onPressRef = useRef(onPress);\n onPressRef.current = onPress;\n\n const matcherRef = useRef<KeyMatcher>(parseKeyDescriptor(keypress));\n matcherRef.current = parseKeyDescriptor(keypress);\n\n useEffect(() => {\n if (!inputCtx || disabled) return;\n\n if (priority) {\n // Priority handler - runs before focused input handlers\n const handler = (key: Key): boolean => {\n if (!matchesKey(matcherRef.current, key)) return false;\n\n // If whenFocused is specified, only fire when that ID is focused\n if (whenFocused && focusCtx?.focusedId !== whenFocused) return false;\n\n onPressRef.current();\n return true; // Consumed - prevent further propagation\n };\n\n return inputCtx.subscribePriority(handler);\n } else {\n // Normal handler - runs after focused input handlers (if not consumed)\n const handler = (key: Key) => {\n if (!matchesKey(matcherRef.current, key)) return;\n\n // If whenFocused is specified, only fire when that ID is focused\n if (whenFocused && focusCtx?.focusedId !== whenFocused) return;\n\n onPressRef.current();\n };\n\n return inputCtx.subscribe(handler);\n }\n }, [inputCtx, focusCtx, whenFocused, priority, disabled]);\n\n return null;\n}\n","import React from \"react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PortalProps {\n children?: ReactNode;\n zIndex?: number;\n}\n\n/**\n * Portal renders children as a fullscreen absolute overlay on top of the main tree.\n * Useful for modals, notifications, and dropdowns that should paint above all other content.\n */\nexport function Portal({ children, zIndex = 1000 }: PortalProps): React.JSX.Element {\n return React.createElement(\n \"box\" as any,\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n height: \"100%\",\n zIndex,\n },\n },\n children,\n );\n}\n","import React, { useContext, useEffect, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport { FocusContext, InputContext } from \"../hooks/context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface ButtonProps {\n onPress?: () => void;\n style?: Style;\n focusedStyle?: Style;\n children?: ReactNode;\n disabled?: boolean;\n}\n\nexport function Button({\n onPress,\n style,\n focusedStyle,\n children,\n disabled,\n}: ButtonProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onPressRef = useRef(onPress);\n onPressRef.current = onPress;\n\n // Track when node is mounted with a valid focusId - this triggers effect re-runs\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || disabled) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, disabled, nodeReady]);\n\n // Subscribe to focus changes for reactive visual state\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n // Set initial state\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Handle enter/space when focused\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n if (key.name === \"return\" || key.name === \" \" || key.sequence === \" \") {\n onPressRef.current?.();\n return true;\n }\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, disabled, nodeReady]);\n\n const mergedStyle: Style = {\n ...style,\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n return React.createElement(\n \"box\" as any,\n {\n style: mergedStyle,\n focusable: !disabled,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n children,\n );\n}\n","import { useContext, useState, useEffect } from \"react\";\nimport { LayoutContext } from \"./context.js\";\nimport type { LayoutRect } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nconst DEFAULT_RECT: LayoutRect = {\n x: 0, y: 0, width: 0, height: 0,\n innerX: 0, innerY: 0, innerWidth: 0, innerHeight: 0,\n};\n\nexport function useLayout(nodeRef?: { current: GlyphNode | null }): LayoutRect {\n const ctx = useContext(LayoutContext);\n const [layout, setLayout] = useState<LayoutRect>(DEFAULT_RECT);\n\n useEffect(() => {\n if (!ctx || !nodeRef?.current) return;\n setLayout(ctx.getLayout(nodeRef.current));\n return ctx.subscribe(nodeRef.current, setLayout);\n }, [ctx, nodeRef]);\n\n return layout;\n}\n","import { useContext, useEffect } from \"react\";\nimport { InputContext } from \"./context.js\";\nimport type { Key } from \"../types/index.js\";\n\nexport function useInput(\n handler: (key: Key) => void,\n deps: any[] = [],\n): void {\n const ctx = useContext(InputContext);\n\n useEffect(() => {\n if (!ctx) return;\n return ctx.subscribe(handler);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ctx, ...deps]);\n}\n","import React, { useRef, useState, useCallback, useEffect, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { useLayout } from \"../hooks/useLayout.js\";\nimport { useInput } from \"../hooks/useInput.js\";\nimport { FocusContext, LayoutContext, ScrollViewContext } from \"../hooks/context.js\";\nimport type { ScrollViewContextValue, ScrollViewBounds } from \"../hooks/context.js\";\n\nexport interface ScrollViewProps {\n children?: ReactNode;\n style?: Style;\n /** Controlled scroll offset (rows from top) */\n scrollOffset?: number;\n /** Callback when scroll offset should change (controlled mode) */\n onScroll?: (offset: number) => void;\n /** Initial offset for uncontrolled mode */\n defaultScrollOffset?: number;\n /** Lines to scroll per arrow key press (default: 1) */\n scrollStep?: number;\n /** Disable keyboard scrolling */\n disableKeyboard?: boolean;\n /** Auto-scroll to focused element (default: true) */\n scrollToFocus?: boolean;\n /** Show scrollbar when content is scrollable (default: true) */\n showScrollbar?: boolean;\n /** Make ScrollView itself focusable. Default: true. Set to false if you want scroll to follow child focus only. */\n focusable?: boolean;\n /** Style applied when ScrollView is focused */\n focusedStyle?: Style;\n}\n\nexport function ScrollView({\n children,\n style,\n scrollOffset: controlledOffset,\n onScroll,\n defaultScrollOffset = 0,\n scrollStep = 1,\n disableKeyboard,\n scrollToFocus = true,\n showScrollbar = true,\n focusable = true,\n focusedStyle,\n}: ScrollViewProps): React.JSX.Element {\n const isControlled = controlledOffset !== undefined;\n const [internalOffset, setInternalOffset] = useState(defaultScrollOffset);\n const offset = isControlled ? controlledOffset : internalOffset;\n\n const viewportRef = useRef<GlyphNode | null>(null);\n const contentRef = useRef<GlyphNode | null>(null);\n const viewportLayout = useLayout(viewportRef);\n const contentLayout = useLayout(contentRef);\n \n const focusCtx = useContext(FocusContext);\n const layoutCtx = useContext(LayoutContext);\n\n // Generate stable focus ID for this ScrollView if focusable\n const focusIdRef = useRef<string | null>(null);\n if (focusable && !focusIdRef.current) {\n focusIdRef.current = `scrollview-${Math.random().toString(36).slice(2, 9)}`;\n }\n const focusId = focusable ? focusIdRef.current : null;\n\n // Register with focus system if focusable\n useEffect(() => {\n if (!focusable || !focusId || !focusCtx || !viewportRef.current) return;\n return focusCtx.register(focusId, viewportRef.current);\n }, [focusable, focusId, focusCtx]);\n\n // Check if this ScrollView is directly focused\n const isSelfFocused = focusable && focusId && focusCtx?.focusedId === focusId;\n\n const viewportHeight = viewportLayout.innerHeight;\n const contentHeight = contentLayout.height;\n const maxOffset = Math.max(0, contentHeight - viewportHeight);\n\n // Always clamp the effective offset used for rendering\n const effectiveOffset = Math.max(0, Math.min(offset, maxOffset));\n\n // Provide ScrollView context for children (e.g., Select) to know their boundaries\n const scrollViewContextValue = useMemo((): ScrollViewContextValue => ({\n getBounds: (): ScrollViewBounds => {\n const viewportY = viewportLayout.y;\n return {\n visibleTop: viewportY,\n visibleBottom: viewportY + viewportHeight,\n viewportHeight,\n scrollOffset: effectiveOffset,\n };\n },\n }), [viewportLayout.y, viewportHeight, effectiveOffset]);\n\n const setOffset = useCallback(\n (next: number) => {\n const clamped = Math.max(0, Math.min(next, maxOffset));\n if (isControlled) {\n onScroll?.(clamped);\n } else {\n setInternalOffset(clamped);\n }\n },\n [isControlled, onScroll, maxOffset],\n );\n\n // Re-clamp when content/viewport changes\n useEffect(() => {\n if (offset > maxOffset && maxOffset >= 0) {\n setOffset(maxOffset);\n }\n }, [offset, maxOffset, setOffset]);\n\n // Focus-aware scrolling: scroll to make focused element visible\n useEffect(() => {\n if (!scrollToFocus || !focusCtx || !layoutCtx || !contentRef.current) return;\n\n const unsubscribe = focusCtx.onFocusChange((focusedId) => {\n if (!focusedId || !contentRef.current) return;\n\n // Find the focused node by walking the content tree\n const findNode = (node: GlyphNode): GlyphNode | null => {\n if (node.focusId === focusedId) return node;\n for (const child of node.children) {\n const found = findNode(child);\n if (found) return found;\n }\n return null;\n };\n\n const focusedNode = findNode(contentRef.current);\n if (!focusedNode) return; // Focused element is not inside this ScrollView\n\n // Get layout of focused element relative to content\n const focusedLayout = layoutCtx.getLayout(focusedNode);\n const contentTopY = contentRef.current.layout?.y ?? 0;\n \n // Calculate element position relative to content top\n const elementTop = focusedLayout.y - contentTopY;\n const elementBottom = elementTop + focusedLayout.height;\n \n // Current visible range\n const visibleTop = offset;\n const visibleBottom = offset + viewportHeight;\n \n // Check if element is fully visible\n if (elementTop < visibleTop) {\n // Element is above visible area - scroll up\n setOffset(elementTop);\n } else if (elementBottom > visibleBottom) {\n // Element is below visible area - scroll down\n setOffset(elementBottom - viewportHeight);\n }\n });\n\n return unsubscribe;\n }, [scrollToFocus, focusCtx, layoutCtx, offset, viewportHeight, setOffset]);\n\n // Check if this ScrollView contains the currently focused element (or is itself focused)\n const containsFocus = useCallback((): boolean => {\n if (!focusCtx) return false;\n const currentFocusId = focusCtx.focusedId;\n if (!currentFocusId) return false;\n\n // Check if ScrollView itself is focused\n if (focusable && focusId && currentFocusId === focusId) return true;\n\n // Walk the content tree to find if focused element is inside\n if (!contentRef.current) return false;\n const findNode = (node: GlyphNode): boolean => {\n if (node.focusId === currentFocusId) return true;\n for (const child of node.children) {\n if (findNode(child)) return true;\n }\n return false;\n };\n\n return findNode(contentRef.current);\n }, [focusCtx, focusable, focusId]);\n\n useInput((key: Key) => {\n if (disableKeyboard) return;\n\n // Only respond to scroll keys if this ScrollView contains focus\n // This prevents multiple ScrollViews from all scrolling at once\n if (!containsFocus()) return;\n\n const halfPage = Math.max(1, Math.floor(viewportHeight / 2));\n const fullPage = Math.max(1, viewportHeight);\n\n // Check if a text input is likely focused (skip conflicting vim keys)\n // We use Page Up/Down which never conflict with text inputs\n \n switch (key.name) {\n // Page keys - always safe, inputs don't use these\n case \"pageup\":\n setOffset(offset - fullPage);\n break;\n case \"pagedown\":\n setOffset(offset + fullPage);\n break;\n default:\n // Ctrl combinations that don't conflict with input editing\n if (key.ctrl) {\n if (key.name === \"d\") {\n // Ctrl+D - half page down\n setOffset(offset + halfPage);\n } else if (key.name === \"u\") {\n // Ctrl+U - half page up\n setOffset(offset - halfPage);\n } else if (key.name === \"f\") {\n // Ctrl+F - full page down\n setOffset(offset + fullPage);\n } else if (key.name === \"b\") {\n // Ctrl+B - full page up\n setOffset(offset - fullPage);\n }\n }\n break;\n }\n }, [offset, scrollStep, viewportHeight, maxOffset, disableKeyboard, setOffset, containsFocus]);\n\n // Extract padding from the user style — it must live on the inner content\n // wrapper, not the outer viewport. The clip region is the outer box's\n // *content area* (after border + padding). The inner absolute child is\n // positioned relative to the *padding box* (after border only). If padding\n // stays on the outer box, the first columns/rows of content fall outside the\n // clip and get cut off.\n const {\n padding: _pad,\n paddingX: _px,\n paddingY: _py,\n paddingTop: _pt,\n paddingRight: _pr,\n paddingBottom: _pb,\n paddingLeft: _pl,\n ...styleRest\n } = style ?? {};\n\n // Calculate intrinsic height (content + border if any)\n const hasBorder = styleRest.border != null && styleRest.border !== \"none\";\n const borderHeight = hasBorder ? 2 : 0;\n const intrinsicHeight = contentHeight > 0 ? contentHeight + borderHeight : undefined;\n \n // Outer viewport style:\n // - If no explicit height set by user, use content height as intrinsic size\n // - flexShrink: 1 allows shrinking when parent constrains (e.g., maxHeight)\n // - minHeight: 0 allows shrinking to any size\n // - clip: true enables content clipping for scrolling\n const outerStyle: Style = {\n ...styleRest,\n ...(isSelfFocused ? focusedStyle : {}),\n clip: true,\n // Only set intrinsic height if user didn't set explicit height\n ...(styleRest.height === undefined && intrinsicHeight !== undefined\n ? {\n height: intrinsicHeight,\n flexShrink: styleRest.flexShrink ?? 1,\n minHeight: styleRest.minHeight ?? 0,\n }\n : {}),\n };\n\n // Inner content: absolutely positioned to fill viewport width,\n // shifted up by scrollOffset. Padding lives here so text is indented\n // without being clipped.\n const innerStyle: Style = {\n position: \"absolute\" as const,\n top: -effectiveOffset,\n left: 0,\n right: 0,\n flexDirection: \"column\" as const,\n ...(_pad !== undefined && { padding: _pad }),\n ...(_px !== undefined && { paddingX: _px }),\n ...(_py !== undefined && { paddingY: _py }),\n ...(_pt !== undefined && { paddingTop: _pt }),\n ...(_pr !== undefined && { paddingRight: _pr }),\n ...(_pb !== undefined && { paddingBottom: _pb }),\n ...(_pl !== undefined && { paddingLeft: _pl }),\n };\n\n // Calculate scrollbar dimensions\n const isScrollable = contentHeight > viewportHeight && viewportHeight > 0;\n const scrollbarVisible = showScrollbar && isScrollable;\n \n // Scrollbar thumb size and position\n const thumbHeight = Math.max(1, Math.floor((viewportHeight / contentHeight) * viewportHeight));\n const scrollableRange = contentHeight - viewportHeight;\n const thumbPosition = scrollableRange > 0 \n ? Math.floor((effectiveOffset / scrollableRange) * (viewportHeight - thumbHeight))\n : 0;\n\n // Build scrollbar characters\n const scrollbarChars: string[] = [];\n if (scrollbarVisible) {\n for (let i = 0; i < viewportHeight; i++) {\n if (i >= thumbPosition && i < thumbPosition + thumbHeight) {\n scrollbarChars.push(\"█\");\n } else {\n scrollbarChars.push(\"░\");\n }\n }\n }\n\n // Scrollbar style - positioned on the right edge\n const scrollbarStyle: Style = {\n position: \"absolute\" as const,\n top: 0,\n right: 0,\n width: 1,\n height: viewportHeight,\n flexDirection: \"column\" as const,\n };\n\n return React.createElement(\n ScrollViewContext.Provider,\n { value: scrollViewContextValue },\n React.createElement(\n \"box\" as any,\n {\n style: outerStyle,\n ref: (node: any) => {\n viewportRef.current = node ?? null;\n },\n ...(focusable ? { focusable: true, focusId } : {}),\n },\n // Content (absolutely positioned, scrolls via top offset)\n React.createElement(\n \"box\" as any,\n {\n style: {\n ...innerStyle,\n // Reserve space for scrollbar when visible\n paddingRight: scrollbarVisible ? (innerStyle.paddingRight ?? 0) + 1 : innerStyle.paddingRight,\n },\n ref: (node: any) => {\n contentRef.current = node ?? null;\n },\n },\n children,\n ),\n // Scrollbar\n scrollbarVisible && React.createElement(\n \"box\" as any,\n { style: scrollbarStyle },\n React.createElement(\n \"text\" as any,\n { style: { color: \"blackBright\" as const } },\n scrollbarChars.join(\"\\n\"),\n ),\n ),\n ),\n );\n}\n","import React, { useContext, useEffect, useRef, useState, useCallback } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { FocusContext, InputContext } from \"../hooks/context.js\";\n\nexport interface ListItemInfo {\n index: number;\n selected: boolean;\n focused: boolean;\n}\n\nexport interface ListProps {\n /** Total number of items */\n count: number;\n /** Render function for each item */\n renderItem: (info: ListItemInfo) => ReactNode;\n /** Controlled selected index */\n selectedIndex?: number;\n /** Callback when selected index should change */\n onSelectionChange?: (index: number) => void;\n /** Callback when enter is pressed on selected item */\n onSelect?: (index: number) => void;\n /** Initial index for uncontrolled mode */\n defaultSelectedIndex?: number;\n /** Set of disabled indices that are skipped during navigation */\n disabledIndices?: Set<number>;\n /** Outer box style */\n style?: Style;\n /** Whether the list is focusable (default: true) */\n focusable?: boolean;\n}\n\nexport function List({\n count,\n renderItem,\n selectedIndex: controlledIndex,\n onSelectionChange,\n onSelect,\n defaultSelectedIndex = 0,\n disabledIndices,\n style,\n focusable = true,\n}: ListProps): React.JSX.Element {\n const isControlled = controlledIndex !== undefined;\n const [internalIndex, setInternalIndex] = useState(defaultSelectedIndex);\n const selectedIndex = isControlled ? controlledIndex : internalIndex;\n\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onSelectRef = useRef(onSelect);\n onSelectRef.current = onSelect;\n\n // Track when node is mounted with a valid focusId\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const lastKeyRef = useRef<string | null>(null);\n\n const setIndex = useCallback(\n (next: number) => {\n const clamped = Math.max(0, Math.min(next, count - 1));\n if (isControlled) {\n onSelectionChange?.(clamped);\n } else {\n setInternalIndex(clamped);\n }\n },\n [isControlled, onSelectionChange, count],\n );\n\n // Find next non-disabled index in given direction\n const findNextEnabled = useCallback(\n (from: number, direction: 1 | -1): number => {\n if (!disabledIndices || disabledIndices.size === 0) {\n return Math.max(0, Math.min(from + direction, count - 1));\n }\n let next = from + direction;\n while (next >= 0 && next < count && disabledIndices.has(next)) {\n next += direction;\n }\n if (next < 0 || next >= count) return from; // stay put\n return next;\n },\n [disabledIndices, count],\n );\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || !focusable) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, focusable, nodeReady]);\n\n // Subscribe to focus changes\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Find first non-disabled index from start or end\n const findFirstEnabled = useCallback(\n (fromEnd: boolean): number => {\n const start = fromEnd ? count - 1 : 0;\n const direction = fromEnd ? -1 : 1;\n let index = start;\n while (index >= 0 && index < count && disabledIndices?.has(index)) {\n index += direction;\n }\n return index >= 0 && index < count ? index : (fromEnd ? count - 1 : 0);\n },\n [disabledIndices, count],\n );\n\n // Handle keyboard when focused\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || !focusable) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n\n // gg - go to top (requires two consecutive 'g' presses)\n if (key.name === \"g\" && !key.ctrl && !key.alt) {\n if (lastKeyRef.current === \"g\") {\n setIndex(findFirstEnabled(false));\n lastKeyRef.current = null;\n return true;\n }\n lastKeyRef.current = \"g\";\n return true;\n }\n\n // G - go to bottom\n if (key.name === \"G\" || (key.name === \"g\" && key.shift)) {\n lastKeyRef.current = null;\n setIndex(findFirstEnabled(true));\n return true;\n }\n\n // Clear lastKey for any other key\n lastKeyRef.current = null;\n\n // Up / k - move up\n if (key.name === \"up\" || key.name === \"k\") {\n setIndex(findNextEnabled(selectedIndex, -1));\n return true;\n }\n\n // Down / j - move down\n if (key.name === \"down\" || key.name === \"j\") {\n setIndex(findNextEnabled(selectedIndex, 1));\n return true;\n }\n\n // Enter - select\n if (key.name === \"return\") {\n if (!(disabledIndices?.has(selectedIndex))) {\n onSelectRef.current?.(selectedIndex);\n }\n return true;\n }\n\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, focusable, selectedIndex, setIndex, findNextEnabled, findFirstEnabled, disabledIndices, nodeReady]);\n\n // Render items\n const items: ReactNode[] = [];\n for (let i = 0; i < count; i++) {\n items.push(\n React.createElement(React.Fragment, { key: i },\n renderItem({ index: i, selected: i === selectedIndex, focused: isFocused }),\n ),\n );\n }\n\n return React.createElement(\n \"box\" as any,\n {\n style: { flexDirection: \"column\" as const, ...style },\n focusable: focusable,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n ...items,\n );\n}\n","import React from \"react\";\nimport type { Style, Color } from \"../types/index.js\";\nimport { List } from \"./List.js\";\n\nexport interface MenuItem {\n label: string;\n value: string;\n disabled?: boolean;\n}\n\nexport interface MenuProps {\n items: MenuItem[];\n /** Controlled selected index */\n selectedIndex?: number;\n /** Callback when selected index changes */\n onSelectionChange?: (index: number) => void;\n /** Callback when enter is pressed on item */\n onSelect?: (value: string, index: number) => void;\n /** Initial index for uncontrolled mode */\n defaultSelectedIndex?: number;\n /** Outer box style */\n style?: Style;\n /** Color for the selected item indicator and text (default: \"cyan\") */\n highlightColor?: Color;\n /** Whether the menu is focusable (default: true) */\n focusable?: boolean;\n}\n\nexport function Menu({\n items,\n selectedIndex,\n onSelectionChange,\n onSelect,\n defaultSelectedIndex = 0,\n style,\n highlightColor = \"cyan\",\n focusable = true,\n}: MenuProps): React.JSX.Element {\n const disabledIndices = new Set<number>();\n for (let i = 0; i < items.length; i++) {\n if (items[i]!.disabled) disabledIndices.add(i);\n }\n\n const handleSelect = (index: number) => {\n const item = items[index];\n if (item && !item.disabled) {\n onSelect?.(item.value, index);\n }\n };\n\n return React.createElement(List, {\n count: items.length,\n selectedIndex,\n onSelectionChange,\n onSelect: handleSelect,\n defaultSelectedIndex,\n disabledIndices: disabledIndices.size > 0 ? disabledIndices : undefined,\n style,\n focusable,\n renderItem: ({ index, selected, focused }) => {\n const item = items[index]!;\n const isDisabled = item.disabled;\n const isHighlighted = selected && focused;\n\n const indicator = selected ? \">\" : \" \";\n\n return React.createElement(\n \"box\" as any,\n {\n style: {\n flexDirection: \"row\" as const,\n ...(isHighlighted ? { bg: highlightColor } : {}),\n },\n },\n React.createElement(\n \"text\" as any,\n {\n style: isHighlighted\n ? { bold: true, color: \"black\" }\n : isDisabled\n ? { dim: true }\n : {},\n },\n `${indicator} ${item.label}`,\n ),\n );\n },\n });\n}\n","import React, { useRef, useState, useEffect } from \"react\";\nimport type { Style, DimensionValue } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { useLayout } from \"../hooks/useLayout.js\";\n\nexport interface ProgressProps {\n /** Progress value 0..1. Omit when indeterminate. */\n value?: number;\n /** Animate as indeterminate (marquee). Default false. */\n indeterminate?: boolean;\n /** Width of the progress bar. Default \"100%\". */\n width?: DimensionValue;\n /** Optional label text displayed before the bar. */\n label?: string;\n /** Show percentage text after the bar. Default false. */\n showPercent?: boolean;\n /** Outer container style. */\n style?: Style;\n /** Character(s) for the filled portion. Default \"█\". */\n filled?: string;\n /** Character(s) for the empty portion. Default \"░\". */\n empty?: string;\n}\n\nexport function Progress({\n value,\n indeterminate = false,\n width = \"100%\",\n label,\n showPercent = false,\n style,\n filled = \"█\",\n empty = \"░\",\n}: ProgressProps): React.JSX.Element {\n const trackRef = useRef<GlyphNode | null>(null);\n const trackLayout = useLayout(trackRef);\n const trackWidth = trackLayout.innerWidth;\n\n // Indeterminate animation state\n const [indeterminatePos, setIndeterminatePos] = useState(0);\n\n useEffect(() => {\n if (!indeterminate) return;\n const timer = setInterval(() => {\n setIndeterminatePos((p) => (p + 1) % Math.max(1, trackWidth + 6));\n }, 100);\n return () => clearInterval(timer);\n }, [indeterminate, trackWidth]);\n\n const clamped = Math.max(0, Math.min(1, value ?? 0));\n const pctText = showPercent ? ` ${Math.round(clamped * 100)}%` : \"\";\n\n let barText = \"\";\n if (trackWidth > 0) {\n if (indeterminate && value === undefined) {\n // Marquee: a 3-char chunk bouncing across the track\n const chunkSize = Math.max(1, Math.min(3, Math.floor(trackWidth / 4)));\n const chars: string[] = [];\n for (let i = 0; i < trackWidth; i++) {\n if (i >= indeterminatePos - chunkSize && i < indeterminatePos) {\n chars.push(filled);\n } else {\n chars.push(empty);\n }\n }\n barText = chars.join(\"\");\n } else {\n const filledCount = Math.round(clamped * trackWidth);\n barText = filled.repeat(filledCount) + empty.repeat(trackWidth - filledCount);\n }\n }\n\n const children: React.ReactNode[] = [];\n\n if (label) {\n children.push(\n React.createElement(\"text\" as any, { key: \"label\", style: { bold: true } }, label + \" \"),\n );\n }\n\n children.push(\n React.createElement(\n \"box\" as any,\n {\n key: \"track\",\n style: { flexGrow: 1, flexShrink: 1 },\n ref: (node: any) => { trackRef.current = node ?? null; },\n },\n React.createElement(\"text\" as any, { key: \"bar\", style: {} }, barText),\n ),\n );\n\n if (showPercent) {\n children.push(\n React.createElement(\"text\" as any, { key: \"pct\", style: { bold: true } }, pctText),\n );\n }\n\n return React.createElement(\n \"box\" as any,\n {\n style: {\n flexDirection: \"row\" as const,\n width,\n ...style,\n },\n },\n ...children,\n );\n}\n","import React, { useState, useEffect } from \"react\";\nimport type { Style } from \"../types/index.js\";\n\nconst BRAILLE_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n\nexport interface SpinnerProps {\n /** Animation frames. Defaults to braille dots. */\n frames?: string[];\n /** Interval between frames in ms. Default 80. */\n intervalMs?: number;\n /** Optional label text next to the spinner. */\n label?: string;\n /** Style applied to the spinner character. */\n style?: Style;\n}\n\nexport function Spinner({\n frames = BRAILLE_FRAMES,\n intervalMs = 80,\n label,\n style,\n}: SpinnerProps): React.JSX.Element {\n const [frameIndex, setFrameIndex] = useState(0);\n\n useEffect(() => {\n const timer = setInterval(() => {\n setFrameIndex((i) => (i + 1) % frames.length);\n }, intervalMs);\n return () => clearInterval(timer);\n }, [frames.length, intervalMs]);\n\n const children: React.ReactNode[] = [\n React.createElement(\"text\" as any, { key: \"frame\", style }, frames[frameIndex]),\n ];\n\n if (label) {\n children.push(\n React.createElement(\"text\" as any, { key: \"label\", style: {} }, \" \" + label),\n );\n }\n\n return React.createElement(\n \"box\" as any,\n { style: { flexDirection: \"row\" as const } },\n ...children,\n );\n}\n","import React, { createContext, useContext, useState, useCallback, useEffect, useRef } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Color } from \"../types/index.js\";\n\n// ---- Types ----\n\nexport type ToastVariant = \"info\" | \"success\" | \"warning\" | \"error\";\n\nexport interface Toast {\n id: string;\n message: string;\n title?: string;\n variant?: ToastVariant;\n durationMs?: number;\n}\n\nexport type ToastPosition = \"top-right\" | \"top-left\" | \"bottom-right\" | \"bottom-left\";\n\nexport interface ToastHostProps {\n /** Where toasts appear. Default \"bottom-right\". */\n position?: ToastPosition;\n /** Max visible toasts. Default 5. */\n maxVisible?: number;\n children?: ReactNode;\n}\n\n// ---- Context ----\n\ninterface ToastContextValue {\n push(toast: Omit<Toast, \"id\">): void;\n}\n\nconst ToastContext = createContext<ToastContextValue | null>(null);\n\nlet nextToastId = 0;\n\n// ---- Hook ----\n\nexport function useToast(): (toast: Omit<Toast, \"id\">) => void {\n const ctx = useContext(ToastContext);\n if (!ctx) throw new Error(\"useToast must be used within a <ToastHost>\");\n return ctx.push;\n}\n\n// ---- Variant colors ----\n\nconst VARIANT_COLORS: Record<ToastVariant, { bg: Color; title: Color; text: Color }> = {\n info: { bg: \"blackBright\", title: \"cyanBright\", text: \"white\" },\n success: { bg: \"blackBright\", title: \"greenBright\", text: \"white\" },\n warning: { bg: \"blackBright\", title: \"yellowBright\", text: \"white\" },\n error: { bg: \"blackBright\", title: \"redBright\", text: \"white\" },\n};\n\n// ---- ToastHost ----\n\nexport function ToastHost({\n position = \"bottom-right\",\n maxVisible = 5,\n children,\n}: ToastHostProps): React.JSX.Element {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());\n\n const push = useCallback((toast: Omit<Toast, \"id\">) => {\n const id = `toast-${nextToastId++}`;\n const full: Toast = { id, durationMs: 3000, variant: \"info\", ...toast };\n setToasts((prev) => [...prev, full]);\n\n if (full.durationMs && full.durationMs > 0) {\n const timer = setTimeout(() => {\n timersRef.current.delete(id);\n setToasts((prev) => prev.filter((t) => t.id !== id));\n }, full.durationMs);\n timersRef.current.set(id, timer);\n }\n }, []);\n\n // Cleanup all timers on unmount\n useEffect(() => {\n return () => {\n for (const timer of timersRef.current.values()) {\n clearTimeout(timer);\n }\n timersRef.current.clear();\n };\n }, []);\n\n const ctxValue = useRef({ push });\n ctxValue.current.push = push;\n\n // Position styles\n const isTop = position.startsWith(\"top\");\n const isRight = position.endsWith(\"right\");\n\n const portalStyle: Style = {\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n height: \"100%\",\n zIndex: 900,\n flexDirection: \"column\",\n justifyContent: isTop ? \"flex-start\" : \"flex-end\",\n alignItems: isRight ? \"flex-end\" : \"flex-start\",\n padding: 1,\n };\n\n const visible = toasts.slice(-maxVisible);\n\n const toastElements = visible.map((toast) => {\n const variant = toast.variant ?? \"info\";\n const colors = VARIANT_COLORS[variant];\n\n const innerChildren: ReactNode[] = [];\n\n if (toast.title) {\n innerChildren.push(\n React.createElement(\"text\" as any, {\n key: \"title\",\n style: { bold: true, color: colors.title },\n }, toast.title),\n );\n }\n\n innerChildren.push(\n React.createElement(\"text\" as any, {\n key: \"msg\",\n style: { color: colors.text },\n }, toast.message),\n );\n\n return React.createElement(\n \"box\" as any,\n {\n key: toast.id,\n style: {\n bg: colors.bg,\n paddingX: 1,\n flexDirection: \"column\" as const,\n minWidth: 20,\n maxWidth: 50,\n },\n },\n ...innerChildren,\n );\n });\n\n return React.createElement(\n ToastContext.Provider,\n { value: ctxValue.current },\n children,\n toastElements.length > 0\n ? React.createElement(\"box\" as any, { style: portalStyle }, ...toastElements)\n : null,\n );\n}\n","import React, {\n useContext,\n useEffect,\n useRef,\n useState,\n useCallback,\n useMemo,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key, Color } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { FocusContext, InputContext, AppContext, ScrollViewContext } from \"../hooks/context.js\";\nimport { useLayout } from \"../hooks/useLayout.js\";\n\nexport interface SelectItem {\n label: string;\n value: string;\n disabled?: boolean;\n}\n\nexport interface SelectProps {\n /** List of selectable items */\n items: SelectItem[];\n /** Currently selected value (controlled) */\n value?: string;\n /** Callback when selection changes */\n onChange?: (value: string) => void;\n /** Placeholder text when nothing is selected */\n placeholder?: string;\n /** Trigger box style */\n style?: Style;\n /** Trigger style when focused */\n focusedStyle?: Style;\n /** Dropdown overlay style overrides */\n dropdownStyle?: Style;\n /** Highlight color for the selected item in the dropdown (default: \"cyan\") */\n highlightColor?: Color;\n /** Max visible items in the dropdown before scrolling (default: 8) */\n maxVisible?: number;\n /** Enable type-to-filter when dropdown is open (default: true) */\n searchable?: boolean;\n /** Disabled state */\n disabled?: boolean;\n}\n\nexport function Select({\n items,\n value,\n onChange,\n placeholder = \"Select...\",\n style,\n focusedStyle,\n dropdownStyle,\n highlightColor = \"cyan\",\n maxVisible = 8,\n searchable = true,\n disabled,\n}: SelectProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const appCtx = useContext(AppContext);\n const scrollViewCtx = useContext(ScrollViewContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n\n // Track when node is mounted with a valid focusId - this triggers effect re-runs\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [isOpen, setIsOpen] = useState(false);\n const [highlightIndex, setHighlightIndex] = useState(0);\n const [searchText, setSearchText] = useState(\"\");\n const [scrollOffset, setScrollOffset] = useState(0);\n\n const triggerLayout = useLayout(nodeRef);\n const screenRows = appCtx?.rows ?? 24;\n \n // Get ScrollView bounds if we're inside one\n const scrollViewBounds = scrollViewCtx?.getBounds();\n\n // Selected item label\n const selectedItem = items.find((item) => item.value === value);\n const selectedLabel = selectedItem?.label ?? \"\";\n\n // Filter items based on search\n const filteredItems = useMemo(() => {\n if (!searchText) return items;\n const lower = searchText.toLowerCase();\n return items.filter((item) => item.label.toLowerCase().includes(lower));\n }, [items, searchText]);\n\n // Visible slice\n const visibleCount = Math.min(maxVisible, filteredItems.length);\n const visibleItems = filteredItems.slice(\n scrollOffset,\n scrollOffset + visibleCount,\n );\n\n // Reset highlight and scroll when filter changes\n useEffect(() => {\n setHighlightIndex(0);\n setScrollOffset(0);\n }, [searchText]);\n\n // Close dropdown when focus is lost\n useEffect(() => {\n if (!isFocused && isOpen) {\n setIsOpen(false);\n setSearchText(\"\");\n }\n }, [isFocused, isOpen]);\n\n // --- Focus registration ---\n // Always register on mount to maintain position in tab order\n // nodeReady triggers re-run when ref callback fires\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, nodeReady]);\n \n // Mark as skippable when disabled - Tab will skip this element\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n focusCtx.setSkippable(focusIdRef.current, !!disabled);\n }, [focusCtx, disabled, nodeReady]);\n\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Find next non-disabled index\n const findNextEnabled = useCallback(\n (from: number, direction: 1 | -1): number => {\n let next = from + direction;\n while (next >= 0 && next < filteredItems.length) {\n if (!filteredItems[next]!.disabled) return next;\n next += direction;\n }\n return from;\n },\n [filteredItems],\n );\n\n // Scroll to keep highlight visible\n const ensureVisible = useCallback(\n (index: number) => {\n if (index < scrollOffset) {\n setScrollOffset(index);\n } else if (index >= scrollOffset + visibleCount) {\n setScrollOffset(index - visibleCount + 1);\n }\n },\n [scrollOffset, visibleCount],\n );\n\n // --- Input handler ---\n // nodeReady ensures we re-run when the ref is set after conditional mount\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n\n // --- Closed state ---\n if (!isOpen) {\n if (\n key.name === \"return\" ||\n key.name === \" \" ||\n key.sequence === \" \" ||\n key.name === \"down\"\n ) {\n setIsOpen(true);\n setSearchText(\"\");\n const idx = filteredItems.findIndex((item) => item.value === value);\n const start = idx >= 0 ? idx : 0;\n setHighlightIndex(start);\n setScrollOffset(\n Math.max(0, start - Math.floor(maxVisible / 2)),\n );\n return true;\n }\n return false;\n }\n\n // --- Open state ---\n\n // Tab: close and let focus system handle\n if (key.name === \"tab\") {\n setIsOpen(false);\n setSearchText(\"\");\n return false;\n }\n\n if (key.name === \"escape\") {\n setIsOpen(false);\n setSearchText(\"\");\n return true;\n }\n\n if (key.name === \"return\") {\n const item = filteredItems[highlightIndex];\n if (item && !item.disabled) {\n onChangeRef.current?.(item.value);\n setIsOpen(false);\n setSearchText(\"\");\n }\n return true;\n }\n\n if (key.name === \"up\") {\n const next = findNextEnabled(highlightIndex, -1);\n setHighlightIndex(next);\n ensureVisible(next);\n return true;\n }\n\n if (key.name === \"down\") {\n const next = findNextEnabled(highlightIndex, 1);\n setHighlightIndex(next);\n ensureVisible(next);\n return true;\n }\n\n if (key.name === \"backspace\") {\n if (searchable && searchText.length > 0) {\n setSearchText((prev) => prev.slice(0, -1));\n }\n return true;\n }\n\n if (key.name === \"home\") {\n const first = findNextEnabled(-1, 1);\n setHighlightIndex(first);\n ensureVisible(first);\n return true;\n }\n\n if (key.name === \"end\") {\n const last = findNextEnabled(filteredItems.length, -1);\n setHighlightIndex(last);\n ensureVisible(last);\n return true;\n }\n\n // Printable characters → search filter\n if (\n searchable &&\n key.sequence &&\n key.sequence.length === 1 &&\n !key.ctrl &&\n !key.alt\n ) {\n const ch = key.sequence;\n if (ch >= \" \" && ch <= \"~\") {\n setSearchText((prev) => prev + ch);\n return true;\n }\n }\n\n // Consume all other keys when open\n return true;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [\n inputCtx,\n focusCtx,\n disabled,\n isOpen,\n highlightIndex,\n filteredItems,\n value,\n maxVisible,\n searchable,\n searchText,\n findNextEnabled,\n ensureVisible,\n nodeReady,\n ]);\n\n // --- Trigger ---\n // Only apply default border if user hasn't specified bg (flat style) or their own border\n const useDefaultBorder = !style?.bg && style?.border === undefined;\n const triggerStyle: Style = {\n flexDirection: \"row\",\n width: \"100%\",\n ...(useDefaultBorder ? { border: \"single\" } : {}),\n ...style,\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n const labelColor = selectedLabel\n ? style?.color ?? undefined\n : \"blackBright\";\n\n const triggerChildren: ReactNode[] = [\n React.createElement(\n \"text\" as any,\n {\n key: \"label\",\n style: {\n flexGrow: 1,\n flexShrink: 1,\n color: labelColor,\n wrap: \"ellipsis\",\n ...(selectedLabel ? {} : { dim: true }),\n },\n },\n selectedLabel || placeholder,\n ),\n React.createElement(\n \"text\" as any,\n {\n key: \"arrow\",\n style: { flexShrink: 0, color: isFocused ? highlightColor : \"blackBright\" },\n },\n isOpen ? \" ▲\" : \" ▼\",\n ),\n ];\n\n // --- Dropdown ---\n let dropdownElement: ReactNode = null;\n\n if (isOpen) {\n const dropdownChildren: ReactNode[] = [];\n\n // Search indicator\n if (searchable && searchText) {\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n { key: \"search\", style: { paddingX: 1 } },\n React.createElement(\n \"text\" as any,\n { style: { color: \"blackBright\", dim: true } },\n `/${searchText}`,\n ),\n ),\n );\n }\n\n // No results\n if (filteredItems.length === 0) {\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n { key: \"empty\", style: { paddingX: 1 } },\n React.createElement(\n \"text\" as any,\n { style: { dim: true, color: \"blackBright\" } },\n \"No matches\",\n ),\n ),\n );\n }\n\n // Scroll up indicator\n if (scrollOffset > 0) {\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n {\n key: \"scroll-up\",\n style: { justifyContent: \"center\", alignItems: \"center\" },\n },\n React.createElement(\n \"text\" as any,\n { style: { dim: true, color: \"blackBright\" } },\n \"▲\",\n ),\n ),\n );\n }\n\n // Visible items\n visibleItems.forEach((item, vi) => {\n const actualIndex = scrollOffset + vi;\n const isHighlighted = actualIndex === highlightIndex;\n const isDisabled = item.disabled;\n\n const itemStyle: Style = {\n paddingX: 1,\n ...(isHighlighted && !isDisabled ? { bg: highlightColor } : {}),\n };\n\n const textStyle: Style = {\n ...(isHighlighted && !isDisabled\n ? { color: \"black\", bold: true }\n : {}),\n ...(isDisabled ? { dim: true, color: \"blackBright\" } : {}),\n };\n\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n { key: `item-${item.value}`, style: itemStyle },\n React.createElement(\n \"text\" as any,\n { style: textStyle },\n item.label,\n ),\n ),\n );\n });\n\n // Scroll down indicator\n if (scrollOffset + visibleCount < filteredItems.length) {\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n {\n key: \"scroll-down\",\n style: { justifyContent: \"center\", alignItems: \"center\" },\n },\n React.createElement(\n \"text\" as any,\n { style: { dim: true, color: \"blackBright\" } },\n \"▼\",\n ),\n ),\n );\n }\n\n // Calculate dropdown height (items + border + scroll indicators + search)\n const hasScrollUp = scrollOffset > 0;\n const hasScrollDown = scrollOffset + visibleCount < filteredItems.length;\n const hasSearch = searchable && searchText;\n const hasNoMatches = filteredItems.length === 0;\n \n // Only apply default border if user hasn't specified their own dropdown style\n const useDropdownBorder = !dropdownStyle?.bg && dropdownStyle?.border === undefined;\n const borderSize = useDropdownBorder ? 2 : 0; // top + bottom border\n \n let dropdownHeight = visibleCount + borderSize;\n if (hasScrollUp) dropdownHeight += 1;\n if (hasScrollDown) dropdownHeight += 1;\n if (hasSearch) dropdownHeight += 1;\n if (hasNoMatches) dropdownHeight += 1;\n \n // Determine if we should open upward\n // Consider ScrollView bounds if inside one, otherwise use screen bounds\n const triggerBottom = triggerLayout.y + triggerLayout.height;\n \n let spaceBelow: number;\n let spaceAbove: number;\n \n if (scrollViewBounds) {\n // Inside ScrollView - use ScrollView's visible bounds\n spaceBelow = scrollViewBounds.visibleBottom - triggerBottom;\n spaceAbove = triggerLayout.y - scrollViewBounds.visibleTop;\n } else {\n // Not inside ScrollView - use screen bounds\n spaceBelow = screenRows - triggerBottom;\n spaceAbove = triggerLayout.y;\n }\n \n // Open upward if not enough space below but enough above\n const openUpward = spaceBelow < dropdownHeight && spaceAbove >= dropdownHeight;\n \n const dropdownTop = openUpward \n ? -(dropdownHeight) \n : (triggerLayout.height || 1);\n\n dropdownElement = React.createElement(\n \"box\" as any,\n {\n style: {\n position: \"absolute\" as const,\n top: dropdownTop,\n left: 0,\n right: 0,\n zIndex: 9999,\n ...(useDropdownBorder ? { border: \"single\" as const } : {}),\n bg: \"black\" as const,\n flexDirection: \"column\" as const,\n ...dropdownStyle,\n },\n },\n ...dropdownChildren,\n );\n }\n\n // --- Render ---\n // Extract width/flex properties for outer wrapper\n // Default to filling available space if no explicit width is set\n const outerStyle: Style = {\n flexDirection: \"column\" as const,\n width: triggerStyle.width ?? \"100%\",\n minWidth: triggerStyle.minWidth,\n maxWidth: triggerStyle.maxWidth,\n flexGrow: triggerStyle.flexGrow,\n flexShrink: triggerStyle.flexShrink ?? 1,\n };\n\n return React.createElement(\n \"box\" as any,\n { style: outerStyle },\n // Trigger\n React.createElement(\n \"box\" as any,\n {\n style: triggerStyle,\n // Always focusable - disabled state is handled in input handler\n // This ensures focusId is assigned on mount, even if initially disabled\n focusable: true,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n // Trigger effect re-runs now that refs are set\n setNodeReady(true);\n } else {\n // Node unmounted\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n ...triggerChildren,\n ),\n // Dropdown overlay\n dropdownElement,\n );\n}\n","import React, { useContext, useEffect, useRef, useState } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport { FocusContext, InputContext } from \"../hooks/context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface CheckboxProps {\n /** Whether the checkbox is checked */\n checked: boolean;\n /** Called when the checkbox is toggled */\n onChange: (checked: boolean) => void;\n /** Label text displayed next to the checkbox */\n label?: string;\n /** Style for the checkbox container */\n style?: Style;\n /** Style when focused */\n focusedStyle?: Style;\n /** Whether the checkbox is disabled */\n disabled?: boolean;\n /** Custom character for checked state (default: \"✓\") */\n checkedChar?: string;\n /** Custom character for unchecked state (default: \" \") */\n uncheckedChar?: string;\n}\n\nexport function Checkbox({\n checked,\n onChange,\n label,\n style,\n focusedStyle,\n disabled,\n checkedChar = \"✓\",\n uncheckedChar = \" \",\n}: CheckboxProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n const checkedRef = useRef(checked);\n checkedRef.current = checked;\n\n // Track when node is mounted with a valid focusId\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || disabled) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, disabled, nodeReady]);\n\n // Subscribe to focus changes\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Handle space/enter to toggle\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n if (key.name === \"return\" || key.name === \" \" || key.sequence === \" \") {\n onChangeRef.current(!checkedRef.current);\n return true;\n }\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, disabled, nodeReady]);\n\n const mergedStyle: Style = {\n flexDirection: \"row\",\n gap: 1,\n ...style,\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n const boxChar = checked ? checkedChar : uncheckedChar;\n const boxStyle: Style = {\n color: disabled ? \"blackBright\" : (isFocused ? \"white\" : style?.color),\n };\n const labelStyle: Style = {\n color: disabled ? \"blackBright\" : style?.color,\n };\n\n return React.createElement(\n \"box\" as any,\n {\n style: mergedStyle,\n focusable: !disabled,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n React.createElement(\n \"text\" as any,\n { key: \"box\", style: boxStyle },\n `[${boxChar}]`,\n ),\n label\n ? React.createElement(\n \"text\" as any,\n { key: \"label\", style: labelStyle },\n label,\n )\n : null,\n );\n}\n","import React, { useContext, useEffect, useRef, useState, useCallback } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport { FocusContext, InputContext } from \"../hooks/context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface RadioItem<T = string> {\n /** Display label */\n label: string;\n /** Value returned on selection */\n value: T;\n /** Whether this option is disabled */\n disabled?: boolean;\n}\n\nexport interface RadioProps<T = string> {\n /** Radio options */\n items: RadioItem<T>[];\n /** Currently selected value */\n value: T | undefined;\n /** Called when selection changes */\n onChange: (value: T) => void;\n /** Style for the radio group container */\n style?: Style;\n /** Style for each radio item */\n itemStyle?: Style;\n /** Style for the focused item */\n focusedItemStyle?: Style;\n /** Style for the selected item */\n selectedItemStyle?: Style;\n /** Whether the entire group is disabled */\n disabled?: boolean;\n /** Layout direction (default: \"column\") */\n direction?: \"row\" | \"column\";\n /** Gap between items (default: 0) */\n gap?: number;\n /** Custom character for selected state (default: \"●\") */\n selectedChar?: string;\n /** Custom character for unselected state (default: \"○\") */\n unselectedChar?: string;\n}\n\nexport function Radio<T = string>({\n items,\n value,\n onChange,\n style,\n itemStyle,\n focusedItemStyle,\n selectedItemStyle,\n disabled,\n direction = \"column\",\n gap = 0,\n selectedChar = \"●\",\n unselectedChar = \"○\",\n}: RadioProps<T>): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n\n // Track when node is mounted with a valid focusId\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [highlightedIndex, setHighlightedIndex] = useState(() => {\n // Initialize to the selected item or first enabled item\n const selectedIdx = items.findIndex((item) => item.value === value);\n if (selectedIdx >= 0) return selectedIdx;\n return items.findIndex((item) => !item.disabled);\n });\n\n // Find next/prev enabled item\n const findNextEnabled = useCallback(\n (startIndex: number, direction: 1 | -1): number => {\n let index = startIndex;\n for (let i = 0; i < items.length; i++) {\n index = (index + direction + items.length) % items.length;\n if (!items[index]?.disabled) return index;\n }\n return startIndex;\n },\n [items],\n );\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || disabled) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, disabled, nodeReady]);\n\n // Subscribe to focus changes\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Handle keyboard navigation\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n\n // Previous: up, left, k, shift+tab\n if (\n key.name === \"up\" ||\n key.name === \"left\" ||\n key.name === \"k\" ||\n (key.name === \"tab\" && key.shift)\n ) {\n setHighlightedIndex((idx) => findNextEnabled(idx, -1));\n return true;\n }\n\n // Next: down, right, j, tab\n if (\n key.name === \"down\" ||\n key.name === \"right\" ||\n key.name === \"j\" ||\n (key.name === \"tab\" && !key.shift)\n ) {\n setHighlightedIndex((idx) => findNextEnabled(idx, 1));\n return true;\n }\n\n // Select current item\n if (key.name === \"return\" || key.name === \" \" || key.sequence === \" \") {\n const item = items[highlightedIndex];\n if (item && !item.disabled) {\n onChangeRef.current(item.value);\n }\n return true;\n }\n\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, disabled, items, highlightedIndex, findNextEnabled, nodeReady]);\n\n // Sync highlighted index when value changes externally\n useEffect(() => {\n const selectedIdx = items.findIndex((item) => item.value === value);\n if (selectedIdx >= 0) {\n setHighlightedIndex(selectedIdx);\n }\n }, [value, items]);\n\n const containerStyle: Style = {\n flexDirection: direction,\n gap,\n ...style,\n };\n\n const radioItems = items.map((item, index) => {\n const isSelected = item.value === value;\n const isHighlighted = index === highlightedIndex;\n const isItemDisabled = disabled || item.disabled;\n\n const radioChar = isSelected ? selectedChar : unselectedChar;\n\n let computedStyle: Style = {\n flexDirection: \"row\",\n gap: 1,\n ...itemStyle,\n };\n\n if (isSelected && selectedItemStyle) {\n computedStyle = { ...computedStyle, ...selectedItemStyle };\n }\n\n if (isFocused && isHighlighted && focusedItemStyle) {\n computedStyle = { ...computedStyle, ...focusedItemStyle };\n }\n\n const textColor = isItemDisabled\n ? \"blackBright\"\n : isFocused && isHighlighted\n ? focusedItemStyle?.color ?? \"white\"\n : isSelected\n ? selectedItemStyle?.color ?? itemStyle?.color\n : itemStyle?.color;\n\n return React.createElement(\n \"box\" as any,\n { key: index, style: computedStyle },\n React.createElement(\n \"text\" as any,\n { key: \"radio\", style: { color: textColor } },\n `(${radioChar})`,\n ),\n React.createElement(\n \"text\" as any,\n { key: \"label\", style: { color: textColor } },\n item.label,\n ),\n );\n });\n\n return React.createElement(\n \"box\" as any,\n {\n style: containerStyle,\n focusable: !disabled,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n ...radioItems,\n );\n}\n","import React, { createContext, useContext, useState, useCallback, useEffect, useRef } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style } from \"../types/index.js\";\nimport { FocusContext } from \"../hooks/context.js\";\nimport { useInput } from \"../hooks/useInput.js\";\nimport { FocusScope } from \"./FocusScope.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface AlertOptions {\n /** Text for the OK button (default: \"OK\") */\n okText?: string;\n /** Style for the dialog box */\n style?: Style;\n /** Base style for buttons */\n buttonStyle?: Style;\n /** Style for the OK button (merged with buttonStyle) */\n okButtonStyle?: Style;\n /** Style for focused button state (merged with button styles) */\n focusedButtonStyle?: Style;\n /** Style for the backdrop overlay */\n backdropStyle?: Style;\n}\n\nexport interface ConfirmOptions extends AlertOptions {\n /** Text for the Cancel button (default: \"Cancel\") */\n cancelText?: string;\n /** Style for the Cancel button (merged with buttonStyle) */\n cancelButtonStyle?: Style;\n}\n\nexport interface DialogContextValue {\n /** Show an alert dialog. Returns a promise that resolves when dismissed. */\n alert: (content: ReactNode, options?: AlertOptions) => Promise<void>;\n /** Show a confirm dialog. Returns a promise that resolves to true (OK) or false (Cancel). */\n confirm: (content: ReactNode, options?: ConfirmOptions) => Promise<boolean>;\n}\n\ninterface DialogState {\n id: number;\n type: \"alert\" | \"confirm\";\n content: ReactNode;\n okText: string;\n cancelText: string;\n style?: Style;\n buttonStyle?: Style;\n okButtonStyle?: Style;\n cancelButtonStyle?: Style;\n focusedButtonStyle?: Style;\n backdropStyle?: Style;\n resolve: (value: boolean) => void;\n}\n\n// ─── Context ─────────────────────────────────────────────────────────────────\n\nconst DialogContext = createContext<DialogContextValue | null>(null);\n\n// ─── Hook ────────────────────────────────────────────────────────────────────\n\n/**\n * Hook to show alert and confirm dialogs.\n * Must be used within a DialogHost.\n * \n * @example\n * ```tsx\n * const { alert, confirm } = useDialog();\n * \n * // Alert\n * await alert(\"Something happened!\");\n * \n * // Confirm\n * const ok = await confirm(\"Delete this item?\", {\n * okText: \"Delete\",\n * cancelText: \"Keep\"\n * });\n * ```\n */\nexport function useDialog(): DialogContextValue {\n const ctx = useContext(DialogContext);\n if (!ctx) {\n throw new Error(\"useDialog must be used within a DialogHost\");\n }\n return ctx;\n}\n\n// ─── Dialog Host ─────────────────────────────────────────────────────────────\n\nexport interface DialogHostProps {\n children?: ReactNode;\n}\n\n/**\n * Host component for dialogs. Place this at the root of your app.\n * Provides the useDialog hook to children.\n * \n * @example\n * ```tsx\n * function App() {\n * return (\n * <DialogHost>\n * <MyApp />\n * </DialogHost>\n * );\n * }\n * ```\n */\nexport function DialogHost({ children }: DialogHostProps): React.JSX.Element {\n const [dialogs, setDialogs] = useState<DialogState[]>([]);\n const idCounter = useRef(0);\n\n const alert = useCallback((content: ReactNode, options?: AlertOptions): Promise<void> => {\n return new Promise((resolve) => {\n const id = ++idCounter.current;\n setDialogs((prev) => [\n ...prev,\n {\n id,\n type: \"alert\",\n content,\n okText: options?.okText ?? \"OK\",\n cancelText: \"\",\n style: options?.style,\n buttonStyle: options?.buttonStyle,\n okButtonStyle: options?.okButtonStyle,\n focusedButtonStyle: options?.focusedButtonStyle,\n backdropStyle: options?.backdropStyle,\n resolve: () => resolve(),\n },\n ]);\n });\n }, []);\n\n const confirm = useCallback((content: ReactNode, options?: ConfirmOptions): Promise<boolean> => {\n return new Promise((resolve) => {\n const id = ++idCounter.current;\n setDialogs((prev) => [\n ...prev,\n {\n id,\n type: \"confirm\",\n content,\n okText: options?.okText ?? \"OK\",\n cancelText: options?.cancelText ?? \"Cancel\",\n style: options?.style,\n buttonStyle: options?.buttonStyle,\n okButtonStyle: options?.okButtonStyle,\n cancelButtonStyle: options?.cancelButtonStyle,\n focusedButtonStyle: options?.focusedButtonStyle,\n backdropStyle: options?.backdropStyle,\n resolve,\n },\n ]);\n });\n }, []);\n\n const dismissDialog = useCallback((id: number, result: boolean) => {\n setDialogs((prev) => {\n const dialog = prev.find((d) => d.id === id);\n if (dialog) {\n dialog.resolve(result);\n }\n return prev.filter((d) => d.id !== id);\n });\n }, []);\n\n const contextValue: DialogContextValue = { alert, confirm };\n\n // Only show the topmost dialog\n const activeDialog = dialogs[dialogs.length - 1];\n\n return React.createElement(\n DialogContext.Provider,\n { value: contextValue },\n children,\n activeDialog && React.createElement(DialogOverlay, {\n key: activeDialog.id,\n dialog: activeDialog,\n onDismiss: dismissDialog,\n }),\n );\n}\n\n// ─── Dialog Overlay ──────────────────────────────────────────────────────────\n\ninterface DialogOverlayProps {\n dialog: DialogState;\n onDismiss: (id: number, result: boolean) => void;\n}\n\nfunction DialogOverlay({ dialog, onDismiss }: DialogOverlayProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n \n // Refs to get the actual focusIds from the rendered nodes\n const okButtonRef = useRef<any>(null);\n const cancelButtonRef = useRef<any>(null);\n const okFocusIdRef = useRef<string | null>(null);\n const cancelFocusIdRef = useRef<string | null>(null);\n\n // Track which button is focused\n const [focusedButton, setFocusedButton] = useState<\"ok\" | \"cancel\">(\"ok\");\n \n // Force re-registration when refs are populated\n const [refsReady, setRefsReady] = useState(0);\n\n // Register buttons with focus system\n useEffect(() => {\n if (!focusCtx || refsReady === 0) return;\n \n const cleanups: (() => void)[] = [];\n \n if (okButtonRef.current && okFocusIdRef.current) {\n cleanups.push(focusCtx.register(okFocusIdRef.current, okButtonRef.current));\n }\n if (cancelButtonRef.current && cancelFocusIdRef.current) {\n cleanups.push(focusCtx.register(cancelFocusIdRef.current, cancelButtonRef.current));\n }\n \n // Focus OK button initially\n if (okFocusIdRef.current) {\n focusCtx.requestFocus(okFocusIdRef.current);\n }\n \n return () => cleanups.forEach(fn => fn());\n }, [focusCtx, refsReady]);\n\n // Listen to focus changes to track which button is selected\n useEffect(() => {\n if (!focusCtx) return;\n \n return focusCtx.onFocusChange((id) => {\n if (id === okFocusIdRef.current) {\n setFocusedButton(\"ok\");\n } else if (id === cancelFocusIdRef.current) {\n setFocusedButton(\"cancel\");\n }\n });\n }, [focusCtx]);\n\n // Keyboard handling\n useInput((key) => {\n // Enter or Space to select\n if (key.name === \"return\" || key.name === \"space\") {\n if (dialog.type === \"alert\") {\n onDismiss(dialog.id, true);\n } else {\n // For confirm: OK = true, Cancel = false\n onDismiss(dialog.id, focusedButton === \"ok\");\n }\n return;\n }\n\n // Escape to cancel/dismiss\n if (key.name === \"escape\") {\n onDismiss(dialog.id, false);\n return;\n }\n\n // Arrow keys to switch buttons (Tab is handled by focus system)\n if (dialog.type === \"confirm\" && focusCtx) {\n if (key.name === \"left\" || key.name === \"right\") {\n if (focusedButton === \"ok\" && cancelFocusIdRef.current) {\n focusCtx.requestFocus(cancelFocusIdRef.current);\n } else if (okFocusIdRef.current) {\n focusCtx.requestFocus(okFocusIdRef.current);\n }\n }\n }\n }, [dialog, focusedButton, focusCtx, onDismiss]);\n\n // Calculate dialog dimensions\n const contentIsString = typeof dialog.content === \"string\";\n const contentLength = contentIsString ? (dialog.content as string).length : 0;\n const minWidth = Math.max(20, contentIsString ? Math.min(contentLength + 6, 50) : 30);\n\n // Dialog box style (no absolute positioning - centering wrapper handles it)\n const boxStyle: Style = {\n minWidth,\n maxWidth: 50,\n bg: \"black\",\n border: \"round\",\n borderColor: \"white\",\n padding: 1,\n flexDirection: \"column\",\n gap: 1,\n ...dialog.style,\n };\n\n // Button styles - merge base, specific, and focused styles\n const getButtonStyle = (button: \"ok\" | \"cancel\", isSelected: boolean): Style => {\n const baseStyle: Style = {\n paddingX: 2,\n bg: \"blackBright\",\n color: \"white\",\n };\n \n const defaultFocusedStyle: Style = {\n bg: \"white\",\n color: \"black\",\n bold: true,\n };\n \n const specificStyle = button === \"ok\" \n ? dialog.okButtonStyle \n : dialog.cancelButtonStyle;\n \n return {\n ...baseStyle,\n ...dialog.buttonStyle,\n ...specificStyle,\n ...(isSelected ? { ...defaultFocusedStyle, ...dialog.focusedButtonStyle } : {}),\n };\n };\n \n // Backdrop style\n const backdropStyle: Style = {\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n zIndex: 999,\n ...dialog.backdropStyle,\n };\n\n return React.createElement(\n FocusScope,\n { trap: true },\n // Backdrop\n React.createElement(\"box\" as any, {\n style: backdropStyle,\n }),\n // Centering wrapper\n React.createElement(\n \"box\" as any,\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n justifyContent: \"center\",\n alignItems: \"center\",\n zIndex: 1000,\n },\n },\n // Dialog box\n React.createElement(\n \"box\" as any,\n { style: boxStyle },\n // Content\n React.createElement(\n \"box\" as any,\n { style: { flexDirection: \"column\" } },\n typeof dialog.content === \"string\"\n ? React.createElement(\"text\" as any, null, dialog.content)\n : dialog.content,\n ),\n // Buttons row\n React.createElement(\n \"box\" as any,\n {\n style: {\n flexDirection: \"row\",\n justifyContent: \"flex-end\",\n gap: 1,\n },\n },\n // Cancel button (confirm only)\n dialog.type === \"confirm\" &&\n React.createElement(\n \"box\" as any,\n {\n style: getButtonStyle(\"cancel\", focusedButton === \"cancel\"),\n focusable: true,\n ref: (node: any) => {\n if (node && node.focusId && !cancelFocusIdRef.current) {\n cancelButtonRef.current = node;\n cancelFocusIdRef.current = node.focusId;\n setRefsReady(r => r + 1);\n }\n },\n },\n React.createElement(\"text\" as any, null, dialog.cancelText),\n ),\n // OK button\n React.createElement(\n \"box\" as any,\n {\n style: getButtonStyle(\"ok\", focusedButton === \"ok\"),\n focusable: true,\n ref: (node: any) => {\n if (node && node.focusId && !okFocusIdRef.current) {\n okButtonRef.current = node;\n okFocusIdRef.current = node.focusId;\n setRefsReady(r => r + 1);\n }\n },\n },\n React.createElement(\"text\" as any, null, dialog.okText),\n ),\n ),\n ),\n ),\n );\n}\n","import React, { useState, useEffect, useCallback, useContext, useRef, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Color } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport type { LayoutRect } from \"../types/index.js\";\nimport { InputContext, FocusContext, LayoutContext } from \"../hooks/context.js\";\n\ninterface TrackedElement {\n id: string;\n node: GlyphNode;\n layout: LayoutRect;\n}\n\nexport interface JumpNavProps {\n children?: ReactNode;\n /** Keybind to activate jump mode (default: \"ctrl+o\") */\n activationKey?: string;\n /** Style for the hint labels */\n hintStyle?: Style;\n /** Color for hint background (default: \"yellow\") */\n hintBg?: Color;\n /** Color for hint text (default: \"black\") */\n hintFg?: Color;\n /** Characters to use for hints (default: \"asdfghjklqwertyuiopzxcvbnm\") */\n hintChars?: string;\n /** Whether jump nav is enabled (default: true) */\n enabled?: boolean;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n// Generate hint keys for N elements\nfunction generateHints(count: number, chars: string): string[] {\n const hints: string[] = [];\n const charList = chars.split(\"\");\n \n if (count <= charList.length) {\n // Single character hints\n for (let i = 0; i < count; i++) {\n hints.push(charList[i]!);\n }\n } else {\n // Two character hints for larger lists\n for (let i = 0; i < charList.length && hints.length < count; i++) {\n for (let j = 0; j < charList.length && hints.length < count; j++) {\n hints.push(charList[i]! + charList[j]!);\n }\n }\n }\n \n return hints;\n}\n\n/**\n * JumpNav provides vim-style quick navigation to focusable elements.\n * Press the activation key (default: Ctrl+O) to show hints next to each\n * focusable element, then press the hint key to jump to that element.\n * \n * JumpNav is trap-aware: it automatically only shows hints for elements\n * in the current FocusScope trap (e.g., a modal). You only need ONE JumpNav\n * at the root of your app.\n */\nexport function JumpNav({\n children,\n activationKey = \"ctrl+o\",\n hintStyle,\n hintBg = \"yellow\",\n hintFg = \"black\",\n hintChars = \"asdfghjklqwertyuiopzxcvbnm\",\n enabled = true,\n debug = false,\n}: JumpNavProps): React.JSX.Element {\n const log = debug ? (...args: any[]) => console.error('[JumpNav]', ...args) : () => {};\n \n const [isActive, setIsActive] = useState(false);\n const [inputBuffer, setInputBuffer] = useState(\"\");\n const [elements, setElements] = useState<TrackedElement[]>([]);\n \n const inputCtx = useContext(InputContext);\n const focusCtx = useContext(FocusContext);\n const layoutCtx = useContext(LayoutContext);\n\n // Log mount info\n useEffect(() => {\n log('Mounted, inputCtx:', !!inputCtx, 'focusCtx:', !!focusCtx, 'enabled:', enabled);\n }, []);\n\n // Parse activation key\n const parseKey = useCallback((keyStr: string) => {\n const parts = keyStr.toLowerCase().split(\"+\");\n return {\n ctrl: parts.includes(\"ctrl\"),\n alt: parts.includes(\"alt\"),\n shift: parts.includes(\"shift\"),\n meta: parts.includes(\"meta\"),\n name: parts[parts.length - 1] ?? \"\",\n };\n }, []);\n\n const activationKeyParsed = parseKey(activationKey);\n\n // Refresh elements from the ACTIVE focus scope (trap-aware)\n const refreshElements = useCallback(() => {\n if (!focusCtx?.getActiveElements) {\n log('refreshElements: no getActiveElements');\n return;\n }\n \n const active = focusCtx.getActiveElements();\n log('getActiveElements returned', active.length, 'elements');\n \n const mapped: TrackedElement[] = active.map(({ id, node }) => ({\n id,\n node,\n layout: layoutCtx?.getLayout(node) ?? node.layout,\n }));\n \n // Sort by visual position (top-to-bottom, left-to-right)\n mapped.sort((a, b) => {\n if (a.layout.y !== b.layout.y) {\n return a.layout.y - b.layout.y;\n }\n return a.layout.x - b.layout.x;\n });\n \n setElements(mapped);\n }, [focusCtx, layoutCtx, log]);\n\n // Track previous isActive to detect activation transition\n const wasActiveRef = useRef(false);\n \n // Refresh elements when activated\n useEffect(() => {\n if (isActive && !wasActiveRef.current) {\n log('Activated! Refreshing elements...');\n refreshElements();\n }\n wasActiveRef.current = isActive;\n }, [isActive, refreshElements, log]);\n\n // Filter elements with valid layout (visible and computed)\n const visibleElements = elements.filter(el => \n el.layout.width > 0 && el.layout.height > 0\n );\n const visibleHints = generateHints(visibleElements.length, hintChars);\n\n // Create visible hint -> element mapping\n const visibleHintMap = useMemo(() => {\n const map = new Map<string, string>();\n visibleElements.forEach((el, i) => {\n if (visibleHints[i]) {\n map.set(visibleHints[i]!, el.id);\n }\n });\n return map;\n }, [visibleElements, visibleHints]);\n\n // Handle key input\n useEffect(() => {\n if (!inputCtx || !enabled) {\n log('Not subscribing - inputCtx:', !!inputCtx, 'enabled:', enabled);\n return;\n }\n\n log('Subscribing to priority input, activation key:', activationKey);\n\n const handler = (key: { name?: string; ctrl?: boolean; alt?: boolean; shift?: boolean; meta?: boolean; sequence?: string }) => {\n // Check for activation key\n const nameMatch = key.name === activationKeyParsed.name;\n const ctrlMatch = !!key.ctrl === activationKeyParsed.ctrl;\n const altMatch = !!key.alt === activationKeyParsed.alt;\n const shiftMatch = !!key.shift === activationKeyParsed.shift;\n const metaMatch = !!key.meta === activationKeyParsed.meta;\n \n if (\n !isActive &&\n nameMatch && ctrlMatch && altMatch && shiftMatch && metaMatch\n ) {\n log('Activation key matched! Activating...');\n setIsActive(true);\n setInputBuffer(\"\");\n return true;\n }\n\n // When active, handle hint input\n if (isActive) {\n // Escape to cancel\n if (key.name === \"escape\") {\n log('Escape pressed, deactivating');\n setIsActive(false);\n setInputBuffer(\"\");\n return true;\n }\n\n // Backspace to clear buffer\n if (key.name === \"backspace\") {\n setInputBuffer(\"\");\n return true;\n }\n\n // Letter input\n if (key.sequence && key.sequence.length === 1 && /[a-z]/i.test(key.sequence)) {\n const newBuffer = inputBuffer + key.sequence.toLowerCase();\n log('Buffer:', newBuffer);\n \n // Check for exact match\n const targetId = visibleHintMap.get(newBuffer);\n if (targetId) {\n log('Jumping to', targetId);\n focusCtx?.requestFocus(targetId);\n setIsActive(false);\n setInputBuffer(\"\");\n return true;\n }\n \n // Check if any hint starts with this buffer\n const hasPartialMatch = [...visibleHintMap.keys()].some(h => h.startsWith(newBuffer));\n if (hasPartialMatch) {\n setInputBuffer(newBuffer);\n return true;\n }\n \n // No match - reset\n setInputBuffer(\"\");\n return true;\n }\n\n // Consume all other keys when active\n return true;\n }\n\n return false;\n };\n\n // Use priority handler so we capture keys before focused inputs\n return inputCtx.subscribePriority(handler);\n }, [inputCtx, enabled, isActive, activationKeyParsed, inputBuffer, visibleHintMap, focusCtx, activationKey, log]);\n\n // Render floating hint labels when active - wrapped in Portal to not affect layout\n const hintsOverlay = isActive ? React.createElement(\n \"box\" as any,\n {\n // Portal-like wrapper - fullscreen absolute overlay\n style: {\n position: \"absolute\" as const,\n top: 0,\n left: 0,\n width: \"100%\",\n height: \"100%\",\n zIndex: 99998,\n },\n },\n // Hint labels - floating on top of content\n ...visibleElements.map((el, i) => {\n const hint = visibleHints[i];\n if (!hint) return null;\n \n // Position hint at element's location\n const { x, y } = el.layout;\n \n // Highlight matching prefix\n const isPartialMatch = hint.startsWith(inputBuffer) && inputBuffer.length > 0;\n \n return React.createElement(\n \"box\" as any,\n {\n key: el.id,\n style: {\n position: \"absolute\" as const,\n top: y,\n left: Math.max(0, x - hint.length - 2),\n bg: isPartialMatch ? \"cyan\" : hintBg,\n color: hintFg,\n paddingX: 1,\n zIndex: 99999,\n ...hintStyle,\n },\n },\n React.createElement(\"text\" as any, {\n style: { bold: true, color: hintFg },\n }, hint),\n );\n }),\n // Status bar at bottom\n React.createElement(\n \"box\" as any,\n {\n style: {\n position: \"absolute\" as const,\n bottom: 0,\n left: 0,\n right: 0,\n bg: \"blackBright\" as const,\n paddingX: 1,\n zIndex: 99999,\n },\n },\n React.createElement(\"text\" as any, {\n style: { color: \"white\" as const },\n }, inputBuffer ? `Jump: ${inputBuffer}_` : \"Press a key to jump • ESC to cancel\"),\n ),\n ) : null;\n\n return React.createElement(\n React.Fragment,\n null,\n children,\n hintsOverlay,\n );\n}\n","import { useContext, useEffect, useState, useRef, useMemo } from \"react\";\nimport { FocusContext } from \"./context.js\";\nimport { AppContext } from \"./context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\ninterface UseFocusResult {\n focused: boolean;\n focus(): void;\n}\n\nexport function useFocus(nodeRef?: { current: GlyphNode | null }): UseFocusResult {\n const focusCtx = useContext(FocusContext);\n const [id] = useState(() => `focus-${Math.random().toString(36).slice(2, 9)}`);\n\n const isFocused = focusCtx ? focusCtx.focusedId === id : false;\n\n useEffect(() => {\n if (!focusCtx || !nodeRef?.current) return;\n // Assign the focus ID to the node\n nodeRef.current.focusId = id;\n return focusCtx.register(id, nodeRef.current);\n }, [focusCtx, id, nodeRef]);\n\n const focus = useMemo(() => {\n return () => {\n focusCtx?.requestFocus(id);\n };\n }, [focusCtx, id]);\n\n return { focused: isFocused, focus };\n}\n","import { useContext, useEffect, useRef, useState, useCallback } from \"react\";\nimport { FocusContext, InputContext } from \"./context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport type { Key } from \"../types/index.js\";\n\nexport interface UseFocusableOptions {\n /** Whether the element is currently disabled (skipped in tab order) */\n disabled?: boolean;\n /** Called when the element receives focus */\n onFocus?: () => void;\n /** Called when the element loses focus */\n onBlur?: () => void;\n /**\n * Key handler when focused. Return `true` to consume the key.\n * This runs after priority handlers but before global handlers.\n */\n onKeyPress?: (key: Key) => boolean | void;\n}\n\nexport interface UseFocusableResult {\n /** Ref to attach to your focusable element */\n ref: (node: GlyphNode | null) => void;\n /** Whether this element is currently focused */\n isFocused: boolean;\n /** Programmatically request focus on this element */\n focus: () => void;\n /** The focus ID (useful for conditional logic) */\n focusId: string | null;\n}\n\n/**\n * Hook to make any element focusable with keyboard support.\n * \n * @example\n * ```tsx\n * function CustomPicker({ onSelect }) {\n * const { ref, isFocused, focus } = useFocusable({\n * onKeyPress: (key) => {\n * if (key.name === \"return\") {\n * onSelect();\n * return true;\n * }\n * return false;\n * },\n * });\n * \n * return (\n * <Box\n * ref={ref}\n * focusable\n * style={{ \n * border: \"round\",\n * borderColor: isFocused ? \"cyan\" : \"gray\" \n * }}\n * >\n * <Text>Custom Picker</Text>\n * </Box>\n * );\n * }\n * ```\n */\nexport function useFocusable(options: UseFocusableOptions = {}): UseFocusableResult {\n const { disabled, onFocus, onBlur, onKeyPress } = options;\n \n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n \n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const [isFocused, setIsFocused] = useState(false);\n \n // Keep callbacks in refs to avoid stale closures\n const onFocusRef = useRef(onFocus);\n const onBlurRef = useRef(onBlur);\n const onKeyPressRef = useRef(onKeyPress);\n onFocusRef.current = onFocus;\n onBlurRef.current = onBlur;\n onKeyPressRef.current = onKeyPress;\n \n // Ref callback for the element\n const ref = useCallback((node: GlyphNode | null) => {\n nodeRef.current = node;\n if (node) {\n focusIdRef.current = node.focusId ?? null;\n } else {\n focusIdRef.current = null;\n }\n }, []);\n \n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx]);\n \n // Handle disabled state (mark as skippable in tab order)\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n focusCtx.setSkippable(focusIdRef.current, !!disabled);\n }, [focusCtx, disabled]);\n \n // Subscribe to focus changes\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n \n // Check initial focus state\n const initiallyFocused = focusCtx.focusedId === fid;\n setIsFocused(initiallyFocused);\n \n return focusCtx.onFocusChange((newId) => {\n const nowFocused = newId === fid;\n setIsFocused((wasFocused) => {\n if (nowFocused && !wasFocused) {\n onFocusRef.current?.();\n } else if (!nowFocused && wasFocused) {\n onBlurRef.current?.();\n }\n return nowFocused;\n });\n });\n }, [focusCtx]);\n \n // Register key handler when focused\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n \n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n return onKeyPressRef.current?.(key) === true;\n };\n \n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, disabled]);\n \n // Focus function\n const focus = useCallback(() => {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n }, [focusCtx]);\n \n return {\n ref,\n isFocused,\n focus,\n focusId: focusIdRef.current,\n };\n}\n","import { useContext } from \"react\";\nimport { AppContext } from \"./context.js\";\n\nexport interface UseAppResult {\n exit(code?: number): void;\n columns: number;\n rows: number;\n}\n\nexport function useApp(): UseAppResult {\n const ctx = useContext(AppContext);\n if (!ctx) {\n throw new Error(\"useApp must be used within a Glyph render tree\");\n }\n\n return {\n exit: ctx.exit,\n get columns() {\n return ctx.columns;\n },\n get rows() {\n return ctx.rows;\n },\n };\n}\n","import { useContext, useState, useEffect, useCallback, useRef } from \"react\";\nimport { FocusContext, LayoutContext } from \"./context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport type { LayoutRect } from \"../types/index.js\";\n\nexport interface FocusableElement {\n /** Unique focus ID */\n id: string;\n /** The GlyphNode */\n node: GlyphNode;\n /** Current layout (position, size) */\n layout: LayoutRect;\n /** Node type (box, input, etc.) */\n type: string;\n}\n\nexport interface FocusRegistryValue {\n /** All currently registered focusable elements */\n elements: FocusableElement[];\n /** Currently focused element ID */\n focusedId: string | null;\n /** Request focus on a specific element */\n requestFocus: (id: string) => void;\n /** Move to next focusable element */\n focusNext: () => void;\n /** Move to previous focusable element */\n focusPrev: () => void;\n /** Manually refresh the element list (useful after layout updates) */\n refresh: () => void;\n}\n\n/**\n * Hook to access all registered focusable elements in the current focus context.\n * Useful for building custom navigation UIs like jump-to overlays.\n */\nexport function useFocusRegistry(): FocusRegistryValue | null {\n const focusCtx = useContext(FocusContext);\n const layoutCtx = useContext(LayoutContext);\n const [elements, setElements] = useState<FocusableElement[]>([]);\n const updateRef = useRef<() => void>(() => {});\n\n const updateElements = useCallback(() => {\n if (!focusCtx) return;\n \n // Use getActiveElements to respect current focus trap\n const registered = focusCtx.getActiveElements?.() ?? focusCtx.getRegisteredElements?.() ?? [];\n const mapped: FocusableElement[] = registered.map(({ id, node }) => ({\n id,\n node,\n layout: layoutCtx?.getLayout(node) ?? node.layout,\n type: node.type,\n }));\n \n // Sort by visual position (top-to-bottom, left-to-right)\n mapped.sort((a, b) => {\n if (a.layout.y !== b.layout.y) {\n return a.layout.y - b.layout.y;\n }\n return a.layout.x - b.layout.x;\n });\n \n setElements(mapped);\n }, [focusCtx, layoutCtx]);\n\n // Store the update function in a ref so it can be called externally\n updateRef.current = updateElements;\n\n useEffect(() => {\n if (!focusCtx) return;\n\n updateElements();\n\n // Re-update when focus changes (elements may have been added/removed)\n const unsubscribe = focusCtx.onFocusChange(() => {\n updateElements();\n });\n\n // Also update after a short delay to catch layout computation\n const timer = setTimeout(updateElements, 50);\n\n return () => {\n unsubscribe();\n clearTimeout(timer);\n };\n }, [focusCtx, layoutCtx, updateElements]);\n\n if (!focusCtx) return null;\n\n return {\n elements,\n focusedId: focusCtx.focusedId,\n requestFocus: focusCtx.requestFocus,\n focusNext: focusCtx.focusNext,\n focusPrev: focusCtx.focusPrev,\n refresh: () => updateRef.current(),\n };\n}\n","/**\n * Input mask utilities for Glyph Input component.\n * \n * Mask pattern characters:\n * - `9` - Digit (0-9)\n * - `a` - Letter (a-z, A-Z)\n * - `*` - Alphanumeric (a-z, A-Z, 0-9)\n * - Any other character is treated as a literal (separator)\n * \n * @example\n * ```tsx\n * import { createMask } from \"@nick-skriabin/glyph\";\n * \n * // Phone: (123) 456-7890\n * const phoneMask = createMask(\"(999) 999-9999\");\n * <Input onBeforeChange={phoneMask} />\n * \n * // Date: 12/31/2024\n * const dateMask = createMask(\"99/99/9999\");\n * <Input onBeforeChange={dateMask} />\n * \n * // License plate: ABC-1234\n * const plateMask = createMask(\"aaa-9999\");\n * <Input onBeforeChange={plateMask} />\n * ```\n */\n\nexport interface MaskOptions {\n /** The mask pattern */\n mask: string;\n /** Placeholder character for unfilled positions (default: \"_\") */\n placeholder?: string;\n /** Show placeholder in output (default: false) */\n showPlaceholder?: boolean;\n}\n\ntype MaskChar = {\n type: \"digit\" | \"letter\" | \"alphanumeric\" | \"literal\";\n char: string;\n};\n\nfunction parseMask(mask: string): MaskChar[] {\n const result: MaskChar[] = [];\n for (const char of mask) {\n switch (char) {\n case \"9\":\n result.push({ type: \"digit\", char });\n break;\n case \"a\":\n result.push({ type: \"letter\", char });\n break;\n case \"*\":\n result.push({ type: \"alphanumeric\", char });\n break;\n default:\n result.push({ type: \"literal\", char });\n break;\n }\n }\n return result;\n}\n\nfunction isValidChar(char: string, type: MaskChar[\"type\"]): boolean {\n switch (type) {\n case \"digit\":\n return /\\d/.test(char);\n case \"letter\":\n return /[a-zA-Z]/.test(char);\n case \"alphanumeric\":\n return /[a-zA-Z0-9]/.test(char);\n case \"literal\":\n return true; // Literals are auto-inserted\n }\n}\n\n/**\n * Creates a mask handler for use with Input's onBeforeChange prop.\n * \n * @param maskOrOptions - Mask pattern string or options object\n * @returns onBeforeChange handler function\n */\nexport function createMask(\n maskOrOptions: string | MaskOptions\n): (newValue: string, oldValue: string) => string | false | void {\n const options: MaskOptions = typeof maskOrOptions === \"string\" \n ? { mask: maskOrOptions } \n : maskOrOptions;\n \n const { mask, placeholder = \"_\", showPlaceholder = false } = options;\n const maskChars = parseMask(mask);\n\n return (newValue: string, _oldValue: string): string | false | void => {\n // Extract only valid input characters (strip literals and placeholders)\n const inputChars: string[] = [];\n for (const char of newValue) {\n if (char !== placeholder && !/[\\s\\-\\(\\)\\/\\.\\:]/.test(char) || /[a-zA-Z0-9]/.test(char)) {\n if (/[a-zA-Z0-9]/.test(char)) {\n inputChars.push(char);\n }\n }\n }\n\n // Build masked output\n let result = \"\";\n let inputIndex = 0;\n\n for (const maskChar of maskChars) {\n if (maskChar.type === \"literal\") {\n // Always include literals if we have more input to process\n // or if showPlaceholder is true\n if (inputIndex < inputChars.length || showPlaceholder) {\n result += maskChar.char;\n }\n } else {\n // Input position\n if (inputIndex < inputChars.length) {\n const char = inputChars[inputIndex]!;\n if (isValidChar(char, maskChar.type)) {\n result += char;\n inputIndex++;\n } else {\n // Skip invalid character\n inputIndex++;\n // Try again with next input char\n continue;\n }\n } else if (showPlaceholder) {\n result += placeholder;\n }\n }\n }\n\n return result;\n };\n}\n\n/**\n * Pre-built mask patterns for common use cases.\n */\nexport const masks = {\n /** US Phone: (123) 456-7890 */\n usPhone: createMask(\"(999) 999-9999\"),\n \n /** International Phone: +1 234 567 8900 */\n intlPhone: createMask(\"+9 999 999 9999\"),\n \n /** Date MM/DD/YYYY */\n dateUS: createMask(\"99/99/9999\"),\n \n /** Date DD/MM/YYYY */\n dateEU: createMask(\"99/99/9999\"),\n \n /** Date YYYY-MM-DD */\n dateISO: createMask(\"9999-99-99\"),\n \n /** Time HH:MM */\n time: createMask(\"99:99\"),\n \n /** Time HH:MM:SS */\n timeFull: createMask(\"99:99:99\"),\n \n /** Credit Card: 1234 5678 9012 3456 */\n creditCard: createMask(\"9999 9999 9999 9999\"),\n \n /** SSN: 123-45-6789 */\n ssn: createMask(\"999-99-9999\"),\n \n /** ZIP Code: 12345 */\n zip: createMask(\"99999\"),\n \n /** ZIP+4: 12345-6789 */\n zipPlus4: createMask(\"99999-9999\"),\n \n /** IPv4: 192.168.001.001 */\n ipv4: createMask(\"999.999.999.999\"),\n \n /** MAC Address: AA:BB:CC:DD:EE:FF */\n mac: createMask(\"**:**:**:**:**:**\"),\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/reconciler/nodes.ts","../src/reconciler/hostConfig.ts","../src/reconciler/reconciler.ts","../src/runtime/terminal.ts","../src/runtime/input.ts","../src/paint/color.ts","../src/paint/framebuffer.ts","../src/paint/borders.ts","../src/layout/textMeasure.ts","../src/paint/ansi.ts","../src/paint/painter.ts","../src/paint/diff.ts","../src/layout/yogaLayout.ts","../src/hooks/context.ts","../src/render.ts","../src/components/Box.tsx","../src/components/Text.tsx","../src/components/Input.tsx","../src/components/FocusScope.tsx","../src/components/Spacer.tsx","../src/components/Keybind.tsx","../src/components/Portal.tsx","../src/components/Button.tsx","../src/hooks/useLayout.ts","../src/hooks/useInput.ts","../src/components/ScrollView.tsx","../src/components/List.tsx","../src/components/Menu.tsx","../src/components/Progress.tsx","../src/components/Spinner.tsx","../src/components/Toast.tsx","../src/components/Select.tsx","../src/components/Checkbox.tsx","../src/components/Radio.tsx","../src/components/Dialog.tsx","../src/components/JumpNav.tsx","../src/hooks/useFocus.ts","../src/hooks/useFocusable.ts","../src/hooks/useApp.ts","../src/hooks/useFocusRegistry.ts","../src/utils/mask.ts"],"names":["nextFocusId","generateFocusId","createGlyphNode","type","props","style","appendChild","parent","child","removeChild","idx","insertBefore","beforeChild","getInheritedTextStyle","node","result","current","s","collectTextContent","DefaultEventPriority","hostConfig","_priority","_callback","_type","_props","_instance","methodName","args","_errorPrefix","_rootContainer","_hostContext","_internalHandle","text","parentInstance","textChild","t","parentHostContext","instance","_containerInfo","containerInfo","container","before","textInstance","_oldText","newText","_oldProps","newProps","reconciler","ReactReconciler","Terminal","stdout","stdin","data","x","y","color","str","handler","raw","clean","i","ch","code","match","index","r","g","b","resolve","done","timeout","query","doCleanup","handleSignal","signal","err","getKeyNameFromCode","getTildeKeyName","param","applyModifiers","key","mod","m","parseKeySequence","keys","seq","parseCsiSequence","parseSs3Sequence","letter","start","final","sequence","params","modParts","keyCode","parts","NAMED_FG","NAMED_BG","parseHex","hex","h","colorToFg","colorToBg","NAMED_RGB","NAMED_INDEX","terminalPalette","setTerminalPalette","palette","resolveNamedRgb","name","tp","colorToRgb","c","isLightColor","rgb","colorsEqual","a","getContrastCursorColor","bg","Framebuffer","_Framebuffer","width","height","cell","fg","bold","dim","italic","underline","w","row","col","fb","BORDER_CHARS","getBorderChars","measureText","maxWidth","widthMode","wrapMode","lines","MeasureMode","maxW","line","stringWidth","availWidth","wrappedLines","wrapLines","truncateLine","truncateWithEllipsis","wrapped","wordWrap","char","charWidth","truncated","currentLine","currentWidth","wordBuffer","wordBufferWidth","isEnd","isSpace","cw","ANSI_FG_COLORS","ANSI_BG_COLORS","applySgrParams","parseAnsi","input","segments","currentStyle","currentText","ansiRegex","lastIndex","textBefore","p","remainingText","stripAnsi","paintTree","roots","options","entries","screenClip","root","collectPaintEntries","entry","nodeResult","paintNode","parentClip","parentZ","zIndex","clip","intersectClip","right","bottom","isInClip","innerX","innerY","innerWidth","innerHeight","effectiveBg","borderChars","bc","setClipped","paintText","paintInput","autoContrastFg","explicitColor","inherited","baseFg","textAlign","rawLines","strippedLines","wrappedStripped","lineIdx","origLineIdx","wrappedCount","linesFromThis","wrappedLine","visibleWidth","offsetX","originalLine","subLineIdx","wrappedVersions","charOffset","charEnd","segmentCharIdx","segment","cursorInfo","useNativeCursor","value","placeholder","displayText","isPlaceholder","multiline","autoFg","placeholderFg","textFg","textDim","isFocused","cursorScreenLine","cursorScreenCol","pos","logicalLine","offsetInLogicalLine","runningPos","lineLen","wrappedLinesBefore","wrappedCurrentLine","charsProcessed","subLine","scrollOffset","rowIdx","lineNum","screenRow","cCol","cursorX","cursorY","existing","cursorChar","cursorFg","cursorBg","cursorCol","ESC","CSI","moveCursor","buildSGR","diffFramebuffers","prev","next","fullRedraw","out","lastX","lastY","lastSGR","nc","pc","sgr","FLEX_DIR_MAP","FlexDirection","JUSTIFY_MAP","Justify","ALIGN_MAP","Align","setDimension","setter","setPosition","edge","applyStyleToYogaNode","yogaNode","nodeType","v","Edge","hasBorder","Wrap","Gutter","PositionType","Overflow","buildYogaTree","Yoga","heightMode","collectAllText","extractLayout","parentX","parentY","yn","computedLayout","borderWidth","paddingTop","paddingRight","paddingBottom","paddingLeft","computeLayout","screenWidth","screenHeight","rootYoga","Direction","clearYogaRefs","nodes","InputContext","createContext","FocusContext","LayoutContext","AppContext","ScrollViewContext","render","element","opts","debug","terminal","nativeCursorVisible","scheduleRender","prevFb","currentFb","inputHandlers","priorityHandlers","focusedInputHandlers","inputContextValue","focusId","focusedId","focusRegistry","focusOrder","skippableIds","trapStack","focusChangeHandlers","setFocusedId","id","getActiveFocusableIds","ids","trap","nodeA","nodeB","layoutA","layoutB","focusContextValue","activeIds","nextIdx","prevIdx","skippable","layoutSubscriptions","layoutContextValue","subs","appContextValue","handle","renderScheduled","performRender","cols","rows","notifyLayoutSubscribers","focusedNode","paintResult","output","cursorColor","removeDataListener","consumed","inputHandler","removeResizeListener","handleSigcont","wrappedElement","React","onUncaughtError","error","onCaughtError","onRecoverableError","Box","forwardRef","children","focusable","ref","Text","wrap","mergedStyle","cursorToVisualLine","logicalLines","allVisualLines","logicalOffset","offsetInLogical","charCount","vl","isEndOfLogicalLine","effectiveLen","lastIdx","visualLineToCursor","visualLine","visualCol","offset","targetLine","cursorToLineCol","remaining","last","lineColToCursor","Input","controlledValue","defaultValue","onChange","onKeyPress","onBeforeChange","focusedStyle","autoFocus","internalValue","setInternalValue","useState","cursorPos","setCursorPos","setInnerWidth","setIsFocused","nodeReady","setNodeReady","inputCtx","useContext","focusCtx","layoutCtx","nodeRef","useRef","focusIdRef","isControlled","useEffect","layout","rect","workingValueRef","workingCursorRef","lastSentValueRef","lastSentCursorRef","stateRef","autoFocusedRef","fid","timer","newId","ctrl","cb","onKey","onBefore","ml","val","updateValue","newVal","newCursor","finalVal","finalCursor","updateCursor","lineEnd","info","inputType","isDigit","isDecimal","isMinus","FocusScope","prevFocusRef","scopeIdsRef","useLayoutEffect","cleanup","firstId","Spacer","size","parseKeyDescriptor","descriptor","matchesKey","matcher","Keybind","keypress","onPress","whenFocused","priority","disabled","onPressRef","matcherRef","Portal","Button","DEFAULT_RECT","useLayout","ctx","setLayout","useInput","deps","ScrollView","controlledOffset","onScroll","defaultScrollOffset","scrollStep","disableKeyboard","scrollToFocus","showScrollbar","internalOffset","setInternalOffset","viewportRef","contentRef","viewportLayout","contentLayout","isSelfFocused","viewportHeight","contentHeight","maxOffset","effectiveOffset","scrollViewContextValue","useMemo","viewportY","setOffset","useCallback","clamped","findNode","found","focusedLayout","contentTopY","elementTop","elementBottom","visibleTop","visibleBottom","containsFocus","currentFocusId","halfPage","fullPage","_pad","_px","_py","_pt","_pr","_pb","_pl","styleRest","borderHeight","intrinsicHeight","outerStyle","innerStyle","isScrollable","scrollbarVisible","thumbHeight","scrollableRange","thumbPosition","scrollbarChars","scrollbarStyle","List","count","renderItem","controlledIndex","onSelectionChange","onSelect","defaultSelectedIndex","disabledIndices","internalIndex","setInternalIndex","selectedIndex","onSelectRef","lastKeyRef","setIndex","findNextEnabled","from","direction","findFirstEnabled","fromEnd","items","Menu","highlightColor","handleSelect","item","selected","focused","isDisabled","isHighlighted","indicator","Progress","indeterminate","label","showPercent","filled","empty","trackRef","trackWidth","indeterminatePos","setIndeterminatePos","pctText","barText","chunkSize","chars","filledCount","BRAILLE_FRAMES","Spinner","frames","intervalMs","frameIndex","setFrameIndex","ToastContext","nextToastId","useToast","VARIANT_COLORS","ToastHost","position","maxVisible","toasts","setToasts","timersRef","push","toast","full","ctxValue","isTop","isRight","portalStyle","toastElements","variant","colors","innerChildren","Select","dropdownStyle","searchable","appCtx","scrollViewCtx","onChangeRef","isOpen","setIsOpen","highlightIndex","setHighlightIndex","searchText","setSearchText","setScrollOffset","triggerLayout","screenRows","scrollViewBounds","selectedLabel","filteredItems","lower","visibleCount","visibleItems","ensureVisible","first","triggerStyle","labelColor","triggerChildren","dropdownElement","dropdownChildren","vi","itemStyle","textStyle","hasScrollUp","hasScrollDown","hasSearch","hasNoMatches","useDropdownBorder","dropdownHeight","triggerBottom","spaceBelow","spaceAbove","dropdownTop","Checkbox","checked","checkedChar","uncheckedChar","checkedRef","boxChar","boxStyle","labelStyle","Radio","focusedItemStyle","selectedItemStyle","gap","selectedChar","unselectedChar","highlightedIndex","setHighlightedIndex","selectedIdx","startIndex","containerStyle","radioItems","isSelected","isItemDisabled","radioChar","computedStyle","textColor","DialogContext","useDialog","DialogHost","dialogs","setDialogs","idCounter","alert","content","confirm","dismissDialog","dialog","d","contextValue","activeDialog","DialogOverlay","onDismiss","okButtonRef","cancelButtonRef","okFocusIdRef","cancelFocusIdRef","focusedButton","setFocusedButton","refsReady","setRefsReady","cleanups","fn","contentIsString","contentLength","getButtonStyle","button","baseStyle","defaultFocusedStyle","specificStyle","backdropStyle","generateHints","hints","charList","j","JumpNav","activationKey","hintStyle","hintBg","hintFg","hintChars","enabled","log","isActive","setIsActive","inputBuffer","setInputBuffer","elements","setElements","activationKeyParsed","keyStr","refreshElements","active","mapped","wasActiveRef","visibleElements","el","visibleHints","visibleHintMap","map","nameMatch","ctrlMatch","altMatch","shiftMatch","metaMatch","newBuffer","targetId","hintsOverlay","hint","isPartialMatch","useFocus","focus","useFocusable","onFocus","onBlur","onFocusRef","onBlurRef","onKeyPressRef","initiallyFocused","nowFocused","wasFocused","useApp","useFocusRegistry","updateRef","updateElements","unsubscribe","parseMask","mask","isValidChar","createMask","maskOrOptions","showPlaceholder","maskChars","newValue","_oldValue","inputChars","inputIndex","maskChar","masks"],"mappings":"6SA+BA,IAAIA,EAAAA,CAAc,CAAA,CACX,SAASC,EAAAA,EAA0B,CACxC,OAAO,CAAA,YAAA,EAAeD,IAAa,CAAA,CACrC,CAEO,SAASE,EAAAA,CACdC,CAAAA,CACAC,CAAAA,CACW,CACX,IAAMC,CAAAA,CAASD,CAAAA,CAAM,KAAA,EAAmB,EAAC,CACzC,OAAO,CACL,IAAA,CAAAD,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAU,EAAC,CACX,eAAA,CAAiB,EAAC,CAClB,MAAA,CAAQ,IAAA,CACR,QAAA,CAAU,IAAA,CACV,IAAA,CAAM,IAAA,CACN,MAAA,CAAQ,CAAE,CAAA,CAAG,CAAA,CAAG,CAAA,CAAG,CAAA,CAAG,KAAA,CAAO,CAAA,CAAG,MAAA,CAAQ,CAAA,CAAG,M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AAW,mBAAmB,CACrC","file":"index.js","sourcesContent":["import type { Node as YogaNode } from \"yoga-layout\";\nimport type { Style, LayoutRect, Color } from \"../types/index.js\";\n\nexport type GlyphNodeType = \"box\" | \"text\" | \"input\";\n\nexport interface GlyphNode {\n type: GlyphNodeType;\n props: Record<string, any>;\n style: Style;\n children: GlyphNode[];\n rawTextChildren: GlyphTextInstance[];\n parent: GlyphNode | null;\n yogaNode: YogaNode | null;\n text: string | null;\n layout: LayoutRect;\n focusId: string | null;\n hidden: boolean;\n}\n\nexport interface GlyphTextInstance {\n type: \"raw-text\";\n text: string;\n parent: GlyphNode | null;\n}\n\nexport interface GlyphContainer {\n type: \"root\";\n children: GlyphNode[];\n onCommit: () => void;\n}\n\nlet nextFocusId = 0;\nexport function generateFocusId(): string {\n return `glyph-focus-${nextFocusId++}`;\n}\n\nexport function createGlyphNode(\n type: GlyphNodeType,\n props: Record<string, any>,\n): GlyphNode {\n const style = (props.style as Style) ?? {};\n return {\n type,\n props,\n style,\n children: [],\n rawTextChildren: [],\n parent: null,\n yogaNode: null,\n text: null,\n layout: { x: 0, y: 0, width: 0, height: 0, innerX: 0, innerY: 0, innerWidth: 0, innerHeight: 0 },\n focusId: type === \"input\" ? generateFocusId() : (props.focusable ? generateFocusId() : null),\n hidden: false,\n };\n}\n\nexport function appendChild(parent: GlyphNode, child: GlyphNode): void {\n child.parent = parent;\n parent.children.push(child);\n}\n\nexport function removeChild(parent: GlyphNode, child: GlyphNode): void {\n const idx = parent.children.indexOf(child);\n if (idx !== -1) {\n parent.children.splice(idx, 1);\n child.parent = null;\n }\n}\n\nexport function insertBefore(\n parent: GlyphNode,\n child: GlyphNode,\n beforeChild: GlyphNode,\n): void {\n child.parent = parent;\n const idx = parent.children.indexOf(beforeChild);\n if (idx !== -1) {\n parent.children.splice(idx, 0, child);\n } else {\n parent.children.push(child);\n }\n}\n\nexport function getInheritedTextStyle(node: GlyphNode): {\n color?: Color;\n bg?: Color;\n bold?: boolean;\n dim?: boolean;\n italic?: boolean;\n underline?: boolean;\n} {\n const result: {\n color?: Color;\n bg?: Color;\n bold?: boolean;\n dim?: boolean;\n italic?: boolean;\n underline?: boolean;\n } = {};\n\n let current: GlyphNode | null = node;\n while (current) {\n const s = current.style;\n if (result.color === undefined && s.color !== undefined) result.color = s.color;\n if (result.bg === undefined && s.bg !== undefined) result.bg = s.bg;\n if (result.bold === undefined && s.bold !== undefined) result.bold = s.bold;\n if (result.dim === undefined && s.dim !== undefined) result.dim = s.dim;\n if (result.italic === undefined && s.italic !== undefined) result.italic = s.italic;\n if (result.underline === undefined && s.underline !== undefined) result.underline = s.underline;\n current = current.parent;\n }\n\n return result;\n}\n\nexport function collectTextContent(node: GlyphNode): string {\n if (node.text != null) return node.text;\n let result = \"\";\n for (const child of node.children) {\n result += collectTextContent(child);\n }\n return result;\n}\n","import type {\n GlyphNode,\n GlyphTextInstance,\n GlyphContainer,\n GlyphNodeType,\n} from \"./nodes.js\";\nimport {\n createGlyphNode,\n appendChild as glyphAppendChild,\n removeChild as glyphRemoveChild,\n insertBefore as glyphInsertBefore,\n} from \"./nodes.js\";\nimport type { Style } from \"../types/index.js\";\n\n// react-reconciler/constants\n// We import these at the module level - they're simple numeric values\nconst DefaultEventPriority = 32;\n\ntype Props = Record<string, any>;\n\nexport const hostConfig = {\n supportsMutation: true,\n supportsPersistence: false,\n supportsHydration: false,\n isPrimaryRenderer: true,\n\n // Timeouts\n scheduleTimeout: setTimeout,\n cancelTimeout: clearTimeout,\n noTimeout: -1 as const,\n supportsMicrotasks: true,\n scheduleMicrotask: queueMicrotask,\n\n // Priority & event methods required by react-reconciler v0.31\n getCurrentUpdatePriority: () => DefaultEventPriority,\n setCurrentUpdatePriority: (_priority: number) => {},\n resolveUpdatePriority: () => DefaultEventPriority,\n getCurrentEventPriority: () => DefaultEventPriority,\n resolveEventType: () => null as any,\n resolveEventTimeStamp: () => -1.1,\n shouldAttemptEagerTransition: () => false,\n\n getInstanceFromNode: () => null,\n beforeActiveInstanceBlur: () => {},\n afterActiveInstanceBlur: () => {},\n prepareScopeUpdate: () => {},\n getInstanceFromScope: () => null,\n detachDeletedInstance: () => {},\n\n requestPostPaintCallback: (_callback: any) => {},\n\n // Commit suspension stubs (required by react-reconciler v0.31)\n maySuspendCommit: (_type: string, _props: Props) => false,\n preloadInstance: (_type: string, _props: Props) => true,\n startSuspendingCommit: () => {},\n suspendInstance: (_type: string, _props: Props) => {},\n waitForCommitToBeReady: () => null,\n\n // Transition stubs\n NotPendingTransition: null as any,\n HostTransitionContext: { $$typeof: Symbol.for(\"react.context\"), _currentValue: null as any } as any,\n resetFormInstance: (_instance: any) => {},\n\n // Console binding\n bindToConsole: (methodName: string, args: any[], _errorPrefix: string) => {\n return (Function.prototype.bind as any).call(\n (console as any)[methodName],\n console,\n ...args,\n );\n },\n\n // Resource/singleton stubs\n supportsResources: false,\n isHostHoistableType: (_type: string, _props: Props) => false,\n supportsSingletons: false,\n isHostSingletonType: (_type: string) => false,\n supportsTestSelectors: false,\n\n createInstance(\n type: string,\n props: Props,\n _rootContainer: GlyphContainer,\n _hostContext: null,\n _internalHandle: any,\n ): GlyphNode {\n return createGlyphNode(type as GlyphNodeType, props);\n },\n\n createTextInstance(\n text: string,\n _rootContainer: GlyphContainer,\n _hostContext: null,\n _internalHandle: any,\n ): GlyphTextInstance {\n return { type: \"raw-text\", text, parent: null };\n },\n\n appendInitialChild(\n parentInstance: GlyphNode,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") {\n const textChild = child as GlyphTextInstance;\n textChild.parent = parentInstance;\n parentInstance.rawTextChildren.push(textChild);\n parentInstance.text = parentInstance.rawTextChildren.map((t) => t.text).join(\"\");\n } else {\n glyphAppendChild(parentInstance, child as GlyphNode);\n }\n },\n\n finalizeInitialChildren(\n _instance: GlyphNode,\n _type: string,\n _props: Props,\n _rootContainer: GlyphContainer,\n _hostContext: null,\n ): boolean {\n return false;\n },\n\n shouldSetTextContent(_type: string, _props: Props): boolean {\n return false;\n },\n\n getRootHostContext(_rootContainer: GlyphContainer): Record<string, never> {\n return {};\n },\n\n getChildHostContext(\n parentHostContext: Record<string, never>,\n _type: string,\n _rootContainer: GlyphContainer,\n ): Record<string, never> {\n return parentHostContext;\n },\n\n getPublicInstance(instance: GlyphNode | GlyphTextInstance): GlyphNode | GlyphTextInstance {\n return instance;\n },\n\n prepareForCommit(_containerInfo: GlyphContainer): null {\n return null;\n },\n\n resetAfterCommit(containerInfo: GlyphContainer): void {\n containerInfo.onCommit();\n },\n\n preparePortalMount(): void {},\n\n // Mutation methods\n appendChild(\n parentInstance: GlyphNode,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") {\n const textChild = child as GlyphTextInstance;\n textChild.parent = parentInstance;\n parentInstance.rawTextChildren.push(textChild);\n parentInstance.text = parentInstance.rawTextChildren.map((t) => t.text).join(\"\");\n } else {\n glyphAppendChild(parentInstance, child as GlyphNode);\n }\n },\n\n appendChildToContainer(\n container: GlyphContainer,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") return;\n const node = child as GlyphNode;\n node.parent = null;\n container.children.push(node);\n },\n\n insertBefore(\n parentInstance: GlyphNode,\n child: GlyphNode | GlyphTextInstance,\n beforeChild: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\" || beforeChild.type === \"raw-text\") return;\n glyphInsertBefore(parentInstance, child as GlyphNode, beforeChild as GlyphNode);\n },\n\n insertInContainerBefore(\n container: GlyphContainer,\n child: GlyphNode | GlyphTextInstance,\n beforeChild: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\" || beforeChild.type === \"raw-text\") return;\n const node = child as GlyphNode;\n const before = beforeChild as GlyphNode;\n const idx = container.children.indexOf(before);\n if (idx !== -1) {\n container.children.splice(idx, 0, node);\n } else {\n container.children.push(node);\n }\n },\n\n removeChild(\n parentInstance: GlyphNode,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") {\n const textChild = child as GlyphTextInstance;\n textChild.parent = null;\n const idx = parentInstance.rawTextChildren.indexOf(textChild);\n if (idx !== -1) parentInstance.rawTextChildren.splice(idx, 1);\n parentInstance.text = parentInstance.rawTextChildren.map((t) => t.text).join(\"\") || null;\n return;\n }\n glyphRemoveChild(parentInstance, child as GlyphNode);\n },\n\n removeChildFromContainer(\n container: GlyphContainer,\n child: GlyphNode | GlyphTextInstance,\n ): void {\n if (child.type === \"raw-text\") return;\n const node = child as GlyphNode;\n const idx = container.children.indexOf(node);\n if (idx !== -1) {\n container.children.splice(idx, 1);\n }\n },\n\n commitTextUpdate(\n textInstance: GlyphTextInstance,\n _oldText: string,\n newText: string,\n ): void {\n textInstance.text = newText;\n if (textInstance.parent) {\n // Rebuild parent text from tracked raw text children\n textInstance.parent.text = textInstance.parent.rawTextChildren\n .map((t) => t.text)\n .join(\"\");\n }\n },\n\n // v0.31 signature: (instance, type, oldProps, newProps, internalHandle)\n // updatePayload was removed in this version\n commitUpdate(\n instance: GlyphNode,\n _type: string,\n _oldProps: Props,\n newProps: Props,\n _internalHandle: any,\n ): void {\n instance.props = newProps;\n instance.style = (newProps.style as Style) ?? {};\n if (newProps.focusable && !instance.focusId) {\n instance.focusId = `focus-${Math.random().toString(36).slice(2, 9)}`;\n }\n },\n\n hideInstance(instance: GlyphNode): void {\n instance.hidden = true;\n },\n\n hideTextInstance(textInstance: GlyphTextInstance): void {\n textInstance.text = \"\";\n },\n\n unhideInstance(instance: GlyphNode, _props: Props): void {\n instance.hidden = false;\n },\n\n unhideTextInstance(textInstance: GlyphTextInstance, text: string): void {\n textInstance.text = text;\n },\n\n clearContainer(container: GlyphContainer): void {\n container.children.length = 0;\n },\n\n resetTextContent(instance: GlyphNode): void {\n instance.text = null;\n },\n};\n\n","import ReactReconciler from \"react-reconciler\";\nimport { hostConfig } from \"./hostConfig.js\";\n\n// @ts-expect-error - react-reconciler types don't perfectly match runtime\nconst reconciler = ReactReconciler(hostConfig);\n\nreconciler.injectIntoDevTools({\n bundleType: process.env.NODE_ENV === \"production\" ? 0 : 1,\n version: \"0.1.0\",\n rendererPackageName: \"glyph\",\n});\n\nexport { reconciler };\n","const ESC = \"\\x1b\";\nconst CSI = `${ESC}[`;\n\nexport class Terminal {\n stdout: NodeJS.WriteStream;\n stdin: NodeJS.ReadStream;\n private wasRaw = false;\n private cleanedUp = false;\n\n // Data handler dispatch - single stdin listener, filters OSC, dispatches clean data\n private dataHandlers = new Set<(data: string) => void>();\n private stdinAttached = false;\n\n // OSC response filtering state\n private oscState: \"normal\" | \"esc\" | \"osc\" | \"osc_esc\" = \"normal\";\n private oscAccum = \"\";\n private escFlushTimer: ReturnType<typeof setTimeout> | null = null;\n\n // Terminal palette (populated by queryPalette)\n palette = new Map<number, [number, number, number]>();\n private paletteResolve: (() => void) | null = null;\n\n constructor(\n stdout: NodeJS.WriteStream = process.stdout,\n stdin: NodeJS.ReadStream = process.stdin,\n ) {\n this.stdout = stdout;\n this.stdin = stdin;\n }\n\n get columns(): number {\n return this.stdout.columns || 80;\n }\n\n get rows(): number {\n return this.stdout.rows || 24;\n }\n\n enterRawMode(): void {\n if (this.stdin.isTTY) {\n this.wasRaw = this.stdin.isRaw;\n this.stdin.setRawMode(true);\n this.stdin.resume();\n this.stdin.setEncoding(\"utf-8\");\n }\n }\n\n exitRawMode(): void {\n if (this.stdin.isTTY && !this.wasRaw) {\n this.stdin.setRawMode(false);\n this.stdin.pause();\n }\n }\n\n write(data: string): void {\n this.stdout.write(data);\n }\n\n hideCursor(): void {\n this.write(`${CSI}?25l`);\n }\n\n showCursor(): void {\n this.write(`${CSI}?25h`);\n }\n\n /** Move cursor to (x, y) position (0-indexed) */\n moveCursor(x: number, y: number): void {\n // ANSI uses 1-indexed positions\n this.write(`${CSI}${y + 1};${x + 1}H`);\n }\n\n /** Set cursor color using OSC 12 */\n setCursorColor(color: string): void {\n // OSC 12 sets cursor color, terminated by BEL\n this.write(`${ESC}]12;${color}\\x07`);\n }\n\n /** Reset cursor color to terminal default */\n resetCursorColor(): void {\n // Empty color resets to default\n this.write(`${ESC}]112\\x07`);\n }\n\n enterAltScreen(): void {\n this.write(`${CSI}?1049h`);\n }\n\n exitAltScreen(): void {\n this.write(`${CSI}?1049l`);\n }\n\n clearScreen(): void {\n this.write(`${CSI}2J${CSI}H`);\n }\n\n resetStyles(): void {\n this.write(`${CSI}0m`);\n }\n\n /** Enable kitty keyboard protocol for enhanced key detection */\n enableKittyKeyboard(): void {\n // Push keyboard mode with flags:\n // 1 = Disambiguate escape codes\n // 2 = Report event types\n // 4 = Report alternate keys\n // 8 = Report all keys as escape codes\n // We use 1 (disambiguate) which gives us Ctrl+Enter, etc.\n this.write(`${CSI}>1u`);\n }\n\n /** Disable kitty keyboard protocol */\n disableKittyKeyboard(): void {\n // Pop keyboard mode\n this.write(`${CSI}<u`);\n }\n\n setup(): void {\n this.enterRawMode();\n this.enterAltScreen();\n this.enableKittyKeyboard(); // Enable extended keyboard protocol\n this.hideCursor();\n this.clearScreen();\n this.attachStdinListener();\n this.installCleanupHandlers();\n }\n\n cleanup(): void {\n if (this.cleanedUp) return;\n this.cleanedUp = true;\n\n if (this.escFlushTimer !== null) {\n clearTimeout(this.escFlushTimer);\n this.escFlushTimer = null;\n }\n\n this.resetStyles();\n this.resetCursorColor();\n this.disableKittyKeyboard(); // Restore normal keyboard mode\n this.showCursor();\n this.exitAltScreen();\n this.exitRawMode();\n }\n\n /** Restore terminal state for background suspension (does NOT mark as cleaned up). */\n suspend(): void {\n if (this.escFlushTimer !== null) {\n clearTimeout(this.escFlushTimer);\n this.escFlushTimer = null;\n }\n this.oscState = \"normal\";\n this.oscAccum = \"\";\n\n this.resetStyles();\n this.resetCursorColor();\n this.disableKittyKeyboard();\n this.showCursor();\n this.exitAltScreen();\n this.exitRawMode();\n }\n\n /** Re-enter raw mode and alt screen after SIGCONT resume. */\n resume(): void {\n this.enterRawMode();\n this.enterAltScreen();\n this.enableKittyKeyboard();\n this.hideCursor();\n this.clearScreen();\n }\n\n // ---- Data handling with OSC filtering ----\n\n private attachStdinListener(): void {\n if (this.stdinAttached) return;\n this.stdinAttached = true;\n\n this.stdin.on(\"data\", (data: Buffer | string) => {\n let str = typeof data === \"string\" ? data : data.toString(\"utf-8\");\n this.dispatchFiltered(str);\n });\n }\n\n onData(handler: (data: string) => void): () => void {\n this.dataHandlers.add(handler);\n return () => {\n this.dataHandlers.delete(handler);\n };\n }\n\n // ---- OSC response filtering ----\n\n private dispatchFiltered(raw: string): void {\n // Cancel any pending standalone-ESC flush since more data arrived\n if (this.escFlushTimer !== null) {\n clearTimeout(this.escFlushTimer);\n this.escFlushTimer = null;\n }\n\n const clean = this.filterOsc(raw);\n\n if (clean.length > 0) {\n for (const handler of this.dataHandlers) {\n handler(clean);\n }\n }\n\n // If filterOsc ended in \"esc\" state, a standalone ESC byte is pending.\n // Use a short timeout to disambiguate: if no more data arrives within 50ms,\n // treat it as a standalone Escape keypress and flush it.\n if (this.oscState === \"esc\") {\n this.escFlushTimer = setTimeout(() => {\n this.escFlushTimer = null;\n this.oscState = \"normal\";\n for (const handler of this.dataHandlers) {\n handler(\"\\x1b\");\n }\n }, 50);\n }\n }\n\n private filterOsc(raw: string): string {\n let clean = \"\";\n\n for (let i = 0; i < raw.length; i++) {\n const ch = raw[i]!;\n const code = raw.charCodeAt(i);\n\n switch (this.oscState) {\n case \"normal\":\n if (code === 0x1b) {\n this.oscState = \"esc\";\n } else {\n clean += ch;\n }\n break;\n\n case \"esc\":\n if (ch === \"]\") {\n // Start of OSC sequence\n this.oscState = \"osc\";\n this.oscAccum = \"\";\n } else {\n // Not OSC — pass through the ESC and current char\n clean += \"\\x1b\" + ch;\n this.oscState = \"normal\";\n }\n break;\n\n case \"osc\":\n if (code === 0x07) {\n // BEL terminator\n this.handleOscResponse(this.oscAccum);\n this.oscAccum = \"\";\n this.oscState = \"normal\";\n } else if (code === 0x1b) {\n // Possible ST (ESC \\)\n this.oscState = \"osc_esc\";\n } else {\n this.oscAccum += ch;\n }\n break;\n\n case \"osc_esc\":\n if (ch === \"\\\\\") {\n // ST terminator\n this.handleOscResponse(this.oscAccum);\n this.oscAccum = \"\";\n this.oscState = \"normal\";\n } else {\n // Not ST, accumulate\n this.oscAccum += \"\\x1b\" + ch;\n this.oscState = \"osc\";\n }\n break;\n }\n }\n\n return clean;\n }\n\n private handleOscResponse(data: string): void {\n // Parse OSC 4 response: \"4;{index};rgb:{rrrr}/{gggg}/{bbbb}\"\n const match = data.match(\n /^4;(\\d+);rgb:([0-9a-fA-F]+)\\/([0-9a-fA-F]+)\\/([0-9a-fA-F]+)/,\n );\n if (match) {\n const index = parseInt(match[1]!, 10);\n // Terminal reports 16-bit hex (e.g. \"ffff\"), take high byte for 8-bit\n const r = parseInt(match[2]!.substring(0, 2), 16);\n const g = parseInt(match[3]!.substring(0, 2), 16);\n const b = parseInt(match[4]!.substring(0, 2), 16);\n this.palette.set(index, [r, g, b]);\n if (this.palette.size >= 16 && this.paletteResolve) {\n this.paletteResolve();\n this.paletteResolve = null;\n }\n }\n }\n\n // ---- Palette querying ----\n\n queryPalette(): Promise<Map<number, [number, number, number]>> {\n return new Promise((resolve) => {\n const done = () => resolve(this.palette);\n\n // If terminal doesn't respond, resolve with whatever we have after timeout\n const timeout = setTimeout(done, 200);\n\n this.paletteResolve = () => {\n clearTimeout(timeout);\n done();\n };\n\n // Query colors 0-15 (the 16 standard ANSI colors)\n let query = \"\";\n for (let i = 0; i < 16; i++) {\n query += `\\x1b]4;${i};?\\x07`;\n }\n this.write(query);\n });\n }\n\n // ---- Event handling ----\n\n onResize(handler: () => void): () => void {\n this.stdout.on(\"resize\", handler);\n return () => {\n this.stdout.off(\"resize\", handler);\n };\n }\n\n private installCleanupHandlers(): void {\n const doCleanup = () => this.cleanup();\n\n process.on(\"exit\", doCleanup);\n\n const handleSignal = (signal: NodeJS.Signals) => {\n doCleanup();\n process.kill(process.pid, signal);\n };\n\n process.once(\"SIGINT\", () => handleSignal(\"SIGINT\"));\n process.once(\"SIGTERM\", () => handleSignal(\"SIGTERM\"));\n\n process.on(\"uncaughtException\", (err) => {\n doCleanup();\n console.error(err);\n process.exit(1);\n });\n\n process.on(\"unhandledRejection\", (err) => {\n doCleanup();\n console.error(err);\n process.exit(1);\n });\n }\n}\n","import type { Key } from \"../types/index.js\";\n\n// Map key codes to key names (for kitty protocol and xterm modifyOtherKeys)\nfunction getKeyNameFromCode(code: number): string {\n // Special keys (kitty protocol uses these codes)\n switch (code) {\n // Standard ASCII\n case 9: return \"tab\";\n case 13: return \"return\";\n case 27: return \"escape\";\n case 32: return \" \";\n case 127: return \"backspace\";\n \n // Kitty protocol special keys\n case 57358: return \"capslock\";\n case 57359: return \"scrolllock\";\n case 57360: return \"numlock\";\n case 57361: return \"printscreen\";\n case 57362: return \"pause\";\n case 57363: return \"menu\";\n \n // Function keys (kitty uses these codes)\n case 57364: return \"f13\";\n case 57365: return \"f14\";\n case 57366: return \"f15\";\n case 57367: return \"f16\";\n case 57368: return \"f17\";\n case 57369: return \"f18\";\n case 57370: return \"f19\";\n case 57371: return \"f20\";\n case 57372: return \"f21\";\n case 57373: return \"f22\";\n case 57374: return \"f23\";\n case 57375: return \"f24\";\n case 57376: return \"f25\";\n \n // Keypad keys\n case 57399: return \"kp0\";\n case 57400: return \"kp1\";\n case 57401: return \"kp2\";\n case 57402: return \"kp3\";\n case 57403: return \"kp4\";\n case 57404: return \"kp5\";\n case 57405: return \"kp6\";\n case 57406: return \"kp7\";\n case 57407: return \"kp8\";\n case 57408: return \"kp9\";\n case 57409: return \"kpdecimal\";\n case 57410: return \"kpdivide\";\n case 57411: return \"kpmultiply\";\n case 57412: return \"kpminus\";\n case 57413: return \"kpplus\";\n case 57414: return \"kpenter\";\n case 57415: return \"kpequal\";\n \n // Navigation (kitty protocol)\n case 57416: return \"kpleft\";\n case 57417: return \"kpright\";\n case 57418: return \"kpup\";\n case 57419: return \"kpdown\";\n case 57420: return \"kppageup\";\n case 57421: return \"kppagedown\";\n case 57422: return \"kphome\";\n case 57423: return \"kpend\";\n case 57424: return \"kpinsert\";\n case 57425: return \"kpdelete\";\n \n // Media keys\n case 57428: return \"mediaplaypause\";\n case 57429: return \"mediastop\";\n case 57430: return \"mediaprev\";\n case 57431: return \"medianext\";\n case 57432: return \"mediarewind\";\n case 57433: return \"mediafastforward\";\n case 57434: return \"mediamute\";\n case 57435: return \"volumedown\";\n case 57436: return \"volumeup\";\n \n default:\n // Printable ASCII\n if (code >= 32 && code <= 126) {\n return String.fromCharCode(code).toLowerCase();\n }\n return \"unknown\";\n }\n}\n\n// Map CSI ~ params to key names\nfunction getTildeKeyName(param: string): string {\n // Handle param;modifier format\n const baseParam = param.split(\";\")[0];\n switch (baseParam) {\n case \"1\": return \"home\";\n case \"2\": return \"insert\";\n case \"3\": return \"delete\";\n case \"4\": return \"end\";\n case \"5\": return \"pageup\";\n case \"6\": return \"pagedown\";\n case \"7\": return \"home\";\n case \"8\": return \"end\";\n case \"11\": return \"f1\";\n case \"12\": return \"f2\";\n case \"13\": return \"f3\";\n case \"14\": return \"f4\";\n case \"15\": return \"f5\";\n case \"17\": return \"f6\";\n case \"18\": return \"f7\";\n case \"19\": return \"f8\";\n case \"20\": return \"f9\";\n case \"21\": return \"f10\";\n case \"23\": return \"f11\";\n case \"24\": return \"f12\";\n case \"25\": return \"f13\";\n case \"26\": return \"f14\";\n case \"28\": return \"f15\";\n case \"29\": return \"f16\";\n case \"31\": return \"f17\";\n case \"32\": return \"f18\";\n case \"33\": return \"f19\";\n case \"34\": return \"f20\";\n default: return \"unknown\";\n }\n}\n\n// Parse modifier bits (shared between protocols)\nfunction applyModifiers(key: Key, mod: number): void {\n // mod is 1-indexed in the protocol, so subtract 1\n const m = mod - 1;\n if (m & 1) key.shift = true;\n if (m & 2) key.alt = true;\n if (m & 4) key.ctrl = true;\n if (m & 8) key.meta = true; // Super/Cmd key\n}\n\nexport function parseKeySequence(data: string): Key[] {\n const keys: Key[] = [];\n let i = 0;\n\n while (i < data.length) {\n const ch = data[i]!;\n const code = data.charCodeAt(i);\n\n // ESC sequences\n if (ch === \"\\x1b\") {\n // CSI sequences: ESC [\n if (data[i + 1] === \"[\") {\n const seq = parseCsiSequence(data, i);\n if (seq) {\n keys.push(seq.key);\n i = seq.end;\n continue;\n }\n }\n\n // SS3 sequences: ESC O (function keys on some terminals)\n if (data[i + 1] === \"O\") {\n const seq = parseSs3Sequence(data, i);\n if (seq) {\n keys.push(seq.key);\n i = seq.end;\n continue;\n }\n }\n\n // Alt + char: ESC followed by a printable char\n if (i + 1 < data.length && data.charCodeAt(i + 1) >= 32) {\n keys.push({\n name: data[i + 1]!.toLowerCase(),\n sequence: data.substring(i, i + 2),\n alt: true,\n });\n i += 2;\n continue;\n }\n\n // Standalone ESC\n keys.push({ name: \"escape\", sequence: \"\\x1b\" });\n i++;\n continue;\n }\n\n // Ctrl combos (0x01-0x1a except known special)\n if (code >= 1 && code <= 26) {\n const letter = String.fromCharCode(code + 96); // a-z\n if (code === 13) {\n keys.push({ name: \"return\", sequence: \"\\r\" });\n } else if (code === 9) {\n keys.push({ name: \"tab\", sequence: \"\\t\" });\n } else if (code === 8) {\n keys.push({ name: \"backspace\", sequence: \"\\b\" });\n } else {\n keys.push({ name: letter, sequence: ch, ctrl: true });\n }\n i++;\n continue;\n }\n\n // Backspace / DEL\n if (code === 127) {\n keys.push({ name: \"backspace\", sequence: ch });\n i++;\n continue;\n }\n\n // Printable characters\n keys.push({ name: ch, sequence: ch });\n i++;\n }\n\n return keys;\n}\n\ninterface SeqResult {\n key: Key;\n end: number;\n}\n\n// Parse SS3 sequences (ESC O ...)\nfunction parseSs3Sequence(data: string, start: number): SeqResult | null {\n // start points to ESC, start+1 is O\n if (start + 2 >= data.length) return null;\n \n const final = data[start + 2]!;\n const sequence = data.substring(start, start + 3);\n \n let key: Key;\n \n switch (final) {\n // Arrow keys (some terminals)\n case \"A\": key = { name: \"up\", sequence }; break;\n case \"B\": key = { name: \"down\", sequence }; break;\n case \"C\": key = { name: \"right\", sequence }; break;\n case \"D\": key = { name: \"left\", sequence }; break;\n \n // Home/End (some terminals)\n case \"H\": key = { name: \"home\", sequence }; break;\n case \"F\": key = { name: \"end\", sequence }; break;\n \n // Function keys F1-F4\n case \"P\": key = { name: \"f1\", sequence }; break;\n case \"Q\": key = { name: \"f2\", sequence }; break;\n case \"R\": key = { name: \"f3\", sequence }; break;\n case \"S\": key = { name: \"f4\", sequence }; break;\n \n // Keypad (application mode)\n case \"j\": key = { name: \"kpmultiply\", sequence }; break;\n case \"k\": key = { name: \"kpplus\", sequence }; break;\n case \"l\": key = { name: \"kpcomma\", sequence }; break;\n case \"m\": key = { name: \"kpminus\", sequence }; break;\n case \"n\": key = { name: \"kpdecimal\", sequence }; break;\n case \"o\": key = { name: \"kpdivide\", sequence }; break;\n case \"p\": key = { name: \"kp0\", sequence }; break;\n case \"q\": key = { name: \"kp1\", sequence }; break;\n case \"r\": key = { name: \"kp2\", sequence }; break;\n case \"s\": key = { name: \"kp3\", sequence }; break;\n case \"t\": key = { name: \"kp4\", sequence }; break;\n case \"u\": key = { name: \"kp5\", sequence }; break;\n case \"v\": key = { name: \"kp6\", sequence }; break;\n case \"w\": key = { name: \"kp7\", sequence }; break;\n case \"x\": key = { name: \"kp8\", sequence }; break;\n case \"y\": key = { name: \"kp9\", sequence }; break;\n case \"M\": key = { name: \"kpenter\", sequence }; break;\n \n default:\n return null;\n }\n \n return { key, end: start + 3 };\n}\n\nfunction parseCsiSequence(data: string, start: number): SeqResult | null {\n // start points to ESC, start+1 is [\n let i = start + 2;\n let params = \"\";\n\n while (i < data.length) {\n const code = data.charCodeAt(i);\n // Parameter bytes: 0x30-0x3F (digits, semicolon, etc.)\n if (code >= 0x30 && code <= 0x3f) {\n params += data[i];\n i++;\n } else {\n break;\n }\n }\n\n if (i >= data.length) return null;\n\n const final = data[i]!;\n const sequence = data.substring(start, i + 1);\n i++;\n\n let key: Key;\n\n switch (final) {\n // Arrow keys\n case \"A\":\n key = { name: \"up\", sequence };\n break;\n case \"B\":\n key = { name: \"down\", sequence };\n break;\n case \"C\":\n key = { name: \"right\", sequence };\n break;\n case \"D\":\n key = { name: \"left\", sequence };\n break;\n \n // Home/End\n case \"H\":\n key = { name: \"home\", sequence };\n break;\n case \"F\":\n key = { name: \"end\", sequence };\n break;\n \n // Shift+Tab\n case \"Z\":\n key = { name: \"tab\", sequence, shift: true };\n break;\n \n // Function keys (some terminals)\n case \"P\":\n key = { name: \"f1\", sequence };\n break;\n case \"Q\":\n key = { name: \"f2\", sequence };\n break;\n case \"R\":\n key = { name: \"f3\", sequence };\n break;\n case \"S\":\n key = { name: \"f4\", sequence };\n break;\n \n // ~ terminated sequences (VT-style)\n case \"~\": {\n // Check for xterm modifyOtherKeys format: CSI 27;mod;code ~\n if (params.startsWith(\"27;\")) {\n const modParts = params.split(\";\");\n const mod = parseInt(modParts[1] ?? \"1\", 10);\n const keyCode = parseInt(modParts[2] ?? \"0\", 10);\n key = { name: getKeyNameFromCode(keyCode), sequence };\n applyModifiers(key, mod);\n break;\n }\n \n // Standard ~ sequences with optional modifiers\n key = { name: getTildeKeyName(params), sequence };\n \n // Apply modifiers if present (e.g., 3;5~ for Ctrl+Delete)\n if (params.includes(\";\")) {\n const parts = params.split(\";\");\n const mod = parseInt(parts[1] ?? \"1\", 10);\n applyModifiers(key, mod);\n }\n break;\n }\n \n // Kitty keyboard protocol: CSI code;mod u\n case \"u\": {\n const parts = params.split(\";\");\n const keyCode = parseInt(parts[0] ?? \"0\", 10);\n const mod = parseInt(parts[1] ?? \"1\", 10);\n key = { name: getKeyNameFromCode(keyCode), sequence };\n applyModifiers(key, mod);\n break;\n }\n \n // Focus events (if terminal reports them)\n case \"I\":\n key = { name: \"focus\", sequence };\n break;\n case \"O\":\n key = { name: \"blur\", sequence };\n break;\n \n default:\n key = { name: \"unknown\", sequence };\n }\n\n // Apply modifiers from params for letter-terminated sequences (e.g., 1;2A = shift+up)\n // But skip if we already applied them (like in ~ and u handlers)\n if (params.includes(\";\") && ![\"~\", \"u\"].includes(final)) {\n const parts = params.split(\";\");\n const mod = parseInt(parts[parts.length - 1] ?? \"1\", 10);\n // Only apply if it looks like a modifier (small number)\n if (mod >= 1 && mod <= 16) {\n applyModifiers(key, mod);\n }\n }\n\n return { key, end: i };\n}\n","import type { Color, NamedColor, RGBColor } from \"../types/index.js\";\n\nconst NAMED_FG: Record<NamedColor, string> = {\n black: \"\\x1b[30m\",\n red: \"\\x1b[31m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n blue: \"\\x1b[34m\",\n magenta: \"\\x1b[35m\",\n cyan: \"\\x1b[36m\",\n white: \"\\x1b[37m\",\n blackBright: \"\\x1b[90m\",\n redBright: \"\\x1b[91m\",\n greenBright: \"\\x1b[92m\",\n yellowBright: \"\\x1b[93m\",\n blueBright: \"\\x1b[94m\",\n magentaBright: \"\\x1b[95m\",\n cyanBright: \"\\x1b[96m\",\n whiteBright: \"\\x1b[97m\",\n};\n\nconst NAMED_BG: Record<NamedColor, string> = {\n black: \"\\x1b[40m\",\n red: \"\\x1b[41m\",\n green: \"\\x1b[42m\",\n yellow: \"\\x1b[43m\",\n blue: \"\\x1b[44m\",\n magenta: \"\\x1b[45m\",\n cyan: \"\\x1b[46m\",\n white: \"\\x1b[47m\",\n blackBright: \"\\x1b[100m\",\n redBright: \"\\x1b[101m\",\n greenBright: \"\\x1b[102m\",\n yellowBright: \"\\x1b[103m\",\n blueBright: \"\\x1b[104m\",\n magentaBright: \"\\x1b[105m\",\n cyanBright: \"\\x1b[106m\",\n whiteBright: \"\\x1b[107m\",\n};\n\nfunction parseHex(hex: string): RGBColor {\n const h = hex.replace(\"#\", \"\");\n const r = parseInt(h.substring(0, 2), 16);\n const g = parseInt(h.substring(2, 4), 16);\n const b = parseInt(h.substring(4, 6), 16);\n return { r, g, b };\n}\n\nexport function colorToFg(color: Color): string {\n if (typeof color === \"string\") {\n if (color.startsWith(\"#\")) {\n const { r, g, b } = parseHex(color);\n return `\\x1b[38;2;${r};${g};${b}m`;\n }\n return NAMED_FG[color as NamedColor] ?? \"\\x1b[39m\";\n }\n if (typeof color === \"number\") {\n return `\\x1b[38;5;${color}m`;\n }\n const { r, g, b } = color;\n return `\\x1b[38;2;${r};${g};${b}m`;\n}\n\nexport function colorToFgRaw(color: Color): [number, number, number] | null {\n if (typeof color === \"string\") {\n if (color.startsWith(\"#\")) {\n const c = parseHex(color);\n return [c.r, c.g, c.b];\n }\n return null;\n }\n if (typeof color === \"number\") {\n return null;\n }\n return [color.r, color.g, color.b];\n}\n\nexport function colorToBg(color: Color): string {\n if (typeof color === \"string\") {\n if (color.startsWith(\"#\")) {\n const { r, g, b } = parseHex(color);\n return `\\x1b[48;2;${r};${g};${b}m`;\n }\n return NAMED_BG[color as NamedColor] ?? \"\\x1b[49m\";\n }\n if (typeof color === \"number\") {\n return `\\x1b[48;5;${color}m`;\n }\n const { r, g, b } = color;\n return `\\x1b[48;2;${r};${g};${b}m`;\n}\n\n// Approximate RGB fallbacks for the 16 ANSI colors (used until terminal palette is queried)\nconst NAMED_RGB: Record<NamedColor, [number, number, number]> = {\n black: [0, 0, 0],\n red: [170, 0, 0],\n green: [0, 170, 0],\n yellow: [170, 170, 0],\n blue: [0, 0, 170],\n magenta: [170, 0, 170],\n cyan: [0, 170, 170],\n white: [170, 170, 170],\n blackBright: [85, 85, 85],\n redBright: [255, 85, 85],\n greenBright: [85, 255, 85],\n yellowBright: [255, 255, 85],\n blueBright: [85, 85, 255],\n magentaBright: [255, 85, 255],\n cyanBright: [85, 255, 255],\n whiteBright: [255, 255, 255],\n};\n\nconst NAMED_INDEX: NamedColor[] = [\n \"black\", \"red\", \"green\", \"yellow\", \"blue\", \"magenta\", \"cyan\", \"white\",\n \"blackBright\", \"redBright\", \"greenBright\", \"yellowBright\", \"blueBright\", \"magentaBright\", \"cyanBright\", \"whiteBright\",\n];\n\n// Terminal-reported palette overrides the fallback approximations\nlet terminalPalette: Map<number, [number, number, number]> | null = null;\n\nexport function setTerminalPalette(palette: Map<number, [number, number, number]>): void {\n if (palette.size > 0) {\n terminalPalette = palette;\n }\n}\n\nfunction resolveNamedRgb(name: NamedColor): [number, number, number] | null {\n // Prefer terminal-reported values if available\n if (terminalPalette) {\n const idx = NAMED_INDEX.indexOf(name);\n if (idx !== -1) {\n const tp = terminalPalette.get(idx);\n if (tp) return tp;\n }\n }\n return NAMED_RGB[name] ?? null;\n}\n\nexport function colorToRgb(color: Color): [number, number, number] | null {\n if (typeof color === \"string\") {\n if (color.startsWith(\"#\")) {\n const c = parseHex(color);\n return [c.r, c.g, c.b];\n }\n return resolveNamedRgb(color as NamedColor);\n }\n if (typeof color === \"number\") {\n if (color < 16) {\n // Use terminal palette or fallback\n if (terminalPalette) {\n const tp = terminalPalette.get(color);\n if (tp) return tp;\n }\n return NAMED_RGB[NAMED_INDEX[color]!];\n }\n if (color >= 232) {\n const g = (color - 232) * 10 + 8;\n return [g, g, g];\n }\n // 216-color cube (indices 16-231)\n const idx = color - 16;\n const b = (idx % 6) * 51;\n const g = (Math.floor(idx / 6) % 6) * 51;\n const r = Math.floor(idx / 36) * 51;\n return [r, g, b];\n }\n return [color.r, color.g, color.b];\n}\n\n/** Returns true if the color is perceptually light (should use dark text on it). */\nexport function isLightColor(color: Color): boolean {\n const rgb = colorToRgb(color);\n if (!rgb) return false;\n // W3C relative luminance formula\n const [r, g, b] = rgb.map((c) => {\n const s = c / 255;\n return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);\n });\n const luminance = 0.2126 * r! + 0.7152 * g! + 0.0722 * b!;\n return luminance > 0.4;\n}\n\nexport function colorsEqual(\n a: Color | undefined,\n b: Color | undefined,\n): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a === \"object\" && typeof b === \"object\") {\n return a.r === b.r && a.g === b.g && a.b === b.b;\n }\n return false;\n}\n\n/** Convert Color to a string suitable for OSC sequences (e.g. cursor color) */\nexport function colorToOscString(color: Color): string {\n const rgb = colorToRgb(color);\n if (rgb) {\n const [r, g, b] = rgb;\n // OSC uses \"rgb:RR/GG/BB\" format with hex values\n const rHex = r.toString(16).padStart(2, \"0\");\n const gHex = g.toString(16).padStart(2, \"0\");\n const bHex = b.toString(16).padStart(2, \"0\");\n return `rgb:${rHex}/${gHex}/${bHex}`;\n }\n // Fallback to named color string\n return String(color);\n}\n\n/** Get a contrasting cursor color for a given background */\nexport function getContrastCursorColor(bg: Color | undefined): string {\n if (!bg) return \"white\";\n return isLightColor(bg) ? \"black\" : \"white\";\n}\n","import type { Color } from \"../types/index.js\";\nimport { colorsEqual } from \"./color.js\";\n\nexport interface Cell {\n ch: string;\n fg?: Color;\n bg?: Color;\n bold?: boolean;\n dim?: boolean;\n italic?: boolean;\n underline?: boolean;\n}\n\nexport class Framebuffer {\n width: number;\n height: number;\n cells: Cell[];\n\n constructor(width: number, height: number) {\n this.width = width;\n this.height = height;\n this.cells = new Array(width * height);\n this.clear();\n }\n\n clear(): void {\n for (let i = 0; i < this.cells.length; i++) {\n this.cells[i] = { ch: \" \" };\n }\n }\n\n resize(width: number, height: number): void {\n this.width = width;\n this.height = height;\n this.cells = new Array(width * height);\n this.clear();\n }\n\n get(x: number, y: number): Cell | undefined {\n if (x < 0 || x >= this.width || y < 0 || y >= this.height) return undefined;\n return this.cells[y * this.width + x];\n }\n\n set(x: number, y: number, cell: Cell): void {\n if (x < 0 || x >= this.width || y < 0 || y >= this.height) return;\n this.cells[y * this.width + x] = cell;\n }\n\n setChar(\n x: number,\n y: number,\n ch: string,\n fg?: Color,\n bg?: Color,\n bold?: boolean,\n dim?: boolean,\n italic?: boolean,\n underline?: boolean,\n ): void {\n if (x < 0 || x >= this.width || y < 0 || y >= this.height) return;\n this.cells[y * this.width + x] = { ch, fg, bg, bold, dim, italic, underline };\n }\n\n fillRect(\n x: number,\n y: number,\n w: number,\n h: number,\n ch: string,\n fg?: Color,\n bg?: Color,\n ): void {\n for (let row = y; row < y + h; row++) {\n for (let col = x; col < x + w; col++) {\n this.setChar(col, row, ch, fg, bg);\n }\n }\n }\n\n clone(): Framebuffer {\n const fb = new Framebuffer(this.width, this.height);\n for (let i = 0; i < this.cells.length; i++) {\n const c = this.cells[i]!;\n fb.cells[i] = { ...c };\n }\n return fb;\n }\n\n cellsEqual(a: Cell, b: Cell): boolean {\n return (\n a.ch === b.ch &&\n colorsEqual(a.fg, b.fg) &&\n colorsEqual(a.bg, b.bg) &&\n (a.bold ?? false) === (b.bold ?? false) &&\n (a.dim ?? false) === (b.dim ?? false) &&\n (a.italic ?? false) === (b.italic ?? false) &&\n (a.underline ?? false) === (b.underline ?? false)\n );\n }\n}\n","import type { BorderStyle } from \"../types/index.js\";\n\nexport interface BorderChars {\n topLeft: string;\n topRight: string;\n bottomLeft: string;\n bottomRight: string;\n horizontal: string;\n vertical: string;\n}\n\nconst BORDER_CHARS: Record<Exclude<BorderStyle, \"none\">, BorderChars> = {\n single: {\n topLeft: \"┌\",\n topRight: \"┐\",\n bottomLeft: \"└\",\n bottomRight: \"┘\",\n horizontal: \"─\",\n vertical: \"│\",\n },\n double: {\n topLeft: \"╔\",\n topRight: \"╗\",\n bottomLeft: \"╚\",\n bottomRight: \"╝\",\n horizontal: \"═\",\n vertical: \"║\",\n },\n round: {\n topLeft: \"╭\",\n topRight: \"╮\",\n bottomLeft: \"╰\",\n bottomRight: \"╯\",\n horizontal: \"─\",\n vertical: \"│\",\n },\n ascii: {\n topLeft: \"+\",\n topRight: \"+\",\n bottomLeft: \"+\",\n bottomRight: \"+\",\n horizontal: \"-\",\n vertical: \"|\",\n },\n};\n\nexport function getBorderChars(\n style: BorderStyle,\n): BorderChars | null {\n if (style === \"none\") return null;\n return BORDER_CHARS[style];\n}\n","import stringWidth from \"string-width\";\nimport { MeasureMode } from \"yoga-layout\";\nimport type { WrapMode } from \"../types/index.js\";\n\nexport function measureText(\n text: string,\n maxWidth: number,\n widthMode: MeasureMode,\n wrapMode: WrapMode,\n): { width: number; height: number } {\n if (text.length === 0) {\n return { width: 0, height: 0 };\n }\n\n const lines = text.split(\"\\n\");\n\n if (widthMode === MeasureMode.Undefined || wrapMode === \"none\") {\n // No constraint: measure as-is\n let maxW = 0;\n for (const line of lines) {\n const w = stringWidth(line);\n if (w > maxW) maxW = w;\n }\n return { width: maxW, height: lines.length };\n }\n\n const availWidth = Math.max(1, Math.floor(maxWidth));\n const wrappedLines = wrapLines(lines, availWidth, wrapMode);\n\n let maxW = 0;\n for (const line of wrappedLines) {\n const w = stringWidth(line);\n if (w > maxW) maxW = w;\n }\n\n return { width: maxW, height: wrappedLines.length };\n}\n\nexport function wrapLines(\n lines: string[],\n maxWidth: number,\n wrapMode: WrapMode,\n): string[] {\n const result: string[] = [];\n\n for (const line of lines) {\n const lineWidth = stringWidth(line);\n\n if (lineWidth <= maxWidth) {\n result.push(line);\n continue;\n }\n\n if (wrapMode === \"truncate\") {\n result.push(truncateLine(line, maxWidth));\n continue;\n }\n\n if (wrapMode === \"ellipsis\") {\n result.push(truncateWithEllipsis(line, maxWidth));\n continue;\n }\n\n // wrap mode\n const wrapped = wordWrap(line, maxWidth);\n result.push(...wrapped);\n }\n\n return result;\n}\n\nfunction truncateLine(text: string, maxWidth: number): string {\n let result = \"\";\n let width = 0;\n for (const char of text) {\n const charWidth = stringWidth(char);\n if (width + charWidth > maxWidth) break;\n result += char;\n width += charWidth;\n }\n return result;\n}\n\nfunction truncateWithEllipsis(text: string, maxWidth: number): string {\n if (maxWidth <= 1) {\n return maxWidth === 1 ? \"…\" : \"\";\n }\n const truncated = truncateLine(text, maxWidth - 1);\n if (stringWidth(truncated) < stringWidth(text)) {\n return truncated + \"…\";\n }\n return text;\n}\n\nfunction wordWrap(text: string, maxWidth: number): string[] {\n const lines: string[] = [];\n let currentLine = \"\";\n let currentWidth = 0;\n let wordBuffer = \"\";\n let wordBufferWidth = 0;\n \n for (let i = 0; i <= text.length; i++) {\n const char = text[i];\n const isEnd = i === text.length;\n const isSpace = char === \" \";\n \n if (isEnd || isSpace) {\n // End of a word - try to add word buffer to current line\n if (wordBuffer.length > 0) {\n if (currentWidth + wordBufferWidth <= maxWidth) {\n // Word fits on current line\n currentLine += wordBuffer;\n currentWidth += wordBufferWidth;\n } else if (wordBufferWidth <= maxWidth) {\n // Word fits on a new line\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n currentLine = wordBuffer;\n currentWidth = wordBufferWidth;\n } else {\n // Word is too long - break it character by character\n for (const c of wordBuffer) {\n const cw = stringWidth(c);\n if (currentWidth + cw > maxWidth && currentLine.length > 0) {\n lines.push(currentLine);\n currentLine = \"\";\n currentWidth = 0;\n }\n currentLine += c;\n currentWidth += cw;\n }\n }\n wordBuffer = \"\";\n wordBufferWidth = 0;\n }\n \n // Handle the space\n if (isSpace) {\n if (currentWidth + 1 <= maxWidth) {\n // Space fits on current line\n currentLine += \" \";\n currentWidth += 1;\n } else {\n // Space doesn't fit - start new line, put space at start\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n currentLine = \" \";\n currentWidth = 1;\n }\n }\n } else if (char) {\n // Building a word\n wordBuffer += char;\n wordBufferWidth += stringWidth(char);\n }\n }\n \n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n \n return lines.length > 0 ? lines : [\"\"];\n}\n","/**\n * ANSI escape code parser for text with embedded formatting.\n * \n * Parses strings containing ANSI SGR (Select Graphic Rendition) codes\n * and returns an array of styled segments.\n */\n\nimport type { Color } from \"../types/index.js\";\n\nexport interface AnsiStyle {\n fg?: Color;\n bg?: Color;\n bold?: boolean;\n dim?: boolean;\n italic?: boolean;\n underline?: boolean;\n}\n\nexport interface StyledSegment {\n text: string;\n style: AnsiStyle;\n}\n\n// ANSI color code to named color mapping\nconst ANSI_FG_COLORS: Record<number, Color> = {\n 30: \"black\",\n 31: \"red\",\n 32: \"green\",\n 33: \"yellow\",\n 34: \"blue\",\n 35: \"magenta\",\n 36: \"cyan\",\n 37: \"white\",\n 90: \"blackBright\",\n 91: \"redBright\",\n 92: \"greenBright\",\n 93: \"yellowBright\",\n 94: \"blueBright\",\n 95: \"magentaBright\",\n 96: \"cyanBright\",\n 97: \"whiteBright\",\n};\n\nconst ANSI_BG_COLORS: Record<number, Color> = {\n 40: \"black\",\n 41: \"red\",\n 42: \"green\",\n 43: \"yellow\",\n 44: \"blue\",\n 45: \"magenta\",\n 46: \"cyan\",\n 47: \"white\",\n 100: \"blackBright\",\n 101: \"redBright\",\n 102: \"greenBright\",\n 103: \"yellowBright\",\n 104: \"blueBright\",\n 105: \"magentaBright\",\n 106: \"cyanBright\",\n 107: \"whiteBright\",\n};\n\n/**\n * Parse ANSI SGR parameters and update the style object.\n */\nfunction applySgrParams(params: number[], style: AnsiStyle): void {\n let i = 0;\n while (i < params.length) {\n const code = params[i]!;\n \n switch (code) {\n case 0: // Reset all\n style.fg = undefined;\n style.bg = undefined;\n style.bold = false;\n style.dim = false;\n style.italic = false;\n style.underline = false;\n break;\n case 1: // Bold\n style.bold = true;\n break;\n case 2: // Dim\n style.dim = true;\n break;\n case 3: // Italic\n style.italic = true;\n break;\n case 4: // Underline\n style.underline = true;\n break;\n case 22: // Neither bold nor dim\n style.bold = false;\n style.dim = false;\n break;\n case 23: // Not italic\n style.italic = false;\n break;\n case 24: // Not underline\n style.underline = false;\n break;\n case 39: // Default foreground\n style.fg = undefined;\n break;\n case 49: // Default background\n style.bg = undefined;\n break;\n case 38: // Extended foreground color\n if (params[i + 1] === 5 && params[i + 2] !== undefined) {\n // 256-color: \\x1b[38;5;<n>m\n style.fg = params[i + 2];\n i += 2;\n } else if (params[i + 1] === 2 && params[i + 4] !== undefined) {\n // True color: \\x1b[38;2;<r>;<g>;<b>m\n const r = params[i + 2] ?? 0;\n const g = params[i + 3] ?? 0;\n const b = params[i + 4] ?? 0;\n style.fg = `#${r.toString(16).padStart(2, \"0\")}${g.toString(16).padStart(2, \"0\")}${b.toString(16).padStart(2, \"0\")}`;\n i += 4;\n }\n break;\n case 48: // Extended background color\n if (params[i + 1] === 5 && params[i + 2] !== undefined) {\n // 256-color: \\x1b[48;5;<n>m\n style.bg = params[i + 2];\n i += 2;\n } else if (params[i + 1] === 2 && params[i + 4] !== undefined) {\n // True color: \\x1b[48;2;<r>;<g>;<b>m\n const r = params[i + 2] ?? 0;\n const g = params[i + 3] ?? 0;\n const b = params[i + 4] ?? 0;\n style.bg = `#${r.toString(16).padStart(2, \"0\")}${g.toString(16).padStart(2, \"0\")}${b.toString(16).padStart(2, \"0\")}`;\n i += 4;\n }\n break;\n default:\n // Standard foreground colors (30-37, 90-97)\n if (ANSI_FG_COLORS[code]) {\n style.fg = ANSI_FG_COLORS[code];\n }\n // Standard background colors (40-47, 100-107)\n else if (ANSI_BG_COLORS[code]) {\n style.bg = ANSI_BG_COLORS[code];\n }\n break;\n }\n i++;\n }\n}\n\n/**\n * Parse a string with ANSI escape codes into styled segments.\n * \n * Handles:\n * - SGR codes: \\x1b[<params>m (colors, bold, italic, etc.)\n * - Resets escape sequences to plain text\n * \n * @param input String potentially containing ANSI escape codes\n * @returns Array of segments with text and associated style\n */\nexport function parseAnsi(input: string): StyledSegment[] {\n const segments: StyledSegment[] = [];\n const currentStyle: AnsiStyle = {};\n let currentText = \"\";\n \n // Regex to match ANSI SGR sequences: ESC [ <params> m\n // Also matches common variant with just ESC [ m (implicit 0)\n const ansiRegex = /\\x1b\\[([0-9;]*)m/g;\n \n let lastIndex = 0;\n let match: RegExpExecArray | null;\n \n while ((match = ansiRegex.exec(input)) !== null) {\n // Add text before this escape sequence\n const textBefore = input.slice(lastIndex, match.index);\n if (textBefore) {\n currentText += textBefore;\n }\n \n // Flush current segment if we have text\n if (currentText) {\n segments.push({\n text: currentText,\n style: { ...currentStyle },\n });\n currentText = \"\";\n }\n \n // Parse and apply the SGR parameters\n const paramStr = match[1] || \"0\"; // Empty means reset\n const params = paramStr.split(\";\").map(p => parseInt(p, 10) || 0);\n applySgrParams(params, currentStyle);\n \n lastIndex = ansiRegex.lastIndex;\n }\n \n // Add any remaining text\n const remainingText = input.slice(lastIndex);\n if (remainingText) {\n currentText += remainingText;\n }\n \n if (currentText) {\n segments.push({\n text: currentText,\n style: { ...currentStyle },\n });\n }\n \n return segments;\n}\n\n/**\n * Strip all ANSI escape codes from a string.\n * Useful for measuring visible width.\n */\nexport function stripAnsi(input: string): string {\n // eslint-disable-next-line no-control-regex\n return input.replace(/\\x1b\\[[0-9;]*m/g, \"\");\n}\n\n/**\n * Calculate the visible width of a string, excluding ANSI codes.\n */\nexport function ansiWidth(input: string): number {\n // Use string-width on the stripped string\n // This is imported in the painter, so we just strip here\n return stripAnsi(input).length;\n}\n","import type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { getInheritedTextStyle, collectTextContent } from \"../reconciler/nodes.js\";\nimport type { Cell } from \"./framebuffer.js\";\nimport { Framebuffer } from \"./framebuffer.js\";\nimport { getBorderChars } from \"./borders.js\";\nimport { isLightColor } from \"./color.js\";\nimport type { Color, Style } from \"../types/index.js\";\nimport { wrapLines } from \"../layout/textMeasure.js\";\nimport stringWidth from \"string-width\";\nimport { parseAnsi, stripAnsi } from \"./ansi.js\";\n\ninterface ClipRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\ninterface PaintEntry {\n node: GlyphNode;\n clip: ClipRect;\n zIndex: number;\n}\n\nexport interface CursorScreenPosition {\n x: number;\n y: number;\n /** Background color at cursor position for contrast calculation */\n bg?: Color;\n}\n\nexport interface PaintOptions {\n cursorInfo?: { nodeId: string; position: number };\n /** If true, don't paint the cursor and return its screen position instead */\n useNativeCursor?: boolean;\n}\n\nexport interface PaintResult {\n /** Cursor screen position if useNativeCursor is true and an input is focused */\n cursorPosition?: CursorScreenPosition;\n}\n\nexport function paintTree(\n roots: GlyphNode[],\n fb: Framebuffer,\n options: PaintOptions = {},\n): PaintResult {\n fb.clear();\n\n const result: PaintResult = {};\n\n // Collect all nodes with their z-index for proper ordering\n const entries: PaintEntry[] = [];\n const screenClip: ClipRect = { x: 0, y: 0, width: fb.width, height: fb.height };\n\n for (const root of roots) {\n if (root.hidden) continue;\n collectPaintEntries(root, screenClip, root.style.zIndex ?? 0, entries);\n }\n\n // Sort by zIndex (stable sort preserves tree order within same z)\n entries.sort((a, b) => a.zIndex - b.zIndex);\n\n // Paint each entry\n for (const entry of entries) {\n const nodeResult = paintNode(entry.node, fb, entry.clip, options);\n // Capture cursor position from the focused input\n if (nodeResult?.cursorPosition) {\n result.cursorPosition = nodeResult.cursorPosition;\n }\n }\n\n return result;\n}\n\nfunction collectPaintEntries(\n node: GlyphNode,\n parentClip: ClipRect,\n parentZ: number,\n entries: PaintEntry[],\n): void {\n if (node.hidden) return;\n\n const zIndex = node.style.zIndex ?? parentZ;\n\n // Compute clip for this node\n const clip = node.style.clip ? intersectClip(parentClip, {\n x: node.layout.innerX,\n y: node.layout.innerY,\n width: node.layout.innerWidth,\n height: node.layout.innerHeight,\n }) : parentClip;\n\n entries.push({ node, clip: parentClip, zIndex });\n\n // Children - skip for text/input (leaf nodes for painting)\n if (node.type !== \"text\" && node.type !== \"input\") {\n for (const child of node.children) {\n collectPaintEntries(child, clip, zIndex, entries);\n }\n }\n}\n\nfunction intersectClip(a: ClipRect, b: ClipRect): ClipRect {\n const x = Math.max(a.x, b.x);\n const y = Math.max(a.y, b.y);\n const right = Math.min(a.x + a.width, b.x + b.width);\n const bottom = Math.min(a.y + a.height, b.y + b.height);\n return {\n x,\n y,\n width: Math.max(0, right - x),\n height: Math.max(0, bottom - y),\n };\n}\n\nfunction isInClip(x: number, y: number, clip: ClipRect): boolean {\n return x >= clip.x && x < clip.x + clip.width && y >= clip.y && y < clip.y + clip.height;\n}\n\nfunction paintNode(\n node: GlyphNode,\n fb: Framebuffer,\n clip: ClipRect,\n options: PaintOptions = {},\n): PaintResult | undefined {\n const { x, y, width, height, innerX, innerY, innerWidth, innerHeight } = node.layout;\n const style = node.style;\n\n if (width <= 0 || height <= 0) return;\n\n // Resolve inherited bg so borders and fills don't erase a parent's background\n const inherited = getInheritedTextStyle(node);\n const effectiveBg = inherited.bg;\n\n // 1. Background fill\n if (style.bg) {\n for (let row = y; row < y + height; row++) {\n for (let col = x; col < x + width; col++) {\n if (isInClip(col, row, clip)) {\n fb.setChar(col, row, \" \", undefined, style.bg);\n }\n }\n }\n }\n\n // 2. Border\n const borderChars = style.border ? getBorderChars(style.border) : null;\n if (borderChars && width >= 2 && height >= 2) {\n const bc = style.borderColor;\n const bg = effectiveBg;\n\n // Top border\n setClipped(fb, clip, x, y, borderChars.topLeft, bc, bg);\n for (let col = x + 1; col < x + width - 1; col++) {\n setClipped(fb, clip, col, y, borderChars.horizontal, bc, bg);\n }\n setClipped(fb, clip, x + width - 1, y, borderChars.topRight, bc, bg);\n\n // Bottom border\n setClipped(fb, clip, x, y + height - 1, borderChars.bottomLeft, bc, bg);\n for (let col = x + 1; col < x + width - 1; col++) {\n setClipped(fb, clip, col, y + height - 1, borderChars.horizontal, bc, bg);\n }\n setClipped(fb, clip, x + width - 1, y + height - 1, borderChars.bottomRight, bc, bg);\n\n // Side borders\n for (let row = y + 1; row < y + height - 1; row++) {\n setClipped(fb, clip, x, row, borderChars.vertical, bc, bg);\n setClipped(fb, clip, x + width - 1, row, borderChars.vertical, bc, bg);\n }\n }\n\n // 3. Text content\n if (node.type === \"text\") {\n paintText(node, fb, clip);\n } else if (node.type === \"input\") {\n return paintInput(node, fb, clip, options);\n }\n\n return undefined;\n}\n\nfunction setClipped(\n fb: Framebuffer,\n clip: ClipRect,\n x: number,\n y: number,\n ch: string,\n fg?: Color,\n bg?: Color,\n bold?: boolean,\n dim?: boolean,\n italic?: boolean,\n underline?: boolean,\n): void {\n if (isInClip(x, y, clip)) {\n fb.setChar(x, y, ch, fg, bg, bold, dim, italic, underline);\n }\n}\n\nfunction autoContrastFg(explicitColor: Color | undefined, bg: Color | undefined): Color | undefined {\n if (explicitColor !== undefined) return explicitColor;\n if (bg === undefined) return undefined;\n return isLightColor(bg) ? \"black\" : \"white\";\n}\n\nfunction paintText(node: GlyphNode, fb: Framebuffer, clip: ClipRect): void {\n const { innerX, innerY, innerWidth, innerHeight } = node.layout;\n const inherited = getInheritedTextStyle(node);\n const text = collectTextContent(node);\n if (!text) return;\n\n const baseFg = autoContrastFg(inherited.color, inherited.bg);\n const wrapMode = node.style.wrap ?? \"wrap\";\n const textAlign = node.style.textAlign ?? \"left\";\n const rawLines = text.split(\"\\n\");\n \n // For wrapping, we need to strip ANSI codes to get correct widths\n // Then re-apply styles when painting\n const strippedLines = rawLines.map(line => stripAnsi(line));\n const wrappedStripped = wrapLines(strippedLines, innerWidth, wrapMode);\n\n // We need to track position in original text to maintain ANSI codes\n // So we'll wrap the stripped version for layout, but paint from originals\n // Actually, let's parse ANSI per-line and handle wrapping differently\n\n for (let lineIdx = 0; lineIdx < wrappedStripped.length && lineIdx < innerHeight; lineIdx++) {\n // Find which original line this wrapped line came from\n let origLineIdx = 0;\n let wrappedCount = 0;\n for (let i = 0; i < strippedLines.length; i++) {\n const linesFromThis = wrapLines([strippedLines[i]!], innerWidth, wrapMode).length;\n if (lineIdx < wrappedCount + linesFromThis) {\n origLineIdx = i;\n break;\n }\n wrappedCount += linesFromThis;\n }\n\n const wrappedLine = wrappedStripped[lineIdx]!;\n const visibleWidth = stringWidth(wrappedLine);\n let offsetX = 0;\n\n if (textAlign === \"center\") {\n offsetX = Math.max(0, Math.floor((innerWidth - visibleWidth) / 2));\n } else if (textAlign === \"right\") {\n offsetX = Math.max(0, innerWidth - visibleWidth);\n }\n\n // Parse the original line to get ANSI styles\n const originalLine = rawLines[origLineIdx]!;\n const segments = parseAnsi(originalLine);\n \n // Figure out which characters from the original line are in this wrapped line\n const subLineIdx = lineIdx - wrappedCount;\n const wrappedVersions = wrapLines([strippedLines[origLineIdx]!], innerWidth, wrapMode);\n \n // Calculate character offset into the stripped line\n let charOffset = 0;\n for (let i = 0; i < subLineIdx; i++) {\n charOffset += wrappedVersions[i]!.length;\n }\n const charEnd = charOffset + wrappedLine.length;\n\n // Paint characters with their ANSI styles\n let col = 0;\n let segmentCharIdx = 0; // Position in the stripped (visible) text\n \n for (const segment of segments) {\n for (const char of segment.text) {\n // Check if this character falls within our wrapped line range\n if (segmentCharIdx >= charOffset && segmentCharIdx < charEnd) {\n const charWidth = stringWidth(char);\n if (charWidth > 0) {\n // Merge ANSI style with inherited style (ANSI takes precedence)\n const fg = segment.style.fg ?? baseFg;\n const bg = segment.style.bg ?? inherited.bg;\n const bold = segment.style.bold ?? inherited.bold;\n const dim = segment.style.dim ?? inherited.dim;\n const italic = segment.style.italic ?? inherited.italic;\n const underline = segment.style.underline ?? inherited.underline;\n \n setClipped(\n fb, clip,\n innerX + offsetX + col, innerY + lineIdx,\n char,\n fg, bg, bold, dim, italic, underline,\n );\n }\n col += stringWidth(char);\n }\n segmentCharIdx++;\n }\n }\n }\n}\n\nfunction paintInput(\n node: GlyphNode,\n fb: Framebuffer,\n clip: ClipRect,\n options: PaintOptions = {},\n): PaintResult | undefined {\n const { cursorInfo, useNativeCursor } = options;\n const { innerX, innerY, innerWidth, innerHeight } = node.layout;\n if (innerWidth <= 0 || innerHeight <= 0) return;\n\n const value: string = node.props.value ?? node.props.defaultValue ?? \"\";\n const placeholder: string = node.props.placeholder ?? \"\";\n const displayText = value || placeholder;\n const isPlaceholder = !value && !!placeholder;\n const multiline: boolean = node.props.multiline ?? false;\n const inherited = getInheritedTextStyle(node);\n\n const autoFg = autoContrastFg(inherited.color, inherited.bg);\n // For placeholder: use a dimmed contrast color based on background\n // Light bg -> dark gray placeholder, dark bg -> light gray placeholder\n const placeholderFg: Color = inherited.bg \n ? (isLightColor(inherited.bg) ? \"blackBright\" : \"whiteBright\")\n : \"blackBright\";\n const fg = isPlaceholder\n ? placeholderFg\n : (autoFg ?? inherited.color ?? node.style.color);\n const textFg = isPlaceholder ? placeholderFg : fg;\n // Force dim for placeholder text to make it visually distinct\n const textDim = isPlaceholder ? true : inherited.dim;\n\n const isFocused = cursorInfo && cursorInfo.nodeId === node.focusId;\n let result: PaintResult | undefined;\n\n if (multiline && !isPlaceholder) {\n // ── Multiline rendering with wrapping ─────────────────────\n const wrapMode = node.style.wrap ?? \"wrap\";\n const rawLines = displayText.split(\"\\n\");\n const wrappedLines = wrapLines(rawLines, innerWidth, wrapMode);\n\n // Convert flat cursor position to screen (wrappedLine, col)\n let cursorScreenLine = 0;\n let cursorScreenCol = 0;\n if (isFocused) {\n const pos = cursorInfo.position;\n \n // Find which logical line the cursor is on\n let logicalLine = 0;\n let offsetInLogicalLine = pos;\n let runningPos = 0;\n \n for (let i = 0; i < rawLines.length; i++) {\n const lineLen = rawLines[i]!.length;\n if (pos <= runningPos + lineLen) {\n logicalLine = i;\n offsetInLogicalLine = pos - runningPos;\n break;\n }\n runningPos += lineLen + 1; // +1 for newline\n }\n \n // Count wrapped lines before this logical line\n let wrappedLinesBefore = 0;\n for (let i = 0; i < logicalLine; i++) {\n wrappedLinesBefore += wrapLines([rawLines[i]!], innerWidth, wrapMode).length;\n }\n \n // Wrap the current logical line and find cursor position within it\n const wrappedCurrentLine = wrapLines([rawLines[logicalLine]!], innerWidth, wrapMode);\n let charsProcessed = 0;\n let subLineIdx = 0;\n \n for (let i = 0; i < wrappedCurrentLine.length; i++) {\n const subLine = wrappedCurrentLine[i]!;\n if (offsetInLogicalLine <= charsProcessed + subLine.length) {\n subLineIdx = i;\n break;\n }\n charsProcessed += subLine.length;\n }\n \n cursorScreenLine = wrappedLinesBefore + subLineIdx;\n cursorScreenCol = stringWidth(rawLines[logicalLine]!.slice(charsProcessed, charsProcessed + (offsetInLogicalLine - charsProcessed)));\n }\n\n // Auto-scroll to keep cursor visible\n const scrollOffset = Math.max(0, cursorScreenLine - innerHeight + 1);\n\n // Render visible wrapped lines\n for (let rowIdx = 0; rowIdx < innerHeight; rowIdx++) {\n const lineNum = scrollOffset + rowIdx;\n if (lineNum >= wrappedLines.length) break;\n const line = wrappedLines[lineNum]!;\n let col = 0;\n for (const char of line) {\n if (col >= innerWidth) break;\n const charWidth = stringWidth(char);\n if (charWidth > 0) {\n setClipped(\n fb, clip,\n innerX + col, innerY + rowIdx,\n char,\n textFg, inherited.bg,\n inherited.bold, textDim, inherited.italic, inherited.underline,\n );\n }\n col += charWidth;\n }\n }\n\n // Cursor handling\n if (isFocused) {\n const screenRow = cursorScreenLine - scrollOffset;\n if (screenRow >= 0 && screenRow < innerHeight) {\n const cCol = Math.min(cursorScreenCol, innerWidth - 1);\n const cursorX = innerX + cCol;\n const cursorY = innerY + screenRow;\n if (isInClip(cursorX, cursorY, clip) && cursorX < innerX + innerWidth) {\n if (useNativeCursor) {\n // Return cursor position for native cursor positioning\n result = { cursorPosition: { x: cursorX, y: cursorY, bg: inherited.bg } };\n } else {\n // Paint simulated cursor\n const existing = fb.get(cursorX, cursorY);\n const cursorChar = existing?.ch && existing.ch !== \" \" ? existing.ch : \"▌\";\n const cursorFg = inherited.bg ?? \"black\";\n const cursorBg = inherited.color ?? \"white\";\n fb.setChar(\n cursorX, cursorY,\n cursorChar,\n cursorFg,\n cursorBg,\n existing?.bold, existing?.dim, existing?.italic,\n false,\n );\n }\n }\n }\n }\n } else {\n // ── Single-line rendering ───────────────────────────────\n let col = 0;\n for (const char of displayText) {\n if (col >= innerWidth) break;\n const charWidth = stringWidth(char);\n if (charWidth > 0) {\n setClipped(\n fb, clip,\n innerX + col, innerY,\n char,\n textFg, inherited.bg,\n inherited.bold, textDim, inherited.italic, inherited.underline,\n );\n }\n col += charWidth;\n }\n\n // Cursor handling\n if (isFocused) {\n const cursorCol = Math.min(cursorInfo.position, innerWidth - 1);\n const cursorX = innerX + cursorCol;\n if (isInClip(cursorX, innerY, clip) && cursorX < innerX + innerWidth) {\n if (useNativeCursor) {\n // Return cursor position for native cursor positioning\n result = { cursorPosition: { x: cursorX, y: innerY, bg: inherited.bg } };\n } else {\n // Paint simulated cursor\n const existing = fb.get(cursorX, innerY);\n const cursorChar = existing?.ch && existing.ch !== \" \" ? existing.ch : \"▌\";\n const cursorFg = inherited.bg ?? \"black\";\n const cursorBg = inherited.color ?? \"white\";\n fb.setChar(\n cursorX, innerY,\n cursorChar,\n cursorFg,\n cursorBg,\n existing?.bold, existing?.dim, existing?.italic,\n false,\n );\n }\n }\n }\n }\n\n return result;\n}\n","import type { Cell } from \"./framebuffer.js\";\nimport { Framebuffer } from \"./framebuffer.js\";\nimport { colorToFg, colorToBg } from \"./color.js\";\n\nconst ESC = \"\\x1b\";\nconst CSI = `${ESC}[`;\n\nfunction moveCursor(x: number, y: number): string {\n return `${CSI}${y + 1};${x + 1}H`;\n}\n\nfunction buildSGR(cell: Cell): string {\n let seq = `${CSI}0m`;\n if (cell.bold) seq += `${CSI}1m`;\n if (cell.dim) seq += `${CSI}2m`;\n if (cell.italic) seq += `${CSI}3m`;\n if (cell.underline) seq += `${CSI}4m`;\n if (cell.fg != null) seq += colorToFg(cell.fg);\n if (cell.bg != null) seq += colorToBg(cell.bg);\n return seq;\n}\n\nexport function diffFramebuffers(\n prev: Framebuffer,\n next: Framebuffer,\n fullRedraw: boolean,\n): string {\n let out = \"\";\n let lastX = -1;\n let lastY = -1;\n let lastSGR = \"\";\n\n for (let y = 0; y < next.height; y++) {\n for (let x = 0; x < next.width; x++) {\n const nc = next.get(x, y)!;\n if (!fullRedraw) {\n const pc = prev.get(x, y);\n if (pc && next.cellsEqual(nc, pc)) continue;\n }\n\n if (lastY !== y || lastX !== x) {\n out += moveCursor(x, y);\n }\n\n const sgr = buildSGR(nc);\n if (sgr !== lastSGR) {\n out += sgr;\n lastSGR = sgr;\n }\n\n out += nc.ch;\n lastX = x + 1;\n lastY = y;\n }\n }\n\n if (out.length > 0) {\n out += `${CSI}0m`;\n }\n\n return out;\n}\n","import Yoga, {\n Align,\n Edge,\n FlexDirection,\n Gutter,\n Justify,\n PositionType,\n Wrap,\n Direction,\n Overflow,\n} from \"yoga-layout\";\nimport type { Node as YogaNode } from \"yoga-layout\";\nimport type { GlyphNode, GlyphContainer } from \"../reconciler/nodes.js\";\nimport type { Style, DimensionValue } from \"../types/index.js\";\nimport { measureText } from \"./textMeasure.js\";\n\nconst FLEX_DIR_MAP: Record<string, FlexDirection> = {\n row: FlexDirection.Row,\n column: FlexDirection.Column,\n};\n\nconst JUSTIFY_MAP: Record<string, Justify> = {\n \"flex-start\": Justify.FlexStart,\n center: Justify.Center,\n \"flex-end\": Justify.FlexEnd,\n \"space-between\": Justify.SpaceBetween,\n \"space-around\": Justify.SpaceAround,\n};\n\nconst ALIGN_MAP: Record<string, Align> = {\n \"flex-start\": Align.FlexStart,\n center: Align.Center,\n \"flex-end\": Align.FlexEnd,\n stretch: Align.Stretch,\n};\n\nfunction setDimension(\n node: YogaNode,\n setter: (v: number | `${number}%` | undefined) => void,\n value: DimensionValue | undefined,\n): void {\n if (value === undefined) return;\n if (typeof value === \"string\" && value.endsWith(\"%\")) {\n setter(value as `${number}%`);\n } else {\n setter(value as number);\n }\n}\n\nfunction setPosition(\n node: YogaNode,\n edge: Edge,\n value: DimensionValue | undefined,\n): void {\n if (value === undefined) return;\n if (typeof value === \"string\" && value.endsWith(\"%\")) {\n node.setPositionPercent(edge, parseFloat(value));\n } else {\n node.setPosition(edge, value as number);\n }\n}\n\nfunction applyStyleToYogaNode(yogaNode: YogaNode, style: Style, nodeType: string): void {\n // Dimensions\n setDimension(yogaNode, (v) => yogaNode.setWidth(v as any), style.width);\n setDimension(yogaNode, (v) => yogaNode.setHeight(v as any), style.height);\n\n if (style.minWidth !== undefined) yogaNode.setMinWidth(style.minWidth);\n if (style.minHeight !== undefined) yogaNode.setMinHeight(style.minHeight);\n if (style.maxWidth !== undefined) yogaNode.setMaxWidth(style.maxWidth);\n if (style.maxHeight !== undefined) yogaNode.setMaxHeight(style.maxHeight);\n\n // Padding\n if (style.padding !== undefined) yogaNode.setPadding(Edge.All, style.padding);\n if (style.paddingX !== undefined) yogaNode.setPadding(Edge.Horizontal, style.paddingX);\n if (style.paddingY !== undefined) yogaNode.setPadding(Edge.Vertical, style.paddingY);\n if (style.paddingTop !== undefined) yogaNode.setPadding(Edge.Top, style.paddingTop);\n if (style.paddingRight !== undefined) yogaNode.setPadding(Edge.Right, style.paddingRight);\n if (style.paddingBottom !== undefined) yogaNode.setPadding(Edge.Bottom, style.paddingBottom);\n if (style.paddingLeft !== undefined) yogaNode.setPadding(Edge.Left, style.paddingLeft);\n\n // Border thickness for layout (1 cell if border is set, 0 otherwise)\n const hasBorder = style.border != null && style.border !== \"none\";\n yogaNode.setBorder(Edge.All, hasBorder ? 1 : 0);\n\n // Flex\n if (style.flexDirection) {\n yogaNode.setFlexDirection(FLEX_DIR_MAP[style.flexDirection] ?? FlexDirection.Column);\n }\n if (style.flexWrap) {\n yogaNode.setFlexWrap(style.flexWrap === \"wrap\" ? Wrap.Wrap : Wrap.NoWrap);\n }\n if (style.justifyContent) {\n yogaNode.setJustifyContent(JUSTIFY_MAP[style.justifyContent] ?? Justify.FlexStart);\n }\n if (style.alignItems) {\n yogaNode.setAlignItems(ALIGN_MAP[style.alignItems] ?? Align.Stretch);\n }\n if (style.flexGrow !== undefined) yogaNode.setFlexGrow(style.flexGrow);\n if (style.flexShrink !== undefined) yogaNode.setFlexShrink(style.flexShrink);\n\n // Gap\n if (style.gap !== undefined) yogaNode.setGap(Gutter.All, style.gap);\n\n // Positioning\n if (style.position === \"absolute\") {\n yogaNode.setPositionType(PositionType.Absolute);\n } else {\n yogaNode.setPositionType(PositionType.Relative);\n }\n\n // Inset shorthand\n if (style.inset !== undefined) {\n setPosition(yogaNode, Edge.Top, style.inset);\n setPosition(yogaNode, Edge.Right, style.inset);\n setPosition(yogaNode, Edge.Bottom, style.inset);\n setPosition(yogaNode, Edge.Left, style.inset);\n }\n\n setPosition(yogaNode, Edge.Top, style.top);\n setPosition(yogaNode, Edge.Right, style.right);\n setPosition(yogaNode, Edge.Bottom, style.bottom);\n setPosition(yogaNode, Edge.Left, style.left);\n\n // Overflow / clip\n if (style.clip) {\n yogaNode.setOverflow(Overflow.Hidden);\n }\n}\n\nfunction buildYogaTree(node: GlyphNode): void {\n const yogaNode = Yoga.Node.create();\n node.yogaNode = yogaNode;\n\n applyStyleToYogaNode(yogaNode, node.style, node.type);\n\n if (node.type === \"text\" || node.type === \"input\") {\n yogaNode.setMeasureFunc((width, widthMode, height, heightMode) => {\n let text: string;\n if (node.type === \"input\") {\n text = node.props.value ?? node.props.defaultValue ?? node.props.placeholder ?? \"\";\n if (text.length === 0) text = \" \";\n } else {\n text = collectAllText(node);\n }\n return measureText(\n text,\n width,\n widthMode,\n node.style.wrap ?? \"wrap\",\n );\n });\n } else {\n // Build children\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i]!;\n if (child.hidden) continue;\n buildYogaTree(child);\n yogaNode.insertChild(child.yogaNode!, yogaNode.getChildCount());\n }\n }\n}\n\nfunction collectAllText(node: GlyphNode): string {\n if (node.text != null) return node.text;\n let result = \"\";\n for (const child of node.children) {\n result += collectAllText(child);\n }\n if (result === \"\" && node.props.children != null) {\n if (typeof node.props.children === \"string\") return node.props.children;\n if (typeof node.props.children === \"number\") return String(node.props.children);\n }\n return result;\n}\n\nfunction extractLayout(node: GlyphNode, parentX: number, parentY: number): void {\n const yn = node.yogaNode!;\n const computedLayout = yn.getComputedLayout();\n\n const x = parentX + computedLayout.left;\n const y = parentY + computedLayout.top;\n const width = computedLayout.width;\n const height = computedLayout.height;\n\n const borderWidth = node.style.border && node.style.border !== \"none\" ? 1 : 0;\n const paddingTop = yn.getComputedPadding(Edge.Top);\n const paddingRight = yn.getComputedPadding(Edge.Right);\n const paddingBottom = yn.getComputedPadding(Edge.Bottom);\n const paddingLeft = yn.getComputedPadding(Edge.Left);\n\n const innerX = x + borderWidth + paddingLeft;\n const innerY = y + borderWidth + paddingTop;\n const innerWidth = Math.max(0, width - borderWidth * 2 - paddingLeft - paddingRight);\n const innerHeight = Math.max(0, height - borderWidth * 2 - paddingTop - paddingBottom);\n\n node.layout = { x, y, width, height, innerX, innerY, innerWidth, innerHeight };\n\n for (const child of node.children) {\n if (child.hidden || !child.yogaNode) continue;\n extractLayout(child, x, y);\n }\n}\n\nfunction freeYogaTree(node: GlyphNode): void {\n for (const child of node.children) {\n if (child.yogaNode) freeYogaTree(child);\n }\n if (node.yogaNode) {\n node.yogaNode.freeRecursive();\n node.yogaNode = null;\n }\n}\n\nexport function computeLayout(\n roots: GlyphNode[],\n screenWidth: number,\n screenHeight: number,\n): void {\n // Create a virtual root Yoga node for the screen\n const rootYoga = Yoga.Node.create();\n rootYoga.setWidth(screenWidth);\n rootYoga.setHeight(screenHeight);\n rootYoga.setFlexDirection(FlexDirection.Column);\n\n for (const child of roots) {\n if (child.hidden) continue;\n buildYogaTree(child);\n rootYoga.insertChild(child.yogaNode!, rootYoga.getChildCount());\n }\n\n rootYoga.calculateLayout(screenWidth, screenHeight, Direction.LTR);\n\n for (const child of roots) {\n if (child.hidden || !child.yogaNode) continue;\n extractLayout(child, 0, 0);\n }\n\n // Free yoga tree\n rootYoga.freeRecursive();\n\n // Clear references (they were freed)\n clearYogaRefs(roots);\n}\n\nfunction clearYogaRefs(nodes: GlyphNode[]): void {\n for (const node of nodes) {\n node.yogaNode = null;\n clearYogaRefs(node.children);\n }\n}\n","import { createContext } from \"react\";\nimport type { Key, LayoutRect } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\n// ---- Input Context ----\nexport type InputHandler = (key: Key) => void;\n/** Returns true if the key was consumed and should not propagate further */\nexport type FocusedInputHandler = (key: Key) => boolean;\n/** Priority handler - returns true if consumed, preventing all other handlers */\nexport type PriorityInputHandler = (key: Key) => boolean;\n\nexport interface InputContextValue {\n subscribe(handler: InputHandler): () => void;\n /** Register a high-priority handler that runs BEFORE focused input handlers */\n subscribePriority(handler: PriorityInputHandler): () => void;\n registerInputHandler(focusId: string, handler: FocusedInputHandler): () => void;\n}\n\nexport const InputContext = createContext<InputContextValue | null>(null);\n\n// ---- Focus Context ----\nexport interface RegisteredElement {\n id: string;\n node: GlyphNode;\n}\n\nexport interface FocusContextValue {\n focusedId: string | null;\n register(id: string, node: GlyphNode): () => void;\n requestFocus(id: string): void;\n focusNext(): void;\n focusPrev(): void;\n /** Mark an element as skippable during Tab navigation (e.g., disabled elements) */\n setSkippable(id: string, skippable: boolean): void;\n trapIds: Set<string> | null;\n pushTrap(ids: Set<string>): () => void;\n onFocusChange(handler: (focusedId: string | null) => void): () => void;\n /** Get all registered focusable elements (for custom navigation UIs) */\n getRegisteredElements(): RegisteredElement[];\n /** Get focusable elements in the current trap scope (or all if no trap) */\n getActiveElements(): RegisteredElement[];\n}\n\nexport const FocusContext = createContext<FocusContextValue | null>(null);\n\n// ---- Layout Context ----\nexport interface LayoutContextValue {\n getLayout(node: GlyphNode): LayoutRect;\n subscribe(node: GlyphNode, handler: (rect: LayoutRect) => void): () => void;\n}\n\nexport const LayoutContext = createContext<LayoutContextValue | null>(null);\n\n// ---- App Context ----\nexport interface AppContextValue {\n registerNode(node: GlyphNode): void;\n unregisterNode(node: GlyphNode): void;\n scheduleRender(): void;\n exit(code?: number): void;\n columns: number;\n rows: number;\n}\n\nexport const AppContext = createContext<AppContextValue | null>(null);\n\n// ---- ScrollView Context ----\n/** Provides boundary information for elements inside a ScrollView */\nexport interface ScrollViewBounds {\n /** Absolute Y position of visible area top (screen coordinates) */\n visibleTop: number;\n /** Absolute Y position of visible area bottom (screen coordinates) */\n visibleBottom: number;\n /** Height of the visible viewport */\n viewportHeight: number;\n /** Current scroll offset */\n scrollOffset: number;\n}\n\nexport interface ScrollViewContextValue {\n /** Get the current visible bounds of the ScrollView */\n getBounds(): ScrollViewBounds;\n}\n\nexport const ScrollViewContext = createContext<ScrollViewContextValue | null>(null);\n","import React from \"react\";\nimport type { ReactElement } from \"react\";\nimport { reconciler } from \"./reconciler/reconciler.js\";\nimport type { GlyphContainer } from \"./reconciler/nodes.js\";\nimport type { GlyphNode } from \"./reconciler/nodes.js\";\nimport { Terminal } from \"./runtime/terminal.js\";\nimport { parseKeySequence } from \"./runtime/input.js\";\nimport { Framebuffer } from \"./paint/framebuffer.js\";\nimport { paintTree } from \"./paint/painter.js\";\nimport { diffFramebuffers } from \"./paint/diff.js\";\nimport { computeLayout } from \"./layout/yogaLayout.js\";\nimport { setTerminalPalette, getContrastCursorColor } from \"./paint/color.js\";\nimport {\n InputContext,\n FocusContext,\n LayoutContext,\n AppContext,\n} from \"./hooks/context.js\";\nimport type {\n InputHandler,\n FocusedInputHandler,\n PriorityInputHandler,\n InputContextValue,\n FocusContextValue,\n LayoutContextValue,\n AppContextValue,\n} from \"./hooks/context.js\";\nimport type { RenderOptions, AppHandle, LayoutRect } from \"./types/index.js\";\n\nexport function render(\n element: ReactElement,\n opts: RenderOptions = {},\n): AppHandle {\n const stdout = opts.stdout ?? process.stdout;\n const stdin = opts.stdin ?? process.stdin;\n const debug = opts.debug ?? false;\n const useNativeCursor = opts.useNativeCursor ?? true;\n\n const terminal = new Terminal(stdout, stdin);\n terminal.setup();\n\n // Track whether native cursor is currently visible\n let nativeCursorVisible = false;\n\n // Query terminal for actual ANSI palette colors (async, repaint when done)\n terminal.queryPalette().then((palette) => {\n setTerminalPalette(palette);\n fullRedraw = true;\n scheduleRender();\n });\n\n const prevFb = new Framebuffer(terminal.columns, terminal.rows);\n const currentFb = new Framebuffer(terminal.columns, terminal.rows);\n let fullRedraw = true;\n\n // ---- Input system ----\n const inputHandlers = new Set<InputHandler>();\n const priorityHandlers = new Set<PriorityInputHandler>(); // Run before focused handlers\n const focusedInputHandlers = new Map<string, FocusedInputHandler>();\n\n const inputContextValue: InputContextValue = {\n subscribe(handler: InputHandler) {\n inputHandlers.add(handler);\n return () => inputHandlers.delete(handler);\n },\n subscribePriority(handler: PriorityInputHandler) {\n priorityHandlers.add(handler);\n return () => priorityHandlers.delete(handler);\n },\n registerInputHandler(focusId: string, handler: FocusedInputHandler) {\n focusedInputHandlers.set(focusId, handler);\n return () => focusedInputHandlers.delete(focusId);\n },\n };\n\n // ---- Focus system ----\n let focusedId: string | null = null;\n const focusRegistry = new Map<string, GlyphNode>();\n const focusOrder: string[] = [];\n const skippableIds = new Set<string>(); // Disabled/skippable elements during Tab\n let trapStack: Array<Set<string>> = [];\n const focusChangeHandlers = new Set<(id: string | null) => void>();\n\n function setFocusedId(id: string | null): void {\n if (focusedId !== id) {\n focusedId = id;\n scheduleRender();\n for (const handler of focusChangeHandlers) {\n handler(focusedId);\n }\n }\n }\n\n function getActiveFocusableIds(): string[] {\n let ids = [...focusOrder]; // Copy to avoid mutating original\n \n // Filter by trap if active\n if (trapStack.length > 0) {\n const trap = trapStack[trapStack.length - 1]!;\n ids = ids.filter((id) => trap.has(id));\n }\n \n // Filter out skippable (disabled) elements\n ids = ids.filter((id) => !skippableIds.has(id));\n \n // Sort by visual position (top-to-bottom, left-to-right) - like web DOM order\n ids.sort((a, b) => {\n const nodeA = focusRegistry.get(a);\n const nodeB = focusRegistry.get(b);\n if (!nodeA || !nodeB) return 0;\n \n const layoutA = nodeA.layout;\n const layoutB = nodeB.layout;\n \n // Compare Y first (row), then X (column)\n if (layoutA.y !== layoutB.y) {\n return layoutA.y - layoutB.y;\n }\n return layoutA.x - layoutB.x;\n });\n \n return ids;\n }\n\n const focusContextValue: FocusContextValue = {\n get focusedId() {\n return focusedId;\n },\n register(id: string, node: GlyphNode) {\n focusRegistry.set(id, node);\n if (!focusOrder.includes(id)) {\n focusOrder.push(id);\n }\n // Auto-register in active trap\n if (trapStack.length > 0) {\n trapStack[trapStack.length - 1]!.add(id);\n }\n // Auto-focus first item if nothing focused (by visual order)\n if (focusedId === null) {\n const activeIds = getActiveFocusableIds();\n if (activeIds.length > 0) {\n setFocusedId(activeIds[0]!);\n }\n }\n return () => {\n focusRegistry.delete(id);\n const idx = focusOrder.indexOf(id);\n if (idx !== -1) focusOrder.splice(idx, 1);\n if (focusedId === id) {\n // Focus first by visual order\n const activeIds = getActiveFocusableIds();\n setFocusedId(activeIds[0] ?? null);\n }\n };\n },\n requestFocus(id: string) {\n setFocusedId(id);\n },\n focusNext() {\n const ids = getActiveFocusableIds();\n if (ids.length === 0) return;\n const currentIdx = focusedId ? ids.indexOf(focusedId) : -1;\n const nextIdx = (currentIdx + 1) % ids.length;\n setFocusedId(ids[nextIdx]!);\n },\n focusPrev() {\n const ids = getActiveFocusableIds();\n if (ids.length === 0) return;\n const currentIdx = focusedId ? ids.indexOf(focusedId) : 0;\n const prevIdx = (currentIdx - 1 + ids.length) % ids.length;\n setFocusedId(ids[prevIdx]!);\n },\n setSkippable(id: string, skippable: boolean) {\n if (skippable) {\n skippableIds.add(id);\n // If this element is currently focused and now skippable, move focus\n if (focusedId === id) {\n const ids = getActiveFocusableIds();\n if (ids.length > 0) {\n setFocusedId(ids[0]!);\n }\n }\n } else {\n skippableIds.delete(id);\n }\n },\n trapIds: null,\n pushTrap(ids: Set<string>) {\n trapStack.push(ids);\n return () => {\n const idx = trapStack.indexOf(ids);\n if (idx !== -1) trapStack.splice(idx, 1);\n };\n },\n onFocusChange(handler: (id: string | null) => void) {\n focusChangeHandlers.add(handler);\n return () => {\n focusChangeHandlers.delete(handler);\n };\n },\n getRegisteredElements() {\n // Return all non-skippable registered elements\n const result: { id: string; node: GlyphNode }[] = [];\n for (const id of focusOrder) {\n if (skippableIds.has(id)) continue;\n const node = focusRegistry.get(id);\n if (node) {\n result.push({ id, node });\n }\n }\n return result;\n },\n getActiveElements() {\n // Return elements in the current trap scope (or all if no trap)\n const activeIds = getActiveFocusableIds();\n const result: { id: string; node: GlyphNode }[] = [];\n for (const id of activeIds) {\n if (skippableIds.has(id)) continue;\n const node = focusRegistry.get(id);\n if (node) {\n result.push({ id, node });\n }\n }\n return result;\n },\n };\n\n // ---- Layout system ----\n const layoutSubscriptions = new Map<GlyphNode, Set<(rect: LayoutRect) => void>>();\n\n const layoutContextValue: LayoutContextValue = {\n getLayout(node: GlyphNode) {\n return node.layout;\n },\n subscribe(node: GlyphNode, handler: (rect: LayoutRect) => void) {\n if (!layoutSubscriptions.has(node)) {\n layoutSubscriptions.set(node, new Set());\n }\n layoutSubscriptions.get(node)!.add(handler);\n return () => {\n const subs = layoutSubscriptions.get(node);\n if (subs) {\n subs.delete(handler);\n if (subs.size === 0) layoutSubscriptions.delete(node);\n }\n };\n },\n };\n\n // ---- App context ----\n const appContextValue: AppContextValue = {\n registerNode() {},\n unregisterNode() {},\n scheduleRender,\n exit(code?: number) {\n handle.exit(code);\n },\n get columns() {\n return terminal.columns;\n },\n get rows() {\n return terminal.rows;\n },\n };\n\n // ---- Container ----\n const container: GlyphContainer = {\n type: \"root\",\n children: [],\n onCommit() {\n scheduleRender();\n },\n };\n\n // ---- Render scheduling ----\n let renderScheduled = false;\n\n function scheduleRender(): void {\n if (renderScheduled) return;\n renderScheduled = true;\n queueMicrotask(() => {\n renderScheduled = false;\n performRender();\n });\n }\n\n function performRender(): void {\n const cols = terminal.columns;\n const rows = terminal.rows;\n\n if (currentFb.width !== cols || currentFb.height !== rows) {\n currentFb.resize(cols, rows);\n prevFb.resize(cols, rows);\n fullRedraw = true;\n }\n\n // Compute layout\n computeLayout(container.children, cols, rows);\n\n // Notify layout subscribers\n notifyLayoutSubscribers(container.children);\n\n // Find cursor info for focused input\n let cursorInfo: { nodeId: string; position: number } | undefined;\n if (focusedId) {\n const focusedNode = focusRegistry.get(focusedId);\n if (focusedNode?.type === \"input\") {\n cursorInfo = {\n nodeId: focusedId,\n position: focusedNode.props.cursorPosition ?? (focusedNode.props.value?.length ?? 0),\n };\n }\n }\n\n // Paint\n const paintResult = paintTree(container.children, currentFb, {\n cursorInfo,\n useNativeCursor,\n });\n\n // Diff & flush\n const output = diffFramebuffers(prevFb, currentFb, fullRedraw);\n if (output.length > 0) {\n terminal.write(output);\n }\n\n // Handle native cursor positioning\n if (useNativeCursor) {\n if (paintResult.cursorPosition) {\n // Set cursor color to contrast with input background\n const cursorColor = getContrastCursorColor(paintResult.cursorPosition.bg);\n terminal.setCursorColor(cursorColor);\n // Position and show native cursor\n terminal.moveCursor(paintResult.cursorPosition.x, paintResult.cursorPosition.y);\n if (!nativeCursorVisible) {\n terminal.showCursor();\n nativeCursorVisible = true;\n }\n } else {\n // No focused input - hide native cursor\n if (nativeCursorVisible) {\n terminal.hideCursor();\n nativeCursorVisible = false;\n }\n }\n }\n\n // Swap buffers\n for (let i = 0; i < currentFb.cells.length; i++) {\n prevFb.cells[i] = { ...currentFb.cells[i]! };\n }\n fullRedraw = false;\n }\n\n function notifyLayoutSubscribers(nodes: GlyphNode[]): void {\n for (const node of nodes) {\n const subs = layoutSubscriptions.get(node);\n if (subs) {\n for (const handler of subs) {\n handler(node.layout);\n }\n }\n notifyLayoutSubscribers(node.children);\n }\n }\n\n // ---- Input handling ----\n const removeDataListener = terminal.onData((data: string) => {\n const keys = parseKeySequence(data);\n for (const key of keys) {\n // Global: ctrl+c exits\n if (key.ctrl && key.name === \"c\") {\n handle.exit();\n return;\n }\n\n // Global: ctrl+z suspends (background the process)\n // 1. SIGSTOP not SIGTSTP — Node.js ignores SIGTSTP by default.\n // 2. pid 0 = entire process group, so the shell sees the foreground\n // job as stopped (handles bun→tsx→node chains correctly).\n if (key.ctrl && key.name === \"z\") {\n terminal.suspend();\n process.kill(0, \"SIGSTOP\");\n return;\n }\n\n // 1. Priority handlers run first (e.g., global keybinds like Ctrl+Enter)\n let consumed = false;\n for (const handler of priorityHandlers) {\n if (handler(key)) {\n consumed = true;\n break;\n }\n }\n\n // 2. If not consumed, let focused input handler try\n if (!consumed && focusedId) {\n const inputHandler = focusedInputHandlers.get(focusedId);\n if (inputHandler) {\n consumed = inputHandler(key);\n }\n }\n\n // 3. Tab navigation (if not consumed by input handler)\n // This allows inputs to handle Tab via onKeyPress and return true to prevent focus change\n if (!consumed && key.name === \"tab\" && !key.ctrl && !key.alt) {\n if (key.shift) {\n focusContextValue.focusPrev();\n } else {\n focusContextValue.focusNext();\n }\n continue;\n }\n\n // 4. If still not consumed, run global handlers\n if (!consumed) {\n for (const handler of inputHandlers) {\n handler(key);\n }\n }\n }\n });\n\n // ---- Resize handling ----\n const removeResizeListener = terminal.onResize(() => {\n fullRedraw = true;\n scheduleRender();\n });\n\n // ---- SIGCONT: resume after Ctrl+Z suspend ----\n const handleSigcont = () => {\n terminal.resume();\n fullRedraw = true;\n scheduleRender();\n };\n process.on(\"SIGCONT\", handleSigcont);\n\n // ---- Create React tree ----\n const wrappedElement = React.createElement(\n AppContext.Provider,\n { value: appContextValue },\n React.createElement(\n InputContext.Provider,\n { value: inputContextValue },\n React.createElement(\n FocusContext.Provider,\n { value: focusContextValue },\n React.createElement(\n LayoutContext.Provider,\n { value: layoutContextValue },\n element,\n ),\n ),\n ),\n );\n\n // Error handlers for React 19 reconciler\n const onUncaughtError = (error: Error) => {\n if (debug) console.error(\"Uncaught error:\", error);\n };\n const onCaughtError = (error: Error) => {\n // Error caught by ErrorBoundary - this is expected\n if (debug) console.error(\"Error caught by boundary:\", error);\n };\n const onRecoverableError = (error: Error) => {\n if (debug) console.error(\"Recoverable error:\", error);\n };\n\n // Create fiber root\n // Cast to any - react-reconciler types don't match React 19 runtime API\n const root = (reconciler.createContainer as any)(\n container,\n 0, // LegacyRoot tag\n null, // hydrationCallbacks\n false, // isStrictMode\n null, // concurrentUpdatesByDefaultOverride\n \"\", // identifierPrefix\n onUncaughtError,\n onCaughtError,\n onRecoverableError,\n null, // transitionCallbacks\n );\n\n reconciler.updateContainer(wrappedElement, root, null, null);\n\n // ---- Handle ----\n const handle: AppHandle = {\n unmount() {\n reconciler.updateContainer(null, root, null, null);\n removeDataListener();\n removeResizeListener();\n process.off(\"SIGCONT\", handleSigcont);\n terminal.cleanup();\n },\n exit(code?: number) {\n handle.unmount();\n process.exit(code ?? 0);\n },\n };\n\n return handle;\n}\n","import React, { forwardRef } from \"react\";\nimport type { Style } from \"../types/index.js\";\nimport type { ReactNode, Ref } from \"react\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface BoxProps {\n style?: Style;\n children?: ReactNode;\n focusable?: boolean;\n}\n\nexport const Box = forwardRef<GlyphNode, BoxProps>(\n function Box({ children, style, focusable }, ref): React.JSX.Element {\n return React.createElement(\"box\" as any, { style, focusable, ref }, children);\n }\n);\n","import React, { forwardRef } from \"react\";\nimport type { Style } from \"../types/index.js\";\nimport type { ReactNode } from \"react\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface TextProps {\n style?: Style;\n children?: ReactNode;\n wrap?: Style[\"wrap\"];\n}\n\nexport const Text = forwardRef<GlyphNode, TextProps>(\n function Text({ children, style, wrap }, ref): React.JSX.Element {\n const mergedStyle = wrap ? { ...style, wrap } : style;\n return React.createElement(\"text\" as any, { style: mergedStyle, ref }, children);\n }\n);\n","import React, { useState, useContext, useEffect, useRef } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport { InputContext, FocusContext, LayoutContext } from \"../hooks/context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { wrapLines } from \"../layout/textMeasure.js\";\n\n// ── Visual line helpers (accounts for word wrapping) ──────────\n\ninterface VisualLineInfo {\n visualLine: number;\n visualCol: number;\n totalVisualLines: number;\n /** Character offset where current visual line starts in original text */\n lineStartOffset: number;\n /** Length of current visual line */\n lineLength: number;\n}\n\n/**\n * Convert flat cursor position → visual (wrapped) line/col.\n * This accounts for soft wrapping based on width.\n */\nfunction cursorToVisualLine(\n text: string,\n pos: number,\n width: number,\n): VisualLineInfo {\n if (width <= 0) {\n return { visualLine: 0, visualCol: pos, totalVisualLines: 1, lineStartOffset: 0, lineLength: text.length };\n }\n \n const logicalLines = text.split(\"\\n\");\n const allVisualLines: { text: string; logicalOffset: number }[] = [];\n \n let logicalOffset = 0;\n for (const logicalLine of logicalLines) {\n const wrapped = wrapLines([logicalLine], width, \"wrap\");\n let offsetInLogical = 0;\n for (const wrappedLine of wrapped) {\n allVisualLines.push({ \n text: wrappedLine, \n logicalOffset: logicalOffset + offsetInLogical \n });\n offsetInLogical += wrappedLine.length;\n }\n logicalOffset += logicalLine.length + 1; // +1 for newline\n }\n \n // Find which visual line contains the cursor\n let charCount = 0;\n for (let i = 0; i < allVisualLines.length; i++) {\n const vl = allVisualLines[i]!;\n const lineLen = vl.text.length;\n // Account for newline at end of logical lines (except last)\n const isEndOfLogicalLine = i + 1 < allVisualLines.length && \n allVisualLines[i + 1]!.logicalOffset !== vl.logicalOffset + lineLen;\n const effectiveLen = lineLen + (isEndOfLogicalLine ? 1 : 0);\n \n // Use < instead of <= so cursor at wrap boundary belongs to the NEXT line\n // Exception: last line always captures remaining positions\n if (pos < charCount + lineLen || i === allVisualLines.length - 1) {\n return {\n visualLine: i,\n visualCol: Math.min(pos - charCount, lineLen),\n totalVisualLines: allVisualLines.length,\n lineStartOffset: charCount,\n lineLength: lineLen,\n };\n }\n charCount += effectiveLen;\n }\n \n // Fallback\n const lastIdx = allVisualLines.length - 1;\n return {\n visualLine: lastIdx,\n visualCol: allVisualLines[lastIdx]!.text.length,\n totalVisualLines: allVisualLines.length,\n lineStartOffset: charCount - allVisualLines[lastIdx]!.text.length,\n lineLength: allVisualLines[lastIdx]!.text.length,\n };\n}\n\n/**\n * Convert visual (wrapped) line/col → flat cursor position.\n */\nfunction visualLineToCursor(\n text: string,\n visualLine: number,\n visualCol: number,\n width: number,\n): number {\n if (width <= 0) {\n return Math.min(visualCol, text.length);\n }\n \n const logicalLines = text.split(\"\\n\");\n const allVisualLines: { text: string; startOffset: number }[] = [];\n \n let offset = 0;\n for (const logicalLine of logicalLines) {\n const wrapped = wrapLines([logicalLine], width, \"wrap\");\n let offsetInLogical = 0;\n for (const wrappedLine of wrapped) {\n allVisualLines.push({ \n text: wrappedLine, \n startOffset: offset + offsetInLogical \n });\n offsetInLogical += wrappedLine.length;\n }\n offset += logicalLine.length + 1;\n }\n \n const targetLine = Math.max(0, Math.min(visualLine, allVisualLines.length - 1));\n const vl = allVisualLines[targetLine]!;\n const col = Math.min(visualCol, vl.text.length);\n \n return vl.startOffset + col;\n}\n\n// ── Logical line helpers (for Ctrl+A/E/U/K, Home/End) ─────────\n\n/** Convert flat cursor position → (line, col) within newline-separated text. */\nfunction cursorToLineCol(\n text: string,\n pos: number,\n): { line: number; col: number; lines: string[] } {\n const lines = text.split(\"\\n\");\n let remaining = pos;\n for (let i = 0; i < lines.length; i++) {\n if (remaining <= lines[i]!.length) {\n return { line: i, col: remaining, lines };\n }\n remaining -= lines[i]!.length + 1;\n }\n const last = lines.length - 1;\n return { line: last, col: lines[last]!.length, lines };\n}\n\n/** Convert (line, col) → flat cursor position. */\nfunction lineColToCursor(\n lines: string[],\n line: number,\n col: number,\n): number {\n let pos = 0;\n for (let i = 0; i < line && i < lines.length; i++) {\n pos += lines[i]!.length + 1;\n }\n return pos + Math.min(col, lines[line]?.length ?? 0);\n}\n\n// ── Component ─────────────────────────────────────────────────\n\nexport type InputType = \"text\" | \"number\";\n\nexport interface InputProps {\n value?: string;\n defaultValue?: string;\n onChange?: (value: string) => void;\n /** Called on every key press. Return `true` to prevent default handling. */\n onKeyPress?: (key: Key) => boolean | void;\n /** \n * Called before a value change is applied. Useful for input masking/validation.\n * @param newValue - The proposed new value\n * @param oldValue - The current value\n * @returns \n * - `string` to use a different value (and cursor moves to end of returned string)\n * - `false` to reject the change entirely\n * - `undefined` to accept the change as-is\n */\n onBeforeChange?: (newValue: string, oldValue: string) => string | false | void;\n placeholder?: string;\n style?: Style;\n /** Style when focused (merged with style) */\n focusedStyle?: Style;\n /** Enable multiline editing (Enter inserts newlines, Up/Down navigate lines). */\n multiline?: boolean;\n /** Automatically focus this input when mounted */\n autoFocus?: boolean;\n /** \n * Input type for validation:\n * - \"text\" (default): accepts any character\n * - \"number\": only accepts digits, decimal point, and minus sign\n */\n type?: InputType;\n}\n\nexport function Input(props: InputProps): React.JSX.Element {\n const {\n value: controlledValue,\n defaultValue = \"\",\n onChange,\n onKeyPress,\n onBeforeChange,\n placeholder,\n style,\n focusedStyle,\n multiline,\n autoFocus,\n type = \"text\",\n } = props;\n const [internalValue, setInternalValue] = useState(defaultValue);\n const [cursorPos, setCursorPos] = useState(defaultValue.length);\n const [innerWidth, setInnerWidth] = useState(0);\n const [isFocused, setIsFocused] = useState(false);\n // Track when node is mounted with a valid focusId\n const [nodeReady, setNodeReady] = useState(false);\n const inputCtx = useContext(InputContext);\n const focusCtx = useContext(FocusContext);\n const layoutCtx = useContext(LayoutContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n\n const isControlled = controlledValue !== undefined;\n const value = isControlled ? controlledValue : internalValue;\n\n // Subscribe to layout changes to get innerWidth for visual line navigation\n useEffect(() => {\n if (!layoutCtx || !nodeRef.current) return;\n const layout = layoutCtx.getLayout(nodeRef.current);\n setInnerWidth(layout.innerWidth);\n return layoutCtx.subscribe(nodeRef.current, (rect) => {\n setInnerWidth(rect.innerWidth);\n });\n }, [layoutCtx]);\n\n // Keep working value/cursor in refs that update SYNCHRONOUSLY \n // This prevents race conditions when typing faster than React renders\n const workingValueRef = useRef(value);\n const workingCursorRef = useRef(cursorPos);\n // Track what we last sent to detect external vs echoed changes\n const lastSentValueRef = useRef(value);\n const lastSentCursorRef = useRef(cursorPos);\n \n // Sync refs with React state when it updates\n // Only update if the incoming value is an EXTERNAL change (not just echoing what we sent)\n // This prevents overwriting working refs during fast typing\n useEffect(() => {\n // Only accept the incoming value if it's different from what we last sent\n // This means it's either an external change or a transformed value from the parent\n if (value !== lastSentValueRef.current) {\n workingValueRef.current = value;\n lastSentValueRef.current = value;\n // Move cursor to end of new value for programmatic changes\n workingCursorRef.current = value.length;\n lastSentCursorRef.current = value.length;\n setCursorPos(value.length);\n }\n }, [value]);\n \n // Same logic for cursor - only accept external changes\n useEffect(() => {\n if (cursorPos !== lastSentCursorRef.current) {\n workingCursorRef.current = cursorPos;\n lastSentCursorRef.current = cursorPos;\n }\n }, [cursorPos]);\n\n // Keep a ref to current values so the handler closure always reads fresh state\n const stateRef = useRef({\n isControlled,\n onChange,\n onKeyPress,\n onBeforeChange,\n multiline: multiline ?? false,\n innerWidth,\n type,\n });\n stateRef.current = {\n isControlled,\n onChange,\n onKeyPress,\n onBeforeChange,\n multiline: multiline ?? false,\n innerWidth,\n type,\n };\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, nodeReady]);\n\n // Auto-focus on mount if requested\n // Use setTimeout to ensure this runs AFTER all registrations and layout effects complete\n const autoFocusedRef = useRef(false);\n useEffect(() => {\n // Reset the flag when node is not ready (component unmounted/remounting)\n if (!nodeReady) {\n autoFocusedRef.current = false;\n return;\n }\n \n if (autoFocus && !autoFocusedRef.current && focusCtx && focusIdRef.current) {\n autoFocusedRef.current = true;\n const fid = focusIdRef.current;\n // Use setTimeout(0) instead of queueMicrotask for more reliable timing\n // This ensures registration has fully propagated through the focus system\n const timer = setTimeout(() => {\n focusCtx.requestFocus(fid);\n }, 0);\n return () => clearTimeout(timer);\n }\n }, [autoFocus, focusCtx, nodeReady]);\n\n // Subscribe to focus changes for reactive visual state\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Register focused input handler - returns true for consumed keys\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n const {\n isControlled: ctrl,\n onChange: cb,\n onKeyPress: onKey,\n onBeforeChange: onBefore,\n multiline: ml,\n } = stateRef.current;\n \n // Call onKeyPress callback first - if it returns true, prevent default handling\n if (onKey?.(key) === true) {\n return true;\n }\n \n // Read from working refs (updated synchronously) to handle fast typing\n const val = workingValueRef.current;\n const pos = workingCursorRef.current;\n\n // Escape always passes through\n if (key.name === \"escape\") return false;\n\n // Helper to update value and cursor synchronously\n // Calls onBeforeChange if provided, allowing masking/validation\n const updateValue = (newVal: string, newCursor: number) => {\n let finalVal = newVal;\n let finalCursor = newCursor;\n \n if (onBefore) {\n const result = onBefore(newVal, val);\n if (result === false) {\n // Reject the change entirely\n return;\n }\n if (typeof result === \"string\") {\n // Use the modified value, cursor goes to end\n finalVal = result;\n finalCursor = result.length;\n }\n }\n \n workingValueRef.current = finalVal;\n workingCursorRef.current = finalCursor;\n lastSentValueRef.current = finalVal; // Track what we're sending\n lastSentCursorRef.current = finalCursor;\n if (!ctrl) setInternalValue(finalVal);\n cb?.(finalVal);\n setCursorPos(finalCursor);\n };\n \n const updateCursor = (newCursor: number) => {\n workingCursorRef.current = newCursor;\n lastSentCursorRef.current = newCursor; // Track what we're sending\n setCursorPos(newCursor);\n };\n\n // Return: pass through for single-line, insert newline for multiline\n if (key.name === \"return\") {\n if (ml) {\n const newVal = val.slice(0, pos) + \"\\n\" + val.slice(pos);\n updateValue(newVal, pos + 1);\n return true;\n }\n return false;\n }\n\n // Ctrl shortcuts consumed by the input\n if (key.ctrl) {\n if (key.name === \"w\") {\n // Delete word backward (stops at newline in multiline)\n if (pos > 0) {\n let i = pos;\n while (i > 0 && val[i - 1] === \" \") i--;\n while (\n i > 0 &&\n val[i - 1] !== \" \" &&\n (!ml || val[i - 1] !== \"\\n\")\n )\n i--;\n const newVal = val.slice(0, i) + val.slice(pos);\n updateValue(newVal, i);\n }\n return true;\n }\n if (key.name === \"a\") {\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n updateCursor(lineColToCursor(lines, line, 0));\n } else {\n updateCursor(0);\n }\n return true;\n }\n if (key.name === \"e\") {\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n updateCursor(lineColToCursor(lines, line, lines[line]!.length));\n } else {\n updateCursor(val.length);\n }\n return true;\n }\n if (key.name === \"k\") {\n // Delete from cursor to end of line\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n const lineEnd = lineColToCursor(lines, line, lines[line]!.length);\n if (pos < lineEnd) {\n const newVal = val.slice(0, pos) + val.slice(lineEnd);\n updateValue(newVal, pos);\n }\n } else {\n if (pos < val.length) {\n const newVal = val.slice(0, pos);\n updateValue(newVal, pos);\n }\n }\n return true;\n }\n // All other ctrl combos pass through to useInput\n return false;\n }\n\n // ── Alt + Arrow: Word navigation ────────────────────────\n if (key.alt) {\n if (key.name === \"left\" || key.name === \"b\") {\n // Move to start of previous word\n let i = pos;\n // Skip any spaces before cursor\n while (i > 0 && val[i - 1] === \" \") i--;\n // Skip the word\n while (i > 0 && val[i - 1] !== \" \" && val[i - 1] !== \"\\n\") i--;\n updateCursor(i);\n return true;\n }\n if (key.name === \"right\" || key.name === \"f\") {\n // Move to end of next word\n let i = pos;\n // Skip current word\n while (i < val.length && val[i] !== \" \" && val[i] !== \"\\n\") i++;\n // Skip spaces after word\n while (i < val.length && val[i] === \" \") i++;\n updateCursor(i);\n return true;\n }\n if (key.name === \"backspace\" || key.name === \"d\") {\n // Delete word backward (Alt+Backspace or Alt+D for forward)\n if (key.name === \"backspace\") {\n if (pos > 0) {\n let i = pos;\n while (i > 0 && val[i - 1] === \" \") i--;\n while (i > 0 && val[i - 1] !== \" \" && val[i - 1] !== \"\\n\") i--;\n const newVal = val.slice(0, i) + val.slice(pos);\n updateValue(newVal, i);\n }\n return true;\n } else {\n // Alt+D: delete word forward\n if (pos < val.length) {\n let i = pos;\n while (i < val.length && val[i] !== \" \" && val[i] !== \"\\n\") i++;\n while (i < val.length && val[i] === \" \") i++;\n const newVal = val.slice(0, pos) + val.slice(i);\n updateValue(newVal, pos);\n }\n return true;\n }\n }\n // Pass through other alt combos\n return false;\n }\n\n // ── Navigation ──────────────────────────────────────────\n\n if (key.name === \"left\") {\n updateCursor(Math.max(0, pos - 1));\n return true;\n }\n if (key.name === \"right\") {\n updateCursor(Math.min(val.length, pos + 1));\n return true;\n }\n if (key.name === \"up\") {\n const { innerWidth: w } = stateRef.current;\n // Use visual line navigation (accounts for word wrapping)\n const info = cursorToVisualLine(val, pos, w);\n if (info.visualLine > 0) {\n updateCursor(visualLineToCursor(val, info.visualLine - 1, info.visualCol, w));\n }\n return true;\n }\n if (key.name === \"down\") {\n const { innerWidth: w } = stateRef.current;\n // Use visual line navigation (accounts for word wrapping)\n const info = cursorToVisualLine(val, pos, w);\n if (info.visualLine < info.totalVisualLines - 1) {\n updateCursor(visualLineToCursor(val, info.visualLine + 1, info.visualCol, w));\n }\n return true;\n }\n if (key.name === \"home\") {\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n updateCursor(lineColToCursor(lines, line, 0));\n } else {\n updateCursor(0);\n }\n return true;\n }\n if (key.name === \"end\") {\n if (ml) {\n const { line, lines } = cursorToLineCol(val, pos);\n updateCursor(lineColToCursor(lines, line, lines[line]!.length));\n } else {\n updateCursor(val.length);\n }\n return true;\n }\n\n // ── Editing ─────────────────────────────────────────────\n\n if (key.name === \"backspace\") {\n if (pos > 0) {\n const newVal = val.slice(0, pos - 1) + val.slice(pos);\n updateValue(newVal, pos - 1);\n }\n return true;\n }\n if (key.name === \"delete\") {\n if (pos < val.length) {\n const newVal = val.slice(0, pos) + val.slice(pos + 1);\n updateValue(newVal, pos);\n }\n return true;\n }\n\n // Special/function keys we don't handle - pass through\n if (key.name.length > 1) return false;\n\n // Printable character - consume it\n const ch = key.sequence;\n if (ch.length === 1 && ch.charCodeAt(0) >= 32) {\n // Validate input based on type\n const { type: inputType } = stateRef.current;\n if (inputType === \"number\") {\n // Only allow digits, decimal point, minus sign (at start)\n const isDigit = /[0-9]/.test(ch);\n const isDecimal = ch === \".\" && !val.includes(\".\");\n const isMinus = ch === \"-\" && pos === 0 && !val.includes(\"-\");\n if (!isDigit && !isDecimal && !isMinus) {\n return true; // Consume but don't insert\n }\n }\n \n const newVal = val.slice(0, pos) + ch + val.slice(pos);\n updateValue(newVal, pos + 1);\n return true;\n }\n\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, nodeReady]);\n\n // Merge styles based on focus state\n const mergedStyle: Style = {\n ...style,\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n return React.createElement(\"input\" as any, {\n style: mergedStyle,\n value,\n defaultValue,\n placeholder,\n onChange,\n // Use ref (always current) instead of state (can lag during fast typing)\n cursorPosition: workingCursorRef.current,\n multiline: multiline ?? false,\n focused: isFocused,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n });\n}\n","import React, { useContext, useEffect, useLayoutEffect, useRef } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { FocusContext } from \"../hooks/context.js\";\n\nexport interface FocusScopeProps {\n trap?: boolean;\n children?: ReactNode;\n}\n\nexport function FocusScope({ trap = false, children }: FocusScopeProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const prevFocusRef = useRef<string | null>(null);\n const scopeIdsRef = useRef<Set<string>>(new Set());\n\n // Push trap during layout phase - this runs BEFORE children's useEffect,\n // so when children register in their useEffect, the trap is already active\n // and their IDs get added to scopeIdsRef.current\n useLayoutEffect(() => {\n if (!trap || !focusCtx) return;\n\n prevFocusRef.current = focusCtx.focusedId;\n const cleanup = focusCtx.pushTrap(scopeIdsRef.current);\n\n return () => {\n cleanup();\n // Restore previous focus when trap is removed\n if (prevFocusRef.current) {\n focusCtx.requestFocus(prevFocusRef.current);\n }\n };\n }, [trap, focusCtx]);\n\n // Focus first trapped item AFTER children have registered (useEffect runs after children's useEffect)\n useEffect(() => {\n if (!trap || !focusCtx) return;\n if (scopeIdsRef.current.size > 0) {\n const firstId = scopeIdsRef.current.values().next().value;\n if (firstId) focusCtx.requestFocus(firstId);\n }\n }, [trap, focusCtx]);\n\n return React.createElement(React.Fragment, null, children);\n}\n","import React from \"react\";\n\nexport interface SpacerProps {\n size?: number;\n}\n\nexport function Spacer({ size }: SpacerProps): React.JSX.Element {\n return React.createElement(\"box\" as any, {\n style: { flexGrow: size ?? 1 },\n });\n}\n","import { useContext, useEffect, useRef } from \"react\";\nimport { InputContext, FocusContext } from \"../hooks/context.js\";\nimport type { Key } from \"../types/index.js\";\n\nexport interface KeybindProps {\n /** Key descriptor, e.g. \"q\", \"escape\", \"ctrl+c\", \"ctrl+shift+a\" */\n keypress: string;\n /** Handler called when the key matches */\n onPress: () => void;\n /** Only fire when this focus ID is active */\n whenFocused?: string;\n /** Only fire when nothing is focused or the focused element doesn't consume the key */\n global?: boolean;\n /** \n * If true, this keybind runs BEFORE focused input handlers.\n * Use for keybinds that should work even when an Input is focused (e.g., Ctrl+Enter to submit).\n */\n priority?: boolean;\n /** Disabled state */\n disabled?: boolean;\n}\n\ninterface KeyMatcher {\n name: string;\n ctrl: boolean;\n alt: boolean;\n shift: boolean;\n meta: boolean;\n}\n\nfunction parseKeyDescriptor(descriptor: string): KeyMatcher {\n const parts = descriptor.toLowerCase().split(\"+\");\n const name = parts[parts.length - 1]!;\n return {\n name,\n ctrl: parts.includes(\"ctrl\"),\n alt: parts.includes(\"alt\"),\n shift: parts.includes(\"shift\"),\n meta: parts.includes(\"meta\") || parts.includes(\"cmd\") || parts.includes(\"super\") || parts.includes(\"win\"),\n };\n}\n\nfunction matchesKey(matcher: KeyMatcher, key: Key): boolean {\n if (key.name !== matcher.name) return false;\n if (matcher.ctrl !== !!key.ctrl) return false;\n if (matcher.alt !== !!key.alt) return false;\n if (matcher.shift !== !!key.shift) return false;\n if (matcher.meta !== !!key.meta) return false;\n return true;\n}\n\nexport function Keybind({\n keypress,\n onPress,\n whenFocused,\n priority,\n disabled,\n}: KeybindProps): null {\n const inputCtx = useContext(InputContext);\n const focusCtx = useContext(FocusContext);\n const onPressRef = useRef(onPress);\n onPressRef.current = onPress;\n\n const matcherRef = useRef<KeyMatcher>(parseKeyDescriptor(keypress));\n matcherRef.current = parseKeyDescriptor(keypress);\n\n useEffect(() => {\n if (!inputCtx || disabled) return;\n\n if (priority) {\n // Priority handler - runs before focused input handlers\n const handler = (key: Key): boolean => {\n if (!matchesKey(matcherRef.current, key)) return false;\n\n // If whenFocused is specified, only fire when that ID is focused\n if (whenFocused && focusCtx?.focusedId !== whenFocused) return false;\n\n onPressRef.current();\n return true; // Consumed - prevent further propagation\n };\n\n return inputCtx.subscribePriority(handler);\n } else {\n // Normal handler - runs after focused input handlers (if not consumed)\n const handler = (key: Key) => {\n if (!matchesKey(matcherRef.current, key)) return;\n\n // If whenFocused is specified, only fire when that ID is focused\n if (whenFocused && focusCtx?.focusedId !== whenFocused) return;\n\n onPressRef.current();\n };\n\n return inputCtx.subscribe(handler);\n }\n }, [inputCtx, focusCtx, whenFocused, priority, disabled]);\n\n return null;\n}\n","import React from \"react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PortalProps {\n children?: ReactNode;\n zIndex?: number;\n}\n\n/**\n * Portal renders children as a fullscreen absolute overlay on top of the main tree.\n * Useful for modals, notifications, and dropdowns that should paint above all other content.\n */\nexport function Portal({ children, zIndex = 1000 }: PortalProps): React.JSX.Element {\n return React.createElement(\n \"box\" as any,\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n height: \"100%\",\n zIndex,\n },\n },\n children,\n );\n}\n","import React, { useContext, useEffect, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport { FocusContext, InputContext } from \"../hooks/context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface ButtonProps {\n onPress?: () => void;\n style?: Style;\n focusedStyle?: Style;\n children?: ReactNode;\n disabled?: boolean;\n}\n\nexport function Button({\n onPress,\n style,\n focusedStyle,\n children,\n disabled,\n}: ButtonProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onPressRef = useRef(onPress);\n onPressRef.current = onPress;\n\n // Track when node is mounted with a valid focusId - this triggers effect re-runs\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || disabled) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, disabled, nodeReady]);\n\n // Subscribe to focus changes for reactive visual state\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n // Set initial state\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Handle enter/space when focused\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n if (key.name === \"return\" || key.name === \" \" || key.sequence === \" \") {\n onPressRef.current?.();\n return true;\n }\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, disabled, nodeReady]);\n\n const mergedStyle: Style = {\n ...style,\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n return React.createElement(\n \"box\" as any,\n {\n style: mergedStyle,\n focusable: !disabled,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n children,\n );\n}\n","import { useContext, useState, useEffect } from \"react\";\nimport { LayoutContext } from \"./context.js\";\nimport type { LayoutRect } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nconst DEFAULT_RECT: LayoutRect = {\n x: 0, y: 0, width: 0, height: 0,\n innerX: 0, innerY: 0, innerWidth: 0, innerHeight: 0,\n};\n\nexport function useLayout(nodeRef?: { current: GlyphNode | null }): LayoutRect {\n const ctx = useContext(LayoutContext);\n const [layout, setLayout] = useState<LayoutRect>(DEFAULT_RECT);\n\n useEffect(() => {\n if (!ctx || !nodeRef?.current) return;\n setLayout(ctx.getLayout(nodeRef.current));\n return ctx.subscribe(nodeRef.current, setLayout);\n }, [ctx, nodeRef]);\n\n return layout;\n}\n","import { useContext, useEffect } from \"react\";\nimport { InputContext } from \"./context.js\";\nimport type { Key } from \"../types/index.js\";\n\nexport function useInput(\n handler: (key: Key) => void,\n deps: any[] = [],\n): void {\n const ctx = useContext(InputContext);\n\n useEffect(() => {\n if (!ctx) return;\n return ctx.subscribe(handler);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [ctx, ...deps]);\n}\n","import React, { useRef, useState, useCallback, useEffect, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { useLayout } from \"../hooks/useLayout.js\";\nimport { useInput } from \"../hooks/useInput.js\";\nimport { FocusContext, LayoutContext, ScrollViewContext } from \"../hooks/context.js\";\nimport type { ScrollViewContextValue, ScrollViewBounds } from \"../hooks/context.js\";\n\nexport interface ScrollViewProps {\n children?: ReactNode;\n style?: Style;\n /** Controlled scroll offset (rows from top) */\n scrollOffset?: number;\n /** Callback when scroll offset should change (controlled mode) */\n onScroll?: (offset: number) => void;\n /** Initial offset for uncontrolled mode */\n defaultScrollOffset?: number;\n /** Lines to scroll per arrow key press (default: 1) */\n scrollStep?: number;\n /** Disable keyboard scrolling */\n disableKeyboard?: boolean;\n /** Auto-scroll to focused element (default: true) */\n scrollToFocus?: boolean;\n /** Show scrollbar when content is scrollable (default: true) */\n showScrollbar?: boolean;\n /** Make ScrollView itself focusable. Default: true. Set to false if you want scroll to follow child focus only. */\n focusable?: boolean;\n /** Style applied when ScrollView is focused */\n focusedStyle?: Style;\n}\n\nexport function ScrollView({\n children,\n style,\n scrollOffset: controlledOffset,\n onScroll,\n defaultScrollOffset = 0,\n scrollStep = 1,\n disableKeyboard,\n scrollToFocus = true,\n showScrollbar = true,\n focusable = true,\n focusedStyle,\n}: ScrollViewProps): React.JSX.Element {\n const isControlled = controlledOffset !== undefined;\n const [internalOffset, setInternalOffset] = useState(defaultScrollOffset);\n const offset = isControlled ? controlledOffset : internalOffset;\n\n const viewportRef = useRef<GlyphNode | null>(null);\n const contentRef = useRef<GlyphNode | null>(null);\n const viewportLayout = useLayout(viewportRef);\n const contentLayout = useLayout(contentRef);\n \n const focusCtx = useContext(FocusContext);\n const layoutCtx = useContext(LayoutContext);\n\n // Generate stable focus ID for this ScrollView if focusable\n const focusIdRef = useRef<string | null>(null);\n if (focusable && !focusIdRef.current) {\n focusIdRef.current = `scrollview-${Math.random().toString(36).slice(2, 9)}`;\n }\n const focusId = focusable ? focusIdRef.current : null;\n\n // Register with focus system if focusable\n useEffect(() => {\n if (!focusable || !focusId || !focusCtx || !viewportRef.current) return;\n return focusCtx.register(focusId, viewportRef.current);\n }, [focusable, focusId, focusCtx]);\n\n // Check if this ScrollView is directly focused\n const isSelfFocused = focusable && focusId && focusCtx?.focusedId === focusId;\n\n const viewportHeight = viewportLayout.innerHeight;\n const contentHeight = contentLayout.height;\n const maxOffset = Math.max(0, contentHeight - viewportHeight);\n\n // Always clamp the effective offset used for rendering\n const effectiveOffset = Math.max(0, Math.min(offset, maxOffset));\n\n // Provide ScrollView context for children (e.g., Select) to know their boundaries\n const scrollViewContextValue = useMemo((): ScrollViewContextValue => ({\n getBounds: (): ScrollViewBounds => {\n const viewportY = viewportLayout.y;\n return {\n visibleTop: viewportY,\n visibleBottom: viewportY + viewportHeight,\n viewportHeight,\n scrollOffset: effectiveOffset,\n };\n },\n }), [viewportLayout.y, viewportHeight, effectiveOffset]);\n\n const setOffset = useCallback(\n (next: number) => {\n const clamped = Math.max(0, Math.min(next, maxOffset));\n if (isControlled) {\n onScroll?.(clamped);\n } else {\n setInternalOffset(clamped);\n }\n },\n [isControlled, onScroll, maxOffset],\n );\n\n // Re-clamp when content/viewport changes\n useEffect(() => {\n if (offset > maxOffset && maxOffset >= 0) {\n setOffset(maxOffset);\n }\n }, [offset, maxOffset, setOffset]);\n\n // Focus-aware scrolling: scroll to make focused element visible\n useEffect(() => {\n if (!scrollToFocus || !focusCtx || !layoutCtx || !contentRef.current) return;\n\n const unsubscribe = focusCtx.onFocusChange((focusedId) => {\n if (!focusedId || !contentRef.current) return;\n\n // Find the focused node by walking the content tree\n const findNode = (node: GlyphNode): GlyphNode | null => {\n if (node.focusId === focusedId) return node;\n for (const child of node.children) {\n const found = findNode(child);\n if (found) return found;\n }\n return null;\n };\n\n const focusedNode = findNode(contentRef.current);\n if (!focusedNode) return; // Focused element is not inside this ScrollView\n\n // Get layout of focused element relative to content\n const focusedLayout = layoutCtx.getLayout(focusedNode);\n const contentTopY = contentRef.current.layout?.y ?? 0;\n \n // Calculate element position relative to content top\n const elementTop = focusedLayout.y - contentTopY;\n const elementBottom = elementTop + focusedLayout.height;\n \n // Current visible range\n const visibleTop = offset;\n const visibleBottom = offset + viewportHeight;\n \n // Check if element is fully visible\n if (elementTop < visibleTop) {\n // Element is above visible area - scroll up\n setOffset(elementTop);\n } else if (elementBottom > visibleBottom) {\n // Element is below visible area - scroll down\n setOffset(elementBottom - viewportHeight);\n }\n });\n\n return unsubscribe;\n }, [scrollToFocus, focusCtx, layoutCtx, offset, viewportHeight, setOffset]);\n\n // Check if this ScrollView contains the currently focused element (or is itself focused)\n const containsFocus = useCallback((): boolean => {\n if (!focusCtx) return false;\n const currentFocusId = focusCtx.focusedId;\n if (!currentFocusId) return false;\n\n // Check if ScrollView itself is focused\n if (focusable && focusId && currentFocusId === focusId) return true;\n\n // Walk the content tree to find if focused element is inside\n if (!contentRef.current) return false;\n const findNode = (node: GlyphNode): boolean => {\n if (node.focusId === currentFocusId) return true;\n for (const child of node.children) {\n if (findNode(child)) return true;\n }\n return false;\n };\n\n return findNode(contentRef.current);\n }, [focusCtx, focusable, focusId]);\n\n useInput((key: Key) => {\n if (disableKeyboard) return;\n\n // Only respond to scroll keys if this ScrollView contains focus\n // This prevents multiple ScrollViews from all scrolling at once\n if (!containsFocus()) return;\n\n const halfPage = Math.max(1, Math.floor(viewportHeight / 2));\n const fullPage = Math.max(1, viewportHeight);\n\n // Check if a text input is likely focused (skip conflicting vim keys)\n // We use Page Up/Down which never conflict with text inputs\n \n switch (key.name) {\n // Page keys - always safe, inputs don't use these\n case \"pageup\":\n setOffset(offset - fullPage);\n break;\n case \"pagedown\":\n setOffset(offset + fullPage);\n break;\n default:\n // Ctrl combinations that don't conflict with input editing\n if (key.ctrl) {\n if (key.name === \"d\") {\n // Ctrl+D - half page down\n setOffset(offset + halfPage);\n } else if (key.name === \"u\") {\n // Ctrl+U - half page up\n setOffset(offset - halfPage);\n } else if (key.name === \"f\") {\n // Ctrl+F - full page down\n setOffset(offset + fullPage);\n } else if (key.name === \"b\") {\n // Ctrl+B - full page up\n setOffset(offset - fullPage);\n }\n }\n break;\n }\n }, [offset, scrollStep, viewportHeight, maxOffset, disableKeyboard, setOffset, containsFocus]);\n\n // Extract padding from the user style — it must live on the inner content\n // wrapper, not the outer viewport. The clip region is the outer box's\n // *content area* (after border + padding). The inner absolute child is\n // positioned relative to the *padding box* (after border only). If padding\n // stays on the outer box, the first columns/rows of content fall outside the\n // clip and get cut off.\n const {\n padding: _pad,\n paddingX: _px,\n paddingY: _py,\n paddingTop: _pt,\n paddingRight: _pr,\n paddingBottom: _pb,\n paddingLeft: _pl,\n ...styleRest\n } = style ?? {};\n\n // Calculate intrinsic height (content + border if any)\n const hasBorder = styleRest.border != null && styleRest.border !== \"none\";\n const borderHeight = hasBorder ? 2 : 0;\n const intrinsicHeight = contentHeight > 0 ? contentHeight + borderHeight : undefined;\n \n // Outer viewport style:\n // - If no explicit height set by user, use content height as intrinsic size\n // - flexShrink: 1 allows shrinking when parent constrains (e.g., maxHeight)\n // - minHeight: 0 allows shrinking to any size\n // - clip: true enables content clipping for scrolling\n const outerStyle: Style = {\n ...styleRest,\n ...(isSelfFocused ? focusedStyle : {}),\n clip: true,\n // Only set intrinsic height if user didn't set explicit height\n ...(styleRest.height === undefined && intrinsicHeight !== undefined\n ? {\n height: intrinsicHeight,\n flexShrink: styleRest.flexShrink ?? 1,\n minHeight: styleRest.minHeight ?? 0,\n }\n : {}),\n };\n\n // Inner content: absolutely positioned to fill viewport width,\n // shifted up by scrollOffset. Padding lives here so text is indented\n // without being clipped.\n const innerStyle: Style = {\n position: \"absolute\" as const,\n top: -effectiveOffset,\n left: 0,\n right: 0,\n flexDirection: \"column\" as const,\n ...(_pad !== undefined && { padding: _pad }),\n ...(_px !== undefined && { paddingX: _px }),\n ...(_py !== undefined && { paddingY: _py }),\n ...(_pt !== undefined && { paddingTop: _pt }),\n ...(_pr !== undefined && { paddingRight: _pr }),\n ...(_pb !== undefined && { paddingBottom: _pb }),\n ...(_pl !== undefined && { paddingLeft: _pl }),\n };\n\n // Calculate scrollbar dimensions\n const isScrollable = contentHeight > viewportHeight && viewportHeight > 0;\n const scrollbarVisible = showScrollbar && isScrollable;\n \n // Scrollbar thumb size and position\n const thumbHeight = Math.max(1, Math.floor((viewportHeight / contentHeight) * viewportHeight));\n const scrollableRange = contentHeight - viewportHeight;\n const thumbPosition = scrollableRange > 0 \n ? Math.floor((effectiveOffset / scrollableRange) * (viewportHeight - thumbHeight))\n : 0;\n\n // Build scrollbar characters\n const scrollbarChars: string[] = [];\n if (scrollbarVisible) {\n for (let i = 0; i < viewportHeight; i++) {\n if (i >= thumbPosition && i < thumbPosition + thumbHeight) {\n scrollbarChars.push(\"█\");\n } else {\n scrollbarChars.push(\"░\");\n }\n }\n }\n\n // Scrollbar style - positioned on the right edge\n const scrollbarStyle: Style = {\n position: \"absolute\" as const,\n top: 0,\n right: 0,\n width: 1,\n height: viewportHeight,\n flexDirection: \"column\" as const,\n };\n\n return React.createElement(\n ScrollViewContext.Provider,\n { value: scrollViewContextValue },\n React.createElement(\n \"box\" as any,\n {\n style: outerStyle,\n ref: (node: any) => {\n viewportRef.current = node ?? null;\n },\n ...(focusable ? { focusable: true, focusId } : {}),\n },\n // Content (absolutely positioned, scrolls via top offset)\n React.createElement(\n \"box\" as any,\n {\n style: {\n ...innerStyle,\n // Reserve space for scrollbar when visible\n paddingRight: scrollbarVisible ? (innerStyle.paddingRight ?? 0) + 1 : innerStyle.paddingRight,\n },\n ref: (node: any) => {\n contentRef.current = node ?? null;\n },\n },\n children,\n ),\n // Scrollbar\n scrollbarVisible && React.createElement(\n \"box\" as any,\n { style: scrollbarStyle },\n React.createElement(\n \"text\" as any,\n { style: { color: \"blackBright\" as const } },\n scrollbarChars.join(\"\\n\"),\n ),\n ),\n ),\n );\n}\n","import React, { useContext, useEffect, useRef, useState, useCallback } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { FocusContext, InputContext } from \"../hooks/context.js\";\n\nexport interface ListItemInfo {\n index: number;\n selected: boolean;\n focused: boolean;\n}\n\nexport interface ListProps {\n /** Total number of items */\n count: number;\n /** Render function for each item */\n renderItem: (info: ListItemInfo) => ReactNode;\n /** Controlled selected index */\n selectedIndex?: number;\n /** Callback when selected index should change */\n onSelectionChange?: (index: number) => void;\n /** Callback when enter is pressed on selected item */\n onSelect?: (index: number) => void;\n /** Initial index for uncontrolled mode */\n defaultSelectedIndex?: number;\n /** Set of disabled indices that are skipped during navigation */\n disabledIndices?: Set<number>;\n /** Outer box style */\n style?: Style;\n /** Whether the list is focusable (default: true) */\n focusable?: boolean;\n}\n\nexport function List({\n count,\n renderItem,\n selectedIndex: controlledIndex,\n onSelectionChange,\n onSelect,\n defaultSelectedIndex = 0,\n disabledIndices,\n style,\n focusable = true,\n}: ListProps): React.JSX.Element {\n const isControlled = controlledIndex !== undefined;\n const [internalIndex, setInternalIndex] = useState(defaultSelectedIndex);\n const selectedIndex = isControlled ? controlledIndex : internalIndex;\n\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onSelectRef = useRef(onSelect);\n onSelectRef.current = onSelect;\n\n // Track when node is mounted with a valid focusId\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const lastKeyRef = useRef<string | null>(null);\n\n const setIndex = useCallback(\n (next: number) => {\n const clamped = Math.max(0, Math.min(next, count - 1));\n if (isControlled) {\n onSelectionChange?.(clamped);\n } else {\n setInternalIndex(clamped);\n }\n },\n [isControlled, onSelectionChange, count],\n );\n\n // Find next non-disabled index in given direction\n const findNextEnabled = useCallback(\n (from: number, direction: 1 | -1): number => {\n if (!disabledIndices || disabledIndices.size === 0) {\n return Math.max(0, Math.min(from + direction, count - 1));\n }\n let next = from + direction;\n while (next >= 0 && next < count && disabledIndices.has(next)) {\n next += direction;\n }\n if (next < 0 || next >= count) return from; // stay put\n return next;\n },\n [disabledIndices, count],\n );\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || !focusable) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, focusable, nodeReady]);\n\n // Subscribe to focus changes\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Find first non-disabled index from start or end\n const findFirstEnabled = useCallback(\n (fromEnd: boolean): number => {\n const start = fromEnd ? count - 1 : 0;\n const direction = fromEnd ? -1 : 1;\n let index = start;\n while (index >= 0 && index < count && disabledIndices?.has(index)) {\n index += direction;\n }\n return index >= 0 && index < count ? index : (fromEnd ? count - 1 : 0);\n },\n [disabledIndices, count],\n );\n\n // Handle keyboard when focused\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || !focusable) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n\n // gg - go to top (requires two consecutive 'g' presses)\n if (key.name === \"g\" && !key.ctrl && !key.alt) {\n if (lastKeyRef.current === \"g\") {\n setIndex(findFirstEnabled(false));\n lastKeyRef.current = null;\n return true;\n }\n lastKeyRef.current = \"g\";\n return true;\n }\n\n // G - go to bottom\n if (key.name === \"G\" || (key.name === \"g\" && key.shift)) {\n lastKeyRef.current = null;\n setIndex(findFirstEnabled(true));\n return true;\n }\n\n // Clear lastKey for any other key\n lastKeyRef.current = null;\n\n // Up / k - move up\n if (key.name === \"up\" || key.name === \"k\") {\n setIndex(findNextEnabled(selectedIndex, -1));\n return true;\n }\n\n // Down / j - move down\n if (key.name === \"down\" || key.name === \"j\") {\n setIndex(findNextEnabled(selectedIndex, 1));\n return true;\n }\n\n // Enter - select\n if (key.name === \"return\") {\n if (!(disabledIndices?.has(selectedIndex))) {\n onSelectRef.current?.(selectedIndex);\n }\n return true;\n }\n\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, focusable, selectedIndex, setIndex, findNextEnabled, findFirstEnabled, disabledIndices, nodeReady]);\n\n // Render items\n const items: ReactNode[] = [];\n for (let i = 0; i < count; i++) {\n items.push(\n React.createElement(React.Fragment, { key: i },\n renderItem({ index: i, selected: i === selectedIndex, focused: isFocused }),\n ),\n );\n }\n\n return React.createElement(\n \"box\" as any,\n {\n style: { flexDirection: \"column\" as const, ...style },\n focusable: focusable,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n ...items,\n );\n}\n","import React from \"react\";\nimport type { Style, Color } from \"../types/index.js\";\nimport { List } from \"./List.js\";\n\nexport interface MenuItem {\n label: string;\n value: string;\n disabled?: boolean;\n}\n\nexport interface MenuProps {\n items: MenuItem[];\n /** Controlled selected index */\n selectedIndex?: number;\n /** Callback when selected index changes */\n onSelectionChange?: (index: number) => void;\n /** Callback when enter is pressed on item */\n onSelect?: (value: string, index: number) => void;\n /** Initial index for uncontrolled mode */\n defaultSelectedIndex?: number;\n /** Outer box style */\n style?: Style;\n /** Color for the selected item indicator and text (default: \"cyan\") */\n highlightColor?: Color;\n /** Whether the menu is focusable (default: true) */\n focusable?: boolean;\n}\n\nexport function Menu({\n items,\n selectedIndex,\n onSelectionChange,\n onSelect,\n defaultSelectedIndex = 0,\n style,\n highlightColor = \"cyan\",\n focusable = true,\n}: MenuProps): React.JSX.Element {\n const disabledIndices = new Set<number>();\n for (let i = 0; i < items.length; i++) {\n if (items[i]!.disabled) disabledIndices.add(i);\n }\n\n const handleSelect = (index: number) => {\n const item = items[index];\n if (item && !item.disabled) {\n onSelect?.(item.value, index);\n }\n };\n\n return React.createElement(List, {\n count: items.length,\n selectedIndex,\n onSelectionChange,\n onSelect: handleSelect,\n defaultSelectedIndex,\n disabledIndices: disabledIndices.size > 0 ? disabledIndices : undefined,\n style,\n focusable,\n renderItem: ({ index, selected, focused }) => {\n const item = items[index]!;\n const isDisabled = item.disabled;\n const isHighlighted = selected && focused;\n\n const indicator = selected ? \">\" : \" \";\n\n return React.createElement(\n \"box\" as any,\n {\n style: {\n flexDirection: \"row\" as const,\n ...(isHighlighted ? { bg: highlightColor } : {}),\n },\n },\n React.createElement(\n \"text\" as any,\n {\n style: isHighlighted\n ? { bold: true, color: \"black\" }\n : isDisabled\n ? { dim: true }\n : {},\n },\n `${indicator} ${item.label}`,\n ),\n );\n },\n });\n}\n","import React, { useRef, useState, useEffect } from \"react\";\nimport type { Style, DimensionValue } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { useLayout } from \"../hooks/useLayout.js\";\n\nexport interface ProgressProps {\n /** Progress value 0..1. Omit when indeterminate. */\n value?: number;\n /** Animate as indeterminate (marquee). Default false. */\n indeterminate?: boolean;\n /** Width of the progress bar. Default \"100%\". */\n width?: DimensionValue;\n /** Optional label text displayed before the bar. */\n label?: string;\n /** Show percentage text after the bar. Default false. */\n showPercent?: boolean;\n /** Outer container style. */\n style?: Style;\n /** Character(s) for the filled portion. Default \"█\". */\n filled?: string;\n /** Character(s) for the empty portion. Default \"░\". */\n empty?: string;\n}\n\nexport function Progress({\n value,\n indeterminate = false,\n width = \"100%\",\n label,\n showPercent = false,\n style,\n filled = \"█\",\n empty = \"░\",\n}: ProgressProps): React.JSX.Element {\n const trackRef = useRef<GlyphNode | null>(null);\n const trackLayout = useLayout(trackRef);\n const trackWidth = trackLayout.innerWidth;\n\n // Indeterminate animation state\n const [indeterminatePos, setIndeterminatePos] = useState(0);\n\n useEffect(() => {\n if (!indeterminate) return;\n const timer = setInterval(() => {\n setIndeterminatePos((p) => (p + 1) % Math.max(1, trackWidth + 6));\n }, 100);\n return () => clearInterval(timer);\n }, [indeterminate, trackWidth]);\n\n const clamped = Math.max(0, Math.min(1, value ?? 0));\n const pctText = showPercent ? ` ${Math.round(clamped * 100)}%` : \"\";\n\n let barText = \"\";\n if (trackWidth > 0) {\n if (indeterminate && value === undefined) {\n // Marquee: a 3-char chunk bouncing across the track\n const chunkSize = Math.max(1, Math.min(3, Math.floor(trackWidth / 4)));\n const chars: string[] = [];\n for (let i = 0; i < trackWidth; i++) {\n if (i >= indeterminatePos - chunkSize && i < indeterminatePos) {\n chars.push(filled);\n } else {\n chars.push(empty);\n }\n }\n barText = chars.join(\"\");\n } else {\n const filledCount = Math.round(clamped * trackWidth);\n barText = filled.repeat(filledCount) + empty.repeat(trackWidth - filledCount);\n }\n }\n\n const children: React.ReactNode[] = [];\n\n if (label) {\n children.push(\n React.createElement(\"text\" as any, { key: \"label\", style: { bold: true } }, label + \" \"),\n );\n }\n\n children.push(\n React.createElement(\n \"box\" as any,\n {\n key: \"track\",\n style: { flexGrow: 1, flexShrink: 1 },\n ref: (node: any) => { trackRef.current = node ?? null; },\n },\n React.createElement(\"text\" as any, { key: \"bar\", style: {} }, barText),\n ),\n );\n\n if (showPercent) {\n children.push(\n React.createElement(\"text\" as any, { key: \"pct\", style: { bold: true } }, pctText),\n );\n }\n\n return React.createElement(\n \"box\" as any,\n {\n style: {\n flexDirection: \"row\" as const,\n width,\n ...style,\n },\n },\n ...children,\n );\n}\n","import React, { useState, useEffect } from \"react\";\nimport type { Style } from \"../types/index.js\";\n\nconst BRAILLE_FRAMES = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\n\nexport interface SpinnerProps {\n /** Animation frames. Defaults to braille dots. */\n frames?: string[];\n /** Interval between frames in ms. Default 80. */\n intervalMs?: number;\n /** Optional label text next to the spinner. */\n label?: string;\n /** Style applied to the spinner character. */\n style?: Style;\n}\n\nexport function Spinner({\n frames = BRAILLE_FRAMES,\n intervalMs = 80,\n label,\n style,\n}: SpinnerProps): React.JSX.Element {\n const [frameIndex, setFrameIndex] = useState(0);\n\n useEffect(() => {\n const timer = setInterval(() => {\n setFrameIndex((i) => (i + 1) % frames.length);\n }, intervalMs);\n return () => clearInterval(timer);\n }, [frames.length, intervalMs]);\n\n const children: React.ReactNode[] = [\n React.createElement(\"text\" as any, { key: \"frame\", style }, frames[frameIndex]),\n ];\n\n if (label) {\n children.push(\n React.createElement(\"text\" as any, { key: \"label\", style: {} }, \" \" + label),\n );\n }\n\n return React.createElement(\n \"box\" as any,\n { style: { flexDirection: \"row\" as const } },\n ...children,\n );\n}\n","import React, { createContext, useContext, useState, useCallback, useEffect, useRef } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Color } from \"../types/index.js\";\n\n// ---- Types ----\n\nexport type ToastVariant = \"info\" | \"success\" | \"warning\" | \"error\";\n\nexport interface Toast {\n id: string;\n message: string;\n title?: string;\n variant?: ToastVariant;\n durationMs?: number;\n}\n\nexport type ToastPosition = \"top-right\" | \"top-left\" | \"bottom-right\" | \"bottom-left\";\n\nexport interface ToastHostProps {\n /** Where toasts appear. Default \"bottom-right\". */\n position?: ToastPosition;\n /** Max visible toasts. Default 5. */\n maxVisible?: number;\n children?: ReactNode;\n}\n\n// ---- Context ----\n\ninterface ToastContextValue {\n push(toast: Omit<Toast, \"id\">): void;\n}\n\nconst ToastContext = createContext<ToastContextValue | null>(null);\n\nlet nextToastId = 0;\n\n// ---- Hook ----\n\nexport function useToast(): (toast: Omit<Toast, \"id\">) => void {\n const ctx = useContext(ToastContext);\n if (!ctx) throw new Error(\"useToast must be used within a <ToastHost>\");\n return ctx.push;\n}\n\n// ---- Variant colors ----\n\nconst VARIANT_COLORS: Record<ToastVariant, { bg: Color; title: Color; text: Color }> = {\n info: { bg: \"blackBright\", title: \"cyanBright\", text: \"white\" },\n success: { bg: \"blackBright\", title: \"greenBright\", text: \"white\" },\n warning: { bg: \"blackBright\", title: \"yellowBright\", text: \"white\" },\n error: { bg: \"blackBright\", title: \"redBright\", text: \"white\" },\n};\n\n// ---- ToastHost ----\n\nexport function ToastHost({\n position = \"bottom-right\",\n maxVisible = 5,\n children,\n}: ToastHostProps): React.JSX.Element {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());\n\n const push = useCallback((toast: Omit<Toast, \"id\">) => {\n const id = `toast-${nextToastId++}`;\n const full: Toast = { id, durationMs: 3000, variant: \"info\", ...toast };\n setToasts((prev) => [...prev, full]);\n\n if (full.durationMs && full.durationMs > 0) {\n const timer = setTimeout(() => {\n timersRef.current.delete(id);\n setToasts((prev) => prev.filter((t) => t.id !== id));\n }, full.durationMs);\n timersRef.current.set(id, timer);\n }\n }, []);\n\n // Cleanup all timers on unmount\n useEffect(() => {\n return () => {\n for (const timer of timersRef.current.values()) {\n clearTimeout(timer);\n }\n timersRef.current.clear();\n };\n }, []);\n\n const ctxValue = useRef({ push });\n ctxValue.current.push = push;\n\n // Position styles\n const isTop = position.startsWith(\"top\");\n const isRight = position.endsWith(\"right\");\n\n const portalStyle: Style = {\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n height: \"100%\",\n zIndex: 900,\n flexDirection: \"column\",\n justifyContent: isTop ? \"flex-start\" : \"flex-end\",\n alignItems: isRight ? \"flex-end\" : \"flex-start\",\n padding: 1,\n };\n\n const visible = toasts.slice(-maxVisible);\n\n const toastElements = visible.map((toast) => {\n const variant = toast.variant ?? \"info\";\n const colors = VARIANT_COLORS[variant];\n\n const innerChildren: ReactNode[] = [];\n\n if (toast.title) {\n innerChildren.push(\n React.createElement(\"text\" as any, {\n key: \"title\",\n style: { bold: true, color: colors.title },\n }, toast.title),\n );\n }\n\n innerChildren.push(\n React.createElement(\"text\" as any, {\n key: \"msg\",\n style: { color: colors.text },\n }, toast.message),\n );\n\n return React.createElement(\n \"box\" as any,\n {\n key: toast.id,\n style: {\n bg: colors.bg,\n paddingX: 1,\n flexDirection: \"column\" as const,\n minWidth: 20,\n maxWidth: 50,\n },\n },\n ...innerChildren,\n );\n });\n\n return React.createElement(\n ToastContext.Provider,\n { value: ctxValue.current },\n children,\n toastElements.length > 0\n ? React.createElement(\"box\" as any, { style: portalStyle }, ...toastElements)\n : null,\n );\n}\n","import React, {\n useContext,\n useEffect,\n useRef,\n useState,\n useCallback,\n useMemo,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key, Color } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { FocusContext, InputContext, AppContext, ScrollViewContext } from \"../hooks/context.js\";\nimport { useLayout } from \"../hooks/useLayout.js\";\n\nexport interface SelectItem {\n label: string;\n value: string;\n disabled?: boolean;\n}\n\nexport interface SelectProps {\n /** List of selectable items */\n items: SelectItem[];\n /** Currently selected value (controlled) */\n value?: string;\n /** Callback when selection changes */\n onChange?: (value: string) => void;\n /** Placeholder text when nothing is selected */\n placeholder?: string;\n /** Trigger box style */\n style?: Style;\n /** Trigger style when focused */\n focusedStyle?: Style;\n /** Dropdown overlay style overrides */\n dropdownStyle?: Style;\n /** Highlight color for the selected item in the dropdown (default: \"cyan\") */\n highlightColor?: Color;\n /** Max visible items in the dropdown before scrolling (default: 8) */\n maxVisible?: number;\n /** Enable type-to-filter when dropdown is open (default: true) */\n searchable?: boolean;\n /** Disabled state */\n disabled?: boolean;\n}\n\nexport function Select({\n items,\n value,\n onChange,\n placeholder = \"Select...\",\n style,\n focusedStyle,\n dropdownStyle,\n highlightColor = \"cyan\",\n maxVisible = 8,\n searchable = true,\n disabled,\n}: SelectProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const appCtx = useContext(AppContext);\n const scrollViewCtx = useContext(ScrollViewContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n\n // Track when node is mounted with a valid focusId - this triggers effect re-runs\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [isOpen, setIsOpen] = useState(false);\n const [highlightIndex, setHighlightIndex] = useState(0);\n const [searchText, setSearchText] = useState(\"\");\n const [scrollOffset, setScrollOffset] = useState(0);\n\n const triggerLayout = useLayout(nodeRef);\n const screenRows = appCtx?.rows ?? 24;\n \n // Get ScrollView bounds if we're inside one\n const scrollViewBounds = scrollViewCtx?.getBounds();\n\n // Selected item label\n const selectedItem = items.find((item) => item.value === value);\n const selectedLabel = selectedItem?.label ?? \"\";\n\n // Filter items based on search\n const filteredItems = useMemo(() => {\n if (!searchText) return items;\n const lower = searchText.toLowerCase();\n return items.filter((item) => item.label.toLowerCase().includes(lower));\n }, [items, searchText]);\n\n // Visible slice\n const visibleCount = Math.min(maxVisible, filteredItems.length);\n const visibleItems = filteredItems.slice(\n scrollOffset,\n scrollOffset + visibleCount,\n );\n\n // Reset highlight and scroll when filter changes\n useEffect(() => {\n setHighlightIndex(0);\n setScrollOffset(0);\n }, [searchText]);\n\n // Close dropdown when focus is lost\n useEffect(() => {\n if (!isFocused && isOpen) {\n setIsOpen(false);\n setSearchText(\"\");\n }\n }, [isFocused, isOpen]);\n\n // --- Focus registration ---\n // Always register on mount to maintain position in tab order\n // nodeReady triggers re-run when ref callback fires\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, nodeReady]);\n \n // Mark as skippable when disabled - Tab will skip this element\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n focusCtx.setSkippable(focusIdRef.current, !!disabled);\n }, [focusCtx, disabled, nodeReady]);\n\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Find next non-disabled index\n const findNextEnabled = useCallback(\n (from: number, direction: 1 | -1): number => {\n let next = from + direction;\n while (next >= 0 && next < filteredItems.length) {\n if (!filteredItems[next]!.disabled) return next;\n next += direction;\n }\n return from;\n },\n [filteredItems],\n );\n\n // Scroll to keep highlight visible\n const ensureVisible = useCallback(\n (index: number) => {\n if (index < scrollOffset) {\n setScrollOffset(index);\n } else if (index >= scrollOffset + visibleCount) {\n setScrollOffset(index - visibleCount + 1);\n }\n },\n [scrollOffset, visibleCount],\n );\n\n // --- Input handler ---\n // nodeReady ensures we re-run when the ref is set after conditional mount\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n\n // --- Closed state ---\n if (!isOpen) {\n if (\n key.name === \"return\" ||\n key.name === \" \" ||\n key.sequence === \" \" ||\n key.name === \"down\"\n ) {\n setIsOpen(true);\n setSearchText(\"\");\n const idx = filteredItems.findIndex((item) => item.value === value);\n const start = idx >= 0 ? idx : 0;\n setHighlightIndex(start);\n setScrollOffset(\n Math.max(0, start - Math.floor(maxVisible / 2)),\n );\n return true;\n }\n return false;\n }\n\n // --- Open state ---\n\n // Tab: close and let focus system handle\n if (key.name === \"tab\") {\n setIsOpen(false);\n setSearchText(\"\");\n return false;\n }\n\n if (key.name === \"escape\") {\n setIsOpen(false);\n setSearchText(\"\");\n return true;\n }\n\n if (key.name === \"return\") {\n const item = filteredItems[highlightIndex];\n if (item && !item.disabled) {\n onChangeRef.current?.(item.value);\n setIsOpen(false);\n setSearchText(\"\");\n }\n return true;\n }\n\n if (key.name === \"up\") {\n const next = findNextEnabled(highlightIndex, -1);\n setHighlightIndex(next);\n ensureVisible(next);\n return true;\n }\n\n if (key.name === \"down\") {\n const next = findNextEnabled(highlightIndex, 1);\n setHighlightIndex(next);\n ensureVisible(next);\n return true;\n }\n\n if (key.name === \"backspace\") {\n if (searchable && searchText.length > 0) {\n setSearchText((prev) => prev.slice(0, -1));\n }\n return true;\n }\n\n if (key.name === \"home\") {\n const first = findNextEnabled(-1, 1);\n setHighlightIndex(first);\n ensureVisible(first);\n return true;\n }\n\n if (key.name === \"end\") {\n const last = findNextEnabled(filteredItems.length, -1);\n setHighlightIndex(last);\n ensureVisible(last);\n return true;\n }\n\n // Printable characters → search filter\n if (\n searchable &&\n key.sequence &&\n key.sequence.length === 1 &&\n !key.ctrl &&\n !key.alt\n ) {\n const ch = key.sequence;\n if (ch >= \" \" && ch <= \"~\") {\n setSearchText((prev) => prev + ch);\n return true;\n }\n }\n\n // Consume all other keys when open\n return true;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [\n inputCtx,\n focusCtx,\n disabled,\n isOpen,\n highlightIndex,\n filteredItems,\n value,\n maxVisible,\n searchable,\n searchText,\n findNextEnabled,\n ensureVisible,\n nodeReady,\n ]);\n\n // --- Trigger ---\n // Only apply default border if user hasn't specified bg (flat style) or their own border\n const useDefaultBorder = !style?.bg && style?.border === undefined;\n const triggerStyle: Style = {\n flexDirection: \"row\",\n width: \"100%\",\n ...(useDefaultBorder ? { border: \"single\" } : {}),\n ...style,\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n const labelColor = selectedLabel\n ? style?.color ?? undefined\n : \"blackBright\";\n\n const triggerChildren: ReactNode[] = [\n React.createElement(\n \"text\" as any,\n {\n key: \"label\",\n style: {\n flexGrow: 1,\n flexShrink: 1,\n color: labelColor,\n wrap: \"ellipsis\",\n ...(selectedLabel ? {} : { dim: true }),\n },\n },\n selectedLabel || placeholder,\n ),\n React.createElement(\n \"text\" as any,\n {\n key: \"arrow\",\n style: { flexShrink: 0, color: isFocused ? highlightColor : \"blackBright\" },\n },\n isOpen ? \" ▲\" : \" ▼\",\n ),\n ];\n\n // --- Dropdown ---\n let dropdownElement: ReactNode = null;\n\n if (isOpen) {\n const dropdownChildren: ReactNode[] = [];\n\n // Search indicator\n if (searchable && searchText) {\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n { key: \"search\", style: { paddingX: 1 } },\n React.createElement(\n \"text\" as any,\n { style: { color: \"blackBright\", dim: true } },\n `/${searchText}`,\n ),\n ),\n );\n }\n\n // No results\n if (filteredItems.length === 0) {\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n { key: \"empty\", style: { paddingX: 1 } },\n React.createElement(\n \"text\" as any,\n { style: { dim: true, color: \"blackBright\" } },\n \"No matches\",\n ),\n ),\n );\n }\n\n // Scroll up indicator\n if (scrollOffset > 0) {\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n {\n key: \"scroll-up\",\n style: { justifyContent: \"center\", alignItems: \"center\" },\n },\n React.createElement(\n \"text\" as any,\n { style: { dim: true, color: \"blackBright\" } },\n \"▲\",\n ),\n ),\n );\n }\n\n // Visible items\n visibleItems.forEach((item, vi) => {\n const actualIndex = scrollOffset + vi;\n const isHighlighted = actualIndex === highlightIndex;\n const isDisabled = item.disabled;\n\n const itemStyle: Style = {\n paddingX: 1,\n ...(isHighlighted && !isDisabled ? { bg: highlightColor } : {}),\n };\n\n const textStyle: Style = {\n ...(isHighlighted && !isDisabled\n ? { color: \"black\", bold: true }\n : {}),\n ...(isDisabled ? { dim: true, color: \"blackBright\" } : {}),\n };\n\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n { key: `item-${item.value}`, style: itemStyle },\n React.createElement(\n \"text\" as any,\n { style: textStyle },\n item.label,\n ),\n ),\n );\n });\n\n // Scroll down indicator\n if (scrollOffset + visibleCount < filteredItems.length) {\n dropdownChildren.push(\n React.createElement(\n \"box\" as any,\n {\n key: \"scroll-down\",\n style: { justifyContent: \"center\", alignItems: \"center\" },\n },\n React.createElement(\n \"text\" as any,\n { style: { dim: true, color: \"blackBright\" } },\n \"▼\",\n ),\n ),\n );\n }\n\n // Calculate dropdown height (items + border + scroll indicators + search)\n const hasScrollUp = scrollOffset > 0;\n const hasScrollDown = scrollOffset + visibleCount < filteredItems.length;\n const hasSearch = searchable && searchText;\n const hasNoMatches = filteredItems.length === 0;\n \n // Only apply default border if user hasn't specified their own dropdown style\n const useDropdownBorder = !dropdownStyle?.bg && dropdownStyle?.border === undefined;\n const borderSize = useDropdownBorder ? 2 : 0; // top + bottom border\n \n let dropdownHeight = visibleCount + borderSize;\n if (hasScrollUp) dropdownHeight += 1;\n if (hasScrollDown) dropdownHeight += 1;\n if (hasSearch) dropdownHeight += 1;\n if (hasNoMatches) dropdownHeight += 1;\n \n // Determine if we should open upward\n // Consider ScrollView bounds if inside one, otherwise use screen bounds\n const triggerBottom = triggerLayout.y + triggerLayout.height;\n \n let spaceBelow: number;\n let spaceAbove: number;\n \n if (scrollViewBounds) {\n // Inside ScrollView - use ScrollView's visible bounds\n spaceBelow = scrollViewBounds.visibleBottom - triggerBottom;\n spaceAbove = triggerLayout.y - scrollViewBounds.visibleTop;\n } else {\n // Not inside ScrollView - use screen bounds\n spaceBelow = screenRows - triggerBottom;\n spaceAbove = triggerLayout.y;\n }\n \n // Open upward if not enough space below but enough above\n const openUpward = spaceBelow < dropdownHeight && spaceAbove >= dropdownHeight;\n \n const dropdownTop = openUpward \n ? -(dropdownHeight) \n : (triggerLayout.height || 1);\n\n dropdownElement = React.createElement(\n \"box\" as any,\n {\n style: {\n position: \"absolute\" as const,\n top: dropdownTop,\n left: 0,\n right: 0,\n zIndex: 9999,\n ...(useDropdownBorder ? { border: \"single\" as const } : {}),\n bg: \"black\" as const,\n flexDirection: \"column\" as const,\n ...dropdownStyle,\n },\n },\n ...dropdownChildren,\n );\n }\n\n // --- Render ---\n // Extract width/flex properties for outer wrapper\n // Default to filling available space if no explicit width is set\n const outerStyle: Style = {\n flexDirection: \"column\" as const,\n width: triggerStyle.width ?? \"100%\",\n minWidth: triggerStyle.minWidth,\n maxWidth: triggerStyle.maxWidth,\n flexGrow: triggerStyle.flexGrow,\n flexShrink: triggerStyle.flexShrink ?? 1,\n };\n\n return React.createElement(\n \"box\" as any,\n { style: outerStyle },\n // Trigger\n React.createElement(\n \"box\" as any,\n {\n style: triggerStyle,\n // Always focusable - disabled state is handled in input handler\n // This ensures focusId is assigned on mount, even if initially disabled\n focusable: true,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n // Trigger effect re-runs now that refs are set\n setNodeReady(true);\n } else {\n // Node unmounted\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n ...triggerChildren,\n ),\n // Dropdown overlay\n dropdownElement,\n );\n}\n","import React, { useContext, useEffect, useRef, useState } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport { FocusContext, InputContext } from \"../hooks/context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface CheckboxProps {\n /** Whether the checkbox is checked */\n checked: boolean;\n /** Called when the checkbox is toggled */\n onChange: (checked: boolean) => void;\n /** Label text displayed next to the checkbox */\n label?: string;\n /** Style for the checkbox container */\n style?: Style;\n /** Style when focused */\n focusedStyle?: Style;\n /** Whether the checkbox is disabled */\n disabled?: boolean;\n /** Custom character for checked state (default: \"✓\") */\n checkedChar?: string;\n /** Custom character for unchecked state (default: \" \") */\n uncheckedChar?: string;\n}\n\nexport function Checkbox({\n checked,\n onChange,\n label,\n style,\n focusedStyle,\n disabled,\n checkedChar = \"✓\",\n uncheckedChar = \" \",\n}: CheckboxProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n const checkedRef = useRef(checked);\n checkedRef.current = checked;\n\n // Track when node is mounted with a valid focusId\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || disabled) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, disabled, nodeReady]);\n\n // Subscribe to focus changes\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Handle space/enter to toggle\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n if (key.name === \"return\" || key.name === \" \" || key.sequence === \" \") {\n onChangeRef.current(!checkedRef.current);\n return true;\n }\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, disabled, nodeReady]);\n\n const mergedStyle: Style = {\n flexDirection: \"row\",\n gap: 1,\n ...style,\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n const boxChar = checked ? checkedChar : uncheckedChar;\n const boxStyle: Style = {\n color: disabled ? \"blackBright\" : (isFocused ? \"white\" : style?.color),\n };\n const labelStyle: Style = {\n color: disabled ? \"blackBright\" : style?.color,\n };\n\n return React.createElement(\n \"box\" as any,\n {\n style: mergedStyle,\n focusable: !disabled,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n React.createElement(\n \"text\" as any,\n { key: \"box\", style: boxStyle },\n `[${boxChar}]`,\n ),\n label\n ? React.createElement(\n \"text\" as any,\n { key: \"label\", style: labelStyle },\n label,\n )\n : null,\n );\n}\n","import React, { useContext, useEffect, useRef, useState, useCallback } from \"react\";\nimport type { Style, Key } from \"../types/index.js\";\nimport { FocusContext, InputContext } from \"../hooks/context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\nexport interface RadioItem<T = string> {\n /** Display label */\n label: string;\n /** Value returned on selection */\n value: T;\n /** Whether this option is disabled */\n disabled?: boolean;\n}\n\nexport interface RadioProps<T = string> {\n /** Radio options */\n items: RadioItem<T>[];\n /** Currently selected value */\n value: T | undefined;\n /** Called when selection changes */\n onChange: (value: T) => void;\n /** Style for the radio group container */\n style?: Style;\n /** Style for each radio item */\n itemStyle?: Style;\n /** Style for the focused item */\n focusedItemStyle?: Style;\n /** Style for the selected item */\n selectedItemStyle?: Style;\n /** Whether the entire group is disabled */\n disabled?: boolean;\n /** Layout direction (default: \"column\") */\n direction?: \"row\" | \"column\";\n /** Gap between items (default: 0) */\n gap?: number;\n /** Custom character for selected state (default: \"●\") */\n selectedChar?: string;\n /** Custom character for unselected state (default: \"○\") */\n unselectedChar?: string;\n}\n\nexport function Radio<T = string>({\n items,\n value,\n onChange,\n style,\n itemStyle,\n focusedItemStyle,\n selectedItemStyle,\n disabled,\n direction = \"column\",\n gap = 0,\n selectedChar = \"●\",\n unselectedChar = \"○\",\n}: RadioProps<T>): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n\n // Track when node is mounted with a valid focusId\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [highlightedIndex, setHighlightedIndex] = useState(() => {\n // Initialize to the selected item or first enabled item\n const selectedIdx = items.findIndex((item) => item.value === value);\n if (selectedIdx >= 0) return selectedIdx;\n return items.findIndex((item) => !item.disabled);\n });\n\n // Find next/prev enabled item\n const findNextEnabled = useCallback(\n (startIndex: number, direction: 1 | -1): number => {\n let index = startIndex;\n for (let i = 0; i < items.length; i++) {\n index = (index + direction + items.length) % items.length;\n if (!items[index]?.disabled) return index;\n }\n return startIndex;\n },\n [items],\n );\n\n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || disabled) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx, disabled, nodeReady]);\n\n // Subscribe to focus changes\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n setIsFocused(focusCtx.focusedId === fid);\n return focusCtx.onFocusChange((newId) => {\n setIsFocused(newId === fid);\n });\n }, [focusCtx, nodeReady]);\n\n // Handle keyboard navigation\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n\n // Previous: up, left, k, shift+tab\n if (\n key.name === \"up\" ||\n key.name === \"left\" ||\n key.name === \"k\" ||\n (key.name === \"tab\" && key.shift)\n ) {\n setHighlightedIndex((idx) => findNextEnabled(idx, -1));\n return true;\n }\n\n // Next: down, right, j, tab\n if (\n key.name === \"down\" ||\n key.name === \"right\" ||\n key.name === \"j\" ||\n (key.name === \"tab\" && !key.shift)\n ) {\n setHighlightedIndex((idx) => findNextEnabled(idx, 1));\n return true;\n }\n\n // Select current item\n if (key.name === \"return\" || key.name === \" \" || key.sequence === \" \") {\n const item = items[highlightedIndex];\n if (item && !item.disabled) {\n onChangeRef.current(item.value);\n }\n return true;\n }\n\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, disabled, items, highlightedIndex, findNextEnabled, nodeReady]);\n\n // Sync highlighted index when value changes externally\n useEffect(() => {\n const selectedIdx = items.findIndex((item) => item.value === value);\n if (selectedIdx >= 0) {\n setHighlightedIndex(selectedIdx);\n }\n }, [value, items]);\n\n const containerStyle: Style = {\n flexDirection: direction,\n gap,\n ...style,\n };\n\n const radioItems = items.map((item, index) => {\n const isSelected = item.value === value;\n const isHighlighted = index === highlightedIndex;\n const isItemDisabled = disabled || item.disabled;\n\n const radioChar = isSelected ? selectedChar : unselectedChar;\n\n let computedStyle: Style = {\n flexDirection: \"row\",\n gap: 1,\n ...itemStyle,\n };\n\n if (isSelected && selectedItemStyle) {\n computedStyle = { ...computedStyle, ...selectedItemStyle };\n }\n\n if (isFocused && isHighlighted && focusedItemStyle) {\n computedStyle = { ...computedStyle, ...focusedItemStyle };\n }\n\n const textColor = isItemDisabled\n ? \"blackBright\"\n : isFocused && isHighlighted\n ? focusedItemStyle?.color ?? \"white\"\n : isSelected\n ? selectedItemStyle?.color ?? itemStyle?.color\n : itemStyle?.color;\n\n return React.createElement(\n \"box\" as any,\n { key: index, style: computedStyle },\n React.createElement(\n \"text\" as any,\n { key: \"radio\", style: { color: textColor } },\n `(${radioChar})`,\n ),\n React.createElement(\n \"text\" as any,\n { key: \"label\", style: { color: textColor } },\n item.label,\n ),\n );\n });\n\n return React.createElement(\n \"box\" as any,\n {\n style: containerStyle,\n focusable: !disabled,\n ref: (node: any) => {\n if (node) {\n nodeRef.current = node;\n focusIdRef.current = node.focusId;\n setNodeReady(true);\n } else {\n nodeRef.current = null;\n focusIdRef.current = null;\n setNodeReady(false);\n }\n },\n },\n ...radioItems,\n );\n}\n","import React, { createContext, useContext, useState, useCallback, useEffect, useRef } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style } from \"../types/index.js\";\nimport { FocusContext } from \"../hooks/context.js\";\nimport { useInput } from \"../hooks/useInput.js\";\nimport { FocusScope } from \"./FocusScope.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface AlertOptions {\n /** Text for the OK button (default: \"OK\") */\n okText?: string;\n /** Style for the dialog box */\n style?: Style;\n /** Base style for buttons */\n buttonStyle?: Style;\n /** Style for the OK button (merged with buttonStyle) */\n okButtonStyle?: Style;\n /** Style for focused button state (merged with button styles) */\n focusedButtonStyle?: Style;\n /** Style for the backdrop overlay */\n backdropStyle?: Style;\n}\n\nexport interface ConfirmOptions extends AlertOptions {\n /** Text for the Cancel button (default: \"Cancel\") */\n cancelText?: string;\n /** Style for the Cancel button (merged with buttonStyle) */\n cancelButtonStyle?: Style;\n}\n\nexport interface DialogContextValue {\n /** Show an alert dialog. Returns a promise that resolves when dismissed. */\n alert: (content: ReactNode, options?: AlertOptions) => Promise<void>;\n /** Show a confirm dialog. Returns a promise that resolves to true (OK) or false (Cancel). */\n confirm: (content: ReactNode, options?: ConfirmOptions) => Promise<boolean>;\n}\n\ninterface DialogState {\n id: number;\n type: \"alert\" | \"confirm\";\n content: ReactNode;\n okText: string;\n cancelText: string;\n style?: Style;\n buttonStyle?: Style;\n okButtonStyle?: Style;\n cancelButtonStyle?: Style;\n focusedButtonStyle?: Style;\n backdropStyle?: Style;\n resolve: (value: boolean) => void;\n}\n\n// ─── Context ─────────────────────────────────────────────────────────────────\n\nconst DialogContext = createContext<DialogContextValue | null>(null);\n\n// ─── Hook ────────────────────────────────────────────────────────────────────\n\n/**\n * Hook to show alert and confirm dialogs.\n * Must be used within a DialogHost.\n * \n * @example\n * ```tsx\n * const { alert, confirm } = useDialog();\n * \n * // Alert\n * await alert(\"Something happened!\");\n * \n * // Confirm\n * const ok = await confirm(\"Delete this item?\", {\n * okText: \"Delete\",\n * cancelText: \"Keep\"\n * });\n * ```\n */\nexport function useDialog(): DialogContextValue {\n const ctx = useContext(DialogContext);\n if (!ctx) {\n throw new Error(\"useDialog must be used within a DialogHost\");\n }\n return ctx;\n}\n\n// ─── Dialog Host ─────────────────────────────────────────────────────────────\n\nexport interface DialogHostProps {\n children?: ReactNode;\n}\n\n/**\n * Host component for dialogs. Place this at the root of your app.\n * Provides the useDialog hook to children.\n * \n * @example\n * ```tsx\n * function App() {\n * return (\n * <DialogHost>\n * <MyApp />\n * </DialogHost>\n * );\n * }\n * ```\n */\nexport function DialogHost({ children }: DialogHostProps): React.JSX.Element {\n const [dialogs, setDialogs] = useState<DialogState[]>([]);\n const idCounter = useRef(0);\n\n const alert = useCallback((content: ReactNode, options?: AlertOptions): Promise<void> => {\n return new Promise((resolve) => {\n const id = ++idCounter.current;\n setDialogs((prev) => [\n ...prev,\n {\n id,\n type: \"alert\",\n content,\n okText: options?.okText ?? \"OK\",\n cancelText: \"\",\n style: options?.style,\n buttonStyle: options?.buttonStyle,\n okButtonStyle: options?.okButtonStyle,\n focusedButtonStyle: options?.focusedButtonStyle,\n backdropStyle: options?.backdropStyle,\n resolve: () => resolve(),\n },\n ]);\n });\n }, []);\n\n const confirm = useCallback((content: ReactNode, options?: ConfirmOptions): Promise<boolean> => {\n return new Promise((resolve) => {\n const id = ++idCounter.current;\n setDialogs((prev) => [\n ...prev,\n {\n id,\n type: \"confirm\",\n content,\n okText: options?.okText ?? \"OK\",\n cancelText: options?.cancelText ?? \"Cancel\",\n style: options?.style,\n buttonStyle: options?.buttonStyle,\n okButtonStyle: options?.okButtonStyle,\n cancelButtonStyle: options?.cancelButtonStyle,\n focusedButtonStyle: options?.focusedButtonStyle,\n backdropStyle: options?.backdropStyle,\n resolve,\n },\n ]);\n });\n }, []);\n\n const dismissDialog = useCallback((id: number, result: boolean) => {\n setDialogs((prev) => {\n const dialog = prev.find((d) => d.id === id);\n if (dialog) {\n dialog.resolve(result);\n }\n return prev.filter((d) => d.id !== id);\n });\n }, []);\n\n const contextValue: DialogContextValue = { alert, confirm };\n\n // Only show the topmost dialog\n const activeDialog = dialogs[dialogs.length - 1];\n\n return React.createElement(\n DialogContext.Provider,\n { value: contextValue },\n children,\n activeDialog && React.createElement(DialogOverlay, {\n key: activeDialog.id,\n dialog: activeDialog,\n onDismiss: dismissDialog,\n }),\n );\n}\n\n// ─── Dialog Overlay ──────────────────────────────────────────────────────────\n\ninterface DialogOverlayProps {\n dialog: DialogState;\n onDismiss: (id: number, result: boolean) => void;\n}\n\nfunction DialogOverlay({ dialog, onDismiss }: DialogOverlayProps): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n \n // Refs to get the actual focusIds from the rendered nodes\n const okButtonRef = useRef<any>(null);\n const cancelButtonRef = useRef<any>(null);\n const okFocusIdRef = useRef<string | null>(null);\n const cancelFocusIdRef = useRef<string | null>(null);\n\n // Track which button is focused\n const [focusedButton, setFocusedButton] = useState<\"ok\" | \"cancel\">(\"ok\");\n \n // Force re-registration when refs are populated\n const [refsReady, setRefsReady] = useState(0);\n\n // Register buttons with focus system\n useEffect(() => {\n if (!focusCtx || refsReady === 0) return;\n \n const cleanups: (() => void)[] = [];\n \n if (okButtonRef.current && okFocusIdRef.current) {\n cleanups.push(focusCtx.register(okFocusIdRef.current, okButtonRef.current));\n }\n if (cancelButtonRef.current && cancelFocusIdRef.current) {\n cleanups.push(focusCtx.register(cancelFocusIdRef.current, cancelButtonRef.current));\n }\n \n // Focus OK button initially\n if (okFocusIdRef.current) {\n focusCtx.requestFocus(okFocusIdRef.current);\n }\n \n return () => cleanups.forEach(fn => fn());\n }, [focusCtx, refsReady]);\n\n // Listen to focus changes to track which button is selected\n useEffect(() => {\n if (!focusCtx) return;\n \n return focusCtx.onFocusChange((id) => {\n if (id === okFocusIdRef.current) {\n setFocusedButton(\"ok\");\n } else if (id === cancelFocusIdRef.current) {\n setFocusedButton(\"cancel\");\n }\n });\n }, [focusCtx]);\n\n // Keyboard handling\n useInput((key) => {\n // Enter or Space to select\n if (key.name === \"return\" || key.name === \"space\") {\n if (dialog.type === \"alert\") {\n onDismiss(dialog.id, true);\n } else {\n // For confirm: OK = true, Cancel = false\n onDismiss(dialog.id, focusedButton === \"ok\");\n }\n return;\n }\n\n // Escape to cancel/dismiss\n if (key.name === \"escape\") {\n onDismiss(dialog.id, false);\n return;\n }\n\n // Arrow keys to switch buttons (Tab is handled by focus system)\n if (dialog.type === \"confirm\" && focusCtx) {\n if (key.name === \"left\" || key.name === \"right\") {\n if (focusedButton === \"ok\" && cancelFocusIdRef.current) {\n focusCtx.requestFocus(cancelFocusIdRef.current);\n } else if (okFocusIdRef.current) {\n focusCtx.requestFocus(okFocusIdRef.current);\n }\n }\n }\n }, [dialog, focusedButton, focusCtx, onDismiss]);\n\n // Calculate dialog dimensions\n const contentIsString = typeof dialog.content === \"string\";\n const contentLength = contentIsString ? (dialog.content as string).length : 0;\n const minWidth = Math.max(20, contentIsString ? Math.min(contentLength + 6, 50) : 30);\n\n // Dialog box style (no absolute positioning - centering wrapper handles it)\n const boxStyle: Style = {\n minWidth,\n maxWidth: 50,\n bg: \"black\",\n border: \"round\",\n borderColor: \"white\",\n padding: 1,\n flexDirection: \"column\",\n gap: 1,\n ...dialog.style,\n };\n\n // Button styles - merge base, specific, and focused styles\n const getButtonStyle = (button: \"ok\" | \"cancel\", isSelected: boolean): Style => {\n const baseStyle: Style = {\n paddingX: 2,\n bg: \"blackBright\",\n color: \"white\",\n };\n \n const defaultFocusedStyle: Style = {\n bg: \"white\",\n color: \"black\",\n bold: true,\n };\n \n const specificStyle = button === \"ok\" \n ? dialog.okButtonStyle \n : dialog.cancelButtonStyle;\n \n return {\n ...baseStyle,\n ...dialog.buttonStyle,\n ...specificStyle,\n ...(isSelected ? { ...defaultFocusedStyle, ...dialog.focusedButtonStyle } : {}),\n };\n };\n \n // Backdrop style\n const backdropStyle: Style = {\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n zIndex: 999,\n ...dialog.backdropStyle,\n };\n\n return React.createElement(\n FocusScope,\n { trap: true },\n // Backdrop\n React.createElement(\"box\" as any, {\n style: backdropStyle,\n }),\n // Centering wrapper\n React.createElement(\n \"box\" as any,\n {\n style: {\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n bottom: 0,\n justifyContent: \"center\",\n alignItems: \"center\",\n zIndex: 1000,\n },\n },\n // Dialog box\n React.createElement(\n \"box\" as any,\n { style: boxStyle },\n // Content\n React.createElement(\n \"box\" as any,\n { style: { flexDirection: \"column\" } },\n typeof dialog.content === \"string\"\n ? React.createElement(\"text\" as any, null, dialog.content)\n : dialog.content,\n ),\n // Buttons row\n React.createElement(\n \"box\" as any,\n {\n style: {\n flexDirection: \"row\",\n justifyContent: \"flex-end\",\n gap: 1,\n },\n },\n // Cancel button (confirm only)\n dialog.type === \"confirm\" &&\n React.createElement(\n \"box\" as any,\n {\n style: getButtonStyle(\"cancel\", focusedButton === \"cancel\"),\n focusable: true,\n ref: (node: any) => {\n if (node && node.focusId && !cancelFocusIdRef.current) {\n cancelButtonRef.current = node;\n cancelFocusIdRef.current = node.focusId;\n setRefsReady(r => r + 1);\n }\n },\n },\n React.createElement(\"text\" as any, null, dialog.cancelText),\n ),\n // OK button\n React.createElement(\n \"box\" as any,\n {\n style: getButtonStyle(\"ok\", focusedButton === \"ok\"),\n focusable: true,\n ref: (node: any) => {\n if (node && node.focusId && !okFocusIdRef.current) {\n okButtonRef.current = node;\n okFocusIdRef.current = node.focusId;\n setRefsReady(r => r + 1);\n }\n },\n },\n React.createElement(\"text\" as any, null, dialog.okText),\n ),\n ),\n ),\n ),\n );\n}\n","import React, { useState, useEffect, useCallback, useContext, useRef, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Color } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport type { LayoutRect } from \"../types/index.js\";\nimport { InputContext, FocusContext, LayoutContext } from \"../hooks/context.js\";\n\ninterface TrackedElement {\n id: string;\n node: GlyphNode;\n layout: LayoutRect;\n}\n\nexport interface JumpNavProps {\n children?: ReactNode;\n /** Keybind to activate jump mode (default: \"ctrl+o\") */\n activationKey?: string;\n /** Style for the hint labels */\n hintStyle?: Style;\n /** Color for hint background (default: \"yellow\") */\n hintBg?: Color;\n /** Color for hint text (default: \"black\") */\n hintFg?: Color;\n /** Characters to use for hints (default: \"asdfghjklqwertyuiopzxcvbnm\") */\n hintChars?: string;\n /** Whether jump nav is enabled (default: true) */\n enabled?: boolean;\n /** Enable debug logging */\n debug?: boolean;\n}\n\n// Generate hint keys for N elements\nfunction generateHints(count: number, chars: string): string[] {\n const hints: string[] = [];\n const charList = chars.split(\"\");\n \n if (count <= charList.length) {\n // Single character hints\n for (let i = 0; i < count; i++) {\n hints.push(charList[i]!);\n }\n } else {\n // Two character hints for larger lists\n for (let i = 0; i < charList.length && hints.length < count; i++) {\n for (let j = 0; j < charList.length && hints.length < count; j++) {\n hints.push(charList[i]! + charList[j]!);\n }\n }\n }\n \n return hints;\n}\n\n/**\n * JumpNav provides vim-style quick navigation to focusable elements.\n * Press the activation key (default: Ctrl+O) to show hints next to each\n * focusable element, then press the hint key to jump to that element.\n * \n * JumpNav is trap-aware: it automatically only shows hints for elements\n * in the current FocusScope trap (e.g., a modal). You only need ONE JumpNav\n * at the root of your app.\n */\nexport function JumpNav({\n children,\n activationKey = \"ctrl+o\",\n hintStyle,\n hintBg = \"yellow\",\n hintFg = \"black\",\n hintChars = \"asdfghjklqwertyuiopzxcvbnm\",\n enabled = true,\n debug = false,\n}: JumpNavProps): React.JSX.Element {\n const log = debug ? (...args: any[]) => console.error('[JumpNav]', ...args) : () => {};\n \n const [isActive, setIsActive] = useState(false);\n const [inputBuffer, setInputBuffer] = useState(\"\");\n const [elements, setElements] = useState<TrackedElement[]>([]);\n \n const inputCtx = useContext(InputContext);\n const focusCtx = useContext(FocusContext);\n const layoutCtx = useContext(LayoutContext);\n\n // Log mount info\n useEffect(() => {\n log('Mounted, inputCtx:', !!inputCtx, 'focusCtx:', !!focusCtx, 'enabled:', enabled);\n }, []);\n\n // Parse activation key\n const parseKey = useCallback((keyStr: string) => {\n const parts = keyStr.toLowerCase().split(\"+\");\n return {\n ctrl: parts.includes(\"ctrl\"),\n alt: parts.includes(\"alt\"),\n shift: parts.includes(\"shift\"),\n meta: parts.includes(\"meta\"),\n name: parts[parts.length - 1] ?? \"\",\n };\n }, []);\n\n const activationKeyParsed = parseKey(activationKey);\n\n // Refresh elements from the ACTIVE focus scope (trap-aware)\n const refreshElements = useCallback(() => {\n if (!focusCtx?.getActiveElements) {\n log('refreshElements: no getActiveElements');\n return;\n }\n \n const active = focusCtx.getActiveElements();\n log('getActiveElements returned', active.length, 'elements');\n \n const mapped: TrackedElement[] = active.map(({ id, node }) => ({\n id,\n node,\n layout: layoutCtx?.getLayout(node) ?? node.layout,\n }));\n \n // Sort by visual position (top-to-bottom, left-to-right)\n mapped.sort((a, b) => {\n if (a.layout.y !== b.layout.y) {\n return a.layout.y - b.layout.y;\n }\n return a.layout.x - b.layout.x;\n });\n \n setElements(mapped);\n }, [focusCtx, layoutCtx, log]);\n\n // Track previous isActive to detect activation transition\n const wasActiveRef = useRef(false);\n \n // Refresh elements when activated\n useEffect(() => {\n if (isActive && !wasActiveRef.current) {\n log('Activated! Refreshing elements...');\n refreshElements();\n }\n wasActiveRef.current = isActive;\n }, [isActive, refreshElements, log]);\n\n // Filter elements with valid layout (visible and computed)\n const visibleElements = elements.filter(el => \n el.layout.width > 0 && el.layout.height > 0\n );\n const visibleHints = generateHints(visibleElements.length, hintChars);\n\n // Create visible hint -> element mapping\n const visibleHintMap = useMemo(() => {\n const map = new Map<string, string>();\n visibleElements.forEach((el, i) => {\n if (visibleHints[i]) {\n map.set(visibleHints[i]!, el.id);\n }\n });\n return map;\n }, [visibleElements, visibleHints]);\n\n // Handle key input\n useEffect(() => {\n if (!inputCtx || !enabled) {\n log('Not subscribing - inputCtx:', !!inputCtx, 'enabled:', enabled);\n return;\n }\n\n log('Subscribing to priority input, activation key:', activationKey);\n\n const handler = (key: { name?: string; ctrl?: boolean; alt?: boolean; shift?: boolean; meta?: boolean; sequence?: string }) => {\n // Check for activation key\n const nameMatch = key.name === activationKeyParsed.name;\n const ctrlMatch = !!key.ctrl === activationKeyParsed.ctrl;\n const altMatch = !!key.alt === activationKeyParsed.alt;\n const shiftMatch = !!key.shift === activationKeyParsed.shift;\n const metaMatch = !!key.meta === activationKeyParsed.meta;\n \n if (\n !isActive &&\n nameMatch && ctrlMatch && altMatch && shiftMatch && metaMatch\n ) {\n log('Activation key matched! Activating...');\n setIsActive(true);\n setInputBuffer(\"\");\n return true;\n }\n\n // When active, handle hint input\n if (isActive) {\n // Escape to cancel\n if (key.name === \"escape\") {\n log('Escape pressed, deactivating');\n setIsActive(false);\n setInputBuffer(\"\");\n return true;\n }\n\n // Backspace to clear buffer\n if (key.name === \"backspace\") {\n setInputBuffer(\"\");\n return true;\n }\n\n // Letter input\n if (key.sequence && key.sequence.length === 1 && /[a-z]/i.test(key.sequence)) {\n const newBuffer = inputBuffer + key.sequence.toLowerCase();\n log('Buffer:', newBuffer);\n \n // Check for exact match\n const targetId = visibleHintMap.get(newBuffer);\n if (targetId) {\n log('Jumping to', targetId);\n focusCtx?.requestFocus(targetId);\n setIsActive(false);\n setInputBuffer(\"\");\n return true;\n }\n \n // Check if any hint starts with this buffer\n const hasPartialMatch = [...visibleHintMap.keys()].some(h => h.startsWith(newBuffer));\n if (hasPartialMatch) {\n setInputBuffer(newBuffer);\n return true;\n }\n \n // No match - reset\n setInputBuffer(\"\");\n return true;\n }\n\n // Consume all other keys when active\n return true;\n }\n\n return false;\n };\n\n // Use priority handler so we capture keys before focused inputs\n return inputCtx.subscribePriority(handler);\n }, [inputCtx, enabled, isActive, activationKeyParsed, inputBuffer, visibleHintMap, focusCtx, activationKey, log]);\n\n // Render floating hint labels when active - wrapped in Portal to not affect layout\n const hintsOverlay = isActive ? React.createElement(\n \"box\" as any,\n {\n // Portal-like wrapper - fullscreen absolute overlay\n style: {\n position: \"absolute\" as const,\n top: 0,\n left: 0,\n width: \"100%\",\n height: \"100%\",\n zIndex: 99998,\n },\n },\n // Hint labels - floating on top of content\n ...visibleElements.map((el, i) => {\n const hint = visibleHints[i];\n if (!hint) return null;\n \n // Position hint at element's location\n const { x, y } = el.layout;\n \n // Highlight matching prefix\n const isPartialMatch = hint.startsWith(inputBuffer) && inputBuffer.length > 0;\n \n return React.createElement(\n \"box\" as any,\n {\n key: el.id,\n style: {\n position: \"absolute\" as const,\n top: y,\n left: Math.max(0, x - hint.length - 2),\n bg: isPartialMatch ? \"cyan\" : hintBg,\n color: hintFg,\n paddingX: 1,\n zIndex: 99999,\n ...hintStyle,\n },\n },\n React.createElement(\"text\" as any, {\n style: { bold: true, color: hintFg },\n }, hint),\n );\n }),\n // Status bar at bottom\n React.createElement(\n \"box\" as any,\n {\n style: {\n position: \"absolute\" as const,\n bottom: 0,\n left: 0,\n right: 0,\n bg: \"blackBright\" as const,\n paddingX: 1,\n zIndex: 99999,\n },\n },\n React.createElement(\"text\" as any, {\n style: { color: \"white\" as const },\n }, inputBuffer ? `Jump: ${inputBuffer}_` : \"Press a key to jump • ESC to cancel\"),\n ),\n ) : null;\n\n return React.createElement(\n React.Fragment,\n null,\n children,\n hintsOverlay,\n );\n}\n","import { useContext, useEffect, useState, useRef, useMemo } from \"react\";\nimport { FocusContext } from \"./context.js\";\nimport { AppContext } from \"./context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\n\ninterface UseFocusResult {\n focused: boolean;\n focus(): void;\n}\n\nexport function useFocus(nodeRef?: { current: GlyphNode | null }): UseFocusResult {\n const focusCtx = useContext(FocusContext);\n const [id] = useState(() => `focus-${Math.random().toString(36).slice(2, 9)}`);\n\n const isFocused = focusCtx ? focusCtx.focusedId === id : false;\n\n useEffect(() => {\n if (!focusCtx || !nodeRef?.current) return;\n // Assign the focus ID to the node\n nodeRef.current.focusId = id;\n return focusCtx.register(id, nodeRef.current);\n }, [focusCtx, id, nodeRef]);\n\n const focus = useMemo(() => {\n return () => {\n focusCtx?.requestFocus(id);\n };\n }, [focusCtx, id]);\n\n return { focused: isFocused, focus };\n}\n","import { useContext, useEffect, useRef, useState, useCallback } from \"react\";\nimport { FocusContext, InputContext } from \"./context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport type { Key } from \"../types/index.js\";\n\nexport interface UseFocusableOptions {\n /** Whether the element is currently disabled (skipped in tab order) */\n disabled?: boolean;\n /** Called when the element receives focus */\n onFocus?: () => void;\n /** Called when the element loses focus */\n onBlur?: () => void;\n /**\n * Key handler when focused. Return `true` to consume the key.\n * This runs after priority handlers but before global handlers.\n */\n onKeyPress?: (key: Key) => boolean | void;\n}\n\nexport interface UseFocusableResult {\n /** Ref to attach to your focusable element */\n ref: (node: GlyphNode | null) => void;\n /** Whether this element is currently focused */\n isFocused: boolean;\n /** Programmatically request focus on this element */\n focus: () => void;\n /** The focus ID (useful for conditional logic) */\n focusId: string | null;\n}\n\n/**\n * Hook to make any element focusable with keyboard support.\n * \n * @example\n * ```tsx\n * function CustomPicker({ onSelect }) {\n * const { ref, isFocused, focus } = useFocusable({\n * onKeyPress: (key) => {\n * if (key.name === \"return\") {\n * onSelect();\n * return true;\n * }\n * return false;\n * },\n * });\n * \n * return (\n * <Box\n * ref={ref}\n * focusable\n * style={{ \n * border: \"round\",\n * borderColor: isFocused ? \"cyan\" : \"gray\" \n * }}\n * >\n * <Text>Custom Picker</Text>\n * </Box>\n * );\n * }\n * ```\n */\nexport function useFocusable(options: UseFocusableOptions = {}): UseFocusableResult {\n const { disabled, onFocus, onBlur, onKeyPress } = options;\n \n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n \n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const [isFocused, setIsFocused] = useState(false);\n \n // Keep callbacks in refs to avoid stale closures\n const onFocusRef = useRef(onFocus);\n const onBlurRef = useRef(onBlur);\n const onKeyPressRef = useRef(onKeyPress);\n onFocusRef.current = onFocus;\n onBlurRef.current = onBlur;\n onKeyPressRef.current = onKeyPress;\n \n // Ref callback for the element\n const ref = useCallback((node: GlyphNode | null) => {\n nodeRef.current = node;\n if (node) {\n focusIdRef.current = node.focusId ?? null;\n } else {\n focusIdRef.current = null;\n }\n }, []);\n \n // Register with focus system\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current);\n }, [focusCtx]);\n \n // Handle disabled state (mark as skippable in tab order)\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n focusCtx.setSkippable(focusIdRef.current, !!disabled);\n }, [focusCtx, disabled]);\n \n // Subscribe to focus changes\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n const fid = focusIdRef.current;\n \n // Check initial focus state\n const initiallyFocused = focusCtx.focusedId === fid;\n setIsFocused(initiallyFocused);\n \n return focusCtx.onFocusChange((newId) => {\n const nowFocused = newId === fid;\n setIsFocused((wasFocused) => {\n if (nowFocused && !wasFocused) {\n onFocusRef.current?.();\n } else if (!nowFocused && wasFocused) {\n onBlurRef.current?.();\n }\n return nowFocused;\n });\n });\n }, [focusCtx]);\n \n // Register key handler when focused\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || disabled) return;\n const fid = focusIdRef.current;\n \n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n return onKeyPressRef.current?.(key) === true;\n };\n \n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, disabled]);\n \n // Focus function\n const focus = useCallback(() => {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n }, [focusCtx]);\n \n return {\n ref,\n isFocused,\n focus,\n focusId: focusIdRef.current,\n };\n}\n","import { useContext } from \"react\";\nimport { AppContext } from \"./context.js\";\n\nexport interface UseAppResult {\n exit(code?: number): void;\n columns: number;\n rows: number;\n}\n\nexport function useApp(): UseAppResult {\n const ctx = useContext(AppContext);\n if (!ctx) {\n throw new Error(\"useApp must be used within a Glyph render tree\");\n }\n\n return {\n exit: ctx.exit,\n get columns() {\n return ctx.columns;\n },\n get rows() {\n return ctx.rows;\n },\n };\n}\n","import { useContext, useState, useEffect, useCallback, useRef } from \"react\";\nimport { FocusContext, LayoutContext } from \"./context.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport type { LayoutRect } from \"../types/index.js\";\n\nexport interface FocusableElement {\n /** Unique focus ID */\n id: string;\n /** The GlyphNode */\n node: GlyphNode;\n /** Current layout (position, size) */\n layout: LayoutRect;\n /** Node type (box, input, etc.) */\n type: string;\n}\n\nexport interface FocusRegistryValue {\n /** All currently registered focusable elements */\n elements: FocusableElement[];\n /** Currently focused element ID */\n focusedId: string | null;\n /** Request focus on a specific element */\n requestFocus: (id: string) => void;\n /** Move to next focusable element */\n focusNext: () => void;\n /** Move to previous focusable element */\n focusPrev: () => void;\n /** Manually refresh the element list (useful after layout updates) */\n refresh: () => void;\n}\n\n/**\n * Hook to access all registered focusable elements in the current focus context.\n * Useful for building custom navigation UIs like jump-to overlays.\n */\nexport function useFocusRegistry(): FocusRegistryValue | null {\n const focusCtx = useContext(FocusContext);\n const layoutCtx = useContext(LayoutContext);\n const [elements, setElements] = useState<FocusableElement[]>([]);\n const updateRef = useRef<() => void>(() => {});\n\n const updateElements = useCallback(() => {\n if (!focusCtx) return;\n \n // Use getActiveElements to respect current focus trap\n const registered = focusCtx.getActiveElements?.() ?? focusCtx.getRegisteredElements?.() ?? [];\n const mapped: FocusableElement[] = registered.map(({ id, node }) => ({\n id,\n node,\n layout: layoutCtx?.getLayout(node) ?? node.layout,\n type: node.type,\n }));\n \n // Sort by visual position (top-to-bottom, left-to-right)\n mapped.sort((a, b) => {\n if (a.layout.y !== b.layout.y) {\n return a.layout.y - b.layout.y;\n }\n return a.layout.x - b.layout.x;\n });\n \n setElements(mapped);\n }, [focusCtx, layoutCtx]);\n\n // Store the update function in a ref so it can be called externally\n updateRef.current = updateElements;\n\n useEffect(() => {\n if (!focusCtx) return;\n\n updateElements();\n\n // Re-update when focus changes (elements may have been added/removed)\n const unsubscribe = focusCtx.onFocusChange(() => {\n updateElements();\n });\n\n // Also update after a short delay to catch layout computation\n const timer = setTimeout(updateElements, 50);\n\n return () => {\n unsubscribe();\n clearTimeout(timer);\n };\n }, [focusCtx, layoutCtx, updateElements]);\n\n if (!focusCtx) return null;\n\n return {\n elements,\n focusedId: focusCtx.focusedId,\n requestFocus: focusCtx.requestFocus,\n focusNext: focusCtx.focusNext,\n focusPrev: focusCtx.focusPrev,\n refresh: () => updateRef.current(),\n };\n}\n","/**\n * Input mask utilities for Glyph Input component.\n * \n * Mask pattern characters:\n * - `9` - Digit (0-9)\n * - `a` - Letter (a-z, A-Z)\n * - `*` - Alphanumeric (a-z, A-Z, 0-9)\n * - Any other character is treated as a literal (separator)\n * \n * @example\n * ```tsx\n * import { createMask } from \"@nick-skriabin/glyph\";\n * \n * // Phone: (123) 456-7890\n * const phoneMask = createMask(\"(999) 999-9999\");\n * <Input onBeforeChange={phoneMask} />\n * \n * // Date: 12/31/2024\n * const dateMask = createMask(\"99/99/9999\");\n * <Input onBeforeChange={dateMask} />\n * \n * // License plate: ABC-1234\n * const plateMask = createMask(\"aaa-9999\");\n * <Input onBeforeChange={plateMask} />\n * ```\n */\n\nexport interface MaskOptions {\n /** The mask pattern */\n mask: string;\n /** Placeholder character for unfilled positions (default: \"_\") */\n placeholder?: string;\n /** Show placeholder in output (default: false) */\n showPlaceholder?: boolean;\n}\n\ntype MaskChar = {\n type: \"digit\" | \"letter\" | \"alphanumeric\" | \"literal\";\n char: string;\n};\n\nfunction parseMask(mask: string): MaskChar[] {\n const result: MaskChar[] = [];\n for (const char of mask) {\n switch (char) {\n case \"9\":\n result.push({ type: \"digit\", char });\n break;\n case \"a\":\n result.push({ type: \"letter\", char });\n break;\n case \"*\":\n result.push({ type: \"alphanumeric\", char });\n break;\n default:\n result.push({ type: \"literal\", char });\n break;\n }\n }\n return result;\n}\n\nfunction isValidChar(char: string, type: MaskChar[\"type\"]): boolean {\n switch (type) {\n case \"digit\":\n return /\\d/.test(char);\n case \"letter\":\n return /[a-zA-Z]/.test(char);\n case \"alphanumeric\":\n return /[a-zA-Z0-9]/.test(char);\n case \"literal\":\n return true; // Literals are auto-inserted\n }\n}\n\n/**\n * Creates a mask handler for use with Input's onBeforeChange prop.\n * \n * @param maskOrOptions - Mask pattern string or options object\n * @returns onBeforeChange handler function\n */\nexport function createMask(\n maskOrOptions: string | MaskOptions\n): (newValue: string, oldValue: string) => string | false | void {\n const options: MaskOptions = typeof maskOrOptions === \"string\" \n ? { mask: maskOrOptions } \n : maskOrOptions;\n \n const { mask, placeholder = \"_\", showPlaceholder = false } = options;\n const maskChars = parseMask(mask);\n\n return (newValue: string, _oldValue: string): string | false | void => {\n // Extract only valid input characters (strip literals and placeholders)\n const inputChars: string[] = [];\n for (const char of newValue) {\n if (char !== placeholder && !/[\\s\\-\\(\\)\\/\\.\\:]/.test(char) || /[a-zA-Z0-9]/.test(char)) {\n if (/[a-zA-Z0-9]/.test(char)) {\n inputChars.push(char);\n }\n }\n }\n\n // Build masked output\n let result = \"\";\n let inputIndex = 0;\n\n for (const maskChar of maskChars) {\n if (maskChar.type === \"literal\") {\n // Always include literals if we have more input to process\n // or if showPlaceholder is true\n if (inputIndex < inputChars.length || showPlaceholder) {\n result += maskChar.char;\n }\n } else {\n // Input position\n if (inputIndex < inputChars.length) {\n const char = inputChars[inputIndex]!;\n if (isValidChar(char, maskChar.type)) {\n result += char;\n inputIndex++;\n } else {\n // Skip invalid character\n inputIndex++;\n // Try again with next input char\n continue;\n }\n } else if (showPlaceholder) {\n result += placeholder;\n }\n }\n }\n\n return result;\n };\n}\n\n/**\n * Pre-built mask patterns for common use cases.\n */\nexport const masks = {\n /** US Phone: (123) 456-7890 */\n usPhone: createMask(\"(999) 999-9999\"),\n \n /** International Phone: +1 234 567 8900 */\n intlPhone: createMask(\"+9 999 999 9999\"),\n \n /** Date MM/DD/YYYY */\n dateUS: createMask(\"99/99/9999\"),\n \n /** Date DD/MM/YYYY */\n dateEU: createMask(\"99/99/9999\"),\n \n /** Date YYYY-MM-DD */\n dateISO: createMask(\"9999-99-99\"),\n \n /** Time HH:MM */\n time: createMask(\"99:99\"),\n \n /** Time HH:MM:SS */\n timeFull: createMask(\"99:99:99\"),\n \n /** Credit Card: 1234 5678 9012 3456 */\n creditCard: createMask(\"9999 9999 9999 9999\"),\n \n /** SSN: 123-45-6789 */\n ssn: createMask(\"999-99-9999\"),\n \n /** ZIP Code: 12345 */\n zip: createMask(\"99999\"),\n \n /** ZIP+4: 12345-6789 */\n zipPlus4: createMask(\"99999-9999\"),\n \n /** IPv4: 192.168.001.001 */\n ipv4: createMask(\"999.999.999.999\"),\n \n /** MAC Address: AA:BB:CC:DD:EE:FF */\n mac: createMask(\"**:**:**:**:**:**\"),\n};\n"]}
|