xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / components / src / button.ts

2.5 KB
1import { HStack, Text } from "@cel-tui/core";
2import type { ContainerNode, ContainerProps, StyleProps } from "@cel-tui/types";
3
4/**
5 * Props for the {@link Button} component.
6 *
7 * Extends {@link StyleProps} — all style props (`fgColor`, `bgColor`,
8 * `bold`, `italic`, `underline`) are set on the container and inherited
9 * by the label text. This enables `focusStyle` to override them when
10 * the button is focused.
11 */
12export interface ButtonProps extends StyleProps {
13  /** Called on mouse click or Enter when focused. */
14  onClick: () => void;
15  /**
16   * Whether the button participates in focus traversal.
17   * @default true
18   */
19  focusable?: boolean;
20  /**
21   * Whether this button is currently focused (controlled mode).
22   * When provided, the app owns focus state and must update it
23   * via {@link onFocus}/{@link onBlur}.
24   */
25  focused?: boolean;
26  /** Called when the button receives focus. */
27  onFocus?: ContainerProps["onFocus"];
28  /** Called when the button loses focus. */
29  onBlur?: ContainerProps["onBlur"];
30  /**
31   * Style overrides applied when focused. Overridden values
32   * participate in inheritance — the label text sees the
33   * focused styles as its defaults.
34   */
35  focusStyle?: StyleProps;
36  /**
37   * Key event handler. Receives normalized semantic keys that bubble up
38   * to this button. Return `false` to keep bubbling.
39   */
40  onKeyPress?: ContainerProps["onKeyPress"];
41  /** Internal padding in cells. */
42  padding?: { x?: number; y?: number };
43}
44
45/**
46 * Clickable button with a styled text label.
47 *
48 * A convenience wrapper around an `HStack` with `onClick` containing
49 * a styled `Text` node. Focusable by default — reachable via Tab and
50 * activated with Enter.
51 *
52 * Style props are set on the container, not the text — this means
53 * `bgColor` fills the button rect and `focusStyle` can override
54 * any style when focused.
55 *
56 * @param label - Button text.
57 * @param props - Click handler, styling, and focus configuration.
58 * @returns A clickable container node.
59 *
60 * @example
61 * // Basic styled button
62 * Button("[Send]", { onClick: handleSend, bold: true, fgColor: "color06" })
63 *
64 * @example
65 * // Button with focus style (keyboard navigation)
66 * Button("[OK]", {
67 *   onClick: handleOk,
68 *   bgColor: "color08",
69 *   focusStyle: { bgColor: "color02", fgColor: "color00" },
70 * })
71 *
72 * @example
73 * // Mouse-only button (not in Tab order)
74 * Button("✕", { onClick: handleClose, focusable: false })
75 */
76export function Button(label: string, props: ButtonProps): ContainerNode {
77  return HStack(props, [Text(label)]);
78}