@ai-matrx/records-ui 0.113.31 → 0.113.33

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.
@@ -1,15 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var core = require('@ai-matrx/records/core');
4
- var uuid = require('@ai-matrx/kit/uuid');
5
- var textCase = require('@ai-matrx/kit/text-case');
6
- var records = require('@ai-matrx/records');
7
- var dataTable = require('@ai-matrx/design-system/data-table');
8
- require('react');
9
- var versions_star = require('@ai-matrx/records/versions');
3
+ var firstPage = require('@ai-matrx/records/first-page');
4
+ var base = require('@ai-matrx/records/views');
10
5
  var tableStyle = require('@ai-matrx/design-system/data-table/table-style');
6
+ require('@ai-matrx/design-system/data-table');
11
7
  require('@ai-matrx/design-system/field-formats');
12
- var entity = require('@ai-matrx/records/entity');
8
+ require('@ai-matrx/records');
13
9
 
14
10
  function _interopNamespace(e) {
15
11
  if (e && e.__esModule) return e;
@@ -29,270 +25,9 @@ function _interopNamespace(e) {
29
25
  return Object.freeze(n);
30
26
  }
31
27
 
32
- var versions_star__namespace = /*#__PURE__*/_interopNamespace(versions_star);
28
+ var base__namespace = /*#__PURE__*/_interopNamespace(base);
33
29
 
34
- var __defProp = Object.defineProperty;
35
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
36
- var __getOwnPropNames = Object.getOwnPropertyNames;
37
- var __hasOwnProp = Object.prototype.hasOwnProperty;
38
- var __copyProps = (to, from, except, desc) => {
39
- if (from && typeof from === "object" || typeof from === "function") {
40
- for (let key of __getOwnPropNames(from))
41
- if (!__hasOwnProp.call(to, key) && key !== except)
42
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
43
- }
44
- return to;
45
- };
46
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget);
47
- function fieldName(field2) {
48
- const label = (field2.label ?? "").trim();
49
- if (label !== "" && label === field2.key && /^[a-z0-9]+(?:[_.-][a-z0-9]+)+$/.test(label)) return textCase.humanizeIdentifier(label);
50
- if (label !== "") return label;
51
- const name = (field2.name ?? "").trim();
52
- if (name !== "") return name;
53
- return textCase.humanizeIdentifier(field2.key);
54
- }
55
- var kernelId = (name) => records.KERNEL_TABLES.find((t) => t.name === name)?.id ?? "";
56
- var KERNEL_FILE_TABLE = kernelId("File");
57
- var KERNEL_PERSON_TABLE = kernelId("Person");
58
- Object.fromEntries(
59
- records.PARITY_FIELD_TYPES.map((p) => [p.parity_type, p.made_of])
60
- );
61
- var KERNEL = { file: KERNEL_FILE_TABLE, person: KERNEL_PERSON_TABLE };
62
- function editorKindFor(field2) {
63
- return records.fieldKindFor(field2, KERNEL);
64
- }
65
-
66
- // src/gridLook.ts
67
- function defaultSortOf(table, fields) {
68
- const raw = table?.default_sort ?? null;
69
- const first = Array.isArray(raw) ? raw[0] : raw;
70
- let name = null;
71
- let direction = "asc";
72
- if (typeof first === "string") {
73
- const trimmed = first.trim();
74
- if (trimmed === "") return null;
75
- if (trimmed.startsWith("-")) {
76
- name = trimmed.slice(1).trim();
77
- direction = "desc";
78
- } else {
79
- const [head, tail] = trimmed.split(/\s+/);
80
- name = head ?? null;
81
- if (tail && tail.toLowerCase() === "desc") direction = "desc";
82
- }
83
- } else if (first && typeof first === "object") {
84
- const entry = first;
85
- const named = entry["field"] ?? entry["key"] ?? entry["id"];
86
- name = typeof named === "string" ? named : null;
87
- if (String(entry["direction"] ?? "").toLowerCase() === "desc") direction = "desc";
88
- }
89
- if (!name) return null;
90
- const field2 = fields.find((f) => f.key === name) ?? fields.find((f) => f.id === name);
91
- return field2 ? { id: field2.key, direction } : null;
92
- }
93
- var MEASURE_LABEL = {
94
- count: "Count",
95
- sum: "Sum",
96
- avg: "Average",
97
- min: "Smallest",
98
- max: "Largest",
99
- median: "Median",
100
- filled: "Filled",
101
- empty: "Empty",
102
- unique: "Unique",
103
- percent_empty: "Percent empty",
104
- percent_filled: "Percent filled",
105
- range: "Range"
106
- };
107
-
108
- // src/gridPage.ts
109
- function filterRefusal(f) {
110
- if (!computedOnRead(f)) return null;
111
- return `${fieldName(f)} is worked out each time it is read, so the store keeps no value to filter the whole table by. Filter by a column it is worked out from.`;
112
- }
113
- function computedOnRead(f) {
114
- const kind = String(editorKindFor(f));
115
- return (f.type === "formula" || kind === "formula" || kind === "lookup" || kind === "rollup") && String(f.compute_on ?? "read") === "read";
116
- }
117
- function holdsNumbers(field2) {
118
- const kind = String(editorKindFor(field2));
119
- if (kind === "number" || kind === "currency" || kind === "percent") return true;
120
- return String((field2.config ?? {})["system"] ?? "") === "autonumber";
121
- }
122
- function sortAsFor(field2) {
123
- const kind = String(editorKindFor(field2));
124
- if (holdsNumbers(field2)) return "number";
125
- if (kind === "datetime") return "date";
126
- return "text";
127
- }
128
- function pageSortFor(fields, sort) {
129
- if (!sort) return [];
130
- const field2 = fields.find((f) => f.key === sort.id);
131
- if (!field2) return [];
132
- return [{ field: field2.key, direction: sort.direction === "desc" ? "desc" : "asc", as: sortAsFor(field2) }];
133
- }
134
- function containsPattern(text) {
135
- return `(?i)${text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`;
136
- }
137
- var BLANK_VALUE = "__empty__";
138
- var field = (f) => ({ field: f.id });
139
- var constant = (value) => ({ const: value });
140
- var withinWindow = (f, window) => ({ op: "within", args: [field(f), constant(window)] });
141
- var op = (name, ...args) => ({ op: name, args });
142
- function clauseFor(f, value, now = /* @__PURE__ */ new Date()) {
143
- const name = fieldName(f);
144
- const refused = filterRefusal(f);
145
- if (refused) return refused;
146
- const not = (rule) => op("not", rule);
147
- switch (value.kind) {
148
- case "text": {
149
- const mode = value.mode ?? "contains";
150
- if (mode === "empty" || mode === "null") return value.negated ? { rule: op("present", field(f)) } : { rule: not(op("present", field(f))) };
151
- if (mode === "not_empty" || mode === "not_null") return value.negated ? { rule: not(op("present", field(f))) } : { rule: op("present", field(f)) };
152
- const text = value.value.trim();
153
- if (text === "") return null;
154
- const kind = String(editorKindFor(f));
155
- if (kind === "number" || kind === "currency" || kind === "percent" || kind === "checkbox") {
156
- return `${name} holds numbers, so it is filtered by a range, not by words.`;
157
- }
158
- const matches = op("matches", field(f), constant(containsPattern(text)));
159
- return { rule: value.negated ? not(matches) : matches };
160
- }
161
- case "select": {
162
- const ticked = value.values ?? (value.value === "" ? [] : [value.value]);
163
- const blank = ticked.includes(BLANK_VALUE);
164
- const words = ticked.filter((w) => w !== BLANK_VALUE);
165
- if (!blank && words.length === 0) return value.negated ? null : { rule: constant(false) };
166
- const present = op("present", field(f));
167
- const kind = String(editorKindFor(f));
168
- if (kind === "datetime" || kind === "date") {
169
- if (words.length === 0) return { rule: value.negated ? present : not(present) };
170
- const holdsDays = String((f.config ?? {})["kind"] ?? "") === "date";
171
- if (words.length === 1 && !blank && !value.negated) return { flat: { [f.key]: dayWindow(words[0], holdsDays) } };
172
- const leaves = words.map((day) => withinWindow(f, dayWindow(day, holdsDays)));
173
- const anyDay = leaves.length === 1 ? leaves[0] : op("or", ...leaves);
174
- if (!value.negated) return { rule: blank ? op("or", not(present), anyDay) : anyDay };
175
- return { rule: blank ? op("and", present, not(anyDay)) : not(anyDay) };
176
- }
177
- const asStored = (w) => holdsNumbers(f) || kind === "rating" ? Number.isFinite(Number(w)) ? Number(w) : w : kind === "checkbox" && (w === "true" || w === "false") ? w === "true" : w;
178
- const stored = words.map(asStored);
179
- const anyWord = stored.length === 0 ? null : stored.length === 1 ? op("eq", field(f), constant(stored[0])) : op("or", ...stored.map((w) => op("eq", field(f), constant(w))));
180
- if (!value.negated) {
181
- if (!blank && stored.length === 1) return { flat: { [f.key]: stored[0] } };
182
- if (!blank) return { rule: anyWord };
183
- return { rule: anyWord ? op("or", not(present), anyWord) : not(present) };
184
- }
185
- if (blank) return { rule: anyWord ? op("and", present, not(anyWord)) : present };
186
- return { rule: op("or", not(present), not(anyWord)) };
187
- }
188
- case "boolean":
189
- return value.negated ? { rule: op("ne", field(f), constant(value.value)) } : { flat: { [f.key]: value.value } };
190
- case "number": {
191
- const turned = (rule) => ({ rule: value.negated ? not(rule) : rule });
192
- if (value.op === "empty") return turned(not(op("present", field(f))));
193
- if (value.op === "not_empty") return turned(op("present", field(f)));
194
- if (value.op === "eq" || value.op === "ne") {
195
- if (typeof value.min !== "number") return null;
196
- return turned(op(value.op, field(f), constant(value.min)));
197
- }
198
- if (value.op === "lt") return typeof value.max === "number" ? turned(op("lt", field(f), constant(value.max))) : null;
199
- if (value.op === "gt") return typeof value.min === "number" ? turned(op("gt", field(f), constant(value.min))) : null;
200
- const parts = [];
201
- if (typeof value.min === "number") parts.push(op("gte", field(f), constant(value.min)));
202
- if (typeof value.max === "number") parts.push(op("lte", field(f), constant(value.max)));
203
- if (parts.length === 0) return null;
204
- const range = parts.length === 1 ? parts[0] : op("and", ...parts);
205
- return { rule: value.negated ? not(range) : range };
206
- }
207
- case "date": {
208
- const zone2 = void 0;
209
- const moments = dataTable.dateFilterBounds(value.preset ? { ...value, anchor: now.toISOString() } : value, now, zone2);
210
- const holdsDays = String((f.config ?? {})["kind"] ?? "") === "date";
211
- const bounds = holdsDays ? dataTable.dateFilterDayBounds(moments, zone2) : moments;
212
- if (bounds.since === void 0 && bounds.until === void 0) return null;
213
- return {
214
- flat: {
215
- [f.key]: {
216
- ...bounds.since === void 0 ? {} : { from: bounds.since },
217
- ...bounds.until === void 0 ? {} : { to: bounds.until }
218
- }
219
- }
220
- };
221
- }
222
- default:
223
- return `${name} cannot be filtered that way by the store.`;
224
- }
225
- }
226
- function dayWindow(day, holdsDays) {
227
- if (!holdsDays) return dataTable.dayInstantWindow(day, void 0);
228
- const [y, m, d] = day.split("-").map(Number);
229
- const ymd = (t) => `${t.getUTCFullYear()}-${String(t.getUTCMonth() + 1).padStart(2, "0")}-${String(t.getUTCDate()).padStart(2, "0")}`;
230
- return { from: ymd(new Date(Date.UTC(y, (m ?? 1) - 1, d ?? 1))), to: ymd(new Date(Date.UTC(y, (m ?? 1) - 1, (d ?? 1) + 1))) };
231
- }
232
- function storeQuestion(fields, base, columnFilters, now = /* @__PURE__ */ new Date()) {
233
- const refused = [];
234
- const flat = {};
235
- const rules = [];
236
- if (base && records.isRuleFilter(base)) rules.push(base);
237
- else if (base) Object.assign(flat, base);
238
- for (const [key, value] of Object.entries(columnFilters)) {
239
- if (!value) continue;
240
- const f = fields.find((candidate) => candidate.key === key);
241
- if (!f) continue;
242
- const clause = clauseFor(f, value, now);
243
- if (clause === null) continue;
244
- if (typeof clause === "string") {
245
- refused.push(clause);
246
- continue;
247
- }
248
- if ("flat" in clause) Object.assign(flat, clause.flat);
249
- else rules.push(clause.rule);
250
- }
251
- const flatKeys = Object.keys(flat);
252
- if (rules.length === 0) return { filter: flatKeys.length > 0 ? flat : void 0, refused };
253
- for (const key of flatKeys) {
254
- const f = fields.find((candidate) => candidate.key === key);
255
- const value = flat[key];
256
- if (!f) continue;
257
- if (value !== null && typeof value === "object") {
258
- rules.push(withinWindow(f, value));
259
- continue;
260
- }
261
- rules.push(value === null ? op("not", op("present", field(f))) : op("eq", field(f), constant(value)));
262
- }
263
- return { filter: rules.length === 1 ? rules[0] : op("and", ...rules), refused };
264
- }
265
-
266
- // src/rowVersion.ts
267
- var rowVersion_exports = {};
268
- __reExport(rowVersion_exports, versions_star__namespace);
269
-
270
- // src/groupReads.ts
271
- function isPlainGrouping(grouping) {
272
- return Boolean(grouping) && !(grouping.then && grouping.then.length > 0) && !grouping.across && !(grouping.trail && grouping.trail.length > 0);
273
- }
274
- function groupedPageSort(fields, groupKey, sort) {
275
- if (!groupKey) return sort;
276
- const field2 = fields.find((f) => f.key === groupKey);
277
- if (!field2) return sort;
278
- return [{ field: groupKey, direction: "asc", as: sortAsFor(field2) }, ...sort.filter((s) => s.field !== groupKey)];
279
- }
280
- function chosenEntries(chosen) {
281
- return JSON.parse(JSON.stringify(Object.entries(chosen).sort())).filter(([, op2]) => op2 in MEASURE_LABEL);
282
- }
283
- function groupFactMeasures(chosen) {
284
- return [{ op: "count" }, ...chosenEntries(chosen).filter(([, op2]) => op2 !== "count").map(([key, op2]) => ({ op: op2, key }))];
285
- }
286
- function summaryBarMeasures(chosen) {
287
- return chosenEntries(chosen).map(([key, op2]) => op2 === "count" ? { op: "count" } : { op: op2, key });
288
- }
289
- function choiceFieldKeys(fields) {
290
- return fields.filter((f) => {
291
- const kind = String(editorKindFor(f));
292
- return kind === "select" || kind === "multi_select";
293
- }).map((f) => f.key);
294
- }
295
- var REVERSE_CELL_CHIPS = 3;
30
+ // src/firstPage.ts
296
31
  var MIN_ROW_HEIGHT = 24;
