derive-dashboards 0.4.0 → 0.5.1

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 (84) hide show
  1. package/README.md +2 -3
  2. package/dist/cli/check.mjs +36 -1
  3. package/dist/cli/doctor.mjs +2 -2
  4. package/dist/core/document/display-entries.mjs +48 -0
  5. package/dist/core/document/display.d.mts +15 -3
  6. package/dist/core/document/display.mjs +35 -11
  7. package/dist/core/engine/filter.mjs +4 -2
  8. package/dist/core/engine/version.d.mts +1 -1
  9. package/dist/core/engine/version.mjs +1 -1
  10. package/dist/core/error/codes.d.mts +2 -0
  11. package/dist/core/error/codes.mjs +2 -0
  12. package/dist/core/index.d.mts +4 -3
  13. package/dist/core/index.mjs +8 -7
  14. package/dist/core/model/catalog/check.mjs +11 -5
  15. package/dist/core/model/member.mjs +6 -1
  16. package/dist/core/model/validate/members.mjs +31 -1
  17. package/dist/core/oracle/visibility.mjs +3 -1
  18. package/dist/core/query/drill/line.mjs +2 -2
  19. package/dist/core/query/to-wire.d.mts +7 -0
  20. package/dist/core/query/to-wire.mjs +18 -7
  21. package/dist/core/result/additive.d.mts +9 -0
  22. package/dist/core/result/additive.mjs +59 -0
  23. package/dist/core/result/columns.mjs +8 -2
  24. package/dist/core/result/types.d.mts +12 -0
  25. package/dist/core/schema/answer-parts.mjs +2 -1
  26. package/dist/core/schema/answers.d.mts +6 -0
  27. package/dist/core/types/api.d.mts +1 -1
  28. package/dist/core/types/api.mjs +1 -1
  29. package/dist/handler.mjs +10 -2
  30. package/dist/index.mjs +1 -1
  31. package/dist/llms.txt +1 -1
  32. package/dist/react/History.mjs +1 -1
  33. package/dist/react/Tile.mjs +18 -10
  34. package/dist/react/builder/FilterEditor.mjs +2 -7
  35. package/dist/react/builder/Preview.mjs +1 -1
  36. package/dist/react/columns.mjs +15 -0
  37. package/dist/react/context.d.mts +7 -0
  38. package/dist/react/context.mjs +3 -0
  39. package/dist/react/digits.mjs +46 -0
  40. package/dist/react/drill/Bars.mjs +2 -1
  41. package/dist/react/drill/Controls.mjs +2 -1
  42. package/dist/react/drill/Header.mjs +2 -1
  43. package/dist/react/drill/Items.mjs +6 -1
  44. package/dist/react/drill/Notes.mjs +2 -1
  45. package/dist/react/drill/item-parts.mjs +2 -1
  46. package/dist/react/english.mjs +4 -0
  47. package/dist/react/export/ExportButton.mjs +23 -0
  48. package/dist/react/export/csv.d.mts +9 -0
  49. package/dist/react/export/csv.mjs +42 -0
  50. package/dist/react/export/download.d.mts +5 -0
  51. package/dist/react/export/download.mjs +61 -0
  52. package/dist/react/format-time.d.mts +15 -0
  53. package/dist/react/format-time.mjs +71 -0
  54. package/dist/react/format.d.mts +6 -16
  55. package/dist/react/format.mjs +48 -86
  56. package/dist/react/index.d.mts +8 -3
  57. package/dist/react/index.mjs +8 -3
  58. package/dist/react/messages.d.mts +8 -0
  59. package/dist/react/renderers/entries.mjs +15 -0
  60. package/dist/react/renderers/exact.d.mts +6 -0
  61. package/dist/react/renderers/exact.mjs +68 -0
  62. package/dist/react/renderers/index.d.mts +5 -11
  63. package/dist/react/renderers/index.mjs +70 -84
  64. package/dist/react/renderers/list.mjs +5 -17
  65. package/dist/react/renderers/table-cells.mjs +130 -0
  66. package/dist/react/renderers/table-fit.mjs +52 -0
  67. package/dist/react/renderers/table-head.mjs +47 -0
  68. package/dist/react/renderers/table-measure.mjs +49 -0
  69. package/dist/react/renderers/table-row.mjs +61 -0
  70. package/dist/react/renderers/table-scale.mjs +70 -0
  71. package/dist/react/renderers/table-sort.mjs +99 -0
  72. package/dist/react/renderers/table.d.mts +3 -0
  73. package/dist/react/renderers/table.mjs +121 -0
  74. package/dist/react/series.mjs +1 -1
  75. package/dist/react/theme-unlayered.css +3144 -0
  76. package/dist/react/theme-unlayered.css.d.ts +1 -0
  77. package/dist/react/theme.css +379 -8
  78. package/dist/recharts/axes.mjs +13 -10
  79. package/dist/recharts/axis.mjs +25 -1
  80. package/dist/recharts/bar.d.mts +2 -1
  81. package/dist/recharts/bar.mjs +29 -6
  82. package/dist/recharts/parts.mjs +1 -1
  83. package/dist/skills/derive-dashboards/SKILL.md +13 -1
  84. package/package.json +42 -4
