@@ -0,0 +1,858 @@
1+/**
2+ * cel-tui: Virtual Pet (Tamagotchi)
3+ *
4+ * A feature-rich example exercising the full API surface:
5+ * - Layers (creation modal, log modal, death screen overlay)
6+ * - TextInput (pet name)
7+ * - Focus traversal (Tab/Shift+Tab/Enter/Escape)
8+ * - Controlled scroll (activity log)
9+ * - Timers & animation frames
10+ * - Buttons, key bindings, click handlers
11+ * - External state management
12+ *
13+ * Run: bun run examples/pet.ts
14+ */
15+
16+import {
17+ cel,
18+ VStack,
19+ HStack,
20+ Text,
21+ TextInput,
22+ ProcessTerminal,
23+} from "@cel-tui/core";
24+import { Button, Divider, Spacer } from "@cel-tui/components";
25+
26+// ─── Pet Definitions ────────────────────────────────────────────
27+
28+interface PetDef {
29+ kind: string;
30+ idle: { happy: string[][]; hungry: string[][] };
31+ excited: string[][];
32+ dead: string[];
33+}
34+
35+const PETS: PetDef[] = [
36+ {
37+ kind: "Cat",
38+ idle: {
39+ happy: [
40+ [
41+ " /\\_/\\ ",
42+ " ( ^.^ ) ",
43+ " > ^ < ",
44+ " /| |\\ ",
45+ " (_| |_) ",
46+ ],
47+ [
48+ " /\\_/\\ ",
49+ " ( ^.^ ) ",
50+ " > ^ < ",
51+ " /| |\\ ",
52+ " (_| |_) ",
53+ " ~ ~ ",
54+ ],
55+ ],
56+ hungry: [
57+ [
58+ " /\\_/\\ ",
59+ " ( T.T ) ",
60+ " > o < ",
61+ " /| |\\ ",
62+ " (_| |_) ",
63+ ],
64+ [
65+ " /\\_/\\ ",
66+ " ( T.T ) ",
67+ " > o < ",
68+ " | | ",
69+ " _| |_ ",
70+ ],
71+ ],
72+ },
73+ excited: [
74+ [
75+ " /\\_/\\ ",
76+ " ( >.< ) ",
77+ " >\\^/< ",
78+ " \\| |/ ",
79+ " (_\\_/_) ",
80+ " \\ / ",
81+ ],
82+ [
83+ " /\\_/\\ ",
84+ " \\( ^o^ )/ ",
85+ " > ^ < ",
86+ " | | ",
87+ " (_\\_/_) ",
88+ " / \\ ",
89+ ],
90+ ],
91+ dead: [
92+ " /\\_/\\ ",
93+ " ( x.x ) ",
94+ " > - < ",
95+ " | | ",
96+ " |___| ",
97+ ],
98+ },
99+ {
100+ kind: "Dog",
101+ idle: {
102+ happy: [
103+ [
104+ " |\\_/| ",
105+ " | @ @ ",
106+ " | <> _ ",
107+ " |_/| |// ",
108+ " |/ / ",
109+ " / / ",
110+ ],
111+ [
112+ " |\\_/| ",
113+ " | @ @ ",
114+ " | <> _ ",
115+ " |_/| |// ",
116+ " |/ / ",
117+ " / |_/ ",
118+ ],
119+ ],
120+ hungry: [
121+ [
122+ " |\\_/| ",
123+ " | ; ; ",
124+ " | .. _ ",
125+ " |_/| |// ",
126+ " |/ / ",
127+ " / / ",
128+ ],
129+ [
130+ " |\\_/| ",
131+ " | ; ; ",
132+ " | .. ",
133+ " |_/| | ",
134+ " |/ | ",
135+ " / / ",
136+ ],
137+ ],
138+ },
139+ excited: [
140+ [
141+ " |\\_/| ",
142+ " | O O ",
143+ " | D> _ ",
144+ " |_/| |// ",
145+ " /|/ _/ ",
146+ " / |__/ ",
147+ ],
148+ [
149+ " |\\_/| ",
150+ " | O O ",
151+ " | D> ",
152+ " __|_/|\\__ ",
153+ " / |/ \\ ",
154+ " / | / ",
155+ ],
156+ ],
157+ dead: [
158+ " |\\_/| ",
159+ " | x x ",
160+ " | -- _ ",
161+ " |_/| |// ",
162+ " |/ / ",
163+ " /____/ ",
164+ ],
165+ },
166+ {
167+ kind: "Bunny",
168+ idle: {
169+ happy: [
170+ [" (\\(\\ ", " ( -.-) ", ' o_(")(") '],
171+ [" (\\(\\ ", " ( -.-) ", ' o_(")(") ', " * "],
172+ ],
173+ hungry: [
174+ [" (\\(\\ ", " ( ;.;) ", ' c_(")(") '],
175+ [" (\\(\\ ", " ( ;.;) ", ' c_(")(") ', " ... "],
176+ ],
177+ },
178+ excited: [
179+ [" (\\(\\ ", " ( ^.^) ", ' (")(")_o ', " \\|/ "],
180+ [" (\\(\\ ", " \\( ^o^)/ ", ' (")(") ', " /|\\ "],
181+ ],
182+ dead: [
183+ " (\\(\\ ",
184+ " ( x.x) ",
185+ ' c_(")(") ',
186+ " R.I.P ",
187+ ],
188+ },
189+];
190+
191+// ─── App State ──────────────────────────────────────────────────
192+
193+type Screen = "create" | "main" | "dead";
194+let screen: Screen = "create";
195+
196+// -- Creation state --
197+let petName = "";
198+let selectedKind = 0;
199+let nameInputFocused = false; // only TextInput needs controlled focus (arrow key routing)
200+
201+// -- Pet state --
202+let pet: PetDef | null = null;
203+let health = 100;
204+let hunger = 0; // 0 = full, 100 = starving
205+let happiness = 100;
206+
207+// -- Animation --
208+let frame = 0;
209+let anim: "idle" | "excited" = "idle";
210+let excitedTimer: ReturnType<typeof setTimeout> | null = null;
211+
212+// -- Timers --
213+let tickTimer: ReturnType<typeof setInterval> | null = null;
214+let decayTimer: ReturnType<typeof setInterval> | null = null;
215+
216+// -- Activity log --
217+let log: string[] = [];
218+let showLog = false;
219+let logScroll = 0;
220+
221+// ─── Helpers ────────────────────────────────────────────────────
222+
223+function ts(): string {
224+ return new Date().toLocaleTimeString("en-US", { hour12: false });
225+}
226+
227+function addLog(msg: string) {
228+ log.push(`[${ts()}] ${msg}`);
229+ logScroll = Math.max(0, log.length - 12);
230+}
231+
232+function startGame() {
233+ pet = PETS[selectedKind]!;
234+ if (!petName.trim()) petName = pet.kind;
235+ health = 100;
236+ hunger = 0;
237+ happiness = 100;
238+ anim = "idle";
239+ frame = 0;
240+ log = [];
241+ screen = "main";
242+
243+ addLog(`${petName} the ${pet.kind} was born!`);
244+ addLog("Press [F] feed · [P] pet · [L] log");
245+ startTimers();
246+ cel.render();
247+}
248+
249+function startTimers() {
250+ stopTimers();
251+ tickTimer = setInterval(() => {
252+ frame++;
253+ cel.render();
254+ }, 600);
255+
256+ decayTimer = setInterval(() => {
257+ if (screen !== "main") return;
258+ hunger = Math.min(100, hunger + 3);
259+ happiness = Math.max(0, happiness - 2);
260+ if (hunger >= 80) happiness = Math.max(0, happiness - 2);
261+ if (hunger >= 90 && happiness <= 20) health = Math.max(0, health - 5);
262+ if (health <= 0) return die();
263+ if (hunger >= 70) addLog(`${petName} is hungry...`);
264+ if (happiness <= 25) addLog(`${petName} feels lonely...`);
265+ if (health <= 30) addLog(`${petName} doesn't look well!`);
266+ cel.render();
267+ }, 3000);
268+}
269+
270+function stopTimers() {
271+ if (tickTimer) clearInterval(tickTimer);
272+ if (decayTimer) clearInterval(decayTimer);
273+ if (excitedTimer) clearTimeout(excitedTimer);
274+ tickTimer = decayTimer = excitedTimer = null;
275+}
276+
277+function feed() {
278+ if (screen !== "main") return;
279+ hunger = Math.max(0, hunger - 30);
280+ health = Math.min(100, health + 5);
281+ addLog(`You fed ${petName}! Hunger -30`);
282+ playExcited();
283+}
284+
285+function petIt() {
286+ if (screen !== "main") return;
287+ happiness = Math.min(100, happiness + 25);
288+ addLog(`You pet ${petName}! Happy +25`);
289+ playExcited();
290+}
291+
292+function playExcited() {
293+ anim = "excited";
294+ frame = 0;
295+ if (excitedTimer) clearTimeout(excitedTimer);
296+ excitedTimer = setTimeout(() => {
297+ anim = "idle";
298+ cel.render();
299+ }, 2400);
300+ cel.render();
301+}
302+
303+function die() {
304+ addLog(`${petName} has passed away...`);
305+ screen = "dead";
306+ stopTimers();
307+ cel.render();
308+}
309+
310+function restart() {
311+ stopTimers();
312+ pet = null;
313+ petName = "";
314+ selectedKind = 0;
315+ screen = "create";
316+ log = [];
317+ showLog = false;
318+ cel.render();
319+}
320+
321+function quit() {
322+ stopTimers();
323+ cel.stop();
324+ process.exit(0);
325+}
326+
327+// ─── Terminal Size ──────────────────────────────────────────────
328+
329+const MIN_COLS = 40;
330+const MIN_ROWS = 15;
331+
332+function termSize(): { cols: number; rows: number } {
333+ return {
334+ cols: process.stdout.columns || 80,
335+ rows: process.stdout.rows || 24,
336+ };
337+}
338+
339+function tooSmallView() {
340+ return VStack(
341+ {
342+ height: "100%",
343+ justifyContent: "center",
344+ alignItems: "center",
345+ onKeyPress: (key) => {
346+ if (key === "ctrl+q" || key === "ctrl+c") quit();
347+ },
348+ },
349+ [
350+ Text("┌─────────────────────────┐", { fgColor: "yellow" }),
351+ Text("│ Terminal too small :( │", { fgColor: "yellow" }),
352+ Text("│ │", { fgColor: "yellow" }),
353+ Text("│ Please resize to at │", { fgColor: "yellow" }),
354+ Text(
355+ `│ least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars. │`,
356+ { fgColor: "yellow" },
357+ ),
358+ Text("│ │", { fgColor: "yellow" }),
359+ Text("│ Ctrl+Q to quit │", { fgColor: "yellow" }),
360+ Text("└─────────────────────────┘", { fgColor: "yellow" }),
361+ ],
362+ );
363+}
364+
365+// ─── Art Helpers ────────────────────────────────────────────────
366+
367+function maxArtHeight(def: PetDef): number {
368+ const frames = [
369+ ...def.idle.happy,
370+ ...def.idle.hungry,
371+ ...def.excited,
372+ def.dead,
373+ ];
374+ return Math.max(...frames.map((f) => f.length));
375+}
376+
377+function currentArt(): string[] {
378+ if (!pet) return [];
379+ let lines: string[];
380+ if (anim === "excited") {
381+ lines = pet.excited[frame % pet.excited.length]!;
382+ } else {
383+ const mood = hunger > 60 || happiness < 30 ? "hungry" : "happy";
384+ const frames = pet.idle[mood];
385+ lines = frames[frame % frames.length]!;
386+ }
387+ // Pad to consistent height so buttons don't bounce
388+ const target = maxArtHeight(pet);
389+ while (lines.length < target) lines = [...lines, ""];
390+ return lines;
391+}
392+
393+function artColor(): "cyan" | "yellow" | "magenta" {
394+ if (anim === "excited") return "magenta";
395+ if (hunger > 60 || happiness < 30) return "yellow";
396+ return "cyan";
397+}
398+
399+// ─── Reusable Widgets ───────────────────────────────────────────
400+
401+function StatBar(
402+ label: string,
403+ value: number,
404+ color: "green" | "yellow" | "red" | "cyan",
405+) {
406+ const w = 12;
407+ const filled = Math.round((value / 100) * w);
408+ return VStack({}, [
409+ Text(label, { bold: true, fgColor: "white" }),
410+ HStack({}, [
411+ Text("█", { repeat: Math.max(filled, 0), fgColor: color }),
412+ Text("░", { repeat: Math.max(w - filled, 0), fgColor: "brightBlack" }),
413+ Text(` ${value}`, { fgColor: "brightBlack" }),
414+ ]),
415+ ]);
416+}
417+
418+function barColor(val: number, invert = false): "green" | "yellow" | "red" {
419+ const v = invert ? 100 - val : val;
420+ if (v > 60) return "green";
421+ if (v > 30) return "yellow";
422+ return "red";
423+}
424+
425+// ─── Create Screen ──────────────────────────────────────────────
426+
427+function createView() {
428+ const { rows } = termSize();
429+ const preview = PETS[selectedKind]!;
430+ const previewArt = preview.idle.happy[frame % preview.idle.happy.length]!;
431+ // Compact mode: drop art preview when height is tight
432+ const showPreview = rows >= 22;
433+
434+ return VStack(
435+ {
436+ height: "100%",
437+ alignItems: "center",
438+ overflow: "scroll",
439+ onKeyPress: (key) => {
440+ if (key === "ctrl+q" || key === "ctrl+c") quit();
441+ // Arrow keys to pick species (only when name input is NOT focused)
442+ if (!nameInputFocused) {
443+ if (key === "up") {
444+ selectedKind = (selectedKind - 1 + PETS.length) % PETS.length;
445+ cel.render();
446+ } else if (key === "down") {
447+ selectedKind = (selectedKind + 1) % PETS.length;
448+ cel.render();
449+ }
450+ }
451+ },
452+ },
453+ [
454+ Spacer(),
455+ VStack({ width: 40, padding: { x: 2 }, gap: 0 }, [
456+ // Title
457+ HStack({ justifyContent: "center" }, [
458+ Text("~ New Pet ~", { bold: true, fgColor: "cyan" }),
459+ ]),
460+ Divider({ fgColor: "brightBlack" }),
461+
462+ // Name
463+ Text("Name:", { bold: true, fgColor: "white" }),
464+ TextInput({
465+ value: petName,
466+ onChange: (v) => {
467+ petName = v;
468+ cel.render();
469+ },
470+ height: 1,
471+ fgColor: "brightWhite",
472+ bgColor: "black",
473+ placeholder: Text("enter a name...", {
474+ fgColor: "brightBlack",
475+ bgColor: "black",
476+ }),
477+ // Controlled focus: needed to gate arrow key routing above
478+ focused: nameInputFocused,
479+ onFocus: () => {
480+ nameInputFocused = true;
481+ cel.render();
482+ },
483+ onBlur: () => {
484+ nameInputFocused = false;
485+ cel.render();
486+ },
487+ submitKey: "enter",
488+ onSubmit: () => {
489+ nameInputFocused = false;
490+ cel.render();
491+ },
492+ }),
493+
494+ // Species picker
495+ Text(""),
496+ Text("Species:", { bold: true, fgColor: "white" }),
497+ ...PETS.map((p, i) => {
498+ const sel = i === selectedKind;
499+ return HStack(
500+ {
501+ onClick: () => {
502+ selectedKind = i;
503+ cel.render();
504+ },
505+ focusable: false,
506+ },
507+ [
508+ Text(sel ? " > " : " ", {
509+ fgColor: sel ? "cyan" : "brightBlack",
510+ bold: sel,
Cut short: this commit's diff is over 1000 lines.