@sincpro/web-ui 1.10.0 → 1.11.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 (47) hide show
  1. package/dist/components/board/Board.d.ts +51 -0
  2. package/dist/components/board/Board.js +15 -0
  3. package/dist/components/board/index.d.ts +1 -0
  4. package/dist/components/board/index.js +2 -0
  5. package/dist/components/frame/Chart.d.ts +12 -7
  6. package/dist/components/frame/Chart.js +17 -17
  7. package/dist/components/frame/FrameView.d.ts +3 -3
  8. package/dist/components/frame/FrameView.js +79 -26
  9. package/dist/components/frame/model.d.ts +12 -3
  10. package/dist/components/frame/model.js +53 -19
  11. package/dist/components/index.d.ts +1 -0
  12. package/dist/components/index.js +1 -0
  13. package/dist/components/listing/AxisLevels.d.ts +24 -0
  14. package/dist/components/listing/AxisLevels.js +58 -0
  15. package/dist/components/listing/ChartExplorer.d.ts +79 -0
  16. package/dist/components/listing/ChartExplorer.js +114 -0
  17. package/dist/components/listing/PivotExplorer.js +5 -36
  18. package/dist/components/listing/index.d.ts +2 -0
  19. package/dist/components/listing/index.js +2 -0
  20. package/dist/components/listing/set.d.ts +3 -1
  21. package/dist/foundations/calendar.d.ts +15 -0
  22. package/dist/foundations/calendar.js +59 -1
  23. package/dist/foundations/chart.d.ts +126 -0
  24. package/dist/foundations/chart.js +297 -0
  25. package/dist/foundations/copy.d.ts +39 -0
  26. package/dist/foundations/copy.es.js +27 -0
  27. package/dist/foundations/copy.js +27 -0
  28. package/dist/foundations/index.d.ts +2 -1
  29. package/dist/foundations/index.js +4 -1
  30. package/dist/foundations/pivot.d.ts +9 -0
  31. package/dist/foundations/pivot.js +1 -0
  32. package/dist/primitives/chart/Chart.d.ts +39 -0
  33. package/dist/primitives/chart/Chart.js +235 -0
  34. package/dist/primitives/chart/index.d.ts +1 -0
  35. package/dist/primitives/chart/index.js +1 -0
  36. package/dist/primitives/index.d.ts +1 -0
  37. package/dist/primitives/index.js +1 -0
  38. package/dist/primitives/value/Metric.d.ts +13 -2
  39. package/dist/primitives/value/Metric.js +25 -3
  40. package/dist/tokens.css +45 -0
  41. package/dist/views/list/List.d.ts +2 -1
  42. package/dist/views/list/List.js +8 -1
  43. package/dist/views/list/ListView.d.ts +1 -1
  44. package/dist/views/list/ListView.js +37 -5
  45. package/dist/views/list/index.d.ts +1 -1
  46. package/dist/views/list/types.d.ts +34 -0
  47. package/package.json +2 -1
