@malloy-publisher/sdk 0.4.0 → 0.5.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 (72) hide show
  1. package/README.md +19 -0
  2. package/dist/{DocumentStorageProvider-CyOJ0hqf.es.js → DocumentStorage-B04sZ5Ie.es.js} +2307 -2334
  3. package/dist/{DocumentStorageProvider-DGPQEd_l.cjs.js → DocumentStorage-B_MMJ0Ot.cjs.js} +20 -20
  4. package/dist/{RenderedResult-BnPzJ9Jf.es.js → RenderedResult-BB7eokcf.es.js} +100 -80
  5. package/dist/RenderedResult-DVuGhatg.cjs.js +135 -0
  6. package/dist/ServerProvider-D-jjzfE5.cjs.js +1 -0
  7. package/dist/{ServerProvider-BWOEKg0O.es.js → ServerProvider-Do-GBvpn.es.js} +492 -481
  8. package/dist/builder/index.cjs.js +57 -52
  9. package/dist/builder/index.es.js +4421 -3738
  10. package/dist/client/api.d.ts +14 -1
  11. package/dist/client/index.cjs.js +1 -1
  12. package/dist/client/index.es.js +1 -1
  13. package/dist/components/Dashboard/TileCard.d.ts +7 -3
  14. package/dist/components/Dashboard/telemetry.d.ts +20 -8
  15. package/dist/components/DashboardBuilder/DashboardBuilder.d.ts +16 -4
  16. package/dist/components/DashboardBuilder/DashboardEditor.d.ts +31 -8
  17. package/dist/components/DashboardBuilder/controls.d.ts +8 -6
  18. package/dist/components/DashboardBuilder/document.d.ts +19 -5
  19. package/dist/components/DashboardBuilder/malloyText.d.ts +0 -30
  20. package/dist/components/DashboardBuilder/malloyTree.d.ts +232 -0
  21. package/dist/components/DashboardBuilder/preview.d.ts +17 -0
  22. package/dist/components/DashboardBuilder/readDocument.d.ts +23 -28
  23. package/dist/components/DashboardBuilder/spliceDocument.d.ts +12 -0
  24. package/dist/components/DocumentStorage/DocumentStorage.d.ts +69 -5
  25. package/dist/components/DocumentStorage/index.d.ts +1 -0
  26. package/dist/index.cjs.js +9 -9
  27. package/dist/index.es.js +508 -506
  28. package/dist/theme/resolveTheme.d.ts +1 -1
  29. package/dist/theme/types.d.ts +12 -2
  30. package/package.json +1 -1
  31. package/src/components/Dashboard/TileCard.tsx +8 -4
  32. package/src/components/Dashboard/telemetry.ts +20 -8
  33. package/src/components/DashboardBuilder/BuilderToolbar.tsx +4 -5
  34. package/src/components/DashboardBuilder/DashboardBuilder.tsx +21 -3
  35. package/src/components/DashboardBuilder/DashboardEditor.authoritative.spec.tsx +706 -0
  36. package/src/components/DashboardBuilder/DashboardEditor.resourceUri.spec.tsx +356 -0
  37. package/src/components/DashboardBuilder/DashboardEditor.tsx +468 -103
  38. package/src/components/DashboardBuilder/FilterDialog.tsx +19 -6
  39. package/src/components/DashboardBuilder/TileFrame.tsx +11 -2
  40. package/src/components/DashboardBuilder/TileMenu.tsx +6 -0
  41. package/src/components/DashboardBuilder/__test__/inventory.ts +367 -0
  42. package/src/components/DashboardBuilder/controls.spec.ts +53 -3
  43. package/src/components/DashboardBuilder/controls.ts +9 -7
  44. package/src/components/DashboardBuilder/document.ts +17 -5
  45. package/src/components/DashboardBuilder/invariants.spec.ts +297 -0
  46. package/src/components/DashboardBuilder/malloyText.spec.ts +27 -66
  47. package/src/components/DashboardBuilder/malloyText.ts +4 -109
  48. package/src/components/DashboardBuilder/malloyTree.spec.ts +362 -0
  49. package/src/components/DashboardBuilder/malloyTree.ts +954 -0
  50. package/src/components/DashboardBuilder/preview.spec.ts +18 -0
  51. package/src/components/DashboardBuilder/preview.ts +24 -6
  52. package/src/components/DashboardBuilder/readDocument.spec.ts +312 -21
  53. package/src/components/DashboardBuilder/readDocument.ts +144 -165
  54. package/src/components/DashboardBuilder/scannerShapes.spec.ts +550 -0
  55. package/src/components/DashboardBuilder/spliceDocument.spec.ts +955 -21
  56. package/src/components/DashboardBuilder/spliceDocument.ts +509 -119
  57. package/src/components/DashboardBuilder/statementExtent.spec.ts +606 -0
  58. package/src/components/DocumentStorage/BrowserDocumentStorage.ts +7 -6
  59. package/src/components/DocumentStorage/DocumentStorage.ts +78 -5
  60. package/src/components/DocumentStorage/index.ts +1 -0
  61. package/src/components/Package/Package.tsx +12 -7
  62. package/src/components/RenderedResult/RenderedResult.tsx +21 -1
  63. package/src/components/given/GivensPanel.tsx +15 -3
  64. package/src/theme/buildTableCssVars.spec.ts +3 -0
  65. package/src/theme/buildTableCssVars.ts +6 -0
  66. package/src/theme/defaults.ts +16 -12
  67. package/src/theme/resolveTheme.spec.ts +14 -7
  68. package/src/theme/resolveTheme.ts +14 -8
  69. package/src/theme/types.ts +12 -2
  70. package/tsconfig.spec.json +5 -1
  71. package/dist/RenderedResult-Dp22kZsQ.cjs.js +0 -115
  72. package/dist/ServerProvider-Cc489A3f.cjs.js +0 -1
