@malloy-publisher/sdk 0.3.1 → 0.4.0

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 (129) hide show
  1. package/README.md +14 -9
  2. package/dist/{DocumentStorageProvider-tGvodI8f.es.js → DocumentStorageProvider-CyOJ0hqf.es.js} +7114 -6939
  3. package/dist/DocumentStorageProvider-DGPQEd_l.cjs.js +134 -0
  4. package/dist/{RenderedResult-mDE-4u8S.es.js → RenderedResult-BnPzJ9Jf.es.js} +64 -57
  5. package/dist/{RenderedResult-CPi6uQWq.cjs.js → RenderedResult-Dp22kZsQ.cjs.js} +2 -2
  6. package/dist/{ServerProvider-X2Ma0HRs.es.js → ServerProvider-BWOEKg0O.es.js} +1217 -1244
  7. package/dist/ServerProvider-Cc489A3f.cjs.js +1 -0
  8. package/dist/builder/index.cjs.js +41 -41
  9. package/dist/builder/index.es.js +2752 -2831
  10. package/dist/client/api.d.ts +100 -42
  11. package/dist/client/index.cjs.js +1 -1
  12. package/dist/client/index.es.js +1 -1
  13. package/dist/components/AppDialog.d.ts +30 -0
  14. package/dist/components/BackLink.d.ts +32 -0
  15. package/dist/components/Dashboard/DashboardBar.d.ts +21 -0
  16. package/dist/components/Dashboard/telemetry.d.ts +10 -5
  17. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +12 -10
  18. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +8 -2
  19. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +8 -10
  20. package/dist/components/DashboardBuilder/newDashboard.d.ts +17 -0
  21. package/dist/components/DashboardBuilder/spliceDocument.d.ts +10 -1
  22. package/dist/components/ItemRow.d.ts +38 -0
  23. package/dist/components/Materializations/MaterializationDetailDialog.d.ts +1 -2
  24. package/dist/components/Materializations/MaterializationRunsList.d.ts +1 -5
  25. package/dist/components/Materializations/Materializations.d.ts +7 -3
  26. package/dist/components/Materializations/ScopeButton.d.ts +18 -0
  27. package/dist/components/Materializations/SectionLabel.d.ts +7 -4
  28. package/dist/components/Materializations/TriggerLabel.d.ts +14 -0
  29. package/dist/components/Materializations/index.d.ts +0 -1
  30. package/dist/components/Package/ContentTypeIcon.d.ts +3 -5
  31. package/dist/components/Package/NewDashboardDialog.d.ts +18 -0
  32. package/dist/components/Package/index.d.ts +0 -1
  33. package/dist/components/PackageSection.d.ts +23 -0
  34. package/dist/components/buttons.d.ts +53 -0
  35. package/dist/components/index.d.ts +5 -0
  36. package/dist/components/styles.d.ts +49 -40
  37. package/dist/hooks/useCrudMutation.d.ts +42 -0
  38. package/dist/index.cjs.js +22 -26
  39. package/dist/index.d.ts +1 -0
  40. package/dist/index.es.js +17425 -20672
  41. package/dist/telemetry/consoleEvents.d.ts +60 -0
  42. package/dist/utils/sha256.d.ts +2 -0
  43. package/package.json +1 -1
  44. package/src/components/AppDialog.tsx +115 -0
  45. package/src/components/BackLink.tsx +83 -0
  46. package/src/components/Connections/AddConnectionDialog.tsx +50 -70
  47. package/src/components/Connections/DeleteConnectionDialog.tsx +23 -50
  48. package/src/components/Connections/EditConnectionDialog.tsx +54 -73
  49. package/src/components/Dashboard/DashboardBar.tsx +88 -0
  50. package/src/components/Dashboard/telemetry.ts +10 -3
  51. package/src/components/DashboardBuilder/AddTileDialog.tsx +141 -143
  52. package/src/components/DashboardBuilder/BuilderToolbar.tsx +110 -218
  53. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +5 -11
  54. package/src/components/DashboardBuilder/DashboardBuilder.tsx +184 -171
  55. package/src/components/DashboardBuilder/DashboardEditor.package.spec.tsx +163 -0
  56. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +2 -25
  57. package/src/components/DashboardBuilder/DashboardEditor.tsx +135 -61
  58. package/src/components/DashboardBuilder/DiffDialog.tsx +75 -82
  59. package/src/components/DashboardBuilder/DrillDialog.tsx +144 -156
  60. package/src/components/DashboardBuilder/FilterDialog.tsx +276 -295
  61. package/src/components/DashboardBuilder/FilterStrip.tsx +11 -10
  62. package/src/components/DashboardBuilder/newDashboard.spec.ts +40 -0
  63. package/src/components/DashboardBuilder/newDashboard.ts +48 -0
  64. package/src/components/DashboardBuilder/spliceDocument.spec.ts +53 -0
  65. package/src/components/DashboardBuilder/spliceDocument.ts +45 -8
  66. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +56 -0
  67. package/src/components/DashboardBuilder/useDashboardEditor.ts +12 -4
  68. package/src/components/Environment/About.tsx +14 -28
  69. package/src/components/Environment/AddPackageDialog.tsx +85 -154
  70. package/src/components/Environment/Connections.tsx +125 -205
  71. package/src/components/Environment/DeletePackageDialog.tsx +32 -77
  72. package/src/components/Environment/EditPackageDialog.tsx +46 -58
  73. package/src/components/Environment/Environment.tsx +34 -36
  74. package/src/components/Environment/Packages.tsx +63 -128
  75. package/src/components/Home/AddEnvironmentDialog.tsx +47 -70
  76. package/src/components/Home/DeleteEnvironmentDialog.tsx +32 -77
  77. package/src/components/Home/EditEnvironmentDialog.tsx +47 -61
  78. package/src/components/Home/Home.tsx +101 -214
  79. package/src/components/ItemRow.tsx +165 -0
  80. package/src/components/Materializations/CreateMaterializationDialog.tsx +34 -51
  81. package/src/components/Materializations/DeleteMaterializationDialog.tsx +31 -53
  82. package/src/components/Materializations/MaterializationDetailDialog.tsx +60 -69
  83. package/src/components/Materializations/MaterializationRunsList.tsx +29 -42
  84. package/src/components/Materializations/Materializations.tsx +137 -140
  85. package/src/components/Materializations/ScopeButton.tsx +85 -0
  86. package/src/components/Materializations/SectionLabel.tsx +7 -4
  87. package/src/components/Materializations/SetScheduleDialog.tsx +48 -89
  88. package/src/components/Materializations/TriggerLabel.tsx +36 -0
  89. package/src/components/Materializations/cron.spec.ts +113 -0
  90. package/src/components/Materializations/index.ts +0 -1
  91. package/src/components/Materializations/utils.spec.ts +182 -0
  92. package/src/components/Package/ContentTypeIcon.spec.ts +22 -37
  93. package/src/components/Package/ContentTypeIcon.tsx +10 -12
  94. package/src/components/Package/NewDashboardDialog.spec.tsx +129 -0
  95. package/src/components/Package/NewDashboardDialog.tsx +265 -0
  96. package/src/components/Package/Package.tsx +179 -238
  97. package/src/components/Package/index.ts +0 -1
  98. package/src/components/PackageSection.tsx +85 -0
  99. package/src/components/RenderedResult/RenderedResult.lifecycle.spec.tsx +198 -0
  100. package/src/components/RenderedResult/RenderedResult.tsx +22 -8
  101. package/src/components/ResultsDialog.tsx +8 -32
  102. package/src/components/buttons.tsx +114 -0
  103. package/src/components/designSystem.spec.tsx +316 -0
  104. package/src/components/given/paramCodec.spec.ts +1 -1
  105. package/src/components/index.ts +10 -0
  106. package/src/components/styles.ts +49 -85
  107. package/src/hooks/useCrudMutation.spec.tsx +119 -0
  108. package/src/hooks/useCrudMutation.tsx +85 -0
  109. package/src/index.ts +9 -0
  110. package/src/telemetry/consoleEvents.spec.ts +130 -0
  111. package/src/telemetry/consoleEvents.ts +124 -0
  112. package/src/theme/defaults.ts +34 -23
  113. package/src/theme/resolveTheme.spec.ts +9 -4
  114. package/src/theme/resolveTheme.ts +12 -8
  115. package/src/utils/sha256.ts +13 -0
  116. package/test/README.md +1 -1
  117. package/test/serverProvider.tsx +5 -2
  118. package/dist/DocumentStorageProvider-BeBD0uWc.cjs.js +0 -134
  119. package/dist/ServerProvider-CH71GsoL.cjs.js +0 -1
  120. package/dist/components/Materializations/CreateEnvMaterializationDialog.d.ts +0 -14
  121. package/dist/components/Materializations/EnvironmentMaterializations.d.ts +0 -7
  122. package/dist/components/Materializations/ScheduleCard.d.ts +0 -20
  123. package/dist/components/Materializations/TriggerChip.d.ts +0 -10
  124. package/dist/components/Package/Models.d.ts +0 -6
  125. package/src/components/Materializations/CreateEnvMaterializationDialog.tsx +0 -179
  126. package/src/components/Materializations/EnvironmentMaterializations.tsx +0 -267
  127. package/src/components/Materializations/ScheduleCard.tsx +0 -231
  128. package/src/components/Materializations/TriggerChip.tsx +0 -44
  129. package/src/components/Package/Models.tsx +0 -71
