mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
fix(web): synchronize iOS keyboard edits (#830)
Keep one native-input owner per iOS terminal and reconcile keyboard edits without duplicate producers. Preserve session-bound input ordering, local-echo Unicode deletion, and visual caret geometry. Cover device event sequences and lifecycle handoffs; remove obsolete helpers and source-text-only regression tests. Fixes #830
This commit is contained in:
1 parent
5548c17c4a
commit
c4b382b727
39 files changed
+5292
-824
No files matched your search
@@ -8,6 +8,7 @@ export type {
|
||||
ZerolagInputState,
|
||||
PromptFinder,
|
||||
PromptPosition,
|
||||
InputEndAnchor,
|
||||
CellDimensions,
|
||||
} from './types.js';
|
||||
export type { PredictiveEchoOptions, PredictionState } from './predictive-echo-addon.js';
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { RenderParams, FontStyle, XtermTerminal } from './types.js';
|
||||
import type { RenderParams, FontStyle, XtermTerminal, InputEndAnchor } from './types.js';
|
||||
|
||||
// ─── CJK / fullwidth character width detection ───────────────────────
|
||||
|
||||
@@ -102,7 +102,7 @@ function holdsOnlyRendered(container: HTMLDivElement, state: RenderedLines): boo
|
||||
* DOM work, layout and paint, which a long prompt on a phone paid for in
|
||||
* dropped frames.
|
||||
*/
|
||||
export function renderOverlay(container: HTMLDivElement, params: RenderParams): void {
|
||||
export function renderOverlay(container: HTMLDivElement, params: RenderParams): InputEndAnchor | null {
|
||||
const {
|
||||
lines,
|
||||
compositionStart,
|
||||
@@ -233,11 +233,11 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
|
||||
state.lines.length = visibleLines.length;
|
||||
state.lineKeys.length = visibleLines.length;
|
||||
|
||||
// Block cursor at end of last line (use visual width for CJK support)
|
||||
if (showCursor) {
|
||||
const lastLine = visibleLines[visibleLines.length - 1];
|
||||
const lastLineLeft = visibleLines.length === 1 && keepsPromptLine ? startCol : 0;
|
||||
const cursorCol = lastLineLeft + stringCellWidth(terminal, lastLine);
|
||||
// Publish the text end from this layout even when the block cursor is hidden.
|
||||
const lastLine = visibleLines[visibleLines.length - 1];
|
||||
const lastLineLeft = visibleLines.length === 1 && keepsPromptLine ? startCol : 0;
|
||||
const cursorCol = lastLineLeft + stringCellWidth(terminal, lastLine ?? '');
|
||||
if (showCursor && lastLine !== undefined) {
|
||||
if (cursorCol < totalCols) {
|
||||
const cursor = document.createElement('span');
|
||||
cursor.style.cssText = 'position:absolute;display:inline-block';
|
||||
@@ -252,6 +252,7 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
|
||||
}
|
||||
|
||||
container.style.display = '';
|
||||
return lastLine === undefined ? null : { col: cursorCol, row: topRow + visibleLines.length - 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -66,6 +66,14 @@ export interface PromptPosition {
|
||||
col: number;
|
||||
}
|
||||
|
||||
/** Viewport position at the end of the visible overlay input. */
|
||||
export interface InputEndAnchor {
|
||||
/** Column (0-based); equals the column count at a full line's right edge. */
|
||||
col: number;
|
||||
/** Viewport-relative row (0 = top of viewport). */
|
||||
row: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt detection strategy.
|
||||
*
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
PromptPosition,
|
||||
PromptFinder,
|
||||
FontStyle,
|
||||
InputEndAnchor,
|
||||
} from './types.js';
|
||||
import { getCellDimensions } from './cell-dimensions.js';
|
||||
import { findPrompt, readTextAfterPrompt, promptRowInViewport } from './prompt-finder.js';
|
||||
@@ -18,6 +19,13 @@ const DEFAULT_BG = '#0d0d0d';
|
||||
const DEFAULT_FG = '#eeeeee';
|
||||
const DEFAULT_CURSOR = '#e0e0e0';
|
||||
|
||||
/** UTF-16 width of the final code point (one for an empty legacy flushed string). */
|
||||
function lastCodePointWidth(text: string): number {
|
||||
const last = text.charCodeAt(text.length - 1);
|
||||
const previous = text.charCodeAt(text.length - 2);
|
||||
return last >= 0xdc00 && last <= 0xdfff && previous >= 0xd800 && previous <= 0xdbff ? 2 : 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* xterm.js addon that provides instant keystroke feedback via a DOM overlay.
|
||||
*
|
||||
@@ -76,6 +84,8 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
// Render cache
|
||||
private _lastRenderKey = '';
|
||||
private _lastPromptPos: PromptPosition | null = null;
|
||||
private _inputEndAnchor: InputEndAnchor | null = null;
|
||||
private _layoutListeners = new Set<() => void>();
|
||||
|
||||
// Font cache
|
||||
private _font: FontStyle = {
|
||||
@@ -130,6 +140,8 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
try {
|
||||
if (!promptRowInViewport(this._terminal!)) {
|
||||
this._overlay!.style.display = 'none';
|
||||
this._inputEndAnchor = null;
|
||||
this._notifyLayout();
|
||||
if (this._scrollTimer) {
|
||||
clearTimeout(this._scrollTimer);
|
||||
this._scrollTimer = null;
|
||||
@@ -171,6 +183,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
this._scrollViewport = null;
|
||||
this._scrollHandler = null;
|
||||
this._terminal = null;
|
||||
this._layoutListeners.clear();
|
||||
}
|
||||
|
||||
// ─── Input methods ────────────────────────────────────────────────
|
||||
@@ -196,7 +209,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the last character from the overlay.
|
||||
* Remove the last Unicode code point from the overlay.
|
||||
*
|
||||
* Cascade order:
|
||||
* 1. Remove from `pendingText` if non-empty → returns `'pending'`
|
||||
@@ -219,7 +232,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
const droppedComposition = this._composition.length > 0;
|
||||
this._composition = '';
|
||||
if (this._pendingText.length > 0) {
|
||||
this._pendingText = this._pendingText.slice(0, -1);
|
||||
this._pendingText = this._pendingText.slice(0, -lastCodePointWidth(this._pendingText));
|
||||
if (this._pendingText.length > 0 || this._flushedOffset > 0) {
|
||||
this._render();
|
||||
} else {
|
||||
@@ -228,23 +241,13 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
return 'pending';
|
||||
}
|
||||
|
||||
if (this._flushedOffset > 0) {
|
||||
this._flushedOffset--;
|
||||
this._flushedText = this._flushedText.slice(0, -1);
|
||||
if (this._flushedOffset > 0) {
|
||||
this._render();
|
||||
} else {
|
||||
this._hide();
|
||||
}
|
||||
return 'flushed';
|
||||
}
|
||||
|
||||
// Both empty — try detecting text already on the prompt line
|
||||
// (handles tab completion, arrow-key edits, etc.)
|
||||
this._detectBufferText();
|
||||
// (handles tab completion, arrow-key edits, etc.).
|
||||
if (this._flushedOffset === 0) this._detectBufferText();
|
||||
if (this._flushedOffset > 0) {
|
||||
this._flushedOffset--;
|
||||
this._flushedText = this._flushedText.slice(0, -1);
|
||||
const width = lastCodePointWidth(this._flushedText);
|
||||
this._flushedOffset -= width;
|
||||
this._flushedText = this._flushedText.slice(0, -width);
|
||||
if (this._flushedOffset > 0) {
|
||||
this._render();
|
||||
} else {
|
||||
@@ -320,6 +323,19 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
|
||||
// ─── Rendering control ────────────────────────────────────────────
|
||||
|
||||
/** Viewport text end from the renderer's last visible layout, or null when hidden. */
|
||||
getInputEndAnchor(): InputEndAnchor | null {
|
||||
return this._inputEndAnchor ? { ...this._inputEndAnchor } : null;
|
||||
}
|
||||
|
||||
/** Subscribe after each layout, including hide. Returns an unsubscribe function. */
|
||||
onLayout(cb: () => void): () => void {
|
||||
this._layoutListeners.add(cb);
|
||||
return () => {
|
||||
this._layoutListeners.delete(cb);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Force a re-render of the overlay at the current prompt position.
|
||||
* Call after terminal resets, buffer reloads, or full-screen redraws
|
||||
@@ -578,22 +594,34 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
}
|
||||
}
|
||||
|
||||
private _notifyLayout(): void {
|
||||
for (const cb of this._layoutListeners) {
|
||||
try {
|
||||
cb();
|
||||
} catch {
|
||||
// A visual observer must not interrupt input or the other listeners.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _hide(): void {
|
||||
if (!this._overlay) return;
|
||||
this._lastRenderKey = '';
|
||||
this._lastPromptPos = null;
|
||||
this._overlay.innerHTML = '';
|
||||
this._overlay.style.display = 'none';
|
||||
this._inputEndAnchor = null;
|
||||
this._notifyLayout();
|
||||
}
|
||||
|
||||
private _render(): void {
|
||||
if (!this._terminal || !this._overlay) return;
|
||||
if (!this._hasContent()) {
|
||||
this._overlay.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
let layoutChanged = true;
|
||||
try {
|
||||
if (!this._hasContent()) {
|
||||
this._overlay.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
const buf = this._terminal.buffer.active;
|
||||
|
||||
// Hide the overlay while the cursor row is scrolled out of view
|
||||
@@ -612,7 +640,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
} else {
|
||||
this._lastPromptPos = prompt;
|
||||
}
|
||||
} else if (!this._lastPromptPos) {
|
||||
} else {
|
||||
this._overlay.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
@@ -658,7 +686,10 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
// redundant render.
|
||||
const totalRows = this._layoutRows();
|
||||
const renderKey = `${displayText}:${compositionStart}:${startCol}:${activePrompt.row}:${activePrompt.col}:${totalCols}:${totalRows}:${this._flushedOffset}`;
|
||||
if (renderKey === this._lastRenderKey && this._overlay.style.display !== 'none') return;
|
||||
if (renderKey === this._lastRenderKey && this._overlay.style.display !== 'none') {
|
||||
layoutChanged = false;
|
||||
return;
|
||||
}
|
||||
this._lastRenderKey = renderKey;
|
||||
|
||||
// Split into visual lines by column width (CJK wide chars = 2 cols)
|
||||
@@ -695,7 +726,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
|
||||
const cursorColor = this._options.cursorColor ?? this._terminal.options.theme?.cursor ?? DEFAULT_CURSOR;
|
||||
|
||||
renderOverlay(this._overlay, {
|
||||
this._inputEndAnchor = renderOverlay(this._overlay, {
|
||||
lines,
|
||||
compositionStart: this._composition ? compositionStart : undefined,
|
||||
startCol,
|
||||
@@ -718,6 +749,9 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
this._overlay.innerHTML = '';
|
||||
this._overlay.style.display = 'none';
|
||||
}
|
||||
} finally {
|
||||
if (this._overlay.style.display === 'none') this._inputEndAnchor = null;
|
||||
if (layoutChanged) this._notifyLayout();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import { createMockTerminal } from './helpers.js';
|
||||
import { ZerolagInputAddon } from '../src/zerolag-input-addon.js';
|
||||
import type { InputEndAnchor } from '../src/types.js';
|
||||
|
||||
function setup(lines: string[] = ['$ '], promptChar = '$') {
|
||||
const mock = createMockTerminal({ buffer: { lines } });
|
||||
@@ -91,6 +92,41 @@ describe('ZerolagInputAddon', () => {
|
||||
expect(addon.pendingText).toBe('a');
|
||||
});
|
||||
|
||||
it('removes a whole pending emoji without changing flushed UTF-16 offsets', () => {
|
||||
const { addon } = tracked();
|
||||
addon.setFlushed(2, 'ab');
|
||||
addon.appendText('c😀');
|
||||
expect(addon.removeChar()).toBe('pending');
|
||||
expect(addon.pendingText).toBe('c');
|
||||
expect(addon.getFlushed()).toEqual({ count: 2, text: 'ab' });
|
||||
expect(addon.removeChar()).toBe('pending');
|
||||
expect(addon.pendingText).toBe('');
|
||||
});
|
||||
|
||||
it('removes a whole flushed emoji and subtracts its UTF-16 width', () => {
|
||||
const { addon } = tracked();
|
||||
addon.setFlushed(3, 'a😀');
|
||||
expect(addon.removeChar()).toBe('flushed');
|
||||
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
|
||||
expect(addon.removeChar()).toBe('flushed');
|
||||
expect(addon.getFlushed()).toEqual({ count: 0, text: '' });
|
||||
expect(addon.state.visible).toBe(false);
|
||||
});
|
||||
|
||||
it('removes a whole emoji from newly detected buffer text', () => {
|
||||
const { addon } = tracked(['$ a😀']);
|
||||
expect(addon.removeChar()).toBe('flushed');
|
||||
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
|
||||
});
|
||||
|
||||
it('hides after deleting the only pending emoji', () => {
|
||||
const { addon } = tracked();
|
||||
addon.appendText('😀');
|
||||
expect(addon.removeChar()).toBe('pending');
|
||||
expect(addon.pendingText).toBe('');
|
||||
expect(addon.state.visible).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when nothing to remove', () => {
|
||||
const { addon } = tracked();
|
||||
expect(addon.removeChar()).toBe(false);
|
||||
@@ -831,3 +867,164 @@ describe('setRowLimit', () => {
|
||||
expect(overlay().style.top).toBe(`${9 * 17}px`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('input end anchor and layout subscriptions', () => {
|
||||
function layoutSetup({ cols = 20, rows = 6, promptRow = 1, showCursor = true } = {}) {
|
||||
const lines = Array.from({ length: rows }, (_, i) => (i === promptRow ? '$ ' : ''));
|
||||
const mock = createMockTerminal({ buffer: { lines }, cols, rows });
|
||||
const addon = new ZerolagInputAddon({
|
||||
prompt: { type: 'character', char: '$', offset: 2 },
|
||||
showCursor,
|
||||
});
|
||||
mock.terminal.loadAddon(addon);
|
||||
cleanups.push(() => {
|
||||
addon.dispose();
|
||||
mock.cleanup();
|
||||
});
|
||||
return { addon, mock };
|
||||
}
|
||||
|
||||
it('returns the text end on a short line, including flushed and wide characters', () => {
|
||||
const { addon } = layoutSetup();
|
||||
addon.setFlushed(1, 'a');
|
||||
addon.appendText('你😀');
|
||||
expect(addon.getInputEndAnchor()).toEqual({ col: 7, row: 1 });
|
||||
const anchor = addon.getInputEndAnchor()!;
|
||||
anchor.col = 0;
|
||||
expect(addon.getInputEndAnchor()).toEqual({ col: 7, row: 1 });
|
||||
});
|
||||
|
||||
it('returns the short text end rather than the row edge with showCursor false', () => {
|
||||
const { addon, mock } = layoutSetup({ showCursor: false });
|
||||
addon.appendText('abc');
|
||||
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 1 });
|
||||
const overlay = mock.terminal.element.querySelector('.xterm-screen')!.lastElementChild!;
|
||||
expect(overlay.children.length).toBe(1); // line only, no cursor span
|
||||
});
|
||||
|
||||
it('returns the unindented end of a wrapped line', () => {
|
||||
const { addon } = layoutSetup();
|
||||
addon.appendText('x'.repeat(23)); // 18 cells on the first line, then 5
|
||||
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 2 });
|
||||
});
|
||||
|
||||
it('uses the renderer bottom clamp rather than the original prompt row', () => {
|
||||
const { addon } = layoutSetup({ promptRow: 5 });
|
||||
addon.appendText('x'.repeat(23));
|
||||
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 5 });
|
||||
});
|
||||
|
||||
it('follows a narrowed row limit and a clipped tail without prompt indentation', () => {
|
||||
const { addon } = layoutSetup({ promptRow: 5 });
|
||||
addon.appendText('x'.repeat(43)); // lines of 18, 20 and 5 cells
|
||||
addon.setRowLimit(2);
|
||||
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 1 });
|
||||
addon.setRowLimit(1);
|
||||
expect(addon.getInputEndAnchor()).toEqual({ col: 5, row: 0 });
|
||||
});
|
||||
|
||||
it('reports the right edge of an exactly full line without requiring a cursor span', () => {
|
||||
const { addon } = layoutSetup();
|
||||
addon.appendText('x'.repeat(18));
|
||||
expect(addon.getInputEndAnchor()).toEqual({ col: 20, row: 1 });
|
||||
});
|
||||
|
||||
it('returns null before showing, after clear, and after dispose', () => {
|
||||
const { addon } = layoutSetup();
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
addon.appendText('abc');
|
||||
addon.clear();
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
addon.appendText('x');
|
||||
addon.dispose();
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null after deleting or clearing the last visible text', () => {
|
||||
const { addon } = layoutSetup();
|
||||
addon.addChar('x');
|
||||
addon.removeChar();
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
addon.setFlushed(1, 'x');
|
||||
addon.clearFlushed();
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when a previously visible prompt is no longer found', () => {
|
||||
const { addon, mock } = layoutSetup();
|
||||
addon.appendText('abc');
|
||||
mock.setLines(['output without a prompt']);
|
||||
addon.rerender();
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
expect(addon.state.visible).toBe(false);
|
||||
});
|
||||
|
||||
it('publishes null on a scroll hide before repainting', () => {
|
||||
const { addon, mock } = layoutSetup();
|
||||
addon.appendText('abc');
|
||||
const anchors: (InputEndAnchor | null)[] = [];
|
||||
addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
|
||||
mock.setScroll(0, 30);
|
||||
mock.terminal.element.querySelector('.xterm-viewport')!.dispatchEvent(new Event('scroll'));
|
||||
expect(anchors).toEqual([null]);
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
});
|
||||
|
||||
it('publishes null when render finds the cursor outside the viewport', () => {
|
||||
const { addon, mock } = layoutSetup();
|
||||
addon.appendText('abc');
|
||||
mock.setScroll(0, 30);
|
||||
addon.rerender();
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
});
|
||||
|
||||
it('publishes null when cell dimensions disappear', () => {
|
||||
const { addon, mock } = layoutSetup();
|
||||
addon.appendText('abc');
|
||||
Reflect.deleteProperty(mock.terminal._core._renderService, 'dimensions');
|
||||
addon.rerender();
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
});
|
||||
|
||||
it('publishes null on render failure while preserving the pending input', () => {
|
||||
const { addon } = layoutSetup();
|
||||
addon.appendText('abc');
|
||||
addon.setPrompt({
|
||||
type: 'custom',
|
||||
find: () => {
|
||||
throw new Error('buffer unavailable');
|
||||
},
|
||||
});
|
||||
expect(addon.getInputEndAnchor()).toBeNull();
|
||||
expect(addon.pendingText).toBe('abc');
|
||||
});
|
||||
|
||||
it('notifies after each layout and hide, and stops after disposal of the listener', () => {
|
||||
const { addon } = layoutSetup();
|
||||
const anchors: (InputEndAnchor | null)[] = [];
|
||||
const dispose = addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
|
||||
addon.addChar('a');
|
||||
addon.addChar('b');
|
||||
addon.rerender();
|
||||
addon.clear();
|
||||
expect(anchors).toEqual([{ col: 3, row: 1 }, { col: 4, row: 1 }, { col: 4, row: 1 }, null]);
|
||||
dispose();
|
||||
dispose();
|
||||
addon.addChar('c');
|
||||
addon.clear();
|
||||
expect(anchors).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('isolates listener failures from rendering and other listeners', () => {
|
||||
const { addon } = layoutSetup();
|
||||
addon.onLayout(() => {
|
||||
throw new Error('observer failed');
|
||||
});
|
||||
const anchors: (InputEndAnchor | null)[] = [];
|
||||
addon.onLayout(() => anchors.push(addon.getInputEndAnchor()));
|
||||
expect(() => addon.appendText('abc')).not.toThrow();
|
||||
expect(addon.state.visible).toBe(true);
|
||||
expect(() => addon.clear()).not.toThrow();
|
||||
expect(anchors).toEqual([{ col: 5, row: 1 }, null]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user