holoviz/panel · #9187

perf: Mount ReactComponent roots in batches

philippjfr · merged Nov 29, 20263 files · 132 + / 9 −
panel/custom.py1 + / 0 −
@@ -1027,6 +1027,7 @@ def _exports__(cls) -> ExportSpec:  # type: ignore         imports = cls._importmap.get('imports', {})         exports: dict[str, list[str | tuple[str, ...]]] = {             "react": ["*React"],+            "react-dom": [("flushSync",)],             "react-dom/client": [("createRoot",)]         }         if any('@mui' in v for v in imports.values()):
panel/models/react_component.ts73 + / 9 −
@@ -416,25 +416,29 @@ export class ReactComponentView extends ReactiveESMView { type ReactLibs = {   React: any   createRoot: any+  flushSync?: any+  react_dom?: any   createCache?: any   CacheProvider?: any } -const REACT_PACKAGES = ["react", "react-dom/client", "@emotion/cache", "@emotion/react"]+const REACT_PACKAGES = ["react", "react-dom", "react-dom/client", "@emotion/cache", "@emotion/react"]  function react_libs_code(mui: boolean): string {   if (mui) {     return ` import * as React from "react"+import { flushSync } from "react-dom" import { createRoot } from "react-dom/client" import createCache from "@emotion/cache" import { CacheProvider } from "@emotion/react"-export default {React, createRoot, createCache, CacheProvider}`+export default {React, createRoot, flushSync, createCache, CacheProvider}`   }   return ` import * as React from "react"+import { flushSync } from "react-dom" import { createRoot } from "react-dom/client"-export default {React, createRoot}`+export default {React, createRoot, flushSync}` }  type ReactWrappers = {@@ -899,6 +903,71 @@ function uses_emotion(libs: ReactLibs): boolean {   return libs.createCache != null && libs.CacheProvider != null } +// React renders each root in a scheduler task of its own and yields to the+// browser every 5ms, so when many roots mount at once, e.g. one per widget in+// a large layout, only a few mount per frame and the browser restyles and+// repaints the whole page for every one of those frames. Mounts are instead+// queued and flushed synchronously in batches, yielding once a batch has run+// for MOUNT_BUDGET ms.+const MOUNT_BUDGET = 50+let pending_mounts: (() => void)[] = []+let mount_channel: MessageChannel | null = null++function flush_mounts(): void {+  const start = performance.now()+  let i = 0+  while (i < pending_mounts.length && performance.now() - start < MOUNT_BUDGET) {+    try {+      pending_mounts[i++]()+    } catch (e) {+      // Errors raised while rendering used to surface from React's own task,+      // so they are re-raised without holding up the remaining mounts.+      queueMicrotask(() => { throw e })+    }+  }+  pending_mounts = pending_mounts.slice(i)+  if (pending_mounts.length > 0) {+    mount_channel!.port2.postMessage(null)+  }+}++function queue_mount(mount: () => void): void {+  if (mount_channel == null) {+    mount_channel = new MessageChannel()+    mount_channel.port1.onmessage = flush_mounts+  }+  pending_mounts.push(mount)+  if (pending_mounts.length === 1) {+    mount_channel.port2.postMessage(null)+  }+}++function mount_root(view: ReactComponentView, root: any, rendered: any, flushSync: any): void {+  const mount = () => {+    try {+      root.render(rendered)+    } catch (e) {+      view._resolve_mounted()+      view.render_error(e as SyntaxError)+    }+  }+  if (flushSync == null) {+    mount()+    return+  }+  let unmounted = false+  const unmount = root.unmount.bind(root)+  root.unmount = () => {+    unmounted = true+    unmount()+  }+  queue_mount(() => {+    if (!unmounted && !view.is_destroyed) {+      flushSync(mount)+    }+  })+}+ function render_react(view: ReactComponentView, libs: ReactLibs): any {   if (view.is_destroyed) {     return null@@ -929,12 +998,7 @@ function render_react(view: ReactComponentView, libs: ReactLibs): any {     container = view.container   }   const root = createRoot(container)-  try {-    root.render(rendered)-  } catch (e) {-    view._resolve_mounted()-    view.render_error(e as SyntaxError)-  }+  mount_root(view, root, rendered, libs.flushSync ?? libs.react_dom?.flushSync)   return root } 
panel/tests/ui/test_custom.py58 + / 0 −
@@ -2723,3 +2723,61 @@ def test_append_does_not_rerender_unmoved_siblings(page):     page.wait_for_timeout(300)      assert page.evaluate('window.__renders') == renders + 1+++class ReactSlowMount(ReactComponent):++    _esm = """+    export function render() {+      React.useEffect(() => { (window.__mount_frames ??= []).push(window.__frame) }, [])+      const start = performance.now()+      while (performance.now() - start < 2) {}+      return <div className="slow-mount">mounted</div>+    }+    """+++@pytest.mark.internet+def test_many_react_roots_mount_in_few_frames(page):+    layout = Column(ReactSlowMount())++    serve_component(page, layout)++    expect(page.locator('.slow-mount')).to_have_count(1)+    page.evaluate("""() => {+      window.__frame = 0+      window.__mount_frames = []+      const tick = () => { window.__frame++; requestAnimationFrame(tick) }+      requestAnimationFrame(tick)+    }""")++    layout.objects = [ReactSlowMount() for _ in range(100)]++    expect(page.locator('.slow-mount')).to_have_count(100)+    frames = page.evaluate('window.__mount_frames')+    assert len(frames) == 100+    # Unbatched, React yields to the browser every 5ms, so the 200ms of+    # rendering would be spread over about 40 frames.+    assert max(frames) - min(frames) < 15+++class ReactThrows(ReactComponent):++    _esm = """+    export function render() {+      throw new Error("render failed")+    }+    """+++@pytest.mark.internet+def test_react_root_failing_to_render_does_not_block_other_roots(page):+    layout = Column(ReactUpdate(text='before'))++    serve_component(page, layout)++    expect(page.locator('h1')).to_have_text('before')++    layout.objects = [ReactThrows(), ReactUpdate(text='after'), ReactThrows(), ReactUpdate(text='last')]++    expect(page.locator('h1')).to_have_text(['after', 'last'])