@@ -0,0 +1,79 @@
1
+ import { type ChartKind, type ChartOrder } from "../../foundations/chart.js";
2
+ import type { GroupableField, GroupLevel, PileOf } from "../../foundations/grouping.js";
3
+ import { type Pivot, type PivotFold, type PivotKey } from "../../foundations/pivot.js";
4
+ /**
5
+ * The PREVIOUS period, to draw beside the current one — Odoo's «compare with».
6
+ *
7
+ * The application knows what «previous» means (the same months last year, the week before)
8
+ * and hands over those records, or that pivot folded by the server. The chart folds them
9
+ * with the same axis and measure and draws them quiet, behind the current ones.
10
+ */
11
+ export type ChartComparison<T> = {
12
+ /** What the current period is called on the legend: «2026». */
13
+ current: string;
14
+ /** What the previous one is called: «2025». It also names the toggle. */
15
+ previous: string;
16
+ items?: readonly T[];
17
+ folded?: Pivot;
18
+ /** On from the start. */
19
+ defaultOn?: boolean;
20
+ };
21
+ export type ChartExplorerProps<T> = {
22
+ /**
23
+ * The pivot already folded by whoever holds the data. Its axes are theirs, so they are
24
+ * shown and not edited; the chart type, the measure and the order stay the person's.
25
+ * Wins over `items` when both are given.
26
+ */
27
+ folded?: Pivot;
28
+ /** The records to fold here, with `of`, `fields` and `measures`. */
29
+ items?: readonly T[];
30
+ /** Which pile a record falls in, at a level — the same contract that groups a list. */
31
+ of?: PileOf<T>;
32
+ /** What the chart can be split by: a field, and its grains when it is a date. */
33
+ fields?: readonly GroupableField[];
34
+ /** How a level is named when it is not among `fields` — the spec's `labelOf`. */
35
+ labelOf?: (level: GroupLevel) => string;
36
+ /** What can be measured, besides the count (always offered). */
37
+ measures?: readonly PivotFold<T>[];
38
+ /** The measure it opens on. The first of `measures` by default; `COUNT_MEASURE` for the count. */
39
+ defaultMeasure?: string;
40
+ /** Several measures at once, each its OWN chart, one under the other: two measures of
41
+ * different scale on one axis flatten the smaller one, and two axes invent a
42
+ * correlation. Wins over `defaultMeasure`. */
43
+ defaultMeasures?: readonly string[];
44
+ /** The levels, CONTROLLED from outside — the search bar's grouping, as in Odoo: the first
45
+ * goes along the axis, the rest are the series. While given, they are not edited here. */
46
+ levels?: readonly GroupLevel[];
47
+ /** Where the axis and the series start when nothing outside decides them. */
48
+ defaultCategories?: readonly GroupLevel[];
49
+ defaultSeries?: readonly GroupLevel[];
50
+ kind?: ChartKind;
51
+ defaultKind?: ChartKind;
52
+ onKindChange?: (kind: ChartKind) => void;
53
+ /** Bars stacked from the start (Odoo stacks them). */
54
+ defaultStacked?: boolean;
55
+ /** A line that adds up from the start: «how much so far». */
56
+ defaultCumulative?: boolean;
57
+ /** The axis ordered by size from the start. */
58
+ defaultOrder?: ChartOrder;
59
+ /** The previous period, to draw beside this one. */
60
+ compare?: ChartComparison<T>;
61
+ /** A bar, a point or a slice was pressed: open the records that fell there. */
62
+ onPoint?: (category: PivotKey, series?: PivotKey) => void;
63
+ /** What the chart shows, for the screen reader: «Ventas por sucursal». */
64
+ label?: string;
65
+ height?: number | string;
66
+ /** The file's name when downloaded. */
67
+ fileName?: string;
68
+ };
69
+ /**
70
+ * Odoo's GRAPH view, for any set: bars, lines or a pie; which measures; split by what along
71
+ * the axis and by what into series; stacked, cumulative, ordered; against the previous
72
+ * period; and a press on a mark opens the records under it.
73
+ *
74
+ * Context: it folds with the same `pivotFrom` the pivot uses, so the numbers on the chart
75
+ * and on the grid can never disagree — and a server-folded pivot (`folded`) draws the same.
76
+ * Inside a list the levels FOLLOW the search bar's grouping and the records are the ones
77
+ * the search left: the chart answers the same question the list is asking.
78
+ */
79
+ export declare function ChartExplorer<T>({ folded, items, of, fields, labelOf: outerLabel, measures, defaultMeasure, defaultMeasures, levels: outerLevels, defaultCategories, defaultSeries, kind: kindProp, defaultKind, onKindChange, defaultStacked, defaultCumulative, defaultOrder, compare, onPoint, label, height, fileName, }: ChartExplorerProps<T>): import("react").JSX.Element;
@@ -0,0 +1,114 @@
1
+ "use client";
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { AxisLevels, namer } from "./AxisLevels.js";
4
+ import { chartCompare, chartFromPivot, chartMeasures, COUNT_MEASURE, orderChart, } from "../../foundations/chart.js";
5
+ import { fillCopy, useUiCopy } from "../../foundations/copy.js";
6
+ import { pivotFrom, } from "../../foundations/pivot.js";
7
+ import { downloadPivot } from "../../foundations/pivotSheet.js";
8
+ import { Button, IconButton } from "../../primitives/button/Button.js";
9
+ import { Chart } from "../../primitives/chart/Chart.js";
10
+ import { SegmentedControl } from "../../primitives/choice/SegmentedControl.js";
11
+ import { Menu } from "../../primitives/menu/Menu.js";
12
+ import { ArrowDownWideNarrow, ArrowUpNarrowWide, ChartColumnBig, ChartLine, ChartPie, Download, GitCompareArrows, Layers, Sigma, TrendingUp, } from "lucide-react";
13
+ import { useMemo, useState } from "react";
14
+ const KIND_ICON = { bar: ChartColumnBig, line: ChartLine, pie: ChartPie };
15
+ /**
16
+ * Odoo's GRAPH view, for any set: bars, lines or a pie; which measures; split by what along
17
+ * the axis and by what into series; stacked, cumulative, ordered; against the previous
18
+ * period; and a press on a mark opens the records under it.
19
+ *
20
+ * Context: it folds with the same `pivotFrom` the pivot uses, so the numbers on the chart
21
+ * and on the grid can never disagree — and a server-folded pivot (`folded`) draws the same.
22
+ * Inside a list the levels FOLLOW the search bar's grouping and the records are the ones
23
+ * the search left: the chart answers the same question the list is asking.
24
+ */
25
+ export function ChartExplorer({ folded, items, of, fields = [], labelOf: outerLabel, measures = [], defaultMeasure, defaultMeasures, levels: outerLevels, defaultCategories = [], defaultSeries = [], kind: kindProp, defaultKind = "bar", onKindChange, defaultStacked = true, defaultCumulative = false, defaultOrder, compare, onPoint, label, height, fileName, }) {
26
+ const copy = useUiCopy();
27
+ const words = copy.chart;
28
+ const [ownKind, setOwnKind] = useState(kindProp ?? defaultKind);
29
+ const kind = onKindChange === undefined ? ownKind : (kindProp ?? defaultKind);
30
+ const setKind = onKindChange ?? setOwnKind;
31
+ const [ownCategories, setOwnCategories] = useState(defaultCategories);
32
+ const [ownSeries, setOwnSeries] = useState(defaultSeries);
33
+ const following = outerLevels !== undefined && outerLevels.length > 0;
34
+ const categories = following ? outerLevels.slice(0, 1) : ownCategories;
35
+ const series = following ? outerLevels.slice(1) : ownSeries;
36
+ const [chosen, setChosen] = useState(() => defaultMeasures ?? [defaultMeasure ?? measures[0]?.id ?? COUNT_MEASURE]);
37
+ const [stacked, setStacked] = useState(defaultStacked);
38
+ const [cumulative, setCumulative] = useState(defaultCumulative);
39
+ const [order, setOrder] = useState(defaultOrder);
40
+ const [comparing, setComparing] = useState(compare?.defaultOn === true);
41
+ const labelOf = namer(fields, outerLabel);
42
+ const fold = (records, columns) => of === undefined
43
+ ? undefined
44
+ : pivotFrom(records ?? [], { rows: categories, columns, of, measures, labelOf });
45
+ /* A pie is one whole: its series would be split and summed back. */
46
+ const columns = kind === "pie" ? [] : series;
47
+ const pivot = useMemo(() => folded ?? fold(items, columns),
48
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `fold` reads these same inputs
49
+ [folded, items, of, measures, fields, categories, columns]);
50
+ /* Comparing draws two periods of ONE series each: with series of its own, or as a pie
51
+ (one whole), there is nothing to put beside it. */
52
+ const canCompare = compare !== undefined && kind !== "pie" && columns.length === 0;
53
+ const previousPivot = useMemo(() => !canCompare || !comparing ? undefined : (compare.folded ?? fold(compare.items, [])),
54
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `fold` reads these same inputs
55
+ [canCompare, comparing, compare, of, measures, fields, categories]);
56
+ /* Time is compared by position (the first month with the first month); a thing, by key. */
57
+ const timeAxis = (pivot?.rows.levels.length ?? 0) === 1 && pivot?.rows.levels[0]?.grain !== undefined;
58
+ const available = pivot === undefined ? [] : chartMeasures(pivot);
59
+ const shown = available.filter((one) => chosen.includes(one.id));
60
+ const measuresShown = shown.length > 0 ? shown : available.slice(0, 1);
61
+ const charts = useMemo(() => {
62
+ if (pivot === undefined)
63
+ return [];
64
+ return measuresShown.map((measure) => {
65
+ const reading = {
66
+ measure: measure.id,
67
+ cumulative: kind === "line" && cumulative,
68
+ ...(kind === "pie" ? { maxCategories: 7 } : {}),
69
+ };
70
+ const current = chartFromPivot(pivot, reading);
71
+ if (previousPivot === undefined || compare === undefined) {
72
+ return orderChart(current, order);
73
+ }
74
+ const previous = chartFromPivot(previousPivot, reading);
75
+ return orderChart(chartCompare(current, previous, { current: compare.current, previous: compare.previous }, timeAxis ? "position" : "key"), order);
76
+ });
77
+ }, [pivot, previousPivot, measuresShown, kind, cumulative, order, compare, timeAxis]);
78
+ const manySeries = charts.some((data) => data.series.length > 1 && data.compare !== true);
79
+ const additive = measuresShown.every((one) => one.additive);
80
+ const first = measuresShown[0];
81
+ const measureLabel = first === undefined
82
+ ? words.measure
83
+ : measuresShown.length === 1
84
+ ? first.header
85
+ : fillCopy(words.moreMeasures, {
86
+ name: first.header,
87
+ count: measuresShown.length - 1,
88
+ });
89
+ const toggleOrder = (next) => setOrder((now) => (now === next ? undefined : next));
90
+ const toggleMeasure = (id) => {
91
+ const on = measuresShown.map((one) => one.id);
92
+ /* The last one stays: a chart of no measure is no chart. */
93
+ setChosen(!on.includes(id) ? [...on, id] : on.length === 1 ? on : on.filter((one) => one !== id));
94
+ };
95
+ return (_jsxs("div", { className: "flex min-w-0 flex-col gap-4", children: [_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-x-5 gap-y-2", children: [_jsx(SegmentedControl, { "aria-label": words.kind, size: "sm", value: kind, onChange: (next) => setKind(next), options: ["bar", "line", "pie"].map((one) => ({
96
+ value: one,
97
+ label: words[one],
98
+ icon: KIND_ICON[one],
99
+ })) }), _jsx(Menu, { label: measureLabel, title: words.measure, icon: Sigma, closeOnSelect: false, groups: [
100
+ {
101
+ label: words.measure,
102
+ options: available.map((one) => ({
103
+ id: one.id,
104
+ label: one.header,
105
+ checked: measuresShown.some((on) => on.id === one.id),
106
+ })),
107
+ },
108
+ ], onSelect: toggleMeasure }), folded === undefined ? (_jsxs(_Fragment, { children: [_jsx(AxisLevels, { name: words.categoriesAxis, levels: categories, onChange: following ? null : setOwnCategories, fields: fields, used: series, labelOf: labelOf }), kind === "pie" || (following && series.length === 0) ? null : (_jsx(AxisLevels, { name: words.seriesAxis, levels: series, onChange: following ? null : setOwnSeries, fields: fields, used: categories, labelOf: labelOf }))] })) : null, _jsxs("div", { className: "ml-auto flex items-center gap-1", children: [canCompare ? (_jsx(IconButton, { icon: GitCompareArrows, label: fillCopy(words.compareWith, { name: compare.previous }), "aria-pressed": comparing, onClick: () => setComparing((now) => !now) })) : null, kind !== "pie" && manySeries ? (_jsx(IconButton, { icon: Layers, label: words.stacked, "aria-pressed": stacked, onClick: () => setStacked((now) => !now) })) : null, kind === "line" ? (_jsx(IconButton, { icon: TrendingUp, label: words.cumulative, "aria-pressed": cumulative && additive, disabled: !additive, onClick: () => setCumulative((now) => !now) })) : null, _jsx(IconButton, { icon: ArrowDownWideNarrow, label: words.descending, "aria-pressed": order === "desc", onClick: () => toggleOrder("desc") }), _jsx(IconButton, { icon: ArrowUpNarrowWide, label: words.ascending, "aria-pressed": order === "asc", onClick: () => toggleOrder("asc") }), pivot === undefined ? null : (_jsx(Button, { role: "ghost", size: "sm", icon: Download, onClick: () => downloadPivot(pivot, fileName === undefined ? {} : { name: fileName }), children: copy.pivot.download }))] })] }), charts.map((data) => (_jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [charts.length > 1 ? (_jsx("h3", { className: "text-meta font-semibold text-ink", children: data.measure.header })) : null, _jsx(Chart, { data: data, kind: kind, stacked: stacked, label: charts.length > 1
109
+ ? describe(data.measure.header, label ?? data.categoryTitle)
110
+ : (label ?? describe(data.measure.header, data.categoryTitle)), ...(onPoint === undefined ? {} : { onPoint }), ...(height === undefined ? {} : { height }) })] }, data.measure.id)))] }));
111
+ }
112
+ function describe(measure, by) {
113
+ return by === "" ? measure : `${measure} · ${by}`;
114
+ }
@@ -1,20 +1,14 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { grainName } from "../../foundations/calendar.js";
4
- import { fillCopy, useUiCopy } from "../../foundations/copy.js";
3
+ import { AxisLevels, levelLabeler } from "./AxisLevels.js";
4
+ import { useUiCopy } from "../../foundations/copy.js";
5
5
  import { pivotFrom } from "../../foundations/pivot.js";
