@pi-kaush/pi-content-layout 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/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ - Pad submitted message text two columns right of the accent rail (one extra leading space inside the body) for more breathing room in the chat log.
6
+ - Paint the active editor surface and submitted message body with a fixed
7
+ `#071312` background (`PROMPT_SURFACE_BG`) instead of the theme's `selectedBg`
8
+ token, keeping both user-input surfaces identical while the theme token
9
+ continues to serve selections and dialogs.
10
+ - Inset dim system status rows (for example `showStatus` reload notices) to the
11
+ shared transcript column via instance-level decoration registered on the
12
+ `kg.pi.chatContainerHooks.v1` hook registry, so the inset composes with
13
+ `pi-tool-call-markers`' grouping wrapper in either load order.
14
+ - Add a two-column outer inset to assistant and user transcript rows.
15
+ - Render the active editor as a rail-free, edge-to-edge dark surface with one extra horizontal layout column on each side and one background-colored padding row above and below; preserve functional scroll indicators in those rows.
16
+ - Render submitted user messages with a thin accent rail and the same darker semantic background behind the padded message body.
17
+ - Compose with existing custom editors and preserve Pi's native input, autocomplete, cursor, history, paste, and keybinding behavior.
18
+ - Keep autocomplete rows outside the prompt block.
19
+ - Add guarded, reversible native message render adapters that fail open to Pi's renderer.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaushik Gopal
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,56 @@
1
+ # pi-content-layout
2
+
3
+ A small Pi extension that insets the main conversation, renders the active editor as a full-width dark surface, and gives submitted prompts a compact rail shell.
4
+
5
+ ```text
6
+ Assistant output
7
+ Text wraps inside the inset width.
8
+
9
+ Active prompt
10
+ ████████████████████████████████████████████████
11
+ prompt text darker background
12
+ ████████████████████████████████████████████████
13
+
14
+ Submitted prompt
15
+ ▎ darker background
16
+ ▎ prompt text darker background
17
+ ▎ darker background
18
+ ```
19
+
20
+ Assistant and submitted-message content keep the two-column outer inset. The active prompt intentionally ignores that inset: its darker background fills the terminal width, with no rail, one extra layout column on each side of Pi's configured editor padding, and one background-colored row above and below the content. Real scroll indicators replace the corresponding padding row when needed. The submitted prompt remains unchanged: it keeps Pi's message padding and the thin rail outside its darker body. Autocomplete stays outside the active surface.
21
+
22
+ ## Install
23
+
24
+ ```json
25
+ {
26
+ "packages": ["npm:@pi-kaush/pi-content-layout"]
27
+ }
28
+ ```
29
+
30
+ The package is not published while its version is `0.0.0`; use the repository path for local development.
31
+
32
+ ## Theme ownership
33
+
34
+ The active editor surface and submitted message body paint with a fixed
35
+ near-black `#071312` background (`PROMPT_SURFACE_BG`) so both user-input
36
+ surfaces stay identical; the theme's `selectedBg` token continues to serve
37
+ selections and dialogs. The extension consumes two theme tokens: `accent`
38
+ for the submitted-prompt rail and `muted` for the editor scroll hints.
39
+
40
+ Themes control colors, while this extension controls width and component
41
+ shape; a theme cannot provide the layout itself.
42
+
43
+ ## Composition and compatibility
44
+
45
+ The editor factory wraps the currently configured custom editor, or creates Pi's `CustomEditor` when none exists. It decorates `render()` only; text handling, callbacks, autocomplete, history, paste, application keybindings, image paste, and extension shortcuts remain on Pi's editor.
46
+
47
+ Pi does not currently expose public renderers for native user and assistant messages. Their side inset and submitted prompt shell therefore use guarded prototype adapters around Pi's exported components. The adapters are idempotent, restore the original renderers on shutdown, and fall back to native rendering if the runtime shape changes.
48
+
49
+ For the complete visual system, combine this package with:
50
+
51
+ - `@pi-kaush/pi-footer-minimal` for matching footer inset and footer working state; and
52
+ - `@pi-kaush/pi-tool-call-markers` for unboxed tool rows, subagent plans, and thinking markers.
53
+
54
+ ## License
55
+
56
+ MIT
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@pi-kaush/pi-content-layout",
3
+ "version": "0.1.0",
4
+ "description": "Inset Pi's conversation surface and style active and submitted prompts as matching blocks.",
5
+ "license": "MIT",
6
+ "author": "Kaushik Gopal",
7
+ "type": "module",
8
+ "exports": "./src/index.ts",
9
+ "types": "./src/index.ts",
10
+ "keywords": [
11
+ "pi-package",
12
+ "pi-extension",
13
+ "layout",
14
+ "terminal-ui"
15
+ ],
16
+ "homepage": "https://github.com/kaushikgopal/pi-kaush/tree/main/extensions/pi-content-layout#readme",
17
+ "bugs": {
18
+ "url": "https://github.com/kaushikgopal/pi-kaush/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/kaushikgopal/pi-kaush.git",
23
+ "directory": "extensions/pi-content-layout"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "CHANGELOG.md",
28
+ "LICENSE",
29
+ "README.md"
30
+ ],
31
+ "pi": {
32
+ "extensions": [
33
+ "./src/index.ts"
34
+ ]
35
+ },
36
+ "peerDependencies": {
37
+ "@earendil-works/pi-coding-agent": ">=0.80.6",
38
+ "@earendil-works/pi-tui": ">=0.80.6"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "@earendil-works/pi-coding-agent": {
42
+ "optional": true
43
+ },
44
+ "@earendil-works/pi-tui": {
45
+ "optional": true
46
+ }
47
+ },
48
+ "engines": {
49
+ "node": ">=20"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "scripts": {
55
+ "package:check": "node ./scripts/check-package.mjs"
56
+ },
57
+ "sideEffects": false
58
+ }
@@ -0,0 +1,56 @@
1
+ // Shared chat-container composition contract. pi-content-layout and
2
+ // pi-tool-call-markers each replace Container.prototype.render for different
3
+ // concerns (system-text inset vs tool grouping), and a whole-container
4
+ // wrapper always shadows whatever wrapped the prototype before it. Both
5
+ // packages instead run every registered hook before rendering and restore
6
+ // after, so child-level decoration composes in either load order. The
7
+ // registry is a globalThis set keyed by a well-known symbol: no module
8
+ // coupling, and an empty registry is a no-op when the other package is
9
+ // absent. pi-tool-call-markers carries a deliberate copy of this file
10
+ // (decision: duplicate tiny contracts over runtime dependencies).
11
+
12
+ export type ChatContainerHook = (
13
+ container: object,
14
+ children: unknown[],
15
+ width: number,
16
+ ) => (() => void) | undefined;
17
+
18
+ export const CHAT_CONTAINER_HOOKS = Symbol.for("kg.pi.chatContainerHooks.v1");
19
+
20
+ type HookRegistry = Set<ChatContainerHook>;
21
+
22
+ export function chatContainerHooks(): HookRegistry {
23
+ const root = globalThis as Record<symbol, HookRegistry | undefined>;
24
+ const existing = root[CHAT_CONTAINER_HOOKS];
25
+ if (existing) return existing;
26
+ const created: HookRegistry = new Set();
27
+ root[CHAT_CONTAINER_HOOKS] = created;
28
+ return created;
29
+ }
30
+
31
+ export function runChatContainerHooks(
32
+ container: object,
33
+ children: unknown,
34
+ width: number,
35
+ ): () => void {
36
+ const restores: Array<() => void> = [];
37
+ if (Array.isArray(children)) {
38
+ for (const hook of chatContainerHooks()) {
39
+ try {
40
+ const restore = hook(container, children, width);
41
+ if (typeof restore === "function") restores.push(restore);
42
+ } catch {
43
+ // Hooks are cosmetic; one failing hook must not break rendering.
44
+ }
45
+ }
46
+ }
47
+ return () => {
48
+ for (const restore of restores.reverse()) {
49
+ try {
50
+ restore();
51
+ } catch {
52
+ // Best-effort restore; rendering already completed.
53
+ }
54
+ }
55
+ };
56
+ }
package/src/index.ts ADDED
@@ -0,0 +1,367 @@
1
+ import {
2
+ AssistantMessageComponent,
3
+ CustomEditor,
4
+ type ExtensionAPI,
5
+ type KeybindingsManager,
6
+ type Theme,
7
+ UserMessageComponent,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import type { EditorComponent, EditorTheme, TUI } from "@earendil-works/pi-tui";
10
+ import {
11
+ chatContainerHooks,
12
+ runChatContainerHooks,
13
+ } from "./container-hooks.ts";
14
+ import {
15
+ contentInset,
16
+ insetLines,
17
+ renderActiveEditor,
18
+ renderSubmittedUserLines,
19
+ } from "./render.ts";
20
+
21
+ const ASSISTANT_RENDER_PATCH = Symbol.for(
22
+ "kg.pi.contentLayout.assistantRender.v1",
23
+ );
24
+ const USER_RENDER_PATCH = Symbol.for("kg.pi.contentLayout.userRender.v1");
25
+ const SYSTEM_CONTAINER_RENDER_PATCH = Symbol.for(
26
+ "kg.pi.contentLayout.systemContainerRender.v1",
27
+ );
28
+
29
+ type EditorFactory = (
30
+ tui: TUI,
31
+ theme: EditorTheme,
32
+ keybindings: KeybindingsManager,
33
+ ) => EditorComponent;
34
+
35
+ type ThemeGetter = () => Theme | undefined;
36
+
37
+ type RenderRow = {
38
+ render(width: number): string[];
39
+ };
40
+
41
+ type ContainerRow = RenderRow & {
42
+ children?: unknown[];
43
+ };
44
+
45
+ type NativeTextRow = RenderRow & {
46
+ text?: string;
47
+ paddingX?: number;
48
+ paddingY?: number;
49
+ customBgFn?: unknown;
50
+ };
51
+
52
+ type RenderPatchState = {
53
+ originalRender: (this: RenderRow, width: number) => string[];
54
+ patchedRender: (this: RenderRow, width: number) => string[];
55
+ owners: Map<object, ThemeGetter>;
56
+ };
57
+
58
+ type RenderDecorator = (
59
+ original: RenderPatchState["originalRender"],
60
+ row: RenderRow,
61
+ width: number,
62
+ theme: Theme,
63
+ ) => string[];
64
+
65
+ type PatchableRenderPrototype = RenderRow &
66
+ Record<symbol, RenderPatchState | undefined>;
67
+
68
+ function currentTheme(state: RenderPatchState): Theme | undefined {
69
+ return [...state.owners.values()].at(-1)?.();
70
+ }
71
+
72
+ function installRenderPatch(
73
+ prototype: PatchableRenderPrototype,
74
+ key: symbol,
75
+ owner: object,
76
+ getTheme: ThemeGetter,
77
+ decorate: RenderDecorator,
78
+ ): RenderPatchState | undefined {
79
+ try {
80
+ const existing = prototype[key];
81
+ if (existing) {
82
+ existing.owners.set(owner, getTheme);
83
+ return existing;
84
+ }
85
+ if (typeof prototype.render !== "function") return undefined;
86
+
87
+ const state = {} as RenderPatchState;
88
+ state.originalRender = prototype.render;
89
+ state.owners = new Map([[owner, getTheme]]);
90
+ state.patchedRender = function renderWithContentLayout(
91
+ this: RenderRow,
92
+ width: number,
93
+ ): string[] {
94
+ const theme = currentTheme(state);
95
+ if (!theme) return state.originalRender.call(this, width);
96
+ try {
97
+ return decorate(state.originalRender, this, width, theme);
98
+ } catch {
99
+ return state.originalRender.call(this, width);
100
+ }
101
+ };
102
+
103
+ prototype.render = state.patchedRender;
104
+ Object.defineProperty(prototype, key, {
105
+ configurable: true,
106
+ value: state,
107
+ });
108
+ return state;
109
+ } catch {
110
+ return undefined;
111
+ }
112
+ }
113
+
114
+ function uninstallRenderPatch(
115
+ prototype: PatchableRenderPrototype,
116
+ key: symbol,
117
+ owner: object,
118
+ state: RenderPatchState | undefined,
119
+ ): void {
120
+ if (!state || prototype[key] !== state) return;
121
+ state.owners.delete(owner);
122
+ if (state.owners.size > 0) return;
123
+
124
+ if (prototype.render === state.patchedRender) {
125
+ prototype.render = state.originalRender;
126
+ }
127
+ delete prototype[key];
128
+ }
129
+
130
+ function assistantDecorator(
131
+ original: RenderPatchState["originalRender"],
132
+ row: RenderRow,
133
+ width: number,
134
+ ): string[] {
135
+ const nativeInset = Math.max(
136
+ 0,
137
+ Number((row as RenderRow & { outputPad?: number }).outputPad) || 0,
138
+ );
139
+ const inset = Math.max(0, contentInset(width) - nativeInset);
140
+ if (inset === 0) return original.call(row, width);
141
+ const lines = original.call(row, Math.max(1, width - inset * 2));
142
+ return insetLines(lines, width, inset);
143
+ }
144
+
145
+ function isChatMessageChild(child: unknown): boolean {
146
+ return (
147
+ child instanceof AssistantMessageComponent ||
148
+ child instanceof UserMessageComponent
149
+ );
150
+ }
151
+
152
+ function isSystemTextChild(child: unknown): child is NativeTextRow {
153
+ if (!child || typeof (child as NativeTextRow).render !== "function")
154
+ return false;
155
+ const text = child as NativeTextRow & { constructor?: { name?: string } };
156
+ return (
157
+ text.constructor?.name === "Text" &&
158
+ typeof text.text === "string" &&
159
+ text.paddingX === 1 &&
160
+ text.paddingY === 0 &&
161
+ text.customBgFn === undefined
162
+ );
163
+ }
164
+
165
+ const knownChatContainers = new WeakSet<object>();
166
+
167
+ let systemTextHookActive = 0;
168
+
169
+ // The system-text inset decorates matching Text instances in place instead of
170
+ // intercepting the container's child list. Other whole-container wrappers
171
+ // (pi-tool-call-markers' grouping) run the shared hooks without delegating to
172
+ // this package's wrapper, and instance-level decoration is the only shape
173
+ // that composes in both load orders.
174
+ function systemTextHook(
175
+ container: object,
176
+ children: unknown[],
177
+ width: number,
178
+ ): (() => void) | undefined {
179
+ if (systemTextHookActive > 0) {
180
+ // A nested wrapper invoked the hooks for the same render pass; the
181
+ // outermost call already decorated these children.
182
+ systemTextHookActive += 1;
183
+ return () => {
184
+ systemTextHookActive -= 1;
185
+ };
186
+ }
187
+ if (children.some(isChatMessageChild)) knownChatContainers.add(container);
188
+ if (!knownChatContainers.has(container)) return undefined;
189
+
190
+ const targetInset = contentInset(width);
191
+ const restores: Array<() => void> = [];
192
+ for (const child of children) {
193
+ if (!isSystemTextChild(child)) continue;
194
+ const extraInset = Math.max(0, targetInset - (child.paddingX ?? 0));
195
+ if (extraInset === 0) continue;
196
+ const originalRender = child.render;
197
+ child.render = (childWidth: number): string[] =>
198
+ insetLines(
199
+ originalRender.call(child, Math.max(1, childWidth - extraInset * 2)),
200
+ childWidth,
201
+ extraInset,
202
+ );
203
+ restores.push(() => {
204
+ delete (child as Partial<NativeTextRow>).render;
205
+ });
206
+ }
207
+ if (restores.length === 0) return undefined;
208
+ systemTextHookActive = 1;
209
+ return () => {
210
+ systemTextHookActive = 0;
211
+ for (const restore of restores.reverse()) restore();
212
+ };
213
+ }
214
+
215
+ function systemContainerDecorator(
216
+ original: RenderPatchState["originalRender"],
217
+ row: RenderRow,
218
+ width: number,
219
+ ): string[] {
220
+ const restore = runChatContainerHooks(
221
+ row,
222
+ (row as ContainerRow).children,
223
+ width,
224
+ );
225
+ try {
226
+ return original.call(row, width);
227
+ } finally {
228
+ restore();
229
+ }
230
+ }
231
+
232
+ function userDecorator(
233
+ original: RenderPatchState["originalRender"],
234
+ row: RenderRow,
235
+ width: number,
236
+ theme: Theme,
237
+ ): string[] {
238
+ const inset = contentInset(width);
239
+ const bodyWidth = width - inset * 2 - 1;
240
+ if (inset === 0 || bodyWidth < 1) return original.call(row, width);
241
+ const lines = original.call(row, bodyWidth);
242
+ return renderSubmittedUserLines(lines, width, theme, inset);
243
+ }
244
+
245
+ function decorateEditor(
246
+ editor: EditorComponent,
247
+ getTheme: ThemeGetter,
248
+ ): EditorComponent {
249
+ const target = editor as EditorComponent & {
250
+ borderColor?: (text: string) => string;
251
+ };
252
+
253
+ return new Proxy(target, {
254
+ get(component, property) {
255
+ if (property === "render") {
256
+ return (width: number) => {
257
+ const theme = getTheme();
258
+ return theme
259
+ ? renderActiveEditor(component, width, theme)
260
+ : component.render(width);
261
+ };
262
+ }
263
+ const value = Reflect.get(component, property, component) as unknown;
264
+ return typeof value === "function" ? value.bind(component) : value;
265
+ },
266
+ set(component, property, value) {
267
+ return Reflect.set(component, property, value, component);
268
+ },
269
+ });
270
+ }
271
+
272
+ export default function contentLayout(pi: ExtensionAPI): void {
273
+ const owner = {};
274
+ let activeTheme: Theme | undefined;
275
+ let assistantPatch: RenderPatchState | undefined;
276
+ let userPatch: RenderPatchState | undefined;
277
+ let systemContainerPatch: RenderPatchState | undefined;
278
+ let editorRegistration:
279
+ | {
280
+ factory: EditorFactory;
281
+ previous: EditorFactory | undefined;
282
+ }
283
+ | undefined;
284
+
285
+ const getTheme = () => activeTheme;
286
+
287
+ pi.on("session_start", (_event, ctx) => {
288
+ if (ctx.mode !== "tui") return;
289
+ activeTheme = ctx.ui.theme;
290
+
291
+ const assistantPrototype =
292
+ AssistantMessageComponent.prototype as unknown as PatchableRenderPrototype;
293
+ const userPrototype =
294
+ UserMessageComponent.prototype as unknown as PatchableRenderPrototype;
295
+ assistantPatch = installRenderPatch(
296
+ assistantPrototype,
297
+ ASSISTANT_RENDER_PATCH,
298
+ owner,
299
+ getTheme,
300
+ assistantDecorator,
301
+ );
302
+ userPatch = installRenderPatch(
303
+ userPrototype,
304
+ USER_RENDER_PATCH,
305
+ owner,
306
+ getTheme,
307
+ userDecorator,
308
+ );
309
+ const hostContainerPrototype = Object.getPrototypeOf(
310
+ AssistantMessageComponent.prototype,
311
+ ) as PatchableRenderPrototype;
312
+ chatContainerHooks().add(systemTextHook);
313
+ systemContainerPatch = installRenderPatch(
314
+ hostContainerPrototype,
315
+ SYSTEM_CONTAINER_RENDER_PATCH,
316
+ owner,
317
+ getTheme,
318
+ systemContainerDecorator,
319
+ );
320
+
321
+ const previous = ctx.ui.getEditorComponent() as EditorFactory | undefined;
322
+ const factory: EditorFactory = (tui, editorTheme, keybindings) => {
323
+ const editor = previous
324
+ ? previous(tui, editorTheme, keybindings)
325
+ : new CustomEditor(tui, editorTheme, keybindings);
326
+ return decorateEditor(editor, getTheme);
327
+ };
328
+ editorRegistration = { factory, previous };
329
+ ctx.ui.setEditorComponent(factory);
330
+ });
331
+
332
+ pi.on("session_shutdown", (_event, ctx) => {
333
+ chatContainerHooks().delete(systemTextHook);
334
+ if (
335
+ editorRegistration &&
336
+ ctx.ui.getEditorComponent() === editorRegistration.factory
337
+ ) {
338
+ ctx.ui.setEditorComponent(editorRegistration.previous);
339
+ }
340
+ editorRegistration = undefined;
341
+
342
+ uninstallRenderPatch(
343
+ AssistantMessageComponent.prototype as unknown as PatchableRenderPrototype,
344
+ ASSISTANT_RENDER_PATCH,
345
+ owner,
346
+ assistantPatch,
347
+ );
348
+ uninstallRenderPatch(
349
+ UserMessageComponent.prototype as unknown as PatchableRenderPrototype,
350
+ USER_RENDER_PATCH,
351
+ owner,
352
+ userPatch,
353
+ );
354
+ uninstallRenderPatch(
355
+ Object.getPrototypeOf(
356
+ AssistantMessageComponent.prototype,
357
+ ) as PatchableRenderPrototype,
358
+ SYSTEM_CONTAINER_RENDER_PATCH,
359
+ owner,
360
+ systemContainerPatch,
361
+ );
362
+ assistantPatch = undefined;
363
+ userPatch = undefined;
364
+ systemContainerPatch = undefined;
365
+ activeTheme = undefined;
366
+ });
367
+ }
package/src/render.ts ADDED
@@ -0,0 +1,220 @@
1
+ import type { Theme } from "@earendil-works/pi-coding-agent";
2
+ import type { EditorComponent } from "@earendil-works/pi-tui";
3
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
+
5
+ export const OUTER_INSET = 2;
6
+ export const PROMPT_RAIL = "▎";
7
+ export const ACTIVE_SIDE_PADDING = 1;
8
+
9
+ // The prompt surface (active editor block and submitted message body) uses a
10
+ // fixed near-black green tint instead of the theme's selectedBg token so both
11
+ // user-input surfaces stay identical; the theme token remains for selections
12
+ // and dialogs.
13
+ export const PROMPT_SURFACE_BG = "\x1b[48;2;7;19;18m"; // #071312
14
+
15
+ const BORDER_SENTINEL = "\x1b]133;P;pi-content-layout\x07";
16
+ const SGR_PATTERN = /\x1b\[([0-9;]*)m/g;
17
+ const BACKGROUND_PATTERN =
18
+ /\x1b\[(?:4[0-8]|10[0-7]|48;5;\d{1,3}|48;2;\d{1,3};\d{1,3};\d{1,3})m/g;
19
+ const DISPLAY_ANSI_PATTERN = /\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;
20
+
21
+ type BorderEditor = EditorComponent & {
22
+ borderColor?: (text: string) => string;
23
+ };
24
+
25
+ export function contentInset(width: number): number {
26
+ return width > OUTER_INSET * 2 ? OUTER_INSET : 0;
27
+ }
28
+
29
+ function semanticControlEnd(text: string, offset: number): number | undefined {
30
+ if (text[offset] !== "\x1b") return undefined;
31
+ const kind = text[offset + 1];
32
+ if (kind !== "]" && kind !== "_" && kind !== "P" && kind !== "^") {
33
+ return undefined;
34
+ }
35
+
36
+ for (let index = offset + 2; index < text.length; index++) {
37
+ if (text[index] === "\x07") return index + 1;
38
+ if (text[index] === "\x1b" && text[index + 1] === "\\") {
39
+ return index + 2;
40
+ }
41
+ }
42
+ return undefined;
43
+ }
44
+
45
+ export function splitLeadingSemanticControls(line: string): {
46
+ controls: string;
47
+ content: string;
48
+ } {
49
+ let offset = 0;
50
+ while (offset < line.length) {
51
+ const end = semanticControlEnd(line, offset);
52
+ if (end === undefined) break;
53
+ offset = end;
54
+ }
55
+ return { controls: line.slice(0, offset), content: line.slice(offset) };
56
+ }
57
+
58
+ export function fitLine(line: string, width: number): string {
59
+ if (width <= 0) return "";
60
+ const clipped = truncateToWidth(line, width, "");
61
+ return clipped + " ".repeat(Math.max(0, width - visibleWidth(clipped)));
62
+ }
63
+
64
+ export function insetLines(
65
+ lines: string[],
66
+ width: number,
67
+ inset = contentInset(width),
68
+ ): string[] {
69
+ if (inset === 0) return lines.map((line) => fitLine(line, width));
70
+ const contentWidth = Math.max(1, width - inset * 2);
71
+ const margin = " ".repeat(inset);
72
+ return lines.map((line) => {
73
+ const { controls, content } = splitLeadingSemanticControls(line);
74
+ return `${controls}${margin}${fitLine(content, contentWidth)}${margin}`;
75
+ });
76
+ }
77
+
78
+ function reapplyBackgroundAfterReset(
79
+ text: string,
80
+ backgroundAnsi: string,
81
+ ): string {
82
+ return text.replace(SGR_PATTERN, (sequence, rawParameters: string) => {
83
+ const parameters =
84
+ rawParameters === "" ? [0] : rawParameters.split(";").map(Number);
85
+ return parameters.includes(0) || parameters.includes(49)
86
+ ? `${sequence}${backgroundAnsi}`
87
+ : sequence;
88
+ });
89
+ }
90
+
91
+ export function paintBackground(
92
+ line: string,
93
+ width: number,
94
+ backgroundAnsi: string,
95
+ ): string {
96
+ const fitted = fitLine(line, width);
97
+ // Mirrors Theme.bg: background, content, then a background-only reset.
98
+ return `${backgroundAnsi}${reapplyBackgroundAfterReset(fitted, backgroundAnsi)}\x1b[49m`;
99
+ }
100
+
101
+ function stripDisplayAnsi(text: string): string {
102
+ return text.replace(DISPLAY_ANSI_PATTERN, "");
103
+ }
104
+
105
+ function scrollHint(line: string): string | undefined {
106
+ return stripDisplayAnsi(line).match(/[↑↓] \d+ more/)?.[0];
107
+ }
108
+
109
+ function activeBlockLine(
110
+ line: string,
111
+ isBoundary: boolean,
112
+ width: number,
113
+ theme: Theme,
114
+ ): string {
115
+ const hint = isBoundary ? scrollHint(line) : undefined;
116
+ const body = hint ? theme.fg("muted", ` ${hint}`) : isBoundary ? "" : line;
117
+ const innerWidth = Math.max(0, width - ACTIVE_SIDE_PADDING * 2);
118
+ const padding = " ".repeat(ACTIVE_SIDE_PADDING);
119
+ return paintBackground(
120
+ `${padding}${fitLine(body, innerWidth)}${padding}`,
121
+ width,
122
+ PROMPT_SURFACE_BG,
123
+ );
124
+ }
125
+
126
+ function markEditorBoundaries(editor: BorderEditor): () => void {
127
+ const original = editor.borderColor;
128
+ if (typeof original !== "function") return () => {};
129
+ editor.borderColor = (text: string) =>
130
+ `${BORDER_SENTINEL}${original(text)}${BORDER_SENTINEL}`;
131
+ return () => {
132
+ editor.borderColor = original;
133
+ };
134
+ }
135
+
136
+ export function renderActiveEditor(
137
+ editor: BorderEditor,
138
+ width: number,
139
+ theme: Theme,
140
+ ): string[] {
141
+ const editorWidth = width - ACTIVE_SIDE_PADDING * 2;
142
+ if (editorWidth < 1 || typeof editor.borderColor !== "function") {
143
+ return editor.render(width);
144
+ }
145
+
146
+ const restoreBorder = markEditorBoundaries(editor);
147
+ let markedLines: string[];
148
+ try {
149
+ markedLines = editor.render(editorWidth);
150
+ } finally {
151
+ restoreBorder();
152
+ }
153
+
154
+ try {
155
+ const boundaries = markedLines
156
+ .map((line, index) => (line.includes(BORDER_SENTINEL) ? index : -1))
157
+ .filter((index) => index >= 0);
158
+ if (boundaries.length !== 2 || boundaries[0] !== 0) {
159
+ return editor.render(width);
160
+ }
161
+
162
+ const bottomBoundary = boundaries[1];
163
+ if (bottomBoundary === undefined || bottomBoundary <= 0) {
164
+ return editor.render(width);
165
+ }
166
+
167
+ const cleanLines = markedLines.map((line) =>
168
+ line.split(BORDER_SENTINEL).join(""),
169
+ );
170
+ const block = cleanLines
171
+ .slice(0, bottomBoundary + 1)
172
+ .map((line, index) =>
173
+ activeBlockLine(
174
+ line,
175
+ index === 0 || index === bottomBoundary,
176
+ width,
177
+ theme,
178
+ ),
179
+ );
180
+ const suggestions = cleanLines
181
+ .slice(bottomBoundary + 1)
182
+ .map((line) => fitLine(line, width));
183
+
184
+ return [...block, ...suggestions];
185
+ } catch {
186
+ return editor.render(width);
187
+ }
188
+ }
189
+
190
+ function replaceBackground(text: string, backgroundAnsi: string): string {
191
+ return text.replace(BACKGROUND_PATTERN, backgroundAnsi);
192
+ }
193
+
194
+ export function renderSubmittedUserLines(
195
+ lines: string[],
196
+ width: number,
197
+ theme: Theme,
198
+ inset = contentInset(width),
199
+ ): string[] {
200
+ const blockWidth = width - inset * 2;
201
+ if (inset === 0 || blockWidth <= visibleWidth(PROMPT_RAIL)) {
202
+ return lines.map((line) => fitLine(line, width));
203
+ }
204
+
205
+ const bodyWidth = blockWidth - visibleWidth(PROMPT_RAIL);
206
+ const margin = " ".repeat(inset);
207
+ return lines.map((line) => {
208
+ const { controls, content } = splitLeadingSemanticControls(line);
209
+ const recolored = replaceBackground(content, PROMPT_SURFACE_BG);
210
+ const rail = theme.fg("accent", PROMPT_RAIL);
211
+ // One extra leading space inside the body, so submitted text sits two
212
+ // columns right of the rail instead of one.
213
+ const body = paintBackground(
214
+ ` ${fitLine(recolored, Math.max(1, bodyWidth - 1))}`,
215
+ bodyWidth,
216
+ PROMPT_SURFACE_BG,
217
+ );
218
+ return `${controls}${margin}${rail}${body}${margin}`;
219
+ });
220
+ }