mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-20 04:59:34 +01:00
Merge #820: Send on Enter for the pinned CJK input field
A per-device mode for the pinned CJK field on phones: a typed answer stays in the field while the terminal scrolls and goes out only on Enter.
This commit is contained in:
commit
6222444e82
20 files changed
+1725
-42
No files matched your search
@@ -0,0 +1,201 @@
|
||||
// test/cjk-hold-per-device-setting.test.ts
|
||||
// Port: none (static analysis + vm, runs in CI, no browser/server).
|
||||
//
|
||||
// Send on Enter for the CJK input field (`cjkInputHoldUntilEnter`) is a
|
||||
// PER-DEVICE setting like `cjkInputEnabled`: in settings-ui.js's displayKeys
|
||||
// merge policy, stripped out of the object saveAppSettings() PUTs
|
||||
// (SettingsUpdateSchema is .strict(), so sending it would 400 every save), and
|
||||
// never declared in the schema. Plus the pieces around the mode: a held draft
|
||||
// surviving a reload of the same session, the field staying one line tall with
|
||||
// the keyboard down, and zh-CN strings for its placeholders.
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { join } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
|
||||
const HERE = fileURLToPath(new URL('.', import.meta.url));
|
||||
const PUBLIC = join(HERE, '../src/web/public');
|
||||
const read = (file: string) => readFileSync(join(PUBLIC, file), 'utf8');
|
||||
|
||||
describe('cjkInputHoldUntilEnter stays per-device: display key, stripped from the PUT, absent from the schema', () => {
|
||||
const settingsUi = read('settings-ui.js');
|
||||
const schemas = readFileSync(join(HERE, '../src/web/schemas.ts'), 'utf8');
|
||||
|
||||
it('is in the client-side displayKeys merge policy', () => {
|
||||
const start = settingsUi.indexOf('const displayKeys = new Set([');
|
||||
const displayKeys = settingsUi.slice(start, settingsUi.indexOf('])', start));
|
||||
expect(displayKeys).toContain("'cjkInputHoldUntilEnter'");
|
||||
});
|
||||
|
||||
it('is stripped out of the object saveAppSettings() PUTs to the server', () => {
|
||||
expect(settingsUi).toContain('cjkInputHoldUntilEnter: _cjkHold,');
|
||||
});
|
||||
|
||||
it('is never declared in the .strict() SettingsUpdateSchema', () => {
|
||||
expect(schemas).not.toContain('cjkInputHoldUntilEnter');
|
||||
});
|
||||
|
||||
it('defaults OFF on handhelds, next to cjkInputEnabled', () => {
|
||||
expect(settingsUi).toMatch(/cjkInputEnabled: false,\s*cjkInputHoldUntilEnter: false,/);
|
||||
});
|
||||
|
||||
it('is loaded into and saved from its App Settings switch', () => {
|
||||
expect(read('index.html')).toContain('id="appSettingsCjkHoldUntilEnter"');
|
||||
expect(settingsUi).toContain("document.getElementById('appSettingsCjkHoldUntilEnter').checked =");
|
||||
expect(settingsUi).toContain(
|
||||
"cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked,"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a held draft survives a reload of the same session', () => {
|
||||
// The REAL _cleanupPreviousSession from app.js. selectSession() nulls
|
||||
// activeSessionId before calling it on a same-session forceReload (tapping the
|
||||
// tab already shown, the geometry retry), so it is told through keepCjkDraft.
|
||||
function cleanup(hold: boolean, keepCjkDraft: boolean, outgoing: string | null = null) {
|
||||
const clear = vi.fn();
|
||||
const stashDraft = vi.fn();
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
requestAnimationFrame: vi.fn(),
|
||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||
WebSocket: { OPEN: 1 },
|
||||
fetch: vi.fn(),
|
||||
URLSearchParams,
|
||||
document: { addEventListener: vi.fn(), documentElement: { dataset: {} }, getElementById: () => null },
|
||||
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
MobileDetection: { isTouchDevice: () => true, isHandheldDevice: () => true, getDeviceType: () => 'mobile' },
|
||||
CjkInput: { holdUntilEnter: hold, clear, stashDraft },
|
||||
});
|
||||
vm.runInContext(`${read('constants.js')}\n${read('app.js')}\nglobalThis.__CodemanApp = CodemanApp;`, context);
|
||||
const CodemanApp = (context as unknown as { __CodemanApp: { prototype: object } }).__CodemanApp;
|
||||
const app = Object.create(CodemanApp.prototype) as Record<string, unknown> & {
|
||||
_cleanupPreviousSession(id: string, opts?: { keepCjkDraft?: boolean }): void;
|
||||
};
|
||||
app.activeSessionId = outgoing;
|
||||
app.sessions = new Map();
|
||||
app._clearTimer = vi.fn();
|
||||
app._disconnectWs = vi.fn();
|
||||
app._xtermSnapshots = new Map();
|
||||
app.pendingWrites = [];
|
||||
app._cleanupPreviousSession('s1', { keepCjkDraft });
|
||||
return Object.assign(clear, { stashDraft });
|
||||
}
|
||||
|
||||
it('keeps the draft on a same-session reload in Send on Enter mode', () => {
|
||||
expect(cleanup(true, true)).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still clears on a real switch', () => {
|
||||
expect(cleanup(true, false)).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('still clears in live mode, where a pending flush could fire mid-reconnect', () => {
|
||||
expect(cleanup(false, true)).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stashes the held draft of the session being left before clearing', () => {
|
||||
const clear = cleanup(true, false, 's0');
|
||||
expect(clear.stashDraft).toHaveBeenCalledWith('s0');
|
||||
expect(clear.stashDraft.mock.invocationCallOrder[0]).toBeLessThan(clear.mock.invocationCallOrder[0]);
|
||||
});
|
||||
|
||||
it('selectSession restores the draft of the session it lands on', () => {
|
||||
// After _activateFileBrowserSession: test/file-browser-search.test.ts pins
|
||||
// that call as the line right after the activeSessionId assignment.
|
||||
expect(read('app.js')).toContain(
|
||||
"this.activeSessionId = sessionId;\n this._activateFileBrowserSession?.(sessionId);\n if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);"
|
||||
);
|
||||
});
|
||||
|
||||
it('leaving the tile grid for another session stashes the focused tile draft', () => {
|
||||
// selectSession nulls activeSessionId there, which hides the tile from
|
||||
// _cleanupPreviousSession.
|
||||
expect(read('app.js')).toMatch(
|
||||
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\n(?:\s*\/\/.*\n)*\s*this\.activeSessionId = null;/
|
||||
);
|
||||
});
|
||||
|
||||
it('tile focus does not stash again for a tile closed from this tab', () => {
|
||||
// removeSession discards the closed session's draft first; a stash after
|
||||
// that would keep it in the map until the page reloads.
|
||||
expect(read('tile-grid.js')).toContain(
|
||||
'if (this.sessions?.has(this.activeSessionId)) CjkInput.stashDraft?.(this.activeSessionId);'
|
||||
);
|
||||
});
|
||||
|
||||
it('tile focus stashes the draft of the tile left and restores the focused one', () => {
|
||||
const tiles = read('tile-grid.js');
|
||||
const start = tiles.indexOf(' _selectTiledSession(sessionId, options = {}) {');
|
||||
const body = tiles.slice(start, tiles.indexOf('grid.focusedId = sessionId;', start));
|
||||
expect(body).toMatch(
|
||||
/CjkInput\.stashDraft\?\.\(this\.activeSessionId\);\s*CjkInput\.clear\(\);\s*\}\s*CjkInput\.restoreDraft\?\.\(sessionId\);\s*\}\s*this\.activeSessionId = sessionId;/
|
||||
);
|
||||
});
|
||||
|
||||
it('going Home stashes the draft of the session it leaves', () => {
|
||||
const appJs = read('app.js');
|
||||
const start = appJs.indexOf(' goHome() {');
|
||||
const body = appJs.slice(start, appJs.indexOf('this.activeSessionId = null;', start));
|
||||
expect(body).toContain('CjkInput.stashDraft?.(this.activeSessionId);');
|
||||
});
|
||||
|
||||
it('a removed session drops its stashed draft', () => {
|
||||
expect(read('app.js')).toMatch(
|
||||
/discardComposerDraft\?\.\(sessionId\);\n\s*if \(typeof CjkInput !== 'undefined'\) CjkInput\.discardDraft\?\.\(sessionId\);/
|
||||
);
|
||||
});
|
||||
|
||||
it('selectSession passes the same-session flag it captured before nulling activeSessionId', () => {
|
||||
const appJs = read('app.js');
|
||||
expect(appJs).toMatch(
|
||||
/if \(this\.activeSessionId === sessionId && forceReload\) \{\s*reloadingSameSession = true;/
|
||||
);
|
||||
expect(appJs).toContain('this._cleanupPreviousSession(sessionId, { keepCjkDraft: reloadingSameSession });');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Send on Enter field layout and strings', () => {
|
||||
it('keeps the field one line tall while the keyboard is down', () => {
|
||||
// .main reserves a fixed 84px there; a grown field would cover the terminal.
|
||||
expect(read('styles.css')).toMatch(
|
||||
/\.touch-device:not\(\.keyboard-visible\) #cjkInput\.cjk-input-visible \{\s*max-height: 34px;\s*\}/
|
||||
);
|
||||
});
|
||||
|
||||
it('caps the field on every device, not only in the .touch-device rule', () => {
|
||||
// The setting is not limited to phones; on desktop an uncapped field grew to
|
||||
// 502px at 25 lines and resized the PTY on every step.
|
||||
const css = read('styles.css');
|
||||
const base = css.slice(css.indexOf('#cjkInput {'), css.indexOf('}', css.indexOf('#cjkInput {')));
|
||||
expect(base).toContain('max-height: 68px;');
|
||||
expect(base).toContain('overflow-y: auto;');
|
||||
});
|
||||
|
||||
it('the phone toolbar Enter presses Enter in the visible CJK field', () => {
|
||||
// onData drops everything while cjkActive, so the xterm path does nothing.
|
||||
const sessionUi = read('session-ui.js');
|
||||
const start = sessionUi.indexOf(' sendEnterKey() {');
|
||||
const body = sessionUi.slice(start, sessionUi.indexOf('triggerDataEvent', start));
|
||||
expect(body).toContain("classList.contains('cjk-input-visible')");
|
||||
expect(body).toContain('CjkInput.submit?.();');
|
||||
});
|
||||
|
||||
it('has zh-CN strings for both field placeholders', () => {
|
||||
const i18n = read('i18n.js');
|
||||
const cjk = read('input-cjk.js');
|
||||
for (const placeholder of [
|
||||
'CJK input (Enter = send, Esc = clear)',
|
||||
'Type, Enter to send (Shift+Enter: new line, Esc: clear)',
|
||||
]) {
|
||||
expect(cjk).toContain(`'${placeholder}'`);
|
||||
expect(i18n.split(`'${placeholder}':`).length - 1).toBe(1);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,617 @@
|
||||
/**
|
||||
* @fileoverview Send-on-Enter mode of the CJK input field (input-cjk.js,
|
||||
* setting cjkInputHoldUntilEnter): typed text stays in the field until Enter,
|
||||
* so a phone user can scroll the terminal and edit an answer before sending.
|
||||
*
|
||||
* Same vm-sandbox approach as input-cjk.test.ts, with a stub textarea that also
|
||||
* carries the attributes and style the mode touches.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PHANTOM = '';
|
||||
|
||||
function makeTextarea() {
|
||||
const listeners = new Map<string, Array<(e?: unknown) => void>>();
|
||||
const attrs: Record<string, string> = {};
|
||||
return {
|
||||
value: '',
|
||||
placeholder: '',
|
||||
style: { height: '' } as Record<string, string>,
|
||||
scrollHeight: 34,
|
||||
// border-box with a 1px border: offsetHeight - clientHeight is the borders.
|
||||
offsetHeight: 36,
|
||||
clientHeight: 34,
|
||||
attrs,
|
||||
blur: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
getClientRects: (): unknown[] => [{}],
|
||||
classList: { contains: (c: string) => c === 'cjk-input-visible' },
|
||||
setSelectionRange: () => {},
|
||||
setAttribute: vi.fn((k: string, v: string) => {
|
||||
attrs[k] = v;
|
||||
}),
|
||||
addEventListener: (ev: string, fn: (e?: unknown) => void) => {
|
||||
listeners.set(ev, [...(listeners.get(ev) ?? []), fn]);
|
||||
},
|
||||
removeEventListener: (ev: string, fn: (e?: unknown) => void) => {
|
||||
listeners.set(
|
||||
ev,
|
||||
(listeners.get(ev) ?? []).filter((f) => f !== fn)
|
||||
);
|
||||
},
|
||||
fire(ev: string, arg: Record<string, unknown> = {}) {
|
||||
const base = { preventDefault: () => {}, stopPropagation: () => {}, ...arg };
|
||||
for (const fn of listeners.get(ev) ?? []) fn(base);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function load({
|
||||
hold = true,
|
||||
promptResult = true,
|
||||
touch = true,
|
||||
translate,
|
||||
}: { hold?: boolean; promptResult?: boolean; touch?: boolean; translate?: (s: string) => string } = {}) {
|
||||
const textarea = makeTextarea();
|
||||
const sent: string[] = [];
|
||||
const prompts: string[] = [];
|
||||
const layout = vi.fn();
|
||||
// The shell bar's one-shot Ctrl, reduced to its armed flag.
|
||||
const bar = {
|
||||
armed: false,
|
||||
isCtrlArmed() {
|
||||
return this.armed;
|
||||
},
|
||||
clearCtrl() {
|
||||
this.armed = false;
|
||||
},
|
||||
};
|
||||
const context = vm.createContext({
|
||||
window: translate ? { CodemanI18n: { t: translate } } : {},
|
||||
document: {
|
||||
getElementById: (id: string) => (id === 'cjkInput' ? textarea : null),
|
||||
activeElement: null,
|
||||
body: { classList: { contains: (c: string) => touch && c === 'touch-device' } },
|
||||
},
|
||||
navigator: { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X)' },
|
||||
KeyboardHandler: { updateLayoutForKeyboard: layout },
|
||||
KeyboardAccessoryBar: bar,
|
||||
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
|
||||
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
|
||||
performance: { now: () => performance.now() },
|
||||
console,
|
||||
});
|
||||
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/input-cjk.js'), 'utf8');
|
||||
vm.runInContext(src, context, { filename: 'input-cjk.js' });
|
||||
const CjkInput = vm.runInContext('CjkInput', context);
|
||||
CjkInput.init({
|
||||
send: (t: string) => sent.push(t),
|
||||
sendPrompt: (t: string) => {
|
||||
prompts.push(t);
|
||||
return promptResult;
|
||||
},
|
||||
});
|
||||
CjkInput.setHoldUntilEnter(hold);
|
||||
textarea.fire('focus');
|
||||
return { CjkInput, textarea, sent, prompts, layout, bar };
|
||||
}
|
||||
|
||||
function type(textarea: ReturnType<typeof makeTextarea>, text: string) {
|
||||
textarea.value = PHANTOM + text;
|
||||
textarea.fire('input', { isComposing: false, inputType: 'insertText' });
|
||||
}
|
||||
|
||||
function backspace(textarea: ReturnType<typeof makeTextarea>, valueAfter: string) {
|
||||
textarea.value = valueAfter;
|
||||
textarea.fire('input', { isComposing: false, inputType: 'deleteContentBackward' });
|
||||
}
|
||||
|
||||
const enter = (textarea: ReturnType<typeof makeTextarea>) =>
|
||||
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
|
||||
|
||||
describe('CJK input: Send on Enter', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] });
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('keeps typed text in the field instead of streaming it', () => {
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'use Postgres');
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(sent).toEqual([]);
|
||||
expect(textarea.value).toBe(PHANTOM + 'use Postgres');
|
||||
});
|
||||
|
||||
it('keeps text after a physical keystroke (no zero-latency flush)', () => {
|
||||
const { textarea, sent } = load();
|
||||
textarea.fire('keydown', { key: 'a', keyCode: 65, ctrlKey: false, altKey: false, metaKey: false });
|
||||
type(textarea, 'a');
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps text across a composition cycle and autocorrect rewrites', () => {
|
||||
const { textarea, sent } = load();
|
||||
textarea.fire('compositionstart');
|
||||
textarea.value = PHANTOM + 'teh';
|
||||
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
|
||||
textarea.fire('compositionend');
|
||||
textarea.value = PHANTOM + 'the';
|
||||
textarea.fire('input', { isComposing: false, inputType: 'insertReplacementText' });
|
||||
vi.advanceTimersByTime(5000);
|
||||
expect(sent).toEqual([]);
|
||||
expect(textarea.value).toBe(PHANTOM + 'the');
|
||||
});
|
||||
|
||||
it('sends one line on Enter through the prompt path, then clears the field', () => {
|
||||
const { textarea, sent, prompts } = load();
|
||||
type(textarea, 'yes, use Postgres');
|
||||
const preventDefault = vi.fn();
|
||||
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false, preventDefault });
|
||||
expect(preventDefault).toHaveBeenCalled();
|
||||
expect(prompts).toEqual(['yes, use Postgres']);
|
||||
expect(sent).toEqual([]);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('never writes text and Enter together, whatever the length', () => {
|
||||
// Codex takes characters arriving in one burst as a paste and folds an Enter
|
||||
// inside it into the paste, so even `1\r` in one write stays unsent; Claude
|
||||
// Code does the same for a long burst. terminal-ui.js _sendCjkPrompt types a
|
||||
// single character and pastes anything longer, Enter always on its own.
|
||||
const { textarea, sent, prompts } = load();
|
||||
for (const answer of ['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]) {
|
||||
type(textarea, answer);
|
||||
enter(textarea);
|
||||
}
|
||||
expect(sent).toEqual([]);
|
||||
expect(prompts).toEqual(['2', 'yes', 'a'.repeat(64), 'b'.repeat(150)]);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('keeps a short answer in the field when it is refused (no session)', () => {
|
||||
const { textarea, prompts } = load({ promptResult: false });
|
||||
type(textarea, 'yes');
|
||||
enter(textarea);
|
||||
expect(prompts).toEqual(['yes']);
|
||||
expect(textarea.value).toBe(PHANTOM + 'yes');
|
||||
});
|
||||
|
||||
it('sends several lines as a prompt (bracketed paste + session-bound Enter)', () => {
|
||||
const { textarea, sent, prompts } = load();
|
||||
type(textarea, 'line one\nline two');
|
||||
enter(textarea);
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(prompts).toEqual(['line one\nline two']);
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps the text in the field when the prompt is refused (too long, no session)', () => {
|
||||
const { textarea, prompts } = load({ promptResult: false });
|
||||
type(textarea, 'line one\nline two');
|
||||
enter(textarea);
|
||||
expect(prompts).toHaveLength(1);
|
||||
expect(textarea.value).toBe(PHANTOM + 'line one\nline two');
|
||||
});
|
||||
|
||||
it('treats Shift+Enter as a newline, never a send', () => {
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'first');
|
||||
const preventDefault = vi.fn();
|
||||
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: true, preventDefault });
|
||||
vi.advanceTimersByTime(10);
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('sends a bare Enter when the field is empty (accepting a default answer)', () => {
|
||||
const { textarea, sent } = load();
|
||||
textarea.fire('keydown', { key: 'Enter', keyCode: 13, shiftKey: false });
|
||||
expect(sent).toEqual(['\r']);
|
||||
});
|
||||
|
||||
it('still forwards Backspace on an empty field to the PTY', () => {
|
||||
const { textarea, sent } = load();
|
||||
textarea.fire('keydown', { key: 'Backspace', keyCode: 8 });
|
||||
expect(sent).toEqual(['\x7f']);
|
||||
});
|
||||
|
||||
it('does not send Backspace when deleting the last held character', () => {
|
||||
// The CLI's own composer may hold text (Attach, image paste, Path, mic):
|
||||
// a stray DEL would eat its last character.
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'a');
|
||||
type(textarea, 'ab');
|
||||
backspace(textarea, PHANTOM + 'a');
|
||||
backspace(textarea, PHANTOM);
|
||||
expect(sent).toEqual([]);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('sends Backspace once the field is empty and the phantom itself is deleted', () => {
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'a');
|
||||
backspace(textarea, PHANTOM);
|
||||
backspace(textarea, '');
|
||||
expect(sent).toEqual(['\x7f']);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('does not send Backspace for select-all + delete of held text', () => {
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'abc');
|
||||
backspace(textarea, '');
|
||||
expect(sent).toEqual([]);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('deletes held text right after typing it, before any debounce, without a DEL', () => {
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'a');
|
||||
backspace(textarea, PHANTOM);
|
||||
vi.advanceTimersByTime(2000);
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('puts the phantom back when Backspace at the start of the text deleted it', () => {
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'abc');
|
||||
backspace(textarea, 'abc');
|
||||
expect(sent).toEqual([]);
|
||||
expect(textarea.value).toBe(PHANTOM + 'abc');
|
||||
});
|
||||
|
||||
it('one-shot Ctrl: the next typed character goes out instead of being held', () => {
|
||||
// _handleCjkInput turns the single character into the control byte.
|
||||
const { textarea, sent, bar } = load();
|
||||
bar.armed = true;
|
||||
type(textarea, 'c');
|
||||
expect(sent).toEqual(['c']);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('one-shot Ctrl: held text stays and only the new character leaves the field', () => {
|
||||
const { textarea, sent, bar } = load();
|
||||
type(textarea, 'ab');
|
||||
bar.armed = true;
|
||||
type(textarea, 'abc');
|
||||
expect(sent).toEqual(['c']);
|
||||
expect(textarea.value).toBe(PHANTOM + 'ab');
|
||||
});
|
||||
|
||||
it('one-shot Ctrl: a character committed by an IME composition also goes out', () => {
|
||||
const { textarea, sent, bar } = load();
|
||||
bar.armed = true;
|
||||
textarea.fire('compositionstart');
|
||||
textarea.value = PHANTOM + 'c';
|
||||
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
|
||||
textarea.fire('compositionend');
|
||||
vi.advanceTimersByTime(10);
|
||||
expect(sent).toEqual(['c']);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('one-shot Ctrl: a multi-character commit stays held and spends the modifier', () => {
|
||||
const { textarea, sent, bar } = load();
|
||||
bar.armed = true;
|
||||
type(textarea, 'hello');
|
||||
expect(sent).toEqual([]);
|
||||
expect(textarea.value).toBe(PHANTOM + 'hello');
|
||||
expect(bar.armed).toBe(false);
|
||||
});
|
||||
|
||||
it('Escape clears the held text without sending', () => {
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'never mind');
|
||||
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
|
||||
expect(sent).toEqual([]);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('turning the mode off drops the held draft and the stashes, so live mode sends only new keys', () => {
|
||||
const { CjkInput, textarea, sent } = load();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
type(textarea, 'rm -rf build\nsecond line');
|
||||
CjkInput.stashDraft('session-b');
|
||||
CjkInput.setHoldUntilEnter(false);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
type(textarea, 'x');
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(sent).toEqual(['x']);
|
||||
CjkInput.setHoldUntilEnter(true);
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-b');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('stays one line on a desktop, where growing would resize the PTY', () => {
|
||||
const { textarea, layout } = load({ touch: false });
|
||||
layout.mockClear();
|
||||
textarea.scrollHeight = 60;
|
||||
type(textarea, 'a\nb\nc');
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(textarea.style.height).toBe('');
|
||||
expect(layout).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('translates its placeholder itself, since i18n.js skips textareas', () => {
|
||||
const { CjkInput, textarea } = load({ translate: (s) => `zh:${s}` });
|
||||
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
|
||||
CjkInput.setHoldUntilEnter(false);
|
||||
expect(textarea.placeholder).toBe('zh:CJK input (Enter = send, Esc = clear)');
|
||||
});
|
||||
|
||||
it('turns autocorrect on in the mode and back off without it', () => {
|
||||
const { CjkInput, textarea } = load();
|
||||
expect(textarea.attrs.autocorrect).toBe('on');
|
||||
expect(textarea.attrs.spellcheck).toBe('true');
|
||||
CjkInput.setHoldUntilEnter(false);
|
||||
expect(textarea.attrs.autocorrect).toBe('off');
|
||||
expect(textarea.attrs.spellcheck).toBe('false');
|
||||
expect(CjkInput.holdUntilEnter).toBe(false);
|
||||
});
|
||||
|
||||
it('grows the field with its text and re-runs the keyboard layout', () => {
|
||||
const { textarea, layout } = load();
|
||||
layout.mockClear();
|
||||
textarea.scrollHeight = 60;
|
||||
type(textarea, 'a\nb\nc');
|
||||
vi.advanceTimersByTime(1000);
|
||||
// scrollHeight + the 2px of border, so a two-line draft does not scroll inside.
|
||||
expect(textarea.style.height).toBe('62px');
|
||||
expect(layout).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('leaves the field alone when the mode is set again unchanged', () => {
|
||||
// Runs on every session select and SSE reconnect, possibly mid-composition.
|
||||
const { CjkInput, textarea } = load();
|
||||
textarea.setAttribute.mockClear();
|
||||
const placeholder = textarea.placeholder;
|
||||
let writes = 0;
|
||||
Object.defineProperty(textarea, 'placeholder', {
|
||||
get: () => placeholder,
|
||||
set: () => {
|
||||
writes++;
|
||||
},
|
||||
});
|
||||
CjkInput.setHoldUntilEnter(true);
|
||||
expect(textarea.setAttribute).not.toHaveBeenCalled();
|
||||
expect(writes).toBe(0);
|
||||
CjkInput.setHoldUntilEnter(false);
|
||||
expect(textarea.setAttribute).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('follows a live language switch with the mode unchanged', () => {
|
||||
// App Settings runs applyLocalization(), then _updateCjkInputState(), which
|
||||
// calls setHoldUntilEnter() with the same mode.
|
||||
let lang = 'en';
|
||||
const { CjkInput, textarea } = load({ translate: (s) => (lang === 'zh' ? `zh:${s}` : s) });
|
||||
expect(textarea.placeholder).toBe('Type, Enter to send (Shift+Enter: new line, Esc: clear)');
|
||||
textarea.setAttribute.mockClear();
|
||||
lang = 'zh';
|
||||
CjkInput.setHoldUntilEnter(true);
|
||||
expect(textarea.placeholder).toBe('zh:Type, Enter to send (Shift+Enter: new line, Esc: clear)');
|
||||
expect(textarea.setAttribute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submit() from outside the field (toolbar Enter) sends like Enter', () => {
|
||||
const { CjkInput, textarea, prompts, sent } = load();
|
||||
type(textarea, 'go ahead');
|
||||
expect(CjkInput.submit()).toBe(true);
|
||||
expect(prompts).toEqual(['go ahead']);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
expect(CjkInput.submit()).toBe(true);
|
||||
expect(sent).toEqual(['\r']);
|
||||
});
|
||||
|
||||
it('submit() keeps a refused answer and reports it', () => {
|
||||
const { CjkInput, textarea } = load({ promptResult: false });
|
||||
type(textarea, 'go ahead');
|
||||
expect(CjkInput.submit()).toBe(false);
|
||||
expect(textarea.value).toBe(PHANTOM + 'go ahead');
|
||||
});
|
||||
|
||||
it('a draft stashed on a switch comes back for its own session only', () => {
|
||||
const { CjkInput, textarea, sent, prompts } = load();
|
||||
type(textarea, 'half an answer');
|
||||
CjkInput.stashDraft('session-a');
|
||||
CjkInput.clear();
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
CjkInput.restoreDraft('session-b');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM + 'half an answer');
|
||||
// Restored once: the stash is consumed, so once the user empties the
|
||||
// field (Esc here) a second visit does not bring it back. A draft still in
|
||||
// the field when the session is left is stashed again by clear().
|
||||
textarea.fire('keydown', { key: 'Escape', keyCode: 27 });
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
expect(sent).toEqual([]);
|
||||
expect(prompts).toEqual([]);
|
||||
});
|
||||
|
||||
it('a restored draft is held text: Backspace edits it without a DEL', () => {
|
||||
const { CjkInput, textarea, sent } = load();
|
||||
type(textarea, 'ok');
|
||||
CjkInput.stashDraft('session-a');
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
backspace(textarea, PHANTOM + 'o');
|
||||
backspace(textarea, PHANTOM);
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('an empty field stashes nothing, and a discarded draft is gone', () => {
|
||||
const { CjkInput, textarea } = load();
|
||||
type(textarea, 'draft');
|
||||
CjkInput.stashDraft('session-a');
|
||||
CjkInput.discardDraft('session-a');
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
CjkInput.stashDraft('session-b');
|
||||
CjkInput.restoreDraft('session-b');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('a switch with an empty field keeps the draft already stashed for that session', () => {
|
||||
// The tile grid stashes the session it parks, then may stash it again from
|
||||
// tile focus with the field already cleared.
|
||||
const { CjkInput, textarea } = load();
|
||||
type(textarea, 'keep me');
|
||||
CjkInput.stashDraft('session-a');
|
||||
CjkInput.clear();
|
||||
CjkInput.stashDraft('session-a');
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM + 'keep me');
|
||||
});
|
||||
|
||||
it('clear() stashes a held draft for the session it was typed for, with no stash call', () => {
|
||||
// goHome(), _replaceTileGrid and _onTileAdoptedElsewhere drop the active
|
||||
// session before the next cleanup, which then has no session to stash for.
|
||||
const { CjkInput, textarea, sent } = load();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
type(textarea, 'typed for a');
|
||||
CjkInput.clear();
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
CjkInput.restoreDraft('session-b');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM + 'typed for a');
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('clear({ discard }) throws the draft away: a same-tab restore and a switch back stay empty', () => {
|
||||
// The keyboard bar's clear-line key (terminal-ui.js clearTerminalInput).
|
||||
const { CjkInput, textarea } = load();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
type(textarea, 'thrown away');
|
||||
CjkInput.clear({ discard: true });
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
expect(CjkInput.draftOwner).toBe('session-a');
|
||||
// Tapping the session's own tab: the field is kept, then restoreDraft runs.
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
// Switching away and back.
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-b');
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('clear({ discard }) also drops an older stash of the same session', () => {
|
||||
const { CjkInput, textarea } = load();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
type(textarea, 'old');
|
||||
CjkInput.stashDraft('session-a');
|
||||
CjkInput.clear({ discard: true });
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('a removed session loses its field text: discardDraft drops the owner', () => {
|
||||
const { CjkInput, textarea } = load();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
type(textarea, 'for a closed tile');
|
||||
CjkInput.discardDraft('session-a');
|
||||
expect(CjkInput.draftOwner).toBe(null);
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('a field still holding text keeps its owner when another session is shown', () => {
|
||||
const { CjkInput, textarea } = load();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
type(textarea, 'still for a');
|
||||
CjkInput.restoreDraft('session-b');
|
||||
expect(CjkInput.draftOwner).toBe('session-a');
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM + 'still for a');
|
||||
});
|
||||
|
||||
it('Ctrl shortcuts stay in the field while it holds a draft', () => {
|
||||
// Ctrl+Z is undo, Ctrl+A select all, Ctrl+C copy: never a control byte to
|
||||
// the CLI while there is a draft to act on.
|
||||
const { textarea, sent } = load();
|
||||
type(textarea, 'draft');
|
||||
for (const key of ['z', 'a', 'c']) {
|
||||
const preventDefault = vi.fn();
|
||||
textarea.fire('keydown', { key, keyCode: key.toUpperCase().charCodeAt(0), ctrlKey: true, preventDefault });
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
}
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
|
||||
it('Ctrl shortcuts reach the CLI from an empty field', () => {
|
||||
const { textarea, sent } = load();
|
||||
const preventDefault = vi.fn();
|
||||
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true, preventDefault });
|
||||
expect(preventDefault).toHaveBeenCalled();
|
||||
expect(sent).toEqual(['\x03']);
|
||||
});
|
||||
|
||||
it('live mode keeps sending Ctrl shortcuts with text in the field', () => {
|
||||
const { textarea, sent } = load({ hold: false });
|
||||
textarea.value = PHANTOM + 'x';
|
||||
textarea.fire('keydown', { key: 'c', keyCode: 67, ctrlKey: true });
|
||||
expect(sent).toEqual(['\x03']);
|
||||
});
|
||||
|
||||
it('sends a bare Enter when the field holds only blank lines', () => {
|
||||
const { textarea, sent, prompts } = load();
|
||||
type(textarea, '\n');
|
||||
enter(textarea);
|
||||
expect(prompts).toEqual([]);
|
||||
expect(sent).toEqual(['\r']);
|
||||
});
|
||||
|
||||
it('submit() mid-composition commits it first (blur, focus) and sends what landed', () => {
|
||||
const { CjkInput, textarea, prompts } = load();
|
||||
textarea.fire('compositionstart');
|
||||
textarea.value = PHANTOM + 'yes';
|
||||
textarea.fire('input', { isComposing: true, inputType: 'insertCompositionText' });
|
||||
expect(CjkInput.submit()).toBe(true);
|
||||
expect(textarea.blur).toHaveBeenCalled();
|
||||
expect(textarea.focus).toHaveBeenCalled();
|
||||
expect(prompts).toEqual(['yes']);
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('a hidden field does not get a 0px height (no session shown yet)', () => {
|
||||
const { CjkInput, textarea } = load({ hold: false });
|
||||
textarea.getClientRects = () => [];
|
||||
textarea.scrollHeight = 0;
|
||||
textarea.style.height = '40px';
|
||||
CjkInput.setHoldUntilEnter(true);
|
||||
expect(textarea.style.height).toBe('');
|
||||
});
|
||||
|
||||
it('live mode stashes no drafts', () => {
|
||||
const { CjkInput, textarea } = load({ hold: false });
|
||||
textarea.value = PHANTOM + 'abc';
|
||||
CjkInput.stashDraft('session-a');
|
||||
CjkInput.clear();
|
||||
CjkInput.restoreDraft('session-a');
|
||||
expect(textarea.value).toBe(PHANTOM);
|
||||
});
|
||||
|
||||
it('live mode is unchanged: text streams after the debounce', () => {
|
||||
const { textarea, sent } = load({ hold: false });
|
||||
type(textarea, 'hi');
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(sent).toEqual(['hi']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
// Port: none (pure logic in a vm context — no browser, no server).
|
||||
//
|
||||
// KeyboardHandler scrolls a newly focused text field into view (scrollInputIntoView,
|
||||
// `scrollIntoView({ block: 'center' })`) once the keyboard is up. The pinned CJK /
|
||||
// Send on Enter field (#cjkInput) is position:fixed and already lifted above the
|
||||
// keyboard by updateLayoutForKeyboard(), so scrolling it into view only centred it in
|
||||
// its scrollable ancestors and pushed the terminal off screen. It must be skipped,
|
||||
// like xterm's own inputs, while ordinary inputs keep the behaviour.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const SOURCE = readFileSync(resolve(import.meta.dirname, '../src/web/public/mobile-handlers.js'), 'utf8');
|
||||
|
||||
function loadHandler() {
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
navigator: { userAgent: 'test', maxTouchPoints: 1 },
|
||||
window: { addEventListener: () => {}, matchMedia: () => ({ matches: false }), scrollTo: () => {} },
|
||||
document: {
|
||||
body: { classList: { add: () => {}, remove: () => {} } },
|
||||
addEventListener: () => {},
|
||||
getElementById: () => null,
|
||||
querySelector: () => null,
|
||||
},
|
||||
setTimeout: () => 1,
|
||||
clearTimeout: () => {},
|
||||
});
|
||||
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
|
||||
return (context as { __KH: any }).__KH;
|
||||
}
|
||||
|
||||
function element(tagName: string, { id = '', inside = '' }: { id?: string; inside?: string } = {}) {
|
||||
return { tagName, id, type: '', isContentEditable: false, closest: (sel: string) => (sel === inside ? {} : null) };
|
||||
}
|
||||
|
||||
describe('KeyboardHandler.isInputElement', () => {
|
||||
it('skips the pinned CJK field, which the keyboard layout positions itself', () => {
|
||||
expect(loadHandler().isInputElement(element('TEXTAREA', { id: 'cjkInput' }))).toBe(false);
|
||||
});
|
||||
|
||||
it('still skips xterm inputs and still scrolls ordinary fields into view', () => {
|
||||
const kh = loadHandler();
|
||||
expect(kh.isInputElement(element('TEXTAREA', { inside: '.xterm' }))).toBe(false);
|
||||
expect(kh.isInputElement(element('TEXTAREA', { id: 'someOtherField' }))).toBe(true);
|
||||
expect(kh.isInputElement(element('INPUT'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
function loadLayout({
|
||||
focused = 'cjkInput',
|
||||
offsetTop,
|
||||
height = 458,
|
||||
width = 390,
|
||||
innerHeight = 744,
|
||||
clientHeight = 744,
|
||||
}: {
|
||||
focused?: string;
|
||||
offsetTop: number;
|
||||
height?: number;
|
||||
width?: number;
|
||||
innerHeight?: number;
|
||||
clientHeight?: number;
|
||||
}) {
|
||||
const el = (offsetHeight = 36) => ({
|
||||
style: {} as Record<string, string>,
|
||||
offsetHeight,
|
||||
classList: { contains: () => true },
|
||||
});
|
||||
// .app is sized to the visual viewport (--app-height), which is what its fixed
|
||||
// children are placed against once it carries a transform.
|
||||
const nodes: Record<string, any> = {
|
||||
'.app': el(height),
|
||||
'.toolbar': el(),
|
||||
'.main': el(),
|
||||
'.keyboard-accessory-bar': el(),
|
||||
'.mobile-case-picker.active .mobile-case-picker-sheet': el(300),
|
||||
};
|
||||
const cjk = { ...el(), id: 'cjkInput' };
|
||||
const context = vm.createContext({
|
||||
console,
|
||||
navigator: { userAgent: 'test', maxTouchPoints: 1 },
|
||||
window: {
|
||||
addEventListener: () => {},
|
||||
matchMedia: () => ({ matches: false }),
|
||||
scrollTo: () => {},
|
||||
innerHeight,
|
||||
innerWidth: width, // MobileDetection (defined in the module) reads this
|
||||
visualViewport: { offsetTop, height },
|
||||
},
|
||||
document: {
|
||||
body: { classList: { add: () => {}, remove: () => {} } },
|
||||
documentElement: { clientHeight },
|
||||
addEventListener: () => {},
|
||||
activeElement: focused === 'cjkInput' ? cjk : { id: focused },
|
||||
getElementById: (id: string) => (id === 'cjkInput' ? cjk : null),
|
||||
querySelector: (sel: string) => nodes[sel] || null,
|
||||
},
|
||||
setTimeout: () => 1,
|
||||
clearTimeout: () => {},
|
||||
});
|
||||
vm.runInContext(`${SOURCE}\nglobalThis.__KH = KeyboardHandler;`, context, { filename: 'mobile-handlers.js' });
|
||||
const kh = (context as { __KH: any }).__KH;
|
||||
kh.keyboardVisible = true;
|
||||
kh.initialViewportHeight = 744;
|
||||
return { kh, nodes, cjk };
|
||||
}
|
||||
|
||||
describe('KeyboardHandler follows the visual-viewport pan on phones', () => {
|
||||
it('moves the app down by the pan and lifts nothing more (measured Android case)', () => {
|
||||
const { kh, nodes, cjk } = loadLayout({ offsetTop: 285 });
|
||||
kh.updateLayoutForKeyboard();
|
||||
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
|
||||
// .app bottom = 285 + 458 = 743, visual bottom = 743: the bars already sit on it.
|
||||
expect(nodes['.toolbar'].style.transform).toBe('');
|
||||
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
|
||||
expect(cjk.style.transform).toBe('');
|
||||
});
|
||||
|
||||
it('does not lift the bars twice on a partial pan', () => {
|
||||
// Mid-animation: offsetTop 100 in a 744 layout. Lifting by the layout gap (186px)
|
||||
// inside the shifted .app would float the bars 186px above the keyboard.
|
||||
const { kh, nodes, cjk } = loadLayout({ offsetTop: 100 });
|
||||
kh.updateLayoutForKeyboard();
|
||||
expect(nodes['.app'].style.transform).toBe('translateY(100px)');
|
||||
expect(nodes['.toolbar'].style.transform).toBe('');
|
||||
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('');
|
||||
expect(cjk.style.transform).toBe('');
|
||||
// The open case sheet is inside .app too (index.html #mobileCasePickerModal):
|
||||
// the layout gap on top of the shift floated it 186px above the keyboard.
|
||||
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('');
|
||||
});
|
||||
|
||||
it('keeps the old lift when there is no pan', () => {
|
||||
const { kh, nodes } = loadLayout({ offsetTop: 0 });
|
||||
kh.updateLayoutForKeyboard();
|
||||
expect(nodes['.app'].style.transform).toBe('');
|
||||
expect(nodes['.toolbar'].style.transform).toBe('translateY(-286px)');
|
||||
// Without a pan insideLift is the layout gap, so the case sheet keeps its lift
|
||||
// (test/mobile-case-sheet-keyboard-lift.test.ts).
|
||||
expect(nodes['.mobile-case-picker.active .mobile-case-picker-sheet'].style.transform).toBe('translateY(-286px)');
|
||||
});
|
||||
|
||||
it('follows a pan whatever has focus, so a focus change cannot drop the shift', () => {
|
||||
const { kh, nodes } = loadLayout({ focused: 'someOtherField', offsetTop: 285 });
|
||||
kh.updateLayoutForKeyboard();
|
||||
expect(nodes['.app'].style.transform).toBe('translateY(285px)');
|
||||
});
|
||||
|
||||
it('never shifts the app outside the phone layout (tablet landscape)', () => {
|
||||
const { kh, nodes } = loadLayout({ offsetTop: 285, width: 1024 });
|
||||
nodes['.app'].style.transform = 'translateY(285px)'; // left over from portrait
|
||||
kh.updateLayoutForKeyboard();
|
||||
expect(nodes['.app'].style.transform).toBe('');
|
||||
});
|
||||
|
||||
it('lifts the bars when iOS reports innerHeight as the shrunk visual height', () => {
|
||||
// Measured on an iPhone, first keyboard open: innerHeight 323 = visual height,
|
||||
// documentElement.clientHeight 640. Lifting by innerHeight - visual bottom gave 0.
|
||||
const { kh, nodes, cjk } = loadLayout({ offsetTop: 0, height: 323, innerHeight: 323, clientHeight: 640 });
|
||||
kh.updateLayoutForKeyboard();
|
||||
expect(nodes['.toolbar'].style.transform).toBe('translateY(-317px)');
|
||||
expect(nodes['.keyboard-accessory-bar'].style.transform).toBe('translateY(-317px)');
|
||||
expect(cjk.style.transform).toBe('translateY(-317px)');
|
||||
});
|
||||
|
||||
it('clears the shift when the layout resets', () => {
|
||||
const { kh, nodes } = loadLayout({ offsetTop: 285 });
|
||||
kh.updateLayoutForKeyboard();
|
||||
kh.resetLayout();
|
||||
expect(nodes['.app'].style.transform).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -41,8 +41,9 @@ function loadTerminalModule(): TerminalModule {
|
||||
console,
|
||||
setInterval: vi.fn(),
|
||||
clearInterval: vi.fn(),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
// Looked up per call, so a test's vi.useFakeTimers() reaches the cached module.
|
||||
setTimeout: (fn: () => void, ms?: number) => setTimeout(fn, ms),
|
||||
clearTimeout: (t: ReturnType<typeof setTimeout>) => clearTimeout(t),
|
||||
requestAnimationFrame: vi.fn(),
|
||||
HTMLCanvasElement: class HTMLCanvasElement {},
|
||||
WebSocket: { OPEN: 1 },
|
||||
@@ -547,6 +548,141 @@ describe('one-shot Ctrl through the CJK input field', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Send on Enter: a held answer goes out with Enter as its own write', () => {
|
||||
// _sendCjkPrompt is CjkInput's sendPrompt callback. Anything longer than one
|
||||
// character goes to the composer's _sendComposedPrompt with the session
|
||||
// captured at Enter, so the delayed Enter cannot follow a tab switch.
|
||||
function promptApp() {
|
||||
const { CodemanApp, bar } = loadTerminalModule();
|
||||
bar.clearCtrl();
|
||||
const app = Object.create(CodemanApp.prototype) as {
|
||||
activeSessionId: string | null;
|
||||
_sendCjkPrompt(text: string): boolean;
|
||||
};
|
||||
app.activeSessionId = 'session-a';
|
||||
const composed = vi
|
||||
.spyOn(bar as unknown as { _sendComposedPrompt: (s: string, t: string) => boolean }, '_sendComposedPrompt')
|
||||
.mockReturnValue(true);
|
||||
return { app, bar, composed };
|
||||
}
|
||||
|
||||
it('sends through the composer path, bound to the session active at Enter', () => {
|
||||
const { app, composed } = promptApp();
|
||||
expect(app._sendCjkPrompt('line one\nline two')).toBe(true);
|
||||
app.activeSessionId = 'session-b';
|
||||
expect(composed).toHaveBeenCalledWith('session-a', 'line one\nline two');
|
||||
composed.mockRestore();
|
||||
});
|
||||
|
||||
it('spends an armed one-shot Ctrl, like any multi-character chunk', () => {
|
||||
const { app, bar, composed } = promptApp();
|
||||
bar.toggleCtrl();
|
||||
app._sendCjkPrompt('x'.repeat(100));
|
||||
expect(bar.isCtrlArmed()).toBe(false);
|
||||
composed.mockRestore();
|
||||
});
|
||||
|
||||
it('types a single character, then Enter ~120 ms later to the same session', () => {
|
||||
// Codex folds an Enter that arrives in the same burst as the text into a
|
||||
// paste, even for `1\r`; a selection dialog ignores a pasted digit. Same
|
||||
// split as TmuxManager.sendInput (submitsAsKeys).
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const { app, composed } = promptApp();
|
||||
const writes: Array<[string, string, unknown]> = [];
|
||||
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (id: string, input: string, opts?: unknown) =>
|
||||
writes.push([id, input, opts]);
|
||||
expect(app._sendCjkPrompt('1')).toBe(true);
|
||||
expect(writes).toEqual([['session-a', '1', undefined]]);
|
||||
app.activeSessionId = 'session-b';
|
||||
vi.advanceTimersByTime(119);
|
||||
expect(writes).toHaveLength(1);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(writes[1]).toEqual(['session-a', '\r', { useMux: true }]);
|
||||
expect(composed).not.toHaveBeenCalled();
|
||||
composed.mockRestore();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('sends a lone digit without Enter while a permission or question dialog waits', () => {
|
||||
// The dialog acts on the digit keypress itself; an Enter 120 ms later would
|
||||
// confirm whatever the CLI shows next (a second permission prompt, unseen).
|
||||
// Same rule as the Approvals Inbox and the Discord bridge (awaitingChoice).
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
for (const hook of ['permission_prompt', 'elicitation_dialog']) {
|
||||
const { app, composed } = promptApp();
|
||||
const writes: Array<[string, string, unknown]> = [];
|
||||
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
|
||||
id: string,
|
||||
input: string,
|
||||
opts?: unknown
|
||||
) => writes.push([id, input, opts]);
|
||||
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
|
||||
['session-a', new Set([hook])],
|
||||
]);
|
||||
expect(app._sendCjkPrompt('2')).toBe(true);
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(writes).toEqual([['session-a', '2', undefined]]);
|
||||
composed.mockRestore();
|
||||
}
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the delayed Enter for a digit when only an idle prompt is pending, or for a letter in a dialog', () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const cases: Array<[string, string]> = [
|
||||
['idle_prompt', '1'],
|
||||
['permission_prompt', 'y'],
|
||||
];
|
||||
for (const [hook, text] of cases) {
|
||||
const { app, composed } = promptApp();
|
||||
const writes: Array<[string, string, unknown]> = [];
|
||||
(app as unknown as { _sendInputAsync: unknown })._sendInputAsync = (
|
||||
id: string,
|
||||
input: string,
|
||||
opts?: unknown
|
||||
) => writes.push([id, input, opts]);
|
||||
(app as unknown as { pendingHooks: Map<string, Set<string>> }).pendingHooks = new Map([
|
||||
['session-a', new Set([hook])],
|
||||
]);
|
||||
expect(app._sendCjkPrompt(text)).toBe(true);
|
||||
vi.advanceTimersByTime(120);
|
||||
expect(writes).toEqual([
|
||||
['session-a', text, undefined],
|
||||
['session-a', '\r', { useMux: true }],
|
||||
]);
|
||||
composed.mockRestore();
|
||||
}
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('pastes even a short word: only one character is typed', () => {
|
||||
const { app, composed } = promptApp();
|
||||
expect(app._sendCjkPrompt('yes')).toBe(true);
|
||||
expect(composed).toHaveBeenCalledWith('session-a', 'yes');
|
||||
composed.mockRestore();
|
||||
});
|
||||
|
||||
it('reports a refusal so the field keeps the text', () => {
|
||||
const { app, composed } = promptApp();
|
||||
composed.mockReturnValue(false);
|
||||
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
|
||||
app.activeSessionId = null;
|
||||
expect(app._sendCjkPrompt('x'.repeat(100))).toBe(false);
|
||||
expect(app._sendCjkPrompt('1')).toBe(false);
|
||||
expect(composed).toHaveBeenCalledTimes(1);
|
||||
composed.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('armed styling survives the light-skin overrides', () => {
|
||||
const mobileCss = readFileSync(resolve('src/web/public/mobile.css'), 'utf8');
|
||||
|
||||
|
||||
@@ -145,6 +145,28 @@ describe('terminal touch tap mouse guard', () => {
|
||||
expect(app._isMobileTerminalInputFocused()).toBe(true);
|
||||
});
|
||||
|
||||
it('a content touchstart blurs xterm input but leaves the pinned CJK field focused', () => {
|
||||
const { app, setActiveElement } = loadTerminalUiHarness();
|
||||
setActiveElement({ id: '', classList: { contains: (c: string) => c === 'xterm-helper-textarea' } });
|
||||
expect(app._contentTouchStartBlurs()).toBe(true);
|
||||
// A swipe that starts on the live screen must not close the keyboard the field owns.
|
||||
setActiveElement({ id: 'cjkInput', classList: { contains: () => false } });
|
||||
expect(app._contentTouchStartBlurs()).toBe(false);
|
||||
setActiveElement(null);
|
||||
expect(app._contentTouchStartBlurs()).toBe(true);
|
||||
});
|
||||
|
||||
it('the content touchstart only blurs through _contentTouchStartBlurs()', () => {
|
||||
// The touchstart listener lives in initTerminal, which this harness does not run,
|
||||
// so pin its one line: an unconditional blur there closes the pinned field's
|
||||
// keyboard on every swipe that starts on the live screen.
|
||||
const code = readFileSync(resolve(import.meta.dirname, '../src/web/public/terminal-ui.js'), 'utf8');
|
||||
const branch = code.slice(code.indexOf("if (touchStartIntent === 'content') {"));
|
||||
const body = branch.slice(0, branch.indexOf('// Hold still and this press becomes a text selection.'));
|
||||
expect(body).toContain('if (this._contentTouchStartBlurs()) this._blurMobileTerminalInput();');
|
||||
expect(body.match(/_blurMobileTerminalInput\(\)/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('routes a readback row to the TUI while keeping the prompt row as keyboard input', () => {
|
||||
const { app } = loadTerminalUiHarness();
|
||||
app.activeSessionId = 'sess-1';
|
||||
@@ -973,9 +995,27 @@ describe('terminal link tap', () => {
|
||||
app._isOutsideWorktreePath = () => false;
|
||||
windowRef.open = vi.fn();
|
||||
app.registerFilePathLinkProvider();
|
||||
return { app, windowRef, sent };
|
||||
return { app, windowRef, sent, setActiveElement: harness.setActiveElement };
|
||||
}
|
||||
|
||||
it('a link tap closes the keyboard of the pinned CJK field, which touchstart left focused', () => {
|
||||
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
|
||||
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
|
||||
const cjk = { id: 'cjkInput', classList: { contains: () => false }, blur: vi.fn() };
|
||||
setActiveElement(cjk);
|
||||
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
|
||||
expect(cjk.blur).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a link tap leaves focus alone otherwise (touchstart already blurred xterm input)', () => {
|
||||
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
|
||||
const { app, setActiveElement } = linkHarness([line, '', '❯ ']);
|
||||
const other = { id: '', classList: { contains: () => false }, blur: vi.fn() };
|
||||
setActiveElement(other);
|
||||
expect(app._handleMobileTerminalTap(at(line.indexOf('https')), false, 'content')).toBe('link');
|
||||
expect(other.blur).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens a URL under the finger in a new tab', () => {
|
||||
const line = 'Login at https://claude.ai/oauth/authorize?code=true&client_id=abc to finish';
|
||||
const { app, windowRef } = linkHarness([line, '', '❯ ']);
|
||||
|
||||
Reference in new issue
Block a user