@sincpro/web-ui 1.11.1 → 2.0.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.
@@ -4,30 +4,43 @@ export interface BuiltSort {
4
4
  field: string;
5
5
  descending?: boolean;
6
6
  }
7
+ /** Un nivel de agrupado, como el `Level` de criteria: el campo y, si es fecha, el grano. */
7
8
  export interface BuiltLevel {
8
9
  field: string;
9
10
  grain?: string | null;
10
11
  }
11
- /** Un número plegado de las filas de un montón: `["sum", "row_count"]`. */
12
- export type BuiltFold = [string, string];
12
+ /**
13
+ * Un número que cada montón contesta, como el `Measure` de criteria:
14
+ * `{ function: "sum", field: "row_count" }`. Partes con nombre y no un par, igual que una
15
+ * condición viaja como `{field, operator, value}`.
16
+ */
17
+ export interface BuiltMeasure {
18
+ function: string;
19
+ field: string;
20
+ /** Lo que la función necesita además del campo. Sólo `percentile`: la fracción del corte. */
21
+ argument?: number;
22
+ }
13
23
  /** Desde dónde empieza una página de montones — la misma forma que la paginación de filas. */
14
24
  export type BuiltPageStrategy = {
15
- token?: string | null;
25
+ token: string | null;
16
26
  } | {
17
- rows?: number;
27
+ rows: number;
18
28
  };
19
29
  export interface BuiltGroupPagination {
20
30
  limit?: number;
21
31
  strategy?: BuiltPageStrategy;
22
32
  }