@@ -147,7 +147,13 @@ export interface DashboardBuilderProps {
147
147
  /** Saves and refusals, for the host to log; see `DashboardEvent`. */
148
148
  onEvent?: DashboardEventHandler;
149
149
  /**
150
- * The host's own actions for the edit bar — Export, Done — rendered beside
150
+ * Where `onSave` puts the file, for the event it reports. The builder
151
+ * cannot tell — it is handed a function — and a save into the package and a
152
+ * save into this browser are not the same event.
153
+ */
154
+ savesTo?: "package" | "browser";
155
+ /**
156
+ * The host's own actions for the edit bar — Done — rendered beside
151
157
  * undo, redo and save. The builder owns the edits; where the file goes
152
158
  * afterwards is the host's, so its buttons sit in the host's slot.
153
159
  */
@@ -166,6 +172,7 @@ export function DashboardBuilder({
166
172
  toolbar,
167
173
  dashboards,
168
174
  onEvent,
175
+ savesTo = "package",
169
176
  }: DashboardBuilderProps) {
170
177
  const editor = useDashboardEditor({
171
178
  source,
@@ -315,6 +322,7 @@ export function DashboardBuilder({
315
322
  type: "dashboard.saved",
316
323
  tiles,
317
324
  structural,
325
+ where: savesTo,
318
326
  durationMs: now() - started,
319
327
  });
320
328
  else
@@ -324,7 +332,7 @@ export function DashboardBuilder({
324
332
  });
325
333
  })
326
334
  .finally(() => setSaving(false));
327
- }, [editor, onEvent]);
335
+ }, [editor, onEvent, savesTo]);
328
336
  const save = useCallback(() => {
329
337
  if (!onSave || !editor.dirty || saving) return;
330
338
  if (!editor.structural) {
@@ -376,15 +384,6 @@ export function DashboardBuilder({
376
384
  setSelected(editor.document.tiles.length);
377
385
  };
378
386
 
379
- /** Every tile this file owns, to one fraction of the grid. */
380
- const quickLayout = (share: 1 | 2 | 3 | 4) => {
381
- const span = Math.max(1, Math.round(columns / share));
382
- editor.update((draft) => {
383
- for (const tile of draft.tiles)
384
- if (tile.declaration.kind !== "inherited") tile.colspan = span;
385
- });
386
- };
387
-
388
387
  const removeTile = (index: number) => {
389
388
  setMenu(undefined);
390
389
  setSelected(undefined);
@@ -470,9 +469,11 @@ export function DashboardBuilder({
470
469
  // grid alone, so the header, the control row and the tiles all inset
471
470
  // together and stay aligned with each other. 4px = the ring's 2px offset
472
471
  // plus its 2px width.
473
- <Stack sx={{ gap: 2, p: "4px" }}>
474
- {/* The reader's own header, from the component the dashboard renders:
475
- the surface whose job is showing the author what a reader gets. */}
472
+ // The bar carries its own gap to what it sits over, so the surface adds
473
+ // none between the two.
474
+ <Stack sx={{ gap: 0 }}>
475
+ {/* Outside the ring's inset, so the bar lines up to the pixel with the
476
+ reader's — the whole point of it being the same bar. */}
476
477
  <BuilderToolbar
477
478
  canUndo={editor.canUndo}
478
479
  canRedo={editor.canRedo}
@@ -484,170 +485,182 @@ export function DashboardBuilder({
484
485
  {...(toolbar ? { actions: toolbar } : {})}
485
486
  {...(catalog ? { onAddTile: () => setAddingTile(true) } : {})}
486
487
  onSettings={setSettingsAnchor}
487
- onQuickLayout={quickLayout}
488
488
  />
489
489
 
490
- <DashboardProse
491
- title={editor.document.title || "Untitled dashboard"}
492
- {...(editor.document.description
493
- ? { description: editor.document.description }
494
- : {})}
495
- />
490
+ {/* The ring's inset, minus the top: nothing at the top of this stack
491
+ can be selected (the prose and the control row are not tiles), and
492
+ 4px there would put the title 4px further from the bar than the
493
+ reader's is. */}
494
+ <Stack sx={{ gap: 2, px: "4px", pb: "4px" }}>
495
+ <DashboardProse
496
+ title={editor.document.title || "Untitled dashboard"}
497
+ {...(editor.document.description
498
+ ? { description: editor.document.description }
499
+ : {})}
500
+ />
496
501
 
497
- <FilterStrip
498
- controls={controlList}
499
- tileCount={editor.document.tiles.length}
500
- unknownFieldsOf={unknownFieldsOf}
501
- onEdit={(control) => setFilterDialog({ control })}
502
- onAdd={() => setFilterDialog({})}
503
- >
504
- {controls}
505
- </FilterStrip>
502
+ <FilterStrip
503
+ controls={controlList}
504
+ tileCount={editor.document.tiles.length}
505
+ unknownFieldsOf={unknownFieldsOf}
506
+ onEdit={(control) => setFilterDialog({ control })}
507
+ onAdd={() => setFilterDialog({})}
508
+ >
509
+ {controls}
510
+ </FilterStrip>
506
511
 
507
- {editor.error && (
508
- // The edit is still here; the message says what stopped it reaching
509
- // the file, which is a different thing from losing the work.
510
- <Alert severity="warning">{editor.error}</Alert>
511
- )}
512
+ {editor.error && (
513
+ // The edit is still here; the message says what stopped it reaching
514
+ // the file, which is a different thing from losing the work.
515
+ <Alert severity="warning">{editor.error}</Alert>
516
+ )}
512
517
 
513
- <DragDropProvider
514
- sensors={builderSensors}
515
- onDragStart={onDragStart}
516
- onDragOver={onDragOver}
517
- onDragEnd={onDragEnd}
518
- >
519
- <Box ref={gridBox} sx={{ position: "relative" }}>
520
- {(resize !== undefined || dragging) && (
521
- <GridGuides columns={columns} />
522
- )}
518
+ <DragDropProvider
519
+ sensors={builderSensors}
520
+ onDragStart={onDragStart}
521
+ onDragOver={onDragOver}
522
+ onDragEnd={onDragEnd}
523
+ >
524
+ <Box ref={gridBox} sx={{ position: "relative" }}>
525
+ {(resize !== undefined || dragging) && (
526
+ <GridGuides columns={columns} />
527
+ )}
523
528
 
524
- <DashboardGrid
525
- tiles={entries}
526
- columns={columns}
527
- keyOf={(entry) =>
528
- entry.kind === "gap"
529
- ? gapId(entry.after)
530
- : tileKey(entry.tile)
531
- }
532
- renderTile={(entry) => {
533
- if (entry.kind === "gap")
534
- return <GapTarget after={entry.after} />;
535
- const { tile: each, index } = entry;
536
- return (
537
- <TileFrame
538
- tile={each}
539
- index={index}
540
- selected={index === selected}
541
- menuOpen={menu?.index === index}
542
- resizeSpan={
543
- resize?.index === index ? resize.span : undefined
544
- }
545
- columns={columns}
546
- onSelect={() => setSelected(index)}
547
- onOpenMenu={(anchor) => {
548
- setSelected(index);
549
- setMenu({ anchor, index });
550
- }}
551
- onResizeStart={(event) => startResize(event, index)}
552
- onResizeMove={onResize}
553
- onResizeEnd={endResize}
554
- >
555
- {renderTile ? (
556
- renderTile(each)
557
- ) : (
558
- <TilePlaceholder tile={each} />
559
- )}
560
- </TileFrame>
529
+ <DashboardGrid
530
+ tiles={entries}
531
+ columns={columns}
532
+ keyOf={(entry) =>
533
+ entry.kind === "gap"
534
+ ? gapId(entry.after)
535
+ : tileKey(entry.tile)
536
+ }
537
+ renderTile={(entry) => {
538
+ if (entry.kind === "gap")
539
+ return <GapTarget after={entry.after} />;
540
+ const { tile: each, index } = entry;
541
+ return (
542
+ <TileFrame
543
+ tile={each}
544
+ index={index}
545
+ selected={index === selected}
546
+ menuOpen={menu?.index === index}
547
+ resizeSpan={
548
+ resize?.index === index
549
+ ? resize.span
550
+ : undefined
551
+ }
552
+ columns={columns}
553
+ onSelect={() => setSelected(index)}
554
+ onOpenMenu={(anchor) => {
555
+ setSelected(index);
556
+ setMenu({ anchor, index });
557
+ }}
558
+ onResizeStart={(event) =>
559
+ startResize(event, index)
560
+ }
561
+ onResizeMove={onResize}
562
+ onResizeEnd={endResize}
563
+ >
564
+ {renderTile ? (
565
+ renderTile(each)
566
+ ) : (
567
+ <TilePlaceholder tile={each} />
568
+ )}
569
+ </TileFrame>
570
+ );
571
+ }}
572
+ />
573
+ </Box>
574
+ </DragDropProvider>
575
+ <FilterDialog
576
+ open={filterDialog !== undefined}
577
+ document={editor.document}
578
+ {...(filterDialog?.control
579
+ ? { control: filterDialog.control }
580
+ : {})}
581
+ available={available}
582
+ {...(catalog ? { fieldsFor } : {})}
583
+ onClose={() => setFilterDialog(undefined)}
584
+ onApply={applyFilter}
585
+ onRemove={dropControl}
586
+ />
587
+ <TileMenu
588
+ anchor={menu?.anchor ?? null}
589
+ tile={
590
+ menu === undefined
591
+ ? undefined
592
+ : editor.document.tiles[menu.index]
593
+ }
594
+ onClose={() => setMenu(undefined)}
595
+ onCommit={(next) => {
596
+ const at = menu?.index;
597
+ if (at === undefined) return;
598
+ editor.update((draft) => {
599
+ draft.tiles[at] = next;
600
+ });
601
+ }}
602
+ onRemove={() => {
603
+ if (menu !== undefined) removeTile(menu.index);
604
+ }}
605
+ columns={columns}
606
+ onDrills={() => {
607
+ if (menu !== undefined)
608
+ setDrillSource(editor.document.tiles[menu.index]?.source);
609
+ }}
610
+ />
611
+ <DrillDialog
612
+ open={drillSource !== undefined}
613
+ document={editor.document}
614
+ source={editor.document.sources.find(
615
+ (s) => s.name === drillSource,
616
+ )}
617
+ givenNames={controlList.map((c) => c.name)}
618
+ dashboards={dashboards ?? []}
619
+ onClose={() => setDrillSource(undefined)}
620
+ onApply={(drills) =>
621
+ editor.update((draft) => {
622
+ const kept = (draft.drills ?? []).filter(
623
+ (d) => d.source !== drillSource,
561
624
  );
562
- }}
563
- />
564
- </Box>
565
- </DragDropProvider>
566
- <FilterDialog
567
- open={filterDialog !== undefined}
568
- document={editor.document}
569
- {...(filterDialog?.control
570
- ? { control: filterDialog.control }
571
- : {})}
572
- available={available}
573
- {...(catalog ? { fieldsFor } : {})}
574
- onClose={() => setFilterDialog(undefined)}
575
- onApply={applyFilter}
576
- onRemove={dropControl}
577
- />
578
- <TileMenu
579
- anchor={menu?.anchor ?? null}
580
- tile={
581
- menu === undefined
582
- ? undefined
583
- : editor.document.tiles[menu.index]
584
- }
585
- onClose={() => setMenu(undefined)}
586
- onCommit={(next) => {
587
- const at = menu?.index;
588
- if (at === undefined) return;
589
- editor.update((draft) => {
590
- draft.tiles[at] = next;
591
- });
592
- }}
593
- onRemove={() => {
594
- if (menu !== undefined) removeTile(menu.index);
595
- }}
596
- columns={columns}
597
- onDrills={() => {
598
- if (menu !== undefined)
599
- setDrillSource(editor.document.tiles[menu.index]?.source);
600
- }}
601
- />
602
- <DrillDialog
603
- open={drillSource !== undefined}
604
- document={editor.document}
605
- source={editor.document.sources.find((s) => s.name === drillSource)}
606
- givenNames={controlList.map((c) => c.name)}
607
- dashboards={dashboards ?? []}
608
- onClose={() => setDrillSource(undefined)}
609
- onApply={(drills) =>
610
- editor.update((draft) => {
611
- const kept = (draft.drills ?? []).filter(
612
- (d) => d.source !== drillSource,
613
- );
614
- const next = [...kept, ...drills];
615
- if (next.length === 0) delete draft.drills;
616
- else draft.drills = next;
617
- })
618
- }
619
- />
620
- <SettingsPopover
621
- anchor={settingsAnchor}
622
- settings={settings}
623
- onClose={() => setSettingsAnchor(null)}
624
- onCommit={(next) =>
625
- editor.update((draft) => {
626
- draft.title = next.title;
627
- if (next.description === undefined) delete draft.description;
628
- else draft.description = next.description;
629
- if (next.columns === undefined) delete draft.columns;
630
- else draft.columns = next.columns;
631
- if (next.autorun === undefined) delete draft.autorun;
632
- else draft.autorun = next.autorun;
633
- })
634
- }
635
- />
636
- <AddTileDialog
637
- open={addingTile}
638
- document={editor.document}
639
- catalog={catalog}
640
- columns={columns}
641
- onClose={() => setAddingTile(false)}
642
- onAdd={addTile}
643
- />
644
- <DiffDialog
645
- open={pendingSave !== undefined}
646
- before={pendingSave?.before ?? ""}
647
- after={pendingSave?.after ?? ""}
648
- onConfirm={commitSave}
649
- onClose={() => setPendingSave(undefined)}
650
- />
625
+ const next = [...kept, ...drills];
626
+ if (next.length === 0) delete draft.drills;
627
+ else draft.drills = next;
628
+ })
629
+ }
630
+ />
631
+ <SettingsPopover
632
+ anchor={settingsAnchor}
633
+ settings={settings}
634
+ onClose={() => setSettingsAnchor(null)}
635
+ onCommit={(next) =>
636
+ editor.update((draft) => {
637
+ draft.title = next.title;
638
+ if (next.description === undefined)
639
+ delete draft.description;
640
+ else draft.description = next.description;
641
+ if (next.columns === undefined) delete draft.columns;
642
+ else draft.columns = next.columns;
643
+ if (next.autorun === undefined) delete draft.autorun;
644
+ else draft.autorun = next.autorun;
645
+ })
646
+ }
647
+ />
648
+ <AddTileDialog
649
+ open={addingTile}
650
+ document={editor.document}
651
+ catalog={catalog}
652
+ columns={columns}
653
+ onClose={() => setAddingTile(false)}
654
+ onAdd={addTile}
655
+ />
656
+ <DiffDialog
657
+ open={pendingSave !== undefined}
658
+ before={pendingSave?.before ?? ""}
659
+ after={pendingSave?.after ?? ""}
660
+ onConfirm={commitSave}
661
+ onClose={() => setPendingSave(undefined)}
662
+ />
663
+ </Stack>
651
664
  </Stack>
652
665
  );
653
666
  }
@@ -0,0 +1,163 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { fireEvent, render, screen, waitFor } from "@testing-library/react";
5
+ import { beforeEach, describe, expect, it, mock } from "bun:test";
6
+ import {
7
+ clearCache,
8
+ mockServerProvider,
9
+ pending,
10
+ serverWrapper,
11
+ } from "../../../test/serverProvider";
12
+ import { sha256Hex } from "../../utils/sha256";
13
+ import { BrowserDocumentStorage } from "../DocumentStorage/BrowserDocumentStorage";
14
+ import { DocumentStorageProvider } from "../DocumentStorage/DocumentStorageProvider";
15
+
16
+ /**
17
+ * The editor against a server that takes writes: Save goes into the package,
18
+ * carrying the hash of the text that was opened, and a browser draft of the
19
+ * same file is superseded by it.
20
+ */
21
+ const PACKAGE_FILE = `## artifact { title="Storefront" tiles=["a -> by_cat"] } dashboard { columns=12 }
22
+ import { scoped_orders } from "../data_app.malloy"
23
+
24
+ source: a is scoped_orders extend {
25
+ # colspan=6
26
+ # label="By category"
27
+ view: by_cat is by_category
28
+ }`;
29
+
30
+ const getModel = mock((_env: string, _pkg: string, path: string) =>
31
+ Promise.resolve({
32
+ data:
33
+ path === "dashboards/overview.malloy"
34
+ ? { modelPath: path, sourceText: PACKAGE_FILE }
35
+ : { modelPath: path, sources: [], sourceInfos: [] },
36
+ }),
37
+ );
38
+ const updateModelSource = mock(
39
+ (_env: string, _pkg: string, path: string, body: { source: string }) =>
40
+ Promise.resolve({
41
+ data: {
42
+ path,
43
+ contentHash: `hash-of-${body.source.length}`,
44
+ created: false,
45
+ },
46
+ }),
47
+ );
48
+ mockServerProvider(
49
+ {
50
+ models: {
51
+ getModel,
52
+ executeQueryModel: mock(() => pending()),
53
+ updateModelSource,
54
+ },
55
+ dashboards: {
56
+ getDashboard: mock(() =>
57
+ Promise.resolve({
58
+ data: {
59
+ path: "dashboards/overview.malloy",
60
+ givens: [],
61
+ tiles: [],
62
+ },
63
+ }),
64
+ ),
65
+ listDashboards: mock(() =>
66
+ Promise.resolve({ data: [{ name: "overview" }] }),
67
+ ),
68
+ },
69
+ },
70
+ { mutable: true },
71
+ );
72
+
73
+ const { DashboardEditor } = await import("./DashboardEditor");
74
+
75
+ const DRAFT = {
76
+ workspace: "Local",
77
+ type: "dashboard" as const,
78
+ path: "env/pkg/dashboards/overview.malloy",
79
+ };
80
+
81
+ const mount = () => {
82
+ const storage = new BrowserDocumentStorage();
83
+ render(
84
+ <DocumentStorageProvider documentStorage={storage}>
85
+ <DashboardEditor
86
+ environmentName="env"
87
+ packageName="pkg"
88
+ dashboardName="overview"
89
+ />
90
+ </DocumentStorageProvider>,
91
+ { wrapper: serverWrapper },
92
+ );
93
+ return storage;
94
+ };
95
+ const button = (name: string) =>
96
+ screen.getByRole("button", { name, hidden: true });
97
+
98
+ beforeEach(() => {
99
+ clearCache();
100
+ localStorage.clear();
101
+ updateModelSource.mockClear();
102
+ });
103
+
104
+ describe("DashboardEditor, when the server takes writes", () => {
105
+ it("saves into the package with the hash of the text it opened, and supersedes the browser draft", async () => {
106
+ const storage = mount();
107
+ await new BrowserDocumentStorage().saveDocument(DRAFT, "stale draft");
108
+ await screen.findByText("Storefront");
109
+ expect(
110
+ screen.getByText("Save writes the file into the package."),
111
+ ).toBeDefined();
112
+
113
+ fireEvent.click(screen.getByLabelText("Settings for By category"));
114
+ fireEvent.change(screen.getByLabelText("Tile title"), {
115
+ target: { value: "Categories" },
116
+ });
117
+ fireEvent.keyDown(screen.getByLabelText("Tile title"), { key: "Escape" });
118
+ fireEvent.click(button("Save changes"));
119
+
120
+ await waitFor(() => expect(updateModelSource).toHaveBeenCalledTimes(1));
121
+ const [env, pkg, path, body] = updateModelSource.mock.calls[0];
122
+ expect([env, pkg, path]).toEqual([
123
+ "env",
124
+ "pkg",
125
+ "dashboards/overview.malloy",
126
+ ]);
127
+ expect(body.source).toContain('# label="Categories"');
128
+ expect((body as { expectedHash?: string }).expectedHash).toBe(
129
+ await sha256Hex(PACKAGE_FILE),
130
+ );
131
+ await waitFor(() => expect(button("Saved")).toBeDefined());
132
+ await expect(storage.getDocument(DRAFT)).rejects.toBeDefined();
133
+ // No offer to resume a draft over what was just written.
134
+ expect(screen.queryByText(/saved in this browser/)).toBeNull();
135
+ });
136
+
137
+ it("keeps the edit and shows the server's reason when the package refuses the write", async () => {
138
+ updateModelSource.mockImplementationOnce(() =>
139
+ Promise.reject({
140
+ response: {
141
+ data: {
142
+ message:
143
+ "`dashboards/overview.malloy` changed in the package since you opened it.",
144
+ },
145
+ },
146
+ }),
147
+ );
148
+ mount();
149
+ await screen.findByText("Storefront");
150
+ fireEvent.click(screen.getByLabelText("Settings for By category"));
151
+ fireEvent.change(screen.getByLabelText("Tile title"), {
152
+ target: { value: "Categories" },
153
+ });
154
+ fireEvent.keyDown(screen.getByLabelText("Tile title"), { key: "Escape" });
155
+ fireEvent.click(button("Save changes"));
156
+ await waitFor(() =>
157
+ expect(screen.getByRole("alert").textContent).toContain(
158
+ "changed in the package since you opened it",
159
+ ),
160
+ );
161
+ expect(button("Save changes")).toBeDefined();
162
+ });
163
+ });
@@ -167,7 +167,7 @@ describe("DashboardEditor", () => {
167
167
  expect(screen.queryByText(/saved in this browser/)).toBeNull();
168
168
  });
169
169
 
170
- it("exports the file a save would write, hands Done to the host, and reports both opening and exporting", async () => {
170
+ it("hands the exit to the host and reports the open", async () => {
171
171
  const onExit = mock(() => {});
172
172
  const onEvent = mock((_event: DashboardEvent) => {});
173
173
  mount(onExit, onEvent);
@@ -182,30 +182,7 @@ describe("DashboardEditor", () => {
182
182
  from: "package",
183
183
  tiles: 1,
184
184
  });
185
- const created: Blob[] = [];
186
- const createObjectURL = mock((blob: Blob) => {
187
- created.push(blob);
188
- return "blob:test";
189
- });
190
- const revoked = mock(() => {});
191
- Object.assign(URL, { createObjectURL, revokeObjectURL: revoked });
192
- const clicked = mock(() => {});
193
- const click = HTMLAnchorElement.prototype.click;
194
- HTMLAnchorElement.prototype.click = clicked;
195
- try {
196
- fireEvent.click(button("Export"));
197
- await waitFor(() => expect(created).toHaveLength(1));
198
- expect(await created[0].text()).toBe(PACKAGE_FILE);
199
- expect(clicked).toHaveBeenCalledTimes(1);
200
- expect(revoked).toHaveBeenCalledWith("blob:test");
201
- expect(onEvent.mock.calls.at(-1)?.[0]).toEqual({
202
- type: "dashboard.exported",
203
- bytes: PACKAGE_FILE.length,
204
- });
205
- } finally {
206
- HTMLAnchorElement.prototype.click = click;
207
- }
208
- fireEvent.click(button("Done"));
185
+ fireEvent.click(button("Done editing"));
209
186
  expect(onExit).toHaveBeenCalledTimes(1);
210
187
  });
211
188
  });