@malloy-publisher/sdk 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (292) hide show
  1. package/dist/{Dashboard-H1kJlDFo.es.js → DashboardTile-BFcxdv7R.es.js} +15918 -17760
  2. package/dist/DashboardTile-sg8LjUk8.cjs.js +137 -0
  3. package/dist/RenderedResult-B48wAjM8.cjs.js +141 -0
  4. package/dist/{RenderedResult-BRgIgxWh.es.js → RenderedResult-CBLHr32C.es.js} +193 -183
  5. package/dist/{ServerProvider-Boxrv6Ym.es.js → ServerProvider-DCV8BUWD.es.js} +529 -521
  6. package/dist/ServerProvider-HRqT3w1C.cjs.js +1 -0
  7. package/dist/builder/index.cjs.js +146 -58
  8. package/dist/builder/index.es.js +9076 -6479
  9. package/dist/builder-entry.d.ts +4 -0
  10. package/dist/client/api.d.ts +82 -48
  11. package/dist/client/configuration.d.ts +1 -1
  12. package/dist/client/index.cjs.js +1 -1
  13. package/dist/client/index.d.ts +1 -1
  14. package/dist/client/index.es.js +84 -82
  15. package/dist/components/Dashboard/Dashboard.d.ts +8 -15
  16. package/dist/components/Dashboard/DashboardGrid.d.ts +23 -6
  17. package/dist/components/Dashboard/DashboardTile.d.ts +10 -1
  18. package/dist/components/Dashboard/DashboardView.d.ts +36 -0
  19. package/dist/components/Dashboard/TileCard.d.ts +15 -4
  20. package/dist/components/Dashboard/TileFilterTag.d.ts +12 -0
  21. package/dist/components/Dashboard/index.d.ts +3 -0
  22. package/dist/components/Dashboard/telemetry.d.ts +15 -3
  23. package/dist/components/DashboardBuilder/AddTileDialog.d.ts +8 -1
  24. package/dist/components/DashboardBuilder/BuilderToolbar.d.ts +16 -5
  25. package/dist/components/DashboardBuilder/ChartPicker.d.ts +29 -0
  26. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +48 -21
  27. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +17 -4
  28. package/dist/components/DashboardBuilder/DiffDialog.d.ts +2 -10
  29. package/dist/components/DashboardBuilder/FilterDialog.d.ts +2 -2
  30. package/dist/components/DashboardBuilder/FilterStrip.d.ts +3 -1
  31. package/dist/components/DashboardBuilder/InlineMarkdown.d.ts +18 -0
  32. package/dist/components/DashboardBuilder/InlineText.d.ts +19 -0
  33. package/dist/components/DashboardBuilder/NotebookEditor.d.ts +15 -0
  34. package/dist/components/DashboardBuilder/SaveNotice.d.ts +27 -0
  35. package/dist/components/DashboardBuilder/SettingsPopover.d.ts +19 -7
  36. package/dist/components/DashboardBuilder/SourceViewPicker.d.ts +9 -0
  37. package/dist/components/DashboardBuilder/TextTileBody.d.ts +7 -0
  38. package/dist/components/DashboardBuilder/TileFrame.d.ts +14 -12
  39. package/dist/components/DashboardBuilder/TileMenu.d.ts +11 -3
  40. package/dist/components/DashboardBuilder/annotationText.d.ts +4 -0
  41. package/dist/components/DashboardBuilder/catalog.d.ts +4 -0
  42. package/dist/components/DashboardBuilder/changedTile.d.ts +7 -0
  43. package/dist/components/DashboardBuilder/chartLine.d.ts +33 -0
  44. package/dist/components/DashboardBuilder/controls.d.ts +2 -2
  45. package/dist/components/DashboardBuilder/document.d.ts +42 -26
  46. package/dist/components/DashboardBuilder/documentSession.d.ts +100 -0
  47. package/dist/components/DashboardBuilder/legacyNotebook.d.ts +73 -0
  48. package/dist/components/DashboardBuilder/loadMalloy.d.ts +15 -0
  49. package/dist/components/DashboardBuilder/malloyText.d.ts +45 -5
  50. package/dist/components/DashboardBuilder/malloyTree.d.ts +119 -0
  51. package/dist/components/DashboardBuilder/newDashboard.d.ts +3 -1
  52. package/dist/components/DashboardBuilder/openDraft.d.ts +10 -0
  53. package/dist/components/DashboardBuilder/preview.d.ts +24 -4
  54. package/dist/components/DashboardBuilder/readDocument.d.ts +4 -1
  55. package/dist/components/DashboardBuilder/readForEditor.d.ts +16 -0
  56. package/dist/components/DashboardBuilder/sortable.d.ts +14 -0
  57. package/dist/components/DashboardBuilder/spliceDocument.d.ts +13 -13
  58. package/dist/components/DashboardBuilder/spliceResult.d.ts +11 -0
  59. package/dist/components/DashboardBuilder/tagParse.d.ts +24 -0
  60. package/dist/components/DashboardBuilder/telemetry.d.ts +43 -0
  61. package/dist/components/DashboardBuilder/testing/fixtures.d.ts +3 -1
  62. package/dist/components/DashboardBuilder/testing/inline.d.ts +4 -0
  63. package/dist/components/DashboardBuilder/useBuilderSession.d.ts +89 -0
  64. package/dist/components/DashboardBuilder/useBuilderShortcuts.d.ts +9 -6
  65. package/dist/components/DashboardBuilder/useDashboardEditor.d.ts +17 -55
  66. package/dist/components/DashboardBuilder/useDocumentEditor.d.ts +105 -0
  67. package/dist/components/DashboardBuilder/useExitGuard.d.ts +19 -0
  68. package/dist/components/DashboardBuilder/useFilterForm.d.ts +3 -3
  69. package/dist/components/DocumentCreate/canRetry.d.ts +6 -0
  70. package/dist/components/DocumentCreate/createDocument.d.ts +58 -0
  71. package/dist/components/DocumentCreate/documentPath.d.ts +10 -0
  72. package/dist/components/DocumentCreate/events.d.ts +10 -0
  73. package/dist/components/DocumentCreate/exportedSources.d.ts +7 -0
  74. package/dist/components/DocumentCreate/guards.d.ts +12 -0
  75. package/dist/components/DocumentCreate/index.d.ts +6 -0
  76. package/dist/components/DocumentCreate/newNotebook.d.ts +9 -0
  77. package/dist/components/DocumentCreate/useDocumentChoices.d.ts +32 -0
  78. package/dist/components/DocumentStorage/DocumentStorage.d.ts +2 -1
  79. package/dist/components/NarrowEditGate.d.ts +8 -0
  80. package/dist/components/Notebook/Notebook.d.ts +1 -1
  81. package/dist/components/Package/NewDocumentDialog.d.ts +33 -0
  82. package/dist/components/Package/Package.d.ts +1 -0
  83. package/dist/components/Package/documentLocation.d.ts +28 -0
  84. package/dist/components/Package/index.d.ts +4 -0
  85. package/dist/components/Package/useDocumentLocation.d.ts +12 -0
  86. package/dist/components/PackageSection.d.ts +2 -2
  87. package/dist/components/RenderedResult/RenderedResult.d.ts +2 -0
  88. package/dist/components/RenderedResult/ResultContainer.d.ts +8 -1
  89. package/dist/components/RenderedResult/ResultPanel.d.ts +3 -1
  90. package/dist/components/RenderedResult/resultSizing.d.ts +9 -1
  91. package/dist/components/ServerProvider.d.ts +2 -1
  92. package/dist/components/UnsavedChangesDialog.d.ts +9 -0
  93. package/dist/components/given/GivensPanel.d.ts +2 -2
  94. package/dist/components/index.d.ts +2 -0
  95. package/dist/hooks/index.d.ts +1 -0
  96. package/dist/hooks/useNarrowScreen.d.ts +4 -0
  97. package/dist/hooks/useQueryResult.d.ts +2 -0
  98. package/dist/hooks/useSettled.d.ts +14 -0
  99. package/dist/index.cjs.js +23 -24
  100. package/dist/index.es.js +9714 -7072
  101. package/dist/text/index.cjs.js +1 -0
  102. package/dist/text/index.d.ts +2 -0
  103. package/dist/text/index.es.js +6 -0
  104. package/dist/text-entry-BJwltZiy.cjs.js +7 -0
  105. package/dist/text-entry-CbbBcZl8.es.js +196 -0
  106. package/dist/text-entry.d.ts +2 -0
  107. package/dist/utils/clock.d.ts +2 -0
  108. package/package.json +10 -1
  109. package/src/builder-entry.ts +35 -0
  110. package/src/components/Dashboard/Dashboard.tsx +27 -278
  111. package/src/components/Dashboard/DashboardGrid.tsx +68 -7
  112. package/src/components/Dashboard/DashboardTile.spec.tsx +24 -0
  113. package/src/components/Dashboard/DashboardTile.tsx +31 -4
  114. package/src/components/Dashboard/DashboardView.spec.tsx +212 -0
  115. package/src/components/Dashboard/DashboardView.tsx +352 -0
  116. package/src/components/Dashboard/RowsDialog.tsx +1 -1
  117. package/src/components/Dashboard/TileCard.tsx +44 -10
  118. package/src/components/Dashboard/TileFilterTag.spec.tsx +73 -0
  119. package/src/components/Dashboard/TileFilterTag.tsx +78 -0
  120. package/src/components/Dashboard/defaultTileSpan.spec.ts +32 -0
  121. package/src/components/Dashboard/index.ts +3 -0
  122. package/src/components/Dashboard/telemetry.ts +16 -5
  123. package/src/components/DashboardBuilder/AddTileDialog.spec.tsx +88 -0
  124. package/src/components/DashboardBuilder/AddTileDialog.tsx +137 -111
  125. package/src/components/DashboardBuilder/BuilderToolbar.tsx +85 -27
  126. package/src/components/DashboardBuilder/ChartPicker.render.spec.tsx +25 -0
  127. package/src/components/DashboardBuilder/ChartPicker.spec.ts +77 -0
  128. package/src/components/DashboardBuilder/ChartPicker.tsx +153 -0
  129. package/src/components/DashboardBuilder/DashboardBuilder.charts.spec.tsx +205 -0
  130. package/src/components/DashboardBuilder/DashboardBuilder.exit.spec.tsx +192 -0
  131. package/src/components/DashboardBuilder/DashboardBuilder.inline.spec.tsx +329 -0
  132. package/src/components/DashboardBuilder/DashboardBuilder.notebook.spec.tsx +363 -0
  133. package/src/components/DashboardBuilder/DashboardBuilder.notice.spec.tsx +194 -0
  134. package/src/components/DashboardBuilder/DashboardBuilder.openDraft.spec.tsx +157 -0
  135. package/src/components/DashboardBuilder/DashboardBuilder.sources.spec.tsx +124 -0
  136. package/src/components/DashboardBuilder/DashboardBuilder.spec.tsx +103 -78
  137. package/src/components/DashboardBuilder/DashboardBuilder.textTiles.spec.tsx +177 -0
  138. package/src/components/DashboardBuilder/DashboardBuilder.tsx +610 -315
  139. package/src/components/DashboardBuilder/DashboardEditor.authoritative.spec.tsx +58 -8
  140. package/src/components/DashboardBuilder/DashboardEditor.emptyStart.spec.tsx +191 -0
  141. package/src/components/DashboardBuilder/DashboardEditor.filterTag.spec.tsx +162 -0
  142. package/src/components/DashboardBuilder/DashboardEditor.notebook.spec.tsx +316 -0
  143. package/src/components/DashboardBuilder/DashboardEditor.package.spec.tsx +56 -10
  144. package/src/components/DashboardBuilder/DashboardEditor.resourceUri.spec.tsx +5 -22
  145. package/src/components/DashboardBuilder/DashboardEditor.spec.tsx +96 -14
  146. package/src/components/DashboardBuilder/DashboardEditor.tsx +482 -332
  147. package/src/components/DashboardBuilder/DiffDialog.spec.tsx +25 -0
  148. package/src/components/DashboardBuilder/DiffDialog.tsx +5 -24
  149. package/src/components/DashboardBuilder/DrillDialog.tsx +1 -1
  150. package/src/components/DashboardBuilder/FilterDialog.tsx +10 -3
  151. package/src/components/DashboardBuilder/FilterStrip.tsx +26 -4
  152. package/src/components/DashboardBuilder/InlineMarkdown.tsx +184 -0
  153. package/src/components/DashboardBuilder/InlineText.tsx +106 -0
  154. package/src/components/DashboardBuilder/NotebookEditor.tsx +44 -0
  155. package/src/components/DashboardBuilder/SaveNotice.tsx +113 -0
  156. package/src/components/DashboardBuilder/SettingsPopover.spec.tsx +87 -0
  157. package/src/components/DashboardBuilder/SettingsPopover.tsx +225 -67
  158. package/src/components/DashboardBuilder/SourceViewPicker.tsx +122 -0
  159. package/src/components/DashboardBuilder/TextTileBody.tsx +28 -0
  160. package/src/components/DashboardBuilder/TileFrame.tsx +89 -115
  161. package/src/components/DashboardBuilder/TileMenu.tsx +168 -90
  162. package/src/components/DashboardBuilder/annotationText.spec.ts +33 -0
  163. package/src/components/DashboardBuilder/annotationText.ts +17 -0
  164. package/src/components/DashboardBuilder/artifactBlock.spec.ts +248 -0
  165. package/src/components/DashboardBuilder/artifactTagParity.spec.ts +41 -0
  166. package/src/components/DashboardBuilder/catalog.aggregate.spec.ts +49 -0
  167. package/src/components/DashboardBuilder/catalog.spec.ts +2 -0
  168. package/src/components/DashboardBuilder/catalog.ts +61 -21
  169. package/src/components/DashboardBuilder/changedTile.spec.ts +46 -0
  170. package/src/components/DashboardBuilder/changedTile.ts +28 -0
  171. package/src/components/DashboardBuilder/chartLine.spec.ts +180 -0
  172. package/src/components/DashboardBuilder/chartLine.ts +121 -0
  173. package/src/components/DashboardBuilder/controls.spec.ts +21 -10
  174. package/src/components/DashboardBuilder/controls.ts +22 -8
  175. package/src/components/DashboardBuilder/document.ts +53 -5
  176. package/src/components/DashboardBuilder/documentSession.spec.ts +209 -0
  177. package/src/components/DashboardBuilder/documentSession.ts +257 -0
  178. package/src/components/DashboardBuilder/emptyStart.spec.ts +131 -0
  179. package/src/components/DashboardBuilder/invariants.spec.ts +6 -2
  180. package/src/components/DashboardBuilder/legacyNotebook.chart.spec.ts +77 -0
  181. package/src/components/DashboardBuilder/legacyNotebook.convert.spec.ts +630 -0
  182. package/src/components/DashboardBuilder/legacyNotebook.read.spec.ts +338 -0
  183. package/src/components/DashboardBuilder/legacyNotebook.ts +1117 -0
  184. package/src/components/DashboardBuilder/loadMalloy.spec.ts +80 -0
  185. package/src/components/DashboardBuilder/loadMalloy.ts +39 -0
  186. package/src/components/DashboardBuilder/malloyText.spec.ts +48 -0
  187. package/src/components/DashboardBuilder/malloyText.ts +181 -27
  188. package/src/components/DashboardBuilder/malloyTree.ts +155 -7
  189. package/src/components/DashboardBuilder/newDashboard.spec.ts +46 -2
  190. package/src/components/DashboardBuilder/newDashboard.ts +30 -3
  191. package/src/components/DashboardBuilder/openDraft.ts +52 -0
  192. package/src/components/DashboardBuilder/preview.shapes.spec.ts +75 -0
  193. package/src/components/DashboardBuilder/preview.spec.ts +159 -12
  194. package/src/components/DashboardBuilder/preview.ts +83 -9
  195. package/src/components/DashboardBuilder/readDocument.spec.ts +139 -27
  196. package/src/components/DashboardBuilder/readDocument.ts +130 -44
  197. package/src/components/DashboardBuilder/readForEditor.spec.ts +80 -0
  198. package/src/components/DashboardBuilder/readForEditor.ts +47 -0
  199. package/src/components/DashboardBuilder/scannerShapes.spec.ts +14 -13
  200. package/src/components/DashboardBuilder/sortable.spec.ts +65 -0
  201. package/src/components/DashboardBuilder/sortable.tsx +2 -12
  202. package/src/components/DashboardBuilder/spliceDocument.chart.spec.ts +340 -0
  203. package/src/components/DashboardBuilder/spliceDocument.imports.spec.ts +167 -0
  204. package/src/components/DashboardBuilder/spliceDocument.spec.ts +229 -94
  205. package/src/components/DashboardBuilder/spliceDocument.ts +762 -130
  206. package/src/components/DashboardBuilder/spliceResult.ts +15 -0
  207. package/src/components/DashboardBuilder/statementExtent.spec.ts +33 -30
  208. package/src/components/DashboardBuilder/tagParse.spec.ts +149 -0
  209. package/src/components/DashboardBuilder/tagParse.ts +103 -0
  210. package/src/components/DashboardBuilder/telemetry.ts +47 -0
  211. package/src/components/DashboardBuilder/testing/artifactTagParity.json +197 -0
  212. package/src/components/DashboardBuilder/testing/fixtures.ts +16 -1
  213. package/src/components/DashboardBuilder/testing/inline.ts +25 -0
  214. package/src/components/DashboardBuilder/textTiles.spec.ts +718 -0
  215. package/src/components/DashboardBuilder/useBuilderSession.spec.ts +335 -0
  216. package/src/components/DashboardBuilder/useBuilderSession.ts +292 -0
  217. package/src/components/DashboardBuilder/useBuilderShortcuts.overlay.spec.tsx +65 -0
  218. package/src/components/DashboardBuilder/useBuilderShortcuts.spec.tsx +60 -0
  219. package/src/components/DashboardBuilder/useBuilderShortcuts.ts +36 -10
  220. package/src/components/DashboardBuilder/useDashboardEditor.spec.ts +16 -13
  221. package/src/components/DashboardBuilder/useDashboardEditor.ts +54 -181
  222. package/src/components/DashboardBuilder/useDocumentEditor.spec.ts +565 -0
  223. package/src/components/DashboardBuilder/useDocumentEditor.ts +399 -0
  224. package/src/components/DashboardBuilder/useExitGuard.spec.ts +159 -0
  225. package/src/components/DashboardBuilder/useExitGuard.ts +89 -0
  226. package/src/components/DashboardBuilder/useFilterForm.existing.spec.tsx +41 -0
  227. package/src/components/DashboardBuilder/useFilterForm.spec.tsx +24 -2
  228. package/src/components/DashboardBuilder/useFilterForm.ts +41 -13
  229. package/src/components/DashboardBuilder/useTileReorder.spec.tsx +28 -5
  230. package/src/components/DashboardBuilder/useTileReorder.ts +5 -7
  231. package/src/components/DocumentCreate/canRetry.spec.ts +32 -0
  232. package/src/components/DocumentCreate/canRetry.ts +19 -0
  233. package/src/components/DocumentCreate/createDocument.spec.ts +310 -0
  234. package/src/components/DocumentCreate/createDocument.ts +159 -0
  235. package/src/components/DocumentCreate/documentPath.ts +40 -0
  236. package/src/components/DocumentCreate/events.ts +15 -0
  237. package/src/components/DocumentCreate/exportedSources.ts +25 -0
  238. package/src/components/DocumentCreate/guards.ts +45 -0
  239. package/src/components/DocumentCreate/index.ts +27 -0
  240. package/src/components/DocumentCreate/newNotebook.spec.ts +156 -0
  241. package/src/components/DocumentCreate/newNotebook.ts +44 -0
  242. package/src/components/DocumentCreate/useDocumentChoices.spec.tsx +138 -0
  243. package/src/components/DocumentCreate/useDocumentChoices.ts +113 -0
  244. package/src/components/DocumentStorage/DocumentStorage.ts +2 -1
  245. package/src/components/Model/ModelExplorer.spec.tsx +2 -2
  246. package/src/components/Model/SourcesExplorer.tsx +2 -4
  247. package/src/components/NarrowEditGate.spec.tsx +73 -0
  248. package/src/components/NarrowEditGate.tsx +29 -0
  249. package/src/components/Notebook/Notebook.layout.spec.tsx +94 -0
  250. package/src/components/Notebook/Notebook.tsx +66 -27
  251. package/src/components/Package/NewDocumentDialog.spec.tsx +749 -0
  252. package/src/components/Package/NewDocumentDialog.tsx +401 -0
  253. package/src/components/Package/Package.artifacts.spec.tsx +190 -0
  254. package/src/components/Package/Package.create.spec.tsx +380 -0
  255. package/src/components/Package/Package.notebooks.spec.tsx +18 -0
  256. package/src/components/Package/Package.tsx +366 -171
  257. package/src/components/Package/documentLocation.spec.ts +81 -0
  258. package/src/components/Package/documentLocation.ts +55 -0
  259. package/src/components/Package/index.ts +13 -0
  260. package/src/components/Package/useDocumentLocation.ts +59 -0
  261. package/src/components/PackageSection.tsx +2 -2
  262. package/src/components/RenderedResult/RenderedResult.tsx +18 -1
  263. package/src/components/RenderedResult/ResultContainer.tsx +44 -11
  264. package/src/components/RenderedResult/ResultPanel.tsx +4 -0
  265. package/src/components/RenderedResult/resultSizing.spec.ts +68 -0
  266. package/src/components/RenderedResult/resultSizing.ts +14 -3
  267. package/src/components/ServerProvider.tsx +2 -1
  268. package/src/components/UnsavedChangesDialog.spec.tsx +70 -0
  269. package/src/components/UnsavedChangesDialog.tsx +49 -0
  270. package/src/components/given/GivensPanel.spec.tsx +6 -6
  271. package/src/components/given/GivensPanel.tsx +3 -3
  272. package/src/components/index.ts +2 -0
  273. package/src/hooks/index.ts +3 -0
  274. package/src/hooks/useNarrowScreen.ts +21 -0
  275. package/src/hooks/useQueryResult.ts +16 -0
  276. package/src/hooks/useSettled.spec.ts +41 -0
  277. package/src/hooks/useSettled.ts +27 -0
  278. package/src/mainEntry.spec.ts +145 -0
  279. package/src/text-entry.ts +12 -0
  280. package/src/textEntry.spec.ts +118 -0
  281. package/src/utils/clock.spec.ts +12 -0
  282. package/src/utils/clock.ts +6 -0
  283. package/vite.config.ts +4 -0
  284. package/dist/Dashboard-ChyylkTD.cjs.js +0 -136
  285. package/dist/RenderedResult-AJPMUkAD.cjs.js +0 -135
  286. package/dist/ServerProvider-CXrOKD6g.cjs.js +0 -1
  287. package/dist/components/DashboardBuilder/useTileResize.d.ts +0 -29
  288. package/dist/components/Package/NewDashboardDialog.d.ts +0 -18
  289. package/src/components/DashboardBuilder/useTileResize.spec.tsx +0 -121
  290. package/src/components/DashboardBuilder/useTileResize.ts +0 -110
  291. package/src/components/Package/NewDashboardDialog.spec.tsx +0 -129
  292. package/src/components/Package/NewDashboardDialog.tsx +0 -265
