mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
fix(web): delete one grapheme per iOS Backspace, keep the recovery fallback (#830)
Count native edits and overlay deletions in grapheme clusters (Intl.Segmenter, code-point fallback), so one Backspace on a multi-code-point emoji sends one DEL. Toolbar Enter with echo off tells the codex predictor about the CR, clearing its predictions as typed Enter does. Fall back to the keyCode-229 recovery when the iOS owner refuses to start, in the main pane and tiles.
This commit is contained in:
1 parent
05fc2f990b
commit
71c7d01d02
8 files changed
+184
-24
No files matched your search
@@ -19,8 +19,33 @@ 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 {
|
||||
type GraphemeSegmenter = {
|
||||
segment(input: string): Iterable<{ segment: string }>;
|
||||
};
|
||||
|
||||
const GRAPHEME_SEGMENTER: GraphemeSegmenter | null = (() => {
|
||||
try {
|
||||
const Segmenter = (
|
||||
Intl as typeof Intl & {
|
||||
Segmenter?: new (locale?: string, options?: { granularity: 'grapheme' }) => GraphemeSegmenter;
|
||||
}
|
||||
).Segmenter;
|
||||
return Segmenter ? new Segmenter(undefined, { granularity: 'grapheme' }) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
/** UTF-16 width of the final grapheme cluster (one for an empty legacy flushed string). */
|
||||
function lastGraphemeWidth(text: string): number {
|
||||
if (GRAPHEME_SEGMENTER) {
|
||||
let width = 1;
|
||||
for (const { segment } of GRAPHEME_SEGMENTER.segment(text)) {
|
||||
width = segment.length;
|
||||
}
|
||||
return width;
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -209,7 +234,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the last Unicode code point from the overlay.
|
||||
* Remove the last grapheme cluster (one user-perceived character).
|
||||
*
|
||||
* Cascade order:
|
||||
* 1. Remove from `pendingText` if non-empty → returns `'pending'`
|
||||
@@ -232,7 +257,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, -lastCodePointWidth(this._pendingText));
|
||||
this._pendingText = this._pendingText.slice(0, -lastGraphemeWidth(this._pendingText));
|
||||
if (this._pendingText.length > 0 || this._flushedOffset > 0) {
|
||||
this._render();
|
||||
} else {
|
||||
@@ -245,7 +270,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
||||
// (handles tab completion, arrow-key edits, etc.).
|
||||
if (this._flushedOffset === 0) this._detectBufferText();
|
||||
if (this._flushedOffset > 0) {
|
||||
const width = lastCodePointWidth(this._flushedText);
|
||||
const width = lastGraphemeWidth(this._flushedText);
|
||||
this._flushedOffset -= width;
|
||||
this._flushedText = this._flushedText.slice(0, -width);
|
||||
if (this._flushedOffset > 0) {
|
||||
|
||||
@@ -127,6 +127,28 @@ describe('ZerolagInputAddon', () => {
|
||||
expect(addon.state.visible).toBe(false);
|
||||
});
|
||||
|
||||
const graphemeCases = [
|
||||
['red heart', '\u2764\uFE0F'],
|
||||
['skin-tone thumbs up', '\u{1F44D}\u{1F3FD}'],
|
||||
['flag', '\u{1F1EB}\u{1F1F7}'],
|
||||
['ZWJ family', '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}'],
|
||||
];
|
||||
|
||||
it.each(graphemeCases)('removes a whole pending %s grapheme', (_name, emoji) => {
|
||||
const { addon } = tracked();
|
||||
addon.appendText('ok' + emoji);
|
||||
expect(addon.removeChar()).toBe('pending');
|
||||
expect(addon.pendingText).toBe('ok');
|
||||
});
|
||||
|
||||
it.each(graphemeCases)('removes a whole flushed %s grapheme and subtracts its UTF-16 width', (_name, emoji) => {
|
||||
const { addon } = tracked();
|
||||
const text = 'ok' + emoji;
|
||||
addon.setFlushed(text.length, text);
|
||||
expect(addon.removeChar()).toBe('flushed');
|
||||
expect(addon.getFlushed()).toEqual({ count: 2, text: 'ok' });
|
||||
});
|
||||
|
||||
it('returns false when nothing to remove', () => {
|
||||
const { addon } = tracked();
|
||||
expect(addon.removeChar()).toBe(false);
|
||||
|
||||
@@ -15,9 +15,27 @@
|
||||
(function (global) {
|
||||
'use strict';
|
||||
|
||||
// WebKit removes one grapheme cluster per Backspace, and Claude Code and Codex
|
||||
// delete one grapheme per DEL, so an edit is counted in graphemes: a red heart,
|
||||
// a skin-tone emoji, a flag or a ZWJ family is one DEL, as it was through xterm.
|
||||
// Code points stand in where Intl.Segmenter is missing.
|
||||
const graphemeSegmenter = (function () {
|
||||
try {
|
||||
return typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'
|
||||
? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
|
||||
: null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
function graphemes(text) {
|
||||
return graphemeSegmenter ? Array.from(graphemeSegmenter.segment(text), (part) => part.segment) : Array.from(text);
|
||||
}
|
||||
|
||||
function editBetween(previous, next) {
|
||||
const a = Array.from(previous);
|
||||
const b = Array.from(next);
|
||||
const a = graphemes(previous);
|
||||
const b = graphemes(next);
|
||||
let prefix = 0;
|
||||
while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix += 1;
|
||||
return { deleted: a.length - prefix, inserted: b.slice(prefix).join('') };
|
||||
|
||||
@@ -661,7 +661,11 @@
|
||||
});
|
||||
if (this._iosNativeInput) {
|
||||
this._iosCaretMarker = nativeInput.attachCaretMarker(this.terminal, this._iosNativeInput);
|
||||
return;
|
||||
}
|
||||
// create() refused (screen reader, missing xterm internals): keep the
|
||||
// soft-keyboard recovery rather than leaving the tile with neither.
|
||||
this._createKeyCode229Recovery();
|
||||
}
|
||||
|
||||
_sendNativeInputTransaction(ops) {
|
||||
|
||||
@@ -764,21 +764,26 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
|
||||
});
|
||||
this._iosCaretMarker = window.CodemanIosNativeInput.attachCaretMarker?.(this.terminal, this._iosNativeInput, {
|
||||
anchor: () => this._nativeInputAnchor(),
|
||||
subscribe: (callback) => this._localEchoOverlay?.onLayout?.(callback),
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
this._keyCode229Recovery = window.CodemanKeyCode229Recovery?.create?.({
|
||||
textarea: this.terminal.textarea,
|
||||
emitRecovered: (data) => this._handleTerminalData(data, this.activeSessionId),
|
||||
getCompositionHelper: () => this.terminal?._core?._compositionHelper,
|
||||
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
|
||||
if (this._iosNativeInput) {
|
||||
this._iosCaretMarker = window.CodemanIosNativeInput.attachCaretMarker?.(this.terminal, this._iosNativeInput, {
|
||||
anchor: () => this._nativeInputAnchor(),
|
||||
subscribe: (callback) => this._localEchoOverlay?.onLayout?.(callback),
|
||||
});
|
||||
} catch {
|
||||
this._keyCode229Recovery = null;
|
||||
return;
|
||||
}
|
||||
// create() refused (screen reader, missing xterm internals): keep master's
|
||||
// soft-keyboard recovery rather than leaving iOS with neither.
|
||||
this._iosNativeInput = null;
|
||||
}
|
||||
try {
|
||||
this._keyCode229Recovery = window.CodemanKeyCode229Recovery?.create?.({
|
||||
textarea: this.terminal.textarea,
|
||||
emitRecovered: (data) => this._handleTerminalData(data, this.activeSessionId),
|
||||
getCompositionHelper: () => this.terminal?._core?._compositionHelper,
|
||||
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
|
||||
});
|
||||
} catch {
|
||||
this._keyCode229Recovery = null;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -829,6 +834,9 @@ Object.assign(CodemanApp.prototype, {
|
||||
this._enqueueInput(sessionId, [{ write: text }, { gap: 80 }, { write: '\r' }]);
|
||||
} else {
|
||||
this._echoPassthroughSessions?.delete(sessionId);
|
||||
// The CR bypasses onData here, so tell the codex predictor about it as
|
||||
// typed Enter does (it clears the prediction run).
|
||||
this._predictHookOnData('\r');
|
||||
this._enqueueInput(sessionId, [{ write: '\r' }]);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -936,6 +936,35 @@ describe('native main transactions and boundaries', () => {
|
||||
app._initTerminalInputOwner();
|
||||
expect(recovery.destroy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('falls back to the recovery when the iOS module is supported but create() refuses', () => {
|
||||
const { app, wire, context } = harness();
|
||||
const native = { isSupported: () => true, create: vi.fn(() => null), attachCaretMarker: vi.fn() };
|
||||
const create = vi.fn((_options: { emitRecovered: (data: string) => void }) => ({ destroy: vi.fn() }));
|
||||
context.window.CodemanIosNativeInput = native;
|
||||
context.window.CodemanKeyCode229Recovery = { create };
|
||||
app._localEchoEnabled = false;
|
||||
app._initTerminalInputOwner();
|
||||
expect(native.create).toHaveBeenCalledOnce();
|
||||
expect(native.attachCaretMarker).not.toHaveBeenCalled();
|
||||
expect(app._iosNativeInput).toBeNull();
|
||||
expect(create).toHaveBeenCalledOnce();
|
||||
create.mock.calls[0][0].emitRecovered('recovered');
|
||||
expect(wire).toEqual([['old', 'recovered']]);
|
||||
});
|
||||
|
||||
it('toolbar Enter with echo off clears codex predictions like typed Enter', () => {
|
||||
const { app, wire } = harness();
|
||||
// The harness stubs the hook; run the real one from terminal-ui.js.
|
||||
delete app._predictHookOnData;
|
||||
app._localEchoEnabled = false;
|
||||
app._localEchoPolicy = 'predict';
|
||||
app._predictiveEcho = { clearPredictions: vi.fn(), predictChar: vi.fn(), predictBackspace: vi.fn() };
|
||||
app._submitMainInput('old');
|
||||
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalledOnce();
|
||||
expect(wire).toEqual([['old', '\r']]);
|
||||
});
|
||||
|
||||
it('settles and resets native ownership before inserting external text into the overlay', () => {
|
||||
const { app } = harness();
|
||||
app._iosNativeInput = {
|
||||
|
||||
@@ -159,7 +159,12 @@ type Listener = (event: Event) => void;
|
||||
const DEL = '\x7f';
|
||||
const dels = (count: number) => Array(count).fill(DEL);
|
||||
const project = (value: string) => value.replace(/\r\n|[\r\n]/g, ' ');
|
||||
const trimPoint = (value: string) => Array.from(value).slice(0, -1).join('');
|
||||
// The destination (Claude Code, Codex, the local-echo overlay) deletes one grapheme cluster per DEL.
|
||||
const trimGrapheme = (value: string) =>
|
||||
[...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value)]
|
||||
.slice(0, -1)
|
||||
.map((part) => part.segment)
|
||||
.join('');
|
||||
|
||||
class FakeNode {
|
||||
listeners = new Map<string, Set<Listener>>();
|
||||
@@ -356,8 +361,8 @@ function harness(
|
||||
const consume = (data: string) => {
|
||||
sent.push(data);
|
||||
if (data === DEL) {
|
||||
if (pending) pending = trimPoint(pending);
|
||||
else line = trimPoint(line);
|
||||
if (pending) pending = trimGrapheme(pending);
|
||||
else line = trimGrapheme(line);
|
||||
} else if (data === '\r') {
|
||||
commits.push(line + pending);
|
||||
line = '';
|
||||
@@ -421,7 +426,11 @@ function harness(
|
||||
if (inputType === 'deleteContentBackward') {
|
||||
if (start === end) {
|
||||
if (start === 0) return;
|
||||
start -= Array.from(textarea.value.slice(0, start)).at(-1)!.length;
|
||||
// WebKit removes one whole grapheme cluster per Backspace.
|
||||
const clusters = [
|
||||
...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(textarea.value.slice(0, start)),
|
||||
];
|
||||
start -= clusters.at(-1)!.segment.length;
|
||||
}
|
||||
textarea.value = textarea.value.slice(0, start) + textarea.value.slice(end);
|
||||
textarea.setSelectionRange(start, start);
|
||||
@@ -548,6 +557,17 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
||||
expect(h.api.create({})).toBeNull();
|
||||
expect(h.api.create({ terminal: h.terminal, sendTransaction() {}, isScreenReaderMode: () => true })).toBeNull();
|
||||
expect(h.api.editBetween('a👍b', 'aX')).toEqual({ deleted: 2, inserted: 'X' });
|
||||
// One DEL per grapheme cluster: WebKit removes the whole cluster on one
|
||||
// Backspace, and Claude Code and Codex delete one grapheme per DEL.
|
||||
for (const emoji of [
|
||||
'\u2764\uFE0F',
|
||||
'\u{1F44D}\u{1F3FD}',
|
||||
'\u{1F1EB}\u{1F1F7}',
|
||||
'\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}',
|
||||
]) {
|
||||
expect(h.api.editBetween(`ok${emoji}`, 'ok')).toEqual({ deleted: 1, inserted: '' });
|
||||
expect(h.api.editBetween(`a${emoji}b`, 'aX')).toEqual({ deleted: 2, inserted: 'X' });
|
||||
}
|
||||
for (const ch of 'hel') h.type(ch);
|
||||
h.type('lo');
|
||||
h.tick();
|
||||
@@ -914,6 +934,31 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
||||
expect(h.textarea.value).toBe('hello');
|
||||
},
|
||||
],
|
||||
[
|
||||
'20b grapheme-cluster deletion sends one DEL',
|
||||
(h) => {
|
||||
for (const emoji of [
|
||||
'\u2764\uFE0F',
|
||||
'\u{1F44D}\u{1F3FD}',
|
||||
'\u{1F1EB}\u{1F1F7}',
|
||||
'\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}',
|
||||
]) {
|
||||
h.type('ok');
|
||||
h.edit(emoji);
|
||||
h.clearSent();
|
||||
h.backspace();
|
||||
expect(h.textarea.value).toBe('ok');
|
||||
h.bytes([DEL]);
|
||||
// The destination keeps the draft: one DEL took the whole emoji, nothing before it.
|
||||
expect(h.value()).toBe('ok');
|
||||
h.invariant();
|
||||
h.backspace();
|
||||
h.backspace();
|
||||
expect(h.value()).toBe('');
|
||||
h.clearSent();
|
||||
}
|
||||
},
|
||||
],
|
||||
[
|
||||
'21 destroy restoration and stock behavior',
|
||||
(h) => {
|
||||
|
||||
@@ -1560,6 +1560,15 @@ describe('TerminalTile iOS native input ownership', () => {
|
||||
expect(term.keyHandler!({ type: 'keydown', key: 'a', code: 'KeyA' })).toBe(true);
|
||||
});
|
||||
|
||||
it('falls back to the 229 recovery when the iOS module refuses to create an owner', async () => {
|
||||
const native = install();
|
||||
native.create.mockReturnValueOnce(null);
|
||||
const { tile } = await connectTile(makeApp());
|
||||
expect(native.create).toHaveBeenCalledOnce();
|
||||
expect(native.attachCaretMarker).not.toHaveBeenCalled();
|
||||
expect((tile as ControllerTile)._keyCode229Recovery).not.toBeNull();
|
||||
});
|
||||
|
||||
it('reserves separate DEL writes and insertion for the tile session in one call', async () => {
|
||||
const native = install();
|
||||
const app = makeApp();
|
||||
|
||||
Reference in new issue
Block a user