70160
Ce
cel-tui / files
cel-tui / packages / types / src / index.ts
20.3 KB
1/** 2 * A numbered color slot in the 16-color palette. 3 * 4 * Colors are abstract palette references — `"color00"` through `"color15"`. 5 * The active {@link Theme} determines what each slot actually looks like. 6 * With the default ANSI 16 theme, they map to the terminal's configured 7 * color palette (matching standard ANSI indices 0–15). 8 * 9 * Omitting a color prop (`undefined`) means "use the terminal default", 10 * which is separate from any palette slot. 11 */ 12export type Color = 13 | "color00" 14 | "color01" 15 | "color02" 16 | "color03" 17 | "color04" 18 | "color05" 19 | "color06" 20 | "color07" 21 | "color08" 22 | "color09" 23 | "color10" 24 | "color11" 25 | "color12" 26 | "color13" 27 | "color14" 28 | "color15"; 29 30/** 31 * A theme value for a single color slot. 32 * 33 * - `number` (0–15) — ANSI 16 palette index. Emitted as standard SGR codes 34 * (e.g., index 1 → fg 31, bg 41). Values outside 0–15 are not supported 35 * and will produce incorrect SGR codes. 36 * - `string` — 24-bit hex color (e.g., `"#ff0000"`). Emitted as 37 * true-color SGR codes (`38;2;r;g;b` / `48;2;r;g;b`). 38 */ 39export type ThemeValue = number | string; 40 41/** 42 * A mapping from the 16 color slots to rendering output. 43 * 44 * The default theme maps each slot to its matching ANSI palette index 45 * (color00 → 0, color01 → 1, etc.), inheriting the terminal's configured 46 * color scheme automatically. 47 * 48 * Custom themes can remap slots to different ANSI indices, 24-bit hex 49 * colors, or a mix of both. 50 * 51 * @example 52 * // Catppuccin Mocha (true color) 53 * const mocha: Theme = { 54 * color00: "#1e1e2e", 55 * color01: "#f38ba8", 56 * color02: "#a6e3a1", 57 * // ... remaining slots 58 * }; 59 */ 60export type Theme = Record<Color, ThemeValue>; 61 62/** 63 * Kitty keyboard protocol progressive-enhancement flags requested at init. 64 * Baseline escape-code disambiguation is always enabled. Associated text 65 * automatically enables all-keys reporting, as required by the protocol. 66 */ 67export interface KittyKeyboardOptions { 68 /** Report `press`, `repeat`, and `release` event types. */ 69 reportEventTypes?: boolean; 70 /** Report shifted and base-keyboard-layout alternate keys. */ 71 reportAlternateKeys?: boolean; 72 /** Encode text-producing and modifier keys as structured CSI-u events. */ 73 reportAllKeys?: boolean; 74 /** Include produced text as code points. Implies {@link reportAllKeys}. */ 75 reportAssociatedText?: boolean; 76} 77 78/** 79 * Styling props shared by all node types. 80 * 81 * Maps directly to terminal SGR (Select Graphic Rendition) attributes. 82 * Containers propagate their styles to descendants — child nodes inherit 83 * the nearest ancestor's values unless they set a value explicitly. 84 */ 85export interface StyleProps { 86 /** Render text with bold weight. */ 87 bold?: boolean; 88 /** Render text in italic style. */ 89 italic?: boolean; 90 /** Render text with an underline. */ 91 underline?: boolean; 92 /** Foreground (text) color. */ 93 fgColor?: Color; 94 /** Background color. */ 95 bgColor?: Color; 96} 97 98/** 99 * A size value expressed as a fixed cell count or a percentage string. 100 * 101 * @example 102 * 30 // 30 cells 103 * "50%" // 50% of parent 104 * "100%" // fill parent 105 */ 106export type SizeValue = number | `${number}%`; 107 108/** 109 * Stable identity for framework-managed node state. 110 * 111 * Keys are unique among mounted stateful nodes in a viewport. State follows 112 * the key across ordinary re-renders and structural reordering, and is 113 * discarded after the key is absent for a rendered frame. 114 */ 115export type StateKey = string | number; 116 117/** Visual shape used for a focused TextInput cursor. */ 118export type CursorStyle = "block" | "bar" | "underline"; 119 120/** Kitty keyboard event phase. Legacy input can report only `"press"`. */ 121export type KeyEventType = "press" | "repeat" | "release"; 122 123/** Modifier state reported with a keyboard event. */ 124export interface KeyModifiers { 125 readonly shift: boolean; 126 readonly alt: boolean; 127 readonly ctrl: boolean; 128 readonly super: boolean; 129 readonly hyper: boolean; 130 readonly meta: boolean; 131 readonly capsLock: boolean; 132 readonly numLock: boolean; 133} 134 135/** Structured metadata delivered as the second `onKeyPress` argument. */ 136export interface KeyEvent { 137 /** Normalized semantic key string, also supplied as the first argument. */ 138 readonly key: string; 139 /** Exact insertable text when the terminal reported text for this event. */ 140 readonly text?: string; 141 /** Press/repeat/release phase. Legacy input is reported as `"press"`. */ 142 readonly eventType: KeyEventType; 143 /** Main CSI-u Unicode/private-use code point, when available. */ 144 readonly codePoint?: number; 145 /** Shifted key reported by Kitty alternate-key mode. */ 146 readonly shiftedKey?: string; 147 /** Standard PC-101 layout key reported by Kitty alternate-key mode. */ 148 readonly baseLayoutKey?: string; 149 /** 150 * Modifier and lock-key state reported by the host. Legacy byte/text input 151 * cannot carry this metadata, so fields the host did not report are false. 152 */ 153 readonly modifiers: KeyModifiers; 154} 155 156/** 157 * Props shared by layout container nodes ({@link ContainerNode}). 158 * 159 * Controls layout, sizing, scrolling, focus, click handling, key events, 160 * and styling. Style props on containers are inherited by descendants — 161 * child nodes use the nearest ancestor's values unless they set their own. 162 * Container `bgColor` fills the container rect before painting children. 163 */ 164export type KeyPressHandler = 165 | ((key: string, event: KeyEvent) => void) 166 | ((key: string, event: KeyEvent) => boolean); 167 168/** 169 * Scroll input callback for controlled and uncontrolled scroll containers. 170 * 171 * Return exactly `false` to decline handling and continue scroll propagation 172 * to the next scrollable ancestor. Any other return value, including 173 * `undefined`, consumes the scroll event. Controlled containers update through 174 * this callback; uncontrolled containers update framework state after the 175 * callback accepts the event. 176 * 177 * This is a union of `void`-returning and `boolean`-returning callback 178 * signatures instead of a single `boolean | void` return type so legacy 179 * expression-bodied void handlers remain source-compatible even when they 180 * incidentally return another value. 181 */ 182export type ScrollHandler = 183 | ((offset: number, maxOffset: number) => void) 184 | ((offset: number, maxOffset: number) => boolean); 185 186/** Why a focus change callback fired. */ 187export type FocusChangeReason = 188 "auto" | "tab" | "shift+tab" | "click" | "escape"; 189 190/** Metadata for {@link ContainerProps.onFocus} / {@link ContainerProps.onBlur}. */ 191export interface FocusChangeEvent { 192 /** What caused the focus transition. */ 193 reason: FocusChangeReason; 194} 195 196/** Focus change notification callback. */ 197export type FocusChangeHandler = (event: FocusChangeEvent) => void; 198 199/** Character and terminal style for one scrollbar part. */ 200export interface ScrollbarPartStyle extends StyleProps { 201 /** A single terminal-column grapheme. */ 202 char?: string; 203} 204 205/** Custom thumb and track rendering for container scrollbars. */ 206export interface ScrollbarStyle { 207 /** Scrollbar thumb appearance. */ 208 thumb?: ScrollbarPartStyle; 209 /** Scrollbar track appearance. */ 210 track?: ScrollbarPartStyle; 211} 212 213export interface ContainerProps extends StyleProps { 214 /** 215 * Stable identity for framework-managed focus, scroll, and TextInput state. 216 * 217 * Provide this when a stateful node can move, when callbacks are recreated 218 * inline, or when multiple TextInputs share an `onChange` callback. Keys 219 * must be unique among mounted stateful nodes in the viewport. Omitting the 220 * key retains the legacy structural/callback-based fallback behavior. 221 */ 222 stateKey?: StateKey; 223 224 /** 225 * Fixed width in cells, or percentage of parent width. 226 * When omitted, the container uses intrinsic sizing (fits content) 227 * or flex/percentage if those are set. 228 */ 229 width?: SizeValue; 230 231 /** 232 * Fixed height in cells, or percentage of parent height. 233 * When omitted, the container uses intrinsic sizing (fits content) 234 * or flex/percentage if those are set. 235 */ 236 height?: SizeValue; 237 238 /** 239 * Flex grow factor. Space remaining after fixed and intrinsic children 240 * is distributed proportionally among flex children. 241 * 242 * @example 243 * flex: 1 // equal share 244 * flex: 2 // double share 245 */ 246 flex?: number; 247 248 /** Minimum width constraint in cells. */ 249 minWidth?: number; 250 /** Maximum width constraint in cells. */ 251 maxWidth?: number; 252 /** Minimum height constraint in cells. */ 253 minHeight?: number; 254 /** Maximum height constraint in cells. */ 255 maxHeight?: number; 256 257 /** 258 * Internal padding in cells. 259 * `x` adds horizontal padding (left + right), `y` adds vertical (top + bottom). 260 */ 261 padding?: { x?: number; y?: number }; 262 263 /** Spacing between children in cells. */ 264 gap?: number; 265 266 /** 267 * Distribute children along the main axis. 268 * - VStack main axis = vertical 269 * - HStack main axis = horizontal 270 */ 271 justifyContent?: "start" | "end" | "center" | "space-between"; 272 273 /** 274 * Align children along the cross axis. 275 * - VStack cross axis = horizontal 276 * - HStack cross axis = vertical 277 */ 278 alignItems?: "start" | "end" | "center" | "stretch"; 279 280 /** 281 * Whether children wrap to the next line when they exceed the 282 * container's main-axis size. Only meaningful on HStack. 283 * 284 * - `"nowrap"` (default) — all children on one line, may overflow. 285 * - `"wrap"` — children that exceed the width flow to the next row. 286 * 287 * When wrapping, each row is laid out independently: flex children 288 * distribute remaining space within their row, `justifyContent` 289 * applies per row, and `alignItems` applies per row. Rows are 290 * stacked vertically with `gap` spacing between them. 291 */ 292 flexWrap?: "nowrap" | "wrap"; 293 294 /** 295 * Content overflow behavior. 296 * - `"hidden"` (default) — clip content at the container edge. 297 * - `"scroll"` — enable scrolling along the main axis. 298 */ 299 overflow?: "hidden" | "scroll"; 300 301 /** Show a scrollbar indicator when `overflow` is `"scroll"`. */ 302 scrollbar?: boolean; 303 304 /** Customize scrollbar thumb/track characters and terminal styles. */ 305 scrollbarStyle?: ScrollbarStyle; 306 307 /** 308 * Mouse wheel step size in cells along the container's main axis. 309 * When omitted, the framework uses an adaptive default based on the 310 * scroll target's viewport size: `floor(viewportMainAxis / 3)`, 311 * clamped to the range `3..8`. 312 * 313 * Affects mouse wheel input only — not programmatic {@link scrollOffset} 314 * updates or TextInput cursor-follow behavior. 315 */ 316 scrollStep?: number; 317 318 /** 319 * Controlled scroll position in cells. When provided, the app owns 320 * scroll state and must update this value via {@link onScroll}. 321 * When omitted, scroll is framework-managed (uncontrolled). 322 */ 323 scrollOffset?: number; 324 325 /** 326 * Called when the user scrolls this container (mouse wheel). 327 * In controlled mode, update {@link scrollOffset} with the new value 328 * to move the scroll position. 329 * 330 * Return `false` to decline handling and continue scroll propagation 331 * to the next scrollable ancestor. Any other return value consumes the 332 * scroll event and stops propagation. 333 * 334 * @param offset - The new scroll offset in cells. 335 * @param maxOffset - The maximum scroll offset (content size minus viewport size). 336 * @returns `false` to keep bubbling, anything else to consume. 337 */ 338 onScroll?: ScrollHandler; 339 340 /** 341 * Called on mouse click or Enter key when this container is focused. 342 * Setting this prop makes the container focusable by default. 343 */ 344 onClick?: () => void; 345 346 /** 347 * Whether this element participates in keyboard traversal and mouse focus. 348 * TextInput defaults to `true`; containers default to `true` when 349 * {@link onClick} is set. Explicit controlled focus still works when false. 350 */ 351 focusable?: boolean; 352 353 /** 354 * Whether this container is currently focused. 355 * 356 * When provided, focus is **controlled** — the app owns the state and 357 * must update this value via {@link onFocus}/{@link onBlur}. 358 * When omitted, focus is **uncontrolled** — the framework manages 359 * focus internally (Tab/Shift+Tab/Escape/click just work). 360 */ 361 focused?: boolean; 362 363 /** 364 * Seed focus once when this identity first mounts in the active layer. 365 * The topmost layer wins. After Escape, auto focus is not reclaimed until 366 * the identity unmounts for a rendered frame and mounts again. 367 */ 368 autoFocus?: boolean; 369 370 /** 371 * Called when this container receives focus. 372 * The event includes the transition reason (`auto`, `tab`, `shift+tab`, `click`, or `escape`). 373 * In uncontrolled mode, this is a notification callback. 374 * In controlled mode, update {@link focused} here. 375 */ 376 onFocus?: FocusChangeHandler; 377 378 /** 379 * Called when this container loses focus. 380 * The event includes the transition reason (`auto`, `tab`, `shift+tab`, `click`, or `escape`). 381 * In uncontrolled mode, this is a notification callback. 382 * In controlled mode, update {@link focused} here. 383 */ 384 onBlur?: FocusChangeHandler; 385 386 /** 387 * Style overrides applied when this element is focused. 388 * Accepts any {@link StyleProps} — overridden values replace the 389 * element's normal styles and participate in inheritance. 390 * 391 * Works in both uncontrolled and controlled focus modes. 392 * 393 * @example 394 * { bgColor: "color06", fgColor: "color00" } // reverse-video effect 395 */ 396 focusStyle?: StyleProps; 397 398 /** 399 * Called on key events that bubble up to this container. 400 * Keys are first handled by the focused element; unconsumed keys 401 * (e.g., non-editing shortcuts like `"ctrl+s"`) bubble up through ancestors. 402 * The root container's `onKeyPress` acts as the global key handler. 403 * 404 * Return `false` to indicate the key was **not consumed** — it will 405 * continue bubbling to the next ancestor handler. Any other return 406 * value (`undefined`, `true`, or no return) means the key was consumed 407 * and bubbling stops. This is backward-compatible: existing `void` 408 * handlers consume by default. 409 * 410 * Key format: all lowercase, modifiers joined by `+` in canonical order 411 * `ctrl+alt+shift+super+hyper+meta+<key>` (e.g., `"ctrl+s"`, `"alt+up"`, 412 * `"escape"`). 413 * The key string is a **semantic identifier**, not necessarily the exact 414 * inserted text — for example, uppercase `A` is reported as key `"a"`. 415 * Structured event metadata (including repeat/release phase, insertable 416 * text, alternate keys, and reported modifiers) is supplied as the second 417 * argument. One-argument handlers remain valid. 418 * 419 * @param key - Normalized semantic key string. 420 * @param event - Structured keyboard event metadata. 421 * @returns `false` to keep bubbling, anything else to consume. 422 */ 423 onKeyPress?: KeyPressHandler; 424} 425 426/** 427 * Props for the `Text` primitive. 428 * 429 * Text is a styled leaf node with no children and no sizing props — 430 * the parent container controls the box. Height is intrinsic, computed 431 * from content, newlines, and word-wrapping at the given width. 432 */ 433export interface TextProps extends StyleProps { 434 /** 435 * Repeat the text content a fixed number of times or to fill the 436 * available width. When set, wrapping is ignored. 437 * 438 * @example 439 * repeat: "fill" // fills parent width (e.g., dividers) 440 * repeat: 20 // repeats exactly 20 times 441 */ 442 repeat?: number | "fill"; 443 444 /** 445 * Text wrapping mode. 446 * - `"none"` (default) — no wrapping, content is hard-clipped at the box edge. 447 * - `"word"` — word-wrap to fit available width. Affects computed height. 448 * 449 * Whitespace is always preserved. `\n` produces explicit line breaks. 450 */ 451 wrap?: "none" | "word"; 452} 453 454/** 455 * Container-derived props that are meaningful for a TextInput. 456 * 457 * This is an explicit allowlist: TextInput supports box sizing, inherited 458 * style, focus, key routing, and mouse-wheel step configuration. Child-layout 459 * controls, container scroll state/scrollbars, and click activation are 460 * intentionally excluded because TextInput has no children and owns its 461 * editing scroll behavior internally. 462 */ 463export type TextInputBaseProps = Pick< 464 ContainerProps, 465 | keyof StyleProps 466 | "stateKey" 467 | "width" 468 | "height" 469 | "flex" 470 | "minWidth" 471 | "maxWidth" 472 | "minHeight" 473 | "maxHeight" 474 | "padding" 475 | "scrollStep" 476 | "focusable" 477 | "focused" 478 | "autoFocus" 479 | "onFocus" 480 | "onBlur" 481 | "focusStyle" 482 | "onKeyPress" 483>; 484 485/** 486 * Props for the `TextInput` primitive. 487 * 488 * TextInput is a multi-line editable text container. It accepts container 489 * sizing props but has no children — its content is the `value` prop. 490 * Scroll is always framework-managed: the stored offset is clamped every render, 491 * mouse wheel input adjusts it, and focused inputs further adjust only as needed 492 * to keep the cursor visible after edits, cursor movement, or reflow. 493 * Word-wrap is always on. 494 * 495 * When focused, TextInput consumes insertable text plus editing/navigation 496 * keys (arrows, backspace, delete, Enter, Tab), along with a small set of 497 * readline-style shortcuts: `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, 498 * `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`. Word movement and 499 * deletion use whitespace-delimited boundaries, and `up` / `down` follow 500 * visual wrapped lines. Other modifier combos and non-insertable control 501 * keys bubble to ancestor {@link onKeyPress} handlers. 502 */ 503export interface TextInputProps extends TextInputBaseProps { 504 /** Current text content. Controlled — the app owns this value. */ 505 value: string; 506 507 /** 508 * Called when the user edits text. Update the controlled `value` prop 509 * with the new string and call `cel.render()` to reflect the change. 510 * 511 * @param value - The new text content. 512 */ 513 onChange: (value: string) => void; 514 515 /** 516 * Controlled UTF-16 cursor offset. The value is clamped backward to a 517 * grapheme boundary, so emoji and combining sequences are never split. 518 * When omitted, the framework manages the cursor internally. 519 */ 520 cursor?: number; 521 522 /** 523 * Called when editing or navigation requests a new cursor offset. 524 * In controlled mode, update `cursor` and render the new value. 525 */ 526 onCursorChange?: (cursor: number) => void; 527 528 /** 529 * Cursor shape for both the painted fallback and native terminal cursor. 530 * Defaults to `"block"`. 531 */ 532 cursorStyle?: CursorStyle; 533 534 /** 535 * Key handler that fires **before** the built-in editing logic. 536 * Return `false` to prevent the default editing action for that key 537 * (no character insertion, no cursor movement, no deletion). 538 * Any other return (or no return) lets the default action proceed. 539 * 540 * Receives the normalized **semantic** key string plus structured event 541 * metadata, not necessarily the exact inserted text. For example, typing 542 * uppercase `A` can report key `"a"` while `event.text` remains `"A"`. 543 * 544 * @example 545 * // Enter submits instead of inserting a newline 546 * onKeyPress: (key) => { 547 * if (key === "enter") { handleSend(); return false; } 548 * } 549 */ 550 onKeyPress?: KeyPressHandler; 551 552 /** 553 * A {@link TextNode} displayed when {@link value} is empty. 554 * Fully stylable — pass a `Text()` call with any styling props. 555 * 556 * @example 557 * placeholder: Text("type a message...", { fgColor: "color08" }) 558 */ 559 placeholder?: TextNode; 560} 561 562/** 563 * A text leaf node in the UI tree. 564 * 565 * Created by the `Text` function. Has no children — the parent 566 * container controls the box, and height is intrinsic (computed from 567 * content and wrapping). 568 */ 569export interface TextNode { 570 type: "text"; 571 /** The text content to display. */ 572 content: string; 573 /** Text styling and behavior props. */ 574 props: TextProps; 575} 576 577/** 578 * An editable text container node in the UI tree. 579 * 580 * Created by the `TextInput` function. Accepts container sizing 581 * props but has no children — its content is the `value` prop. 582 */ 583export interface TextInputNode { 584 type: "textinput"; 585 /** TextInput configuration and styling props. */ 586 props: TextInputProps; 587} 588 589/** 590 * A layout container node in the UI tree. 591 * 592 * Created by `VStack` (vertical) or `HStack` (horizontal). 593 * Contains an ordered list of child nodes. 594 */ 595export interface ContainerNode { 596 /** `"vstack"` for vertical layout, `"hstack"` for horizontal. */ 597 type: "vstack" | "hstack"; 598 /** Container layout, sizing, and interaction props. */ 599 props: ContainerProps; 600 /** Ordered child nodes. */ 601 children: Node[]; 602} 603 604/** 605 * Any node in the cel-tui UI tree. 606 * 607 * The tree is built from three node types: 608 * - {@link ContainerNode} — layout containers (VStack, HStack) 609 * - {@link TextNode} — styled text leaf 610 * - {@link TextInputNode} — editable text container 611 */ 612export type Node = TextNode | TextInputNode | ContainerNode;