6
6
  import { downloadPivot } from "../../foundations/pivotSheet.js";
7
7
  import { Button, IconButton } from "../../primitives/button/Button.js";
8
8
  import { Menu } from "../../primitives/menu/Menu.js";
9
9
  import { PivotTable } from "../../primitives/table/PivotTable.js";
10
- import { Tags } from "../../primitives/tag/Tags.js";
11
- import { ArrowLeftRight, Download, Plus, Sigma } from "lucide-react";
10
+ import { ArrowLeftRight, Download, Sigma } from "lucide-react";
12
11
  import { useMemo, useState } from "react";
13
- const levelId = (level) => `${level.field}:${level.grain ?? ""}`;
14
- const fromId = (id) => {
15
- const [field = "", grain = ""] = id.split(":");
16
- return grain === "" ? { field } : { field, grain: grain };
17
- };
18
12
  /**
19
13
  * A pivot people actually pivot: what goes down the rows, what goes across the columns, which
20
14
  * measures — chosen on the grid, not fixed in code.
@@ -34,36 +28,11 @@ export function PivotExplorer({ items, of, fields, measures, defaultMeasures, ro
34
28
  const [chosen, setChosen] = useState(() => new Set(defaultMeasures ?? measures.slice(0, 1).map((one) => one.id)));
35
29
  const rows = outerRows ?? ownRows;
36
30
  const following = outerRows !== undefined;
37
- const labelOf = (level) => {
38
- const field = fields.find((one) => one.field === level.field)?.label ?? level.field;
39
- return level.grain === undefined
40
- ? field
41
- : `${field} · ${grainName(level.grain).toLowerCase()}`;
42
- };
31
+ const labelOf = levelLabeler(fields);
43
32
  const shownMeasures = measures.filter((one) => chosen.has(one.id));
44
33
  const pivot = useMemo(() => pivotFrom(items, { rows, columns, of, measures: shownMeasures, labelOf }),
45
34
  // eslint-disable-next-line react-hooks/exhaustive-deps
46
35
  [items, rows, columns, of, shownMeasures.map((one) => one.id).join("|")]);
47
- /* What can be added to an axis: every field (each grain of a date) not on either axis. */
48
- const used = new Set([...rows, ...columns].map(levelId));
49
- const options = fields.flatMap((field) => (field.grains ?? [undefined]).map((grain) => {
50
- const level = grain === undefined ? { field: field.field } : { field: field.field, grain };
51
- return {
52
- id: levelId(level),
53
- label: labelOf(level),
54
- disabled: used.has(levelId(level)),
55
- };
56
- }));
57
- const axis = (name, levels, set) => (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-1.5", children: [_jsx("span", { className: "text-micro font-medium text-muted", children: name }), _jsx(Tags, { label: name, items: levels.map((level) => ({
58
- id: levelId(level),
59
- label: labelOf(level),
60
- ...(set === null
61
- ? {}
62
- : {
63
- onRemove: () => set(levels.filter((one) => levelId(one) !== levelId(level))),
64
- removeLabel: fillCopy(words.removeLevel, { level: labelOf(level) }),
65
- }),
66
- })) }), set === null ? (_jsx("span", { className: "text-micro text-muted italic", children: words.fromSearch })) : (_jsx(Menu, { label: fillCopy(words.addLevel, { axis: name }), icon: Plus, iconOnly: true, chevron: false, variant: "text", groups: [{ options }], onSelect: (id) => set([...levels, fromId(id)]) }))] }));
67
36
  return (_jsxs("div", { className: "flex min-w-0 flex-col gap-3", children: [_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-x-5 gap-y-2", children: [_jsx(Menu, { label: words.measures, icon: Sigma, groups: [
68
37
  {
69
38
  options: measures.map((one) => ({
@@ -79,7 +48,7 @@ export function PivotExplorer({ items, of, fields, measures, defaultMeasures, ro
79
48
  else
80
49
  next.add(id);
81
50
  return next;
82
- }) }), axis(words.rowsAxis, rows, following ? null : setOwnRows), axis(words.columnsAxis, columns, setColumns), _jsxs("div", { className: "ml-auto flex items-center gap-1", children: [following ? null : (_jsx(IconButton, { icon: ArrowLeftRight, label: words.swap, onClick: () => {
51
+ }) }), _jsx(AxisLevels, { name: words.rowsAxis, levels: rows, onChange: following ? null : setOwnRows, fields: fields, used: columns }), _jsx(AxisLevels, { name: words.columnsAxis, levels: columns, onChange: setColumns, fields: fields, used: rows }), _jsxs("div", { className: "ml-auto flex items-center gap-1", children: [following ? null : (_jsx(IconButton, { icon: ArrowLeftRight, label: words.swap, onClick: () => {
83
52
  setOwnRows(columns);
84
53
  setColumns(rows);
85
54
  } })), _jsx(Button, { role: "ghost", size: "sm", icon: Download, onClick: () => downloadPivot(pivot, fileName === undefined ? {} : { name: fileName }), children: words.download })] })] }), _jsx(PivotTable, { pivot: pivot, ...(onCell === undefined ? {} : { onCell }), ...(height === undefined ? {} : { height }) })] }));
@@ -12,7 +12,9 @@ export { type Selection, useSelection } from "./selection.js";
12
12
  export { type SetControl, useSetControl } from "./set.js";
13
13
  export { toggleCollapsed, type TreeControl, useTreeControl, } from "./tree.js";
14
14
  export { type ViewIcon, type ViewOption, ViewSwitcher, } from "./ViewSwitcher.js";
15
+ export { AxisLevels, levelId, levelLabeler, } from "./AxisLevels.js";
15
16
  export { type BoardColumn, BoardColumns, type BoardStages, } from "./BoardColumns.js";
17
+ export { type ChartComparison, ChartExplorer, type ChartExplorerProps, } from "./ChartExplorer.js";
16
18
  export { type GroupingControl, useGroupingControl, } from "./grouping.js";
17
19
  export { GroupingLevels, type GroupingLevelsProps, } from "./GroupingLevels.js";
18
20
  export { PivotExplorer, type PivotExplorerProps, } from "./PivotExplorer.js";
@@ -15,7 +15,9 @@ export { useSetControl } from "./set.js";
15
15
  export { toggleCollapsed, useTreeControl, } from "./tree.js";
16
16
  export { ViewSwitcher, } from "./ViewSwitcher.js";
17
17
  /* El control de los niveles. El vocabulario está en `system/grouping.ts`. */
18
+ export { AxisLevels, levelId, levelLabeler, } from "./AxisLevels.js";
18
19
  export { BoardColumns, } from "./BoardColumns.js";
20
+ export { ChartExplorer, } from "./ChartExplorer.js";
19
21
  export { useGroupingControl, } from "./grouping.js";
20
22
  export { GroupingLevels, } from "./GroupingLevels.js";
21
23
  export { PivotExplorer, } from "./PivotExplorer.js";
@@ -32,8 +32,10 @@ import { type Pages } from "./pages.js";
32
32
  * pivot dos EJES a la vez. Una fila es un montón y una columna
33
33
  * también; lo que se lee está en el cruce. Tampoco se
34
34
  * ordena: el orden de cada eje es el de sus claves.
35
+ * chart el mismo pivote, dibujado: barras, líneas o torta. El
36
+ * primer agrupado es el eje y el segundo, las series.
35
37
  */
36
- export type BuiltInPresent = "rows" | "table" | "board" | "sheet" | "report" | "pivot" | "calendar" | "gantt" | "timeline";
38
+ export type BuiltInPresent = "rows" | "table" | "board" | "sheet" | "report" | "pivot" | "chart" | "calendar" | "gantt" | "timeline";
37
39
  /** A presentation of a list: one the package draws, or the `id` of a `List.Present` the
38
40
  * application wrote. `string & {}` keeps the built-in names in autocomplete. */
39
41
  export type ListPresent = BuiltInPresent | (string & {});
@@ -21,6 +21,21 @@ export declare function dateKey(when: Date | string | number | null | undefined,
21
21
  * en vez de desaparecer detrás de una fecha inventada.
22
22
  */
23
23
  export declare function dateLabel(key: string, grain: GroupGrain, within?: readonly GroupGrain[]): string;
24
+ /**
25
+ * La clave SIGUIENTE en el mismo grano: «2026-09» → «2026-10», «2026-Q4» → «2027-Q1»,
26
+ * «2026-W52» → la semana ISO que sigue. `null` si la clave no tiene la forma de su grano —
27
+ * una contada afuera, que esta capa no escribió y entonces no puede continuar.
28
+ */
29
+ export declare function nextDateKey(key: string, grain: GroupGrain): string | null;
30
+ /**
31
+ * Todas las claves de un grano entre dos, las dos incluidas: el EJE de tiempo entero.
32
+ *
33
+ * Un eje que salta el mes en que no pasó nada miente sobre el tiempo —agosto pegado a
34
+ * octubre se lee como un mes— y ese hueco suele ser justo lo que alguien busca. `null` si
35
+ * alguna clave no se puede continuar o si serían más de `max`: un eje por día de diez años
36
+ * no es un gráfico.
37
+ */
38
+ export declare function dateKeysBetween(first: string, last: string, grain: GroupGrain, max?: number): string[] | null;
24
39
  /** El nombre de un mes —1 a 12— en el idioma activo. Lo usa el que ofrece meses
25
40
  * sin tener ninguna fecha en la mano, como el recorte por período. */
26
41
  export declare function monthName(month: number): string;
@@ -64,7 +64,15 @@ const KEY_SHAPES = {
64
64
  export function dateKey(when, grain) {
65
65
  if (when === null || when === undefined || when === "")
66
66
  return "";
67
- const date = when instanceof Date ? when : new Date(when);
67
+ /* A date WITHOUT a time («2025-01-01») is a day of the calendar, not an instant: `new Date`
68
+ reads it as midnight UTC, which in La Paz (UTC−4) is the 31st of December — and January's
69
+ sales landed in last year's December. It is read as a local day instead. */
70
+ const day = typeof when === "string" ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(when) : null;
71
+ const date = day !== null
72
+ ? new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]))
73
+ : when instanceof Date
74
+ ? when
75
+ : new Date(when);
68
76
  if (Number.isNaN(date.getTime()))
69
77
  return "";
70
78
  const year = date.getFullYear();
@@ -140,6 +148,56 @@ export function dateLabel(key, grain, within = []) {
140
148
  ...(said("year") ? {} : { year: "numeric" }),
141
149
  }).format(when));
