@malloy-publisher/sdk 0.9.15 → 0.10.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 (94) hide show
  1. package/dist/{RenderedResult-BClN_PG6.cjs.js → RenderedResult-B5f4qOjp.cjs.js} +21 -4
  2. package/dist/{RenderedResult-YBzVMVH2.es.js → RenderedResult-DiDsN6JE.es.js} +204 -187
  3. package/dist/builder/index.cjs.js +75 -75
  4. package/dist/builder/index.es.js +5304 -5156
  5. package/dist/builder-entry.d.ts +1 -1
  6. package/dist/client/api.d.ts +1 -1
  7. package/dist/components/Dashboard/DashboardGrid.d.ts +2 -0
  8. package/dist/components/Dashboard/DashboardTile.d.ts +3 -1
  9. package/dist/components/RenderedResult/ResultContainer.d.ts +8 -1
  10. package/dist/components/RenderedResult/ResultPanel.d.ts +3 -1
  11. package/dist/components/RenderedResult/resultSizing.d.ts +5 -0
  12. package/dist/components/ReportBuilder/ArrangeMenu.d.ts +9 -0
  13. package/dist/components/ReportBuilder/BuilderGrid.d.ts +5 -7
  14. package/dist/components/ReportBuilder/BuilderToolbar.d.ts +3 -1
  15. package/dist/components/ReportBuilder/ReportBuilder.d.ts +1 -1
  16. package/dist/components/ReportBuilder/TextTileBody.d.ts +9 -2
  17. package/dist/components/ReportBuilder/TileFrame.d.ts +34 -22
  18. package/dist/components/ReportBuilder/builderControls.d.ts +19 -0
  19. package/dist/components/ReportBuilder/placement.d.ts +48 -2
  20. package/dist/components/ReportBuilder/sortable.d.ts +9 -0
  21. package/dist/components/ReportBuilder/useBuilderSession.d.ts +1 -1
  22. package/dist/components/ReportBuilder/useBuilderShortcuts.d.ts +9 -1
  23. package/dist/components/ReportBuilder/useEdgeResize.d.ts +84 -0
  24. package/dist/components/ReportBuilder/useTileReorder.d.ts +3 -0
  25. package/dist/components/legacy/malloynb/CellRunnerView.d.ts +6 -6
  26. package/dist/hooks/useSettled.d.ts +5 -8
  27. package/dist/hooks/useSettledDraft.d.ts +33 -0
  28. package/dist/index.cjs.js +10 -10
  29. package/dist/index.es.js +3861 -3870
  30. package/dist/theme/classes.d.ts +1 -1
  31. package/dist/useCompiledDocument-C995sQ3j.cjs.js +142 -0
  32. package/dist/{useCompiledDocument-BGk38oaW.es.js → useCompiledDocument-CRmmbUza.es.js} +6426 -6257
  33. package/dist/utils/malloyLiteral.d.ts +2 -0
  34. package/package.json +11 -16
  35. package/src/builder-entry.ts +1 -0
  36. package/src/components/Dashboard/DashboardGrid.tsx +2 -0
  37. package/src/components/Dashboard/DashboardTile.tsx +4 -0
  38. package/src/components/Dashboard/DashboardView.tsx +1 -0
  39. package/src/components/RenderedResult/RenderedResult.tsx +18 -0
  40. package/src/components/RenderedResult/ResultContainer.tsx +39 -3
  41. package/src/components/RenderedResult/ResultPanel.tsx +4 -0
  42. package/src/components/RenderedResult/resultSizing.ts +6 -0
  43. package/src/components/ReportBuilder/ArrangeMenu.tsx +80 -0
  44. package/src/components/ReportBuilder/BuilderBar.tsx +4 -0
  45. package/src/components/ReportBuilder/BuilderDialogs.tsx +8 -1
  46. package/src/components/ReportBuilder/BuilderGrid.tsx +62 -60
  47. package/src/components/ReportBuilder/BuilderToolbar.tsx +4 -0
  48. package/src/components/ReportBuilder/EditorSurface.tsx +9 -2
  49. package/src/components/ReportBuilder/ReportBuilder.spec.tsx +99 -0
  50. package/src/components/ReportBuilder/ReportBuilder.tsx +110 -30
  51. package/src/components/ReportBuilder/TextTileBody.tsx +24 -4
  52. package/src/components/ReportBuilder/TileFrame.tsx +261 -310
  53. package/src/components/ReportBuilder/builderControls.ts +34 -0
  54. package/src/components/ReportBuilder/placement.spec.ts +235 -0
  55. package/src/components/ReportBuilder/placement.ts +179 -9
  56. package/src/components/ReportBuilder/readDocument.spec.ts +7 -17
  57. package/src/components/ReportBuilder/readDocument.ts +3 -6
  58. package/src/components/ReportBuilder/sortable.tsx +26 -2
  59. package/src/components/ReportBuilder/spliceDocument.spec.ts +0 -40
  60. package/src/components/ReportBuilder/spliceDocument.ts +0 -39
  61. package/src/components/ReportBuilder/useBuilderSession.ts +7 -2
  62. package/src/components/ReportBuilder/useBuilderShortcuts.ts +25 -1
  63. package/src/components/ReportBuilder/useEdgeResize.spec.tsx +324 -0
  64. package/src/components/ReportBuilder/useEdgeResize.ts +397 -0
  65. package/src/components/ReportBuilder/useTileReorder.ts +1 -1
  66. package/src/components/given/GivenInput.spec.tsx +447 -2
  67. package/src/components/given/GivenInput.tsx +192 -80
  68. package/src/components/given/GivensPanel.spec.tsx +59 -0
  69. package/src/components/given/GivensPanel.tsx +14 -2
  70. package/src/components/legacy/malloynb/CellRunnerView.tsx +6 -6
  71. package/src/hooks/useDimensionFilters.ts +1 -35
  72. package/src/hooks/useDimensionFiltersQuery.ts +2 -36
  73. package/src/hooks/useDimensionalFilterRangeData.ts +1 -35
  74. package/src/hooks/useGivensState.spec.ts +106 -1
  75. package/src/hooks/useGivensState.ts +48 -13
  76. package/src/hooks/useSettled.ts +5 -8
  77. package/src/hooks/useSettledDraft.ts +127 -0
  78. package/src/theme/classes.ts +1 -1
  79. package/src/utils/malloyLiteral.spec.ts +12 -1
  80. package/src/utils/malloyLiteral.ts +32 -0
  81. package/vite.config.ts +0 -2
  82. package/.eslintrc +0 -36
  83. package/dist/components/DOMElement/DOMElement.d.ts +0 -5
  84. package/dist/components/DOMElement/index.d.ts +0 -1
  85. package/dist/components/Package/FileTreeView.d.ts +0 -9
  86. package/dist/components/ReportBuilder/useTileHeight.d.ts +0 -39
  87. package/dist/components/ReportBuilder/useTileResize.d.ts +0 -40
  88. package/dist/useCompiledDocument-D9t5ry_t.cjs.js +0 -142
  89. package/src/components/DOMElement/DOMElement.tsx +0 -22
  90. package/src/components/DOMElement/index.ts +0 -4
  91. package/src/components/Package/FileTreeView.tsx +0 -244
  92. package/src/components/ReportBuilder/useTileHeight.ts +0 -149
  93. package/src/components/ReportBuilder/useTileResize.spec.tsx +0 -146
  94. package/src/components/ReportBuilder/useTileResize.ts +0 -148
