mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-12-01 16:59:32 +01:00
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:
1 parent
414dd51eb2
commit
cda5d96451
26 files changed
+1072
-170
No files matched your search
@@ -3,4 +3,4 @@
|
|||||||
'xterm-zerolag-input': patch
|
'xterm-zerolag-input': patch
|
||||||
---
|
---
|
||||||
|
|
||||||
Fix iOS keyboard suggestions, phrase replacement, dictation and hold-delete by retaining native input ownership in each terminal pane. Preserve local-echo Enter ordering across session switches, reset native editing at toolbar and programmatic input boundaries, and show the native trackpad caret against the visible input, including emoji-safe deletion.
|
Fix iOS keyboard suggestions, phrase replacement, dictation and hold-delete by retaining native input ownership in each terminal pane. Preserve local-echo Enter ordering across session switches, reset native editing at toolbar and programmatic input boundaries, and show the native trackpad caret on the exact cell of the visible input, including across wide-character wraps, with emoji-safe deletion. The local-echo overlay deletes one grapheme cluster per backspace and adds `getInputEndAnchor()`, `getInputAnchor(offset)`, `committedText` and `onLayout()` for hosts that position a caret against the drawn input.
|
||||||
@@ -355,7 +355,7 @@ npm test -- -t "pattern" # By name
|
|||||||
Three suites are deliberately left out, because they cannot pass on an arbitrary machine. Each has its own runner, and a failure there means "not runnable here", not a regression:
|
Three suites are deliberately left out, because they cannot pass on an arbitrary machine. Each has its own runner, and a failure there means "not runnable here", not a regression:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run test:browser # Playwright + chromium, live server; codex-predictive-echo also needs a real codex binary
|
npm run test:browser # Playwright + chromium, live server (own pretest vendor step); codex-predictive-echo also needs a real codex binary
|
||||||
npm run test:mobile # the above plus environment-specific PNG baselines (own config, own pretest vendor step)
|
npm run test:mobile # the above plus environment-specific PNG baselines (own config, own pretest vendor step)
|
||||||
npm run test:perf # wall-clock benchmarks — need an otherwise idle machine
|
npm run test:perf # wall-clock benchmarks — need an otherwise idle machine
|
||||||
npm run test:all # literally everything; fails ~87 tests on a clean master here, which is why it is not the default
|
npm run test:all # literally everything; fails ~87 tests on a clean master here, which is why it is not the default
|
||||||
|
|||||||
@@ -145,7 +145,7 @@ Spawn commands are pinned as literal strings in `test/cli-registry-spawn-golden.
|
|||||||
|
|
||||||
### Input delivery and WS resilience
|
### Input delivery and WS resilience
|
||||||
|
|
||||||
**Input**: `session.writeViaMux()` for programmatic/curl input — the text as one tmux bracketed paste (`paste-buffer -p`, so Codex cannot fold the Enter into a paste burst) + `send-keys Enter`. A single character is typed with `send-keys -l` instead (`submitsAsKeys()`): Claude Code's and Codex's selection dialogs ignore a pasted `3`, and the Enter then confirms the highlighted option. A multi-line prompt keeps its line breaks inside that one paste, with or without the Enter (fire-and-once). Interactive **browser** input goes through a durable **exactly-once** layer: each frame carries a stable `clientId` + monotonic per-session `seq`, persisted to localStorage until the server ACKs (`{t:'ia',seq}` over WS, or HTTP 2xx), so a dropped link/reconnect can't lose or double-deliver a prompt. **Session FIFO** (`_enqueueInput`, app.js, #830): every browser producer (typed main-pane input, toolbar submit, accessory keys and commands, paste, Compose, voice, image upload) captures its session id when the user acts and enqueues ops (`write`, `key`, `gap`) on that session's FIFO, which drains in order into `_enqueueReliableInput`. ⚠️ A `gap` orders ENQUEUEING only: the next op is handed to the reliable layer after the delay, with no wait for the previous frame's ACK, so a delayed Enter keeps its session and its place but gains no delivery guarantee beyond the exactly-once layer. ⚠️ Ops for an id missing from `app.sessions` are dropped (a probe or deleted session never reaches the wire; tests must register their session). ⚠️ `_cleanupSessionData()` clears the session's FIFO and its pending gap timer, so a deleted session cannot type into a reused id. A duplicate is ACKed as `{t:'ia',seq,dup:true,last}` so a client whose persisted counter rolled back below the server's watermark can lift itself out instead of typing into a silently dead terminal (`docs/reliable-input-delivery.md`). **WS resilience** (#149): the upgrade URL carries `cid = clientId + ':' + perTabNonce`, and `ws-connection-registry.ts` supersedes only same-TAB reconnects (two tabs on one session coexist; input frames keep the bare `clientId` for seq dedup); reconnects back off exponentially (attempts preserved across `_connectWs`), and the header connection chip renders from a real `_wsState` lifecycle (`connecting`/`connected`/`fallback`/`reconnecting`/`disconnected`).
|
**Input**: `session.writeViaMux()` for programmatic/curl input — the text as one tmux bracketed paste (`paste-buffer -p`, so Codex cannot fold the Enter into a paste burst) + `send-keys Enter`. A single character is typed with `send-keys -l` instead (`submitsAsKeys()`): Claude Code's and Codex's selection dialogs ignore a pasted `3`, and the Enter then confirms the highlighted option. A multi-line prompt keeps its line breaks inside that one paste, with or without the Enter (fire-and-once). Interactive **browser** input goes through a durable **exactly-once** layer: each frame carries a stable `clientId` + monotonic per-session `seq`, persisted to localStorage until the server ACKs (`{t:'ia',seq}` over WS, or HTTP 2xx), so a dropped link/reconnect can't lose or double-deliver a prompt. **Session FIFO** (`_enqueueInput`, app.js, #830): every browser producer (typed main-pane input, toolbar submit, accessory keys and commands, paste, Compose, voice, image upload) captures its session id when the user acts and enqueues ops (`write`, `key`, `gap`) on that session's FIFO, which drains them in order: a `write` goes to `_enqueueReliableInput`, a `key` (a modified Enter such as Shift/Ctrl+Enter) is a direct `POST /api/sessions/:id/send-key` outside the exactly-once layer, and a `gap` delays the next op. ⚠️ A `gap` orders ENQUEUEING only: the next op is handed to the reliable layer after the delay, with no wait for the previous frame's ACK, so a delayed Enter keeps its session and its place but gains no delivery guarantee beyond the exactly-once layer. ⚠️ Ops for an id missing from `app.sessions` are dropped (a probe or deleted session never reaches the wire; tests must register their session). ⚠️ `_cleanupSessionData()` clears the session's FIFO and its pending gap timer, so a deleted session cannot type into a reused id. A duplicate is ACKed as `{t:'ia',seq,dup:true,last}` so a client whose persisted counter rolled back below the server's watermark can lift itself out instead of typing into a silently dead terminal (`docs/reliable-input-delivery.md`). **WS resilience** (#149): the upgrade URL carries `cid = clientId + ':' + perTabNonce`, and `ws-connection-registry.ts` supersedes only same-TAB reconnects (two tabs on one session coexist; input frames keep the bare `clientId` for seq dedup); reconnects back off exponentially (attempts preserved across `_connectWs`), and the header connection chip renders from a real `_wsState` lifecycle (`connecting`/`connected`/`fallback`/`reconnecting`/`disconnected`).
|
||||||
|
|
||||||
### Per-session env overrides: exact-key allowlist and CLAUDE_CONFIG_DIR
|
### Per-session env overrides: exact-key allowlist and CLAUDE_CONFIG_DIR
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,14 @@
|
|||||||
|
|
||||||
On iOS WebKit touch devices, `terminal-ios-native-input.js` owns the terminal's native textarea. Its support check shares `MobileImePreview.isIosWebKitTouch`; it loads after the preview and before the primary terminal and tile hosts. These hosts do not also install keyCode-229 recovery on iOS. Other coarse-pointer devices retain that recovery.
|
On iOS WebKit touch devices, `terminal-ios-native-input.js` owns the terminal's native textarea. Its support check shares `MobileImePreview.isIosWebKitTouch`; it loads after the preview and before the primary terminal and tile hosts. These hosts do not also install keyCode-229 recovery on iOS. Other coarse-pointer devices retain that recovery.
|
||||||
|
|
||||||
The native field retains the editable line, including dictation hypotheses and native newlines. Reconciliation emits shell-safe transactions rather than forwarding each browser event. A dictated line break must never send CR or LF. Trackpad movement changes only the visual caret; it sends no terminal arrows. With local echo, caret geometry comes from the overlay's input-end anchor, and unavailable geometry hides the marker.
|
The native field retains the editable line, including dictation hypotheses and native newlines. Reconciliation emits shell-safe transactions rather than forwarding each browser event. A dictated line break must never send CR or LF. Trackpad movement changes only the visual caret; it sends no terminal arrows, never focuses the field and never changes its selection.
|
||||||
|
|
||||||
|
The owner exposes `caret(): { visible, text, offset }`, with projected text and a UTF-16 offset into that projection (CRLF and LF each become one space). The marker has two authoritative positioning modes:
|
||||||
|
|
||||||
|
- **Local echo:** the field must be an exact suffix of the overlay's last displayed `committedText`. The marker queries `getInputAnchor(base + offset)` for the painted cell, including wide-character wraps. A mismatch or unavailable/clipped layout hides it.
|
||||||
|
- **Parsed buffer:** with echo off, passthrough, tiles or Pane B, the marker matches the full native text backwards from xterm's cursor, crossing only soft wraps. It skips wide-glyph continuation cells and validated empty wrap padding, then maps the offset to an actual buffer cell. A mismatch, an identical preceding repetition, an offset inside a combined cell (such as a combining mark or ZWJ cluster), or an offscreen row hides it. After a native text change it also hides until the next `onWriteParsed`, rather than mistaking old output for a delivered edit.
|
||||||
|
|
||||||
|
Both modes hide for an unfocused field, composition, a range selection, the end of the field, a pending/unreconciled edit, an invalidated baseline, a failed transaction sink or a borrowed clipboard snapshot. No mode estimates the caret by subtracting a text width from an end anchor.
|
||||||
|
|
||||||
Programmatic input calls `_prepareExternalInput` on the captured pane before sending. Toolbar Enter calls `submitFromToolbar()`. The per-session FIFO reserves pending local-echo text, an 80ms gap, and CR together, so switching sessions cannot redirect CR or let later edits overtake it. This is enqueue ordering, not an acknowledgement-completion fence. Logical ACK fences, tagged HTTP success semantics, HTTP/WebSocket handover gating and `/send-key` ACK fencing are outside this fix.
|
Programmatic input calls `_prepareExternalInput` on the captured pane before sending. Toolbar Enter calls `submitFromToolbar()`. The per-session FIFO reserves pending local-echo text, an 80ms gap, and CR together, so switching sessions cannot redirect CR or let later edits overtake it. This is enqueue ordering, not an acknowledgement-completion fence. Logical ACK fences, tagged HTTP success semantics, HTTP/WebSocket handover gating and `/send-key` ACK fencing are outside this fix.
|
||||||
|
|
||||||
@@ -13,7 +20,7 @@ node scripts/prepare-test-vendor.mjs
|
|||||||
npm run test:browser -- test/ios-native-input.browser.test.ts
|
npm run test:browser -- test/ios-native-input.browser.test.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
The browser runner also prepares the source-served vendor overlay through `pretest:browser`. `src/web/public/vendor/` is gitignored; the source vendor is generated, not tracked. Production builds independently regenerate the overlay from `packages/xterm-zerolag-input` and content-hash it. The overlay must include `getInputEndAnchor` before running these tests.
|
The browser runner also prepares the source-served vendor overlay through `pretest:browser`. `src/web/public/vendor/` is gitignored; source vendor is generated, not tracked. Production builds independently regenerate the overlay from `packages/xterm-zerolag-input` and content-hash it. The overlay must include `getInputAnchor` and `committedText` before running these tests.
|
||||||
|
|
||||||
The suite serves the real application with Chromium, an iPhone user agent, touch points and a coarse pointer. It observes `_enqueueReliableInput` without replacing `_sendInputAsync`, and reuses the phone-validated WebKit replay defaults. Assertions cover suggestion op boundaries, phrase replacement, held delete, dictation newline suppression, toolbar submission and subsequent suggestions, old-session CR ownership during the gap, trusted CDP paste, caret geometry in both echo modes, emoji deletion, tile session ownership and non-iOS recovery.
|
The suite serves the real application with Chromium, an iPhone user agent, touch points and a coarse pointer. It observes `_enqueueReliableInput` without replacing `_sendInputAsync`, and reuses the phone-validated WebKit replay defaults. Assertions cover suggestion op boundaries, phrase replacement, held delete, dictation newline suppression, toolbar submission and subsequent suggestions, old-session CR ownership during the gap, trusted CDP paste, caret geometry in both echo modes, emoji deletion, tile session ownership and non-iOS recovery.
|
||||||
|
|
||||||
|
|||||||
@@ -263,6 +263,7 @@ Finds text that exists after the prompt but was never typed through the overlay.
|
|||||||
| `rerender()` | Force a re-render. Call after buffer reloads, screen redraws, resizes and reconnects. A no-op when there is nothing to draw, so it needs no guard. |
|
| `rerender()` | Force a re-render. Call after buffer reloads, screen redraws, resizes and reconnects. A no-op when there is nothing to draw, so it needs no guard. |
|
||||||
| `refreshFont()` | Re-cache font and color properties from the terminal. Call after a font size or theme change. |
|
| `refreshFont()` | Re-cache font and color properties from the terminal. Call after a font size or theme change. |
|
||||||
| `getInputEndAnchor()` | Where the overlay's visible text ends, from its last layout: `{ col, row }` in viewport cells (`col` equals the column count at a full line's right edge), or `null` while the overlay is hidden. For placing a caret marker against the drawn input. |
|
| `getInputEndAnchor()` | Where the overlay's visible text ends, from its last layout: `{ col, row }` in viewport cells (`col` equals the column count at a full line's right edge), or `null` while the overlay is hidden. For placing a caret marker against the drawn input. |
|
||||||
|
| `getInputAnchor(offset)` | Resolve an offset in UTF-16 units into the last displayed flushed + pending + composition text to `{ col, row }` in viewport cells. Wrap boundaries prefer the next line; the final offset returns the end anchor. Returns `null` when hidden, out of range, inside a surrogate pair, or on a tail-sliced row. Performs no width measurement or DOM work. |
|
||||||
| `onLayout(callback)` | Call `callback` after each layout, a hide included. Returns an unsubscribe function. |
|
| `onLayout(callback)` | Call `callback` after each layout, a hide included. Returns an unsubscribe function. |
|
||||||
|
|
||||||
### Prompt
|
### Prompt
|
||||||
@@ -278,6 +279,7 @@ Finds text that exists after the prompt but was never typed through the overlay.
|
|||||||
| Property | Type | Description |
|
| Property | Type | Description |
|
||||||
|----------|------|-------------|
|
|----------|------|-------------|
|
||||||
| `pendingText` | `string` | Unacknowledged text (read-only) |
|
| `pendingText` | `string` | Unacknowledged text (read-only) |
|
||||||
|
| `committedText` | `string` | Flushed + pending text exactly as last displayed, excluding composition; `''` when hidden (read-only). Visual correspondence data, not a delivery acknowledgement. Offsets use UTF-16 units. |
|
||||||
| `hasPending` | `boolean` | `true` if there is pending or flushed text. Excludes the IME composition, so it can be `false` while the overlay still shows one |
|
| `hasPending` | `boolean` | `true` if there is pending or flushed text. Excludes the IME composition, so it can be `false` while the overlay still shows one |
|
||||||
| `composition` | `string` | The text set by `setComposition()`, `''` when none (read-only) |
|
| `composition` | `string` | The text set by `setComposition()`, `''` when none (read-only) |
|
||||||
| `state` | `ZerolagInputState` | Full snapshot: `pendingText`, `flushedLength`, `flushedText`, `visible`, `promptPosition` |
|
| `state` | `ZerolagInputState` | Full snapshot: `pendingText`, `flushedLength`, `flushedText`, `visible`, `promptPosition` |
|
||||||
|
|||||||
@@ -88,6 +88,13 @@ function holdsOnlyRendered(container: HTMLDivElement, state: RenderedLines): boo
|
|||||||
return !state.cursor || children[state.lines.length] === state.cursor;
|
return !state.cursor || children[state.lines.length] === state.cursor;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface OverlayPlacement {
|
||||||
|
end: InputEndAnchor | null;
|
||||||
|
firstVisible: number;
|
||||||
|
topRow: number;
|
||||||
|
keepsPromptLine: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Render the overlay content into the container element.
|
* Render the overlay content into the container element.
|
||||||
*
|
*
|
||||||
@@ -102,7 +109,7 @@ function holdsOnlyRendered(container: HTMLDivElement, state: RenderedLines): boo
|
|||||||
* DOM work, layout and paint, which a long prompt on a phone paid for in
|
* DOM work, layout and paint, which a long prompt on a phone paid for in
|
||||||
* dropped frames.
|
* dropped frames.
|
||||||
*/
|
*/
|
||||||
export function renderOverlay(container: HTMLDivElement, params: RenderParams): InputEndAnchor | null {
|
export function renderOverlay(container: HTMLDivElement, params: RenderParams): OverlayPlacement {
|
||||||
const {
|
const {
|
||||||
lines,
|
lines,
|
||||||
compositionStart,
|
compositionStart,
|
||||||
@@ -252,7 +259,12 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
|
|||||||
}
|
}
|
||||||
|
|
||||||
container.style.display = '';
|
container.style.display = '';
|
||||||
return lastLine === undefined ? null : { col: cursorCol, row: topRow + visibleLines.length - 1 };
|
return {
|
||||||
|
end: lastLine === undefined ? null : { col: cursorCol, row: topRow + visibleLines.length - 1 },
|
||||||
|
firstVisible,
|
||||||
|
topRow,
|
||||||
|
keepsPromptLine,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -19,8 +19,27 @@ const DEFAULT_BG = '#0d0d0d';
|
|||||||
const DEFAULT_FG = '#eeeeee';
|
const DEFAULT_FG = '#eeeeee';
|
||||||
const DEFAULT_CURSOR = '#e0e0e0';
|
const DEFAULT_CURSOR = '#e0e0e0';
|
||||||
|
|
||||||
|
interface InputLayoutLine {
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
startCol: number;
|
||||||
|
cols: number[];
|
||||||
|
codeUnits: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InputLayout {
|
||||||
|
text: string;
|
||||||
|
committedLength: number;
|
||||||
|
lines: InputLayoutLine[];
|
||||||
|
firstVisible: number;
|
||||||
|
topRow: number;
|
||||||
|
keepsPromptLine: boolean;
|
||||||
|
startCol: number;
|
||||||
|
totalCols: number;
|
||||||
|
}
|
||||||
|
|
||||||
type GraphemeSegmenter = {
|
type GraphemeSegmenter = {
|
||||||
segment(input: string): Iterable<{ segment: string }>;
|
segment(input: string): { containing(index: number): { segment: string } | undefined };
|
||||||
};
|
};
|
||||||
|
|
||||||
const GRAPHEME_SEGMENTER: GraphemeSegmenter | null = (() => {
|
const GRAPHEME_SEGMENTER: GraphemeSegmenter | null = (() => {
|
||||||
@@ -36,15 +55,15 @@ const GRAPHEME_SEGMENTER: GraphemeSegmenter | null = (() => {
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
/** UTF-16 width of the final grapheme cluster (one for an empty legacy flushed string). */
|
/**
|
||||||
|
* UTF-16 width of the final grapheme cluster (one for an empty legacy flushed string).
|
||||||
|
* `containing()` finds the cluster at the end without walking the whole string (measured
|
||||||
|
* 0.09 ms at 60,000 characters, against 41 ms for a full scan), and segments with the
|
||||||
|
* whole text as context, so a cluster of any length and an odd run of flags come out right.
|
||||||
|
*/
|
||||||
function lastGraphemeWidth(text: string): number {
|
function lastGraphemeWidth(text: string): number {
|
||||||
if (GRAPHEME_SEGMENTER) {
|
if (!text) return 1;
|
||||||
let width = 1;
|
if (GRAPHEME_SEGMENTER) return GRAPHEME_SEGMENTER.segment(text).containing(text.length - 1)?.segment.length ?? 1;
|
||||||
for (const { segment } of GRAPHEME_SEGMENTER.segment(text)) {
|
|
||||||
width = segment.length;
|
|
||||||
}
|
|
||||||
return width;
|
|
||||||
}
|
|
||||||
|
|
||||||
const last = text.charCodeAt(text.length - 1);
|
const last = text.charCodeAt(text.length - 1);
|
||||||
const previous = text.charCodeAt(text.length - 2);
|
const previous = text.charCodeAt(text.length - 2);
|
||||||
@@ -110,6 +129,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
private _lastRenderKey = '';
|
private _lastRenderKey = '';
|
||||||
private _lastPromptPos: PromptPosition | null = null;
|
private _lastPromptPos: PromptPosition | null = null;
|
||||||
private _inputEndAnchor: InputEndAnchor | null = null;
|
private _inputEndAnchor: InputEndAnchor | null = null;
|
||||||
|
private _layout: InputLayout | null = null;
|
||||||
private _layoutListeners = new Set<() => void>();
|
private _layoutListeners = new Set<() => void>();
|
||||||
|
|
||||||
// Font cache
|
// Font cache
|
||||||
@@ -166,6 +186,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
if (!promptRowInViewport(this._terminal!)) {
|
if (!promptRowInViewport(this._terminal!)) {
|
||||||
this._overlay!.style.display = 'none';
|
this._overlay!.style.display = 'none';
|
||||||
this._inputEndAnchor = null;
|
this._inputEndAnchor = null;
|
||||||
|
this._layout = null;
|
||||||
this._notifyLayout();
|
this._notifyLayout();
|
||||||
if (this._scrollTimer) {
|
if (this._scrollTimer) {
|
||||||
clearTimeout(this._scrollTimer);
|
clearTimeout(this._scrollTimer);
|
||||||
@@ -237,7 +258,9 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
* Remove the last grapheme cluster (one user-perceived character).
|
* Remove the last grapheme cluster (one user-perceived character).
|
||||||
*
|
*
|
||||||
* Cascade order:
|
* Cascade order:
|
||||||
* 1. Remove from `pendingText` if non-empty → returns `'pending'`
|
* 1. Remove the last visible cluster from pending text; if it crosses into
|
||||||
|
* trustworthy flushed text, remove that tail too → returns `'flushed'`,
|
||||||
|
* otherwise returns `'pending'`
|
||||||
* 2. Decrement `flushedOffset` if pending is empty but flushed exists → returns `'flushed'`
|
* 2. Decrement `flushedOffset` if pending is empty but flushed exists → returns `'flushed'`
|
||||||
* 3. Try `detectBufferText()` if both are empty, then decrement → returns `'flushed'`
|
* 3. Try `detectBufferText()` if both are empty, then decrement → returns `'flushed'`
|
||||||
*
|
*
|
||||||
@@ -245,8 +268,8 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
*
|
*
|
||||||
* - `'pending'`: A character was removed from unsent text. The consumer
|
* - `'pending'`: A character was removed from unsent text. The consumer
|
||||||
* should NOT send backspace to the PTY (the text was never transmitted).
|
* should NOT send backspace to the PTY (the text was never transmitted).
|
||||||
* - `'flushed'`: A character was removed from text already sent to the PTY.
|
* - `'flushed'`: A character was removed wholly or partly from text already
|
||||||
* The consumer SHOULD send backspace to the PTY.
|
* sent to the PTY. The consumer SHOULD send one backspace to the PTY.
|
||||||
* - `false`: Nothing to remove. The consumer should NOT send backspace.
|
* - `false`: Nothing to remove. The consumer should NOT send backspace.
|
||||||
*
|
*
|
||||||
* Any IME composition is dropped in every case, and the overlay is repainted
|
* Any IME composition is dropped in every case, and the overlay is repainted
|
||||||
@@ -257,13 +280,21 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
const droppedComposition = this._composition.length > 0;
|
const droppedComposition = this._composition.length > 0;
|
||||||
this._composition = '';
|
this._composition = '';
|
||||||
if (this._pendingText.length > 0) {
|
if (this._pendingText.length > 0) {
|
||||||
this._pendingText = this._pendingText.slice(0, -lastGraphemeWidth(this._pendingText));
|
const pendingLength = this._pendingText.length;
|
||||||
|
const hasFlushedText = this._flushedOffset > 0 && this._flushedText.length === this._flushedOffset;
|
||||||
|
const width = lastGraphemeWidth(hasFlushedText ? this._flushedText + this._pendingText : this._pendingText);
|
||||||
|
const flushedWidth = Math.max(0, width - pendingLength);
|
||||||
|
this._pendingText = this._pendingText.slice(0, -width);
|
||||||
|
if (flushedWidth > 0) {
|
||||||
|
this._flushedOffset -= flushedWidth;
|
||||||
|
this._flushedText = this._flushedText.slice(0, -flushedWidth);
|
||||||
|
}
|
||||||
if (this._pendingText.length > 0 || this._flushedOffset > 0) {
|
if (this._pendingText.length > 0 || this._flushedOffset > 0) {
|
||||||
this._render();
|
this._render();
|
||||||
} else {
|
} else {
|
||||||
this._hide();
|
this._hide();
|
||||||
}
|
}
|
||||||
return 'pending';
|
return flushedWidth > 0 ? 'flushed' : 'pending';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Both empty — try detecting text already on the prompt line
|
// Both empty — try detecting text already on the prompt line
|
||||||
@@ -353,6 +384,29 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
return this._inputEndAnchor ? { ...this._inputEndAnchor } : null;
|
return this._inputEndAnchor ? { ...this._inputEndAnchor } : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resolve a UTF-16 offset in the last displayed text, with forward wrap affinity. */
|
||||||
|
getInputAnchor(offset: number): InputEndAnchor | null {
|
||||||
|
const layout = this._layout;
|
||||||
|
if (!layout || !Number.isInteger(offset) || offset < 0 || offset > layout.text.length) return null;
|
||||||
|
if (offset === layout.text.length) return this.getInputEndAnchor();
|
||||||
|
for (let i = layout.lines.length - 1; i >= layout.firstVisible; i--) {
|
||||||
|
const line = layout.lines[i];
|
||||||
|
if (offset < line.start || offset >= line.end) continue;
|
||||||
|
const index = line.codeUnits.indexOf(offset - line.start);
|
||||||
|
if (index < 0) return null;
|
||||||
|
return {
|
||||||
|
col: (i === 0 && layout.keepsPromptLine ? layout.startCol : 0) + line.cols[index],
|
||||||
|
row: layout.topRow + i - layout.firstVisible,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Last displayed flushed + pending text, not a delivery acknowledgement. */
|
||||||
|
get committedText(): string {
|
||||||
|
return this._layout ? this._layout.text.slice(0, this._layout.committedLength) : '';
|
||||||
|
}
|
||||||
|
|
||||||
/** Subscribe after each layout, including hide. Returns an unsubscribe function. */
|
/** Subscribe after each layout, including hide. Returns an unsubscribe function. */
|
||||||
onLayout(cb: () => void): () => void {
|
onLayout(cb: () => void): () => void {
|
||||||
this._layoutListeners.add(cb);
|
this._layoutListeners.add(cb);
|
||||||
@@ -636,6 +690,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
this._overlay.innerHTML = '';
|
this._overlay.innerHTML = '';
|
||||||
this._overlay.style.display = 'none';
|
this._overlay.style.display = 'none';
|
||||||
this._inputEndAnchor = null;
|
this._inputEndAnchor = null;
|
||||||
|
this._layout = null;
|
||||||
this._notifyLayout();
|
this._notifyLayout();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -700,6 +755,7 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The composition is a styled tail after everything the user has typed.
|
// The composition is a styled tail after everything the user has typed.
|
||||||
|
const committedLength = displayText.length;
|
||||||
const compositionStart = [...displayText].length;
|
const compositionStart = [...displayText].length;
|
||||||
displayText += this._composition;
|
displayText += this._composition;
|
||||||
|
|
||||||
@@ -721,37 +777,51 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
const firstLineCols = Math.max(1, totalCols - startCol);
|
const firstLineCols = Math.max(1, totalCols - startCol);
|
||||||
const chars = [...displayText]; // proper Unicode iteration
|
const chars = [...displayText]; // proper Unicode iteration
|
||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
|
const layoutLines: InputLayoutLine[] = [];
|
||||||
|
let codeUnit = 0;
|
||||||
let ci = 0;
|
let ci = 0;
|
||||||
// First line: remaining columns after prompt
|
// First line: remaining columns after prompt
|
||||||
{
|
{
|
||||||
let lineStr = '';
|
let lineStr = '';
|
||||||
let lineCols = 0;
|
let lineCols = 0;
|
||||||
|
const line: InputLayoutLine = { start: codeUnit, end: codeUnit, startCol, cols: [], codeUnits: [] };
|
||||||
while (ci < chars.length) {
|
while (ci < chars.length) {
|
||||||
const cw = charCellWidth(this._terminal, chars[ci]);
|
const cw = charCellWidth(this._terminal, chars[ci]);
|
||||||
if (lineCols + cw > firstLineCols) break;
|
if (lineCols + cw > firstLineCols) break;
|
||||||
|
line.cols.push(lineCols);
|
||||||
|
line.codeUnits.push(codeUnit - line.start);
|
||||||
|
codeUnit += chars[ci].length;
|
||||||
lineStr += chars[ci];
|
lineStr += chars[ci];
|
||||||
lineCols += cw;
|
lineCols += cw;
|
||||||
ci++;
|
ci++;
|
||||||
}
|
}
|
||||||
lines.push(lineStr);
|
lines.push(lineStr);
|
||||||
|
line.end = codeUnit;
|
||||||
|
layoutLines.push(line);
|
||||||
}
|
}
|
||||||
// Subsequent lines: full terminal width
|
// Subsequent lines: full terminal width
|
||||||
while (ci < chars.length) {
|
while (ci < chars.length) {
|
||||||
let lineStr = '';
|
let lineStr = '';
|
||||||
let lineCols = 0;
|
let lineCols = 0;
|
||||||
|
const line: InputLayoutLine = { start: codeUnit, end: codeUnit, startCol: 0, cols: [], codeUnits: [] };
|
||||||
while (ci < chars.length) {
|
while (ci < chars.length) {
|
||||||
const cw = charCellWidth(this._terminal, chars[ci]);
|
const cw = charCellWidth(this._terminal, chars[ci]);
|
||||||
if (lineCols + cw > totalCols) break;
|
if (lineCols + cw > totalCols) break;
|
||||||
|
line.cols.push(lineCols);
|
||||||
|
line.codeUnits.push(codeUnit - line.start);
|
||||||
|
codeUnit += chars[ci].length;
|
||||||
lineStr += chars[ci];
|
lineStr += chars[ci];
|
||||||
lineCols += cw;
|
lineCols += cw;
|
||||||
ci++;
|
ci++;
|
||||||
}
|
}
|
||||||
lines.push(lineStr);
|
lines.push(lineStr);
|
||||||
|
line.end = codeUnit;
|
||||||
|
layoutLines.push(line);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cursorColor = this._options.cursorColor ?? this._terminal.options.theme?.cursor ?? DEFAULT_CURSOR;
|
const cursorColor = this._options.cursorColor ?? this._terminal.options.theme?.cursor ?? DEFAULT_CURSOR;
|
||||||
|
|
||||||
this._inputEndAnchor = renderOverlay(this._overlay, {
|
const placement = renderOverlay(this._overlay, {
|
||||||
lines,
|
lines,
|
||||||
compositionStart: this._composition ? compositionStart : undefined,
|
compositionStart: this._composition ? compositionStart : undefined,
|
||||||
startCol,
|
startCol,
|
||||||
@@ -767,6 +837,17 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
cursorColor,
|
cursorColor,
|
||||||
terminal: this._terminal,
|
terminal: this._terminal,
|
||||||
});
|
});
|
||||||
|
this._inputEndAnchor = placement.end;
|
||||||
|
this._layout = {
|
||||||
|
text: displayText,
|
||||||
|
committedLength,
|
||||||
|
lines: layoutLines,
|
||||||
|
firstVisible: placement.firstVisible,
|
||||||
|
topRow: placement.topRow,
|
||||||
|
keepsPromptLine: placement.keepsPromptLine,
|
||||||
|
startCol,
|
||||||
|
totalCols,
|
||||||
|
};
|
||||||
} catch {
|
} catch {
|
||||||
// Hide on render error but preserve pendingText —
|
// Hide on render error but preserve pendingText —
|
||||||
// next rerender() will retry when terminal is ready.
|
// next rerender() will retry when terminal is ready.
|
||||||
@@ -775,7 +856,10 @@ export class ZerolagInputAddon implements XtermAddon {
|
|||||||
this._overlay.style.display = 'none';
|
this._overlay.style.display = 'none';
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (this._overlay.style.display === 'none') this._inputEndAnchor = null;
|
if (this._overlay.style.display === 'none') {
|
||||||
|
this._inputEndAnchor = null;
|
||||||
|
this._layout = null;
|
||||||
|
}
|
||||||
if (layoutChanged) this._notifyLayout();
|
if (layoutChanged) this._notifyLayout();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -531,6 +531,29 @@ describe('renderOverlay — staying on screen (totalRows)', () => {
|
|||||||
|
|
||||||
expect(container.style.top).toBe(6 * 17 + 'px');
|
expect(container.style.top).toBe(6 * 17 + 'px');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('returns the same placement used for upward growth and tail clipping', () => {
|
||||||
|
const container = document.createElement('div');
|
||||||
|
const params = makeParams({ lines: ['ab', '你好', 'x'], startCol: 3, promptRow: 5, totalRows: 6 });
|
||||||
|
expect(renderOverlay(container, params)).toEqual({
|
||||||
|
end: { col: 1, row: 5 },
|
||||||
|
firstVisible: 0,
|
||||||
|
topRow: 3,
|
||||||
|
keepsPromptLine: true,
|
||||||
|
});
|
||||||
|
expect(renderOverlay(container, { ...params, totalRows: 2 })).toEqual({
|
||||||
|
end: { col: 1, row: 1 },
|
||||||
|
firstVisible: 1,
|
||||||
|
topRow: 0,
|
||||||
|
keepsPromptLine: false,
|
||||||
|
});
|
||||||
|
expect(renderOverlay(container, { ...params, lines: [] })).toEqual({
|
||||||
|
end: null,
|
||||||
|
firstVisible: 0,
|
||||||
|
topRow: 5,
|
||||||
|
keepsPromptLine: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('renderOverlay: rebuilding only the lines that changed', () => {
|
describe('renderOverlay: rebuilding only the lines that changed', () => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { describe, it, expect, afterEach } from 'vitest';
|
import { describe, it, expect, afterEach, vi } from 'vitest';
|
||||||
import { createMockTerminal } from './helpers.js';
|
import { createMockTerminal } from './helpers.js';
|
||||||
import { ZerolagInputAddon } from '../src/zerolag-input-addon.js';
|
import { ZerolagInputAddon } from '../src/zerolag-input-addon.js';
|
||||||
import type { InputEndAnchor } from '../src/types.js';
|
import type { InputEndAnchor } from '../src/types.js';
|
||||||
@@ -103,6 +103,28 @@ describe('ZerolagInputAddon', () => {
|
|||||||
expect(addon.pendingText).toBe('');
|
expect(addon.pendingText).toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['combining accent', 'a', '\u0301'],
|
||||||
|
['skin-tone modifier', '\u{1F44D}', '\u{1F3FD}'],
|
||||||
|
])('removes a %s cluster across the pending/flushed boundary', (_name, base, suffix) => {
|
||||||
|
const { addon } = tracked();
|
||||||
|
addon.setFlushed(base.length, base);
|
||||||
|
addon.appendText(suffix);
|
||||||
|
expect(addon.removeChar()).toBe('flushed');
|
||||||
|
expect(addon.getFlushed()).toEqual({ count: 0, text: '' });
|
||||||
|
expect(addon.pendingText).toBe('');
|
||||||
|
expect(addon.state.visible).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps flushed text when removing a separate pending character', () => {
|
||||||
|
const { addon } = tracked();
|
||||||
|
addon.setFlushed(1, 'a');
|
||||||
|
addon.appendText('b');
|
||||||
|
expect(addon.removeChar()).toBe('pending');
|
||||||
|
expect(addon.getFlushed()).toEqual({ count: 1, text: 'a' });
|
||||||
|
expect(addon.pendingText).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
it('removes a whole flushed emoji and subtracts its UTF-16 width', () => {
|
it('removes a whole flushed emoji and subtracts its UTF-16 width', () => {
|
||||||
const { addon } = tracked();
|
const { addon } = tracked();
|
||||||
addon.setFlushed(3, 'a😀');
|
addon.setFlushed(3, 'a😀');
|
||||||
@@ -141,6 +163,34 @@ describe('ZerolagInputAddon', () => {
|
|||||||
expect(addon.pendingText).toBe('ok');
|
expect(addon.pendingText).toBe('ok');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('removes a cluster longer than 64 UTF-16 units in one call', () => {
|
||||||
|
const { addon } = tracked();
|
||||||
|
// `a` plus 80 combining acute accents is one grapheme cluster of 81 units.
|
||||||
|
const cluster = 'a' + '\u0301'.repeat(80);
|
||||||
|
addon.appendText('ok' + cluster);
|
||||||
|
expect(addon.removeChar()).toBe('pending');
|
||||||
|
expect(addon.pendingText).toBe('ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pairs regional indicators from the start of the run', () => {
|
||||||
|
const { addon } = tracked();
|
||||||
|
// Five flags then a lone indicator: the last cluster is the lone one, not a pair.
|
||||||
|
const flags = '\u{1F1EB}\u{1F1F7}'.repeat(5);
|
||||||
|
addon.appendText('ok' + flags + '\u{1F1EB}');
|
||||||
|
expect(addon.removeChar()).toBe('pending');
|
||||||
|
expect(addon.pendingText).toBe('ok' + flags);
|
||||||
|
expect(addon.removeChar()).toBe('pending');
|
||||||
|
expect(addon.pendingText).toBe('ok' + '\u{1F1EB}\u{1F1F7}'.repeat(4));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('removes the last grapheme of a long draft', () => {
|
||||||
|
const { addon } = tracked();
|
||||||
|
const family = '\u{1F468}\u200D\u{1F469}\u200D\u{1F467}\u200D\u{1F466}';
|
||||||
|
addon.appendText('a'.repeat(60000) + family);
|
||||||
|
expect(addon.removeChar()).toBe('pending');
|
||||||
|
expect(addon.pendingText).toBe('a'.repeat(60000));
|
||||||
|
});
|
||||||
|
|
||||||
it.each(graphemeCases)('removes a whole flushed %s grapheme and subtracts its UTF-16 width', (_name, emoji) => {
|
it.each(graphemeCases)('removes a whole flushed %s grapheme and subtracts its UTF-16 width', (_name, emoji) => {
|
||||||
const { addon } = tracked();
|
const { addon } = tracked();
|
||||||
const text = 'ok' + emoji;
|
const text = 'ok' + emoji;
|
||||||
@@ -1051,4 +1101,142 @@ describe('input end anchor and layout subscriptions', () => {
|
|||||||
expect(() => addon.clear()).not.toThrow();
|
expect(() => addon.clear()).not.toThrow();
|
||||||
expect(anchors).toEqual([{ col: 5, row: 1 }, null]);
|
expect(anchors).toEqual([{ col: 5, row: 1 }, null]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('maps a wide wrap with forward affinity from column 78', () => {
|
||||||
|
const { addon } = layoutSetup({ cols: 80 });
|
||||||
|
addon.setPrompt({ type: 'custom', offset: 0, find: () => ({ col: 78, row: 1 }) });
|
||||||
|
addon.appendText('a你b');
|
||||||
|
expect([0, 1, 2, 3].map((offset) => addon.getInputAnchor(offset))).toEqual([
|
||||||
|
{ col: 78, row: 1 },
|
||||||
|
{ col: 0, row: 2 },
|
||||||
|
{ col: 2, row: 2 },
|
||||||
|
{ col: 3, row: 2 },
|
||||||
|
]);
|
||||||
|
expect(addon.getInputEndAnchor()).toEqual({ col: 3, row: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps multiple wide wraps including an empty prompt line', () => {
|
||||||
|
const { addon } = layoutSetup({ cols: 5 });
|
||||||
|
addon.setPrompt({ type: 'custom', offset: 0, find: () => ({ col: 4, row: 1 }) });
|
||||||
|
addon.appendText('你好世界a你b');
|
||||||
|
expect([0, 1, 2, 3, 4, 5, 6, 7].map((offset) => addon.getInputAnchor(offset))).toEqual([
|
||||||
|
{ col: 0, row: 2 },
|
||||||
|
{ col: 2, row: 2 },
|
||||||
|
{ col: 0, row: 3 },
|
||||||
|
{ col: 2, row: 3 },
|
||||||
|
{ col: 4, row: 3 },
|
||||||
|
{ col: 0, row: 4 },
|
||||||
|
{ col: 2, row: 4 },
|
||||||
|
{ col: 3, row: 4 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps ZWJ code points and combining marks without accepting surrogate interiors', () => {
|
||||||
|
const { addon, mock } = layoutSetup();
|
||||||
|
Object.assign(mock.terminal, {
|
||||||
|
unicode: {
|
||||||
|
getStringCellWidth: (ch: string) => (ch === '\u200d' || ch === '\u0301' ? 0 : ch.length === 2 ? 2 : 1),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
addon.appendText('👩\u200d💻e\u0301x');
|
||||||
|
expect([0, 1, 2, 3, 4, 5, 6, 7, 8].map((offset) => addon.getInputAnchor(offset))).toEqual([
|
||||||
|
{ col: 2, row: 1 },
|
||||||
|
null,
|
||||||
|
{ col: 4, row: 1 },
|
||||||
|
{ col: 4, row: 1 },
|
||||||
|
null,
|
||||||
|
{ col: 6, row: 1 },
|
||||||
|
{ col: 7, row: 1 },
|
||||||
|
{ col: 7, row: 1 },
|
||||||
|
{ col: 8, row: 1 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('queries the composition tail but exposes only the last displayed committed text', () => {
|
||||||
|
const { addon } = layoutSetup({ cols: 8 });
|
||||||
|
addon.setFlushed(2, '😀');
|
||||||
|
addon.appendText('ab');
|
||||||
|
addon.setComposition('你好');
|
||||||
|
expect(addon.committedText).toBe('😀ab');
|
||||||
|
expect(addon.getInputAnchor(4)).toEqual({ col: 6, row: 1 });
|
||||||
|
expect(addon.getInputAnchor(5)).toEqual({ col: 0, row: 2 });
|
||||||
|
expect(addon.getInputAnchor(6)).toEqual({ col: 2, row: 2 });
|
||||||
|
expect(addon.getInputEndAnchor()).toEqual({ col: 2, row: 2 });
|
||||||
|
addon.setFlushed(2, 'zz', false);
|
||||||
|
expect(addon.committedText).toBe('😀ab');
|
||||||
|
expect(addon.state).not.toHaveProperty('committedText');
|
||||||
|
expect(addon.state).not.toHaveProperty('composition');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses upward growth and hides tail-sliced caret rows', () => {
|
||||||
|
const { addon } = layoutSetup({ cols: 6, rows: 4, promptRow: 3 });
|
||||||
|
addon.appendText('abcdefghijkl'); // abcd / efghij / kl
|
||||||
|
expect(addon.getInputAnchor(0)).toEqual({ col: 2, row: 1 });
|
||||||
|
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 2 });
|
||||||
|
expect(addon.getInputAnchor(10)).toEqual({ col: 0, row: 3 });
|
||||||
|
addon.setRowLimit(2);
|
||||||
|
expect(addon.getInputAnchor(0)).toBeNull();
|
||||||
|
expect(addon.getInputAnchor(3)).toBeNull();
|
||||||
|
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 0 });
|
||||||
|
expect(addon.getInputAnchor(10)).toEqual({ col: 0, row: 1 });
|
||||||
|
expect(addon.getInputAnchor(12)).toEqual({ col: 2, row: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the final offset at the right edge of a full final row', () => {
|
||||||
|
const { addon } = layoutSetup({ cols: 6 });
|
||||||
|
addon.appendText('abcdefghij');
|
||||||
|
expect(addon.getInputAnchor(4)).toEqual({ col: 0, row: 2 });
|
||||||
|
expect(addon.getInputAnchor(10)).toEqual({ col: 6, row: 2 });
|
||||||
|
expect(addon.getInputEndAnchor()).toEqual({ col: 6, row: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does no width measurement for a redundant render or an anchor query', () => {
|
||||||
|
const { addon, mock } = layoutSetup();
|
||||||
|
const width = vi.fn((ch: string) => (ch === '你' ? 2 : 1));
|
||||||
|
Object.assign(mock.terminal, { unicode: { getStringCellWidth: width } });
|
||||||
|
addon.setFlushed(3, 'a你b');
|
||||||
|
expect(width).toHaveBeenCalled();
|
||||||
|
width.mockClear();
|
||||||
|
addon.setFlushed(3, 'a你b'); // same key, unlike forced rerender()
|
||||||
|
expect(addon.getInputAnchor(1)).toEqual({ col: 3, row: 1 });
|
||||||
|
expect(addon.getInputAnchor(3)).toEqual({ col: 6, row: 1 });
|
||||||
|
expect(addon.committedText).toBe('a你b');
|
||||||
|
expect(width).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects invalid offsets and clears visual correspondence on hide and disposal', () => {
|
||||||
|
const { addon, mock } = layoutSetup();
|
||||||
|
expect(addon.getInputAnchor(0)).toBeNull();
|
||||||
|
expect(addon.committedText).toBe('');
|
||||||
|
addon.appendText('abc');
|
||||||
|
for (const offset of [-1, 4, 0.5, NaN, Infinity]) expect(addon.getInputAnchor(offset)).toBeNull();
|
||||||
|
mock.setScroll(0, 30);
|
||||||
|
mock.terminal.element.querySelector('.xterm-viewport')!.dispatchEvent(new Event('scroll'));
|
||||||
|
expect(addon.getInputAnchor(0)).toBeNull();
|
||||||
|
expect(addon.committedText).toBe('');
|
||||||
|
mock.setScroll(0, 0);
|
||||||
|
addon.rerender();
|
||||||
|
expect(addon.committedText).toBe('abc');
|
||||||
|
addon.clear();
|
||||||
|
expect(addon.getInputAnchor(0)).toBeNull();
|
||||||
|
expect(addon.committedText).toBe('');
|
||||||
|
addon.appendText('x');
|
||||||
|
addon.dispose();
|
||||||
|
expect(addon.getInputAnchor(0)).toBeNull();
|
||||||
|
expect(addon.committedText).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears offset anchors and committed text on render failure', () => {
|
||||||
|
const { addon } = layoutSetup();
|
||||||
|
addon.appendText('abc');
|
||||||
|
addon.setPrompt({
|
||||||
|
type: 'custom',
|
||||||
|
find: () => {
|
||||||
|
throw new Error('buffer unavailable');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(addon.getInputAnchor(0)).toBeNull();
|
||||||
|
expect(addon.committedText).toBe('');
|
||||||
|
expect(addon.pendingText).toBe('abc');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
* this script adds is FRESHNESS and independence from install time: a checkout
|
* this script adds is FRESHNESS and independence from install time: a checkout
|
||||||
* installed with `--ignore-scripts`, or one borrowing another tree's
|
* installed with `--ignore-scripts`, or one borrowing another tree's
|
||||||
* `node_modules`, never ran postinstall, and an edit to the zerolag package after
|
* `node_modules`, never ran postinstall, and an edit to the zerolag package after
|
||||||
* install leaves the bundle stale. It runs as `pretest:mobile`.
|
* install leaves the bundle stale. It runs as `pretest:mobile` and `pretest:browser`.
|
||||||
*
|
*
|
||||||
* Mirrors the vendor steps in scripts/build.mjs, targeting the source tree. Same
|
* Mirrors the vendor steps in scripts/build.mjs, targeting the source tree. Same
|
||||||
* inputs and output names, so the page markup needs no test-only branch. That
|
* inputs and output names, so the page markup needs no test-only branch. That
|
||||||
|
|||||||
+13
-10
@@ -17,10 +17,10 @@
|
|||||||
* and a lone digit at a pending dialog goes without it). Shift+Enter is a
|
* 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
|
* 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
|
* 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
|
* belongs to one session: a captured target takes precedence over _owner when
|
||||||
* restoreDraft() brings it back when the session is shown again, except a
|
* clear() stashes it, and restoreDraft() brings it back when that session is
|
||||||
* clear({ discard: true }) (the keyboard bar's clear-line key), which throws
|
* shown again, except a clear({ discard: true }) (the keyboard bar's clear-line
|
||||||
* it away.
|
* key), which throws it away.
|
||||||
*
|
*
|
||||||
* ## Android IME challenge
|
* ## Android IME challenge
|
||||||
*
|
*
|
||||||
@@ -91,10 +91,10 @@ const CjkInput = (() => {
|
|||||||
let _holdApplied = false;
|
let _holdApplied = false;
|
||||||
// Send-on-Enter: held drafts of the sessions switched away from, by session id.
|
// Send-on-Enter: held drafts of the sessions switched away from, by session id.
|
||||||
const _drafts = new Map();
|
const _drafts = new Map();
|
||||||
// Send-on-Enter: the session the field's text belongs to (the one last shown,
|
// Send-on-Enter: the session last shown, set by restoreDraft. A captured
|
||||||
// set by restoreDraft). clear() stashes a held draft under it, so every path
|
// target takes precedence; otherwise clear() stashes a held draft under this
|
||||||
// that drops the active session before the next cleanup (goHome, the tile
|
// owner, so paths that drop the active session before the next cleanup
|
||||||
// grid's _replaceTileGrid and _onTileAdoptedElsewhere) keeps the answer.
|
// (goHome, _replaceTileGrid and _onTileAdoptedElsewhere) keep the answer.
|
||||||
let _owner = null;
|
let _owner = null;
|
||||||
const _listeners = {};
|
const _listeners = {};
|
||||||
|
|
||||||
@@ -690,13 +690,15 @@ const CjkInput = (() => {
|
|||||||
// nothing is stashed, any older stash of this session goes too, and the
|
// nothing is stashed, any older stash of this session goes too, and the
|
||||||
// field keeps its owner, since the session shown has not changed.
|
// field keeps its owner, since the session shown has not changed.
|
||||||
if (_owner) _drafts.delete(_owner);
|
if (_owner) _drafts.delete(_owner);
|
||||||
|
if (_hasTarget && _target) _drafts.delete(_target);
|
||||||
} else {
|
} else {
|
||||||
// Send-on-Enter: a held draft is stashed for the session it was typed
|
// 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
|
// for, whichever path got here. discardDraft() drops the owner of a
|
||||||
// removed session, so its text is not stashed again.
|
// 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);
|
const draft = _strip(_textarea.value);
|
||||||
if (draft.trim()) _drafts.set(_owner, draft);
|
if (draft.trim()) _drafts.set(sessionId, draft);
|
||||||
}
|
}
|
||||||
_owner = null;
|
_owner = null;
|
||||||
}
|
}
|
||||||
@@ -785,6 +787,7 @@ const CjkInput = (() => {
|
|||||||
* clear(); restoreDraft() puts it back when that session is shown again.
|
* clear(); restoreDraft() puts it back when that session is shown again.
|
||||||
*/
|
*/
|
||||||
stashDraft(sessionId) {
|
stashDraft(sessionId) {
|
||||||
|
if (_hasTarget && _target) sessionId = _target;
|
||||||
if (!_initialized || !_textarea || !_hold || !sessionId) return;
|
if (!_initialized || !_textarea || !_hold || !sessionId) return;
|
||||||
// An empty field leaves any stash alone: a draft only sits in the map
|
// 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
|
// while its session is not shown (restoreDraft takes it out), and the
|
||||||
|
|||||||
@@ -1231,7 +1231,9 @@ const KeyboardAccessoryBar = {
|
|||||||
this.flushPendingThen('\t');
|
this.flushPendingThen('\t');
|
||||||
break;
|
break;
|
||||||
case 'shift-tab':
|
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;
|
break;
|
||||||
case 'ctrl-o':
|
case 'ctrl-o':
|
||||||
this.sendKey('\x0f');
|
this.sendKey('\x0f');
|
||||||
@@ -1401,9 +1403,10 @@ const KeyboardAccessoryBar = {
|
|||||||
|
|
||||||
/** Send a special key (arrow, escape, etc.) directly to the PTY.
|
/** Send a special key (arrow, escape, etc.) directly to the PTY.
|
||||||
* Bypasses tmux send-keys -l (literal mode) since escape sequences
|
* Bypasses tmux send-keys -l (literal mode) since escape sequences
|
||||||
* must be written raw to be interpreted as key presses by Ink. */
|
* must be written raw to be interpreted as key presses by Ink.
|
||||||
sendKey(escapeSequence) {
|
* `keepDraft` leaves the unsent local-echo draft in the overlay. */
|
||||||
const sessionId = this._prepareInput(undefined, 'accessory-key', { flushEcho: true });
|
sendKey(escapeSequence, { keepDraft = false } = {}) {
|
||||||
|
const sessionId = this._prepareInput(undefined, 'accessory-key', keepDraft ? undefined : { flushEcho: true });
|
||||||
if (!sessionId) return;
|
if (!sessionId) return;
|
||||||
app._predictiveEcho?.clearPredictions();
|
app._predictiveEcho?.clearPredictions();
|
||||||
app._enqueueInput(sessionId, [{ write: escapeSequence }]);
|
app._enqueueInput(sessionId, [{ write: escapeSequence }]);
|
||||||
@@ -1422,6 +1425,7 @@ const KeyboardAccessoryBar = {
|
|||||||
directoriesOnly: false,
|
directoriesOnly: false,
|
||||||
onSelect: (path) => {
|
onSelect: (path) => {
|
||||||
const targetPane = app._paneForSession?.(sessionId);
|
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)) {
|
if (targetPane?.isPrimary && app._localEchoEnabled && app._localEchoOverlay && !app._echoPassthroughSessions?.has(sessionId)) {
|
||||||
app._prepareExternalInput?.(targetPane, 'accessory-path');
|
app._prepareExternalInput?.(targetPane, 'accessory-path');
|
||||||
app._localEchoOverlay.appendText(path);
|
app._localEchoOverlay.appendText(path);
|
||||||
@@ -1637,7 +1641,7 @@ const KeyboardAccessoryBar = {
|
|||||||
};
|
};
|
||||||
syncUploadUi();
|
syncUploadUi();
|
||||||
try {
|
try {
|
||||||
const paths = await app._uploadAndInsertImages(images, { insert: false });
|
const paths = await app._uploadAndInsertImages(images, { insert: false, sessionId });
|
||||||
if (paths?.length) {
|
if (paths?.length) {
|
||||||
const currentOverlay =
|
const currentOverlay =
|
||||||
this._composerOverlay?.isConnected && this._composerOverlay.dataset.sessionId === sessionId
|
this._composerOverlay?.isConnected && this._composerOverlay.dataset.sessionId === sessionId
|
||||||
|
|||||||
@@ -35,8 +35,8 @@
|
|||||||
|
|
||||||
function editBetween(previous, next) {
|
function editBetween(previous, next) {
|
||||||
// A pure append (including a combining mark or tone typed onto the last letter)
|
// 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
|
// is sent as-is, as xterm sends it: re-typing the extended cluster would make
|
||||||
// code-point line editor (zsh) double the base letter.
|
// a code-point line editor (zsh) double the base letter.
|
||||||
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
|
if (next.startsWith(previous)) return { deleted: 0, inserted: next.slice(previous.length) };
|
||||||
const a = graphemes(previous);
|
const a = graphemes(previous);
|
||||||
const b = graphemes(next);
|
const b = graphemes(next);
|
||||||
@@ -213,29 +213,26 @@
|
|||||||
const caret = guard(
|
const caret = guard(
|
||||||
'caret',
|
'caret',
|
||||||
function () {
|
function () {
|
||||||
const value = Array.from(project(textarea.value));
|
const text = project(textarea.value);
|
||||||
const index = Array.from(project(textarea.value.slice(0, textarea.selectionEnd))).length;
|
const offset = 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. */
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
visible:
|
visible:
|
||||||
!destroyed &&
|
!destroyed &&
|
||||||
textarea.ownerDocument.activeElement === textarea &&
|
textarea.ownerDocument.activeElement === textarea &&
|
||||||
!composing &&
|
!composing &&
|
||||||
textarea.selectionStart === textarea.selectionEnd &&
|
textarea.selectionStart === textarea.selectionEnd &&
|
||||||
index < value.length,
|
offset < text.length &&
|
||||||
cellsFromEnd,
|
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;
|
let previousCaret;
|
||||||
notifyCaret = function () {
|
notifyCaret = function () {
|
||||||
@@ -243,7 +240,9 @@
|
|||||||
if (
|
if (
|
||||||
previousCaret &&
|
previousCaret &&
|
||||||
previousCaret.visible === current.visible &&
|
previousCaret.visible === current.visible &&
|
||||||
previousCaret.cellsFromEnd === current.cellsFromEnd
|
previousCaret.text === current.text &&
|
||||||
|
previousCaret.offset === current.offset &&
|
||||||
|
previousCaret.generation === current.generation
|
||||||
)
|
)
|
||||||
return;
|
return;
|
||||||
previousCaret = current;
|
previousCaret = current;
|
||||||
@@ -352,6 +351,7 @@
|
|||||||
sendTransaction(ops);
|
sendTransaction(ops);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
record({ type: 'error', hook: 'sendTransaction', error });
|
record({ type: 'error', hook: 'sendTransaction', error });
|
||||||
|
invalidated = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Empty/deletion-only compositions still settle the visual preview.
|
// Empty/deletion-only compositions still settle the visual preview.
|
||||||
@@ -389,6 +389,7 @@
|
|||||||
if (ev.type === 'keypress') return false;
|
if (ev.type === 'keypress') return false;
|
||||||
if (ev.type === 'keyup') return textarea.ownerDocument.activeElement === textarea;
|
if (ev.type === 'keyup') return textarea.ownerDocument.activeElement === textarea;
|
||||||
if (ev.type !== 'keydown') return true;
|
if (ev.type !== 'keydown') return true;
|
||||||
|
restoreForeign();
|
||||||
const kind = composing ? 'compose' : classifyKey(ev, textarea);
|
const kind = composing ? 'compose' : classifyKey(ev, textarea);
|
||||||
if (kind === 'compose') {
|
if (kind === 'compose') {
|
||||||
schedule();
|
schedule();
|
||||||
@@ -418,7 +419,8 @@
|
|||||||
target.addEventListener(type, listener, true);
|
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;
|
return false;
|
||||||
});
|
});
|
||||||
patch(helper, '_handleAnyTextareaChanges', schedule);
|
patch(helper, '_handleAnyTextareaChanges', schedule);
|
||||||
@@ -499,6 +501,7 @@
|
|||||||
direction: textarea.selectionDirection,
|
direction: textarea.selectionDirection,
|
||||||
synced,
|
synced,
|
||||||
};
|
};
|
||||||
|
notifyCaret();
|
||||||
},
|
},
|
||||||
terminal.element
|
terminal.element
|
||||||
);
|
);
|
||||||
@@ -557,20 +560,80 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// This is a visual projection only: native caret changes never become keys.
|
// Visual only: an anchor(caret) supplies the exact viewport cell, 'hide', or
|
||||||
// `options.anchor()` returns the viewport cell `{col, row}` where the VISIBLE line
|
// null to resolve against parsed xterm cells. Neither mode moves native input.
|
||||||
// ends (where the next typed character would appear), 'hide' to hide the
|
// subscribe(callback) follows overlay repaints without an xterm render.
|
||||||
// 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
|
function bufferCaretAnchor(terminal, caret) {
|
||||||
// cursor stays at the prompt, so the overlay must supply that anchor. Without an
|
const buffer = terminal.buffer.active;
|
||||||
// anchor the xterm cursor is used, which is right whenever every byte reached
|
const text = caret.text;
|
||||||
// the PTY (local echo off, tiles).
|
if (!text || caret.offset < 0 || caret.offset > text.length) return null;
|
||||||
// `options.subscribe(callback)` returns a disposer and is used to reposition
|
let row = buffer.baseY + buffer.cursorY;
|
||||||
// when the anchor moves without an xterm render (overlay repaint).
|
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) {
|
function attachCaretMarker(terminal, owner, options) {
|
||||||
const anchor = options && typeof options.anchor === 'function' ? options.anchor : null;
|
const anchor = options && typeof options.anchor === 'function' ? options.anchor : null;
|
||||||
const disposables = [];
|
const disposables = [];
|
||||||
let marker;
|
let marker;
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
|
let caretGeneration = 0;
|
||||||
|
let awaitingEcho = false;
|
||||||
function dispose() {
|
function dispose() {
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
disposed = true;
|
disposed = true;
|
||||||
@@ -586,6 +649,7 @@
|
|||||||
try {
|
try {
|
||||||
const screen = terminal.element && terminal.element.querySelector('.xterm-screen');
|
const screen = terminal.element && terminal.element.querySelector('.xterm-screen');
|
||||||
if (!screen || !owner || typeof owner.caret !== 'function' || typeof owner.onCaret !== 'function') return dispose;
|
if (!screen || !owner || typeof owner.caret !== 'function' || typeof owner.onCaret !== 'function') return dispose;
|
||||||
|
caretGeneration = owner.caret().generation;
|
||||||
marker = screen.ownerDocument.createElement('div');
|
marker = screen.ownerDocument.createElement('div');
|
||||||
marker.className = 'ios-native-caret';
|
marker.className = 'ios-native-caret';
|
||||||
marker.setAttribute('aria-hidden', 'true');
|
marker.setAttribute('aria-hidden', 'true');
|
||||||
@@ -597,41 +661,50 @@
|
|||||||
const core = terminal._core;
|
const core = terminal._core;
|
||||||
const dimensions = core && core._renderService && core._renderService.dimensions;
|
const dimensions = core && core._renderService && core._renderService.dimensions;
|
||||||
const cell = dimensions && dimensions.css && dimensions.css.cell;
|
const cell = dimensions && dimensions.css && dimensions.css.cell;
|
||||||
const buffer = terminal.buffer.active;
|
|
||||||
if (disposed || !caret.visible || !cell || !cell.width || !cell.height || !terminal.cols) {
|
if (disposed || !caret.visible || !cell || !cell.width || !cell.height || !terminal.cols) {
|
||||||
marker.style.display = 'none';
|
marker.style.display = 'none';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let end = null;
|
let target = null;
|
||||||
if (anchor) {
|
if (anchor) {
|
||||||
try {
|
try {
|
||||||
end = anchor();
|
target = anchor(caret);
|
||||||
} catch (_) {
|
} 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';
|
marker.style.display = 'none';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (end == null) end = { col: buffer.cursorX, row: buffer.cursorY + buffer.baseY - buffer.viewportY };
|
marker.style.display = 'block';
|
||||||
let column = end.col - caret.cellsFromEnd;
|
marker.style.left = target.col * cell.width + 'px';
|
||||||
let row = end.row;
|
marker.style.top = target.row * cell.height + 'px';
|
||||||
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.height = cell.height + 'px';
|
marker.style.height = cell.height + 'px';
|
||||||
marker.style.backgroundColor = (terminal.options.theme && terminal.options.theme.cursor) || 'currentColor';
|
marker.style.backgroundColor = (terminal.options.theme && terminal.options.theme.cursor) || 'currentColor';
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
marker.style.display = 'none';
|
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']) {
|
for (const name of ['onRender', 'onCursorMove']) {
|
||||||
if (typeof terminal[name] === 'function') {
|
if (typeof terminal[name] === 'function') {
|
||||||
const subscription = terminal[name](position);
|
const subscription = terminal[name](position);
|
||||||
|
|||||||
@@ -660,6 +660,7 @@
|
|||||||
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
|
isScreenReaderMode: () => this.terminal?.options?.screenReaderMode === true,
|
||||||
});
|
});
|
||||||
if (this._iosNativeInput) {
|
if (this._iosNativeInput) {
|
||||||
|
// Tiles have no local-echo overlay: resolve only from verified parsed cells.
|
||||||
this._iosCaretMarker = nativeInput.attachCaretMarker(this.terminal, this._iosNativeInput);
|
this._iosCaretMarker = nativeInput.attachCaretMarker(this.terminal, this._iosNativeInput);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -678,6 +679,7 @@
|
|||||||
// through unchanged, but it still disarms, so the next `c` stays a `c`.
|
// through unchanged, but it still disarms, so the next `c` stays a `c`.
|
||||||
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
|
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
|
||||||
ctrlIndex = ops.findIndex((data) => data !== '\x7f');
|
ctrlIndex = ops.findIndex((data) => data !== '\x7f');
|
||||||
|
if (ctrlIndex === -1 && ops.includes('\x7f')) KeyboardAccessoryBar.clearCtrl?.();
|
||||||
}
|
}
|
||||||
// Keep replacement deletions: Ctrl changes only the insertion, once for
|
// Keep replacement deletions: Ctrl changes only the insertion, once for
|
||||||
// this edit, never once per DEL. Tiles have no local echo to reconcile.
|
// this edit, never once per DEL. Tiles have no local echo to reconcile.
|
||||||
|
|||||||
@@ -766,7 +766,7 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
});
|
});
|
||||||
if (this._iosNativeInput) {
|
if (this._iosNativeInput) {
|
||||||
this._iosCaretMarker = window.CodemanIosNativeInput.attachCaretMarker?.(this.terminal, 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),
|
subscribe: (callback) => this._localEchoOverlay?.onLayout?.(callback),
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
@@ -787,11 +787,16 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
_nativeInputAnchor() {
|
_nativeInputCaretAnchor(caret) {
|
||||||
const overlay = this._localEchoOverlay;
|
const overlay = this._localEchoOverlay;
|
||||||
if (this._localEchoEnabled && !this._echoPassthroughSessions?.has(this.activeSessionId) &&
|
if (
|
||||||
(overlay?.pendingText || overlay?.getFlushed?.().count)) {
|
this._localEchoEnabled &&
|
||||||
return overlay.getInputEndAnchor?.() || 'hide';
|
!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;
|
return null;
|
||||||
},
|
},
|
||||||
@@ -865,6 +870,8 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
submitFromToolbar() {
|
submitFromToolbar() {
|
||||||
const pane = this._focusedPane();
|
const pane = this._focusedPane();
|
||||||
if (!pane?.terminal || !pane.sessionId || pane.tile?._destroyed || !this.sessions.has(pane.sessionId)) return;
|
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),
|
// 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.
|
// so its scrollOnUserInput never runs; scroll to the prompt as it would.
|
||||||
const terminal = pane.terminal;
|
const terminal = pane.terminal;
|
||||||
@@ -887,6 +894,7 @@ Object.assign(CodemanApp.prototype, {
|
|||||||
let ctrlIndex = -1;
|
let ctrlIndex = -1;
|
||||||
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
|
if (typeof KeyboardAccessoryBar !== 'undefined' && KeyboardAccessoryBar.isCtrlArmed?.()) {
|
||||||
ctrlIndex = ops.findIndex((data) => data !== '\x7f' && !window.CodemanTerminalInput?.isTerminalFocusOrMouseReport(data));
|
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++) {
|
for (let i = 0; i < ops.length; i++) {
|
||||||
const data = i === ctrlIndex ? KeyboardAccessoryBar.consumeCtrl(ops[i]) : ops[i];
|
const data = i === ctrlIndex ? KeyboardAccessoryBar.consumeCtrl(ops[i]) : ops[i];
|
||||||
|
|||||||
@@ -1097,6 +1097,7 @@ const VoiceInput = {
|
|||||||
// If a compose overlay is already open, populate its textarea instead of recreating
|
// If a compose overlay is already open, populate its textarea instead of recreating
|
||||||
const existingTextarea = document.querySelector('.voice-compose-overlay .paste-textarea');
|
const existingTextarea = document.querySelector('.voice-compose-overlay .paste-textarea');
|
||||||
if (existingTextarea) {
|
if (existingTextarea) {
|
||||||
|
existingTextarea.closest('.voice-compose-overlay').dataset.targetSessionId = target;
|
||||||
existingTextarea.value = trimmed;
|
existingTextarea.value = trimmed;
|
||||||
existingTextarea.focus();
|
existingTextarea.focus();
|
||||||
existingTextarea.selectionStart = existingTextarea.selectionEnd = trimmed.length;
|
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 */
|
/** Show an editable compose overlay so the user can review/edit before sending */
|
||||||
_showComposeOverlay(text) {
|
_showComposeOverlay(text) {
|
||||||
const target = this._targetSession();
|
|
||||||
document.querySelector('.voice-compose-overlay')?.remove();
|
document.querySelector('.voice-compose-overlay')?.remove();
|
||||||
const overlay = document.createElement('div');
|
const overlay = document.createElement('div');
|
||||||
overlay.className = 'voice-compose-overlay paste-overlay';
|
overlay.className = 'voice-compose-overlay paste-overlay';
|
||||||
|
overlay.dataset.targetSessionId = this._targetSession();
|
||||||
overlay.innerHTML = `
|
overlay.innerHTML = `
|
||||||
<div class="paste-dialog">
|
<div class="paste-dialog">
|
||||||
<textarea class="paste-textarea">${text.replace(/</g, '<')}</textarea>
|
<textarea class="paste-textarea">${text.replace(/</g, '<')}</textarea>
|
||||||
@@ -1234,7 +1235,7 @@ const VoiceInput = {
|
|||||||
const send = () => {
|
const send = () => {
|
||||||
const val = textarea.value.trim();
|
const val = textarea.value.trim();
|
||||||
overlay.remove();
|
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 cancel = () => overlay.remove();
|
||||||
const newInput = () => {
|
const newInput = () => {
|
||||||
|
|||||||
Vendored
+51
-16
@@ -6,22 +6,32 @@
|
|||||||
|
|
||||||
function kev(type, key, keyCode, extra = {}) {
|
function kev(type, key, keyCode, extra = {}) {
|
||||||
const ev = new KeyboardEvent(type, {
|
const ev = new KeyboardEvent(type, {
|
||||||
key, code: extra.code || (key === 'Backspace' ? 'Backspace' : 'Unidentified'),
|
key,
|
||||||
bubbles: true, cancelable: true, composed: true,
|
code: extra.code || (key === 'Backspace' ? 'Backspace' : 'Unidentified'),
|
||||||
ctrlKey: !!extra.ctrlKey, shiftKey: !!extra.shiftKey,
|
bubbles: true,
|
||||||
altKey: !!extra.altKey, metaKey: !!extra.metaKey, isComposing: !!extra.isComposing,
|
cancelable: true,
|
||||||
|
composed: true,
|
||||||
|
ctrlKey: !!extra.ctrlKey,
|
||||||
|
shiftKey: !!extra.shiftKey,
|
||||||
|
altKey: !!extra.altKey,
|
||||||
|
metaKey: !!extra.metaKey,
|
||||||
|
isComposing: !!extra.isComposing,
|
||||||
});
|
});
|
||||||
Object.defineProperties(ev, {
|
Object.defineProperties(ev, {
|
||||||
keyCode: { get: () => keyCode }, which: { get: () => keyCode },
|
keyCode: { get: () => keyCode },
|
||||||
charCode: { get: () => type === 'keypress' ? keyCode : 0 },
|
which: { get: () => keyCode },
|
||||||
|
charCode: { get: () => (type === 'keypress' ? keyCode : 0) },
|
||||||
});
|
});
|
||||||
return ev;
|
return ev;
|
||||||
}
|
}
|
||||||
|
|
||||||
function iev(type, inputType, data, options = {}) {
|
function iev(type, inputType, data, options = {}) {
|
||||||
return new InputEvent(type, {
|
return new InputEvent(type, {
|
||||||
inputType, data: data ?? null,
|
inputType,
|
||||||
bubbles: true, cancelable: type === 'beforeinput', composed: true,
|
data: data ?? null,
|
||||||
|
bubbles: true,
|
||||||
|
cancelable: type === 'beforeinput',
|
||||||
|
composed: true,
|
||||||
isComposing: !!options.isComposing,
|
isComposing: !!options.isComposing,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -35,12 +45,17 @@
|
|||||||
if (inputType === 'deleteContentBackward') {
|
if (inputType === 'deleteContentBackward') {
|
||||||
if (start === end) {
|
if (start === end) {
|
||||||
if (start === 0) return false;
|
if (start === 0) return false;
|
||||||
start -= Array.from(value.slice(0, start)).pop().length;
|
const segments = new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(value.slice(0, start));
|
||||||
|
start -= Array.from(segments).pop().segment.length;
|
||||||
}
|
}
|
||||||
setValue.call(ta, value.slice(0, start) + value.slice(end));
|
setValue.call(ta, value.slice(0, start) + value.slice(end));
|
||||||
select.call(ta, start, start);
|
select.call(ta, start, start);
|
||||||
} else if (inputType === 'insertText' || inputType === 'insertReplacementText' ||
|
} else if (
|
||||||
inputType === 'insertCompositionText' || inputType === 'insertLineBreak') {
|
inputType === 'insertText' ||
|
||||||
|
inputType === 'insertReplacementText' ||
|
||||||
|
inputType === 'insertCompositionText' ||
|
||||||
|
inputType === 'insertLineBreak'
|
||||||
|
) {
|
||||||
const text = inputType === 'insertLineBreak' ? '\n' : data;
|
const text = inputType === 'insertLineBreak' ? '\n' : data;
|
||||||
setValue.call(ta, value.slice(0, start) + text + value.slice(end));
|
setValue.call(ta, value.slice(0, start) + text + value.slice(end));
|
||||||
// Textarea values normalize CRLF. Use the normalized inserted length.
|
// Textarea values normalize CRLF. Use the normalized inserted length.
|
||||||
@@ -66,7 +81,11 @@
|
|||||||
// caret advance in the intact field as real browser defaults would.
|
// caret advance in the intact field as real browser defaults would.
|
||||||
function capturedEdits(ta, records, afterInput, afterEvent) {
|
function capturedEdits(ta, records, afterInput, afterEvent) {
|
||||||
const select = HTMLTextAreaElement.prototype.setSelectionRange;
|
const select = HTMLTextAreaElement.prototype.setSelectionRange;
|
||||||
const decode = value => value.replace(/<LF>/g, '\n').replace(/<CR>/g, '\r').replace(/<NBSP>/g, '\u00a0');
|
const decode = (value) =>
|
||||||
|
value
|
||||||
|
.replace(/<LF>/g, '\n')
|
||||||
|
.replace(/<CR>/g, '\r')
|
||||||
|
.replace(/<NBSP>/g, '\u00a0');
|
||||||
let pending;
|
let pending;
|
||||||
for (const record of records) {
|
for (const record of records) {
|
||||||
if (record.kind !== 'ev' || !['beforeinput', 'input'].includes(record.type)) continue;
|
if (record.kind !== 'ev' || !['beforeinput', 'input'].includes(record.type)) continue;
|
||||||
@@ -142,12 +161,28 @@
|
|||||||
function paste(ta, text) {
|
function paste(ta, text) {
|
||||||
const clipboardData = new DataTransfer();
|
const clipboardData = new DataTransfer();
|
||||||
clipboardData.setData('text/plain', text);
|
clipboardData.setData('text/plain', text);
|
||||||
ta.dispatchEvent(new ClipboardEvent('paste', {
|
ta.dispatchEvent(
|
||||||
clipboardData, bubbles: true, cancelable: true, composed: true,
|
new ClipboardEvent('paste', {
|
||||||
}));
|
clipboardData,
|
||||||
|
bubbles: true,
|
||||||
|
cancelable: true,
|
||||||
|
composed: true,
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
global.IosReplay = Object.freeze({
|
global.IosReplay = Object.freeze({
|
||||||
kev, iev, edit, capturedEdits, typeKey, backspace, holdDeleteRepeat, replaceSuggestion, enter, caret, composition, paste,
|
kev,
|
||||||
|
iev,
|
||||||
|
edit,
|
||||||
|
capturedEdits,
|
||||||
|
typeKey,
|
||||||
|
backspace,
|
||||||
|
holdDeleteRepeat,
|
||||||
|
replaceSuggestion,
|
||||||
|
enter,
|
||||||
|
caret,
|
||||||
|
composition,
|
||||||
|
paste,
|
||||||
});
|
});
|
||||||
})(window);
|
})(window);
|
||||||
@@ -54,7 +54,14 @@ function load({
|
|||||||
promptResult = true,
|
promptResult = true,
|
||||||
touch = true,
|
touch = true,
|
||||||
translate,
|
translate,
|
||||||
}: { hold?: boolean; promptResult?: boolean; touch?: boolean; translate?: (s: string) => string } = {}) {
|
captureTarget,
|
||||||
|
}: {
|
||||||
|
hold?: boolean;
|
||||||
|
promptResult?: boolean;
|
||||||
|
touch?: boolean;
|
||||||
|
translate?: (s: string) => string;
|
||||||
|
captureTarget?: () => string;
|
||||||
|
} = {}) {
|
||||||
const textarea = makeTextarea();
|
const textarea = makeTextarea();
|
||||||
const sent: string[] = [];
|
const sent: string[] = [];
|
||||||
const prompts: string[] = [];
|
const prompts: string[] = [];
|
||||||
@@ -88,6 +95,7 @@ function load({
|
|||||||
vm.runInContext(src, context, { filename: 'input-cjk.js' });
|
vm.runInContext(src, context, { filename: 'input-cjk.js' });
|
||||||
const CjkInput = vm.runInContext('CjkInput', context);
|
const CjkInput = vm.runInContext('CjkInput', context);
|
||||||
CjkInput.init({
|
CjkInput.init({
|
||||||
|
captureTarget,
|
||||||
send: (t: string) => sent.push(t),
|
send: (t: string) => sent.push(t),
|
||||||
sendPrompt: (t: string) => {
|
sendPrompt: (t: string) => {
|
||||||
prompts.push(t);
|
prompts.push(t);
|
||||||
@@ -438,6 +446,28 @@ describe('CJK input: Send on Enter', () => {
|
|||||||
expect(prompts).toEqual([]);
|
expect(prompts).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each([true, false])('a captured target owns the draft across clear (explicit stash: %s)', (stash) => {
|
||||||
|
const { CjkInput, textarea } = load({ captureTarget: () => 'session-b' });
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
type(textarea, 'answer for b');
|
||||||
|
if (stash) CjkInput.stashDraft('session-a');
|
||||||
|
CjkInput.clear();
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
CjkInput.restoreDraft('session-b');
|
||||||
|
expect(textarea.value).toBe(PHANTOM + 'answer for b');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clear({ discard }) also drops a stash under the captured target', () => {
|
||||||
|
const { CjkInput, textarea } = load({ captureTarget: () => 'session-b' });
|
||||||
|
CjkInput.restoreDraft('session-a');
|
||||||
|
type(textarea, 'answer for b');
|
||||||
|
CjkInput.stashDraft('session-b');
|
||||||
|
CjkInput.clear({ discard: true });
|
||||||
|
CjkInput.restoreDraft('session-b');
|
||||||
|
expect(textarea.value).toBe(PHANTOM);
|
||||||
|
});
|
||||||
|
|
||||||
it('a restored draft is held text: Backspace edits it without a DEL', () => {
|
it('a restored draft is held text: Backspace edits it without a DEL', () => {
|
||||||
const { CjkInput, textarea, sent } = load();
|
const { CjkInput, textarea, sent } = load();
|
||||||
type(textarea, 'ok');
|
type(textarea, 'ok');
|
||||||
|
|||||||
@@ -9,10 +9,11 @@ interface TestTerminal {
|
|||||||
textarea: HTMLTextAreaElement;
|
textarea: HTMLTextAreaElement;
|
||||||
element: HTMLElement;
|
element: HTMLElement;
|
||||||
write(text: string, callback: () => void): void;
|
write(text: string, callback: () => void): void;
|
||||||
|
cols: number;
|
||||||
scrollToTop(): void;
|
scrollToTop(): void;
|
||||||
buffer: { active: { cursorX: number; cursorY: number; viewportY: number; baseY: number } };
|
buffer: { active: { cursorX: number; cursorY: number; viewportY: number; baseY: number } };
|
||||||
_core: {
|
_core: {
|
||||||
_renderService: { dimensions: { css: { cell: { width: number } } } };
|
_renderService: { dimensions: { css: { cell: { width: number; height: number } } } };
|
||||||
_customKeyEventHandler(event: KeyboardEvent): boolean;
|
_customKeyEventHandler(event: KeyboardEvent): boolean;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -21,6 +22,9 @@ interface NativeOwner {
|
|||||||
}
|
}
|
||||||
interface TestApp {
|
interface TestApp {
|
||||||
terminal: TestTerminal;
|
terminal: TestTerminal;
|
||||||
|
fitAddon: { proposeDimensions(): { cols: number; rows: number } | undefined };
|
||||||
|
syncTerminalGeometry(): { cols: number; rows: number } | null;
|
||||||
|
_resizeTimeout: number | null;
|
||||||
activeSessionId: string;
|
activeSessionId: string;
|
||||||
sessions: Map<string, { id: string; mode: string; status?: string }>;
|
sessions: Map<string, { id: string; mode: string; status?: string }>;
|
||||||
_localEchoEnabled: boolean;
|
_localEchoEnabled: boolean;
|
||||||
@@ -143,6 +147,19 @@ describe('iOS native input served-app wiring (#830)', () => {
|
|||||||
}, action);
|
}, action);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function markerCell() {
|
||||||
|
return page.evaluate(() => {
|
||||||
|
const terminal = (window as unknown as TestWindow).app.terminal;
|
||||||
|
const marker = terminal.element.querySelector<HTMLElement>('.ios-native-caret')!;
|
||||||
|
const cell = terminal._core._renderService.dimensions.css.cell;
|
||||||
|
return {
|
||||||
|
display: marker.style.display,
|
||||||
|
col: Math.round(parseFloat(marker.style.left) / cell.width),
|
||||||
|
row: Math.round(parseFloat(marker.style.top) / cell.height),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
for (const echo of [false, true]) {
|
for (const echo of [false, true]) {
|
||||||
it(`suggestion commits hello once, and Enter preserves the 80ms gap (echo ${echo})`, async () => {
|
it(`suggestion commits hello once, and Enter preserves the 80ms gap (echo ${echo})`, async () => {
|
||||||
await setup(echo);
|
await setup(echo);
|
||||||
@@ -194,26 +211,54 @@ describe('iOS native input served-app wiring (#830)', () => {
|
|||||||
if (echo) expect(result.pending).toBe('lo');
|
if (echo) expect(result.pending).toBe('lo');
|
||||||
});
|
});
|
||||||
|
|
||||||
it(`trackpad caret marker sits after he in hello (echo ${echo})`, async () => {
|
it(`trackpad caret marker sits at cell (4, 0) after he in hello (echo ${echo})`, async () => {
|
||||||
await setup(echo);
|
await setup(echo);
|
||||||
await run(
|
await run(
|
||||||
"await type('hello'); if (!app._localEchoEnabled) await new Promise(resolve => app.terminal.write('hello', resolve)); r.caret(ta, 2);"
|
"await type('hello'); if (!app._localEchoEnabled) await new Promise(resolve => app.terminal.write('hello', resolve)); r.caret(ta, 2);"
|
||||||
);
|
);
|
||||||
const geometry = await page.evaluate(() => {
|
expect(await markerCell()).toEqual({ display: 'block', col: 4, row: 0 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it(`a你b wide wrap maps offsets to (78, 0), (0, 1), (2, 1) (echo ${echo})`, async () => {
|
||||||
|
await setup(echo);
|
||||||
|
await page.evaluate(async () => {
|
||||||
const app = (window as unknown as TestWindow).app;
|
const app = (window as unknown as TestWindow).app;
|
||||||
const marker = app.terminal.element.querySelector<HTMLElement>('.ios-native-caret')!;
|
const container = app.terminal.element.parentElement!;
|
||||||
|
const proposed = app.fitAddon.proposeDimensions()!;
|
||||||
const cell = app.terminal._core._renderService.dimensions.css.cell;
|
const cell = app.terminal._core._renderService.dimensions.css.cell;
|
||||||
const end = app._localEchoEnabled
|
// A raw terminal.resize(80, ...) is undone by the app's ResizeObserver.
|
||||||
? app._localEchoOverlay.getInputEndAnchor()
|
// Size its real box instead, so every subsequent auto-fit also yields 80.
|
||||||
: { col: app.terminal.buffer.active.cursorX, row: app.terminal.buffer.active.cursorY };
|
const width = parseFloat(getComputedStyle(container).width) + (80 - proposed.cols) * cell.width;
|
||||||
return {
|
container.style.width = container.style.minWidth = container.style.maxWidth = `${width}px`;
|
||||||
display: marker.style.display,
|
app.syncTerminalGeometry();
|
||||||
col: parseFloat(marker.style.left) / cell.width,
|
const layout = Promise.withResolvers<void>();
|
||||||
expected: end!.col - 3,
|
requestAnimationFrame(() => requestAnimationFrame(() => layout.resolve()));
|
||||||
};
|
await layout.promise;
|
||||||
});
|
});
|
||||||
expect(geometry.display).not.toBe('none');
|
// The real 300ms resize handler can clear the viewport; let it finish
|
||||||
expect(geometry.col).toBeCloseTo(geometry.expected, 1);
|
// before installing the prompt and typing the native field.
|
||||||
|
await page.waitForFunction(() => {
|
||||||
|
const app = (window as unknown as TestWindow).app;
|
||||||
|
return app.terminal.cols === 80 && app._resizeTimeout === null;
|
||||||
|
});
|
||||||
|
await page.evaluate(async () => {
|
||||||
|
const app = (window as unknown as TestWindow).app;
|
||||||
|
const written = Promise.withResolvers<void>();
|
||||||
|
app.terminal.write('\x1bc' + '.'.repeat(76) + '❯ ', written.resolve);
|
||||||
|
await written.promise;
|
||||||
|
});
|
||||||
|
await run(
|
||||||
|
"await type('a你b'); if (!app._localEchoEnabled) await new Promise(resolve => app.terminal.write('a你b', resolve));"
|
||||||
|
);
|
||||||
|
for (const [offset, col, row] of [
|
||||||
|
[0, 78, 0],
|
||||||
|
[1, 0, 1],
|
||||||
|
[2, 2, 1],
|
||||||
|
]) {
|
||||||
|
await run(`r.caret(ta, ${offset});`);
|
||||||
|
expect(await page.evaluate(() => (window as unknown as TestWindow).app.terminal.cols)).toBe(80);
|
||||||
|
expect(await markerCell()).toEqual({ display: 'block', col, row });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it(`typing while scrolled back returns the viewport to the prompt (echo ${echo})`, async () => {
|
it(`typing while scrolled back returns the viewport to the prompt (echo ${echo})`, async () => {
|
||||||
@@ -386,6 +431,21 @@ describe('iOS native input served-app wiring (#830)', () => {
|
|||||||
expect(result.sent).toEqual([]);
|
expect(result.sent).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
for (const echo of [false, true]) {
|
||||||
|
it.each([
|
||||||
|
['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}'],
|
||||||
|
])(`deletes a whole %s grapheme with one backspace (echo ${echo})`, async (_name, emoji) => {
|
||||||
|
await setup(echo);
|
||||||
|
const result = await run(`await type(${JSON.stringify('ok' + emoji)}); r.backspace(ta);`);
|
||||||
|
expect(result.value).toBe('ok');
|
||||||
|
expect(result.pending).toBe(echo ? 'ok' : '');
|
||||||
|
expect(result.sent.map((x) => x.input)).toEqual(echo ? [] : [...('ok' + emoji), '\x7f']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
it('a Pane B/grid TerminalTile owns suggestions for its session without 229 recovery', async () => {
|
it('a Pane B/grid TerminalTile owns suggestions for its session without 229 recovery', async () => {
|
||||||
await setup(false);
|
await setup(false);
|
||||||
const result = await page.evaluate(async () => {
|
const result = await page.evaluate(async () => {
|
||||||
|
|||||||
@@ -386,6 +386,7 @@ describe('mobile prompt composer', () => {
|
|||||||
|
|
||||||
it('uploads images without writing into the PTY and inserts their paths into the draft', async () => {
|
it('uploads images without writing into the PTY and inserts their paths into the draft', async () => {
|
||||||
const { app, bar, document } = loadComposer();
|
const { app, bar, document } = loadComposer();
|
||||||
|
app._focusedPane = () => ({ sessionId: 'session-2', isPrimary: false });
|
||||||
let finishUpload!: (paths: string[]) => void;
|
let finishUpload!: (paths: string[]) => void;
|
||||||
app._uploadAndInsertImages.mockImplementation(
|
app._uploadAndInsertImages.mockImplementation(
|
||||||
() => new Promise<string[]>((resolveUpload) => (finishUpload = resolveUpload))
|
() => new Promise<string[]>((resolveUpload) => (finishUpload = resolveUpload))
|
||||||
@@ -405,7 +406,7 @@ describe('mobile prompt composer', () => {
|
|||||||
finishUpload(['/tmp/image-one.png']);
|
finishUpload(['/tmp/image-one.png']);
|
||||||
await vi.waitFor(() => expect(input.value).toBe('review /tmp/image-one.png'));
|
await vi.waitFor(() => expect(input.value).toBe('review /tmp/image-one.png'));
|
||||||
|
|
||||||
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([image], { insert: false });
|
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([image], { insert: false, sessionId: 'session-2' });
|
||||||
expect((document.querySelector('.paste-send') as HTMLButtonElement).disabled).toBe(false);
|
expect((document.querySelector('.paste-send') as HTMLButtonElement).disabled).toBe(false);
|
||||||
expect(app.terminal.paste).not.toHaveBeenCalled();
|
expect(app.terminal.paste).not.toHaveBeenCalled();
|
||||||
expect(app._sendInputAsync).not.toHaveBeenCalled();
|
expect(app._sendInputAsync).not.toHaveBeenCalled();
|
||||||
@@ -620,7 +621,7 @@ describe('mobile prompt composer', () => {
|
|||||||
Object.defineProperty(fileInput, 'files', { configurable: true, value: [video, pdf, script] });
|
Object.defineProperty(fileInput, 'files', { configurable: true, value: [video, pdf, script] });
|
||||||
|
|
||||||
fileInput.dispatchEvent(new document.defaultView!.Event('change', { bubbles: true }));
|
fileInput.dispatchEvent(new document.defaultView!.Event('change', { bubbles: true }));
|
||||||
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video, pdf], { insert: false });
|
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video, pdf], { insert: false, sessionId: 'session-1' });
|
||||||
expect(app.showToast).toHaveBeenCalledWith('1 file skipped: unsupported type', 'info');
|
expect(app.showToast).toHaveBeenCalledWith('1 file skipped: unsupported type', 'info');
|
||||||
await vi.waitFor(() => expect(textarea(document).value).toContain('/tmp/image-one.png'));
|
await vi.waitFor(() => expect(textarea(document).value).toContain('/tmp/image-one.png'));
|
||||||
});
|
});
|
||||||
@@ -685,7 +686,7 @@ describe('mobile prompt composer', () => {
|
|||||||
});
|
});
|
||||||
input.dispatchEvent(event);
|
input.dispatchEvent(event);
|
||||||
expect(event.defaultPrevented).toBe(true);
|
expect(event.defaultPrevented).toBe(true);
|
||||||
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video], { insert: false });
|
expect(app._uploadAndInsertImages).toHaveBeenCalledWith([video], { insert: false, sessionId: 'session-1' });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -48,6 +48,8 @@ function loadKeyboardModule() {
|
|||||||
_focusedPane: () => ({ sessionId: 'session-1', isPrimary: true }),
|
_focusedPane: () => ({ sessionId: 'session-1', isPrimary: true }),
|
||||||
_paneForSession: (sessionId: string) => ({ sessionId, isPrimary: true }),
|
_paneForSession: (sessionId: string) => ({ sessionId, isPrimary: true }),
|
||||||
_localEchoEnabled: false,
|
_localEchoEnabled: false,
|
||||||
|
_localEchoPolicy: 'off',
|
||||||
|
_predictiveEcho: { clearPredictions: vi.fn() },
|
||||||
_localEchoOverlay: { appendText: vi.fn() },
|
_localEchoOverlay: { appendText: vi.fn() },
|
||||||
_prepareExternalInput: vi.fn(),
|
_prepareExternalInput: vi.fn(),
|
||||||
};
|
};
|
||||||
@@ -186,6 +188,22 @@ describe('mobile filesystem picker actions', () => {
|
|||||||
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/mnt/d/AI/project/file.ts', { useMux: true });
|
expect(app._sendInputAsync).toHaveBeenCalledWith('session-1', '/mnt/d/AI/project/file.ts', { useMux: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each([false, true])('clears primary predictions before inserting a path (buffered=%s)', (buffered) => {
|
||||||
|
const { app, bar, picker } = loadKeyboardModule();
|
||||||
|
app._localEchoPolicy = 'predict';
|
||||||
|
app._localEchoEnabled = buffered;
|
||||||
|
picker.open = vi.fn();
|
||||||
|
bar.handleAction('pick-path');
|
||||||
|
|
||||||
|
picker.open.mock.calls[0][0].onSelect('/project/file.ts');
|
||||||
|
|
||||||
|
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalledOnce();
|
||||||
|
const insert = buffered ? app._localEchoOverlay.appendText : app._sendInputAsync;
|
||||||
|
expect(app._predictiveEcho.clearPredictions.mock.invocationCallOrder[0]).toBeLessThan(
|
||||||
|
insert.mock.invocationCallOrder[0]
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it.each([false, true])(
|
it.each([false, true])(
|
||||||
'appends a picked path to the destination primary overlay without flushing (focus moved=%s)',
|
'appends a picked path to the destination primary overlay without flushing (focus moved=%s)',
|
||||||
(moved) => {
|
(moved) => {
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ function harness() {
|
|||||||
app._localEchoOverlay = {
|
app._localEchoOverlay = {
|
||||||
pendingText: '',
|
pendingText: '',
|
||||||
flushed: '',
|
flushed: '',
|
||||||
|
get committedText() {
|
||||||
|
return this.flushed + this.pendingText;
|
||||||
|
},
|
||||||
addChar(text: string) {
|
addChar(text: string) {
|
||||||
this.pendingText += text;
|
this.pendingText += text;
|
||||||
},
|
},
|
||||||
@@ -68,7 +71,7 @@ function harness() {
|
|||||||
this[key] = Array.from(this[key]).slice(0, -1).join('');
|
this[key] = Array.from(this[key]).slice(0, -1).join('');
|
||||||
return key === 'pendingText' ? 'pending' : 'flushed';
|
return key === 'pendingText' ? 'pending' : 'flushed';
|
||||||
},
|
},
|
||||||
getInputEndAnchor: vi.fn(() => ({ col: 8, row: 2 })),
|
getInputAnchor: vi.fn(() => ({ col: 8, row: 2 })),
|
||||||
};
|
};
|
||||||
const wire: Array<[string, string]> = [];
|
const wire: Array<[string, string]> = [];
|
||||||
app._enqueueReliableInput = vi.fn((id: string, text: string) => wire.push([id, text]));
|
app._enqueueReliableInput = vi.fn((id: string, text: string) => wire.push([id, text]));
|
||||||
@@ -367,6 +370,27 @@ describe('native main transactions and boundaries', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('spends Ctrl on a deletion-only transaction without resetting the owner', () => {
|
||||||
|
const { app, wire, context } = harness();
|
||||||
|
loadProducerModules(app, context);
|
||||||
|
app._localEchoEnabled = false;
|
||||||
|
app._iosNativeInput = { reset: vi.fn() };
|
||||||
|
const bar = vm.runInContext('KeyboardAccessoryBar', context);
|
||||||
|
bar.toggleCtrl();
|
||||||
|
|
||||||
|
app._sendNativeInputTransaction(['\x7f']);
|
||||||
|
|
||||||
|
expect(wire).toEqual([['old', '\x7f']]);
|
||||||
|
expect(bar.isCtrlArmed()).toBe(false);
|
||||||
|
expect(app._iosNativeInput.reset).not.toHaveBeenCalled();
|
||||||
|
app._sendNativeInputTransaction(['c']);
|
||||||
|
expect(wire).toEqual([
|
||||||
|
['old', '\x7f'],
|
||||||
|
['old', 'c'],
|
||||||
|
]);
|
||||||
|
expect(app._iosNativeInput.reset).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('settles, seals, flushes, resets owner and preview before session cleanup', () => {
|
it('settles, seals, flushes, resets owner and preview before session cleanup', () => {
|
||||||
const { app, wire } = harness();
|
const { app, wire } = harness();
|
||||||
attachCleanupStubs(app);
|
attachCleanupStubs(app);
|
||||||
@@ -817,17 +841,21 @@ describe('native main transactions and boundaries', () => {
|
|||||||
expect(app._localEchoOverlay.pendingText).toBe('hel /p ');
|
expect(app._localEchoOverlay.pendingText).toBe('hel /p ');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('hides the caret when a buffering overlay cannot supply an anchor', () => {
|
it('maps the native suffix after a non-BMP committed prefix and hides mismatches or missing cells', () => {
|
||||||
const { app } = harness();
|
const { app } = harness();
|
||||||
expect(app._nativeInputAnchor()).toBeNull();
|
const caret = { visible: true, text: 'hello', offset: 2 };
|
||||||
app._localEchoOverlay.pendingText = 'text';
|
expect(app._nativeInputCaretAnchor(caret)).toBeNull();
|
||||||
expect(app._nativeInputAnchor()).toEqual({ col: 8, row: 2 });
|
app._localEchoOverlay.flushed = '👍';
|
||||||
app._localEchoOverlay.getInputEndAnchor = () => null;
|
app._localEchoOverlay.pendingText = 'hello';
|
||||||
expect(app._nativeInputAnchor()).toBe('hide');
|
expect(app._nativeInputCaretAnchor(caret)).toEqual({ col: 8, row: 2 });
|
||||||
delete app._localEchoOverlay.getInputEndAnchor;
|
expect(app._localEchoOverlay.getInputAnchor).toHaveBeenLastCalledWith(4);
|
||||||
expect(app._nativeInputAnchor()).toBe('hide');
|
expect(app._nativeInputCaretAnchor({ ...caret, text: 'hullo' })).toBe('hide');
|
||||||
|
app._localEchoOverlay.getInputAnchor = () => null;
|
||||||
|
expect(app._nativeInputCaretAnchor(caret)).toBe('hide');
|
||||||
|
delete app._localEchoOverlay.getInputAnchor;
|
||||||
|
expect(app._nativeInputCaretAnchor(caret)).toBe('hide');
|
||||||
app._echoPassthroughSessions = new Set(['old']);
|
app._echoPassthroughSessions = new Set(['old']);
|
||||||
expect(app._nativeInputAnchor()).toBeNull();
|
expect(app._nativeInputCaretAnchor(caret)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('prepares only the captured tile owner, not the primary owner', () => {
|
it('prepares only the captured tile owner, not the primary owner', () => {
|
||||||
@@ -854,6 +882,44 @@ describe('native main transactions and boundaries', () => {
|
|||||||
app.submitFromToolbar();
|
app.submitFromToolbar();
|
||||||
expect(wire).toHaveLength(2);
|
expect(wire).toHaveLength(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('toolbar Enter spends an armed one-shot Ctrl, so the next typed c stays a c', () => {
|
||||||
|
for (const echo of [true, false]) {
|
||||||
|
const { app, wire, context } = harness();
|
||||||
|
loadProducerModules(app, context);
|
||||||
|
app._localEchoEnabled = echo;
|
||||||
|
const bar = vm.runInContext('KeyboardAccessoryBar', context);
|
||||||
|
bar.toggleCtrl();
|
||||||
|
expect(bar.isCtrlArmed()).toBe(true);
|
||||||
|
app.submitFromToolbar();
|
||||||
|
vi.advanceTimersByTime(80);
|
||||||
|
expect(bar.isCtrlArmed()).toBe(false);
|
||||||
|
wire.length = 0;
|
||||||
|
app._handleTerminalData('c', 'old');
|
||||||
|
app.submitFromToolbar();
|
||||||
|
vi.advanceTimersByTime(80);
|
||||||
|
expect(wire).toEqual([
|
||||||
|
['old', 'c'],
|
||||||
|
['old', '\r'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accessory Shift+Tab leaves the unsent draft in the overlay, as a typed Shift+Tab does', () => {
|
||||||
|
const { app, wire, context } = harness();
|
||||||
|
loadProducerModules(app, context);
|
||||||
|
app._handleTerminalData('hel', 'old');
|
||||||
|
vm.runInContext("KeyboardAccessoryBar.handleAction('shift-tab')", context);
|
||||||
|
expect(wire).toEqual([['old', '\x1b[Z']]);
|
||||||
|
expect(app._localEchoOverlay.pendingText).toBe('hel');
|
||||||
|
// The typed key takes the same path: the draft stays put.
|
||||||
|
app._handleTerminalData('\x1b[Z', 'old');
|
||||||
|
expect(wire).toEqual([
|
||||||
|
['old', '\x1b[Z'],
|
||||||
|
['old', '\x1b[Z'],
|
||||||
|
]);
|
||||||
|
expect(app._localEchoOverlay.pendingText).toBe('hel');
|
||||||
|
});
|
||||||
it('resets native ownership before dispatching synthetic compositionend', () => {
|
it('resets native ownership before dispatching synthetic compositionend', () => {
|
||||||
const { app, context } = harness();
|
const { app, context } = harness();
|
||||||
attachCleanupStubs(app);
|
attachCleanupStubs(app);
|
||||||
@@ -916,7 +982,7 @@ describe('native main transactions and boundaries', () => {
|
|||||||
options.onTransaction(transaction);
|
options.onTransaction(transaction);
|
||||||
expect(app._mobileImePreview.nativeTransaction).toHaveBeenCalledWith(transaction);
|
expect(app._mobileImePreview.nativeTransaction).toHaveBeenCalledWith(transaction);
|
||||||
const markerOptions = native.attachCaretMarker.mock.calls[0][2];
|
const markerOptions = native.attachCaretMarker.mock.calls[0][2];
|
||||||
expect(markerOptions.anchor()).toBeNull();
|
expect(markerOptions.anchor({ visible: true, text: 'native', offset: 2 })).toBeNull();
|
||||||
expect(markerOptions.subscribe(vi.fn())).toBe(unsubscribe);
|
expect(markerOptions.subscribe(vi.fn())).toBe(unsubscribe);
|
||||||
app._initTerminalInputOwner();
|
app._initTerminalInputOwner();
|
||||||
expect(owner.destroy).toHaveBeenCalledOnce();
|
expect(owner.destroy).toHaveBeenCalledOnce();
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ import { describe, expect, it, vi } from 'vitest';
|
|||||||
type Event = Record<string, unknown>;
|
type Event = Record<string, unknown>;
|
||||||
interface Caret {
|
interface Caret {
|
||||||
visible: boolean;
|
visible: boolean;
|
||||||
cellsFromEnd: number;
|
text: string;
|
||||||
|
offset: number;
|
||||||
}
|
}
|
||||||
interface Transaction {
|
interface Transaction {
|
||||||
inserted: string;
|
inserted: string;
|
||||||
@@ -45,7 +46,7 @@ interface NativeApi {
|
|||||||
terminal: FakeTerminal,
|
terminal: FakeTerminal,
|
||||||
owner: NativeOwner,
|
owner: NativeOwner,
|
||||||
options?: {
|
options?: {
|
||||||
anchor?: () => { col: number; row: number } | 'hide' | null | undefined;
|
anchor?: (caret: Caret) => { col: number; row: number } | 'hide' | null | undefined;
|
||||||
subscribe?: (callback: () => void) => () => void;
|
subscribe?: (callback: () => void) => () => void;
|
||||||
}
|
}
|
||||||
): () => void;
|
): () => void;
|
||||||
@@ -65,23 +66,41 @@ interface FakeHelper {
|
|||||||
_isSendingComposition: boolean;
|
_isSendingComposition: boolean;
|
||||||
}
|
}
|
||||||
interface FakeCore {
|
interface FakeCore {
|
||||||
_inputEvent(): unknown;
|
_inputEvent(ev?: Event): unknown;
|
||||||
|
_unprocessedDeadKey?: boolean;
|
||||||
_handleTextAreaBlur(): void;
|
_handleTextAreaBlur(): void;
|
||||||
_compositionHelper: FakeHelper;
|
_compositionHelper: FakeHelper;
|
||||||
coreService: { triggerDataEvent(): void; decPrivateModes?: { applicationCursorKeys: boolean } };
|
coreService: { triggerDataEvent(): void; decPrivateModes?: { applicationCursorKeys: boolean } };
|
||||||
unicodeService: { getStringCellWidth?: (text: string) => number };
|
unicodeService: { getStringCellWidth?: (text: string) => number };
|
||||||
_renderService: { dimensions: { css: { cell: { width: number; height: number } } } | null };
|
_renderService: { dimensions: { css: { cell: { width: number; height: number } } } | null };
|
||||||
}
|
}
|
||||||
|
interface BufferCell {
|
||||||
|
getChars(): string;
|
||||||
|
getWidth(): number;
|
||||||
|
}
|
||||||
|
interface BufferLine {
|
||||||
|
isWrapped: boolean;
|
||||||
|
getCell(col: number): BufferCell | undefined;
|
||||||
|
}
|
||||||
interface FakeTerminal {
|
interface FakeTerminal {
|
||||||
textarea: FakeTextarea;
|
textarea: FakeTextarea;
|
||||||
element: FakeNode;
|
element: FakeNode;
|
||||||
_core: FakeCore;
|
_core: FakeCore;
|
||||||
cols: number;
|
cols: number;
|
||||||
rows: number;
|
rows: number;
|
||||||
buffer: { active: { cursorX: number; cursorY: number; baseY: number; viewportY: number } };
|
buffer: {
|
||||||
|
active: {
|
||||||
|
cursorX: number;
|
||||||
|
cursorY: number;
|
||||||
|
baseY: number;
|
||||||
|
viewportY: number;
|
||||||
|
getLine(row: number): BufferLine | undefined;
|
||||||
|
};
|
||||||
|
};
|
||||||
options: { theme: { cursor: string }; screenReaderMode: boolean };
|
options: { theme: { cursor: string }; screenReaderMode: boolean };
|
||||||
onRender(callback: () => void): { dispose(): void };
|
onRender(callback: () => void): { dispose(): void };
|
||||||
onCursorMove(callback: () => void): { dispose(): void };
|
onCursorMove(callback: () => void): { dispose(): void };
|
||||||
|
onWriteParsed(callback: () => void): { dispose(): void };
|
||||||
}
|
}
|
||||||
interface Harness {
|
interface Harness {
|
||||||
api: NativeApi;
|
api: NativeApi;
|
||||||
@@ -108,6 +127,7 @@ interface Harness {
|
|||||||
screen: FakeNode;
|
screen: FakeNode;
|
||||||
renders: Set<() => void>;
|
renders: Set<() => void>;
|
||||||
moves: Set<() => void>;
|
moves: Set<() => void>;
|
||||||
|
parsed: Set<() => void>;
|
||||||
owner: NativeOwner;
|
owner: NativeOwner;
|
||||||
tick(): void;
|
tick(): void;
|
||||||
selection(start: number, end?: number, direction?: string): void;
|
selection(start: number, end?: number, direction?: string): void;
|
||||||
@@ -252,6 +272,18 @@ class FakeTextarea extends FakeNode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function bufferLine(cells: Array<string | [string, number]>, isWrapped = false): BufferLine {
|
||||||
|
return {
|
||||||
|
isWrapped,
|
||||||
|
getCell(col) {
|
||||||
|
const value = cells[col];
|
||||||
|
if (value === undefined) return undefined;
|
||||||
|
const [chars, width] = typeof value === 'string' ? [value, 1] : value;
|
||||||
|
return { getChars: () => chars, getWidth: () => width };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function harness(
|
function harness(
|
||||||
mode = 'direct',
|
mode = 'direct',
|
||||||
options: {
|
options: {
|
||||||
@@ -324,6 +356,7 @@ function harness(
|
|||||||
element.querySelector = (selector: string) => (selector === '.xterm-screen' ? screen : null);
|
element.querySelector = (selector: string) => (selector === '.xterm-screen' ? screen : null);
|
||||||
const renders = new Set<() => void>();
|
const renders = new Set<() => void>();
|
||||||
const moves = new Set<() => void>();
|
const moves = new Set<() => void>();
|
||||||
|
const parsed = new Set<() => void>();
|
||||||
const subscribe = (set: Set<() => void>, callback: () => void) => {
|
const subscribe = (set: Set<() => void>, callback: () => void) => {
|
||||||
set.add(callback);
|
set.add(callback);
|
||||||
return { dispose: () => set.delete(callback) };
|
return { dispose: () => set.delete(callback) };
|
||||||
@@ -334,10 +367,22 @@ function harness(
|
|||||||
_core: core,
|
_core: core,
|
||||||
cols: 10,
|
cols: 10,
|
||||||
rows: 5,
|
rows: 5,
|
||||||
buffer: { active: { cursorX: 5, cursorY: 2, baseY: 0, viewportY: 0 } },
|
buffer: {
|
||||||
|
active: {
|
||||||
|
cursorX: 5,
|
||||||
|
cursorY: 2,
|
||||||
|
baseY: 0,
|
||||||
|
viewportY: 0,
|
||||||
|
getLine: (row) =>
|
||||||
|
row === terminal.buffer.active.baseY + terminal.buffer.active.cursorY
|
||||||
|
? bufferLine(Array.from(line + pending))
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
},
|
||||||
options: { theme: { cursor: '#fff' }, screenReaderMode: !!options.screenReaderMode },
|
options: { theme: { cursor: '#fff' }, screenReaderMode: !!options.screenReaderMode },
|
||||||
onRender: (callback: () => void) => subscribe(renders, callback),
|
onRender: (callback: () => void) => subscribe(renders, callback),
|
||||||
onCursorMove: (callback: () => void) => subscribe(moves, callback),
|
onCursorMove: (callback: () => void) => subscribe(moves, callback),
|
||||||
|
onWriteParsed: (callback: () => void) => subscribe(parsed, callback),
|
||||||
};
|
};
|
||||||
const originals = [
|
const originals = [
|
||||||
{ target: core, name: '_inputEvent' },
|
{ target: core, name: '_inputEvent' },
|
||||||
@@ -511,6 +556,7 @@ function harness(
|
|||||||
screen,
|
screen,
|
||||||
renders,
|
renders,
|
||||||
moves,
|
moves,
|
||||||
|
parsed,
|
||||||
consume,
|
consume,
|
||||||
get owner() {
|
get owner() {
|
||||||
return owner;
|
return owner;
|
||||||
@@ -1048,7 +1094,7 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
|||||||
h.clearSent();
|
h.clearSent();
|
||||||
h.selection(2);
|
h.selection(2);
|
||||||
h.bytes([]);
|
h.bytes([]);
|
||||||
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 3 });
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'hello', offset: 2 });
|
||||||
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
||||||
const marker = h.screen.children[0];
|
const marker = h.screen.children[0];
|
||||||
expect(marker.attributes['aria-hidden']).toBe('true');
|
expect(marker.attributes['aria-hidden']).toBe('true');
|
||||||
@@ -1062,23 +1108,20 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
|||||||
h.edit('X');
|
h.edit('X');
|
||||||
h.bytes([...dels(3), 'Xllo']);
|
h.bytes([...dels(3), 'Xllo']);
|
||||||
expect(h.value()).toBe('heXllo');
|
expect(h.value()).toBe('heXllo');
|
||||||
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 3 });
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'heXllo', offset: 3 });
|
||||||
h.clearSent();
|
h.clearSent();
|
||||||
h.selection(6);
|
h.selection(6);
|
||||||
expect(marker.style.display).toBe('none');
|
expect(marker.style.display).toBe('none');
|
||||||
h.bytes([]);
|
h.bytes([]);
|
||||||
h.selection(3);
|
h.selection(3);
|
||||||
h.terminal.buffer.active.cursorX = 0;
|
expect(marker.style.display).toBe('none'); // No parsed echo of the edit yet.
|
||||||
h.terminal.buffer.active.cursorY = 1;
|
h.terminal.buffer.active.cursorX = 6;
|
||||||
for (const callback of h.renders) callback();
|
for (const callback of h.parsed) callback();
|
||||||
expect([marker.style.left, marker.style.top]).toEqual(['56px', '0px']);
|
expect([marker.style.left, marker.style.top, marker.style.display]).toEqual(['24px', '32px', 'block']);
|
||||||
h.terminal.buffer.active.cursorY = 0;
|
|
||||||
for (const callback of h.moves) callback();
|
|
||||||
expect(marker.style.display).toBe('none');
|
|
||||||
dispose();
|
dispose();
|
||||||
dispose();
|
dispose();
|
||||||
expect(h.screen.children).toHaveLength(0);
|
expect(h.screen.children).toHaveLength(0);
|
||||||
expect(h.renders.size + h.moves.size).toBe(0);
|
expect(h.renders.size + h.moves.size + h.parsed.size).toBe(0);
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
@@ -1142,10 +1185,10 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
|||||||
h.core.coreService.decPrivateModes = { applicationCursorKeys };
|
h.core.coreService.decPrivateModes = { applicationCursorKeys };
|
||||||
h.selection(1);
|
h.selection(1);
|
||||||
h.bytes([]);
|
h.bytes([]);
|
||||||
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 2 });
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: '你好', offset: 1 });
|
||||||
}
|
}
|
||||||
h.core.unicodeService.getStringCellWidth = undefined;
|
h.core.unicodeService.getStringCellWidth = undefined;
|
||||||
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 1 });
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: '你好', offset: 1 });
|
||||||
h.selection(2);
|
h.selection(2);
|
||||||
expect(h.owner.caret().visible).toBe(false);
|
expect(h.owner.caret().visible).toBe(false);
|
||||||
},
|
},
|
||||||
@@ -1159,7 +1202,8 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
|||||||
const unsubscribe = h.owner.onCaret((caret: Caret) => changes.push(caret));
|
const unsubscribe = h.owner.onCaret((caret: Caret) => changes.push(caret));
|
||||||
h.selection(2);
|
h.selection(2);
|
||||||
h.selection(2);
|
h.selection(2);
|
||||||
expect(changes).toEqual([{ visible: true, cellsFromEnd: 3 }]);
|
expect(changes).toMatchObject([{ visible: true, text: 'hello', offset: 2 }]);
|
||||||
|
expect(changes).toHaveLength(1);
|
||||||
h.blur();
|
h.blur();
|
||||||
const before = h.caretChanges.length;
|
const before = h.caretChanges.length;
|
||||||
h.document.fire('selectionchange');
|
h.document.fire('selectionchange');
|
||||||
@@ -1179,16 +1223,16 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'31 projected code-point caret',
|
'31 projected UTF-16 caret',
|
||||||
(h) => {
|
(h) => {
|
||||||
h.edit('a👍\nb');
|
h.edit('a👍\nb');
|
||||||
h.clearSent();
|
h.clearSent();
|
||||||
h.selection(4);
|
h.selection(4);
|
||||||
expect(h.owner.caret().cellsFromEnd).toBe(1);
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 4 });
|
||||||
h.selection(3);
|
h.selection(3);
|
||||||
expect(h.owner.caret().cellsFromEnd).toBe(2);
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 3 });
|
||||||
h.selection(1);
|
h.selection(1);
|
||||||
expect(h.owner.caret().cellsFromEnd).toBe(h.core.unicodeService.getStringCellWidth!('👍 b'));
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b', offset: 1 });
|
||||||
h.selection(3);
|
h.selection(3);
|
||||||
h.edit('X');
|
h.edit('X');
|
||||||
h.bytes([DEL, DEL, 'X b']);
|
h.bytes([DEL, DEL, 'X b']);
|
||||||
@@ -1231,7 +1275,7 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
|||||||
});
|
});
|
||||||
h.edit('X', [2, 2], 'insertText', false, false);
|
h.edit('X', [2, 2], 'insertText', false, false);
|
||||||
h.bytes(['hello', ...dels(3), 'Xllo']);
|
h.bytes(['hello', ...dels(3), 'Xllo']);
|
||||||
expect(h.owner.caret()).toEqual({ visible: true, cellsFromEnd: 2 });
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'heXllo', offset: 4 });
|
||||||
h.invariant();
|
h.invariant();
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -1280,6 +1324,19 @@ const replayCases: Array<[string, (h: Harness) => void]> = [
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
[
|
||||||
|
'contextmenu clipboard snapshot restores before empty-line Backspace classification',
|
||||||
|
(h) => {
|
||||||
|
expect(h.textarea.value).toBe('');
|
||||||
|
h.terminal.element.fire('contextmenu');
|
||||||
|
// xterm's bubble handler writes a selection before its next capture keydown.
|
||||||
|
h.textarea.value = 'clipboard';
|
||||||
|
h.selection(0, 9);
|
||||||
|
expect(h.owner.keyFilter({ type: 'keydown', key: 'Backspace', keyCode: 8 })).toBe(true);
|
||||||
|
expect(h.textarea.value).toBe('');
|
||||||
|
h.bytes([]);
|
||||||
|
},
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const mode of ['direct', 'local-echo']) {
|
for (const mode of ['direct', 'local-echo']) {
|
||||||
@@ -1289,6 +1346,166 @@ for (const mode of ['direct', 'local-echo']) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('CodemanIosNativeInput integration contract', () => {
|
describe('CodemanIosNativeInput integration contract', () => {
|
||||||
|
it('projects CRLF and LF prefixes into UTF-16 caret offsets', () => {
|
||||||
|
const h = harness();
|
||||||
|
h.edit('a👍\r\nb\nc');
|
||||||
|
for (const [selection, offset] of [
|
||||||
|
[1, 1],
|
||||||
|
[3, 3],
|
||||||
|
[5, 4],
|
||||||
|
[7, 6],
|
||||||
|
]) {
|
||||||
|
h.selection(selection);
|
||||||
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'a👍 b c', offset });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides pending, invalidated and foreign native snapshots', () => {
|
||||||
|
const h = harness();
|
||||||
|
h.type('hello');
|
||||||
|
h.selection(2);
|
||||||
|
expect(h.owner.caret().visible).toBe(true);
|
||||||
|
h.textarea.value = 'hellox';
|
||||||
|
h.selection(2);
|
||||||
|
expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hellox', offset: 2 });
|
||||||
|
h.textarea.fire('beforeinput');
|
||||||
|
expect(h.owner.caret().visible).toBe(false);
|
||||||
|
h.owner.reset('test');
|
||||||
|
h.type('hello');
|
||||||
|
h.selection(2);
|
||||||
|
h.terminal.element.fire('contextmenu');
|
||||||
|
expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hello', offset: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps a你b through validated wide-wrap padding to explicit cells', () => {
|
||||||
|
const h = harness();
|
||||||
|
h.type('a你b');
|
||||||
|
h.terminal.cols = 80;
|
||||||
|
const lines = new Map([
|
||||||
|
[0, bufferLine([...Array(78).fill(' '), 'a', ''])],
|
||||||
|
[1, bufferLine([['你', 2], ['', 0], 'b'], true)],
|
||||||
|
]);
|
||||||
|
Object.assign(h.terminal.buffer.active, { cursorX: 3, cursorY: 1, getLine: (row: number) => lines.get(row) });
|
||||||
|
h.selection(0);
|
||||||
|
const snapshot = h.snapshot();
|
||||||
|
const sent = [...h.sent];
|
||||||
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
||||||
|
const marker = h.screen.children[0];
|
||||||
|
for (const [offset, col, row] of [
|
||||||
|
[0, 78, 0],
|
||||||
|
[1, 0, 1],
|
||||||
|
[2, 2, 1],
|
||||||
|
]) {
|
||||||
|
h.selection(offset);
|
||||||
|
expect([marker.style.display, marker.style.left, marker.style.top]).toEqual([
|
||||||
|
'block',
|
||||||
|
`${col * 8}px`,
|
||||||
|
`${row * 16}px`,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
h.selection(0);
|
||||||
|
expect(h.snapshot()).toEqual(snapshot);
|
||||||
|
expect(h.sent).toEqual(sent);
|
||||||
|
expect(h.document.activeElement).toBe(h.textarea);
|
||||||
|
h.terminal.buffer.active.viewportY = 1;
|
||||||
|
for (const callback of h.renders) callback();
|
||||||
|
expect(marker.style.display).toBe('none');
|
||||||
|
dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['e\u0301', '👩💻'])('hides offsets inside one buffer cluster %s but maps its start', (cluster) => {
|
||||||
|
const h = harness();
|
||||||
|
h.type(cluster + 'b');
|
||||||
|
Object.assign(h.terminal.buffer.active, {
|
||||||
|
cursorX: 3,
|
||||||
|
cursorY: 0,
|
||||||
|
getLine: () => bufferLine([[cluster, 2], ['', 0], 'b']),
|
||||||
|
});
|
||||||
|
h.selection(1);
|
||||||
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
||||||
|
const marker = h.screen.children[0];
|
||||||
|
expect(marker.style.display).toBe('none');
|
||||||
|
h.selection(0);
|
||||||
|
expect([marker.style.display, marker.style.left, marker.style.top]).toEqual(['block', '0px', '0px']);
|
||||||
|
dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides an old identical hello until the next parsed write', () => {
|
||||||
|
const h = harness();
|
||||||
|
h.terminal.buffer.active.getLine = () => bufferLine(Array.from('hello'));
|
||||||
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
||||||
|
h.type('hello');
|
||||||
|
h.selection(2);
|
||||||
|
const marker = h.screen.children[0];
|
||||||
|
expect(marker.style.display).toBe('none');
|
||||||
|
for (const callback of h.renders) callback();
|
||||||
|
for (const callback of h.moves) callback();
|
||||||
|
expect(marker.style.display).toBe('none');
|
||||||
|
for (const callback of h.parsed) callback();
|
||||||
|
expect([marker.style.display, marker.style.left, marker.style.top]).toEqual(['block', '16px', '32px']);
|
||||||
|
dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the marker after a copy borrows and restores the native field, with no new output', () => {
|
||||||
|
const h = harness();
|
||||||
|
h.terminal.buffer.active.getLine = () => bufferLine(Array.from('hello'));
|
||||||
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
||||||
|
h.type('hello');
|
||||||
|
h.selection(2);
|
||||||
|
for (const callback of h.parsed) callback();
|
||||||
|
const marker = h.screen.children[0];
|
||||||
|
expect([marker.style.display, marker.style.left]).toEqual(['block', '16px']);
|
||||||
|
// xterm's right-click handler lends the field to native Copy: a different
|
||||||
|
// terminal selection, then the copy timer restores the draft. No input is
|
||||||
|
// sent and no xterm write follows.
|
||||||
|
h.terminal.element.fire('contextmenu');
|
||||||
|
h.textarea.value = 'other selection';
|
||||||
|
h.selection(0, 15);
|
||||||
|
expect(marker.style.display).toBe('none');
|
||||||
|
h.document.fire('copy');
|
||||||
|
h.tick();
|
||||||
|
h.selection(2);
|
||||||
|
expect(h.owner.caret()).toMatchObject({ visible: true, text: 'hello', offset: 2 });
|
||||||
|
expect([marker.style.display, marker.style.left]).toEqual(['block', '16px']);
|
||||||
|
dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not treat an unwritten cell as a native space', () => {
|
||||||
|
const h = harness();
|
||||||
|
h.type('a b');
|
||||||
|
h.selection(1);
|
||||||
|
Object.assign(h.terminal.buffer.active, { cursorX: 3, getLine: () => bufferLine(['a', '', 'b']) });
|
||||||
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
||||||
|
expect(h.screen.children[0].style.display).toBe('none');
|
||||||
|
dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never crosses a hard line break while matching the native field', () => {
|
||||||
|
const h = harness();
|
||||||
|
h.type('ab');
|
||||||
|
h.selection(0);
|
||||||
|
const lines = new Map([
|
||||||
|
[0, bufferLine(['a'])],
|
||||||
|
[1, bufferLine(['b'])],
|
||||||
|
]);
|
||||||
|
Object.assign(h.terminal.buffer.active, { cursorX: 1, cursorY: 1, getLine: (row: number) => lines.get(row) });
|
||||||
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
||||||
|
expect(h.screen.children[0].style.display).toBe('none');
|
||||||
|
dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['hellohello', 'hullo', 'xhello'])('checks the full buffer suffix and repetition for %s', (text) => {
|
||||||
|
const h = harness();
|
||||||
|
h.type('hello');
|
||||||
|
Object.assign(h.terminal.buffer.active, { cursorX: text.length, getLine: () => bufferLine(Array.from(text)) });
|
||||||
|
h.selection(2);
|
||||||
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner);
|
||||||
|
const marker = h.screen.children[0];
|
||||||
|
expect(marker.style.display).toBe(text === 'xhello' ? 'block' : 'none');
|
||||||
|
if (text === 'xhello') expect([marker.style.left, marker.style.top]).toEqual(['24px', '32px']);
|
||||||
|
dispose();
|
||||||
|
});
|
||||||
|
|
||||||
it('requires a transaction sink and leaves unsupported xterm internals untouched', () => {
|
it('requires a transaction sink and leaves unsupported xterm internals untouched', () => {
|
||||||
const h = harness();
|
const h = harness();
|
||||||
h.owner.destroy();
|
h.owner.destroy();
|
||||||
@@ -1311,6 +1528,16 @@ describe('CodemanIosNativeInput integration contract', () => {
|
|||||||
expect(h.silent('input').defaultPrevented).toBe(false);
|
expect(h.silent('input').defaultPrevented).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('clears the pending dead key on committed native text without emitting xterm data', () => {
|
||||||
|
const h = harness();
|
||||||
|
h.core._unprocessedDeadKey = true;
|
||||||
|
expect(h.core._inputEvent({ data: 'é', inputType: 'insertText' })).toBe(false);
|
||||||
|
expect(h.core._unprocessedDeadKey).toBe(false);
|
||||||
|
expect(h.rawProducer).not.toHaveBeenCalled();
|
||||||
|
h.tick();
|
||||||
|
h.bytes([]);
|
||||||
|
});
|
||||||
|
|
||||||
it('notifies every settled edit, deletion-only/unchanged composition, and reset', () => {
|
it('notifies every settled edit, deletion-only/unchanged composition, and reset', () => {
|
||||||
const h = harness();
|
const h = harness();
|
||||||
h.type('ab');
|
h.type('ab');
|
||||||
@@ -1363,8 +1590,8 @@ describe('CodemanIosNativeInput integration contract', () => {
|
|||||||
expect(() => h.edit('hello')).not.toThrow();
|
expect(() => h.edit('hello')).not.toThrow();
|
||||||
expect(h.owner.state().synced).toBe('hello');
|
expect(h.owner.state().synced).toBe('hello');
|
||||||
h.selection(2);
|
h.selection(2);
|
||||||
expect(() => h.edit('X')).not.toThrow();
|
expect(h.owner.caret()).toMatchObject({ visible: false, text: 'hello', offset: 2 });
|
||||||
expect(h.owner.state().synced).toBe('heXllo');
|
expect(h.owner.state().invalidated).toBe(true);
|
||||||
expect(h.records.filter((entry) => entry.type === 'error').map((entry) => entry.hook)).toContain('sendTransaction');
|
expect(h.records.filter((entry) => entry.type === 'error').map((entry) => entry.hook)).toContain('sendTransaction');
|
||||||
expect(h.records.filter((entry) => entry.type === 'error').map((entry) => entry.hook)).toContain('onTransaction');
|
expect(h.records.filter((entry) => entry.type === 'error').map((entry) => entry.hook)).toContain('onTransaction');
|
||||||
});
|
});
|
||||||
@@ -1416,7 +1643,8 @@ describe('CodemanIosNativeInput integration contract', () => {
|
|||||||
let layout = () => {};
|
let layout = () => {};
|
||||||
const unsubscribe = vi.fn();
|
const unsubscribe = vi.fn();
|
||||||
const dispose = h.api.attachCaretMarker(h.terminal, h.owner, {
|
const dispose = h.api.attachCaretMarker(h.terminal, h.owner, {
|
||||||
anchor() {
|
anchor(caret) {
|
||||||
|
expect(caret).toMatchObject({ visible: true, text: 'hello', offset: 2 });
|
||||||
if (fail) throw new Error('layout');
|
if (fail) throw new Error('layout');
|
||||||
return anchor;
|
return anchor;
|
||||||
},
|
},
|
||||||
@@ -1426,7 +1654,7 @@ describe('CodemanIosNativeInput integration contract', () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
const marker = h.screen.children[0];
|
const marker = h.screen.children[0];
|
||||||
expect([marker.style.left, marker.style.top]).toEqual(['40px', '48px']);
|
expect([marker.style.left, marker.style.top]).toEqual(['64px', '48px']);
|
||||||
anchor = 'hide';
|
anchor = 'hide';
|
||||||
layout();
|
layout();
|
||||||
expect(marker.style.display).toBe('none');
|
expect(marker.style.display).toBe('none');
|
||||||
|
|||||||
@@ -1543,7 +1543,7 @@ describe('TerminalTile iOS native input ownership', () => {
|
|||||||
return { owner, create, attachCaretMarker, dispose, send: (ops: string[]) => options.sendTransaction(ops) };
|
return { owner, create, attachCaretMarker, dispose, send: (ops: string[]) => options.sendTransaction(ops) };
|
||||||
};
|
};
|
||||||
|
|
||||||
it('creates an owner and xterm-cursor marker, but no 229 recovery, on iOS', async () => {
|
it('creates an owner and parsed-buffer marker without an anchor, but no 229 recovery, on iOS', async () => {
|
||||||
const native = install();
|
const native = install();
|
||||||
const { tile, term } = await connectTile(makeApp());
|
const { tile, term } = await connectTile(makeApp());
|
||||||
expect(native.create).toHaveBeenCalledOnce();
|
expect(native.create).toHaveBeenCalledOnce();
|
||||||
@@ -1676,14 +1676,30 @@ describe('TerminalTile iOS native input ownership', () => {
|
|||||||
expect(native.owner.reset).toHaveBeenCalledExactlyOnceWith('ctrl');
|
expect(native.owner.reset).toHaveBeenCalledExactlyOnceWith('ctrl');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not consume Ctrl for a deletion-only transaction', async () => {
|
it('spends Ctrl on a deletion-only transaction without resetting the owner', async () => {
|
||||||
const native = install();
|
const native = install();
|
||||||
const app = makeApp();
|
const app = makeApp();
|
||||||
app._enqueueInput = vi.fn();
|
app._enqueueInput = vi.fn();
|
||||||
const consumeCtrl = vi.fn();
|
let armed = true;
|
||||||
context.KeyboardAccessoryBar = { isCtrlArmed: () => true, consumeCtrl };
|
const consumeCtrl = vi.fn(() => {
|
||||||
|
armed = false;
|
||||||
|
return '\x03';
|
||||||
|
});
|
||||||
|
context.KeyboardAccessoryBar = {
|
||||||
|
isCtrlArmed: () => armed,
|
||||||
|
consumeCtrl,
|
||||||
|
clearCtrl: () => {
|
||||||
|
armed = false;
|
||||||
|
},
|
||||||
|
};
|
||||||
await connectTile(app);
|
await connectTile(app);
|
||||||
native.send(['\x7f']);
|
native.send(['\x7f']);
|
||||||
|
expect(armed).toBe(false);
|
||||||
|
native.send(['c']);
|
||||||
|
expect(app._enqueueInput.mock.calls).toEqual([
|
||||||
|
['s-tile', [{ write: '\x7f' }]],
|
||||||
|
['s-tile', [{ write: 'c' }]],
|
||||||
|
]);
|
||||||
expect(consumeCtrl).not.toHaveBeenCalled();
|
expect(consumeCtrl).not.toHaveBeenCalled();
|
||||||
expect(native.owner.reset).not.toHaveBeenCalled();
|
expect(native.owner.reset).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -290,6 +290,7 @@ describe('dictation target', () => {
|
|||||||
const textarea = { value: '', focus: vi.fn(), blur: vi.fn(), selectionStart: 0, selectionEnd: 0 };
|
const textarea = { value: '', focus: vi.fn(), blur: vi.fn(), selectionStart: 0, selectionEnd: 0 };
|
||||||
doc.createElement = () => ({
|
doc.createElement = () => ({
|
||||||
className: '',
|
className: '',
|
||||||
|
dataset: {},
|
||||||
innerHTML: '',
|
innerHTML: '',
|
||||||
remove: vi.fn(),
|
remove: vi.fn(),
|
||||||
addEventListener: vi.fn(),
|
addEventListener: vi.fn(),
|
||||||
@@ -314,6 +315,42 @@ describe('dictation target', () => {
|
|||||||
expect(overlayClear).not.toHaveBeenCalled();
|
expect(overlayClear).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('retargets an existing compose overlay for the next dictation', () => {
|
||||||
|
const { voice, sendInputAsync, doc } = load({ insertMode: 'compose' });
|
||||||
|
const handlers = new Map<string, () => void>();
|
||||||
|
const textarea = {
|
||||||
|
value: '',
|
||||||
|
focus: vi.fn(),
|
||||||
|
blur: vi.fn(),
|
||||||
|
selectionStart: 0,
|
||||||
|
selectionEnd: 0,
|
||||||
|
closest: (): { dataset: Record<string, string> } => overlay,
|
||||||
|
};
|
||||||
|
const overlay = {
|
||||||
|
dataset: {},
|
||||||
|
className: '',
|
||||||
|
innerHTML: '',
|
||||||
|
remove: vi.fn(),
|
||||||
|
addEventListener: vi.fn(),
|
||||||
|
querySelector: (sel: string) =>
|
||||||
|
sel === 'textarea'
|
||||||
|
? textarea
|
||||||
|
: {
|
||||||
|
addEventListener: (_type: string, handler: () => void) => handlers.set(sel, handler),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
doc.createElement = () => overlay;
|
||||||
|
voice._targetSessionId = 'session-a';
|
||||||
|
voice._insertText('first dictation');
|
||||||
|
doc.querySelector = (sel: string) => (sel === '.voice-compose-overlay .paste-textarea' ? textarea : null);
|
||||||
|
|
||||||
|
voice._targetSessionId = 'session-b';
|
||||||
|
voice._insertText('second dictation');
|
||||||
|
handlers.get('.paste-send')!();
|
||||||
|
|
||||||
|
expect(sendInputAsync).toHaveBeenCalledExactlyOnceWith('session-b', 'second dictation\r', { useMux: true });
|
||||||
|
});
|
||||||
|
|
||||||
it('refuses to start with no session at all', () => {
|
it('refuses to start with no session at all', () => {
|
||||||
const { voice, app, showToast } = load();
|
const { voice, app, showToast } = load();
|
||||||
app.activeSessionId = null;
|
app.activeSessionId = null;
|
||||||
|
|||||||
@@ -70,8 +70,11 @@ describe('xterm private-API dependency guard', () => {
|
|||||||
// and touch quietly stops forwarding to native SGR tracking apps. Property names survive
|
// and touch quietly stops forwarding to native SGR tracking apps. Property names survive
|
||||||
// minification, so a string check on the shipped bundle catches a rename on upgrade.
|
// minification, so a string check on the shipped bundle catches a rename on upgrade.
|
||||||
// terminal-ios-native-input.js wraps `_inputEvent`, `_handleTextAreaBlur` and `_finalizeComposition`
|
// terminal-ios-native-input.js wraps `_inputEvent`, `_handleTextAreaBlur` and `_finalizeComposition`
|
||||||
// and reads `_compositionView`; if any is missing its create() returns null, and iOS then gets
|
// and reads `_compositionView`; if any is missing its create() returns null, and iOS falls back
|
||||||
// neither the native-input owner nor the keyCode-229 recovery, so #830 returns without a signal.
|
// to the keyCode-229 recovery, so #830 (suggestions, phrase replacement, held delete) returns
|
||||||
|
// without a signal.
|
||||||
|
// The iOS owner also clears `_unprocessedDeadKey` when native input commits text,
|
||||||
|
// so the next terminal command is not swallowed as part of the dead-key sequence.
|
||||||
it('still ships the composition-helper and mouse-service fields terminal input depends on', () => {
|
it('still ships the composition-helper and mouse-service fields terminal input depends on', () => {
|
||||||
const bundle = readFileSync(resolve(root, 'node_modules/@xterm/xterm/lib/xterm.js'), 'utf8');
|
const bundle = readFileSync(resolve(root, 'node_modules/@xterm/xterm/lib/xterm.js'), 'utf8');
|
||||||
for (const name of [
|
for (const name of [
|
||||||
@@ -84,6 +87,7 @@ describe('xterm private-API dependency guard', () => {
|
|||||||
'coreMouseService',
|
'coreMouseService',
|
||||||
'activeEncoding',
|
'activeEncoding',
|
||||||
'_inputEvent',
|
'_inputEvent',
|
||||||
|
'_unprocessedDeadKey',
|
||||||
'_handleTextAreaBlur',
|
'_handleTextAreaBlur',
|
||||||
'_finalizeComposition',
|
'_finalizeComposition',
|
||||||
'_compositionView',
|
'_compositionView',
|
||||||
|
|||||||
Reference in new issue
Block a user