@holoviz/panel 1.10.0-b.1 → 1.10.0-b.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/bundled/licenses/index.json +2 -2
  2. package/dist/css/codeeditor_mui.css +11 -0
  3. package/dist/css/dataframe_mui.css +46 -0
  4. package/dist/css/filedropper_mui.css +33 -0
  5. package/dist/css/json_mui.css +38 -0
  6. package/dist/css/jsoneditor_mui.css +114 -0
  7. package/dist/css/loading.css +9 -1
  8. package/dist/css/markdown_mui.css +45 -0
  9. package/dist/css/models/tabulator.css +4 -0
  10. package/dist/css/tabulator_mui.css +186 -0
  11. package/dist/css/terminal_mui.css +5 -0
  12. package/dist/css/texteditor_mui.css +76 -0
  13. package/dist/dts/styles/codeeditor_mui.css.d.ts +4 -0
  14. package/dist/dts/styles/dataframe_mui.css.d.ts +4 -0
  15. package/dist/dts/styles/filedropper_mui.css.d.ts +5 -0
  16. package/dist/dts/styles/json_mui.css.d.ts +4 -0
  17. package/dist/dts/styles/jsoneditor_mui.css.d.ts +4 -0
  18. package/dist/dts/styles/markdown_mui.css.d.ts +4 -0
  19. package/dist/dts/styles/tabulator_mui.css.d.ts +4 -0
  20. package/dist/dts/styles/terminal_mui.css.d.ts +4 -0
  21. package/dist/dts/styles/texteditor_mui.css.d.ts +4 -0
  22. package/dist/lib/models/anywidget_component.d.ts +1 -1
  23. package/dist/lib/models/anywidget_component.js +13 -14
  24. package/dist/lib/models/anywidget_component.js.map +1 -1
  25. package/dist/lib/models/cell_formatters.d.ts +9 -0
  26. package/dist/lib/models/cell_formatters.js +174 -0
  27. package/dist/lib/models/cell_formatters.js.map +1 -0
  28. package/dist/lib/models/html.d.ts +42 -2
  29. package/dist/lib/models/html.js +287 -22
  30. package/dist/lib/models/html.js.map +1 -1
  31. package/dist/lib/models/index.d.ts +1 -1
  32. package/dist/lib/models/index.js +1 -1
  33. package/dist/lib/models/index.js.map +1 -1
  34. package/dist/lib/models/layout.d.ts +17 -6
  35. package/dist/lib/models/layout.js +75 -45
  36. package/dist/lib/models/layout.js.map +1 -1
  37. package/dist/lib/models/react_component.d.ts +12 -2
  38. package/dist/lib/models/react_component.js +468 -370
  39. package/dist/lib/models/react_component.js.map +1 -1
  40. package/dist/lib/models/reactive_esm.d.ts +59 -5
  41. package/dist/lib/models/reactive_esm.js +347 -211
  42. package/dist/lib/models/reactive_esm.js.map +1 -1
  43. package/dist/lib/models/resources.js +11 -4
  44. package/dist/lib/models/resources.js.map +1 -1
  45. package/dist/lib/models/tabulator.d.ts +25 -3
  46. package/dist/lib/models/tabulator.js +100 -74
  47. package/dist/lib/models/tabulator.js.map +1 -1
  48. package/dist/lib/models/vtk/util.d.ts +1 -1
  49. package/dist/lib/models/vtk/vtkaxes.js +25 -7
  50. package/dist/lib/models/vtk/vtkaxes.js.map +1 -1
  51. package/dist/lib/styles/codeeditor_mui.css.d.ts +2 -0
  52. package/dist/lib/styles/codeeditor_mui.css.js +1 -0
  53. package/dist/lib/styles/dataframe_mui.css.d.ts +2 -0
  54. package/dist/lib/styles/dataframe_mui.css.js +1 -0
  55. package/dist/lib/styles/filedropper_mui.css.d.ts +3 -0
  56. package/dist/lib/styles/filedropper_mui.css.js +2 -0
  57. package/dist/lib/styles/json_mui.css.d.ts +2 -0
  58. package/dist/lib/styles/json_mui.css.js +1 -0
  59. package/dist/lib/styles/jsoneditor_mui.css.d.ts +2 -0
  60. package/dist/lib/styles/jsoneditor_mui.css.js +1 -0
  61. package/dist/lib/styles/loading.css.js +4 -1
  62. package/dist/lib/styles/markdown_mui.css.d.ts +2 -0
  63. package/dist/lib/styles/markdown_mui.css.js +1 -0
  64. package/dist/lib/styles/models/tabulator.css.js +1 -1
  65. package/dist/lib/styles/tabulator_mui.css.d.ts +2 -0
  66. package/dist/lib/styles/tabulator_mui.css.js +75 -0
  67. package/dist/lib/styles/terminal_mui.css.d.ts +2 -0
  68. package/dist/lib/styles/terminal_mui.css.js +1 -0
  69. package/dist/lib/styles/texteditor_mui.css.d.ts +2 -0
  70. package/dist/lib/styles/texteditor_mui.css.js +1 -0
  71. package/dist/panel.js +1776 -7483
  72. package/dist/panel.js.map +1 -1
  73. package/dist/panel.json +1 -1
  74. package/dist/panel.min.js +45 -50
  75. package/package.json +3 -4