@@ -36,6 +36,11 @@ export interface BuilderControls {
36
36
  /** Why a filter cannot be added here, when it cannot; `filter` is then absent. */
37
37
  filterUnavailable?: string;
38
38
  };
39
+ /**
40
+ * The layout as a whole, on a grid report whose tiles are placed: close
41
+ * its gaps, or let its tiles flow again. Absent on a report that flows.
42
+ */
43
+ arrange?: ArrangeActions;
39
44
  /** Leave the builder: asks first when edits are unsaved. Absent unless the host passed `onExit`. */
40
45
  exit?: () => void;
41
46
  /**
@@ -63,6 +68,21 @@ export interface BuilderControls {
63
68
  dismissRestored?: () => void;
64
69
  }
65
70
 
71
+ /**
72
+ * What can be done to a placed report's layout as a whole, as
73
+ * {@link BuilderControls.arrange} offers it.
74
+ */
75
+ export interface ArrangeActions {
76
+ /**
77
+ * Slide every tile up into the empty space above it. Present only when
78
+ * there is such a gap: absent means there is nothing to close, and a host
79
+ * draws the action disabled (or not at all).
80
+ */
81
+ pack?: () => void;
82
+ /** Take every tile's place off, so the report flows again; sizes are kept. */
83
+ flow: () => void;
84
+ }
85
+
66
86
  /** What a host passes to take over the builder's page-level controls. */
67
87
  export type BuilderControlsHandler = (
68
88
  controls: BuilderControls | undefined,
@@ -97,6 +117,8 @@ export function useReportControls(
97
117
  discard: () => latest.current.discard?.(),
98
118
  restore: () => latest.current.restore?.(),
99
119
  dismissRestored: () => latest.current.dismissRestored?.(),
120
+ pack: () => latest.current.arrange?.pack?.(),
121
+ flow: () => latest.current.arrange?.flow(),
100
122
  }),
101
123
  [],
102
124
  );
