holoviz/panel · #9156

fix: Apply Plotly relayouts and restyles sent before render

philippjfr · merged Nov 24, 20263 files · 364 + / 15 −
panel/models/plotly.ts173 + / 8 −
@@ -79,6 +79,99 @@ const decodeUndefined = (obj: any): any => {   return obj } +type PlotlyUpdate = {[key: string]: unknown}++/**+ * A relayout, or a restyle of a single trace, sent before the plot rendered.+ * Applied in order once plotted, they leave the plot as it would be had they+ * been applied as they arrived.+ */+type PendingUpdate = {kind: "relayout", data: PlotlyUpdate} | {kind: "restyle", trace: number, data: PlotlyUpdate}++const is_descendant = (key: string, of: string): boolean => {+  return key.startsWith(`${of}.`) || key.startsWith(`${of}[`)+}++const parent_path = (key: string): string => {+  const index = Math.max(key.lastIndexOf("."), key.lastIndexOf("["))+  return index < 0 ? "" : key.slice(0, index)+}++/**+ * The array an item-level key such as `annotations[0]` writes to. Plotly+ * treats such a write as an insert (or, with null, a removal) that shifts+ * the items after it, so it is never superseded and orders later writes.+ */+const item_array = (key: string): string | null => {+  return key.endsWith("]") ? key.slice(0, key.lastIndexOf("[")) : null+}++const within = (key: string, path: string): boolean => key == path || is_descendant(key, path)++/**+ * Whether `key` must be applied after `other` rather than together with it:+ * keys under a written ancestor, keys next to a sibling such as+ * `xaxis.range` and `xaxis.autorange` that Plotly resolves together, and+ * keys in an array that an item-level write shifts.+ */+const conflicts = (key: string, other: string): boolean => {+  if (is_descendant(key, other) || is_descendant(other, key)) {+    return true+  }+  const key_array = item_array(key)+  const other_array = item_array(other)+  if ((key_array != null && within(other, key_array)) || (other_array != null && within(key, other_array))) {+    return true+  }+  const parent = parent_path(key)+  return parent !== "" && parent === parent_path(other)+}++/**+ * Adds an update to the queue, dropping earlier writes it supersedes (the+ * same key or a descendant, up to an item-level write that shifted them)+ * and merging it into the last entry when that entry is of the same kind+ * and target and none of its keys conflict. Apart from item-level writes,+ * every key is then pending at most once, which bounds the queue.+ */+export function queue_update(queue: PendingUpdate[], update: PendingUpdate): PendingUpdate[] {+  const keys = Object.keys(update.data)+  const same_target = (entry: PendingUpdate) => {+    return entry.kind == update.kind && (entry.kind == "relayout" || entry.trace == (update as any).trace)+  }+  for (const k of keys) {+    if (item_array(k) != null) {+      continue+    }+    for (let i = queue.length - 1; i >= 0; i--) {+      const entry = queue[i]+      if (!same_target(entry)) {+        continue+      }+      const entry_keys = Object.keys(entry.data)+      if (entry_keys.some((key) => {+        const array = item_array(key)+        return array != null && is_descendant(k, array)+      })) {+        break+      }+      for (const key of entry_keys) {+        if (within(key, k)) {+          delete entry.data[key]+        }+      }+    }+  }+  const pending = queue.filter((entry) => Object.keys(entry.data).length > 0)+  const last = pending.at(-1)+  if (last != null && same_target(last) && !Object.keys(last.data).some((key) => keys.some((k) => conflicts(k, key)))) {+    Object.assign(last.data, update.data)+  } else {+    pending.push({...update, data: {...update.data}})+  }+  return pending+}+ const filterEventData = (gd: any, eventData: any, event: string) => {   // Ported from dash-core-components/src/components/Graph.react.js   const filteredEventData: {[k: string]: any} = Array.isArray(eventData)? []: {}@@ -212,6 +305,7 @@ export class PlotlyPlotView extends HTMLBoxView {   _reacting: boolean = false   _relayouting: boolean = false   _model_restyles: number = 0+  _pending_updates: PendingUpdate[] = []   _hoverdata: any = null   container: PlotlyHTMLElement   _end_relayouting = debounce(() => {@@ -238,28 +332,37 @@ export class PlotlyPlotView extends HTMLBoxView {     } = this.model.properties      this.on_change([data, data_sources, layout, _render_count], () => {+      // The new state already includes any update sent before render+      this._pending_updates = []       this._schedule_plot()     })     this.on_change(frames, () => {       this._schedule_plot(true)     })     this.on_change(relayout, () => {-      if (this.model.relayout == null || this.container == null) {+      const {relayout} = this.model+      if (relayout == null) {         return       }-      (window as any).Plotly.relayout(this.container, this.model.relayout)       this.model.relayout = null+      if (this.container == null) {+        this._pending_updates = queue_update(this._pending_updates, {kind: "relayout", data: relayout})+      } else {+        (window as any).Plotly.relayout(this.container, relayout)+      }     })     this.on_change(restyle, () => {-      if (this.model.restyle == null || this.container == null) {+      const {restyle} = this.model+      if (restyle == null) {         return       }-      const data = decodeUndefined(this.model.restyle.data)-      this._model_restyles += 1-      ;(window as any).Plotly.restyle(this.container, data, this.model.restyle.traces).finally(() => {-        this._model_restyles -= 1-      })       this.model.restyle = null+      const data = decodeUndefined(restyle.data)+      if (this.container == null) {+        this._queue_restyle(data, restyle.traces)+      } else {+        this._restyle(data, restyle.traces)+      }     })      this.on_change(viewport_update_policy, () => {@@ -315,10 +418,72 @@ export class PlotlyPlotView extends HTMLBoxView {       this.resize_layout()       if (this.model.relayout != null) {         (window as any).Plotly.relayout(this.container, this.model.relayout)+        this.model.relayout = null+      }+      return this._apply_pending_updates()+    })+  }++  _restyle(data: PlotlyUpdate, traces: number | number[] | null): Promise<unknown> {+    this._model_restyles += 1+    return (window as any).Plotly.restyle(this.container, data, traces).finally(() => {+      this._model_restyles -= 1+    })+  }++  /**+   * Splits a restyle into one update per trace, resolving values the way+   * Plotly does: arrays are indexed (and wrapped) by position in `traces`,+   * and undefined values leave the trace unchanged.+   */+  _queue_restyle(data: PlotlyUpdate, traces: number | number[] | null): void {+    const ntraces = this.model.data.length+    const indices = traces == null ? [...Array(ntraces).keys()] : Array.isArray(traces) ? traces : [traces]+    indices.forEach((trace, position) => {+      // Plotly ignores negative trace indices+      if (trace < 0) {+        return+      }+      const update: PlotlyUpdate = {}+      for (const [key, value] of Object.entries(data)) {+        const trace_value = Array.isArray(value) ? value[position % value.length] : value+        if (trace_value !== undefined) {+          update[key] = trace_value+        }+      }+      if (Object.keys(update).length > 0) {+        this._pending_updates = queue_update(this._pending_updates, {kind: "restyle", trace, data: update})       }     })   } +  async _apply_pending_updates(): Promise<void> {+    const pending = this._pending_updates+    this._pending_updates = []+    let i = 0+    while (i < pending.length) {+      const entry = pending[i]+      if (entry.kind == "relayout") {+        await (window as any).Plotly.relayout(this.container, entry.data)+        i+++        continue+      }+      // Consecutive restyles of the same keys on different traces go in one call+      const keys = Object.keys(entry.data).join("\0")+      const batch = [entry]+      while (i + batch.length < pending.length) {+        const next = pending[i + batch.length]+        if (next.kind != "restyle" || Object.keys(next.data).join("\0") != keys || batch.some((e) => e.trace == next.trace)) {+          break+        }+        batch.push(next)+      }+      const data = Object.fromEntries(Object.keys(entry.data).map((key) => [key, batch.map((e) => e.data[key])]))+      await this._restyle(data, batch.map((e) => e.trace))+      i += batch.length+    }+  }+   /**    * The plot size derived from the model and the element, or null while    * the element is not laid out.
panel/tests/ui/pane/test_plotly.py184 + / 0 −
@@ -7,11 +7,14 @@ pytest.importorskip("plotly")  import numpy as np+import param import plotly.graph_objs as go import plotly.io as pio  from playwright.sync_api import expect +from panel.custom import Child, ReactComponent+from panel.layout import Column from panel.pane import Plotly from panel.tests.util import serve_component, wait_until @@ -518,3 +521,184 @@ def test_plotly_data_update_keeps_frames(page):     new_frames = frames + [go.Frame(name='second', data=[go.Scatter(y=[7, 8])])]     pane.object = go.Figure(data=[go.Scatter(x=[0, 1], y=[5, 6])], frames=new_frames)     wait_until(lambda: gd.evaluate("gd => gd._transitionData._frames.length") == 2, page)+++class PlotlyToggle(ReactComponent):+    """Renders its child only once `mounted` is set."""++    child = Child()++    mounted = param.Boolean(default=False)++    text = param.String()++    _esm = """+    export function render({ model }) {+      const [mounted] = model.useState("mounted")+      const [text] = model.useState("text")+      const child = model.get_child("child")+      return <div><h2>{text}</h2>{mounted ? child : null}</div>+    }+    """+++U = '_undefined_'++RESTYLES = {+    'traces_0_then_01_then_1': [+        ({'marker.color': ['red']}, [0]),+        ({'marker.color': ['blue', 'green']}, [0, 1]),+        ({'marker.color': ['orange']}, [1]),+    ],+    'merge_past_other_key_same_traces': [+        ({'marker.color': ['a1', 'b1']}, [0, 1]),+        ({'opacity': [0.5]}, [1]),+        ({'marker.color': ['red', 'blue']}, [0, 1]),+    ],+    'null_mixed_with_specific': [+        ({'opacity': 0.2}, None),+        ({'opacity': [0.7]}, [1]),+        ({'marker.color': 'red'}, None),+        ({'opacity': [0.9]}, [0]),+        ({'marker.color': ['blue']}, [2]),+        ({'opacity': 0.4}, None),+        ({'marker.color': ['green']}, [1]),+    ],+    'same_key_overlapping_sets_between': [+        ({'marker.color': ['red', 'red']}, [0, 1]),+        ({'marker.color': ['blue', 'blue']}, [1, 2]),+        ({'marker.color': ['green', 'green']}, [0, 1]),+        ({'marker.color': ['black']}, [2]),+        ({'marker.color': ['white', 'white']}, [1, 2]),+    ],+    'overlap_then_same_merge': [+        ({'marker.color': ['red'], 'opacity': [0.3]}, [0]),+        ({'opacity': [0.6, 0.6]}, [0, 1]),+        ({'marker.color': ['blue']}, [0]),+        ({'opacity': [0.8]}, [0]),+    ],+    'nested_parent_child_keys': [+        ({'marker.color': ['red', 'blue']}, [0, 1]),+        ({'marker': [{'color': 'green', 'size': 20}]}, [1]),+        ({'marker.color': ['black', 'white']}, [0, 1]),+    ],+    'undefined_slots': [+        ({'marker.color': ['red', 'blue']}, [0, 1]),+        ({'marker.color': [U, 'green']}, [0, 1]),+    ],+    'undefined_slots_cover': [+        ({'marker.color': ['red']}, [0]),+        ({'marker.color': [U, 'green', 'blue']}, [0, 1, 2]),+    ],+    'negative_trace_index': [+        ({'marker.color': ['red']}, [-1]),+        ({'marker.color': ['blue']}, [2]),+        ({'opacity': [0.4]}, [-1]),+    ],+}++RELAYOUTS = {+    'leaf_then_parent': [{'xaxis.range': [0, 5]}, {'xaxis': {'title': {'text': 'X'}}}],+    'parent_then_leaf': [{'xaxis': {'title': {'text': 'X'}, 'range': [0, 2]}}, {'xaxis.range': [0, 5]}],+    'leaf_parent_leaf': [{'xaxis.range': [0, 5]}, {'xaxis': {'title': {'text': 'X'}}}, {'xaxis.range': [1, 3]}],+    'title_text_then_title': [{'title.text': 'A'}, {'title': {'text': 'B', 'x': 0.2}}, {'title.text': 'C'}],+    'range_then_autorange': [{'xaxis.range': [0, 5]}, {'xaxis.autorange': True}],+    'autorange_then_range': [{'xaxis.autorange': True}, {'xaxis.range': [0, 5]}],+    'annotation_insert': [+        {'annotations[0].text': 'x0'},+        {'annotations[1].text': 'x1'},+        {'annotations[0]': {'x': 0, 'y': 0, 'text': 'new0'}},+        {'annotations[0].text': 'y0'},+        {'annotations[1].x': 2},+    ],+    'annotation_remove': [+        {'annotations[1].text': 'x1'},+        {'annotations[0]': None},+        {'annotations[0].text': 'y0'},+    ],+    'annotations_then_item': [+        {'annotations[0].text': 'x0'},+        {'annotations': [{'x': 0, 'y': 0, 'text': 'w0'}]},+        {'annotations[0].text': 'z0'},+    ],+}++READ_TRACES = "gd => gd.data.map(t => [t.marker?.color ?? null, t.marker?.size ?? null, t.opacity ?? null])"++READ_LAYOUT = """gd => [+  gd.layout.xaxis?.range ?? null, gd.layout.xaxis?.title?.text ?? null, gd.layout.title?.text ?? null,+  gd.layout.title?.x ?? null, gd.layout.xaxis?.autorange ?? null,+  (gd.layout.annotations ?? []).map(a => [a.text, a.x])+]"""+++def _serve_mounted_and_unmounted(page):+    figures = [+        go.Figure(+            [go.Scatter(x=[0, 1], y=[i, i + 1], mode='markers') for i in range(3)],+            layout={'annotations': [{'x': 0, 'y': 0, 'text': 'a0'}, {'x': 1, 'y': 1, 'text': 'a1'}]}+        )+        for _ in range(2)+    ]+    mounted, unmounted = Plotly(figures[0]), Plotly(figures[1])+    toggle = PlotlyToggle(child=unmounted, text='Unmounted')+    layout = Column(PlotlyToggle(child=mounted, text='Mounted', mounted=True), toggle)+    serve_component(page, layout)+    gd = page.locator('.js-plotly-plot')+    expect(gd).to_have_count(1)+    models = [next(iter(pane._models.values()))[0] for pane in (mounted, unmounted)]+    return gd, toggle, next(iter(layout._documents)), models, unmounted+++def _send(page, doc, models, prop, value):+    def send():+        for model in models:+            setattr(model, prop, value)+    doc.add_next_tick_callback(send)+    wait_until(lambda: all(getattr(model, prop) is None for model in models), page)+++@pytest.mark.parametrize('name', list(RESTYLES))+def test_plotly_restyles_before_render_match_mounted_plot(page, name):+    gd, toggle, doc, models, _ = _serve_mounted_and_unmounted(page)++    for data, traces in RESTYLES[name]:+        _send(page, doc, models, 'restyle', {'data': data, 'traces': traces})++    toggle.mounted = True+    expect(gd).to_have_count(2)+    wait_until(lambda: gd.nth(1).evaluate(READ_TRACES) == gd.nth(0).evaluate(READ_TRACES), page)+++@pytest.mark.parametrize('name', list(RELAYOUTS))+def test_plotly_relayouts_before_render_match_mounted_plot(page, name):+    gd, toggle, doc, models, _ = _serve_mounted_and_unmounted(page)++    for relayout in RELAYOUTS[name]:+        _send(page, doc, models, 'relayout', relayout)++    toggle.mounted = True+    expect(gd).to_have_count(2)+    wait_until(lambda: gd.nth(1).evaluate(READ_LAYOUT) == gd.nth(0).evaluate(READ_LAYOUT), page)+++def test_plotly_updates_before_render_stay_bounded(page):+    gd, toggle, doc, models, _ = _serve_mounted_and_unmounted(page)+    model = models[1]++    def send():+        for i in range(200):+            model.restyle = {'data': {'y': [list(range(i, i+1000))]}, 'traces': [0]}+            model.relayout = {'title.text': f'Title {i}'}+        toggle.text = 'Sent'+    doc.add_next_tick_callback(send)++    # The text arrives in the same patch, after all the updates+    expect(page.locator('h2').nth(1)).to_have_text('Sent')+    pending = page.evaluate(f"() => Bokeh.index.find_one_by_id('{model.id}')._pending_updates.length")+    assert pending == 2++    toggle.mounted = True+    expect(gd).to_have_count(2)+    wait_until(lambda: gd.nth(1).evaluate("gd => [gd.data[0].y[0], gd.data[0].y.length]") == [199, 1000], page)+    expect(gd.nth(1).locator('.gtitle')).to_have_text('Title 199')
panel/tests/ui/test_custom.py7 + / 7 −
@@ -203,16 +203,16 @@ class ReactToggle(ReactComponent):      child = Child() -    show = param.Boolean(default=False)+    mounted = param.Boolean(default=False)      text = param.String()      _esm = """     export function render({ model }) {-      const [show] = model.useState("show")+      const [mounted] = model.useState("mounted")       const [text] = model.useState("text")       const child = model.get_child("child")-      return <div><h2>{text}</h2>{show ? child : null}</div>+      return <div><h2>{text}</h2>{mounted ? child : null}</div>     }     """ @@ -233,7 +233,7 @@ def test_resize_unmounted_child_does_not_abort_patch(page):      expect(page.locator('h2')).to_have_text('After') -    parent.show = True+    parent.mounted = True      expect(page.locator('h1')).to_have_text('Child')     wait_until(lambda: _sizes(page)['width'] == 200, page)@@ -253,7 +253,7 @@ def test_resize_unmounted_no_shadow_dom_child_does_not_abort_patch(page):      expect(page.locator('h2')).to_have_text('After') -    parent.show = True+    parent.mounted = True      expect(page.locator('h1')).to_have_text('Child')     wait_until(lambda: page.locator('h1').evaluate(@@ -275,7 +275,7 @@ def test_resize_unmounted_markdown_child_does_not_abort_patch(page):      expect(page.locator('h2')).to_have_text('After') -    parent.show = True+    parent.mounted = True      expect(page.locator('.markdown')).to_have_text('Child')     wait_until(lambda: page.locator('.markdown').evaluate(@@ -306,7 +306,7 @@ def update():      expect(page.locator('h2')).to_have_text('After') -    parent.show = True+    parent.mounted = True      expect(page.locator('.js-plotly-plot')).to_have_count(1)     expect(page.locator('.js-plotly-plot .gtitle')).to_have_text('Relayout')