Skip to content

Commit b8bf7a0

Browse files
authored
fix: keep focus in the standalone Editor after the first keystroke (#416)
### Description Fixes #415. The standalone `Editor` lost DOM focus after the first keystroke, so only one character could be typed until the user clicked back in. `use-editable` keys its editing-setup layout effect on the element ref, which is still `null` during the first render. `LiveProvider` re-renders when its initial transpile resolves, so that effect settles before the user types; the standalone `Editor` does not re-render until the first edit, so the first edit is what makes the effect re-run. The effect's cleanup resets `contentEditable` (which blurs the element in Chrome) and its setup then calls `focus()` while the element is still non-editable, so focus is not restored. `Editor` now re-renders once after mount, so use-editable's setup settles before the editor can be edited. The branch is rebased on master, so the test uses the vitest setup from #418: `packages/react-live/src/components/Editor/index.test.jsx`. #### Type of Change - [x] Bug fix (non-breaking change which fixes an issue) ### How Has This Been Tested? Added a regression test in `packages/react-live/src/components/Editor/index.test.jsx`. It mounts the standalone `Editor`, drives an edit through use-editable the same way the browser does (DOM mutation plus keydown/keyup), and asserts the editing surface is not torn down and rebuilt. Without the fix it fails: `contentEditable` is written twice (`undefined`, then `"plaintext-only"`), which is the teardown/rebuild that resets the surface and drops focus. With the fix no writes occur and the edit is applied. Running the same scenario against `<LiveProvider>` + `<LiveEditor>` never writes `contentEditable`, matching the report that the provider path was unaffected. The test takes `act` from `@testing-library/react` rather than `react`, because `React.act` only exists from 18.3.0 and the `React 18.0.0` job fails with `act is not a function` without it. The library re-exports `act` for whichever React it is testing against, and the other tests in this package already import it from there. jsdom has no contentEditable editing or focus model, so the browser-level focus loss itself cannot be reproduced in this suite; the regression test asserts the cause instead. I did not run a real-browser test. Validation, all run locally on the rebased branch against the lockfile React 19.3.0 and against React 18.0.0 (pinned exactly the way the `react-compat` job does): - `npm run check` under React 19.3.0 - lint, format, typecheck, and tests passed (8 files, 58 tests). - `npm run check` under React 18.0.0 - same result, and the test fails with `act is not a function` before the import change. - `npm run build` - library and docs site build passed under both. ### Checklist: - [x] I have included a changeset if this change will require a version change to one of the packages. - [x] I have performed a self-review of my own code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have run all builds, tests, and linting and all checks pass - [x] I have added tests that prove my fix is effective or that my feature works - [x] My changes generate no new warnings
1 parent 876a2a9 commit b8bf7a0

3 files changed

Lines changed: 122 additions & 2 deletions

File tree

‎.changeset/tidy-donkeys-refocus.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-live": patch
3+
---
4+
5+
Fix the standalone `Editor` losing focus after the first keystroke. `use-editable` rebuilt its editing surface on the first edit's re-render, which reset `contentEditable` and dropped focus; `Editor` now settles that surface before it can be edited.

‎packages/react-live/src/components/Editor/index.test.jsx‎

Lines changed: 104 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
import { render } from "@testing-library/react";
1+
import { setTimeout } from "node:timers/promises";
2+
import { createRoot } from "react-dom/client";
3+
import { act, render } from "@testing-library/react";
24
import { Prism, themes } from "prism-react-renderer";
35

46
import Editor from "./index";
@@ -10,6 +12,75 @@ import Editor from "./index";
1012
* CONTRIBUTING.
1113
*/
1214

15+
const settle = () => setTimeout(0);
16+
17+
const textNodes = (element) => {
18+
const nodes = [];
19+
const walk = (node) => {
20+
if (node.nodeType === Node.TEXT_NODE) nodes.push(node);
21+
node.childNodes.forEach(walk);
22+
};
23+
walk(element);
24+
return nodes;
25+
};
26+
27+
// The editor renders a trailing newline text node after the code, so the caret
28+
// goes at the end of the last text node that actually holds source.
29+
const codeTextNode = (element) =>
30+
textNodes(element)
31+
.filter((node) => node.textContent.trim() !== "")
32+
.pop();
33+
34+
const renderEditor = async (props) => {
35+
const container = document.createElement("div");
36+
document.body.appendChild(container);
37+
const root = createRoot(container);
38+
39+
await act(() => {
40+
root.render(<Editor language="javascript" {...props} />);
41+
});
42+
43+
const pre = container.querySelector("pre");
44+
// jsdom does not treat the contenteditable property that use-editable sets as
45+
// focusable, so give the element a tabIndex in order to focus it.
46+
pre.setAttribute("tabindex", "0");
47+
48+
await act(() => {
49+
pre.focus();
50+
const node = codeTextNode(pre);
51+
const range = document.createRange();
52+
range.setStart(node, node.textContent.length);
53+
range.collapse(true);
54+
const selection = window.getSelection();
55+
selection.removeAllRanges();
56+
selection.addRange(range);
57+
// use-editable records the caret from the browser's selectstart event.
58+
pre.dispatchEvent(new Event("selectstart", { bubbles: true }));
59+
});
60+
61+
return { container, root, pre };
62+
};
63+
64+
// use-editable reacts to the DOM mutation the browser makes while typing and
65+
// flushes it on keyup, so replicating that sequence exercises the same path.
66+
const typeCharacter = async (element, character) => {
67+
await act(() => {
68+
codeTextNode(element).textContent += character;
69+
element.dispatchEvent(
70+
new KeyboardEvent("keydown", { key: character, bubbles: true }),
71+
);
72+
element.dispatchEvent(
73+
new KeyboardEvent("keyup", { key: character, bubbles: true }),
74+
);
75+
});
76+
await settle();
77+
};
78+
79+
const unmount = async ({ container, root }) => {
80+
await act(() => root.unmount());
81+
document.body.removeChild(container);
82+
};
83+
1384
describe("Editor", () => {
1485
it("renders the code as highlighted tokens", () => {
1586
const { container } = render(
@@ -102,4 +173,36 @@ describe("Editor", () => {
102173
withDefault.container.querySelector("pre .token.keyword"),
103174
).toBeNull();
104175
});
176+
177+
// Regression test for #415.
178+
it("keeps the editing surface intact across the first edit", async () => {
179+
const rendered = await renderEditor({ code: "abc" });
180+
const { container, pre } = rendered;
181+
182+
// jsdom has no contentEditable editing model, so it cannot reproduce the
183+
// focus loss itself. What it can observe is the cause: use-editable keys its
184+
// setup on the element ref, which is null for the first render, so a
185+
// re-render rebuilds the surface -- resetting `contentEditable`, which blurs
186+
// the element in Chrome, and calling `focus()` while it is still
187+
// non-editable, which silently fails. No re-render on the first edit means
188+
// no teardown.
189+
let contentEditable = pre.contentEditable;
190+
const contentEditableWrites = [];
191+
Object.defineProperty(pre, "contentEditable", {
192+
configurable: true,
193+
get: () => contentEditable,
194+
set: (value) => {
195+
contentEditableWrites.push(value);
196+
contentEditable = value;
197+
},
198+
});
199+
200+
await typeCharacter(pre, "X");
201+
202+
expect(container.querySelector("pre")).toBe(pre);
203+
expect(pre.textContent).toBe("abcX\n");
204+
expect(contentEditableWrites).toEqual([]);
205+
206+
await unmount(rendered);
207+
});
105208
});

‎packages/react-live/src/components/Editor/index.tsx‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
duplicate lines and would remount nodes inside a contentEditable on every
44
edit, which is exactly where DOM churn is least welcome. */
55
import { Highlight, Prism, themes } from "prism-react-renderer";
6-
import { CSSProperties, useEffect, useRef, useState } from "react";
6+
import { CSSProperties, useEffect, useReducer, useRef, useState } from "react";
77
import { useEditable } from "use-editable";
88

99
export type Props = {
@@ -28,6 +28,18 @@ const CodeEditor = (props: Props) => {
2828
setCode(props.code);
2929
}, [props.code]);
3030

31+
// use-editable keys its editing setup on the element ref, which is still null
32+
// during the first render. Standalone Editor does not re-render between
33+
// mounting and the first edit, so that setup only reaches the real element
34+
// when the edit re-renders: it tears down and rebuilds the contenteditable
35+
// surface, resetting `contentEditable` (which blurs the element in Chrome)
36+
// and calling focus() while the element is still non-editable. LiveProvider
37+
// re-renders when its initial transpile resolves, which is why LiveEditor is
38+
// unaffected. Re-render once after mount so the setup settles beforehand.
39+
// See #415.
40+
const [, forceRender] = useReducer((n: number) => n + 1, 0);
41+
useEffect(forceRender, []);
42+
3143
useEditable(
3244
editorRef,
3345
(text) => {

0 commit comments

Comments
 (0)