70160
Ce
cel-tui / files
cel-tui / packages / components / src / spinner.ts
4.8 KB
1import { cel, Text, visibleWidth } from "@cel-tui/core"; 2import type { TextNode, TextProps } from "@cel-tui/types"; 3import { createTicker } from "./ticker.js"; 4 5/** Common Braille spinner frames used when no custom sequence is provided. */ 6export const DEFAULT_SPINNER_FRAMES = [ 7 "⠋", 8 "⠙", 9 "⠹", 10 "⠸", 11 "⠼", 12 "⠴", 13 "⠦", 14 "⠧", 15 "⠇", 16 "⠏", 17] as const; 18 19/** Configuration captured by a {@link Spinner} instance. */ 20export interface SpinnerProps extends TextProps { 21 /** Animation frames. Every frame must contain at least one visible cell. */ 22 frames?: readonly string[]; 23 /** 24 * Hard upper bound on animation and render frequency. 25 * @default 12.5 26 */ 27 maxFps?: number; 28 /** 29 * Start immediately when the instance is created. 30 * 31 * The default is `false`, keeping cel-tui reactive until animation is 32 * explicitly requested with {@link SpinnerInstance.start}. 33 * @default false 34 */ 35 autoStart?: boolean; 36 /** 37 * Pad narrower frames so every rendered frame has the same terminal width. 38 * @default true 39 */ 40 padFrames?: boolean; 41 /** Called after the active frame advances. */ 42 onFrame?: (frame: string, index: number) => void; 43 /** Override the default `cel.render()` request made after each frame. */ 44 requestRender?: () => void; 45} 46 47/** Callable, explicitly managed spinner component. */ 48export interface SpinnerInstance { 49 /** Render the current frame as a styled Text node. */ 50 (style?: TextProps): TextNode; 51 /** Zero-based current frame number; wraps only when selecting frame content. */ 52 readonly frame: number; 53 /** Current rendered frame content, including width-stabilizing padding. */ 54 readonly current: string; 55 /** Whether animation is currently scheduled. */ 56 readonly running: boolean; 57 /** Whether this instance has permanently released its ticker. */ 58 readonly disposed: boolean; 59 /** Begin animation. Repeated calls while running are ignored. */ 60 start(): void; 61 /** Pause animation without changing the current frame. */ 62 stop(): void; 63 /** Reset to the first frame and request a render. */ 64 reset(): void; 65 /** Stop permanently and release timer callbacks. */ 66 dispose(): void; 67} 68 69const DEFAULT_SPINNER_FPS = 12.5; 70 71function normalizeFrames( 72 source: readonly string[], 73 padFrames: boolean, 74): readonly string[] { 75 if (source.length === 0) { 76 throw new RangeError("Spinner requires at least one frame"); 77 } 78 79 const widths = source.map((frame) => visibleWidth(frame)); 80 if (widths.some((width) => width === 0)) { 81 throw new RangeError("Every Spinner frame must contain a visible cell"); 82 } 83 if (!padFrames) return [...source]; 84 85 const width = Math.max(...widths); 86 return source.map((frame, index) => 87 frame.padEnd(frame.length + width - (widths[index] ?? 0)), 88 ); 89} 90 91/** 92 * Create a configurable Spinner with explicit animation lifecycle. 93 * 94 * Constructing an instance is inert by default. Call `.start()` while work is 95 * active, `.stop()` when it pauses, and `.dispose()` when the owner unmounts. 96 * The callable itself is cheap and simply returns the current frame as Text. 97 * 98 * @example 99 * ```ts 100 * const saving = Spinner({ fgColor: "color06", maxFps: 12 }); 101 * 102 * saving.start(); 103 * cel.viewport(() => HStack({}, [saving(), Text(" Saving...")])); 104 * 105 * // Once saving finishes: 106 * saving.dispose(); 107 * ``` 108 */ 109export function Spinner(props: SpinnerProps = {}): SpinnerInstance { 110 const { 111 frames: sourceFrames = DEFAULT_SPINNER_FRAMES, 112 maxFps = DEFAULT_SPINNER_FPS, 113 autoStart = false, 114 padFrames = true, 115 onFrame, 116 requestRender, 117 ...textProps 118 } = props; 119 const frames = normalizeFrames(sourceFrames, padFrames); 120 const renderRequest = requestRender ?? cel.render; 121 let frame = 0; 122 123 const ticker = createTicker({ 124 maxFps, 125 requestRender: renderRequest, 126 onTick: () => { 127 frame++; 128 const content = frames[frame % frames.length]; 129 if (content !== undefined) onFrame?.(content, frame); 130 }, 131 }); 132 133 function currentFrame(): string { 134 const content = frames[frame % frames.length]; 135 if (content === undefined) { 136 // normalizeFrames guarantees this; retain a local invariant for TS and 137 // for defensive behavior if the captured array is mutated externally. 138 throw new Error("Spinner has no frame to render"); 139 } 140 return content; 141 } 142 143 const render = ((style?: TextProps) => 144 Text(currentFrame(), { ...textProps, ...style })) as SpinnerInstance; 145 146 Object.defineProperties(render, { 147 frame: { get: () => frame }, 148 current: { get: currentFrame }, 149 running: { get: () => ticker.running }, 150 disposed: { get: () => ticker.disposed }, 151 }); 152 render.start = () => ticker.start(); 153 render.stop = () => ticker.stop(); 154 render.reset = () => { 155 frame = 0; 156 renderRequest(); 157 }; 158 render.dispose = () => ticker.dispose(); 159 160 if (autoStart) ticker.start(); 161 return render; 162}