@@ -164,6 +164,23 @@ function FieldPicker({
164
164
  );
165
165
  }
166
166
 
167
+ /**
168
+ * Why a tile cannot take a binding. A tile declared on its source and one
169
+ * declared HERE in a body with no single block for a `where:` are different
170
+ * situations, and saying "from the model" about the second one is untrue.
171
+ */
172
+ const unbindable = (tile: DashboardTile | undefined) =>
173
+ tile?.declaration.kind === "opaque"
174
+ ? {
175
+ label: "Not bindable",
176
+ reason: `Its body is ${tile.declaration.why}, so a filter has no single place to go.`,
177
+ }
178
+ : {
179
+ label: "From the model",
180
+ reason:
181
+ "Declared on its source, which this dashboard does not write.",
182
+ };
183
+
167
184
  export function FilterDialog({
168
185
  open,
169
186
  document,
@@ -502,18 +519,14 @@ export function FilterDialog({
502
519
  {!bindable[index] ? (
503
520
  <Tooltip
504
521
  title={
505
- tile.declaration.kind === "inherited"
506
- ? "Declared on its source, which this dashboard does not write."
507
- : "Its query is written out here rather than named, so a filter cannot be added to it."
522
+ unbindable(document.tiles[index]).reason
508
523
  }
509
524
  >
510
525
  <Typography
511
526
  variant="caption"
512
527
  sx={{ color: theme.tileTitle }}
513
528
  >
514
- {tile.declaration.kind === "inherited"
515
- ? "From the model"
516
- : "Inline query"}
529
+ {unbindable(document.tiles[index]).label}
517
530
  </Typography>
518
531
  </Tooltip>
519
532
  ) : (
@@ -132,7 +132,9 @@ export function TileFrame({
132
132
  // will respond to the pointer, told apart
133
133
  // from the ones that will not.
134
134
  "&:hover": {
135
- outlineColor: selected ? theme.drillLink : theme.border,
135
+ outlineColor: selected
136
+ ? theme.drillLink
137
+ : theme.cardBorder,
136
138
  boxShadow: "0 2px 10px rgba(0, 0, 0, 0.10)",
137
139
  },
138
140
  }}
@@ -333,7 +335,14 @@ export function GapTarget({ after }: { after: string }) {
333
335
  minHeight: 48,
334
336
  borderRadius: 1,
335
337
  border: `1px dashed ${theme.drillLink}`,
336
- bgcolor: isDropTarget ? theme.tile : "transparent",
338
+ // Tinted with the same hue as the dashed edge, so the fill
339
+ // and the border read as one affordance lighting up. It was
340
+ // `theme.tile`, the CARD colour, which is the one value
341
+ // guaranteed to match whatever this sits on: a near-no-op
342
+ // before the card went white, and an exact one after.
343
+ bgcolor: isDropTarget
344
+ ? `color-mix(in srgb, ${theme.drillLink} 12%, transparent)`
345
+ : "transparent",
337
346
  opacity: isDropTarget ? 0.95 : 0.4,
338
347
  transition: "opacity 120ms, background-color 120ms",
339
348
  }}
@@ -155,6 +155,12 @@ export function TileMenu({
155
155
  the model. It can still be moved.
156
156
  </Typography>
157
157
  )}
158
+ {draft?.declaration.kind === "opaque" && (
159
+ <Typography variant="body2" sx={{ color: theme.tileTitle }}>
160
+ Its body is {draft.declaration.why}, so a filter has no
161
+ single place to go. Everything else here is editable.
162
+ </Typography>
163
+ )}
158
164
  <Divider />
159
165
  <Stack direction="row" sx={{ justifyContent: "space-between" }}>
160
166
  {editable ? (
@@ -0,0 +1,367 @@
1
+ // Copyright (c) Credible Data Inc.
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * ONE ORACLE for the whole writer: an edit changes the declaration it names,
6
+ * and nothing else.
7
+ *
8
+ * Every defect this directory has shipped was a WRONGLY COMPUTED SPAN, and the
9
+ * two gates in `spliceDocument` cannot see one: the syntax check only asks
10
+ * whether the result parses, and the read-back check compares the projection,
11
+ * which holds neither comments nor the tags the document does not model. Each
12
+ * miss got a hand-written spec of its own, and the next sibling of the same
13
+ * shape went out anyway.
14
+ *
15
+ * So this takes an inventory of a file from a FRESH PARSE, before and after,
16
+ * and {@link diffInventories} says what moved. Never from the writer's own
17
+ * spans: an oracle phrased in the numbers the writer computed inherits the
18
+ * mistake and certifies it. And never "the bytes outside the planned edits are
19
+ * unchanged", which is vacuous -- the writer applies exactly the edits it
20
+ * planned, so it can never fail that.
21
+ */
22
+
23
+ import { parseMalloy, parseRefused, type Span } from "../malloyTree";
24
+
25
+ /** Everything about a declaration that an edit elsewhere must not disturb. */
26
+ export interface Declaration {
27
+ /**
28
+ * The `#` lines that annotate it, in order, each MODELLED one reduced to
29
+ * its key and each other one kept as written.
30
+ *
31
+ * Reduced rather than dropped, and held apart from `text` rather than left
32
+ * in it, so that one question can be asked of a retag: did the SET of tag
33
+ * lines change? Rewriting `# colspan=6` to `# colspan=3` is the edit; ending
34
+ * up with both is the defect, and it is the defect a writer produces when it
35
+ * cannot see a tag it is about to duplicate.
36
+ */
37
+ tags: string[];
38
+ /**
39
+ * The same lines as written.
40
+ *
41
+ * `tags` masks a modelled tag to its key, so it answers "did the set of tag
42
+ * lines change?" and CANNOT see `# label="A"` become `# label="B"`. That is
43
+ * the whole of the damage when a writer retags the wrong declaration, so the
44
+ * verbatim text is kept beside the masked form rather than instead of it.
45
+ */
46
+ tagText: string[];
47
+ /** The comment lines above it, `#` and `##` lines excluded. */
48
+ block: string[];
49
+ /** Its statement, tag block off the front and child declarations excised. */
50
+ text: string;
51
+ /** The whitespace its first line of code begins with. */
52
+ indent: string;
53
+ }
54
+
55
+ export interface Inventory {
56
+ /**
57
+ * Keyed `source:NAME`, `view:SOURCE.NAME`, `dimension:SOURCE.NAME`,
58
+ * `given:NAME`, `import:PATH`.
59
+ */
60
+ declarations: Record<string, Declaration>;
61
+ /**
62
+ * The code on a line -> the comment trailing it.
63
+ *
64
+ * Per STATEMENT, not per declaration, which is the whole point of it: the
65
+ * comment that slides lives on a line INSIDE a view body
66
+ * (`aggregate: n is count() // keep with measure` becoming
67
+ * `where: b ~ $B // keep with measure`). Asking a declaration for the
68
+ * comment trailing its own first line looks at `view: kpis is {`, which
69
+ * never had one. Keyed by the code rather than by the line number, so a
70
+ * comment that lands on a different statement is a different key.
71
+ */
72
+ attached: Record<string, string>;
73
+ /** Every comment in the file, in order, both of the lexer's token kinds. */
74
+ comments: string[];
75
+ /**
76
+ * The statements no declaration covers and no gate models: `run:`, `query:`,
77
+ * a bare `sql:`. Without these a `run:` sharing a removed tile's line
78
+ * vanishes with nothing going red.
79
+ *
80
+ * `#` and `##` lines are NOT here. A `#` line belongs to the declaration
81
+ * below it and is in that declaration's `tags`; a `##` line is the model
82
+ * annotation surface that `planOrder` and `planSettings` own and rewrite on
83
+ * purpose, so holding it here would paint every correct reorder red.
84
+ */
85
+ residue: string[];
86
+ }
87
+
88
+ /**
89
+ * The tag keys the document models, across tiles, givens and drills -- the only
90
+ * `#` lines the writer may rewrite.
91
+ */
92
+ const MODELLED_TAG =
93
+ /^#\s*(colspan|break|borderless|label|subtitle|description|control|suggest|range_min|range_max|drill)\b/;
94
+
95
+ /** A modelled tag reduced to its key; anything else kept as written. */
96
+ function maskTag(trimmed: string): string {
97
+ const key = MODELLED_TAG.exec(trimmed);
98
+ return key ? `#${key[1]}` : trimmed;
99
+ }
100
+
101
+ /** Whitespace flattened, so formatting is not mistaken for meaning. */
102
+ const flatten = (text: string) => text.replace(/\s+/g, " ").trim();
103
+
104
+ export async function inventory(source: string): Promise<Inventory> {
105
+ const result = await parseMalloy(source);
106
+ if (parseRefused(result))
107
+ throw new Error(`the oracle needs a file that parses: ${result.reason}`);
108
+ const parsed = result.parsed;
109
+ const lines = source.split("\n");
110
+ const lineOf = (offset: number) =>
111
+ parsed.lineStarts.findLastIndex((at) => at <= offset);
112
+ const covered: Span[] = [];
113
+ const declarations: Record<string, Declaration> = {};
114
+
115
+ // The file with every comment blanked out, newlines kept, so a line can be
116
+ // asked what CODE is on it. Built here from the lexer's raw spans rather
117
+ // than taken from `parsed.blockStart` or `parsed.commentLine`, which are the
118
+ // same locators the writer walks: an oracle that shares one can be blind in
119
+ // exactly the way the code is, and it was -- a line holding a comment AND a
120
+ // declaration read as wholly comment on both sides at once.
121
+ let code = "";
122
+ {
123
+ let at = 0;
124
+ for (const span of [...parsed.comments].sort(
125
+ (a, b) => a.start - b.start,
126
+ )) {
127
+ code += source.slice(at, Math.max(at, span.start));
128
+ code += source
129
+ .slice(Math.max(at, span.start), Math.max(at, span.end))
130
+ .replace(/[^\n\r]/g, " ");
131
+ at = Math.max(at, span.end);
132
+ }
133
+ code += source.slice(at);
134
+ }
135
+ const codeOn = (line: number) =>
136
+ code.slice(
137
+ parsed.lineStarts[line],
138
+ parsed.lineStarts[line + 1] ?? code.length,
139
+ );
140
+ /** A line carrying a comment and no code of its own. */
141
+ const commentOnly = (line: number) =>
142
+ codeOn(line).trim() === "" && lines[line]?.trim() !== "";
143
+
144
+ /** The first line of the `#`/comment block above `line`. */
145
+ const blockStart = (line: number): number => {
146
+ let start = line;
147
+ for (let i = line - 1; i >= 0; i--) {
148
+ const text = lines[i].trim();
149
+ if (commentOnly(i)) {
150
+ start = i;
151
+ continue;
152
+ }
153
+ if (text === "") break;
154
+ if (text.startsWith("#")) start = i;
155
+ else break;
156
+ }
157
+ return start;
158
+ };
159
+
160
+ const record = (key: string, statement: Span, excise: Span[] = []) => {
161
+ covered.push(statement);
162
+ // The prelude is walked from `blockStart` DOWNWARD to the first line of
163
+ // code, rather than upward from the declaration: a view's statement span
164
+ // opens at its first `#` tag while a given's opens at its name, and
165
+ // `view:\n kpis is ...` puts the keyword on a line of its own. One walk
166
+ // that stops at the first line which is neither blank, a `#` line nor a
167
+ // comment lands in the right place for all of them.
168
+ let codeLine = lineOf(statement.start);
169
+ const tags: string[] = [];
170
+ const tagText: string[] = [];
171
+ const block: string[] = [];
172
+ for (let i = blockStart(codeLine); i < lines.length; i++) {
173
+ const text = lines[i].trim();
174
+ if (text === "") continue;
175
+ // Wholly comment, where a line beginning `#` is prose.
176
+ if (commentOnly(i)) {
177
+ block.push(text);
178
+ continue;
179
+ }
180
+ // `##` is a MODEL annotation. It is dropped rather than walked past
181
+ // because the walk above counts one as a `#`, and `## artifact {...}`
182
+ // sits directly above `import` in every dashboard -- keeping it would
183
+ // make the import's prelude differ on every correct tile removal.
184
+ if (text.startsWith("##")) continue;
185
+ if (text.startsWith("#")) {
186
+ tags.push(maskTag(text));
187
+ tagText.push(text);
188
+ } else {
189
+ codeLine = i;
190
+ break;
191
+ }
192
+ }
193
+ // A declaration that is not the first thing on its line owns no prelude:
194
+ // Malloy lets a second `view:` share a line, and the tags above belong to
195
+ // the one that opens it.
196
+ const start = Math.max(statement.start, parsed.lineStarts[codeLine]);
197
+ // CODE before it on the line, not merely a comment: a declaration that
198
+ // follows `/* note */` is still the first declaration on its line and
199
+ // still owns the tag block above it.
200
+ const shared =
201
+ code.slice(parsed.lineStarts[codeLine], start).trim() !== "";
202
+ let text = "";
203
+ let at = start;
204
+ for (const child of [...excise].sort((a, b) => a.start - b.start)) {
205
+ text += source.slice(at, Math.max(at, child.start));
206
+ at = Math.max(at, child.end);
207
+ }
208
+ text += source.slice(at, Math.max(at, statement.end));
209
+ declarations[key] = {
210
+ tags: shared ? [] : tags,
211
+ tagText: shared ? [] : tagText,
212
+ block: shared ? [] : block,
213
+ text: flatten(text),
214
+ indent: /^[ \t]*/.exec(lines[codeLine])?.[0] ?? "",
215
+ };
216
+ };
217
+
218
+ for (const at of parsed.imports) record(`import:${at.from}`, at.statement);
219
+ for (const given of parsed.givens)
220
+ record(`given:${given.name}`, given.statement);
221
+ for (const declared of parsed.sources) {
222
+ const children = [
223
+ ...declared.views.map((v) => v.statement),
224
+ ...declared.dimensions.map((d) => d.statement),
225
+ ];
226
+ // The source keeps its key: its base, its own `where:` and its
227
+ // `extend { ... }` braces are worth watching. Its CHILDREN come out, or
228
+ // every filter edit and every tile removal would report the enclosing
229
+ // source as changed as well.
230
+ record(`source:${declared.name}`, declared.statement, children);
231
+ for (const view of declared.views)
232
+ record(`view:${declared.name}.${view.name}`, view.statement);
233
+ for (const dimension of declared.dimensions)
234
+ record(
235
+ `dimension:${declared.name}.${dimension.name}`,
236
+ dimension.statement,
237
+ );
238
+ }
239
+
240
+ const attached: Record<string, string> = {};
241
+ for (const at of parsed.comments) {
242
+ const before = source
243
+ .slice(parsed.lineStarts[lineOf(at.start)], at.start)
244
+ .trim();
245
+ if (before === "") continue;
246
+ let key = before;
247
+ for (let n = 2; key in attached; n++) key = `${before} #${n}`;
248
+ attached[key] = source.slice(at.start, at.end).trim();
249
+ }
250
+
251
+ const residue: string[] = [];
252
+ lines.forEach((raw, i) => {
253
+ const text = raw.trim();
254
+ if (text === "" || text.startsWith("#") || commentOnly(i)) return;
255
+ const start = parsed.lineStarts[i];
256
+ const end = start + raw.length;
257
+ if (covered.some((at) => at.start < end && at.end > start)) return;
258
+ residue.push(text);
259
+ });
260
+
261
+ return {
262
+ declarations,
263
+ attached,
264
+ comments: parsed.comments.map((at) =>
265
+ source.slice(at.start, at.end).trim(),
266
+ ),
267
+ residue,
268
+ };
269
+ }
270
+
271
+ /**
272
+ * What moved between two inventories, one list per field so a failure names the
273
+ * thing that broke rather than dumping two files. `+` appeared, `-` vanished,
274
+ * `~` changed.
275
+ */
276
+ export interface InventoryDiff {
277
+ declarations: string[];
278
+ tags: string[];
279
+ tagText: string[];
280
+ block: string[];
281
+ indent: string[];
282
+ attached: string[];
283
+ comments: string[];
284
+ residue: string[];
285
+ }
286
+
287
+ /** What every field must be when an edit disturbed nothing it did not name. */
288
+ export const NOTHING_MOVED: InventoryDiff = {
289
+ declarations: [],
290
+ tags: [],
291
+ tagText: [],
292
+ block: [],
293
+ indent: [],
294
+ attached: [],
295
+ comments: [],
296
+ residue: [],
297
+ };
298
+
299
+ function keyDiff<T>(
300
+ before: Record<string, T>,
301
+ after: Record<string, T>,
302
+ same: (a: T, b: T) => boolean,
303
+ ): string[] {
304
+ const out: string[] = [];
305
+ for (const key of Object.keys(before))
306
+ if (!(key in after)) out.push(`-${key}`);
307
+ else if (!same(before[key], after[key])) out.push(`~${key}`);
308
+ for (const key of Object.keys(after))
309
+ if (!(key in before)) out.push(`+${key}`);
310
+ return out.sort();
311
+ }
312
+
313
+ /** A multiset difference, so two identical comments are two entries. */
314
+ function listDiff(before: string[], after: string[]): string[] {
315
+ const remaining = [...after];
316
+ const out: string[] = [];
317
+ for (const entry of before) {
318
+ const at = remaining.indexOf(entry);
319
+ if (at < 0) out.push(`-${entry}`);
320
+ else remaining.splice(at, 1);
321
+ }
322
+ for (const entry of remaining) out.push(`+${entry}`);
323
+ // The same multiset in a different order: one comment moved past another,
324
+ // which changes which code each of them sits beside.
325
+ if (out.length === 0 && before.join("\v") !== after.join("\v"))
326
+ out.push("~order");
327
+ return out.sort();
328
+ }
329
+
330
+ export function diffInventories(
331
+ before: Inventory,
332
+ after: Inventory,
333
+ ): InventoryDiff {
334
+ const both = (key: string) =>
335
+ key in before.declarations && key in after.declarations;
336
+ const changed = (read: (d: Declaration) => string) =>
337
+ Object.keys(before.declarations)
338
+ .filter(
339
+ (key) =>
340
+ both(key) &&
341
+ read(before.declarations[key]) !== read(after.declarations[key]),
342
+ )
343
+ .map((key) => `~${key}`)
344
+ .sort();
345
+ return {
346
+ declarations: keyDiff(
347
+ before.declarations,
348
+ after.declarations,
349
+ (a, b) => a.text === b.text,
350
+ ),
351
+ tags: changed((d) => d.tags.join("\v")),
352
+ tagText: changed((d) => d.tagText.join("\v")),
353
+ block: changed((d) => d.block.join("\v")),
354
+ indent: changed((d) => d.indent),
355
+ attached: keyDiff(before.attached, after.attached, (a, b) => a === b),
356
+ comments: listDiff(before.comments, after.comments),
357
+ residue: listDiff(before.residue, after.residue),
358
+ };
359
+ }
360
+
361
+ /** The diff between two texts, which is how every sweep here asks. */
362
+ export async function whatMoved(
363
+ before: string,
364
+ after: string,
365
+ ): Promise<InventoryDiff> {
366
+ return diffInventories(await inventory(before), await inventory(after));
367
+ }
@@ -7,6 +7,7 @@ import {
7
7
  kindForFieldType,
8
8
  typeLabel,
9
9
  applyMapping,
10
+ canBind,
10
11
  controlsOf,
11
12
  declareControl,
12
13
  defaultOperator,
@@ -147,12 +148,13 @@ describe("mappings", () => {
147
148
  });
148
149
  });
149
150
 
150
- it("applies a mapping as a diff and skips tiles that cannot bind", () => {
151
+ it("applies a mapping as a diff, including an inline tile's own first stage", () => {
151
152
  const d = doc();
152
153
  applyMapping(d, "SINCE", [
153
154
  { include: true, field: "created_at", op: ">=" },
154
155
  { include: true, field: "created_at", op: ">=" },
155
- // Inline: cannot take a refinement, so ticking it does nothing.
156
+ // Inline: a depth-1 `where:` in its own first stage, same as a
157
+ // reference tile's refinement as far as applyMapping is concerned.
156
158
  { include: true, field: "created_at", op: ">=" },
157
159
  ]);
158
160
  expect(d.tiles[0].filters).toEqual([
@@ -162,7 +164,9 @@ describe("mappings", () => {
162
164
  expect(d.tiles[1].filters).toEqual([
163
165
  { field: "created_at", given: "SINCE", op: ">=" },
164
166
  ]);
165
- expect(d.tiles[2].filters).toBeUndefined();
167
+ expect(d.tiles[2].filters).toEqual([
168
+ { field: "created_at", given: "SINCE", op: ">=" },
169
+ ]);
166
170
 
167
171
  // Unticking removes, and a `~` is left implicit.
168
172
  applyMapping(d, "SINCE", [
@@ -176,6 +180,52 @@ describe("mappings", () => {
176
180
  expect(d.tiles[1].filters).toEqual([
177
181
  { field: "created_at", given: "SINCE" },
178
182
  ]);
183
+ expect(d.tiles[2].filters).toBeUndefined();
184
+ });
185
+
186
+ it("still skips a tile the writer cannot locate at all: inherited", () => {
187
+ const d = doc();
188
+ d.tiles.push({
189
+ name: "by_region",
190
+ source: "orders",
191
+ declaration: { kind: "inherited" },
192
+ });
193
+ applyMapping(d, "SINCE", [
194
+ { include: false, field: "created_at" },
195
+ { include: false, field: "created_at" },
196
+ { include: false, field: "created_at" },
197
+ { include: true, field: "created_at", op: ">=" },
198
+ ]);
199
+ expect(d.tiles[3].filters).toBeUndefined();
200
+ });
201
+ });
202
+
203
+ describe("canBind", () => {
204
+ // The doc comment on canBind used to say an inline tile's body "is a
205
+ // query, not a reference", which stopped a filter from being addable on
206
+ // the majority of real dashboards: an inline body is how most tiles are
207
+ // actually written. What is excluded is the two kinds with nowhere to put
208
+ // a binding: a view declared on the model, and one declared here whose
209
+ // body the builder does not rewrite.
210
+ it("excludes inherited and opaque, and nothing else", () => {
211
+ const d = doc();
212
+ d.tiles.push({
213
+ name: "by_region",
214
+ source: "orders",
215
+ declaration: { kind: "inherited" },
216
+ });
217
+ d.tiles.push({
218
+ name: "chained",
219
+ source: "orders",
220
+ declaration: { kind: "opaque", why: "a chained refinement" },
221
+ });
222
+ expect(d.tiles.map((t) => canBind(t))).toEqual([
223
+ true,
224
+ true,
225
+ true,
226
+ false,
227
+ false,
228
+ ]);
179
229
  });
180
230
  });
181
231
 
@@ -306,15 +306,17 @@ export interface MappingRow {
306
306
  /**
307
307
  * Which tiles can take a binding, and why the others cannot.
308
308
  *
309
- * A binding is a `+ { where: … }` refinement on the tile's declaration, so the
310
- * tile has to BE a declaration this file owns that the reader will read back.
311
- * That is the `reference` form only: an `inherited` tile is declared on the
312
- * model's source, and an `inline` tile's body is a query, not a reference, so a
313
- * refinement written onto it would not come back and the round-trip gate would
314
- * refuse the whole save. Better to refuse the tick.
309
+ * A binding is a `where:` the splice writer can locate and own: a `+ {
310
+ * where: … }` refinement on a `reference` tile, or a `where:` statement in an
311
+ * `inline` tile's own first stage — `TreeStage.wheres` in `malloyTree`, which
312
+ * is the parse tree's answer rather than a depth count. Both forms are
313
+ * declarations this file owns and the reader reads back. An `inherited` tile is declared on the
314
+ * model's source, which the builder never writes, so it is the one kind this
315
+ * excludes, and so is an `opaque` one: its body has no single block a binding
316
+ * belongs in, which the reader can see before a save is ever attempted.
315
317
  */
316
318
  export const canBind = (tile: DashboardTile) =>
317
- tile.declaration.kind === "reference";
319
+ tile.declaration.kind !== "inherited" && tile.declaration.kind !== "opaque";
318
320
 
319
321
  /** The mapping a control has NOW, one row per tile, for the dialog to open on. */
320
322
  export function mappingOf(
@@ -93,15 +93,24 @@ export interface DashboardDrill {
93
93
  /**
94
94
  * Where a tile's view is declared, and therefore what the builder may edit.
95
95
  *
96
- * Three forms, all of them found in dashboards that ship in this repository, and
96
+ * Four forms, all of them found in dashboards that ship in this repository, and
97
97
  * the distinction decides which affordances a tile gets:
98
98
  *
99
99
  * - `reference` — `view: revenue_trend is sales_by_month` in this file. Fully
100
100
  * editable: the layout tags sit above that line and the builder owns them.
101
101
  * - `inline` — `view: order_tile is { aggregate: order_count }` in this file.
102
- * Its tags are editable for the same reason; its QUERY is not, because
103
- * authoring a query body is a separate feature. The projection holds: the body
104
- * is never rewritten, so it cannot be damaged.
102
+ * Its tags are editable for the same reason, and so is a FILTER: a binding is
103
+ * a depth-1 `where:` statement in the body's own first stage rather than a `+
104
+ * { … }` refinement, but it is still a declaration this file owns and the
105
+ * reader reads back — see {@link DashboardTile.filters} and BINDING_CLAUSE in
106
+ * readDocument.ts. The QUERY otherwise is not editable, because authoring a
107
+ * query body is a separate feature; the body is never rewritten beyond its
108
+ * binding lines, so the rest of it cannot be damaged.
109
+ * - `opaque` — declared in this file, in a body the builder does not rewrite: a
110
+ * `->` pipeline from a named view, or a chained `vx + { … } + { … }` where no
111
+ * one block is where a binding belongs. Its TAGS are ordinary `#` lines here,
112
+ * so its label, colspan and position are editable like any other tile's; only
113
+ * a FILTER has nowhere to go, and `why` says which shape it is.
105
114
  * - `inherited` — not declared in this file at all, as in a dashboard whose only
106
115
  * tile is `orders -> by_brand` against an imported source. Nothing about it is
107
116
  * editable here, because its tags live on the model's own view and the builder
@@ -110,6 +119,7 @@ export interface DashboardDrill {
110
119
  export type TileDeclaration =
111
120
  | { kind: "reference"; from: string }
112
121
  | { kind: "inline" }
122
+ | { kind: "opaque"; why: string }
113
123
  | { kind: "inherited" };
114
124
 
115
125
  /** One tile: a view shown on the page, plus how it is presented. */
@@ -129,7 +139,9 @@ export interface DashboardTile {
129
139
  source: string;
130
140
  declaration: TileDeclaration;
131
141
  /**
132
- * Given bindings, emitted as a `+ { where: … }` refinement on the view.
142
+ * Given bindings: a `+ { where: … }` refinement on a `reference` tile, or a
143
+ * depth-1 `where:` statement in an `inline` tile's own first stage — see
144
+ * {@link TileDeclaration}.
133
145
  *
134
146
  * `op` is the comparison, and absent means `~`, which is how a `filter<…>`
135
147
  * given binds. A plain `date` or `number` given is a VALUE, not a filter,