142
150
  }
151
+ /**
152
+ * La clave SIGUIENTE en el mismo grano: «2026-09» → «2026-10», «2026-Q4» → «2027-Q1»,
153
+ * «2026-W52» → la semana ISO que sigue. `null` si la clave no tiene la forma de su grano —
154
+ * una contada afuera, que esta capa no escribió y entonces no puede continuar.
155
+ */
156
+ export function nextDateKey(key, grain) {
157
+ const parts = KEY_SHAPES[grain].exec(key);
158
+ if (parts === null)
159
+ return null;
160
+ const year = Number(key.slice(0, 4));
161
+ if (grain === "year")
162
+ return String(year + 1);
163
+ if (grain === "quarter") {
164
+ const quarter = Number(key.slice(6));
165
+ return quarter === 4 ? `${year + 1}-Q1` : `${year}-Q${quarter + 1}`;
166
+ }
167
+ if (grain === "month") {
168
+ const month = Number(key.slice(5, 7));
169
+ return month === 12 ? `${year + 1}-01` : `${year}-${pad(month + 1)}`;
170
+ }
171
+ if (grain === "week") {
172
+ /* The Monday of ISO week 1 is the Monday of the week holding 4 January. */
173
+ const week = Number(key.slice(6));
174
+ const fourth = new Date(year, 0, 4);
175
+ const monday = new Date(year, 0, 4 - ((fourth.getDay() + 6) % 7) + (week - 1) * 7);
176
+ return dateKey(new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 7), "week");
177
+ }
178
+ const date = new Date(year, Number(key.slice(5, 7)) - 1, Number(key.slice(8, 10)) + 1);
179
+ return dateKey(date, "day");
180
+ }
181
+ /**
182
+ * Todas las claves de un grano entre dos, las dos incluidas: el EJE de tiempo entero.
183
+ *
184
+ * Un eje que salta el mes en que no pasó nada miente sobre el tiempo —agosto pegado a
185
+ * octubre se lee como un mes— y ese hueco suele ser justo lo que alguien busca. `null` si
186
+ * alguna clave no se puede continuar o si serían más de `max`: un eje por día de diez años
187
+ * no es un gráfico.
188
+ */
189
+ export function dateKeysBetween(first, last, grain, max = 1000) {
190
+ const out = [first];
191
+ let key = first;
192
+ while (key < last) {
193
+ const next = nextDateKey(key, grain);
194
+ if (next === null || out.length >= max)
195
+ return null;
196
+ out.push(next);
197
+ key = next;
198
+ }
199
+ return key === last ? out : null;
200
+ }
143
201
  /** El nombre de un mes —1 a 12— en el idioma activo. Lo usa el que ofrece meses
144
202
  * sin tener ninguna fecha en la mano, como el recorte por período. */