@@ -22,13 +22,24 @@ function laterCalc(alias, calcIndex) {
22
22
  const { kind, index } = aliasPart(alias);
23
23
  return kind === "calc" && index + 1 > calcIndex;
24
24
  }
25
- /** Aliases in stored order: m1.. for measures, d1.. for dimensions, c1.. for calcs. */
25
+ /** A stored query's entries with their aliases, in stored order: m1.. for measures, d1.. for dimensions, c1.. for calcs. */
26
+ const aliasPairs = (stored) => [
27
+ ...stored.measures.map((entry, i) => [entry.id, `m${i + 1}`]),
28
+ ...(stored.dimensions ?? []).map((entry, i) => [entry.id, `d${i + 1}`]),
29
+ ...(stored.calc ?? []).map((entry, i) => [entry.id, `c${i + 1}`])
30
+ ];
31
+ /**
32
+ * The alias each entry of a stored query has in the query that runs, and so the id of its
33
+ * column in an answer, by the entry's editing id. For a reader that names entries as the
34
+ * widget does (a `display` option) and must find them in an answer. Of two entries with one id
35
+ * (which `toWire` refuses) the later is kept.
36
+ */
37
+ function entryAliases(stored) {
38
+ return new Map(aliasPairs(stored));
39
+ }
40
+ /** The aliases of a query that runs: as `entryAliases`, refusing two entries with one id. */
26
41
  function assignAliases(stored) {
27
- const pairs = [
28
- ...stored.measures.map((entry, i) => [entry.id, `m${i + 1}`]),
29
- ...(stored.dimensions ?? []).map((entry, i) => [entry.id, `d${i + 1}`]),
30
- ...(stored.calc ?? []).map((entry, i) => [entry.id, `c${i + 1}`])
31
- ];
42
+ const pairs = aliasPairs(stored);
32
43
  const aliases = new Map(pairs);
33
44
  const repeated = pairs.find(([id], i) => pairs.findIndex(([other]) => other === id) !== i);
34
45
  if (repeated) throw new QueryReferenceError(repeated[0], "Two entries share an id; one");
@@ -121,4 +132,4 @@ function toWire(stored) {
121
132
  aliasToId: Object.fromEntries([...aliases].map(([id, name]) => [name, id]))
122
133
  };
123
134
  }
124
- export { QueryReferenceError, toWire };
135
+ export { QueryReferenceError, entryAliases, toWire };
@@ -0,0 +1,9 @@
1
+ import { ResultColumn } from "./types.mjs";
2
+ /**
3
+ * Whether the parts of a split may be stacked or summed into a whole: only where the answer's
4
+ * column says its values add up. An answer that does not say (one from an older server) is
5
+ * never stacked or summed. Every renderer asks here; none reads `additive` itself. The parts
6
+ * are the groups of one time bucket: a share of its bucket adds up across them, which is what
7
+ * a chart stacks, and not across the buckets, each of which has its own whole.
8
+ */
9
+ export declare function addsUp(column: Pick<ResultColumn, "additive">): boolean;
@@ -0,0 +1,59 @@
1
+ // src/result/additive.ts
2
+ /**
3
+ * Whether the parts of a split may be stacked or summed into a whole: only where the answer's
4
+ * column says its values add up. An answer that does not say (one from an older server) is
5
+ * never stacked or summed. Every renderer asks here; none reads `additive` itself. The parts
6
+ * are the groups of one time bucket: a share of its bucket adds up across them, which is what
7
+ * a chart stacks, and not across the buckets, each of which has its own whole.
8
+ */
9
+ function addsUp(column) {
10
+ return column.additive === true;
11
+ }
12
+ /**
13
+ * What two operands make, where it is not "neither". A value that adds up still does when it
14
+ * is scaled: times or over a constant. A constant offset does not: it would be counted once
15
+ * for each part. Nor does a sum or a difference of two values that each add up: a calc has no
16
+ * value where either has none, so a part with one and not the other would be left out whole
17
+ * (gross less refunds, where a part has no refunds).
18
+ */
19
+ const MAKES = {
20
+ "+": { "constant constant": "constant" },
21
+ "-": { "constant constant": "constant" },
22
+ "*": {
23
+ "additive constant": "additive",
24
+ "constant additive": "additive",
25
+ "constant constant": "constant"
26
+ },
27
+ "/": {
28
+ "additive constant": "additive",
29
+ "constant constant": "constant"
30
+ }
31
+ };
32
+ /**
33
+ * A ref to the total or the bucket is the same in every part. A ref to the entry's own row
34
+ * adds up when the entry does. A previous value does not: the comparison period can hold a
35
+ * group the period asked lacks, and that group is a part of the whole's previous value only.
36
+ */
37
+ function refAcross(node, additive) {
38
+ if (node.of === "total" || node.of === "bucket") return "constant";
39
+ return node.of === void 0 && additive.get(node.ref) === true ? "additive" : "neither";
40
+ }
41
+ function across(node, additive) {
42
+ if ("lit" in node) return "constant";
43
+ if ("ref" in node) return refAcross(node, additive);
44
+ const first = across(node.args[0], additive);
45
+ if (node.op === "abs") return first === "constant" ? "constant" : "neither";
46
+ return MAKES[node.op][`${first} ${across(node.args[1], additive)}`] ?? "neither";
47
+ }
48
+ /**
49
+ * Whether a calc's values add up across the parts of a split, from its formula: `additive`
50
+ * says it of each entry the formula can name (the measures, and the calcs before it). A calc
51
+ * adds up when it is one value that adds up, scaled by constants: a share of the total does,
52
+ * and a rate, an offset or a sum of two entries does not. Cells are rounded when written, so
53
+ * the parts of a quotient add up to the whole to within that rounding. A part with no value
54
+ * adds nothing.
55
+ */
56
+ function calcAddsUp(formula, additive) {
57
+ return across(formula, additive) === "additive";
58
+ }
59
+ export { addsUp, calcAddsUp };
@@ -1,6 +1,7 @@
1
- import { resolveDimension, resolveMeasure } from "../model/member.mjs";
1
+ import { mergesBySum, resolveDimension, resolveMeasure } from "../model/member.mjs";
2
2
  import { idRole } from "../query/alias.mjs";
