Skip to content

Commit 9b043ad

Browse files
committed
deploy: 7e64238
1 parent 69614b9 commit 9b043ad

2 files changed

Lines changed: 18 additions & 6 deletions

File tree

app.wasm

6.2 KB
Binary file not shown.

caret.js

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,27 @@
55
// value and drops the caret at the end. The update function knows the offset the
66
// caret should have, and calls this once the patch has landed.
77
//
8-
// The rAF is what waits for that patch: the update returns before miso has
9-
// touched the DOM, so setting the selection synchronously would set it on the
10-
// pre-rewrite text and be overwritten a frame later.
11-
globalThis.setEditorCaret = function (offset) {
12-
requestAnimationFrame(function () {
8+
// Waiting for that patch is the whole difficulty. miso diffs inside an animation
9+
// frame of its own, queued after the one this call could take, and assigning
10+
// .value moves the caret to the end — so setting the selection a frame too early
11+
// is silently undone. Rather than guess the ordering, wait until the textarea
12+
// actually holds the text the caret offset refers to, then place it.
13+
//
14+
// The bound on retries keeps a mismatch (an edit that arrived meanwhile, say)
15+
// from spinning forever; giving up leaves the caret where the browser put it.
16+
globalThis.setEditorCaret = function (offset, expected) {
17+
let tries = 0;
18+
const place = function () {
1319
const el = document.querySelector("textarea.editor");
1420
if (!el) return;
21+
if (el.value !== expected && tries < 10) {
22+
tries++;
23+
requestAnimationFrame(place);
24+
return;
25+
}
1526
const i = Math.max(0, Math.min(Number(offset) || 0, el.value.length));
1627
el.focus();
1728
el.setSelectionRange(i, i);
18-
});
29+
};
30+
requestAnimationFrame(place);
1931
};

0 commit comments

Comments
 (0)