@@ -121,6 +143,8 @@ export function useReportControls(
121
143
  const restoredPending = controls.restored?.pending ?? false;
122
144
  const hasRestore = controls.restore !== undefined;
123
145
  const hasDismissRestored = controls.dismissRestored !== undefined;
146
+ const hasArrange = controls.arrange !== undefined;
147
+ const canPack = controls.arrange?.pack !== undefined;
124
148
 
125
149
  const shown = useMemo<BuilderControls>(
126
150
  () => ({
@@ -154,6 +178,14 @@ export function useReportControls(
154
178
  ...(hasDismissRestored
155
179
  ? { dismissRestored: actions.dismissRestored }
156
180
  : {}),
181
+ ...(hasArrange
182
+ ? {
183
+ arrange: {
184
+ ...(canPack ? { pack: actions.pack } : {}),
185
+ flow: actions.flow,
186
+ },
187
+ }
188
+ : {}),
157
189
  }),
158
190
  [
159
191
  actions,
@@ -175,6 +207,8 @@ export function useReportControls(
175
207
  restoredPending,
176
208
  hasRestore,
177
209
  hasDismissRestored,
210
+ hasArrange,
211
+ canPack,
178
212
  ],
179
213
  );
180
214
 
@@ -6,10 +6,16 @@ import type { DashboardTile, QueryTile } from "./document";
6
6
  import {
7
7
  cellAt,
8
8
  dropAt,
9
+ flowTiles,
10
+ hasGaps,
11
+ holdChartRows,
12
+ minRowsOf,
13
+ pack,
9
14
  placeAtEnd,
10
15
  inReadingOrder,
11
16
  placeWhereDrawn,
12
17
  settle,
18
+ stepPlaced,
13
19
  trackWidth,
14
20
  } from "./placement";
15
21
 
@@ -120,6 +126,33 @@ describe("placeWhereDrawn", () => {
120
126
  // A row break means nothing once tiles are placed.
121
127
  expect(placeWhereDrawn(tiles, boxes, 12, track)[0].break).toBeUndefined();
122
128
  });
129
+
130
+ it("rounds a text tile's bottom edge up, so its prose keeps every line", () => {
131
+ const track = trackWidth(1200, 12);
132
+ // A heading and two lines: 124px, under a row and a half, which rounded to one row
133
+ // of 80px and left the last line under the tiles placed beneath.
134
+ const intro: DashboardTile = {
135
+ kind: "text",
136
+ name: "intro",
137
+ markdown: "# Hi\n\ntwo lines",
138
+ colspan: 12,
139
+ };
140
+ const tiles: DashboardTile[] = [intro, tile("trend", { colspan: 12 })];
141
+ const boxes = [
142
+ { top: 0, left: 0, width: 1200, height: 124 },
143
+ { top: 140, left: 0, width: 1200, height: 272 },
144
+ ];
145
+ const placed = where(placeWhereDrawn(tiles, boxes, 12, track));
146
+ expect(placed[0]).toEqual({
147
+ name: "intro",
148
+ row: 1,
149
+ col: 1,
150
+ colspan: 12,
151
+ rowspan: 2,
152
+ });
153
+ // The chart below starts where it was drawn; a text tile that grew a row is settled under it.
154
+ expect(placed[1].row).toBeGreaterThanOrEqual(3);
155
+ });
123
156
  });
124
157
 
125
158
  describe("inReadingOrder", () => {
@@ -191,3 +224,205 @@ describe("dropAt, far below", () => {
191
224
  expect(dropAt(tiles, 1, { row: 40, col: 7 }, 12)[1].row).toBe(4);
192
225
  });
193
226
  });
227
+
228
+ describe("pack", () => {
229
+ it("slides every tile up into the gaps above it, never sideways", () => {
230
+ const tiles = [
231
+ tile("a", { row: 1, col: 1, colspan: 6, rowspan: 3 }),
232
+ tile("b", { row: 7, col: 1, colspan: 6, rowspan: 2 }),
233
+ tile("c", { row: 5, col: 7, colspan: 6, rowspan: 4 }),
234
+ ];
235
+ expect(hasGaps(tiles, 12)).toBe(true);
236
+ expect(where(pack(tiles, 12))).toEqual([
237
+ { name: "a", row: 1, col: 1, colspan: 6, rowspan: 3 },
238
+ { name: "b", row: 4, col: 1, colspan: 6, rowspan: 2 },
239
+ { name: "c", row: 1, col: 7, colspan: 6, rowspan: 4 },
240
+ ]);
241
+ expect(hasGaps(pack(tiles, 12), 12)).toBe(false);
242
+ });
243
+
244
+ it("stops a tile under the lowest tile it would pass through", () => {
245
+ const tiles = [
246
+ tile("wide", { row: 1, col: 1, colspan: 12, rowspan: 2 }),
247
+ tile("low", { row: 9, col: 4, colspan: 4, rowspan: 2 }),
248
+ ];
249
+ expect(pack(tiles, 12)[1].row).toBe(3);
250
+ });
251
+ });
252
+
253
+ describe("flowTiles", () => {
254
+ it("takes every place off and keeps sizes, in reading order", () => {
255
+ const tiles = [
256
+ tile("b", { row: 4, col: 1, colspan: 6, rowspan: 3 }),
257
+ tile("a", { row: 1, col: 7, colspan: 6, rowspan: 2 }),
258
+ ];
259
+ expect(where(flowTiles(tiles))).toEqual([
260
+ { name: "a", row: undefined, col: undefined, colspan: 6, rowspan: 2 },
261
+ { name: "b", row: undefined, col: undefined, colspan: 6, rowspan: 3 },
262
+ ]);
263
+ });
264
+ });
265
+
266
+ describe("placeWhereDrawn keeps rows where they are drawn", () => {
267
+ it("takes each edge to its nearest row line, so stacked tiles still touch and nothing is pushed", () => {
268
+ const track = trackWidth(1200, 12);
269
+ const half = 6 * (track + 16) - 16;
270
+ // Four rows of two auto tiles, each 300px tall with a 16px gap: drawn
271
+ // tops at 0, 316, 632, 948.
272
+ const tiles = Array.from({ length: 8 }, (_, i) =>
273
+ tile(`t${i}`, { colspan: 6 }),
274
+ );
275
+ const boxes = tiles.map((_, i) => ({
276
+ top: Math.floor(i / 2) * 316,
277
+ left: i % 2 === 0 ? 0 : half + 16,
278
+ width: half,
279
+ height: 300,
280
+ }));
281
+ const placed = placeWhereDrawn(tiles, boxes, 12, track);
282
+ // Every row's top stays within half a row (48px) of where it was drawn.
283
+ for (const [i, each] of placed.entries())
284
+ expect(
285
+ Math.abs((each.row! - 1) * 96 - boxes[i].top),
286
+ ).toBeLessThanOrEqual(48);
287
+ // And each row starts right where the one above ends: no row was pushed.
288
+ for (let r = 2; r < 8; r += 2)
289
+ expect(placed[r].row).toBe(
290
+ placed[r - 2].row! + placed[r - 2].rowspan!,
291
+ );
292
+ });
293
+ });
294
+
295
+ describe("minRowsOf", () => {
296
+ const drawn = (html: string) => {
297
+ const frame = document.createElement("div");
298
+ frame.innerHTML = html;
299
+ return frame;
300
+ };
301
+ it("gives a chart three rows, value cards and a table two, and prose one", () => {
302
+ expect(minRowsOf(tile("chart"), drawn('<svg class="plot"></svg>'))).toBe(
303
+ 3,
304
+ );
305
+ expect(
306
+ minRowsOf(tile("kpis"), drawn('<div class="malloy-big-value"></div>')),
307
+ ).toBe(2);
308
+ expect(
309
+ minRowsOf(tile("rows"), drawn('<div class="malloy-table"></div>')),
310
+ ).toBe(2);
311
+ expect(
312
+ minRowsOf({ kind: "text", name: "note", markdown: "" }, null),
313
+ ).toBe(1);
314
+ });
315
+
316
+ it("takes a query tile for a chart until it has drawn", () => {
317
+ expect(minRowsOf(tile("t"))).toBe(3);
318
+ });
319
+
320
+ it("gives a dashboard with a chart beside its cards a chart's rows", () => {
321
+ expect(
322
+ minRowsOf(
323
+ tile("mixed"),
324
+ drawn(
325
+ '<div class="malloy-dashboard"><div class="malloy-big-value"></div><div class="malloy-chart"></div></div>',
326
+ ),
327
+ ),
328
+ ).toBe(3);
329
+ });
330
+
331
+ it("lets a chart inside a card or a table's cell size with its host", () => {
332
+ expect(
333
+ minRowsOf(
334
+ tile("spark"),
335
+ drawn(
336
+ '<div class="malloy-big-value"><div class="malloy-chart"></div></div>',
337
+ ),
338
+ ),
339
+ ).toBe(2);
340
+ expect(
341
+ minRowsOf(
342
+ tile("cells"),
343
+ drawn(
344
+ '<div class="malloy-table"><div class="malloy-chart"></div></div>',
345
+ ),
346
+ ),
347
+ ).toBe(2);
348
+ });
349
+ });
350
+
351
+ describe("holdChartRows", () => {
352
+ it("raises a tile switched to a plotted chart to a chart's rows", () => {
353
+ expect(
354
+ holdChartRows(tile("t", { rowspan: 2, chart: "line_chart" })).rowspan,
355
+ ).toBe(3);
356
+ });
357
+ it("leaves value cards, a table, and a tile on auto height alone", () => {
358
+ expect(
359
+ holdChartRows(tile("t", { rowspan: 2, chart: "big_value" })).rowspan,
360
+ ).toBe(2);
361
+ expect(
362
+ holdChartRows(tile("t", { rowspan: 2, chart: "none" })).rowspan,
363
+ ).toBe(2);
364
+ expect(
365
+ holdChartRows(tile("t", { chart: "bar_chart" })).rowspan,
366
+ ).toBeUndefined();
367
+ });
368
+ });
369
+
370
+ describe("stepPlaced", () => {
371
+ const at = (tiles: DashboardTile[], name: string) => {
372
+ const t = tiles.find((each) => each.name === name)!;
373
+ return [t.row, t.col];
374
+ };
375
+ const stacked = () => [
376
+ tile("a", { row: 1, col: 1, colspan: 6, rowspan: 4 }),
377
+ tile("b", { row: 5, col: 1, colspan: 6, rowspan: 3 }),
378
+ ];
379
+
380
+ it("swaps a tile down past the one under it", () => {
381
+ const next = stepPlaced(stacked(), 0, 1, 0, 12);
382
+ expect(at(next, "b")).toEqual([1, 1]);
383
+ expect(at(next, "a")).toEqual([4, 1]);
384
+ });
385
+
386
+ it("swaps a tile up past the one over it, the mirror of down", () => {
387
+ const next = stepPlaced(stacked(), 1, -1, 0, 12);
388
+ expect(at(next, "b")).toEqual([1, 1]);
389
+ expect(at(next, "a")).toEqual([4, 1]);
390
+ });
391
+
392
+ it("swaps tiles side by side", () => {
393
+ const tiles = [
394
+ tile("a", { row: 1, col: 1, colspan: 4, rowspan: 3 }),
395
+ tile("b", { row: 1, col: 5, colspan: 8, rowspan: 3 }),
396
+ ];
397
+ const right = stepPlaced(tiles, 0, 0, 1, 12);
398
+ expect(at(right, "b")).toEqual([1, 1]);
399
+ expect(at(right, "a")).toEqual([1, 9]);
400
+ const left = stepPlaced(tiles, 1, 0, -1, 12);
401
+ expect(at(left, "b")).toEqual([1, 1]);
402
+ expect(at(left, "a")).toEqual([1, 9]);
403
+ });
404
+
405
+ it("steps one cell into empty space", () => {
406
+ const next = stepPlaced(stacked(), 0, 0, 1, 12);
407
+ expect(at(next, "a")).toEqual([1, 2]);
408
+ expect(at(next, "b")).toEqual([5, 1]);
409
+ });
410
+
411
+ it("pushes down what it lands on when two tiles are in the way", () => {
412
+ const tiles = [
413
+ tile("a", { row: 1, col: 1, colspan: 12, rowspan: 3 }),
414
+ tile("b", { row: 4, col: 1, colspan: 6, rowspan: 3 }),
415
+ tile("c", { row: 4, col: 7, colspan: 6, rowspan: 3 }),
416
+ ];
417
+ const next = stepPlaced(tiles, 0, 1, 0, 12);
418
+ expect(at(next, "a")).toEqual([2, 1]);
419
+ expect(at(next, "b")).toEqual([5, 1]);
420
+ expect(at(next, "c")).toEqual([5, 7]);
421
+ });
422
+
423
+ it("leaves the tiles as they were at the grid's edge", () => {
424
+ const tiles = stacked();
425
+ const next = stepPlaced(tiles, 0, -1, 0, 12);
426
+ expect(next.every((each, i) => each === tiles[i])).toBe(true);
427
+ });
428
+ });
@@ -5,9 +5,11 @@ import {
5
5
  GRID_GAP_PX,
6
6
  MIN_TEXT_TILE_ROWS,
7
7
  MIN_TILE_ROWS,
8
+ MIN_VALUE_TILE_ROWS,
8
9
  PLACED_DEFAULT_ROWSPAN,
9
10
  TILE_ROW_PX,
10
11
  } from "../Dashboard/DashboardGrid";
12
+ import { isChartPick } from "./chartLine";
11
13
  import { isTextTile, type DashboardTile } from "./document";
12
14
 
13
15
  /**
@@ -29,9 +31,34 @@ export interface Cell {
29
31
  rowspan: number;
30
32
  }
31
33
 
32
- /** The fewest rows the builder offers a tile: a chart needs room to draw, prose does not. */
33
- export const minRowsOf = (tile: DashboardTile) =>
34
- isTextTile(tile) ? MIN_TEXT_TILE_ROWS : MIN_TILE_ROWS;
34
+ /** Value cards or a table, which hold their shape when short. */
35
+ const NOT_A_CHART = ".malloy-big-value, .malloy-table";
36
+
37
+ /**
38
+ * Whether a drawn result is only value cards or a table. A dashboard result
39
+ * can hold a chart beside its cards, and that chart needs a chart's rows; a
40
+ * sparkline in a card, or a chart in a table's cell, sizes with its host.
41
+ */
42
+ const drawsNoChart = (frame: Element) =>
43
+ frame.querySelector(NOT_A_CHART) !== null &&
44
+ ![...frame.querySelectorAll(".malloy-chart")].some(
45
+ (chart) => chart.closest(NOT_A_CHART) === null,
46
+ );
47
+
48
+ /**
49
+ * The fewest rows the builder offers a tile: a chart needs three to draw its
50
+ * plot at all (at two a line chart had no plot area and the renderer failed
51
+ * on it); value cards and a table fit in two, the cards drawing compact;
52
+ * prose fits in one. Which a query tile is comes from what it draws, so
53
+ * `frame` is the tile's element when the caller has it; without it, a query
54
+ * tile is taken for a chart.
55
+ */
56
+ export const minRowsOf = (tile: DashboardTile, frame?: Element | null) =>
57
+ isTextTile(tile)
58
+ ? MIN_TEXT_TILE_ROWS
59
+ : frame && drawsNoChart(frame)
60
+ ? MIN_VALUE_TILE_ROWS
61
+ : MIN_TILE_ROWS;
35
62
 
36
63
  /** Rows a tile takes on a placed report: its own, or its kind's default. */
37
64
  export const rowsOf = (tile: DashboardTile) =>
@@ -213,16 +240,24 @@ export function placeWhereDrawn(
213
240
  1,
214
241
  Math.round((box.width + GRID_GAP_PX) / (track + GRID_GAP_PX)),
215
242
  );
243
+ const cell = cellAt(box.left, box.top, colspan, columns, track);
244
+ // Its top and bottom are each taken to the nearest row line, rather
245
+ // than its height rounded on its own: tiles that touched still touch,
246
+ // so a whole page's rounding never adds up and pushes rows down. No
247
+ // edge moves more than half a row. Except a text tile's bottom, which
248
+ // only ever moves down: a chart redraws at whatever height it gets,
249
+ // but prose cannot shrink, and a bottom rounded up by half a row left
250
+ // its last line scrolling out of a one-row tile.
251
+ const bottom = (box.top + box.height + GRID_GAP_PX) / ROW_STEP;
252
+ const lastRow = isTextTile(tile)
253
+ ? Math.ceil(bottom - 0.02)
254
+ : Math.round(bottom);
216
255
  return {
217
256
  ...rest,
218
- ...cellAt(box.left, box.top, colspan, columns, track),
257
+ ...cell,
219
258
  colspan,
220
259
  rowspan:
221
- tile.rowspan ??
222
- Math.max(
223
- minRowsOf(tile),
224
- Math.round((box.height + GRID_GAP_PX) / ROW_STEP),
225
- ),
260
+ tile.rowspan ?? Math.max(minRowsOf(tile), lastRow - cell.row + 1),
226
261
  };
227
262
  });