3
3
  import { formulaRefs } from "../query/formulas.mjs";
4
+ import { calcAddsUp } from "./additive.mjs";
4
5
  // src/result/columns.ts
5
6
  /** "createdAt" reads "Created at". */
6
7
  const words = (name) => {
@@ -112,9 +113,11 @@ function resultColumns(model, query) {
112
113
  role: "measure",
113
114
  label: m.label ?? memberLabel(m.measure, def?.label),
114
115
  type: def === void 0 ? "float" : measureType(model, query.source, def),
115
- ...readsAs(def)
116
+ ...readsAs(def),
117
+ additive: def !== void 0 && mergesBySum(def)
116
118
  };
117
119
  });
120
+ const adds = new Map(measures.map((c) => [c.id, c.additive === true]));
118
121
  const types = new Map(measures.map((c) => [c.id, c.type]));
119
122
  const units = new Map(measures.flatMap((c) => c.unit === void 0 ? [] : [[c.id, c.unit]]));
120
123
  const calcs = (query.calc ?? []).map((c, i) => {
@@ -122,11 +125,14 @@ function resultColumns(model, query) {
122
125
  types.set(c.id, type);
123
126
  const unit = c.format === "currency" ? sharedUnit(c.formula, units) : void 0;
124
127
  if (unit !== void 0) units.set(c.id, unit);
128
+ const additive = calcAddsUp(c.formula, adds);
129
+ adds.set(c.id, additive);
125
130
  return {
126
131
  id: c.id,
127
132
  role: "calc",
128
133
  label: c.label ?? `Calc ${i + 1}`,
129
134
  type,
135
+ additive,
130
136
  ...c.format === void 0 ? {} : { format: c.format },
131
137
  ...formulaRefs(c.formula).some((r) => r.of === "previous") ? { signed: true } : {},
132
138
  ...unit === void 0 ? {} : { unit }
@@ -28,6 +28,18 @@ export type ResultColumn = {
28
28
  signed?: true;
29
29
  /** On a ratio read as a percent: its values are fractions of one (0.55 reads 55%), not points. */
30
30
  fraction?: true;
31
+ /**
32
+ * On a measure and a calc: whether its values add up across the parts of a split, so the
33
+ * parts may be stacked or summed into a whole. A measure says it by the model's merge rule:
34
+ * true for a count or a sum, false for an average, a rate, a percentile, a minimum, a maximum
35
+ * or a distinct count. A calc says it by its formula: true for one value that adds up, times
36
+ * or over a constant (a share of the total); false for a rate, a constant offset, a sum or
37
+ * difference of two entries (a part may have one and not the other) or a previous value. The
38
+ * parts are the groups of one time bucket: a share of its bucket adds up across them, not
39
+ * across the buckets. Absent only on an answer from an older server, which a renderer never
40
+ * stacks or sums. Read it with `addsUp(column)`, never by itself.
41
+ */
42
+ additive?: boolean;
31
43
  };
32
44
  /** A column of a records page: the member it shows, labelled and typed from the model. */
33
45
  export type RecordColumn = {
@@ -44,7 +44,8 @@ const column = z.looseObject({
44
44
  "duration"
45
45
  ]).exactOptional(),
46
46
  signed: z.literal(true).exactOptional(),
47
- fraction: z.literal(true).exactOptional()
47
+ fraction: z.literal(true).exactOptional(),
48
+ additive: z.boolean().exactOptional()
48
49
  });
49
50
  const resolvedRange = z.looseObject({
50
51
  from: z.string(),
@@ -58,6 +58,7 @@ export declare const tileLineSchema: z.ZodUnion<readonly [z.ZodObject<{
58
58
  }>>;
59
59
  signed: z.ZodExactOptional<z.ZodLiteral<true>>;
60
60
  fraction: z.ZodExactOptional<z.ZodLiteral<true>>;
61
+ additive: z.ZodExactOptional<z.ZodBoolean>;
61
62
  }, z.core.$loose>>>;
62
63
  time: z.ZodExactOptional<z.ZodObject<{
63
64
  grain: z.ZodEnum<{
@@ -2307,6 +2308,7 @@ export declare const answerSchemas: {
2307
2308
  }>>;
2308
2309
  signed: z.ZodExactOptional<z.ZodLiteral<true>>;
2309
2310
  fraction: z.ZodExactOptional<z.ZodLiteral<true>>;
2311
+ additive: z.ZodExactOptional<z.ZodBoolean>;
2310
2312
  }, z.core.$loose>>;
2311
2313
  noun: z.ZodExactOptional<z.ZodObject<{
2312
2314
  one: z.ZodString;
@@ -2597,6 +2599,7 @@ export declare const answerSchemas: {
2597
2599
  }>>;
2598
2600
  signed: z.ZodExactOptional<z.ZodLiteral<true>>;
2599
2601
  fraction: z.ZodExactOptional<z.ZodLiteral<true>>;
2602
+ additive: z.ZodExactOptional<z.ZodBoolean>;
2600
2603
  }, z.core.$loose>>>;
2601
2604
  time: z.ZodExactOptional<z.ZodObject<{
2602
2605
  grain: z.ZodEnum<{
@@ -3100,6 +3103,7 @@ export declare const answerSchemas: {
3100
3103
  }>>;
3101
3104
  signed: z.ZodExactOptional<z.ZodLiteral<true>>;
3102
3105
  fraction: z.ZodExactOptional<z.ZodLiteral<true>>;
3106
+ additive: z.ZodExactOptional<z.ZodBoolean>;
3103
3107
  }, z.core.$loose>>>;
3104
3108
  time: z.ZodExactOptional<z.ZodObject<{
3105
3109
  grain: z.ZodEnum<{
@@ -3508,6 +3512,7 @@ export declare const answerSchemas: {
3508
3512
  }>>;
3509
3513
  signed: z.ZodExactOptional<z.ZodLiteral<true>>;
3510
3514
  fraction: z.ZodExactOptional<z.ZodLiteral<true>>;
3515
+ additive: z.ZodExactOptional<z.ZodBoolean>;
3511
3516
  }, z.core.$loose>>;
3512
3517
  noun: z.ZodExactOptional<z.ZodObject<{
3513
3518
  one: z.ZodString;
@@ -3798,6 +3803,7 @@ export declare const answerSchemas: {
3798
3803
  }>>;
3799
3804
  signed: z.ZodExactOptional<z.ZodLiteral<true>>;
3800
3805
  fraction: z.ZodExactOptional<z.ZodLiteral<true>>;
3806
+ additive: z.ZodExactOptional<z.ZodBoolean>;
3801
3807
  }, z.core.$loose>>>;
3802
3808
  time: z.ZodExactOptional<z.ZodObject<{
3803
3809
  grain: z.ZodEnum<{
@@ -344,4 +344,4 @@ export type CoreContract = {
344
344
  * than reading a shape it does not know. A test recomputes it from the answer schemas, so a
345
345
  * change to an answer fails until this is updated.
346
346
  */
347
- export declare const CONTRACT_VERSION = "ed1ec2bd454a1d16";
347
+ export declare const CONTRACT_VERSION = "7ce2908a7608aacd";
@@ -5,5 +5,5 @@
5
5
  * than reading a shape it does not know. A test recomputes it from the answer schemas, so a
6
6
  * change to an answer fails until this is updated.
7
7
  */
8
- const CONTRACT_VERSION = "ed1ec2bd454a1d16";
8
+ const CONTRACT_VERSION = "7ce2908a7608aacd";
9
9
  export { CONTRACT_VERSION };
package/dist/handler.mjs CHANGED
@@ -168,9 +168,17 @@ function notFound(rt, router, method, path) {
168
168
  const where = path.startsWith(base) ? `No endpoint answers ${method} ${path}.` : `${method} ${path} is outside basePath "${base}". Mount the handler there, or set basePath to where it is mounted.`;
169
169
  return new HttpError(404, "NOT_FOUND", where);
170
170
  }
171
- /** Every answer says which contract it keeps, so a client from another release can tell. */
171
+ /**
172
+ * Every answer says which contract it keeps, so a client from another release can tell; the
173
+ * header is exposed to cross-origin pages too (the app's CORS still decides who may read).
174
+ */
172
175
  function stamped(response) {
173
- response.headers.set("dd-contract", CONTRACT_VERSION);
176
+ const { headers } = response;
177
+ headers.set("dd-contract", CONTRACT_VERSION);
178
+ const exposed = headers.get("access-control-expose-headers")?.trim() ?? "";
179
+ const names = new Set(exposed.toLowerCase().split(/\s*,\s*/u));
180
+ const next = exposed ? `${exposed}, dd-contract` : "dd-contract";
181
+ if (!names.has("dd-contract") && !names.has("*")) headers.set("access-control-expose-headers", next);
174
182
  return response;
175
183
  }
176
184
  /**
package/dist/index.mjs CHANGED
@@ -29,7 +29,7 @@ function checkedDashboards(options) {
29
29
  const wrong = documentDisplayIssues(loaded.doc);
30
30
  if (wrong.length > 0) {
31
31
  const problems = wrong.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
32
- throw new Error(`The dashboard "${d.key}" has display options of the wrong type: ${problems}`);
32
+ throw new Error(`The dashboard "${d.key}" has display options to fix: ${problems}`);
33
33
  }
34
34
  return {
35
35
  key: d.key,
package/dist/llms.txt CHANGED
@@ -9,7 +9,7 @@ Install skill for coding agents: `npx skills add derive-to/dashboards --skill de
9
9
  - [Quick start](https://github.com/derive-to/dashboards/blob/main/docs/quick-start.md): install, describe your data, mount the handler, show a dashboard, drill in.
10
10
  - [Concepts](https://github.com/derive-to/dashboards/blob/main/docs/concepts.md): the model, measures, joins, tenancy and row policies, access, documents, drill-in.
11
11
  - [Filters](https://github.com/derive-to/dashboards/blob/main/docs/filters.md): the built-in filter bar, theming, options, words, the shadcn copy, custom bars.
12
- - [React](https://github.com/derive-to/dashboards/blob/main/docs/react.md): provider, Dashboard, editing UI, URL state, drill parts, widget builder.
12
+ - [React](https://github.com/derive-to/dashboards/blob/main/docs/react.md): provider, Dashboard, editing UI, URL state, drill parts, widget builder; the tiles and their `display` options (a number's `value` and `secondary`, a table's `bars`, `heat` and `compact`, a list's lines); a table a viewer sorts; a tile's answer as CSV (`csv={false}` turns the button off, `downloadCsv` and `csvOf` for your own).
13
13
  - [CLI](https://github.com/derive-to/dashboards/blob/main/docs/cli.md): init, check, generate, create-tables, add, importing from dbt or Cube.
14
14
  - [Endpoints](https://github.com/derive-to/dashboards/blob/main/docs/endpoints.md): every handler endpoint, its body and answer.
15
15
  - [MCP](https://github.com/derive-to/dashboards/blob/main/docs/mcp.md): tools that let agents query and edit dashboards as themselves.
@@ -1,7 +1,7 @@
1
1
  import { CancelRestore } from "./CancelRestore.mjs";
2
2
  import { useDashboards } from "./context.mjs";
3
3
  import { LIST_KEY } from "./DashboardList.mjs";
4
- import { formatInstant } from "./format.mjs";
4
+ import { formatInstant } from "./format-time.mjs";
5
5
  import { Panel } from "./Panel.mjs";
6
6
  import { ReadFailed } from "./ReadFailed.mjs";
7
7
  import { useState } from "react";
@@ -1,6 +1,7 @@
1
1
  import { useDashboards } from "./context.mjs";
2
2
  import { useTileDrill } from "./drill/host.mjs";
3
- import { formatInstantAt } from "./format.mjs";
3
+ import { ExportButton } from "./export/ExportButton.mjs";
4
+ import { formatInstantAt } from "./format-time.mjs";
4
5
  import { SeriesSlotsContext } from "./scope.mjs";
5
6
  import { seriesSlots } from "./series-slots.mjs";
6
7
  import { memo, useContext, useState } from "react";
@@ -150,15 +151,22 @@ const Tile = memo(function Tile(props) {
150
151
  props.badge,
151
152
  /* @__PURE__ */ jsxs("span", {
152
153
  className: "dd-tile-actions",
153
- children: [hasRows(props.result) && drill !== void 0 ? /* @__PURE__ */ jsx("button", {
154
- type: "button",
155
- className: "dd-tile-rows",
156
- "aria-label": messages.rowsBehind(props.widget.title),
157
- onClick: () => {
158
- drill.openAll();
159
- },
160
- children: messages.rows
161
- }) : null, props.actions]
154
+ children: [
155
+ hasRows(props.result) && drill !== void 0 ? /* @__PURE__ */ jsx("button", {
156
+ type: "button",
157
+ className: "dd-tile-rows",
158
+ "aria-label": messages.rowsBehind(props.widget.title),
159
+ onClick: () => {
160
+ drill.openAll();
161
+ },
162
+ children: messages.rows
163
+ }) : null,
164
+ drawable(props.result) ? /* @__PURE__ */ jsx(ExportButton, {
165
+ title: props.widget.title,
166
+ answer: props.result
167
+ }) : null,
168
+ props.actions
169
+ ]
162
170
  })
163
171
  ]
164
172
  }),
@@ -1,3 +1,4 @@
1
+ import { isNumberType } from "../columns.mjs";
1
2
  import { useDashboards } from "../context.mjs";
2
3
  import { fieldOptions } from "./options.mjs";
3
4
  import { Chip } from "./Sections.mjs";
@@ -46,17 +47,11 @@ const NUMBER = /* @__PURE__ */ new Set([
46
47
  "lt",
47
48
  "lte"
48
49
  ]);
49
- const NUMERIC = /* @__PURE__ */ new Set([
50
- "number",
51
- "int",
52
- "decimal",
53
- "float"
54
- ]);
55
50
  /** A field's type for its operators (string, number or boolean), from the fields it can filter by. */
56
51
  function typeOf(b, member) {
57
52
  const source = b.state.query?.source ?? "";
58
53
  const type = fieldOptions(b.meta, source).find((o) => o.id === member)?.hint ?? "string";
59
- return NUMERIC.has(type) ? "number" : type;
54
+ return isNumberType(type) ? "number" : type;
60
55
  }
61
56
  /** Typed numbers, `count` of them, or undefined when one is missing or not a number. */
62
57
  function numbersOf(typed, count) {
@@ -1,5 +1,5 @@
1
1
  import { useDashboards } from "../context.mjs";
2
- import { TableTile } from "../renderers/index.mjs";
2
+ import { TableTile } from "../renderers/table.mjs";
3
3
  import { useBuilder } from "./useBuilder.mjs";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  // src/builder/Preview.tsx
@@ -0,0 +1,15 @@
1
+ import { roleOf } from "derive-dashboards/core";
2
+ // src/columns.ts
3
+ /** Whether a column holds values: a measure or a calc. */
4
+ const isValue = (column) => roleOf(column) === "measure" || roleOf(column) === "calc";
5
+ const NUMBER_TYPES = /* @__PURE__ */ new Set([
6
+ "number",
7
+ "int",
8
+ "decimal",
9
+ "float"
10
+ ]);
11
+ /** Whether a column's cells are numbers: a value, or a group that is a number. They are set to the right and never cut. */
12
+ const isNumeric = (column) => isValue(column) || NUMBER_TYPES.has(column.type);
13
+ /** Whether a column's type holds numbers. */
14
+ const isNumberType = (type) => NUMBER_TYPES.has(type);
15
+ export { isNumberType, isNumeric, isValue };
@@ -22,6 +22,8 @@ type Value = {
22
22
  renderers: Record<string, TileRenderer>;
23
23
  locale?: string;
24
24
  messages: Messages;
25
+ /** Whether a tile offers its answer as a CSV file. */
26
+ csv: boolean;
25
27
  authorName?: (author: Author) => string | undefined;
26
28
  /** Who answers and for whom: the viewer's key and the client, so no cache serves another viewer. */
27
29
  cacheScope: string;
@@ -39,6 +41,11 @@ export type DashboardsProviderProps = {
39
41
  * Pass it whenever the signed-in person can change without a page load.
40
42
  */
41
43
  viewerKey?: string;
44
+ /**
45
+ * Whether each tile offers its answer as a CSV file, made in the browser from the answer the
46
+ * tile already holds. On unless set to false.
47
+ */
48
+ csv?: boolean;
42
49
  /** A person's or agent's name, for the history; without it, versions show only when. */
43
50
  authorName?: (author: Author) => string | undefined;
44
51
  /** The link component every link the library draws uses, so they go through your router. */
@@ -20,6 +20,7 @@ const Context = createContext(null);
20
20
  const ownCache = { provider: () => /* @__PURE__ */ new Map() };
21
21
  function DashboardsProvider(props) {
22
22
  const { client, renderers, locale, messages, viewerKey, authorName, link, components, children } = props;
23
+ const csv = props.csv !== false;
23
24
  const cacheScope = `${viewerKey ?? ""}:${String(clientId(client))}`;
24
25
  const value = useMemo(() => ({
25
26
  client,
@@ -33,6 +34,7 @@ function DashboardsProvider(props) {
33
34
  ...ENGLISH,
34
35
  ...messages
35
36
  },
37
+ csv,
36
38
  ...authorName === void 0 ? {} : { authorName },
37
39
  ...link === void 0 ? {} : { link },
38
40
  components: {
@@ -45,6 +47,7 @@ function DashboardsProvider(props) {
45
47
  renderers,
46
48
  locale,
47
49
  messages,
50
+ csv,
48
51
  authorName,
49
52
  link,
50
53
  components
@@ -0,0 +1,46 @@
1
+ // src/digits.ts
2
+ /** Under this size a number that is not zero is written by its power of ten: a row of zeros is not read. */
3
+ const MINUTE = 1e-6;
4
+ /** A number too small for its places by its first two figures (0.0004), and under a millionth by those and its power of ten (5.6E-17). */
5
+ const fine = (size, minute = MINUTE) => size < minute ? {
6
+ notation: "scientific",
7
+ maximumSignificantDigits: 2
8
+ } : { maximumSignificantDigits: 2 };
9
+ /**
10
+ * How many digits a number keeps: `places` after the point, unless that would write a number
11
+ * that is not zero as zero. Then it keeps its first figures (`fine`), so a value never reads
12
+ * as nothing while it is something, nor as a row of zeros.
13
+ */
14
+ /** Whether a number that is not zero would be written as zero with `places` after the point. */
15
+ const lost = (value, places) => value !== 0 && Math.abs(value) < .5 * 10 ** -places;
16
+ const digitsFor = (value, places) => lost(value, places) ? fine(Math.abs(value)) : { maximumFractionDigits: places };
17
+ /**
18
+ * The digits an axis tick is written in, for a value and the whole it is a part of (1, or 100
19
+ * for percent points). Three figures hold every round step an axis takes (0.025, 12.5, 1.25K),
20
+ * where one decimal wrote 0.05, 0.1 and 0.15 all as 0.1. Under a millionth of the whole the
21
+ * figures come with their power of ten.
22
+ */
23
+ const tickDigits = (value, whole) => value !== 0 && Math.abs(value) < MINUTE * whole ? {
24
+ notation: "scientific",
25
+ maximumSignificantDigits: 3
26
+ } : {
27
+ notation: "compact",
28
+ maximumSignificantDigits: 3
29
+ };
30
+ /**
31
+ * The digits a percent is written in, from its value and the whole it is a part of (1 for a
32
+ * fraction, 100 for points). Whole percents read cleanly (67%); below 10% one decimal keeps
33
+ * small rates apart (4.5%); under a twentieth of a percent a value that is not zero keeps its
34
+ * first figures (`fine`), never "0.0%". The value is weighed against the whole, never divided
35
+ * by it: the smallest float divided by a hundred is zero.
36
+ */
37
+ function percentDigits(value, whole) {
38
+ const size = Math.abs(value);
39
+ if (value !== 0 && size < 5e-4 * whole) return fine(size, MINUTE * .01 * whole);
40
+ const places = size >= .1 * whole || value === 0 ? 0 : 1;
41
+ return {
42
+ minimumFractionDigits: places,
43
+ maximumFractionDigits: places
44
+ };
45
+ }
46
+ export { digitsFor, fine, lost, percentDigits, tickDigits };
@@ -1,5 +1,6 @@
1
+ import { formatBucket } from "../format-time.mjs";
1
2
  import { useDashboards } from "../context.mjs";
2
- import { formatBucket, formatCell, plotValue } from "../format.mjs";
3
+ import { formatCell, plotValue } from "../format.mjs";
3
4
  import { rowEntry } from "./state.mjs";
4
5
  import { isMark, roleOf } from "derive-dashboards/core";
5
6
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
@@ -1,5 +1,6 @@
1
+ import { formatInstantAt } from "../format-time.mjs";
1
2
  import { useDashboards } from "../context.mjs";
2
- import { formatCell, formatInstantAt } from "../format.mjs";
3
+ import { formatCell } from "../format.mjs";
3
4
  import { useEffect, useState } from "react";
4
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
6
  // src/drill/Controls.tsx
@@ -1,5 +1,6 @@
1
+ import { formatInstantAt } from "../format-time.mjs";
1
2
  import { useDashboards } from "../context.mjs";
2
- import { formatCell, formatInstantAt } from "../format.mjs";
3
+ import { formatCell } from "../format.mjs";
3
4
  import { countOf, countText } from "./counts.mjs";
4
5
  import { Notes, valueColumn } from "./Notes.mjs";
5
6
  import { useEffect, useRef } from "react";
@@ -1,3 +1,4 @@
1
+ import { isNumberType } from "../columns.mjs";
1
2
  import { useDashboards } from "../context.mjs";
2
3
  import { formatCell } from "../format.mjs";
3
4
  import { RowBody } from "../RowBody.mjs";
@@ -66,6 +67,7 @@ function Table(props) {
66
67
  children: named?.label ?? headOf(props.noun) ?? format.messages.drillItem
67
68
  }), rest.map((c) => /* @__PURE__ */ jsx("th", {
68
69
  scope: "col",
70
+ "data-numeric": isNumberType(c.type),
69
71
  children: c.label
70
72
  }, c.member))] }) }), /* @__PURE__ */ jsx("tbody", { children: props.items.map((item, i) => /* @__PURE__ */ jsxs("tr", { children: [/* @__PURE__ */ jsx("th", {
71
73
  scope: "row",
@@ -78,7 +80,10 @@ function Table(props) {
78
80
  noun: props.noun
79
81
  }, cell).title
80
82
  })
81
- }), rest.map((c) => /* @__PURE__ */ jsx("td", { children: formatCell(item.values[c.member] ?? null, columnShape(c), cell) }, c.member))] }, item.id)) })]
83
+ }), rest.map((c) => /* @__PURE__ */ jsx("td", {
84
+ "data-numeric": isNumberType(c.type),
85
+ children: formatCell(item.values[c.member] ?? null, columnShape(c), cell)
86
+ }, c.member))] }, item.id)) })]
82
87
  })
