xonecas.io
70160
Ce

cel-tui / files

cel-tui / examples / simple-scroll.ts

6.8 KB
1/**
2 * cel-tui: Activity Feed
3 *
4 * A polished uncontrolled-scroll example: a live-looking feed of
5 * deploys, alerts, and background jobs. The framework owns scroll
6 * position; the app just renders a long list.
7 *
8 * Run: bun run examples/simple-scroll.ts
9 */
10
11import { Divider, Spacer } from "@cel-tui/components";
12import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
13import { warningBox } from "./warning-box";
14
15const MIN_COLS = 46;
16const MIN_ROWS = 12;
17
18type FeedLevel = "deploy" | "healthy" | "warning" | "incident";
19
20interface FeedItem {
21  time: string;
22  level: FeedLevel;
23  service: string;
24  title: string;
25  detail: string;
26}
27
28const SERVICES = [
29  "edge-api",
30  "billing-worker",
31  "search-indexer",
32  "session-cache",
33  "upload-proxy",
34  "docs-site",
35  "queue-router",
36  "release-bot",
37];
38
39const ACTIONS: Record<FeedLevel, string[]> = {
40  deploy: [
41    "rolled out build",
42    "promoted canary",
43    "published preview",
44    "finished migration",
45  ],
46  healthy: [
47    "latency back in budget",
48    "queue depth normalized",
49    "cache warmed successfully",
50    "all health checks green",
51  ],
52  warning: [
53    "retry rate climbing",
54    "disk usage trending up",
55    "fallback path engaged",
56    "background job running slow",
57  ],
58  incident: [
59    "error burst detected",
60    "deploy automatically paused",
61    "worker restarted after crash",
62    "replica marked unhealthy",
63  ],
64};
65
66const DETAILS = [
67  "Observed in the last 5 minutes across the primary region.",
68  "A follow-up run is already queued for verification.",
69  "Operators left it visible here so the scroll demo has texture.",
70  "The next render should diff cleanly without repainting the whole screen.",
71  "This is intentionally long enough to exercise wrapping in the feed pane.",
72  "Nothing is interactive here besides scroll and refresh — the example stays focused.",
73];
74
75let items = buildFeed();
76
77function randomFrom<T>(values: readonly T[]): T {
78  return values[Math.floor(Math.random() * values.length)]!;
79}
80
81function levelStyle(level: FeedLevel) {
82  switch (level) {
83    case "deploy":
84      return { label: "DEPLOY", color: "color04" as const };
85    case "healthy":
86      return { label: "OK", color: "color02" as const };
87    case "warning":
88      return { label: "WARN", color: "color03" as const };
89    case "incident":
90      return { label: "ALERT", color: "color01" as const };
91  }
92}
93
94function formatTime(minutesAgo: number): string {
95  const date = new Date(Date.now() - minutesAgo * 60_000);
96  return date.toLocaleTimeString("en-US", {
97    hour12: false,
98    hour: "2-digit",
99    minute: "2-digit",
100  });
101}
102
103function buildFeed(count = 64): FeedItem[] {
104  return Array.from({ length: count }, (_, index) => {
105    const level = randomFrom([
106      "deploy",
107      "healthy",
108      "healthy",
109      "warning",
110      "incident",
111    ] as const);
112    const service = randomFrom(SERVICES);
113    const action = randomFrom(ACTIONS[level]);
114    const detail = randomFrom(DETAILS);
115    const minutesAgo = index * 3 + Math.floor(Math.random() * 3);
116
117    return {
118      time: formatTime(minutesAgo),
119      level,
120      service,
121      title: `${service} ${action}`,
122      detail,
123    };
124  });
125}
126
127function count(level: FeedLevel): number {
128  return items.filter((item) => item.level === level).length;
129}
130
131function regenerateFeed() {
132  items = buildFeed();
133  cel.render();
134}
135
136function quit() {
137  cel.stop();
138  process.exit(0);
139}
140
141function renderSummaryChip(level: FeedLevel) {
142  const style = levelStyle(level);
143  return HStack({ gap: 1 }, [
144    Text(` ${style.label} `, {
145      fgColor: "color00",
146      bgColor: style.color,
147      bold: true,
148    }),
149    Text(String(count(level)), { fgColor: "color08" }),
150  ]);
151}
152
153function renderFeedItem(item: FeedItem, index: number) {
154  const style = levelStyle(item.level);
155
156  return VStack({ gap: 0 }, [
157    HStack({ gap: 1 }, [
158      Text(item.time, { fgColor: "color08" }),
159      Text(` ${style.label} `, {
160        fgColor: "color00",
161        bgColor: style.color,
162        bold: true,
163      }),
164      Text(item.title, { bold: true }),
165      Spacer(),
166      Text(`#${String(items.length - index).padStart(2, "0")}`, {
167        fgColor: "color08",
168      }),
169    ]),
170    Text(`  ${item.detail}`, {
171      fgColor: "color08",
172      wrap: "word",
173    }),
174  ]);
175}
176
177cel.init(new ProcessTerminal());
178cel.viewport(() => {
179  const cols = process.stdout.columns || 80;
180  const rows = process.stdout.rows || 24;
181
182  if (cols < MIN_COLS || rows < MIN_ROWS) {
183    return VStack(
184      {
185        height: "100%",
186        justifyContent: "center",
187        alignItems: "center",
188        onKeyPress: (key) => {
189          if (key === "ctrl+q" || key === "ctrl+c") quit();
190        },
191      },
192      [
193        ...warningBox([
194          "  Terminal too small :(",
195          "",
196          "  Please resize to at",
197          `  least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars.`,
198          "",
199          "  Ctrl+Q to quit",
200        ]),
201      ],
202    );
203  }
204
205  const compactHeader = cols < 72;
206
207  return VStack(
208    {
209      height: "100%",
210      onKeyPress: (key) => {
211        if (key === "ctrl+q" || key === "ctrl+c") quit();
212        if (key === "ctrl+r") regenerateFeed();
213      },
214    },
215    [
216      compactHeader
217        ? HStack({ padding: { x: 1 }, gap: 1, flexWrap: "wrap" }, [
218            Text("Live Activity Feed", { bold: true, fgColor: "color06" }),
219            Text("uncontrolled scroll", {
220              fgColor: "color08",
221              italic: true,
222            }),
223            Text(`${items.length} events`, { fgColor: "color08" }),
224          ])
225        : HStack({ padding: { x: 1 }, gap: 2 }, [
226            Text("Live Activity Feed", { bold: true, fgColor: "color06" }),
227            Text("uncontrolled scroll", {
228              fgColor: "color08",
229              italic: true,
230            }),
231            Spacer(),
232            Text(`${items.length} events`, { fgColor: "color08" }),
233          ]),
234      HStack({ padding: { x: 1 }, gap: 2, flexWrap: "wrap" }, [
235        renderSummaryChip("deploy"),
236        renderSummaryChip("healthy"),
237        renderSummaryChip("warning"),
238        renderSummaryChip("incident"),
239      ]),
240      Divider({ fgColor: "color08" }),
241      VStack(
242        {
243          flex: 1,
244          overflow: "scroll",
245          scrollbar: true,
246          padding: { x: 1, y: 1 },
247          gap: 1,
248        },
249        items.map(renderFeedItem),
250      ),
251      Divider({ fgColor: "color08" }),
252      HStack({ padding: { x: 1 }, flexWrap: "wrap", gap: 1 }, [
253        Text("Mouse wheel", { fgColor: "color08", bold: true }),
254        Text("scroll", { fgColor: "color08" }),
255        Text("·", { fgColor: "color08" }),
256        Text("Ctrl+R", { fgColor: "color08", bold: true }),
257        Text("refresh feed", { fgColor: "color08" }),
258        Text("·", { fgColor: "color08" }),
259        Text("Ctrl+Q", { fgColor: "color08", bold: true }),
260        Text("quit", { fgColor: "color08" }),
261      ]),
262    ],
263  );
264});