@velum-labs/routekit-cli-ui 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Velum Labs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # @velum-labs/routekit-cli-ui
2
+
3
+ Brand-configurable terminal UI primitives for CLIs.
4
+
5
+ ## Architecture
6
+
7
+ This package provides the Ink presenter, prompt facade, and plain-text fallback used by user-facing commands.
8
+
9
+ ## Usage
10
+
11
+ Use this package when extending a RouteKit-based CLI presentation layer.
12
+
13
+ ```ts
14
+ import { configureBrand, createPresenter } from "@velum-labs/routekit-cli-ui";
15
+ ```
16
+
17
+ ## Docs
18
+
19
+ - Product docs: https://fusionkit.velum-labs.com
20
+ - Maintainer reference: [../../docs/typescript-reference.md](../../docs/typescript-reference.md)
@@ -0,0 +1,27 @@
1
+ /** Small human-readable formatters shared across surfaces. */
2
+ /** Human-readable bytes (binary units), e.g. 1.2 GB. */
3
+ export declare function formatBytes(bytes: number): string;
4
+ /** mm:ss for a duration in seconds (caps at 99:59 to stay one column-stable). */
5
+ export declare function formatEta(seconds: number): string;
6
+ /** A compact human-friendly "time ago" for a timestamp (epoch millis). */
7
+ export declare function relativeTime(epochMs: number): string;
8
+ /** A compact human-friendly "time until" for a future timestamp (epoch millis). */
9
+ export declare function timeUntil(epochMs: number): string;
10
+ /**
11
+ * Truncate with a middle ellipsis so both ends stay recognizable — long model
12
+ * ids like `openrouter:moonshotai/kimi-k2-thinking` keep their provider prefix
13
+ * and model suffix. Plain-text only (measure/slice before styling).
14
+ */
15
+ export declare function middleEllipsis(text: string, max: number): string;
16
+ /**
17
+ * Greedy word-wrap to `width` columns. Words longer than the width are hard
18
+ * split. Existing newlines are respected. Plain-text only.
19
+ */
20
+ export declare function wrapText(text: string, width: number): string[];
21
+ /**
22
+ * The usable content width for wrapped UI text on the current terminal. The
23
+ * default cap matches the widest box content (`box()` caps frames at 100
24
+ * columns and its frame consumes 4), so pre-wrapped text nests in boxes
25
+ * without re-wrapping.
26
+ */
27
+ export declare function contentWidth(stream?: NodeJS.WriteStream, max?: number): number;
package/dist/format.js ADDED
@@ -0,0 +1,112 @@
1
+ /** Small human-readable formatters shared across surfaces. */
2
+ /** The single-character horizontal ellipsis ("…"), used when truncating. */
3
+ const ELLIPSIS = "…";
4
+ /** Human-readable bytes (binary units), e.g. 1.2 GB. */
5
+ export function formatBytes(bytes) {
6
+ if (!Number.isFinite(bytes) || bytes <= 0)
7
+ return "0 B";
8
+ const units = ["B", "KB", "MB", "GB", "TB"];
9
+ let value = bytes;
10
+ let unit = 0;
11
+ while (value >= 1024 && unit < units.length - 1) {
12
+ value /= 1024;
13
+ unit += 1;
14
+ }
15
+ const precision = value >= 100 || unit === 0 ? 0 : 1;
16
+ const text = value.toFixed(precision);
17
+ const trimmed = text.endsWith(".0") ? text.slice(0, -2) : text;
18
+ return `${trimmed} ${units[unit]}`;
19
+ }
20
+ /** mm:ss for a duration in seconds (caps at 99:59 to stay one column-stable). */
21
+ export function formatEta(seconds) {
22
+ if (!Number.isFinite(seconds) || seconds < 0)
23
+ return "--:--";
24
+ const capped = Math.min(seconds, 99 * 60 + 59);
25
+ const mins = Math.floor(capped / 60);
26
+ const secs = Math.floor(capped % 60);
27
+ return `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
28
+ }
29
+ /** Coarse "Nx" magnitude (`45s`, `12m`, `3h`, `2d`) for a duration in seconds. */
30
+ function coarseDuration(seconds) {
31
+ if (seconds < 60)
32
+ return `${seconds}s`;
33
+ const minutes = Math.round(seconds / 60);
34
+ if (minutes < 60)
35
+ return `${minutes}m`;
36
+ const hours = Math.round(minutes / 60);
37
+ if (hours < 24)
38
+ return `${hours}h`;
39
+ const days = Math.round(hours / 24);
40
+ return `${days}d`;
41
+ }
42
+ /** A compact human-friendly "time ago" for a timestamp (epoch millis). */
43
+ export function relativeTime(epochMs) {
44
+ return `${coarseDuration(Math.max(0, Math.round((Date.now() - epochMs) / 1000)))} ago`;
45
+ }
46
+ /** A compact human-friendly "time until" for a future timestamp (epoch millis). */
47
+ export function timeUntil(epochMs) {
48
+ const seconds = Math.round((epochMs - Date.now()) / 1000);
49
+ return seconds <= 0 ? "now" : `in ${coarseDuration(seconds)}`;
50
+ }
51
+ /**
52
+ * Truncate with a middle ellipsis so both ends stay recognizable — long model
53
+ * ids like `openrouter:moonshotai/kimi-k2-thinking` keep their provider prefix
54
+ * and model suffix. Plain-text only (measure/slice before styling).
55
+ */
56
+ export function middleEllipsis(text, max) {
57
+ if (max <= 1 || text.length <= max)
58
+ return text;
59
+ const keep = max - ELLIPSIS.length;
60
+ const head = Math.ceil(keep / 2);
61
+ const tail = keep - head;
62
+ return `${text.slice(0, head)}${ELLIPSIS}${tail > 0 ? text.slice(-tail) : ""}`;
63
+ }
64
+ /**
65
+ * Greedy word-wrap to `width` columns. Words longer than the width are hard
66
+ * split. Existing newlines are respected. Plain-text only.
67
+ */
68
+ export function wrapText(text, width) {
69
+ if (width <= 0)
70
+ return [text];
71
+ const out = [];
72
+ for (const paragraph of text.split("\n")) {
73
+ if (paragraph.length <= width) {
74
+ out.push(paragraph);
75
+ continue;
76
+ }
77
+ let line = "";
78
+ for (const word of paragraph.split(" ")) {
79
+ let piece = word;
80
+ while (piece.length > width) {
81
+ if (line.length > 0) {
82
+ out.push(line);
83
+ line = "";
84
+ }
85
+ out.push(piece.slice(0, width));
86
+ piece = piece.slice(width);
87
+ }
88
+ if (line.length === 0)
89
+ line = piece;
90
+ else if (line.length + 1 + piece.length <= width)
91
+ line += ` ${piece}`;
92
+ else {
93
+ out.push(line);
94
+ line = piece;
95
+ }
96
+ }
97
+ out.push(line);
98
+ }
99
+ return out;
100
+ }
101
+ /**
102
+ * The usable content width for wrapped UI text on the current terminal. The
103
+ * default cap matches the widest box content (`box()` caps frames at 100
104
+ * columns and its frame consumes 4), so pre-wrapped text nests in boxes
105
+ * without re-wrapping.
106
+ */
107
+ export function contentWidth(stream = process.stderr, max = 96) {
108
+ const columns = stream.columns;
109
+ if (columns === undefined || columns <= 0)
110
+ return Math.min(80, max);
111
+ return Math.min(Math.max(columns - 4, 20), max);
112
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The fuzzy matcher behind `fuzzySelect` and dynamic shell completion: a
3
+ * case-insensitive subsequence match with a small scoring model (consecutive
4
+ * runs and word starts score higher, earlier and shorter matches win ties).
5
+ * Dependency-free so completion can use it without pulling in Ink.
6
+ */
7
+ export type FuzzyMatch = {
8
+ /** Higher is better; only comparable across matches for the same query. */
9
+ score: number;
10
+ /** Indices of matched characters in the original text (for highlighting). */
11
+ positions: readonly number[];
12
+ };
13
+ /**
14
+ * Match `query` as a subsequence of `text`. Returns undefined when the query
15
+ * does not match. An empty query matches everything with score 0.
16
+ */
17
+ export declare function fuzzyMatch(query: string, text: string): FuzzyMatch | undefined;
18
+ export type FuzzyResult<T> = {
19
+ item: T;
20
+ match: FuzzyMatch;
21
+ };
22
+ /** Filter and rank `items` by fuzzy-matching `query` against `textOf(item)`. */
23
+ export declare function fuzzyFilter<T>(query: string, items: readonly T[], textOf: (item: T) => string): FuzzyResult<T>[];
package/dist/fuzzy.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The fuzzy matcher behind `fuzzySelect` and dynamic shell completion: a
3
+ * case-insensitive subsequence match with a small scoring model (consecutive
4
+ * runs and word starts score higher, earlier and shorter matches win ties).
5
+ * Dependency-free so completion can use it without pulling in Ink.
6
+ */
7
+ /** True when `ch` starts a word (after a separator or a case boundary). */
8
+ function isWordStart(text, index) {
9
+ if (index === 0)
10
+ return true;
11
+ const prev = text[index - 1] ?? "";
12
+ if (/[\s\-_/.:=]/.test(prev))
13
+ return true;
14
+ const ch = text[index] ?? "";
15
+ return /[a-z]/.test(prev) && /[A-Z]/.test(ch);
16
+ }
17
+ /**
18
+ * Match `query` as a subsequence of `text`. Returns undefined when the query
19
+ * does not match. An empty query matches everything with score 0.
20
+ */
21
+ export function fuzzyMatch(query, text) {
22
+ if (query.length === 0)
23
+ return { score: 0, positions: [] };
24
+ const lowerQuery = query.toLowerCase();
25
+ const lowerText = text.toLowerCase();
26
+ const positions = [];
27
+ let score = 0;
28
+ let textIndex = 0;
29
+ let previousMatch = -2;
30
+ for (let queryIndex = 0; queryIndex < lowerQuery.length; queryIndex++) {
31
+ const ch = lowerQuery[queryIndex] ?? "";
32
+ const found = lowerText.indexOf(ch, textIndex);
33
+ if (found === -1)
34
+ return undefined;
35
+ positions.push(found);
36
+ score += 1;
37
+ if (found === previousMatch + 1)
38
+ score += 2; // consecutive run
39
+ if (isWordStart(text, found))
40
+ score += 3; // word-start hit
41
+ previousMatch = found;
42
+ textIndex = found + 1;
43
+ }
44
+ // Earlier first hit and shorter text read as tighter matches.
45
+ const first = positions[0] ?? 0;
46
+ score += Math.max(0, 3 - first * 0.5);
47
+ score -= text.length * 0.01;
48
+ return { score, positions };
49
+ }
50
+ /** Filter and rank `items` by fuzzy-matching `query` against `textOf(item)`. */
51
+ export function fuzzyFilter(query, items, textOf) {
52
+ const results = [];
53
+ for (const item of items) {
54
+ const match = fuzzyMatch(query, textOf(item));
55
+ if (match !== undefined)
56
+ results.push({ item, match });
57
+ }
58
+ if (query.length > 0)
59
+ results.sort((left, right) => right.match.score - left.match.score);
60
+ return results;
61
+ }
@@ -0,0 +1,21 @@
1
+ import type { Presenter } from "./presenter.js";
2
+ export * from "./theme.js";
3
+ export * from "./runtime.js";
4
+ export * from "./format.js";
5
+ export * from "./presenter.js";
6
+ export { PlainPresenter, renderErrorPanelLines, renderKeyValueLines, renderTableLines } from "./plain.js";
7
+ export { InkPresenter, mountInk, settleInk } from "./ink/presenter.js";
8
+ export { select, multiselect, confirm, text, fuzzySelect, autocompleteText, BACK, done, note } from "./prompt.js";
9
+ export type { SelectOption, Back } from "./prompt.js";
10
+ export { fuzzyFilter, fuzzyMatch } from "./fuzzy.js";
11
+ export type { FuzzyMatch, FuzzyResult } from "./fuzzy.js";
12
+ export { runWizard } from "./wizard.js";
13
+ export type { WizardStep } from "./wizard.js";
14
+ /**
15
+ * The presenter for this invocation: Ink when attached to an interactive TTY,
16
+ * plain line logs otherwise. `forceNonInteractive()` (the `--json` /
17
+ * `--no-input` flags) flips this to plain for the rest of the process.
18
+ */
19
+ export declare function createPresenter(options?: {
20
+ interactive?: boolean;
21
+ }): Presenter;
package/dist/index.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @velum-labs/routekit-cli-ui — a brand-configurable terminal UX layer.
3
+ *
4
+ * One presenter contract, two implementations: rich Ink (React) rendering on
5
+ * interactive TTYs, ordered plain-text lines everywhere else (CI, pipes,
6
+ * `ROUTEKIT_NO_TUI=1`). All UI goes to stderr; stdout stays reserved for
7
+ * machine payloads and the launched tool's output.
8
+ */
9
+ import { InkPresenter } from "./ink/presenter.js";
10
+ import { PlainPresenter } from "./plain.js";
11
+ import { isInteractive } from "./runtime.js";
12
+ export * from "./theme.js";
13
+ export * from "./runtime.js";
14
+ export * from "./format.js";
15
+ export * from "./presenter.js";
16
+ export { PlainPresenter, renderErrorPanelLines, renderKeyValueLines, renderTableLines } from "./plain.js";
17
+ export { InkPresenter, mountInk, settleInk } from "./ink/presenter.js";
18
+ export { select, multiselect, confirm, text, fuzzySelect, autocompleteText, BACK, done, note } from "./prompt.js";
19
+ export { fuzzyFilter, fuzzyMatch } from "./fuzzy.js";
20
+ export { runWizard } from "./wizard.js";
21
+ /**
22
+ * The presenter for this invocation: Ink when attached to an interactive TTY,
23
+ * plain line logs otherwise. `forceNonInteractive()` (the `--json` /
24
+ * `--no-input` flags) flips this to plain for the rest of the process.
25
+ */
26
+ export function createPresenter(options = {}) {
27
+ const interactive = options.interactive ?? isInteractive();
28
+ return interactive ? new InkPresenter() : new PlainPresenter();
29
+ }
@@ -0,0 +1,49 @@
1
+ import type { ReactElement } from "react";
2
+ import type { StepStatus } from "../presenter.js";
3
+ import { Store } from "./store.js";
4
+ export type LiveFrameState = {
5
+ lines: readonly string[];
6
+ };
7
+ export declare function LiveFrameView({ store }: {
8
+ store: Store<LiveFrameState>;
9
+ }): ReactElement;
10
+ /** Animate through the braille spinner frames while mounted. */
11
+ export declare function useSpinnerFrame(intervalMs?: number): string;
12
+ export type TaskState = {
13
+ text: string;
14
+ settled?: {
15
+ kind: "success" | "fail" | "warn" | "info";
16
+ text: string;
17
+ };
18
+ };
19
+ export declare function TaskView({ store }: {
20
+ store: Store<TaskState>;
21
+ }): ReactElement;
22
+ export type ChecklistStep = {
23
+ id: string;
24
+ label: string;
25
+ status: StepStatus;
26
+ detail?: string;
27
+ startedAt?: number;
28
+ endedAt?: number;
29
+ };
30
+ export type ChecklistState = {
31
+ title?: string;
32
+ steps: ChecklistStep[];
33
+ };
34
+ export declare function ChecklistView({ store }: {
35
+ store: Store<ChecklistState>;
36
+ }): ReactElement;
37
+ export type ProgressState = {
38
+ label: string;
39
+ downloaded: number;
40
+ total?: number;
41
+ startedAt: number;
42
+ settled?: {
43
+ kind: "success" | "fail";
44
+ text: string;
45
+ };
46
+ };
47
+ export declare function ProgressView({ store }: {
48
+ store: Store<ProgressState>;
49
+ }): ReactElement;
@@ -0,0 +1,116 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * The Ink components behind the presenter's live surfaces: a spinner task, a
4
+ * multi-step checklist, and a byte-download progress bar. Each is driven by a
5
+ * mutable {@link Store} that the imperative controller updates.
6
+ */
7
+ import { Box, Text } from "ink";
8
+ import { useEffect, useState, useSyncExternalStore } from "react";
9
+ import { formatBytes, formatEta } from "../format.js";
10
+ import { SPINNER_FRAMES, glyph, supportsColor } from "../theme.js";
11
+ export function LiveFrameView({ store }) {
12
+ const state = useSyncExternalStore(store.subscribe, store.get, store.get);
13
+ return (_jsx(Box, { flexDirection: "column", children: state.lines.map((line, index) => (_jsx(Text, { children: line }, `${index}:${line}`))) }));
14
+ }
15
+ /** Animate through the braille spinner frames while mounted. */
16
+ export function useSpinnerFrame(intervalMs = 80) {
17
+ const [frame, setFrame] = useState(0);
18
+ useEffect(() => {
19
+ const timer = setInterval(() => {
20
+ setFrame((previous) => (previous + 1) % SPINNER_FRAMES.length);
21
+ }, intervalMs);
22
+ timer.unref();
23
+ return () => clearInterval(timer);
24
+ }, [intervalMs]);
25
+ return SPINNER_FRAMES[frame] ?? "-";
26
+ }
27
+ function settledGlyph(kind) {
28
+ switch (kind) {
29
+ case "success":
30
+ return { symbol: glyph.tick(), color: "green" };
31
+ case "fail":
32
+ return { symbol: glyph.cross(), color: "red" };
33
+ case "warn":
34
+ return { symbol: glyph.warn(), color: "yellow" };
35
+ case "info":
36
+ return { symbol: glyph.bullet(), color: "cyan" };
37
+ default: {
38
+ const exhaustive = kind;
39
+ throw new Error(`unknown settle kind: ${String(exhaustive)}`);
40
+ }
41
+ }
42
+ }
43
+ export function TaskView({ store }) {
44
+ const state = useSyncExternalStore(store.subscribe, store.get, store.get);
45
+ const frame = useSpinnerFrame();
46
+ if (state.settled !== undefined) {
47
+ const { symbol, color } = settledGlyph(state.settled.kind);
48
+ return (_jsxs(Text, { children: [_jsx(Text, { color: color, children: symbol }), " ", state.settled.text] }));
49
+ }
50
+ return (_jsxs(Text, { children: [_jsx(Text, { color: "cyan", children: frame }), " ", state.text] }));
51
+ }
52
+ function elapsedLabel(step) {
53
+ if (step.startedAt === undefined)
54
+ return "";
55
+ const end = step.endedAt ?? Date.now();
56
+ const seconds = (end - step.startedAt) / 1000;
57
+ if (seconds < 0.05)
58
+ return "";
59
+ return ` ${seconds.toFixed(1)}s`;
60
+ }
61
+ function StepRow({ step, frame }) {
62
+ let symbol;
63
+ switch (step.status) {
64
+ case "pending":
65
+ symbol = _jsx(Text, { color: "gray", children: glyph.pending() });
66
+ break;
67
+ case "active":
68
+ symbol = _jsx(Text, { color: "cyan", children: frame });
69
+ break;
70
+ case "done":
71
+ symbol = _jsx(Text, { color: "green", children: glyph.tick() });
72
+ break;
73
+ case "failed":
74
+ symbol = _jsx(Text, { color: "red", children: glyph.cross() });
75
+ break;
76
+ case "skipped":
77
+ symbol = _jsx(Text, { color: "yellow", children: glyph.bullet() });
78
+ break;
79
+ default: {
80
+ const exhaustive = step.status;
81
+ throw new Error(`unknown step status: ${String(exhaustive)}`);
82
+ }
83
+ }
84
+ return (_jsxs(Text, { children: [symbol, " ", step.label, step.detail !== undefined ? _jsxs(Text, { dimColor: true, children: [" ", step.detail] }) : null, _jsx(Text, { color: "gray", children: elapsedLabel(step) })] }));
85
+ }
86
+ export function ChecklistView({ store }) {
87
+ const state = useSyncExternalStore(store.subscribe, store.get, store.get);
88
+ const frame = useSpinnerFrame();
89
+ return (_jsxs(Box, { flexDirection: "column", children: [state.title !== undefined ? _jsx(Text, { dimColor: true, children: state.title }) : null, state.steps.map((step) => (_jsx(StepRow, { step: step, frame: frame }, step.id)))] }));
90
+ }
91
+ const BAR_WIDTH = 24;
92
+ function ProgressBarLine({ state, frame }) {
93
+ const elapsed = (Date.now() - state.startedAt) / 1000;
94
+ const speed = elapsed > 0 ? state.downloaded / elapsed : 0;
95
+ const speedLabel = speed > 0 ? `${formatBytes(speed)}/s` : "";
96
+ if (state.total !== undefined && state.total > 0) {
97
+ const fraction = Math.max(0, Math.min(1, state.downloaded / state.total));
98
+ const filledChar = supportsColor() ? "\u2588" : "#";
99
+ const emptyChar = supportsColor() ? "\u2591" : "-";
100
+ const filled = Math.round(fraction * BAR_WIDTH);
101
+ const pct = `${Math.floor(fraction * 100)}%`.padStart(4);
102
+ const sizes = `${formatBytes(state.downloaded)} / ${formatBytes(state.total)}`;
103
+ const remaining = speed > 0 ? formatEta((state.total - state.downloaded) / speed) : "--:--";
104
+ return (_jsxs(Text, { children: [state.label, " ", _jsx(Text, { color: "cyan", children: filledChar.repeat(filled) }), _jsx(Text, { dimColor: true, children: emptyChar.repeat(BAR_WIDTH - filled) }), " ", _jsx(Text, { color: "cyan", children: pct }), " ", _jsxs(Text, { dimColor: true, children: [sizes, " ", speedLabel, " ", "eta ", remaining] })] }));
105
+ }
106
+ return (_jsxs(Text, { children: [state.label, " ", _jsx(Text, { color: "cyan", children: frame }), " ", _jsxs(Text, { dimColor: true, children: [formatBytes(state.downloaded), speedLabel.length > 0 ? ` ${speedLabel}` : ""] })] }));
107
+ }
108
+ export function ProgressView({ store }) {
109
+ const state = useSyncExternalStore(store.subscribe, store.get, store.get);
110
+ const frame = useSpinnerFrame(90);
111
+ if (state.settled !== undefined) {
112
+ const ok = state.settled.kind === "success";
113
+ return (_jsxs(Text, { children: [_jsx(Text, { color: ok ? "green" : "red", children: ok ? glyph.tick() : glyph.cross() }), " ", state.settled.text] }));
114
+ }
115
+ return _jsx(ProgressBarLine, { state: state, frame: frame });
116
+ }