diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx index a90eabe..3cdb2e6 100644 --- a/src/web/CodeEditor.tsx +++ b/src/web/CodeEditor.tsx @@ -5,7 +5,7 @@ import { useCallback, useEffect, useImperativeHandle, - useLayoutEffect, + useInsertionEffect, useMemo, useRef, useState, @@ -74,8 +74,8 @@ export const CodeEditor = forwardRef(function Co onBlur, onGapLayout, }); - // Written on commit, so a render React drops never calls its handlers. - useLayoutEffect(() => { + // Written on commit before any layout effect runs, so a render React drops never calls its handlers. + useInsertionEffect(() => { handlers.current = { onReady, onScroll, @@ -158,8 +158,8 @@ export const CodeEditor = forwardRef(function Co ], ); const latest = useRef({ options, language, decorations, decorationsRevision }); - // Written on commit, so the props of a render React drops never reach the view. - useLayoutEffect(() => { + // Written on commit before any layout effect runs, so the props of a render React drops never reach the view. + useInsertionEffect(() => { latest.current = { options, language, decorations, decorationsRevision }; }); // The decorations last sent, so the view gets them before its first draw and a repeat is not mapped twice. diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx index 304fa7e..7b64b5f 100644 --- a/src/web/__tests__/CodeEditor.test.tsx +++ b/src/web/__tests__/CodeEditor.test.tsx @@ -1,6 +1,6 @@ import { beforeEach, expect, jest, test } from '@jest/globals'; import { act, render } from '@testing-library/react-native'; -import { createRef, Suspense, startTransition, use, useState } from 'react'; +import { createRef, Suspense, startTransition, use, useLayoutEffect, useState } from 'react'; import type { CodeEditorRef } from '../../types'; import type { ViewOptions } from '../EditorView'; @@ -265,6 +265,32 @@ test('a render that never commits keeps its decorations, options and handlers of expect(ready).toEqual([['committed', 14]]); }); +test("a layout effect earlier in the tree that focuses the editor reaches the same commit's onFocus", async () => { + const ref = createRef(); + const calls: string[] = []; + function Focuser({ n }: { n: number }) { + useLayoutEffect(() => { + if (n > 0) void ref.current?.focus(); + }, [n]); + return null; + } + function App({ n }: { n: number }) { + return ( + <> + + calls.push(`focus ${n}`)} /> + + ); + } + const { rerender } = await render(); + await act(async () => { + mockCore.resolve({}); + await tick(); + }); + await rerender(); + expect(calls).toEqual(['focus 1']); +}); + test('decorations without a revision are for the current text', async () => { const items = [{ kind: 'lineBackground' as const, line: 1, color: 'red' }]; await render();