@@ -1,21 +1,39 @@
1
1
  // Copyright (c) Credible Data Inc.
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { annotationTextProblem } from "./annotationText";
5
+ import {
6
+ chartLineText,
7
+ isChartPick,
8
+ mentionsChartTag,
9
+ parseChartLine,
10
+ type ChartPick,
11
+ } from "./chartLine";
4
12
  import type {
5
13
  DashboardDocument,
6
14
  DashboardDrill,
7
15
  DashboardSource,
8
16
  DashboardTile,
17
+ DocumentKind,
18
+ QueryTile,
19
+ TextTile,
9
20
  } from "./document";
21
+ import { isQueryTile, isTextTile } from "./document";
10
22
  import type { LocalGiven } from "./document";
11
23
  import {
12
24
  artifactLine,
25
+ artifactTag,
26
+ type ArtifactTag,
13
27
  descriptionNotes,
14
- hasNonQuotedTiles,
28
+ isIdentifier,
29
+ isBareName,
30
+ isStrictName,
31
+ malloyPath,
15
32
  } from "./malloyText";
16
33
  import {
17
34
  parseMalloy,
18
35
  parseRefused,
36
+ readTileList,
19
37
  translate,
20
38
  type ParsedMalloy,
21
39
  type Span,
@@ -24,6 +42,11 @@ import {
24
42
  type TreeView,
25
43
  } from "./malloyTree";
26
44
  import { blockAbove, readDashboardDocument, readFailed } from "./readDocument";
45
+ import {
46
+ spliceFailed,
47
+ type SpliceFailure,
48
+ type SpliceResult,
49
+ } from "./spliceResult";
27
50
 
28
51
  /**
29
52
  * The syntax errors Malloy's own parser reports for `text`, as a multiset of
@@ -68,8 +91,8 @@ export async function syntaxErrors(text: string): Promise<string[]> {
68
91
  * ADDED or REMOVED: a new `view:` inside the extension of the source it reads
69
92
  * (or a new extension, when the file imports that source by name), a removed
70
93
  * one deleted with its `#` tags. Those moves are the one place the file cannot
71
- * say who owns the comment beside a declaration, so the builder shows the diff
72
- * before a structural save and the `//` comments are left where they were.
94
+ * say who owns the comment beside a declaration, so the `//` comments are left
95
+ * where they were and the author can read the change back with View change.
73
96
  *
74
97
  * A given is different from a tile in exactly the way that matters there: the
75
98
  * `#` tags above its declaration are its control contract and have no other
@@ -77,16 +100,7 @@ export async function syntaxErrors(text: string): Promise<string[]> {
77
100
  * in the same block is left where it is.
78
101
  */
79
102
 
80
- export interface SpliceFailure {
81
- ok: false;
82
- reason: string;
83
- }
84
-
85
- export type SpliceResult = { ok: true; source: string } | SpliceFailure;
86
-
87
- /** Narrow to the failure arm; see {@link readFailed} for why a guard. */
88
- export const spliceFailed = (result: SpliceResult): result is SpliceFailure =>
89
- result.ok === false;
103
+ export { spliceFailed, type SpliceFailure, type SpliceResult };
90
104
 
91
105
  /**
92
106
  * A stable serialisation for comparing documents.
@@ -112,6 +126,11 @@ function canonical(value: unknown): string {
112
126
  return JSON.stringify(walk(value));
113
127
  }
114
128
 
129
+ /** A description without blank lines at either end, each of which would write a bare `##"`. */
130
+ function trimDescription(text: string): string {
131
+ return text.replace(/^(?:[ \t]*\r?\n)+/, "").trimEnd();
132
+ }
133
+
115
134
  /** A byte-range replacement. Applied last-first so earlier offsets stay valid. */
116
135
  interface Edit {
117
136
  start: number;
@@ -141,8 +160,14 @@ function applyEdits(source: string, edits: Edit[]): string {
141
160
  return out;
142
161
  }
143
162
 
163
+ /** The chart a tile's `chart` asks the writer to put on its wrapper; `default` and `custom` ask for no line. */
164
+ const writableChart = (
165
+ chart: QueryTile["chart"],
166
+ ): ChartPick | "none" | undefined =>
167
+ chart === "none" || isChartPick(chart) ? chart : undefined;
168
+
144
169
  /** The `#` tags a tile's presentation implies, in the order they are written. */
145
- function tagsFor(tile: DashboardTile): string[] {
170
+ function tagsFor(tile: QueryTile, withChart = true): string[] {
146
171
  const tags: string[] = [];
147
172
  if (tile.colspan !== undefined) tags.push(`# colspan=${tile.colspan}`);
148
173
  if (tile.break) tags.push("# break");
@@ -150,6 +175,8 @@ function tagsFor(tile: DashboardTile): string[] {
150
175
  if (tile.label !== undefined) tags.push(`# label=${quoted(tile.label)}`);
151
176
  if (tile.subtitle !== undefined)
152
177
  tags.push(`# subtitle=${quoted(tile.subtitle)}`);
178
+ const chart = withChart ? writableChart(tile.chart) : undefined;
179
+ if (chart !== undefined) tags.push(chartLineText(chart, tile.chartCarried));
153
180
  return tags;
154
181
  }
155
182
 
@@ -194,10 +221,8 @@ const MODELLED_GIVEN_TAG_KEYS: ReadonlySet<string> = new Set([
194
221
  "range_max",
195
222
  ]);
196
223
 
197
- const isSameDocumentExceptTiles = (
198
- a: DashboardDocument,
199
- b: DashboardDocument,
200
- ) => canonical(a.imports) === canonical(b.imports);
224
+ const kindOf = (document: DashboardDocument): DocumentKind =>
225
+ document.kind ?? "dashboard";
201
226
 
202
227
  /**
203
228
  * A given's tag line, composed from its control contract. One line, in the
@@ -215,10 +240,10 @@ function givenTagLine(given: LocalGiven): string | undefined {
215
240
  given.suggest.source !== undefined
216
241
  ? `source=${given.suggest.source}`
217
242
  : given.suggest.query !== undefined
218
- ? `query=${given.suggest.query}`
243
+ ? `query=${quoted(given.suggest.query)}`
219
244
  : undefined;
220
245
  parts.push(
221
- `suggest { ${by ? `${by} ` : ""}dimension=${given.suggest.dimension} }`,
246
+ `suggest { ${by ? `${by} ` : ""}dimension=${quoted(given.suggest.dimension)} }`,
222
247
  );
223
248
  }
224
249
  if (given.rangeMin !== undefined) parts.push(`range_min=${given.rangeMin}`);
@@ -278,7 +303,9 @@ const quoted = (text: string) =>
278
303
  * rewrite declarations?" wants THIS key.
279
304
  */
280
305
  export const tileFileKey = (t: DashboardTile) =>
281
- canonical([t.name, t.source, t.declaration]);
306
+ isTextTile(t)
307
+ ? canonical(["text", t.name])
308
+ : canonical([t.name, t.source, t.declaration]);
282
309
  const tileKey = tileFileKey;
283
310
 
284
311
  /** The tile list as identities, IN ORDER. Differs under a reorder. */
@@ -307,6 +334,8 @@ interface SpliceContext extends TileMembership {
307
334
  current: DashboardDocument;
308
335
  next: DashboardDocument;
309
336
  edits: Edit[];
337
+ /** The file's package path, when known. */
338
+ modelPath?: string;
310
339
  }
311
340
 
312
341
  /**
@@ -316,12 +345,19 @@ interface SpliceContext extends TileMembership {
316
345
  function checkShape(
317
346
  current: DashboardDocument,
318
347
  next: DashboardDocument,
348
+ changeKind: boolean,
319
349
  ): SpliceFailure | TileMembership {
350
+ if (kindOf(current) !== kindOf(next) && !changeKind) {
351
+ return {
352
+ ok: false,
353
+ reason:
354
+ "The document's kind is not changed by an ordinary edit; switch it with the explicit kind change.",
355
+ };
356
+ }
320
357
  // Tiles ADDED and REMOVED, by identity. A removed tile's declaration goes,
321
358
  // with its `#` tags; a `//` comment above it stays, because the file cannot
322
359
  // say whether it belonged to the tile, the row or the page, and a comment
323
- // left behind is a smaller wrong than one destroyed — and the builder shows
324
- // this diff before it saves. An added tile is a `view:` in the extension of
360
+ // left behind is a smaller wrong than one destroyed. An added tile is a `view:` in the extension of
325
361
  // the source it reads, or a new extension when the file has none yet.
326
362
  //
327
363
  // REORDERING is neither: a tile's position is the `tiles=[…]` array on the
@@ -334,7 +370,7 @@ function checkShape(
334
370
  const reordered =
335
371
  membershipChanged || tileIdentity(current) !== tileIdentity(next);
336
372
  for (const tile of addedTiles) {
337
- if (tile.declaration.kind !== "reference") {
373
+ if (isQueryTile(tile) && tile.declaration.kind !== "reference") {
338
374
  return {
339
375
  ok: false,
340
376
  reason:
@@ -345,12 +381,11 @@ function checkShape(
345
381
  }
346
382
  }
347
383
  // Sources may only be ADDED, and only for a tile being added on them — the
348
- // builder never renames or removes an extension, and never edits imports,
349
- // so a new extension's base has to be a source the file already imports by
350
- // name (or already extends).
384
+ // builder never renames or removes an extension, so a new extension's base
385
+ // has to be a source the file imports by name (or already extends).
351
386
  const currentSources = new Map(current.sources.map((s) => [s.name, s]));
352
387
  const importedByName = new Set(
353
- current.imports.flatMap((i) => (i.kind === "names" ? i.names : [])),
388
+ next.imports.flatMap((i) => (i.kind === "names" ? i.names : [])),
354
389
  );
355
390
  for (const source of current.sources) importedByName.add(source.base);
356
391
  const newSources = next.sources.filter((s) => !currentSources.has(s.name));
@@ -364,7 +399,7 @@ function checkShape(
364
399
  }
365
400
  }
366
401
  for (const source of newSources) {
367
- if (!addedTiles.some((t) => t.source === source.name)) {
402
+ if (!addedTiles.some((t) => isQueryTile(t) && t.source === source.name)) {
368
403
  return {
369
404
  ok: false,
370
405
  reason: `A new source \`${source.name}\` needs a tile on it.`,
@@ -375,17 +410,10 @@ function checkShape(
375
410
  ok: false,
376
411
  reason:
377
412
  `\`${source.base}\` is not imported by name in this file, so a ` +
378
- `tile cannot be put on it. The builder does not add imports: ` +
379
- `import { ${source.base} } from the model first.`,
413
+ `tile cannot be put on it. Add it as a source first.`,
380
414
  };
381
415
  }
382
416
  }
383
- if (!isSameDocumentExceptTiles(current, next)) {
384
- return {
385
- ok: false,
386
- reason: "The dashboard's imports cannot be changed here.",
387
- };
388
- }
389
417
  return {
390
418
  currentKeys,
391
419
  nextKeys,
@@ -397,64 +425,178 @@ function checkShape(
397
425
  };
398
426
  }
399
427
 
400
- function planOrder(ctx: SpliceContext): SpliceFailure | undefined {
401
- const { lines, wholeLine, next, reordered, currentKeys, nextKeys, edits } =
402
- ctx;
403
- // A reorder is one rewritten array on the `## artifact` line. Each entry is
404
- // re-emitted AS IT WAS WRITTEN rather than rebuilt from `source` and `name`,
405
- // so a file that spells a tile `overview->kpis` keeps its spelling and the
406
- // diff is the reordering and nothing else.
407
- if (reordered) {
408
- const artifactAt = artifactLine(lines);
409
- if (artifactAt < 0) {
410
- return {
411
- ok: false,
412
- reason: "Could not find the `## artifact` tag to reorder.",
413
- };
414
- }
415
- if (hasNonQuotedTiles(lines[artifactAt])) {
416
- return {
417
- ok: false,
418
- reason:
419
- "The `tiles=[…]` list holds an entry the builder does not model, such as a text tile, and rewriting the list would drop it. Reorder, add and remove tiles in the file's text.",
420
- };
428
+ /** A text entry's width and row break, which the list entry carries because the block has no tags. */
429
+ const textEntryChanged = (was: TextTile, now: TextTile) =>
430
+ was.colspan !== now.colspan || Boolean(was.break) !== Boolean(now.break);
431
+
432
+ /** `text` with every quoted string blanked to `x`s of the same length, so a scan for syntax cannot land inside one. */
433
+ function maskStrings(text: string): string {
434
+ let out = "";
435
+ for (let i = 0; i < text.length; i++) {
436
+ if (text[i] !== '"') {
437
+ out += text[i];
438
+ continue;
421
439
  }
422
- const written = [...lines[artifactAt].matchAll(/"([^"]+)"/g)].map(
423
- (m) => m[1],
424
- );
425
- const byKey = new Map<string, string>();
426
- for (const entry of written) {
427
- const parts = entry.split("->").map((part) => part.trim());
428
- if (parts.length === 2) byKey.set(`${parts[0]}->${parts[1]}`, entry);
440
+ const end = endOfString(text, i);
441
+ out += "x".repeat(Math.min(end, text.length - 1) - i + 1);
442
+ i = end;
443
+ }
444
+ return out;
445
+ }
446
+
447
+ /** A `name { kind=text … }` entry with its `colspan` and `break` set as `tile` has them, every other property as written. */
448
+ function textEntry(tile: TextTile, written?: string): string {
449
+ if (written === undefined)
450
+ return `${tile.name} { kind=text${
451
+ tile.colspan === undefined ? "" : ` colspan=${tile.colspan}`
452
+ }${tile.break ? " break" : ""} }`;
453
+ const masked = maskStrings(written);
454
+ const open = masked.indexOf("{");
455
+ const close = masked.lastIndexOf("}");
456
+ let inner = written.slice(open + 1, close);
457
+ let maskedInner = masked.slice(open + 1, close);
458
+ const drop = (re: RegExp) => {
459
+ const hit = re.exec(maskedInner);
460
+ if (!hit) return;
461
+ inner =
462
+ inner.slice(0, hit.index) + inner.slice(hit.index + hit[0].length);
463
+ maskedInner =
464
+ maskedInner.slice(0, hit.index) +
465
+ maskedInner.slice(hit.index + hit[0].length);
466
+ };
467
+ drop(/\s*\bcolspan\s*=\s*[^\s}]+/);
468
+ drop(/\s*\bbreak\b(?!\s*=)/);
469
+ const props = [
470
+ inner.trim(),
471
+ tile.colspan === undefined ? "" : `colspan=${tile.colspan}`,
472
+ tile.break ? "break" : "",
473
+ ].filter(Boolean);
474
+ return `${written.slice(0, open)}{ ${props.join(" ")} }${written.slice(close + 1)}`;
475
+ }
476
+
477
+ function planOrder(ctx: SpliceContext): SpliceFailure | undefined {
478
+ const {
479
+ lines,
480
+ wholeLine,
481
+ current,
482
+ next,
483
+ reordered,
484
+ currentKeys,
485
+ nextKeys,
486
+ edits,
487
+ } = ctx;
488
+ const wasText = new Map(
489
+ current.tiles.filter(isTextTile).map((tile) => [tile.name, tile]),
490
+ );
491
+ const resized = next.tiles.filter(isTextTile).some((tile) => {
492
+ const was = wasText.get(tile.name);
493
+ return was !== undefined && textEntryChanged(was, tile);
494
+ });
495
+ // A reorder, and a text tile's width, are one rewritten array on the
496
+ // `## artifact` line. Each entry is re-emitted AS IT WAS WRITTEN rather than
497
+ // rebuilt from `source` and `name`, so a file that spells a tile
498
+ // `overview->kpis` keeps its spelling and the diff is the change and nothing else.
499
+ if (!reordered && !resized) return undefined;
500
+ const tag = artifactTag(lines);
501
+ if (!tag) {
502
+ return {
503
+ ok: false,
504
+ reason: "Could not find the `## artifact` tag to reorder.",
505
+ };
506
+ }
507
+ const line = tag.text;
508
+ const list = readTileList(line);
509
+ if (!list) {
510
+ return {
511
+ ok: false,
512
+ reason: "Could not read the `tiles=[…]` list to rewrite it.",
513
+ };
514
+ }
515
+ if (nextKeys.size === 0 && currentKeys.size > 0) {
516
+ return {
517
+ ok: false,
518
+ reason:
519
+ "A dashboard with no tiles is not served, so the last tile cannot be removed. Add another tile first.",
520
+ };
521
+ }
522
+ const byKey = new Map<string, string>();
523
+ for (const { text } of list.entries) {
524
+ const quoted = /^"((?:[^"\\]|\\.)+)"$/.exec(text);
525
+ if (quoted) {
526
+ const parts = quoted[1].split("->").map((part) => part.trim());
527
+ if (parts.length === 2) byKey.set(`${parts[0]}->${parts[1]}`, text);
528
+ continue;
429
529
  }
430
- // An existing tile keeps its spelling; a new one is written canonically.
431
- const nextEntries = next.tiles.map(
432
- (tile) =>
433
- byKey.get(`${tile.source}->${tile.name}`) ??
434
- (nextKeys.has(tileKey(tile)) && !currentKeys.has(tileKey(tile))
435
- ? `${tile.source} -> ${tile.name}`
436
- : undefined),
437
- );
438
- if (nextEntries.some((entry) => entry === undefined)) {
439
- return {
440
- ok: false,
441
- reason:
442
- "A tile in the new order is not one the `## artifact` tag names.",
443
- };
530
+ const name = /^([A-Za-z_][A-Za-z0-9_]*)\s*\{/.exec(text)?.[1];
531
+ if (name !== undefined) byKey.set(`text.${name}`, text);
532
+ }
533
+ // An existing tile keeps its spelling; a new one is written canonically.
534
+ const nextEntries = next.tiles.map((tile) => {
535
+ const isNew = !currentKeys.has(tileKey(tile));
536
+ if (isTextTile(tile)) {
537
+ const written = byKey.get(`text.${tile.name}`);
538
+ return written !== undefined
539
+ ? wasText.has(tile.name) &&
540
+ !textEntryChanged(wasText.get(tile.name), tile)
541
+ ? written
542
+ : textEntry(tile, written)
543
+ : isNew
544
+ ? textEntry(tile)
545
+ : undefined;
444
546
  }
445
- const list = `tiles=[${nextEntries.map((e) => `"${e}"`).join(", ")}]`;
446
- // The `## artifact` tag must stay on ONE line or the package fails to
447
- // compile, so the array is replaced in place rather than reformatted.
448
- const rewritten = lines[artifactAt].replace(
449
- /tiles\s*=\s*\[[\s\S]*?\]/,
450
- list,
547
+ return (
548
+ byKey.get(`${tile.source}->${tile.name}`) ??
549
+ (isNew ? `"${tile.source} -> ${tile.name}"` : undefined)
451
550
  );
452
- if (rewritten !== lines[artifactAt])
453
- edits.push({ ...wholeLine(artifactAt), text: `${rewritten}\n` });
551
+ });
552
+ if (nextEntries.some((entry) => entry === undefined)) {
553
+ return {
554
+ ok: false,
555
+ reason:
556
+ "A tile in the new order is not one the `## artifact` tag names.",
557
+ };
454
558
  }
559
+ // A `## artifact` line must stay on ONE line or the package fails to
560
+ // compile, so the array is replaced in place rather than reformatted; a
561
+ // `##|` block keeps whatever line layout its array was written in.
562
+ const keyAt = line.slice(0, list.open).search(/tiles\s*=\s*$/);
563
+ const rewritten = `${line.slice(0, keyAt)}tiles=[${arrayBody(line, list, nextEntries)}]${line.slice(list.close + 1)}`;
564
+ if (rewritten !== line)
565
+ edits.push({ ...tagExtent(wholeLine, tag), text: `${rewritten}\n` });
455
566
  return undefined;
456
567
  }
457
568
 
569
+ /** The whole lines a tag's text occupies; a block's closer is not part of its text. */
570
+ function tagExtent(
571
+ wholeLine: (line: number) => { start: number; end: number },
572
+ tag: ArtifactTag,
573
+ ) {
574
+ return {
575
+ start: wholeLine(tag.from).start,
576
+ end: wholeLine(tag.block ? tag.to - 1 : tag.from).end,
577
+ };
578
+ }
579
+
580
+ /** The text between a list's brackets for `entries`, spaced as the list was: a multi-line list keeps its lead, separator and tail. */
581
+ function arrayBody(
582
+ line: string,
583
+ list: NonNullable<ReturnType<typeof readTileList>>,
584
+ entries: string[],
585
+ ): string {
586
+ const first = list.entries[0];
587
+ const last = list.entries[list.entries.length - 1];
588
+ if (!first || !/\n/.test(line.slice(list.open, list.close)))
589
+ return entries.join(", ");
590
+ const lead = line.slice(list.open + 1, first.span.start);
591
+ const tail = line.slice(last.span.end, list.close);
592
+ const indent = lead.slice(lead.lastIndexOf("\n"));
593
+ const separator =
594
+ list.entries.length > 1
595
+ ? line.slice(first.span.end, list.entries[1].span.start)
596
+ : `,${indent.startsWith("\n") ? indent : " "}`;
597
+ return `${lead}${entries.join(separator)}${tail}`;
598
+ }
599
+
458
600
  /**
459
601
  * `line` without one property of the artifact tag's own braces: spelled with
460
602
  * any spacing round the `=`, and never matched inside a quoted string or a
@@ -533,32 +675,35 @@ function endOfString(line: string, open: number): number {
533
675
  function planSettings(ctx: SpliceContext): SpliceFailure | undefined {
534
676
  const { lines, wholeLine, current, next, edits } = ctx;
535
677
  // THE PAGE'S OWN SETTINGS. Title, autorun and starting values are
536
- // properties on the one-line `## artifact { … }` tag; the grid width is the
537
- // `dashboard { columns=N }` beside it; the description is the run of `##"`
538
- // lines above. Each is patched in place on its own line, so the tag stays
539
- // on one line — the package fails to compile otherwise — and a property
678
+ // properties on the `## artifact { … }` tag (one line, or a `##|` block);
679
+ // the grid width is the `dashboard { columns=N }` beside it; the description is the run of `##"`
680
+ // lines above. Each is patched in place, so a one-line tag stays one line
681
+ // — the package fails to compile otherwise — and a property
540
682
  // the file spells its own way keeps that spelling when it did not change.
541
683
  if (
684
+ kindOf(current) !== kindOf(next) ||
542
685
  current.title !== next.title ||
543
686
  current.autorun !== next.autorun ||
544
687
  current.columns !== next.columns ||
545
688
  canonical(current.startingGivens) !== canonical(next.startingGivens)
546
689
  ) {
547
- const artifactAt = artifactLine(lines);
548
- if (artifactAt < 0) {
690
+ const tag = artifactTag(lines);
691
+ if (!tag) {
549
692
  return {
550
693
  ok: false,
551
694
  reason:
552
695
  "Could not find the `## artifact` tag to change the page's settings.",
553
696
  };
554
697
  }
555
- // Whatever the reorder wrote to this line is the text to patch further.
698
+ const extent = tagExtent(wholeLine, tag);
699
+ // Whatever the reorder wrote to this tag is the text to patch further.
556
700
  const already = edits.find(
557
- (edit) =>
558
- edit.start === wholeLine(artifactAt).start &&
559
- edit.end === wholeLine(artifactAt).end,
701
+ (edit) => edit.start === extent.start && edit.end === extent.end,
560
702
  );
561
- let line = already ? already.text.replace(/\n$/, "") : lines[artifactAt];
703
+ let line = already ? already.text.replace(/\n$/, "") : tag.text;
704
+ // Depth-aware, since a text tile's own `kind=text` sits inside the tag.
705
+ if (kindOf(current) !== kindOf(next))
706
+ line = removeArtifactProperty(line, "kind");
562
707
  // The artifact tag's braces: everything up to the matching `}`.
563
708
  const open = line.indexOf("artifact");
564
709
  const braceOpen = line.indexOf("{", open);
@@ -578,14 +723,37 @@ function planSettings(ctx: SpliceContext): SpliceFailure | undefined {
578
723
  };
579
724
  }
580
725
  let inner = line.slice(braceOpen + 1, braceClose);
726
+ // A block puts each property on a line of its own, as its array is.
727
+ const lineBreak = tag.block
728
+ ? `\n${/\n([ \t]+)\S/.exec(inner)?.[1] ?? " "}`
729
+ : " ";
730
+ const append = (property: string) =>
731
+ tag.block
732
+ ? `${inner.trimEnd()}${lineBreak}${property}\n`
733
+ : `${inner.trimEnd()} ${property} `;
581
734
  const setProperty = (key: string, value: string | undefined) => {
582
735
  const re = new RegExp(
583
- `\\s*\\b${key}=(?:"(?:[^"\\\\]|\\\\.)*"|[^\\s}]+)`,
736
+ `${tag.block ? "[ \\t]*" : "\\s*"}\\b${key}=(?:"(?:[^"\\\\]|\\\\.)*"|[^\\s}]+)`,
584
737
  );
585
- if (value === undefined) inner = inner.replace(re, "");
586
- else if (re.test(inner)) inner = inner.replace(re, ` ${key}=${value}`);
587
- else inner = `${inner.replace(/\s+$/, "")} ${key}=${value} `;
738
+ if (value === undefined) {
739
+ const own = new RegExp(`\n${re.source}[ \\t]*(?=\n)`);
740
+ inner = inner.replace(tag.block && own.test(inner) ? own : re, "");
741
+ } else if (re.test(inner))
742
+ inner = inner.replace(
743
+ re,
744
+ (hit) =>
745
+ `${tag.block ? hit.slice(0, hit.length - hit.trimStart().length) : " "}${key}=${value}`,
746
+ );
747
+ else inner = append(`${key}=${value}`);
588
748
  };
749
+ if (kindOf(current) !== kindOf(next) && kindOf(next) === "notebook")
750
+ inner = append("kind=notebook");
751
+ // The server reads an untagged file under notebooks/ as a notebook, so a dashboard there must say so.
752
+ else if (
753
+ kindOf(current) !== kindOf(next) &&
754
+ ctx.modelPath?.startsWith("notebooks/")
755
+ )
756
+ inner = append("kind=dashboard");
589
757
  if (current.title !== next.title)
590
758
  setProperty("title", next.title ? quoted(next.title) : undefined);
591
759
  if (current.autorun !== next.autorun)
@@ -602,12 +770,16 @@ function planSettings(ctx: SpliceContext): SpliceFailure | undefined {
602
770
  // string's text — `CATEGORY="Jeans"` reads as `Jeans`, which is
603
771
  // what the document holds and what is written back here.
604
772
  if (entries.length > 0)
605
- inner = `${inner.replace(/\s+$/, "")} givens { ${entries
606
- .map(([k, v]) => `${k}=${quoted(v)}`)
607
- .join(" ")} }`;
773
+ inner = append(
774
+ `givens { ${entries.map(([k, v]) => `${k}=${quoted(v)}`).join(" ")} }`,
775
+ );
776
+ }
777
+ if (tag.block) {
778
+ line = `${line.slice(0, braceOpen + 1)}${inner}${line.slice(braceClose)}`;
779
+ } else {
780
+ inner = inner.replace(/\s{2,}/g, " ");
781
+ line = `${line.slice(0, braceOpen + 1)}${inner.startsWith(" ") ? inner : ` ${inner}`}${inner.endsWith(" ") ? "" : " "}${line.slice(braceClose)}`;
608
782
  }
609
- inner = inner.replace(/\s{2,}/g, " ");
610
- line = `${line.slice(0, braceOpen + 1)}${inner.startsWith(" ") ? inner : ` ${inner}`}${inner.endsWith(" ") ? "" : " "}${line.slice(braceClose)}`;
611
783
  if (current.columns !== next.columns) {
612
784
  // The deprecated alias would otherwise sit beside the new width and conflict with it.
613
785
  line = removeArtifactProperty(line, "dashboard_columns");
@@ -616,7 +788,7 @@ function planSettings(ctx: SpliceContext): SpliceFailure | undefined {
616
788
  line = `${line.trimEnd()} dashboard { columns=${next.columns} }`;
617
789
  }
618
790
  if (already) already.text = `${line}\n`;
619
- else edits.push({ ...wholeLine(artifactAt), text: `${line}\n` });
791
+ else edits.push({ ...extent, text: `${line}\n` });
620
792
  }
621
793
  if (current.description !== next.description) {
622
794
  // Written above the tag, where the server reads it. A description read
@@ -630,7 +802,7 @@ function planSettings(ctx: SpliceContext): SpliceFailure | undefined {
630
802
  "The description is written in a `##|\"` block, which the builder cannot edit in place. Change it in the file's text.",
631
803
  };
632
804
  }
633
- const text = (next.description ?? "")
805
+ const text = trimDescription(next.description ?? "")
634
806
  .split("\n")
635
807
  .map((para) => (para.trim() === "" ? '##"' : `##" ${para.trim()}`))
636
808
  .join("\n");
@@ -824,6 +996,100 @@ function planGivens(ctx: SpliceContext): SpliceFailure | undefined {
824
996
  return undefined;
825
997
  }
826
998
 
999
+ /** `import { a, b } from "../model.malloy"`, the one-line spelling the builder writes. */
1000
+ const importStatement = (names: string[], from: string) =>
1001
+ `import { ${names.join(", ")} } from ${quoted(from)}`;
1002
+
1003
+ /**
1004
+ * IMPORTS. Only a `{ names }` import is the builder's to edit: a name is added
1005
+ * to the statement for its file (or a new statement follows the last import),
1006
+ * a name taken off rewrites it, and the last name takes the statement. A bare
1007
+ * `import "…"` brings in a whole file's declarations and is never touched, and
1008
+ * a name a source or tile still reads cannot go.
1009
+ */
1010
+ function planImports(ctx: SpliceContext): SpliceFailure | undefined {
1011
+ const { parsed, current, next, edits, wholeLine } = ctx;
1012
+ const bare = (document: DashboardDocument) =>
1013
+ canonical(
1014
+ document.imports
1015
+ .flatMap((i) => (i.kind === "all" ? [i.from] : []))
1016
+ .sort(),
1017
+ );
1018
+ if (bare(current) !== bare(next)) {
1019
+ return {
1020
+ ok: false,
1021
+ reason: "A whole-file `import` cannot be changed here.",
1022
+ };
1023
+ }
1024
+ if (canonical(current.imports) === canonical(next.imports)) return undefined;
1025
+
1026
+ const wanted = next.imports.flatMap((i) =>
1027
+ i.kind === "names" ? [{ ...i, claimed: false }] : [],
1028
+ );
1029
+ const inUse = new Set([
1030
+ ...next.sources.map((s) => s.base),
1031
+ ...next.tiles.filter(isQueryTile).map((t) => t.source),
1032
+ ]);
1033
+ const written = parsed.imports.map((statement, index) => ({
1034
+ statement,
1035
+ entry: current.imports[index],
1036
+ }));
1037
+ for (const { statement, entry } of written) {
1038
+ if (!entry || entry.kind !== "names") continue;
1039
+ const keep = wanted.find((w) => !w.claimed && w.from === entry.from);
1040
+ if (keep) keep.claimed = true;
1041
+ const names = keep?.names ?? [];
1042
+ const dropped = entry.names.filter((n) => !names.includes(n));
1043
+ const stuck = dropped.find((n) => inUse.has(n));
1044
+ if (stuck !== undefined) {
1045
+ return {
1046
+ ok: false,
1047
+ reason: `\`${stuck}\` is still read by a tile, so its import cannot be removed.`,
1048
+ };
1049
+ }
1050
+ if (canonical(names) === canonical(entry.names)) continue;
1051
+ const cut =
1052
+ names.length === 0
1053
+ ? statementCut(parsed, statement.statement)
1054
+ : statement.statement;
1055
+ const lost = parsed.commentIn(cut);
1056
+ if (lost) {
1057
+ return {
1058
+ ok: false,
1059
+ reason:
1060
+ `Changing this import would also remove the comment inside it ` +
1061
+ `(\`${parsed.text.slice(lost.start, lost.end).trim()}\`), so ` +
1062
+ `nothing was written. Delete it in the file first.`,
1063
+ };
1064
+ }
1065
+ edits.push({
1066
+ ...cut,
1067
+ text: names.length === 0 ? "" : importStatement(names, entry.from),
1068
+ });
1069
+ }
1070
+
1071
+ const added = wanted.filter((w) => !w.claimed);
1072
+ if (added.length > 0) {
1073
+ const last = parsed.imports.at(-1);
1074
+ if (!last) {
1075
+ return {
1076
+ ok: false,
1077
+ reason:
1078
+ "This file has no `import` to put a source beside. Import its first source in the file.",
1079
+ };
1080
+ }
1081
+ const at = wholeLine(lineOf(parsed, last.statement.end - 1)).end;
1082
+ edits.push({
1083
+ start: at,
1084
+ end: at,
1085
+ text: added
1086
+ .map((w) => `${importStatement(w.names, w.from)}\n`)
1087
+ .join(""),
1088
+ });
1089
+ }
1090
+ return undefined;
1091
+ }
1092
+
827
1093
  function planDrills(ctx: SpliceContext): SpliceFailure | undefined {
828
1094
  const { lines, wholeLine, indentOf, current, next, edits, parsed } = ctx;
829
1095
  // DRILLS. A drill is one `# drill` tag on a dimension THIS FILE declares —
@@ -888,7 +1154,7 @@ function planRemovedTiles(ctx: SpliceContext): SpliceFailure | undefined {
888
1154
  // runs to its closing brace; a reference is one line. An inherited tile has
889
1155
  // nothing here to remove — its entry left the artifact list above.
890
1156
  for (const tile of removedTiles) {
891
- if (tile.declaration.kind === "inherited") continue;
1157
+ if (isTextTile(tile) || tile.declaration.kind === "inherited") continue;
892
1158
  const view = viewOf(ctx, tile);
893
1159
  if (!view) {
894
1160
  return {
@@ -961,19 +1227,20 @@ function planAddedTiles(ctx: SpliceContext): SpliceFailure | undefined {
961
1227
  // ADDED TILES: a `view:` with its tags, inside the extension of the source
962
1228
  // the tile reads — before that extension's closing brace — or in a new
963
1229
  // extension after the last one, when the file has none for that source.
964
- const byExtension = new Map<string, DashboardTile[]>();
1230
+ const byExtension = new Map<string, QueryTile[]>();
965
1231
  for (const tile of addedTiles) {
1232
+ if (isTextTile(tile)) continue;
966
1233
  const list = byExtension.get(tile.source) ?? [];
967
1234
  list.push(tile);
968
1235
  byExtension.set(tile.source, list);
969
1236
  }
970
- const declarationOf = (tile: DashboardTile, indent: string) => {
1237
+ const declarationOf = (tile: QueryTile, indent: string) => {
971
1238
  const from =
972
1239
  tile.declaration.kind === "reference"
973
1240
  ? tile.declaration.from
974
1241
  : tile.name;
975
1242
  const bindings = (tile.filters ?? [])
976
- .map((f) => `where: ${f.field} ${f.op ?? "~"} $${f.given}`)
1243
+ .map((f) => `where: ${malloyPath(f.field)} ${f.op ?? "~"} $${f.given}`)
977
1244
  .join(", ");
978
1245
  return [
979
1246
  ...tagsFor(tile).map((tag) => `${indent}${tag}`),
@@ -1074,9 +1341,13 @@ function planTilePresentation(ctx: SpliceContext): SpliceFailure | undefined {
1074
1341
 
1075
1342
  for (const tile of next.tiles) {
1076
1343
  const was = currentByKey.get(tileKey(tile));
1077
- // Written whole above, tags and all.
1078
- if (was === undefined) continue;
1079
- if (canonical(was) === canonical(tile)) continue;
1344
+ // Written whole above, tags and all; a text tile has no declaration to retag.
1345
+ if (was === undefined || isTextTile(tile) || isTextTile(was)) continue;
1346
+ if (
1347
+ canonical(withoutDefaultChart(was)) ===
1348
+ canonical(withoutDefaultChart(tile))
1349
+ )
1350
+ continue;
1080
1351
 
1081
1352
  // Declared in the model, not here, so there is nothing in this file to
1082
1353
  // patch -- saying so beats writing a tag that would land on the wrong
@@ -1106,15 +1377,55 @@ function planTilePresentation(ctx: SpliceContext): SpliceFailure | undefined {
1106
1377
 
1107
1378
  const { tags } = blockAbove(parsed, lines, declLine);
1108
1379
  const indent = indentOf(declLine);
1109
- const wanted = tagsFor(tile);
1380
+ const wanted = tagsFor(tile, false);
1110
1381
  const wantedByKey = new Map(
1111
1382
  wanted.map((text) => [tagKey(text) ?? text, text]),
1112
1383
  );
1113
1384
  const seen = new Set<string>();
1114
1385
 
1386
+ // Only a changed chart touches a chart line, so a bare `# bar_chart` survives every other edit.
1387
+ const wantChart = writableChart(tile.chart);
1388
+ const chartChanged = chartOf(was) !== chartOf(tile);
1389
+ if (chartChanged) {
1390
+ const blockers = tags.filter((tag) => mentionsChartTag(tag.text));
1391
+ const ours = tags.filter((tag) => parseChartLine(tag.text));
1392
+ const stuck =
1393
+ was.chart === "custom"
1394
+ ? tags.filter(
1395
+ (tag) =>
1396
+ parseChartLine(tag.text) || mentionsChartTag(tag.text),
1397
+ )
1398
+ : blockers.length > 0
1399
+ ? blockers
1400
+ : ours.length > 1
1401
+ ? ours
1402
+ : [];
1403
+ if (stuck.length > 0) {
1404
+ return {
1405
+ ok: false,
1406
+ reason:
1407
+ `\`${tile.source} -> ${tile.name}\` has a chart line the builder does not ` +
1408
+ `model (${stuck.map((tag) => tag.text).join(" and ")}), so its chart ` +
1409
+ `cannot be changed here.`,
1410
+ };
1411
+ }
1412
+ }
1413
+ let chartPlaced = false;
1414
+
1115
1415
  // Existing tag lines are patched or removed IN PLACE, so anything else in
1116
1416
  // the block — a comment explaining the tile — keeps its position.
1117
1417
  for (const tag of tags) {
1418
+ if (chartChanged && parseChartLine(tag.text)) {
1419
+ if (wantChart === undefined)
1420
+ edits.push({ ...wholeLine(tag.line), text: "" });
1421
+ else if (tag.text !== chartLineText(wantChart, tile.chartCarried))
1422
+ edits.push({
1423
+ ...wholeLine(tag.line),
1424
+ text: `${indent}${chartLineText(wantChart, tile.chartCarried)}\n`,
1425
+ });
1426
+ chartPlaced = true;
1427
+ continue;
1428
+ }
1118
1429
  const key = tagKey(tag.text);
1119
1430
  // Not a property this document models: not ours to touch.
1120
1431
  if (key === undefined || !MODELLED_TAG_KEYS.has(key)) continue;
@@ -1132,6 +1443,8 @@ function planTilePresentation(ctx: SpliceContext): SpliceFailure | undefined {
1132
1443
  // New tags go immediately above the declaration, which is where a reader
1133
1444
  // looks for them and where `blockAbove` will find them again.
1134
1445
  const added = wanted.filter((text) => !seen.has(tagKey(text) ?? text));
1446
+ if (chartChanged && wantChart !== undefined && !chartPlaced)
1447
+ added.push(chartLineText(wantChart, tile.chartCarried));
1135
1448
  if (added.length > 0) {
1136
1449
  const at = starts[declLine];
1137
1450
  edits.push({
@@ -1174,12 +1487,293 @@ function planTilePresentation(ctx: SpliceContext): SpliceFailure | undefined {
1174
1487
  return undefined;
1175
1488
  }
1176
1489
 
1490
+ /** A tile's chart as the writer compares it: no line (absent or `default`) is one state. */
1491
+ const chartOf = (tile: QueryTile) =>
1492
+ tile.chart === "default" ? undefined : tile.chart;
1493
+
1494
+ /** The tile as the writer compares it: "default" is no line, and `chartLines` and `chartCarried` are not part of what is asked for. */
1495
+ const withoutDefaultChart = (tile: QueryTile): QueryTile => {
1496
+ const { chartLines: _lines, chartCarried: _carried, ...rest } = tile;
1497
+ if (rest.chart !== "default") return rest;
1498
+ const { chart: _chart, ...bare } = rest;
1499
+ return bare;
1500
+ };
1501
+
1502
+ /** A matched tile with no `chart` stated is unchanged, so only an explicit "default" removes a line. */
1503
+ function keepUnstatedCharts(
1504
+ current: DashboardDocument,
1505
+ next: DashboardDocument,
1506
+ ): DashboardDocument {
1507
+ const was = new Map(current.tiles.map((t) => [tileKey(t), t]));
1508
+ return {
1509
+ ...next,
1510
+ tiles: next.tiles.map((tile) => {
1511
+ const before = was.get(tileKey(tile));
1512
+ return isQueryTile(tile) &&
1513
+ tile.chart === undefined &&
1514
+ before &&
1515
+ isQueryTile(before) &&
1516
+ before.chart !== undefined
1517
+ ? { ...tile, chart: before.chart }
1518
+ : tile;
1519
+ }),
1520
+ };
1521
+ }
1522
+
1523
+ /** Why a text tile's markdown cannot be written into a block, or undefined when it can: the writer's refusals, for an editor to show live. */
1524
+ export function markdownProblem(markdown: string): string | undefined {
1525
+ if (markdown.includes("\r"))
1526
+ return "Text uses plain line breaks; a carriage return cannot be written.";
1527
+ if (/^\|##/m.test(markdown))
1528
+ return "A line starting with `|##` would close the text early. Indent that line or reword it.";
1529
+ return undefined;
1530
+ }
1531
+
1532
+ /** Why `tile` cannot be written, or undefined; only what changed from `before` is judged, so an existing odd value does not block unrelated edits. */
1533
+ function textTileProblem(
1534
+ tile: TextTile,
1535
+ before: TextTile | undefined,
1536
+ seen: Set<string>,
1537
+ ): string | undefined {
1538
+ if (seen.has(tile.name))
1539
+ return `Two text tiles are named \`${tile.name}\`, so they could not be told apart.`;
1540
+ seen.add(tile.name);
1541
+ if (before === undefined && !isIdentifier(tile.name))
1542
+ return `The text tile name ${JSON.stringify(tile.name)} must be a bare word.`;
1543
+ if (before === undefined || tile.markdown !== before.markdown) {
1544
+ const problem = markdownProblem(tile.markdown);
1545
+ if (problem) return problem;
1546
+ }
1547
+ if (
1548
+ tile.colspan !== undefined &&
1549
+ tile.colspan !== before?.colspan &&
1550
+ !(Number.isInteger(tile.colspan) && tile.colspan >= 1)
1551
+ )
1552
+ return "A text tile's width is a whole number of columns, 1 or more.";
1553
+ return undefined;
1554
+ }
1555
+
1556
+ /** The block a text tile's prose is written in. */
1557
+ const textBlockText = (tile: TextTile) =>
1558
+ `##|(markdown) ${tile.name}\n${tile.markdown === "" ? "" : `${tile.markdown}\n`}|##\n`;
1559
+
1560
+ function planTextBlocks(ctx: SpliceContext): SpliceFailure | undefined {
1561
+ const { sourceText, lines, wholeLine, current, next, parsed, edits } = ctx;
1562
+ // TEXT TILES: the `##|(markdown) name` block is the tile's body, so adding
1563
+ // one writes a block, editing one replaces its block, and removing one takes
1564
+ // the block out; the `tiles=[…]` entry was already handled with the order.
1565
+ const wasText = new Map(
1566
+ current.tiles.filter(isTextTile).map((tile) => [tile.name, tile]),
1567
+ );
1568
+ const nowText = next.tiles.filter(isTextTile);
1569
+ const blockOf = (name: string) =>
1570
+ parsed.textBlocks.find((block) => block.name === name);
1571
+ const nowNames = new Set(nowText.map((tile) => tile.name));
1572
+
1573
+ for (const name of wasText.keys()) {
1574
+ const block = nowNames.has(name) ? undefined : blockOf(name);
1575
+ if (!block) continue;
1576
+ const last = lineOf(parsed, block.span.end - 1);
1577
+ edits.push({ ...block.span, text: "" });
1578
+ const after = wholeLine(last + 1);
1579
+ const blankBefore =
1580
+ block.line === 0 || lines[block.line - 1].trim() === "";
1581
+ // The blank line after goes too when one already precedes, or two separators meet.
1582
+ if (
1583
+ after.end > after.start &&
1584
+ lines[last + 1].trim() === "" &&
1585
+ blankBefore
1586
+ )
1587
+ edits.push({ ...after, text: "" });
1588
+ // A last block takes the blank line that set it off.
1589
+ else if (
1590
+ block.line > 0 &&
1591
+ blankBefore &&
1592
+ sourceText.slice(block.span.end).trim() === ""
1593
+ )
1594
+ edits.push({ ...wholeLine(block.line - 1), text: "" });
1595
+ }
1596
+
1597
+ const fresh: string[] = [];
1598
+ for (const tile of nowText) {
1599
+ const was = wasText.get(tile.name);
1600
+ const block = blockOf(tile.name);
1601
+ if (was === undefined) {
1602
+ if (block) {
1603
+ return {
1604
+ ok: false,
1605
+ reason: `A block named \`${tile.name}\` is already in this file, so a new text tile cannot take that name.`,
1606
+ };
1607
+ }
1608
+ fresh.push(textBlockText(tile));
1609
+ } else if (was.markdown !== tile.markdown) {
1610
+ if (block) edits.push({ ...block.span, text: textBlockText(tile) });
1611
+ else fresh.push(textBlockText(tile));
1612
+ }
1613
+ }
1614
+ if (fresh.length > 0) {
1615
+ // Prose blocks group together ahead of the `<source>_tiles` extension, in tile order.
1616
+ const kept = parsed.textBlocks.filter(
1617
+ (block) => block.name === undefined || nowNames.has(block.name),
1618
+ );
1619
+ const lastKept = kept[kept.length - 1];
1620
+ const extension = parsed.sources.find((s) => s.name.endsWith("_tiles"));
1621
+ if (lastKept) {
1622
+ const at = lastKept.span.end;
1623
+ const after = sourceText.slice(at);
1624
+ edits.push({
1625
+ start: at,
1626
+ end: at,
1627
+ text: `\n${fresh.join("\n")}${after === "" || after.startsWith("\n") ? "" : "\n"}`,
1628
+ });
1629
+ return undefined;
1630
+ }
1631
+ if (extension) {
1632
+ const at = ctx.starts[parsed.blockStart(extension.line)];
1633
+ const blankBefore =
1634
+ at === 0 || sourceText.slice(0, at).endsWith("\n\n");
1635
+ edits.push({
1636
+ start: at,
1637
+ end: at,
1638
+ text: `${blankBefore ? "" : "\n"}${fresh.join("\n")}\n`,
1639
+ });
1640
+ return undefined;
1641
+ }
1642
+ const at = sourceText.length;
1643
+ const lead =
1644
+ sourceText === "" || sourceText.endsWith("\n\n")
1645
+ ? ""
1646
+ : sourceText.endsWith("\n")
1647
+ ? "\n"
1648
+ : "\n\n";
1649
+ edits.push({ start: at, end: at, text: lead + fresh.join("\n") });
1650
+ }
1651
+ return undefined;
1652
+ }
1653
+
1654
+ /** A name the writer emits unquoted, or why it cannot be written. */
1655
+ const nameProblem = (name: string, bare = isBareName) =>
1656
+ bare(name)
1657
+ ? undefined
1658
+ : `The name ${JSON.stringify(name)} cannot be written as a Malloy name.`;
1659
+
1660
+ /** Why `next` holds a chart, name or annotation text the writer must not emit; only what changed is judged, so an existing odd string does not block unrelated edits. */
1661
+ function unwritable(
1662
+ current: DashboardDocument,
1663
+ next: DashboardDocument,
1664
+ ): string | undefined {
1665
+ const was = new Map(current.tiles.map((t) => [tileKey(t), t]));
1666
+ if (
1667
+ kindOf(next) === "notebook" &&
1668
+ next.columns !== undefined &&
1669
+ (kindOf(current) !== "notebook" || next.columns !== current.columns)
1670
+ )
1671
+ return "A notebook is one column, so its width is not written. Clear the width when switching a dashboard to a notebook.";
1672
+ const textNames = new Set<string>();
1673
+ for (const tile of next.tiles) {
1674
+ const before = was.get(tileKey(tile));
1675
+ if (isTextTile(tile)) {
1676
+ const problem = textTileProblem(
1677
+ tile,
1678
+ before && isTextTile(before) ? before : undefined,
1679
+ textNames,
1680
+ );
1681
+ if (problem) return problem;
1682
+ continue;
1683
+ }
1684
+ const prior = before && isQueryTile(before) ? before : undefined;
1685
+ if (before && !prior) continue;
1686
+ const chart = tile.chart;
1687
+ if (
1688
+ chart !== undefined &&
1689
+ chart !== "default" &&
1690
+ chart !== "none" &&
1691
+ !isChartPick(chart) &&
1692
+ !(chart === "custom" && prior?.chart === "custom")
1693
+ )
1694
+ return `"${String(chart)}" is not a chart this editor writes.`;
1695
+ const filtersBefore = new Set(prior?.filters?.map((f) => f.field));
1696
+ for (const f of tile.filters ?? []) {
1697
+ if (!filtersBefore.has(f.field) && /[\r\n]/.test(f.field))
1698
+ return "A filter field is one line.";
1699
+ }
1700
+ if (before === undefined) {
1701
+ const names = [tile.name, tile.source];
1702
+ if (tile.declaration.kind === "reference")
1703
+ names.push(tile.declaration.from);
1704
+ for (const name of names) {
1705
+ const problem = nameProblem(name);
1706
+ if (problem) return problem;
1707
+ }
1708
+ }
1709
+ for (const key of ["label", "subtitle"] as const) {
1710
+ const text = tile[key];
1711
+ if (text === undefined || text === prior?.[key]) continue;
1712
+ const problem = annotationTextProblem(`tile ${key}`, text);
1713
+ if (problem) return problem;
1714
+ }
1715
+ }
1716
+ const knownSources = new Set(current.sources.map((s) => s.name));
1717
+ for (const source of next.sources) {
1718
+ if (knownSources.has(source.name)) continue;
1719
+ for (const name of [source.name, source.base]) {
1720
+ const problem = nameProblem(name);
1721
+ if (problem) return problem;
1722
+ }
1723
+ }
1724
+ if (next.description !== current.description) {
1725
+ for (const line of (next.description ?? "").split(/\r?\n/)) {
1726
+ const problem = annotationTextProblem("description line", line);
1727
+ if (problem) return problem;
1728
+ }
1729
+ }
1730
+ if (next.title !== current.title) {
1731
+ const problem = annotationTextProblem("title", next.title);
1732
+ if (problem) return problem;
1733
+ }
1734
+ const givens = new Map((current.localGivens ?? []).map((g) => [g.name, g]));
1735
+ for (const given of next.localGivens ?? []) {
1736
+ const was = givens.get(given.name);
1737
+ if (was === undefined) {
1738
+ const problem = nameProblem(given.name, isStrictName);
1739
+ if (problem) return problem;
1740
+ }
1741
+ const source = given.suggest?.source;
1742
+ if (source !== undefined && source !== was?.suggest?.source) {
1743
+ const problem = nameProblem(source);
1744
+ if (problem) return `The suggest source is not a name. ${problem}`;
1745
+ }
1746
+ for (const key of ["query", "dimension"] as const) {
1747
+ const text = given.suggest?.[key];
1748
+ if (text === undefined || text === was?.suggest?.[key]) continue;
1749
+ const problem = annotationTextProblem(`suggest ${key}`, text);
1750
+ if (problem) return problem;
1751
+ }
1752
+ for (const key of ["label", "description"] as const) {
1753
+ const text = given[key];
1754
+ if (text === undefined || text === givens.get(given.name)?.[key])
1755
+ continue;
1756
+ const problem = annotationTextProblem(`given ${key}`, text);
1757
+ if (problem) return problem;
1758
+ }
1759
+ }
1760
+ for (const [name, value] of Object.entries(next.startingGivens ?? {})) {
1761
+ if (value === current.startingGivens?.[name]) continue;
1762
+ const problem = annotationTextProblem(
1763
+ `starting value for ${name}`,
1764
+ value,
1765
+ );
1766
+ if (problem) return problem;
1767
+ }
1768
+ return undefined;
1769
+ }
1770
+
1177
1771
  /** The 0-based line an offset falls on. */
1178
1772
  const lineOf = (parsed: ParsedMalloy, offset: number): number =>
1179
1773
  parsed.lineStarts.findLastIndex((at) => at <= offset);
1180
1774
 
1181
1775
  /** The parsed declaration a tile names, if this file declares it. */
1182
- function viewOf(ctx: SpliceContext, tile: DashboardTile): TreeView | undefined {
1776
+ function viewOf(ctx: SpliceContext, tile: QueryTile): TreeView | undefined {
1183
1777
  return ctx.parsed.sources
1184
1778
  .find((source) => source.name === tile.source)
1185
1779
  ?.views.find((view) => view.name === tile.name);
@@ -1218,7 +1812,7 @@ function collisionRefusal(tileName: string, given: string): SpliceFailure {
1218
1812
  }
1219
1813
 
1220
1814
  const bindingText = (f: { field: string; given: string; op?: string }) =>
1221
- `where: ${f.field} ${f.op ?? "~"} $${f.given}`;
1815
+ `where: ${malloyPath(f.field)} ${f.op ?? "~"} $${f.given}`;
1222
1816
 
1223
1817
  /**
1224
1818
  * THE RULE the three removal paths obey: a comment goes only with a
@@ -1228,8 +1822,7 @@ const bindingText = (f: { field: string; given: string; op?: string }) =>
1228
1822
  * is nobody's to strand either. Both refuse, and say which comment.
1229
1823
  *
1230
1824
  * Removing a TILE is the other case, and the one exception: the declaration
1231
- * itself is what was asked for, so its own comments go with it, and the builder
1232
- * shows that diff before a structural save.
1825
+ * itself is what was asked for, so its own comments go with it.
1233
1826
  */
1234
1827
  function commentRefusal(
1235
1828
  tileName: string,
@@ -1330,7 +1923,7 @@ function statementCut(parsed: ParsedMalloy, span: Span): Span {
1330
1923
  */
1331
1924
  function planStageFilters(
1332
1925
  ctx: SpliceContext,
1333
- tile: DashboardTile,
1926
+ tile: QueryTile,
1334
1927
  stage: TreeStage,
1335
1928
  ): SpliceFailure | undefined {
1336
1929
  const { parsed, edits } = ctx;
@@ -1421,7 +2014,7 @@ function planStageFilters(
1421
2014
  */
1422
2015
  function planReferenceFilters(
1423
2016
  ctx: SpliceContext,
1424
- tile: DashboardTile,
2017
+ tile: QueryTile,
1425
2018
  view: TreeView,
1426
2019
  ): SpliceFailure | undefined {
1427
2020
  if (view.body.kind !== "reference") return undefined;
@@ -1472,11 +2065,37 @@ function planReferenceFilters(
1472
2065
  return planStageFilters(ctx, tile, refinement);
1473
2066
  }
1474
2067
 
2068
+ export interface SpliceOptions {
2069
+ /** Lets `requested.kind` differ from the file's: the one edit that switches a dashboard to a notebook or back. */
2070
+ changeKind?: boolean;
2071
+ /** The file's path within the package; a dashboard under `notebooks/` is tagged `kind=dashboard` rather than left untagged. */
2072
+ modelPath?: string;
2073
+ }
2074
+
1475
2075
  export async function spliceDashboardDocument(
1476
2076
  sourceText: string,
1477
- next: DashboardDocument,
2077
+ requested: DashboardDocument,
2078
+ options: SpliceOptions = {},
2079
+ ): Promise<SpliceResult> {
2080
+ // The planners split and join on `\n`, so a wholly CRLF file is edited as LF and written back as CRLF.
2081
+ const crlf = sourceText.includes("\r\n") && !/(?<!\r)\n/.test(sourceText);
2082
+ if (!crlf) return spliceLines(sourceText, requested, options);
2083
+ const result = await spliceLines(
2084
+ sourceText.replace(/\r\n/g, "\n"),
2085
+ requested,
2086
+ options,
2087
+ );
2088
+ return spliceFailed(result)
2089
+ ? result
2090
+ : { ...result, source: result.source.replace(/\n/g, "\r\n") };
2091
+ }
2092
+
2093
+ async function spliceLines(
2094
+ sourceText: string,
2095
+ requested: DashboardDocument,
2096
+ options: SpliceOptions,
1478
2097
  ): Promise<SpliceResult> {
1479
- const before = await readDashboardDocument(sourceText);
2098
+ const before = await readDashboardDocument(sourceText, options.modelPath);
1480
2099
  if (readFailed(before)) {
1481
2100
  return {
1482
2101
  ok: false,
@@ -1484,8 +2103,11 @@ export async function spliceDashboardDocument(
1484
2103
  };
1485
2104
  }
1486
2105
  const current = before.document;
1487
- const shape = checkShape(current, next);
2106
+ const next = keepUnstatedCharts(current, requested);
2107
+ const shape = checkShape(current, next, options.changeKind === true);
1488
2108
  if ("reason" in shape) return shape;
2109
+ const problem = unwritable(current, next);
2110
+ if (problem) return { ok: false, reason: problem };
1489
2111
 
1490
2112
  const parse = await parseMalloy(sourceText);
1491
2113
  if (parseRefused(parse))
@@ -1514,6 +2136,9 @@ export async function spliceDashboardDocument(
1514
2136
  current,
1515
2137
  next,
1516
2138
  edits,
2139
+ ...(options.modelPath !== undefined
2140
+ ? { modelPath: options.modelPath }
2141
+ : {}),
1517
2142
  };
1518
2143
 
1519
2144
  // Each concern plans its own edits against the file as it stands; the
@@ -1522,11 +2147,13 @@ export async function spliceDashboardDocument(
1522
2147
  for (const plan of [
1523
2148
  planOrder,
1524
2149
  planSettings,
2150
+ planImports,
1525
2151
  planGivens,
1526
2152
  planDrills,
1527
2153
  planRemovedTiles,
1528
2154
  planAddedTiles,
1529
2155
  planTilePresentation,
2156
+ planTextBlocks,
1530
2157
  ]) {
1531
2158
  const failure = plan(ctx);
1532
2159
  if (failure) return failure;
@@ -1540,14 +2167,19 @@ export async function spliceDashboardDocument(
1540
2167
  // normalises its shape asks for no change, gets no edits, and would be told
1541
2168
  // its save did not produce what it asked for.
1542
2169
  const comparable = (document: DashboardDocument): DashboardDocument => {
1543
- const { drills, localGivens, ...rest } = document;
2170
+ const { drills, localGivens, kind, description, ...rest } = document;
1544
2171
  const tiles = document.tiles.map((tile) => {
1545
- if (tile.filters?.length) return tile;
2172
+ if (isTextTile(tile)) return tile;
2173
+ if (tile.filters?.length) return withoutDefaultChart(tile);
1546
2174
  const { filters: _filters, ...tileRest } = tile;
1547
- return tileRest as DashboardTile;
2175
+ return withoutDefaultChart(tileRest as QueryTile);
1548
2176
  });
1549
2177
  return {
1550
2178
  ...rest,
2179
+ ...(description === undefined
2180
+ ? {}
2181
+ : { description: trimDescription(description) }),
2182
+ ...(kind === "notebook" ? { kind } : {}),
1551
2183
  tiles,
1552
2184
  ...(drills?.length
1553
2185
  ? {
@@ -1608,7 +2240,7 @@ export async function spliceDashboardDocument(
1608
2240
  // The second gate. Read back what was actually written and compare it
1609
2241
  // against what was asked for. Comments survived because they were never
1610
2242
  // rewritten; correctness is established here rather than assumed.
1611
- const after = await readDashboardDocument(spliced);
2243
+ const after = await readDashboardDocument(spliced, options.modelPath);
1612
2244
  if (readFailed(after)) {
1613
2245
  return {
1614
2246
  ok: false,