83
88
  });
84
89
  }
@@ -1,5 +1,6 @@
1
+ import { formatInstantAt } from "../format-time.mjs";
1
2
  import { useDashboards } from "../context.mjs";
2
- import { formatCell, formatInstantAt } from "../format.mjs";
3
+ import { formatCell } from "../format.mjs";
3
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
5
  // src/drill/Notes.tsx
5
6
  /** The value as the line reads it: a ratio as a percent when its column says so. */
@@ -1,4 +1,5 @@
1
- import { formatCell, formatInstantAt } from "../format.mjs";
1
+ import { formatInstantAt } from "../format-time.mjs";
2
+ import { formatCell } from "../format.mjs";
2
3
  // src/drill/item-parts.ts
3
4
  /** A column's own format for a cell: its type, its unit (a currency) and its time zone. */
4
5
  const columnShape = (c) => ({
@@ -12,6 +12,8 @@ const ENGLISH = {
12
12
  total: "Total",
13
13
  empty: "None",
14
14
  noValue: "–",
15
+ sortBy: (column) => `Sort by ${column}`,
16
+ showMoreRows: (more, of) => `Show ${more} more of ${of} rows`,
15
17
  loading: "Loading",
16
18
  noAccess: "You don't have access to this data",
17
19
  noData: "No data for this range",
@@ -27,6 +29,8 @@ const ENGLISH = {
27
29
  rowsShowing: (n, more) => `Showing ${String(n)} ${n === 1 ? "row" : "rows"}${more ? ", more to load" : ""}`,
28
30
  reset: "Reset",
29
31
  rowsBehind: (title) => `Rows behind ${title}`,
32
+ csv: "CSV",
33
+ csvLabel: (title) => `Download ${title} as CSV`,
30
34
  notFilteredBy: (controls) => `Not filtered by ${controls.join(", ")}`,
31
35
  firstRows: (count) => `Showing the first ${count} rows`,
32
36
  range: relativeLabel,
@@ -0,0 +1,23 @@
1
+ import { useDashboards } from "../context.mjs";
2
+ import { csvOf } from "./csv.mjs";
3
+ import { downloadCsv } from "./download.mjs";
4
+ import { jsx } from "react/jsx-runtime";
5
+ // src/export/ExportButton.tsx
6
+ /**
7
+ * A tile's button that saves its answer as a CSV file named by the tile's title: the rows and
8
+ * columns the tile shows, as data. Not drawn where the provider turns exports off.
9
+ */
10
+ function ExportButton({ title, answer }) {
11
+ const { messages, csv } = useDashboards();
12
+ if (!csv) return null;
13
+ return /* @__PURE__ */ jsx("button", {
14
+ type: "button",
15
+ className: "dd-tile-rows",
16
+ "aria-label": messages.csvLabel(title),
17
+ onClick: () => {
18
+ downloadCsv(title, csvOf(answer, messages));
19
+ },
20
+ children: messages.csv
21
+ });
22
+ }
23
+ export { ExportButton };
@@ -0,0 +1,9 @@
1
+ import { Messages } from "../messages.mjs";
2
+ import { TileAnswer } from "derive-dashboards/core";
3
+ type Answer = Pick<TileAnswer, "columns" | "rows">;
4
+ type Words = Pick<Messages, "other" | "total">;
5
+ /** The answer as rows of texts: its headings, then each row, every cell as it is exported. `words` name Other and a total. */
6
+ export declare function exportRows(answer: Answer, words: Words): string[][];
7
+ /** The answer as CSV text: a line per row, each ended as RFC 4180 ends one. */
8
+ export declare const csvOf: (answer: Answer, words: Words) => string;
9
+ export {};
@@ -0,0 +1,42 @@
1
+ import { isNumeric } from "../columns.mjs";
2
+ import { digitsOf, moved } from "../renderers/exact.mjs";
3
+ import { isMark } from "derive-dashboards/core";
4
+ // src/export/csv.ts
5
+ /** A text a spreadsheet must not take for a formula: one that begins as a formula does is led by an apostrophe. */
6
+ const guarded = (text) => /^[=+\-@\t\r]/u.test(text) ? `'${text}` : text;
7
+ /** A field as CSV writes it: in quotes, its own quotes doubled, when it holds a comma, a quote or a line break. */
8
+ const field = (text) => /[",\r\n]/u.test(text) ? `"${text.replaceAll("\"", "\"\"")}"` : text;
9
+ /** A column's heading: its label, with the unit its numbers are in when the digits alone would lose it. */
10
+ function headingOf(column) {
11
+ if (column.format === "duration") return guarded(`${column.label} (seconds)`);
12
+ if (column.format === "percent" || column.unit === void 0) return guarded(column.label);
13
+ return guarded(`${column.label} (${column.unit})`);
14
+ }
15
+ /**
16
+ * A number's digits as a spreadsheet reads them: as they are, and a percent in percent points
17
+ * with its sign (42.5%). A percent held as a fraction has its point moved two places as text;
18
+ * no value is put through a float on the way.
19
+ */
20
+ const written = (digits, column) => column.format === "percent" ? `${column.fraction === true ? moved(digits, 2) : digits}%` : digits;
21
+ /**
22
+ * One cell: nothing for no value, the fold's word for a mark, true or false, a number's own
23
+ * digits as a plain decimal, and any other text guarded. A text is a number only in a column
24
+ * of numbers, where a driver may hand one over as text: "-12" there is a number, never a
25
+ * formula. A cell of a number's kind that is no finite number (not a number, or an exact cell
26
+ * whose text is none) is written as the text it is, guarded as any text.
27
+ */
28
+ function cellText(cell, column, words) {
29
+ if (cell === null) return "";
30
+ if (isMark(cell)) return guarded(cell.mark === "all" ? words.total : words.other);
31
+ if (typeof cell === "boolean") return String(cell);
32
+ const digits = typeof cell === "string" && !isNumeric(column) ? void 0 : digitsOf(cell);
33
+ if (digits !== void 0) return written(digits, column);
34
+ return guarded(typeof cell === "object" ? cell.v : String(cell));
35
+ }
36
+ /** The answer as rows of texts: its headings, then each row, every cell as it is exported. `words` name Other and a total. */
37
+ function exportRows(answer, words) {
38
+ return [answer.columns.map((column) => headingOf(column)), ...answer.rows.map((cells) => answer.columns.map((column, at) => cellText(cells[at] ?? null, column, words)))];
39
+ }
40
+ /** The answer as CSV text: a line per row, each ended as RFC 4180 ends one. */
41
+ const csvOf = (answer, words) => exportRows(answer, words).map((row) => `${row.map((text) => field(text)).join(",")}\r\n`).join("");
42
+ export { csvOf, exportRows };