297
32
  var MAX_ROW_HEIGHT = 96;
298
33
  var AGGREGATE_KINDS = [
@@ -391,8 +126,8 @@ function parseGridPresentation(raw) {
391
126
  if (footer === "sticky" || footer === "inline") out.footer = footer;
392
127
  if (isRecord(value["summaries"])) {
393
128
  const summaries = {};
394
- for (const [key, op2] of Object.entries(value["summaries"])) {
395
- if (typeof op2 === "string" && op2.trim() !== "") summaries[key] = op2;
129
+ for (const [key, op] of Object.entries(value["summaries"])) {
130
+ if (typeof op === "string" && op.trim() !== "") summaries[key] = op;
396
131
  }
397
132
  if (Object.keys(summaries).length > 0) out.summaries = summaries;
398
133
  }
@@ -400,9 +135,9 @@ function parseGridPresentation(raw) {
400
135
  }
401
136
  function parseGrouping(raw) {
402
137
  if (!isRecord(raw)) return void 0;
403
- const field2 = raw["field"];
404
- if (typeof field2 !== "string" || field2.trim() === "") return void 0;
405
- const out = { field: field2 };
138
+ const field = raw["field"];
139
+ if (typeof field !== "string" || field.trim() === "") return void 0;
140
+ const out = { field };
406
141
  if (isRecord(raw["aggregates"])) {
407
142
  const aggregates = {};
408
143
  for (const [key, spec] of Object.entries(raw["aggregates"])) {
@@ -460,338 +195,60 @@ function parseGrouping(raw) {
460
195
  }
461
196
  return out;
462
197
  }
463
- var STORE_KEPT_LAYOUTS = ["grid", "kanban", "calendar", "gallery", ...["timeline"] , "list"];
464
- var KINDS = STORE_KEPT_LAYOUTS;
465
- function viewSettings(definition, rowFilters) {
466
- const data = definition ?? {};
467
- const text = (key) => {
468
- const v = data[key];
469
- return typeof v === "string" && v !== "" ? v : null;
470
- };
471
- const layout = String(data["layout"] ?? "grid");
472
- const flat = rowFilters ?? (isObject(data["filters"]) ? data["filters"] : null);
473
- const moved = data["moved_from"];
474
- return {
475
- layout: KINDS.includes(layout) ? layout : "grid",
476
- filters: flat && Object.keys(flat).length > 0 ? flat : null,
477
- where: isRule(data["where"]) ? data["where"] : null,
478
- groupField: text("group_field"),
479
- swimlaneField: text("swimlane_field"),
480
- collapsedColumns: Array.isArray(data["collapsed_columns"]) ? data["collapsed_columns"].filter((v) => ["string", "number", "boolean"].includes(typeof v)).map(String) : [],
481
- measure: text("measure"),
482
- dateField: text("date_field"),
483
- startField: text("start_field"),
484
- endField: text("end_field"),
485
- imageField: text("image_field"),
486
- sorts: parseSorts(data["sorts"]),
487
- ruleId: text("rule_id"),
488
- isDefault: data["is_default"] === true || data["is_default"] === "true",
489
- presentation: parseGridPresentation(data["presentation"]),
490
- movedFrom: isObject(moved) ? moved : null
491
- };
492
- }
493
- function isObject(raw) {
494
- return Boolean(raw) && typeof raw === "object" && !Array.isArray(raw);
495
- }
496
- function isRule(raw) {
497
- if (!isObject(raw)) return false;
498
- const node = raw;
499
- return typeof node.op === "string" && Array.isArray(node.args);
500
- }
501
- function parseSorts(raw) {
502
- let list = raw;
503
- if (typeof raw === "string") {
504
- try {
505
- list = raw.trim() === "" ? [] : JSON.parse(raw);
506
- } catch {
507
- return [];
508
- }
509
- }
510
- if (!Array.isArray(list)) return [];
511
- return list.filter((s) => isObject(s) && typeof s.field === "string").map((s) => ({ field: s.field, direction: s.direction === "desc" ? "desc" : "asc" }));
512
- }
513
-
514
- // src/views.ts
515
- var VIEW_LAYOUTS = ["grid", "kanban", "calendar", "gallery", "timeline", "list"];
516
- function viewOrderOf(definition) {
517
- const raw = definition?.["order"];
518
- return raw === "manual" ? "manual" : raw === "sorted" ? "sorted" : null;
519
- }
520
- function defaultViewOf(views) {
521
- return views.find((v) => v.isDefault);
522
- }
523
- function viewFromRow(row) {
524
- const data = row.definition ?? {};
525
- const k = viewSettings(data, row.filters && Object.keys(row.filters).length > 0 ? row.filters : null);
526
- const tableFromDefinition = typeof data["table_id"] === "string" && data["table_id"] !== "" ? data["table_id"] : null;
527
- return {
528
- id: row.view_id,
529
- name: row.name || "Untitled view",
530
- subject: row.table_id ?? tableFromDefinition ?? "",
531
- layout: k.layout,
532
- groupField: k.groupField,
533
- swimlaneField: k.swimlaneField,
534
- collapsedColumns: k.collapsedColumns,
535
- measure: k.measure,
536
- dateField: k.dateField,
537
- startField: k.startField,
538
- endField: k.endField,
539
- imageField: k.imageField,
540
- sorts: k.sorts,
541
- order: viewOrderOf(data),
542
- ruleId: k.ruleId,
543
- ...k.filters ? { filters: k.filters } : {},
544
- where: k.where,
545
- // The older table's own default view, carried in by the mover, IS this table's default —
546
- // the mover wrote the row's column, which `custom.views` does not return. Read as anything
547
- // else, the page would seed a second "All records" beside it and open on that.
548
- isDefault: k.isDefault || k.movedFrom?.["kind"] === "default_view",
549
- presentation: k.presentation,
550
- movedFrom: k.movedFrom
551
- };
552
- }
553
-
554
- // src/viewLook.ts
555
- function lookFromDocument(doc) {
556
- const data = doc ?? {};
557
- const read = viewSettings(data);
558
- const out = {};
559
- const has = (key) => Object.prototype.hasOwnProperty.call(data, key);
560
- if (has("layout") && VIEW_LAYOUTS.includes(String(data["layout"]))) {
561
- out.layout = data["layout"];
562
- }
563
- if (has("group_field")) out.groupField = read.groupField;
564
- if (has("swimlane_field")) out.swimlaneField = read.swimlaneField;
565
- if (has("collapsed_columns")) out.collapsedColumns = read.collapsedColumns;
566
- if (has("measure")) out.measure = read.measure;
567
- if (has("date_field")) out.dateField = read.dateField;
568
- if (has("start_field")) out.startField = read.startField;
569
- if (has("end_field")) out.endField = read.endField;
570
- if (has("image_field")) out.imageField = read.imageField;
571
- if (has("sorts")) out.sorts = read.sorts;
572
- if (has("where")) out.where = read.where;
573
- if (has("presentation")) out.presentation = parseGridPresentation(data["presentation"]);
574
- return out;
575
- }
576
- function applyLook(view, look) {
577
- if (!look) return view;
578
- return { ...view, ...look };
198
+ function presentationIsEmpty(p) {
199
+ return (p.style === void 0 || tableStyle.tableStyleIsEmpty(p.style)) && Object.keys(p.formats ?? {}).length === 0 && (p.frozen?.length ?? 0) === 0 && p.grouping === void 0 && Object.keys(p.widths ?? {}).length === 0 && p.rowHeight === void 0 && (p.hiddenFields?.length ?? 0) === 0 && p.cardHidden === void 0 && (p.columnOrder?.length ?? 0) === 0 && p.gallerySize === void 0 && p.wrap === void 0 && p.fit === void 0 && p.freezeFirst === void 0 && p.footer === void 0 && Object.keys(p.summaries ?? {}).length === 0;
579
200
  }
580
- async function readLooks(client, tableId) {
581
- const answered = await client.viewLookRead({ table_id: tableId });
582
- if (!answered.ok) return answered;
583
- const out = {};
584
- for (const [viewId, row] of Object.entries(answered.data ?? {})) {
585
- out[viewId] = lookFromDocument(row?.look ?? null);
586
- }
587
- return { ok: true, data: out };
588
- }
589
-
590
- // src/entityQuery.ts
591
- function entityTableQuery(options = {}) {
592
- const search = (options.search ?? "").trim();
593
- return { ...options.pageSize ? { pageSize: options.pageSize } : {}, ...search ? { search } : {} };
594
- }
595
- function entityChartQuestion(input) {
596
- const m = input.measure ?? { op: "count" };
597
- return {
598
- ...input.by ? { by: [input.by] } : {},
599
- show: [m.op === "count" ? "count" : { op: m.op, of: m.of }],
600
- ...input.where ? { where: input.where } : {},
601
- ...input.organization ? { organization: input.organization } : {}
602
- };
603
- }
604
-
605
- // src/firstPageEntity.ts
606
- function recordedClient(input) {
607
- const recording = core.recordingDataSource(core.asRecordsDataSource(input.dataSource));
608
- const client = core.createRecordsClient({ dataSource: recording.source, organizationId: input.organizationId, actor: input.actor, onError: () => {
609
- } });
610
- return { recording, client };
611
- }
612
- function mergeSeeds(...seeds) {
613
- const held = seeds.filter((s) => Boolean(s));
614
- const answers = /* @__PURE__ */ new Map();
615
- for (const seed of held) for (const a of seed.answers) answers.set(`${a.door}|${JSON.stringify(a.args)}`, a);
616
- return { at: held.length ? Math.min(...held.map((s) => s.at)) : Date.now(), answers: [...answers.values()] };
617
- }
618
- async function askEntityBlockSeed(input) {
619
- const recording = core.recordingDataSource(core.asRecordsDataSource(input.dataSource));
620
- const port = entity.createSeedPort(recording.source);
621
- try {
622
- await Promise.all([port.describe(input.token), port.list(input.token, entityTableQuery(input.question ?? {}))]);
623
- } catch {
624
- }
625
- return recording.seed();
626
- }
627
- async function askChartSeed(input) {
628
- const { recording, client } = recordedClient(input);
629
- try {
630
- await client.drillAsk({ source: input.source, question: entityChartQuestion(input.question ?? {}) });
631
- } catch {
632
- }
633
- return recording.seed();
634
- }
635
- async function askTileSeed(input) {
636
- const { recording, client } = recordedClient(input);
637
- const specs = Array.isArray(input.spec) ? input.spec : [input.spec];
638
- await Promise.all(specs.map((spec) => client.recordAggregate({ table_id: input.tableId, ...spec }).catch(() => null)));
639
- return recording.seed();
201
+ function presentationDocument(p) {
202
+ return presentationIsEmpty(p) ? "" : JSON.stringify(p);
640
203
  }
204
+ var gridPresentationCodec = {
205
+ parse: parseGridPresentation,
206
+ isEmpty: presentationIsEmpty,
207
+ toDocument: (presentation) => JSON.parse(presentationDocument(presentation))
208
+ };
209
+ var boundViews = base__namespace.bindViewCodec(gridPresentationCodec);
210
+ var { viewSettings, viewSettingsPatch } = boundViews;
641
211
 
642
212
  // src/firstPage.ts
643
- var TABLE_PAGE_SIZE = 100;
644
- var EMBEDDED_PAGE_SIZE = 50;
645
- function viewFilterOf(shown, fields) {
646
- if (!shown) return void 0;
647
- const base = shown.where ?? (shown.filters && Object.keys(shown.filters).length > 0 ? shown.filters : void 0);
648
- return storeQuestion(fields, base, {}).filter;
649
- }
650
- function firstGridPageArgs(input) {
651
- const { shown, fields } = input;
652
- if (!shown) return null;
653
- if ((shown.layout ?? "grid") !== "grid") return null;
654
- if (shown.ruleId) return null;
655
- if (shown.order === "manual") return null;
656
- const grouping = shown.presentation?.grouping;
657
- if (grouping && !(input.merged && isPlainGrouping(grouping))) return null;
658
- const first = (shown.sorts ?? [])[0];
659
- const viewSort = first && fields.some((f) => f.key === first.field) ? { id: first.field, direction: first.direction } : null;
660
- const opening = viewSort ?? defaultSortOf(input.table, fields);
661
- return {
662
- p_table_id: input.tableId,
663
- p_filter: viewFilterOf(shown, fields) ?? {},
664
- p_search: null,
665
- p_sort: groupedPageSort(fields, grouping?.field ?? null, pageSortFor(fields, opening)),
666
- p_view_id: null,
667
- p_limit: input.pageSize ?? TABLE_PAGE_SIZE,
668
- p_offset: 0
669
- };
670
- }
671
- async function firstGridPageRequest(client, tableId, options = {}) {
672
- return (await firstGridOpening(client, tableId, options))?.args ?? null;
673
- }
674
- function defaultSpec(tableId) {
675
- return { name: "All", subject: tableId, layout: "grid", isDefault: true };
676
- }
677
- function shownFromSpec(spec, tableId) {
678
- return { ...spec, subject: spec.subject ?? tableId, id: "", movedFrom: null };
679
- }
680
- async function firstGridOpening(client, tableId, options) {
681
- const explicit = options.view;
682
- const [table, fields, views, looks] = await Promise.all([
683
- client.tableRead({ table_id: tableId }),
684
- client.fields({ table_id: tableId }),
685
- explicit ? Promise.resolve(null) : client.views({ table_id: tableId }),
686
- explicit ? Promise.resolve(null) : readLooks(client, tableId)
687
- ]);
688
- if (!table.ok || !fields.ok) return null;
689
- let shown;
690
- if (explicit) {
691
- shown = shownFromSpec(explicit, tableId);
692
- } else {
693
- if (!views?.ok || !looks?.ok) return null;
694
- const mine = views.data.map(viewFromRow).filter((v) => v.subject === tableId);
695
- const view = defaultViewOf(mine) ?? mine[0] ?? null;
696
- shown = view ? applyLook(view, looks.data[view.id]) : shownFromSpec(defaultSpec(tableId), tableId);
697
- }
698
- const args = firstGridPageArgs({
699
- tableId,
700
- table: table.data,
701
- fields: fields.data,
702
- shown,
703
- ...options.pageSize ? { pageSize: options.pageSize } : {},
704
- ...options.merged ? { merged: true } : {}
705
- });
706
- return args ? { args, shown, fields: fields.data } : null;
707
- }
708
- function serverRowsOf(seed) {
709
- const found = seed?.answers.find((a) => a.door === "server_rows");
710
- const data = found?.data;
711
- if (!data || typeof data !== "object") return null;
712
- return { on: data.on === true, capMs: typeof data.cap_ms === "number" && data.cap_ms > 0 ? data.cap_ms : null };
713
- }
714
- async function askTablePageSeed(input) {
715
- const recording = core.recordingDataSource(core.asRecordsDataSource(input.dataSource));
716
- const client = core.createRecordsClient({
717
- dataSource: recording.source,
718
- organizationId: input.organizationId,
719
- actor: input.actor,
720
- onError: () => {
721
- }
722
- });
723
- const record = input.recordId ? Promise.resolve(
724
- recording.source.rpc("record_page_bundle", { p_organization_id: input.organizationId, p_record_id: input.recordId }, { schema: "custom" })
725
- ).catch(() => null) : null;
726
- try {
727
- const pageSize = input.pageSize ?? (input.embedded ? EMBEDDED_PAGE_SIZE : TABLE_PAGE_SIZE);
728
- const opening = await firstGridOpening(client, input.tableId, { pageSize, ...input.merged ? { merged: true } : {}, ...input.view ? { view: input.view } : {} });
729
- const wantRows = typeof input.rows === "function" ? input.rows(recording.seed()) : input.rows !== false;
730
- if (opening && wantRows) {
731
- const { args, shown, fields } = opening;
732
- const page = await client.listPage({
733
- table_id: args.p_table_id,
734
- filter: args.p_filter,
735
- search: args.p_search,
736
- sort: args.p_sort,
737
- view_id: args.p_view_id,
738
- limit: args.p_limit,
739
- offset: args.p_offset
740
- });
741
- if (page.ok) {
742
- const chosen = shown?.presentation?.summaries ?? {};
743
- const groupKey = shown?.presentation?.grouping?.field ?? null;
744
- const reads = [];
745
- const filter = args.p_filter && Object.keys(args.p_filter).length > 0 ? args.p_filter : void 0;
746
- if (groupKey) {
747
- reads.push(client.recordAggregate({ table_id: input.tableId, groupBy: [groupKey], measures: groupFactMeasures(chosen), limit: 1e3, ...filter ? { filter } : {} }));
748
- }
749
- const bar = summaryBarMeasures(chosen);
750
- if (bar.length > 0) reads.push(client.recordAggregate({ table_id: input.tableId, measures: bar, ...filter ? { filter } : {} }));
751
- for (const field2 of fields) {
752
- if (field2.type !== "list" && field2.type !== "relation") continue;
753
- const ids = /* @__PURE__ */ new Set();
754
- for (const row of page.data.rows) {
755
- const value = row.document?.[field2.key];
756
- for (const id of Array.isArray(value) ? value.map(String) : typeof value === "string" ? [value] : []) if (uuid.isUuidShape(id)) ids.add(id);
757
- }
758
- if (ids.size > 0) reads.push(client.relationWordsMany({ field_id: field2.id, record_ids: [...ids] }));
759
- }
760
- if (input.merged) {
761
- for (const key of choiceFieldKeys(fields)) {
762
- reads.push(client.recordAggregate({ table_id: input.tableId, groupBy: [key], measures: [{ op: "count" }], limit: 500, ...filter ? { filter } : {} }));
763
- }
764
- }
765
- const unversioned = page.data.rows.filter((row) => (0, rowVersion_exports.ownVersion)(row) === null).map((row) => row.id);
766
- if (unversioned.length > 0) reads.push(client.recordHeaders({ ids: unversioned }));
767
- reads.push(
768
- client.reverseColumns({ table_id: input.tableId }).then(async (columns) => {
769
- if (!columns.ok || columns.data.length === 0) return null;
770
- const record_ids = page.data.rows.map((row) => row.id);
771
- const all = await client.reverseLinksFields({ table_id: input.tableId, source_field_ids: columns.data.map((c) => c.source_field_id), record_ids, limit: REVERSE_CELL_CHIPS });
772
- if (all.ok || all.error.code !== "door_absent") return null;
773
- return Promise.all(columns.data.map((c) => client.reverseLinksMany({ table_id: input.tableId, source_field_id: c.source_field_id, record_ids, limit: REVERSE_CELL_CHIPS })));
774
- })
775
- );
776
- await Promise.all(reads.map((read) => read.catch(() => null)));
777
- }
778
- }
779
- } catch {
780
- }
781
- if (record) await record;
782
- return recording.seed();
783
- }
213
+ var { firstGridPageRequest, askTablePageSeed } = firstPage.bindFirstPageCodec(gridPresentationCodec);
784
214
 
785
- exports.EMBEDDED_PAGE_SIZE = EMBEDDED_PAGE_SIZE;
786
- exports.TABLE_PAGE_SIZE = TABLE_PAGE_SIZE;
787
- exports.askChartSeed = askChartSeed;
788
- exports.askEntityBlockSeed = askEntityBlockSeed;
215
+ Object.defineProperty(exports, "EMBEDDED_PAGE_SIZE", {
216
+ enumerable: true,
217
+ get: function () { return firstPage.EMBEDDED_PAGE_SIZE; }
218
+ });
219
+ Object.defineProperty(exports, "TABLE_PAGE_SIZE", {
220
+ enumerable: true,
221
+ get: function () { return firstPage.TABLE_PAGE_SIZE; }
222
+ });
223
+ Object.defineProperty(exports, "askChartSeed", {
224
+ enumerable: true,
225
+ get: function () { return firstPage.askChartSeed; }
226
+ });
227
+ Object.defineProperty(exports, "askEntityBlockSeed", {
228
+ enumerable: true,
229
+ get: function () { return firstPage.askEntityBlockSeed; }
230
+ });
231
+ Object.defineProperty(exports, "askTileSeed", {
232
+ enumerable: true,
233
+ get: function () { return firstPage.askTileSeed; }
234
+ });
235
+ Object.defineProperty(exports, "firstGridPageArgs", {
236
+ enumerable: true,
237
+ get: function () { return firstPage.firstGridPageArgs; }
238
+ });
239
+ Object.defineProperty(exports, "mergeSeeds", {
240
+ enumerable: true,
241
+ get: function () { return firstPage.mergeSeeds; }
242
+ });
243
+ Object.defineProperty(exports, "serverRowsOf", {
244
+ enumerable: true,
245
+ get: function () { return firstPage.serverRowsOf; }
246
+ });
247
+ Object.defineProperty(exports, "viewFilterOf", {
248
+ enumerable: true,
249
+ get: function () { return firstPage.viewFilterOf; }
250
+ });
789
251
  exports.askTablePageSeed = askTablePageSeed;
790
- exports.askTileSeed = askTileSeed;
791
- exports.firstGridPageArgs = firstGridPageArgs;
792
252
  exports.firstGridPageRequest = firstGridPageRequest;
793
- exports.mergeSeeds = mergeSeeds;
794
- exports.serverRowsOf = serverRowsOf;
795
- exports.viewFilterOf = viewFilterOf;
796
253
  //# sourceMappingURL=first-page.cjs.map
797
254
  //# sourceMappingURL=first-page.cjs.map