@ai-matrx/records-ui 0.115.107 → 0.115.108

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.
@@ -0,0 +1,1681 @@
1
+ "use client";
2
+ import {
3
+ NOT_ANSWERED_YET,
4
+ fieldTypeChoice,
5
+ isSystemFieldKind,
6
+ whatYouMayDo,
7
+ whatYouMayDoWithTable
8
+ } from "./chunk-6NSGVKYL.js";
9
+ import {
10
+ __reExport
11
+ } from "./chunk-HKYEHBQT.js";
12
+
13
+ // src/tableRights.ts
14
+ function tableRights(may, overallReason) {
15
+ return {
16
+ ...may,
17
+ admin: may.structure,
18
+ reason: overallReason ?? (may.structure ? "" : may.why("structure"))
19
+ };
20
+ }
21
+ var NO_RIGHTS = tableRights(NOT_ANSWERED_YET);
22
+ function tableRightsAt(level) {
23
+ return tableRights(whatYouMayDo(level, true));
24
+ }
25
+
26
+ // src/host.tsx
27
+ import { createContext, useContext, useMemo } from "react";
28
+ import { useMyLevel, useMyLevels } from "@ai-matrx/records/react";
29
+ import { jsx } from "react/jsx-runtime";
30
+ var NO_SAVED_VIEWS_REASON = "There are no saved views here yet, so there is nothing to be told about. Save a view of this table first and it will be offered here.";
31
+ var NO_MEMBERS_REASON = "This app cannot offer the people in your organization on this screen yet, so there is nobody to pick. Type the person's name into a text field for now, and tell us \u2014 it is on our list, not yours.";
32
+ var NO_SHARE_REASON = "Sharing is not available on this screen, so there is no Share button here rather than one that opens nothing. Share this table from the tables list instead.";
33
+ var NO_OPEN_RECORDS_REASON = "These numbers do not click through yet. Every one of them is a count of real records \u2014 open the records view and group it by the same field to see them. It is on our list, not yours.";
34
+ var NO_REASK_REASON = "Changing this dashboard by describing it is not switched on here yet, so this box is off rather than one that goes nowhere. Add and remove the blocks by hand above. It is on our list, not yours.";
35
+ var NO_UPLOAD_REASON = "This screen cannot take a file yet, so there is no chooser here rather than one that loses what you pick. Put a link to the file in a text field for now. It is on our list, not yours.";
36
+ var HostContext = createContext(null);
37
+ function RecordsUiProvider({ value, children }) {
38
+ const bound = useMemo(() => value, [value]);
39
+ return /* @__PURE__ */ jsx(HostContext.Provider, { value: bound, children });
40
+ }
41
+ function useRecordsUi() {
42
+ return useContext(HostContext) ?? {};
43
+ }
44
+ function quiet(may, say) {
45
+ if (say !== false) return may;
46
+ return { ...may, why: () => "", ..."reason" in may ? { reason: "" } : {} };
47
+ }
48
+ function useTableRights(table) {
49
+ const host = useRecordsUi();
50
+ const asked2 = useTableRightsAsked(table, host);
51
+ return useMemo(() => quiet(asked2, host.sayLevelNeeded), [asked2, host.sayLevelNeeded]);
52
+ }
53
+ function useTableRightsAsked(table, host) {
54
+ const bound = Boolean(host.rights);
55
+ const asked2 = useMyLevel(bound || !table ? null : table.id);
56
+ return useMemo(() => {
57
+ if (!table) return NO_RIGHTS;
58
+ if (host.rights) return host.rights(table);
59
+ if (asked2.loading) return tableRights(NOT_ANSWERED_YET);
60
+ const level = asked2.error ? null : asked2.data;
61
+ return tableRights(whatYouMayDoWithTable(table, level, true));
62
+ }, [host, table, bound, asked2.loading, asked2.error, asked2.data]);
63
+ }
64
+ function useRecordRights(recordId) {
65
+ const asked2 = useMyLevel(recordId);
66
+ const say = useRecordsUi().sayLevelNeeded;
67
+ return useMemo(() => {
68
+ if (!recordId) return NOT_ANSWERED_YET;
69
+ if (asked2.loading) return NOT_ANSWERED_YET;
70
+ if (asked2.error) return quiet(whatYouMayDo(null, true), say);
71
+ return quiet(whatYouMayDo(asked2.data, true), say);
72
+ }, [recordId, asked2.loading, asked2.error, asked2.data, say]);
73
+ }
74
+ function useRowRights(rowIds, enabled) {
75
+ const asked2 = useMyLevels(enabled ? rowIds : []);
76
+ const say = useRecordsUi().sayLevelNeeded;
77
+ return useMemo(() => {
78
+ if (!enabled) return () => null;
79
+ if (asked2.loading) return () => NOT_ANSWERED_YET;
80
+ if (asked2.error) return () => quiet(whatYouMayDo(null, true), say);
81
+ const held = asked2.data ?? {};
82
+ return (rowId) => quiet(whatYouMayDo(held[rowId] ?? null, true), say);
83
+ }, [enabled, asked2.loading, asked2.error, asked2.data, say]);
84
+ }
85
+
86
+ // src/names.ts
87
+ import { isUuidShape } from "@ai-matrx/kit/uuid";
88
+ import { humanizeIdentifier } from "@ai-matrx/kit/text-case";
89
+ function fieldName(field) {
90
+ const label = (field.label ?? "").trim();
91
+ if (label !== "" && label === field.key && /^[a-z0-9]+(?:[_.-][a-z0-9]+)+$/.test(label)) return humanizeIdentifier(label);
92
+ if (label !== "") return label;
93
+ const name = (field.name ?? "").trim();
94
+ if (name !== "") return name;
95
+ return humanizeIdentifier(field.key);
96
+ }
97
+ function tableName(table) {
98
+ const name = (table.name ?? "").trim();
99
+ if (name !== "") return name;
100
+ const singular = (table.label_singular ?? "").trim();
101
+ if (singular !== "") return singular;
102
+ return humanizeIdentifier(table.slug ?? "");
103
+ }
104
+ function recordName(document, titleKey, fallback = "Untitled") {
105
+ const data = document ?? {};
106
+ const keys = [titleKey, "title", "name", "label", "full_name", "subject", "summary"].filter(
107
+ (key) => typeof key === "string" && key !== ""
108
+ );
109
+ for (const key of keys) {
110
+ const value = data[key];
111
+ if (typeof value === "string" && value.trim() !== "" && !looksLikeId(value.trim())) {
112
+ return value.trim();
113
+ }
114
+ if (typeof value === "number") return String(value);
115
+ }
116
+ return fallback;
117
+ }
118
+ function looksLikeId(value) {
119
+ return typeof value === "string" && isUuidShape(value.trim());
120
+ }
121
+ function rowName(row, titleKey, fallback = "Untitled") {
122
+ return recordName(row?.document, titleKey, fallback);
123
+ }
124
+ function recordNameIn(table, document, fallback = "Untitled") {
125
+ return recordName(document, table?.title_field ?? null, fallback);
126
+ }
127
+ function changedRecordName(table, document, key, after) {
128
+ const now = recordName({ ...document ?? {}, [key]: after }, table?.title_field ?? null, "");
129
+ return now !== "" ? now : recordNameIn(table, document);
130
+ }
131
+ function rowNameIn(table, row, fallback = "Untitled") {
132
+ return recordName(row?.document, table?.title_field ?? null, fallback);
133
+ }
134
+ var WITHHELD_RECORD_LABEL = "A record you have not been given access to";
135
+ var UNREAD_RECORD_LABEL = "Couldn't load this name";
136
+ function realPlural(table) {
137
+ const plural = (table.label_plural ?? "").trim();
138
+ if (plural === "") return null;
139
+ for (const base of [table.name, table.label_singular]) {
140
+ const b = (base ?? "").trim();
141
+ if (b !== "" && plural === `${b}s`) return null;
142
+ }
143
+ return plural;
144
+ }
145
+ function singularNoun(table, fallback = "record") {
146
+ const word = (table?.label_singular ?? "").trim() || (table?.name ?? "").trim() || fallback;
147
+ return word.split(/\s+/).map((w) => /^[A-Z][a-z'’-]*$/.test(w) ? w.toLowerCase() : w).join(" ");
148
+ }
149
+ function pluralNoun(table, fallback = "record") {
150
+ const real = table ? realPlural(table) : null;
151
+ if (real) return real;
152
+ const singular = (table?.label_singular ?? "").trim() || fallback;
153
+ return /s$/i.test(singular) ? singular : `${singular}s`;
154
+ }
155
+ var CONVENTIONAL_TITLE_KEYS = ["title", "name", "label", "full_name", "subject", "summary"];
156
+ function canTitle(field, excluded) {
157
+ if (excluded.has(field.key)) return false;
158
+ if (field.type === "boolean") return false;
159
+ if (field.type === "formula" && (field.config ?? {})["system"]) return false;
160
+ return true;
161
+ }
162
+ function cardTitleField(fields, titleKey, exclude = []) {
163
+ const excluded = new Set(exclude.filter((k) => typeof k === "string" && k !== ""));
164
+ const ordered = [...fields].sort((a, b) => (a.sort ?? 100) - (b.sort ?? 100) || a.key.localeCompare(b.key));
165
+ const byKey = (key) => ordered.find((f) => f.key === key && canTitle(f, excluded));
166
+ if (titleKey) {
167
+ const declared = byKey(titleKey);
168
+ if (declared) return declared;
169
+ }
170
+ for (const key of CONVENTIONAL_TITLE_KEYS) {
171
+ const found = byKey(key);
172
+ if (found) return found;
173
+ }
174
+ return ordered.find((f) => f.type === "text" && canTitle(f, excluded)) ?? ordered.find((f) => canTitle(f, excluded));
175
+ }
176
+
177
+ // src/plainWords.ts
178
+ var MACHINE_IDENTITY = [
179
+ /\b[A-Z]{2,4}-\d{1,3}\b/,
180
+ // A build lane's tag: capital words joined by hyphens, then a colon ("STORE-TAILS-3:",
181
+ // "MOVE-AND-OUTSIDER:"). A person never reads which lane wrote a sentence.
182
+ /\b[A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+:/,
183
+ /\b(?:custom|platform|iam|history|public|auth|campaign_watch)\.[a-z_]+/,
184
+ /\b(?:config|data|document|spec|patch)\.[a-z_]+/,
185
+ /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i,
186
+ /\b[a-z][a-z0-9]*(?:_[a-z0-9]+)+\b/,
187
+ // Five characters of digits and capitals, at least one a digit — so `23514`
188
+ // and `PT409` match and an emphatic `NEVER` does not.
189
+ /\b(?=[0-9A-Z]{5}\b)(?=[0-9A-Z]*\d)[0-9A-Z]{5}\b/
190
+ ];
191
+ function isMachineIdentity(text) {
192
+ return MACHINE_IDENTITY.some((shape) => shape.test(text));
193
+ }
194
+ function machineIdentityIn(text) {
195
+ const found = [];
196
+ for (const shape of MACHINE_IDENTITY) {
197
+ const all = new RegExp(shape.source, shape.flags.includes("g") ? shape.flags : `${shape.flags}g`);
198
+ for (const hit of text.matchAll(all)) if (hit[0]) found.push(hit[0]);
199
+ }
200
+ return [...new Set(found)];
201
+ }
202
+ var TITLE = {
203
+ stale_write: "Someone else wrote first",
204
+ door: "You do not have access to this",
205
+ door_absent: "That is not built yet",
206
+ refused_by_rule: "That value was not accepted",
207
+ invalid_argument: "That was not accepted",
208
+ not_found: "Not there any more",
209
+ missing_reference: "That points at something that is not there",
210
+ already_exists: "That already exists",
211
+ not_supported: "That cannot be done here",
212
+ store_limit: "This has got as big as it can",
213
+ // 🚨 NOT "THE SWITCH IS OFF" (lane 7 W1 fix round 1). PGRST202 / PGRST205 land here, and the
214
+ // commonest cause is a door this screen asks for that the database it talks to does not serve
215
+ // YET — a release in flight. Telling the person her organization has its store switched off was
216
+ // false (the switch is answered by its own door, `platform.unified_data_store_on`). Honest:
217
+ // nothing happened, and it is ours, and it passes.
218
+ store_not_served: "This isn't available right now",
219
+ unreachable: "We could not reach your data",
220
+ needs_approval: "This is waiting on someone's approval",
221
+ stale_read: "Your view of this is a moment behind",
222
+ timed_out: "That took too long to answer",
223
+ internal: "Something went wrong at our end"
224
+ };
225
+ var REMEDY = {
226
+ stale_write: "Look at what they wrote. Keep theirs, or try again and yours goes on top.",
227
+ door: "Ask somebody who administers this to share it with you at the level you need.",
228
+ door_absent: "There is nothing to do here yet. It is on our list, not yours.",
229
+ refused_by_rule: "Change the value so it passes, then try again.",
230
+ invalid_argument: "Change what you entered, then try again.",
231
+ not_found: "It may have been deleted. Go back to the list and open it again from there.",
232
+ missing_reference: "Pick something that is still there.",
233
+ already_exists: "Use a different name.",
234
+ not_supported: "There is another way to do this \u2014 ask, and we will point you at it.",
235
+ store_limit: "Split it up, or ask us to raise the ceiling for your organization.",
236
+ store_not_served: "Nothing was changed. Try again in a few minutes.",
237
+ // 🚨 NOTHING WAS WRITTEN AND NOTHING WAS REFUSED (lane TAILS-6). The call
238
+ // never arrived, so "try again" is the honest instruction rather than a
239
+ // consolation — and saying nothing changed is the half a person actually
240
+ // worries about.
241
+ unreachable: "Nothing was changed. Check your connection and open this again.",
242
+ needs_approval: "Nothing was changed yet. The people who can approve it have been asked.",
243
+ stale_read: "Open this again in a moment and it will be up to date.",
244
+ // 🚨 ONE REMEDY THAT IS TRUE OF EVERY DOOR (lane CHAIR-STORE-PERF, 2026-10-03). The store cancels the
245
+ // WHOLE statement at its clock, so a timed-out door wrote nothing — a create, a column add and a page
246
+ // read alike. "Try a smaller page" was written for the page read and was printed to a person adding
247
+ // one row to a three-row table (clone walk, 2026-10-03; the clock was a lock another lane's
248
+ // rehearsal held, not the row). A door whose page can shrink says so in its own hint, which wins here.
249
+ timed_out: "Nothing was changed. Try again in a moment.",
250
+ internal: "Nothing you did caused this. Try again, and tell us if it keeps happening."
251
+ };
252
+ var ENGINEER_TEXT = [
253
+ /@ai-matrx\//,
254
+ /\bSQLSTATE\b/i,
255
+ /\bPostgREST\b/i,
256
+ /\bIndexedDB\b/i,
257
+ // `<RecordsUiProvider>` — a component, on a screen.
258
+ /<\/?[A-Z][A-Za-z0-9]*\s*\/?>/,
259
+ // `savedViews`, `openRecords`, `onReask` — an identifier, however it is
260
+ // quoted. English does not write camelCase; code does.
261
+ /\b[a-z][a-z0-9]*[A-Z][A-Za-z0-9]*\b/,
262
+ // A backticked token is a thing you type into an editor, not a thing you do.
263
+ /`[A-Za-z_][A-Za-z0-9_.]*`/,
264
+ // "bind X on Y", "pass X", "import X" — an instruction to whoever maintains
265
+ // the app, arriving on the screen of somebody who cannot act on it.
266
+ /\bbind\s+[`'"A-Za-z]/i
267
+ ];
268
+ function isDeveloperHint(hint) {
269
+ const text = hint.trim();
270
+ if (text === "") return false;
271
+ if (text.includes("```")) return true;
272
+ if (/\n\s+at\s+\S+/.test(text)) return true;
273
+ if (text.length > 600) return true;
274
+ return isEngineerText(text);
275
+ }
276
+ function peopleHint(hint) {
277
+ const said = (hint ?? "").trim();
278
+ if (said === "" || isDeveloperHint(said)) return null;
279
+ return plainSentence(said).kept;
280
+ }
281
+ function isEngineerText(text) {
282
+ return ENGINEER_TEXT.some((shape) => shape.test(text));
283
+ }
284
+ function withoutMachineClauses(sentence) {
285
+ const dropped = [];
286
+ const footnotes = [];
287
+ const withoutFootnotes = sentence.replace(/\s*\((?:see\s+)?[A-Z]{2,5}-[A-Z0-9-]{1,8}\)/g, (hit) => {
288
+ footnotes.push(hit.trim());
289
+ return "";
290
+ });
291
+ dropped.push(...footnotes);
292
+ const clauses = withoutFootnotes.split(/(?:,\s+so\s+|\s+—\s+|\s+--\s+|\s*\|\s*)/).map((clause) => clause.trim()).filter((clause) => clause !== "");
293
+ const kept = clauses.filter((clause) => {
294
+ if (!isMachineIdentity(clause)) return true;
295
+ dropped.push(clause);
296
+ return false;
297
+ });
298
+ if (kept.length === 0) return { kept: null, dropped };
299
+ if (dropped.length === 0) return { kept: sentence.trim(), dropped };
300
+ let joined = kept.join(". ").replace(/\.\.+/g, ".").trim();
301
+ if (!/[.!?]$/.test(joined)) joined = `${joined}.`;
302
+ return { kept: joined, dropped };
303
+ }
304
+ function peopleSentence(message) {
305
+ const [lead = "", ...tail] = message.split(/\s+—\s+|\s+--\s+/);
306
+ const sentences = lead.trim().split(/(?<=(?<!\b(?:Dr|Mr|Mrs|Ms|St|vs|No|e\.g|i\.e|etc|[A-Z]))[.!?])\s+/);
307
+ const first = sentences[0] ?? "";
308
+ const rest = [...sentences.slice(1), ...tail].map((part) => part.trim()).filter((part) => part !== "");
309
+ const cleaned = plainSentence(first);
310
+ return { kept: cleaned.kept, dropped: [...cleaned.dropped, ...rest] };
311
+ }
312
+ function refusalSentence(error) {
313
+ return refusalForAPerson(error).sentence;
314
+ }
315
+ function plainSentence(message) {
316
+ const dropped = [];
317
+ const kept = [];
318
+ for (const raw of message.split(/(?<=[.!?])\s+/)) {
319
+ const sentence = raw.trim();
320
+ if (sentence === "") continue;
321
+ const cleaned = withoutMachineClauses(sentence);
322
+ dropped.push(...cleaned.dropped);
323
+ if (cleaned.kept) kept.push(cleaned.kept);
324
+ }
325
+ return { kept: kept.length === 0 ? null : kept.join(" "), dropped };
326
+ }
327
+ function exampleOf(error) {
328
+ const detail = error.detail;
329
+ if (!detail || typeof detail !== "object") return null;
330
+ const example = detail.example;
331
+ return typeof example === "string" && example.trim() !== "" ? example.trim() : null;
332
+ }
333
+ function refusalForAPerson(error) {
334
+ const code = error.code ?? "internal";
335
+ const ours = error.ours === true;
336
+ const hint = plainSentence(String(error.hint ?? ""));
337
+ const message = ours ? plainSentence(String(error.message ?? "")) : peopleSentence(String(error.message ?? ""));
338
+ const title = TITLE[code] ?? "The store refused this";
339
+ const hintIsForEngineers = isDeveloperHint(String(error.hint ?? ""));
340
+ const example = exampleOf(error);
341
+ const remedy = (example ? `Enter it like ${example}.` : null) ?? (hintIsForEngineers ? null : hint.kept) ?? REMEDY[code] ?? REMEDY["internal"];
342
+ const messageIsForEngineers = isEngineerText(String(error.message ?? ""));
343
+ const said = (messageIsForEngineers ? "" : message.kept ?? "").trim();
344
+ const forEngineers = [
345
+ error.sqlstate ? `SQLSTATE ${error.sqlstate}.` : null,
346
+ // The client's own note about a class it did not recognise, or a call that
347
+ // never reached the store. It is rendered out of sight, never as a sentence.
348
+ error.diagnostic ? error.diagnostic : null,
349
+ messageIsForEngineers ? `Message: ${error.message}` : null,
350
+ error.hint && (hintIsForEngineers || hint.kept !== error.hint) ? `Hint: ${error.hint}` : null,
351
+ message.dropped.length > 0 || hint.dropped.length > 0 ? `Dropped from the person's view: ${[...message.dropped, ...hint.dropped].join(" | ")}` : null
352
+ ].filter(Boolean).join(" ");
353
+ return {
354
+ title,
355
+ // Nothing invented. When every clause was machine identity the title says
356
+ // what happened and the remedy says what to do; a made-up diagnosis would
357
+ // be worse than the identifier it replaced.
358
+ sentence: said === "" ? `${title}.` : said,
359
+ remedy,
360
+ storeSaid: said !== "",
361
+ forEngineers
362
+ };
363
+ }
364
+ function refusalLineForAPerson(error) {
365
+ const plain = refusalForAPerson(error);
366
+ const sentence = plain.sentence.trim();
367
+ const ended = sentence === "" || /[.!?…:]$/.test(sentence) ? sentence : `${sentence}.`;
368
+ return `${ended} ${plain.remedy}`.trim();
369
+ }
370
+ function refusalIsMissingInput(error) {
371
+ return error.sqlstate === "22023" || error.code === "invalid_argument";
372
+ }
373
+
374
+ // src/docs.ts
375
+ function fieldToken(fieldId) {
376
+ return `{{field:${fieldId}}}`;
377
+ }
378
+ function bodyFromKeys(body, fields) {
379
+ const byKey = new Map(fields.map((f) => [f.key, f.id]));
380
+ return body.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (whole, key) => {
381
+ const id = byKey.get(key);
382
+ return id ? fieldToken(id) : whole;
383
+ });
384
+ }
385
+ function bodyForReading(body, fields) {
386
+ const byId = new Map(fields.map((f) => [f.id, f.label || f.key]));
387
+ return body.replace(/\{\{\s*field:([0-9a-fA-F-]{36})\s*\}\}/g, (whole, id) => {
388
+ const label = byId.get(id);
389
+ return label ? `{{${label}}}` : whole;
390
+ });
391
+ }
392
+ function isSignatureField(field) {
393
+ return field.type === "text" && (field.format ?? "").toLowerCase() === "signature";
394
+ }
395
+
396
+ // src/choiceLooks.ts
397
+ import { newerKindOf } from "@ai-matrx/records/field-kinds";
398
+ import { CHOICE_CHIP_CLASS, NEUTRAL_CHIP_CLASS, STYLE_COLORS } from "@ai-matrx/design-system/data-table/table-style";
399
+ function displayFormatOf(field) {
400
+ const raw = field.display_format;
401
+ if (!raw || typeof raw !== "object") return null;
402
+ const id = raw.id;
403
+ if (typeof id !== "string" || id === "") return null;
404
+ const options = raw.options;
405
+ return { id, options: options && typeof options === "object" ? options : {} };
406
+ }
407
+ function isStyleColor(v) {
408
+ return typeof v === "string" && STYLE_COLORS.includes(v);
409
+ }
410
+ function choiceLooksOf(field) {
411
+ const display = displayFormatOf(field);
412
+ const choices = display?.options["choices"];
413
+ if (!Array.isArray(choices)) return [];
414
+ const out = [];
415
+ for (const c of choices) {
416
+ if (!c || typeof c !== "object") continue;
417
+ const value = c.value;
418
+ if (typeof value !== "string" || value.trim() === "") continue;
419
+ const color = c.color;
420
+ const label = c.label;
421
+ out.push({
422
+ value: value.trim(),
423
+ ...typeof label === "string" && label.trim() !== "" ? { label: label.trim() } : {},
424
+ ...isStyleColor(color) ? { color } : {}
425
+ });
426
+ }
427
+ return out;
428
+ }
429
+ function choiceWord(value) {
430
+ return String(value ?? "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
431
+ }
432
+ var STATUS_GROUP_COLOR = { todo: "gray", in_progress: "blue", done: "green" };
433
+ function statusGroupColor(field, value) {
434
+ if (newerKindOf(field) !== "status" || value === null || value === void 0 || value === "") return void 0;
435
+ const word = choiceWord(value);
436
+ if (word === "") return void 0;
437
+ const groups = (field.config ?? {})["status_groups"];
438
+ if (groups && typeof groups === "object") {
439
+ for (const [key, group] of Object.entries(groups)) {
440
+ if (choiceWord(key) !== word) continue;
441
+ return group === "in_progress" ? STATUS_GROUP_COLOR.in_progress : group === "done" ? STATUS_GROUP_COLOR.done : STATUS_GROUP_COLOR.todo;
442
+ }
443
+ }
444
+ return STATUS_GROUP_COLOR.todo;
445
+ }
446
+ function storedChoiceColor(field, value) {
447
+ if (value === null || value === void 0 || value === "") return void 0;
448
+ const word = choiceWord(value);
449
+ if (word === "") return void 0;
450
+ for (const look of choiceLooksOf(field)) {
451
+ if (!look.color) continue;
452
+ if (choiceWord(look.value) === word || look.label && choiceWord(look.label) === word) return look.color;
453
+ }
454
+ return statusGroupColor(field, value);
455
+ }
456
+ function storedChoiceColorLookup(fields, fallback) {
457
+ const byKey = new Map(fields.map((f) => [f.key, f]));
458
+ return (fieldKey, value) => {
459
+ const field = byKey.get(fieldKey);
460
+ return (field ? storedChoiceColor(field, value) : void 0) ?? fallback(fieldKey, value);
461
+ };
462
+ }
463
+ var NEW_CHOICE_PALETTE = ["blue", "green", "amber", "red", "violet", "teal", "slate"];
464
+ function nextChoiceColor(worn) {
465
+ const taken = new Set(worn.filter((c) => Boolean(c)));
466
+ const free = NEW_CHOICE_PALETTE.find((c) => !taken.has(c));
467
+ return free ?? NEW_CHOICE_PALETTE[worn.length % NEW_CHOICE_PALETTE.length];
468
+ }
469
+ function choiceChipLookOf(field, ...words) {
470
+ for (const word of words) {
471
+ const color = storedChoiceColor(field, word);
472
+ if (color) return { className: CHOICE_CHIP_CLASS[color], color };
473
+ }
474
+ return { className: NEUTRAL_CHIP_CLASS, color: null };
475
+ }
476
+
477
+ // src/parity.ts
478
+ import {
479
+ KERNEL_TABLES,
480
+ PARITY_FIELD_TYPES,
481
+ fieldKindFor,
482
+ newerKindOf as newerKindOf2,
483
+ isButtonField
484
+ } from "@ai-matrx/records/field-kinds";
485
+ import { humanizeIdentifier as humanizeIdentifier2 } from "@ai-matrx/kit/text-case";
486
+ var kernelId = (name) => KERNEL_TABLES.find((t) => t.name === name)?.id ?? "";
487
+ var KERNEL_FILE_TABLE = kernelId("File");
488
+ var KERNEL_PERSON_TABLE = kernelId("Person");
489
+ var PARITY_LABEL = {
490
+ attachment: "Attachment",
491
+ checkbox: "Yes / no",
492
+ currency: "Currency",
493
+ datetime: "Date",
494
+ email: "Email",
495
+ formula: "Formula",
496
+ lookup: "Lookup",
497
+ member: "Person",
498
+ multi_select: "Multi-select",
499
+ percent: "Percent",
500
+ phone: "Phone",
501
+ rollup: "Rollup",
502
+ select: "Select",
503
+ url: "Link"
504
+ };
505
+ var PARITY_MADE_OF = Object.fromEntries(
506
+ PARITY_FIELD_TYPES.map((p) => [p.parity_type, p.made_of])
507
+ );
508
+ var KERNEL = { file: KERNEL_FILE_TABLE, person: KERNEL_PERSON_TABLE };
509
+ function editorKindFor(field) {
510
+ return fieldKindFor(field, KERNEL);
511
+ }
512
+ function pickableTypeOf(field) {
513
+ if (isSignatureField(field)) return "signature";
514
+ if (isButtonField(field)) return "button";
515
+ const newer = newerKindOf2(field);
516
+ if (newer) return newer;
517
+ const look = displayFormatOf(field)?.id;
518
+ if (look === "rating" && field.type === "range") return "rating";
519
+ if (look === "time" && field.type === "text") return "time";
520
+ const system = field.config?.["system"];
521
+ if (field.type === "formula" && typeof system === "string" && isSystemFieldKind(system)) return system;
522
+ const kind = editorKindFor(field);
523
+ return fieldTypeChoice(kind) ? kind : void 0;
524
+ }
525
+ function fieldTypeLabel(field) {
526
+ const kind = pickableTypeOf(field) ?? editorKindFor(field);
527
+ const known = fieldTypeChoice(kind)?.label;
528
+ if (known) return field.multi && kind !== "multi_select" ? `${known} (many)` : known;
529
+ const plain = {
530
+ // `boolean` is the BEHAVIOUR word; `checkbox` is the type a person picks. Both are
531
+ // written the way a person writes them, never as a raw token.
532
+ boolean: "Yes / no",
533
+ date: "Date",
534
+ json: "Structured data",
535
+ relation: "Link to a record"
536
+ };
537
+ return plain[kind] ?? humanizeIdentifier2(kind);
538
+ }
539
+
540
+ // src/Refusal.tsx
541
+ import { archivedOrganizationId } from "@ai-matrx/records/core";
542
+ import { Alert as Alert2, AlertDescription as AlertDescription2, AlertTitle as AlertTitle2, ErrorBox, cn as cn2 } from "@ai-matrx/design-system";
543
+
544
+ // src/ArchivedOrganizationNotice.tsx
545
+ import { useEffect, useState } from "react";
546
+ import { Alert, AlertDescription, AlertTitle, cn } from "@ai-matrx/design-system";
547
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
548
+ function ArchivedOrganizationNotice({
549
+ organizationId,
550
+ error,
551
+ className
552
+ }) {
553
+ const port = useRecordsUi().archivedOrganization;
554
+ const [mayRestore, setMayRestore] = useState(null);
555
+ const [busy, setBusy] = useState(false);
556
+ const [failed, setFailed] = useState(null);
557
+ useEffect(() => {
558
+ let live = true;
559
+ if (!port) {
560
+ setMayRestore(false);
561
+ return;
562
+ }
563
+ setMayRestore(null);
564
+ port.state(organizationId).then((answer) => {
565
+ if (live) setMayRestore(answer?.mayRestore === true);
566
+ }).catch(() => {
567
+ if (live) setMayRestore(false);
568
+ });
569
+ return () => {
570
+ live = false;
571
+ };
572
+ }, [organizationId, port?.state]);
573
+ const restore = async () => {
574
+ if (!port || busy) return;
575
+ setBusy(true);
576
+ setFailed(null);
577
+ try {
578
+ await port.restore(organizationId);
579
+ if (port.afterRestore) port.afterRestore();
580
+ else if (typeof window !== "undefined") window.location.reload();
581
+ } catch (thrown) {
582
+ setFailed(thrown instanceof Error && thrown.message ? thrown.message : "The organization could not be restored.");
583
+ setBusy(false);
584
+ }
585
+ };
586
+ return /* @__PURE__ */ jsxs(
587
+ Alert,
588
+ {
589
+ variant: "destructive",
590
+ role: "alert",
591
+ "data-refusal-notice": "",
592
+ "data-archived-organization": organizationId,
593
+ className: cn("text-xs", className),
594
+ errorFacts: { message: "This organization is archived", title: "This organization is archived", error, origin: "records-ui/ArchivedOrganizationNotice" },
595
+ children: [
596
+ /* @__PURE__ */ jsx2(AlertTitle, { className: "text-xs font-medium", children: "This organization is archived" }),
597
+ /* @__PURE__ */ jsxs(AlertDescription, { className: "space-y-1 text-xs", children: [
598
+ /* @__PURE__ */ jsx2("p", { className: "opacity-80", children: "Nothing was deleted. Everything here comes back the moment an owner of the organization, or a super admin, restores it." }),
599
+ mayRestore === true ? /* @__PURE__ */ jsx2(
600
+ "button",
601
+ {
602
+ type: "button",
603
+ "data-restore-organization": "",
604
+ disabled: busy,
605
+ className: "rounded border px-2 py-0.5 text-xs hover:bg-muted disabled:opacity-60",
606
+ onClick: () => void restore(),
607
+ children: busy ? "Restoring..." : "Restore organization"
608
+ }
609
+ ) : null,
610
+ mayRestore === false ? /* @__PURE__ */ jsx2("p", { "data-restore-who": "", className: "opacity-80", children: "Ask an owner of this organization to restore it." }) : null,
611
+ failed ? /* @__PURE__ */ jsx2("p", { "data-restore-refused": "", children: failed }) : null
612
+ ] })
613
+ ]
614
+ }
615
+ );
616
+ }
617
+
618
+ // src/Refusal.tsx
619
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
620
+ function hintIsMachineIdentity(hint) {
621
+ return isMachineIdentity(hint);
622
+ }
623
+ function hintForAPerson(hint) {
624
+ const said = (hint ?? "").trim();
625
+ if (said === "") return null;
626
+ if (isMachineIdentity(said)) return null;
627
+ return peopleHint(said) === null ? null : said;
628
+ }
629
+ function RefusalNotice({
630
+ error,
631
+ className,
632
+ actions,
633
+ onKeepEditing,
634
+ onDiscard
635
+ }) {
636
+ const archivedOrg = archivedOrganizationId(error);
637
+ if (archivedOrg) {
638
+ return /* @__PURE__ */ jsx3(ArchivedOrganizationNotice, { organizationId: archivedOrg, error, className });
639
+ }
640
+ const plain = refusalForAPerson(error);
641
+ const doors = onKeepEditing || onDiscard ? /* @__PURE__ */ jsxs2("div", { className: "flex flex-wrap items-center gap-1 pt-0.5", "data-refusal-doors": "", children: [
642
+ onKeepEditing ? /* @__PURE__ */ jsx3(
643
+ "button",
644
+ {
645
+ type: "button",
646
+ "data-refusal-keep-editing": "",
647
+ className: "rounded border px-2 py-0.5 text-xs hover:bg-muted",
648
+ onClick: onKeepEditing,
649
+ children: "Keep editing"
650
+ }
651
+ ) : null,
652
+ onDiscard ? /* @__PURE__ */ jsx3(
653
+ "button",
654
+ {
655
+ type: "button",
656
+ "data-refusal-discard": "",
657
+ className: "rounded border px-2 py-0.5 text-xs hover:bg-muted",
658
+ onClick: onDiscard,
659
+ children: "Discard"
660
+ }
661
+ ) : null
662
+ ] }) : null;
663
+ return /* @__PURE__ */ jsxs2(
664
+ Alert2,
665
+ {
666
+ variant: "destructive",
667
+ role: "alert",
668
+ "data-refusal-notice": "",
669
+ className: cn2("text-xs", className),
670
+ errorFacts: { message: plain.sentence, title: plain.title, error, origin: "records-ui/RefusalNotice" },
671
+ ...plain.forEngineers ? { "data-for-engineers": plain.forEngineers } : {},
672
+ ...error.sqlstate ? { "data-sqlstate": error.sqlstate } : {},
673
+ children: [
674
+ /* @__PURE__ */ jsx3(AlertTitle2, { className: "text-xs font-medium", children: plain.storeSaid ? plain.sentence : plain.title }),
675
+ /* @__PURE__ */ jsxs2(AlertDescription2, { className: "space-y-1 text-xs", children: [
676
+ plain.storeSaid || plain.sentence.replace(/\.$/, "") === plain.title ? null : /* @__PURE__ */ jsx3("p", { children: plain.sentence }),
677
+ /* @__PURE__ */ jsx3("p", { className: "opacity-80", children: plain.remedy }),
678
+ actions,
679
+ doors
680
+ ] })
681
+ ]
682
+ }
683
+ );
684
+ }
685
+ function RefusalLine({ error, className }) {
686
+ const plain = refusalForAPerson(error);
687
+ return /* @__PURE__ */ jsx3(
688
+ ErrorBox,
689
+ {
690
+ "data-refusal-line": "",
691
+ className: cn2("whitespace-normal break-words text-xs text-destructive [overflow-wrap:anywhere]", className),
692
+ message: archivedOrganizationId(error) ? "This organization is archived. An owner can restore it." : refusalLineForAPerson(error),
693
+ error,
694
+ origin: "records-ui/RefusalLine",
695
+ ...plain.forEngineers ? { "data-for-engineers": plain.forEngineers } : {}
696
+ }
697
+ );
698
+ }
699
+
700
+ // src/PickOrAdd.tsx
701
+ import { useEffect as useEffect2, useRef, useState as useState2 } from "react";
702
+
703
+ // src/personChip.tsx
704
+ import { cn as cn3 } from "@ai-matrx/design-system";
705
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
706
+ function initialsOf(name) {
707
+ const words = name.replace(/@.*$/, "").split(/[\s._-]+/).filter((w) => /\p{L}|\d/u.test(w));
708
+ const letters = words.filter((w) => !/^(dr|mr|mrs|ms|prof)\.?$/i.test(w)).slice(0, 2).map((w) => (w.match(/[\p{L}\d]/u)?.[0] ?? "").toUpperCase());
709
+ return letters.join("") || "?";
710
+ }
711
+ function PersonAvatar({ name, size = "sm" }) {
712
+ return /* @__PURE__ */ jsx4(
713
+ "span",
714
+ {
715
+ "aria-hidden": "true",
716
+ "data-records-person-avatar": "",
717
+ className: cn3(
718
+ "inline-flex shrink-0 items-center justify-center rounded-full bg-foreground/10 font-medium text-foreground/80",
719
+ size === "md" ? "size-5 text-[10px]" : "size-4 text-[9px]"
720
+ ),
721
+ children: initialsOf(name)
722
+ }
723
+ );
724
+ }
725
+ function PersonChip({ name, onRemove, onOpen, className }) {
726
+ return /* @__PURE__ */ jsxs3(
727
+ "span",
728
+ {
729
+ "data-records-person-chip": "",
730
+ title: name,
731
+ className: cn3("inline-flex min-w-0 max-w-full items-center gap-1 rounded-full bg-muted px-1.5 py-0.5 text-[11px] text-foreground", className),
732
+ children: [
733
+ /* @__PURE__ */ jsx4(PersonAvatar, { name }),
734
+ onOpen ? /* @__PURE__ */ jsx4("button", { type: "button", onClick: onOpen, "data-records-person-open": "", className: "min-w-0 truncate hover:underline", children: name }) : /* @__PURE__ */ jsx4("span", { className: "min-w-0 truncate", children: name }),
735
+ onRemove ? /* @__PURE__ */ jsx4("button", { type: "button", onClick: onRemove, "aria-label": `Remove ${name}`, className: "shrink-0 opacity-60 hover:opacity-100", children: "\xD7" }) : null
736
+ ]
737
+ }
738
+ );
739
+ }
740
+
741
+ // src/PickOrAdd.tsx
742
+ import { BasicInput, Button, Popover, PopoverAnchor, PopoverContent, PopoverTrigger, ScrollArea, cn as cn4 } from "@ai-matrx/design-system";
743
+ import { jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
744
+ function Glyph({ d, className }) {
745
+ return /* @__PURE__ */ jsx5("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.5, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true, className, children: /* @__PURE__ */ jsx5("path", { d }) });
746
+ }
747
+ var TICK = "m5 12 4 4L19 6";
748
+ var CROSS = "M18 6 6 18M6 6l12 12";
749
+ var PLUS = "M12 5v14M5 12h14";
750
+ function useListKeys(args) {
751
+ const { count, resetOn, onPick, onNothing, onClose, onFinish, onBackspaceEmpty, searchEmpty } = args;
752
+ const [highlight, setHighlight] = useState2(0);
753
+ const [moved, setMoved] = useState2(false);
754
+ useEffect2(() => {
755
+ setHighlight(0);
756
+ setMoved(false);
757
+ }, [resetOn]);
758
+ const at = count === 0 ? -1 : Math.min(highlight, count - 1);
759
+ const onKeyDown = (event) => {
760
+ if (event.key === "Tab") return;
761
+ event.stopPropagation();
762
+ if (event.key === "ArrowDown") {
763
+ event.preventDefault();
764
+ setMoved(true);
765
+ if (count > 0) setHighlight((h) => (Math.min(h, count - 1) + 1) % count);
766
+ } else if (event.key === "ArrowUp") {
767
+ event.preventDefault();
768
+ setMoved(true);
769
+ if (count > 0) setHighlight((h) => (Math.min(h, count - 1) - 1 + count) % count);
770
+ } else if (event.key === "Enter") {
771
+ event.preventDefault();
772
+ if (onFinish && searchEmpty && !moved) onFinish();
773
+ else if (at >= 0) onPick(at);
774
+ else onNothing?.();
775
+ } else if (event.key === "Escape") {
776
+ event.preventDefault();
777
+ onClose();
778
+ } else if (event.key === "Backspace" && searchEmpty && onBackspaceEmpty) {
779
+ event.preventDefault();
780
+ onBackspaceEmpty();
781
+ }
782
+ };
783
+ return { highlight: at, setHighlight, onKeyDown };
784
+ }
785
+ function PickRow({
786
+ label,
787
+ detail,
788
+ title,
789
+ chip,
790
+ picked,
791
+ highlighted,
792
+ disabled,
793
+ attrs,
794
+ icon,
795
+ person,
796
+ onPick,
797
+ onPoint
798
+ }) {
799
+ const ref = useRef(null);
800
+ useEffect2(() => {
801
+ if (highlighted) ref.current?.scrollIntoView?.({ block: "nearest" });
802
+ }, [highlighted]);
803
+ return /* @__PURE__ */ jsxs4(
804
+ "button",
805
+ {
806
+ ref,
807
+ type: "button",
808
+ role: "option",
809
+ "aria-selected": picked,
810
+ disabled: disabled ?? false,
811
+ onClick: onPick,
812
+ onMouseMove: onPoint,
813
+ title: title ?? label,
814
+ ...attrs ?? {},
815
+ "data-pick-highlighted": highlighted ? "" : void 0,
816
+ className: cn4(
817
+ "flex w-full min-w-0 items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm outline-none disabled:opacity-50",
818
+ highlighted ? "bg-accent text-accent-foreground" : ""
819
+ ),
820
+ children: [
821
+ /* @__PURE__ */ jsxs4("span", { className: "flex size-3.5 shrink-0 items-center justify-center", children: [
822
+ picked ? /* @__PURE__ */ jsx5("span", { "data-pick-tick": "", className: "contents", children: /* @__PURE__ */ jsx5(Glyph, { d: TICK, className: "size-3.5" }) }) : null,
823
+ icon === "plus" ? /* @__PURE__ */ jsx5(Glyph, { d: PLUS, className: "size-3.5 text-muted-foreground" }) : null
824
+ ] }),
825
+ person ? /* @__PURE__ */ jsx5(PersonAvatar, { name: label, size: "md" }) : null,
826
+ /* @__PURE__ */ jsxs4("span", { className: "min-w-0 flex-1", children: [
827
+ chip ? /* @__PURE__ */ jsx5("span", { className: cn4("inline-flex max-w-full truncate rounded-md border px-1.5 py-0.5 text-xs font-medium", chip), "data-records-choice-chip": "", children: label }) : /* @__PURE__ */ jsx5("span", { className: "block truncate", children: label }),
828
+ detail ? /* @__PURE__ */ jsx5("span", { className: "block truncate text-xs text-muted-foreground", "data-tell-apart": "", children: detail }) : null
829
+ ] })
830
+ ]
831
+ }
832
+ );
833
+ }
834
+ function PickChips({ chips }) {
835
+ if (chips.length === 0) return null;
836
+ return /* @__PURE__ */ jsx5("div", { className: "flex flex-wrap gap-1 px-1 pb-1", "data-pick-chips": "", children: chips.map(
837
+ (c) => c.person ? /* @__PURE__ */ jsx5(PersonChip, { name: c.label, onRemove: c.onRemove }, c.id) : /* @__PURE__ */ jsxs4(
838
+ "span",
839
+ {
840
+ "data-pick-chip": "",
841
+ title: c.label,
842
+ className: cn4(
843
+ "inline-flex max-w-full items-center gap-1 rounded-md border px-1.5 py-0.5 text-xs font-medium",
844
+ c.chip ?? "bg-secondary text-secondary-foreground"
845
+ ),
846
+ children: [
847
+ /* @__PURE__ */ jsx5("span", { className: "min-w-0 truncate", children: c.label }),
848
+ c.onRemove ? /* @__PURE__ */ jsx5(
849
+ "button",
850
+ {
851
+ type: "button",
852
+ "aria-label": `Remove ${c.label}`,
853
+ onClick: c.onRemove,
854
+ className: "shrink-0 rounded-sm opacity-60 hover:opacity-100",
855
+ children: /* @__PURE__ */ jsx5(Glyph, { d: CROSS, className: "size-3" })
856
+ }
857
+ ) : null
858
+ ]
859
+ },
860
+ c.id
861
+ )
862
+ ) });
863
+ }
864
+ function PickOrAdd({
865
+ triggerSize = "field",
866
+ triggerLabel,
867
+ triggerText,
868
+ triggerId,
869
+ open,
870
+ onOpenChange,
871
+ search,
872
+ onSearch,
873
+ items,
874
+ onPick,
875
+ notice,
876
+ empty,
877
+ add,
878
+ foot,
879
+ footNote,
880
+ onEnterWithNoMatch,
881
+ anchored,
882
+ children,
883
+ chips,
884
+ multi,
885
+ onEscape
886
+ }) {
887
+ const addRow = add && !foot ? add : null;
888
+ const count = items.length + (addRow ? 1 : 0);
889
+ const addAt = addRow ? items.length : -1;
890
+ const itemAt = (index) => index;
891
+ const removable = (chips ?? []).filter((c) => c.onRemove);
892
+ const keys = useListKeys({
893
+ count,
894
+ resetOn: search,
895
+ onPick: (index) => {
896
+ if (index === addAt) {
897
+ if (addRow && !addRow.disabled) addRow.onAdd();
898
+ return;
899
+ }
900
+ const item = items[itemAt(index)];
901
+ if (item && !item.disabled) onPick(item.id);
902
+ },
903
+ onNothing: onEnterWithNoMatch ?? (add && !add.disabled ? add.onAdd : void 0),
904
+ onClose: () => onEscape ? onEscape() : onOpenChange(false),
905
+ ...multi ? { onFinish: () => onOpenChange(false) } : {},
906
+ ...removable.length > 0 ? { onBackspaceEmpty: () => removable[removable.length - 1]?.onRemove?.() } : {},
907
+ searchEmpty: search === ""
908
+ });
909
+ const hasFoot = Boolean(foot) || Boolean(footNote);
910
+ const addRowNode = addRow ? /* @__PURE__ */ jsx5(
911
+ PickRow,
912
+ {
913
+ label: addRow.label,
914
+ picked: false,
915
+ icon: "plus",
916
+ disabled: addRow.disabled,
917
+ attrs: { "data-pick-add": "" },
918
+ highlighted: addAt === keys.highlight,
919
+ onPick: addRow.onAdd,
920
+ onPoint: () => keys.setHighlight(addAt)
921
+ }
922
+ ) : null;
923
+ return /* @__PURE__ */ jsxs4(Popover, { open, onOpenChange, children: [
924
+ anchored ? /* @__PURE__ */ jsx5(PopoverAnchor, { asChild: true, children: /* @__PURE__ */ jsx5("div", { "data-pick-anchor": "", className: "flex min-h-6 w-full min-w-0 flex-wrap items-center gap-1", "aria-label": triggerLabel, children }) }) : /* @__PURE__ */ jsx5(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx5(Button, { id: triggerId, type: "button", size: "sm", variant: "outline", className: triggerSize === "field" ? "h-9" : void 0, "aria-label": triggerLabel, children: triggerText }) }),
925
+ /* @__PURE__ */ jsxs4(
926
+ PopoverContent,
927
+ {
928
+ sizing: "content",
929
+ padding: "xs",
930
+ align: "start",
931
+ side: "bottom",
932
+ sideOffset: anchored ? 2 : 4,
933
+ animated: false,
934
+ "data-matrx-cell-editor": "",
935
+ onKeyDown: (event) => {
936
+ if (event.key !== "Tab") event.stopPropagation();
937
+ },
938
+ onEscapeKeyDown: (event) => {
939
+ if (!onEscape) return;
940
+ event.preventDefault();
941
+ onEscape();
942
+ },
943
+ onCloseAutoFocus: (event) => {
944
+ if (anchored) event.preventDefault();
945
+ },
946
+ children: [
947
+ chips ? /* @__PURE__ */ jsx5(PickChips, { chips }) : null,
948
+ /* @__PURE__ */ jsx5(
949
+ BasicInput,
950
+ {
951
+ value: search,
952
+ onChange: (e) => onSearch(e.target.value),
953
+ onKeyDown: keys.onKeyDown,
954
+ placeholder: "Search",
955
+ "aria-label": `Search \u2014 ${triggerLabel}`,
956
+ autoFocus: true,
957
+ autoComplete: "off",
958
+ className: "mb-1 h-8 text-sm"
959
+ }
960
+ ),
961
+ notice,
962
+ /* @__PURE__ */ jsxs4(ScrollArea, { className: "max-h-64", children: [
963
+ /* @__PURE__ */ jsxs4("div", { role: "listbox", "aria-label": triggerLabel, "aria-multiselectable": multi ? true : void 0, children: [
964
+ items.map((item, index) => /* @__PURE__ */ jsx5(
965
+ PickRow,
966
+ {
967
+ label: item.label,
968
+ detail: item.detail,
969
+ title: item.title,
970
+ chip: item.chip,
971
+ picked: item.picked,
972
+ disabled: item.disabled,
973
+ attrs: item.attrs,
974
+ person: item.person,
975
+ highlighted: index === keys.highlight,
976
+ onPick: () => onPick(item.id),
977
+ onPoint: () => keys.setHighlight(index)
978
+ },
979
+ item.id
980
+ )),
981
+ addRowNode
982
+ ] }),
983
+ items.length === 0 && empty ? empty : null
984
+ ] }),
985
+ hasFoot ? /* @__PURE__ */ jsxs4("div", { className: "mt-1 border-t pt-1", children: [
986
+ foot,
987
+ footNote
988
+ ] }) : null
989
+ ]
990
+ }
991
+ )
992
+ ] });
993
+ }
994
+
995
+ // src/recordVersions.ts
996
+ var recordVersions_exports = {};
997
+ __reExport(recordVersions_exports, versions_star);
998
+ import * as versions_star from "@ai-matrx/records/versions";
999
+
1000
+ // src/createTable.ts
1001
+ import {
1002
+ declareTable,
1003
+ addFields,
1004
+ fieldDeclarationFor,
1005
+ tokenFor,
1006
+ DEFAULT_FIELDS
1007
+ } from "@ai-matrx/records/field-kinds";
1008
+
1009
+ // src/tablePickerEntries.ts
1010
+ var PLATFORM_TABLE_PREFIX = "records_ui_";
1011
+ function keptByPlatform(table) {
1012
+ return table.platform_owned === true || table.kept_by_the_app === true;
1013
+ }
1014
+ function isValueSet(table) {
1015
+ if (table.kept_for === "choices") return true;
1016
+ return table.kept_for == null && table.kind === "list" && keptByPlatform(table);
1017
+ }
1018
+ function isKeptTable(table) {
1019
+ return keptByPlatform(table) || isValueSet(table) || Boolean(table.work_kind) || (table.slug ?? "").startsWith(PLATFORM_TABLE_PREFIX);
1020
+ }
1021
+ var CHOICES_SUFFIX = / choices$/i;
1022
+ function tablePickerEntries(tables, options = {}) {
1023
+ const byId = new Map(tables.map((t) => [t.id, t]));
1024
+ const lists = tables.filter(isValueSet);
1025
+ const listLabel = (t) => {
1026
+ const column = t.name.replace(CHOICES_SUFFIX, "");
1027
+ if (!t.used_in_table_id || t.used_in_table_id === t.id) {
1028
+ const made = madeOn(t.created_at);
1029
+ return made ? `${column} \u2014 no column \xB7 ${made}` : `${column} \u2014 no column`;
1030
+ }
1031
+ const owner = byId.get(t.used_in_table_id);
1032
+ if (!owner) return t.name;
1033
+ return `${column} \u2014 ${owner.name}`;
1034
+ };
1035
+ const plain = tables.filter((t) => !isKeptTable(t) || t.id === options.keep && !isValueSet(t)).map((t) => ({ table: t, id: t.id, label: t.name, isList: false })).sort((a, b) => a.label.localeCompare(b.label));
1036
+ const shownLists = lists.filter((t) => options.showLists || t.id === options.keep).map((t) => ({ table: t, id: t.id, label: listLabel(t), isList: true })).sort((a, b) => a.label.localeCompare(b.label));
1037
+ const entries = [...plain, ...shownLists];
1038
+ const seen = /* @__PURE__ */ new Map();
1039
+ for (const entry of entries) {
1040
+ const key = entry.label.toLowerCase();
1041
+ const n = (seen.get(key) ?? 0) + 1;
1042
+ seen.set(key, n);
1043
+ if (n > 1) entry.label = `${entry.label} (${n})`;
1044
+ }
1045
+ return { entries, listCount: lists.length };
1046
+ }
1047
+ function madeOn(stamp) {
1048
+ if (!stamp) return null;
1049
+ const at = new Date(stamp);
1050
+ if (Number.isNaN(at.getTime())) return null;
1051
+ return new Intl.DateTimeFormat(void 0, { month: "short", day: "numeric", year: "numeric" }).format(at);
1052
+ }
1053
+
1054
+ // src/tablePicking.tsx
1055
+ import { useCallback, useEffect as useEffect3, useMemo as useMemo2, useState as useState3 } from "react";
1056
+ import { withTablePlacement } from "@ai-matrx/records";
1057
+ import { useRecordsClient, useTables } from "@ai-matrx/records/react";
1058
+ import { Checkbox, cn as cn5 } from "@ai-matrx/design-system";
1059
+ import { jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
1060
+ function usePickerTables() {
1061
+ const client = useRecordsClient();
1062
+ const tables = useTables();
1063
+ const [facts, setFacts] = useState3("reading");
1064
+ const [nonce, setNonce] = useState3(0);
1065
+ const reloadTables = tables.reload;
1066
+ const reload = useCallback(() => {
1067
+ reloadTables();
1068
+ setNonce((n) => n + 1);
1069
+ }, [reloadTables]);
1070
+ useEffect3(() => {
1071
+ let alive = true;
1072
+ void client.tableFacts().then((answered) => {
1073
+ if (alive) setFacts(answered.ok ? answered.data ?? null : null);
1074
+ });
1075
+ return () => {
1076
+ alive = false;
1077
+ };
1078
+ }, [client, nonce]);
1079
+ const data = useMemo2(
1080
+ () => withTablePlacement(tables.data ?? [], facts === "reading" ? null : facts),
1081
+ [tables.data, facts]
1082
+ );
1083
+ return { loading: tables.loading || facts === "reading", data, reload };
1084
+ }
1085
+ function ShowListsToggle({
1086
+ count,
1087
+ on,
1088
+ onChange,
1089
+ className
1090
+ }) {
1091
+ if (count === 0) return null;
1092
+ return /* @__PURE__ */ jsxs5("label", { className: cn5("flex items-center gap-1.5 text-[11px] text-muted-foreground", className), children: [
1093
+ /* @__PURE__ */ jsx6(Checkbox, { checked: on, onCheckedChange: (next) => onChange(next === true), "aria-label": "Show lists" }),
1094
+ "Show lists (",
1095
+ count,
1096
+ ")"
1097
+ ] });
1098
+ }
1099
+
1100
+ // src/dates.ts
1101
+ import { formatFieldValue } from "@ai-matrx/design-system/field-formats";
1102
+ var BARE_CALENDAR_DATE = /^(\d{4})-(\d{2})-(\d{2})(?:[T ]00:00(?::00(?:\.0+)?)?)?$/;
1103
+ function systemStampOf(field) {
1104
+ if (field.type !== "formula") return null;
1105
+ const system = String((field.config ?? {})["system"] ?? "");
1106
+ return system === "autonumber" || system === "created_time" || system === "modified_time" ? system : null;
1107
+ }
1108
+ function carriesTimeOfDay(field, value) {
1109
+ if (value !== void 0 && value !== null && value !== "") return hasTimePart(value);
1110
+ const stamp = systemStampOf(field);
1111
+ if (stamp === "created_time" || stamp === "modified_time") return true;
1112
+ return (field.format ?? "").toLowerCase() === "datetime";
1113
+ }
1114
+ function timeOfDayWords(value) {
1115
+ if (!hasTimePart(value)) return null;
1116
+ const at = value instanceof Date ? value : new Date(value);
1117
+ return Number.isNaN(at.getTime()) ? null : at.toLocaleTimeString(void 0, { hour: "numeric", minute: "2-digit" });
1118
+ }
1119
+ function hasTimePart(value) {
1120
+ if (value instanceof Date || typeof value === "number") return true;
1121
+ if (typeof value !== "string") return false;
1122
+ const trimmed = value.trim();
1123
+ if (BARE_CALENDAR_DATE.test(trimmed)) return false;
1124
+ return /^\d{4}-\d{2}-\d{2}[T ]\d/.test(trimmed);
1125
+ }
1126
+ function isDateField(field) {
1127
+ const stamp = systemStampOf(field);
1128
+ if (stamp === "created_time" || stamp === "modified_time") return true;
1129
+ if (field.type !== "range") return false;
1130
+ const kind = String((field.config ?? {})["kind"] ?? "");
1131
+ return kind === "date" || kind === "datetime";
1132
+ }
1133
+ function dateFormatFor(field, value) {
1134
+ if (!isDateField(field)) return void 0;
1135
+ return carriesTimeOfDay(field, value) ? { id: "datetime" } : { id: "date" };
1136
+ }
1137
+ function dateText(field, value) {
1138
+ const format = dateFormatFor(field, value) ?? (isDateLike(value) ? { id: hasTimePart(value) ? "datetime" : "date" } : void 0);
1139
+ if (!format) return null;
1140
+ const result = formatFieldValue(value, format);
1141
+ return result.ok && !result.empty ? result.text : null;
1142
+ }
1143
+ function isDateLike(value) {
1144
+ return typeof value === "string" && /^\d{4}-\d{2}-\d{2}/.test(value.trim());
1145
+ }
1146
+ function pad(n) {
1147
+ return n < 10 ? `0${n}` : String(n);
1148
+ }
1149
+ function calendarDayOf(value) {
1150
+ if (typeof value === "string") {
1151
+ const trimmed = value.trim();
1152
+ const bare = BARE_CALENDAR_DATE.exec(trimmed);
1153
+ if (bare) return `${bare[1]}-${bare[2]}-${bare[3]}`;
1154
+ if (trimmed === "") return null;
1155
+ } else if (typeof value !== "number" && !(value instanceof Date)) {
1156
+ return null;
1157
+ }
1158
+ const at = value instanceof Date ? value : new Date(value);
1159
+ if (Number.isNaN(at.getTime())) return null;
1160
+ return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}`;
1161
+ }
1162
+ function calendarDayLabel(day) {
1163
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day);
1164
+ if (!m) return day;
1165
+ const at = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
1166
+ return at.toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
1167
+ }
1168
+ function dayKeyOf(at) {
1169
+ return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}`;
1170
+ }
1171
+ function dayAt(day) {
1172
+ const [y, m, d] = day.split("-").map(Number);
1173
+ return new Date(y, (m ?? 1) - 1, d ?? 1);
1174
+ }
1175
+ function addDays(day, n) {
1176
+ const at = dayAt(day);
1177
+ at.setDate(at.getDate() + n);
1178
+ return dayKeyOf(at);
1179
+ }
1180
+ function daysBetween(from, to) {
1181
+ return Math.round((dayAt(to).getTime() - dayAt(from).getTime()) / 864e5);
1182
+ }
1183
+
1184
+ // src/refusals.ts
1185
+ var refusals_exports = {};
1186
+ __reExport(refusals_exports, versions_star2);
1187
+ import * as versions_star2 from "@ai-matrx/records/versions";
1188
+
1189
+ // src/enumLabels.ts
1190
+ function exhaustiveValuesOf() {
1191
+ return function(values) {
1192
+ return values;
1193
+ };
1194
+ }
1195
+ var WORK_DUE_STATES = exhaustiveValuesOf()([
1196
+ "overdue",
1197
+ "due_today",
1198
+ "scheduled",
1199
+ "undated",
1200
+ "finished"
1201
+ ]);
1202
+ var DUE_STATE_LABEL = {
1203
+ overdue: "Overdue",
1204
+ due_today: "Today",
1205
+ scheduled: "Scheduled",
1206
+ undated: "No date",
1207
+ finished: "Done"
1208
+ };
1209
+ var WORK_INBOX_KINDS = exhaustiveValuesOf()(["assignment", "approval", "proposal"]);
1210
+ var WORK_INBOX_KIND_LABEL = {
1211
+ assignment: "Assigned",
1212
+ approval: "Approval",
1213
+ proposal: "Agent proposal"
1214
+ };
1215
+ var WORK_INBOX_KIND_GROUP_LABEL = {
1216
+ approval: "Approvals",
1217
+ proposal: "Agent proposals",
1218
+ assignment: "Assigned to you"
1219
+ };
1220
+ var WORK_APPROVAL_STATES = exhaustiveValuesOf()(["pending", "approved", "declined", "withdrawn"]);
1221
+ var WORK_APPROVAL_STATE_LABEL = {
1222
+ pending: "Waiting",
1223
+ approved: "Approved",
1224
+ declined: "Declined",
1225
+ withdrawn: "Withdrawn"
1226
+ };
1227
+ var CHECKLIST_REQUIREMENT_KINDS = exhaustiveValuesOf()([
1228
+ "none",
1229
+ "note",
1230
+ "answer",
1231
+ "record_field",
1232
+ "form",
1233
+ "document"
1234
+ ]);
1235
+ var CHECKLIST_REQUIREMENT_LABEL = {
1236
+ none: "",
1237
+ note: "Say what you did",
1238
+ answer: "Fill this in",
1239
+ record_field: "This has to be filled in on the record",
1240
+ form: "This step is a form",
1241
+ document: "This step is a document"
1242
+ };
1243
+ var FIELD_SENSITIVITY_LABEL = {
1244
+ public: "Anyone who can open the record",
1245
+ internal: "People in this organization",
1246
+ confidential: "People who have been given the record",
1247
+ restricted: "Owners and administrators only"
1248
+ };
1249
+ var CONTEXT_POLICY_LABEL = {
1250
+ include: "Yes, an assistant can read it",
1251
+ summarize: "Only a summary of it",
1252
+ on_request: "Only when somebody asks for it",
1253
+ exclude: "No, keep it away from assistants"
1254
+ };
1255
+ var STAGE_RULE_ON_FAIL_LABEL = {
1256
+ refuse: "Turn it away",
1257
+ require_approval: "Ask for approval"
1258
+ };
1259
+ var SUBSCRIPTION_CADENCES = exhaustiveValuesOf()(["instant", "hourly", "daily", "weekly"]);
1260
+ var SUBSCRIPTION_CADENCE_LABEL = {
1261
+ instant: "as it happens",
1262
+ hourly: "hourly summary",
1263
+ daily: "daily summary",
1264
+ weekly: "weekly summary"
1265
+ };
1266
+ var SUBSCRIPTION_CHANNEL_VALUES = ["in_app", "email", "sms"];
1267
+ var SUBSCRIPTION_CHANNEL_LABEL = {
1268
+ in_app: "in the app",
1269
+ email: "by email \u2014 only if an address is on the account",
1270
+ sms: "by text \u2014 only if a number is on the account"
1271
+ };
1272
+ var ROLLUP_AGG_VALUES = [
1273
+ "count",
1274
+ "sum",
1275
+ "avg",
1276
+ "min",
1277
+ "max",
1278
+ // AIRTABLE PARITY (lane AT-FORMULA): the aggregates that read the linked values as they are.
1279
+ "countall",
1280
+ "counta",
1281
+ "and",
1282
+ "or",
1283
+ "xor",
1284
+ "arrayjoin",
1285
+ "concatenate",
1286
+ "arrayunique",
1287
+ "arraycompact"
1288
+ ];
1289
+ var ROLLUP_AGG_LABEL = {
1290
+ count: "How many there are",
1291
+ sum: "The total of",
1292
+ avg: "The average of",
1293
+ min: "The smallest",
1294
+ max: "The largest",
1295
+ countall: "How many values, empty ones too",
1296
+ counta: "How many values are filled in",
1297
+ and: "Yes when every value is yes",
1298
+ or: "Yes when any value is yes",
1299
+ xor: "Yes when an odd number are yes",
1300
+ arrayjoin: "All the values, joined with commas",
1301
+ concatenate: "All the values, run together",
1302
+ arrayunique: "Each different value once",
1303
+ arraycompact: "The values that are filled in"
1304
+ };
1305
+ var FORMULA_OP_VALUES = ["concat", "add", "sub", "mul", "div"];
1306
+ var FORMULA_OP_LABEL = {
1307
+ concat: "Join them together",
1308
+ add: "Add them up",
1309
+ sub: "Take the second from the first",
1310
+ mul: "Multiply them",
1311
+ div: "Divide the first by the second"
1312
+ };
1313
+ var FORMULA_OP_JOINS = {
1314
+ concat: true,
1315
+ add: true,
1316
+ sub: false,
1317
+ mul: true,
1318
+ div: false
1319
+ };
1320
+ var FIELD_RULE_KIND_VALUES = ["min", "max", "length", "pattern", "equals_field", "differs_from_field"];
1321
+ var FIELD_RULE_KIND_LABEL = {
1322
+ min: "At least",
1323
+ max: "At most",
1324
+ length: "Number of characters",
1325
+ pattern: "Looks like",
1326
+ equals_field: "Same as the column",
1327
+ differs_from_field: "Different from the column"
1328
+ };
1329
+ var PROPOSED_CHANGE_ACT_VALUES = ["add", "update", "remove"];
1330
+ var PROPOSED_CHANGE_ACT_LABEL = {
1331
+ add: "Add",
1332
+ update: "Update",
1333
+ remove: "Remove"
1334
+ };
1335
+ var BOOKING_PAGE_STATE_VALUES = ["draft", "open", "closed", "full"];
1336
+ var BOOKING_PAGE_STATE_LABEL = {
1337
+ draft: "Not open yet \u2014 nobody can book until you open it.",
1338
+ open: "Open. Anyone with the link can book a time.",
1339
+ closed: "Closed. The link still works and says you are not taking bookings.",
1340
+ full: "Every time you offered is taken."
1341
+ };
1342
+ var ABSENCE_WORD_VALUES = ["never asked", "none", "refused", "conflicting"];
1343
+ var ABSENCE_WORD_LABEL = {
1344
+ "never asked": "never asked",
1345
+ none: "none",
1346
+ refused: "refused",
1347
+ conflicting: "conflicting"
1348
+ };
1349
+
1350
+ // src/FilePicker.tsx
1351
+ import { useCallback as useCallback2, useId, useRef as useRef2, useState as useState4 } from "react";
1352
+ import { Button as Button2, cn as cn6 } from "@ai-matrx/design-system";
1353
+ import { jsx as jsx7, jsxs as jsxs6 } from "react/jsx-runtime";
1354
+ function FilePicker({
1355
+ label,
1356
+ accept,
1357
+ inputLabel,
1358
+ hint,
1359
+ disabled = false,
1360
+ onFile,
1361
+ onClear,
1362
+ chosenName,
1363
+ className
1364
+ }) {
1365
+ const inputId = useId();
1366
+ const input = useRef2(null);
1367
+ const [over, setOver] = useState4(false);
1368
+ const take = useCallback2(
1369
+ (file) => {
1370
+ if (!file || disabled) return;
1371
+ onFile(file);
1372
+ },
1373
+ [disabled, onFile]
1374
+ );
1375
+ const onDrop = useCallback2(
1376
+ (e) => {
1377
+ e.preventDefault();
1378
+ setOver(false);
1379
+ take(e.dataTransfer?.files?.[0]);
1380
+ },
1381
+ [take]
1382
+ );
1383
+ return /* @__PURE__ */ jsxs6(
1384
+ "div",
1385
+ {
1386
+ "data-matrx-file-picker": true,
1387
+ className: cn6("flex min-w-0 flex-col gap-1", className),
1388
+ onDragOver: (e) => {
1389
+ if (disabled) return;
1390
+ e.preventDefault();
1391
+ setOver(true);
1392
+ },
1393
+ onDragLeave: () => setOver(false),
1394
+ onDrop,
1395
+ children: [
1396
+ /* @__PURE__ */ jsxs6(
1397
+ "div",
1398
+ {
1399
+ className: cn6(
1400
+ "flex min-w-0 flex-wrap items-center gap-2 rounded-md border border-dashed px-2 py-1.5",
1401
+ over ? "border-primary bg-primary/5" : "border-border",
1402
+ disabled && "opacity-60"
1403
+ ),
1404
+ children: [
1405
+ /* @__PURE__ */ jsx7(
1406
+ "input",
1407
+ {
1408
+ ref: input,
1409
+ id: inputId,
1410
+ type: "file",
1411
+ "aria-label": inputLabel ?? label,
1412
+ tabIndex: -1,
1413
+ ...accept ? { accept } : {},
1414
+ disabled,
1415
+ className: "sr-only",
1416
+ onChange: (e) => {
1417
+ take(e.target.files?.[0]);
1418
+ e.target.value = "";
1419
+ }
1420
+ }
1421
+ ),
1422
+ /* @__PURE__ */ jsx7(
1423
+ Button2,
1424
+ {
1425
+ type: "button",
1426
+ size: "sm",
1427
+ variant: "outline",
1428
+ disabled,
1429
+ onClick: () => input.current?.click(),
1430
+ children: chosenName ? "Choose a different file" : label
1431
+ }
1432
+ ),
1433
+ chosenName ? /* @__PURE__ */ jsx7("span", { className: "min-w-0 flex-1 truncate text-xs", title: chosenName, children: chosenName }) : /* @__PURE__ */ jsx7("span", { className: "text-xs text-muted-foreground", children: "or drop it here" }),
1434
+ chosenName && onClear ? /* @__PURE__ */ jsx7(Button2, { type: "button", size: "sm", variant: "ghost", disabled, onClick: onClear, children: "Cancel" }) : null
1435
+ ]
1436
+ }
1437
+ ),
1438
+ hint && !chosenName ? /* @__PURE__ */ jsx7("p", { className: "text-xs text-muted-foreground", children: hint }) : null
1439
+ ]
1440
+ }
1441
+ );
1442
+ }
1443
+
1444
+ // src/choiceNudge.ts
1445
+ import { useEffect as useEffect4, useState as useState5 } from "react";
1446
+ import { useOptionalRecordsClient } from "@ai-matrx/records/react";
1447
+ var asked = /* @__PURE__ */ new WeakMap();
1448
+ function choiceNudgeOf(client) {
1449
+ let answer = asked.get(client);
1450
+ if (!answer) {
1451
+ answer = Promise.resolve().then(() => client.choiceNudge()).then(
1452
+ (result) => result.ok ? result.data : "ask",
1453
+ () => "ask"
1454
+ );
1455
+ asked.set(client, answer);
1456
+ }
1457
+ return answer;
1458
+ }
1459
+ function useChoiceNudge(enabled = true) {
1460
+ const client = useOptionalRecordsClient();
1461
+ const [nudge, setNudge] = useState5(null);
1462
+ useEffect4(() => {
1463
+ if (!enabled || !client) return;
1464
+ let live = true;
1465
+ void choiceNudgeOf(client).then((answer) => {
1466
+ if (live) setNudge(answer);
1467
+ });
1468
+ return () => {
1469
+ live = false;
1470
+ };
1471
+ }, [client, enabled]);
1472
+ if (!client) return "ask";
1473
+ return nudge;
1474
+ }
1475
+
1476
+ // src/PickOne.tsx
1477
+ import { useState as useState6 } from "react";
1478
+ import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue, cn as cn7 } from "@ai-matrx/design-system";
1479
+ import { jsx as jsx8, jsxs as jsxs7 } from "react/jsx-runtime";
1480
+ var PICK_ONE_SEARCH_AFTER = 7;
1481
+ var EMPTY = "__records_pick_one_empty__";
1482
+ var inner = (v) => v === "" ? EMPTY : v;
1483
+ var outer = (v) => v === EMPTY ? "" : v;
1484
+ function PickOne({
1485
+ value,
1486
+ onChange,
1487
+ options,
1488
+ label,
1489
+ placeholder,
1490
+ id,
1491
+ className,
1492
+ disabled,
1493
+ attrs
1494
+ }) {
1495
+ const [open, setOpen] = useState6(false);
1496
+ const [search, setSearch] = useState6("");
1497
+ const current = options.find((o) => o.value === value);
1498
+ if (options.length > PICK_ONE_SEARCH_AFTER) {
1499
+ const q = search.trim().toLowerCase();
1500
+ const shown = q === "" ? options : options.filter((o) => o.label.toLowerCase().includes(q));
1501
+ return /* @__PURE__ */ jsx8("span", { className: cn7("inline-flex min-w-0", className), "data-records-pick-one": "search", "data-pick-value": value, ...attrs ?? {}, children: /* @__PURE__ */ jsx8(
1502
+ PickOrAdd,
1503
+ {
1504
+ triggerSize: "compact",
1505
+ triggerLabel: label,
1506
+ triggerText: current?.label ?? placeholder ?? "",
1507
+ triggerId: id,
1508
+ open: open && !disabled,
1509
+ onOpenChange: (next) => {
1510
+ setOpen(next);
1511
+ if (!next) setSearch("");
1512
+ },
1513
+ search,
1514
+ onSearch: setSearch,
1515
+ items: shown.map((o) => ({
1516
+ id: inner(o.value),
1517
+ label: o.label,
1518
+ detail: o.group,
1519
+ picked: o.value === value,
1520
+ attrs: { "data-pick-value": o.value, ...o.group ? { "data-pick-group": o.group } : {} }
1521
+ })),
1522
+ onPick: (picked) => {
1523
+ onChange(outer(picked));
1524
+ setOpen(false);
1525
+ setSearch("");
1526
+ },
1527
+ empty: /* @__PURE__ */ jsx8("p", { className: "p-2 text-xs text-muted-foreground", children: "No match" })
1528
+ }
1529
+ ) });
1530
+ }
1531
+ return /* @__PURE__ */ jsxs7(Select, { value: current ? inner(current.value) : "", onValueChange: (v) => onChange(outer(v)), disabled: disabled ?? false, children: [
1532
+ /* @__PURE__ */ jsx8(
1533
+ SelectTrigger,
1534
+ {
1535
+ id,
1536
+ size: "sm",
1537
+ "aria-label": label,
1538
+ className: cn7("h-7 w-auto min-w-[7rem] text-xs", className),
1539
+ "data-records-pick-one": "list",
1540
+ "data-pick-value": value,
1541
+ ...attrs ?? {},
1542
+ children: /* @__PURE__ */ jsx8(SelectValue, { placeholder })
1543
+ }
1544
+ ),
1545
+ /* @__PURE__ */ jsx8(SelectContent, { children: groupsOf(options).map(
1546
+ ([group, items]) => group ? /* @__PURE__ */ jsxs7(SelectGroup, { children: [
1547
+ /* @__PURE__ */ jsx8(SelectLabel, { children: group }),
1548
+ items.map((o) => /* @__PURE__ */ jsx8(SelectItem, { value: inner(o.value), "data-pick-value": o.value, "data-pick-group": group, children: o.label }, inner(o.value)))
1549
+ ] }, group) : items.map((o) => /* @__PURE__ */ jsx8(SelectItem, { value: inner(o.value), "data-pick-value": o.value, children: o.label }, inner(o.value)))
1550
+ ) })
1551
+ ] });
1552
+ }
1553
+ function groupsOf(options) {
1554
+ const out = [];
1555
+ for (const o of options) {
1556
+ const last = out[out.length - 1];
1557
+ if (last && last[0] === o.group) last[1].push(o);
1558
+ else out.push([o.group, [o]]);
1559
+ }
1560
+ return out;
1561
+ }
1562
+
1563
+ export {
1564
+ NO_RIGHTS,
1565
+ tableRightsAt,
1566
+ NO_SAVED_VIEWS_REASON,
1567
+ NO_MEMBERS_REASON,
1568
+ NO_SHARE_REASON,
1569
+ NO_OPEN_RECORDS_REASON,
1570
+ NO_REASK_REASON,
1571
+ NO_UPLOAD_REASON,
1572
+ RecordsUiProvider,
1573
+ useRecordsUi,
1574
+ useTableRights,
1575
+ useRecordRights,
1576
+ useRowRights,
1577
+ fieldName,
1578
+ tableName,
1579
+ recordName,
1580
+ looksLikeId,
1581
+ rowName,
1582
+ recordNameIn,
1583
+ changedRecordName,
1584
+ rowNameIn,
1585
+ WITHHELD_RECORD_LABEL,
1586
+ UNREAD_RECORD_LABEL,
1587
+ realPlural,
1588
+ singularNoun,
1589
+ pluralNoun,
1590
+ cardTitleField,
1591
+ MACHINE_IDENTITY,
1592
+ isMachineIdentity,
1593
+ machineIdentityIn,
1594
+ ENGINEER_TEXT,
1595
+ isEngineerText,
1596
+ refusalSentence,
1597
+ refusalForAPerson,
1598
+ refusalLineForAPerson,
1599
+ refusalIsMissingInput,
1600
+ displayFormatOf,
1601
+ choiceLooksOf,
1602
+ choiceWord,
1603
+ storedChoiceColor,
1604
+ storedChoiceColorLookup,
1605
+ nextChoiceColor,
1606
+ choiceChipLookOf,
1607
+ fieldToken,
1608
+ bodyFromKeys,
1609
+ bodyForReading,
1610
+ isSignatureField,
1611
+ PARITY_LABEL,
1612
+ PARITY_MADE_OF,
1613
+ editorKindFor,
1614
+ pickableTypeOf,
1615
+ fieldTypeLabel,
1616
+ hintIsMachineIdentity,
1617
+ hintForAPerson,
1618
+ RefusalNotice,
1619
+ RefusalLine,
1620
+ PersonChip,
1621
+ PickOrAdd,
1622
+ recordVersions_exports,
1623
+ PickOne,
1624
+ declareTable,
1625
+ addFields,
1626
+ fieldDeclarationFor,
1627
+ tokenFor,
1628
+ DEFAULT_FIELDS,
1629
+ isValueSet,
1630
+ isKeptTable,
1631
+ tablePickerEntries,
1632
+ usePickerTables,
1633
+ ShowListsToggle,
1634
+ systemStampOf,
1635
+ carriesTimeOfDay,
1636
+ timeOfDayWords,
1637
+ hasTimePart,
1638
+ isDateField,
1639
+ dateFormatFor,
1640
+ dateText,
1641
+ calendarDayOf,
1642
+ calendarDayLabel,
1643
+ dayKeyOf,
1644
+ dayAt,
1645
+ addDays,
1646
+ daysBetween,
1647
+ refusals_exports,
1648
+ WORK_DUE_STATES,
1649
+ DUE_STATE_LABEL,
1650
+ WORK_INBOX_KINDS,
1651
+ WORK_INBOX_KIND_LABEL,
1652
+ WORK_INBOX_KIND_GROUP_LABEL,
1653
+ WORK_APPROVAL_STATES,
1654
+ WORK_APPROVAL_STATE_LABEL,
1655
+ CHECKLIST_REQUIREMENT_KINDS,
1656
+ CHECKLIST_REQUIREMENT_LABEL,
1657
+ FIELD_SENSITIVITY_LABEL,
1658
+ CONTEXT_POLICY_LABEL,
1659
+ STAGE_RULE_ON_FAIL_LABEL,
1660
+ SUBSCRIPTION_CADENCES,
1661
+ SUBSCRIPTION_CADENCE_LABEL,
1662
+ SUBSCRIPTION_CHANNEL_VALUES,
1663
+ SUBSCRIPTION_CHANNEL_LABEL,
1664
+ ROLLUP_AGG_VALUES,
1665
+ ROLLUP_AGG_LABEL,
1666
+ FORMULA_OP_VALUES,
1667
+ FORMULA_OP_LABEL,
1668
+ FORMULA_OP_JOINS,
1669
+ FIELD_RULE_KIND_VALUES,
1670
+ FIELD_RULE_KIND_LABEL,
1671
+ PROPOSED_CHANGE_ACT_VALUES,
1672
+ PROPOSED_CHANGE_ACT_LABEL,
1673
+ BOOKING_PAGE_STATE_VALUES,
1674
+ BOOKING_PAGE_STATE_LABEL,
1675
+ ABSENCE_WORD_VALUES,
1676
+ ABSENCE_WORD_LABEL,
1677
+ FilePicker,
1678
+ choiceNudgeOf,
1679
+ useChoiceNudge
1680
+ };
1681
+ //# sourceMappingURL=chunk-4U2JCICC.js.map