228
263
  return settle(placed, columns);
@@ -248,3 +283,138 @@ export function placeAtEnd(
248
283
  i === index ? { ...tile, row: bottom, col: 1 } : tile,
249
284
  );
250
285
  }
286
+
287
+ /**
288
+ * The tiles slid up as far as each will go, top to bottom and then left to
289
+ * right, so every gap above a tile closes; nothing moves sideways. A tile
290
+ * with no place is left for the grid to place.
291
+ */
292
+ export function pack(
293
+ tiles: readonly DashboardTile[],
294
+ columns: number,
295
+ ): DashboardTile[] {
296
+ const out = tiles.map((tile) => ({ ...tile }));
297
+ const held: Cell[] = [];
298
+ const order = out
299
+ .map((tile, index) => ({ tile, index }))
300
+ .filter(({ tile }) => tile.row !== undefined && tile.col !== undefined)
301
+ .sort(
302
+ (a, b) =>
303
+ (a.tile.row ?? 0) - (b.tile.row ?? 0) ||
304
+ (a.tile.col ?? 0) - (b.tile.col ?? 0) ||
305
+ a.index - b.index,
306
+ );
307
+ for (const { index } of order) {
308
+ const cell = cellOf(out[index], columns);
309
+ if (!cell) continue;
310
+ while (
311
+ cell.row > 1 &&
312
+ !held.some((other) => overlaps({ ...cell, row: cell.row - 1 }, other))
313
+ )
314
+ cell.row -= 1;
315
+ out[index].row = cell.row;
316
+ out[index].col = cell.col;
317
+ held.push(cell);
318
+ }
319
+ return out;
320
+ }
321
+
322
+ /** Whether packing would move anything: the action is offered only then. */
323
+ export const hasGaps = (tiles: readonly DashboardTile[], columns: number) =>
324
+ pack(tiles, columns).some(
325
+ (tile, index) =>
326
+ tile.row !== tiles[index].row || tile.col !== tiles[index].col,
327
+ );
328
+
329
+ /**
330
+ * The tiles with their places taken off, so the report flows again in the
331
+ * order it is read. Widths and heights stay; a row break means nothing to a
332
+ * placed report, so none is set.
333
+ */
334
+ export function flowTiles(tiles: readonly DashboardTile[]): DashboardTile[] {
335
+ return inReadingOrder(tiles).map((tile) => {
336
+ const { row: _row, col: _col, ...rest } = tile;
337
+ return rest as DashboardTile;
338
+ });
339
+ }
340
+
341
+ /** The tiles with the one at `index` set to `at`, nothing else changed: a keyboard step, before it settles. */
342
+ export const stepTo = (
343
+ tiles: readonly DashboardTile[],
344
+ index: number,
345
+ at: { row: number; col: number },
346
+ ): DashboardTile[] =>
347
+ tiles.map((tile, i) => (i === index ? { ...tile, ...at } : tile));
348
+
349
+ /**
350
+ * A placed tile moved one cell by the keyboard, settled. A step into the one
351
+ * tile beside it in that direction swaps the two, so Down past a tile is the
352
+ * mirror of Up past it; otherwise the tile steps and whatever it lands on is
353
+ * pushed down. Returns the tiles unchanged when the tile is at the grid's edge.
354
+ */
355
+ export function stepPlaced(
356
+ tiles: readonly DashboardTile[],
357
+ index: number,
358
+ rows: -1 | 0 | 1,
359
+ cols: -1 | 0 | 1,
360
+ columns: number,
361
+ ): DashboardTile[] {
362
+ const cell = cellOf(tiles[index], columns);
363
+ if (!cell) return [...tiles];
364
+ const to = {
365
+ row: Math.max(1, cell.row + rows),
366
+ // Held so the tile's right edge stays on the grid.
367
+ col: Math.min(Math.max(1, cell.col + cols), columns - cell.colspan + 1),
368
+ };
369
+ if (to.row === cell.row && to.col === cell.col) return [...tiles];
370
+ const moved = { ...cell, ...to };
371
+ const blockers = tiles.flatMap((each, i) => {
372
+ const other = i === index ? undefined : cellOf(each, columns);
373
+ return other && overlaps(moved, other) && !overlaps(cell, other)
374
+ ? [{ i, other }]
375
+ : [];
376
+ });
377
+ const swap = blockers.length === 1 ? blockers[0] : undefined;
378
+ if (!swap) return settle(stepTo(tiles, index, to), columns, index);
379
+ const { i, other } = swap;
380
+ const out = tiles.map((tile) => ({ ...tile }));
381
+ if (rows > 0) {
382
+ out[i].row = cell.row;
383
+ out[index].row = cell.row + other.rowspan;
384
+ } else if (rows < 0) {
385
+ out[index].row = other.row;
386
+ out[i].row = other.row + cell.rowspan;
387
+ } else if (cols > 0) {
388
+ out[i].col = cell.col;
389
+ out[index].col = cell.col + other.colspan;
390
+ } else {
391
+ out[index].col = other.col;
392
+ out[i].col = other.col + cell.colspan;
393
+ }
394
+ return settle(out, columns, index);
395
+ }
396
+
397
+ /**
398
+ * The widest a tile may be dragged: the whole grid, or, for a placed tile, up
399
+ * to the grid's right edge from its column. A right edge dragged past the grid
400
+ * stops there; it never moves the tile's left edge.
401
+ */
402
+ export const widestFrom = (
403
+ tile: DashboardTile | undefined,
404
+ columns: number,
405
+ ): number =>
406
+ tile?.col === undefined ? columns : Math.max(1, columns - tile.col + 1);
407
+
408
+ /**
409
+ * A tile given a chart that plots (anything but value cards or a table) at
410
+ * fewer rows than a chart draws in, raised to that floor. A tile set to two
411
+ * rows as a table and then switched to a line chart in its menu would
412
+ * otherwise keep two rows, where the plot has no room and the renderer fails.
413
+ */
414
+ export function holdChartRows(tile: DashboardTile): DashboardTile {
415
+ if (isTextTile(tile) || tile.rowspan === undefined) return tile;
416
+ const plots = isChartPick(tile.chart) && tile.chart !== "big_value";
417
+ return plots && tile.rowspan < MIN_TILE_ROWS
418
+ ? { ...tile, rowspan: MIN_TILE_ROWS }
419
+ : tile;
420
+ }
@@ -192,42 +192,32 @@ describe("blockAbove", () => {
192
192
  });
