蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

对照编辑器和全屏接收的实际键序列

JAVASCRIPTWindows、Node.js 24.22.3、Pi 1.5.0、实际 TUI 组件和 pywinpty 3.1.2。keyboard-actions.mjs
keyboard-actions.mjs239 行
import assert from 'node:assert/strict';
import {mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {basename, dirname, join, resolve} from 'node:path';
import {pathToFileURL} from 'node:url';

const modules = process.argv[2];
if (!modules) throw new Error('Supply the installed node_modules path.');
const packageFile = (pkg, file) => pathToFileURL(resolve(modules, '@earendil-works', pkg, 'dist', file)).href;
const {KeybindingsManager, migrateKeybindingsConfig, useWindowsKeybindings} =
  await import(packageFile('pi-coding-agent', 'core/keybindings.js'));
const {parseKey, SelectList, setKeybindings, TuiAltScreen, TuiMainScreen} =
  await import(packageFile('pi-tui', 'index.js'));
const {CustomEditor} = await import(packageFile('pi-coding-agent', 'modes/interactive/components/custom-editor.js'));
const {version} = JSON.parse(await readFile(resolve(modules, '@earendil-works', 'pi-coding-agent', 'package.json'), 'utf8'));
const ESC = '\x1b';
const controls = {
  home: ESC + '[H', end: ESC + '[F', ctrlHome: ESC + '[1;5H', ctrlEnd: ESC + '[1;5F',
  pageUp: ESC + '[5~', pageDown: ESC + '[6~', ctrlPageUp: ESC + '[5;5~', search: '\x06',
};
const identity = text => text;
function terminal() {
  return {
    rows: 12, columns: 84, kittyProtocolActive: false, frames: [],
    start(onInput) { this.send = onInput; }, stop() {}, hideCursor() {}, showCursor() {},
    moveBy() {}, clearLine() {}, clearFromCursor() {}, clearScreen() {}, setTitle() {},
    write(chunk) { this.frames.push(chunk); },
  };
}
const makeEditor = (tui, keys) => new CustomEditor(tui, {borderColor: identity}, keys);
const plain = lines => lines.join('\n').replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '');
const results = [];
function check(name, input, expected, actual) {
  assert.deepStrictEqual(actual, expected, name);
  results.push({name, input, expected, actual, passed: true});
}