145
203
  export function monthName(month) {
@@ -0,0 +1,126 @@
1
+ import { type Pivot, type PivotKey } from "./pivot.js";
2
+ /**
3
+ * EL GRÁFICO: un pivote leído como marcas.
4
+ *
5
+ * Context: un gráfico de un ERP —el de Odoo, el de cualquiera— contesta la misma pregunta
6
+ * que un pivote: el conjunto partido por un campo (el eje), a veces por otro más (las
7
+ * series), y en cada cruce un número plegado. Por eso esto NO trae otra manera de plegar:
8
+ * lee un `Pivot`. Y como un `Pivot` lo arma igual quien tiene los registros en la mano
9
+ * (`pivotFrom`), quien lo plegó en el servidor (`pivotOf`) o quien lo armó desde las celdas
10
+ * de un archivo, el mismo gráfico sirve para registros, para un dataset y para lo agrupado
11
+ * a mil kilómetros. Un diccionario o un `SeriesBar[]` entran por sus dos helpers de abajo.
12
+ *
13
+ * ── Las filas del pivote son el EJE; sus columnas, las SERIES ───────
14
+ *
15
+ * Igual que en Odoo: el primer agrupado va abajo y el segundo se apila o se pone al lado.
16
+ *
17
+ * ── Tres reglas que vienen del pivote, y siguen valiendo ────────────
18
+ *
19
+ * 1. **Un agujero no es un cero.** `null` es «ahí no hay filas»: la barra no se dibuja y
20
+ * la línea se corta. Un cero es una barra a ras del eje.
21
+ * 2. **No se inventan sumas.** Juntar la cola en «otros» o acumular una línea es sumar, y
22
+ * sólo se hace si la medida se suma (`additive`; el conteo siempre). Si no, la cola se
23
+ * deja afuera y se DICE (`hiddenSeries`): un promedio de promedios no es un promedio.
24
+ * 3. **El color sigue a la serie, no a su puesto.** Las series que quedan conservan el
25
+ * orden del pivote; ordenar por tamaño ordena el EJE, nunca repinta.
26
+ */
27
+ export type ChartKind = "bar" | "line" | "pie";
28
+ export type ChartOrder = "asc" | "desc";
29
+ /** El conteo de filas de cada cruce, ofrecido como una medida más: es la única que
30
+ * siempre se puede contestar. */
31
+ export declare const COUNT_MEASURE = "__count";
32
+ /** Cuántas series se distinguen por color. Es el largo de la paleta (`--color-series-*`):
33
+ * una novena serie sería un color generado, y bajo daltonismo ése se confunde con otro. */
34
+ export declare const SERIES_COLORS = 8;
35
+ /** Una clave de un eje del gráfico: su ruta en el pivote y cómo se lee. */
36
+ export type ChartPoint = {
37
+ key: PivotKey;
38
+ /** `pathKey(key)`: la identidad estable para React y para el color. */
39
+ id: string;
40
+ label: string;
41
+ /** La cola juntada en una: «otros (12)». Se dibuja más callada y no se abre. */
42
+ rest?: boolean;
43
+ /** El período anterior de una comparación: se dibuja callado, detrás del actual. */
44
+ previous?: boolean;
45
+ };
46
+ export type ChartMeasure = {
47
+ id: string;
48
+ header: string;
49
+ format?: (value: number) => string;
50
+ additive: boolean;
51
+ };
52
+ export type ChartData = {
53
+ categories: readonly ChartPoint[];
54
+ series: readonly ChartPoint[];
55
+ /** `values[categoría][serie]`; `null` es un agujero. */
56
+ values: readonly (readonly (number | null)[])[];
57
+ /** Lo que da cada categoría entera, plegado de la base cuando el pivote lo trae. Es lo
58
+ * que mide una torta y lo que ordena el eje. */
59
+ totals: readonly (number | null)[];
60
+ measure: ChartMeasure;
61
+ /** Cómo se llaman los cortes: «sucursal», «año · forma de pago». */
62
+ categoryTitle: string;
63
+ seriesTitle: string;
64
+ /** Series que no entraron y no se pudieron juntar en «otros» (la medida no se suma). */
65
+ hiddenSeries: number;
66
+ /** Lo mismo, para las categorías que una torta no puede mostrar. */
67
+ hiddenCategories: number;
68
+ /** Las dos series son el período actual y el anterior (`chartCompare`). */
69
+ compare?: boolean;
70
+ };
71
+ export type ChartReading = {
72
+ /** El id de la medida, o `COUNT_MEASURE`. Por defecto la primera del pivote. */
73
+ measure?: string;
74
+ /** Ordena el EJE por lo que da cada categoría. Sin esto, el orden de sus claves. */
75
+ order?: ChartOrder;
76
+ /** Cada punto suma los anteriores: «cuánto llevamos». Sólo con una medida que se suma. */
77
+ cumulative?: boolean;
78
+ /** Más series que esto se juntan en «otros». Por defecto, los colores de la paleta. */
79
+ maxSeries?: number;
80
+ /** Más categorías que esto se juntan en «otros». Una torta pide seis. */
81
+ maxCategories?: number;
82
+ /**
83
+ * Con un solo nivel de FECHA en el eje, completa los períodos en que no pasó nada:
84
+ * agosto no queda pegado a octubre. El conteo de un período vacío es 0; cualquier otra
85
+ * medida es un agujero (`null`), como cualquier cruce sin filas. Encendido por defecto.
86
+ */
87
+ fillDates?: boolean;
88
+ };
89
+ /** Las medidas que se pueden graficar de un pivote: el conteo y las suyas. */
90
+ export declare function chartMeasures(pivot: Pivot): ChartMeasure[];
91
+ /**
92
+ * El pivote como gráfico: las filas son el eje, las columnas las series, y en cada cruce
93
+ * el número de la medida elegida.
94
+ */
95
+ export declare function chartFromPivot(pivot: Pivot, reading?: ChartReading): ChartData;
96
+ /**
97
+ * Ordena el EJE de un gráfico ya armado por lo que da cada categoría. La cola juntada
98
+ * («otros») queda al final. Es lo mismo que `order` en `chartFromPivot`, para un gráfico
99
+ * que se armó de otra manera —una comparación, un diccionario—.
100
+ */
101
+ export declare function orderChart(data: ChartData, order: ChartOrder | undefined): ChartData;
102
+ /**
103
+ * EL PERÍODO ANTERIOR al lado del actual — el «comparar con» de Odoo.
104
+ *
105
+ * Cada gráfico se arma por su lado (`chartFromPivot` sobre los registros de cada período)
106
+ * y esto los junta en dos series: el actual y el anterior, que se dibuja callado. Lo que se
107
+ * compara es lo que da cada categoría entera.
108
+ *
109
+ * `by` dice cómo se encuentran: por CLAVE cuando el eje es una cosa —La Paz con La Paz— y
110
+ * por POSICIÓN cuando es tiempo —el primer mes con el primer mes—, porque «2026-09» y
111
+ * «2025-09» son claves distintas y lo que se compara es «el mismo momento del período».
112
+ * Una categoría del anterior que no está en el actual no se dibuja: el eje es el de ahora.
113
+ */
114
+ export declare function chartCompare(current: ChartData, previous: ChartData, labels: {
115
+ current: string;
116
+ previous: string;
117
+ }, by?: "key" | "position"): ChartData;
118
+ /**
119
+ * Un DICCIONARIO como gráfico: `{ "La Paz": 120, "Oruro": 40 }`, o sus pares. Es lo que
120
+ * devuelve un endpoint de resumen, y no hace falta armarle un pivote.
121
+ */
122
+ export declare function chartFromRecord(entries: Readonly<Record<string, number | null>> | readonly (readonly [string, number | null])[], measure: {
123
+ header: string;
124
+ format?: (value: number) => string;
125
+ additive?: boolean;
126
+ }): ChartData;