193
193
 
194
194
  describe("readDashboardDocument", () => {
195
- it("reads a width spelled only as the dashboard_columns alias", async () => {
196
- const doc = await read(
197
- SIMPLE.replace(
198
- '"a -> by_cat"] givens { CATEGORY="Jeans" } } dashboard { columns=12 }',
199
- '"a -> by_cat"] givens { CATEGORY="Jeans" } dashboard_columns=8 }',
200
- ),
201
- );
202
- expect(doc.columns).toBe(8);
203
- });
204
-
205
195
  describe("a width written badly", () => {
206
196
  const withTag = (tagLine: string) =>
207
197
  SIMPLE.replace(/^## artifact.*$/m, tagLine);
208
198
 
209
- it("lets a written columns win even when it is not a width", async () => {
199
+ it("leaves the default width for a columns that is not a width", async () => {
210
200
  const doc = await read(
211
201
  withTag(
212
- '## artifact { tiles=["a -> by_cat"] dashboard_columns=8 } dashboard { columns=1.5 }',
202
+ '## artifact { tiles=["a -> by_cat"] } dashboard { columns=1.5 }',
213
203
  ),
214
204
  );
215
205
  expect(doc.columns).toBeUndefined();
216
206
  });
217
207
 
218
- it("reads the alias, spaced round its =, when no columns is written", async () => {
208
+ it("takes text that only begins with digits as no width", async () => {
219
209
  const doc = await read(
220
210
  withTag(
221
- '## artifact { tiles=["a -> by_cat"] dashboard_columns = 8 }',
211
+ '## artifact { tiles=["a -> by_cat"] } dashboard { columns="8px" }',
222
212
  ),
223
213
  );
224
- expect(doc.columns).toBe(8);
214
+ expect(doc.columns).toBeUndefined();
225
215
  });
226
216
 
227
- it("takes text that only begins with digits as no width", async () => {
217
+ it("reads no width from the removed dashboard_columns spelling", async () => {
228
218
  const doc = await read(
229
219
  withTag(
230
- '## artifact { tiles=["a -> by_cat"] dashboard_columns=8px }',
220
+ '## artifact { tiles=["a -> by_cat"] dashboard_columns=8 }',
231
221
  ),
232
222
  );
233
223
  expect(doc.columns).toBeUndefined();
@@ -721,14 +721,11 @@ async function readDocumentText(sourceText: string): Promise<ReadResult> {
721
721
  if (value !== undefined) startingGivens[key] = value;
722
722
  }
723
723
 
724
- // The server's rule: a written `dashboard { columns }` wins even when it is
725
- // not a width (the default width then applies), and the alias only counts
726
- // beside `tiles`.
724
+ // The server's rule: a `dashboard { columns }` that is not a width leaves
725
+ // the default width.
727
726
  const columnsTag = tag?.tag("dashboard")?.has("columns")
728
727
  ? gridWidth(tag.tag("dashboard"), "columns")
729
- : artifactTag?.array("tiles")
730
- ? gridWidth(artifactTag, "dashboard_columns")
731
- : undefined;
728
+ : undefined;
732
729
 
733
730
  return {
734
731
  ok: true,
@@ -3,9 +3,9 @@
3
3
 
4
4
  import { pointerIntersection } from "@dnd-kit/collision";
5
5
  import { Feedback, KeyboardSensor, PointerSensor } from "@dnd-kit/dom";
6
- import { useDroppable } from "@dnd-kit/react";
6
+ import { useDragDropManager, useDroppable } from "@dnd-kit/react";
7
7
  import { useSortable, type UseSortableInput } from "@dnd-kit/react/sortable";
8
- import type { ReactNode } from "react";
8
+ import { useEffect, type ReactNode } from "react";
9
9
 
10
10
  /**
11
11
  * The builder's drag and drop, on `@dnd-kit/react`.
@@ -162,3 +162,27 @@ export function GapDroppable({
162
162
  });
163
163
  return <>{children({ ref, isDropTarget })}</>;
164
164
  }
165
+
166
+ /**
167
+ * Escape cancels a drag wherever focus is. The library's pointer drag listens
168
+ * for Escape only on the element under the pointer, and a press on a tile's
169
+ * padding focuses nothing, so the key reached the page instead and the drop
170
+ * landed on release. Mounted inside the drag provider while a drag is live.
171
+ */
172
+ export function EscapeCancelsDrag({ active }: { active: boolean }) {
173
+ const manager = useDragDropManager();
174
+ useEffect(() => {
175
+ if (!active || !manager) return;
176
+ const onKey = (event: KeyboardEvent) => {
177
+ if (event.key !== "Escape" || manager.dragOperation.status.idle)
178
+ return;
179
+ // The drag's, not the builder's: it must not also drop the selection.
180
+ event.preventDefault();
181
+ event.stopPropagation();
182
+ manager.actions.stop({ event, canceled: true });
183
+ };
184
+ window.addEventListener("keydown", onKey, true);
185
+ return () => window.removeEventListener("keydown", onKey, true);
186
+ }, [active, manager]);
187
+ return null;
188
+ }