const base = resolve(tmpdir());
const root = await mkdtemp(join(base, 'mbsky-pi-keys-'));
assert.equal(dirname(resolve(root)), base);
assert.ok(basename(root).startsWith('mbsky-pi-keys-'));
try {
  const config = join(root, 'keybindings.json');
  const save = value => writeFile(config, JSON.stringify(value), 'utf8');
  const manager = KeybindingsManager.create(root);
  check('unconfigured_submit_applies_default', {}, ['enter'], manager.getKeys('tui.input.submit'));
  const migrated = migrateKeybindingsConfig({
    cursorUp: 'alt+k', expandTools: 'ctrl+u', 'tui.editor.cursorUp': ['up', 'alt+i'],
  });
  check('legacy_mapping_and_explicit_id_precedence', {legacy: ['cursorUp', 'expandTools']},
    [true, ['up', 'alt+i'], 'ctrl+u', false], [migrated.migrated,
      migrated.config['tui.editor.cursorUp'], migrated.config['app.tools.expand'], 'cursorUp' in migrated.config]);
  await save({
    'tui.editor.historyPrevious': 'ctrl+p',
    'tui.editor.cursorUp': ['up', 'alt+k'],
    'tui.altScreen.pageUp': [],
  });
  check('existing_manager_keeps_keys_until_reload', {edited: 'cursorUp'},
    ['up'], manager.getKeys('tui.editor.cursorUp'));
  manager.reload();
  check('reload_applies_array_and_explicit_unbind', {edited: ['cursorUp', 'pageUp']},
    [['up', 'alt+k'], [], ['enter']], ['tui.editor.cursorUp', 'tui.altScreen.pageUp', 'tui.input.submit']
      .map(id => manager.getKeys(id)));
  check('terminal_control_byte_matches_two_actions', {byte: '0x10'},
    ['ctrl+p', true, true], [parseKey('\x10'), manager.matches('\x10', 'tui.editor.historyPrevious'),
      manager.matches('\x10', 'app.model.cycleForward')]);
  check('conflicts_only_include_explicit_duplicate_claims', {explicitOverrides: 1}, [],
    manager.getConflicts());
  await save({'tui.editor.historyPrevious': 'ctrl+p', 'app.model.cycleForward': 'ctrl+p'});
  manager.reload();
  check('two_explicit_claims_produce_conflict', {explicitOverrides: 2},
    [{key: 'ctrl+p', keybindings: ['tui.editor.historyPrevious', 'app.model.cycleForward']}],
    manager.getConflicts());
  check('windows_and_wsl_select_windows_compatibility', {platforms: ['win32', 'linux (WSL)', 'linux']},
    [true, true, false], [useWindowsKeybindings('win32', {}), useWindowsKeybindings('linux', {WSL_INTEROP: 'example'}),
      useWindowsKeybindings('linux', {})]);
  const stock = new KeybindingsManager();
  const stockGroups = [
    ['tui.editor.cursorUp', ['up']], ['tui.editor.cursorDown', ['down']],
    ['tui.editor.cursorLeft', ['left', 'ctrl+b']], ['tui.editor.cursorRight', ['right', 'ctrl+f']],
    ['tui.editor.cursorWordLeft', ['alt+left', 'ctrl+left', 'alt+b']],
    ['tui.editor.cursorWordRight', ['alt+right', 'ctrl+right', 'alt+f']],
    ['tui.editor.cursorLineStart', ['home', 'ctrl+a']], ['tui.editor.cursorLineEnd', ['end', 'ctrl+e']],
    ['tui.editor.deleteCharBackward', ['backspace']], ['tui.editor.deleteCharForward', ['delete', 'ctrl+d']],
    ['tui.editor.deleteWordBackward', ['ctrl+w', 'alt+backspace']],
    ['tui.editor.deleteWordForward', ['alt+d', 'alt+delete']],
    ['tui.editor.deleteToLineStart', ['ctrl+u']], ['tui.editor.deleteToLineEnd', ['ctrl+k']],
    ['tui.input.newLine', ['shift+enter', 'ctrl+j']], ['tui.input.submit', ['enter']],
    ['tui.input.tab', ['tab']], ['tui.editor.undo', [process.platform === 'win32' ? 'ctrl+z' :
      useWindowsKeybindings() ? 'alt+z' : 'ctrl+-']], ['tui.editor.yank', ['ctrl+y']],
    ['app.interrupt', ['escape']], ['app.clear', ['ctrl+c']], ['app.exit', ['ctrl+d']],
    ['app.editor.external', ['ctrl+g']], ['app.clipboard.pasteImage', [useWindowsKeybindings() ? 'alt+v' : 'ctrl+v']],
    ['app.message.copy', ['ctrl+x']], ['app.message.followUp', [useWindowsKeybindings() ? 'ctrl+q' : 'alt+enter']],
    ['app.message.dequeue', [useWindowsKeybindings() ? 'alt+q' : 'alt+up']], ['app.model.select', ['ctrl+l']], ['app.model.cycleForward', ['ctrl+p']],
    ['app.model.cycleBackward', [useWindowsKeybindings() ? 'alt+p' : 'shift+ctrl+p']],
    ['app.thinking.cycle', ['shift+tab']], ['app.thinking.toggle', ['ctrl+t']], ['app.tools.expand', ['ctrl+o']],
    ['tui.altScreen.top', ['ctrl+home']], ['tui.altScreen.bottom', ['ctrl+end']],
    ['app.tree.filter.cycleForward', ['ctrl+o']],
  ];
  for (const [id, binding] of stockGroups) check('stock:' + id, {id}, binding, stock.getKeys(id));
  const formats = [['\x02', 'ctrl+b'], [ESC + '1', 'alt+1'], [ESC + 'OQ', 'f2'],
    [ESC + '[1;3D', 'alt+left'], ['\r', 'enter'], [';', ';']];
  check('parse_key_categories_from_input_bytes', {categories: ['letter', 'digit', 'function', 'arrow', 'enter', 'symbol']},
    formats.map(pair => pair[1]), formats.map(pair => parseKey(pair[0])));

  const regularTerminal = terminal();
  const regular = new TuiMainScreen(regularTerminal);
  const custom = new KeybindingsManager({'tui.editor.historyPrevious': 'ctrl+p'});
  const editor = makeEditor(regular, custom);
  regular.addChild(editor);
  regular.setFocus(editor);
  let modelCycles = 0;
  editor.onAction('app.model.cycleForward', () => modelCycles++);
  setKeybindings(custom);
  regular.start();
  try {
    editor.addToHistory('First full prompt');
    editor.addToHistory('Most recent prompt');
    editor.setText('This draft\nhas two lines');
    regularTerminal.send('\x10');
    check('history_wins_over_model_action_with_editor_focus', {mode: 'regular', key: 'Ctrl+P', multiline: true},
      ['Most recent prompt', 0], [editor.getText(), modelCycles]);
    custom.setUserBindings({});
    regularTerminal.send('\x10');
    check('model_action_runs_without_history_binding', {mode: 'regular', key: 'Ctrl+P'}, 1, modelCycles);
    editor.setText('word');
    regularTerminal.send(controls.home);
    regularTerminal.send('A');
    regularTerminal.send(controls.end);
    regularTerminal.send('Z');
    check('regular_home_end_move_the_editor', {homeText: 'A', endText: 'Z'}, 'AwordZ', editor.getText());
    let exits = 0;
    editor.onAction('app.exit', () => exits++);
    editor.setText('abc');
    regularTerminal.send(controls.home);
    regularTerminal.send('\x04');
    const edited = editor.getText();
    editor.setText('');
    regularTerminal.send('\x04');
    check('ctrl_d_distinguishes_delete_and_empty_exit', {mode: 'regular', input: 'abc'},
      ['bc', 1], [edited, exits]);
    editor.setText('first');
    regularTerminal.send('\x0a');
    regularTerminal.send('second');
    check('editor_newline_is_not_a_submission', {key: 'Ctrl+J'}, 'first\nsecond', editor.getText());
    custom.setUserBindings({'tui.editor.cursorLeft': ['left', 'alt+h'], 'tui.editor.cursorRight': ['right', 'alt+l']});
    editor.setText('abcd');
    regularTerminal.send(ESC + 'h');
    regularTerminal.send(ESC + 'h');
    regularTerminal.send(ESC + 'l');
    regularTerminal.send('Q');
    check('vim_alt_pair_moves_in_real_editor', {keys: ['Alt+H', 'Alt+H', 'Alt+L']}, 'abcQd', editor.getText());
  } finally {
    regular.stop();
  }

  const fullscreenTerminal = terminal();
  const fullscreen = new TuiAltScreen(fullscreenTerminal, false, undefined, {mouse: false});
  const transcript = Array.from({length: 52}, (_, index) =>
    ([4, 24].includes(index) ? ESC + ']133;A\x07' : '') +
    'Transcript row ' + index + ([4, 41].includes(index) ? ' OPAQUE MARKER' : ''));
  const fullscreenEditor = makeEditor(fullscreen, stock);
  fullscreen.addChild({render: () => transcript, invalidate() {}});
  fullscreen.setFocus(fullscreenEditor);
  setKeybindings(stock);
  const searchOpen = () => fullscreen.getFocusedComponent() !== fullscreenEditor;
  fullscreen.start();
  try {
    fullscreen.renderNow();
    const initial = fullscreen.viewportTop;
    assert.ok(initial > 10);
    fullscreenTerminal.send(controls.pageUp);
    fullscreen.renderNow();
    const paged = fullscreen.viewportTop;
    fullscreenTerminal.send(controls.pageDown);
    fullscreen.renderNow();
    check('fullscreen_plain_page_keys_scroll_transcript', {rows: 52},
      [true, true], [paged > 0 && paged < initial, fullscreen.viewportTop === initial]);
    fullscreenTerminal.send(controls.ctrlHome);
    fullscreen.renderNow();
    const top = fullscreen.viewportTop;
    fullscreenTerminal.send(controls.ctrlEnd);
    fullscreen.renderNow();
    check('fullscreen_ctrl_home_end_scroll_transcript_edges', {rows: 52},
      [0, initial], [top, fullscreen.viewportTop]);
    fullscreenEditor.setText('draft');
    fullscreenTerminal.send(controls.home);
    fullscreenTerminal.send('A');
    fullscreenTerminal.send(controls.end);
    fullscreenTerminal.send('Z');
    check('fullscreen_plain_home_end_still_edit', {keyInputs: ['Home', 'End']},
      ['AdraftZ', initial], [fullscreenEditor.getText(), fullscreen.viewportTop]);
    fullscreenTerminal.send(controls.ctrlPageUp);
    fullscreen.renderNow();
    check('fullscreen_ctrl_page_up_leaves_transcript_position', {after: 'Ctrl+PageUp'}, initial, fullscreen.viewportTop);

    fullscreenTerminal.send(controls.ctrlHome);
    fullscreen.renderNow();
    fullscreenTerminal.send(ESC + '[1;5B');
    fullscreen.renderNow();
    const firstMarker = fullscreen.viewportTop;
    fullscreenTerminal.send(ESC + '[1;5B');
    fullscreen.renderNow();
    const secondMarker = fullscreen.viewportTop;
    fullscreenTerminal.send(ESC + '[1;5A');
    fullscreen.renderNow();
    check('fullscreen_prompt_navigation_follows_marked_rows', {keys: ['Ctrl+Down', 'Ctrl+Down', 'Ctrl+Up']},
      [4, 24, 4], [firstMarker, secondMarker, fullscreen.viewportTop]);

    fullscreenTerminal.send(controls.search);
    for (const key of 'OPAQUE') fullscreenTerminal.send(key);
    fullscreen.renderNow();
    const searched = plain(fullscreen.getScreenLines());
    fullscreenTerminal.send('\r');
    fullscreen.renderNow();
    const advanced = plain(fullscreen.getScreenLines());
    check('fullscreen_search_finds_two_visible_matches', {keys: ['Ctrl+F', 'OPAQUE', 'Enter']}, [true, true, true],
      [searchOpen(), /[12]\/2/.test(searched), /[12]\/2/.test(advanced) && searched !== advanced]);
    fullscreenTerminal.send(ESC);
    fullscreen.renderNow();
    check('fullscreen_escape_closes_search_and_restores_editor', {key: 'Escape'}, false, searchOpen());

    const items = Array.from({length: 12}, (_, index) => ({value: String(index), label: 'Item ' + index}));
    const select = new SelectList(items, 3, {selectedPrefix: identity, selectedText: identity,
      description: identity, scrollInfo: identity, noMatch: identity});
    fullscreen.setFocus(select);
    const offset = fullscreen.viewportTop;
    fullscreenTerminal.send(controls.pageDown);
    check('focused_list_receives_page_key_before_transcript', {key: 'PageDown', visibleOptions: 3}, ['3', offset],
      [select.getSelectedItem().value, fullscreen.viewportTop]);
  } finally {
    fullscreen.stop();
  }
  process.stdout.write(JSON.stringify({nodeVersion: process.version, packageVersion: version,
    platform: process.platform, cases: results}) + '\n');
} finally {
  await rm(root, {recursive: true, force: true});
}
本例需在 Windows、Node.js 24.22.3、Pi 1.5.0、实际 TUI 组件和 pywinpty 3.1.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Node.js 24.22.3、Pi 1.5.0、实际 TUI 组件和 pywinpty 3.1.2。

入口文件:projects/pi-agent-keybindings-lab/keyboard-actions.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 keyboard-actions.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Node.js 24.22.3、Pi 1.5.0、实际 TUI 组件和 pywinpty 3.1.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Pi Agent

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a267.zip

下载课程关联工程包:Pi Agent

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a279.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习