import { useState, useEffect, useMemo } from "react"; import { Box, Text, Newline as InkNewline, Spacer as InkSpacer, useInput, } from "ink"; import { marked, type Token, type Tokens } from "marked"; import type { ComponentRenderProps, ComponentRegistry } from "../renderer"; import { useBoundProp } from "../hooks"; import { useFocus } from "../contexts/focus"; // ============================================================================= // Layout Components (Ink Primitives) // ============================================================================= // Props that must never be forwarded from AI-generated specs to React/Ink elements. const BLOCKED_PROPS = new Set([ "key", "ref", "children", "dangerouslySetInnerHTML", "style", "className", "id", ]); // Colors that are invisible on typical dark terminal backgrounds. const INVISIBLE_COLORS = new Set(["black", "#000", "#000000"]); /** Return undefined for colors that would be invisible on dark terminals. */ function safeColor(color: string | undefined): string | undefined { if (color && INVISIBLE_COLORS.has(color)) return undefined; return color; } // Strip null values so Ink's default layout applies (Ink has no concept of null props) // and block dangerous or web-only props from AI-generated specs. function safeBoxProps(obj: Record): Record { const result: Record = {}; for (const [k, v] of Object.entries(obj)) { if (v !== undefined && v !== null && !BLOCKED_PROPS.has(k)) { // Drop foreground colors that would be invisible on dark backgrounds if (k === "color" && typeof v === "string" && INVISIBLE_COLORS.has(v)) { continue; } result[k] = v; } } return result; } function BoxComponent({ element, children }: ComponentRenderProps) { const p = element.props as Record; return {children}; } function TextComponent({ element }: ComponentRenderProps) { const { text, ...style } = element.props as Record; return {(text as string) ?? ""}; } function NewlineComponent({ element }: ComponentRenderProps) { const p = element.props as { count?: number }; return ; } function SpacerComponent() { return ; } // ============================================================================= // Content Components (Higher-Level) // ============================================================================= function HeadingComponent({ element }: ComponentRenderProps) { const p = element.props as { text?: string; level?: "h1" | "h2" | "h3" | "h4"; color?: string; }; const level = p.level ?? "h2"; switch (level) { case "h1": return ( {p.text ?? ""} ); case "h2": return ( {p.text ?? ""} ); case "h3": return ( {p.text ?? ""} ); case "h4": default: return ( {p.text ?? ""} ); } } function DividerComponent({ element }: ComponentRenderProps) { const p = element.props as { character?: string; color?: string; dimColor?: boolean; title?: string; width?: number; }; const char = Array.from(p.character ?? "─")[0] || "─"; const totalWidth = p.width ?? 40; if (p.title) { const titleStr = ` ${p.title} `; const available = Math.max(0, totalWidth - titleStr.length); const leftLen = Math.floor(available / 2); const rightLen = available - leftLen; return ( {char.repeat(leftLen)} {titleStr} {char.repeat(rightLen)} ); } return ( {char.repeat(totalWidth)} ); } const BADGE_COLORS: Record = { default: "white", info: "blue", success: "green", warning: "yellow", error: "red", }; function BadgeComponent({ element }: ComponentRenderProps) { const p = element.props as { label?: string; variant?: "default" | "info" | "success" | "warning" | "error"; }; const color = BADGE_COLORS[p.variant ?? "default"] ?? "white"; return ( {` ${p.label ?? ""} `} ); } const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; function SpinnerComponent({ element }: ComponentRenderProps) { const p = element.props as { label?: string; color?: string; }; const [frame, setFrame] = useState(0); useEffect(() => { const timer = setInterval(() => { setFrame((prev) => (prev + 1) % SPINNER_FRAMES.length); }, 80); return () => clearInterval(timer); }, []); return ( {SPINNER_FRAMES[frame]} {p.label ? {p.label} : null} ); } function ProgressBarComponent({ element }: ComponentRenderProps) { const p = element.props as { progress?: number; width?: number; color?: string; label?: string; }; const progress = Math.min(1, Math.max(0, p.progress ?? 0)); const barWidth = p.width ?? 30; const filled = Math.round(progress * barWidth); const empty = barWidth - filled; const percentage = Math.round(progress * 100); return ( {p.label ? {p.label} : null} {"█".repeat(filled)} {"░".repeat(empty)} {percentage}% ); } const SPARK_BLOCKS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"]; function SparklineComponent({ element }: ComponentRenderProps) { const p = element.props as { data?: number[]; width?: number; color?: string; label?: string; min?: number; max?: number; }; const data = p.data ?? []; if (data.length === 0) { return p.label ? {p.label}: (no data) : null; } const minVal = p.min ?? Math.min(...data); const maxVal = p.max ?? Math.max(...data); const range = maxVal - minVal || 1; // If width is set and smaller than data length, sample down const maxWidth = p.width ?? data.length; let sampled = data; if (maxWidth < data.length) { sampled = []; for (let i = 0; i < maxWidth; i++) { const idx = maxWidth === 1 ? 0 : Math.round((i / (maxWidth - 1)) * (data.length - 1)); sampled.push(data[idx]!); } } const blocks = sampled .map((v) => { const normalized = (v - minVal) / range; const idx = Math.min( SPARK_BLOCKS.length - 1, Math.round(normalized * (SPARK_BLOCKS.length - 1)), ); return SPARK_BLOCKS[idx]; }) .join(""); return ( {p.label ? {p.label} : null} {blocks} ); } function BarChartComponent({ element }: ComponentRenderProps) { const p = element.props as { data?: Array<{ label: string; value: number; color?: string }>; width?: number; showValues?: boolean; showPercentage?: boolean; }; const data = p.data ?? []; if (data.length === 0) return null; const maxValue = Math.max(...data.map((d) => d.value), 1); const total = data.reduce((sum, d) => sum + d.value, 0); const maxLabelLen = Math.max(...data.map((d) => d.label.length)); const barWidth = p.width ?? 30; return ( {data.map((item) => { const filled = Math.round((item.value / maxValue) * barWidth); const padded = item.label.padEnd(maxLabelLen); const suffix: string[] = []; if (p.showValues) suffix.push(String(item.value)); if (p.showPercentage && total > 0) suffix.push(`${Math.round((item.value / total) * 100)}%`); return ( {padded} {"█".repeat(filled)} {suffix.length > 0 ? ( {suffix.join(" ")} ) : null} ); })} ); } function TableComponent({ element }: ComponentRenderProps) { const p = element.props as { columns?: Array<{ header: string; key: string; width?: number; align?: "left" | "center" | "right"; }>; rows?: Array>; borderStyle?: string; backgroundColor?: string; headerColor?: string; }; const columns = p.columns ?? []; const rows = p.rows ?? []; // Calculate column widths const colWidths = columns.map((col) => { if (col.width) return col.width; let max = col.header.length; for (const row of rows) { const val = row[col.key] ?? ""; if (val.length > max) max = val.length; } return max + 2; }); const padCell = (text: string, width: number, align?: string): string => { const truncated = text.length > width ? text.slice(0, width - 1) + "…" : text; const pad = width - truncated.length; if (align === "right") return " ".repeat(pad) + truncated; if (align === "center") { const left = Math.floor(pad / 2); return " ".repeat(left) + truncated + " ".repeat(pad - left); } return truncated + " ".repeat(pad); }; const borderStyleProp = p.borderStyle as | "single" | "double" | "round" | "bold" | "classic" | undefined; return ( {/* Header */} {columns.map((col, i) => ( {padCell(col.header, colWidths[i]!, col.align)} ))} {/* Separator */} {colWidths.map((w) => "─".repeat(w)).join("─")} {/* Rows */} {rows.map((row, rowIdx) => { const rowKey = columns.map((c) => row[c.key] ?? "").join("\0") || String(rowIdx); return ( {columns.map((col, i) => ( {padCell(row[col.key] || "—", colWidths[i]!, col.align)} ))} ); })} ); } function ListComponent({ element }: ComponentRenderProps) { const p = element.props as { items?: string[]; ordered?: boolean; bulletChar?: string; spacing?: number; }; const items = p.items ?? []; const bullet = p.bulletChar ?? "•"; return ( {items.map((item, i) => ( {p.ordered ? `${i + 1}.` : bullet} {item} ))} ); } function ListItemComponent({ element }: ComponentRenderProps) { const p = element.props as { title?: string; subtitle?: string; leading?: string; trailing?: string; }; return ( {p.leading ? {p.leading} : null} {p.title ?? ""} {p.subtitle ? {p.subtitle} : null} {p.trailing ? {String(p.trailing)} : null} ); } function CardComponent({ element, children }: ComponentRenderProps) { const p = element.props as { title?: string; backgroundColor?: string; padding?: number; }; return ( {p.title ? ( {p.title} ) : null} {children} ); } /** Coerce any value into a display string. Handles arrays, numbers, objects. */ function coerceToString(val: unknown): string { if (val == null) return ""; if (typeof val === "string") return val; if (typeof val === "number") return val.toLocaleString(); if (typeof val === "boolean") return val ? "true" : "false"; if (Array.isArray(val)) return val.map(coerceToString).join(", "); if (typeof val === "object") { // Handle {language: "TypeScript", percentage: 65} style objects const values = Object.values(val as Record); return values.map(coerceToString).join(" "); } return String(val); } function KeyValueComponent({ element }: ComponentRenderProps) { const p = element.props as { label?: string; value?: unknown; labelColor?: string; separator?: string; }; const sep = p.separator ?? ":"; return ( {p.label ?? ""} {sep} {coerceToString(p.value) || "—"} ); } function LinkComponent({ element }: ComponentRenderProps) { const p = element.props as { url?: string; label?: string; color?: string; }; const url = p.url ?? ""; const label = p.label ?? url; return ( {label} {label !== url ? ` (${url})` : ""} ); } const STATUS_CONFIG: Record = { info: { icon: "ℹ", color: "blue" }, success: { icon: "✔", color: "green" }, warning: { icon: "⚠", color: "yellow" }, error: { icon: "✖", color: "red" }, }; function StatusLineComponent({ element }: ComponentRenderProps) { const p = element.props as { text?: string; status?: "info" | "success" | "warning" | "error"; icon?: string; }; const status = p.status ?? "info"; const config = STATUS_CONFIG[status]; const icon = p.icon ?? config?.icon ?? "•"; const color = config?.color ?? "white"; return ( {icon} {p.text ?? ""} ); } // ============================================================================= // Metric, Callout, Timeline // ============================================================================= const TREND_CONFIG: Record = { up: { prefix: "+", color: "green" }, down: { prefix: "", color: "red" }, neutral: { prefix: "~", color: "gray" }, }; function MetricComponent({ element }: ComponentRenderProps) { const p = element.props as { label?: string; value?: string; detail?: string; trend?: "up" | "down" | "neutral"; }; const trend = p.trend ? TREND_CONFIG[p.trend] : null; return ( {p.label ?? ""} {p.value ?? ""} {trend && p.detail ? ( {trend.prefix} {p.detail} ) : null} {!trend && p.detail ? {p.detail} : null} ); } const CALLOUT_CONFIG: Record = { info: { label: "INFO", color: "blue" }, tip: { label: "TIP", color: "green" }, warning: { label: "WARNING", color: "yellow" }, important: { label: "IMPORTANT", color: "magenta" }, }; function CalloutComponent({ element }: ComponentRenderProps) { const p = element.props as { type?: "info" | "tip" | "warning" | "important"; title?: string; content?: string; }; const config = CALLOUT_CONFIG[p.type ?? "info"] ?? CALLOUT_CONFIG.info!; return ( {p.title ? ( {p.title} ) : null} {p.content ?? ""} ); } const TIMELINE_DOT: Record = { completed: { dot: "●", color: "green" }, current: { dot: "◆", color: "cyan" }, upcoming: { dot: "○", color: "gray" }, }; function TimelineComponent({ element }: ComponentRenderProps) { const p = element.props as { items?: Array<{ title?: string; description?: string; date?: string; status?: "completed" | "current" | "upcoming"; }>; }; const items = p.items ?? []; return ( {items.map((item, i) => { const cfg = TIMELINE_DOT[item.status ?? "upcoming"] ?? TIMELINE_DOT.upcoming!; return ( {cfg.dot} {item.title ?? ""} {item.date ? {item.date} : null} {item.description ? ( {item.description} ) : null} ); })} ); } // ============================================================================= // Interactive Components // ============================================================================= /** Count code points instead of UTF-16 code units (handles emoji/surrogate pairs). */ function codePointLength(s: string): number { return Array.from(s).length; } /** Slice by code point index instead of UTF-16 offset. */ function codePointSlice(s: string, start: number, end?: number): string { return Array.from(s).slice(start, end).join(""); } function TextInputComponent({ element, emit, bindings }: ComponentRenderProps) { const p = element.props as { placeholder?: string; value?: string; label?: string; mask?: string; }; const { isActive } = useFocus(); const [value, setValue] = useBoundProp( (p.value as string) ?? "", bindings?.value, ); const currentValue = value ?? ""; const [cursorPos, setCursorPos] = useState(codePointLength(currentValue)); // Keep cursor in bounds when value changes externally useEffect(() => { setCursorPos((prev) => Math.min(prev, codePointLength(currentValue))); }, [currentValue]); useInput( (input, key) => { if (key.return) { emit("submit"); return; } if (key.backspace || key.delete) { if (cursorPos > 0) { const newVal = codePointSlice(currentValue, 0, cursorPos - 1) + codePointSlice(currentValue, cursorPos); setValue(newVal); setCursorPos((prev) => prev - 1); emit("change"); } return; } // Cursor movement if (key.leftArrow) { setCursorPos((prev) => Math.max(0, prev - 1)); return; } if (key.rightArrow) { setCursorPos((prev) => Math.min(codePointLength(currentValue), prev + 1), ); return; } // Ignore control keys if (key.ctrl || key.meta || key.escape || key.tab) return; if (key.upArrow || key.downArrow) return; if (input) { const newVal = codePointSlice(currentValue, 0, cursorPos) + input + codePointSlice(currentValue, cursorPos); setValue(newVal); setCursorPos((prev) => prev + codePointLength(input)); emit("change"); } }, { isActive }, ); const displayValue = currentValue ? p.mask ? p.mask.repeat(codePointLength(currentValue)) : currentValue : ""; const before = codePointSlice(displayValue, 0, cursorPos); const after = codePointSlice(displayValue, cursorPos); return ( {p.label ? {p.label}: : null} {currentValue ? ( <> {before} {isActive ? ▎ : null} {after} ) : ( <> {isActive ? ▎ : null} {p.placeholder ?? ""} )} ); } function SelectComponent({ element, emit, bindings }: ComponentRenderProps) { const p = element.props as { options?: Array<{ label: string; value: string }>; value?: string; label?: string; }; const { isActive } = useFocus(); const options = p.options ?? []; const [selectedValue, setSelectedValue] = useBoundProp( (p.value as string) ?? "", bindings?.value, ); const currentIndex = options.findIndex((o) => o.value === selectedValue); const [highlightIndex, setHighlightIndex] = useState( currentIndex >= 0 ? currentIndex : 0, ); // Stable key derived from option values — prevents the effect from firing // on every render due to resolved props creating new array references. const optionsKey = options.map((o) => o.value).join("\0"); // Sync highlight when selectedValue changes externally (e.g. via another action) // Also clamp when options shrink to prevent out-of-bounds highlight useEffect(() => { const idx = options.findIndex((o) => o.value === selectedValue); if (idx >= 0) { setHighlightIndex(idx); } else if (options.length > 0) { setHighlightIndex((prev) => Math.min(prev, options.length - 1)); } else { setHighlightIndex(0); } // eslint-disable-next-line react-hooks/exhaustive-deps -- optionsKey is a stable proxy for options identity }, [selectedValue, optionsKey]); useInput( (_input, key) => { if (options.length === 0) return; if (key.upArrow) { setHighlightIndex((prev) => (prev > 0 ? prev - 1 : options.length - 1)); } else if (key.downArrow) { setHighlightIndex((prev) => (prev < options.length - 1 ? prev + 1 : 0)); } else if (key.return) { const option = options[highlightIndex]; if (option) { setSelectedValue(option.value); emit("change"); } } }, { isActive }, ); return ( {p.label ? ( {p.label}: ) : null} {options.map((option, i) => { const isHighlighted = i === highlightIndex; const isSelected = option.value === selectedValue; return ( {isHighlighted ? "❯" : " "} {option.label} ); })} ); } function MultiSelectComponent({ element, emit, bindings, }: ComponentRenderProps) { const p = element.props as { options?: Array<{ label: string; value: string }>; value?: string[]; label?: string; min?: number; max?: number; }; const { isActive } = useFocus(); const options = p.options ?? []; const [selectedValues, setSelectedValues] = useBoundProp( (p.value as string[]) ?? [], bindings?.value, ); const selected = selectedValues ?? []; const [highlightIndex, setHighlightIndex] = useState(0); const optionsKey = options.map((o) => o.value).join("\0"); useEffect(() => { if (options.length > 0) { setHighlightIndex((prev) => Math.min(prev, options.length - 1)); } else { setHighlightIndex(0); } // eslint-disable-next-line react-hooks/exhaustive-deps -- optionsKey is a stable proxy for options identity }, [optionsKey]); useInput( (_input, key) => { if (options.length === 0) return; if (key.upArrow) { setHighlightIndex((prev) => (prev > 0 ? prev - 1 : options.length - 1)); } else if (key.downArrow) { setHighlightIndex((prev) => (prev < options.length - 1 ? prev + 1 : 0)); } else if (_input === " ") { const option = options[highlightIndex]; if (!option) return; const isSelected = selected.includes(option.value); let next: string[]; if (isSelected) { if (p.min != null && selected.length <= p.min) return; next = selected.filter((v) => v !== option.value); } else { if (p.max != null && selected.length >= p.max) return; next = [...selected, option.value]; } setSelectedValues(next); emit("change"); } else if (key.return) { emit("submit"); } }, { isActive }, ); return ( {p.label ? ( {p.label}: (space to toggle, enter to confirm) ) : null} {options.map((option, i) => { const isHighlighted = i === highlightIndex; const isChecked = selected.includes(option.value); return ( {isHighlighted ? "❯" : " "} {isChecked ? "◉" : "◯"} {option.label} ); })} {selected.length > 0 ? ( Selected: {selected.length} ) : null} ); } function ConfirmInputComponent({ element, emit }: ComponentRenderProps) { const p = element.props as { message?: string; defaultValue?: boolean; yesLabel?: string; noLabel?: string; }; const { isActive } = useFocus(); const [value, setValue] = useState(p.defaultValue ?? null); useInput( (input, key) => { const lower = input.toLowerCase(); if (lower === "y") { setValue(true); emit("confirm"); } else if (lower === "n") { setValue(false); emit("deny"); } else if (key.return && value !== null) { emit(value ? "confirm" : "deny"); } }, { isActive }, ); const yesLabel = p.yesLabel ?? "Yes"; const noLabel = p.noLabel ?? "No"; return ( {p.message ?? "Are you sure?"} {yesLabel} / {noLabel} (y/n) ); } function TabsComponent({ element, emit, bindings, children, }: ComponentRenderProps) { const p = element.props as { tabs?: Array<{ label: string; value: string; icon?: string }>; value?: string; color?: string; }; const { isActive } = useFocus(); const tabs = p.tabs ?? []; const [activeTab, setActiveTab] = useBoundProp( (p.value as string) ?? tabs[0]?.value ?? "", bindings?.value, ); const activeIndex = tabs.findIndex((t) => t.value === activeTab); useInput( (_input, key) => { if (tabs.length === 0) return; const currentIdx = activeIndex >= 0 ? activeIndex : 0; if (key.leftArrow) { const next = currentIdx > 0 ? currentIdx - 1 : tabs.length - 1; const tab = tabs[next]; if (tab) { setActiveTab(tab.value); emit("change"); } } else if (key.rightArrow) { const next = currentIdx < tabs.length - 1 ? currentIdx + 1 : 0; const tab = tabs[next]; if (tab) { setActiveTab(tab.value); emit("change"); } } }, { isActive }, ); const accentColor = p.color ?? "cyan"; return ( {tabs.map((tab) => { const isActive = tab.value === activeTab; return ( {tab.icon ? `${tab.icon} ` : ""} {tab.label} ); })} {tabs .map((tab) => { const isActive = tab.value === activeTab; const labelWidth = (tab.icon ? tab.icon.length + 1 : 0) + tab.label.length; return isActive ? "━".repeat(labelWidth) + " " : " ".repeat(labelWidth) + " "; }) .join("")} {children} ); } // ============================================================================= // Markdown Component // ============================================================================= /** Render an array of inline tokens into Ink Text elements. */ function renderInline(tokens: Token[]): React.ReactNode[] { const nodes: React.ReactNode[] = []; for (let i = 0; i < tokens.length; i++) { const t = tokens[i]!; switch (t.type) { case "strong": nodes.push( {renderInline((t as Tokens.Strong).tokens)} , ); break; case "em": nodes.push( {renderInline((t as Tokens.Em).tokens)} , ); break; case "codespan": nodes.push( {`\`${(t as Tokens.Codespan).text}\``}, ); break; case "del": nodes.push( {renderInline((t as Tokens.Del).tokens)} , ); break; case "link": nodes.push( {renderInline((t as Tokens.Link).tokens)} , ); break; case "text": { const tt = t as Tokens.Text; // Paragraph-level text tokens can have nested inline tokens if (tt.tokens) { nodes.push(...renderInline(tt.tokens)); } else { nodes.push(tt.text); } break; } case "br": nodes.push("\n"); break; case "escape": nodes.push((t as Tokens.Escape).text); break; default: if ("text" in t) nodes.push((t as { text: string }).text); break; } } return nodes; } /** Render a single block-level token into Ink components. */ function renderBlock(token: Token, key: number): React.ReactNode { switch (token.type) { case "heading": { const h = token as Tokens.Heading; const content = renderInline(h.tokens); if (h.depth === 1) return ( {content} ); if (h.depth === 2) return ( {content} ); if (h.depth === 3) return ( {content} ); return ( {content} ); } case "paragraph": { const p = token as Tokens.Paragraph; return {renderInline(p.tokens)}; } case "code": { const c = token as Tokens.Code; return ( {c.text} ); } case "blockquote": { const bq = token as Tokens.Blockquote; return ( {bq.tokens.map((child, i) => renderBlock(child, i))} ); } case "list": { const l = token as Tokens.List; return ( {l.items.map((item, idx) => ( {l.ordered ? `${Number(l.start ?? 1) + idx}.` : "•"} {item.tokens.flatMap((child) => { if (child.type === "text") { const tt = child as Tokens.Text; return tt.tokens ? renderInline(tt.tokens) : [tt.text]; } if (child.type === "list") return [renderBlock(child, idx)]; return "tokens" in child ? renderInline((child as { tokens: Token[] }).tokens) : []; })} ))} ); } case "hr": return ( {"─".repeat(40)} ); case "space": return null; default: // Fallback: render raw text if present if ("text" in token) return {(token as { text: string }).text}; return null; } } /** * MarkdownText — renders markdown-formatted text with proper terminal styling. * * Uses `marked` lexer to parse markdown into an AST, then maps tokens to * Ink components. Supports headings, bold, italic, code (inline + blocks), * lists, blockquotes, horizontal rules, strikethrough, and links. * */ function MarkdownText({ text }: { text: string }) { const tokens = useMemo( () => marked.lexer(text, { gfm: true, breaks: true }), [text], ); const blocks = tokens .map((t, i) => renderBlock(t, i)) .filter((n) => n != null); return ( {blocks} ); } function MarkdownComponent({ element }: ComponentRenderProps) { const p = element.props as { text?: string }; return ; } // ============================================================================= // Standard Components Registry // ============================================================================= export const standardComponents: ComponentRegistry = { Box: BoxComponent, Text: TextComponent, Newline: NewlineComponent, Spacer: SpacerComponent, Heading: HeadingComponent, Divider: DividerComponent, Badge: BadgeComponent, Spinner: SpinnerComponent, ProgressBar: ProgressBarComponent, Sparkline: SparklineComponent, BarChart: BarChartComponent, Table: TableComponent, List: ListComponent, ListItem: ListItemComponent, Card: CardComponent, KeyValue: KeyValueComponent, Link: LinkComponent, StatusLine: StatusLineComponent, Metric: MetricComponent, Callout: CalloutComponent, Timeline: TimelineComponent, TextInput: TextInputComponent, Select: SelectComponent, MultiSelect: MultiSelectComponent, ConfirmInput: ConfirmInputComponent, Tabs: TabsComponent, Markdown: MarkdownComponent, };