Skip to content

Commit c77ff7d

Browse files
authored
fix(shortcuts): keep key shortcuts working in Vite HMR sessions (#6214)
- The Vite dev server gets no stdin while the CLI's own shortcuts read the terminal, so Vite's readline no longer takes keys meant for the CLI. Otherwise it inherits stdin as before and Vite's own shortcuts keep working. - After each shortcut action the terminal is put back into raw mode: a Node child writing to the terminal (such as the dev server R or w stops) restores the mode it started with when it exits, which left keys waiting for Enter.
1 parent 8a55b3e commit c77ff7d

4 files changed

Lines changed: 232 additions & 6 deletions

File tree

‎lib/services/bundler/bundler-compiler-service.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
resolvePackagePath,
4040
resolvePackageJSONPath,
4141
} from "../../helpers/package-path-helper";
42+
import { commandShortcutsOwnTerminal } from "../key-shortcuts";
4243

4344
// todo: move out of here
4445
interface IBundlerMessage<T = any> {
@@ -736,10 +737,17 @@ export class BundlerCompilerService
736737

737738
const options: { [key: string]: any } = {
738739
cwd: projectData.projectDir,
739-
// Inherit so the dev server's URLs/logs stream to the user as
740-
// before. No IPC needed here — the build watcher provides the
740+
// Output is inherited so the dev server's URLs/logs stream to the
741+
// user. No IPC needed here — the build watcher provides the
741742
// bundle-complete IPC; the dev server is fetched over HTTP/ws.
742-
stdio: "inherit",
743+
// Vite reads a terminal stdin for shortcuts of its own, which would
744+
// take the keys meant for the CLI's; otherwise its shortcuts are the
745+
// only ones the terminal has.
746+
stdio: [
747+
commandShortcutsOwnTerminal() ? "ignore" : "inherit",
748+
"inherit",
749+
"inherit",
750+
],
743751
env: {
744752
...process.env,
745753
NATIVESCRIPT_BUNDLER_ENV: JSON.stringify(envData),

‎lib/services/key-shortcuts.ts‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { RunOnDeviceEvents } from "../constants";
55
import { IChildProcess } from "../common/declarations";
66
import { Injector } from "../common/di/injector";
77
import {
8+
commandShortcutsEnabled,
89
envSwitchIsOn,
910
IKeyShortcutService,
1011
KeyContextBase,
@@ -98,6 +99,16 @@ export function findShortcut<TContext extends KeyContextBase>(
9899
return shortcut;
99100
}
100101

102+
/**
103+
* Node skips `setRawMode(true)` while it believes the terminal is already
104+
* raw, so the mode is cleared first to make the call reach the terminal even
105+
* when something else has changed it since.
106+
*/
107+
function enterRawMode(stdin: NodeJS.ReadStream): void {
108+
stdin.setRawMode(false);
109+
stdin.setRawMode(true);
110+
}
111+
101112
/**
102113
* Raw mode outlives the process that set it, so a CI runner or a redirected
103114
* stdin must never get it; `NS_KEY_SHORTCUTS=false` is the manual opt-out.
@@ -115,6 +126,23 @@ export function keyShortcutsEnabled(): boolean {
115126
return !!process.stdin.isTTY;
116127
}
117128

129+
function isRawModeTerminal(stdin: NodeJS.ReadStream): boolean {
130+
return !!stdin.isTTY && typeof stdin.setRawMode === "function";
131+
}
132+
133+
/**
134+
* Whether a command's shortcuts, once attached, read the keys straight off
135+
* the terminal. Answerable before the attach, so a child spawned earlier can
136+
* be kept off a terminal the CLI is about to read.
137+
*/
138+
export function commandShortcutsOwnTerminal(): boolean {
139+
return (
140+
commandShortcutsEnabled() &&
141+
isRawModeTerminal(process.stdin) &&
142+
keyShortcutsEnabled()
143+
);
144+
}
145+
118146
/**
119147
* The names `devicePlatformsConstants` hands out, read off the constants
120148
* rather than spelled again here.
@@ -410,7 +438,7 @@ export class KeyShortcutService implements IKeyShortcutService {
410438
);
411439

412440
const stdin = process.stdin;
413-
if (!stdin.isTTY || typeof stdin.setRawMode !== "function") {
441+
if (!isRawModeTerminal(stdin)) {
414442
if (typeof process.send !== "function") {
415443
this.releaseShortcuts();
416444
return false;
@@ -428,8 +456,7 @@ export class KeyShortcutService implements IKeyShortcutService {
428456
return false;
429457
}
430458

431-
stdin.setRawMode(false);
432-
stdin.setRawMode(true);
459+
enterRawMode(stdin);
433460
stdin.resume();
434461
stdin.on("data", this.onData);
435462
process.once("exit", this.onExit);
@@ -592,6 +619,12 @@ export class KeyShortcutService implements IKeyShortcutService {
592619
} finally {
593620
this.running = false;
594621
if (process.stdin.setRawMode) {
622+
// A Node child writing to the terminal, such as the Vite dev server
623+
// an action stops, restores the terminal mode it started with when
624+
// it exits; that can be cooked mode, where keys wait for Enter.
625+
if (this.attached && process.stdin.isTTY) {
626+
enterRawMode(process.stdin);
627+
}
595628
process.stdin.resume();
596629
}
597630
}

‎test/services/bundler/bundler-compiler-service.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,92 @@ describe("BundlerCompilerService", () => {
373373
});
374374
});
375375

376+
describe("startViteDevServer", () => {
377+
const env = ["NS_COMMAND_SHORTCUTS", "NS_KEY_SHORTCUTS"];
378+
let savedEnv: { [key: string]: string };
379+
let originalStdin: PropertyDescriptor;
380+
let spawned: { [key: string]: any }[];
381+
382+
const useStdin = (isTTY: boolean): void => {
383+
Object.defineProperty(process, "stdin", {
384+
value: { isTTY, setRawMode: (): void => undefined },
385+
configurable: true,
386+
});
387+
};
388+
389+
const devServerStdin = async (): Promise<string> => {
390+
await (<any>bundlerCompilerService).startViteDevServer(
391+
{ platformNameLowerCase: "ios" },
392+
{
393+
projectDir: "/project",
394+
bundlerConfigPath: "/project/vite.config.ts",
395+
},
396+
{ watch: true, hmr: true },
397+
);
398+
assert.lengthOf(spawned, 1);
399+
400+
return spawned[0].stdio[0];
401+
};
402+
403+
beforeEach(() => {
404+
savedEnv = {};
405+
for (const name of env) {
406+
savedEnv[name] = process.env[name];
407+
delete process.env[name];
408+
}
409+
originalStdin = Object.getOwnPropertyDescriptor(process, "stdin");
410+
411+
spawned = [];
412+
testInjector.resolve("childProcess").spawn = (
413+
_command: string,
414+
_args: string[],
415+
options: { [key: string]: any },
416+
) => {
417+
spawned.push(options);
418+
return fakeChildProcess(321);
419+
};
420+
const service = <any>bundlerCompilerService;
421+
service.getBundler = () => "vite";
422+
service.buildEnvData = () => ({});
423+
service.buildEnvCommandLineParams = async (): Promise<string[]> => [];
424+
service.getBundlerExecutablePath = () => "/project/vite.js";
425+
service.waitForPort = async () => true;
426+
});
427+
428+
afterEach(() => {
429+
Object.defineProperty(process, "stdin", originalStdin);
430+
for (const name of env) {
431+
if (savedEnv[name] === undefined) {
432+
delete process.env[name];
433+
} else {
434+
process.env[name] = savedEnv[name];
435+
}
436+
}
437+
});
438+
439+
it("keeps the dev server off the terminal the CLI's shortcuts read", async () => {
440+
process.env.NS_COMMAND_SHORTCUTS = "1";
441+
process.env.NS_KEY_SHORTCUTS = "true";
442+
useStdin(true);
443+
444+
assert.equal(await devServerStdin(), "ignore");
445+
});
446+
447+
it("hands the dev server the terminal while the CLI's shortcuts are off", async () => {
448+
useStdin(true);
449+
450+
assert.equal(await devServerStdin(), "inherit");
451+
});
452+
453+
it("hands the dev server its stdin when the CLI has no terminal to read", async () => {
454+
process.env.NS_COMMAND_SHORTCUTS = "1";
455+
process.env.NS_KEY_SHORTCUTS = "true";
456+
useStdin(false);
457+
458+
assert.equal(await devServerStdin(), "inherit");
459+
});
460+
});
461+
376462
describe("compileWithWatch", () => {
377463
it("fails when the value set for bundlerConfigPath is not existant file", async () => {
378464
const bundlerConfigPath = "some path.js";

‎test/services/key-shortcuts.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { getContractName } from "../../lib/common/di/contract";
55
import { Injector } from "../../lib/common/di/injector";
66
import { KeyShortcutRegistryService } from "../../lib/services/key-shortcut-registry";
77
import {
8+
commandShortcutsOwnTerminal,
89
findShortcut,
910
KeyContextBase,
1011
KeyShortcut,
@@ -19,10 +20,16 @@ import {
1920
class FakeStdin extends EventEmitter {
2021
public isTTY: boolean = true;
2122
public rawMode: boolean = null;
23+
/** The mode the terminal is really in, which another process can change. */
24+
public terminalRaw: boolean = false;
2225
public resumeCount: number = 0;
2326
public pauseCount: number = 0;
2427

2528
public setRawMode(value: boolean): any {
29+
// Like Node, only a change from the mode it last set reaches the terminal.
30+
if (value !== this.rawMode) {
31+
this.terminalRaw = value;
32+
}
2633
this.rawMode = value;
2734
return this;
2835
}
@@ -467,6 +474,61 @@ describe("key shortcuts", () => {
467474
});
468475
});
469476

477+
describe("commandShortcutsOwnTerminal", () => {
478+
const env = [
479+
"NS_COMMAND_SHORTCUTS",
480+
"NS_KEY_SHORTCUTS",
481+
"CI",
482+
"JENKINS_HOME",
483+
];
484+
let saved: { [key: string]: string };
485+
let stdin: FakeStdin;
486+
let restoreStdin: () => void;
487+
488+
beforeEach(() => {
489+
saved = {};
490+
for (const name of env) {
491+
saved[name] = process.env[name];
492+
delete process.env[name];
493+
}
494+
process.env.NS_COMMAND_SHORTCUTS = "1";
495+
stdin = new FakeStdin();
496+
restoreStdin = swapStdin(stdin);
497+
});
498+
499+
afterEach(() => {
500+
restoreStdin();
501+
for (const name of env) {
502+
if (saved[name] === undefined) {
503+
delete process.env[name];
504+
} else {
505+
process.env[name] = saved[name];
506+
}
507+
}
508+
});
509+
510+
it("holds for a command's shortcuts on a terminal", () => {
511+
assert.isTrue(commandShortcutsOwnTerminal());
512+
});
513+
514+
it("does not hold while command shortcuts are off", () => {
515+
delete process.env.NS_COMMAND_SHORTCUTS;
516+
assert.isFalse(commandShortcutsOwnTerminal());
517+
});
518+
519+
it("does not hold when key shortcuts are switched off", () => {
520+
process.env.NS_KEY_SHORTCUTS = "false";
521+
assert.isFalse(commandShortcutsOwnTerminal());
522+
});
523+
524+
it("does not hold for a stdin that is not a terminal, even when forced on", () => {
525+
// A `ns run` spawned by `ns start`: its keys come over IPC.
526+
process.env.NS_KEY_SHORTCUTS = "true";
527+
stdin.isTTY = false;
528+
assert.isFalse(commandShortcutsOwnTerminal());
529+
});
530+
});
531+
470532
describe("KeyShortcutService", () => {
471533
let stdin: FakeStdin;
472534
let restoreStdin: () => void;
@@ -697,6 +759,43 @@ describe("key shortcuts", () => {
697759
assert.equal(stdin.pauseCount, 1);
698760
});
699761

762+
it("takes the terminal back into raw mode after an action", async () => {
763+
service.attach({
764+
shortcuts: [
765+
{
766+
key: "R",
767+
description: "Restart",
768+
action: () => {
769+
// A child that shared the terminal exits and restores the
770+
// cooked mode it started with.
771+
stdin.terminalRaw = false;
772+
},
773+
},
774+
],
775+
});
776+
assert.isTrue(stdin.terminalRaw);
777+
778+
await press("R");
779+
780+
assert.isTrue(stdin.terminalRaw);
781+
});
782+
783+
it("leaves the terminal alone after an action that detached", async () => {
784+
service.attach({
785+
shortcuts: [
786+
{
787+
key: "x",
788+
description: "Detach",
789+
action: () => service.detach(),
790+
},
791+
],
792+
});
793+
794+
await press("x");
795+
796+
assert.isFalse(stdin.terminalRaw);
797+
});
798+
700799
it("tears down when the process exits", () => {
701800
const before = new Set(process.listeners("exit"));
702801
service.attach({ shortcuts: [] });

0 commit comments

Comments
 (0)