| 31 | } |
| 32 | |
| 33 | export function bindCLIShortcuts<Server extends ViteDevServer | PreviewServer>( |
| 34 | server: Server, |
| 35 | opts?: BindCLIShortcutsOptions<Server>, |
| 36 | enabled: boolean = process.stdin.isTTY && !process.env.CI, |
| 37 | ): void { |
| 38 | if (!server.httpServer || !enabled) { |
| 39 | return |
| 40 | } |
| 41 | |
| 42 | const isDev = isDevServer(server) |
| 43 | |
| 44 | // Merge shortcuts: new at top, existing updated in place (keeps manual > plugin order) |
| 45 | const previousShortcuts = |
| 46 | server._shortcutsState?.options.customShortcuts ?? [] |
| 47 | const newShortcuts = opts?.customShortcuts ?? [] |
| 48 | const previousKeys = new Set(previousShortcuts.map((s) => s.key)) |
| 49 | const customShortcuts: CLIShortcut<ViteDevServer | PreviewServer>[] = [ |
| 50 | ...newShortcuts.filter((s) => !previousKeys.has(s.key)), |
| 51 | ...previousShortcuts.map( |
| 52 | (s) => newShortcuts.find((n) => n.key === s.key) ?? s, |
| 53 | ), |
| 54 | ] |
| 55 | |
| 56 | const newOptions: BindCLIShortcutsOptions<Server> = { |
| 57 | ...opts, |
| 58 | customShortcuts, |
| 59 | } |
| 60 | |
| 61 | if (opts?.print) { |
| 62 | server.config.logger.info( |
| 63 | colors.dim(colors.green(' ➜')) + |
| 64 | colors.dim(' press ') + |
| 65 | colors.bold('h + enter') + |
| 66 | colors.dim(' to show help'), |
| 67 | ) |
| 68 | } |
| 69 | |
| 70 | const shortcuts = customShortcuts.concat( |
| 71 | (isDev |
| 72 | ? BASE_DEV_SHORTCUTS |
| 73 | : BASE_PREVIEW_SHORTCUTS) as CLIShortcut<Server>[], |
| 74 | ) |
| 75 | |
| 76 | let actionRunning = false |
| 77 | |
| 78 | const onInput = async (input: string) => { |
| 79 | if (actionRunning) return |
| 80 | |
| 81 | input = input.trim().toLocaleLowerCase() |
| 82 | if (input === 'h') { |
| 83 | const loggedKeys = new Set<string>() |
| 84 | server.config.logger.info('\n Shortcuts') |
| 85 | |
| 86 | for (const shortcut of shortcuts) { |
| 87 | if (loggedKeys.has(shortcut.key)) continue |
| 88 | loggedKeys.add(shortcut.key) |
| 89 | |
| 90 | if (shortcut.action == null) continue |