@termdraw/pi 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ben Vinegar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @termdraw/pi
2
+
3
+ `@termdraw/pi` embeds termDRAW inside Pi using `opentui-island` so you can open the editor as a full-screen Pi overlay and insert drawings back into the current editor.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pi install npm:@termdraw/pi
9
+ ```
10
+
11
+ For a project-local install:
12
+
13
+ ```bash
14
+ pi install -l npm:@termdraw/pi
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Inside Pi:
20
+
21
+ ```text
22
+ /termdraw
23
+ ```
24
+
25
+ Use `Enter` or `Ctrl+S` to insert the drawing into Pi. Use `Ctrl+Q` to close without inserting.
26
+
27
+ ## Local development
28
+
29
+ From this repo:
30
+
31
+ ```bash
32
+ bun install
33
+ pi install ./packages/pi
34
+ ```
35
+
36
+ Or run the extension directly for a one-off test:
37
+
38
+ ```bash
39
+ pi -e ./packages/pi/extensions/index.ts
40
+ ```
41
+
42
+ ## Smoke test
43
+
44
+ There is a tmux-based end-to-end smoke test that verifies:
45
+
46
+ - Pi starts with the extension loaded
47
+ - `/termdraw` opens the embedded overlay
48
+ - text can be entered into the island
49
+ - saving returns the drawing back into the Pi editor
50
+
51
+ Run it from the repo root:
52
+
53
+ ```bash
54
+ bun run smoke:pi
55
+ ```
56
+
57
+ Requirements:
58
+
59
+ - `pi` installed and on `PATH`
60
+ - `tmux` installed
61
+
62
+ Set `PI_TERMDRAW_SMOKE_KEEP_SESSION=1` if you want the tmux session left alive for debugging on exit.
63
+
64
+ ## Notes
65
+
66
+ - Requires Bun 1.3+ on the machine running Pi.
67
+ - The embedded island currently loads from source (`islands/termdraw.island.tsx`) via Bun.
68
+ - `opentui-island@0.3.0` still has an older optional Pi peer range, so some npm installs may still need `--legacy-peer-deps` depending on the Pi version in use.
69
+ - This package targets the terminal Pi experience first. GUI support will depend on Pi's extension UI surface.
70
+
71
+ ## License
72
+
73
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
2
+ import { runTermDrawCommand } from "./overlay.ts";
3
+
4
+ export default function piTermDrawExtension(pi: ExtensionAPI) {
5
+ pi.registerCommand("termdraw", {
6
+ description: "Open termDRAW inside a Pi overlay",
7
+ handler: async (_args, ctx) => {
8
+ await runTermDrawCommand(ctx);
9
+ },
10
+ });
11
+ }
@@ -0,0 +1,259 @@
1
+ import type { ExtensionCommandContext, Theme } from "@mariozechner/pi-coding-agent";
2
+ import {
3
+ matchesKey,
4
+ truncateToWidth,
5
+ visibleWidth,
6
+ type Component,
7
+ type TUI,
8
+ } from "@mariozechner/pi-tui";
9
+ import type { OpenTuiBridgeEvent } from "opentui-island";
10
+ import {
11
+ createPiTuiOpenTuiSurface,
12
+ disablePiTuiMouseMode,
13
+ enablePiTuiMouseMode,
14
+ type PiTuiOpenTuiSurface,
15
+ } from "opentui-island/pi-tui";
16
+
17
+ const TERM_DRAW_ISLAND_MODULE_URL = new URL("../islands/termdraw.island.tsx", import.meta.url);
18
+ const PI_FOOTER_TEXT =
19
+ "Right palette tools/styles/colors • select tool can marquee multiple objects • drag box corners / line endpoints to edit • Esc deselect • Enter inserts into Pi • Ctrl+Q cancels";
20
+ const READY_STATUS = "termDRAW ready. Press Enter or Ctrl+S to insert into Pi. Ctrl+Q cancels.";
21
+ const LOADING_STATUS = "Starting termDRAW in a Bun sidecar…";
22
+ const INSERTED_MESSAGE = "Inserted drawing into editor.";
23
+ const CANCELLED_MESSAGE = "Drawing cancelled.";
24
+ const ERROR_PREFIX = "termDRAW failed to start:";
25
+ const SMOKE_TEXT = process.env.PI_TERMDRAW_SMOKE_TEXT?.trim() ?? "";
26
+
27
+ function delay(ms: number): Promise<void> {
28
+ return new Promise((resolve) => setTimeout(resolve, ms));
29
+ }
30
+
31
+ type TermDrawSaveEvent = OpenTuiBridgeEvent<"save", { art: string }>;
32
+ type TermDrawCancelEvent = OpenTuiBridgeEvent<"cancel", { reason?: string }>;
33
+ type TermDrawOverlayResult = { kind: "save"; art: string } | { kind: "cancel" };
34
+
35
+ function isTermDrawSaveEvent(event: OpenTuiBridgeEvent): event is TermDrawSaveEvent {
36
+ return (
37
+ event.type === "save" &&
38
+ !!event.payload &&
39
+ typeof event.payload === "object" &&
40
+ "art" in event.payload
41
+ );
42
+ }
43
+
44
+ function isTermDrawCancelEvent(event: OpenTuiBridgeEvent): event is TermDrawCancelEvent {
45
+ return event.type === "cancel";
46
+ }
47
+
48
+ function padLine(text: string, width: number): string {
49
+ const truncated = truncateToWidth(text, width, "", true);
50
+ return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
51
+ }
52
+
53
+ function formatError(error: unknown): string {
54
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
55
+ }
56
+
57
+ function formatForEditor(art: string): string {
58
+ const content = art.length > 0 ? art : " ";
59
+ return `\`\`\`text\n${content}\n\`\`\``;
60
+ }
61
+
62
+ class TermDrawOverlay implements Component {
63
+ private readonly surfaceHeight: number;
64
+ private readonly width: number;
65
+ private readonly smokeText: string;
66
+ private surface: PiTuiOpenTuiSurface | null = null;
67
+ private unsubscribeFromEvents: (() => void) | null = null;
68
+ private status = LOADING_STATUS;
69
+ private error: string | null = null;
70
+ private closing = false;
71
+
72
+ constructor(
73
+ private readonly tui: TUI,
74
+ private readonly theme: Theme,
75
+ private readonly done: (value: TermDrawOverlayResult) => void,
76
+ ) {
77
+ this.width = Math.max(1, this.tui.terminal.columns);
78
+ this.surfaceHeight = Math.max(1, this.tui.terminal.rows - 1);
79
+ this.smokeText = SMOKE_TEXT;
80
+ enablePiTuiMouseMode(this.tui.terminal);
81
+ void this.initialize();
82
+ }
83
+
84
+ private async initialize(): Promise<void> {
85
+ try {
86
+ this.surface = await createPiTuiOpenTuiSurface({
87
+ height: this.surfaceHeight,
88
+ initialWidth: this.width,
89
+ requestRender: () => this.tui.requestRender(),
90
+ island: {
91
+ module: TERM_DRAW_ISLAND_MODULE_URL,
92
+ props: {
93
+ showStartupLogo: false,
94
+ footerText: PI_FOOTER_TEXT,
95
+ },
96
+ },
97
+ });
98
+ this.unsubscribeFromEvents = this.surface.onEvent((event) => {
99
+ if (isTermDrawSaveEvent(event)) {
100
+ void this.close({ kind: "save", art: event.payload.art });
101
+ return;
102
+ }
103
+
104
+ if (isTermDrawCancelEvent(event)) {
105
+ void this.close({ kind: "cancel" });
106
+ }
107
+ });
108
+ this.surface.focused = true;
109
+ this.surface.setScreenBounds({
110
+ row: 0,
111
+ col: 0,
112
+ width: this.width,
113
+ height: this.surfaceHeight,
114
+ });
115
+ await this.surface.sync(this.width);
116
+ this.status = READY_STATUS;
117
+ if (this.smokeText.length > 0) {
118
+ void this.runSmokeAutomation();
119
+ }
120
+ } catch (error) {
121
+ this.error = formatError(error);
122
+ this.status = `${ERROR_PREFIX} ${this.error}`;
123
+ }
124
+
125
+ this.tui.requestRender();
126
+ }
127
+
128
+ private async runSmokeAutomation(): Promise<void> {
129
+ if (!this.surface || this.closing) {
130
+ return;
131
+ }
132
+
133
+ try {
134
+ await delay(150);
135
+ await this.surface.sendInput("\t");
136
+ await delay(50);
137
+ await this.surface.sendInput("\t");
138
+ await delay(50);
139
+
140
+ for (const char of this.smokeText) {
141
+ await this.surface.sendInput(char);
142
+ }
143
+
144
+ await delay(100);
145
+ await this.surface.sendInput("\r");
146
+ } catch (error) {
147
+ this.status = `Smoke automation failed: ${formatError(error)}`;
148
+ this.tui.requestRender();
149
+ }
150
+ }
151
+
152
+ handleInput(data: string): void {
153
+ if (
154
+ this.error &&
155
+ (matchesKey(data, "ctrl+q") || matchesKey(data, "escape") || matchesKey(data, "ctrl+c"))
156
+ ) {
157
+ void this.close({ kind: "cancel" });
158
+ return;
159
+ }
160
+
161
+ this.surface?.handleInput(data);
162
+ this.tui.requestRender();
163
+ }
164
+
165
+ invalidate(): void {
166
+ this.surface?.invalidate();
167
+ }
168
+
169
+ render(width: number): string[] {
170
+ const normalizedWidth = Math.max(1, width);
171
+
172
+ this.surface?.setScreenBounds({
173
+ row: 0,
174
+ col: 0,
175
+ width: normalizedWidth,
176
+ height: this.surfaceHeight,
177
+ });
178
+
179
+ if (this.error) {
180
+ const body = Array.from({ length: Math.max(1, this.surfaceHeight) }, (_, index) => {
181
+ if (index === 0) {
182
+ return padLine(this.theme.fg("error", `${ERROR_PREFIX} ${this.error}`), normalizedWidth);
183
+ }
184
+ if (index === 1) {
185
+ return padLine(
186
+ this.theme.fg("dim", "Make sure Bun 1.3+ is installed and available on PATH."),
187
+ normalizedWidth,
188
+ );
189
+ }
190
+ return " ".repeat(normalizedWidth);
191
+ });
192
+
193
+ return [
194
+ ...body,
195
+ padLine(this.theme.fg("warning", "Ctrl+Q, Esc, or Ctrl+C closes."), normalizedWidth),
196
+ ];
197
+ }
198
+
199
+ if (!this.surface) {
200
+ const body = Array.from({ length: Math.max(1, this.surfaceHeight) }, (_, index) =>
201
+ index === 0
202
+ ? padLine(this.theme.fg("accent", LOADING_STATUS), normalizedWidth)
203
+ : " ".repeat(normalizedWidth),
204
+ );
205
+
206
+ return [...body, padLine(this.theme.fg("dim", "Loading termDRAW…"), normalizedWidth)];
207
+ }
208
+
209
+ const body = this.surface.render(normalizedWidth).slice(0, this.surfaceHeight);
210
+ const footer = padLine(this.theme.fg("dim", this.status), normalizedWidth);
211
+ return [...body, footer];
212
+ }
213
+
214
+ private async close(result: TermDrawOverlayResult): Promise<void> {
215
+ if (this.closing) {
216
+ return;
217
+ }
218
+
219
+ this.closing = true;
220
+ try {
221
+ this.unsubscribeFromEvents?.();
222
+ this.unsubscribeFromEvents = null;
223
+ await this.surface?.destroy();
224
+ } finally {
225
+ disablePiTuiMouseMode(this.tui.terminal);
226
+ this.done(result);
227
+ }
228
+ }
229
+ }
230
+
231
+ export async function runTermDrawCommand(ctx: ExtensionCommandContext): Promise<void> {
232
+ if (!ctx.hasUI) {
233
+ return;
234
+ }
235
+
236
+ const result = await ctx.ui.custom<TermDrawOverlayResult>(
237
+ (tui, theme, _keybindings, done) => new TermDrawOverlay(tui, theme, done),
238
+ {
239
+ overlay: true,
240
+ overlayOptions: {
241
+ row: 0,
242
+ col: 0,
243
+ width: "100%",
244
+ maxHeight: "100%",
245
+ margin: 0,
246
+ },
247
+ },
248
+ );
249
+
250
+ if (!result || result.kind === "cancel") {
251
+ ctx.ui.notify(CANCELLED_MESSAGE, "info");
252
+ return;
253
+ }
254
+
255
+ const existing = ctx.ui.getEditorText();
256
+ const prefix = existing.endsWith("\n") || existing.length === 0 ? "" : "\n";
257
+ ctx.ui.pasteToEditor(`${prefix}${formatForEditor(result.art)}\n`);
258
+ ctx.ui.notify(INSERTED_MESSAGE, "info");
259
+ }
@@ -0,0 +1,39 @@
1
+ /** @jsxImportSource @opentui/react */
2
+
3
+ import { useOpenTuiIslandBridge } from "opentui-island";
4
+ import { TermDrawApp } from "@termdraw/opentui";
5
+
6
+ type PiTermDrawIslandProps = {
7
+ showStartupLogo?: boolean;
8
+ footerText?: string;
9
+ };
10
+
11
+ export default function PiTermDrawIsland({
12
+ showStartupLogo = false,
13
+ footerText,
14
+ }: PiTermDrawIslandProps) {
15
+ const bridge = useOpenTuiIslandBridge();
16
+
17
+ return (
18
+ <TermDrawApp
19
+ width="100%"
20
+ height="100%"
21
+ autoFocus
22
+ showStartupLogo={showStartupLogo}
23
+ cancelOnCtrlC={false}
24
+ footerText={footerText}
25
+ onSave={(art) => {
26
+ bridge.emit({
27
+ type: "save",
28
+ payload: { art },
29
+ });
30
+ }}
31
+ onCancel={() => {
32
+ bridge.emit({
33
+ type: "cancel",
34
+ payload: { reason: "user" },
35
+ });
36
+ }}
37
+ />
38
+ );
39
+ }
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@termdraw/pi",
3
+ "version": "0.1.0",
4
+ "description": "Pi extension package that embeds termDRAW inside Pi via opentui-island.",
5
+ "keywords": [
6
+ "drawing",
7
+ "opentui",
8
+ "pi-extension",
9
+ "pi-package",
10
+ "terminal",
11
+ "tui"
12
+ ],
13
+ "homepage": "https://github.com/benvinegar/termdraw/tree/main/packages/pi#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/benvinegar/termdraw/issues"
16
+ },
17
+ "license": "MIT",
18
+ "author": "Ben Vinegar",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/benvinegar/termdraw.git"
22
+ },
23
+ "files": [
24
+ "extensions",
25
+ "islands",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "type": "module",
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "scripts": {
34
+ "typecheck": "tsc --noEmit -p tsconfig.json",
35
+ "pack:check": "npm pack --dry-run --ignore-scripts",
36
+ "smoke:pi": "bash ./scripts/smoke-pi-save.sh"
37
+ },
38
+ "dependencies": {
39
+ "@opentui/core": "^0.1.97",
40
+ "@opentui/react": "^0.1.97",
41
+ "@termdraw/opentui": "0.3.0",
42
+ "opentui-island": "^0.3.0",
43
+ "react": "^19.2.0"
44
+ },
45
+ "devDependencies": {
46
+ "@mariozechner/pi-coding-agent": "*",
47
+ "@mariozechner/pi-tui": "*",
48
+ "@types/react": "^19.2.14",
49
+ "typescript": "^5.9.3"
50
+ },
51
+ "peerDependencies": {
52
+ "@mariozechner/pi-coding-agent": "*",
53
+ "@mariozechner/pi-tui": "*"
54
+ },
55
+ "engines": {
56
+ "bun": ">=1.3.0",
57
+ "node": ">=18"
58
+ },
59
+ "pi": {
60
+ "extensions": [
61
+ "./extensions"
62
+ ]
63
+ }
64
+ }