@semos-labs/glyph 0.1.74
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 +913 -0
- package/dist/index.d.ts +908 -0
- package/dist/index.js +19 -0
- package/dist/index.js.map +1 -0
- package/package.json +69 -0
|
@@ -0,0 +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/ansi.ts","../src/paint/painter.ts","../src/paint/diff.ts","../src/layout/yogaLayout.ts","../src/hooks/context.ts","../src/runtime/terminalCapabilities.ts","../src/runtime/imageProtocol.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/runtime/imageLoader.ts","../src/runtime/osPreview.ts","../src/components/Image.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","appendTextChild","t","removeChild","idx","allIdx","removeTextChild","insertBefore","beforeChild","insertTextBefore","getInheritedTextStyle","node","result","current","s","collectStyledSegments","inheritedStyle","segments","currentStyle","DefaultEventPriority","hostConfig","_priority","_callback","_type","_props","_instance","methodName","args","_errorPrefix","_rootContainer","_hostContext","_internalHandle","text","parentInstance","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","nextChar","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","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","textAlign","styledChars","lineBreaks","segment","ansiSegments","ansiSeg","mergedStyle","lineStart","breakIdx","plainText","sc","charIdx","wrappedText","wrappedLine","lineIdx","visibleWidth","sum","offsetX","cursorInfo","useNativeCursor","value","placeholder","displayText","isPlaceholder","multiline","autoFg","placeholderFg","textFg","textDim","isFocused","rawLines","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","ImageOverlayContext","cachedCapabilities","detectTerminalCapabilities","debug","term","termProgram","kittyWindowId","ghosttyResourcesDir","weztermPane","lcTerminal","konsoleVersion","supportsInlineImages","caps","inTmux","tmuxWrap","doubled","renderImageEscapeSequence","opts","renderKittyGraphics","renderIterm2Image","clearImageEscapeSequence","id","base64","dims","getImageDimensions","cmd","chunkSize","chunk","more","escSeq","imgSeq","offset","marker","segmentLength","render","element","terminal","nativeCursorVisible","scheduleRender","prevFb","currentFb","inputHandlers","priorityHandlers","focusedInputHandlers","inputContextValue","focusId","renderedImages","pendingImageRenders","imageOverlayContextValue","image","clearSeq","renderPendingImages","escapeSeq","focusedId","focusRegistry","focusOrder","skippableIds","noAutoFocusIds","trapStack","focusChangeHandlers","setFocusedId","getActiveFocusableIds","ids","trap","nodeA","nodeB","layoutA","layoutB","focusContextValue","autoFocus","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","focusedStyle","focusCtx","useContext","nodeRef","useRef","focusIdRef","setIsFocused","useState","useImperativeHandle","useEffect","fid","newId","setRef","cursorToVisualLine","logicalLines","allVisualLines","logicalOffset","offsetInLogical","charCount","vl","isEndOfLogicalLine","effectiveLen","lastIdx","visualLineToCursor","visualLine","visualCol","targetLine","cursorToLineCol","remaining","last","lineColToCursor","Input","controlledValue","defaultValue","onChange","onKeyPress","onBeforeChange","internalValue","setInternalValue","cursorPos","setCursorPos","setInnerWidth","nodeReady","setNodeReady","inputCtx","layoutCtx","isControlled","workingValueRef","layout","rect","workingCursorRef","lastSentValueRef","lastSentCursorRef","stateRef","autoFocusedRef","timer","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","totalLines","overscan","virtualize","estimatedItemHeight","internalOffset","setInternalOffset","isRenderFunction","childArray","useMemo","isLineVirtualized","isArrayVirtualized","viewportRef","contentRef","viewportLayout","contentLayout","measuredHeightsRef","itemRefsRef","isSelfFocused","viewportHeight","getArrayTotalHeight","useCallback","total","contentHeight","maxOffset","effectiveOffset","scrollViewContextValue","viewportY","setOffset","clamped","findNode","found","focusedLayout","contentTopY","elementTop","elementBottom","visibleTop","visibleBottom","containsFocus","currentFocusId","halfPage","fullPage","_pad","_px","_py","_pt","_pr","_pb","_pl","styleRest","borderHeight","intrinsicHeight","outerStyle","visibleRange","end","arrayVisibility","currentOffset","startIndex","startOffset","itemHeight","endIndex","innerStyle","renderedChildren","actualIndex","forceUpdate","needsUpdate","measuredHeight","n","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","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","openDirection","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","RadioInner","focusedItemStyle","selectedItemStyle","gap","selectedChar","unselectedChar","forwardedRef","highlightedIndex","setHighlightedIndex","selectedIdx","containerStyle","radioItems","isSelected","isItemDisabled","radioChar","computedStyle","textColor","Radio","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","computeEffectiveClip","clips","isElementVisible","elRight","elBottom","generateHints","hints","charList","j","JumpNav","activationKey","hintStyle","hintBg","hintFg","hintChars","enabled","log","isActive","setIsActive","inputBuffer","setInputBuffer","elements","setElements","activationKeyParsed","keyStr","refreshElements","active","screenColumns","mapped","wasActiveRef","visibleElements","el","visibleHints","visibleHintMap","map","nameMatch","ctrlMatch","altMatch","shiftMatch","metaMatch","newBuffer","targetId","hintsOverlay","hint","elWidth","labelWidth","clampedY","leftPos","rightPos","labelX","isPartialMatch","CACHE_DIR","join","tmpdir","isRemoteUrl","src","getCachePath","url","format","hash","createHash","ext","getExtensionFromFormat","getExtensionFromUrl","getImageName","urlObj","pathname","basename","ensureCacheDir","existsSync","mkdirSync","loadImage","loadRemoteImage","loadLocalImage","path","readFileSync","possibleExtensions","possiblePath","response","arrayBuffer","isValidImage","detectImageFormat","cachePath","writeFileSync","convertToPng","originalPath","tempId","tempInput","tempOutput","os","platform","converted","execSync","pngData","unlinkSync","detectPreviewMethod","openImagePreview","localPath","openQuickLook","openWithSystem","reject","proc","spawn","bringQuickLookToFront","exec","command","Image","unloadTrigger","placeholderStyle","inline","onStateChange","onError","autoLoad","autoSize","maxHeight","imageOverlayCtx","imageIdRef","lastScrollOffsetRef","state","setState","errorMsg","setErrorMsg","computedDims","setComputedDims","loadedImageRef","imageName","isRemote","lastUnloadTriggerRef","updateState","newState","currentScrollOffset","cellWidth","cellHeight","imageId","timeoutId","loadAndDisplay","imageData","imageDims","targetWidth","targetHeight","effectiveMaxWidth","effectiveMaxHeight","scaleX","scaleY","scale","MAX_IMAGE_WIDTH","MAX_IMAGE_HEIGHT","displayContent","statusIcon","effectiveWidth","effectiveHeight","placeholderMergedStyle","useFocus","focus","useFocusable","onFocus","onBlur","onFocusRef","onBlurRef","onKeyPressRef","initiallyFocused","nowFocused","wasFocused","blur","useApp","useFocusRegistry","updateRef","updateElements","unsubscribe","parseMask","mask","isValidChar","createMask","maskOrOptions","showPlaceholder","maskChars","newValue","_oldValue","inputChars","inputIndex","maskChar","masks"],"mappings":"+hBAmCA,IAAIA,EAAAA,CAAc,CAAA,CACX,SAASC,EAAAA,EAA0B,CACxC,OAAO,CAAA,YAAA,EAAeD,EAAAA,EAAa,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,WAAA,CAAa,EAAC,CACd,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,MAAA,CAAQ,CAAA,CAAG,MAAA,CAAQ,CAAA,CAAG,UAAA,CAAY,CAAA,CAAG,WAAA,CAAa,CAAE,CAAA,CAC/F,OAAA,CAASF,CAAAA,GAAS,OAAA,EAA+BC,CAAAA,CAAM,SAAA,CAA3BH,EAAAA,EAAgB,CAA2C,IAAA,CACvF,MAAA,CAAQ,KACV,CACF,CAEO,SAASK,EAAAA,CAAYC,CAAAA,CAAmBC,CAAAA,CAAwB,CACrEA,CAAAA,CAAM,MAAA,CAASD,CAAAA,CACfA,CAAAA,CAAO,QAAA,CAAS,IAAA,CAAKC,CAAK,CAAA,CAC1BD,CAAAA,CAAO,WAAA,CAAY,IAAA,CAAKC,CAAK,EAC/B,CAEO,SAASC,EAAAA,CAAgBF,CAAAA,CAAmBC,CAAAA,CAAgC,CACjFA,CAAAA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AaD,CAAAA,CAAW,MAAA,EAAUJ,CAAAA,IACpCh7B,CAAAA,EAAUs7B,CAAAA,CAAS,IAAA,CAAA,CAAA,KAAA,GAIjBD,CAAAA,CAAaD,CAAAA,CAAW,MAAA,CAAQ,CAClC,IAAM1yB,CAAAA,CAAO0yB,CAAAA,CAAWC,CAAU,CAAA,CAClC,GAAIR,EAAAA,CAAYnyB,CAAAA,CAAM4yB,CAAAA,CAAS,IAAI,CAAA,CACjCt7B,CAAAA,EAAU0I,CAAAA,CACV2yB,CAAAA,EAAAA,CAAAA,KACK,CAELA,CAAAA,EAAAA,CAEA,QACF,CACF,CAAA,KAAWL,CAAAA,GACTh7B,CAAAA,EAAUoN,CAAAA,CAAAA,CAKhB,OAAOpN,CACT,CACF,CAKO,IAAMu7B,EAAAA,CAAQ,CAEnB,OAAA,CAAST,EAAAA,CAAW,gBAAgB,CAAA,CAGpC,SAAA,CAAWA,EAAAA,CAAW,iBAAiB,CAAA,CAGvC,MAAA,CAAQA,EAAAA,CAAW,YAAY,CAAA,CAG/B,MAAA,CAAQA,EAAAA,CAAW,YAAY,CAAA,CAG/B,OAAA,CAASA,EAAAA,CAAW,YAAY,CAAA,CAGhC,IAAA,CAAMA,EAAAA,CAAW,OAAO,CAAA,CAGxB,QAAA,CAAUA,EAAAA,CAAW,UAAU,CAAA,CAG/B,UAAA,CAAYA,EAAAA,CAAW,qBAAqB,CAAA,CAG5C,GAAA,CAAKA,EAAAA,CAAW,aAAa,CAAA,CAG7B,GAAA,CAAKA,EAAAA,CAAW,OAAO,CAAA,CAGvB,QAAA,CAAUA,EAAAA,CAAW,YAAY,CAAA,CAGjC,IAAA,CAAMA,EAAAA,CAAW,iBAAiB,CAAA,CAGlC,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 type GlyphChild = GlyphNode | GlyphTextInstance;\n\nexport interface GlyphNode {\n type: GlyphNodeType;\n props: Record<string, any>;\n style: Style;\n children: GlyphNode[];\n rawTextChildren: GlyphTextInstance[];\n /** All children in order (both nodes and raw text) for correct text composition */\n allChildren: GlyphChild[];\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 allChildren: [],\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 parent.allChildren.push(child);\n}\n\nexport function appendTextChild(parent: GlyphNode, child: GlyphTextInstance): void {\n child.parent = parent;\n parent.rawTextChildren.push(child);\n parent.allChildren.push(child);\n parent.text = parent.rawTextChildren.map((t) => t.text).join(\"\");\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 const allIdx = parent.allChildren.indexOf(child);\n if (allIdx !== -1) {\n parent.allChildren.splice(allIdx, 1);\n }\n}\n\nexport function removeTextChild(parent: GlyphNode, child: GlyphTextInstance): void {\n child.parent = null;\n const idx = parent.rawTextChildren.indexOf(child);\n if (idx !== -1) parent.rawTextChildren.splice(idx, 1);\n const allIdx = parent.allChildren.indexOf(child);\n if (allIdx !== -1) parent.allChildren.splice(allIdx, 1);\n parent.text = parent.rawTextChildren.map((t) => t.text).join(\"\") || null;\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 // Also maintain allChildren order\n const allIdx = parent.allChildren.indexOf(beforeChild);\n if (allIdx !== -1) {\n parent.allChildren.splice(allIdx, 0, child);\n } else {\n parent.allChildren.push(child);\n }\n}\n\nexport function insertTextBefore(\n parent: GlyphNode,\n child: GlyphTextInstance,\n beforeChild: GlyphChild,\n): void {\n child.parent = parent;\n parent.rawTextChildren.push(child);\n const allIdx = parent.allChildren.indexOf(beforeChild);\n if (allIdx !== -1) {\n parent.allChildren.splice(allIdx, 0, child);\n } else {\n parent.allChildren.push(child);\n }\n parent.text = parent.rawTextChildren.map((t) => t.text).join(\"\");\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 && node.allChildren.length === 0) return node.text;\n let result = \"\";\n for (const child of node.allChildren) {\n if (child.type === \"raw-text\") {\n result += child.text;\n } else {\n result += collectTextContent(child);\n }\n }\n // Fallback for nodes without allChildren populated\n if (!result && node.text != null) return node.text;\n return result;\n}\n\n/** Text style properties for styled segments */\nexport interface TextStyleProps {\n color?: Color;\n bg?: Color;\n bold?: boolean;\n dim?: boolean;\n italic?: boolean;\n underline?: boolean;\n}\n\n/** A segment of text with its accumulated style from nested Text components */\nexport interface TextSegment {\n text: string;\n style: TextStyleProps;\n}\n\n/** Collect text segments with their styles for proper nested text rendering */\nexport function collectStyledSegments(\n node: GlyphNode,\n inheritedStyle: TextStyleProps = {},\n): TextSegment[] {\n const segments: TextSegment[] = [];\n \n // Merge current node's style with inherited\n const currentStyle: TextStyleProps = {\n color: node.style.color ?? inheritedStyle.color,\n bg: node.style.bg ?? inheritedStyle.bg,\n bold: node.style.bold ?? inheritedStyle.bold,\n dim: node.style.dim ?? inheritedStyle.dim,\n italic: node.style.italic ?? inheritedStyle.italic,\n underline: node.style.underline ?? inheritedStyle.underline,\n };\n \n // If no allChildren, use text directly\n if (node.allChildren.length === 0 && node.text != null) {\n segments.push({ text: node.text, style: currentStyle });\n return segments;\n }\n \n // Traverse children in order\n for (const child of node.allChildren) {\n if (child.type === \"raw-text\") {\n segments.push({ text: child.text, style: currentStyle });\n } else {\n // Recurse into child node with current style as inherited\n segments.push(...collectStyledSegments(child, currentStyle));\n }\n }\n \n return segments;\n}\n","import type {\n GlyphNode,\n GlyphTextInstance,\n GlyphContainer,\n GlyphNodeType,\n GlyphChild,\n} from \"./nodes.js\";\nimport {\n createGlyphNode,\n appendChild as glyphAppendChild,\n appendTextChild as glyphAppendTextChild,\n removeChild as glyphRemoveChild,\n removeTextChild as glyphRemoveTextChild,\n insertBefore as glyphInsertBefore,\n insertTextBefore as glyphInsertTextBefore,\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 glyphAppendTextChild(parentInstance, child as GlyphTextInstance);\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 glyphAppendTextChild(parentInstance, child as GlyphTextInstance);\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\") {\n glyphInsertTextBefore(parentInstance, child as GlyphTextInstance, beforeChild as GlyphChild);\n } else if (beforeChild.type === \"raw-text\") {\n // Insert node before a text child - need to handle allChildren ordering\n const node = child as GlyphNode;\n node.parent = parentInstance;\n parentInstance.children.push(node);\n const allIdx = parentInstance.allChildren.indexOf(beforeChild as GlyphChild);\n if (allIdx !== -1) {\n parentInstance.allChildren.splice(allIdx, 0, node);\n } else {\n parentInstance.allChildren.push(node);\n }\n } else {\n glyphInsertBefore(parentInstance, child as GlyphNode, beforeChild as GlyphNode);\n }\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 glyphRemoveTextChild(parentInstance, child as GlyphTextInstance);\n } else {\n glyphRemoveChild(parentInstance, child as GlyphNode);\n }\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 \"space\";\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 const nextChar = data[i + 1]!;\n keys.push({\n name: nextChar === \" \" ? \"space\" : nextChar.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 (space gets special name)\n keys.push({ name: ch === \" \" ? \"space\" : 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, TextSegment } from \"../reconciler/nodes.js\";\nimport { getInheritedTextStyle, collectTextContent, collectStyledSegments } 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\n/** A character with its associated style for painting */\ninterface StyledChar {\n char: string;\n style: TextSegment[\"style\"];\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 \n // Collect styled segments from the nested text tree\n const segments = collectStyledSegments(node, inherited);\n if (segments.length === 0) return;\n \n const wrapMode = node.style.wrap ?? \"wrap\";\n const textAlign = node.style.textAlign ?? \"left\";\n \n // Build a flat array of styled characters, preserving style per character\n // Also track newlines for proper line handling\n const styledChars: StyledChar[] = [];\n const lineBreaks: number[] = []; // Indices where newlines occur\n \n for (const segment of segments) {\n // Parse ANSI codes within the segment text\n const ansiSegments = parseAnsi(segment.text);\n \n for (const ansiSeg of ansiSegments) {\n for (const char of ansiSeg.text) {\n if (char === \"\\n\") {\n lineBreaks.push(styledChars.length);\n } else {\n // Merge segment style with ANSI style (ANSI takes precedence)\n const mergedStyle: TextSegment[\"style\"] = {\n color: ansiSeg.style.fg ?? segment.style.color,\n bg: ansiSeg.style.bg ?? segment.style.bg,\n bold: ansiSeg.style.bold ?? segment.style.bold,\n dim: ansiSeg.style.dim ?? segment.style.dim,\n italic: ansiSeg.style.italic ?? segment.style.italic,\n underline: ansiSeg.style.underline ?? segment.style.underline,\n };\n styledChars.push({ char, style: mergedStyle });\n }\n }\n }\n }\n \n // Split into lines at line breaks\n const lines: StyledChar[][] = [];\n let lineStart = 0;\n for (const breakIdx of lineBreaks) {\n lines.push(styledChars.slice(lineStart, breakIdx));\n lineStart = breakIdx;\n }\n lines.push(styledChars.slice(lineStart)); // Last line (or only line if no breaks)\n \n // Wrap each line and track styled chars\n const wrappedLines: StyledChar[][] = [];\n \n for (const line of lines) {\n if (line.length === 0) {\n wrappedLines.push([]);\n continue;\n }\n \n // Get plain text for wrapping calculation\n const plainText = line.map(sc => sc.char).join(\"\");\n const wrapped = wrapLines([plainText], innerWidth, wrapMode);\n \n // Map wrapped lines back to styled chars\n let charIdx = 0;\n for (const wrappedText of wrapped) {\n const wrappedLine: StyledChar[] = [];\n for (const char of wrappedText) {\n if (charIdx < line.length) {\n wrappedLine.push(line[charIdx]!);\n charIdx++;\n }\n }\n wrappedLines.push(wrappedLine);\n }\n }\n \n // Paint each wrapped line\n for (let lineIdx = 0; lineIdx < wrappedLines.length && lineIdx < innerHeight; lineIdx++) {\n const line = wrappedLines[lineIdx]!;\n const visibleWidth = line.reduce((sum, sc) => sum + stringWidth(sc.char), 0);\n \n let offsetX = 0;\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 let col = 0;\n for (const { char, style } of line) {\n const charWidth = stringWidth(char);\n if (charWidth > 0) {\n const fg = autoContrastFg(style.color, style.bg);\n setClipped(\n fb, clip,\n innerX + offsetX + col, innerY + lineIdx,\n char,\n fg, style.bg, style.bold, style.dim, style.italic, style.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 // Only create new layout object if values actually changed (prevents infinite re-renders)\n const prev = node.layout;\n if (!prev || \n prev.x !== x || prev.y !== y || \n prev.width !== width || prev.height !== height ||\n prev.innerX !== innerX || prev.innerY !== innerY ||\n prev.innerWidth !== innerWidth || prev.innerHeight !== innerHeight) {\n node.layout = { x, y, width, height, innerX, innerY, innerWidth, innerHeight };\n }\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 /** \n * Register a focusable element. \n * @param autoFocus - If false, element won't receive auto-focus when nothing is focused (default: true)\n */\n register(id: string, node: GlyphNode, autoFocus?: boolean): () => void;\n requestFocus(id: string): void;\n /** Clear focus from all elements */\n blur(): 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\n// ---- Image Overlay Context ----\n/** Pending image to be rendered after framebuffer paint */\nexport interface PendingImage {\n id: number;\n data: Buffer;\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\nexport interface ImageOverlayContextValue {\n /** Register an image to be rendered after paint */\n registerImage(image: PendingImage): void;\n /** Unregister an image (when component unmounts or image is cleared) */\n unregisterImage(id: number): void;\n}\n\nexport const ImageOverlayContext = createContext<ImageOverlayContextValue | null>(null);\n","/**\n * Terminal capability detection for image protocols\n */\n\nexport interface TerminalCapabilities {\n name: string;\n supportsKittyGraphics: boolean;\n supportsIterm2Images: boolean;\n supportsSixel: boolean;\n}\n\n// Cache the result\nlet cachedCapabilities: TerminalCapabilities | null = null;\n\n/**\n * Detect which terminal we're running in and what image protocols it supports\n */\nexport function detectTerminalCapabilities(debug = false): TerminalCapabilities {\n if (cachedCapabilities) return cachedCapabilities;\n\n const term = process.env.TERM || \"\";\n const termProgram = process.env.TERM_PROGRAM || \"\";\n const kittyWindowId = process.env.KITTY_WINDOW_ID;\n const ghosttyResourcesDir = process.env.GHOSTTY_RESOURCES_DIR;\n const weztermPane = process.env.WEZTERM_PANE;\n const lcTerminal = process.env.LC_TERMINAL || \"\";\n const konsoleVersion = process.env.KONSOLE_VERSION;\n\n // Kitty - native Kitty graphics protocol\n if (kittyWindowId || term === \"xterm-kitty\") {\n cachedCapabilities = {\n name: \"kitty\",\n supportsKittyGraphics: true,\n supportsIterm2Images: false,\n supportsSixel: false,\n };\n return cachedCapabilities;\n }\n\n // Ghostty - supports Kitty graphics protocol\n if (ghosttyResourcesDir || term.includes(\"ghostty\")) {\n cachedCapabilities = {\n name: \"ghostty\",\n supportsKittyGraphics: true,\n supportsIterm2Images: false,\n supportsSixel: false,\n };\n return cachedCapabilities;\n }\n\n // WezTerm - supports iTerm2 inline images protocol\n if (weztermPane || termProgram === \"WezTerm\") {\n cachedCapabilities = {\n name: \"wezterm\",\n supportsKittyGraphics: true, // WezTerm also supports Kitty protocol\n supportsIterm2Images: true,\n supportsSixel: true,\n };\n return cachedCapabilities;\n }\n\n // iTerm2 - native iTerm2 inline images\n if (termProgram === \"iTerm.app\" || lcTerminal === \"iTerm2\") {\n cachedCapabilities = {\n name: \"iterm2\",\n supportsKittyGraphics: false,\n supportsIterm2Images: true,\n supportsSixel: false,\n };\n return cachedCapabilities;\n }\n\n // Konsole - supports Sixel\n if (konsoleVersion) {\n cachedCapabilities = {\n name: \"konsole\",\n supportsKittyGraphics: false,\n supportsIterm2Images: false,\n supportsSixel: true,\n };\n return cachedCapabilities;\n }\n\n // VS Code terminal - limited support\n if (termProgram === \"vscode\") {\n cachedCapabilities = {\n name: \"vscode\",\n supportsKittyGraphics: false,\n supportsIterm2Images: false,\n supportsSixel: false,\n };\n return cachedCapabilities;\n }\n\n // Default: unknown terminal, no image support\n cachedCapabilities = {\n name: \"unknown\",\n supportsKittyGraphics: false,\n supportsIterm2Images: false,\n supportsSixel: false,\n };\n return cachedCapabilities;\n}\n\n/**\n * Check if the terminal supports any inline image protocol\n */\nexport function supportsInlineImages(): boolean {\n const caps = detectTerminalCapabilities();\n return caps.supportsKittyGraphics || caps.supportsIterm2Images || caps.supportsSixel;\n}\n\n/**\n * Reset cached capabilities (useful for testing)\n */\nexport function resetCapabilitiesCache(): void {\n cachedCapabilities = null;\n}\n","/**\n * Terminal image protocol implementations\n * \n * Supports:\n * - Kitty Graphics Protocol (Kitty, Ghostty, WezTerm)\n * - iTerm2 Inline Images Protocol (iTerm2, WezTerm)\n */\n\nimport { detectTerminalCapabilities } from \"./terminalCapabilities.js\";\n\nconst ESC = \"\\x1b\";\n\nexport interface ImageRenderOptions {\n /** Image data as Buffer */\n data: Buffer;\n /** Target width in terminal cells */\n width: number;\n /** Target height in terminal cells */\n height: number;\n /** X position (0-indexed) */\n x: number;\n /** Y position (0-indexed) */\n y: number;\n /** Unique ID for the image (for Kitty protocol) */\n id?: number;\n}\n\n/**\n * Check if we're running inside tmux\n */\nfunction inTmux(): boolean {\n return !!process.env.TMUX;\n}\n\n/**\n * Wrap an escape sequence for tmux passthrough\n * \n * Tmux DCS passthrough format:\n * \\x1bPtmux;<inner-with-ESC-doubled>\\x1b\\\\\n * \n * All \\x1b characters inside the inner sequence become \\x1b\\x1b\n */\nfunction tmuxWrap(seq: string): string {\n if (!inTmux()) return seq;\n \n // Double all ESC characters in the inner sequence\n const doubled = seq.replace(/\\x1b/g, \"\\x1b\\x1b\");\n return `${ESC}Ptmux;${doubled}${ESC}\\\\`;\n}\n\n/**\n * Generate escape sequence to render an image at the specified position\n * Returns null if terminal doesn't support inline images\n */\nexport function renderImageEscapeSequence(opts: ImageRenderOptions): string | null {\n const caps = detectTerminalCapabilities();\n\n if (caps.supportsKittyGraphics) {\n return renderKittyGraphics(opts);\n }\n\n if (caps.supportsIterm2Images) {\n return renderIterm2Image(opts);\n }\n\n return null;\n}\n\n/**\n * Generate escape sequence to clear an image (Kitty protocol)\n */\nexport function clearImageEscapeSequence(id?: number): string | null {\n const caps = detectTerminalCapabilities();\n\n if (caps.supportsKittyGraphics) {\n let seq: string;\n // Delete all images or specific image by ID\n if (id !== undefined) {\n seq = `${ESC}_Ga=d,d=i,i=${id}${ESC}\\\\`;\n } else {\n // Delete all images\n seq = `${ESC}_Ga=d,d=a${ESC}\\\\`;\n }\n return tmuxWrap(seq);\n }\n\n return null;\n}\n\n/**\n * Kitty Graphics Protocol\n * https://sw.kovidgoyal.net/kitty/graphics-protocol/\n */\nfunction renderKittyGraphics(opts: ImageRenderOptions): string {\n const { data, width, height, x, y, id } = opts;\n const base64 = data.toString(\"base64\");\n\n // Move cursor to position first\n const moveCursor = `${ESC}[${y + 1};${x + 1}H`;\n\n // Try to get image dimensions\n const dims = getImageDimensions(data);\n \n // Build command matching chafa's format:\n // a=T - action: transmit and display\n // f=100 - format: PNG\n // s=<pixels> - source width in pixels\n // v=<pixels> - source height in pixels \n // c=<cols> - width in cells\n // r=<rows> - height in cells\n // m=0/1 - more chunks (0=last, 1=more coming)\n // q=2 - quiet mode (suppress OK response)\n \n let cmd = `a=T,f=100`;\n // Assign image ID so we can delete it later\n if (id !== undefined) {\n cmd += `,i=${id}`;\n }\n if (dims) {\n cmd += `,s=${dims.width},v=${dims.height}`;\n }\n cmd += `,c=${width},r=${height}`;\n \n // Kitty protocol uses chunked transmission for large images\n // Each chunk is max 4096 bytes of base64\n const chunkSize = 4096;\n const result: string[] = [moveCursor];\n \n // In tmux, hide cursor first (not wrapped)\n if (inTmux()) {\n result.unshift(`${ESC}[?25l`);\n }\n\n for (let i = 0; i < base64.length; i += chunkSize) {\n const chunk = base64.slice(i, i + chunkSize);\n const isLast = i + chunkSize >= base64.length;\n const more = isLast ? \"m=0\" : \"m=1\";\n\n let escSeq: string;\n if (i === 0) {\n // First chunk includes the full command\n escSeq = `${ESC}_G${cmd},${more},q=2;${chunk}${ESC}\\\\`;\n } else {\n // Subsequent chunks are continuation\n escSeq = `${ESC}_G${more};${chunk}${ESC}\\\\`;\n }\n \n result.push(tmuxWrap(escSeq));\n }\n \n // In tmux, show cursor after (not wrapped)\n if (inTmux()) {\n result.push(`${ESC}[?25h`);\n }\n\n return result.join(\"\");\n}\n\n/**\n * iTerm2 Inline Images Protocol\n * https://iterm2.com/documentation-images.html\n */\nfunction renderIterm2Image(opts: ImageRenderOptions): string {\n const { data, width, height, x, y } = opts;\n const base64 = data.toString(\"base64\");\n\n // Move cursor to position first\n const moveCursor = `${ESC}[${y + 1};${x + 1}H`;\n\n // iTerm2 uses OSC 1337 for inline images\n // Params:\n // width=<n> - width in cells\n // height=<n> - height in cells\n // preserveAspectRatio=1 - maintain aspect ratio\n // inline=1 - display inline\n\n const params = [\n `width=${width}`,\n `height=${height}`,\n \"preserveAspectRatio=1\",\n \"inline=1\",\n ].join(\";\");\n\n // OSC 1337 ; File=<params> : <base64> BEL\n // May need tmux wrapping too\n const imgSeq = `${ESC}]1337;File=${params}:${base64}\\x07`;\n return moveCursor + (inTmux() ? tmuxWrap(imgSeq) : imgSeq);\n}\n\n/**\n * Get the aspect ratio of a PNG/JPEG image from its header\n * Returns { width, height } in pixels or null if can't parse\n */\nexport function getImageDimensions(data: Buffer): { width: number; height: number } | null {\n // PNG signature: 89 50 4E 47 0D 0A 1A 0A\n if (data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {\n // IHDR chunk starts at byte 8, width at 16, height at 20 (big-endian)\n if (data.length >= 24) {\n const width = data.readUInt32BE(16);\n const height = data.readUInt32BE(20);\n return { width, height };\n }\n }\n\n // JPEG signature: FF D8 FF\n if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {\n // Parse JPEG segments to find SOF (Start of Frame)\n let offset = 2;\n while (offset < data.length - 8) {\n if (data[offset] !== 0xff) {\n offset++;\n continue;\n }\n\n const marker = data[offset + 1];\n \n // SOF markers: 0xC0-0xC3, 0xC5-0xC7, 0xC9-0xCB, 0xCD-0xCF\n if (marker !== undefined && (\n (marker >= 0xc0 && marker <= 0xc3) ||\n (marker >= 0xc5 && marker <= 0xc7) ||\n (marker >= 0xc9 && marker <= 0xcb) ||\n (marker >= 0xcd && marker <= 0xcf)\n )) {\n // Height at offset+5, width at offset+7 (big-endian, 2 bytes each)\n const height = data.readUInt16BE(offset + 5);\n const width = data.readUInt16BE(offset + 7);\n return { width, height };\n }\n\n // Skip to next segment\n const segmentLength = data.readUInt16BE(offset + 2);\n offset += 2 + segmentLength;\n }\n }\n\n // GIF signature: GIF87a or GIF89a\n if (data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46) {\n if (data.length >= 10) {\n const width = data.readUInt16LE(6);\n const height = data.readUInt16LE(8);\n return { width, height };\n }\n }\n\n return null;\n}\n\n/**\n * Calculate terminal cell dimensions for an image while preserving aspect ratio\n */\nexport function calculateCellDimensions(\n imageWidth: number,\n imageHeight: number,\n maxCellWidth: number,\n maxCellHeight: number,\n cellAspectRatio = 2.0, // Terminal cells are typically ~2x taller than wide\n): { width: number; height: number } {\n // Convert max cell dimensions to \"pixel-equivalent\" units\n const maxPixelWidth = maxCellWidth;\n const maxPixelHeight = maxCellHeight * cellAspectRatio;\n\n // Calculate scale to fit\n const scaleX = maxPixelWidth / imageWidth;\n const scaleY = maxPixelHeight / imageHeight;\n const scale = Math.min(scaleX, scaleY);\n\n // Calculate final dimensions\n const finalPixelWidth = imageWidth * scale;\n const finalPixelHeight = imageHeight * scale;\n\n // Convert back to cell dimensions\n const cellWidth = Math.max(1, Math.round(finalPixelWidth));\n const cellHeight = Math.max(1, Math.round(finalPixelHeight / cellAspectRatio));\n\n return { width: cellWidth, height: cellHeight };\n}\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 ImageOverlayContext,\n} from \"./hooks/context.js\";\nimport { clearImageEscapeSequence } from \"./runtime/imageProtocol.js\";\nimport type {\n InputHandler,\n FocusedInputHandler,\n PriorityInputHandler,\n InputContextValue,\n FocusContextValue,\n LayoutContextValue,\n AppContextValue,\n ImageOverlayContextValue,\n PendingImage,\n} from \"./hooks/context.js\";\nimport { renderImageEscapeSequence } from \"./runtime/imageProtocol.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 // ---- Image overlay system ----\n // Track which images have been rendered (to avoid re-sending on every frame)\n const renderedImages = new Map<number, { x: number; y: number; width: number; height: number }>();\n const pendingImageRenders = new Map<number, PendingImage>();\n\n const imageOverlayContextValue: ImageOverlayContextValue = {\n registerImage(image: PendingImage) {\n const existing = renderedImages.get(image.id);\n // Only re-render if position/size changed\n if (!existing || existing.x !== image.x || existing.y !== image.y ||\n existing.width !== image.width || existing.height !== image.height) {\n pendingImageRenders.set(image.id, image);\n scheduleRender();\n }\n },\n unregisterImage(id: number) {\n renderedImages.delete(id);\n pendingImageRenders.delete(id);\n // Clear the image from terminal\n const clearSeq = clearImageEscapeSequence(id);\n if (clearSeq) {\n terminal.write(clearSeq);\n }\n scheduleRender(); // Redraw to fill the cleared space\n },\n };\n\n function renderPendingImages(): void {\n // Only render images that haven't been rendered yet or have moved\n for (const image of pendingImageRenders.values()) {\n const escapeSeq = renderImageEscapeSequence({\n data: image.data,\n width: image.width,\n height: image.height,\n x: image.x,\n y: image.y,\n id: image.id,\n });\n if (escapeSeq) {\n terminal.write(escapeSeq);\n renderedImages.set(image.id, { x: image.x, y: image.y, width: image.width, height: image.height });\n }\n }\n pendingImageRenders.clear();\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 const noAutoFocusIds = new Set<string>(); // Elements that shouldn't receive auto-focus\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, autoFocus: boolean = true) {\n focusRegistry.set(id, node);\n if (!focusOrder.includes(id)) {\n focusOrder.push(id);\n }\n // Track if element should not receive auto-focus\n if (!autoFocus) {\n noAutoFocusIds.add(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 // Skip elements that opted out of auto-focus\n if (focusedId === null && autoFocus) {\n const activeIds = getActiveFocusableIds().filter(i => !noAutoFocusIds.has(i));\n if (activeIds.length > 0) {\n setFocusedId(activeIds[0]!);\n }\n }\n return () => {\n focusRegistry.delete(id);\n noAutoFocusIds.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 (excluding noAutoFocus elements)\n const activeIds = getActiveFocusableIds().filter(i => !noAutoFocusIds.has(i));\n setFocusedId(activeIds[0] ?? null);\n }\n };\n },\n requestFocus(id: string) {\n setFocusedId(id);\n },\n blur() {\n setFocusedId(null);\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 // Render images on top of framebuffer\n // Hide cursor while rendering images to prevent artifacts\n if (pendingImageRenders.size > 0 && nativeCursorVisible) {\n terminal.hideCursor();\n nativeCursorVisible = false;\n }\n renderPendingImages();\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 - always hide native cursor\n // (ensures cursor is hidden when Image or other non-input is focused)\n terminal.hideCursor();\n nativeCursorVisible = false;\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 React.createElement(\n ImageOverlayContext.Provider,\n { value: imageOverlayContextValue },\n element,\n ),\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 \n // Clear any rendered images before cleaning up terminal\n const clearSeq = clearImageEscapeSequence();\n if (clearSeq) {\n terminal.write(clearSeq);\n }\n \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, useContext, useEffect, useRef, useState, useImperativeHandle } from \"react\";\nimport type { Style, TextHandle } from \"../types/index.js\";\nimport type { ReactNode } from \"react\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { FocusContext } from \"../hooks/context.js\";\n\nexport interface TextProps {\n style?: Style;\n children?: ReactNode;\n wrap?: Style[\"wrap\"];\n focusable?: boolean;\n focusedStyle?: Style;\n}\n\nexport const Text = forwardRef<TextHandle, TextProps>(\n function Text({ children, style, wrap, focusable, focusedStyle }, ref): React.JSX.Element {\n const focusCtx = useContext(FocusContext);\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const [isFocused, setIsFocused] = useState(false);\n\n // Expose imperative handle\n useImperativeHandle(ref, () => ({\n focus() {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n },\n blur() {\n if (focusCtx) {\n focusCtx.blur();\n }\n },\n get isFocused() {\n return isFocused;\n },\n }), [focusCtx, isFocused]);\n\n // Track focus state\n useEffect(() => {\n if (!focusCtx || !focusable || !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, focusable]);\n\n // Merge styles\n let mergedStyle = wrap ? { ...style, wrap } : style;\n if (isFocused && focusedStyle) {\n mergedStyle = { ...mergedStyle, ...focusedStyle };\n }\n\n // Internal ref callback\n const setRef = (node: GlyphNode | null) => {\n nodeRef.current = node;\n focusIdRef.current = node?.focusId ?? null;\n };\n\n return React.createElement(\"text\" as any, { style: mergedStyle, focusable, ref: setRef }, children);\n }\n);\n","import React, { useState, useContext, useEffect, useRef, forwardRef, useImperativeHandle } from \"react\";\nimport type { Style, Key, InputHandle } 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 const Input = forwardRef<InputHandle, InputProps>(\n function Input(props, ref) {\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 // Expose imperative handle\n useImperativeHandle(ref, () => ({\n focus() {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n },\n blur() {\n if (focusCtx) {\n focusCtx.blur();\n }\n },\n get isFocused() {\n return isFocused;\n },\n get value() {\n return workingValueRef.current;\n },\n }), [focusCtx, isFocused]);\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);\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, useCallback, useImperativeHandle, forwardRef } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key, ButtonHandle } 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 const Button = forwardRef<ButtonHandle, ButtonProps>(\n function Button({ onPress, style, focusedStyle, children, disabled }, ref) {\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 // Expose imperative handle\n useImperativeHandle(ref, () => ({\n focus() {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n },\n blur() {\n if (focusCtx) {\n focusCtx.blur();\n }\n },\n get isFocused() {\n return isFocused;\n },\n }), [focusCtx, isFocused]);\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);\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\n/** Visible range passed to render function in virtualized mode */\nexport interface VisibleRange {\n /** First visible line index (0-based) */\n start: number;\n /** One past the last visible line index */\n end: number;\n /** Current scroll offset */\n scrollOffset: number;\n /** Viewport height in lines */\n viewportHeight: number;\n}\n\nexport interface ScrollViewProps {\n /** \n * Children to render. When `virtualize` is true, only visible children are rendered.\n * Can also be a render function `(range: VisibleRange) => ReactNode` for line-based virtualization.\n */\n children?: ReactNode | ((range: VisibleRange) => 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 * Total content height in lines (for render function mode).\n * When set with a render function, enables line-based virtualization.\n */\n totalLines?: number;\n /** Extra lines to render above/below viewport (default: 2) */\n overscan?: number;\n /**\n * Enable virtualization. When true, only visible children are rendered.\n * Heights are auto-measured - no need to specify them!\n */\n virtualize?: boolean;\n /**\n * Estimated height per child in lines (default: 1).\n * Used for initial scroll calculations before actual heights are measured.\n */\n estimatedItemHeight?: number;\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 totalLines,\n overscan = 2,\n virtualize = false,\n estimatedItemHeight = 1,\n}: ScrollViewProps): React.JSX.Element {\n const isControlled = controlledOffset !== undefined;\n const [internalOffset, setInternalOffset] = useState(defaultScrollOffset);\n const offset = isControlled ? controlledOffset : internalOffset;\n\n // Check what kind of children we have\n const isRenderFunction = typeof children === \"function\";\n \n // Convert children to array for virtualization (handles fragments, single elements, etc.)\n const childArray = useMemo(() => {\n if (isRenderFunction) return [];\n return React.Children.toArray(children);\n }, [children, isRenderFunction]);\n \n // Line-based virtualization: render function + totalLines\n const isLineVirtualized = totalLines !== undefined && isRenderFunction;\n \n // Array virtualization: enabled when virtualize flag is set and we have children\n const isArrayVirtualized = virtualize && !isRenderFunction && childArray.length > 0;\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 // Track measured heights for array items (index -> height in lines)\n const measuredHeightsRef = useRef<Map<number, number>>(new Map());\n const itemRefsRef = useRef<Map<number, GlyphNode>>(new Map());\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 \n // Calculate total content height based on mode\n const getArrayTotalHeight = useCallback(() => {\n if (!isArrayVirtualized) return 0;\n let total = 0;\n for (let i = 0; i < childArray.length; i++) {\n total += measuredHeightsRef.current.get(i) ?? estimatedItemHeight;\n }\n return total;\n }, [isArrayVirtualized, childArray.length, estimatedItemHeight]);\n \n // Content height: line-virtualized uses totalLines, array-virtualized calculates, otherwise measure\n const contentHeight = isLineVirtualized \n ? totalLines! \n : isArrayVirtualized \n ? getArrayTotalHeight() \n : 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 // Calculate visible range for line-based virtualization\n const visibleRange = useMemo((): VisibleRange => {\n const start = Math.max(0, effectiveOffset - overscan);\n const end = Math.min(totalLines ?? contentHeight, effectiveOffset + viewportHeight + overscan);\n return {\n start,\n end,\n scrollOffset: effectiveOffset,\n viewportHeight,\n };\n }, [effectiveOffset, viewportHeight, overscan, totalLines, contentHeight]);\n\n // Calculate visible items for array virtualization\n const getVisibleArrayItems = useCallback((): { startIndex: number; endIndex: number; startOffset: number } => {\n if (!isArrayVirtualized) return { startIndex: 0, endIndex: 0, startOffset: 0 };\n \n let currentOffset = 0;\n let startIndex = 0;\n let startOffset = 0;\n \n // Find first visible item\n for (let i = 0; i < childArray.length; i++) {\n const itemHeight = measuredHeightsRef.current.get(i) ?? estimatedItemHeight;\n if (currentOffset + itemHeight > effectiveOffset - overscan) {\n startIndex = i;\n startOffset = currentOffset;\n break;\n }\n currentOffset += itemHeight;\n startIndex = i + 1;\n startOffset = currentOffset;\n }\n \n // Find last visible item\n let endIndex = startIndex;\n for (let i = startIndex; i < childArray.length; i++) {\n const itemHeight = measuredHeightsRef.current.get(i) ?? estimatedItemHeight;\n endIndex = i + 1;\n currentOffset += itemHeight;\n if (currentOffset >= effectiveOffset + viewportHeight + overscan) {\n break;\n }\n }\n \n return { startIndex, endIndex, startOffset };\n }, [isArrayVirtualized, childArray.length, effectiveOffset, viewportHeight, overscan, estimatedItemHeight]);\n\n const arrayVisibility = getVisibleArrayItems();\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 // In virtualized mode, we render at the visible start position.\n const innerStyle: Style = {\n position: \"absolute\" as const,\n top: isLineVirtualized \n ? visibleRange.start - effectiveOffset \n : isArrayVirtualized \n ? arrayVisibility.startOffset - effectiveOffset\n : -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 // Resolve children based on mode\n const renderedChildren: ReactNode = isLineVirtualized \n ? (children as (range: VisibleRange) => ReactNode)(visibleRange)\n : isArrayVirtualized\n ? childArray.slice(arrayVisibility.startIndex, arrayVisibility.endIndex).map((child, i) => {\n const actualIndex = arrayVisibility.startIndex + i;\n return React.createElement(\n \"box\" as any,\n {\n key: actualIndex,\n ref: (node: GlyphNode | null) => {\n if (node) {\n itemRefsRef.current.set(actualIndex, node);\n } else {\n itemRefsRef.current.delete(actualIndex);\n }\n },\n },\n child\n );\n })\n : (children as ReactNode);\n\n // Measure item heights after render (for array virtualization)\n const [, forceUpdate] = useState(0);\n useEffect(() => {\n if (!isArrayVirtualized || !layoutCtx) return;\n \n let needsUpdate = false;\n for (const [index, node] of itemRefsRef.current) {\n const layout = layoutCtx.getLayout(node);\n const measuredHeight = layout.height || estimatedItemHeight;\n const currentHeight = measuredHeightsRef.current.get(index);\n \n if (currentHeight !== measuredHeight) {\n measuredHeightsRef.current.set(index, measuredHeight);\n needsUpdate = true;\n }\n }\n \n // Trigger re-render if heights changed to recalculate total content height\n if (needsUpdate) {\n forceUpdate(n => n + 1);\n }\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 renderedChildren,\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, forwardRef, useImperativeHandle } from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key, ListHandle } 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 const List = forwardRef<ListHandle, ListProps>(\n function List({\n count,\n renderItem,\n selectedIndex: controlledIndex,\n onSelectionChange,\n onSelect,\n defaultSelectedIndex = 0,\n disabledIndices,\n style,\n focusable = true,\n }, ref) {\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\n // Expose imperative handle\n useImperativeHandle(ref, () => ({\n focus() {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n },\n blur() {\n if (focusCtx) {\n focusCtx.blur();\n }\n },\n get isFocused() {\n return isFocused;\n },\n get selectedIndex() {\n return selectedIndex;\n },\n }), [focusCtx, isFocused, selectedIndex]);\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);\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 forwardRef,\n useImperativeHandle,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport type { Style, Key, Color, SelectHandle } 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 /** Force dropdown open direction: \"up\", \"down\", or \"auto\" (default: \"auto\") */\n openDirection?: \"up\" | \"down\" | \"auto\";\n /** Disabled state */\n disabled?: boolean;\n}\n\nexport const Select = forwardRef<SelectHandle, SelectProps>(\n 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 openDirection = \"auto\",\n disabled,\n }, ref) {\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\n // Expose imperative handle\n useImperativeHandle(ref, () => ({\n focus() {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n },\n blur() {\n if (focusCtx) {\n focusCtx.blur();\n }\n },\n get isFocused() {\n return isFocused;\n },\n get value() {\n return value;\n },\n get isOpen() {\n return isOpen;\n },\n }), [focusCtx, isFocused, value, isOpen]);\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 ) {\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 // Determine open direction\n const openUpward = openDirection === \"up\" \n ? true \n : openDirection === \"down\" \n ? false \n : 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);\n","import React, { useContext, useEffect, useRef, useState, forwardRef, useImperativeHandle } from \"react\";\nimport type { Style, Key, CheckboxHandle } 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 const Checkbox = forwardRef<CheckboxHandle, CheckboxProps>(\n function Checkbox({\n checked,\n onChange,\n label,\n style,\n focusedStyle,\n disabled,\n checkedChar = \"✓\",\n uncheckedChar = \" \",\n }, ref) {\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 // Expose imperative handle\n useImperativeHandle(ref, () => ({\n focus() {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n },\n blur() {\n if (focusCtx) {\n focusCtx.blur();\n }\n },\n get isFocused() {\n return isFocused;\n },\n get checked() {\n return checkedRef.current;\n },\n }), [focusCtx, isFocused]);\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);\n","import React, { useContext, useEffect, useRef, useState, useCallback, forwardRef, useImperativeHandle } from \"react\";\nimport type { Style, Key, RadioHandle } 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\nfunction RadioInner<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 forwardedRef,\n}: RadioProps<T> & { forwardedRef?: React.Ref<RadioHandle<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\n // Expose imperative handle\n useImperativeHandle(forwardedRef, () => ({\n focus() {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n },\n blur() {\n if (focusCtx) {\n focusCtx.blur();\n }\n },\n get isFocused() {\n return isFocused;\n },\n get value() {\n return value;\n },\n }), [focusCtx, isFocused, value]);\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\n/**\n * Radio group component with imperative handle support.\n * Use `ref` to get `{ focus, blur, isFocused, value }`.\n */\nexport const Radio = forwardRef(function Radio<T = string>(\n props: RadioProps<T>,\n ref: React.Ref<RadioHandle<T>>,\n) {\n return React.createElement(RadioInner, { ...props, forwardedRef: ref } as any);\n}) as <T = string>(props: RadioProps<T> & React.RefAttributes<RadioHandle<T>>) => React.JSX.Element;\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, AppContext } from \"../hooks/context.js\";\n\ninterface ClipRect {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\ninterface TrackedElement {\n id: string;\n node: GlyphNode;\n layout: LayoutRect;\n /** Effective clip region from ancestor ScrollViews/clipped containers */\n clipRegion: ClipRect;\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/**\n * Compute the effective clip region for a node by walking up its parent chain\n * and intersecting all ancestor clip regions. This tells us the actual visible\n * area for the element (accounting for ScrollViews, clipped containers, etc.)\n */\nfunction computeEffectiveClip(node: GlyphNode, screenClip: ClipRect): ClipRect {\n // Collect clip regions from ancestors (bottom-up)\n const clips: ClipRect[] = [];\n let current: GlyphNode | null = node.parent;\n while (current) {\n if (current.style.clip) {\n clips.push({\n x: current.layout.innerX,\n y: current.layout.innerY,\n width: current.layout.innerWidth,\n height: current.layout.innerHeight,\n });\n }\n current = current.parent;\n }\n\n // Start with the screen and intersect all ancestor clips\n let result = screenClip;\n for (const clip of clips) {\n result = intersectClip(result, clip);\n }\n return result;\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\n/**\n * Check if an element is at least partially visible within its clip region\n */\nfunction isElementVisible(layout: LayoutRect, clip: ClipRect): boolean {\n if (clip.width <= 0 || clip.height <= 0) return false;\n const elRight = layout.x + layout.width;\n const elBottom = layout.y + layout.height;\n return (\n layout.x < clip.x + clip.width &&\n elRight > clip.x &&\n layout.y < clip.y + clip.height &&\n elBottom > clip.y\n );\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 const appCtx = useContext(AppContext);\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 screenColumns = appCtx?.columns ?? 80;\n const screenRows = appCtx?.rows ?? 24;\n const screenClip: ClipRect = { x: 0, y: 0, width: screenColumns, height: screenRows };\n \n const mapped: TrackedElement[] = active.map(({ id, node }) => ({\n id,\n node,\n layout: layoutCtx?.getLayout(node) ?? node.layout,\n clipRegion: computeEffectiveClip(node, screenClip),\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, appCtx, 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 // Screen dimensions for boundary checks\n const screenColumns = appCtx?.columns ?? 80;\n const screenRows = appCtx?.rows ?? 24;\n\n // Filter elements: must have valid layout AND be within their clip region (ScrollView, screen, etc.)\n const visibleElements = elements.filter(el => \n el.layout.width > 0 && el.layout.height > 0 &&\n isElementVisible(el.layout, el.clipRegion)\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 const { x, y, width: elWidth } = el.layout;\n const clip = el.clipRegion;\n \n // Label width = hint text + 2 chars padding (1 each side)\n const labelWidth = hint.length + 2;\n \n // Clamp Y within the element's visible clip region and screen\n const clampedY = Math.max(clip.y, Math.min(y, clip.y + clip.height - 1, screenRows - 1));\n \n // Try placing the label to the LEFT of the element\n const leftPos = x - labelWidth;\n // Try placing the label to the RIGHT of the element\n const rightPos = x + elWidth;\n \n let labelX: number;\n \n if (leftPos >= clip.x && leftPos >= 0) {\n // Fits to the left — default position\n labelX = leftPos;\n } else if (rightPos + labelWidth <= clip.x + clip.width && rightPos + labelWidth <= screenColumns) {\n // Doesn't fit left → place to the right\n labelX = rightPos;\n } else {\n // Doesn't fit on either side cleanly — place at element x, overlapping the element\n labelX = Math.max(clip.x, Math.min(x, screenColumns - labelWidth));\n }\n \n // Final safety clamp to screen\n labelX = Math.max(0, Math.min(labelX, screenColumns - labelWidth));\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: clampedY,\n left: labelX,\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","/**\n * Image loading utilities for local and remote images\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync, unlinkSync } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport { tmpdir, platform } from \"node:os\";\nimport { basename } from \"node:path\";\nimport { execSync } from \"node:child_process\";\n\nexport interface LoadedImage {\n data: Buffer;\n name: string;\n localPath: string;\n isRemote: boolean;\n}\n\n// Cache directory for downloaded images\nconst CACHE_DIR = join(tmpdir(), \"glyph-image-cache\");\n\n/**\n * Check if a string is a URL\n */\nexport function isRemoteUrl(src: string): boolean {\n return src.startsWith(\"http://\") || src.startsWith(\"https://\");\n}\n\n/**\n * Get a cache path for a remote URL (with optional format override)\n */\nfunction getCachePath(url: string, format?: \"png\" | \"jpeg\" | \"gif\" | \"webp\" | \"unknown\"): string {\n const hash = createHash(\"md5\").update(url).digest(\"hex\");\n // Use detected format if provided, otherwise try URL extension, fallback to .png\n const ext = format \n ? getExtensionFromFormat(format) \n : (getExtensionFromUrl(url) || \".png\");\n return join(CACHE_DIR, `${hash}${ext}`);\n}\n\n/**\n * Extract file extension from URL (handles query parameters)\n */\nfunction getExtensionFromUrl(url: string): string {\n try {\n const urlObj = new URL(url);\n const pathname = urlObj.pathname;\n // Match extension anywhere in path (before query params which are already stripped)\n const match = pathname.match(/\\.(png|jpg|jpeg|gif|webp|bmp|ico)/i);\n if (match) {\n // Normalize jpg to jpeg\n const ext = match[0].toLowerCase();\n return ext === \".jpg\" ? \".jpeg\" : ext;\n }\n return \"\"; // Return empty, we'll detect from content\n } catch {\n return \"\";\n }\n}\n\n/**\n * Get file extension from detected image format\n */\nfunction getExtensionFromFormat(format: \"png\" | \"jpeg\" | \"gif\" | \"webp\" | \"unknown\"): string {\n switch (format) {\n case \"png\": return \".png\";\n case \"jpeg\": return \".jpeg\";\n case \"gif\": return \".gif\";\n case \"webp\": return \".webp\";\n default: return \".png\"; // Default to PNG for unknown\n }\n}\n\n/**\n * Extract filename from path or URL\n */\nexport function getImageName(src: string): string {\n if (isRemoteUrl(src)) {\n try {\n const urlObj = new URL(src);\n const pathname = urlObj.pathname;\n const name = basename(pathname);\n return name || urlObj.hostname;\n } catch {\n return \"remote-image\";\n }\n }\n return basename(src);\n}\n\n/**\n * Ensure cache directory exists\n */\nfunction ensureCacheDir(): void {\n if (!existsSync(CACHE_DIR)) {\n mkdirSync(CACHE_DIR, { recursive: true });\n }\n}\n\n/**\n * Load an image from local path or remote URL\n * Returns the image data as a Buffer\n */\nexport async function loadImage(src: string): Promise<LoadedImage> {\n const name = getImageName(src);\n\n if (isRemoteUrl(src)) {\n return loadRemoteImage(src, name);\n }\n\n return loadLocalImage(src, name);\n}\n\n/**\n * Load a local image file\n */\nasync function loadLocalImage(path: string, name: string): Promise<LoadedImage> {\n if (!existsSync(path)) {\n throw new Error(`Image not found: ${path}`);\n }\n\n const data = readFileSync(path);\n return {\n data,\n name,\n localPath: path,\n isRemote: false,\n };\n}\n\n/**\n * Load a remote image (with caching)\n */\nasync function loadRemoteImage(url: string, name: string): Promise<LoadedImage> {\n ensureCacheDir();\n \n // Try to find cached file with any extension\n const hash = createHash(\"md5\").update(url).digest(\"hex\");\n const possibleExtensions = [\".png\", \".jpeg\", \".gif\", \".webp\"];\n for (const ext of possibleExtensions) {\n const possiblePath = join(CACHE_DIR, `${hash}${ext}`);\n if (existsSync(possiblePath)) {\n const data = readFileSync(possiblePath);\n return {\n data,\n name,\n localPath: possiblePath,\n isRemote: true,\n };\n }\n }\n\n // Download the image\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new Error(`Failed to download image: ${response.status} ${response.statusText}`);\n }\n\n const arrayBuffer = await response.arrayBuffer();\n const data = Buffer.from(arrayBuffer);\n\n // Validate it's an image (check magic bytes)\n if (!isValidImage(data)) {\n throw new Error(`Invalid image data from: ${url}`);\n }\n\n // Detect actual format and cache with correct extension\n const format = detectImageFormat(data);\n const cachePath = getCachePath(url, format);\n writeFileSync(cachePath, data);\n\n return {\n data,\n name,\n localPath: cachePath,\n isRemote: true,\n };\n}\n\n/**\n * Check if a buffer contains valid image data (by magic bytes)\n */\nfunction isValidImage(data: Buffer): boolean {\n if (data.length < 4) return false;\n\n // PNG: 89 50 4E 47\n if (data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {\n return true;\n }\n\n // JPEG: FF D8 FF\n if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {\n return true;\n }\n\n // GIF: GIF87a or GIF89a\n if (data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46) {\n return true;\n }\n\n // BMP: BM\n if (data[0] === 0x42 && data[1] === 0x4d) {\n return true;\n }\n\n // WebP: RIFF....WEBP\n if (\n data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46 &&\n data.length >= 12 &&\n data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50\n ) {\n return true;\n }\n\n // ICO: 00 00 01 00\n if (data[0] === 0x00 && data[1] === 0x00 && data[2] === 0x01 && data[3] === 0x00) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Clear the image cache\n */\nexport function clearImageCache(): void {\n // Note: We don't delete the whole directory, just let it be cleaned up by OS\n // This is a simple implementation\n}\n\n/**\n * Detect image format from buffer\n */\nexport function detectImageFormat(data: Buffer): \"png\" | \"jpeg\" | \"gif\" | \"webp\" | \"unknown\" {\n if (data.length < 4) return \"unknown\";\n\n // PNG: 89 50 4E 47\n if (data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47) {\n return \"png\";\n }\n\n // JPEG: FF D8 FF\n if (data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {\n return \"jpeg\";\n }\n\n // GIF: GIF87a or GIF89a\n if (data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46) {\n return \"gif\";\n }\n\n // WebP: RIFF....WEBP\n if (\n data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46 &&\n data.length >= 12 &&\n data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50\n ) {\n return \"webp\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Convert an image to PNG format using system tools\n * Returns the PNG data or null if conversion failed\n */\nexport function convertToPng(data: Buffer, originalPath?: string): Buffer | null {\n const format = detectImageFormat(data);\n \n // Already PNG, no conversion needed\n if (format === \"png\") {\n return data;\n }\n\n // Need to convert - use system tools\n ensureCacheDir();\n const tempId = createHash(\"md5\").update(data).digest(\"hex\");\n const tempInput = join(CACHE_DIR, `${tempId}.${format}`);\n const tempOutput = join(CACHE_DIR, `${tempId}.png`);\n\n try {\n // Write input file\n writeFileSync(tempInput, data);\n\n // Try different conversion tools\n const os = platform();\n let converted = false;\n\n if (os === \"darwin\") {\n // macOS: use sips (built-in)\n try {\n execSync(`sips -s format png \"${tempInput}\" --out \"${tempOutput}\" 2>/dev/null`, {\n stdio: \"pipe\",\n });\n converted = true;\n } catch {\n // sips failed, try other methods\n }\n }\n\n if (!converted) {\n // Try ImageMagick (cross-platform)\n try {\n execSync(`magick \"${tempInput}\" \"${tempOutput}\" 2>/dev/null`, {\n stdio: \"pipe\",\n });\n converted = true;\n } catch {\n // magick not available\n }\n }\n\n if (!converted) {\n // Try older ImageMagick command\n try {\n execSync(`convert \"${tempInput}\" \"${tempOutput}\" 2>/dev/null`, {\n stdio: \"pipe\",\n });\n converted = true;\n } catch {\n // convert not available\n }\n }\n\n if (converted && existsSync(tempOutput)) {\n const pngData = readFileSync(tempOutput);\n // Cleanup temp files\n try { unlinkSync(tempInput); } catch {}\n try { unlinkSync(tempOutput); } catch {}\n return pngData;\n }\n\n // Cleanup on failure\n try { unlinkSync(tempInput); } catch {}\n return null;\n } catch {\n // Cleanup on error\n try { unlinkSync(tempInput); } catch {}\n try { unlinkSync(tempOutput); } catch {}\n return null;\n }\n}\n","/**\n * OS-level image preview utilities\n * \n * Supports:\n * - macOS: Quick Look (qlmanage)\n * - Linux: xdg-open\n * - Windows: start\n */\n\nimport { spawn, exec } from \"node:child_process\";\nimport { platform } from \"node:os\";\n\nexport type PreviewMethod = \"quicklook\" | \"open\" | \"none\";\n\n/**\n * Detect which preview method is available\n */\nexport function detectPreviewMethod(): PreviewMethod {\n const os = platform();\n\n if (os === \"darwin\") {\n return \"quicklook\";\n }\n\n if (os === \"linux\" || os === \"win32\") {\n return \"open\";\n }\n\n return \"none\";\n}\n\n/**\n * Open an image file with the OS preview\n * Returns a promise that resolves when the preview is closed (for Quick Look)\n * or when the preview command is launched (for xdg-open/start)\n */\nexport async function openImagePreview(localPath: string): Promise<void> {\n const method = detectPreviewMethod();\n\n switch (method) {\n case \"quicklook\":\n return openQuickLook(localPath);\n case \"open\":\n return openWithSystem(localPath);\n case \"none\":\n throw new Error(\"No preview method available on this platform\");\n }\n}\n\n/**\n * macOS Quick Look preview\n * Uses qlmanage which blocks until the preview is closed\n */\nfunction openQuickLook(path: string): Promise<void> {\n return new Promise((resolve, reject) => {\n // qlmanage -p shows Quick Look preview\n // -p = preview mode\n const proc = spawn(\"qlmanage\", [\"-p\", path], {\n detached: false,\n stdio: [\"ignore\", \"ignore\", \"ignore\"],\n });\n\n proc.on(\"error\", (err) => {\n reject(new Error(`Failed to open Quick Look: ${err.message}`));\n });\n\n // Bring Quick Look window to front after a short delay\n setTimeout(() => {\n bringQuickLookToFront();\n }, 50);\n\n proc.on(\"close\", (code) => {\n if (code === 0) {\n resolve();\n } else {\n // qlmanage can return non-zero even on success sometimes\n resolve();\n }\n });\n });\n}\n\n/**\n * Bring Quick Look window to front using AppleScript\n */\nfunction bringQuickLookToFront(): void {\n // qlmanage runs as a separate process, we need to activate it\n const script = `\n tell application \"System Events\"\n set frontmost of (first process whose name is \"qlmanage\") to true\n end tell\n `;\n \n // exec doesn't support stdio option, just ignore the callback\n exec(`osascript -e '${script}'`, () => {});\n}\n\n/**\n * Open with system default application\n * Works on Linux (xdg-open) and Windows (start)\n */\nfunction openWithSystem(path: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const os = platform();\n let command: string;\n let args: string[];\n\n if (os === \"linux\") {\n command = \"xdg-open\";\n args = [path];\n } else if (os === \"win32\") {\n command = \"cmd\";\n args = [\"/c\", \"start\", '\"\"', path];\n } else {\n // Fallback for macOS if Quick Look failed\n command = \"open\";\n args = [path];\n }\n\n const proc = spawn(command, args, {\n detached: true,\n stdio: [\"ignore\", \"ignore\", \"ignore\"],\n });\n\n proc.unref();\n\n proc.on(\"error\", (err) => {\n reject(new Error(`Failed to open preview: ${err.message}`));\n });\n\n // Don't wait for the process to close - just resolve after spawning\n // The preview app will stay open independently\n setTimeout(resolve, 100);\n });\n}\n\n/**\n * Check if Quick Look is available (macOS only)\n */\nexport function isQuickLookAvailable(): boolean {\n return platform() === \"darwin\";\n}\n","/**\n * Image component for terminal UIs\n * \n * Supports inline rendering via terminal protocols (Kitty, iTerm2)\n * and OS-level preview (Quick Look on macOS, xdg-open on Linux)\n */\n\nimport React, { useContext, useEffect, useRef, useState, useCallback, forwardRef, useImperativeHandle } from \"react\";\nimport type { Style, Key, ImageHandle } from \"../types/index.js\";\nimport type { GlyphNode } from \"../reconciler/nodes.js\";\nimport { FocusContext, InputContext, LayoutContext, ImageOverlayContext, ScrollViewContext } from \"../hooks/context.js\";\nimport type { LayoutRect } from \"../types/index.js\";\nimport { loadImage, getImageName, isRemoteUrl, detectImageFormat, convertToPng } from \"../runtime/imageLoader.js\";\nimport { getImageDimensions } from \"../runtime/imageProtocol.js\";\nimport { supportsInlineImages } from \"../runtime/terminalCapabilities.js\";\nimport { openImagePreview } from \"../runtime/osPreview.js\";\n\nexport type ImageState = \"placeholder\" | \"loading\" | \"loaded\" | \"error\" | \"preview\";\n\nexport interface ImageProps {\n /** Image source - local path or remote URL */\n src: string;\n /** Fixed width in cells (optional, uses flexbox if not set) */\n width?: number;\n /** Fixed height in cells (optional, uses flexbox if not set) */\n height?: number;\n /** Container style (flexbox) */\n style?: Style;\n /** Style when focused */\n focusedStyle?: Style;\n /** Style for the placeholder */\n placeholderStyle?: Style;\n /** Whether the component is focusable (default: true) */\n focusable?: boolean;\n /** Whether the component is disabled (skipped in tab order, no key handling) */\n disabled?: boolean;\n /** Allow inline rendering in terminal (default: true) */\n inline?: boolean;\n /** Custom placeholder text (default: image name) */\n placeholder?: string;\n /** Called when image state changes */\n onStateChange?: (state: ImageState) => void;\n /** Called on error */\n onError?: (error: Error) => void;\n /** Auto-load on mount (default: false - user presses space) */\n autoLoad?: boolean;\n /** \n * Auto-size the box to fit the image dimensions (default: false).\n * When true, the box resizes to match the image's aspect ratio.\n * Use maxWidth/maxHeight to constrain the size.\n */\n autoSize?: boolean;\n /** Maximum width in cells when autoSize is true */\n maxWidth?: number;\n /** Maximum height in cells when autoSize is true */\n maxHeight?: number;\n /**\n * Force unload trigger - increment this value to force the image to unload.\n * Useful when parent component handles Escape or other close actions.\n * Example: <Image unloadTrigger={unloadCount} ... />\n */\n unloadTrigger?: number;\n}\n\nexport const Image = forwardRef<ImageHandle, ImageProps>(\n function Image({\n src,\n width,\n height,\n unloadTrigger,\n style,\n focusedStyle,\n placeholderStyle,\n focusable = true,\n disabled = false,\n inline = true,\n placeholder,\n onStateChange,\n onError,\n autoLoad = false,\n autoSize = false,\n maxWidth,\n maxHeight,\n }, ref) {\n const focusCtx = useContext(FocusContext);\n const inputCtx = useContext(InputContext);\n const layoutCtx = useContext(LayoutContext);\n const imageOverlayCtx = useContext(ImageOverlayContext);\n const scrollViewCtx = useContext(ScrollViewContext);\n\n const nodeRef = useRef<GlyphNode | null>(null);\n const focusIdRef = useRef<string | null>(null);\n const imageIdRef = useRef<number>(Math.floor(Math.random() * 1000000));\n const lastScrollOffsetRef = useRef<number | null>(null); // null = not initialized yet\n\n // Component state\n const [nodeReady, setNodeReady] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [state, setState] = useState<ImageState>(\"placeholder\");\n const [errorMsg, setErrorMsg] = useState<string | null>(null);\n const [layout, setLayout] = useState<LayoutRect | null>(null);\n // Computed dimensions when autoSize is true\n const [computedDims, setComputedDims] = useState<{ width: number; height: number } | null>(null);\n\n // Loaded image data and computed dimensions\n const loadedImageRef = useRef<{ data: Buffer; localPath: string; cellWidth: number; cellHeight: number } | null>(null);\n\n // Expose imperative handle\n useImperativeHandle(ref, () => ({\n focus() {\n if (focusCtx && focusIdRef.current) {\n focusCtx.requestFocus(focusIdRef.current);\n }\n },\n blur() {\n if (focusCtx) {\n focusCtx.blur();\n }\n },\n get isFocused() {\n return isFocused;\n },\n }), [focusCtx, isFocused]);\n\n const imageName = placeholder || getImageName(src);\n const isRemote = isRemoteUrl(src);\n\n // Handle unloadTrigger - unload when trigger changes (and image is loaded)\n const lastUnloadTriggerRef = useRef(unloadTrigger);\n useEffect(() => {\n if (unloadTrigger !== undefined && \n unloadTrigger !== lastUnloadTriggerRef.current && \n state === \"loaded\") {\n loadedImageRef.current = null;\n setComputedDims(null);\n setState(\"placeholder\");\n }\n lastUnloadTriggerRef.current = unloadTrigger;\n }, [unloadTrigger, state]);\n\n // Update state and notify\n const updateState = useCallback((newState: ImageState) => {\n setState(newState);\n onStateChange?.(newState);\n }, [onStateChange]);\n\n // Register with focus system (autoFocus: false - images shouldn't steal focus on mount)\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current || !nodeRef.current || !focusable) return;\n return focusCtx.register(focusIdRef.current, nodeRef.current, false);\n }, [focusCtx, focusable, nodeReady]);\n\n // Handle disabled state (skip in tab order + release focus if held)\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n focusCtx.setSkippable(focusIdRef.current, !!disabled);\n if (disabled && focusCtx.focusedId === focusIdRef.current) {\n focusCtx.blur();\n }\n }, [focusCtx, disabled]);\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 // Subscribe to layout changes\n useEffect(() => {\n if (!layoutCtx || !nodeRef.current) return;\n setLayout(layoutCtx.getLayout(nodeRef.current));\n return layoutCtx.subscribe(nodeRef.current, setLayout);\n }, [layoutCtx, nodeReady]);\n\n // Track scroll position and hide image when user scrolls\n // Only hide when state is \"loaded\" - don't hide during loading or before first load\n const currentScrollOffset = scrollViewCtx?.getBounds().scrollOffset ?? 0;\n \n useEffect(() => {\n if (!scrollViewCtx) return;\n \n // Initialize on first mount\n if (lastScrollOffsetRef.current === null) {\n lastScrollOffsetRef.current = currentScrollOffset;\n return;\n }\n \n // Only hide if image is loaded - don't interfere with loading process\n if (state !== \"loaded\") {\n // Update ref but don't hide\n lastScrollOffsetRef.current = currentScrollOffset;\n return;\n }\n \n // If scroll offset actually changed, unload the image (same as Escape)\n if (currentScrollOffset !== lastScrollOffsetRef.current) {\n lastScrollOffsetRef.current = currentScrollOffset;\n loadedImageRef.current = null;\n setComputedDims(null);\n setState(\"placeholder\");\n }\n }, [scrollViewCtx, currentScrollOffset, state]);\n\n // Register/update image with overlay system when loaded and layout changes\n // Note: We schedule registration on next tick to ensure layout has settled\n useEffect(() => {\n if (!imageOverlayCtx || state !== \"loaded\" || !loadedImageRef.current || !layout) {\n return;\n }\n\n const { data, cellWidth, cellHeight } = loadedImageRef.current;\n const imageId = imageIdRef.current;\n\n // Schedule on next tick to ensure all state has settled\n const timeoutId = setTimeout(() => {\n imageOverlayCtx.registerImage({\n id: imageId,\n data,\n x: layout.innerX,\n y: layout.innerY,\n width: cellWidth,\n height: cellHeight,\n });\n }, 0);\n\n return () => {\n clearTimeout(timeoutId);\n imageOverlayCtx.unregisterImage(imageId);\n };\n }, [imageOverlayCtx, state, layout, scrollViewCtx]);\n\n // Load and display image\n const loadAndDisplay = useCallback(async () => {\n if (state === \"loading\") return;\n\n updateState(\"loading\");\n setErrorMsg(null);\n\n try {\n const image = await loadImage(src);\n \n // Decide how to display the image\n const canInline = inline && supportsInlineImages();\n\n if (canInline && layout) {\n // Check image format - Kitty protocol requires PNG\n const format = detectImageFormat(image.data);\n \n let imageData = image.data;\n if (format !== \"png\") {\n const pngData = convertToPng(image.data);\n if (!pngData) {\n // Fall back to OS preview if conversion fails\n updateState(\"preview\");\n await openImagePreview(image.localPath);\n updateState(\"placeholder\");\n return;\n }\n imageData = pngData;\n }\n \n // Get image pixel dimensions for autoSize calculation\n const imageDims = getImageDimensions(imageData);\n \n let targetWidth: number;\n let targetHeight: number;\n \n if (autoSize && imageDims) {\n // Calculate cell dimensions that fit the image while preserving aspect ratio\n // Terminal cells are roughly 2x taller than wide\n const cellAspectRatio = 2.0;\n \n // Convert image pixels to approximate cell dimensions\n // Assume ~8 pixels per cell width, ~16 pixels per cell height (common terminal sizes)\n const pixelsPerCellWidth = 8;\n const pixelsPerCellHeight = 16;\n \n let cellWidth = Math.ceil(imageDims.width / pixelsPerCellWidth);\n let cellHeight = Math.ceil(imageDims.height / pixelsPerCellHeight);\n \n // Apply max constraints if specified\n const effectiveMaxWidth = maxWidth ?? 80;\n const effectiveMaxHeight = maxHeight ?? 24;\n \n if (cellWidth > effectiveMaxWidth || cellHeight > effectiveMaxHeight) {\n // Scale down to fit within constraints\n const scaleX = effectiveMaxWidth / cellWidth;\n const scaleY = effectiveMaxHeight / cellHeight;\n const scale = Math.min(scaleX, scaleY);\n cellWidth = Math.max(1, Math.round(cellWidth * scale));\n cellHeight = Math.max(1, Math.round(cellHeight * scale));\n }\n \n targetWidth = cellWidth;\n targetHeight = cellHeight;\n \n // Update computed dimensions for the box\n setComputedDims({ width: cellWidth, height: cellHeight });\n } else {\n // Use fixed dimensions or layout dimensions\n targetWidth = width ?? layout.innerWidth;\n targetHeight = height ?? layout.innerHeight;\n }\n\n if (targetWidth <= 0 || targetHeight <= 0) {\n throw new Error(\"Image area too small\");\n }\n\n // Apply hard limit: images should not exceed 30x6 cells\n const MAX_IMAGE_WIDTH = 30;\n const MAX_IMAGE_HEIGHT = 6;\n if (targetWidth > MAX_IMAGE_WIDTH || targetHeight > MAX_IMAGE_HEIGHT) {\n const scaleX = MAX_IMAGE_WIDTH / targetWidth;\n const scaleY = MAX_IMAGE_HEIGHT / targetHeight;\n const scale = Math.min(scaleX, scaleY);\n targetWidth = Math.max(1, Math.round(targetWidth * scale));\n targetHeight = Math.max(1, Math.round(targetHeight * scale));\n }\n\n // Store loaded image with target box dimensions\n // Kitty protocol preserves aspect ratio when given source dims (s,v) and target cells (c,r)\n loadedImageRef.current = {\n data: imageData,\n localPath: image.localPath,\n cellWidth: targetWidth,\n cellHeight: targetHeight,\n };\n\n updateState(\"loaded\");\n } else {\n // Use OS preview\n updateState(\"preview\");\n await openImagePreview(image.localPath);\n updateState(\"placeholder\"); // Return to placeholder after preview closes\n }\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n setErrorMsg(error.message);\n updateState(\"error\");\n onError?.(error);\n }\n }, [src, state, inline, layout, width, height, autoSize, maxWidth, maxHeight, updateState, onError]);\n\n // Handle key press (space to load/preview)\n useEffect(() => {\n if (!inputCtx || !focusIdRef.current || !focusable || disabled) return;\n const fid = focusIdRef.current;\n\n const handler = (key: Key): boolean => {\n if (focusCtx?.focusedId !== fid) return false;\n\n // Space or Enter to load/preview\n if (key.name === \"space\" || key.name === \"return\") {\n loadAndDisplay();\n return true;\n }\n\n // 'r' to reload\n if (key.name === \"r\" && loadedImageRef.current) {\n loadAndDisplay();\n return true;\n }\n\n // Escape to clear inline image and return to placeholder\n if (key.name === \"escape\" && state === \"loaded\") {\n loadedImageRef.current = null;\n setComputedDims(null); // Reset box size\n updateState(\"placeholder\");\n return true;\n }\n\n // Second Escape on placeholder releases focus\n if (key.name === \"escape\" && state === \"placeholder\") {\n focusCtx?.blur();\n return true;\n }\n\n return false;\n };\n\n return inputCtx.registerInputHandler(fid, handler);\n }, [inputCtx, focusCtx, focusable, disabled, nodeReady, loadAndDisplay, state, updateState]);\n\n // Auto-load on mount\n useEffect(() => {\n if (autoLoad && state === \"placeholder\" && layout && layout.innerWidth > 0) {\n loadAndDisplay();\n }\n }, [autoLoad, state, layout, loadAndDisplay]);\n\n // Cleanup on unmount\n useEffect(() => {\n const imageId = imageIdRef.current;\n return () => {\n imageOverlayCtx?.unregisterImage(imageId);\n };\n }, [imageOverlayCtx]);\n\n // Build display content\n let displayContent: React.ReactNode;\n let statusIcon: string;\n\n switch (state) {\n case \"placeholder\":\n statusIcon = isRemote ? \"🌐\" : \"🖼️\";\n displayContent = `${statusIcon} ${imageName}`;\n break;\n case \"loading\":\n statusIcon = \"⏳\";\n displayContent = `${statusIcon} Loading...`;\n break;\n case \"loaded\":\n // When loaded inline, show empty space (image is rendered via overlay)\n displayContent = null;\n break;\n case \"preview\":\n statusIcon = \"👁️\";\n displayContent = `${statusIcon} Previewing...`;\n break;\n case \"error\":\n statusIcon = \"❌\";\n displayContent = `${statusIcon} ${errorMsg || \"Error\"}`;\n break;\n }\n\n // Merge styles\n // When autoSize is true and we have computed dimensions, use those\n const effectiveWidth = autoSize && computedDims ? computedDims.width : width;\n const effectiveHeight = autoSize && computedDims ? computedDims.height : height;\n \n const baseStyle: Style = {\n border: \"round\" as const,\n borderColor: \"blackBright\" as const,\n justifyContent: \"center\" as const,\n alignItems: \"center\" as const,\n ...style,\n ...(effectiveWidth !== undefined ? { width: effectiveWidth } : {}),\n ...(effectiveHeight !== undefined ? { height: effectiveHeight } : {}),\n };\n\n const mergedStyle: Style = {\n ...baseStyle,\n // Default focus style: highlight border\n ...(isFocused ? { borderColor: \"cyan\" as const } : {}),\n // User's focusedStyle overrides defaults\n ...(isFocused && focusedStyle ? focusedStyle : {}),\n };\n\n const placeholderMergedStyle: Style = {\n color: \"blackBright\" as const,\n ...placeholderStyle,\n ...(isFocused ? { color: \"cyan\" as const } : {}),\n };\n\n return React.createElement(\n \"box\" as any,\n {\n style: mergedStyle,\n 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 displayContent !== null\n ? React.createElement(\n \"text\" as any,\n { style: placeholderMergedStyle },\n displayContent\n )\n : null\n );\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 /** Programmatically blur (unfocus) this element */\n blur: () => 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 + release focus if held)\n useEffect(() => {\n if (!focusCtx || !focusIdRef.current) return;\n focusCtx.setSkippable(focusIdRef.current, !!disabled);\n if (disabled && focusCtx.focusedId === focusIdRef.current) {\n focusCtx.blur();\n }\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 // Blur function\n const blur = useCallback(() => {\n if (focusCtx) {\n focusCtx.blur();\n }\n }, [focusCtx]);\n \n return {\n ref,\n isFocused,\n focus,\n blur,\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 \"@semos-labs/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"]}
|