Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 53 additions & 12 deletions src/ink.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import process from 'node:process';
import React, {type ReactNode} from 'react';
import {throttle} from 'es-toolkit/compat';
import {throttle, type DebouncedFunc} from 'es-toolkit/compat';
import ansiEscapes from 'ansi-escapes';
import isInCi from 'is-in-ci';
import autoBind from 'auto-bind';
Expand Down Expand Up @@ -68,7 +68,7 @@ export default class Ink {

private readonly options: Options;
private readonly log: LogUpdate;
private readonly throttledLog: LogUpdate;
private readonly throttledLog: LogUpdate | DebouncedFunc<LogUpdate>;
private readonly isScreenReaderEnabled: boolean;

// Ignore last render after unmounting a tree to prevent empty output before exit
Expand All @@ -84,6 +84,8 @@ export default class Ink {
private exitPromise?: Promise<void>;
private restoreConsole?: () => void;
private readonly unsubscribeResize?: () => void;
// Store reference to throttled onRender for flushing
private readonly throttledOnRender?: DebouncedFunc<() => void>;

constructor(options: Options) {
autoBind(this);
Expand All @@ -101,12 +103,17 @@ export default class Ink {
const renderThrottleMs =
maxFps > 0 ? Math.max(1, Math.ceil(1000 / maxFps)) : 0;

this.rootNode.onRender = unthrottled
? this.onRender
: throttle(this.onRender, renderThrottleMs, {
leading: true,
trailing: true,
});
if (unthrottled) {
this.rootNode.onRender = this.onRender;
this.throttledOnRender = undefined;
} else {
const throttled = throttle(this.onRender, renderThrottleMs, {
leading: true,
trailing: true,
});
this.rootNode.onRender = throttled;
this.throttledOnRender = throttled;
}

this.rootNode.onImmediateRender = this.onRender;
this.log = logUpdate.create(options.stdout, {
Expand All @@ -117,7 +124,7 @@ export default class Ink {
: (throttle(this.log, undefined, {
leading: true,
trailing: true,
}) as unknown as LogUpdate);
}) as unknown as DebouncedFunc<LogUpdate>);

// Ignore last render after unmounting a tree to prevent empty output before exit
this.isUnmounted = false;
Expand Down Expand Up @@ -399,6 +406,11 @@ export default class Ink {
return;
}

// Flush any pending throttled render to ensure the final frame is rendered
if (this.throttledOnRender) {
this.throttledOnRender.flush();
}

this.calculateLayout();
this.onRender();
this.unsubscribeExit();
Expand All @@ -411,6 +423,12 @@ export default class Ink {
this.unsubscribeResize();
}

// Flush any pending throttled log writes
const throttledLog = this.throttledLog as DebouncedFunc<LogUpdate>;
if (typeof throttledLog.flush === 'function') {
throttledLog.flush();
}

// CIs don't handle erasing ansi escapes well, so it's better to
// only render last frame of non-static output
if (isInCi) {
Expand All @@ -432,10 +450,33 @@ export default class Ink {

instances.delete(this.options.stdout);

if (error instanceof Error) {
this.rejectExitPromise(error);
// Ensure all queued writes have been processed before resolving the
// exit promise. For real writable streams, queue an empty write as a
// barrier — its callback fires only after all prior writes complete.
// For non-stream objects (e.g. test spies), resolve on next tick.
//
// When called from signal-exit during process shutdown (error is a
// number or null rather than undefined/Error), resolve synchronously
// because the event loop is draining and async callbacks won't fire.
const resolveOrReject = () => {
if (error instanceof Error) {
this.rejectExitPromise(error);
} else {
this.resolveExitPromise();
}
};

const isProcessExiting = error !== undefined && !(error instanceof Error);

if (isProcessExiting) {
resolveOrReject();
} else if (
(this.options.stdout as any)._writableState !== undefined ||
this.options.stdout.writableLength !== undefined
) {
this.options.stdout.write('', resolveOrReject);
} else {
this.resolveExitPromise();
setImmediate(resolveOrReject);
}
}

Expand Down
60 changes: 60 additions & 0 deletions test/render.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import EventEmitter from 'node:events';
import process from 'node:process';
import {Writable} from 'node:stream';
import url from 'node:url';
import * as path from 'node:path';
import {createRequire} from 'node:module';
Expand Down Expand Up @@ -402,3 +403,62 @@ test.serial('no throttled renders after unmount', t => {
clock.uninstall();
}
});

test.serial('unmount forces pending throttled render', t => {
const clock = FakeTimers.install();
try {
const stdout = createStdout();

const {unmount, rerender} = render(<ThrottleTestComponent text="Hello" />, {
stdout,
maxFps: 1, // 1 Hz => ~1000 ms throttle window
});

// Initial render (leading call)
t.is((stdout.write as any).callCount, 1);
t.is(
stripAnsi((stdout.write as any).lastCall.args[0] as string),
'Hello\n',
);

// Trigger another render inside the throttle window
rerender(<ThrottleTestComponent text="Final" />);
// Not rendered yet due to throttling
t.is((stdout.write as any).callCount, 1);

// Unmount should flush the pending render so the final frame is visible
unmount();

// The final frame should have been rendered
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call
const allCalls: string[] = (stdout.write as any).args.map(
(args: string[]) => stripAnsi(args[0]!),
);
t.true(allCalls.some((call: string) => call.includes('Final')));
} finally {
clock.uninstall();
}
});

test.serial('waitUntilExit resolves after stdout write callback', async t => {
let writeCallbackFired = false;

const stdout = new Writable({
write(_chunk, _encoding, callback) {
setTimeout(() => {
writeCallbackFired = true;
callback();
}, 150);
},
}) as unknown as NodeJS.WriteStream;

stdout.columns = 100;

const {unmount, waitUntilExit} = render(<Text>Hello</Text>, {stdout});
const exitPromise = waitUntilExit();

unmount();
await exitPromise;

t.true(writeCallbackFired);
});