1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ Copyright (c) 2017, the Perspective Authors. ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃ This file is part of the Perspective library, distributed under the terms ┃
// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
#![allow(non_snake_case)]
use std::cell::RefCell;
use std::rc::Rc;
use futures::channel::oneshot::channel;
use futures::future::join_all;
use js_sys::{Array, JsString};
use perspective_client::config::ViewConfigUpdate;
use perspective_client::utils::PerspectiveResultExt;
use perspective_js::utils::global;
use perspective_js::{JsViewConfig, JsViewWindow, Table, View, apierror};
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_derive::try_from_js_option;
use wasm_bindgen_futures::JsFuture;
use web_sys::HtmlElement;
use yew::Callback;
use crate::components::viewer::{PerspectiveViewerMsg, PerspectiveViewerProps};
use crate::config::*;
use crate::custom_events::*;
use crate::js::*;
use crate::presentation::*;
use crate::queries::*;
use crate::root::Root;
use crate::session::{ResetOptions, TableLoadState};
use crate::tasks::*;
use crate::utils::*;
use crate::workspace::{Panel, PanelId, Workspace};
use crate::*;
#[wasm_bindgen]
extern "C" {
/// `load()` argument: a [`Client`], a (deprecated) [`Table`], or a
/// `Promise` resolving to either. Typed rather than `any` so callers get
/// completion; the `Table` forms remain runtime-deprecated.
#[wasm_bindgen(typescript_type = "Client | Table | Promise<Client | Table>")]
pub type JsClientLoad;
/// `eject()` argument dict (`{ client?: string }`).
#[wasm_bindgen(typescript_type = "ClientOptions")]
pub type JsClientOptions;
/// Panel-selector dict (`{ panel?: string }`) for the active/base
/// accessor methods.
#[wasm_bindgen(typescript_type = "PanelOptions")]
pub type JsPanelOptions;
/// `download`/`export`/`copy` options dict
/// (`{ method?: ExportMethod, panel?: string }`).
#[wasm_bindgen(typescript_type = "ExportOptions")]
pub type JsExportOptions;
/// `getTable` options dict (`{ wait?: boolean, panel?: string }`).
#[wasm_bindgen(typescript_type = "GetTableOptions")]
pub type JsGetTableOptions;
/// `getClient` options dict (`{ wait?: boolean, panel?: string }`).
#[wasm_bindgen(typescript_type = "GetClientOptions")]
pub type JsGetClientOptions;
/// `restoreWorkspace()` argument: a whole-element config update.
#[wasm_bindgen(typescript_type = "WorkspaceConfigUpdate")]
pub type JsWorkspaceConfigUpdate;
/// `saveWorkspace()` return: a whole-element config.
#[wasm_bindgen(typescript_type = "Promise<WorkspaceConfig>")]
pub type JsWorkspaceConfigPromise;
/// A `Promise<void>` return, used by the `restore` family (whose
/// `ApiFuture<()>` would otherwise erase to `Promise<any>`).
#[wasm_bindgen(typescript_type = "Promise<void>")]
pub type JsVoidPromise;
/// `save()` return: a single-panel config.
#[wasm_bindgen(typescript_type = "Promise<ViewerConfig>")]
pub type JsViewerConfigPromise;
}
#[derive(serde::Deserialize, Default)]
struct ResizeOptions {
dimensions: Option<ResizeDimensions>,
}
#[derive(serde::Deserialize, Clone, Copy)]
struct ResizeDimensions {
width: f64,
height: f64,
}
/// Leniently deserialize an optional JS options dict into a serde struct,
/// falling back to `Default` on absence or a malformed argument (matching the
/// `ResizeOptions` precedent — an options bag is a best-effort convenience,
/// not a hard-validated payload).
fn parse_options<T, U>(options: Option<T>) -> U
where
T: Into<JsValue>,
U: Default + for<'a> serde::Deserialize<'a>,
{
options
.and_then(|o| o.into_serde_ext().ok())
.unwrap_or_default()
}
/// The `<perspective-viewer>` custom element.
///
/// # JavaScript Examples
///
/// Create a new `<perspective-viewer>`:
///
/// ```javascript
/// const viewer = document.createElement("perspective-viewer");
/// window.body.appendChild(viewer);
/// ```
///
/// Complete example including loading and restoring the [`Table`]:
///
/// ```javascript
/// import perspective from "@perspective-dev/viewer";
/// import perspective from "@perspective-dev/client";
///
/// const viewer = document.createElement("perspective-viewer");
/// const worker = await perspective.worker();
///
/// await worker.table("x\n1", {name: "table_one"});
/// await viewer.load(worker);
/// await viewer.restore({table: "table_one"});
/// ```
#[derive(Clone)]
#[wasm_bindgen]
pub struct PerspectiveViewerElement {
pub(crate) presentation: Presentation,
pub(crate) workspace: Workspace,
pub(crate) elem: HtmlElement,
pub(crate) root: Root<components::viewer::PerspectiveViewer>,
resize_handle: Rc<RefCell<Option<ResizeObserverHandle>>>,
intersection_handle: Rc<RefCell<Option<AutoPauseHandle>>>,
hosted_table_subs: HostedTableSubs,
_subscriptions: Rc<[Subscription; 2]>,
_custom_event_subs: Rc<Vec<Subscription>>,
}
impl CustomElementMetadata for PerspectiveViewerElement {
const CUSTOM_ELEMENT_NAME: &'static str = "perspective-viewer";
const STATICS: &'static [&'static str] =
["registerPlugin", "get_wasm_module", "get_worker_url"].as_slice();
}
impl PerspectiveViewerElement {
fn layout_changed_notify(&self) -> Callback<()> {
let root = self.root.clone();
Callback::from(move |_: ()| {
if let Some(app) = root.borrow().as_ref() {
app.send_message(PerspectiveViewerMsg::LayoutChanged);
}
})
}
fn resolve_panel(&self, name: Option<String>) -> ApiResult<Panel> {
let id = name.map(PanelId::from);
self.workspace.panel_or_active(id.as_ref()).ok_or_else(|| {
format!(
"No panel named \"{}\"",
id.as_ref().map(PanelId::as_str).unwrap_or_default()
)
.into()
})
}
fn layout_element(&self) -> Option<RegularLayout> {
self.elem
.shadow_root()?
.query_selector(RegularLayout::TAG_NAME)
.ok()
.flatten()
.map(|el| el.unchecked_into())
}
async fn workspace_config(this: Self) -> ApiResult<JsValue> {
let mut panels: std::collections::BTreeMap<String, PanelViewerConfig> = Default::default();
for id in &this.workspace.panel_ids() {
let panel = this.workspace.panel(id).into_apierror()?;
let config = panel
.renderer
.clone()
.with_lock(async {
get_viewer_config(&panel.session, &panel.renderer, &this.presentation).await
})
.await?;
panels.insert(id.as_str().to_owned(), config.panel);
}
let active = this
.presentation
.is_settings_open()
.then(|| this.workspace.active_id())
.flatten()
.map(|id| id.as_str().to_owned());
let layout = this
.layout_element()
.map(|l| l.save().into_serde_ext::<crate::js::Layout>())
.transpose()?;
Ok(JsValue::from_serde_ext(&WorkspaceConfig {
version: API_VERSION.to_string(),
active,
layout,
panels,
global_filters: this.workspace.global_filters(),
masters: this
.workspace
.masters()
.iter()
.map(|id| id.as_str().to_owned())
.collect(),
})?)
}
}
fn eject_client_panels(
workspace: &Workspace,
root: &Root<crate::components::viewer::PerspectiveViewer>,
target: String,
ids: Vec<PanelId>,
) -> ApiFuture<()> {
clone!(workspace, root);
let effect = workspace.effects().guard();
ApiFuture::new_throttled(async move {
let _effect = effect;
for id in ids {
let (completion, receiver) = Completion::new();
root.borrow()
.as_ref()
.into_apierror()?
.send_message(PerspectiveViewerMsg::ClosePanel(
id.to_string(),
Some(completion),
));
receiver.await.map_err(|_| ApiError::new("Cancelled"))??;
}
workspace.remove_client(&target);
Ok(())
})
}
#[rustfmt::skip]
const DEPRECATED_TABLE_MESSAGE: &str =
"`load(table)` is deprecated - use `load(client)` followed by `restore({table: \"name\"})` instead";
#[wasm_bindgen]
impl PerspectiveViewerElement {
#[doc(hidden)]
#[wasm_bindgen(constructor)]
pub fn new(elem: web_sys::HtmlElement) -> Self {
let init = web_sys::ShadowRootInit::new(web_sys::ShadowRootMode::Open);
let shadow_root = elem
.attach_shadow(&init)
.unwrap()
.unchecked_into::<web_sys::Element>();
Self::new_from_shadow(elem, shadow_root)
}
fn new_from_shadow(elem: web_sys::HtmlElement, shadow_root: web_sys::Element) -> Self {
// Application State.
let presentation = Presentation::new(&elem);
// Boot with ZERO panels — an unconfigured element is a blank stage. The
// first `load`/`restore`/`addPanel` creates the first panel, which
// adopts the element's `theme` attribute when set (see
// `create_panel_model`'s authored-theme boot).
let workspace = Workspace::new();
let custom_event_subs = wire_element_events(&elem, &presentation, &workspace);
// Create Yew App
let props = yew::props!(PerspectiveViewerProps {
elem: elem.clone(),
presentation: presentation.clone(),
workspace: workspace.clone(),
});
let state = props.clone();
let root = Root::new(shadow_root, props);
// Create callbacks
let eject_sub = presentation.on_eject.add_listener({
let root = root.clone();
move |_| {
clone!(state.workspace, root);
ApiFuture::spawn(async move {
if let Some(target) = workspace.active_client().map(|c| c.get_name().to_owned())
{
let ids = workspace.panels_for_client(&target);
if ids.len() < workspace.panel_ids().len() {
return eject_client_panels(&workspace, &root, target, ids).await;
}
}
delete_all(&workspace, &root).await
})
}
});
let resize_handle = ResizeObserverHandle::new(&elem, &workspace, &presentation, &root);
let intersect_handle = AutoPauseHandle::new(&elem, &presentation, &workspace);
let (lifecycle_sub, hosted_table_subs) = wire_table_lifecycle(&workspace, &presentation);
Self {
elem,
root,
presentation,
workspace,
resize_handle: Rc::new(RefCell::new(Some(resize_handle))),
intersection_handle: Rc::new(RefCell::new(Some(intersect_handle))),
hosted_table_subs,
_subscriptions: Rc::new([eject_sub, lifecycle_sub]),
_custom_event_subs: Rc::new(custom_event_subs),
}
}
#[doc(hidden)]
#[wasm_bindgen(js_name = "connectedCallback")]
pub fn connected_callback(&self) -> ApiResult<()> {
tracing::debug!("Connected <perspective-viewer>");
Ok(())
}
/// Loads a [`Client`], or optionally [`Table`], or optionally a Javascript
/// `Promise` which returns a [`Client`] or [`Table`], in this viewer.
///
/// Loading a [`Client`] does not render, but subsequent calls to
/// [`PerspectiveViewerElement::restore`] will use this [`Client`] to look
/// up the proviced `table` name field for the provided
/// [`ViewerConfigUpdate`].
///
/// Loading a [`Table`] is equivalent to subsequently calling
/// [`Self::restore`] with the `table` field set to [`Table::get_name`], and
/// will render the UI in its default state when [`Self::load`] resolves.
/// If you plan to call [`Self::restore`] anyway, prefer passing a
/// [`Client`] argument to [`Self::load`] as it will conserve one render.
///
/// When [`PerspectiveViewerElement::load`] resolves, the first frame of the
/// UI + visualization is guaranteed to have been drawn. Awaiting the result
/// of this method in a `try`/`catch` block will capture any errors
/// thrown during the loading process, or from the [`Client`] `Promise`
/// itself.
///
/// [`PerspectiveViewerElement::load`] may also be called with a [`Table`],
/// which is equivalent to:
///
/// ```javascript
/// await viewer.load(await table.get_client());
/// await viewer.restore({name: await table.get_name()})
/// ```
///
/// If you plan to call [`PerspectiveViewerElement::restore`] immediately
/// after [`PerspectiveViewerElement::load`] yourself, as is commonly
/// done when loading and configuring a new `<perspective-viewer>`, you
/// should use a [`Client`] as an argument and set the `table` field in the
/// restore call as
///
/// A [`Table`] can be created using the
/// [`@perspective-dev/client`](https://www.npmjs.com/package/@perspective-dev/client)
/// library from NPM (see [`perspective_js`] documentation for details).
///
/// # JavaScript Examples
///
/// ```javascript
/// import perspective from "@perspective-dev/client";
///
/// const worker = await perspective.worker();
/// viewer.load(worker);
/// ```
///
/// ... or
///
/// ```javascript
/// const table = await worker.table(data, {name: "superstore"});
/// viewer.load(table);
/// ```
///
/// Complete example:
///
/// ```javascript
/// const viewer = document.createElement("perspective-viewer");
/// const worker = await perspective.worker();
///
/// await worker.table("x\n1", {name: "table_one"});
/// await viewer.load(worker);
/// await viewer.restore({table: "table_one", columns: ["x"]});
/// ```
///
/// ... or, if you don't want to pass your own arguments to `restore`:
///
/// ```javascript
/// const viewer = document.createElement("perspective-viewer");
/// const worker = await perspective.worker();
///
/// const table = await worker.table("x\n1", {name: "table_one"});
/// await viewer.load(table);
/// ```
pub fn load(&self, client: JsClientLoad) -> ApiResult<ApiFuture<()>> {
let effect = self.workspace.effects().guard();
let table: JsValue = client.into();
let promise = table
.clone()
.dyn_into::<js_sys::Promise>()
.unwrap_or_else(|_| js_sys::Promise::resolve(&table));
// Resolve the target panel. On an EMPTY element (zero panels):
// - a synchronously-detectable `Client` registers inertly with NO panel (the
// common `load(client)` — no phantom panel is left behind);
// - otherwise (a resolved `Table`, or a `Promise` whose type isn't yet known)
// the first panel is RESERVED synchronously here — a full panel model held
// in the workspace's reservation slot, NOT placed — so its ordering position
// is fixed at the call site: a `restore()` fired right after an unawaited
// `load()` CLAIMS the reservation (placing it) and targets THIS panel, not a
// second one. The reservation is likewise placed when the payload proves to
// be a `Table` (or the load fails, surfacing its error), and discarded —
// only while still unclaimed — for an inert `Client` payload. Placement and
// discard are both atomic slot transfers (`Workspace::claim_reserved` /
// `Workspace::take_reserved`), so an inert payload disposing a panel a
// racing `restore` claimed is unrepresentable.
// A pre-existing active panel is used as-is (a `Client` registers
// inertly against it, never clearing its table).
let (panel, notify) = match self.workspace.active_panel() {
Some(panel) => (panel, None),
None => {
// Empty element — classify the payload synchronously where possible.
if let Ok(Some(client)) =
try_from_js_option::<perspective_js::Client>(table.clone())
{
// A resolved `Client` registers SYNCHRONOUSLY (so an unawaited
// `load(client)` is visible to a `restore()` fired right after,
// which creates the first panel and federates against loaded
// clients) and creates NO panel — inert.
self.workspace
.set_default_client(client.get_client().clone());
return Ok(ApiFuture::new(async { Ok(()) }));
}
// A resolved `Table` (or a `Promise` whose type isn't yet known)
// adopts the pending reservation (a second `load()` on a
// still-empty element), else reserves a fresh panel model.
let panel = self.workspace.reserved_panel().unwrap_or_else(|| {
create_panel_model(
&self.elem,
&self.presentation,
&self.workspace,
None,
ViewerConfigUpdate::default(),
None,
Placement::Reserved,
);
self.workspace
.reserved_panel()
.expect("just-reserved panel is present")
});
// Carrying `Some(notify)` marks this load as the reservation's
// owner — the only call that may place or discard it below.
(panel, Some(self.layout_changed_notify()))
},
};
// A `Table` payload targets this panel's engines; a `Client` registers
// inertly against it. Selecting the panel here (not at construction)
// keeps the registry race safe — by `load()` time real plugins have
// registered.
let session = panel.session;
let renderer = panel.renderer;
// Open the pending-load window SYNCHRONOUSLY, at the call site — this
// is what fixes the ordering. The payload's RESET disposition (a
// `Table` resets the view; a `Client` does not) is unknown until the
// promise resolves, but the window's POSITION on the config-commit
// stream is fixed NOW. A `restore()` a caller fires immediately after
// this unawaited `load()` (the React prop-binding pattern, which has
// no async ordering guarantees) commits INTO this window's journal and
// is replayed over the reset base if the payload proves to be a
// `Table` — so a moved-async reset can no longer clobber a later
// commit. See `SESSION_CONFIG_COHERENCE_PLAN.md`.
let generation = session.begin_pending_load();
clone!(self.workspace, self.presentation);
Ok(ApiFuture::new_throttled(async move {
let _effect = effect;
renderer.set_throttle(None);
let _run_token = session.begin_config_run();
let result = {
clone!(session, renderer, workspace, notify);
renderer
.clone()
.render_task(|guard| async move {
renderer.set_default_theme(presentation.get_default_theme_name().await);
renderer.stamp_theme(None);
let jstable = JsFuture::from(promise)
.await
.map_err(|x| apierror!(TableError(x)))?;
if let Ok(Some(table)) =
try_from_js_option::<perspective_js::Table>(jstable.clone())
{
tracing::warn!("{}", DEPRECATED_TABLE_MESSAGE);
let Some(journal) = session.take_pending_load(generation) else {
return Ok(None);
};
if let Some(notify) = ¬ify {
place_reserved(&workspace, notify);
}
let _plugin = renderer.ensure_plugin_selected()?;
let _ = renderer.mount_active_plugin();
session
.reset(ResetOptions {
config: true,
expressions: true,
stats: true,
table: Some(session::TableIntermediateState::Reloaded),
})
.await
.unwrap_or_log();
let client = table.get_client().await;
let inner_client = client.get_client().clone();
session.set_client(inner_client.clone());
workspace.set_default_client(inner_client);
let name = table.get_name().await;
tracing::debug!(
"Loading {:.0} rows from `Table` {}",
table.size().await?,
name
);
session.set_table(name).await?;
for delta in journal {
session.commit_view_config(delta)?;
}
session.commit_table_defaults();
let (disposition, _pin) =
crate::tasks::bind_snapshot(&guard, &session, &renderer).await?;
crate::tasks::dispatch_bound(
&guard,
&renderer,
disposition,
false,
crate::tasks::RunOrigin::Public,
)
.await?;
Ok(None)
} else if let Ok(Some(client)) = wasm_bindgen_derive::try_from_js_option::<
perspective_js::Client,
>(jstable)
{
// INERT: register the client only — never rebind or
// reset the active panel (its table is preserved).
// Panels bind their client lazily at table-resolution
// time (`Workspace::resolve_client_for_table`). The
// window is discarded (not replayed): a `Client`
// performs no reset, and any racing `restore`'s
// commits already applied live (`commit_view_config`).
let owned_window = session.take_pending_load(generation).is_some();
let discard = if owned_window && notify.is_some() {
workspace.take_reserved()
} else {
None
};
workspace.set_default_client(client.get_client().clone());
Ok(discard)
} else {
session.take_pending_load(generation);
Err(ApiError::new("Invalid argument"))
}
})
.await
};
match result {
Err(e) => {
session.take_pending_load(generation);
if let Some(notify) = ¬ify {
place_reserved(&workspace, notify);
}
session.set_error(false, e.clone()).await?;
Err(e)
},
Ok(Some(panel)) => eject_panel(panel).await,
Ok(None) => Ok(()),
}
}))
}
/// Delete all internal [`View`]s and all associated state, rendering this
/// `<perspective-viewer>` unusable and freeing all associated resources.
/// Does not delete any supplied [`Table`] (as this is constructed by the
/// callee).
///
/// Calling _any_ method on a `<perspective-viewer>` after [`Self::delete`]
/// will throw.
///
/// <div class="warning">
///
/// Allowing a `<perspective-viewer>` to be garbage-collected
/// without calling [`PerspectiveViewerElement::delete`] will leak WASM
/// memory!
///
/// </div>
///
/// # JavaScript Examples
///
/// ```javascript
/// await viewer.delete();
/// ```
pub fn delete(self) -> ApiFuture<()> {
let subs = std::mem::take(&mut *self.hosted_table_subs.borrow_mut());
let teardown = delete_all(&self.workspace, &self.root);
ApiFuture::new(async move {
for (client, id) in subs {
let _ = client.remove_hosted_tables_update(id).await;
}
teardown.await
})
}
/// Remove a [`Client`] from this `<perspective-viewer>` and dispose every
/// panel bound to it (each panel's `View` is deleted and its `Table`
/// reference released).
///
/// # Arguments
///
/// - `options` - An optional `{client?: string}` dict naming the client to
/// eject; the active panel's client when omitted.
///
/// # JavaScript Examples
///
/// ```javascript
/// await viewer.eject();
/// await viewer.eject({client: "remote"});
/// ```
pub fn eject(&mut self, options: Option<JsClientOptions>) -> ApiFuture<()> {
let ClientOptions { client } = parse_options(options);
// Default target: the active panel's client, or — when the active panel
// is unbound (`load(Client)` is now inert) — the default client.
let Some(target) = client
.or_else(|| {
self.workspace
.active_client()
.map(|c| c.get_name().to_owned())
})
.or_else(|| {
self.workspace
.default_client()
.map(|c| c.get_name().to_owned())
})
else {
return ApiFuture::new_throttled(async move { Ok(()) });
};
let ids = self.workspace.panels_for_client(&target);
// The target client backs EVERY panel — reset the element to its
// pre-`load` state (dropping the client with it), as a `Workspace`
// must always keep at least one panel.
if !ids.is_empty() && ids.len() == self.workspace.panel_ids().len() {
let mut state = Self::new_from_shadow(
self.elem.clone(),
self.elem.shadow_root().unwrap().unchecked_into(),
);
std::mem::swap(self, &mut state);
return ApiFuture::new_throttled(state.delete());
}
eject_client_panels(&self.workspace, &self.root, target, ids)
}
/// Get the underlying [`View`] for this viewer.
///
/// Use this method to get promgrammatic access to the [`View`] as currently
/// configured by the user, for e.g. serializing as an
/// [Apache Arrow](https://arrow.apache.org/) before passing to another
/// library.
///
/// The [`View`] returned by this method is owned by the
/// [`PerspectiveViewerElement`] and may be _invalidated_ by
/// [`View::delete`] at any time. Plugins which rely on this [`View`] for
/// their [`HTMLPerspectiveViewerPluginElement::draw`] implementations
/// should treat this condition as a _cancellation_ by silently aborting on
/// "View already deleted" errors from method calls.
///
/// # JavaScript Examples
///
/// ```javascript
/// const view = await viewer.getView();
/// ```
#[wasm_bindgen]
pub fn getView(&self, options: Option<JsPanelOptions>) -> ApiFuture<View> {
let PanelOptions { panel: name } = parse_options(options);
let this = self.clone();
ApiFuture::new(async move {
let panel = this.resolve_panel(name)?;
Ok(panel.session.get_view().ok_or("No table set")?.into())
})
}
/// Get a copy of the [`ViewConfig`] for the current [`View`]. This is
/// non-blocking as it does not need to access the plugin (unlike
/// [`PerspectiveViewerElement::save`]), and also makes no API calls to the
/// server (unlike [`PerspectiveViewerElement::getView`] followed by
/// [`View::get_config`])
#[wasm_bindgen]
pub fn getViewConfig(&self, options: Option<JsPanelOptions>) -> ApiFuture<JsViewConfig> {
let PanelOptions { panel: name } = parse_options(options);
let this = self.clone();
ApiFuture::new(async move {
let panel = this.resolve_panel(name)?;
let config = if let Some(ctx) = panel.renderer.render_context() {
(*ctx.view_config).clone()
} else if let Some(rendered) = panel.session.get_rendered_view_config() {
(*rendered).clone()
} else {
panel.session.get_view_config().clone()
};
Ok(JsValue::from_serde_ext(&config)?.unchecked_into())
})
}
/// Get the underlying [`Table`] for this viewer (as passed to
/// [`PerspectiveViewerElement::load`] or as the `table` field to
/// [`PerspectiveViewerElement::restore`]).
///
/// # Arguments
///
/// - `wait_for_table` - whether to wait for
/// [`PerspectiveViewerElement::load`] to be called, or fail immediately
/// if [`PerspectiveViewerElement::load`] has not yet been called.
///
/// # JavaScript Examples
///
/// ```javascript
/// const table = await viewer.getTable();
/// ```
#[wasm_bindgen]
pub fn getTable(&self, options: Option<JsGetTableOptions>) -> ApiFuture<Table> {
let GetTableOptions {
wait: wait_for_table,
panel: name,
} = parse_options(options);
let this = self.clone();
ApiFuture::new(async move {
let panel = this.resolve_panel(name)?;
if !wait_for_table.unwrap_or_default()
&& let Some(ctx) = panel.renderer.render_context()
{
return Ok(ctx.table.clone().into());
}
let session = panel.session;
match session.get_table() {
Some(table) => Ok(table.into()),
None if !wait_for_table.unwrap_or_default() => Err("No `Table` set".into()),
None => {
session.table_loaded.read_next().await?;
Ok(session.get_table().ok_or("No `Table` set")?.into())
},
}
})
}
/// Get the underlying [`Client`] for this viewer (as passed to, or
/// associated with the [`Table`] passed to,
/// [`PerspectiveViewerElement::load`]).
///
/// # Arguments
///
/// - `wait_for_client` - whether to wait for
/// [`PerspectiveViewerElement::load`] to be called, or fail immediately
/// if [`PerspectiveViewerElement::load`] has not yet been called.
///
/// # JavaScript Examples
///
/// ```javascript
/// const client = await viewer.getClient();
/// ```
#[wasm_bindgen]
pub fn getClient(
&self,
options: Option<JsGetClientOptions>,
) -> ApiFuture<perspective_js::Client> {
let GetClientOptions {
wait: wait_for_client,
panel: name,
} = parse_options(options);
let this = self.clone();
ApiFuture::new(async move {
let panel = this.resolve_panel(name)?;
if !wait_for_client.unwrap_or_default()
&& let Some(ctx) = panel.renderer.render_context()
{
return Ok(ctx.client.clone().into());
}
let session = panel.session;
match session.get_client() {
Some(client) => Ok(client.into()),
None if !wait_for_client.unwrap_or_default() => Err("No `Client` set".into()),
None => {
session.table_loaded.read_next().await?;
Ok(session.get_client().ok_or("No `Client` set")?.into())
},
}
})
}
/// Get render statistics. Some fields of the returned stats object are
/// relative to the last time [`PerspectiveViewerElement::getRenderStats`]
/// was called, ergo calling this method resets these fields.
///
/// # JavaScript Examples
///
/// ```javascript
/// const {virtual_fps, actual_fps} = await viewer.getRenderStats();
/// ```
#[wasm_bindgen]
pub fn getRenderStats(&self, options: Option<JsPanelOptions>) -> ApiResult<JsValue> {
let PanelOptions { panel: name } = parse_options(options);
let panel = self.resolve_panel(name)?;
Ok(JsValue::from_serde_ext(
&panel.renderer.render_timer().get_stats(),
)?)
}
/// Flush any pending modifications to this `<perspective-viewer>`. Since
/// `<perspective-viewer>`'s API is almost entirely `async`, it may take
/// some milliseconds before any user-initiated changes to the [`View`]
/// affects the rendered element. If you want to make sure all pending
/// actions have been rendered, call and await [`Self::flush`].
///
/// [`Self::flush`] will resolve immediately if there is no [`Table`] set.
///
/// # JavaScript Examples
///
/// In this example, [`Self::restore`] is called without `await`, but the
/// eventual render which results from this call can still be awaited by
/// immediately awaiting [`Self::flush`] instead.
///
/// ```javascript
/// viewer.restore(config);
/// await viewer.flush();
/// ```
pub fn flush(&self) -> ApiFuture<()> {
let workspace = self.workspace.clone();
let presentation = self.presentation.clone();
ApiFuture::new_throttled(async move {
loop {
workspace.effects().settle().await;
let panels = workspace
.reserved_panel()
.into_iter()
.chain(workspace.panels())
.collect::<Vec<_>>();
let mut fulfilled = false;
for panel in &panels {
panel.renderer.clone().with_lock(async { Ok(()) }).await?;
panel.renderer.clone().with_lock(async { Ok(()) }).await?;
panel.session.settle_dispatches().await?;
if !global::document().hidden()
&& presentation.is_visible()
&& !panel.renderer.is_plugin_activated()?
&& panel.session.get_error().is_none()
&& matches!(panel.session.has_table(), Some(TableLoadState::Loaded))
{
set_panel_paused(&panel.session, &panel.renderer, &presentation, true)
.await?;
if !panel.renderer.is_plugin_activated()? {
just_render(&panel.session, &panel.renderer)?.await?;
}
fulfilled = true;
}
}
if !fulfilled && workspace.effects().is_empty() {
return Ok(());
}
}
})
}
/// Restore a single panel from a full/partial
/// [`perspective_js::JsViewConfig`] (its user-configurable state, including
/// the `Table` name) — the active panel, or a specific panel via the
/// optional `{panel}` selector.
///
/// If `panel` names no existing panel, a NEW panel is created with that id
/// and the config restored into it (an upsert), equivalent to
/// [`Self::addPanel`] but with a caller-chosen id. As with a created panel,
/// the element-level `settings`/`theme` fields are ignored in that case.
///
/// On an empty element with a pending [`Self::load`] whose payload is not
/// yet classified, the active-target form (no `panel`) instead claims and
/// restores into that load's reserved first panel — see [`Self::load`].
///
/// This restores a SINGLE panel; a whole-element config (with a `panels`
/// map) must be applied via [`Self::restoreWorkspace`] — its `panels` /
/// `layout` keys are ignored here.
///
/// One of the best ways to use [`Self::restore`] is by first configuring
/// a `<perspective-viewer>` as you wish, then using either the `Debug`
/// panel or "Copy" -> "config.json" from the toolbar menu to snapshot
/// the [`Self::restore`] argument as JSON.
///
/// # Arguments
///
/// - `update` - The config to restore to, as returned by [`Self::save`] in
/// either "json", "string" or "arraybuffer" format.
/// - `name` - The panel to target, or `None` for the active panel.
///
/// # JavaScript Examples
///
/// Loads a default plugin for the table named `"superstore"`:
///
/// ```javascript
/// await viewer.restore({table: "superstore"});
/// ```
///
/// Apply a `group_by` to the same `viewer` element, without
/// modifying/resetting other fields - you can omit the `table` field,
/// this has already been set once and is not modified:
///
/// ```javascript
/// await viewer.restore({group_by: ["State"]});
/// ```
pub fn restore(
&self,
update: JsViewerConfigUpdate,
options: Option<JsPanelOptions>,
) -> JsVoidPromise {
let PanelOptions { panel: name } = parse_options(options);
let effect = self.workspace.effects().guard();
let this = self.clone();
let fut = ApiFuture::new_throttled(async move {
let _effect = effect;
let id = name.map(PanelId::from);
let update = ViewerConfigUpdate::decode(&update)?;
match this.workspace.panel_or_active(id.as_ref()) {
// An existing (or the active) panel — update it in place.
Some(panel) => {
let active = this.workspace.active_id().as_ref() == Some(&panel.id);
restore_panel(
&panel.session,
&panel.renderer,
&this.presentation,
&this.workspace,
Some(&this.root),
RestoreMode::Existing { active },
update,
)
.await
},
// No existing panel matched. The active-target form
// (`panel: None`) CLAIMS a pending `load()`'s reserved panel
// — placing it and restoring into it — so a `restore` fired
// right after an unawaited `load(promise)` configures the
// panel that load's payload will bind, per the call-site
// ordering contract in [`Self::load`]. Named upserts and
// reservation-less elements create a fresh panel instead,
// routing through the shared `create_panel`
// (`RestoreMode::Fresh`) pipeline so the new panel's id is
// the requested `panel`.
None => {
let notify = this.layout_changed_notify();
let claimed = id
.is_none()
.then(|| place_reserved(&this.workspace, ¬ify))
.flatten();
match claimed {
Some(panel) => {
restore_panel(
&panel.session,
&panel.renderer,
&this.presentation,
&this.workspace,
Some(&this.root),
RestoreMode::Existing { active: true },
update,
)
.await
},
None => {
create_panel(
&this.elem,
&this.presentation,
&this.workspace,
¬ify,
id,
update,
None,
)
.await?;
Ok(())
},
}
},
}
});
js_sys::Promise::from(fut).unchecked_into()
}
/// Restore the ENTIRE element from a whole-element
/// [`WorkspaceConfigUpdate`] (`{version, active?, layout, panels, ...}`) —
/// the multi-panel counterpart of [`Self::restore`]. Every existing panel
/// is replaced by the `panels` entries, and the layout tree + master/detail
/// cross-filter state re-applied. Unlike [`Self::restore`], this never
/// falls back to the single-panel path.
///
/// # JavaScript Examples
///
/// ```javascript
/// await viewer.restoreWorkspace(await otherViewer.saveWorkspace());
/// ```
pub fn restoreWorkspace(&self, update: JsWorkspaceConfigUpdate) -> JsVoidPromise {
let update: JsViewerConfigUpdate = update.unchecked_into();
let effect = self.workspace.effects().guard();
let this = self.clone();
let fut = ApiFuture::new(async move {
let _effect = effect;
let (contents, eject_tasks) = sync_update_panels(&this, update)?;
let results = join_all(contents.into_iter().map(|(id, session, renderer, config)| {
let presentation = this.presentation.clone();
let workspace = this.workspace.clone();
async move {
stamp_global_overlay(&workspace, &id, &session);
restore_panel(
&session,
&renderer,
&presentation,
&workspace,
None,
RestoreMode::Fresh,
config,
)
.await?;
if workspace.is_master(&id) {
set_edit_mode(&session, &renderer, "SELECT_ROW_TREE");
}
Ok(())
}
}))
.await;
results.into_iter().collect::<ApiResult<Vec<_>>>()?;
join_all(eject_tasks)
.await
.into_iter()
.collect::<ApiResult<Vec<_>>>()?;
Ok(())
});
js_sys::Promise::from(fut).unchecked_into()
}
/// If this element is in an _errored_ state, this method will clear it and
/// re-render. Calling this method is equivalent to clicking the error reset
/// button in the UI.
pub fn resetError(&self) -> ApiFuture<()> {
let Some(panel) = self.workspace.active_panel() else {
return ApiFuture::new_throttled(async move { Ok(()) });
};
let reset_effect = self.workspace.effects().guard();
let reset_task = panel.session.reset(ResetOptions::default());
ApiFuture::spawn(async move {
let _effect = reset_effect;
reset_task.await
});
let effect = self.workspace.effects().guard();
ApiFuture::new_throttled(async move {
let _effect = effect;
apply_and_render(&panel.session, &panel.renderer, ViewConfigUpdate::default())?.await?;
Ok(())
})
}
/// Save a single panel's user-configurable state as a [`ViewerConfig`], one
/// which can be restored via [`Self::restore`] — the active panel, or a
/// specific panel via the optional `{panel}` selector.
///
/// This saves a SINGLE panel; to snapshot the ENTIRE element (every panel +
/// layout + cross-filters) use [`Self::saveWorkspace`].
///
/// # Arguments
///
/// - `options` - An optional `{panel?: string}`; the panel to save, or the
/// active panel when omitted.
///
/// # JavaScript Examples
///
/// Get the current `group_by` setting:
///
/// ```javascript
/// const {group_by} = await viewer.save();
/// ```
///
/// Reset workflow attached to an external button `myResetButton`:
///
/// ```javascript
/// const token = await viewer.save();
/// myResetButton.addEventListener("click", async () => {
/// await viewer.restore(token);
/// });
/// ```
pub fn save(&self, options: Option<JsPanelOptions>) -> JsViewerConfigPromise {
let PanelOptions { panel: name } = parse_options(options);
let this = self.clone();
let fut = ApiFuture::new(async move {
let panel = this.resolve_panel(name)?;
let viewer_config = panel
.renderer
.clone()
.with_lock(async {
get_viewer_config(&panel.session, &panel.renderer, &this.presentation).await
})
.await?;
viewer_config.encode()
});
js_sys::Promise::from(fut).unchecked_into()
}
/// Save the ENTIRE element to a whole-element [`WorkspaceConfig`]
/// (`{version, active?, layout, panels, ...}`) — the multi-panel
/// counterpart of [`Self::save`]. Unlike [`Self::save`] (which emits a
/// single `ViewerConfig` for one panel), this ALWAYS emits the
/// whole-element format, restorable via [`Self::restoreWorkspace`].
///
/// # JavaScript Examples
///
/// ```javascript
/// const token = await viewer.saveWorkspace();
/// await viewer.restoreWorkspace(token);
/// ```
pub fn saveWorkspace(&self) -> JsWorkspaceConfigPromise {
let this = self.clone();
let fut = ApiFuture::new(Self::workspace_config(this));
js_sys::Promise::from(fut).unchecked_into()
}
/// Download this viewer's internal [`View`] data via a browser download
/// event.
///
/// # Arguments
///
/// - `method` - The `ExportMethod` to use to render the data to download.
///
/// # JavaScript Examples
///
/// ```javascript
/// myDownloadButton.addEventListener("click", async () => {
/// await viewer.download();
/// })
/// ```
pub fn download(&self, options: Option<JsExportOptions>) -> ApiFuture<()> {
let ExportOptions {
method,
panel: name,
} = parse_options(options);
let method = method.map(|m| JsString::from(m.as_str()));
let this = self.clone();
ApiFuture::new_throttled(async move {
let method = if let Some(method) = method
.map(|x| x.unchecked_into())
.map(serde_wasm_bindgen::from_value)
{
method?
} else {
ExportMethod::Csv
};
let panel = this.resolve_panel(name)?;
let blob =
export_method_to_blob(&panel.session, &panel.renderer, &this.presentation, method)
.await?;
let is_chart = panel.renderer.is_chart();
download(
format!("untitled{}", method.as_filename(is_chart)).as_ref(),
&blob,
)
})
}
/// Exports this viewer's internal [`View`] as a JavaSript data, the
/// exact type of which depends on the `method` but defaults to `String`
/// in CSV format.
///
/// This method is only really useful for the `"plugin"` method, which
/// will use the configured plugin's export (e.g. PNG for
/// `@perspective-dev/viewer-charts`). Otherwise, prefer to call the
/// equivalent method on the underlying [`View`] directly.
///
/// # Arguments
///
/// - `method` - The `ExportMethod` to use to render the data to download.
///
/// # JavaScript Examples
///
/// ```javascript
/// const data = await viewer.export("plugin");
/// ```
pub fn export(&self, options: Option<JsExportOptions>) -> ApiFuture<JsValue> {
let ExportOptions {
method,
panel: name,
} = parse_options(options);
let method = method.map(|m| JsString::from(m.as_str()));
let this = self.clone();
ApiFuture::new(async move {
let method = if let Some(method) = method
.map(|x| x.unchecked_into())
.map(serde_wasm_bindgen::from_value)
{
method?
} else {
ExportMethod::Csv
};
let panel = this.resolve_panel(name)?;
export_method_to_jsvalue(&panel.session, &panel.renderer, &this.presentation, method)
.await
})
}
/// Copy this viewer's `View` or `Table` data as CSV to the system
/// clipboard.
///
/// # Arguments
///
/// - `method` - The `ExportMethod` (serialized as a `String`) to use to
/// render the data to the Clipboard.
///
/// # JavaScript Examples
///
/// ```javascript
/// myDownloadButton.addEventListener("click", async () => {
/// await viewer.copy();
/// })
/// ```
pub fn copy(&self, options: Option<JsExportOptions>) -> ApiFuture<()> {
let ExportOptions {
method,
panel: name,
} = parse_options(options);
let method = method.map(|m| JsString::from(m.as_str()));
let this = self.clone();
ApiFuture::new_throttled(async move {
let method = if let Some(method) = method
.map(|x| x.unchecked_into())
.map(serde_wasm_bindgen::from_value)
{
method?
} else {
ExportMethod::Csv
};
let panel = this.resolve_panel(name)?;
let js_task =
export_method_to_blob(&panel.session, &panel.renderer, &this.presentation, method);
copy_to_clipboard(js_task, MimeType::TextPlain).await
})
}
/// Reset a panel's `ViewerConfig` to its data-relative default.
///
/// Without a `panel`, this is ELEMENT-LEVEL: EVERY panel is reset and the
/// cross-filter overlay cleared (symmetric with whole-element
/// [`Self::save`] / [`Self::restore`]). With `{panel}`, only that panel is
/// reset — the other panels and the overlay are left untouched.
///
/// # Arguments
///
/// - `reset_all` - If set, will clear expressions and column settings as
/// well.
/// - `options` - An optional `{panel?: string}`; the panel to reset, or
/// every panel when omitted.
///
/// # JavaScript Examples
///
/// ```javascript
/// await viewer.reset(); // every panel
/// await viewer.reset(true, {panel: "p1"}); // just "p1", + expressions
/// ```
pub fn reset(&self, reset_all: Option<bool>, options: Option<JsPanelOptions>) -> ApiFuture<()> {
let PanelOptions { panel: name } = parse_options(options);
let effect = self.workspace.effects().guard();
let this = self.clone();
let all = reset_all.unwrap_or_default();
ApiFuture::new_throttled(async move {
let _effect = effect;
let (completion, receiver) = Completion::new();
{
let root = this.root.borrow();
let app = root.as_ref().ok_or("Already deleted")?;
match name {
// Element-level: reset every panel + the cross-filter overlay.
None => {
tracing::debug!("Resetting config");
app.send_message(PerspectiveViewerMsg::Reset(all, Some(completion)));
},
// A single named panel; errors if the panel doesn't exist.
Some(name) => {
let panel = this.resolve_panel(Some(name))?;
tracing::debug!("Resetting config ({})", panel.id);
app.send_message(PerspectiveViewerMsg::ResetPanel(
Some(panel.id.to_string()),
all,
Some(completion),
));
},
}
}
receiver.await.map_err(|_| ApiError::new("Cancelled"))?
})
}
/// Recalculate the viewer's dimensions and redraw.
///
/// Use this method to tell `<perspective-viewer>` its dimensions have
/// changed when auto-size mode has been disabled via [`Self::setAutoSize`].
/// [`Self::resize`] resolves when the resize-initiated redraw of this
/// element has completed.
///
/// # Arguments
///
/// - `options` - An optional object with the following fields:
/// - `dimensions` - An optional object `{width, height}` providing
/// explicit size hints (in pixels) for the plugin container. When
/// provided, the plugin element will be temporarily sized to these
/// dimensions during resize, then reset.
///
/// # JavaScript Examples
///
/// ```javascript
/// await viewer.resize()
/// await viewer.resize({dimensions: {width: 800, height: 600}})
/// ```
#[wasm_bindgen]
pub fn resize(&self, options: Option<JsValue>) -> ApiFuture<()> {
let opts: ResizeOptions = options
.map(|v| v.into_serde_ext())
.transpose()
.unwrap_or_default()
.unwrap_or_default();
let effect = self.workspace.effects().guard();
let workspace = self.workspace.clone();
ApiFuture::new_throttled(async move {
let _effect = effect;
// With zero panels there is nothing to resize; fan out to whatever
// panels exist otherwise.
let Some(panel) = workspace.active_panel() else {
resize_visible_panels(&workspace).await;
return Ok(());
};
if !panel.renderer.is_plugin_activated()? {
apply_and_render(&panel.session, &panel.renderer, ViewConfigUpdate::default())?
.await?;
} else if let Some(dims) = opts.dimensions {
panel
.renderer
.resize_with_dimensions(dims.width, dims.height)
.await?;
} else {
resize_visible_panels(&workspace).await;
}
Ok(())
})
}
/// Sets the auto-size behavior of this component.
///
/// When `true`, this `<perspective-viewer>` will register a
/// `ResizeObserver` on itself and call [`Self::resize`] whenever its own
/// dimensions change. However, when embedded in a larger application
/// context, you may want to call [`Self::resize`] manually to avoid
/// over-rendering; in this case auto-sizing can be disabled via this
/// method. Auto-size behavior is enabled by default.
///
/// # Arguments
///
/// - `autosize` - Whether to enable `auto-size` behavior or not.
///
/// # JavaScript Examples
///
/// Disable auto-size behavior:
///
/// ```javascript
/// viewer.setAutoSize(false);
/// ```
#[wasm_bindgen]
pub fn setAutoSize(&self, autosize: bool) {
if autosize {
let handle = Some(ResizeObserverHandle::new(
&self.elem,
&self.workspace,
&self.presentation,
&self.root,
));
*self.resize_handle.borrow_mut() = handle;
} else {
*self.resize_handle.borrow_mut() = None;
}
}
/// Sets the auto-pause behavior of this component.
///
/// When `true`, this `<perspective-viewer>` will skip rendering
/// whenever it cannot be seen — tracked via an `IntersectionObserver`
/// on itself (scrolled out of the viewport, `display: none`) combined
/// with the document's page visibility (backgrounded browser tab,
/// minimized window). Auto-pause is enabled by default.
///
/// # Arguments
///
/// - `autopause` Whether to enable `auto-pause` behavior or not.
///
/// # JavaScript Examples
///
/// Disable auto-size behavior:
///
/// ```javascript
/// viewer.setAutoPause(false);
/// ```
#[wasm_bindgen]
pub fn setAutoPause(&self, autopause: bool) -> ApiFuture<()> {
if autopause {
let handle = Some(AutoPauseHandle::new(
&self.elem,
&self.presentation,
&self.workspace,
));
*self.intersection_handle.borrow_mut() = handle;
} else {
*self.intersection_handle.borrow_mut() = None;
let effect = self.workspace.effects().guard();
let workspace = self.workspace.clone();
let presentation = self.presentation.clone();
return ApiFuture::new(async move {
let _effect = effect;
for id in workspace.panel_ids() {
if let Some(panel) = workspace.panel(&id) {
// A failed resume is already surfaced as that
// panel's error state — don't let it abort the
// remaining panels' resumes.
let _ =
set_panel_paused(&panel.session, &panel.renderer, &presentation, true)
.await;
}
}
Ok(())
});
}
ApiFuture::new(async move { Ok(()) })
}
/// Return a [`perspective_js::JsViewWindow`] for the currently selected
/// region of the named panel, or the active panel when `panel` is omitted.
#[wasm_bindgen]
pub fn getSelection(&self, options: Option<JsPanelOptions>) -> ApiResult<Option<JsViewWindow>> {
let PanelOptions { panel: name } = parse_options(options);
let panel = self.resolve_panel(name)?;
Ok(panel.renderer.get_selection().map(|x| x.into()))
}
/// Set the selection [`perspective_js::JsViewWindow`] for the named panel,
/// or the active panel when `panel` is omitted.
#[wasm_bindgen]
pub fn setSelection(
&self,
window: Option<JsViewWindow>,
options: Option<JsPanelOptions>,
) -> ApiResult<()> {
let PanelOptions { panel: name } = parse_options(options);
let window = window.map(|x| x.into_serde_ext()).transpose()?;
self.resolve_panel(name)?.renderer.set_selection(window);
Ok(())
}
/// Get this viewer's edit port for the named panel's [`Table`] (see
/// [`Table::update`] for details on ports), or the active panel when
/// `panel` is omitted.
#[wasm_bindgen]
pub fn getEditPort(&self, options: Option<JsPanelOptions>) -> ApiResult<f64> {
let PanelOptions { panel: name } = parse_options(options);
let panel = self.resolve_panel(name)?;
let edit_port = if let Some(ctx) = panel.renderer.render_context() {
ctx.edit_port
} else {
panel.session.metadata().get_edit_port()
};
Ok(edit_port.ok_or("No `Table` loaded")?)
}
/// Restyle all plugins from current document.
///
/// <div class="warning">
///
/// [`Self::restyleElement`] _must_ be called for many runtime changes to
/// CSS properties to be reflected in an already-rendered
/// `<perspective-viewer>`.
///
/// </div>
///
/// # JavaScript Examples
///
/// ```javascript
/// viewer.style = "--psp--color: red";
/// await viewer.restyleElement();
/// ```
#[wasm_bindgen]
pub fn restyleElement(&self) -> ApiFuture<JsValue> {
clone!(self.workspace, self.presentation);
let effect = workspace.effects().guard();
ApiFuture::new(async move {
let _effect = effect;
let default = presentation.get_default_theme_name().await;
for panel in workspace
.panel_ids()
.into_iter()
.filter_map(|id| workspace.panel(&id))
{
panel.renderer.set_default_theme(default.clone());
panel.renderer.restyle_all().await?;
}
Ok(JsValue::UNDEFINED)
})
}
/// Set the available theme names available in the status bar UI.
///
/// Calling [`Self::resetThemes`] may cause the current theme to switch,
/// if e.g. the new theme set does not contain the current theme.
///
/// # JavaScript Examples
///
/// Restrict `<perspective-viewer>` theme options to _only_ default light
/// and dark themes, regardless of what is auto-detected from the page's
/// CSS:
///
/// ```javascript
/// viewer.resetThemes(["Pro Light", "Pro Dark"])
/// ```
#[wasm_bindgen]
pub fn resetThemes(&self, themes: Option<Box<[JsValue]>>) -> ApiFuture<JsValue> {
clone!(self.workspace, self.presentation);
let effect = workspace.effects().guard();
ApiFuture::new(async move {
let _effect = effect;
let themes: Option<Vec<String>> = themes
.unwrap_or_default()
.iter()
.map(|x| x.as_string())
.collect();
let theme_name = presentation.get_selected_theme_name().await;
presentation.reset_available_themes(themes).await;
let available = presentation.get_available_themes().await?;
let reset_theme = available
.iter()
.find(|y| theme_name.as_ref() == Some(y))
.cloned();
presentation.set_theme_name(reset_theme.as_deref()).await?;
let new_default = presentation.get_default_theme_name().await;
for panel in workspace
.panel_ids()
.into_iter()
.filter_map(|id| workspace.panel(&id))
{
// Availability applies to PANELS too: a panel pinned to a
// theme outside the new set follows the host — clear the pin
// so it renders (and `save`s) the new registry default, the
// same keep-if-available-else-default rule applied to the
// host selection above.
if panel
.renderer
.theme()
.is_some_and(|t| !available.contains(&t))
{
panel.renderer.set_theme(None);
}
panel.renderer.set_default_theme(new_default.clone());
if panel.renderer.needs_restyle() {
panel.renderer.restyle_all().await?;
}
}
Ok(JsValue::UNDEFINED)
})
}
/// Determines the render throttling behavior. Can be an integer, for
/// millisecond window to throttle render event; or, if `None`, adaptive
/// throttling will be calculated from the measured render time of the
/// last 5 frames.
///
/// # Arguments
///
/// - `throttle` - The throttle rate in milliseconds (f64), or `None` for
/// adaptive throttling.
///
/// # JavaScript Examples
///
/// Only draws at most 1 frame/sec:
///
/// ```rust
/// viewer.setThrottle(1000);
/// ```
#[wasm_bindgen]
pub fn setThrottle(&self, val: Option<f64>) {
for panel in self
.workspace
.panel_ids()
.into_iter()
.filter_map(|id| self.workspace.panel(&id))
{
panel.renderer.set_throttle(val);
}
}
/// Toggle (or force) the config panel open/closed.
///
/// # Arguments
///
/// - `force` - Force the state of the panel open or closed, or `None` to
/// toggle.
///
/// # JavaScript Examples
///
/// ```javascript
/// await viewer.toggleConfig();
/// ```
#[wasm_bindgen]
pub fn toggleConfig(&self, force: Option<bool>) -> ApiFuture<JsValue> {
let effect = self.workspace.effects().guard();
let root = self.root.clone();
ApiFuture::new(async move {
let _effect = effect;
let force = force.map(SettingsUpdate::Update);
let (sender, receiver) = channel::<ApiResult<wasm_bindgen::JsValue>>();
root.borrow().as_ref().into_apierror()?.send_message(
PerspectiveViewerMsg::ToggleSettingsInit(force, Some(sender)),
);
receiver.await.map_err(|_| JsValue::from("Cancelled"))?
})
}
/// Get an `Array` of all of the plugin custom elements registered for this
/// element. This may not include plugins which called
/// [`registerPlugin`] after the host has rendered for the first time.
#[wasm_bindgen]
pub fn getAllPlugins(&self) -> Array {
self.workspace
.active_renderer()
.map(|r| r.get_all_plugins().iter().collect::<Array>())
.unwrap_or_default()
}
/// Gets a plugin Custom Element with the `name` field, or get the active
/// plugin if no `name` is provided.
///
/// # Arguments
///
/// - `name` - The `name` property of a perspective plugin Custom Element,
/// or `None` for the active plugin's Custom Element.
#[wasm_bindgen]
pub fn getPlugin(&self, name: Option<String>) -> ApiResult<JsPerspectiveViewerPlugin> {
let renderer = self
.workspace
.active_renderer()
.ok_or_else(|| ApiError::new("No active panel"))?;
match name {
None => renderer.ensure_plugin_selected(),
Some(name) => renderer.get_plugin(&name),
}
}
/// Add a new, independent panel to this viewer's layout, rendering the
/// supplied [`ViewerConfigUpdate`] into it. The panel uses the default
/// [`perspective_client::Client`] (the first passed to [`Self::load`]) to
/// resolve its `table`. Returns the generated panel id.
///
/// Element-level config fields (`settings`, `theme`) in the argument are
/// ignored — those are shared across the element, not per-panel.
#[wasm_bindgen]
pub fn addPanel(&self, update: JsViewerConfigUpdate) -> ApiFuture<JsValue> {
clone!(self.elem, self.presentation, self.workspace);
let effect = workspace.effects().guard();
let notify = self.layout_changed_notify();
ApiFuture::new(async move {
let _effect = effect;
let update = ViewerConfigUpdate::decode(&update)?;
let id = create_panel(
&elem,
&presentation,
&workspace,
¬ify,
None,
update,
None,
)
.await?;
Ok(JsValue::from_str(id.as_str()))
})
}
/// Get the ids of all panels in this viewer's layout, in insertion order.
#[wasm_bindgen]
pub fn getPanelNames(&self) -> Array {
self.workspace
.panel_ids()
.iter()
.map(|id| JsValue::from_str(id.as_str()))
.collect()
}
/// The id of the active panel — the one the settings panel and status-bar
/// toolbar target — or `null` when the element has zero panels.
#[wasm_bindgen]
pub fn getActivePanel(&self) -> JsValue {
self.workspace
.active_id()
.map(|id| JsValue::from_str(id.as_str()))
.unwrap_or(JsValue::NULL)
}
/// Make the panel with id `name` the active panel, re-targeting the
/// settings panel and status-bar toolbar (and the root's
/// session/renderer subscriptions) to its engines. Resolves after the
/// activation-chrome redraws on both sides of the switch have completed
/// (invariant I6).
#[wasm_bindgen]
pub fn setActivePanel(&self, name: String) -> ApiFuture<()> {
let effect = self.workspace.effects().guard();
let root = self.root.clone();
ApiFuture::new(async move {
let _effect = effect;
let (completion, receiver) = Completion::new();
root.borrow()
.as_ref()
.into_apierror()?
.send_message(PerspectiveViewerMsg::SetActivePanel(name, Some(completion)));
receiver.await.map_err(|_| ApiError::new("Cancelled"))?
})
}
/// Remove the panel with id `name` from the layout, disposing its engines
/// (its `View` is deleted and its `Table` reference released). The last
/// remaining panel cannot be removed (resolves as a no-op). Resolves
/// after the panel's teardown run completes, carrying any teardown
/// error — previously fire-and-forget and silently dropped (invariant
/// I6). See also [`Self::addPanel`].
#[wasm_bindgen]
pub fn removePanel(&self, name: String) -> ApiFuture<()> {
let effect = self.workspace.effects().guard();
let root = self.root.clone();
ApiFuture::new(async move {
let _effect = effect;
let (completion, receiver) = Completion::new();
root.borrow()
.as_ref()
.into_apierror()?
.send_message(PerspectiveViewerMsg::ClosePanel(name, Some(completion)));
receiver.await.map_err(|_| ApiError::new("Cancelled"))?
})
}
/// Create a new JavaScript Heap reference for this model instance.
#[doc(hidden)]
#[allow(clippy::use_self)]
#[wasm_bindgen]
pub fn __get_model(&self) -> PerspectiveViewerElement {
self.clone()
}
/// Asynchronously opens the column settings for a specific column.
/// When finished, the `<perspective-viewer>` element will emit a
/// "perspective-toggle-column-settings" CustomEvent.
/// The event's details property has two fields: `{open: bool, column_name?:
/// string}`. The CustomEvent is also fired whenever the user toggles the
/// sidebar manually.
#[wasm_bindgen]
pub fn toggleColumnSettings(
&self,
column_name: String,
options: Option<JsPanelOptions>,
) -> ApiFuture<()> {
let PanelOptions { panel: name } = parse_options(options);
let effect = self.workspace.effects().guard();
let this = self.clone();
ApiFuture::new_throttled(async move {
let _effect = effect;
let panel = this.resolve_panel(name)?;
let was_active = this.workspace.active_id().as_ref() == Some(&panel.id);
let locator = get_column_locator(&panel.session.metadata(), Some(column_name));
if !was_active {
this.root.borrow().as_ref().into_apierror()?.send_message(
PerspectiveViewerMsg::SetActivePanel(panel.id.as_str().to_owned(), None),
);
}
let (sender, receiver) = channel::<()>();
this.root.borrow().as_ref().into_apierror()?.send_message(
PerspectiveViewerMsg::OpenColumnSettings {
locator,
sender: Some(sender),
toggle: was_active,
},
);
receiver.await.map_err(|_| ApiError::from("Cancelled"))
})
}
}