fix(tui): keep kitty image redraws inside TUI

Fixes #4208.
This commit is contained in:
Armin Ronacher
2026-05-07 10:34:37 +02:00
parent 50993d743d
commit b8712457d2
5 changed files with 273 additions and 19 deletions

View File

@@ -1,4 +1,5 @@
import {
allocateImageId,
getCapabilities,
getImageDimensions,
type ImageDimensions,
@@ -26,6 +27,7 @@ export class Image implements Component {
private theme: ImageTheme;
private options: ImageOptions;
private imageId?: number;
private readonly explicitImageId?: number;
private cachedLines?: string[];
private cachedWidth?: number;
@@ -42,12 +44,13 @@ export class Image implements Component {
this.theme = theme;
this.options = options;
this.dimensions = dimensions || getImageDimensions(base64Data, mimeType) || { widthPx: 800, heightPx: 600 };
this.explicitImageId = options.imageId;
this.imageId = options.imageId;
}
/** Get the Kitty image ID used by this image (if any). */
/** Get the explicit Kitty image ID configured for this image (if any). */
getImageId(): number | undefined {
return this.imageId;
return this.explicitImageId;
}
invalidate(): void {
@@ -66,9 +69,13 @@ export class Image implements Component {
let lines: string[];
if (caps.images) {
if (caps.images === "kitty" && this.imageId === undefined) {
this.imageId = allocateImageId();
}
const result = renderImage(this.base64Data, this.dimensions, {
maxWidthCells: maxWidth,
imageId: this.imageId,
moveCursor: false,
});
if (result) {
@@ -77,16 +84,19 @@ export class Image implements Component {
this.imageId = result.imageId;
}
// Return `rows` lines so TUI accounts for image height
// First (rows-1) lines are empty (TUI clears them)
// Last line: move cursor back up, then output image sequence
// Return `rows` lines so TUI accounts for image height.
// First (rows-1) lines are empty and cleared before the image is drawn.
// Last line: move cursor back up, draw the image, then move back down
// for Kitty (this component disables Kitty's terminal-side cursor movement)
// so TUI cursor accounting stays inside the scroll area.
lines = [];
for (let i = 0; i < result.rows - 1; i++) {
lines.push("");
}
// Move cursor up to first row, then output image
const moveUp = result.rows > 1 ? `\x1b[${result.rows - 1}A` : "";
lines.push(moveUp + result.sequence);
const rowOffset = result.rows - 1;
const moveUp = rowOffset > 0 ? `\x1b[${rowOffset}A` : "";
const moveDown = caps.images === "kitty" && rowOffset > 0 ? `\x1b[${rowOffset}B` : "";
lines.push(moveUp + result.sequence + moveDown);
} else {
const fallback = imageFallback(this.mimeType, this.dimensions, this.options.filename);
lines = [this.theme.fallbackColor(fallback)];