@@ -1,8 +1,9 @@
1
1
  import { build_views } from "@bokehjs/core/build_views";
2
+ import { View } from "@bokehjs/core/view";
2
3
  import { ClassList, InlineStyleSheet, ImportedStyleSheet } from "@bokehjs/core/dom";
3
4
  import { difference } from "@bokehjs/core/util/array";
4
5
  import { assert } from "@bokehjs/core/util/assert";
5
- import { isString } from "@bokehjs/core/util/types";
6
+ import { isArray, isString } from "@bokehjs/core/util/types";
6
7
  import { ReactiveESM, ReactiveESMView, model_getter, model_setter, } from "./reactive_esm";
7
8
  export class HostedStyleSheet extends InlineStyleSheet {
8
9
  persistent;
@@ -66,6 +67,7 @@ export class ReactComponentView extends ReactiveESMView {
66
67
  _force_update_callbacks = [];
67
68
  _mounted_resolve = null;
68
69
  _scheduled_removals = [];
70
+ _dom_sentinel = null;
69
71
  initialize() {
70
72
  super.initialize();
71
73
  if (!this.use_shadow_dom) {
@@ -106,7 +108,7 @@ export class ReactComponentView extends ReactiveESMView {
106
108
  this._resolve_mounted();
107
109
  return;
108
110
  }
109
- this.react_root = mod.default.render(this.model.id);
111
+ this.react_root = Promise.resolve(mod.default.render(this));
110
112
  }).catch((e) => {
111
113
  this._resolve_mounted();
112
114
  throw e;
@@ -145,12 +147,18 @@ export class ReactComponentView extends ReactiveESMView {
145
147
  // A view removed before it mounted still owes a resolution to the promise
146
148
  // handed to `_await_ready`, otherwise the root never reaches idle.
147
149
  this._resolve_mounted();
148
- if (this.react_root && this.use_shadow_dom) {
150
+ if (this.use_shadow_dom) {
149
151
  super.remove();
150
- this.react_root.then((root) => root && root.unmount());
152
+ this.react_root?.then((root) => root?.unmount?.());
151
153
  this.flush_scheduled_removals();
152
154
  }
153
- else {
155
+ else if (!this.is_destroyed) {
156
+ // The el of a view nested in its parent's React tree is a container
157
+ // owned by that tree, so DOMView.remove must not detach it; React does
158
+ // on unmount. View.remove still disconnects signals, watchers and the
159
+ // event dispatch, and removes the child views.
160
+ this._resize_observer.disconnect();
161
+ View.prototype.remove.call(this);
154
162
  this._applied_stylesheets.forEach((stylesheet) => stylesheet.uninstall());
155
163
  for (const cb of (this._lifecycle_handlers.get("remove") || [])) {
156
164
  cb();
@@ -211,7 +219,7 @@ export class ReactComponentView extends ReactiveESMView {
211
219
  }
212
220
  render() {
213
221
  if (this.react_root) {
214
- this.react_root.then((root) => root.unmount());
222
+ this.react_root.then((root) => root?.unmount?.());
215
223
  }
216
224
  this._force_update_callbacks = [];
217
225
  this.mounted = false;
@@ -229,9 +237,30 @@ export class ReactComponentView extends ReactiveESMView {
229
237
  this._apply_visible();
230
238
  }
231
239
  super.r_after_render();
232
- if (this.use_shadow_dom) {
240
+ if (this.use_shadow_dom && this._dom_reinserted()) {
233
241
  this.force_update();
242
+ this._mark_dom();
243
+ }
244
+ }
245
+ /**
246
+ * Re-inserting a node recreates the style sheets in its shadow root from
247
+ * their text, dropping rules added through the CSSOM, which is how emotion
248
+ * injects styles. A sentinel holding one CSSOM rule detects exactly that,
249
+ * so that the parent re-rendering, which walks every child, only forces an
250
+ * update (and a rebuild of the emotion cache) on the children it moved.
251
+ */
252
+ _dom_reinserted() {
253
+ const sheet = this._dom_sentinel?.sheet;
254
+ return sheet == null || sheet.cssRules.length === 0;
255
+ }
256
+ _mark_dom() {
257
+ let sentinel = this._dom_sentinel;
258
+ if (sentinel == null || sentinel.parentNode !== this.shadow_el) {
259
+ sentinel = document.createElement("style");
260
+ this.shadow_el.append(sentinel);
261
+ this._dom_sentinel = sentinel;
234
262
  }
263
+ sentinel.sheet?.insertRule(":host {}");
235
264
  }
236
265
  _update_layout() {
237
266
  super._update_layout();
@@ -262,22 +291,7 @@ export class ReactComponentView extends ReactiveESMView {
262
291
  }
263
292
  async _update_children_pass() {
264
293
  const created_children = new Set(await this.build_child_views());
265
- const new_views = new Map();
266
- for (const child_view of this.child_views) {
267
- if (!created_children.has(child_view)) {
268
- continue;
269
- }
270
- const child = this._lookup_child(child_view);
271
- if (!child) {
272
- continue;
273
- }
274
- if (new_views.has(child)) {
275
- new_views.get(child).push(child_view);
276
- }
277
- else {
278
- new_views.set(child, [child_view]);
279
- }
280
- }
294
+ const new_views = this._group_new_views(created_children);
281
295
  for (const child of this.model.children) {
282
296
  const callbacks = this._child_callbacks.get(child) || [];
283
297
  const new_children = new_views.get(child) || [];
@@ -341,366 +355,454 @@ export class ReactComponentView extends ReactiveESMView {
341
355
  this.finish();
342
356
  }
343
357
  }
344
- export class ReactComponent extends ReactiveESM {
345
- sucrase_transforms = ["typescript", "jsx"];
346
- constructor(attrs) {
347
- super(attrs);
358
+ const REACT_PACKAGES = ["react", "react-dom/client", "@emotion/cache", "@emotion/react"];
359
+ function react_libs_code(mui) {
360
+ if (mui) {
361
+ return `
362
+ import * as React from "react"
363
+ import { createRoot } from "react-dom/client"
364
+ import createCache from "@emotion/cache"
365
+ import { CacheProvider } from "@emotion/react"
366
+ export default {React, createRoot, createCache, CacheProvider}`;
348
367
  }
349
- get usesMui() {
350
- if (this.importmap?.imports) {
351
- return Object.keys(this.importmap?.imports).some(k => k.startsWith("@mui"));
368
+ return `
369
+ import * as React from "react"
370
+ import { createRoot } from "react-dom/client"
371
+ export default {React, createRoot}`;
372
+ }
373
+ // Keyed by React so each React instance (one per bundle) gets its own
374
+ // classes, defined once rather than per render: a component type that is new
375
+ // on every render makes React remount the subtree and drop its state.
376
+ const REACT_WRAPPERS = new WeakMap();
377
+ // A Component element is keyed by its view, so a view that replaces another
378
+ // in the same slot remounts instead of inheriting the old view's hook state.
379
+ const VIEW_KEYS = new WeakMap();
380
+ let view_key_counter = 0;
381
+ function view_key(view) {
382
+ let key = VIEW_KEYS.get(view);
383
+ if (key === undefined) {
384
+ key = view_key_counter++;
385
+ VIEW_KEYS.set(view, key);
386
+ }
387
+ return key;
388
+ }
389
+ // One emotion key for every component: class names only have to be unique
390
+ // within a shadow root, and a shared key makes the compiled CSS of a style
391
+ // identical across components, so it can be compiled once and replayed.
392
+ const EMOTION_KEY = "pnl";
393
+ // Compiled rules by selector and style hash, per emotion instance.
394
+ const EMOTION_RULES = new WeakMap();
395
+ /**
396
+ * Wraps an emotion cache so that each style is compiled by stylis once per
397
+ * page and its rules replayed into the other components' sheets. Each
398
+ * component still gets its own rules in its own shadow root, so the cascade
399
+ * is unchanged.
400
+ */
401
+ function share_emotion_rules(cache, createCache) {
402
+ let compiled = EMOTION_RULES.get(createCache);
403
+ if (compiled == null) {
404
+ compiled = new Map();
405
+ EMOTION_RULES.set(createCache, compiled);
406
+ }
407
+ const rules_cache = compiled;
408
+ const insert = cache.insert;
409
+ cache.insert = (selector, serialized, sheet, should_cache) => {
410
+ const key = `${selector}\u0000${serialized.name}`;
411
+ const rules = rules_cache.get(key);
412
+ if (rules == null) {
413
+ const recorded = [];
414
+ insert(selector, serialized, { insert: (rule) => { recorded.push(rule); sheet.insert(rule); } }, should_cache);
415
+ rules_cache.set(key, recorded);
416
+ return;
352
417
  }
353
- return false;
354
- }
355
- _render_code() {
356
- let [import_code, bundle_code] = ["", ""];
357
- const cache_key = (this.bundle === "url") ? this.esm : (this.bundle || `${this.class_name}-${this.esm.length}`);
358
- if (this.bundle) {
359
- bundle_code = `
360
- const ns = await view._module_cache.get("${cache_key}")
361
- const {React, createRoot} = ns.default`;
418
+ for (const rule of rules) {
419
+ sheet.insert(rule);
362
420
  }
363
- else {
364
- import_code = `
365
- import * as React from "react"
366
- import { createRoot } from "react-dom/client"`;
421
+ if (should_cache) {
422
+ cache.inserted[serialized.name] = true;
367
423
  }
368
- let init_code = "";
369
- let render_code = "";
370
- if (this.usesMui) {
371
- if (this.bundle) {
372
- bundle_code = `
373
- const ns = await view._module_cache.get("${cache_key}")
374
- const {CacheProvider, React, createCache, createRoot} = ns.default`;
424
+ };
425
+ return cache;
426
+ }
427
+ function react_wrappers(libs) {
428
+ const cached = REACT_WRAPPERS.get(libs.React);
429
+ if (cached != null) {
430
+ return cached;
431
+ }
432
+ const { React } = libs;
433
+ class Child extends React.PureComponent {
434
+ render_callback = null;
435
+ containerRef = React.createRef();
436
+ constructor(props) {
437
+ super(props);
438
+ this.state = { rendered: null };
439
+ // Registers the child as tracked but not yet rendered. React's render
440
+ // phase has to stay free of side effects, since a render may be
441
+ // discarded without ever committing, so the flag is only ever flipped
442
+ // here and from getSnapshotBeforeUpdate.
443
+ this._mark_stale();
444
+ }
445
+ _mark_stale() {
446
+ const view = this.view;
447
+ if (view) {
448
+ this.props.parent._child_rendered.set(view, false);
449
+ }
450
+ }
451
+ updateElement() {
452
+ const el = this.view?.el;
453
+ if (el && this.containerRef.current && !this.containerRef.current.contains(el)) {
454
+ this.containerRef.current.innerHTML = "";
455
+ this.containerRef.current.appendChild(el);
456
+ }
457
+ }
458
+ get view() {
459
+ const model = this.props.model ?? this.props.parent.model.data[this.props.name];
460
+ return this.props.parent.get_child_view(model);
461
+ }
462
+ get element() {
463
+ const view = this.view;
464
+ return view == null ? null : view.el;
465
+ }
466
+ get use_shadow_dom() {
467
+ return this.view?.model.use_shadow_dom || (this.view?.react_root === undefined);
468
+ }
469
+ _render_nested(view, flush) {
470
+ view.patch_container(this.containerRef.current);
471
+ const apply = (mod) => {
472
+ if (view.is_destroyed) {
473
+ return;
474
+ }
475
+ if (flush) {
476
+ this.props.parent.flush_scheduled_removals();
477
+ }
478
+ this.setState({ rendered: mod.default.render(view) }, () => {
479
+ if (view.is_destroyed) {
480
+ return;
481
+ }
482
+ this.props.parent.notify_mount(this.props.name, view.model.id);
483
+ view.r_after_render();
484
+ view.after_rendered();
485
+ });
486
+ };
487
+ // Rendering synchronously once the module is loaded lets a nested tree
488
+ // mount in one commit instead of one commit per level.
489
+ const mod = view.model.resolved_render_module;
490
+ if (mod != null) {
491
+ apply(mod);
375
492
  }
376
493
  else {
377
- import_code = `
378
- ${import_code}
379
- import createCache from "@emotion/cache"
380
- import { CacheProvider } from "@emotion/react"`;
381
- }
382
- init_code = `
383
- if (view.use_shadow_dom) {
384
- const css_key = id.replace("-", "").replace(/\d/g, (digit) => String.fromCharCode(digit.charCodeAt(0) + 49)).toLowerCase()
385
- view.mui_cache = createCache({
386
- key: 'css-'+css_key,
387
- prepend: true,
388
- container: view.style_cache,
389
- })
390
- }`;
391
- render_code = `
392
- if (rendered && ((view.parent?.react_root === undefined) || view.model.use_shadow_dom)) {
393
- rendered = React.createElement(CacheProvider, {value: view.mui_cache}, rendered)
394
- }`;
494
+ view.model.render_module.then(apply);
495
+ }
496
+ }
497
+ componentDidMount() {
498
+ const view = this.view;
499
+ this.render_callback = (new_views) => {
500
+ const view = this.view;
501
+ if (!view || !new_views.includes(view)) {
502
+ return;
503
+ }
504
+ this.updateElement();
505
+ if (this.use_shadow_dom) {
506
+ this.props.parent.flush_scheduled_removals();
507
+ this.props.parent.render_child(view);
508
+ this.props.parent._child_rendered.set(view, true);
509
+ }
510
+ else {
511
+ this._render_nested(view, true);
512
+ }
513
+ };
514
+ this.props.parent.on_child_render(this.props.name, this.render_callback);
515
+ if (view == null) {
516
+ return;
517
+ }
518
+ this.props.parent.flush_scheduled_removals();
519
+ if (this.use_shadow_dom) {
520
+ this.updateElement();
521
+ this.props.parent.render_child(view);
522
+ this.props.parent._child_rendered.set(view, true);
523
+ this.props.parent.notify_mount(this.props.name, view.model.id);
524
+ }
525
+ else {
526
+ this._render_nested(view, false);
527
+ }
528
+ }
529
+ componentWillUnmount() {
530
+ if (this.render_callback) {
531
+ this.props.parent.remove_on_child_render(this.props.name, this.render_callback);
532
+ }
533
+ // The mount bookkeeping lives on the parent, and the view may already be
534
+ // gone by the time React unmounts us, so fall back to the model id prop.
535
+ const id = this.view?.model.id ?? this.props.id;
536
+ if (id != null) {
537
+ this.props.parent.notify_mount(this.props.name, id, true);
538
+ }
539
+ }
540
+ getSnapshotBeforeUpdate() {
541
+ // Commit-phase equivalent of the constructor's registration: the view
542
+ // this Child renders may have been swapped out, so the incoming one is
543
+ // registered as stale here rather than during render.
544
+ this._mark_stale();
545
+ return null;
546
+ }
547
+ componentDidUpdate() {
548
+ if (this.use_shadow_dom) {
549
+ this.updateElement();
550
+ }
551
+ }
552
+ render() {
553
+ const class_name = this.use_shadow_dom ? "child-wrapper" : css_class_name(this.view.model.class_name);
554
+ return React.createElement("div", { id: this.view?.model.id, className: class_name, ref: this.containerRef }, this.state.rendered);
395
555
  }
396
- return `
397
- ${import_code}
398
-
399
- async function render(id) {
400
- const view = Bokeh.index.find_one_by_id(id)
401
- if (view == null) {
402
- return null
403
- }
404
-
405
- ${bundle_code}
406
-
407
- class Child extends React.PureComponent {
408
-
409
- state = {rendered: null}
410
-
411
- constructor(props) {
412
- super(props)
413
- this.render_callback = null
414
- this.containerRef = React.createRef()
415
- // Registers the child as tracked but not yet rendered. React's render
416
- // phase has to stay free of side effects, since a render may be
417
- // discarded without ever committing, so the flag is only ever flipped
418
- // here and from getSnapshotBeforeUpdate.
419
- this._mark_stale()
420
- }
421
-
422
- _mark_stale() {
423
- const view = this.view
424
- if (view) {
425
- this.props.parent._child_rendered.set(view, false)
426
- }
427
- }
428
-
429
- updateElement() {
430
- const childView = this.view
431
- const el = childView?.el
432
- if (el && this.containerRef.current && !this.containerRef.current.contains(el)) {
433
- this.containerRef.current.innerHTML = ""
434
- this.containerRef.current.appendChild(el)
435
- }
436
- }
437
-
438
- get view() {
439
- const child = this.props.parent.model.data[this.props.name]
440
- const model = this.props.id == null ? child : child.find(item => item.id === this.props.id)
441
- return this.props.parent.get_child_view(model)
442
- }
443
-
444
- get element() {
445
- const view = this.view
446
- return view == null ? null : view.el
447
- }
448
-
449
- get use_shadow_dom() {
450
- return this.view?.model.use_shadow_dom || (this.view?.react_root === undefined)
451
- }
452
-
453
- componentDidMount() {
454
- const view = this.view
455
- this.render_callback = (new_views) => {
456
- const view = this.view
457
- if (!view || !new_views.includes(view)) {
458
- return
459
- }
460
- this.updateElement()
461
- if (this.use_shadow_dom) {
462
- this.props.parent.flush_scheduled_removals()
463
- this.props.parent.rerender_(view)
464
- this.props.parent._child_rendered.set(view, true)
465
- } else {
466
- view.patch_container(this.containerRef.current)
467
- view.model.render_module.then(async (mod) => {
468
- this.props.parent.flush_scheduled_removals()
469
- this.setState(
470
- {rendered: await mod.default.render(view.model.id)},
471
- () => {
472
- this.props.parent.notify_mount(this.props.name, view.model.id)
473
- this.view.r_after_render()
474
- this.view.after_rendered()
475
- }
476
- )
477
- })
478
- }
479
- }
480
- this.props.parent.on_child_render(this.props.name, this.render_callback)
481
- if (view == null) { return }
482
- this.props.parent.flush_scheduled_removals()
483
- if (this.use_shadow_dom) {
484
- this.updateElement()
485
- this.props.parent.rerender_(view)
486
- this.props.parent._child_rendered.set(view, true)
487
- this.props.parent.notify_mount(this.props.name, view.model.id)
488
- } else {
489
- view.patch_container(this.containerRef.current)
490
- view.model.render_module.then(async (mod) => {
491
- this.setState(
492
- {rendered: await mod.default.render(view.model.id)},
493
- () => {
494
- this.props.parent.notify_mount(this.props.name, view.model.id)
495
- this.view.r_after_render()
496
- this.view.after_rendered()
497
- }
498
- )
499
- })
500
- }
501
- }
502
-
503
- componentWillUnmount() {
504
- if (this.render_callback) {
505
- this.props.parent.remove_on_child_render(this.props.name, this.render_callback)
506
- }
507
- // The mount bookkeeping lives on the parent, and the view may already be
508
- // gone by the time React unmounts us, so fall back to the model id prop.
509
- const id = this.view?.model.id ?? this.props.id
510
- if (id != null) {
511
- this.props.parent.notify_mount(this.props.name, id, true)
512
- }
513
- }
514
-
515
- getSnapshotBeforeUpdate() {
516
- // Commit-phase equivalent of the constructor's registration: the view
517
- // this Child renders may have been swapped out, so the incoming one is
518
- // registered as stale here rather than during render.
519
- this._mark_stale()
520
- return null
521
556
  }
522
-
523
- componentDidUpdate() {
524
- if (this.use_shadow_dom) {
525
- this.updateElement()
526
- }
557
+ class ErrorBoundary extends React.Component {
558
+ constructor(props) {
559
+ super(props);
560
+ this.state = { hasError: false };
561
+ }
562
+ static getDerivedStateFromError() {
563
+ return { hasError: true };
564
+ }
565
+ componentDidCatch(error) {
566
+ this.props.view.render_error(error);
567
+ }
568
+ render() {
569
+ if (this.state.hasError) {
570
+ return React.createElement("div");
571
+ }
572
+ return React.createElement("div", { className: "error-wrapper" }, this.props.children);
573
+ }
527
574
  }
528
-
529
- render() {
530
- const child = this.state.rendered
531
- const class_name = (this.use_shadow_dom ?
532
- "child-wrapper" : this.view.model.class_name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()
533
- )
534
- return React.createElement('div', {id: this.view?.model.id, className: class_name, ref: this.containerRef}, child)
575
+ const wrappers = {
576
+ Child,
577
+ ErrorBoundary,
578
+ Component: define_component(React, ErrorBoundary, null, null),
579
+ emotion_components: new WeakMap(),
580
+ };
581
+ REACT_WRAPPERS.set(React, wrappers);
582
+ return wrappers;
583
+ }
584
+ /**
585
+ * Returns the Component type for a view. Non-bundled components with and
586
+ * without MUI share one React instance from the same import map URL but load
587
+ * different libs, so emotion is chosen per view rather than per React.
588
+ */
589
+ function component_type(view, libs) {
590
+ const wrappers = react_wrappers(libs);
591
+ const { createCache, CacheProvider } = libs;
592
+ if (!view.model.usesMui || createCache == null || CacheProvider == null) {
593
+ return wrappers.Component;
594
+ }
595
+ let Component = wrappers.emotion_components.get(createCache);
596
+ if (Component == null) {
597
+ Component = define_component(libs.React, wrappers.ErrorBoundary, createCache, CacheProvider);
598
+ wrappers.emotion_components.set(createCache, Component);
599
+ }
600
+ return Component;
601
+ }
602
+ function define_component(React, ErrorBoundary, createCache, CacheProvider) {
603
+ return class Component extends React.Component {
604
+ constructor(props) {
605
+ super(props);
606
+ this._init_cache();
607
+ }
608
+ _init_cache() {
609
+ const { view } = this.props;
610
+ if (createCache != null && view.use_shadow_dom) {
611
+ view.mui_cache = share_emotion_rules(createCache({
612
+ key: EMOTION_KEY,
613
+ prepend: true,
614
+ container: view.style_cache,
615
+ }), createCache);
616
+ }
617
+ }
618
+ componentDidMount() {
619
+ const { view } = this.props;
620
+ if (!view.use_shadow_dom) {
621
+ return;
622
+ }
623
+ view.on_force_update(() => {
624
+ this._init_cache();
625
+ this.forceUpdate();
626
+ });
627
+ view.after_rendered();
628
+ }
629
+ render() {
630
+ const { view } = this.props;
631
+ let rendered = React.createElement(view.render_fn, this.props);
632
+ if (view.model.dev) {
633
+ rendered = React.createElement(ErrorBoundary, { view }, rendered);
634
+ }
635
+ if (CacheProvider != null && rendered && (view.parent?.react_root === undefined || view.model.use_shadow_dom)) {
636
+ rendered = React.createElement(CacheProvider, { value: view.mui_cache }, rendered);
637
+ }
638
+ return rendered;
639
+ }
640
+ };
641
+ }
642
+ function css_class_name(class_name) {
643
+ return class_name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
644
+ }
645
+ function react_model_proxy(view, libs, Child) {
646
+ const { React } = libs;
647
+ const react_proxy = new Proxy(view, {
648
+ get(target, name) {
649
+ if (name === "useMount") {
650
+ return (callback) => React.useEffect(() => {
651
+ target.model_proxy.on("lifecycle:mounted", callback);
652
+ return () => target.model_proxy.off("lifecycle:mounted", callback);
653
+ }, []);
654
+ }
655
+ else if (name === "useState") {
656
+ return (prop) => {
657
+ const path = prop.split(".");
658
+ let model = target.model.data;
659
+ for (let i = 0; i < path.length - 1; i++) {
660
+ if (model && model.properties && path[i] in model.properties) {
661
+ model = model[path[i]];
662
+ }
663
+ else {
664
+ model = null;
665
+ break;
666
+ }
667
+ }
668
+ const attr = path[path.length - 1];
669
+ if (model == null || model.attributes == null || !(attr in model.attributes)) {
670
+ throw ReferenceError(`Could not resolve ${prop} on ${target.model.class_name}`);
671
+ }
672
+ const [value, setValue] = React.useState(model.attributes[attr]);
673
+ React.useEffect(() => {
674
+ const cb = () => {
675
+ if (target.model.events.includes(attr)) {
676
+ model.attributes[attr] && (setValue((v) => v + 1) || model.setv({ [attr]: false }));
677
+ }
678
+ else {
679
+ setValue(model.attributes[attr]);
680
+ }
681
+ };
682
+ react_proxy.on(prop, cb, true);
683
+ return () => react_proxy.off(prop, cb);
684
+ }, []);
685
+ const initialized = React.useRef(false);
686
+ React.useEffect(() => {
687
+ if (!target.model.events.includes(attr) && initialized.current) {
688
+ model.setv({ [attr]: value });
689
+ }
690
+ else {
691
+ initialized.current = true;
692
+ }
693
+ }, [value]);
694
+ return [value, setValue];
695
+ };
696
+ }
697
+ else if (name === "get_child") {
698
+ return (child) => {
699
+ const data_model = target.model.data;
700
+ const value = data_model.attributes[child];
701
+ if (!isArray(value)) {
702
+ return React.createElement(Child, { parent: target, name: child });
703
+ }
704
+ const [children_state, set_children] = React.useState(() => value.map((model) => React.createElement(Child, { parent: target, name: child, key: model.id, id: model.id, model })));
705
+ React.useEffect(() => {
706
+ // Compares against the latest state, not the closure's initial
707
+ // one, and catches lists that only shrank.
708
+ const cb = () => {
709
+ const current_models = data_model.attributes[child];
710
+ set_children((previous) => {
711
+ if (previous.length === current_models.length &&
712
+ current_models.every((model, i) => model.id === previous[i].props.id)) {
713
+ return previous;
714
+ }
715
+ return current_models.map((model) => (React.createElement(Child, { parent: target, name: child, key: model.id, id: model.id, model })));
716
+ });
717
+ };
718
+ target.on_child_render(child, cb);
719
+ return () => target.remove_on_child_render(child, cb);
720
+ }, []);
721
+ return children_state;
722
+ };
723
+ }
724
+ return model_getter(target, name);
725
+ },
726
+ set: model_setter,
727
+ });
728
+ return react_proxy;
729
+ }
730
+ /**
731
+ * Renders a view into a new React root, or, for a view nested in a parent
732
+ * React tree without its own shadow root, returns the element for the parent
733
+ * to render.
734
+ */
735
+ function render_react(view, libs) {
736
+ if (view.is_destroyed) {
737
+ return null;
738
+ }
739
+ const { React, createRoot } = libs;
740
+ const { Child } = react_wrappers(libs);
741
+ const Component = component_type(view, libs);
742
+ const props = { view, model: react_model_proxy(view, libs, Child), data: view.model.data, el: view.container };
743
+ const rendered = React.createElement(Component, { ...props, key: view_key(view) });
744
+ if (!view.model.use_shadow_dom && (view.parent?.react_root !== undefined)) {
745
+ return rendered;
746
+ }
747
+ let container;
748
+ if (view.model.root_node) {
749
+ container = document.querySelector(view.model.root_node);
750
+ if (container == null) {
751
+ container = document.createElement("div");
752
+ container.id = view.model.root_node.replace("#", "");
753
+ document.body.append(container);
754
+ }
535
755
  }
536
- }
537
-
538
- function react_getter(target, name) {
539
- if (name === "useMount") {
540
- return (callback) => React.useEffect(() => {
541
- target.model_proxy.on('lifecycle:mounted', callback)
542
- return () => target.model_proxy.off('lifecycle:mounted', callback)
543
- }, [])
544
- } if (name == "useState") {
545
- return (prop) => {
546
- const data_model = target.model.data
547
- const propPath = prop.split(".")
548
- let targetModel = data_model
549
- let resolvedProp = null
550
-
551
- for (let i = 0; i < propPath.length - 1; i++) {
552
- if (targetModel && targetModel.properties && propPath[i] in targetModel.properties) {
553
- targetModel = targetModel[propPath[i]]
554
- } else {
555
- // Stop if any part of the path is missing
556
- targetModel = null
557
- break
558
- }
559
- }
560
- if (targetModel && targetModel.attributes && propPath[propPath.length - 1] in targetModel.attributes) {
561
- resolvedProp = propPath[propPath.length - 1]
562
- }
563
- if (resolvedProp && targetModel) {
564
- const [value, setValue] = React.useState(targetModel.attributes[resolvedProp])
565
-
566
- React.useEffect(() => {
567
- const cb = () => {
568
- if (target.model.events.includes(resolvedProp)) {
569
- targetModel.attributes[resolvedProp] && (setValue((v) => v+1) || targetModel.setv({[resolvedProp]: false}))
570
- } else {
571
- setValue(targetModel.attributes[resolvedProp])
572
- }
573
- }
574
- react_proxy.on(prop, cb, true)
575
- return () => react_proxy.off(prop, cb)
576
- }, [])
577
-
578
- let initialized = React.useRef(false)
579
- React.useEffect(() => {
580
- if (!target.model.events.includes(resolvedProp) && initialized.current) {
581
- targetModel.setv({ [resolvedProp]: value })
582
- } else { initialized.current = true }
583
- }, [value])
584
-
585
- return [value, setValue]
586
- }
587
- throw ReferenceError("Could not resolve " + prop + " on " + target.model.class_name)
588
- }
589
- } else if (name === "get_child") {
590
- return (child) => {
591
- const data_model = target.model.data
592
- const value = data_model.attributes[child]
593
- if (Array.isArray(value)) {
594
- const [children_state, set_children] = React.useState(value.map((model) =>
595
- React.createElement(Child, { parent: target, name: child, key: model.id, id: model.id })
596
- ))
597
- React.useEffect(() => {
598
- target.on_child_render(child, () => {
599
- const current_models = data_model.attributes[child]
600
- const previous_models = children_state.map(child => child.props.id)
601
- if (current_models.some((model, i) => model.id !== previous_models[i])) {
602
- set_children(current_models.map((model, i) => (
603
- React.createElement(Child, { parent: target, name: child, key: model.id, id: model.id })
604
- )))
605
- }
606
- })
607
- }, [])
608
- return children_state
609
- } else {
610
- return React.createElement(Child, {parent: target, name: child})
611
- }
612
- }
613
- }
614
- return target.model_getter(target, name)
615
- }
616
-
617
- const react_proxy = new Proxy(view, {
618
- get: react_getter,
619
- set: view.model_setter
620
- })
621
-
622
- class ErrorBoundary extends React.Component {
623
- constructor(props) {
624
- super(props)
625
- // initialize the error state
626
- this.state = { hasError: false }
756
+ else if (view.container == null) {
757
+ view._resolve_mounted();
758
+ return null;
627
759
  }
628
-
629
- // if an error happened, set the state to true
630
- static getDerivedStateFromError(error) {
631
- return { hasError: true }
760
+ else {
761
+ container = view.container;
632
762
  }
633
-
634
- componentDidCatch(error) {
635
- this.props.view.render_error(error)
763
+ const root = createRoot(container);
764
+ try {
765
+ root.render(rendered);
636
766
  }
637
-
638
- render() {
639
- if (this.state.hasError) {
640
- return React.createElement('div')
641
- }
642
- return React.createElement('div', {className: "error-wrapper"}, this.props.children)
767
+ catch (e) {
768
+ view._resolve_mounted();
769
+ view.render_error(e);
643
770
  }
644
- }
645
-
646
- class Component extends React.Component {
647
-
648
- constructor(props) {
649
- super(props)
650
- ${init_code}
771
+ return root;
772
+ }
773
+ export class ReactComponent extends ReactiveESM {
774
+ sucrase_transforms = ["typescript", "jsx"];
775
+ constructor(attrs) {
776
+ super(attrs);
651
777
  }
652
-
653
- componentDidMount() {
654
- if (!this.props.view.use_shadow_dom) { return }
655
- this.props.view.on_force_update(() => {
656
- ${init_code}
657
- this.forceUpdate()
658
- })
659
- this.props.view.after_rendered()
778
+ get usesMui() {
779
+ if (this.importmap?.imports) {
780
+ return Object.keys(this.importmap?.imports).some(k => k.startsWith("@mui"));
781
+ }
782
+ return false;
660
783
  }
661
-
662
- render() {
663
- let rendered = React.createElement(this.props.view.render_fn, this.props)
664
- if (this.props.view.model.dev) {
665
- rendered = React.createElement(ErrorBoundary, {view}, rendered)
666
- }
667
- ${render_code}
668
- return rendered
669
- }
670
- }
671
-
672
- const props = {view, model: react_proxy, data: view.model.data, el: view.container}
673
- const rendered = React.createElement(Component, props)
674
- if (!view.model.use_shadow_dom && (view.parent?.react_root !== undefined)) {
675
- return rendered
676
- }
677
- if (rendered) {
678
- let container
679
- if (view.model.root_node) {
680
- container = document.querySelector(view.model.root_node)
681
- if (container == null) {
682
- container = document.createElement("div")
683
- container.id = view.model.root_node.replace("#", "")
684
- document.body.append(container)
685
- }
686
- } else if (view.container == null) {
687
- view._resolve_mounted()
688
- return null
689
- } else {
690
- container = view.container
691
- }
692
- const root = createRoot(container)
693
- try {
694
- root.render(rendered)
695
- } catch(e) {
696
- view._resolve_mounted()
697
- view.render_error(e)
784
+ get _render_cache_key() {
785
+ if (this.bundle) {
786
+ return `react-${this.usesMui}-${this._module_cache_key}`;
787
+ }
788
+ // Non-bundled components share one render module per set of React
789
+ // packages, which the import map decides.
790
+ const imports = this.importmap?.imports ?? {};
791
+ const packages = REACT_PACKAGES.map((name) => imports[name] ?? "").join("|");
792
+ return `react-${this.usesMui}-${packages}`;
698
793
  }
699
- return root
700
- }
701
- }
702
-
703
- export default {render}`;
794
+ _render_module() {
795
+ return this._cached_module(this._render_cache_key, async () => {
796
+ let libs;
797
+ if (this.bundle) {
798
+ const ns = await this._cached_module(this._module_cache_key, () => Promise.resolve(null));
799
+ libs = ns.default;
800
+ }
801
+ else {
802
+ libs = (await this._import_source(react_libs_code(this.usesMui))).default;
803
+ }
804
+ return { default: { render: (view) => render_react(view, libs) } };
805
+ });
704
806
  }
705
807
  compile() {
706
808
  const compiled = super.compile();
@@ -715,10 +817,6 @@ import * as React from "react"
715
817
 
716
818
  ${compiled}`;
717
819
  }
718
- get _render_cache_key() {
719
- const cache_key = (this.bundle === "url") ? this.esm : (this.bundle || `${this.class_name}-${this.esm.length}`);
720
- return `react-${this.usesMui}-${cache_key}`;
721
- }
722
820
  static __module__ = "panel.models.esm";
723
821
  static {
724
822
  this.prototype.default_view = ReactComponentView;