33
+ /** El agrupado tal como lo declara `@sincpro/criteria` 2.0, clave por clave. */
23
34
  export interface BuiltGrouping {
24
- by?: BuiltLevel[];
25
- totals?: Record<string, BuiltFold>;
26
- /** Un filtro sobre lo que los montones plegaron: `count > 10`. Los nombres que admite son
27
- * los de `totals`, más `"count"`. */
28
- having?: BuiltFilter;
35
+ /** Los niveles, en orden: no se suman, se anidan. */
36
+ group_by?: BuiltLevel[];
37
+ /** Los números que cada montón contesta, cada uno bajo un nombre elegido. */
38
+ measures?: Record<string, BuiltMeasure>;
39
+ /** Un filtro sobre lo que los montones midieron, no sobre las filas: `count > 10`. Los
40
+ * nombres que admite son los de `measures`, más `"count"`. */
41
+ where_measures?: BuiltFilter;
29
42
  /** En qué orden vuelven los montones: por el propio campo del nivel, por un nombre de
30
- * `totals`, o por `count`. */
43
+ * `measures`, o por `count`. */
31
44
  order?: BuiltSort[];
32
45
  /** Cuántos montones del primer nivel vuelven, y desde dónde. Ausente es todos. */
33
46
  pagination?: BuiltGroupPagination;
@@ -35,7 +48,7 @@ export interface BuiltGrouping {
35
48
  /** La criteria tal como la declara el motor. Es lo que este componente arma y devuelve, y lo
36
49
  * que el editor de código muestra. */
37
50
  export interface BuiltCriteria {
38
- where?: BuiltFilter;
51
+ selection?: BuiltFilter;
39
52
  order?: BuiltSort[];
40
53
  grouping?: BuiltGrouping;
41
54
  specification?: Record<string, Record<string, never>>;
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
- import { blankGroup, ExpressionView, treeFromFilter, treeToFilter, WhereTree, } from "./FilterBuilder.js";
3
+ import { blankGroup, ExpressionView, SelectionTree, treeFromFilter, treeToFilter, } from "./FilterBuilder.js";
4
4
  import { LazyJsonEditor } from "./LazyJsonEditor.js";
5
5
  import { filterableNames, } from "./model.js";
6
6
  import { fillCopy, useUiCopy } from "../../foundations/copy.js";
@@ -22,20 +22,28 @@ import { Fragment, useMemo, useState } from "react";
22
22
  const GRAINS = [null, ...GRAIN_ORDER];
23
23
  /** Qué tipos admiten un grano: recortar un texto por mes no significa nada. */
24
24
  const DATE_TYPES = new Set(["date", "datetime"]);
25
- /** Los operadores que un plegado —siempre un número— o `count` admiten en un `having`: los
26
- * mismos que la definición del modelo publica para un campo numérico, `is null` aparte, que
27
- * no significa nada sobre un número que el propio motor calculó. */
25
+ /** Los operadores que una medida —siempre un número— o `count` admiten en un
26
+ * `where_measures`: los mismos que la definición del modelo publica para un campo numérico,
27
+ * `is null` aparte, que no significa nada sobre un número que el propio motor calculó. */
28
28
  const COMPARABLE = ["=", "!=", ">", ">=", "<", "<=", "between"];
29
- /** Las funciones que un plegado puede pedir, cerradas del lado del servidor porque el nombre
30
- * llega a SQL. */
31
- const FOLD_FUNCTIONS = ["sum", "avg", "min", "max", "count"];
29
+ /** Las funciones que una medida puede pedir acá, cerradas del lado del servidor porque el
30
+ * nombre llega a SQL. */
31
+ const MEASURE_FUNCTIONS = ["sum", "avg", "min", "max", "count"];
32
32
  function isEmpty(criteria) {
33
- return (criteria.where === undefined &&
33
+ return (criteria.selection === undefined &&
34
34
  (criteria.order ?? []).length === 0 &&
35
- (criteria.grouping?.by ?? []).length === 0 &&
36
- Object.keys(criteria.grouping?.totals ?? {}).length === 0 &&
35
+ (criteria.grouping?.group_by ?? []).length === 0 &&
36
+ Object.keys(criteria.grouping?.measures ?? {}).length === 0 &&
37
37
  Object.keys(criteria.specification ?? {}).length === 0);
38
38
  }
39
+ /** El árbol del editor de `where_measures`: lo leído, envuelto en un grupo si es una sola
40
+ * condición, o uno en blanco sobre `count` si no hay nada que leer. */
41
+ function measuresTreeOf(filter, model) {
42
+ const node = filter === undefined ? null : treeFromFilter(filter);
43
+ if (node === null)
44
+ return blankGroup(model, "count");
45
+ return node.kind === "group" ? node : { kind: "group", join: "all", children: [node] };
46
+ }
39
47
  /**
40
48
  * LA FICHA QUE AGREGA: un «+» que abre la lista de lo que se puede elegir.
41
49
  *
@@ -69,66 +77,62 @@ export function CriteriaBuilder({ model, initial, focus, onApply, onCancel, }) {
69
77
  (`ops` vacío), así que ninguno sirve de blanco para un filtro, un orden o un nivel. */
70
78
  const scalarNames = filterableNames(model);
71
79
  const sortable = names.filter((name) => model.fields[name]?.sortable === true);
72
- const decomposed = initial?.where === undefined ? null : treeFromFilter(initial.where);
80
+ const decomposed = initial?.selection === undefined ? null : treeFromFilter(initial.selection);
73
81
  const [tree, setTree] = useState(() => decomposed !== null && decomposed.kind === "group"
74
82
  ? decomposed
75
83
  : decomposed !== null
76
84
  ? { kind: "group", join: "all", children: [decomposed] }
77
85
  : blankGroup(model, scalarNames[0]));
78
86
  const copy = useUiCopy();
79
- const [lockedWhere, setLockedWhere] = useState(initial?.where !== undefined && decomposed === null ? initial.where : null);
87
+ const [lockedSelection, setLockedSelection] = useState(initial?.selection !== undefined && decomposed === null ? initial.selection : null);
80
88
  const [order, setOrder] = useState(initial?.order ?? []);
81
- const [levels, setLevels] = useState(initial?.grouping?.by ?? []);
82
- const [totals, setTotals] = useState(initial?.grouping?.totals ?? {});
89
+ const [levels, setLevels] = useState(initial?.grouping?.group_by ?? []);
90
+ const [measures, setMeasures] = useState(initial?.grouping?.measures ?? {});
83
91
  const [groupOrder, setGroupOrder] = useState(initial?.grouping?.order ?? []);
84
92
  const [groupLimit, setGroupLimit] = useState(initial?.grouping?.pagination?.limit);
85
- /* `having` es un filtro como cualquier otro, sobre un modelo sintético cuyos únicos campos
86
- son los nombres que admite: los de `totals`, más `count`. Reutilizar `WhereTree` sobre ese
87
- modelo es más simple y más correcto que armar un editor de condiciones aparte. */
88
- const havingModel = useMemo(() => ({
89
- aggregate: "having",
93
+ /* `where_measures` es un filtro como cualquier otro, sobre un modelo sintético cuyos únicos
94
+ campos son los nombres que admite: los de `measures`, más `count`. Reutilizar
95
+ `SelectionTree` sobre ese modelo es más simple y más correcto que armar un editor de
96
+ condiciones aparte. */
97
+ const measuresModel = useMemo(() => ({
98
+ aggregate: "where_measures",
90
99
  identity: "count",
91
100
  fields: Object.fromEntries([
92
101
  ["count", { type: "integer", nullable: false, sortable: false, ops: COMPARABLE }],
93
- ...Object.keys(totals).map((name) => [
102
+ ...Object.keys(measures).map((name) => [
94
103
  name,
95
104
  { type: "number", nullable: false, sortable: false, ops: COMPARABLE },
96
105
  ]),
97
106
  ]),
98
- }), [totals]);
99
- const havingDecomposed = initial?.grouping?.having === undefined ? null : treeFromFilter(initial.grouping.having);
100
- const [havingTree, setHavingTree] = useState(() => havingDecomposed !== null && havingDecomposed.kind === "group"
101
- ? havingDecomposed
102
- : havingDecomposed !== null
103
- ? { kind: "group", join: "all", children: [havingDecomposed] }
104
- : blankGroup(havingModel, "count"));
107
+ }), [measures]);
108
+ const [measuresTree, setMeasuresTree] = useState(() => measuresTreeOf(initial?.grouping?.where_measures, measuresModel));
105
109
  const [fields, setFields] = useState(Object.keys(initial?.specification ?? {}));
106
110
  const [rawText, setRawText] = useState(() => initial === undefined ? "" : JSON.stringify(initial, null, 2));
107
111
  const [rawError, setRawError] = useState(null);
108
112
  /** Lo que los controles dicen, junto: es lo que se aplica y lo que el JSON muestra. */
109
113
  function assemble(next) {
110
- const where = next.locked ?? lockedWhere ?? treeToFilter(next.tree ?? tree);
114
+ const selection = next.locked ?? lockedSelection ?? treeToFilter(next.tree ?? tree);
111
115
  const sorts = next.order ?? order;
112
- const by = next.levels ?? levels;
113
- const folds = next.totals ?? totals;
114
- const having = treeToFilter(next.havingTree ?? havingTree);
116
+ const groupBy = next.levels ?? levels;
117
+ const measured = next.measures ?? measures;
118
+ const whereMeasures = treeToFilter(next.measuresTree ?? measuresTree);
115
119
  const groupSorts = next.groupOrder ?? groupOrder;
116
120
  const limit = "groupLimit" in next ? next.groupLimit : groupLimit;
117
121
  const chosen = next.fields ?? fields;
118
- /* Sin niveles no hay qué plegar, qué filtrar entre montones ni en qué orden o página
119
- volverían — un total, un `having` o una página puestos y luego vaciados de niveles no
120
- tienen que sobrevivir sueltos en la criteria que se manda. */
121
- const grouping = by.length === 0
122
+ /* Sin niveles no hay qué medir, qué filtrar entre montones ni en qué orden o página
123
+ volverían — una medida, un `where_measures` o una página puestos y luego vaciados de
124
+ niveles no tienen que sobrevivir sueltos en la criteria que se manda. */
125
+ const grouping = groupBy.length === 0
122
126
  ? {}
123
127
  : {
124
- by,
125
- ...(Object.keys(folds).length === 0 ? {} : { totals: folds }),
126
- ...(having === undefined ? {} : { having }),
128
+ group_by: groupBy,
129
+ ...(Object.keys(measured).length === 0 ? {} : { measures: measured }),
130
+ ...(whereMeasures === undefined ? {} : { where_measures: whereMeasures }),
127
131
  ...(groupSorts.length === 0 ? {} : { order: groupSorts }),
128
132
  ...(limit === undefined ? {} : { pagination: { limit } }),
129
133
  };
130
134
  return {
131
- ...(where === undefined ? {} : { where }),
135
+ ...(selection === undefined ? {} : { selection }),
132
136
  ...(sorts.length === 0 ? {} : { order: sorts }),
133
137
  ...(Object.keys(grouping).length === 0 ? {} : { grouping }),
134
138
  ...(chosen.length === 0
@@ -143,15 +147,15 @@ export function CriteriaBuilder({ model, initial, focus, onApply, onCancel, }) {
143
147
  if (next.tree !== undefined)
144
148
  setTree(next.tree);
145
149
  if (next.locked !== undefined)
146
- setLockedWhere(next.locked);
150
+ setLockedSelection(next.locked);
147
151
  if (next.order !== undefined)
148
152
  setOrder(next.order);
149
153
  if (next.levels !== undefined)
150
154
  setLevels(next.levels);
151
- if (next.totals !== undefined)
152
- setTotals(next.totals);
153
- if (next.havingTree !== undefined)
154
- setHavingTree(next.havingTree);
155
+ if (next.measures !== undefined)
156
+ setMeasures(next.measures);
157
+ if (next.measuresTree !== undefined)
158
+ setMeasuresTree(next.measuresTree);
155
159
  if (next.groupOrder !== undefined)
156
160
  setGroupOrder(next.groupOrder);
157
161
  if ("groupLimit" in next)
@@ -182,36 +186,31 @@ export function CriteriaBuilder({ model, initial, focus, onApply, onCancel, }) {
182
186
  return;
183
187
  }
184
188
  setRawError(null);
185
- const node = parsed.where === undefined ? null : treeFromFilter(parsed.where);
189
+ const node = parsed.selection === undefined ? null : treeFromFilter(parsed.selection);
186
190
  if (node !== null) {
187
191
  setTree(node.kind === "group" ? node : { kind: "group", join: "all", children: [node] });
188
- setLockedWhere(null);
192
+ setLockedSelection(null);
189
193
  }
190
- else if (parsed.where !== undefined) {
191
- setLockedWhere(parsed.where);
194
+ else if (parsed.selection !== undefined) {
195
+ setLockedSelection(parsed.selection);
192
196
  }
193
197
  else {
194
198
  setTree(blankGroup(model, scalarNames[0]));
195
- setLockedWhere(null);
199
+ setLockedSelection(null);
196
200
  }
197
201
  setOrder(parsed.order ?? []);
198
- setLevels(parsed.grouping?.by ?? []);
199
- setTotals(parsed.grouping?.totals ?? {});
202
+ setLevels(parsed.grouping?.group_by ?? []);
203
+ setMeasures(parsed.grouping?.measures ?? {});
200
204
  setGroupOrder(parsed.grouping?.order ?? []);
201
205
  setGroupLimit(parsed.grouping?.pagination?.limit);
202
- const havingNode = parsed.grouping?.having === undefined ? null : treeFromFilter(parsed.grouping.having);
203
- setHavingTree(havingNode !== null && havingNode.kind === "group"
204
- ? havingNode
205
- : havingNode !== null
206
- ? { kind: "group", join: "all", children: [havingNode] }
207
- : blankGroup(havingModel, "count"));
206
+ setMeasuresTree(measuresTreeOf(parsed.grouping?.where_measures, measuresModel));
208
207
  setFields(Object.keys(parsed.specification ?? {}));
209
208
  }
210
209
  const box = surface === "chrome"
211
210
  ? "border-chrome-ink/20 bg-chrome text-chrome-ink"
212
211
  : "border-ink/15 bg-surface text-ink";
213
212
  const select = `min-w-0 flex-1 basis-40 rounded-control border px-2 py-1 text-meta ${box}`;
214
- return (_jsxs("div", { className: "flex min-w-0 flex-col gap-3 p-3", children: [_jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.filter }), _jsx("div", { className: "max-h-72 min-w-0 overflow-auto", children: lockedWhere !== null ? (_jsxs(_Fragment, { children: [_jsx("p", { className: "mb-2 text-meta text-muted", children: copy.search.unreadable }), _jsx(ExpressionView, { node: lockedWhere, model: model })] })) : (_jsx(WhereTree, { model: model, group: tree, onChange: (next) => push({ tree: next }), ...(focus === undefined ? {} : { focus }) })) })] }), _jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.order }), _jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-1", children: [_jsx(Tags, { items: order.map((sort, index) => ({
213
+ return (_jsxs("div", { className: "flex min-w-0 flex-col gap-3 p-3", children: [_jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.filter }), _jsx("div", { className: "max-h-72 min-w-0 overflow-auto", children: lockedSelection !== null ? (_jsxs(_Fragment, { children: [_jsx("p", { className: "mb-2 text-meta text-muted", children: copy.search.unreadable }), _jsx(ExpressionView, { node: lockedSelection, model: model })] })) : (_jsx(SelectionTree, { model: model, group: tree, onChange: (next) => push({ tree: next }), ...(focus === undefined ? {} : { focus }) })) })] }), _jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.order }), _jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-1", children: [_jsx(Tags, { items: order.map((sort, index) => ({
215
214
  id: `${sort.field}-${index}`,
216
215
  label: sort.field,
217
216
  note: sort.descending === true ? "↓" : "↑",
@@ -239,26 +238,37 @@ export function CriteriaBuilder({ model, initial, focus, onApply, onCancel, }) {
239
238
  onRemove: () => push({ levels: levels.filter((_, at) => at !== index) }),
240
239
  removeLabel: fillCopy(copy.builder.dropLevel, { field: level.field }),
241
240
  },
242
- ] })] }, `${level.field}-${index}`))), _jsx(AddTag, { label: copy.builder.addGroup, options: scalarNames.filter((name) => !levels.some((one) => one.field === name)), onPick: (name) => push({ levels: [...levels, { field: name }] }) })] }), levels.length === 0 ? (_jsx("p", { className: "text-meta text-muted", children: copy.builder.noGrouping })) : null] }), levels.length > 0 ? (_jsxs(_Fragment, { children: [_jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.totals }), Object.keys(totals).length === 0 ? (_jsx("p", { className: "text-meta text-muted", children: copy.builder.noTotals })) : null, Object.entries(totals).map(([name, [fn, field]]) => (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [_jsx("select", { value: fn, onChange: (event) => push({
243
- totals: { ...totals, [name]: [event.target.value, field] },
244
- }), className: `min-w-0 flex-1 basis-28 rounded-control border px-2 py-1 text-meta ${box}`, children: FOLD_FUNCTIONS.map((one) => (_jsx("option", { value: one, children: one }, one))) }), _jsx("select", { value: field, onChange: (event) => push({ totals: { ...totals, [name]: [fn, event.target.value] } }), className: select, children: scalarNames.map((one) => (_jsx("option", { value: one, children: one }, one))) }), _jsx("span", { className: "shrink-0 text-micro text-muted", children: fillCopy(copy.builder.totalAs, { name }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropTotal, onClick: () => {
245
- const { [name]: _dropped, ...rest } = totals;
246
- push({ totals: rest });
241
+ ] })] }, `${level.field}-${index}`))), _jsx(AddTag, { label: copy.builder.addGroup, options: scalarNames.filter((name) => !levels.some((one) => one.field === name)), onPick: (name) => push({ levels: [...levels, { field: name }] }) })] }), levels.length === 0 ? (_jsx("p", { className: "text-meta text-muted", children: copy.builder.noGrouping })) : null] }), levels.length > 0 ? (_jsxs(_Fragment, { children: [_jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.totals }), Object.keys(measures).length === 0 ? (_jsx("p", { className: "text-meta text-muted", children: copy.builder.noTotals })) : null, Object.entries(measures).map(([name, measure]) => (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [_jsx("select", { "aria-label": fillCopy(copy.builder.totalFunction, { name }), value: measure.function, onChange: (event) => push({
242
+ measures: {
243
+ ...measures,
244
+ [name]: { function: event.target.value, field: measure.field },
245
+ },
246
+ }), className: `min-w-0 flex-1 basis-28 rounded-control border px-2 py-1 text-meta ${box}`, children: MEASURE_FUNCTIONS.map((one) => (_jsx("option", { value: one, children: one }, one))) }), _jsx("select", { "aria-label": fillCopy(copy.builder.totalField, { name }), value: measure.field, onChange: (event) => push({
247
+ measures: {
248
+ ...measures,
249
+ [name]: { ...measure, field: event.target.value },
250
+ },
251
+ }), className: select, children: scalarNames.map((one) => (_jsx("option", { value: one, children: one }, one))) }), _jsx("span", { className: "shrink-0 text-micro text-muted", children: fillCopy(copy.builder.totalAs, { name }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropTotal, onClick: () => {
252
+ const { [name]: _dropped, ...rest } = measures;
253
+ push({ measures: rest });
247
254
  }, className: "ml-auto shrink-0 text-muted", children: _jsx(Trash2, { className: "size-4" }) })] }, name))), _jsx("div", { children: _jsxs(Button, { role: "ghost", disabled: scalarNames.length === 0, onClick: () => {
248
255
  let name = "total";
249
256
  let index = 2;
250
- while (name in totals)
257
+ while (name in measures)
251
258
  name = `total_${index++}`;
252
259
  push({
253
- totals: { ...totals, [name]: ["sum", scalarNames[0] ?? ""] },
260
+ measures: {
261
+ ...measures,
262
+ [name]: { function: "sum", field: scalarNames[0] ?? "" },
263
+ },
254
264
  });
255
- }, children: [_jsx(Plus, { className: "size-4" }), " ", copy.builder.addTotal] }) })] }), _jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.filterPiles }), _jsx("p", { className: "text-meta text-muted", children: copy.builder.pilesNote }), _jsx(WhereTree, { model: havingModel, group: havingTree, onChange: (next) => push({ havingTree: next }) })] }), _jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.pileOrder }), groupOrder.length === 0 ? (_jsx("p", { className: "text-meta text-muted", children: copy.builder.noPileOrder })) : null, groupOrder.map((sort, index) => (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [_jsx("select", { value: sort.field, onChange: (event) => push({
265
+ }, children: [_jsx(Plus, { className: "size-4" }), " ", copy.builder.addTotal] }) })] }), _jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.filterPiles }), _jsx("p", { className: "text-meta text-muted", children: copy.builder.pilesNote }), _jsx(SelectionTree, { model: measuresModel, group: measuresTree, onChange: (next) => push({ measuresTree: next }) })] }), _jsxs("section", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(Rule, { label: copy.builder.pileOrder }), groupOrder.length === 0 ? (_jsx("p", { className: "text-meta text-muted", children: copy.builder.noPileOrder })) : null, groupOrder.map((sort, index) => (_jsxs("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [_jsx("select", { "aria-label": copy.builder.pileOrderField, value: sort.field, onChange: (event) => push({
256
266
  groupOrder: groupOrder.map((one, at) => at === index ? { ...one, field: event.target.value } : one),
257
267
  }), className: select, children: [
258
268
  ...levels.map((level) => level.field),
259
- ...Object.keys(totals),
269
+ ...Object.keys(measures),
260
270
  "count",
261
- ].map((name) => (_jsx("option", { value: name, children: name }, name))) }), _jsxs("select", { value: sort.descending === true ? "desc" : "asc", onChange: (event) => push({
271
+ ].map((name) => (_jsx("option", { value: name, children: name }, name))) }), _jsxs("select", { "aria-label": copy.builder.pileOrderDirection, value: sort.descending === true ? "desc" : "asc", onChange: (event) => push({
262
272
  groupOrder: groupOrder.map((one, at) => at === index
263
273
  ? { ...one, descending: event.target.value === "desc" }
264
274
  : one),
@@ -84,7 +84,7 @@ function Node({ node, path, onOpen, onJoin, onRemove, open, surface, }) {
84
84
  /* Una instancia que no lleva expresión no tiene qué editar: el constructor
85
85
  edita lo que VIAJA, y ésta la contesta quien la declaró. Se ve y se saca
86
86
  como cualquiera; lo que no hace es prometer una puerta que da a nada. */
87
- const editable = node.kind === "group" || node.where !== undefined;
87
+ const editable = node.kind === "group" || node.selection !== undefined;
88
88
  return (_jsx(Chip, { label: node.label, path: path, ...(onOpen === undefined || !editable ? {} : { onOpen }), ...(onRemove === undefined ? {} : { onRemove }), surface: surface }));
89
89
  }
90
90
  /* El nodo abierto se marca: es donde va a caer lo próximo. Un anillo y no un
@@ -7,10 +7,11 @@ import { type LoadModel, type ModelCache } from "./paths.js";
7
7
  * intentar mostrar cualquier cosa. */
8
8
  export declare function isRecognizedFilter(value: unknown): value is BuiltFilter;
9
9
  /** One relation crossed on the way to a condition's field: «Líneas», and how many of the
10
- * lines have to match. A to-one relation (`many: false`) reaches one record: no `match`. */
10
+ * lines have to match. Whether the relation reaches many is the MODEL's to say, not the
11
+ * hop's: criteria's `{through, selection}` does not carry it, so a hop read back from a
12
+ * filter could not know it. A to-one relation keeps `"any"` — the one record it reaches. */
11
13
  export interface TreeHop {
12
14
  field: string;
13
- many: boolean;
14
15
  match: ThroughMatch;
15
16
  }
16
17
  export interface TreeCondition {
@@ -111,7 +112,7 @@ export declare function ExpressionView({ node, model, depth, modelAt, at, }: {
111
112
  /** El camino hasta acá (por los `through` de afuera). */
112
113
  at?: readonly string[];
113
114
  }): import("react").JSX.Element;
114
- export declare function WhereTree({ model, group, onChange, depth, focus, loadModel, models: shared, }: {
115
+ export declare function SelectionTree({ model, group, onChange, depth, focus, loadModel, models: shared, }: {
115
116
  model: ModelDefinition;
116
117
  group: TreeGroup;
117
118
  onChange: (next: TreeGroup) => void;
@@ -130,7 +131,7 @@ export declare function WhereTree({ model, group, onChange, depth, focus, loadMo
130
131
  * **Es un nombre de campo, no una ruta**, así que dos condiciones sobre el
131
132
  * mismo campo en ramas distintas se marcan las dos y la vista va a la primera.
132
133
  * Distinguirlas pide que el árbol y las instancias de la barra compartan la
133
- * identidad, y hoy no la comparten: `whereOf` arma el filtro salteándose los
134
+ * identidad, y hoy no la comparten: `selectionOf` arma el filtro salteándose los
134
135
  * niveles y lo que no viaja, así que la posición en uno no es la posición en
135
136
  * el otro.
136
137
  */
@@ -153,6 +154,6 @@ export declare function FilterBuilder({ model, initial, onApply, onCancel, loadM
153
154
  /** El filtro que ya estaba puesto, si había uno. Reabrir el constructor con esto adentro
154
155
  * tiene que seguir donde quedó, no empezar en blanco. */
155
156
  initial?: BuiltFilter;
156
- onApply: (where: BuiltFilter | undefined) => void;
157
+ onApply: (selection: BuiltFilter | undefined) => void;
157
158
  onCancel?: () => void;
158
159
  }): import("react").JSX.Element;
@@ -82,7 +82,7 @@ export function isRecognizedFilter(value) {
82
82
  return true;
83
83
  if ("negate" in record)
84
84
  return true;
85
- if (typeof record.through === "string" && "where" in record)
85
+ if (isThrough(record))
86
86
  return true;
87
87
  return false;
88
88
  }
@@ -91,9 +91,49 @@ function isThrough(value) {
91
91
  if (typeof value !== "object" || value === null)
92
92
  return false;
93
93
  const record = value;
94
- return (typeof record.through === "string" &&
95
- "where" in record &&
96
- (record.match === undefined || MATCHES.includes(record.match)));
94
+ return typeof record.through === "string" && "selection" in record;
95
+ }
96
+ function isNegate(value) {
97
+ return typeof value === "object" && value !== null && "negate" in value;
98
+ }
99
+ /**
100
+ * A relation crossed, read off criteria's shape: the quantifier is not a key, it is the
101
+ * sentence the `negate`s around the `through` make.
102
+ *
103
+ * {through, selection: s} «alguno» s
104
+ * {negate: {through, selection: s}} «ninguno» s
105
+ * {negate: {through, selection: {negate: s}}} «todos» s (none that does not)
106
+ *
107
+ * «Ninguno con no-s» and «todos con s» are the same filter; it reads as the second, the
108
+ * shorter sentence, and that is also how a path of two hops comes back: «ninguna línea con
109
+ * ningún impuesto» returns as «todas las líneas con algún impuesto», which filters the same.
110
+ * Anything else is not a relation crossed: `null`.
111
+ */
112
+ function crossedOf(value) {
113
+ if (isThrough(value)) {
114
+ return { through: value.through, match: "any", selection: value.selection };
115
+ }
116
+ if (!isNegate(value) || !isThrough(value.negate))
117
+ return null;
118
+ const { through, selection } = value.negate;
119
+ return isNegate(selection)
120
+ ? { through, match: "all", selection: selection.negate }
121
+ : { through, match: "none", selection };
122
+ }
123
+ /** The other way: a relation and its quantifier, written the way criteria reads them. */
124
+ function crossing(through, match, inner) {
125
+ if (match === "none")
126
+ return { negate: { through, selection: inner } };
127
+ if (match === "all")
128
+ return { negate: { through, selection: { negate: inner } } };
129
+ return { through, selection: inner };
130
+ }
131
+ /** Whether a «some» crossing reaches ONE record: a to-one relation, as the model says. Then
132
+ * it is said as a path («Cliente > País»), since «alguno de» would be noise. Without the
133
+ * model it is said as what `{through, selection}` means — «alguno de» —, never wrong. */
134
+ function reachesOne(model, crossed) {
135
+ const field = model?.fields[crossed.through];
136
+ return crossed.match === "any" && field !== undefined && !isToMany(field);
97
137
  }
98
138
  export function blankCondition(model, first) {
99
139
  const field = first ?? "";
@@ -129,9 +169,7 @@ export function treeToFilter(node) {
129
169
  /** The relations of a path, as nested `through` nodes around the condition: the first hop
130
170
  * outside, the last one next to the condition — the order the path reads in. */
131
171
  function wrapThrough(hops, leaf) {
132
- return hops.reduceRight((inner, hop) => hop.many
133
- ? { through: hop.field, match: hop.match, where: inner }
134
- : { through: hop.field, where: inner }, leaf);
172
+ return hops.reduceRight((inner, hop) => crossing(hop.field, hop.match, inner), leaf);
135
173
  }
136
174
  function conditionToFilter(node) {
137
175
  {
@@ -219,21 +257,17 @@ export function treeFromFilter(filter) {
219
257
  return conditionToTree(filter);
220
258
  /* A chain of relations ending in ONE condition is one row with its path. A chain that ends
221
259
  in a group («alguna línea con impuesto > 10 Y cantidad > 2», both about the SAME line)
222
- cannot be a row: the tree shows it read-only and the JSON stays the way to edit it. */
223
- if (isThrough(filter)) {
224
- const hops = [];
225
- let node = filter;
226
- while (isThrough(node)) {
227
- hops.push({
228
- field: node.through,
229
- many: node.match !== undefined,
230
- match: node.match ?? "any",
231
- });
232
- node = node.where;
233
- }
234
- if (!isCondition(node))
235
- return null;
236
- return { ...conditionToTree(node), through: hops };
260
+ cannot be a row: the tree shows it read-only and the JSON stays the way to edit it.
261
+ Read before `negate`: «ninguna línea con…» is a `negate` around a `through`, and it is
262
+ one row with its quantifier, not a group. */
263
+ const hops = [];
264
+ let node = filter;
265
+ for (let crossed = crossedOf(node); crossed !== null; crossed = crossedOf(node)) {
266
+ hops.push({ field: crossed.through, match: crossed.match });
267
+ node = crossed.selection;
268
+ }
269
+ if (hops.length > 0) {
270
+ return isCondition(node) ? { ...conditionToTree(node), through: hops } : null;
237
271
  }
238
272
  if (typeof filter !== "object" || filter === null)
239
273
  return null;
@@ -320,14 +354,17 @@ modelAt) {
320
354
  }
321
355
  function say(node, model, depth, at, modelAt) {
322
356
  const copy = currentCopy();
323
- if ("through" in node) {
357
+ const crossed = crossedOf(node);
358
+ if (crossed !== null) {
324
359
  /* «alguno de Líneas con alguno de Impuestos con Monto mayor que 10». The quantifier
325
360
  is a separate word and not «algún impuesto» because the model publishes the label,
326
361
  not its gender or its singular: «algún Impuestos» would be worse than neutral. */
327
- const relation = model === undefined ? node.through : fieldLabel(model, node.through, copy.locale);
328
- const next = [...at, node.through];
329
- const inner = say(node.where, modelAt?.(next), depth + 1, next, modelAt);
330
- const template = node.match === undefined ? copy.fieldPath.say.one : copy.fieldPath.say[node.match];
362
+ const relation = model === undefined ? crossed.through : fieldLabel(model, crossed.through, copy.locale);
363
+ const next = [...at, crossed.through];
364
+ const inner = say(crossed.selection, modelAt?.(next), depth + 1, next, modelAt);
365
+ const template = reachesOne(model, crossed)
366
+ ? copy.fieldPath.say.one
367
+ : copy.fieldPath.say[crossed.match];
331
368
  return fillCopy(template, { relation, inner });
332
369
  }
333
370
  if ("all" in node || "any" in node) {
@@ -343,6 +380,10 @@ function say(node, model, depth, at, modelAt) {
343
380
  if ("negate" in node) {
344
381
  return `${copy.search.notWord} ${say(node.negate, model, depth + 1, at, modelAt)}`;
345
382
  }
383
+ /* Every `through` was said above; anything still not a condition is not a shape of the
384
+ grammar, and it is shown as it came rather than as a sentence it is not. */
385
+ if (!isCondition(node))
386
+ return JSON.stringify(node);
346
387
  const label = model === undefined ? node.field : fieldLabel(model, node.field, copy.locale);
347
388
  return sayCondition(label, node.operator, describeValue(node.value, node.operator));
348
389
  }
@@ -356,13 +397,14 @@ export function ExpressionView({ node, model, depth = 0, modelAt, at = [], }) {
356
397
  const copy = useUiCopy();
357
398
  const box = surface === "chrome" ? "border-chrome-ink/20" : "border-ink/15";
358
399
  const indent = depth === 0 ? "" : "ml-4";
359
- if ("through" in node) {
360
- const relation = model === undefined ? node.through : fieldLabel(model, node.through, copy.locale);
361
- const next = [...at, node.through];
400
+ const crossed = crossedOf(node);
401
+ if (crossed !== null) {
402
+ const relation = model === undefined ? crossed.through : fieldLabel(model, crossed.through, copy.locale);
403
+ const next = [...at, crossed.through];
362
404
  const inner = modelAt?.(next);
363
- return (_jsxs("div", { className: `flex flex-col gap-1 border-l-2 pl-2 ${box} ${indent}`, children: [_jsx("p", { className: "text-micro text-muted", children: node.match === undefined
405
+ return (_jsxs("div", { className: `flex flex-col gap-1 border-l-2 pl-2 ${box} ${indent}`, children: [_jsx("p", { className: "text-micro text-muted", children: reachesOne(model, crossed)
364
406
  ? relation
365
- : `${copy.fieldPath.match[node.match]} · ${relation}` }), _jsx(ExpressionView, { node: node.where, ...(inner === undefined ? {} : { model: inner }), ...(modelAt === undefined ? {} : { modelAt }), at: next, depth: depth + 1 })] }));
407
+ : `${copy.fieldPath.match[crossed.match]} · ${relation}` }), _jsx(ExpressionView, { node: crossed.selection, ...(inner === undefined ? {} : { model: inner }), ...(modelAt === undefined ? {} : { modelAt }), at: next, depth: depth + 1 })] }));
366
408
  }
367
409
  if ("all" in node || "any" in node) {
368
410
  /* LAS MISMAS TRES PALABRAS QUE LA BARRA. Un grupo que acá se llama «coincide
@@ -370,10 +412,10 @@ export function ExpressionView({ node, model, depth = 0, modelAt, at = [], }) {
370
412
  cosa, y el que los lee tiene que aprender los dos. */
371
413
  const label = "all" in node ? copy.search.joins.all : copy.search.joins.any;
372
414
  const items = "all" in node ? node.all : node.any;
373
- return (_jsxs("div", { className: `flex flex-col gap-1 border-l-2 pl-2 ${box} ${indent}`, children: [_jsx("p", { className: "text-micro text-muted", children: label }), items.map((child, index) => (_jsx(ExpressionView, { node: child, ...(model === undefined ? {} : { model }), depth: depth + 1 }, index)))] }));
415
+ return (_jsxs("div", { className: `flex flex-col gap-1 border-l-2 pl-2 ${box} ${indent}`, children: [_jsx("p", { className: "text-micro text-muted", children: label }), items.map((child, index) => (_jsx(ExpressionView, { node: child, ...(model === undefined ? {} : { model }), ...(modelAt === undefined ? {} : { modelAt }), at: at, depth: depth + 1 }, index)))] }));
374
416
  }
375
417
  if ("negate" in node) {
376
- return (_jsxs("div", { className: `flex flex-col gap-1 border-l-2 pl-2 ${box} ${indent}`, children: [_jsx("p", { className: "text-micro text-muted", children: copy.search.joins.none }), _jsx(ExpressionView, { node: node.negate, ...(model === undefined ? {} : { model }), depth: depth + 1 })] }));
418
+ return (_jsxs("div", { className: `flex flex-col gap-1 border-l-2 pl-2 ${box} ${indent}`, children: [_jsx("p", { className: "text-micro text-muted", children: copy.search.joins.none }), _jsx(ExpressionView, { node: node.negate, ...(model === undefined ? {} : { model }), ...(modelAt === undefined ? {} : { modelAt }), at: at, depth: depth + 1 })] }));
377
419
  }
378
420
  /* Y la misma frase que la ficha: una condición se lee igual esté donde esté. */
379
421
  return _jsx("p", { className: `text-meta ${indent}`, children: describeFilter(node, model) });
@@ -381,7 +423,7 @@ export function ExpressionView({ node, model, depth = 0, modelAt, at = [], }) {
381
423
  /* ---------------------------------------------------------------------- *
382
424
  * UN GRUPO, DIBUJADO — la pieza que se llama a sí misma para anidar.
383
425
  * ---------------------------------------------------------------------- */
384
- export function WhereTree({ model, group, onChange, depth = 0, focus, loadModel, models: shared, }) {
426
+ export function SelectionTree({ model, group, onChange, depth = 0, focus, loadModel, models: shared, }) {
385
427
  const names = filterableNames(model);
386
428
  const copy = useUiCopy();
387
429
  const surface = useSurface();
@@ -418,7 +460,7 @@ export function WhereTree({ model, group, onChange, depth = 0, focus, loadModel,
418
460
  function removeAt(index) {
419
461
  onChange({ ...group, children: group.children.filter((_, at) => at !== index) });
420
462
  }
421
- return (_jsxs("div", { className: `flex min-w-0 flex-col gap-2 rounded-control border p-2 ${box}`, children: [_jsxs("p", { className: "flex flex-wrap items-baseline gap-1 text-meta", children: [copy.search.askJoin, _jsx(JoinWord, { join: group.join, onChange: (join) => onChange({ ...group, join }) })] }), group.children.map((child, index) => child.kind === "group" ? (_jsxs("div", { className: "flex min-w-0 items-start gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(WhereTree, { model: model, group: child, onChange: (next) => setChild(index, next), depth: depth + 1, models: models, ...(focus === undefined ? {} : { focus }) }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropGroup, disabled: group.children.length === 1, onClick: () => removeAt(index), className: "mt-2 text-muted disabled:opacity-30", children: _jsx(Trash2, { className: "size-4" }) })] }, index)) : (_jsx(ConditionRow, { model: model, models: models, child: child, box: box, focused: focus !== undefined && child.field === focus, onChange: (next) => setChild(index, next), actions: _jsxs("span", { className: "ml-auto flex shrink-0 items-center gap-2", children: [_jsx("button", { type: "button", "aria-label": copy.builder.addRule, onClick: () => addConditionAfter(index), className: "text-muted hover:text-ink", children: _jsx(Plus, { className: "size-4" }) }), _jsx("button", { type: "button", "aria-label": copy.builder.addNested, onClick: () => addGroupAfter(index), className: "text-muted hover:text-ink", children: _jsx(FolderTree, { className: "size-4" }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropRule, disabled: group.children.length === 1, onClick: () => removeAt(index), className: "text-muted disabled:opacity-30", children: _jsx(Trash2, { className: "size-4" }) })] }) }, index)))] }));
463
+ return (_jsxs("div", { className: `flex min-w-0 flex-col gap-2 rounded-control border p-2 ${box}`, children: [_jsxs("p", { className: "flex flex-wrap items-baseline gap-1 text-meta", children: [copy.search.askJoin, _jsx(JoinWord, { join: group.join, onChange: (join) => onChange({ ...group, join }) })] }), group.children.map((child, index) => child.kind === "group" ? (_jsxs("div", { className: "flex min-w-0 items-start gap-2", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(SelectionTree, { model: model, group: child, onChange: (next) => setChild(index, next), depth: depth + 1, models: models, ...(focus === undefined ? {} : { focus }) }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropGroup, disabled: group.children.length === 1, onClick: () => removeAt(index), className: "mt-2 text-muted disabled:opacity-30", children: _jsx(Trash2, { className: "size-4" }) })] }, index)) : (_jsx(ConditionRow, { model: model, models: models, child: child, box: box, focused: focus !== undefined && child.field === focus, onChange: (next) => setChild(index, next), actions: _jsxs("span", { className: "ml-auto flex shrink-0 items-center gap-2", children: [_jsx("button", { type: "button", "aria-label": copy.builder.addRule, onClick: () => addConditionAfter(index), className: "text-muted hover:text-ink", children: _jsx(Plus, { className: "size-4" }) }), _jsx("button", { type: "button", "aria-label": copy.builder.addNested, onClick: () => addGroupAfter(index), className: "text-muted hover:text-ink", children: _jsx(FolderTree, { className: "size-4" }) }), _jsx("button", { type: "button", "aria-label": copy.builder.dropRule, disabled: group.children.length === 1, onClick: () => removeAt(index), className: "text-muted disabled:opacity-30", children: _jsx(Trash2, { className: "size-4" }) })] }) }, index)))] }));
422
464
  }
423
465
  /* ---------------------------------------------------------------------- *
424
466
  * UNA REGLA — el camino hasta el campo, cuántos de cada relación, el operador y el valor.
@@ -440,7 +482,6 @@ function ConditionRow({ model, models, child, box, focused, onChange, actions, }
440
482
  return;
441
483
  const nextHops = found.slice(0, -1).map((step, at) => ({
442
484
  field: step.name,
443
- many: isToMany(step.field),
444
485
  /* Cambiar el campo final no reinicia la ficha de una relación que sigue en el camino. */
445
486
  match: hops[at]?.field === step.name ? hops[at].match : "any",
446
487
  }));
@@ -462,9 +503,13 @@ function ConditionRow({ model, models, child, box, focused, onChange, actions, }
462
503
  return (_jsxs("div", {
463
504
  /* La que se vino a ver se marca y se trae a la vista. El anillo y no
464
505
  un fondo: el fondo compite con el `select` que hay que tocar. */
465
- ref: focused ? (node) => node?.scrollIntoView({ block: "nearest" }) : undefined, className: `flex min-w-0 flex-wrap items-center gap-2 rounded-control ${focused ? "-m-1 p-1 ring-1 ring-primary/60" : ""}`, children: [_jsx(FieldPath, { model: model, models: models, value: path, label: copy.builder.ruleField, filter: (field) => isFilterable(field), onChange: choosePath }), hops.map((hop, at) => hop.many ? (_jsxs("label", { className: `flex min-w-0 shrink-0 items-center gap-1 rounded-control border px-2 py-0.5 text-micro ${box}`, children: [_jsx("span", { className: "max-w-32 truncate text-muted", children: steps?.[at]?.label ?? hop.field }), _jsx("select", { "aria-label": fillCopy(copy.fieldPath.match.label, {
466
- relation: steps?.[at]?.label ?? hop.field,
467
- }), value: hop.match, onChange: (event) => setMatch(at, event.target.value), className: "bg-transparent text-micro font-medium", children: MATCHES.map((match) => (_jsx("option", { value: match, children: copy.fieldPath.match[match] }, match))) })] }, `${hop.field}-${at}`)) : null), _jsx("select", { "aria-label": copy.builder.ruleOperator, value: child.operator, onChange: (event) => onChange({ ...child, operator: event.target.value }), className: `min-w-0 flex-1 basis-36 rounded-control border px-2 py-1 text-meta ${box}`, children: ops.map((operator) => (_jsx("option", { value: operator, children: opLabel(operator) }, operator))) }), WITHOUT_VALUE.has(child.operator) ? (_jsx("span", { className: "flex-1 text-meta text-muted", children: copy.builder.noValue })) : WITH_RANGE.has(child.operator) ? (_jsxs("span", { className: "flex min-w-0 flex-1 basis-40 items-center gap-1", children: [_jsx("input", { type: inputType(type), value: child.value, onChange: (event) => onChange({ ...child, value: event.target.value }), placeholder: copy.builder.from, className: `min-w-0 flex-1 rounded-control border px-2 py-1 text-meta ${box}` }), _jsx("span", { className: "shrink-0 text-micro text-muted", children: copy.search.and }), _jsx("input", { type: inputType(type), value: child.upper ?? "", onChange: (event) => onChange({ ...child, upper: event.target.value }), placeholder: copy.builder.to, className: `min-w-0 flex-1 rounded-control border px-2 py-1 text-meta ${box}` })] })) : (_jsx("input", { type: inputType(type), value: child.value, onChange: (event) => onChange({ ...child, value: event.target.value }), placeholder: copy.builder.value, className: `min-w-0 flex-1 basis-40 rounded-control border px-2 py-1 text-meta ${box}` })), actions] }));
506
+ ref: focused ? (node) => node?.scrollIntoView({ block: "nearest" }) : undefined, className: `flex min-w-0 flex-wrap items-center gap-2 rounded-control ${focused ? "-m-1 p-1 ring-1 ring-primary/60" : ""}`, children: [_jsx(FieldPath, { model: model, models: models, value: path, label: copy.builder.ruleField, filter: (field) => isFilterable(field), onChange: choosePath }), hops.map((hop, at) => {
507
+ const step = steps?.[at];
508
+ const many = step !== undefined && isToMany(step.field);
509
+ return hop.match !== "any" || many ? (_jsxs("label", { className: `flex min-w-0 shrink-0 items-center gap-1 rounded-control border px-2 py-0.5 text-micro ${box}`, children: [_jsx("span", { className: "max-w-32 truncate text-muted", children: step?.label ?? hop.field }), _jsx("select", { "aria-label": fillCopy(copy.fieldPath.match.label, {
510
+ relation: step?.label ?? hop.field,
511
+ }), value: hop.match, onChange: (event) => setMatch(at, event.target.value), className: "bg-transparent text-micro font-medium", children: MATCHES.map((match) => (_jsx("option", { value: match, children: copy.fieldPath.match[match] }, match))) })] }, `${hop.field}-${at}`)) : null;
512
+ }), _jsx("select", { "aria-label": copy.builder.ruleOperator, value: child.operator, onChange: (event) => onChange({ ...child, operator: event.target.value }), className: `min-w-0 flex-1 basis-36 rounded-control border px-2 py-1 text-meta ${box}`, children: ops.map((operator) => (_jsx("option", { value: operator, children: opLabel(operator) }, operator))) }), WITHOUT_VALUE.has(child.operator) ? (_jsx("span", { className: "flex-1 text-meta text-muted", children: copy.builder.noValue })) : WITH_RANGE.has(child.operator) ? (_jsxs("span", { className: "flex min-w-0 flex-1 basis-40 items-center gap-1", children: [_jsx("input", { type: inputType(type), value: child.value, onChange: (event) => onChange({ ...child, value: event.target.value }), placeholder: copy.builder.from, className: `min-w-0 flex-1 rounded-control border px-2 py-1 text-meta ${box}` }), _jsx("span", { className: "shrink-0 text-micro text-muted", children: copy.search.and }), _jsx("input", { type: inputType(type), value: child.upper ?? "", onChange: (event) => onChange({ ...child, upper: event.target.value }), placeholder: copy.builder.to, className: `min-w-0 flex-1 rounded-control border px-2 py-1 text-meta ${box}` })] })) : (_jsx("input", { type: inputType(type), value: child.value, onChange: (event) => onChange({ ...child, value: event.target.value }), placeholder: copy.builder.value, className: `min-w-0 flex-1 basis-40 rounded-control border px-2 py-1 text-meta ${box}` })), actions] }));
468
513
  }
469
514
  export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, models: shared, }) {
470
515
  const names = filterableNames(model);
@@ -521,5 +566,5 @@ export function FilterBuilder({ model, initial, onApply, onCancel, loadModel, mo
521
566
  setLockedView(parsed);
522
567
  }
523
568
  }
524
- return (_jsxs("div", { className: "flex min-w-0 flex-col gap-3 p-3", children: [_jsx("div", { className: "max-h-80 min-w-0 overflow-auto", children: lockedView !== null ? (_jsxs(_Fragment, { children: [_jsx("p", { className: "text-meta text-muted", children: copy.search.unreadable }), _jsx(ExpressionView, { node: lockedView, model: model, modelAt: models.peek })] })) : (_jsx(WhereTree, { model: model, group: tree, onChange: updateTree, models: models })) }), _jsx(LazyJsonEditor, { value: rawText, onChange: updateRaw, error: rawError, label: copy.builder.jsonFilter }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { role: "primary", disabled: rawError !== null, onClick: () => onApply(rawText.trim() === "" ? undefined : JSON.parse(rawText)), children: copy.builder.add }), onCancel === undefined ? null : (_jsx(Button, { role: "ghost", onClick: onCancel, children: copy.builder.cancel }))] })] }));
569
+ return (_jsxs("div", { className: "flex min-w-0 flex-col gap-3 p-3", children: [_jsx("div", { className: "max-h-80 min-w-0 overflow-auto", children: lockedView !== null ? (_jsxs(_Fragment, { children: [_jsx("p", { className: "text-meta text-muted", children: copy.search.unreadable }), _jsx(ExpressionView, { node: lockedView, model: model, modelAt: models.peek })] })) : (_jsx(SelectionTree, { model: model, group: tree, onChange: updateTree, models: models })) }), _jsx(LazyJsonEditor, { value: rawText, onChange: updateRaw, error: rawError, label: copy.builder.jsonFilter }), _jsxs("div", { className: "flex gap-2", children: [_jsx(Button, { role: "primary", disabled: rawError !== null, onClick: () => onApply(rawText.trim() === "" ? undefined : JSON.parse(rawText)), children: copy.builder.add }), onCancel === undefined ? null : (_jsx(Button, { role: "ghost", onClick: onCancel, children: copy.builder.cancel }))] })] }));
525
570
  }
@@ -63,8 +63,11 @@ export function JsonEditor({ value, onChange, error, height = "16rem", label, })
63
63
  /* The chrome is dark in both themes; the canvas follows the theme. */
64
64
  const dark = surface === "chrome" || resolved === "dark";
65
65
  return (_jsxs("div", { className: "flex min-w-0 flex-col gap-1", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("p", { id: labelId, className: "text-micro text-muted", children: label ?? copy.builder.editor }), _jsxs(Button, { role: "ghost", size: "sm", disabled: value.trim() === "", onClick: () => onChange(formatJson(value)), children: [_jsx(Wand2, { className: "size-3" }), " ", copy.builder.format] })] }), _jsx("div", { className: `overflow-hidden rounded-control border ${error == null ? "border-ink/15" : "border-danger"}`, children: _jsx(CodeMirror, { value: value, onChange: onChange, height: height, theme: dark ? "dark" : "light", extensions: [
66
- /* The editable area is CodeMirror's own element: named here or nowhere. */
67
- EditorView.contentAttributes.of({ "aria-labelledby": labelId }),
66
+ /* The editable area is CodeMirror's own element: named here or nowhere. Marked
67
+ tabbable too: it is already reached with Tab, but its scroller (`tabindex=-1`)
68
+ is a scrollable region, and an accessibility check (axe,
69
+ `scrollable-region-focusable`) only counts content it can see is focusable. */
70
+ EditorView.contentAttributes.of({ "aria-labelledby": labelId, tabindex: "0" }),
68
71
  json(),
69
72
  linter(jsonParseLinter()),
70
73
  lintGutter(),
@@ -228,9 +228,9 @@ export function SearchBar({ facets, model, criteria, onCriteriaChange, placehold
228
228
  return;
229
229
  }
230
230
  if (suggestion.kind === "literal") {
231
- const where = literal?.(suggestion.text) ?? null;
232
- if (where !== null)
233
- put(filterCriteria(where, fillCopy(copy.search.literalChip, { text: suggestion.text })));
231
+ const selection = literal?.(suggestion.text) ?? null;
232
+ if (selection !== null)
233
+ put(filterCriteria(selection, fillCopy(copy.search.literalChip, { text: suggestion.text })));
234
234
  return;
235
235
  }
236
236
  commit(suggestion.field, suggestion.op, suggestion.value);
@@ -6,9 +6,9 @@ export interface BuiltCondition {
6
6
  operator: string;
7
7
  value: unknown;
8
8
  }
9
- /** Lo que el filtro puede ser en su forma real: una condición, un grupo `all`/`any` de más
10
- * filtros —lo que el árbol arma, a cualquier profundidad—, o un `negate` que llegó de otro
11
- * lado y que el árbol no fabrica, pero que este componente sabe mostrar y editar como JSON. */
9
+ /** Lo que el filtro puede ser en su forma real —la `Expression` de `@sincpro/criteria`, clave
10
+ * por clave—: una condición, un grupo `all`/`any` de más filtros —lo que el árbol arma, a
11
+ * cualquier profundidad—, un `negate`, o un filtro a través de una relación. */
12
12
  export type BuiltFilter = BuiltCondition | {
13
13
  all: BuiltFilter[];
14
14
  } | {
@@ -17,26 +17,37 @@ export type BuiltFilter = BuiltCondition | {
17
17
  negate: BuiltFilter;
18
18
  } | BuiltThrough;
19
19
  /** How many of the records reached through a to-many relation have to match: «alguno»,
20
- * «ninguno», «todos». A to-one relation reaches one record, so it carries none. */
20
+ * «ninguno», «todos». It is the TREE's word, not a key that travels: criteria's
21
+ * `{through, selection}` says «some», and the other two are written with `negate` around it
22
+ * (see {@link BuiltThrough}). */
21
23
  export type ThroughMatch = "any" | "none" | "all";
22
24
  /**
23
- * A filter asked about the records at the other end of a relation.
25
+ * A filter asked about the records at the other end of a relation: some record the relation
26
+ * `through` holds answers `selection` — criteria's shape, and nothing beside it.
24
27
  *
25
28
  * «alguna línea con algún impuesto con monto > 10»
26
- * {through: "lines", match: "any",
27
- * where: {through: "taxes", match: "any",
28
- * where: {field: "amount", operator: ">", value: 10}}}
29
+ * {through: "lines",
30
+ * selection: {through: "taxes",
31
+ * selection: {field: "amount", operator: ">", value: 10}}}
29
32
  *
30
- * «el cliente es de Bolivia» (to-one: no `match`)
31
- * {through: "partner_id", where: {field: "country", operator: "=", value: "BO"}}
33
+ * «el cliente es de Bolivia» (to-one: the one record it reaches)
34
+ * {through: "partner_id", selection: {field: "country", operator: "=", value: "BO"}}
35
+ *
36
+ * «ninguna línea con precio > 1»
37
+ * {negate: {through: "lines", selection: {field: "price", operator: ">", value: 1}}}
38
+ *
39
+ * «todas las líneas con precio > 1» (no line that does not have it)
40
+ * {negate: {through: "lines",
41
+ * selection: {negate: {field: "price", operator: ">", value: 1}}}}
32
42
  *
33
43
  * One node per relation crossed, nested in the order of the path: the engine reads it from
34
- * the outside in, the same way the path reads left to right.
44
+ * the outside in, the same way the path reads left to right. There is no `match` key:
45
+ * sincpro_framework's `Through` refuses one, and «none» and «all» are already sentences of
46
+ * the grammar.
35
47
  */
36
48
  export interface BuiltThrough {
37
49
  through: string;
38
- match?: ThroughMatch;
39
- where: BuiltFilter;
50
+ selection: BuiltFilter;
40
51
  }
41
52
  /** Cómo se juntan las instancias de un nodo. `not` niega lo que tiene adentro. */
42
53
  export type CriteriaJoin = "all" | "any" | "not";
@@ -64,12 +75,12 @@ export type SearchCriteria = {
64
75
  * Lo que viaja, en la forma del motor y sin una clave de más.
65
76
  *
66
77
  * FALTA cuando el recorte no se puede preguntar: «con entregas pendientes» se define
67
- * con datos de otro contexto y ningún `where` sobre esta tabla lo
78
+ * con datos de otro contexto y ninguna `selection` sobre esta tabla lo
68
79
  * contesta. La instancia existe igual —se ve, se cuenta, se saca— y lo
69
80
  * contesta quien la declaró. Sin esto, un recorte así no era una instancia
70
81
  * de nada: se dibujaba en el menú y tildarlo no hacía nada.
71
82
  */
72
- where?: BuiltCondition | BuiltFilter;
83
+ selection?: BuiltCondition | BuiltFilter;
73
84
  } | {
74
85
  id: string;
75
86
  kind: "join";
@@ -111,16 +122,17 @@ export declare function criteriaId(prefix: string): string;
111
122
  /** Una instancia de agrupado, a partir de un nivel ya legible. */
112
123
  export declare function groupCriteria(level: GroupLevel, label: string): SearchCriteria;
113
124
  /** Una instancia de filtro. `label` es lo único que distingue a uno declarado en
114
- * código de uno escrito en la barra; sin `where`, es uno que sólo contesta
125
+ * código de uno escrito en la barra; sin `selection`, es uno que sólo contesta
115
126
  * quien lo declaró. */
116
- export declare function filterCriteria(where: BuiltCondition | BuiltFilter | undefined, label: string, id?: string): SearchCriteria;
127
+ export declare function filterCriteria(selection: BuiltCondition | BuiltFilter | undefined, label: string, id?: string): SearchCriteria;
117
128
  /**
118
- * Lo que VIAJA: el `where` del motor, armado con las instancias de filtro.
129
+ * Lo que VIAJA: la `selection` del motor, armada con las instancias de filtro.
119
130
  *
120
131
  * Es lo único que sale de acá hacia afuera, y sale sin rótulos, sin ids y sin
121
- * clases: la UI se queda con lo que la UI necesita.
132
+ * clases: la UI se queda con lo que la UI necesita. Lleva el nombre del campo de la
133
+ * criteria que llena —`Criteria.selection`—, como el `selection` de `@sincpro/criteria`.
122
134
  */
123
- export declare function whereOf(all: readonly SearchCriteria[]): BuiltFilter | undefined;
135
+ export declare function selectionOf(all: readonly SearchCriteria[]): BuiltFilter | undefined;
124
136
  /** Los niveles que viajan, en orden. */
125
137
  export declare function levelsOf(all: readonly SearchCriteria[]): GroupLevel[];
126
138
  export type { GroupGrain, GroupLevel };
@@ -147,7 +159,7 @@ export declare function withLevels(all: readonly SearchCriteria[], levels: reado
147
159
  export declare function toggleNamed(all: readonly SearchCriteria[], named: {
148
160
  id: string;
149
161
  label: string;
150
- where?: BuiltCondition | BuiltFilter;
162
+ selection?: BuiltCondition | BuiltFilter;
151
163
  }): SearchCriteria[];
152
164
  /** Si ese filtro con nombre está puesto. Lo usa el panel para dibujar la marca:
153
165
  * la marca sale de lo PUESTO y no de un estado aparte que podría discrepar. */
@@ -71,23 +71,24 @@ export function groupCriteria(level, label) {
71
71
  return { id: criteriaId("g"), kind: "group", label, level };
72
72
  }
73
73
  /** Una instancia de filtro. `label` es lo único que distingue a uno declarado en
74
- * código de uno escrito en la barra; sin `where`, es uno que sólo contesta
74
+ * código de uno escrito en la barra; sin `selection`, es uno que sólo contesta
75
75
  * quien lo declaró. */
76
- export function filterCriteria(where, label, id) {
76
+ export function filterCriteria(selection, label, id) {
77
77
  return {
78
78
  id: id ?? criteriaId("f"),
79
79
  kind: "filter",
80
80
  label,
81
- ...(where === undefined ? {} : { where }),
81
+ ...(selection === undefined ? {} : { selection }),
82
82
  };
83
83
  }
84
84
  /**
85
- * Lo que VIAJA: el `where` del motor, armado con las instancias de filtro.
85
+ * Lo que VIAJA: la `selection` del motor, armada con las instancias de filtro.
86
86
  *
87
87
  * Es lo único que sale de acá hacia afuera, y sale sin rótulos, sin ids y sin
88
- * clases: la UI se queda con lo que la UI necesita.
88
+ * clases: la UI se queda con lo que la UI necesita. Lleva el nombre del campo de la
89
+ * criteria que llena —`Criteria.selection`—, como el `selection` de `@sincpro/criteria`.
89
90
  */
90
- export function whereOf(all) {
91
+ export function selectionOf(all) {
91
92
  const parts = filtersOf(all)
92
93
  .map(expressionOf)
93
94
  .filter((one) => one !== undefined);
@@ -100,10 +101,10 @@ export function whereOf(all) {
100
101
  function expressionOf(one) {
101
102
  if (one.kind === "group")
102
103
  return undefined;
103
- /* Una instancia sin `where` no viaja: no hay manera de preguntarla, y mandar
104
+ /* Una instancia sin `selection` no viaja: no hay manera de preguntarla, y mandar
104
105
  algo parecido sería contestar otra cosa. La contesta quien la declaró. */
105
106
  if (one.kind === "filter")
106
- return one.where;
107
+ return one.selection;
107
108
  const inside = one.of
108
109
  .map(expressionOf)
109
110
  .filter((each) => each !== undefined);
@@ -150,7 +151,7 @@ export function toggleNamed(all, named) {
150
151
  const at = all.findIndex((one) => one.id === named.id);
151
152
  if (at >= 0)
152
153
  return all.filter((_, index) => index !== at);
153
- return [...all, filterCriteria(named.where, named.label, named.id)];
154
+ return [...all, filterCriteria(named.selection, named.label, named.id)];
154
155
  }
155
156
  /** Si ese filtro con nombre está puesto. Lo usa el panel para dibujar la marca:
156
157
  * la marca sale de lo PUESTO y no de un estado aparte que podría discrepar. */
@@ -1,11 +1,11 @@
1
1
  export { type BuiltCondition, type BuiltFilter, type BuiltThrough, type ThroughMatch, } from "./criteria.js";
2
- export { type BuiltCriteria, type BuiltLevel, type BuiltSort, CriteriaBuilder, } from "./CriteriaBuilder.js";
2
+ export { type BuiltCriteria, type BuiltGrouping, type BuiltLevel, type BuiltMeasure, type BuiltSort, CriteriaBuilder, } from "./CriteriaBuilder.js";
3
3
  export { blankGroup, describeFilter, FilterBuilder, type TreeCondition, treeFromFilter, type TreeGroup, type TreeHop, type TreeNode, treeToFilter, } from "./FilterBuilder.js";
4
4
  export { FieldPath, type FieldPathProps, type FieldPathRule, type PathPick, useFieldPathSteps, useModelCache, } from "./FieldPath.js";
5
5
  export { formatJson, JsonEditor } from "./JsonEditor.js";
6
6
  export { createModelCache, type FieldPathStep, type FieldPathValue, isRelation, isToMany, type LoadModel, type ModelCache, pathLabel, peekLabels, resolvePath, } from "./paths.js";
7
7
  export { SearchBar, type SearchBarProps, type SearchFacet, } from "./SearchBar.js";
8
- export { at, criteriaId, type CriteriaJoin, type CriteriaPath, filterCriteria, filtersOf, type GroupCriteria, groupCriteria, groupsOf, hasNamed, levelsOf, nextJoin, removeAt, replaceAt, type SearchCriteria, toggleNamed, whereOf, withLevels, } from "./criteria.js";
8
+ export { at, criteriaId, type CriteriaJoin, type CriteriaPath, filterCriteria, filtersOf, type GroupCriteria, groupCriteria, groupsOf, hasNamed, levelsOf, nextJoin, removeAt, replaceAt, type SearchCriteria, selectionOf, toggleNamed, withLevels, } from "./criteria.js";
9
9
  export { CriteriaChips, type CriteriaChipsProps, } from "./CriteriaChips.js";
10
10
  export { type FieldDefinition, fieldLabel, filterableNames, isFilterable, isNumericType, type ModelDefinition, type ModelTranslations, } from "./model.js";
11
11
  export { answers, defaultOp, describeCondition, globToLike, opLabel, type QueryDraft, type QueryField, queryFields, type QueryKind, type QuerySuggestion, readTyped, suggest, type TypedValue, valueFor, type ValueShape, withoutValue, } from "./query.js";
@@ -11,7 +11,7 @@ export { SearchBar, } from "./SearchBar.js";
11
11
  /* LO QUE LA BARRA TIENE PUESTO: instancias. Una sola cosa para las dos clases
12
12
  —grupo y filtro—, con sus metadatos de UI afuera y el objeto del motor
13
13
  adentro, intacto. */
14
- export { at, criteriaId, filterCriteria, filtersOf, groupCriteria, groupsOf, hasNamed, levelsOf, nextJoin, removeAt, replaceAt, toggleNamed, whereOf, withLevels, } from "./criteria.js";
14
+ export { at, criteriaId, filterCriteria, filtersOf, groupCriteria, groupsOf, hasNamed, levelsOf, nextJoin, removeAt, replaceAt, selectionOf, toggleNamed, withLevels, } from "./criteria.js";
15
15
  export { CriteriaChips, } from "./CriteriaChips.js";
16
16
  /* EL VOCABULARIO DEL MODELO — lo que el servidor publica sobre sus campos. Lo
17
17
  hablan el constructor de filtros, el de criterias y la barra de búsqueda, así
@@ -24,7 +24,7 @@ export interface FieldDefinition {
24
24
  choices?: readonly unknown[];
25
25
  }
26
26
  export declare function isNumericType(type: string): boolean;
27
- /** Si este campo se puede usar en un `where`, un `order` o un `grouping.by` directamente.
27
+ /** Si este campo se puede usar en una `selection`, un `order` o un `grouping.group_by`, directo.
28
28
  * `ops.length === 0` alcanza como señal: la publican tanto `embedded` como los tres
29
29
  * relacionales, así que no hace falta mirar `kind` aparte. */
30
30
  export declare function isFilterable(field: FieldDefinition): boolean;
@@ -40,8 +40,8 @@ export interface ModelDefinition {
40
40
  aggregate: string;
41
41
  identity: string;
42
42
  fields: Record<string, FieldDefinition>;
43
- /** Ausente en un modelo armado a mano —el `having` sintético de `CriteriaBuilder`, por
44
- * ejemplo—; presente en cualquier `model_meta_data` real. */
43
+ /** Ausente en un modelo armado a mano —el de `where_measures` que `CriteriaBuilder` arma,
44
+ * por ejemplo—; presente en cualquier `model_meta_data` real. */
45
45
  translations?: ModelTranslations;
46
46
  }
47
47
  /** El rótulo de un campo en el idioma pedido: el que el modelo publicó para ese idioma, o el
@@ -20,7 +20,7 @@ const NUMERIC_TYPES = new Set(["integer", "number", "float", "decimal", "monetar
20
20
  export function isNumericType(type) {
21
21
  return NUMERIC_TYPES.has(type.toLowerCase());
22
22
  }
23
- /** Si este campo se puede usar en un `where`, un `order` o un `grouping.by` directamente.
23
+ /** Si este campo se puede usar en una `selection`, un `order` o un `grouping.group_by`, directo.
24
24
  * `ops.length === 0` alcanza como señal: la publican tanto `embedded` como los tres
25
25
  * relacionales, así que no hace falta mirar `kind` aparte. */
26
26
  export function isFilterable(field) {
@@ -597,6 +597,14 @@ export type UiCopy = {
597
597
  /** Sacar, uno por clase: el `aria-label` tiene que decir qué se saca. */
598
598
  dropOrder: string;
599
599
  dropTotal: string;
600
+ /** The name of a total's function select: «how "{name}" is computed». */
601
+ totalFunction: string;
602
+ /** The name of a total's field select: «field of "{name}"». */
603
+ totalField: string;
604
+ /** The name of the select that picks what the piles are ordered by. */
605
+ pileOrderField: string;
606
+ /** The name of the select that picks the piles' order direction. */
607
+ pileOrderDirection: string;
600
608
  dropRule: string;
601
609
  dropGroup: string;
602
610
  /** Agregar, en el árbol de condiciones. */
@@ -402,6 +402,10 @@ export const SPANISH_COPY = {
402
402
  changeGrain: "tocar para cambiar el corte",
403
403
  dropOrder: "quitar este orden",
404
404
  dropTotal: "quitar este total",
405
+ totalFunction: "cómo se calcula «{name}»",
406
+ totalField: "campo de «{name}»",
407
+ pileOrderField: "ordenar los montones por",
408
+ pileOrderDirection: "dirección del orden",
405
409
  dropRule: "quitar esta regla",
406
410
  dropGroup: "quitar este grupo",
407
411
  addRule: "agregar una regla después de ésta",
@@ -420,7 +424,7 @@ export const SPANISH_COPY = {
420
424
  editor: "Editor de código",
421
425
  format: "Formatear",
422
426
  invalidJson: "esto no es JSON válido",
423
- notCriteria: "una criteria es un objeto con where, order, grouping o specification",
427
+ notCriteria: "una criteria es un objeto con selection, order, grouping o specification",
424
428
  notFilter: "esto no es un filtro: hace falta una condición o un all/any/negate",
425
429
  apply: "Aplicar",
426
430
  add: "Agregar",
@@ -392,6 +392,10 @@ export const ENGLISH_COPY = {
392
392
  changeGrain: "tap to change the cut",
393
393
  dropOrder: "remove this sort",
394
394
  dropTotal: "remove this total",
395
+ totalFunction: "how «{name}» is computed",
396
+ totalField: "field of «{name}»",
397
+ pileOrderField: "order the piles by",
398
+ pileOrderDirection: "order direction",
395
399
  dropRule: "remove this rule",
396
400
  dropGroup: "remove this group",
397
401
  addRule: "add a rule after this one",
@@ -410,7 +414,7 @@ export const ENGLISH_COPY = {
410
414
  invalidJson: "this is not valid JSON",
411
415
  editor: "Code editor",
412
416
  format: "Format",
413
- notCriteria: "a criteria is an object with where, order, grouping or specification",
417
+ notCriteria: "a criteria is an object with selection, order, grouping or specification",
414
418
  notFilter: "this is not a filter: it needs a condition or an all/any/negate",
415
419
  apply: "Apply",
416
420
  add: "Add",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/web-ui",
3
- "version": "1.11.1",
3
+ "version": "2.0.0",
4
4
  "description": "An enterprise web design system for business software — ERPs, back offices, management tools — in React and Tailwind: tokens, primitives, components and the two views every management screen is made of.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",