fix(web): exact iOS caret, review fixes and round-eight items (#830)

Toolbar Enter spends one-shot Ctrl; Backspace finds the last grapheme with Segments.containing(); accessory Shift+Tab keeps the draft like a typed one.
Pass the captured session to Compose uploads, voice compose and held CJK drafts; clear Ctrl on deletion-only native edits; path picker clears predictions.
Clear xterm dead-key state on native commits; restore a borrowed clipboard field before classifying a key; overlay removeChar spans the pending/flushed boundary.
Place the trackpad caret from the overlay layout (getInputAnchor, committedText) or validated xterm cells, hiding when unproven; no end-minus-width arithmetic.
Grapheme-aware replay Backspace; docs, README rows, changeset and comment updates.
This commit is contained in:
Hadrien Kerlero committed 2026-11-21 21:16:13 +01:00
1 parent 414dd51eb2
commit cda5d96451
26 files changed
+1072 -170

No files matched your search

+13 -10
View File
@@ -17,10 +17,10 @@
* and a lone digit at a pending dialog goes without it). Shift+Enter is a
* newline, Esc clears, Backspace and the arrows reach the PTY only from an
* empty field, and so do the Ctrl shortcuts. Autocorrect is on. A held draft
* belongs to one session (_owner): clear() stashes it under that session and
* restoreDraft() brings it back when the session is shown again, except a
* clear({ discard: true }) (the keyboard bar's clear-line key), which throws
* it away.
* belongs to one session: a captured target takes precedence over _owner when
* clear() stashes it, and restoreDraft() brings it back when that session is
* shown again, except a clear({ discard: true }) (the keyboard bar's clear-line
* key), which throws it away.
*
* ## Android IME challenge
*
@@ -91,10 +91,10 @@ const CjkInput = (() => {
let _holdApplied = false;
// Send-on-Enter: held drafts of the sessions switched away from, by session id.
const _drafts = new Map();
// Send-on-Enter: the session the field's text belongs to (the one last shown,
// set by restoreDraft). clear() stashes a held draft under it, so every path
// that drops the active session before the next cleanup (goHome, the tile
// grid's _replaceTileGrid and _onTileAdoptedElsewhere) keeps the answer.
// Send-on-Enter: the session last shown, set by restoreDraft. A captured
// target takes precedence; otherwise clear() stashes a held draft under this
// owner, so paths that drop the active session before the next cleanup
// (goHome, _replaceTileGrid and _onTileAdoptedElsewhere) keep the answer.
let _owner = null;
const _listeners = {};
@@ -690,13 +690,15 @@ const CjkInput = (() => {
// nothing is stashed, any older stash of this session goes too, and the
// field keeps its owner, since the session shown has not changed.
if (_owner) _drafts.delete(_owner);
if (_hasTarget && _target) _drafts.delete(_target);
} else {
// Send-on-Enter: a held draft is stashed for the session it was typed
// for, whichever path got here. discardDraft() drops the owner of a
// removed session, so its text is not stashed again.
if (_hold && _owner) {
const sessionId = _hasTarget && _target ? _target : _owner;
if (_hold && sessionId) {
const draft = _strip(_textarea.value);
if (draft.trim()) _drafts.set(_owner, draft);
if (draft.trim()) _drafts.set(sessionId, draft);
}
_owner = null;
}
@@ -785,6 +787,7 @@ const CjkInput = (() => {
* clear(); restoreDraft() puts it back when that session is shown again.
*/
stashDraft(sessionId) {
if (_hasTarget && _target) sessionId = _target;
if (!_initialized || !_textarea || !_hold || !sessionId) return;
// An empty field leaves any stash alone: a draft only sits in the map
// while its session is not shown (restoreDraft takes it out), and the
+9 -5
View File
@@ -1231,7 +1231,9 @@ const KeyboardAccessoryBar = {
this.flushPendingThen('\t');
break;
case 'shift-tab':
this.sendKey('\x1b[Z');
// Cycles a mode, never edits the composer: leave the unsent draft in the
// overlay, as a typed Shift+Tab does.
this.sendKey('\x1b[Z', { keepDraft: true });
break;
case 'ctrl-o':
this.sendKey('\x0f');
@@ -1401,9 +1403,10 @@ const KeyboardAccessoryBar = {
/** Send a special key (arrow, escape, etc.) directly to the PTY.
* Bypasses tmux send-keys -l (literal mode) since escape sequences
* must be written raw to be interpreted as key presses by Ink. */
sendKey(escapeSequence) {
const sessionId = this._prepareInput(undefined, 'accessory-key', { flushEcho: true });
* must be written raw to be interpreted as key presses by Ink.
* `keepDraft` leaves the unsent local-echo draft in the overlay. */
sendKey(escapeSequence, { keepDraft = false } = {}) {
const sessionId = this._prepareInput(undefined, 'accessory-key', keepDraft ? undefined : { flushEcho: true });
if (!sessionId) return;
app._predictiveEcho?.clearPredictions();
app._enqueueInput(sessionId, [{ write: escapeSequence }]);
@@ -1422,6 +1425,7 @@ const KeyboardAccessoryBar = {
directoriesOnly: false,
onSelect: (path) => {
const targetPane = app._paneForSession?.(sessionId);
if (targetPane?.isPrimary && app._localEchoPolicy === 'predict') app._predictiveEcho?.clearPredictions();
if (targetPane?.isPrimary && app._localEchoEnabled && app._localEchoOverlay && !app._echoPassthroughSessions?.has(sessionId)) {
app._prepareExternalInput?.(targetPane, 'accessory-path');
app._localEchoOverlay.appendText(path);
@@ -1637,7 +1641,7 @@ const KeyboardAccessoryBar = {
};
syncUploadUi();
try {
const paths = await app._uploadAndInsertImages(images, { insert: false });
const paths = await app._uploadAndInsertImages(images, { insert: false, sessionId });
if (paths?.length) {
const currentOverlay =
this._composerOverlay?.isConnected && this._composerOverlay.dataset.sessionId === sessionId
+118 -45
View File
@@ -35,8 +35,8 @@
function editBetween(previous, next) {
// A pure append (including a combining mark or tone typed onto the last letter)
// is sent as-is, as on master: re-typing the extended cluster would make a
// code-point line editor (zsh) double the base letter.
// is sent as-is, as xterm sends it: re-typing the extended cluster would make
// a code-point line editor (zsh) double the base letter.
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
const a = graphemes(previous);
const b = graphemes(next);
@@ -213,29 +213,26 @@
const caret = guard(
'caret',
function () {
const value = Array.from(project(textarea.value));
const index = Array.from(project(textarea.value.slice(0, textarea.selectionEnd))).length;
const tail = value.slice(index).join('');
let cellsFromEnd = value.length - index;
const unicode = core.unicodeService;
if (unicode && typeof unicode.getStringCellWidth === 'function') {
try {
cellsFromEnd = unicode.getStringCellWidth(tail);
} catch (_) {
/* Older xterm builds use the code-point fallback. */
}
}
const text = project(textarea.value);
const offset = project(textarea.value.slice(0, textarea.selectionEnd)).length;
return {
visible:
!destroyed &&
textarea.ownerDocument.activeElement === textarea &&
!composing &&
textarea.selectionStart === textarea.selectionEnd &&
index < value.length,
cellsFromEnd,
offset < text.length &&
text === synced &&
!invalidated &&
!foreignSnapshot,
text,
offset,
// Advances only when an edit is reconciled (sent) or the line is reset;
// a borrowed clipboard value and its restoration leave it unchanged.
generation,
};
},
{ visible: false, cellsFromEnd: 0 }
{ visible: false, text: '', offset: 0, generation: 0 }
);
let previousCaret;
notifyCaret = function () {
@@ -243,7 +240,9 @@
if (
previousCaret &&
previousCaret.visible === current.visible &&
previousCaret.cellsFromEnd === current.cellsFromEnd
previousCaret.text === current.text &&
previousCaret.offset === current.offset &&
previousCaret.generation === current.generation
)
return;
previousCaret = current;
@@ -352,6 +351,7 @@
sendTransaction(ops);
} catch (error) {
record({ type: 'error', hook: 'sendTransaction', error });
invalidated = true;
}
}
// Empty/deletion-only compositions still settle the visual preview.
@@ -389,6 +389,7 @@
if (ev.type === 'keypress') return false;
if (ev.type === 'keyup') return textarea.ownerDocument.activeElement === textarea;
if (ev.type !== 'keydown') return true;
restoreForeign();
const kind = composing ? 'compose' : classifyKey(ev, textarea);
if (kind === 'compose') {
schedule();
@@ -418,7 +419,8 @@
target.addEventListener(type, listener, true);
}
patch(core, '_inputEvent', function () {
patch(core, '_inputEvent', function (ev) {
if (ev && ev.data && ev.inputType === 'insertText') core._unprocessedDeadKey = false;
return false;
});
patch(helper, '_handleAnyTextareaChanges', schedule);
@@ -499,6 +501,7 @@
direction: textarea.selectionDirection,
synced,
};
notifyCaret();
},
terminal.element
);
@@ -557,20 +560,80 @@
}
}
// This is a visual projection only: native caret changes never become keys.
// `options.anchor()` returns the viewport cell `{col, row}` where the VISIBLE line
// ends (where the next typed character would appear), 'hide' to hide the
// marker, or null/undefined to use xterm's cursor. A throwing anchor hides it. Codeman's local echo shows unsent text in an overlay while xterm's own
// cursor stays at the prompt, so the overlay must supply that anchor. Without an
// anchor the xterm cursor is used, which is right whenever every byte reached
// the PTY (local echo off, tiles).
// `options.subscribe(callback)` returns a disposer and is used to reposition
// when the anchor moves without an xterm render (overlay repaint).
// Visual only: an anchor(caret) supplies the exact viewport cell, 'hide', or
// null to resolve against parsed xterm cells. Neither mode moves native input.
// subscribe(callback) follows overlay repaints without an xterm render.
function bufferCaretAnchor(terminal, caret) {
const buffer = terminal.buffer.active;
const text = caret.text;
if (!text || caret.offset < 0 || caret.offset > text.length) return null;
let row = buffer.baseY + buffer.cursorY;
let col = buffer.cursorX;
let line = buffer.getLine(row);
// Read only as far as the native field and one preceding repetition.
function previousCell() {
while (line) {
if (col === 0) {
if (!line.isWrapped || row === 0) return null;
const following = line;
line = buffer.getLine(--row);
if (!line) return null;
col = terminal.cols;
// A wide glyph that did not fit leaves unused cells before a soft
// wrap. Validate that padding against the following glyph's width;
// ordinary blank cells (including printed spaces) remain text.
let padding = 0;
while (col - padding > 0) {
const cell = line.getCell(col - padding - 1);
if (!cell || cell.getWidth() !== 1 || cell.getChars()) break;
padding += 1;
}
const first = following.getCell(0);
if (padding && first && first.getWidth() > padding) col -= padding;
}
const cell = line.getCell(--col);
if (!cell) return null;
if (cell.getWidth() === 0) continue;
const chars = cell.getChars();
if (!chars) return null;
return { chars, col, row: row - buffer.viewportY };
}
return null;
}
const cells = [];
let remaining = text.length;
while (remaining > 0) {
const cell = previousCell();
if (!cell || cell.chars.length > remaining || text.slice(remaining - cell.chars.length, remaining) !== cell.chars)
return null;
cells.push(cell);
remaining -= cell.chars.length;
}
// A previous identical native-length suffix makes provenance ambiguous.
remaining = text.length;
while (remaining > 0) {
const cell = previousCell();
if (!cell || cell.chars.length > remaining || text.slice(remaining - cell.chars.length, remaining) !== cell.chars)
break;
remaining -= cell.chars.length;
}
if (remaining === 0) return null;
let offset = 0;
for (let i = cells.length - 1; i >= 0; i -= 1) {
const cell = cells[i];
if (caret.offset === offset) return { col: cell.col, row: cell.row };
offset += cell.chars.length;
if (caret.offset < offset) return null; // No cell inside a cluster.
}
return { col: buffer.cursorX, row: buffer.baseY + buffer.cursorY - buffer.viewportY };
}
function attachCaretMarker(terminal, owner, options) {
const anchor = options && typeof options.anchor === 'function' ? options.anchor : null;
const disposables = [];
let marker;
let disposed = false;
let caretGeneration = 0;
let awaitingEcho = false;
function dispose() {
if (disposed) return;
disposed = true;
@@ -586,6 +649,7 @@
try {
const screen = terminal.element && terminal.element.querySelector('.xterm-screen');
if (!screen || !owner || typeof owner.caret !== 'function' || typeof owner.onCaret !== 'function') return dispose;
caretGeneration = owner.caret().generation;
marker = screen.ownerDocument.createElement('div');
marker.className = 'ios-native-caret';
marker.setAttribute('aria-hidden', 'true');
@@ -597,41 +661,50 @@
const core = terminal._core;
const dimensions = core && core._renderService && core._renderService.dimensions;
const cell = dimensions && dimensions.css && dimensions.css.cell;
const buffer = terminal.buffer.active;
if (disposed || !caret.visible || !cell || !cell.width || !cell.height || !terminal.cols) {
marker.style.display = 'none';
return;
}
let end = null;
let target = null;
if (anchor) {
try {
end = anchor();
target = anchor(caret);
} catch (_) {
end = 'hide';
target = 'hide';
}
}
if (end === 'hide') {
if (target == null && !awaitingEcho) target = bufferCaretAnchor(terminal, caret);
if (!target || target === 'hide' || target.row < 0 || target.row >= terminal.rows) {
marker.style.display = 'none';
return;
}
if (end == null) end = { col: buffer.cursorX, row: buffer.cursorY + buffer.baseY - buffer.viewportY };
let column = end.col - caret.cellsFromEnd;
let row = end.row;
if (column < 0) {
const rows = Math.ceil(-column / terminal.cols);
column += rows * terminal.cols;
row -= rows;
}
marker.style.display = row < 0 || row >= terminal.rows ? 'none' : 'block';
marker.style.left = column * cell.width + 'px';
marker.style.top = row * cell.height + 'px';
marker.style.display = 'block';
marker.style.left = target.col * cell.width + 'px';
marker.style.top = target.row * cell.height + 'px';
marker.style.height = cell.height + 'px';
marker.style.backgroundColor = (terminal.options.theme && terminal.options.theme.cursor) || 'currentColor';
} catch (_) {
marker.style.display = 'none';
}
}
disposables.push(owner.onCaret(position));
disposables.push(
owner.onCaret((caret) => {
// Await parsed output only for a reconciled edit or reset (generation),
// never for a borrowed clipboard value or its restoration.
if (caret.generation !== caretGeneration) {
caretGeneration = caret.generation;
awaitingEcho = true;
}
position();
})
);
if (typeof terminal.onWriteParsed === 'function') {
const subscription = terminal.onWriteParsed(() => {
awaitingEcho = false;
position();
});
disposables.push(() => subscription.dispose());
}
for (const name of ['onRender', 'onCursorMove']) {
if (typeof terminal[name] === 'function') {
const subscription = terminal[name](position);
+2
View File
@@ -660,6 +660,7 @@
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
});
if (this._iosNativeInput) {
// Tiles have no local-echo overlay: resolve only from verified parsed cells.
this._iosCaretMarker = nativeInput.attachCaretMarker(this.terminal, this._iosNativeInput);
return;
}
@@ -678,6 +679,7 @@
// through unchanged, but it still disarms, so the next `c` stays a `c`.
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
ctrlIndex = ops.findIndex((data) => data !== '\x7f');
if (ctrlIndex === -1 && ops.includes('\x7f')) KeyboardAccessoryBar.clearCtrl?.();
}
// Keep replacement deletions: Ctrl changes only the insertion, once for
// this edit, never once per DEL. Tiles have no local echo to reconcile.
+13 -5
View File
@@ -766,7 +766,7 @@ Object.assign(CodemanApp.prototype, {
});
if (this._iosNativeInput) {
this._iosCaretMarker = window.CodemanIosNativeInput.attachCaretMarker?.(this.terminal, this._iosNativeInput, {
anchor: () => this._nativeInputAnchor(),
anchor: (caret) => this._nativeInputCaretAnchor(caret),
subscribe: (callback) => this._localEchoOverlay?.onLayout?.(callback),
});
return;
@@ -787,11 +787,16 @@ Object.assign(CodemanApp.prototype, {
}
},
_nativeInputAnchor() {
_nativeInputCaretAnchor(caret) {
const overlay = this._localEchoOverlay;
if (this._localEchoEnabled && !this._echoPassthroughSessions?.has(this.activeSessionId) &&
(overlay?.pendingText || overlay?.getFlushed?.().count)) {
return overlay.getInputEndAnchor?.() || 'hide';
if (
this._localEchoEnabled &&
!this._echoPassthroughSessions?.has(this.activeSessionId) &&
(overlay?.pendingText || overlay?.getFlushed?.().count)
) {
const committed = overlay.committedText;
if (typeof committed !== 'string' || !committed.endsWith(caret.text)) return 'hide';
return overlay.getInputAnchor?.(committed.length - caret.text.length + caret.offset) || 'hide';
}
return null;
},
@@ -865,6 +870,8 @@ Object.assign(CodemanApp.prototype, {
submitFromToolbar() {
const pane = this._focusedPane();
if (!pane?.terminal || !pane.sessionId || pane.tile?._destroyed || !this.sessions.has(pane.sessionId)) return;
// Typed Enter spends an armed one-shot Ctrl in onData; this CR skips onData.
if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.clearCtrl?.();
// The CR goes on the FIFO, not through xterm's triggerDataEvent(data, true),
// so its scrollOnUserInput never runs; scroll to the prompt as it would.
const terminal = pane.terminal;
@@ -887,6 +894,7 @@ Object.assign(CodemanApp.prototype, {
let ctrlIndex = -1;
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
ctrlIndex = ops.findIndex((data) => data !== '\x7f' && !window.CodemanTerminalInput?.isTerminalFocusOrMouseReport(data));
if (ctrlIndex === -1 && ops.includes('\x7f')) KeyboardAccessoryBar.clearCtrl?.();
}
for (let i = 0; i < ops.length; i++) {
const data = i === ctrlIndex ? KeyboardAccessoryBar.consumeCtrl(ops[i]) : ops[i];
+3 -2
View File
@@ -1097,6 +1097,7 @@ const VoiceInput = {
// If a compose overlay is already open, populate its textarea instead of recreating
const existingTextarea = document.querySelector('.voice-compose-overlay .paste-textarea');
if (existingTextarea) {
existingTextarea.closest('.voice-compose-overlay').dataset.targetSessionId = target;
existingTextarea.value = trimmed;
existingTextarea.focus();
existingTextarea.selectionStart = existingTextarea.selectionEnd = trimmed.length;
@@ -1216,10 +1217,10 @@ const VoiceInput = {
/** Show an editable compose overlay so the user can review/edit before sending */
_showComposeOverlay(text) {
const target = this._targetSession();
document.querySelector('.voice-compose-overlay')?.remove();
const overlay = document.createElement('div');
overlay.className = 'voice-compose-overlay paste-overlay';
overlay.dataset.targetSessionId = this._targetSession();
overlay.innerHTML = `
<div class="paste-dialog">
<textarea class="paste-textarea">${text.replace(/</g, '&lt;')}</textarea>
@@ -1234,7 +1235,7 @@ const VoiceInput = {
const send = () => {
const val = textarea.value.trim();
overlay.remove();
if (val) this._sendToTarget(target, val + '\r').catch(() => {});
if (val) this._sendToTarget(overlay.dataset.targetSessionId, val + '\r').catch(() => {});
};
const cancel = () => overlay.remove();
const newInput = () => {