@constructive-io/sheets 0.13.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -148
- package/dist/advanced.cjs +7220 -4030
- package/dist/advanced.cjs.map +1 -1
- package/dist/advanced.d.cts +2 -2
- package/dist/advanced.d.ts +2 -2
- package/dist/advanced.js +5 -5
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.js +3 -3
- package/dist/chunk-CJ4PRA64.js +312 -0
- package/dist/chunk-CJ4PRA64.js.map +1 -0
- package/dist/chunk-II3MSNRO.js +18 -0
- package/dist/chunk-II3MSNRO.js.map +1 -0
- package/dist/{chunk-MXVNIKES.js → chunk-J7KK4UWI.js} +6 -6
- package/dist/chunk-MBSHDF55.js +839 -0
- package/dist/chunk-MBSHDF55.js.map +1 -0
- package/dist/{chunk-ZKANUG3F.js → chunk-MOFFS5WQ.js} +20 -15
- package/dist/chunk-MOFFS5WQ.js.map +1 -0
- package/dist/chunk-VCBY2AMT.js +8920 -0
- package/dist/chunk-VCBY2AMT.js.map +1 -0
- package/dist/{chunk-H5HR5HUJ.js → chunk-ZOQDSOMO.js} +50 -312
- package/dist/chunk-ZOQDSOMO.js.map +1 -0
- package/dist/date-editor-ORCB43ZM.js +346 -0
- package/dist/date-editor-ORCB43ZM.js.map +1 -0
- package/dist/grid-cell-types-YNIVK4hN.d.cts +346 -0
- package/dist/grid-cell-types-YNIVK4hN.d.ts +346 -0
- package/dist/index.cjs +22910 -12084
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1497 -337
- package/dist/index.d.ts +1497 -337
- package/dist/index.js +12833 -6142
- package/dist/index.js.map +1 -1
- package/dist/sheets-context-Bb7ZoNBg.d.cts +436 -0
- package/dist/sheets-context-CPuf31LS.d.ts +436 -0
- package/dist/testing.cjs +1253 -638
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +80 -11
- package/dist/testing.d.ts +80 -11
- package/dist/testing.js +791 -148
- package/dist/testing.js.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-4EZ6A23C.js +0 -44
- package/dist/chunk-4EZ6A23C.js.map +0 -1
- package/dist/chunk-5QPNOKMA.js +0 -4397
- package/dist/chunk-5QPNOKMA.js.map +0 -1
- package/dist/chunk-AYMXT3ME.js +0 -540
- package/dist/chunk-AYMXT3ME.js.map +0 -1
- package/dist/chunk-H5HR5HUJ.js.map +0 -1
- package/dist/chunk-PZL2BCWF.js +0 -168
- package/dist/chunk-PZL2BCWF.js.map +0 -1
- package/dist/chunk-X7DHTSOX.js +0 -21
- package/dist/chunk-X7DHTSOX.js.map +0 -1
- package/dist/chunk-ZKANUG3F.js.map +0 -1
- package/dist/date-editor-ZFNDKYBD.js +0 -358
- package/dist/date-editor-ZFNDKYBD.js.map +0 -1
- package/dist/grid-cell-types-Pbe2m2tE.d.cts +0 -253
- package/dist/grid-cell-types-Pbe2m2tE.d.ts +0 -253
- package/dist/map-picker-ZUGGOIZS.js +0 -290
- package/dist/map-picker-ZUGGOIZS.js.map +0 -1
- package/dist/sheets-context-CY1RmDKL.d.cts +0 -244
- package/dist/sheets-context-Cu3Ec_ca.d.ts +0 -244
- /package/dist/{chunk-MXVNIKES.js.map → chunk-J7KK4UWI.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/relations/relation-navigation.ts","../src/cell-types/column-value.ts","../src/cell-types/cell-registry.ts","../src/cell-types/type-mapping.ts","../src/cell-types/cell-type-resolver.ts","../src/cell-types/column-routing.ts","../src/forms/metadata-hash.ts","../src/forms/model-form.ts","../src/cell-types/field-label.ts","../src/grid/cell-routing.ts","../src/row-identity.ts","../src/adapter/postgraphile-adapter.ts","../src/adapter/use-sheets-adapter.ts","../src/grid/filter-operators.ts","../src/grid/columns/column-layout.ts","../src/grid/view-state/view-state.types.ts","../src/grid/view-state/view-state.ts","../src/grid/feedback/write-errors.ts","../src/grid/feedback/feedback-context.tsx","../src/grid/feedback/feedback-reducer.ts","../src/context/sheets-read-only.tsx","../src/hooks/use-sheets-meta.ts","../src/hooks/use-table-model.ts","../src/cell-model/factories/badges.ts","../src/cell-model/factories/boolean.ts","../src/cell-model/factories/choice.ts","../src/cell-model/factories/datetime.ts","../src/cell-types/shape-kind.ts","../src/grid/sheets.formatters.ts","../src/cell-model/factories/geometry.ts","../src/utils/file.utils.ts","../src/cell-model/factories/image.ts","../src/cell-model/factories/interval.ts","../src/cell-model/factories/number.ts","../src/relations/relation-keys.ts","../src/relations/relation-label.ts","../src/cell-model/factories/relation.ts","../src/cell-model/factories/structured.ts","../src/cell-model/factories/text.ts","../src/cell-model/factories/uri.ts","../src/cell-model/create-sheets-cell.ts","../src/hooks/use-sheets-upload.ts","../src/uploads/column-storage.ts","../src/uploads/storage-catalog.ts","../src/uploads/download-urls.ts","../src/uploads/plane-upload.ts","../src/uploads/bucket-limits.ts","../src/uploads/upload-request.ts","../src/uploads/upload-binding.ts","../src/uploads/upload-config.ts","../src/uploads/file-cell-write.ts","../src/uploads/pending-file-writes.ts","../src/grid/editors/overlay-viewport-guard.tsx","../src/grid-dom/editors/array-editor.tsx","../src/grid/editors/array-editor.tsx","../src/grid-dom/editors/date-editor.tsx","../src/grid-dom/overlay/overlay-pending.tsx","../src/grid/editors/geometry-editor.tsx","../src/utils/map-picker.tsx","../src/utils/module-interop.ts","../src/utils/map-settings.ts","../src/grid/editors/map-load-boundary.tsx","../src/grid-dom/editors/geometry-editor.tsx","../src/grid-dom/editors/image-editor.tsx","../src/grid/editors/image-editor.tsx","../src/uploads/editor/file-dropzone.tsx","../src/uploads/editor/use-editor-focus.ts","../src/uploads/editor/file-entry-row.tsx","../src/hooks/use-sheets-media-url.ts","../src/uploads/editor/use-file-editor.ts","../src/grid/editors/inet-editor.tsx","../src/grid-dom/editors/inet-editor.tsx","../src/grid/editors/interval-editor.tsx","../src/grid-dom/editors/record-editor.tsx","../src/grid-dom/editors/interval-editor.tsx","../src/grid/editors/json-editor.tsx","../src/grid-dom/editors/json-editor.tsx","../src/grid-dom/editors/number-editor.tsx","../src/grid-dom/editors/range-editor.tsx","../src/cell-types/timestamp-text.ts","../src/grid/editors/relation-editor.tsx","../src/relations/relation-editor-body.tsx","../src/relations/relation-create-form.tsx","../src/relations/relation-create.ts","../src/relations/relation-link-list.tsx","../src/relations/relation-picker.tsx","../src/relations/use-relation-editor.ts","../src/grid/filters/filter-value.ts","../src/grid/filters/equality-filter.ts","../src/grid/hooks/history-context.ts","../src/relations/relation-capability.ts","../src/relations/relation-changes.ts","../src/relations/relation-undo.ts","../src/relations/relation-search.ts","../src/relations/use-model-pages.ts","../src/relations/use-relation-links.ts","../src/relations/use-relation-selection.ts","../src/grid-dom/editors/relation-editor.tsx","../src/grid-dom/editors/select-editor.tsx","../src/grid-dom/editors/text-editor.tsx","../src/grid/editors/tsvector-editor.tsx","../src/grid-dom/editors/tsvector-editor.tsx","../src/grid/editors/url-editor.tsx","../src/cell-model/uri-link.ts","../src/grid-dom/editors/url-editor.tsx","../src/grid-dom/editors/value-viewer.tsx","../src/grid-dom/editors/editor-registry-dom.ts"],"sourcesContent":["/**\n * Requests from the relation editor to show something else: another table\n * (for example the table that stores links which need more information than\n * the editor can enter) or one linked record. The relation components never\n * navigate themselves; the host or the record panel decides what opening means.\n */\nimport { createContext, useContext } from 'react';\n\nimport type { SheetsFilterGroup } from '../grid/view-state/view-state.types';\n\nexport interface SheetsOpenTableRequest {\n\t/** `TableModel.key` of the table to open. */\n\ttableKey: string;\n\t/** GraphQL type name of that table. */\n\ttableName: string;\n\t/**\n\t * The rows the user was looking at (the junction rows of this record), as a filter\n\t * group a host passes straight to `<Sheets filters>`; null when no exact filter can be\n\t * built, in which case the host opens the table unfiltered.\n\t */\n\tfilters: SheetsFilterGroup | null;\n\t/** Why the editor asks: the links live in a table with more fields than the editor can fill. */\n\treason: 'linked-records';\n}\n\nexport type SheetsOpenTableHandler = (request: SheetsOpenTableRequest) => void;\n\nexport const SheetsOpenTableContext = createContext<SheetsOpenTableHandler | null>(null);\n\n/** The host's handler for opening another table, or null when the host has none. */\nexport function useOpenTableHandler(): SheetsOpenTableHandler | null {\n\treturn useContext(SheetsOpenTableContext);\n}\n\n/** A request to show one linked record, for example in the record panel's navigation stack. */\nexport interface SheetsOpenRecordRequest {\n\t/** `TableModel.key` of the record's table. */\n\ttableKey: string;\n\t/** GraphQL type name of that table. */\n\ttableName: string;\n\t/** Primary-key values of the record, by field name. */\n\tkey: Readonly<Record<string, unknown>>;\n\t/** The record's label, for a title while it loads. */\n\tlabel: string;\n}\n\nexport type SheetsOpenRecordHandler = (request: SheetsOpenRecordRequest) => void;\n\nexport const SheetsOpenRecordContext = createContext<SheetsOpenRecordHandler | null>(null);\n\n/** The host's handler for opening a linked record, or null when the host has none. */\nexport function useOpenRecordHandler(): SheetsOpenRecordHandler | null {\n\treturn useContext(SheetsOpenRecordContext);\n}\n","// Parse, validate and format one column value, driven by the table model.\n//\n// Every write the grid makes (an editor commit, a paste, a fill, a clear, an undo,\n// a bulk edit, a draft cell) passes through `parseColumnInput`, so the editors and\n// the clipboard share one set of rules. A value that does not fit the column is\n// rejected with a reason the user can read; it is never written as something else.\n//\n// Wire facts this module respects:\n// - whole numbers beyond 2^53 (`bigint`) and exact decimals (`decimal`) are decimal\n// strings and never pass through `Number()`;\n// - enum values are written as their wire value; labels are display text;\n// - a text column that cannot be empty writes '' when cleared, any other cleared\n// column writes null (or is refused when it requires a value).\n\nimport type { ColumnModel, ColumnOption, ColumnValueKind, InputFieldModel, InputValueModel } from '@constructive-io/data';\n\nexport type ColumnInputResult = { ok: true; value: unknown } | { ok: false; reason: string };\n\nexport interface ColumnInputOptions {\n\t/**\n\t * The input is text the user typed or pasted, so JSON and lists are read from\n\t * the text. False (the default) for a value an editor, a fill or an undo produced.\n\t */\n\tfromText?: boolean;\n\t/**\n\t * The value is for a record not created yet (a new row, the new-record form): clearing a\n\t * required text field keeps '' there, since the create checks the required fields as a whole.\n\t */\n\tcreating?: boolean;\n}\n\n/** Why a value of a view-only kind cannot be written. */\nexport const VIEW_ONLY_REASON = 'Values of this kind can be viewed and copied, but not changed here.';\n\nconst ok = (value: unknown): ColumnInputResult => ({ ok: true, value });\nconst fail = (reason: string): ColumnInputResult => ({ ok: false, reason });\n\nconst VIEW_ONLY_KINDS: ReadonlySet<ColumnValueKind> = new Set(['binary', 'vector', 'fulltext', 'unknown']);\nconst TEXT_LIKE_KINDS: ReadonlySet<ColumnValueKind> = new Set(['text', 'bitstring', 'network', 'path']);\n\nconst INT32_MIN = -2147483648;\nconst INT32_MAX = 2147483647;\n// Built from strings, not bigint literals, so hosts that compile for an older target build this file too.\nconst INT64_MIN = BigInt('-9223372036854775808');\nconst INT64_MAX = BigInt('9223372036854775807');\n\nconst WHOLE_RE = /^[+-]?\\d+$/;\nconst DECIMAL_RE = /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)$/;\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst TIME_RE = /^(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.\\d{1,6})?)?(?:Z|[+-]\\d{2}(?::?\\d{2})?)?$/;\nconst DATETIME_RE = /^\\d{4}-\\d{2}-\\d{2}(?:[T ]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}(?::?\\d{2})?)?)?$/;\nconst BITS_RE = /^[01]*$/;\nconst INTERVAL_FIELDS = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] as const;\nconst INTERVAL_TEXT_UNITS: Record<string, (typeof INTERVAL_FIELDS)[number]> = {\n\ty: 'years',\n\tmo: 'months',\n\td: 'days',\n\th: 'hours',\n\tm: 'minutes',\n\ts: 'seconds',\n};\n\n/** The limits a value is checked against; a column or one input field supplies them. */\ninterface ValueRules {\n\tkind: ColumnValueKind;\n\toptions: readonly ColumnOption[] | null;\n\tmaxLength: number | null;\n\tprecision: number | null;\n\tscale: number | null;\n\t/** The whole numbers an integer column holds; null means the GraphQL `Int` range. */\n\tintegerBounds: { min: number; max: number } | null;\n\t/** An amount of money: the text it is shown as (\"$1,234.56\") is read too. */\n\tcurrency: boolean;\n\tinput: InputValueModel | null;\n}\n\nfunction rulesOf(column: ColumnModel): ValueRules {\n\tconst { value } = column;\n\treturn {\n\t\tkind: value.kind,\n\t\toptions: value.options,\n\t\tmaxLength: value.maxLength,\n\t\tprecision: value.precision,\n\t\tscale: value.scale,\n\t\tintegerBounds: value.integerBounds ?? null,\n\t\tcurrency: value.semantic === 'currency',\n\t\tinput: value.input,\n\t};\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isBlank(value: unknown): boolean {\n\treturn value === null || value === undefined || (typeof value === 'string' && value.trim() === '');\n}\n\nfunction characterCount(text: string): number {\n\treturn Array.from(text).length;\n}\n\nfunction parseJsonText(text: string): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: JSON.parse(text) };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\n/** Text of a primitive; null for an object (an object is never silently turned into text). */\nfunction primitiveText(value: unknown): string | null {\n\tif (typeof value === 'string') return value;\n\tif (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') return String(value);\n\treturn null;\n}\n\n// ─── Choices ────────────────────────────────────────────────────────────────\n\n/** Find the option a value names: its wire value first, then its label, then either ignoring case. */\nexport function findColumnOption(options: readonly ColumnOption[], input: string): ColumnOption | null {\n\tconst exact = options.find((option) => option.value === input) ?? options.find((option) => option.label === input);\n\tif (exact) return exact;\n\tconst folded = input.toLowerCase();\n\treturn options.find((option) => option.value.toLowerCase() === folded || option.label.toLowerCase() === folded) ?? null;\n}\n\nfunction parseChoice(rules: ValueRules, input: unknown): ColumnInputResult {\n\tconst text = primitiveText(input)?.trim();\n\tif (text === undefined) return fail('Choose one of the listed values.');\n\tconst option = findColumnOption(rules.options ?? [], text);\n\treturn option ? ok(option.value) : fail(`\"${text}\" is not one of the listed values.`);\n}\n\n// ─── Numbers ────────────────────────────────────────────────────────────────\n\nconst TOO_LARGE = 'This number is too large for this field.';\nconst TOO_SMALL = 'This number is too small for this field.';\n\nfunction parseInteger(rules: ValueRules, input: unknown): ColumnInputResult {\n\tconst text = primitiveText(input)?.trim();\n\tif (text === undefined || !WHOLE_RE.test(text)) return fail('Enter a whole number.');\n\tconst value = Number(text);\n\tconst { min, max } = rules.integerBounds ?? { min: INT32_MIN, max: INT32_MAX };\n\tif (value > max) return fail(TOO_LARGE);\n\tif (value < min) return fail(TOO_SMALL);\n\treturn ok(value);\n}\n\nfunction parseBigInteger(input: unknown): ColumnInputResult {\n\tif (typeof input === 'number' && !Number.isSafeInteger(input)) return fail('Enter a whole number.');\n\tconst text = primitiveText(input)?.trim();\n\tif (text === undefined || !WHOLE_RE.test(text)) return fail('Enter a whole number.');\n\tconst exact = BigInt(text);\n\tif (exact > INT64_MAX) return fail(TOO_LARGE);\n\tif (exact < INT64_MIN) return fail(TOO_SMALL);\n\treturn ok(text.startsWith('+') ? text.slice(1) : text);\n}\n\n/** Digits before and after the decimal point, without sign and leading zeros. */\nfunction decimalDigits(text: string): { whole: number; fraction: number } {\n\tconst unsigned = text.replace(/^[+-]/, '');\n\tconst [wholePart = '', fractionPart = ''] = unsigned.split('.');\n\treturn { whole: wholePart.replace(/^0+/, '').length, fraction: fractionPart.length };\n}\n\nfunction parseDecimal(rules: ValueRules, input: unknown): ColumnInputResult {\n\tif (typeof input === 'number' && !Number.isFinite(input)) return fail('Enter a number.');\n\tconst text = primitiveText(input)?.trim();\n\tif (text === undefined) return fail('Enter a number.');\n\tconst special = /^(nan|[+-]?infinity)$/i.exec(text);\n\tif (special) {\n\t\tconst lower = text.toLowerCase();\n\t\treturn ok(lower === 'nan' ? 'NaN' : lower.startsWith('-') ? '-Infinity' : 'Infinity');\n\t}\n\tif (!DECIMAL_RE.test(text)) return fail('Enter a number, for example 12.50.');\n\tif (rules.precision != null) {\n\t\tconst scale = rules.scale ?? 0;\n\t\tconst { whole, fraction } = decimalDigits(text);\n\t\tif (whole > rules.precision - scale) return fail(`Use at most ${rules.precision - scale} digits before the decimal point.`);\n\t\tif (fraction > scale) {\n\t\t\treturn fail(scale === 0 ? 'Enter a whole number.' : `Use at most ${scale} digits after the decimal point.`);\n\t\t}\n\t}\n\treturn ok(text.startsWith('+') ? text.slice(1) : text);\n}\n\n// A currency symbol or code before or after the amount: $, US$, €, USD.\nconst MONEY_TEXT = /^([+-]?)\\s*(?:[A-Z]{0,3}\\p{Sc}|[A-Z]{3}\\s)?\\s*([+-]?)\\s*([\\d,]*(?:\\.\\d+)?)\\s*(?:\\p{Sc}|\\s[A-Z]{3})?$/u;\nconst GROUPED_DIGITS = /^(?:\\d{1,3}(?:,\\d{3})+|\\d+)(?:\\.\\d+)?$|^\\.\\d+$/;\n\n/**\n * The plain number in money text as Postgres and the grid print it (\"$1,234.56\", \"-$5\",\n * \"($3.00)\"), or the text unchanged when it is not one. Commas only group thousands.\n */\nfunction moneyInput(rules: ValueRules, input: unknown): unknown {\n\tif (!rules.currency || typeof input !== 'string') return input;\n\tlet text = input.trim();\n\tconst bracketed = /^\\((.*)\\)$/.exec(text);\n\tif (bracketed) text = bracketed[1]!.trim();\n\tconst match = MONEY_TEXT.exec(text);\n\tif (!match) return input;\n\tconst [, before = '', after = '', amount = ''] = match;\n\tif ((before && after) || !GROUPED_DIGITS.test(amount)) return input;\n\tconst negative = (before || after) === '-' || Boolean(bracketed);\n\treturn `${negative ? '-' : ''}${amount.replace(/,/g, '')}`;\n}\n\nfunction parseFloatValue(input: unknown): ColumnInputResult {\n\tif (typeof input === 'number') return Number.isFinite(input) ? ok(input) : fail('Enter a finite number.');\n\tconst text = primitiveText(input)?.trim();\n\tif (text === undefined || !DECIMAL_RE.test(text.replace(/e[+-]?\\d+$/i, ''))) return fail('Enter a number.');\n\tconst value = Number(text);\n\treturn Number.isFinite(value) ? ok(value) : fail('Enter a finite number.');\n}\n\n// ─── Other scalars ──────────────────────────────────────────────────────────\n\nconst TRUE_WORDS = new Set(['true', 't', 'yes', 'y', 'on', '1']);\nconst FALSE_WORDS = new Set(['false', 'f', 'no', 'n', 'off', '0']);\n\nfunction parseBoolean(input: unknown): ColumnInputResult {\n\tif (typeof input === 'boolean') return ok(input);\n\tconst text = primitiveText(input)?.trim().toLowerCase();\n\tif (text !== undefined && TRUE_WORDS.has(text)) return ok(true);\n\tif (text !== undefined && FALSE_WORDS.has(text)) return ok(false);\n\treturn fail('Enter true or false.');\n}\n\nfunction parseText(rules: ValueRules, input: unknown): ColumnInputResult {\n\tconst text = typeof input === 'string' ? input : primitiveText(input) ?? (isPlainObject(input) || Array.isArray(input) ? JSON.stringify(input) : null);\n\tif (text === null) return fail('Enter text.');\n\tif (rules.maxLength != null && characterCount(text) > rules.maxLength) {\n\t\treturn fail(`Use at most ${rules.maxLength} characters.`);\n\t}\n\treturn ok(text);\n}\n\nfunction parseBits(rules: ValueRules, input: unknown): ColumnInputResult {\n\tconst text = primitiveText(input)?.trim();\n\tif (text === undefined || !BITS_RE.test(text)) return fail('Use only the digits 0 and 1.');\n\tif (rules.maxLength != null && text.length > rules.maxLength) return fail(`Use at most ${rules.maxLength} digits.`);\n\treturn ok(text);\n}\n\nfunction parseUuid(input: unknown): ColumnInputResult {\n\tconst text = primitiveText(input)?.trim();\n\treturn text !== undefined && UUID_RE.test(text)\n\t\t? ok(text)\n\t\t: fail('Enter an identifier like 123e4567-e89b-12d3-a456-426614174000.');\n}\n\nfunction parseDate(input: unknown): ColumnInputResult {\n\tconst text = primitiveText(input)?.trim();\n\tconst match = text === undefined ? null : DATE_RE.exec(text);\n\tif (!text || !match) return fail('Enter a date like 2024-01-31.');\n\tconst [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];\n\tconst probe = new Date(Date.UTC(year, month - 1, day));\n\tif (probe.getUTCFullYear() !== year || probe.getUTCMonth() !== month - 1 || probe.getUTCDate() !== day) {\n\t\treturn fail('Enter a date like 2024-01-31.');\n\t}\n\treturn ok(text);\n}\n\nfunction parseTime(input: unknown): ColumnInputResult {\n\tconst text = primitiveText(input)?.trim();\n\tconst match = text === undefined ? null : TIME_RE.exec(text);\n\tif (!text || !match) return fail('Enter a time like 13:45 or 13:45:30.');\n\tconst [hours, minutes, seconds] = [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)];\n\tif (hours > 23 || minutes > 59 || seconds > 59) return fail('Enter a time like 13:45 or 13:45:30.');\n\treturn ok(text);\n}\n\nfunction parseDatetime(input: unknown): ColumnInputResult {\n\tconst text = primitiveText(input)?.trim();\n\tif (!text || !DATETIME_RE.test(text) || Number.isNaN(Date.parse(text.replace(' ', 'T')))) {\n\t\treturn fail('Enter a date and time like 2024-01-31T13:45.');\n\t}\n\treturn ok(text);\n}\n\nfunction parseNetwork(input: unknown): ColumnInputResult {\n\tconst text = primitiveText(input)?.trim();\n\treturn text ? ok(text) : fail('Enter an address.');\n}\n\n// ─── Structured values ──────────────────────────────────────────────────────\n\n/** Read an object from a value, or from its JSON text when the input is text. */\nfunction objectInput(input: unknown, fromText: boolean): Record<string, unknown> | null {\n\tif (isPlainObject(input)) return input;\n\tif (typeof input === 'string' && (fromText || input.trim().startsWith('{'))) {\n\t\tconst parsed = parseJsonText(input.trim());\n\t\treturn parsed.ok && isPlainObject(parsed.value) ? parsed.value : null;\n\t}\n\treturn null;\n}\n\n/** Rules for a nested input field, from its GraphQL type; null when the type is not one the grid knows. */\nfunction fieldRules(value: InputValueModel): ValueRules | null {\n\tconst kind = kindOfScalar(value);\n\tif (!kind) return null;\n\treturn {\n\t\tkind,\n\t\toptions: value.enumValues ? value.enumValues.map((entry) => ({ value: entry, label: entry })) : null,\n\t\tmaxLength: null,\n\t\tprecision: null,\n\t\tscale: null,\n\t\tintegerBounds: null,\n\t\tcurrency: false,\n\t\tinput: value,\n\t};\n}\n\n/** Value kind of a nested input field. Only the standard scalars are known; any other value passes as given. */\nfunction kindOfScalar(value: InputValueModel): ColumnValueKind | null {\n\tif (value.shape === 'enum') return 'enum';\n\tif (value.shape === 'object') return 'composite';\n\tswitch (value.typeName) {\n\t\tcase 'Int':\n\t\t\treturn 'integer';\n\t\tcase 'Float':\n\t\t\treturn 'float';\n\t\tcase 'BigInt':\n\t\t\treturn 'bigint';\n\t\tcase 'BigFloat':\n\t\t\treturn 'decimal';\n\t\tcase 'Boolean':\n\t\t\treturn 'boolean';\n\t\tcase 'String':\n\t\t\treturn 'text';\n\t\tcase 'UUID':\n\t\t\treturn 'uuid';\n\t\tcase 'Date':\n\t\t\treturn 'date';\n\t\tcase 'Datetime':\n\t\t\treturn 'datetime';\n\t\tcase 'Time':\n\t\t\treturn 'time';\n\t\tcase 'JSON':\n\t\t\treturn 'json';\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/** Parse each field of an input object by its own type. Unknown fields are refused. */\nfunction parseFields(\n\tfields: readonly InputFieldModel[],\n\tinput: Record<string, unknown>,\n\tfromText: boolean,\n): ColumnInputResult {\n\tconst known = new Map(fields.map((field) => [field.name, field] as const));\n\tconst out: Record<string, unknown> = {};\n\tfor (const [name, raw] of Object.entries(input)) {\n\t\tif (name === '__typename') continue;\n\t\tconst field = known.get(name);\n\t\tif (!field) return fail(`\"${name}\" is not part of this value.`);\n\t\tif (raw === undefined) continue;\n\t\tif (raw === null) {\n\t\t\tif (field.required) return fail(`\"${name}\" needs a value.`);\n\t\t\tout[name] = null;\n\t\t\tcontinue;\n\t\t}\n\t\tconst rules = fieldRules(field.value);\n\t\tconst parsed = rules ? parseRules(rules, raw, fromText) : ok(raw);\n\t\tif (parsed.ok === false) return fail(`${name}: ${parsed.reason}`);\n\t\tout[name] = parsed.value;\n\t}\n\tfor (const field of fields) {\n\t\tif (field.required && out[field.name] === undefined) return fail(`\"${field.name}\" needs a value.`);\n\t}\n\treturn ok(out);\n}\n\nfunction parseComposite(rules: ValueRules, input: unknown, fromText: boolean): ColumnInputResult {\n\tconst object = objectInput(input, fromText);\n\tif (!object) return fail('Enter the value as a set of named fields.');\n\tconst fields = rules.input?.fields;\n\tif (!fields) {\n\t\tconst { __typename: _typename, ...rest } = object;\n\t\treturn ok(rest);\n\t}\n\treturn parseFields(fields, object, fromText);\n}\n\n/** Read \"1y 2mo 3d 4h 5m 6s\" (the cell's display form) into interval fields. */\nfunction intervalFromText(text: string): Record<string, number> | null {\n\tconst parts = text.trim().split(/\\s+/);\n\tconst out: Record<string, number> = {};\n\tfor (const part of parts) {\n\t\tconst match = /^(-?\\d+(?:\\.\\d+)?)(mo|y|d|h|m|s)$/.exec(part);\n\t\tif (!match) return null;\n\t\tout[INTERVAL_TEXT_UNITS[match[2]]] = Number(match[1]);\n\t}\n\treturn out;\n}\n\nfunction parseInterval(rules: ValueRules, input: unknown, fromText: boolean): ColumnInputResult {\n\tconst object =\n\t\tobjectInput(input, fromText) ?? (typeof input === 'string' ? intervalFromText(input) : null);\n\tif (!object) return fail('Enter a duration like 1d 2h 30m.');\n\tconst out: Record<string, number> = {};\n\tfor (const name of INTERVAL_FIELDS) {\n\t\tconst raw = object[name];\n\t\tif (raw === undefined || raw === null) {\n\t\t\tout[name] = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tconst value = typeof raw === 'number' ? raw : Number(primitiveText(raw)?.trim() ?? NaN);\n\t\tif (!Number.isFinite(value)) return fail(`${name}: enter a number.`);\n\t\tif (name !== 'seconds' && !Number.isInteger(value)) return fail(`${name}: enter a whole number.`);\n\t\tout[name] = value;\n\t}\n\tconst unknownField = Object.keys(object).find(\n\t\t(name) => name !== '__typename' && !(INTERVAL_FIELDS as readonly string[]).includes(name),\n\t);\n\tif (unknownField) return fail(`\"${unknownField}\" is not part of a duration.`);\n\tconst accepted = rules.input?.fields?.map((field) => field.name);\n\tif (accepted) for (const name of Object.keys(out)) if (!accepted.includes(name)) delete out[name];\n\treturn ok(out);\n}\n\nfunction parsePoint(input: unknown, fromText: boolean): ColumnInputResult {\n\tlet object = objectInput(input, fromText);\n\tif (!object && typeof input === 'string') {\n\t\tconst match = /^\\(?\\s*(-?[\\d.]+(?:e[+-]?\\d+)?)\\s*,\\s*(-?[\\d.]+(?:e[+-]?\\d+)?)\\s*\\)?$/i.exec(input.trim());\n\t\tif (match) object = { x: match[1], y: match[2] };\n\t}\n\tif (!object) return fail('Enter a point like 1.5, 2.');\n\tconst x = parseFloatValue(object.x);\n\tconst y = parseFloatValue(object.y);\n\tif (!x.ok || !y.ok) return fail('Enter a point like 1.5, 2.');\n\treturn ok({ x: x.value, y: y.value });\n}\n\nfunction parseGeometry(input: unknown, fromText: boolean): ColumnInputResult {\n\tconst object = objectInput(input, fromText);\n\tconst shape = object && isPlainObject(object.geojson) ? object.geojson : object;\n\tif (!shape || typeof shape.type !== 'string') return fail('Enter a GeoJSON shape.');\n\treturn ok(shape);\n}\n\n/** Rules of a range bound value, from the range input's `start.value` field. */\nfunction boundRules(rules: ValueRules): ValueRules | null {\n\tconst start = rules.input?.fields?.find((field) => field.name === 'start');\n\tconst value = start?.value.fields?.find((field) => field.name === 'value');\n\treturn value ? fieldRules(value.value) : null;\n}\n\nfunction parseBound(bound: unknown, rules: ValueRules | null, fromText: boolean): ColumnInputResult {\n\tif (bound === null || bound === undefined) return ok(null);\n\tif (!isPlainObject(bound)) return fail('Each end of a range needs a value and whether it is included.');\n\tif (bound.value === null || bound.value === undefined) return ok(null);\n\tconst parsed = rules ? parseRules(rules, bound.value, fromText) : ok(bound.value);\n\tif (parsed.ok === false) return parsed;\n\treturn ok({ value: parsed.value, inclusive: bound.inclusive !== false });\n}\n\nfunction parseRange(rules: ValueRules, input: unknown, fromText: boolean): ColumnInputResult {\n\tconst object = objectInput(input, fromText);\n\tif (!object) return fail('Enter a range with a start and an end.');\n\tconst valueRules = boundRules(rules);\n\tconst start = parseBound(object.start, valueRules, fromText);\n\tif (start.ok === false) return fail(`Start: ${start.reason}`);\n\tconst end = parseBound(object.end, valueRules, fromText);\n\tif (end.ok === false) return fail(`End: ${end.reason}`);\n\treturn ok({ start: start.value, end: end.value });\n}\n\nfunction parseJson(input: unknown, fromText: boolean): ColumnInputResult {\n\tif (!fromText || typeof input !== 'string') return ok(input);\n\tconst parsed = parseJsonText(input.trim());\n\treturn parsed.ok ? ok(parsed.value) : fail('Enter valid JSON.');\n}\n\n// ─── Dispatch ───────────────────────────────────────────────────────────────\n\n/** Parse one non-empty value by its kind. */\nfunction parseRules(rules: ValueRules, input: unknown, fromText: boolean): ColumnInputResult {\n\tif (rules.options && rules.kind !== 'file') return parseChoice(rules, input);\n\tswitch (rules.kind) {\n\t\tcase 'text':\n\t\t\treturn parseText(rules, input);\n\t\tcase 'integer':\n\t\t\treturn parseInteger(rules, input);\n\t\tcase 'bigint':\n\t\t\treturn parseBigInteger(input);\n\t\tcase 'decimal':\n\t\t\treturn parseDecimal(rules, moneyInput(rules, input));\n\t\tcase 'float':\n\t\t\treturn parseFloatValue(moneyInput(rules, input));\n\t\tcase 'boolean':\n\t\t\treturn parseBoolean(input);\n\t\tcase 'uuid':\n\t\t\treturn parseUuid(input);\n\t\tcase 'date':\n\t\t\treturn parseDate(input);\n\t\tcase 'time':\n\t\t\treturn parseTime(input);\n\t\tcase 'datetime':\n\t\t\treturn parseDatetime(input);\n\t\tcase 'interval':\n\t\t\treturn parseInterval(rules, input, fromText);\n\t\tcase 'json':\n\t\t\treturn parseJson(input, fromText);\n\t\tcase 'enum':\n\t\t\treturn parseChoice(rules, input);\n\t\tcase 'bitstring':\n\t\t\treturn parseBits(rules, input);\n\t\tcase 'network':\n\t\tcase 'path':\n\t\t\treturn parseNetwork(input);\n\t\tcase 'geometry':\n\t\t\treturn parseGeometry(input, fromText);\n\t\tcase 'point':\n\t\t\treturn parsePoint(input, fromText);\n\t\tcase 'range':\n\t\t\treturn parseRange(rules, input, fromText);\n\t\tcase 'composite':\n\t\t\treturn parseComposite(rules, input, fromText);\n\t\t// File values are owned by the upload flow; they pass unchanged.\n\t\tcase 'file':\n\t\t\treturn ok(input);\n\t\tdefault:\n\t\t\treturn fail(VIEW_ONLY_REASON);\n\t}\n}\n\n/**\n * What clearing the column writes: null, an empty list, '' or a refusal. A text column that\n * cannot be null clears to '' only when its schema gives it a default (DEFAULT '' says empty\n * is fine) or the record is not created yet; a required field of a saved record is refused.\n */\nfunction clearedValue(column: ColumnModel, creating: boolean): ColumnInputResult {\n\tif (column.value.isArray) return column.nullable ? ok(null) : ok([]);\n\tif (column.nullable) return ok(null);\n\tif (column.value.kind === 'text' && !column.value.options && (column.hasDefault || creating)) return ok('');\n\treturn fail('This field needs a value.');\n}\n\n/** Split list text: a JSON array, else one element per comma. */\nfunction listFromText(text: string): unknown[] | null {\n\tconst trimmed = text.trim();\n\tif (trimmed.startsWith('[')) {\n\t\tconst parsed = parseJsonText(trimmed);\n\t\treturn parsed.ok && Array.isArray(parsed.value) ? parsed.value : null;\n\t}\n\treturn trimmed.split(',').map((element) => element.trim());\n}\n\nfunction parseList(column: ColumnModel, input: unknown, fromText: boolean): ColumnInputResult {\n\tconst elements = Array.isArray(input) ? input : typeof input === 'string' ? listFromText(input) : null;\n\tif (!elements) return fail('Enter a list of values.');\n\tconst rules = rulesOf(column);\n\tconst out: unknown[] = [];\n\tfor (const [index, element] of elements.entries()) {\n\t\tif (element === null || element === undefined) {\n\t\t\tout.push(null);\n\t\t\tcontinue;\n\t\t}\n\t\tconst parsed = parseRules(rules, element, fromText || typeof element === 'string');\n\t\tif (parsed.ok === false) return fail(`Item ${index + 1}: ${parsed.reason}`);\n\t\tout.push(parsed.value);\n\t}\n\treturn ok(out);\n}\n\n/**\n * Turn a user's input into the value the column stores, or say why it does not fit.\n * Empty input clears the column (see `clearedValue`). The result is still encoded by\n * the write codec (`encodeWriteValues`) before it is sent.\n */\nexport function parseColumnInput(column: ColumnModel, input: unknown, options: ColumnInputOptions = {}): ColumnInputResult {\n\tconst fromText = options.fromText ?? false;\n\tif (VIEW_ONLY_KINDS.has(column.value.kind)) return fail(VIEW_ONLY_REASON);\n\tconst keepsBlankText = TEXT_LIKE_KINDS.has(column.value.kind) && typeof input === 'string' && input !== '';\n\tif (input === undefined || input === null || (!keepsBlankText && isBlank(input))) return clearedValue(column, options.creating ?? false);\n\tif (column.value.isArray) return parseList(column, input, fromText);\n\treturn parseRules(rulesOf(column), input, fromText);\n}\n\n// ─── Formatting ─────────────────────────────────────────────────────────────\n\n/** Label of a stored choice value; an unknown stored value shows as it is. */\nexport function choiceLabel(column: ColumnModel | null | undefined, value: unknown): string {\n\tconst text = primitiveText(value) ?? '';\n\treturn column?.value.options?.find((option) => option.value === text)?.label ?? text;\n}\n\n/**\n * Text for one value when it leaves the grid (copy, export). Structured values and\n * JSON are written as JSON so a paste reads them back exactly; choices use their label.\n */\nexport function formatColumnValue(column: ColumnModel | null | undefined, value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\tif (column?.value.kind === 'json') return JSON.stringify(value);\n\tif (column?.value.options) {\n\t\treturn Array.isArray(value) ? JSON.stringify(value.map((entry) => (entry == null ? null : choiceLabel(column, entry)))) : choiceLabel(column, value);\n\t}\n\tif (typeof value === 'object') return JSON.stringify(value);\n\treturn String(value);\n}\n\n/**\n * The next value of a toggled boolean cell: checked and unchecked flip, and an empty\n * cell becomes checked. A toggle never empties a cell, so a click on an unchecked box\n * checks it; Delete clears a cell that accepts no value, and the record panel offers\n * Empty as a choice of its own.\n */\nexport function nextToggleValue(current: unknown): boolean {\n\treturn current !== true;\n}\n\n/** Copy text of one cell: its column's format when the table model knows the column, else plain text. */\nexport function copyText(columns: readonly ColumnModel[] | null | undefined, colKey: string, value: unknown): string {\n\tconst column = columns?.find((candidate) => candidate.name === colKey);\n\tif (column) return formatColumnValue(column, value);\n\tif (value === null || value === undefined) return '';\n\treturn typeof value === 'object' ? JSON.stringify(value) : String(value);\n}\n","import type { CellType } from './types';\n\nimport type { CellPlugin, CellRegistryEntry, CellRenderer } from './types';\n\nclass CellRegistryClass {\n\tprivate entries = new Map<CellType, CellRegistryEntry>();\n\tprivate plugins = new Map<string, CellPlugin>();\n\n\t// Register a cell renderer for a cell type\n\tregister(entry: CellRegistryEntry): void {\n\t\tthis.entries.set(entry.type, entry);\n\t}\n\n\t// Register multiple entries at once\n\tregisterBatch(entries: CellRegistryEntry[]): void {\n\t\tentries.forEach((entry) => this.register(entry));\n\t}\n\n\t// Get cell renderer for a type\n\tget(type: CellType): CellRegistryEntry | undefined {\n\t\treturn this.entries.get(type);\n\t}\n\n\t// Get all registered cell types\n\tgetAll(): CellRegistryEntry[] {\n\t\treturn Array.from(this.entries.values());\n\t}\n\n\t// Get cell component for a type\n\tgetComponent(type: CellType): CellRenderer | undefined {\n\t\tconst entry = this.entries.get(type);\n\t\treturn entry?.component;\n\t}\n\n\t// Find cell entry by match function\n\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\tfindByMatch(metadata: {\n\t\tgqlType: string;\n\t\tisArray: boolean;\n\t\tpgAlias?: string | null;\n\t\tpgType?: string | null;\n\t\tsubtype?: string | null;\n\t\tfieldName?: string;\n\t}): CellRegistryEntry | undefined {\n\t\t// Iterate through all entries and find the first one with a matching match function\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tif (entry.match && entry.match(metadata)) {\n\t\t\t\treturn entry;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Get cell component using match function first, then fallback to type\n\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\tgetComponentWithMatch(\n\t\ttype: CellType,\n\t\tmetadata?: {\n\t\t\tgqlType: string;\n\t\t\tisArray: boolean;\n\t\t\tpgAlias?: string | null;\n\t\t\tpgType?: string | null;\n\t\t\tsubtype?: string | null;\n\t\t\tfieldName?: string;\n\t\t},\n\t): CellRenderer | undefined {\n\t\t// First try to find by match function if metadata is provided\n\t\tif (metadata) {\n\t\t\tconst matchedEntry = this.findByMatch(metadata);\n\t\t\tif (matchedEntry) {\n\t\t\t\treturn matchedEntry.component;\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to regular type-based lookup\n\t\treturn this.getComponent(type);\n\t}\n\n\t// Get edit component for a type\n\tgetEditComponent(type: CellType): CellRenderer | undefined {\n\t\tconst entry = this.entries.get(type);\n\t\treturn entry?.editComponent || entry?.component;\n\t}\n\n\t// Check if a type is registered\n\thas(type: CellType): boolean {\n\t\treturn this.entries.has(type);\n\t}\n\n\t// Install a plugin\n\tinstallPlugin(plugin: CellPlugin): void {\n\t\tif (this.plugins.has(plugin.name)) {\n\t\t\tconsole.warn(`Plugin ${plugin.name} is already installed`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Install plugin cells\n\t\tplugin.cells.forEach((cell) => this.register(cell));\n\n\t\t// Run plugin install hook\n\t\tplugin.install?.();\n\n\t\tthis.plugins.set(plugin.name, plugin);\n\t}\n\n\t// Uninstall a plugin\n\tuninstallPlugin(pluginName: string): void {\n\t\tconst plugin = this.plugins.get(pluginName);\n\t\tif (!plugin) {\n\t\t\tconsole.warn(`Plugin ${pluginName} is not installed`);\n\t\t\treturn;\n\t\t}\n\n\t\t// Remove plugin cells\n\t\tplugin.cells.forEach((cell) => this.entries.delete(cell.type));\n\n\t\t// Run plugin uninstall hook\n\t\tplugin.uninstall?.();\n\n\t\tthis.plugins.delete(pluginName);\n\t}\n\n\t// Get installed plugins\n\tgetInstalledPlugins(): CellPlugin[] {\n\t\treturn Array.from(this.plugins.values());\n\t}\n\n\t// Clear all entries (useful for testing)\n\tclear(): void {\n\t\tthis.entries.clear();\n\t\tthis.plugins.clear();\n\t}\n\n\t// Get entries by category\n\tgetByCategory(category: string): CellRegistryEntry[] {\n\t\treturn Array.from(this.entries.values()).filter((entry) => entry.metadata?.category === category);\n\t}\n}\n\n// Export singleton instance\n/**\n * @deprecated since 0.2.0 — pass cell types via <SheetsProvider config={{ plugins }}> or <Sheets cellTypes>. CellRegistry only ever affected detection.\n */\nexport const CellRegistry = new CellRegistryClass();\n\n// Export factory function for testing\nexport function createCellRegistry(): CellRegistryClass {\n\treturn new CellRegistryClass();\n}\n","import { ENHANCED_TYPES, MEDIA_TYPES, STRUCTURED_DATA_TYPES } from './cell-type-groups';\nimport type { CellType, ColumnSchema } from './types';\n\n/**\n * Maps raw `_meta` field metadata to a frontend cell type (priority: encoding >\n * pgType > gqlType).\n *\n * @deprecated The grid routes every column from its table model\n * (`cellTypeForColumn` over a `ColumnModel`). This mapping reads raw `_meta` only and\n * is kept for hosts that call it directly.\n */\nexport function mapToFrontendCellType(metadata: {\n\tgqlType: string;\n\tisArray: boolean;\n\tpgAlias?: string | null;\n\tpgType?: string | null;\n\tsubtype?: string | null;\n\tencoding?: { kind: string; geometrySubtype?: string | null } | null;\n}): CellType {\n\tconst { gqlType, isArray, pgType } = metadata;\n\n\tconst encodedType = mapEncodingToCellType(metadata.encoding, gqlType);\n\tif (encodedType) return encodedType;\n\n\t// Handle arrays first (the element type picks the list cell type)\n\tif (isArray) {\n\t\tconst result = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);\n\t\treturn result;\n\t}\n\n\t// Priority 2: Use pgType if available (backend-specific but still useful)\n\tif (pgType) {\n\t\tconst pgTypeMapped = mapBackendTypeToCellType(pgType);\n\t\tif (pgTypeMapped !== 'unknown') return pgTypeMapped;\n\t}\n\n\t// Priority 3: Fall back to GraphQL type\n\tconst fallbackResult = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);\n\treturn fallbackResult;\n}\n\nfunction mapEncodingToCellType(\n\tencoding: { kind: string; geometrySubtype?: string | null } | null | undefined,\n\tgqlType: string,\n): CellType | null {\n\tif (!encoding) return null;\n\n\tswitch (encoding.kind) {\n\t\t// Both whole numbers beyond 2^53 and exact decimals are decimal strings; the GraphQL type tells them apart.\n\t\tcase 'bigint': return gqlType.replace(/[!\\[\\]]/g, '') === 'BigFloat' ? 'decimal' : 'bigint';\n\t\tcase 'datetime': return 'datetime';\n\t\tcase 'date': return 'date';\n\t\tcase 'time': return 'time';\n\t\tcase 'interval': return 'interval';\n\t\tcase 'uuid': return 'uuid';\n\t\tcase 'inet': return 'inet';\n\t\tcase 'point': return 'geometry-point';\n\t\tcase 'geojson':\n\t\t\treturn encoding.geometrySubtype === 'Point' ? 'geometry-point' : 'geometry';\n\t\tcase 'vector': return 'number-array';\n\t\tcase 'composite': return 'json';\n\t\tcase 'ltree':\n\t\tcase 'bytea':\n\t\t\treturn 'text';\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Maps backend-specific types to frontend cell types\n */\nfunction mapBackendTypeToCellType(pgType: string): CellType {\n\tconst typeMap: Record<string, CellType> = {\n\t\t// Text types\n\t\ttext: 'text',\n\t\tvarchar: 'text',\n\t\tcharacter: 'text',\n\t\tchar: 'text',\n\t\t'character varying': 'text',\n\t\tcitext: 'citext',\n\t\tbpchar: 'bpchar',\n\n\t\t// Numeric types\n\t\tinteger: 'integer',\n\t\tint4: 'integer',\n\t\tsmallint: 'smallint',\n\t\tint2: 'smallint',\n\t\tbigint: 'bigint',\n\t\tint8: 'bigint',\n\t\tnumeric: 'decimal',\n\t\tdecimal: 'decimal',\n\t\treal: 'number',\n\t\tfloat4: 'number',\n\t\t'double precision': 'number',\n\t\tfloat8: 'number',\n\t\tmoney: 'currency',\n\n\t\t// Boolean\n\t\tboolean: 'boolean',\n\t\tbool: 'boolean',\n\n\t\t// Bit strings are text of 0 and 1, never a checkbox\n\t\tbit: 'bitstring',\n\t\t'bit varying': 'bitstring',\n\t\tvarbit: 'bitstring',\n\n\t\t// Date/time types\n\t\tdate: 'date',\n\t\ttimestamp: 'datetime',\n\t\ttimestamptz: 'timestamptz',\n\t\t'timestamp with time zone': 'timestamptz',\n\t\t'timestamp without time zone': 'datetime',\n\t\ttime: 'time',\n\t\ttimetz: 'time',\n\t\t'time with time zone': 'time',\n\t\t'time without time zone': 'time',\n\t\tinterval: 'interval',\n\n\t\t// JSON types\n\t\tjson: 'json',\n\t\tjsonb: 'jsonb',\n\n\t\t// UUID\n\t\tuuid: 'uuid',\n\n\t\t// Full-text search\n\t\ttsvector: 'tsvector',\n\n\t\t// Network types\n\t\tinet: 'inet',\n\t\tcidr: 'inet',\n\t\tmacaddr: 'text',\n\t\tmacaddr8: 'text',\n\n\t\t// Geometric types\n\t\tpoint: 'geometry-point',\n\t\tline: 'geometry',\n\t\tlseg: 'geometry',\n\t\tbox: 'geometry',\n\t\tpath: 'geometry',\n\t\tpolygon: 'geometry',\n\t\tcircle: 'geometry',\n\t\tgeometry: 'geometry',\n\t\tgeography: 'geometry',\n\n\t\t// Custom types\n\t\temail: 'email',\n\t\turl: 'url',\n\t\timage: 'image',\n\t\tupload: 'upload',\n\t\tattachment: 'attachment',\n\t\torigin: 'origin',\n\n\t\t// Arrays are handled by isArray flag\n\t\t_text: 'array',\n\t\t_varchar: 'array',\n\t\t_integer: 'array',\n\t};\n\n\treturn typeMap[pgType.toLowerCase()] || 'unknown';\n}\n\n/**\n * Maps GraphQL types to frontend cell types based on actual _meta data structure\n */\nfunction mapGraphQLTypeToCellType(\n\tgqlType: string,\n\tisArray: boolean,\n\tsubtype?: string | null,\n\t_typmod?: unknown,\n): CellType {\n\t// Handle array types specifically\n\tif (isArray) {\n\t\t// Extract base type from array notation like [String], [UUID], etc.\n\t\tconst baseType = gqlType.replace(/[!\\[\\]]/g, '');\n\n\t\t// Map specific array types to their array cell types\n\t\tconst arrayTypeMap: Record<string, CellType> = {\n\t\t\tString: 'text-array',\n\t\t\tUUID: 'uuid-array',\n\t\t\tBigFloat: 'number-array',\n\t\t\tInt: 'integer-array',\n\t\t\tDate: 'date-array',\n\t\t};\n\n\t\treturn arrayTypeMap[baseType] || 'array'; // fallback to generic array\n\t}\n\n\t// Remove GraphQL type modifiers for base type matching\n\tconst baseType = gqlType.replace(/[!\\[\\]]/g, '');\n\n\t// Handle complex types based on actual metadata patterns\n\n\t// 1. Relation types\n\tif (baseType === 'Relation') {\n\t\treturn 'relation';\n\t}\n\n\t// 2. Interval types\n\tif (baseType === 'Interval') {\n\t\treturn 'interval';\n\t}\n\n\t// 3. GeometryGeometryCollection types\n\tif (baseType === 'GeometryGeometryCollection') {\n\t\treturn 'geometry-collection';\n\t}\n\n\t// 4. GeoJSON types with subtypes\n\tif (baseType === 'GeoJSON') {\n\t\tif (subtype === 'GeometryPoint') {\n\t\t\treturn 'geometry-point';\n\t\t}\n\t\tif (subtype === 'GeometryPolygon') {\n\t\t\treturn 'geometry-collection'; // Could be 'geometry-polygon' if you create that cell type\n\t\t}\n\t\t// Default for other GeoJSON types - should be geometry, not json\n\t\t// This ensures null geometry values are properly handled\n\t\treturn 'geometry';\n\t}\n\n\tconst typeMap: Record<string, CellType> = {\n\t\t// GraphQL scalar types\n\t\tString: 'text',\n\t\tInt: 'integer',\n\t\tFloat: 'number',\n\t\tBoolean: 'boolean',\n\t\tID: 'uuid',\n\n\t\t// Common GraphQL custom scalars\n\t\tDateTime: 'datetime',\n\t\tDatetime: 'datetime', // Handle both cases\n\t\tDate: 'date',\n\t\tTime: 'time',\n\t\tJSON: 'json',\n\t\tJSONObject: 'json',\n\t\tUpload: 'file',\n\t\tURL: 'url',\n\t\tEmailAddress: 'email',\n\t\tPhoneNumber: 'phone',\n\t\tUUID: 'uuid',\n\t\tBigFloat: 'decimal',\n\t\tBigInt: 'bigint',\n\t};\n\n\treturn typeMap[baseType] || 'text'; // Default to text for unknown GraphQL types\n}\n\n/**\n * Determines if a field represents structured data that should be rendered as JSON\n */\nexport function isStructuredDataType(cellType: CellType): boolean {\n\treturn STRUCTURED_DATA_TYPES.has(cellType);\n}\n\n/**\n * Determines if a field represents media content\n */\nexport function isMediaType(cellType: CellType): boolean {\n\treturn MEDIA_TYPES.has(cellType);\n}\n\n/**\n * Determines if a field is a special frontend-enhanced type\n */\nexport function isEnhancedType(cellType: CellType): boolean {\n\treturn ENHANCED_TYPES.has(cellType);\n}\n\n/**\n * Create a ColumnSchema from GraphQL meta field data\n */\nexport function createColumnSchemaFromMeta(field: {\n\tname: string;\n\ttype: {\n\t\tgqlType: string;\n\t\tisArray: boolean;\n\t\tmodifier?: string | number | null;\n\t\tpgAlias?: string | null;\n\t\tpgType?: string | null;\n\t\tsubtype?: string | null;\n\t\ttypmod?: any;\n\t\tencoding?: { kind: string; geometrySubtype?: string | null } | null;\n\t};\n}): ColumnSchema {\n\tconst { name, type } = field;\n\tconst { gqlType, isArray, subtype } = type;\n\n\t// Determine if field is nullable (GraphQL types ending with ! are non-null)\n\tconst nullable = !gqlType.endsWith('!');\n\n\t// Map to frontend cell type using metadata\n\tconst cellType = mapToFrontendCellType(field.type);\n\n\t// Generate human-friendly label\n\tconst label = name\n\t\t.replace(/([A-Z])/g, ' $1')\n\t\t.replace(/^./, (str) => str.toUpperCase())\n\t\t.trim();\n\n\treturn {\n\t\tid: name,\n\t\tname,\n\t\ttype: cellType,\n\t\tnullable,\n\t\tmetadata: {\n\t\t\tlabel,\n\t\t\tdescription: `${gqlType}${isArray ? '[]' : ''}${subtype ? ` (${subtype})` : ''}`,\n\t\t\tsortable: !isArray && cellType !== 'json' && cellType !== 'geometry-collection',\n\t\t\tfilterable: cellType !== 'geometry-collection',\n\t\t},\n\t};\n}\n","import { CellRegistry } from './cell-registry';\nimport { NON_EDITABLE_TYPES, VIEWER_ONLY_TYPES } from './cell-type-groups';\nimport { mapToFrontendCellType } from './type-mapping';\n\nexport interface FieldMetadata {\n\tname: string;\n\ttype?: {\n\t\tgqlType: string;\n\t\tpgType?: string | null;\n\t\tpgAlias?: string | null;\n\t\tisArray?: boolean;\n\t\tsubtype?: string | null;\n\t};\n}\n\nexport interface CellTypeResolution {\n\tcellType: string;\n\tcanEdit: boolean;\n\tcanActivate: boolean;\n\tactivationBehavior: 'single-click' | 'double-click';\n\tisReadonly: boolean;\n}\n\n// Use double-click to activate overlay for all cell types\nconst SINGLE_CLICK_CELL_TYPES = new Set<string>();\n\n/**\n * Resolve a cell type from raw `_meta` field metadata.\n *\n * @deprecated The grid routes table-model columns with `cellTypeForColumn` and takes\n * read-only state from the model's write flags. This resolver never marks a field\n * read-only by its name; it only says whether the cell type itself is editable.\n */\nexport function resolveCellType(fieldName: string, fieldMeta?: FieldMetadata): CellTypeResolution {\n\tconst isReadonly = false;\n\n\tlet cellType: string = 'text'; // Default fallback\n\n\tif (fieldMeta?.type) {\n\t\t// First try CellRegistry matching (same as existing logic)\n\t\t// NOTE: Cell type is determined ONLY from schema metadata, never from runtime values\n\t\tconst matchedEntry = CellRegistry.findByMatch({\n\t\t\tgqlType: fieldMeta.type.gqlType || '',\n\t\t\tisArray: !!fieldMeta.type.isArray,\n\t\t\tpgAlias: fieldMeta.type.pgAlias,\n\t\t\tpgType: fieldMeta.type.pgType,\n\t\t\tsubtype: fieldMeta.type.subtype ?? null,\n\t\t\tfieldName,\n\t\t});\n\n\t\tif (matchedEntry) {\n\t\t\tcellType = matchedEntry.type;\n\t\t} else {\n\t\t\t// Fallback: Map GraphQL field metadata to frontend cell types\n\t\t\tcellType = mapToFrontendCellType({\n\t\t\t\tgqlType: fieldMeta.type.gqlType,\n\t\t\t\tisArray: !!fieldMeta.type.isArray,\n\t\t\t\tpgType: fieldMeta.type.pgType,\n\t\t\t\tsubtype: fieldMeta.type.subtype ?? null,\n\t\t\t});\n\t\t}\n\t}\n\n\t// Determine editing capabilities\n\tconst canEdit = !isReadonly && !NON_EDITABLE_TYPES.has(cellType);\n\tconst canActivate = canEdit || VIEWER_ONLY_TYPES.has(cellType);\n\tconst activationBehavior = SINGLE_CLICK_CELL_TYPES.has(cellType) ? 'single-click' : 'double-click';\n\n\treturn {\n\t\tcellType,\n\t\tcanEdit,\n\t\tcanActivate,\n\t\tactivationBehavior,\n\t\tisReadonly,\n\t};\n}\n\nexport function shouldShowCellActivation(_fieldName: string, cellType: string): boolean {\n\tif (VIEWER_ONLY_TYPES.has(cellType)) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n/**\n * Whether raw field metadata describes an image column. Decided by the type only\n * (a registered matcher or the image type), never by the field's name.\n *\n * @deprecated Read `ColumnModel.value.file?.kind === 'image'` from the table model.\n */\nexport function isImageField(fieldMeta?: FieldMetadata, fieldName?: string): boolean {\n\tif (!fieldMeta || !fieldName) return false;\n\n\tif (mapToFrontendCellType({\n\t\tgqlType: fieldMeta.type?.gqlType || '',\n\t\tisArray: !!fieldMeta.type?.isArray,\n\t\tpgType: fieldMeta.type?.pgType,\n\t\tsubtype: fieldMeta.type?.subtype ?? null,\n\t}) === 'image') return true;\n\n\t// Also check using CellRegistry matching\n\tconst matchedEntry = CellRegistry.findByMatch({\n\t\tgqlType: fieldMeta.type?.gqlType || '',\n\t\tisArray: !!fieldMeta.type?.isArray,\n\t\tpgAlias: fieldMeta.type?.pgAlias,\n\t\tpgType: fieldMeta.type?.pgType,\n\t\tsubtype: fieldMeta.type?.subtype ?? null,\n\t\tfieldName,\n\t});\n\n\treturn matchedEntry?.type === 'image';\n}\n","// The ONE routing rule from a table-model column to a cell type.\n//\n// Every decision here reads the `ColumnModel` (value kind, list flag, semantic\n// hint, option list, file details, input type). Nothing looks at a column name,\n// and nothing guesses from a value. The cell type picks the cell factory, the\n// view and the editor (see `grid-dom/editors/edit-intent.ts`).\n\nimport type { ColumnModel } from '@constructive-io/data';\n\nimport type { CellType } from './types';\n\n/** Cell type of a list column whose elements have a dedicated list cell type. */\nconst LIST_CELL_TYPES: Partial<Record<ColumnModel['value']['kind'], CellType>> = {\n\ttext: 'text-array',\n\tuuid: 'uuid-array',\n\tinteger: 'integer-array',\n\tfloat: 'number-array',\n\tdate: 'date-array',\n};\n\n/** Cell type of a file column. */\nfunction fileCellType(column: ColumnModel): CellType {\n\tswitch (column.value.file?.kind) {\n\t\tcase 'image':\n\t\t\treturn 'image';\n\t\tcase 'attachment':\n\t\t\treturn 'attachment';\n\t\tdefault:\n\t\t\treturn 'upload';\n\t}\n}\n\n/** Cell type of a single text value: presentation follows the semantic hint. */\nfunction textCellType(column: ColumnModel): CellType {\n\tswitch (column.value.semantic) {\n\t\tcase 'email':\n\t\t\treturn 'email';\n\t\tcase 'url':\n\t\t\treturn 'url';\n\t\tcase 'origin':\n\t\t\treturn 'origin';\n\t\tdefault:\n\t\t\treturn 'text';\n\t}\n}\n\n/**\n * Map a table-model column to its cell type. A list column routes to a list cell\n * type (the editor validates each element by the column's value kind); a column with\n * a fixed option list routes to a choice cell type.\n */\nexport function cellTypeForColumn(column: ColumnModel): CellType {\n\tconst { value } = column;\n\tif (value.kind === 'file') return fileCellType(column);\n\tif (value.kind === 'enum' || value.options) return value.isArray ? 'multi-select' : 'select';\n\tif (value.isArray) {\n\t\tif (value.kind === 'vector') return 'vector';\n\t\treturn LIST_CELL_TYPES[value.kind] ?? 'array';\n\t}\n\n\tswitch (value.kind) {\n\t\tcase 'text':\n\t\t\treturn textCellType(column);\n\t\tcase 'integer':\n\t\t\treturn 'integer';\n\t\tcase 'bigint':\n\t\t\treturn 'bigint';\n\t\tcase 'decimal':\n\t\t\treturn 'decimal';\n\t\tcase 'float':\n\t\t\treturn value.semantic === 'currency' ? 'currency' : 'number';\n\t\tcase 'boolean':\n\t\t\treturn 'boolean';\n\t\tcase 'uuid':\n\t\t\treturn 'uuid';\n\t\tcase 'date':\n\t\t\treturn 'date';\n\t\tcase 'time':\n\t\t\treturn 'time';\n\t\tcase 'datetime':\n\t\t\treturn 'datetime';\n\t\tcase 'interval':\n\t\t\treturn 'interval';\n\t\tcase 'json':\n\t\t\treturn 'json';\n\t\tcase 'bitstring':\n\t\t\treturn 'bitstring';\n\t\tcase 'binary':\n\t\t\treturn 'binary';\n\t\t// A hardware address has no network editor; it edits as text.\n\t\tcase 'network':\n\t\t\treturn value.typeName === 'MacAddress' ? 'text' : 'inet';\n\t\tcase 'geometry':\n\t\t\treturn value.geometrySubtype === 'Point' ? 'geometry-point' : 'geometry';\n\t\tcase 'point':\n\t\t\treturn 'point';\n\t\tcase 'vector':\n\t\t\treturn 'vector';\n\t\tcase 'fulltext':\n\t\t\treturn 'tsvector';\n\t\tcase 'path':\n\t\t\treturn 'path';\n\t\tcase 'range':\n\t\t\treturn 'range';\n\t\tcase 'composite':\n\t\t\treturn 'composite';\n\t\tdefault:\n\t\t\treturn 'unknown';\n\t}\n}\n","export function createMetadataHash(value: unknown): string {\n\tconst serialized = JSON.stringify(value, stableReplacer);\n\tlet hash = 0;\n\tfor (let index = 0; index < serialized.length; index += 1) {\n\t\thash = (hash * 33) ^ serialized.charCodeAt(index);\n\t}\n\n\treturn `h${(hash >>> 0).toString(16)}`;\n}\n\nfunction stableReplacer(_key: string, value: unknown): unknown {\n\tif (value && typeof value === 'object' && !Array.isArray(value)) {\n\t\treturn Object.keys(value)\n\t\t\t.sort()\n\t\t\t.reduce<Record<string, unknown>>((acc, key) => {\n\t\t\t\tacc[key] = (value as Record<string, unknown>)[key];\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\t}\n\treturn value;\n}\n","// Form spec and validation schema built from the table model, for a record form\n// (create a record, or edit one) that must follow the same rules as the grid.\n//\n// Each field carries its column, its cell type (the same routing the grid uses), and\n// whether it can be written in this mode, with the reason when it cannot. The schema\n// checks every value with `parseColumnInput`, so a form and a grid cell accept and\n// refuse exactly the same values, and it outputs the parsed values (exact decimal\n// strings, enum wire values) ready for `encodeWriteValues`.\n\nimport { z } from 'zod';\n\nimport type { ColumnModel, ColumnOption, TableModel } from '@constructive-io/data';\n\nimport { parseColumnInput } from '../cell-types/column-value';\nimport { fieldLabel } from '../cell-types/field-label';\nimport { resolveModelCellRoute } from '../grid/cell-routing';\nimport { createMetadataHash } from './metadata-hash';\n\n/** Whether the form creates a record or edits an existing one. */\nexport type ModelFormMode = 'create' | 'update';\n\nexport interface ModelFormField {\n\t/** Field name on the row (also the key in the form values). */\n\tname: string;\n\t/** Readable label. */\n\tlabel: string;\n\t/** Column comment, or null. */\n\tdescription: string | null;\n\t/** The table-model column. */\n\tcolumn: ColumnModel;\n\t/** The cell type key the grid uses for this column (a built-in cell type or a host override); it picks the editor. */\n\tcellType: string;\n\t/** The form may set this field in this mode. */\n\twritable: boolean;\n\t/** Why the field cannot be set in this mode, or null when it can. */\n\treadOnlyReason: string | null;\n\t/** A value must be given: create requires it (no default), or an edit cannot empty it. */\n\trequired: boolean;\n\t/** The column accepts no value. */\n\tnullable: boolean;\n\t/** Fixed choices, or null. `value` is what is stored. */\n\toptions: readonly ColumnOption[] | null;\n\tmaxLength: number | null;\n\tprecision: number | null;\n\tscale: number | null;\n}\n\nexport interface ModelFormSpec {\n\t/** `TableModel.key` of the table. */\n\ttableKey: string;\n\t/** GraphQL type name of the table. */\n\ttableName: string;\n\tmode: ModelFormMode;\n\t/** Changes whenever a field's rules change; use it as a cache key. */\n\tversionHash: string;\n\t/** Readable fields, in column order. */\n\tfields: ModelFormField[];\n}\n\nexport interface BuildModelFormSpecOptions {\n\t/** Host cell-type overrides keyed by `tableName.fieldName` (`SheetsConfig.fieldTypeOverrides`). */\n\ttypeOverrides?: Readonly<Record<string, string>>;\n}\n\n/**\n * Build the fields of a create or edit form from the table model. Each field's cell\n * type and read-only reason come from the grid's own routing (`resolveModelCellRoute`:\n * a create is routed like a draft row, an edit like a saved row with its key fixed),\n * so a form and a grid cell never disagree.\n */\nexport function buildModelFormSpec(model: TableModel, mode: ModelFormMode, options: BuildModelFormSpecOptions = {}): ModelFormSpec {\n\tconst lockedFields = new Set(model.primaryKey);\n\tconst fields: ModelFormField[] = model.columns\n\t\t.filter((column) => column.readable)\n\t\t.map((column) => {\n\t\t\tconst { cellType, readOnlyReason } = resolveModelCellRoute({\n\t\t\t\tcolumn,\n\t\t\t\ttable: model,\n\t\t\t\tisDraftRow: mode === 'create',\n\t\t\t\tcellError: null,\n\t\t\t\ttypeOverride: options.typeOverrides?.[`${model.name}.${column.name}`] ?? null,\n\t\t\t\tlockedFields,\n\t\t\t});\n\t\t\tconst writable = readOnlyReason === null;\n\t\t\treturn {\n\t\t\t\tname: column.name,\n\t\t\t\tlabel: fieldLabel(column.name),\n\t\t\t\tdescription: column.description,\n\t\t\t\tcolumn,\n\t\t\t\tcellType,\n\t\t\t\twritable,\n\t\t\t\treadOnlyReason,\n\t\t\t\trequired: writable && (mode === 'create' ? column.write.requiredOnCreate : !column.nullable),\n\t\t\t\tnullable: column.nullable,\n\t\t\t\toptions: column.value.options,\n\t\t\t\tmaxLength: column.value.maxLength,\n\t\t\t\tprecision: column.value.precision,\n\t\t\t\tscale: column.value.scale,\n\t\t\t};\n\t\t});\n\n\tconst versionHash = createMetadataHash({\n\t\ttable: model.key,\n\t\tmode,\n\t\tfields: fields.map((field) => ({\n\t\t\tname: field.name,\n\t\t\tcellType: field.cellType,\n\t\t\twritable: field.writable,\n\t\t\trequired: field.required,\n\t\t\tnullable: field.nullable,\n\t\t\toptions: field.options,\n\t\t\tmaxLength: field.maxLength,\n\t\t\tprecision: field.precision,\n\t\t\tscale: field.scale,\n\t\t})),\n\t});\n\n\treturn { tableKey: model.key, tableName: model.name, mode, versionHash, fields };\n}\n\nfunction requiredOnSubmit(field: ModelFormField, mode: ModelFormMode): boolean {\n\treturn mode === 'create' && field.required;\n}\n\nfunction fieldSchema(field: ModelFormField, mode: ModelFormMode): z.ZodType<unknown> {\n\treturn z\n\t\t.unknown()\n\t\t.optional()\n\t\t.transform((value, ctx) => {\n\t\t\t// An untouched field is left out: the database default applies on create, the stored value stays on edit.\n\t\t\tif (value === undefined) return undefined;\n\t\t\tif (requiredOnSubmit(field, mode) && (value === null || value === '')) {\n\t\t\t\tctx.addIssue({ code: 'custom', message: `${field.label} is required` });\n\t\t\t\treturn z.NEVER;\n\t\t\t}\n\t\t\t// Clearing follows the column rules: null, '' for text that cannot be empty but has a default\n\t\t\t// (or on create), or a refusal.\n\t\t\tconst parsed = parseColumnInput(field.column, value, { fromText: typeof value === 'string', creating: mode === 'create' });\n\t\t\tif (parsed.ok === false) {\n\t\t\t\tctx.addIssue({ code: 'custom', message: parsed.reason });\n\t\t\t\treturn z.NEVER;\n\t\t\t}\n\t\t\treturn parsed.value;\n\t\t});\n}\n\nconst modelSchemaCache = new Map<string, z.ZodObject<Record<string, z.ZodType<unknown>>>>();\n\n/**\n * Build the validation schema of a model form. Only writable fields are in it; each\n * one is checked and parsed by the column's rules. Unknown keys are dropped, so a\n * read-only field can never reach a write.\n */\nexport function buildModelFormSchema(spec: ModelFormSpec): z.ZodObject<Record<string, z.ZodType<unknown>>> {\n\tconst cached = modelSchemaCache.get(spec.versionHash);\n\tif (cached) return cached;\n\tconst shape: Record<string, z.ZodType<unknown>> = {};\n\tfor (const field of spec.fields) {\n\t\tif (field.writable) shape[field.name] = fieldSchema(field, spec.mode);\n\t}\n\t// A field a create requires must be present; an absent key never reaches its own check.\n\tconst schema = z.object(shape).superRefine((values, ctx) => {\n\t\tfor (const field of spec.fields) {\n\t\t\tif (!field.writable || !requiredOnSubmit(field, spec.mode)) continue;\n\t\t\tif (values[field.name] === undefined) ctx.addIssue({ code: 'custom', path: [field.name], message: `${field.label} is required` });\n\t\t}\n\t});\n\tmodelSchemaCache.set(spec.versionHash, schema);\n\treturn schema;\n}\n","import type { RelationModel, TableModel } from '@constructive-io/data';\n\n/** Turn a field name into a readable label (`dueOn` -> `Due on`, `iso_code` -> `Iso code`). */\nexport function fieldLabel(name: string): string {\n\tconst spaced = name\n\t\t.replace(/_/g, ' ')\n\t\t.replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n\t\t.trim()\n\t\t.toLowerCase();\n\treturn spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\n/** A generated relation name: the related records, `By`, then the key fields that link them. */\nconst GENERATED_RELATION_NAME = /^([a-z][A-Za-z0-9]*?)By([A-Z][A-Za-z0-9]*)$/;\n\nfunction plural(words: string): string {\n\treturn words.endsWith('s') ? words : `${words}s`;\n}\n\n/**\n * A readable label for a relation field. A generated name spells out its key fields\n * (`peopleByManagerId`, `projectsByProjectMemberPersonIdAndProjectId`); the label keeps\n * what a person needs: the related records and what links them, or the link table of a\n * many-to-many relation. Any other name reads like a field name.\n */\nexport function relationFieldLabel(relation: Pick<RelationModel, 'kind' | 'fieldName' | 'junction'>): string {\n\tconst match = GENERATED_RELATION_NAME.exec(relation.fieldName);\n\tif (!match) return fieldLabel(relation.fieldName);\n\tconst [, records, link] = match as unknown as [string, string, string];\n\tif (relation.kind === 'manyToMany' && relation.junction) {\n\t\treturn `${fieldLabel(records)} via ${plural(fieldLabel(relation.junction.tableName).toLowerCase())}`;\n\t}\n\t// `ManagerId` -> `manager`; `WarehouseCodeAndSku` -> `warehouse code and sku`; `OrgIdAndUserId` -> `org and user`.\n\tconst keys = link\n\t\t.split(/And(?=[A-Z])/)\n\t\t.map((part) => fieldLabel(part.replace(/Id$/, '')).toLowerCase())\n\t\t.filter(Boolean);\n\treturn `${fieldLabel(records)} by ${keys.join(' and ')}`;\n}\n\ntype LabelModel = Pick<TableModel, 'key' | 'columns' | 'relations'>;\ntype LabelRelation = Pick<RelationModel, 'kind' | 'fieldName' | 'junction' | 'keys' | 'targetKey'>;\n\n/**\n * The short name of a generated relation name in its table, or null when its full label is\n * the name: a link names what the row's key field says, without the field it points at\n * (`personByAssigneeEmail` -> `Assignee`), else the linked table (`Warehouse item`); a list\n * names the related records (`Tasks`). A list of the table's own records keeps what links\n * them (`People by manager`), or it would read as every record.\n */\nfunction shortRelationLabel(model: LabelModel, relation: LabelRelation): string | null {\n\tconst match = GENERATED_RELATION_NAME.exec(relation.fieldName);\n\tif (!match) return null;\n\tconst records = fieldLabel(match[1]!);\n\tif (relation.kind === 'belongsTo') {\n\t\tconst pair = relation.keys.length === 1 ? relation.keys[0]! : null;\n\t\tconst pointsAt = pair ? pair.remote.charAt(0).toUpperCase() + pair.remote.slice(1) : '';\n\t\tif (pair && pair.local.length > pointsAt.length && pair.local.endsWith(pointsAt)) return fieldLabel(pair.local.slice(0, -pointsAt.length));\n\t\treturn records;\n\t}\n\treturn relation.targetKey === model.key ? null : records;\n}\n\nconst labelsByModel = new WeakMap<LabelModel, ReadonlyMap<string, string>>();\n\n/** The label of each relation of a table: short where no other field of the table reads the same. */\nfunction relationLabels(model: LabelModel): ReadonlyMap<string, string> {\n\tconst cached = labelsByModel.get(model);\n\tif (cached) return cached;\n\tconst short = new Map(model.relations.map((relation) => [relation.fieldName, shortRelationLabel(model, relation) ?? relationFieldLabel(relation)]));\n\tconst uses = new Map<string, number>();\n\tfor (const label of [...model.columns.map((column) => fieldLabel(column.name)), ...short.values()]) {\n\t\tconst key = label.toLowerCase();\n\t\tuses.set(key, (uses.get(key) ?? 0) + 1);\n\t}\n\tconst labels = new Map<string, string>();\n\tfor (const relation of model.relations) {\n\t\tconst label = short.get(relation.fieldName)!;\n\t\tlabels.set(relation.fieldName, (uses.get(label.toLowerCase()) ?? 0) > 1 ? relationFieldLabel(relation) : label);\n\t}\n\tlabelsByModel.set(model, labels);\n\treturn labels;\n}\n\n/** The label of a relation of `model`: its short name unless another field of the table reads the same. */\nexport function relationLabelIn(model: LabelModel | null | undefined, relation: LabelRelation): string {\n\treturn (model && relationLabels(model).get(relation.fieldName)) ?? relationFieldLabel(relation);\n}\n\n/** The label of any field of a table: a relation reads as a relation, a column as a field. */\nexport function modelFieldLabel(model: LabelModel | null | undefined): (name: string) => string {\n\tconst relations = new Map((model?.relations ?? []).map((relation) => [relation.fieldName, relation]));\n\treturn (name) => {\n\t\tconst relation = relations.get(name);\n\t\treturn relation ? relationLabelIn(model, relation) : fieldLabel(name);\n\t};\n}\n","import type { ColumnModel, MetaQuery, RelationModel, TableModel } from '@constructive-io/data';\n\nimport { NON_EDITABLE_TYPES } from '../cell-types/cell-type-groups';\nimport { resolveCellType, type FieldMetadata } from '../cell-types/cell-type-resolver';\nimport { cellTypeForColumn } from '../cell-types/column-routing';\nimport { VIEW_ONLY_REASON } from '../cell-types/column-value';\nimport type { RelationInfo } from '../store/relation-info-slice';\n\n/** Shown on a cell whose value the server could not send. */\nexport const CELL_READ_ERROR_TEXT = 'This value cannot be shown';\nconst CELL_READ_ERROR_REASON = 'The server could not send this value, so it cannot be shown or changed here.';\nconst KEY_LOCKED_REASON = 'This field identifies the record, so it cannot be changed here.';\nconst UNDESCRIBED_PARTS_REASON = 'The parts of this value are not known, so it cannot be changed here.';\n\n/** Cell types whose editor builds the value from the fields of the column's write input. */\nconst FIELD_BUILT_TYPES: ReadonlySet<string> = new Set(['composite', 'point', 'range', 'interval']);\n\nexport interface ModelCellRouteInput {\n\tcolumn: ColumnModel;\n\ttable: TableModel;\n\t/** The row is a draft that has not been created yet. */\n\tisDraftRow: boolean;\n\t/** The list read could not serve this cell's value. */\n\tcellError: string | null;\n\t/** Host override of the cell type (`SheetsConfig.fieldTypeOverrides`). */\n\ttypeOverride?: string | null;\n\t/** Fields of saved rows that stay fixed because they identify the row. */\n\tlockedFields?: ReadonlySet<string>;\n}\n\nexport interface ModelCellRoute {\n\tcellType: string;\n\t/** Why the cell cannot be written, or null when it can. Safe to show to the user. */\n\treadOnlyReason: string | null;\n}\n\nfunction operationIssue(table: TableModel, operation: 'create' | 'update'): string | null {\n\treturn table.issues.find((issue) => issue.scope === 'operation' && issue.target === operation)?.message ?? null;\n}\n\n/** Why a cell of this column cannot be written in this row, from the table model only. */\nfunction modelReadOnlyReason(input: ModelCellRouteInput, cellType: string): string | null {\n\tconst { column, table, isDraftRow, cellError, lockedFields } = input;\n\tif (cellError) return CELL_READ_ERROR_REASON;\n\tif (!column.readable) return column.readReason ?? 'This field cannot be read.';\n\tif (NON_EDITABLE_TYPES.has(cellType)) return VIEW_ONLY_REASON;\n\tif (FIELD_BUILT_TYPES.has(cellType) && column.value.input && !column.value.input.fields?.length) {\n\t\treturn UNDESCRIBED_PARTS_REASON;\n\t}\n\tif (isDraftRow) {\n\t\tif (!table.operations.create) return operationIssue(table, 'create') ?? 'New records cannot be added to this table.';\n\t\treturn column.write.create ? null : column.write.createReason ?? 'This field cannot be set on a new record.';\n\t}\n\tif (!table.operations.update) return operationIssue(table, 'update') ?? 'Records in this table cannot be changed.';\n\tif (lockedFields?.has(column.name)) return KEY_LOCKED_REASON;\n\treturn column.write.update ? null : column.write.updateReason ?? 'This field cannot be changed.';\n}\n\n/**\n * Why a relation cell cannot change its links, or null when the relation editor may\n * (it decides the details per link). A belongsTo writes this table's row, so it also\n * needs the row's create (draft) or update operation; the other kinds write the\n * related or junction table, which the relation editor checks.\n */\nexport function relationCellReadOnlyReason(relation: RelationModel, table: TableModel | null, isDraftRow: boolean): string | null {\n\tif (!relation.readable || !relation.editable) return relation.reason ?? 'These links cannot be changed here.';\n\tif (relation.kind !== 'belongsTo' || !table) return null;\n\tif (isDraftRow) return table.operations.create ? null : operationIssue(table, 'create') ?? 'New records cannot be added to this table.';\n\treturn table.operations.update ? null : operationIssue(table, 'update') ?? 'Records in this table cannot be changed.';\n}\n\n/**\n * Route one column cell from the table model: its cell type and, when it cannot be\n * written in this row, the reason. A host type override changes the cell type only;\n * it never makes a read-only column writable.\n */\nexport function resolveModelCellRoute(input: ModelCellRouteInput): ModelCellRoute {\n\tconst cellType = input.typeOverride || cellTypeForColumn(input.column);\n\treturn { cellType, readOnlyReason: modelReadOnlyReason(input, cellType) };\n}\n\ntype MetaTable = NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number];\n\nexport interface GridCellRouteInput {\n\tcolKey: string;\n\tfieldMeta?: FieldMetadata;\n\trelationInfo?: RelationInfo;\n\tisRelationFallback?: boolean;\n\tisCustomGeometryCell?: boolean;\n\tisDraftIdCell?: boolean;\n\thasForeignKeyField?: boolean;\n}\n\nexport interface GridCellRoute {\n\tcellType: string;\n\tbaseCellType: string;\n\tisRelation: boolean;\n\tcanEdit: boolean;\n\tcanActivate: boolean;\n\tisReadonly: boolean;\n\tactivationBehavior: 'single-click' | 'double-click';\n}\n\nexport function buildRelationFieldNameSet(meta: MetaQuery | undefined, tableName?: string): Set<string> {\n\tif (!tableName) return new Set<string>();\n\n\tconst table = meta?._meta?.tables?.find((entry): entry is MetaTable => Boolean(entry && entry.name === tableName));\n\tif (!table?.relations) return new Set<string>();\n\n\tconst out = new Set<string>();\n\tconst push = (fieldName?: string | null) => {\n\t\tif (fieldName) out.add(fieldName);\n\t};\n\n\ttable.relations.belongsTo?.forEach((relation) => {\n\t\tpush(relation?.fieldName);\n\t\trelation?.keys?.forEach((key) => push(key?.name));\n\t});\n\ttable.relations.hasOne?.forEach((relation) => push(relation?.fieldName));\n\ttable.relations.hasMany?.forEach((relation) => push(relation?.fieldName));\n\ttable.relations.manyToMany?.forEach((relation) => push(relation?.fieldName));\n\n\treturn out;\n}\n\nexport function resolveGridCellRoute({\n\tcolKey,\n\tfieldMeta,\n\trelationInfo,\n\tisRelationFallback = false,\n\tisCustomGeometryCell = false,\n\tisDraftIdCell = false,\n\thasForeignKeyField = false,\n}: GridCellRouteInput): GridCellRoute {\n\tconst base = resolveCellType(colKey, fieldMeta);\n\tconst isRelation = Boolean(relationInfo) || isRelationFallback;\n\tconst canEditRelationInline = Boolean(\n\t\trelationInfo && relationInfo.kind === 'belongsTo' && relationInfo.foreignKeyField && hasForeignKeyField,\n\t);\n\n\tconst canEdit = isDraftIdCell ? false : isRelation ? canEditRelationInline : base.canEdit;\n\tconst canActivate = isDraftIdCell ? false : isRelation ? true : base.canActivate;\n\tconst isReadonly = isDraftIdCell ? true : isRelation ? !canEditRelationInline : base.isReadonly;\n\n\tlet cellType = isRelation ? 'relation' : base.cellType;\n\tif (!isRelation && isCustomGeometryCell) {\n\t\tcellType = 'geometry';\n\t}\n\n\treturn {\n\t\tcellType,\n\t\tbaseCellType: base.cellType,\n\t\tisRelation,\n\t\tcanEdit,\n\t\tcanActivate,\n\t\tisReadonly,\n\t\tactivationBehavior: base.activationBehavior,\n\t};\n}\n","import {\n\tTableModelError,\n\tassessTableWriteCapability,\n\tresolveRowIdentity,\n\trowIdentityToPrimaryKey,\n\tserializeRowIdentity,\n\ttype MetaTable,\n\ttype RowIdentityValue,\n\ttype RowKey,\n\ttype TableModel,\n\ttype TableWriteCapability,\n} from '@constructive-io/data';\n\n/** A row locator accepted by Sheets CRUD operations. */\nexport type SheetsRowIdentifier =\n\t| string\n\t| number\n\t| Readonly<Record<string, RowIdentityValue>>;\n\nexport type SheetsMutationOperation = 'create' | 'update' | 'delete';\n\nexport type SheetsRowIdentityResolution =\n\t| Readonly<{\n\t\t\tstatus: 'identified';\n\t\t\t/** Backwards-compatible scalar for an ordinary `id` PK; otherwise the PK object. */\n\t\t\tidentifier: SheetsRowIdentifier;\n\t\t\t/** GraphQL primary-key input, including renamed and composite keys. */\n\t\t\tprimaryKey: Readonly<Record<string, RowIdentityValue>>;\n\t\t\t/** Stable, schema-qualified key used by caches, selection, and editors. */\n\t\t\tkey: string;\n\t }>\n\t| Readonly<{\n\t\t\tstatus: 'unavailable';\n\t\t\treason: 'no-primary-key' | 'invalid-row';\n\t }>;\n\nfunction isLegacyScalarId(\n\tprimaryKey: Readonly<Record<string, RowIdentityValue>>,\n): primaryKey is Readonly<{ id: string | number }> {\n\tconst entries = Object.entries(primaryKey);\n\treturn (\n\t\tentries.length === 1 &&\n\t\tentries[0][0] === 'id' &&\n\t\t(typeof entries[0][1] === 'string' || typeof entries[0][1] === 'number')\n\t);\n}\n\n/**\n * Resolve one server row from `_meta`. The familiar scalar `id` contract is kept\n * for existing adapters, while renamed and composite keys use the full PK input.\n */\nexport function resolveSheetsRowIdentity(\n\ttable: MetaTable,\n\trow: Readonly<Record<string, unknown>>,\n): SheetsRowIdentityResolution {\n\tconst resolution = resolveRowIdentity(table, row);\n\tif (resolution.status === 'read-only') {\n\t\treturn { status: 'unavailable', reason: 'no-primary-key' };\n\t}\n\tif (resolution.status === 'invalid-row') {\n\t\treturn { status: 'unavailable', reason: 'invalid-row' };\n\t}\n\n\tconst primaryKey = rowIdentityToPrimaryKey(resolution.identity);\n\treturn {\n\t\tstatus: 'identified',\n\t\tidentifier: isLegacyScalarId(primaryKey) ? primaryKey.id : primaryKey,\n\t\tprimaryKey,\n\t\tkey: serializeRowIdentity(resolution.identity),\n\t};\n}\n\n/** Resolve a public CRUD identifier through the same `_meta` identity contract. */\nexport function resolveSheetsIdentifier(\n\ttable: MetaTable,\n\tidentifier: SheetsRowIdentifier,\n): SheetsRowIdentityResolution {\n\tconst row =\n\t\ttypeof identifier === 'object' && identifier !== null\n\t\t\t? identifier\n\t\t\t: { id: identifier };\n\treturn resolveSheetsRowIdentity(table, row);\n}\n\n/** Build the PostGraphile connection filter used by `findOne`. */\nexport function sheetsIdentifierToWhere(\n\ttable: MetaTable,\n\tidentifier: SheetsRowIdentifier,\n): Record<string, { equalTo: RowIdentityValue }> | null {\n\tconst resolution = resolveSheetsIdentifier(table, identifier);\n\tif (resolution.status !== 'identified') return null;\n\treturn Object.fromEntries(\n\t\tObject.entries(resolution.primaryKey).map(([field, value]) => [field, { equalTo: value }]),\n\t);\n}\n\n/**\n * The primary-key values a model document needs. A scalar identifier is the\n * value of a one-field key, whatever that field is called; an object must\n * carry every key field.\n */\nexport function sheetsIdentifierToRowKey(model: TableModel, identifier: SheetsRowIdentifier): RowKey {\n\tif (typeof identifier === 'object' && identifier !== null) return identifier;\n\tif (model.primaryKey.length !== 1) {\n\t\tthrow new TableModelError(\n\t\t\t'KEY_INCOMPLETE',\n\t\t\tmodel.primaryKey.length === 0\n\t\t\t\t? 'This table has no primary key, so its records cannot be changed.'\n\t\t\t\t: 'This table has a multi-field key; pass every key field.',\n\t\t\t{ tableKey: model.key },\n\t\t);\n\t}\n\treturn { [model.primaryKey[0]!]: identifier };\n}\n\n/** Use scalar IDs as cache keys for compatibility; use serialized identities otherwise. */\nexport function sheetsIdentifierCacheKey(\n\ttable: MetaTable,\n\tidentifier: SheetsRowIdentifier,\n): string | number | null {\n\tconst resolution = resolveSheetsIdentifier(table, identifier);\n\tif (resolution.status !== 'identified') return null;\n\treturn typeof resolution.identifier === 'object'\n\t\t? resolution.key\n\t\t: resolution.identifier;\n}\n\n/** Stable TanStack/selection/editor key with an index fallback only for non-writable rows. */\nexport function sheetsRowKey(\n\ttable: MetaTable,\n\trow: Readonly<Record<string, unknown>>,\n\tindex: number,\n): string {\n\tconst resolution = resolveSheetsRowIdentity(table, row);\n\tif (resolution.status === 'identified') {\n\t\treturn typeof resolution.identifier === 'object'\n\t\t\t? resolution.key\n\t\t\t: String(resolution.identifier);\n\t}\n\treturn `${table.schemaName ?? ''}:${table.name}:row:${index}`;\n}\n\nexport function getSheetsWriteCapability(table: MetaTable | null): TableWriteCapability | null {\n\treturn table ? assessTableWriteCapability(table) : null;\n}\n\nexport function canRunSheetsMutation(\n\tcapability: TableWriteCapability | null,\n\toperation: SheetsMutationOperation,\n): boolean {\n\tif (!capability || capability.status !== 'mutable') return false;\n\treturn capability.operations[operation];\n}\n\nexport function assertSheetsMutationAllowed(\n\ttable: MetaTable,\n\toperation: SheetsMutationOperation,\n): void {\n\tconst capability = assessTableWriteCapability(table);\n\tif (capability.status === 'read-only') {\n\t\tthrow new Error(`Table '${table.name}' is read-only because it has no primary key.`);\n\t}\n\tif (!capability.operations[operation]) {\n\t\tconst article = operation === 'update' ? 'an' : 'a';\n\t\tthrow new Error(`Table '${table.name}' does not expose ${article} ${operation} mutation.`);\n\t}\n}\n","import {\n\tTableModelError,\n\tMETA_CAPABILITY_INTROSPECTION_DOCUMENT,\n\tMetaContractError,\n\tassessMetaCapabilities,\n\tassertMetaQuery,\n\tbuildCreateDocument,\n\tbuildDeleteDocument,\n\tbuildListDocument,\n\tbuildMetaDocument,\n\tbuildUpdateDocument,\n\tcreateTableModelResolver,\n} from '@constructive-io/data';\nimport type {\n\tListResult,\n\tMetaCapabilities,\n\tMetaCapabilityIntrospectionQuery,\n\tMetaQuery,\n\tMutationOptions,\n\tTableModel,\n\tTableModelResolver,\n} from '@constructive-io/data';\n\nimport { partialResultOf, type SheetsExecuteFn } from '../context/sheets-execute';\nimport { sheetsIdentifierToRowKey, type SheetsRowIdentifier } from '../row-identity';\nimport type {\n\tAdapterListQuery,\n\tAdapterListResult,\n\tAdapterTableContext,\n\tAdapterTableModelOptions,\n\tSheetsBackendAdapter,\n} from './sheets-adapter';\n\n/** Capability preflight, once per executor. */\nconst capabilityChecks = new WeakMap<SheetsExecuteFn, Promise<MetaCapabilities>>();\n/** One model resolver per `_meta` result, so each schema version keeps its own type cache. */\nconst resolvers = new WeakMap<MetaQuery, TableModelResolver>();\n\nasync function ensureMetaCapabilities(execute: SheetsExecuteFn): Promise<MetaCapabilities> {\n\tconst cached = capabilityChecks.get(execute);\n\tif (cached) return cached;\n\n\tconst check = execute<MetaCapabilityIntrospectionQuery>(META_CAPABILITY_INTROSPECTION_DOCUMENT).then((result) => {\n\t\tconst { compatibility, capabilities } = assessMetaCapabilities(result);\n\t\tif (compatibility.status !== 'compatible') throw new MetaContractError(compatibility);\n\t\treturn capabilities;\n\t});\n\tcapabilityChecks.set(execute, check);\n\n\ttry {\n\t\treturn await check;\n\t} catch (error) {\n\t\t// Contract mismatches remain deterministic, while transport failures can\n\t\t// recover on a later call instead of poisoning this executor forever.\n\t\tif (capabilityChecks.get(execute) === check) capabilityChecks.delete(execute);\n\t\tthrow error;\n\t}\n}\n\nfunction resolverFor(meta: MetaQuery): TableModelResolver {\n\tlet resolver = resolvers.get(meta);\n\tif (!resolver) {\n\t\tresolver = createTableModelResolver(meta);\n\t\tresolvers.set(meta, resolver);\n\t}\n\treturn resolver;\n}\n\n\n/**\n * Create the default PostGraphile-backed adapter. The metadata preflight makes\n * an outdated endpoint distinguishable from an ordinary transport failure and\n * tells which optional `_meta` fields the server has. Table models resolve\n * lazily, one table at a time, from targeted introspection.\n */\n/**\n * An update or delete the server answered without changing a row: no row matched, because a\n * row rule hides it from this user or it is gone. The server reports that without an error,\n * so without this check a refused write would read as saved.\n */\nfunction writeNotApplied(model: TableModel, action: 'update' | 'delete'): TableModelError {\n\tconst message = action === 'update'\n\t\t? 'This record was not changed. You may not be allowed to change it, or it no longer exists.'\n\t\t: 'This record was not deleted. You may not be allowed to delete it, or it no longer exists.';\n\treturn new TableModelError('WRITE_NOT_APPLIED', message, { tableKey: model.key });\n}\n\nexport function createPostGraphileAdapter(): SheetsBackendAdapter {\n\treturn {\n\t\tasync fetchMeta(execute: SheetsExecuteFn): Promise<MetaQuery> {\n\t\t\tconst capabilities = await ensureMetaCapabilities(execute);\n\t\t\tconst meta = await execute<MetaQuery>(buildMetaDocument(capabilities));\n\t\t\tassertMetaQuery(meta);\n\t\t\treturn meta;\n\t\t},\n\n\t\tasync fetchTableModel(\n\t\t\texecute: SheetsExecuteFn,\n\t\t\tmeta: MetaQuery,\n\t\t\ttableRef: string,\n\t\t\toptions: AdapterTableModelOptions = {},\n\t\t): Promise<TableModel> {\n\t\t\treturn resolverFor(meta).resolve(execute, tableRef, { displayOverrides: options.displayOverrides });\n\t\t},\n\n\t\tasync listRows<T = Record<string, unknown>>(\n\t\t\tctx: AdapterTableContext,\n\t\t\tquery: AdapterListQuery,\n\t\t\texecute: SheetsExecuteFn,\n\t\t): Promise<AdapterListResult<T>> {\n\t\t\tconst { model } = ctx;\n\t\t\tconst document = buildListDocument(model, {\n\t\t\t\tfirst: query.limit,\n\t\t\t\toffset: query.offset ? query.offset : undefined,\n\t\t\t\tafter: query.after,\n\t\t\t\twhere: query.where,\n\t\t\t\torderBy: query.orderBy,\n\t\t\t\trelations: query.relations,\n\t\t\t\trelationPageSize: query.relationPageSize,\n\t\t\t\tcolumns: query.columns,\n\t\t\t\ttotalCount: query.includeTotalCount !== false,\n\t\t\t});\n\t\t\tlet result: ListResult;\n\t\t\ttry {\n\t\t\t\tresult = document.read(await execute(document.document, document.variables, { signal: query.signal }));\n\t\t\t} catch (error) {\n\t\t\t\t// Rows with cells the API could not serve (a float NaN) still load; each such\n\t\t\t\t// cell carries its error. Any other failure fails the read as before.\n\t\t\t\tconst partial = partialResultOf(error);\n\t\t\t\tif (!partial) throw error;\n\t\t\t\ttry {\n\t\t\t\t\tresult = document.read(partial.data, partial.errors);\n\t\t\t\t} catch {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trows: result.rows as T[],\n\t\t\t\ttotalCount: result.totalCount ?? result.rows.length,\n\t\t\t\tpageInfo: result.pageInfo ?? undefined,\n\t\t\t};\n\t\t},\n\n\t\tasync createRow<T = Record<string, unknown>>(\n\t\t\tctx: AdapterTableContext,\n\t\t\tdata: Record<string, unknown>,\n\t\t\texecute: SheetsExecuteFn,\n\t\t\toptions: MutationOptions = {},\n\t\t): Promise<T | null> {\n\t\t\t// The caller decides which fields a new row gets: an empty string or a null is sent\n\t\t\t// as given, and a field that is left out is simply absent (the codec skips undefined).\n\t\t\tconst { model } = ctx;\n\t\t\tconst document = buildCreateDocument(model, data, { returning: options.returning });\n\t\t\treturn document.read(await execute(document.document, document.variables)) as T | null;\n\t\t},\n\n\t\tasync updateRow<T = Record<string, unknown>>(\n\t\t\tctx: AdapterTableContext,\n\t\t\tid: SheetsRowIdentifier,\n\t\t\tpatch: Record<string, unknown>,\n\t\t\texecute: SheetsExecuteFn,\n\t\t\toptions: MutationOptions = {},\n\t\t): Promise<T | null> {\n\t\t\t// Clearing a field to null or '' is a real change and reaches the server.\n\t\t\tif (!Object.values(patch).some((value) => value !== undefined)) return null;\n\t\t\tconst { model } = ctx;\n\t\t\tconst document = buildUpdateDocument(model, sheetsIdentifierToRowKey(model, id), patch, {\n\t\t\t\treturning: options.returning,\n\t\t\t});\n\t\t\tconst data = await execute(document.document, document.variables);\n\t\t\tif (document.applied?.(data) === false) throw writeNotApplied(model, 'update');\n\t\t\treturn document.read(data) as T | null;\n\t\t},\n\n\t\tasync deleteRow(ctx: AdapterTableContext, id: SheetsRowIdentifier, execute: SheetsExecuteFn): Promise<void> {\n\t\t\tconst { model } = ctx;\n\t\t\tconst document = buildDeleteDocument(model, sheetsIdentifierToRowKey(model, id));\n\t\t\tconst data = await execute(document.document, document.variables);\n\t\t\tif (document.applied?.(data) === false) throw writeNotApplied(model, 'delete');\n\t\t},\n\t};\n}\n","import { createPostGraphileAdapter } from './postgraphile-adapter';\nimport type { SheetsBackendAdapter } from './sheets-adapter';\nimport { useSheetsContext } from '../context/sheets-context';\n\n// Stable module-level singleton: the default adapter is stateless, so every hook\n// that falls back to it shares one instance (no per-render churn).\nconst defaultAdapter = createPostGraphileAdapter();\n\n/**\n * Resolve the active backend adapter. A consumer that never sets\n * `config.adapter` transparently gets the default PostGraphile adapter,\n * preserving today's behavior exactly.\n */\nexport function useSheetsAdapter(): SheetsBackendAdapter {\n\tconst { config } = useSheetsContext();\n\treturn config.adapter ?? defaultAdapter;\n}\n","/**\n * Filter operators from the table model.\n *\n * A column offers exactly the operators its filter input really has\n * (`ColumnModel.filter.operators`). Each operator gets a plain label, a group,\n * and the value control its input shape and the column's kind call for. An\n * operator this file does not know still appears, named from its field name.\n */\nimport type { ColumnModel, ColumnOption, FilterOperatorModel, InputValueModel } from '@constructive-io/data';\n\nexport type FilterOperatorGroup = 'match' | 'text' | 'compare' | 'items' | 'empty' | 'other';\n\n/** Group headings, in display order. */\nexport const FILTER_OPERATOR_GROUPS: readonly { group: FilterOperatorGroup; label: string }[] = [\n\t{ group: 'match', label: 'Match' },\n\t{ group: 'text', label: 'Text' },\n\t{ group: 'compare', label: 'Compare' },\n\t{ group: 'items', label: 'Items' },\n\t{ group: 'empty', label: 'Empty' },\n\t{ group: 'other', label: 'More' },\n];\n\n/** A control for one value. */\nexport type ScalarValueControl =\n\t| { kind: 'text' }\n\t/** A whole number that fits a JavaScript number; sent as a number. */\n\t| { kind: 'integer' }\n\t/** A floating-point number; sent as a number. */\n\t| { kind: 'number' }\n\t/** A whole number of any size; sent as exact text. */\n\t| { kind: 'exact-integer' }\n\t/** A decimal number of any size; sent as exact text. */\n\t| { kind: 'exact-decimal' }\n\t| { kind: 'date' }\n\t| { kind: 'datetime' }\n\t| { kind: 'time' }\n\t| { kind: 'boolean' }\n\t/** One of a fixed list. `value` is the wire value. */\n\t| { kind: 'choice'; options: readonly ColumnOption[] }\n\t| { kind: 'json' };\n\nexport interface FilterValueField {\n\tname: string;\n\tlabel: string;\n\trequired: boolean;\n\tcontrol: ScalarValueControl;\n}\n\n/** The control a condition shows for its operator. */\nexport type FilterValueControl =\n\t| ScalarValueControl\n\t/** The operator takes no value from the user. */\n\t| { kind: 'none' }\n\t/** The operator takes a list of values. */\n\t| { kind: 'multi'; item: ScalarValueControl }\n\t/** The operator takes an object: one control per field. */\n\t| { kind: 'fields'; fields: readonly FilterValueField[] }\n\t/** The editor cannot enter this operator's value. */\n\t| { kind: 'unsupported'; reason: string };\n\nexport interface FilterOperatorOption {\n\t/** Unique within a column: the operator name, or `isNull:true` / `isNull:false`. */\n\tid: string;\n\t/** Operator field name. */\n\toperator: string;\n\tlabel: string;\n\tgroup: FilterOperatorGroup;\n\tcontrol: FilterValueControl;\n\t/** The operand of an operator that takes no value from the user (`isNull`). */\n\tfixedValue?: boolean;\n}\n\nconst UNSUPPORTED_VALUE = 'This condition needs a value the filter editor cannot enter yet.';\n\nconst GENERIC_LABELS: Readonly<Record<string, string>> = {\n\tequalTo: 'is',\n\tnotEqualTo: 'is not',\n\tin: 'is any of',\n\tnotIn: 'is none of',\n\tequalToInsensitive: 'is (any case)',\n\tnotEqualToInsensitive: 'is not (any case)',\n\tinInsensitive: 'is any of (any case)',\n\tnotInInsensitive: 'is none of (any case)',\n\tdistinctFrom: 'is not, counting empty',\n\tnotDistinctFrom: 'is, counting empty',\n\tdistinctFromInsensitive: 'is not (any case), counting empty',\n\tnotDistinctFromInsensitive: 'is (any case), counting empty',\n\tincludesInsensitive: 'contains',\n\tnotIncludesInsensitive: 'does not contain',\n\tincludes: 'contains (exact case)',\n\tnotIncludes: 'does not contain (exact case)',\n\tstartsWithInsensitive: 'starts with',\n\tnotStartsWithInsensitive: 'does not start with',\n\tstartsWith: 'starts with (exact case)',\n\tnotStartsWith: 'does not start with (exact case)',\n\tendsWithInsensitive: 'ends with',\n\tnotEndsWithInsensitive: 'does not end with',\n\tendsWith: 'ends with (exact case)',\n\tnotEndsWith: 'does not end with (exact case)',\n\tlikeInsensitive: 'matches pattern',\n\tnotLikeInsensitive: 'does not match pattern',\n\tlike: 'matches pattern (exact case)',\n\tnotLike: 'does not match pattern (exact case)',\n\tmatches: 'matches',\n\tsimilarTo: 'is similar to',\n\twordSimilarTo: 'has a word similar to',\n\tlessThan: 'is less than',\n\tlessThanOrEqualTo: 'is at most',\n\tgreaterThan: 'is greater than',\n\tgreaterThanOrEqualTo: 'is at least',\n\tlessThanInsensitive: 'comes before (any case)',\n\tlessThanOrEqualToInsensitive: 'comes before or is (any case)',\n\tgreaterThanInsensitive: 'comes after (any case)',\n\tgreaterThanOrEqualToInsensitive: 'comes after or is (any case)',\n\tcontains: 'contains',\n\tcontainedBy: 'is within',\n\toverlaps: 'overlaps',\n\tanyEqualTo: 'has an item that is',\n\tanyNotEqualTo: 'has an item that is not',\n\tanyLessThan: 'has an item less than',\n\tanyLessThanOrEqualTo: 'has an item at most',\n\tanyGreaterThan: 'has an item greater than',\n\tanyGreaterThanOrEqualTo: 'has an item at least',\n\tcontainsKey: 'has the key',\n\tcontainsAllKeys: 'has all of the keys',\n\tcontainsAnyKeys: 'has any of the keys',\n\tcontainsOrEqualTo: 'contains or is',\n\tcontainedByOrEqualTo: 'is within or is',\n\tcontainsOrContainedBy: 'contains or is within',\n\tcontainsElement: 'contains the value',\n\tstrictlyLeftOf: 'is entirely before',\n\tstrictlyRightOf: 'is entirely after',\n\tnotExtendsRightOf: 'does not reach past',\n\tnotExtendsLeftOf: 'does not start before',\n\tadjacentTo: 'is next to',\n\twithin: 'is within',\n};\n\nconst NUMBER_LABELS: Readonly<Record<string, string>> = {\n\tequalTo: '=',\n\tnotEqualTo: '≠',\n\tlessThan: '<',\n\tlessThanOrEqualTo: '≤',\n\tgreaterThan: '>',\n\tgreaterThanOrEqualTo: '≥',\n};\n\nconst TIME_LABELS: Readonly<Record<string, string>> = {\n\tlessThan: 'is before',\n\tlessThanOrEqualTo: 'is on or before',\n\tgreaterThan: 'is after',\n\tgreaterThanOrEqualTo: 'is on or after',\n};\n\nconst LIST_LABELS: Readonly<Record<string, string>> = {\n\tequalTo: 'is exactly',\n\tnotEqualTo: 'is not exactly',\n\tcontains: 'has all of',\n\tcontainedBy: 'has only items from',\n\toverlaps: 'has any of',\n};\n\nconst PATH_LABELS: Readonly<Record<string, string>> = {\n\twithin: 'is under',\n\tancestorOf: 'is above',\n\tglob: 'matches path pattern',\n};\n\nconst GROUP_OF: Readonly<Record<string, FilterOperatorGroup>> = {\n\tequalTo: 'match',\n\tnotEqualTo: 'match',\n\tin: 'match',\n\tnotIn: 'match',\n\tequalToInsensitive: 'match',\n\tnotEqualToInsensitive: 'match',\n\tinInsensitive: 'match',\n\tnotInInsensitive: 'match',\n\tincludesInsensitive: 'text',\n\tnotIncludesInsensitive: 'text',\n\tincludes: 'text',\n\tnotIncludes: 'text',\n\tstartsWithInsensitive: 'text',\n\tnotStartsWithInsensitive: 'text',\n\tstartsWith: 'text',\n\tnotStartsWith: 'text',\n\tendsWithInsensitive: 'text',\n\tnotEndsWithInsensitive: 'text',\n\tendsWith: 'text',\n\tnotEndsWith: 'text',\n\tlikeInsensitive: 'text',\n\tnotLikeInsensitive: 'text',\n\tlike: 'text',\n\tnotLike: 'text',\n\tmatches: 'text',\n\tsimilarTo: 'text',\n\twordSimilarTo: 'text',\n\tlessThan: 'compare',\n\tlessThanOrEqualTo: 'compare',\n\tgreaterThan: 'compare',\n\tgreaterThanOrEqualTo: 'compare',\n\tcontains: 'items',\n\tcontainedBy: 'items',\n\toverlaps: 'items',\n\tanyEqualTo: 'items',\n\tanyNotEqualTo: 'items',\n\tanyLessThan: 'items',\n\tanyLessThanOrEqualTo: 'items',\n\tanyGreaterThan: 'items',\n\tanyGreaterThanOrEqualTo: 'items',\n\tcontainsKey: 'items',\n\tcontainsAllKeys: 'items',\n\tcontainsAnyKeys: 'items',\n\tisNull: 'empty',\n};\n\n/** Display order: operators named here come first within their group, in this order. */\nconst PREFERRED_ORDER = Object.keys(GROUP_OF);\n\n/** Operators whose value is compared for equality, so a column's option list applies. */\nconst OPTION_OPERATORS = new Set([\n\t'equalTo',\n\t'notEqualTo',\n\t'distinctFrom',\n\t'notDistinctFrom',\n\t'in',\n\t'notIn',\n\t'contains',\n\t'containedBy',\n\t'overlaps',\n\t'anyEqualTo',\n\t'anyNotEqualTo',\n]);\n\n/** A readable name from an operator field name: `bboxIntersects2D` -> `bbox intersects 2D`. */\nexport function humanizeOperatorName(name: string): string {\n\tconst words = name\n\t\t.replace(/([a-z])([A-Z0-9])/g, '$1 $2')\n\t\t.replace(/([0-9])([A-Z][a-z])/g, '$1 $2')\n\t\t.split(/\\s+/)\n\t\t.filter(Boolean)\n\t\t.map((word, index) => (index > 0 && /^[A-Z][a-z]/.test(word) ? word.toLowerCase() : word));\n\treturn words.join(' ') || name;\n}\n\n/** A readable name from an input field name: `postalCode` -> `Postal code`. */\nfunction humanizeFieldName(name: string): string {\n\tconst text = humanizeOperatorName(name).replace(/_/g, ' ');\n\treturn text.charAt(0).toUpperCase() + text.slice(1);\n}\n\nfunction isNumericKind(column: ColumnModel): boolean {\n\tconst { kind } = column.value;\n\treturn kind === 'integer' || kind === 'bigint' || kind === 'decimal' || kind === 'float';\n}\n\nfunction isTimeKind(column: ColumnModel): boolean {\n\tconst { kind } = column.value;\n\treturn kind === 'date' || kind === 'time' || kind === 'datetime';\n}\n\n/** The label of one operator on one column. */\nexport function filterOperatorLabel(column: ColumnModel, operator: string): string {\n\tif (column.value.isArray && LIST_LABELS[operator]) return LIST_LABELS[operator]!;\n\tif (column.value.kind === 'path' && PATH_LABELS[operator]) return PATH_LABELS[operator]!;\n\tif (!column.value.isArray && isNumericKind(column) && NUMBER_LABELS[operator]) return NUMBER_LABELS[operator]!;\n\tif (!column.value.isArray && isTimeKind(column) && TIME_LABELS[operator]) return TIME_LABELS[operator]!;\n\treturn GENERIC_LABELS[operator] ?? humanizeOperatorName(operator);\n}\n\nfunction enumOptions(input: InputValueModel, column: ColumnModel | null): ColumnOption[] {\n\tconst labels = new Map((column?.value.options ?? []).map((option) => [option.value, option.label]));\n\treturn (input.enumValues ?? []).map((value) => ({ value, label: labels.get(value) ?? humanizeFieldName(value.toLowerCase()) }));\n}\n\n/** The control for a scalar of a known GraphQL scalar type, or null for an unknown type. */\nfunction builtinScalarControl(typeName: string): ScalarValueControl | null {\n\tswitch (typeName) {\n\t\tcase 'Boolean':\n\t\t\treturn { kind: 'boolean' };\n\t\tcase 'Int':\n\t\t\treturn { kind: 'integer' };\n\t\tcase 'Float':\n\t\t\treturn { kind: 'number' };\n\t\tcase 'BigInt':\n\t\t\treturn { kind: 'exact-integer' };\n\t\tcase 'BigFloat':\n\t\t\treturn { kind: 'exact-decimal' };\n\t\tcase 'Date':\n\t\t\treturn { kind: 'date' };\n\t\tcase 'Datetime':\n\t\t\treturn { kind: 'datetime' };\n\t\tcase 'Time':\n\t\t\treturn { kind: 'time' };\n\t\tcase 'JSON':\n\t\tcase 'GeoJSON':\n\t\t\treturn { kind: 'json' };\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/** The control for the column's own value kind (a domain type over a number, a date, ...). */\nfunction kindControl(column: ColumnModel): ScalarValueControl {\n\tswitch (column.value.kind) {\n\t\tcase 'integer':\n\t\t\treturn { kind: 'integer' };\n\t\tcase 'bigint':\n\t\t\treturn { kind: 'exact-integer' };\n\t\tcase 'decimal':\n\t\t\treturn { kind: 'exact-decimal' };\n\t\tcase 'float':\n\t\t\treturn { kind: 'number' };\n\t\tcase 'date':\n\t\t\treturn { kind: 'date' };\n\t\tcase 'time':\n\t\t\treturn { kind: 'time' };\n\t\tcase 'datetime':\n\t\t\treturn { kind: 'datetime' };\n\t\tcase 'boolean':\n\t\t\treturn { kind: 'boolean' };\n\t\tcase 'json':\n\t\tcase 'vector':\n\t\tcase 'geometry':\n\t\t\treturn { kind: 'json' };\n\t\tcase 'file':\n\t\t\t// An attachment is a URL; an image or upload is a file object.\n\t\t\treturn column.value.file?.kind === 'attachment' || column.value.semantic === 'attachment' ? { kind: 'text' } : { kind: 'json' };\n\t\tdefault:\n\t\t\treturn { kind: 'text' };\n\t}\n}\n\nfunction scalarControl(input: InputValueModel, column: ColumnModel | null, operator: string): ScalarValueControl | null {\n\tif (input.shape === 'enum') {\n\t\tconst options = enumOptions(input, column);\n\t\treturn options.length > 0 ? { kind: 'choice', options } : null;\n\t}\n\tif (input.shape !== 'scalar') return null;\n\tif (input.typeName === 'Boolean') return { kind: 'boolean' };\n\tconst ownType = column && (input.typeName === column.value.input?.typeName || input.typeName === column.value.typeName);\n\tif (column && ownType && column.value.options && column.value.options.length > 0 && OPTION_OPERATORS.has(operator)) {\n\t\treturn { kind: 'choice', options: column.value.options };\n\t}\n\tif (column && ownType) return kindControl(column);\n\treturn builtinScalarControl(input.typeName) ?? { kind: 'text' };\n}\n\nfunction objectControl(input: InputValueModel): FilterValueControl {\n\tif (!input.fields || input.fields.length === 0) return { kind: 'unsupported', reason: UNSUPPORTED_VALUE };\n\tconst fields: FilterValueField[] = [];\n\tfor (const field of input.fields) {\n\t\tif (field.value.isList) return { kind: 'unsupported', reason: UNSUPPORTED_VALUE };\n\t\tconst control = scalarControl(field.value, null, field.name);\n\t\tif (!control) return { kind: 'unsupported', reason: UNSUPPORTED_VALUE };\n\t\tfields.push({ name: field.name, label: humanizeFieldName(field.name), required: field.required, control });\n\t}\n\treturn { kind: 'fields', fields };\n}\n\n/** The value control for one operator of one column. */\nexport function filterValueControl(column: ColumnModel, operator: FilterOperatorModel): FilterValueControl {\n\tconst { input } = operator;\n\tif (input.shape === 'object') {\n\t\treturn input.isList ? { kind: 'unsupported', reason: UNSUPPORTED_VALUE } : objectControl(input);\n\t}\n\tconst item = scalarControl(input, column, operator.name);\n\tif (!item) return { kind: 'unsupported', reason: UNSUPPORTED_VALUE };\n\treturn input.isList ? { kind: 'multi', item } : item;\n}\n\nfunction orderIndex(operator: string): number {\n\tconst index = PREFERRED_ORDER.indexOf(operator);\n\treturn index === -1 ? PREFERRED_ORDER.length : index;\n}\n\n/**\n * Every operator a column's filter has, as the builder offers them: grouped,\n * labelled, each with its value control. `isNull` becomes two choices, \"is\n * empty\" and \"is not empty\". Empty when the column cannot be filtered.\n */\nexport function filterOperatorOptions(column: ColumnModel): FilterOperatorOption[] {\n\tconst operators = column.filter?.operators ?? [];\n\tconst options: FilterOperatorOption[] = [];\n\tfor (const operator of operators) {\n\t\tif (operator.name === 'isNull' && operator.input.shape === 'scalar' && operator.input.typeName === 'Boolean') {\n\t\t\toptions.push(\n\t\t\t\t{ id: 'isNull:true', operator: 'isNull', label: 'is empty', group: 'empty', control: { kind: 'none' }, fixedValue: true },\n\t\t\t\t{ id: 'isNull:false', operator: 'isNull', label: 'is not empty', group: 'empty', control: { kind: 'none' }, fixedValue: false },\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\t\toptions.push({\n\t\t\tid: operator.name,\n\t\t\toperator: operator.name,\n\t\t\tlabel: filterOperatorLabel(column, operator.name),\n\t\t\tgroup: GROUP_OF[operator.name] ?? 'other',\n\t\t\tcontrol: filterValueControl(column, operator),\n\t\t});\n\t}\n\tconst groupOrder = FILTER_OPERATOR_GROUPS.map((entry) => entry.group);\n\treturn options\n\t\t.map((option, position) => ({ option, position }))\n\t\t.sort(\n\t\t\t(left, right) =>\n\t\t\t\tgroupOrder.indexOf(left.option.group) - groupOrder.indexOf(right.option.group) ||\n\t\t\t\torderIndex(left.option.operator) - orderIndex(right.option.operator) ||\n\t\t\t\tleft.position - right.position,\n\t\t)\n\t\t.map((entry) => entry.option);\n}\n\n/** The option a condition uses: its operator, and for `isNull` its boolean operand. */\nexport function findOperatorOption(\n\toptions: readonly FilterOperatorOption[],\n\toperator: string,\n\tvalue: unknown,\n): FilterOperatorOption | null {\n\tif (operator === 'isNull') return options.find((option) => option.operator === 'isNull' && option.fixedValue === (value !== false)) ?? null;\n\treturn options.find((option) => option.operator === operator) ?? null;\n}\n\n/** Operators a new condition prefers, by what the column holds. */\nfunction defaultPreference(column: ColumnModel): readonly string[] {\n\tif (column.value.isArray) return ['contains', 'anyEqualTo', 'overlaps', 'equalTo'];\n\tif (column.value.options?.length || column.value.kind === 'enum') return ['in', 'equalTo'];\n\tif (column.value.kind === 'text') return ['includesInsensitive', 'includes', 'equalTo'];\n\treturn ['equalTo'];\n}\n\n/** The operator a new condition on this column starts with. */\nexport function defaultOperatorOption(column: ColumnModel): FilterOperatorOption | null {\n\tconst options = filterOperatorOptions(column).filter((option) => option.control.kind !== 'unsupported');\n\tfor (const name of defaultPreference(column)) {\n\t\tconst match = options.find((option) => option.operator === name);\n\t\tif (match) return match;\n\t}\n\treturn options[0] ?? null;\n}\n\n/** True when the column has at least one operator the builder can use. */\nexport function isColumnFilterable(column: ColumnModel): boolean {\n\treturn column.readable && defaultOperatorOption(column) !== null;\n}\n","/**\n * Column layout: pure helpers over `SheetsColumnLayout`.\n *\n * `available` is always the table's grid column keys in the table's order\n * (`gridColumnKeys(model)`). A layout names keys by field name, so it survives\n * a schema change: keys it names that the table lost are ignored here (and\n * reported by the validator), keys the table gained follow at the end.\n */\nimport type { ColumnValueKind, TableModel } from '@constructive-io/data';\n\nimport type { SheetsColumnLayout, SheetsRowHeight } from '../view-state/view-state.types';\n\n/** Row height of each setting, in pixels. */\nexport const ROW_HEIGHT_PX: Readonly<Record<SheetsRowHeight, number>> = {\n\tshort: 32,\n\tmedium: 44,\n\ttall: 64,\n\textraTall: 96,\n};\n\nexport const ROW_HEIGHT_LABELS: Readonly<Record<SheetsRowHeight, string>> = {\n\tshort: 'Short',\n\tmedium: 'Medium',\n\ttall: 'Tall',\n\textraTall: 'Extra tall',\n};\n\nexport const ROW_HEIGHTS = Object.keys(ROW_HEIGHT_PX) as SheetsRowHeight[];\n\n/** Narrowest and widest a column can be dragged or stored. */\nexport const MIN_COLUMN_WIDTH = 40;\nexport const MAX_COLUMN_WIDTH = 2000;\n\n/** The layout with every column shown in the table's order and the first column frozen. */\nexport function createColumnLayout(): SheetsColumnLayout {\n\treturn { order: [], hidden: [], frozenCount: 1, widths: {}, rowHeight: 'medium' };\n}\n\n/** Every available key in display order: the layout's order first, then the rest in the table's order. */\nexport function orderedColumnKeys(available: readonly string[], layout: SheetsColumnLayout): string[] {\n\tconst known = new Set(available);\n\tconst named = layout.order.filter((key) => known.has(key));\n\tconst placed = new Set(named);\n\treturn [...named, ...available.filter((key) => !placed.has(key))];\n}\n\n/** The keys that show, in display order. */\nexport function visibleColumnKeys(available: readonly string[], layout: SheetsColumnLayout): string[] {\n\tconst hidden = new Set(layout.hidden);\n\treturn orderedColumnKeys(available, layout).filter((key) => !hidden.has(key));\n}\n\n/** How many leading visible columns stay in place, within the visible count. */\nexport function effectiveFrozenCount(available: readonly string[], layout: SheetsColumnLayout): number {\n\treturn Math.max(0, Math.min(layout.frozenCount, visibleColumnKeys(available, layout).length));\n}\n\n/** The layout with `key` shown or hidden. */\nexport function setColumnHidden(layout: SheetsColumnLayout, key: string, hidden: boolean): SheetsColumnLayout {\n\tconst rest = layout.hidden.filter((entry) => entry !== key);\n\treturn { ...layout, hidden: hidden ? [...rest, key] : rest };\n}\n\n/** Show every column. */\nexport function showAllColumns(layout: SheetsColumnLayout): SheetsColumnLayout {\n\treturn { ...layout, hidden: [] };\n}\n\n/** Hide every column but the first one in display order (at least one column always shows). */\nexport function hideAllColumns(available: readonly string[], layout: SheetsColumnLayout): SheetsColumnLayout {\n\tconst [first, ...rest] = orderedColumnKeys(available, layout);\n\treturn first === undefined ? layout : { ...layout, hidden: rest };\n}\n\n/** The layout with `key` moved to `index` of the full display order. */\nexport function moveColumnTo(\n\tavailable: readonly string[],\n\tlayout: SheetsColumnLayout,\n\tkey: string,\n\tindex: number,\n): SheetsColumnLayout {\n\tconst order = orderedColumnKeys(available, layout);\n\tconst from = order.indexOf(key);\n\tif (from === -1) return layout;\n\torder.splice(from, 1);\n\torder.splice(Math.max(0, Math.min(index, order.length)), 0, key);\n\treturn { ...layout, order };\n}\n\n/** The layout with `key` placed just before or after `target` (header drag, Fields drag). */\nexport function moveColumnBeside(\n\tavailable: readonly string[],\n\tlayout: SheetsColumnLayout,\n\tkey: string,\n\ttarget: string,\n\tside: 'before' | 'after',\n): SheetsColumnLayout {\n\tif (key === target) return layout;\n\tconst without = orderedColumnKeys(available, layout).filter((entry) => entry !== key);\n\tconst at = without.indexOf(target);\n\tif (at === -1) return layout;\n\twithout.splice(side === 'before' ? at : at + 1, 0, key);\n\treturn { ...layout, order: without };\n}\n\n/**\n * The layout with `key` moved one place among the visible columns (header\n * menu, keyboard). Hidden columns in between keep their places.\n */\nexport function moveColumnStep(\n\tavailable: readonly string[],\n\tlayout: SheetsColumnLayout,\n\tkey: string,\n\tstep: -1 | 1,\n): SheetsColumnLayout {\n\tconst visible = visibleColumnKeys(available, layout);\n\tconst at = visible.indexOf(key);\n\tconst neighbour = visible[at + step];\n\tif (at === -1 || neighbour === undefined) return layout;\n\treturn moveColumnBeside(available, layout, key, neighbour, step === -1 ? 'before' : 'after');\n}\n\n/** Freeze the visible columns up to and including `key`. */\nexport function freezeColumnsUpTo(available: readonly string[], layout: SheetsColumnLayout, key: string): SheetsColumnLayout {\n\tconst at = visibleColumnKeys(available, layout).indexOf(key);\n\treturn at === -1 ? layout : { ...layout, frozenCount: at + 1 };\n}\n\nexport function clampColumnWidth(width: number): number {\n\treturn Math.round(Math.max(MIN_COLUMN_WIDTH, Math.min(MAX_COLUMN_WIDTH, width)));\n}\n\n/** The layout with a stored width for `key`. */\nexport function setColumnWidth(layout: SheetsColumnLayout, key: string, width: number): SheetsColumnLayout {\n\tconst next = clampColumnWidth(width);\n\treturn layout.widths[key] === next ? layout : { ...layout, widths: { ...layout.widths, [key]: next } };\n}\n\n/** Value kinds that read at a glance in a narrow column: a checkbox and numbers. */\nconst NARROW_KINDS: ReadonlySet<ColumnValueKind> = new Set<ColumnValueKind>(['boolean', 'integer', 'bigint', 'decimal', 'float']);\n\n/**\n * The table's checkbox and number columns (single values, not lists). When the grid is\n * wider than its columns, they keep their width while other columns can take the space.\n */\nexport function narrowColumnNames(model: TableModel | null): ReadonlySet<string> {\n\tconst names = (model?.columns ?? []).filter((column) => !column.value.isArray && NARROW_KINDS.has(column.value.kind)).map((column) => column.name);\n\treturn new Set(names);\n}\n","/**\n * The filter, sort, search and column layout of one grid, as one serializable\n * value.\n *\n * Columns and relations are named by their field name in the table model, so a\n * host can store the value (a saved view) and load it later. Load a stored value\n * through `validateSheetsViewState`: it drops every part the current model no\n * longer supports and says what it dropped, and it upgrades a version 1 value\n * (no column layout) to the current version.\n */\n\n/** Version of the state shape. Version 2 added `columns`. */\nexport const SHEETS_VIEW_STATE_VERSION = 2;\n\n/** How the children of a filter group combine. */\nexport type SheetsFilterLogic = 'and' | 'or';\n\n/**\n * A filter value as the user entered it: text (exact decimal text for big\n * numbers, ISO text for dates, times and timestamps), a boolean, a list of\n * values for list operators, field values for an operator that takes an object,\n * or null for an operator without a value.\n */\nexport type SheetsFilterValue = string | boolean | readonly string[] | Readonly<Record<string, string>> | null;\n\n/** A condition on one column. */\nexport interface SheetsColumnCondition {\n\tkind: 'column';\n\t/** Stable id within the state. */\n\tid: string;\n\t/** Column field name. */\n\tcolumn: string;\n\t/** Operator name the column's filter really has, for example `includesInsensitive`. */\n\toperator: string;\n\tvalue: SheetsFilterValue;\n}\n\n/** What a relation condition tests. */\nexport type SheetsRelationTest = 'any' | 'none' | 'labelContains';\n\n/** A condition on one relation. */\nexport interface SheetsRelationCondition {\n\tkind: 'relation';\n\t/** Stable id within the state. */\n\tid: string;\n\t/** Relation field name. */\n\trelation: string;\n\t/** `any`: has a linked record; `none`: has no linked record; `labelContains`: a linked record's label contains `value`. */\n\ttest: SheetsRelationTest;\n\t/** Text for `labelContains`, otherwise null. */\n\tvalue: string | null;\n}\n\nexport type SheetsFilterCondition = SheetsColumnCondition | SheetsRelationCondition;\n\n/** A group of conditions and groups. */\nexport interface SheetsFilterGroup {\n\tkind: 'group';\n\t/** Stable id within the state. */\n\tid: string;\n\tlogic: SheetsFilterLogic;\n\tchildren: readonly SheetsFilterNode[];\n}\n\nexport type SheetsFilterNode = SheetsFilterGroup | SheetsFilterCondition;\n\nexport type SheetsSortDirection = 'asc' | 'desc';\n\n/** One sort key. The first key in a list sorts first. */\nexport interface SheetsSortKey {\n\t/** Column field name. */\n\tcolumn: string;\n\tdirection: SheetsSortDirection;\n}\n\n/** Row heights the grid offers. */\nexport type SheetsRowHeight = 'short' | 'medium' | 'tall' | 'extraTall';\n\n/** Which columns show, in what order, how wide, how many stay in place, and how tall rows are. */\nexport interface SheetsColumnLayout {\n\t/**\n\t * Grid column keys (column and relation field names) in display order. Keys\n\t * the table has but this list does not name follow, in the table's order, so a\n\t * new column shows up at the end.\n\t */\n\torder: readonly string[];\n\t/** Grid column keys that are hidden. */\n\thidden: readonly string[];\n\t/** How many leading visible columns stay in place while the grid scrolls sideways. */\n\tfrozenCount: number;\n\t/** Column widths in pixels, by grid column key. A column without an entry keeps its default width. */\n\twidths: Readonly<Record<string, number>>;\n\trowHeight: SheetsRowHeight;\n}\n\n/** Filter, sort, search and column layout of one grid. */\nexport interface SheetsViewState {\n\tversion: typeof SHEETS_VIEW_STATE_VERSION;\n\tfilters: SheetsFilterGroup;\n\tsort: readonly SheetsSortKey[];\n\t/** Search text; empty for no search. */\n\tsearch: string;\n\tcolumns: SheetsColumnLayout;\n}\n\n/** Why the validator dropped part of a state. */\nexport type SheetsViewStateDropReason =\n\t| 'invalid-shape'\n\t| 'unknown-column'\n\t| 'column-not-filterable'\n\t| 'unknown-operator'\n\t| 'unknown-option'\n\t| 'unknown-relation'\n\t| 'relation-test-unavailable'\n\t| 'column-not-sortable'\n\t| 'duplicate-sort'\n\t| 'search-unavailable';\n\n/** One part of a state that the current model does not support. */\nexport interface SheetsViewStateDrop {\n\t/** Which part of the state. */\n\tpart: 'filters' | 'sort' | 'search' | 'columns';\n\t/** Column or relation the dropped part named, or null. */\n\ttarget: string | null;\n\treason: SheetsViewStateDropReason;\n\t/** Human-readable explanation, safe to show to the user. */\n\tmessage: string;\n}\n\n/** A state the model supports, and what was dropped to get it. */\nexport interface SheetsViewStateValidation {\n\tstate: SheetsViewState;\n\tdropped: readonly SheetsViewStateDrop[];\n}\n","import { createColumnLayout } from '../columns/column-layout';\nimport {\n\tSHEETS_VIEW_STATE_VERSION,\n\ttype SheetsFilterCondition,\n\ttype SheetsFilterGroup,\n\ttype SheetsFilterLogic,\n\ttype SheetsFilterNode,\n\ttype SheetsSortDirection,\n\ttype SheetsSortKey,\n\ttype SheetsViewState,\n} from './view-state.types';\n\n/** Deepest nesting the filter builder offers (the root group is depth 0). */\nexport const MAX_FILTER_DEPTH = 3;\n\nlet nextNodeId = 0;\n\n/** A node id unique within this page. */\nexport function createFilterNodeId(): string {\n\tnextNodeId += 1;\n\treturn `f${Date.now().toString(36)}${nextNodeId.toString(36)}`;\n}\n\nexport function createFilterGroup(logic: SheetsFilterLogic = 'and', children: readonly SheetsFilterNode[] = []): SheetsFilterGroup {\n\treturn { kind: 'group', id: createFilterNodeId(), logic, children };\n}\n\n/** The state with no filter, no sort, no search, and every column shown in the table's order. */\nexport function createSheetsViewState(): SheetsViewState {\n\treturn { version: SHEETS_VIEW_STATE_VERSION, filters: createFilterGroup(), sort: [], search: '', columns: createColumnLayout() };\n}\n\n/** Every condition in a group, depth first. */\nexport function filterConditionsOf(node: SheetsFilterNode): SheetsFilterCondition[] {\n\tif (node.kind !== 'group') return [node];\n\treturn node.children.flatMap(filterConditionsOf);\n}\n\n/** Replace the node with `id` anywhere in the tree. */\nexport function replaceFilterNode(group: SheetsFilterGroup, id: string, next: SheetsFilterNode): SheetsFilterGroup {\n\treturn {\n\t\t...group,\n\t\tchildren: group.children.map((child) => {\n\t\t\tif (child.id === id) return next;\n\t\t\treturn child.kind === 'group' ? replaceFilterNode(child, id, next) : child;\n\t\t}),\n\t};\n}\n\n/** Remove the node with `id` anywhere in the tree. */\nexport function removeFilterNode(group: SheetsFilterGroup, id: string): SheetsFilterGroup {\n\treturn {\n\t\t...group,\n\t\tchildren: group.children\n\t\t\t.filter((child) => child.id !== id)\n\t\t\t.map((child) => (child.kind === 'group' ? removeFilterNode(child, id) : child)),\n\t};\n}\n\n/**\n * The sort after a header click. A plain click cycles that column alone\n * (ascending, descending, none) and replaces any other key. An additive click\n * (Shift) adds the column as the last key, flips it, or removes it, and keeps\n * the other keys.\n */\nexport function cycleSort(sort: readonly SheetsSortKey[], column: string, additive: boolean): SheetsSortKey[] {\n\tconst current = sort.find((key) => key.column === column);\n\tconst next: SheetsSortDirection | null = !current ? 'asc' : current.direction === 'asc' ? 'desc' : null;\n\tif (!additive) return next ? [{ column, direction: next }] : [];\n\tif (!current) return [...sort, { column, direction: 'asc' }];\n\treturn next\n\t\t? sort.map((key) => (key.column === column ? { column, direction: next } : key))\n\t\t: sort.filter((key) => key.column !== column);\n}\n\n/** The sort with `column` set to `direction`, kept in place or added last. */\nexport function setSortDirection(\n\tsort: readonly SheetsSortKey[],\n\tcolumn: string,\n\tdirection: SheetsSortDirection,\n): SheetsSortKey[] {\n\treturn sort.some((key) => key.column === column)\n\t\t? sort.map((key) => (key.column === column ? { column, direction } : key))\n\t\t: [...sort, { column, direction }];\n}\n\n/** The sort with the key at `from` moved to `to`. */\nexport function moveSortKey(sort: readonly SheetsSortKey[], from: number, to: number): SheetsSortKey[] {\n\tif (from === to || from < 0 || to < 0 || from >= sort.length || to >= sort.length) return [...sort];\n\tconst next = [...sort];\n\tconst [moved] = next.splice(from, 1);\n\tnext.splice(to, 0, moved!);\n\treturn next;\n}\n\nfunction withoutIds(node: SheetsFilterNode): unknown {\n\tif (node.kind !== 'group') {\n\t\tconst { id: _id, ...rest } = node;\n\t\treturn rest;\n\t}\n\treturn { kind: node.kind, logic: node.logic, children: node.children.map(withoutIds) };\n}\n\n/**\n * A text form of a state that two states with the same meaning share (filter\n * node ids, key order and width order do not count). A saved view has unsaved\n * changes exactly when this differs from the stored state's.\n */\nexport function viewStateSignature(state: SheetsViewState): string {\n\tconst widths = Object.entries(state.columns.widths).sort(([left], [right]) => left.localeCompare(right));\n\treturn JSON.stringify({\n\t\tfilters: withoutIds(state.filters),\n\t\tsort: state.sort,\n\t\tsearch: state.search,\n\t\tcolumns: { ...state.columns, hidden: [...state.columns.hidden].sort(), widths },\n\t});\n}\n","/**\n * What a failed write tells the user: every message the server returned, in\n * plain words, with a title that names the cell or row when the write did.\n * A permission refusal reads as a permission problem; only an explicit\n * authentication error means the session ended.\n */\nimport { getConstraintMessage, getErrorCode, isAuthenticationCode } from '@constructive-io/data';\nimport type { TableModel } from '@constructive-io/data';\n\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { responseErrorsOf } from '../../context/sheets-execute';\n\nexport type WriteAction = 'update' | 'create' | 'delete';\n\nconst PERMISSION_CODES = new Set(['FORBIDDEN', '42501']);\nconst PERMISSION_TEXT = /\\bpermission denied\\b|\\bnot allowed\\b|\\binsufficient privilege/i;\n\n// The server's words when an update or delete matched no row it lets this user change.\nconst NOT_APPLIED_TEXT = /\\bNo values were (?:updated|deleted) in collection\\b/i;\n\nconst NOT_APPLIED_MESSAGES: Record<WriteAction, string> = {\n\tupdate: 'This record was not changed. You may not be allowed to change it, or it no longer exists.',\n\tcreate: 'This record was not created.',\n\tdelete: 'This record was not deleted. You may not be allowed to delete it, or it no longer exists.',\n};\n\nconst PERMISSION_MESSAGES: Record<WriteAction, string> = {\n\tupdate: 'You do not have permission to change this record.',\n\tcreate: 'You do not have permission to add records to this table.',\n\tdelete: 'You do not have permission to delete this record.',\n};\n\n// A delete the database refuses because other rows still reference the record. The server\n// sends no code for it, only its words, which name the referencing table.\nconst STILL_REFERENCED_TEXT = /\\bviolates (?:RESTRICT setting of )?foreign key constraint \"[^\"]*\" on table \"([^\"]+)\"/i;\n\nconst RULE_CODES = new Set(['UNIQUE_VIOLATION', 'NOT_NULL_VIOLATION', 'CHECK_VIOLATION', 'FOREIGN_KEY_VIOLATION']);\n\ninterface MessageSource {\n\tmessage?: string | null;\n\tcode?: string | null;\n\tcontext?: Readonly<Record<string, unknown>> | null;\n}\n\n/** A refusal the server classified (a database rule), in plain words. */\nfunction ruleMessage(source: MessageSource, action: WriteAction): string | null {\n\t// A message registered for the exact constraint (or its suffix) says it best.\n\tconst constraint = typeof source.context?.constraint === 'string' ? source.context.constraint : null;\n\tconst registered = constraint ? getConstraintMessage(constraint) : undefined;\n\tif (registered && RULE_CODES.has(source.code ?? '')) return registered;\n\tswitch (source.code) {\n\t\tcase 'UNIQUE_VIOLATION':\n\t\t\treturn 'Another record already has this value.';\n\t\tcase 'NOT_NULL_VIOLATION': {\n\t\t\tconst column = typeof source.context?.column === 'string' ? source.context.column : null;\n\t\t\treturn column ? `${fieldLabel(column)} needs a value.` : 'A required field needs a value.';\n\t\t}\n\t\tcase 'CHECK_VIOLATION':\n\t\t\treturn 'This value is not allowed by a rule of this table.';\n\t\tcase 'FOREIGN_KEY_VIOLATION':\n\t\t\treturn action === 'delete' ? 'Other records still link to this record.' : 'The linked record does not exist.';\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\nfunction plainMessage(source: MessageSource, action: WriteAction): string | null {\n\tconst message = source.message?.trim() ?? '';\n\tif ((source.code && PERMISSION_CODES.has(source.code)) || PERMISSION_TEXT.test(message)) return PERMISSION_MESSAGES[action];\n\tif (NOT_APPLIED_TEXT.test(message)) return NOT_APPLIED_MESSAGES[action];\n\tif (isAuthenticationCode(source.code)) return 'Your session has ended. Sign in again to save changes.';\n\tconst rule = ruleMessage(source, action);\n\tif (rule) return rule;\n\tconst referencing = STILL_REFERENCED_TEXT.exec(message)?.[1];\n\tif (referencing && action === 'delete') return `Other records in ${fieldLabel(referencing)} still link to this record. Change or remove them first.`;\n\treturn message || null;\n}\n\n/** Every distinct message of a failed write, in plain words. */\nexport function writeErrorMessages(error: unknown, action: WriteAction): string[] {\n\tconst responseErrors = responseErrorsOf(error) ?? [];\n\tconst fromResponse = responseErrors.map((entry) =>\n\t\tplainMessage({ message: entry.message, code: entry.extensions?.code ?? null, context: entry.extensions?.context ?? null }, action),\n\t);\n\tconst messages = fromResponse.filter((message): message is string => Boolean(message));\n\tif (messages.length === 0) {\n\t\tconst message = error instanceof Error ? error.message : typeof error === 'string' ? error : null;\n\t\tconst context = error && typeof error === 'object' ? ((error as { context?: Record<string, unknown> }).context ?? null) : null;\n\t\tconst plain = plainMessage({ message, code: getErrorCode(error), context }, action);\n\t\tmessages.push(plain ?? 'The change could not be saved.');\n\t}\n\treturn [...new Set(messages)];\n}\n\n/** The text that names a record: its display fields, else its position. */\nexport function recordLabel(model: TableModel | null, row: Readonly<Record<string, unknown>> | null | undefined, rowIndex: number): string {\n\tconst parts = (model?.display.fields ?? [])\n\t\t.map((field) => row?.[field])\n\t\t.filter((value) => value !== null && value !== undefined && value !== '' && typeof value !== 'object')\n\t\t.map(String);\n\tconst label = parts.join(' · ');\n\tif (!label) return `row ${rowIndex + 1}`;\n\treturn label.length > 60 ? `\"${label.slice(0, 57)}...\"` : `\"${label}\"`;\n}\n\n/** One failed write, as the grid shows it. */\nexport interface WriteErrorReport {\n\tid: string;\n\ttitle: string;\n\tmessages: readonly string[];\n}\n\nlet nextReportId = 0;\n\nexport function createWriteErrorReport(title: string, messages: readonly string[]): WriteErrorReport {\n\tnextReportId += 1;\n\treturn { id: `write-error-${nextReportId}`, title, messages };\n}\n","'use client';\n\nimport { createContext, useCallback, useContext, useEffect, useMemo, useReducer } from 'react';\n\nimport {\n\tcreateInitialState,\n\tfeedbackReducer,\n\tgenerateOperationId,\n\ttype FeedbackState,\n\ttype OperationFeedback,\n\ttype OperationType,\n} from './feedback-reducer';\nimport { createWriteErrorReport, type WriteErrorReport } from './write-errors';\n\n/** The words for one write's outcome: what the status says when it saved and when it did not. */\nexport interface WriteMessages {\n\tsaved: string;\n\tfailed: string;\n}\n\ninterface FeedbackContextValue {\n\tstate: FeedbackState;\n\n\t// Save status: every write reports here, so overlapping writes share one status.\n\tstartOperation: (type: OperationType, total: number) => string;\n\tupdateOperationProgress: (id: string, completed: number, failed: number) => void;\n\tcompleteOperation: (\n\t\tid: string,\n\t\tstatus: 'success' | 'partial' | 'error',\n\t\tmessage: string,\n\t\t/** Keep the settled status at least this long (ms); the default depends on the status. */\n\t\tdismissAfter?: number,\n\t) => void;\n\tclearOperationFeedback: () => void;\n\t/** Run one write under the save status; its error is re-thrown after it is reported. */\n\ttrackWrite: <T>(type: OperationType, total: number, run: () => Promise<T>, messages: WriteMessages) => Promise<T>;\n\t/** Report a write that already ended (an editor that saves on its own). */\n\tnoteWrite: (type: OperationType, status: 'success' | 'error', message: string) => void;\n\n\t/** Show a failed write until the user dismisses it. */\n\treportWriteError: (title: string, messages: readonly string[]) => WriteErrorReport;\n\tdismissWriteError: (id: string) => void;\n\tclearWriteErrors: () => void;\n}\n\nconst FeedbackContext = createContext<FeedbackContextValue | null>(null);\n\ninterface FeedbackProviderProps {\n\tchildren: React.ReactNode;\n}\n\nexport function FeedbackProvider({ children }: FeedbackProviderProps) {\n\tconst [state, dispatch] = useReducer(feedbackReducer, undefined, createInitialState);\n\n\t// A settled status clears itself after its duration. The timer belongs to that one settled\n\t// status: a write that starts meanwhile changes the status and cancels the timer, so an old\n\t// timer can never clear a newer status.\n\tconst operation = state.operation;\n\tconst settledId = operation && operation.status !== 'pending' ? operation.id : null;\n\tconst settledAt = operation?.timestamp ?? 0;\n\tconst dismissAfter = operation?.dismissAfter ?? 0;\n\tuseEffect(() => {\n\t\tif (!settledId || dismissAfter <= 0) return;\n\t\tconst timer = setTimeout(() => dispatch({ type: 'OPERATION_DISMISS', id: settledId, timestamp: settledAt }), dismissAfter);\n\t\treturn () => clearTimeout(timer);\n\t}, [settledId, settledAt, dismissAfter]);\n\n\tconst startOperation = useCallback((type: OperationType, total: number): string => {\n\t\tconst id = generateOperationId();\n\t\tdispatch({ type: 'OPERATION_START', operationType: type, total, id, now: Date.now() });\n\t\treturn id;\n\t}, []);\n\n\tconst updateOperationProgress = useCallback((id: string, completed: number, failed: number) => {\n\t\tdispatch({ type: 'OPERATION_PROGRESS', id, completed, failed });\n\t}, []);\n\n\tconst completeOperation = useCallback(\n\t\t(id: string, status: 'success' | 'partial' | 'error', message: string, dismissAfter?: number) => {\n\t\t\tdispatch({ type: 'OPERATION_COMPLETE', id, status, message, dismissAfter: dismissAfter ?? 0, now: Date.now() });\n\t\t},\n\t\t[],\n\t);\n\n\tconst clearOperationFeedback = useCallback(() => {\n\t\tdispatch({ type: 'OPERATION_CLEAR' });\n\t}, []);\n\n\tconst trackWrite = useCallback(\n\t\tasync <T,>(type: OperationType, total: number, run: () => Promise<T>, messages: WriteMessages): Promise<T> => {\n\t\t\tconst id = startOperation(type, total);\n\t\t\ttry {\n\t\t\t\tconst result = await run();\n\t\t\t\tcompleteOperation(id, 'success', messages.saved);\n\t\t\t\treturn result;\n\t\t\t} catch (error) {\n\t\t\t\tcompleteOperation(id, 'error', messages.failed);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\t[startOperation, completeOperation],\n\t);\n\n\tconst noteWrite = useCallback(\n\t\t(type: OperationType, status: 'success' | 'error', message: string) => {\n\t\t\tcompleteOperation(startOperation(type, 1), status, message);\n\t\t},\n\t\t[startOperation, completeOperation],\n\t);\n\n\tconst reportWriteError = useCallback((title: string, messages: readonly string[]) => {\n\t\tconst report = createWriteErrorReport(title, messages);\n\t\tdispatch({ type: 'WRITE_ERROR_ADD', report });\n\t\treturn report;\n\t}, []);\n\n\tconst dismissWriteError = useCallback((id: string) => {\n\t\tdispatch({ type: 'WRITE_ERROR_DISMISS', id });\n\t}, []);\n\n\tconst clearWriteErrors = useCallback(() => {\n\t\tdispatch({ type: 'WRITE_ERROR_CLEAR' });\n\t}, []);\n\n\tconst value = useMemo<FeedbackContextValue>(\n\t\t() => ({\n\t\t\tstate,\n\t\t\tstartOperation,\n\t\t\tupdateOperationProgress,\n\t\t\tcompleteOperation,\n\t\t\tclearOperationFeedback,\n\t\t\ttrackWrite,\n\t\t\tnoteWrite,\n\t\t\treportWriteError,\n\t\t\tdismissWriteError,\n\t\t\tclearWriteErrors,\n\t\t}),\n\t\t[\n\t\t\tstate,\n\t\t\tstartOperation,\n\t\t\tupdateOperationProgress,\n\t\t\tcompleteOperation,\n\t\t\tclearOperationFeedback,\n\t\t\ttrackWrite,\n\t\t\tnoteWrite,\n\t\t\treportWriteError,\n\t\t\tdismissWriteError,\n\t\t\tclearWriteErrors,\n\t\t],\n\t);\n\n\treturn <FeedbackContext.Provider value={value}>{children}</FeedbackContext.Provider>;\n}\n\nexport function useFeedback(): FeedbackContextValue {\n\tconst context = useContext(FeedbackContext);\n\tif (!context) {\n\t\tthrow new Error('useFeedback must be used within a FeedbackProvider');\n\t}\n\treturn context;\n}\n\n/** The feedback of the grid around this component, or null outside a grid (a standalone record panel). */\nexport function useOptionalFeedback(): FeedbackContextValue | null {\n\treturn useContext(FeedbackContext);\n}\n\n/**\n * The save status alone - useful for a status indicator.\n */\nexport function useOperationFeedback(): OperationFeedback | null {\n\tconst { state } = useFeedback();\n\treturn state.operation;\n}\n","/**\n * Grid Feedback Reducer\n *\n * One save status for every write the grid makes: cell saves (an edit, a paste, a\n * fill, undo and redo), new rows, deletes, and the editors and record panel that\n * save on their own. Writes that overlap share the status: it reads \"saving\" while\n * any write is in flight and settles once, when the last one ends, to one outcome\n * for all of them. So two saves can never show two checks, and a fast save cannot\n * replace the outcome of a slow one that is still running.\n *\n * Failed writes are also kept as reports (`writeErrors`) until the user dismisses\n * them, so a message is never lost when the status clears.\n *\n * Uses vanilla React (useReducer): the state is local to the grid, ephemeral, and\n * cleaned up on unmount.\n */\n\nimport type { WriteErrorReport } from './write-errors';\n\nexport type OperationStatus = 'idle' | 'pending' | 'success' | 'partial' | 'error';\n\n/** What a write does. `update` saves values, `submit` creates rows, `delete` removes rows. */\nexport type OperationType = 'delete' | 'submit' | 'update';\n\n/** The save status the grid shows. */\nexport interface OperationFeedback {\n\t/** Stable while the status is on screen, so a new write changes it in place. */\n\tid: string;\n\ttype: OperationType;\n\tstatus: OperationStatus;\n\tmessage: string;\n\ttotal: number;\n\tcompleted: number;\n\tfailed: number;\n\t/** When the status last changed. A settled status is cleared `dismissAfter` ms after it. */\n\ttimestamp: number;\n\t/** Auto-dismiss duration in ms. 0 = shown until it changes. */\n\tdismissAfter: number;\n}\n\n/** One write in flight. */\ninterface PendingWrite {\n\tid: string;\n\ttype: OperationType;\n\ttotal: number;\n\tcompleted: number;\n\tfailed: number;\n}\n\n/** One write that ended while others in the same status were running or had ended. */\ninterface EndedWrite {\n\ttype: OperationType;\n\tstatus: 'success' | 'partial' | 'error';\n\tmessage: string;\n}\n\nexport interface FeedbackState {\n\t/** The save status (shown in the status bar), or null when there is nothing to show. */\n\toperation: OperationFeedback | null;\n\t/** Writes in flight. */\n\tpending: readonly PendingWrite[];\n\t/** Writes that ended since the status was last idle or settled. */\n\tended: readonly EndedWrite[];\n\t/** Failed writes, newest last, until the user dismisses them. */\n\twriteErrors: readonly WriteErrorReport[];\n}\n\n/** Most failed writes kept on screen; older ones are dropped first. */\nexport const MAX_WRITE_ERRORS = 4;\n\n// Action types\ntype FeedbackAction =\n\t| { type: 'OPERATION_START'; operationType: OperationType; total: number; id: string; now: number }\n\t| { type: 'OPERATION_PROGRESS'; id: string; completed: number; failed: number }\n\t| {\n\t\t\ttype: 'OPERATION_COMPLETE';\n\t\t\tid: string;\n\t\t\tstatus: 'success' | 'partial' | 'error';\n\t\t\tmessage: string;\n\t\t\tdismissAfter: number;\n\t\t\tnow: number;\n\t }\n\t| { type: 'OPERATION_DISMISS'; id: string; timestamp: number }\n\t| { type: 'OPERATION_CLEAR' }\n\t| { type: 'WRITE_ERROR_ADD'; report: WriteErrorReport }\n\t| { type: 'WRITE_ERROR_DISMISS'; id: string }\n\t| { type: 'WRITE_ERROR_CLEAR' };\n\n// Duration constants\nexport const FEEDBACK_DURATIONS = {\n\t/** Success operation message duration (ms) */\n\tOPERATION_SUCCESS: 3000,\n\t/** Error operation message - longer for reading (ms) */\n\tOPERATION_ERROR: 5000,\n\t/** Partial success duration (ms) */\n\tOPERATION_PARTIAL: 4000,\n} as const;\n\nexport function createInitialState(): FeedbackState {\n\treturn {\n\t\toperation: null,\n\t\tpending: [],\n\t\tended: [],\n\t\twriteErrors: [],\n\t};\n}\n\nfunction plural(count: number, one: string, many: string): string {\n\treturn `${count.toLocaleString()} ${count === 1 ? one : many}`;\n}\n\n/** What the status says while writes run. One kind of write names itself; a mix is \"Saving…\". */\nfunction pendingMessage(pending: readonly PendingWrite[]): string {\n\tconst [first] = pending;\n\tif (!first || pending.some((write) => write.type !== first.type)) return 'Saving…';\n\tconst total = pending.reduce((sum, write) => sum + write.total, 0);\n\tswitch (first.type) {\n\t\tcase 'delete':\n\t\t\treturn `Deleting ${plural(total, 'row', 'rows')}…`;\n\t\tcase 'submit':\n\t\t\treturn total === 1 ? 'Creating row…' : `Creating ${plural(total, 'row', 'rows')}…`;\n\t\tcase 'update':\n\t\t\treturn total <= 1 ? 'Saving…' : `Saving ${plural(total, 'change', 'changes')}…`;\n\t}\n}\n\n/** The one outcome of the writes that ended together. One write keeps its own message. */\nfunction settledOutcome(ended: readonly EndedWrite[]): { status: 'success' | 'partial' | 'error'; message: string } {\n\tif (ended.length === 1) return { status: ended[0]!.status, message: ended[0]!.message };\n\tconst ok = ended.filter((write) => write.status === 'success').length;\n\tconst failed = ended.filter((write) => write.status === 'error').length;\n\tif (ok === ended.length) return { status: 'success', message: 'All changes saved' };\n\tif (failed === ended.length) return { status: 'error', message: 'Changes were not saved' };\n\treturn { status: 'partial', message: 'Some changes were not saved' };\n}\n\nfunction dismissDuration(status: 'success' | 'partial' | 'error', requested: readonly number[]): number {\n\t// The longest wish of the writes that ended wins, so an error is never cut short by a success.\n\treturn Math.max(getDefaultDismissDuration(status), ...requested);\n}\n\nexport function feedbackReducer(state: FeedbackState, action: FeedbackAction): FeedbackState {\n\tswitch (action.type) {\n\t\tcase 'OPERATION_START': {\n\t\t\t// A write that starts after the status settled begins a new set of writes; the\n\t\t\t// status keeps its id, so it changes in place instead of being replaced.\n\t\t\tconst ended = state.pending.length === 0 ? [] : state.ended;\n\t\t\tconst pending = [\n\t\t\t\t...state.pending,\n\t\t\t\t{ id: action.id, type: action.operationType, total: action.total, completed: 0, failed: 0 },\n\t\t\t];\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tpending,\n\t\t\t\tended,\n\t\t\t\toperation: {\n\t\t\t\t\tid: state.operation?.id ?? action.id,\n\t\t\t\t\ttype: pending.every((write) => write.type === action.operationType) ? action.operationType : 'update',\n\t\t\t\t\tstatus: 'pending',\n\t\t\t\t\tmessage: pendingMessage(pending),\n\t\t\t\t\ttotal: pending.reduce((sum, write) => sum + write.total, 0),\n\t\t\t\t\tcompleted: pending.reduce((sum, write) => sum + write.completed, 0),\n\t\t\t\t\tfailed: pending.reduce((sum, write) => sum + write.failed, 0),\n\t\t\t\t\ttimestamp: action.now,\n\t\t\t\t\tdismissAfter: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_PROGRESS': {\n\t\t\tif (!state.pending.some((write) => write.id === action.id) || !state.operation) return state;\n\t\t\tconst pending = state.pending.map((write) =>\n\t\t\t\twrite.id === action.id ? { ...write, completed: action.completed, failed: action.failed } : write,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tpending,\n\t\t\t\toperation: {\n\t\t\t\t\t...state.operation,\n\t\t\t\t\tcompleted: pending.reduce((sum, write) => sum + write.completed, 0),\n\t\t\t\t\tfailed: pending.reduce((sum, write) => sum + write.failed, 0),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_COMPLETE': {\n\t\t\tconst write = state.pending.find((candidate) => candidate.id === action.id);\n\t\t\t// A write from before a reset (a table switch) has nothing left to report to.\n\t\t\tif (!write || !state.operation) return state;\n\t\t\tconst pending = state.pending.filter((candidate) => candidate.id !== action.id);\n\t\t\tconst ended = [...state.ended, { type: write.type, status: action.status, message: action.message }];\n\t\t\tif (pending.length > 0) {\n\t\t\t\t// Others are still running: the status keeps saying so, and settles with them.\n\t\t\t\treturn {\n\t\t\t\t\t...state,\n\t\t\t\t\tpending,\n\t\t\t\t\tended,\n\t\t\t\t\toperation: { ...state.operation, message: pendingMessage(pending), total: pending.reduce((sum, w) => sum + w.total, 0) },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst outcome = settledOutcome(ended);\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tpending,\n\t\t\t\tended,\n\t\t\t\toperation: {\n\t\t\t\t\t...state.operation,\n\t\t\t\t\ttype: ended.every((entry) => entry.type === ended[0]!.type) ? ended[0]!.type : 'update',\n\t\t\t\t\tstatus: outcome.status,\n\t\t\t\t\tmessage: outcome.message,\n\t\t\t\t\tcompleted: ended.filter((entry) => entry.status !== 'error').length,\n\t\t\t\t\tfailed: ended.filter((entry) => entry.status !== 'success').length,\n\t\t\t\t\ttotal: ended.length,\n\t\t\t\t\ttimestamp: action.now,\n\t\t\t\t\tdismissAfter: dismissDuration(outcome.status, [action.dismissAfter]),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tcase 'OPERATION_DISMISS': {\n\t\t\t// Only the settled status it was set for: a write that started since keeps the status.\n\t\t\tconst operation = state.operation;\n\t\t\tif (!operation || operation.id !== action.id || operation.timestamp !== action.timestamp) return state;\n\t\t\tif (state.pending.length > 0 || operation.status === 'pending') return state;\n\t\t\treturn { ...state, operation: null, ended: [] };\n\t\t}\n\n\t\tcase 'OPERATION_CLEAR': {\n\t\t\treturn { ...state, operation: null, pending: [], ended: [] };\n\t\t}\n\n\t\tcase 'WRITE_ERROR_ADD':\n\t\t\treturn { ...state, writeErrors: [...state.writeErrors, action.report].slice(-MAX_WRITE_ERRORS) };\n\n\t\tcase 'WRITE_ERROR_DISMISS':\n\t\t\treturn { ...state, writeErrors: state.writeErrors.filter((report) => report.id !== action.id) };\n\n\t\tcase 'WRITE_ERROR_CLEAR':\n\t\t\treturn state.writeErrors.length === 0 ? state : { ...state, writeErrors: [] };\n\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}\n\n// Helper to generate operation IDs\nexport function generateOperationId(): string {\n\treturn `op_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\n// Helper to get dismiss duration based on status\nexport function getDefaultDismissDuration(status: 'success' | 'partial' | 'error'): number {\n\tswitch (status) {\n\t\tcase 'success':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_SUCCESS;\n\t\tcase 'partial':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_PARTIAL;\n\t\tcase 'error':\n\t\t\treturn FEEDBACK_DURATIONS.OPERATION_ERROR;\n\t}\n}\n","// A host-level read-only grid (`<Sheets readOnly>`).\n//\n// Every write in Sheets is decided by the table model: a cell, a paste, a fill,\n// Add row, New record, Import, Delete, a link and the record panel all read the\n// model's operations, write flags and relation flags, and show the model's reason\n// when they refuse. So read-only is applied once, where models are read: inside a\n// read-only grid, every table model (this table's and the related ones) loses its\n// create, update and delete operations, and each refusal carries the host's reason.\n// Listing, filters, sort, search and export are untouched.\n\nimport { createContext, useContext, type ReactNode } from 'react';\n\nimport type { ModelIssue, TableModel } from '@constructive-io/data';\n\n/** The reason a grid shows for `readOnly={true}`. */\nexport const DEFAULT_READ_ONLY_REASON = 'This table is read-only here.';\n\nconst SheetsReadOnlyContext = createContext<string | null>(null);\n\n/** The reason of a `readOnly` prop: its text, the default for `true`, or null when the grid can write. */\nexport function readOnlyReasonOf(readOnly: boolean | string | null | undefined): string | null {\n\tif (typeof readOnly === 'string') return readOnly.trim() || DEFAULT_READ_ONLY_REASON;\n\treturn readOnly ? DEFAULT_READ_ONLY_REASON : null;\n}\n\nexport interface SheetsReadOnlyProviderProps {\n\t/** `true`, or the reason to show; false or omitted leaves writes to the table model. */\n\treadOnly?: boolean | string | null;\n\tchildren: ReactNode;\n}\n\n/**\n * Make everything inside read-only with a reason. `<Sheets readOnly>` renders it;\n * a host driving `useSheets` itself wraps its grid in it.\n */\nexport function SheetsReadOnlyProvider({ readOnly, children }: SheetsReadOnlyProviderProps) {\n\treturn <SheetsReadOnlyContext.Provider value={readOnlyReasonOf(readOnly)}>{children}</SheetsReadOnlyContext.Provider>;\n}\n\n/** The host's read-only reason, or null when the grid can write. */\nexport function useSheetsReadOnlyReason(): string | null {\n\treturn useContext(SheetsReadOnlyContext);\n}\n\nconst OPERATION_ISSUES = [\n\t{ target: 'create', code: 'CREATE_UNAVAILABLE' },\n\t{ target: 'update', code: 'UPDATE_UNAVAILABLE' },\n\t{ target: 'delete', code: 'DELETE_UNAVAILABLE' },\n] as const;\n\nfunction buildReadOnlyModel(model: TableModel, reason: string): TableModel {\n\tconst issues: ModelIssue[] = OPERATION_ISSUES.map(({ target, code }) => ({ scope: 'operation', target, code, message: reason }));\n\treturn {\n\t\t...model,\n\t\toperations: { ...model.operations, create: null, update: null, delete: null },\n\t\tcolumns: model.columns.map((column) => ({\n\t\t\t...column,\n\t\t\twrite: { create: false, update: false, requiredOnCreate: false, createReason: reason, updateReason: reason },\n\t\t})),\n\t\trelations: model.relations.map((relation) => ({ ...relation, editable: false, unlinkable: false, reason })),\n\t\t// The host's reason comes first, so every \"why\" lookup finds it.\n\t\tissues: [...issues, ...model.issues],\n\t};\n}\n\nconst readOnlyModels = new WeakMap<TableModel, Map<string, TableModel>>();\n\n/**\n * The model as a read-only grid sees it: no create, update or delete, every field and\n * link read-only, each with `reason`. The same model and reason give the same object,\n * so memoized consumers do not recompute.\n */\nexport function readOnlyTableModel(model: TableModel, reason: string): TableModel {\n\tlet byReason = readOnlyModels.get(model);\n\tif (!byReason) {\n\t\tbyReason = new Map();\n\t\treadOnlyModels.set(model, byReason);\n\t}\n\tlet readOnly = byReason.get(reason);\n\tif (!readOnly) {\n\t\treadOnly = buildReadOnlyModel(model, reason);\n\t\tbyReason.set(reason, readOnly);\n\t}\n\treturn readOnly;\n}\n","// src/hooks/use-sheets-meta.ts\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\nimport type { MetaQuery } from '@constructive-io/data';\n\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsContext, type SheetsScopeKey } from '../context/sheets-context';\nimport { sheetsQueryKeys } from './query-keys';\n\nexport const metaKey = (scope: SheetsScopeKey) => sheetsQueryKeys.meta(scope);\n\nexport interface UseMetaOptions {\n\tenabled?: boolean;\n}\n\nexport function useSheetsMeta(options: UseMetaOptions = {}): UseQueryResult<MetaQuery, Error> {\n\tconst { enabled = true } = options;\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst adapter = useSheetsAdapter();\n\treturn useQuery<MetaQuery, Error>({\n\t\tqueryKey: metaKey(scopeKey),\n\t\tqueryFn: () => adapter.fetchMeta(execute),\n\t\tstaleTime: 5 * 60 * 1000, // 5 min - finite so invalidation + remount triggers refetch\n\t\tgcTime: 30 * 60 * 1000, // 30 min - survive long schema-editing sessions\n\t\trefetchOnMount: true, // Respect staleTime and refetch stale metadata on mount\n\t\tenabled,\n\t});\n}\n","/**\n * The table model of one table: the single source of keys, column kinds and\n * options, write flags, relations, labels, sort and filter names for the grid.\n *\n * Accepts the host's bare table name or a `TableModel.key`. A name shared by\n * tables in several schemas is an error listing the keys. Each table resolves\n * lazily and fails alone: one table's error never blocks another table.\n *\n * Inside a read-only grid (`<Sheets readOnly>`), every model comes back without\n * create, update and delete, each refusal carrying the host's reason.\n */\nimport { useCallback, useMemo } from 'react';\nimport { useQueries, useQuery, type UseQueryOptions } from '@tanstack/react-query';\n\nimport {\n\tTableModelError,\n\tfindMetaTable,\n\tmetaTablesOf,\n\ttableKeyOf,\n\ttype MetaQuery,\n\ttype MetaschemaTable,\n\ttype TableKey,\n\ttype TableModel,\n} from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport type { SheetsExecuteFn } from '../context/sheets-execute';\nimport { useSheetsContext, type SheetsConfig, type SheetsScopeKey } from '../context/sheets-context';\nimport { readOnlyTableModel, useSheetsReadOnlyReason } from '../context/sheets-read-only';\nimport { sheetsQueryKeys } from './query-keys';\nimport { useSheetsMeta } from './use-sheets-meta';\n\nexport interface UseTableModelOptions {\n\t/** Resolve the model. Default true. */\n\tenabled?: boolean;\n}\n\nexport interface UseTableModelResult {\n\t/** The model, or null while it loads or when it failed. */\n\tmodel: TableModel | null;\n\t/** `TableModel.key` of the requested table, or null until `_meta` has loaded or when the name is unknown. */\n\ttableKey: TableKey | null;\n\t/** The `_meta` entry of the table, or null. */\n\tmetaTable: MetaschemaTable | null;\n\t/** True until the model is ready (or failed). */\n\tisLoading: boolean;\n\t/** Why the model is unavailable: `_meta` failed, the name is unknown or ambiguous, or this table failed. */\n\terror: Error | null;\n\t/** Load again what failed: `_meta` when it failed (the model follows), otherwise this table's model. */\n\trefetch: () => Promise<void>;\n}\n\nconst metaVersions = new WeakMap<MetaQuery, number>();\nlet nextMetaVersion = 1;\n\n/** A number per `_meta` result. An unchanged refetch keeps its object, so it keeps its version. */\nfunction metaVersionOf(meta: MetaQuery): number {\n\tlet version = metaVersions.get(meta);\n\tif (version === undefined) {\n\t\tversion = nextMetaVersion;\n\t\tnextMetaVersion += 1;\n\t\tmetaVersions.set(meta, version);\n\t}\n\treturn version;\n}\n\n/** A model error is deterministic for this `_meta`; only a failed schema read is worth a retry. */\nfunction isDeterministicModelError(error: Error): boolean {\n\tconst code = (error as { code?: unknown }).code;\n\treturn error instanceof TableModelError && code !== 'SCHEMA_UNAVAILABLE';\n}\n\nfunction locate(meta: MetaQuery | undefined, tableRef: string | null | undefined): { metaTable: ReturnType<typeof findMetaTable> | null; error: Error | null } {\n\tif (!meta || !tableRef) return { metaTable: null, error: null };\n\ttry {\n\t\treturn { metaTable: findMetaTable(metaTablesOf(meta), tableRef), error: null };\n\t} catch (error) {\n\t\treturn { metaTable: null, error: error as Error };\n\t}\n}\n\ninterface ModelQueryContext {\n\tscopeKey: SheetsScopeKey;\n\tmeta: MetaQuery | undefined;\n\tadapter: SheetsBackendAdapter;\n\texecute: SheetsExecuteFn;\n\tdisplayFields: SheetsConfig['displayFields'];\n\tdisplayKey: string | null;\n}\n\n/** One table model query. `useTableModel` and `useTableModels` share it, so nothing is fetched twice. */\nfunction tableModelQuery(\n\tcontext: ModelQueryContext,\n\ttableKey: TableKey | null,\n\tenabled: boolean,\n): UseQueryOptions<TableModel, Error> {\n\tconst { scopeKey, meta, adapter, execute, displayFields, displayKey } = context;\n\treturn {\n\t\tqueryKey: sheetsQueryKeys.tableModel(scopeKey, tableKey ?? '', meta ? metaVersionOf(meta) : 0, displayKey),\n\t\tqueryFn: () => adapter.fetchTableModel(execute, meta!, tableKey!, { displayOverrides: displayFields }),\n\t\tenabled: enabled && Boolean(meta && tableKey),\n\t\tstaleTime: Number.POSITIVE_INFINITY,\n\t\tgcTime: 30 * 60 * 1000,\n\t\tretry: (failureCount, error) => failureCount < 1 && !isDeterministicModelError(error),\n\t};\n}\n\nfunction useModelQueryContext(enabled: boolean) {\n\tconst { execute, scopeKey, config } = useSheetsContext();\n\tconst adapter = useSheetsAdapter();\n\tconst metaQuery = useSheetsMeta({ enabled });\n\tconst readOnlyReason = useSheetsReadOnlyReason();\n\tconst displayFields = config.displayFields;\n\tconst displayKey = useMemo(() => (displayFields ? JSON.stringify(displayFields) : null), [displayFields]);\n\tconst context: ModelQueryContext = { scopeKey, meta: metaQuery.data, adapter, execute, displayFields, displayKey };\n\treturn { context, metaQuery, readOnlyReason };\n}\n\n/** The model as this grid may use it: read-only with the host's reason inside a read-only grid. */\nfunction asSeen(model: TableModel, readOnlyReason: string | null): TableModel {\n\treturn readOnlyReason ? readOnlyTableModel(model, readOnlyReason) : model;\n}\n\nexport function useTableModel(\n\ttableRef: string | null | undefined,\n\toptions: UseTableModelOptions = {},\n): UseTableModelResult {\n\tconst { enabled = true } = options;\n\tconst active = enabled && Boolean(tableRef);\n\tconst { context, metaQuery, readOnlyReason } = useModelQueryContext(active);\n\tconst meta = metaQuery.data;\n\n\tconst { metaTable, error: locateError } = useMemo(() => locate(meta, tableRef), [meta, tableRef]);\n\tconst tableKey = metaTable ? tableKeyOf(metaTable) : null;\n\tconst modelEnabled = active && Boolean(meta && tableKey);\n\n\tconst query = useQuery<TableModel, Error>(tableModelQuery(context, tableKey, active));\n\tconst { refetch: refetchMeta } = metaQuery;\n\tconst { refetch: refetchModel } = query;\n\tconst metaFailed = Boolean(metaQuery.error || locateError);\n\tconst refetch = useCallback(async () => {\n\t\tif (metaFailed) await refetchMeta();\n\t\telse if (modelEnabled) await refetchModel();\n\t}, [metaFailed, modelEnabled, refetchMeta, refetchModel]);\n\n\treturn {\n\t\tmodel: modelEnabled && query.data ? asSeen(query.data, readOnlyReason) : null,\n\t\ttableKey,\n\t\tmetaTable,\n\t\tisLoading: active && (metaQuery.isPending || (modelEnabled && query.isPending)) && !metaQuery.error && !locateError,\n\t\terror: metaQuery.error ?? locateError ?? (modelEnabled ? query.error : null) ?? null,\n\t\trefetch,\n\t};\n}\n\nexport interface UseTableModelsResult {\n\t/** The models that have loaded, by `TableModel.key`. A table that failed or is unknown is absent. */\n\tmodels: ReadonlyMap<TableKey, TableModel>;\n\t/** True while `_meta` or any of the models still loads. */\n\tisLoading: boolean;\n}\n\n/**\n * The models of a variable set of tables (names or keys), with the same cache\n * entries as `useTableModel`. Unknown or ambiguous names are skipped; use\n * `useTableModel` for one table's error.\n */\nexport function useTableModels(refs: readonly string[], options: UseTableModelOptions = {}): UseTableModelsResult {\n\tconst { enabled = true } = options;\n\tconst active = enabled && refs.length > 0;\n\tconst { context, metaQuery, readOnlyReason } = useModelQueryContext(active);\n\tconst meta = metaQuery.data;\n\tconst refsKey = refs.join('\\u0000');\n\n\tconst tableKeys = useMemo(() => {\n\t\tconst keys = new Set<TableKey>();\n\t\tfor (const ref of refsKey ? refsKey.split('\\u0000') : []) {\n\t\t\tconst { metaTable } = locate(meta, ref);\n\t\t\tif (metaTable) keys.add(tableKeyOf(metaTable));\n\t\t}\n\t\treturn [...keys];\n\t}, [meta, refsKey]);\n\n\tconst results = useQueries({ queries: tableKeys.map((tableKey) => tableModelQuery(context, tableKey, active)) });\n\t// The map keeps its identity until a model changes, so effects that depend on it do not re-run each render.\n\tconst signature = results.map((result) => result.dataUpdatedAt).join(',');\n\tconst models = useMemo(\n\t\t() =>\n\t\t\tnew Map(\n\t\t\t\tresults.flatMap((result, position) =>\n\t\t\t\t\tresult.data ? [[tableKeys[position]!, asSeen(result.data, readOnlyReason)] as const] : [],\n\t\t\t\t),\n\t\t\t),\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t\t[signature, tableKeys, readOnlyReason],\n\t);\n\tconst isLoading = active && (metaQuery.isPending || results.some((result) => result.isPending)) && !metaQuery.error;\n\treturn { models, isLoading };\n}\n","// Badges SheetsCell factory — native analogue of v1 `ArrayCellFactory`.\n//\n// Owns the array/bubble family: every array-like cellType plus `tsvector`. The\n// glide `BubbleCell` carries `data: string[]` and NO `displayData`, so the\n// neutral payload mirrors that exactly — `data` is the string[] (copyText ===\n// JSON.stringify(array)), `displayData` is '' (no display side in v1), and the\n// kind is the neutral `badges`. ALL domain logic from v1 is ported verbatim\n// (tags array/comma-string, tsvector lexeme preview, generic per-item\n// stringify, null/undefined -> [], non-array fallback -> [String(value)]); the\n// tsvector parser is copied in so this file never imports the glide factory\n// (which is deleted at cutover).\n\nimport type { CellType } from '../../cell-types/types';\nimport { isArrayCellType } from '../../cell-types/cell-type-groups';\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\n// Minimal tsvector parser for previews — copied verbatim from v1\n// cell-content-factory.ts (do NOT import it; it stays glide-only).\nfunction parseTsvectorForPreview(tsvector: string): Array<{ lexeme: string; weights: Array<'A' | 'B' | 'C' | 'D'> }> {\n\tif (!tsvector || typeof tsvector !== 'string') return [];\n\tconst results: Array<{ lexeme: string; weights: Array<'A' | 'B' | 'C' | 'D'> }> = [];\n\ttry {\n\t\tconst regex = /'([^']+)':([0-9A-D,]+)/g;\n\t\tlet match: RegExpExecArray | null;\n\t\twhile ((match = regex.exec(tsvector)) !== null) {\n\t\t\tconst lexeme = match[1];\n\t\t\tconst posStr = match[2];\n\t\t\tconst weights = Array.from(\n\t\t\t\tnew Set(\n\t\t\t\t\tposStr\n\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t.map((p) => p.match(/[A-D]$/)?.[0] as 'A' | 'B' | 'C' | 'D' | undefined)\n\t\t\t\t\t\t.filter((w): w is 'A' | 'B' | 'C' | 'D' => !!w),\n\t\t\t\t),\n\t\t\t).sort();\n\t\t\tresults.push({ lexeme, weights });\n\t\t}\n\t} catch {\n\t\t// ignore parsing errors\n\t}\n\treturn results;\n}\n\n// Compute the string[] the v1 BubbleCell put in `.data`, branch-for-branch.\nfunction deriveBadges(value: unknown, metadata: CellCreationMetadata): string[] {\n\tif (value === null || value === undefined) {\n\t\treturn [];\n\t}\n\n\tif (metadata.cellType === 'tags') {\n\t\tif (Array.isArray(value)) {\n\t\t\treturn value.map((v) => (v == null ? '' : String(v))).filter((v) => v.length > 0);\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\treturn value\n\t\t\t\t.split(',')\n\t\t\t\t.map((v) => v.trim())\n\t\t\t\t.filter((v) => v.length > 0);\n\t\t}\n\t}\n\n\tif (metadata.cellType === 'tsvector' && typeof value === 'string') {\n\t\tconst tokens = parseTsvectorForPreview(value);\n\t\treturn tokens.map((t) => (t.weights.length ? `${t.lexeme} ${t.weights.join(',')}` : t.lexeme));\n\t}\n\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item) => {\n\t\t\tif (item === null || item === undefined) return '';\n\t\t\tif (typeof item === 'string') return item;\n\t\t\tif (typeof item === 'number') return String(item);\n\t\t\tif (typeof item === 'boolean') return String(item);\n\t\t\tif (item instanceof Date) return item.toISOString().split('T')[0];\n\t\t\tif (typeof item === 'object') return JSON.stringify(item);\n\t\t\treturn String(item);\n\t\t});\n\t}\n\n\treturn [String(value)];\n}\n\nexport const badgesSheetsCellFactory: SheetsCellFactory = {\n\tcanHandle(cellType: string, _value: unknown): boolean {\n\t\treturn isArrayCellType(cellType) || cellType === 'tsvector';\n\t},\n\n\tcreate(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\t\treturn {\n\t\t\tkind: 'badges',\n\t\t\tdata: deriveBadges(value, metadata),\n\t\t\tdisplayData: '',\n\t\t\treadonly: false,\n\t\t\tmeta: { cellType: metadata.cellType as CellType },\n\t\t};\n\t},\n};\n","// Boolean SheetsCell factory — native analogue of v1's BooleanCellFactory\n// (grid/cell-content-factory.ts). Claims BOOLEAN_TYPES (boolean, toggle).\n//\n// The cell keeps the boolean in `data` for the view and leaves `displayData` empty\n// because the view owns its visual representation. A null value stays null (an\n// empty cell), so \"no value\" never shows as false.\n\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport { BOOLEAN_TYPES } from '../../cell-types/cell-type-groups';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn BOOLEAN_TYPES.has(cellType);\n}\n\nfunction create(value: unknown, _metadata: CellCreationMetadata): SheetsCell {\n\tconst boolValue = value === null || value === undefined ? null : typeof value === 'boolean' ? value : Boolean(value);\n\treturn { kind: 'boolean', data: boolValue, displayData: '', readonly: false };\n}\n\nexport const booleanSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// Choice SheetsCell factory — enum columns and text columns with an allowed-values\n// list (`select`, `multi-select`). The stored value is the wire value; the cell shows\n// each value's label as a badge. A stored value that is not in the option list still\n// shows, as it is.\n\nimport type { CellType } from '../../cell-types/types';\nimport { CHOICE_TYPES } from '../../cell-types/cell-type-groups';\nimport { choiceLabel } from '../../cell-types/column-value';\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn CHOICE_TYPES.has(cellType);\n}\n\nfunction create(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\tconst values = value === null || value === undefined ? [] : Array.isArray(value) ? value : [value];\n\tconst labels = values.filter((entry) => entry !== null && entry !== undefined).map((entry) => choiceLabel(metadata.column, entry));\n\treturn {\n\t\tkind: 'badges',\n\t\tdata: labels,\n\t\tdisplayData: labels.join(', '),\n\t\treadonly: false,\n\t\tmeta: { cellType: metadata.cellType as CellType },\n\t};\n}\n\nexport const choiceSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// SheetsCell factory for the datetime family (date, datetime, time, timestamptz): a\n// neutral `text` cell shown by the one date and time rule (`formatDateTimeText`: a date\n// as stored, a time \"HH:mm:ss\" and a date and time \"YYYY-MM-DD HH:mm:ss\" with fractions\n// only when not zero, a zoned value in the viewer's zone). `data` keeps the exact\n// stored text; the title shows it with the zone used. Copy and export read the raw\n// value. No value is ''.\n\nimport type { CellType } from '../../cell-types/types';\nimport { DATE_TIME_TYPES } from '../../cell-types/cell-type-groups';\nimport { dateTimeKindOf, dateTimeTitle, formatDateTimeText } from '../../cell-types/date-time-format';\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn DATE_TIME_TYPES.has(cellType);\n}\n\nfunction create(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\tconst meta = { cellType: metadata.cellType as CellType };\n\n\tif (value === null || value === undefined) {\n\t\treturn { kind: 'text', data: '', displayData: '', readonly: false, meta };\n\t}\n\n\tconst text = String(value);\n\tconst kind = dateTimeKindOf(metadata.cellType);\n\tif (!kind) return { kind: 'text', data: text, displayData: text, readonly: false, meta };\n\tconst shown = formatDateTimeText(text, kind);\n\treturn { kind: 'text', data: text, displayData: shown.text, readonly: false, meta: { ...meta, title: dateTimeTitle(text, shown.zone) } };\n}\n\nexport const dateTimeSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// Plain names for GeoJSON shapes, shared by the geometry cell and the geometry editor,\n// and a summary of a stored shape for the cell: its kind, how many parts it has, and,\n// for a value that cannot be read as a shape, why.\n\nexport type ShapeCategory = 'point' | 'line' | 'polygon' | 'collection' | 'empty' | 'invalid';\n\nconst KIND_NAMES: Readonly<Record<string, string>> = {\n\tPoint: 'Point',\n\tMultiPoint: 'Multi point',\n\tLineString: 'Line',\n\tMultiLineString: 'Multi line',\n\tPolygon: 'Polygon',\n\tMultiPolygon: 'Multi polygon',\n\tGeometryCollection: 'Collection',\n};\n\nconst KIND_CATEGORY: Readonly<Record<string, ShapeCategory>> = {\n\tPoint: 'point',\n\tMultiPoint: 'point',\n\tLineString: 'line',\n\tMultiLineString: 'line',\n\tPolygon: 'polygon',\n\tMultiPolygon: 'polygon',\n\tGeometryCollection: 'collection',\n};\n\n/** What one part of a multi-part shape is called, singular and plural. */\nconst PART_NAMES: Readonly<Record<string, readonly [string, string]>> = {\n\tMultiPoint: ['point', 'points'],\n\tMultiLineString: ['line', 'lines'],\n\tMultiPolygon: ['polygon', 'polygons'],\n\tGeometryCollection: ['shape', 'shapes'],\n};\n\n/** The plain name of a declared shape kind (\"Polygon\", \"Multi line\"), or the kind itself when unknown. */\nexport function shapeKindName(kind: string): string {\n\treturn KIND_NAMES[kind] ?? kind;\n}\n\nexport interface ShapeSummary {\n\tcategory: ShapeCategory;\n\t/** What the cell shows: \"Point\", \"Line\", \"3 polygons\", \"Empty shape\", \"Not a shape\". */\n\tlabel: string;\n\t/** Why the value cannot be read as a shape; null when it can. */\n\tproblem: string | null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalid(problem: string): ShapeSummary {\n\treturn { category: 'invalid', label: 'Not a shape', problem };\n}\n\n/**\n * Summarize a stored shape: a GeoJSON object, the API's `{ geojson }` wrapper, or\n * GeoJSON text. Null for no value, so the cell stays empty.\n */\nexport function summarizeShape(value: unknown): ShapeSummary | null {\n\tif (value === null || value === undefined || value === '') return null;\n\tlet parsed: unknown = value;\n\tif (typeof value === 'string') {\n\t\ttry {\n\t\t\tparsed = JSON.parse(value);\n\t\t} catch {\n\t\t\treturn invalid('This value is not GeoJSON text.');\n\t\t}\n\t}\n\tif (!isRecord(parsed)) return invalid('This value is not a GeoJSON shape.');\n\tconst shape = isRecord(parsed.geojson) ? parsed.geojson : parsed;\n\tconst kind = shape.type;\n\tif (typeof kind !== 'string') return invalid('This value has no shape type.');\n\tconst category = KIND_CATEGORY[kind];\n\tif (!category) return invalid(`\"${kind}\" is not a GeoJSON shape type.`);\n\n\tconst parts = kind === 'GeometryCollection' ? shape.geometries : shape.coordinates;\n\tif (!Array.isArray(parts)) return invalid(`This ${shapeKindName(kind).toLowerCase()} has no ${kind === 'GeometryCollection' ? 'shapes' : 'coordinates'}.`);\n\tif (parts.length === 0) return { category: 'empty', label: 'Empty shape', problem: null };\n\n\tconst partNames = PART_NAMES[kind];\n\tif (!partNames) return { category, label: shapeKindName(kind), problem: null };\n\tconst count = parts.length;\n\treturn { category, label: `${count} ${count === 1 ? partNames[0] : partNames[1]}`, problem: null };\n}\n","/**\n * Formatter utilities for grid cell previews\n * - Keep these pure so they are easy to test\n */\n\nexport function compactJsonPreview(value: unknown, maxLen = 80): string {\n\ttry {\n\t\tconst s = typeof value === 'string' ? value : JSON.stringify(value);\n\t\tif (s.length <= maxLen) return s;\n\t\treturn s.slice(0, maxLen - 1) + '\\u2026';\n\t} catch {\n\t\tconst s = String(value);\n\t\treturn s.length > maxLen ? s.slice(0, maxLen - 1) + '\\u2026' : s;\n\t}\n}\n\nexport function formatArrayPreview(arr: unknown[], max = 3): string {\n\tconst items = arr\n\t\t.slice(0, max)\n\t\t.map((v) => (typeof v === 'object' && v !== null ? compactJsonPreview(v, 20) : String(v)));\n\tconst more = arr.length > max ? ` +${arr.length - max}` : '';\n\treturn items.join(', ') + more;\n}\n\nexport function formatImagePreview(val: unknown): string {\n\tif (!val) return '';\n\tif (typeof val === 'string') return val.split('/').pop() || val;\n\tif (typeof val === 'object' && val !== null) {\n\t\tconst rec = val as Record<string, unknown>;\n\t\tconst url = (rec.url as string) || '';\n\t\tconst filename = (rec.filename as string) || url.split('/').pop() || 'image';\n\t\treturn filename;\n\t}\n\treturn String(val);\n}\n\n","// Geometry SheetsCell factory — native analogue of v1 `GeometryCellFactory`.\n//\n// Owns GEOMETRY_TYPES (geometry, geometry-point, geometry-collection). Geometry\n// stays out-of-band: when the caller supplies a `deriveGeometry` builder (the\n// native mirror of v1's `createGeometryCell`), this factory delegates to it so\n// this module never imports the leaflet-backed geometry view. Without a builder,\n// it falls back to a compact JSON preview as both the copy value and the display\n// string — identical to v1's Text fallback.\n//\n// Copy and display text intentionally use the same compact JSON preview when no\n// geometry-specific builder is available.\n\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport { GEOMETRY_TYPES } from '../../cell-types/cell-type-groups';\nimport { summarizeShape } from '../../cell-types/shape-kind';\nimport { compactJsonPreview } from '../../grid/sheets.formatters';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn GEOMETRY_TYPES.has(cellType);\n}\n\nfunction create(\n\tvalue: unknown,\n\t_metadata: CellCreationMetadata,\n\tderiveGeometry?: (value: unknown) => SheetsCell,\n): SheetsCell {\n\tif (deriveGeometry) {\n\t\treturn deriveGeometry(value ?? null);\n\t}\n\n\t// No value: an empty cell, like every other kind (not the text \"null\").\n\tconst summary = summarizeShape(value);\n\tif (!summary) return { kind: 'geometry', data: '', displayData: '', readonly: false };\n\n\t// The view shows the summary (kind and part count); the compact JSON stays the text\n\t// for the title. A value that cannot be read as a shape carries the reason.\n\tconst display = compactJsonPreview(value, 80);\n\treturn {\n\t\tkind: 'geometry',\n\t\tdata: display,\n\t\tdisplayData: display,\n\t\treadonly: false,\n\t\tmeta: { shapeLabel: summary.label, shapeCategory: summary.category, shapeProblem: summary.problem },\n\t};\n}\n\nexport const geometrySheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// What a file cell holds, read through the value domains the backend defines:\n//\n// image / upload an object with at least one of `url`, `id`, `key`, plus\n// optional `bucket`, `bucket_id`, `provider`, `mime`, `size`,\n// `filename` (and `versions` for images). The upload\n// mutation returns exactly this projection; `url` is set only\n// for a public bucket and is durable.\n// attachment an http(s) URL string.\n// lists an array of the above (upload[]).\n//\n// Nothing here guesses other property names. A signed download URL never\n// enters a stored value: it expires, so it lives only in the preview cache.\n\nimport type { ColumnFileModel } from '@constructive-io/data';\n\n/** One file of a cell, normalized for display. */\nexport interface StoredFile {\n\t/** Files-row id from the projection, or null. */\n\tid: string | null;\n\t/** Object key from the projection, or null. */\n\tkey: string | null;\n\t/** Durable URL: the projection's public `url`, or the attachment link. Never a signed URL. */\n\turl: string | null;\n\tfilename: string | null;\n\tmime: string | null;\n\tsize: number | null;\n\t/** The stored element exactly as the cell holds it, written back unchanged when the file is kept. */\n\traw: unknown;\n}\n\nfunction text(value: unknown): string | null {\n\treturn typeof value === 'string' && value !== '' ? value : null;\n}\n\nfunction size(value: unknown): number | null {\n\tif (typeof value === 'number' && Number.isFinite(value)) return value;\n\tif (typeof value === 'string' && /^\\d+$/.test(value)) return Number(value);\n\treturn null;\n}\n\nfunction fromObject(value: Record<string, unknown>): StoredFile {\n\treturn {\n\t\tid: text(value.id),\n\t\tkey: text(value.key),\n\t\turl: text(value.url),\n\t\tfilename: text(value.filename),\n\t\tmime: text(value.mime),\n\t\tsize: size(value.size),\n\t\traw: value,\n\t};\n}\n\nfunction fromLink(value: string): StoredFile {\n\treturn { id: null, key: null, url: value, filename: basename(value), mime: null, size: null, raw: value };\n}\n\nfunction fromElement(value: unknown): StoredFile | null {\n\tif (value == null) return null;\n\tif (typeof value === 'string') return value ? fromLink(value) : null;\n\tif (typeof value === 'object' && !Array.isArray(value)) return fromObject(value as Record<string, unknown>);\n\t// Unknown element: keep it so a list write never drops data it did not understand.\n\treturn { id: null, key: null, url: null, filename: null, mime: null, size: null, raw: value };\n}\n\n/**\n * The files of a cell value, in order. A list column yields every element; a\n * single column yields zero or one file. `file` may be null when the column\n * model is not known: the value's shape is then read as is.\n */\nexport function storedFilesOf(value: unknown, file?: ColumnFileModel | null): StoredFile[] {\n\tif (Array.isArray(value)) return value.flatMap((element): StoredFile[] => { const file = fromElement(element); return file ? [file] : []; });\n\tif (file?.multiple && value == null) return [];\n\tconst single = fromElement(value);\n\treturn single ? [single] : [];\n}\n\n/** Last path segment of a URL, without query or hash. */\nexport function basename(url: string): string {\n\tconst path = url.split(/[?#]/)[0] ?? url;\n\tconst segment = path.slice(path.lastIndexOf('/') + 1);\n\ttry {\n\t\treturn decodeURIComponent(segment) || url;\n\t} catch {\n\t\treturn segment || url;\n\t}\n}\n\n/** The name to show for a file: its filename, else the URL's last segment, else its key. */\nexport function fileLabel(file: StoredFile): string {\n\treturn file.filename ?? (file.url ? basename(file.url) : null) ?? (file.key ? basename(file.key) : null) ?? 'File';\n}\n\n/** True when the file should preview as an image. */\nexport function isImageFile(file: StoredFile, kind: ColumnFileModel['kind'] | null): boolean {\n\tif (file.mime) return file.mime.startsWith('image/');\n\treturn kind === 'image';\n}\n\n/** A short human type label: `PNG`, `PDF`, or the mime type. */\nexport function fileTypeLabel(mime: string | null, name?: string | null): string | null {\n\tif (mime) {\n\t\tconst subtype = mime.split('/')[1];\n\t\tif (subtype && /^[a-z0-9.+-]+$/i.test(subtype) && subtype.length <= 8) return subtype.replace(/^x-/, '').toUpperCase();\n\t\treturn mime;\n\t}\n\tconst extension = name?.match(/\\.([a-z0-9]{1,8})$/i)?.[1];\n\treturn extension ? extension.toUpperCase() : null;\n}\n\n/** Name, type and size, joined for a title or a chip's second line. */\nexport function fileDetails(file: StoredFile): string {\n\tconst label = fileLabel(file);\n\treturn [label, fileTypeLabel(file.mime, label), file.size != null ? formatFileSize(file.size) : null]\n\t\t.filter(Boolean)\n\t\t.join(' • ');\n}\n\n/** Format a byte count: `0 B`, `1.5 KB`, `10 MB`. */\nexport const formatFileSize = (bytes: number): string => {\n\tif (bytes === 0) return '0 B';\n\tconst k = 1024;\n\tconst sizes = ['B', 'KB', 'MB', 'GB', 'TB'];\n\tconst i = Math.min(sizes.length - 1, Math.floor(Math.log(bytes) / Math.log(k)));\n\treturn parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];\n};\n\n/** Durable URL of the first file of a value, for copy and export. */\nexport function durableUrlOf(value: unknown): string | null {\n\treturn storedFilesOf(value).find((file) => file.url)?.url ?? null;\n}\n","// Native SheetsCell factory for file columns: image, upload, lists of uploads,\n// and attachment links (the MEDIA family).\n//\n// `data` holds the durable URL of each file (`['']` for an empty single cell),\n// so copy and export carry stored URLs only. A signed preview URL never enters\n// this payload: it expires. `meta` carries the column and table models so the\n// view can resolve previews and show the column's upload state.\n\nimport type { ColumnModel, TableModel } from '@constructive-io/data';\n\nimport type { CellType } from '../../cell-types/types';\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport { MEDIA_TYPES } from '../../cell-types/cell-type-groups';\nimport { storedFilesOf } from '../../utils/file.utils';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\n/** What a file cell's `meta` carries beside its cell type. */\nexport interface FileCellMeta {\n\tcellType: CellType;\n\t/** The column model, or null when the grid has not modeled the column. */\n\tcolumn: ColumnModel | null;\n\t/** The table model, or null. */\n\ttable: TableModel | null;\n}\n\n/** The file meta of a cell, when the cell is a file cell. */\nexport function fileCellMetaOf(cell: SheetsCell): FileCellMeta | null {\n\tconst meta = cell.meta as Partial<FileCellMeta> | undefined;\n\tif (!meta?.cellType) return null;\n\treturn { cellType: meta.cellType, column: meta.column ?? null, table: meta.table ?? null };\n}\n\nexport const imageSheetsCellFactory: SheetsCellFactory = {\n\tcanHandle(cellType: string): boolean {\n\t\treturn MEDIA_TYPES.has(cellType);\n\t},\n\n\tcreate(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\t\tconst column = metadata.column ?? null;\n\t\tconst files = storedFilesOf(value, column?.value.file);\n\t\tconst urls = files.map((file) => file.url ?? '');\n\t\tconst data = urls.length > 0 ? urls : [''];\n\t\tconst meta: FileCellMeta = { cellType: metadata.cellType as CellType, column, table: metadata.table ?? null };\n\t\treturn {\n\t\t\tkind: 'image',\n\t\t\tdata,\n\t\t\tdisplayData: JSON.stringify(data),\n\t\t\treadonly: false,\n\t\t\tmeta: { ...meta },\n\t\t};\n\t}\n};\n","// Interval SheetsCell factory — native analogue of v1 `IntervalCellFactory`\n// (grid/cell-content-factory.ts). Claims `cellType === 'interval'` and emits a\n// neutral `text` SheetsCell whose displayData is the compact interval label and\n// whose data is the raw string (or JSON of the object). The display/copy\n// projection parity with the glide factory is the whole point of this phase.\n//\n// `formatIntervalForDisplay` (+ its `IntervalValue` shape) is interval-only domain\n// logic copied VERBATIM from cell-content-factory.ts — it is intentionally NOT\n// imported, because that module stays glide-only and is deleted at cutover.\n\nimport type { CellType } from '../../cell-types/types';\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\n// PostgreSQL interval value structure\ninterface IntervalValue {\n\tyears?: number;\n\tmonths?: number;\n\tdays?: number;\n\thours?: number;\n\tminutes?: number;\n\tseconds?: number;\n}\n\n/**\n * Format a PostgreSQL interval value for compact cell display.\n * Shows only non-zero units in descending order of magnitude.\n * Examples: \"1y 6mo\", \"2h 30m\", \"7d\", \"45s\"\n */\nfunction formatIntervalForDisplay(value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\n\tlet interval: IntervalValue;\n\n\tif (typeof value === 'string') {\n\t\ttry {\n\t\t\tinterval = JSON.parse(value);\n\t\t} catch {\n\t\t\tif (/\\d+[yMwdhms]/.test(value)) {\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\t} else if (typeof value === 'object') {\n\t\tinterval = value as IntervalValue;\n\t} else {\n\t\treturn String(value);\n\t}\n\n\tconst parts: string[] = [];\n\n\tif (interval.years && interval.years !== 0) {\n\t\tparts.push(`${interval.years}y`);\n\t}\n\tif (interval.months && interval.months !== 0) {\n\t\tparts.push(`${interval.months}mo`);\n\t}\n\tif (interval.days && interval.days !== 0) {\n\t\tparts.push(`${interval.days}d`);\n\t}\n\tif (interval.hours && interval.hours !== 0) {\n\t\tparts.push(`${interval.hours}h`);\n\t}\n\tif (interval.minutes && interval.minutes !== 0) {\n\t\tparts.push(`${interval.minutes}m`);\n\t}\n\tif (interval.seconds && interval.seconds !== 0) {\n\t\t// Seconds show as stored (6.789s); a rounded display would hide part of the value.\n\t\tparts.push(`${interval.seconds}s`);\n\t}\n\n\tif (parts.length === 0) {\n\t\treturn '0s';\n\t}\n\n\treturn parts.join(' ');\n}\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn cellType === 'interval';\n}\n\nfunction create(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\tif (value === null || value === undefined) {\n\t\treturn {\n\t\t\tkind: 'text',\n\t\t\tdata: '',\n\t\t\tdisplayData: '',\n\t\t\treadonly: false,\n\t\t\tmeta: { cellType: metadata.cellType as CellType },\n\t\t};\n\t}\n\n\tconst displayValue = formatIntervalForDisplay(value);\n\tconst dataValue = typeof value === 'string' ? value : JSON.stringify(value);\n\n\treturn {\n\t\tkind: 'text',\n\t\tdata: dataValue,\n\t\tdisplayData: displayValue,\n\t\treadonly: false,\n\t\tmeta: { cellType: metadata.cellType as CellType },\n\t};\n}\n\nexport const intervalSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// Number SheetsCell factory — native analogue of v1's NumberCellFactory\n// (grid/cell-content-factory.ts). Claims NUMBER_TYPES (number, integer, smallint,\n// bigint, decimal, currency, percentage, AND `rating` — `rating` lives in NUMBER_TYPES\n// so the number family wins it before the text fallback; a deliberate v1 quirk).\n//\n// A string value is an exact decimal (whole numbers beyond 2^53, exact decimals,\n// \"NaN\", \"Infinity\") and is shown digit for digit: it is never parsed into a JS\n// number. A number value shows as its string form. Null is an empty cell.\n\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport { NUMBER_TYPES } from '../../cell-types/cell-type-groups';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn NUMBER_TYPES.has(cellType);\n}\n\nfunction create(value: unknown, _metadata: CellCreationMetadata): SheetsCell {\n\tif (value === null || value === undefined || value === '') {\n\t\treturn { kind: 'number', data: undefined, displayData: '', readonly: false };\n\t}\n\tif (typeof value === 'string') {\n\t\treturn { kind: 'number', data: value, displayData: value, readonly: false };\n\t}\n\tif (typeof value === 'number') {\n\t\treturn { kind: 'number', data: value, displayData: String(value), readonly: false };\n\t}\n\treturn { kind: 'number', data: undefined, displayData: String(value), readonly: false };\n}\n\nexport const numberSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","/**\n * Identity and write values of related records, read only from the relation\n * model. Nothing here assumes a key named `id`, a one-field key, or a naming\n * convention: every field comes from `RelationModel.keys`, `junction` or\n * `target.primaryKey`, and records are compared by value.\n */\nimport type { RelationModel, TableModel } from '@constructive-io/data';\n\n/** A record as the API returns it. */\nexport type RecordValues = Readonly<Record<string, unknown>>;\n\n/** Key values per field, in the shape a document builder takes. */\nexport type FieldValues = Record<string, unknown>;\n\nfunction present(value: unknown): boolean {\n\treturn value !== null && value !== undefined;\n}\n\n/**\n * A comparable key for the values of `fields`, or null when any of them is\n * missing. Two records with the same values get the same key.\n */\nexport function valuesKey(values: readonly unknown[]): string | null {\n\tif (values.length === 0 || !values.every(present)) return null;\n\treturn JSON.stringify(values);\n}\n\n/** The comparable key of `record` over `fields`, or null when a field has no value. */\nexport function recordKey(record: RecordValues | null | undefined, fields: readonly string[]): string | null {\n\tif (!record) return null;\n\treturn valuesKey(fields.map((field) => record[field]));\n}\n\n/** The values of `fields` in `record`, or null when one is missing. */\nexport function fieldValues(record: RecordValues | null | undefined, fields: readonly string[]): FieldValues | null {\n\tif (!record || fields.length === 0) return null;\n\tconst values: FieldValues = {};\n\tfor (const field of fields) {\n\t\tconst value = record[field];\n\t\tif (!present(value)) return null;\n\t\tvalues[field] = value;\n\t}\n\treturn values;\n}\n\n/**\n * The fields of a related record that identify it for this relation:\n * the referenced fields for belongsTo, the related table's primary key for\n * hasOne/hasMany (the write targets that row), and the fields the junction\n * references for manyToMany.\n */\nexport function linkFields(relation: RelationModel): readonly string[] {\n\tswitch (relation.kind) {\n\t\tcase 'belongsTo':\n\t\t\treturn relation.keys.map((pair) => pair.remote);\n\t\tcase 'hasOne':\n\t\tcase 'hasMany':\n\t\t\treturn relation.target.primaryKey;\n\t\tcase 'manyToMany':\n\t\t\treturn relation.junction?.right.map((pair) => pair.remote) ?? [];\n\t}\n}\n\n/** The comparable identity of a related record for this relation. */\nexport function linkKey(relation: RelationModel, record: RecordValues | null | undefined): string | null {\n\treturn recordKey(record, linkFields(relation));\n}\n\n/** belongsTo: the key of the record this row links to now, read from the row's own fields. */\nexport function belongsToCurrentKey(relation: RelationModel, row: RecordValues | null | undefined): string | null {\n\tif (!row) return null;\n\treturn valuesKey(relation.keys.map((pair) => row[pair.local]));\n}\n\n/**\n * belongsTo: the values to write on this row to link `record`\n * (`keys[].local` from `keys[].remote`), or null when the record lacks one\n * of the referenced values.\n */\nexport function belongsToLinkPatch(relation: RelationModel, record: RecordValues): FieldValues | null {\n\tconst patch: FieldValues = {};\n\tfor (const pair of relation.keys) {\n\t\tconst value = record[pair.remote];\n\t\tif (!present(value)) return null;\n\t\tpatch[pair.local] = value;\n\t}\n\treturn patch;\n}\n\n/** belongsTo: the values that clear the link on this row. */\nexport function belongsToClearPatch(relation: RelationModel): FieldValues {\n\treturn Object.fromEntries(relation.keys.map((pair): [string, null] => [pair.local, null]));\n}\n\n/**\n * hasOne/hasMany: the values to write on a related record so it points at\n * this row (`keys[].remote` from this row's `keys[].local`), or null when this\n * row has no value for one of them.\n */\nexport function hasLinkPatch(relation: RelationModel, row: RecordValues): FieldValues | null {\n\tconst patch: FieldValues = {};\n\tfor (const pair of relation.keys) {\n\t\tconst value = row[pair.local];\n\t\tif (!present(value)) return null;\n\t\tpatch[pair.remote] = value;\n\t}\n\treturn patch;\n}\n\n/** hasOne/hasMany: the values that detach a related record from this row. */\nexport function hasUnlinkPatch(relation: RelationModel): FieldValues {\n\treturn Object.fromEntries(relation.keys.map((pair): [string, null] => [pair.remote, null]));\n}\n\n/**\n * hasOne/hasMany: where a related record points now. `here` when it links to\n * this row, `elsewhere` when it links to another record, `none` when it is free.\n */\nexport function hasLinkOwner(\n\trelation: RelationModel,\n\trow: RecordValues,\n\trecord: RecordValues,\n): 'here' | 'elsewhere' | 'none' {\n\tconst values = relation.keys.map((pair) => record[pair.remote]);\n\tif (!values.some(present)) return 'none';\n\tconst here = valuesKey(relation.keys.map((pair) => row[pair.local]));\n\treturn here !== null && valuesKey(values) === here ? 'here' : 'elsewhere';\n}\n\n/**\n * manyToMany: the values of a new junction row linking this row and `record`,\n * or null when either side lacks a referenced value.\n */\nexport function junctionLinkValues(relation: RelationModel, row: RecordValues, record: RecordValues): FieldValues | null {\n\tconst junction = relation.junction;\n\tif (!junction) return null;\n\tconst values: FieldValues = {};\n\tfor (const pair of junction.left) {\n\t\tconst value = row[pair.local];\n\t\tif (!present(value)) return null;\n\t\tvalues[pair.junction] = value;\n\t}\n\tfor (const pair of junction.right) {\n\t\tconst value = record[pair.remote];\n\t\tif (!present(value)) return null;\n\t\tvalues[pair.junction] = value;\n\t}\n\treturn values;\n}\n\n/** manyToMany: the filter values that select this row's junction rows (`left[].junction` = this row's values). */\nexport function junctionLeftValues(relation: RelationModel, row: RecordValues): FieldValues | null {\n\tconst junction = relation.junction;\n\tif (!junction) return null;\n\tconst values: FieldValues = {};\n\tfor (const pair of junction.left) {\n\t\tconst value = row[pair.local];\n\t\tif (!present(value)) return null;\n\t\tvalues[pair.junction] = value;\n\t}\n\treturn values;\n}\n\n/** manyToMany: the identity of the related record a junction row points at, comparable with {@link linkKey}. */\nexport function junctionRightKey(relation: RelationModel, junctionRow: RecordValues): string | null {\n\tconst right = relation.junction?.right ?? [];\n\treturn valuesKey(right.map((pair) => junctionRow[pair.junction]));\n}\n\n/**\n * manyToMany: a stand-in for the related record a junction row points at,\n * carrying the referenced values under the related table's field names.\n */\nexport function junctionRightRecord(relation: RelationModel, junctionRow: RecordValues): FieldValues {\n\tconst right = relation.junction?.right ?? [];\n\treturn Object.fromEntries(right.map((pair) => [pair.remote, junctionRow[pair.junction]]));\n}\n\n/** The primary-key values of a record of `model`, or null when the table has no key or the record lacks a value. */\nexport function primaryKeyValues(model: TableModel, record: RecordValues): FieldValues | null {\n\treturn fieldValues(record, model.primaryKey);\n}\n\n/**\n * The equality filter that selects records of `model` whose `fields` equal\n * `values`, using the filter input names and operators the model proved.\n * Null when one of the fields cannot be filtered by equality.\n */\nexport function equalityFilter(model: TableModel, values: FieldValues): Record<string, unknown> | null {\n\tconst filter: Record<string, unknown> = {};\n\tfor (const [field, value] of Object.entries(values)) {\n\t\tconst column = model.columns.find((candidate) => candidate.name === field);\n\t\tconst supportsEquality = column?.filter?.operators.some((operator) => operator.name === 'equalTo');\n\t\tif (!column?.filter || !supportsEquality) return null;\n\t\tfilter[column.filter.field] = { equalTo: value };\n\t}\n\treturn Object.keys(filter).length > 0 ? filter : null;\n}\n","/**\n * Labels of related records, from the related table's display rule\n * (`RelationTargetModel.labelFields`, which already applies the host\n * override). No field-name lists live here.\n */\nimport type { RelationModel, RelationTargetModel } from '@constructive-io/data';\n\nimport { linkFields, type RecordValues } from './relation-keys';\n\nconst KEY_SEPARATOR = ' · ';\n\nfunction text(value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\tif (typeof value === 'object') return '';\n\treturn String(value).trim();\n}\n\nfunction sameFields(left: readonly string[], right: readonly string[]): boolean {\n\treturn left.length === right.length && left.every((field, index) => field === right[index]);\n}\n\n/** Join the values of `fields` that have text, or '' when none has. */\nfunction joined(record: RecordValues, fields: readonly string[]): string {\n\treturn fields.map((field) => text(record[field])).filter(Boolean).join(KEY_SEPARATOR);\n}\n\n/**\n * The label of one related record. The first non-empty label field wins; a\n * label made of the key fields shows every key value, because one part of a\n * composite key does not identify the record. A record whose label fields are\n * empty falls back to its key value.\n */\nexport function targetRecordLabel(\n\trecord: RecordValues | null | undefined,\n\ttarget: RelationTargetModel,\n\tfallbackFields: readonly string[] = [],\n): string {\n\tif (!record || typeof record !== 'object') return '';\n\tconst { labelFields, primaryKey } = target;\n\tif (labelFields.length > 0 && sameFields(labelFields, primaryKey)) {\n\t\tconst key = joined(record, primaryKey);\n\t\tif (key) return key;\n\t} else {\n\t\tfor (const field of labelFields) {\n\t\t\tconst value = text(record[field]);\n\t\t\tif (value) return value;\n\t\t}\n\t}\n\treturn joined(record, primaryKey) || joined(record, fallbackFields);\n}\n\n/** The label of a record related through `relation`, falling back to the fields the relation links by. */\nexport function relationRecordLabel(relation: RelationModel, record: RecordValues | null | undefined): string {\n\treturn targetRecordLabel(record, relation.target, linkFields(relation));\n}\n\n/**\n * What tells a related record apart from others with the same label: its other label fields\n * (an email beside a name), else its key. '' when nothing adds to the label.\n */\nexport function relationRecordDistinction(relation: RelationModel, record: RecordValues | null | undefined): string {\n\tif (!record || typeof record !== 'object') return '';\n\tconst label = relationRecordLabel(relation, record);\n\tconst others = relation.target.labelFields.map((field) => text(record[field])).filter((value) => value && value !== label);\n\tconst distinction = others.length > 0 ? others.join(KEY_SEPARATOR) : joined(record, relation.target.primaryKey);\n\treturn distinction === label ? '' : distinction;\n}\n\n/** The labels more than one record in a list shares. */\nexport function sharedLabels(labels: readonly string[]): ReadonlySet<string> {\n\tconst seen = new Set<string>();\n\tconst shared = new Set<string>();\n\tfor (const label of labels) {\n\t\tif (seen.has(label)) shared.add(label);\n\t\telse seen.add(label);\n\t}\n\treturn shared;\n}\n\n/** A link cell as text to read elsewhere: the linked record's label, or a list's labels, comma separated. */\nexport function relationCopyText(relation: RelationModel, value: unknown): string {\n\tif (Array.isArray(value)) {\n\t\treturn value\n\t\t\t.map((record) => relationRecordLabel(relation, record as RecordValues))\n\t\t\t.filter(Boolean)\n\t\t\t.join(', ');\n\t}\n\treturn value && typeof value === 'object' ? relationRecordLabel(relation, value as RecordValues) : '';\n}\n","// Native SheetsCell factory for the `relation` family. Single relations\n// (belongsTo/hasOne) render one label; list relations (hasMany/manyToMany)\n// render chips and a \"+N more\" overflow counted from the connection total\n// when the model says the relation reports one.\n//\n// Labels come from the related table's display rule\n// (`RelationModel.target.labelFields`, host override included); a record\n// whose label fields are empty shows its key value. No field-name lists.\n//\n// Cell payload:\n// - single: data = displayData = the (truncated) label; meta.relationTitle = full label.\n// - list: data = string[] chips (truncated), plus a trailing \"+N\" when more exist;\n// meta.relationTitles = full chip labels, meta.relationCount = every linked record.\n// - both: meta.relationTarget = { tableKey, tableName } of the related table (or null) and\n// meta.relationLinks = one { key, label } per shown record, `key` being its\n// primary-key values (null when it cannot be identified), so the view can open it.\n\nimport type { RelationModel, RelationTargetModel } from '@constructive-io/data';\n\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport { fieldValues, linkFields } from '../../relations/relation-keys';\nimport { targetRecordLabel } from '../../relations/relation-label';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nconst DEFAULT_MAX_RELATION_CHIPS = 3;\nconst DEFAULT_RELATION_LABEL_MAX_LEN = 24;\nconst DRAFT_PREFIX = 'draft:';\n\nfunction truncateLabel(s: string, max: number): string {\n\tif (s.length <= max) return s;\n\tif (max <= 1) return '…';\n\treturn s.slice(0, Math.max(0, max - 1)) + '…';\n}\n\nfunction isDraftKey(value: unknown): boolean {\n\treturn typeof value === 'string' && value.startsWith(DRAFT_PREFIX);\n}\n\ninterface LabelRule {\n\ttarget: RelationTargetModel;\n\tfallbackFields: readonly string[];\n}\n\n/** A shown linked record the view can open: its primary-key values and full label. */\nexport interface RelationCellLink {\n\tkey: Readonly<Record<string, unknown>> | null;\n\tlabel: string;\n}\n\nfunction linkOf(entry: unknown, label: string, rule: LabelRule): RelationCellLink {\n\tconst record = entry && typeof entry === 'object' && !Array.isArray(entry) ? (entry as Record<string, unknown>) : null;\n\treturn { key: fieldValues(record, rule.target.primaryKey), label };\n}\n\nfunction targetOf(metadata: CellCreationMetadata): { tableKey: string; tableName: string } | null {\n\tconst relation = metadata.relation ?? metadata.relationInfo?.relation ?? null;\n\treturn relation?.targetKey ? { tableKey: relation.targetKey, tableName: relation.targetName } : null;\n}\n\nfunction labelRuleOf(metadata: CellCreationMetadata): LabelRule {\n\tconst relation: RelationModel | null = metadata.relation ?? metadata.relationInfo?.relation ?? null;\n\tif (relation) return { target: relation.target, fallbackFields: linkFields(relation) };\n\treturn { target: { primaryKey: [], labelFields: metadata.relationInfo?.displayCandidates ?? [] }, fallbackFields: [] };\n}\n\n/** The full label of one related record; '' for nothing or for a draft placeholder. */\nfunction recordLabel(entry: unknown, rule: LabelRule): string {\n\tif (entry === null || entry === undefined) return '';\n\tif (typeof entry === 'string' || typeof entry === 'number') {\n\t\treturn isDraftKey(entry) ? '' : String(entry).trim();\n\t}\n\tif (typeof entry !== 'object' || Array.isArray(entry)) return '';\n\tconst record = entry as Record<string, unknown>;\n\tif (rule.target.primaryKey.some((field) => isDraftKey(record[field]))) return '';\n\treturn targetRecordLabel(record, rule.target, rule.fallbackFields);\n}\n\nfunction isListRelation(metadata: CellCreationMetadata): boolean {\n\tconst kind = metadata.relation?.kind ?? metadata.relationInfo?.kind;\n\treturn kind === 'hasMany' || kind === 'manyToMany';\n}\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn cellType === 'relation';\n}\n\nfunction create(value: unknown, metadata: CellCreationMetadata, _deriveGeometry?: (value: unknown) => SheetsCell): SheetsCell {\n\tconst relOptions = metadata.relationOptions;\n\tconst chipLimit = relOptions?.relationChipLimit ?? DEFAULT_MAX_RELATION_CHIPS;\n\tconst labelMax = relOptions?.relationLabelMaxLength ?? DEFAULT_RELATION_LABEL_MAX_LEN;\n\tconst rule = labelRuleOf(metadata);\n\n\tconst relationTarget = targetOf(metadata);\n\n\tif (isListRelation(metadata)) {\n\t\tconst entries = Array.isArray(value) ? value : [];\n\t\tconst labelled = entries\n\t\t\t.map((entry) => ({ entry, label: recordLabel(entry, rule) }))\n\t\t\t.filter((item) => item.label.length > 0);\n\t\tconst labels = labelled.map((item) => item.label);\n\t\tconst shown = labels.slice(0, chipLimit);\n\t\tconst relationLinks = labelled.slice(0, chipLimit).map((item) => linkOf(item.entry, item.label, rule));\n\t\tconst reported = metadata.relationTotalCount;\n\t\tconst count = typeof reported === 'number' && reported >= labels.length ? reported : labels.length;\n\t\tconst remaining = count - shown.length;\n\t\tconst chips = shown.map((label) => truncateLabel(label, labelMax));\n\t\treturn {\n\t\t\tkind: 'relation',\n\t\t\tdata: remaining > 0 ? [...chips, `+${remaining}`] : chips,\n\t\t\tdisplayData: '',\n\t\t\treadonly: false,\n\t\t\tmeta: { relationTitles: shown, relationCount: count, relationTarget, relationLinks },\n\t\t};\n\t}\n\n\tconst single = Array.isArray(value) ? value[0] : value;\n\tconst full = recordLabel(single, rule);\n\tconst label = truncateLabel(full, labelMax);\n\tconst relationLinks = full ? [linkOf(single, full, rule)] : [];\n\treturn {\n\t\tkind: 'relation',\n\t\tdata: label,\n\t\tdisplayData: label,\n\t\treadonly: false,\n\t\tmeta: { relationTitle: full, relationTarget, relationLinks },\n\t};\n}\n\nexport const relationSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// Structured-value SheetsCell factory — JSON, ranges, records, points and the\n// view-only kinds (raw bytes, number vectors, values of an unknown kind). Each value\n// renders as compact, readable text; the full value stays in the row for copy and for\n// the viewer or editor overlay.\n\nimport type { CellType } from '../../cell-types/types';\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport { compactJsonPreview } from '../../grid/sheets.formatters';\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { dateTimeTitle, formatDateTimeText, isTimestampText } from '../../cell-types/date-time-format';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nconst STRUCTURED_CELL_TYPES: ReadonlySet<string> = new Set([\n\t'json',\n\t'jsonb',\n\t'range',\n\t'composite',\n\t'point',\n\t'binary',\n\t'vector',\n\t'unknown',\n]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction scalarText(value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\treturn typeof value === 'object' ? JSON.stringify(value) : String(value);\n}\n\n/**\n * `[1, 10)`, `[2024-01-01, ∞)`; both ends open reads as \"Any value\" (the wire cannot\n * tell it from an empty range). With `shown`, timestamp ends read by the date and time\n * rule (`[2024-01-01 07:00:00, …)`, a zoned end in the viewer's zone, whose name is\n * passed to `onZone`); without it, they are exact.\n */\nexport function formatRange(value: unknown, shown = false, onZone?: (zone: string) => void): string {\n\tif (!isRecord(value)) return scalarText(value);\n\tconst endText = (end: unknown) => {\n\t\tif (!shown || typeof end !== 'string' || !isTimestampText(end)) return scalarText(end);\n\t\tconst display = formatDateTimeText(end, 'datetime');\n\t\tif (display.zone) onZone?.(display.zone);\n\t\treturn display.text;\n\t};\n\tconst bound = (side: unknown) => (isRecord(side) && side.value !== null && side.value !== undefined ? side : null);\n\tconst start = bound(value.start);\n\tconst end = bound(value.end);\n\tif (!start && !end) return 'Any value';\n\tconst open = start ? (start.inclusive === false ? '(' : '[') : '(';\n\tconst close = end ? (end.inclusive === true ? ']' : ')') : ')';\n\treturn `${open}${start ? endText(start.value) : '-∞'}, ${end ? endText(end.value) : '∞'}${close}`;\n}\n\nfunction formatComposite(value: unknown): string {\n\tif (!isRecord(value)) return scalarText(value);\n\treturn Object.entries(value)\n\t\t.filter(([name, field]) => name !== '__typename' && field !== null && field !== undefined)\n\t\t.map(([name, field]) => `${fieldLabel(name)}: ${scalarText(field)}`)\n\t\t.join(', ');\n}\n\nfunction formatPoint(value: unknown): string {\n\tif (!isRecord(value)) return scalarText(value);\n\treturn `(${scalarText(value.x)}, ${scalarText(value.y)})`;\n}\n\n/** Byte count of a base64 text. */\nfunction base64Size(text: string): number {\n\tconst clean = text.replace(/\\s/g, '');\n\tconst padding = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;\n\treturn Math.max(0, Math.floor((clean.length * 3) / 4) - padding);\n}\n\nfunction formatBinary(value: unknown): string {\n\tif (typeof value !== 'string') return scalarText(value);\n\tconst size = base64Size(value);\n\tconst summary = `${size} ${size === 1 ? 'byte' : 'bytes'}`;\n\treturn value ? `${summary} · ${value}` : summary;\n}\n\nfunction formatVector(value: unknown): string {\n\tif (!Array.isArray(value)) return scalarText(value);\n\treturn `${value.length} ${value.length === 1 ? 'number' : 'numbers'} · [${value.map(scalarText).join(', ')}]`;\n}\n\nfunction display(cellType: string, value: unknown): string {\n\tswitch (cellType) {\n\t\tcase 'range':\n\t\t\treturn formatRange(value, true);\n\t\tcase 'composite':\n\t\t\treturn formatComposite(value);\n\t\tcase 'point':\n\t\t\treturn formatPoint(value);\n\t\tcase 'binary':\n\t\t\treturn formatBinary(value);\n\t\tcase 'vector':\n\t\t\treturn formatVector(value);\n\t\tdefault:\n\t\t\t// JSON keeps its JSON form so a JSON string reads as \"text\", not as bare text.\n\t\t\treturn compactJsonPreview(JSON.stringify(value) ?? String(value), 200);\n\t}\n}\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn STRUCTURED_CELL_TYPES.has(cellType);\n}\n\nfunction create(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\tconst meta = { cellType: metadata.cellType as CellType };\n\tif (value === null || value === undefined) {\n\t\treturn { kind: 'text', data: '', displayData: '', readonly: false, meta };\n\t}\n\tif (metadata.cellType === 'range') {\n\t\t// A range's timestamp ends read by the date and time rule; the exact text, and the\n\t\t// zone a zoned end is shown in, are the title.\n\t\tlet zone: string | null = null;\n\t\tconst shownText = formatRange(value, true, (name) => (zone = name));\n\t\tconst exact = formatRange(value);\n\t\treturn { kind: 'text', data: exact, displayData: shownText, readonly: false, meta: { ...meta, title: dateTimeTitle(exact, zone) } };\n\t}\n\tconst text = display(metadata.cellType, value);\n\treturn { kind: 'text', data: text, displayData: text, readonly: false, meta };\n}\n\nexport const structuredSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// Default (fallback) SheetsCell factory — native analogue of v1's TextCellFactory\n// (grid/cell-content-factory.ts). It is the LAST factory in dispatcher precedence:\n// `canHandle` returns true for every cellType, so it only WINS the types no\n// earlier family claimed (text, textarea, phone, citext, bpchar, json, jsonb,\n// inet, uuid, color, origin, unknown).\n//\n// v1 emits a Text glide cell: null/undefined -> data/displayData ''; string ->\n// data/displayData = value; anything else -> compactJsonPreview(value, 80) for\n// both. `compactJsonPreview` is shared (sheets.formatters), so it is imported\n// rather than copied.\n\nimport type { CellType } from '../../cell-types/types';\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport { compactJsonPreview } from '../../grid/sheets.formatters';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nfunction canHandle(_cellType: string, _value: unknown): boolean {\n\treturn true;\n}\n\nfunction create(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\tconst meta = { cellType: metadata.cellType as CellType };\n\n\tif (value === null || value === undefined) {\n\t\treturn { kind: 'text', data: '', displayData: '', readonly: false, meta };\n\t}\n\n\tif (typeof value === 'string') {\n\t\treturn { kind: 'text', data: value, displayData: value, readonly: false, meta };\n\t}\n\n\tconst display = compactJsonPreview(value, 80);\n\treturn { kind: 'text', data: display, displayData: display, readonly: false, meta };\n}\n\nexport const textSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// Native SheetsCell factory — URI family (url | email). Ports v1\n// `UriCellFactory` (grid/cell-content-factory.ts) to the neutral SheetsCell\n// render payload. All domain logic (email -> mailto, url passthrough, empty\n// guard) is reproduced here verbatim so this file is glide-free at cutover.\n//\n// `data` holds the navigable URI while `displayData` keeps the user-facing\n// string; the DOM view owns click behavior.\n\nimport type { CellType } from '../../cell-types/types';\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn cellType === 'url' || cellType === 'email';\n}\n\nfunction create(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\tconst cellType = metadata.cellType as CellType;\n\n\tif (value === null || value === undefined || value === '') {\n\t\treturn { kind: 'uri', data: '', displayData: '', readonly: false, meta: { cellType } };\n\t}\n\n\tconst stringValue = String(value);\n\tconst isEmail = metadata.cellType === 'email';\n\tconst data = isEmail ? `mailto:${stringValue}` : stringValue;\n\n\treturn { kind: 'uri', data, displayData: stringValue, readonly: false, meta: { cellType } };\n}\n\nexport const uriSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// The SheetsCell DISPATCHER — the native analogue of v1's `createCellContent`\n// (grid/cell-content-factory.ts). Given a (value, metadata) it selects the first\n// family factory whose `canHandle(cellType, value)` is true and returns its\n// neutral {@link SheetsCell} render payload. Geometry stays out-of-band: the\n// optional `deriveGeometry` hook is threaded straight through to the geometry\n// factory (v1's `createGeometryCell` mirror) so this module never imports the\n// leaflet-backed geometry view.\n//\n// Precedence MIRRORS v1 CELL_FACTORIES exactly (image, uri, badges, dateTime,\n// interval, geometry, relation, number, boolean, text) — `text` is the universal\n// fallback and MUST stay last. Null handling mirrors `createEmptyCell`: pick the\n// first factory that claims the cellType for a null value and let it emit its own\n// empty cell.\n\nimport type { CellType } from '../cell-types/types';\nimport type { CellCreationMetadata } from '../grid/grid-cell-types';\nimport { badgesSheetsCellFactory } from './factories/badges';\nimport { booleanSheetsCellFactory } from './factories/boolean';\nimport { choiceSheetsCellFactory } from './factories/choice';\nimport { dateTimeSheetsCellFactory } from './factories/datetime';\nimport { geometrySheetsCellFactory } from './factories/geometry';\nimport { imageSheetsCellFactory } from './factories/image';\nimport { intervalSheetsCellFactory } from './factories/interval';\nimport { numberSheetsCellFactory } from './factories/number';\nimport { relationSheetsCellFactory } from './factories/relation';\nimport { structuredSheetsCellFactory } from './factories/structured';\nimport { textSheetsCellFactory } from './factories/text';\nimport type { SheetsCellFactory } from './factories/types';\nimport { uriSheetsCellFactory } from './factories/uri';\nimport type { SheetsCell } from './sheets-cell';\n\n// Registry of all SheetsCell factories — SAME precedence as glide CELL_FACTORIES\n// (more specific first; the text fallback MUST be last).\nconst SHEETS_CELL_FACTORIES: SheetsCellFactory[] = [\n\timageSheetsCellFactory,\n\turiSheetsCellFactory,\n\tchoiceSheetsCellFactory,\n\tbadgesSheetsCellFactory,\n\tdateTimeSheetsCellFactory,\n\tintervalSheetsCellFactory,\n\tstructuredSheetsCellFactory,\n\tgeometrySheetsCellFactory,\n\trelationSheetsCellFactory,\n\tnumberSheetsCellFactory,\n\tbooleanSheetsCellFactory,\n\ttextSheetsCellFactory, // Fallback — must be last.\n];\n\n/**\n * Build the neutral {@link SheetsCell} for a (value, metadata). Mirrors v1\n * `createCellContent`: null/undefined → the first claiming factory's empty cell\n * (mirror of `createEmptyCell`); otherwise the first factory whose\n * `canHandle(cellType, value)` is true. `deriveGeometry` is threaded to the\n * geometry factory unchanged. The `text` factory's `canHandle` always returns\n * true, so a factory is always found and the explicit final fallback below is a\n * defensive belt-and-braces guard.\n */\n/**\n * Stamp the resolved cellType onto the cell's `meta` so the cell SELF-DESCRIBES\n * its type (the host reads `SheetsCellResolution.typeKey`, but the cell carrying\n * `meta.cellType` keeps it self-contained for the editor adapters that already\n * read it — date/geometry). MERGE (not replace) so any factory-set meta key\n * (e.g. geometry's `geometryType`) survives. This does not change display or\n * copy text because projection ignores `meta`.\n */\nfunction withTypeKey(cell: SheetsCell, cellType: string): SheetsCell {\n\treturn { ...cell, meta: { ...cell.meta, cellType: cellType as CellType } };\n}\n\nexport function createSheetsCell(\n\tvalue: unknown,\n\tmetadata: CellCreationMetadata,\n\tderiveGeometry?: (value: unknown) => SheetsCell,\n): SheetsCell {\n\tconst { cellType } = metadata;\n\n\tif (value === null || value === undefined) {\n\t\tconst emptyFactory = SHEETS_CELL_FACTORIES.find((f) => f.canHandle(cellType, null));\n\t\tif (emptyFactory) {\n\t\t\treturn withTypeKey(emptyFactory.create(null, metadata, deriveGeometry), cellType);\n\t\t}\n\t\treturn withTypeKey({ kind: 'text', data: '', displayData: '', readonly: false }, cellType);\n\t}\n\n\tconst factory = SHEETS_CELL_FACTORIES.find((f) => f.canHandle(cellType, value));\n\tif (factory) {\n\t\treturn withTypeKey(factory.create(value, metadata, deriveGeometry), cellType);\n\t}\n\n\treturn withTypeKey(\n\t\t{\n\t\t\tkind: 'text',\n\t\t\tdata: value,\n\t\t\tdisplayData: String(value),\n\t\t\treadonly: false,\n\t\t},\n\t\tcellType,\n\t);\n}\n","// React bindings for file columns: where a column uploads to (and why it\n// cannot), and the cell write that waits out the server's file confirmation.\n//\n// The logic lives in `uploads/`; this file only wires it to the provider\n// (storage transport, adapter, host upload config, query cache).\n\nimport { useCallback, useMemo } from 'react';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport type { ColumnModel, TableModel } from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsContext, type SheetsStorageTransport } from '../context/sheets-context';\nimport type { SheetsExecuteFn } from '../context/sheets-execute';\nimport { isAbortError, type FileProjection, type UploadProgressEvent } from '../context/sheets-upload-presigned';\nimport { sheetsIdentifierToRowKey, type SheetsRowIdentifier } from '../row-identity';\nimport { loadColumnStorage, type ColumnStorage, type SendFile } from '../uploads/column-storage';\nimport { FILE_NOT_LIVE_CODE, fileWriteMessage, writeFileCell } from '../uploads/file-cell-write';\nimport { pendingWriteKey, setPendingFileWrite } from '../uploads/pending-file-writes';\nimport { processingPolicyOf, type ProcessingPolicy } from '../uploads/upload-config';\nimport { sheetsMutationKeys, sheetsQueryKeys } from './query-keys';\nimport { useTableModel } from './use-table-model';\nimport type { MediaUrlResolver } from './use-sheets-media-url';\n\nexport type UploadProgress = UploadProgressEvent;\n\n/** The value a file cell stores after a write: a projection, a link, a list, or null. */\nexport type UploadResponse = unknown;\n\n// ============================================================================\n// Cell values\n// ============================================================================\n\nconst LINK_WITHOUT_PUBLIC_URL =\n\t'This column stores a link to each file, so it needs a public bucket. The file was stored without a public address.';\n\n/** The row key of a row, read with the table model's primary key; null when a key field is missing. */\nexport function rowKeyOfRow(table: TableModel, row: Readonly<Record<string, unknown>>): SheetsRowIdentifier | null {\n\tif (table.primaryKey.length === 0) return null;\n\tconst values = table.primaryKey.map((field) => row[field]);\n\tif (values.some((value) => value === undefined || value === null)) return null;\n\tif (table.primaryKey.length === 1) {\n\t\tconst [value] = values;\n\t\treturn typeof value === 'string' || typeof value === 'number' ? value : null;\n\t}\n\treturn Object.fromEntries(table.primaryKey.map((field, index) => [field, values[index]])) as SheetsRowIdentifier;\n}\n\n/** The element a column stores for one uploaded file. Throws when the column cannot hold it. */\nexport function cellElementFor(column: Pick<ColumnModel, 'value'>, projection: FileProjection, file?: File): unknown {\n\tif (column.value.file?.kind === 'attachment') {\n\t\tif (!projection.url) throw new Error(LINK_WITHOUT_PUBLIC_URL);\n\t\treturn projection.url;\n\t}\n\treturn projection.filename || !file ? projection : { ...projection, filename: file.name };\n}\n\n// ============================================================================\n// Column storage\n// ============================================================================\n\nconst transportIds = new WeakMap<SheetsStorageTransport, number>();\nlet nextTransportId = 1;\n\nfunction transportId(storage: SheetsStorageTransport | undefined): number {\n\tif (!storage) return 0;\n\tlet id = transportIds.get(storage);\n\tif (id === undefined) {\n\t\tid = nextTransportId;\n\t\tnextTransportId += 1;\n\t\ttransportIds.set(storage, id);\n\t}\n\treturn id;\n}\n\nexport interface UseColumnStorageResult {\n\tstorage: ColumnStorage | null;\n\tisLoading: boolean;\n\terror: Error | null;\n}\n\n/** Where a file column uploads to and how its previews are signed. Resolved once per column. */\nexport function useColumnStorage(table: TableModel | null | undefined, column: ColumnModel | null | undefined): UseColumnStorageResult {\n\tconst { storage, scopeKey, config, executeUpload } = useSheetsContext();\n\tconst adapter = useSheetsAdapter();\n\tconst injected = config.executeUpload ? executeUpload : undefined;\n\tconst enabled = Boolean(table && column?.value.file);\n\tconst query = useQuery<ColumnStorage, Error>({\n\t\tqueryKey: [\n\t\t\t...sheetsQueryKeys.scope(scopeKey),\n\t\t\t'column-storage',\n\t\t\ttransportId(storage),\n\t\t\ttable?.key ?? '',\n\t\t\tcolumn?.name ?? '',\n\t\t\tJSON.stringify(column?.value.file ?? null),\n\t\t\tJSON.stringify(config.upload ?? null),\n\t\t\tBoolean(injected),\n\t\t],\n\t\tqueryFn: () => loadColumnStorage({\n\t\t\tstorage,\n\t\t\tadapter,\n\t\t\ttable: table!,\n\t\t\tcolumn: column!,\n\t\t\tconfig: config.upload,\n\t\t\tdatabaseId: config.databaseId ?? null,\n\t\t\texecuteUpload: injected,\n\t\t}),\n\t\tenabled,\n\t\tstaleTime: Number.POSITIVE_INFINITY,\n\t\tgcTime: 30 * 60 * 1000,\n\t\tretry: 1,\n\t\tstructuralSharing: false,\n\t});\n\tconst loaded = query.data;\n\tconst onError = config.onError;\n\tconst tableName = table?.name;\n\t// Every failed upload (not a cancel) reaches the host's `onError` with source 'upload'.\n\t// The error names a file row the upload left, if any (`unfinishedUploadOf`).\n\tconst reported = useMemo((): ColumnStorage | undefined => {\n\t\tif (!loaded || loaded.upload.status !== 'ready' || !onError) return loaded;\n\t\tconst { send } = loaded.upload;\n\t\tconst reportingSend: SendFile = async (file, options) => {\n\t\t\ttry {\n\t\t\t\treturn await send(file, options);\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAbortError(error)) onError(error, { source: 'upload', tableName });\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\t\treturn { ...loaded, upload: { status: 'ready', send: reportingSend } };\n\t}, [loaded, onError, tableName]);\n\treturn { storage: enabled ? reported ?? null : null, isLoading: enabled && query.isPending, error: query.error ?? null };\n}\n\nexport interface ColumnMediaResolver {\n\t/** The resolver for `useSheetsMediaUrl`: null when previews cannot be signed, undefined for the fallback discovery. */\n\tresolver: MediaUrlResolver | null | undefined;\n\t/** True while the column's storage is still resolving. */\n\tisLoading: boolean;\n}\n\n/** How a column's previews are signed. A cell without a column model uses the fallback discovery. */\nexport function useColumnMediaResolver(\n\ttable: TableModel | null | undefined,\n\tcolumn: ColumnModel | null | undefined,\n): ColumnMediaResolver {\n\tconst { storage, isLoading } = useColumnStorage(table, column);\n\treturn useMemo((): ColumnMediaResolver => {\n\t\tif (!table || !column?.value.file) return { resolver: undefined, isLoading: false };\n\t\tif (!storage) return { resolver: null, isLoading };\n\t\tconst resolve = storage.resolveUrls;\n\t\treturn { resolver: resolve && storage.previewKey ? { key: storage.previewKey, resolve } : null, isLoading: false };\n\t}, [table, column, storage, isLoading]);\n}\n\nexport type FileUploadState =\n\t| { status: 'loading' }\n\t| { status: 'ready'; send: SendFile }\n\t| { status: 'unavailable'; reason: string };\n\n/** Why the cell cannot be written, from the table model, or null. */\nexport function fileWriteReason(table: TableModel | null | undefined, column: ColumnModel | null | undefined): string | null {\n\tif (table && !table.operations.update) {\n\t\treturn table.issues.find((issue) => issue.scope === 'operation' && issue.target === 'update')?.message\n\t\t\t?? 'Records in this table cannot be changed.';\n\t}\n\tif (column && !column.write.update) return column.write.updateReason ?? 'This column cannot be changed.';\n\treturn null;\n}\n\n/** Whether the column can take a new file now, and the uploader when it can. */\nexport function useFileUploadState(\n\ttable: TableModel | null | undefined,\n\tcolumn: ColumnModel | null | undefined,\n\treadOnlyReason?: string | null,\n): FileUploadState {\n\tconst { storage, isLoading, error } = useColumnStorage(table, column);\n\tconst reason = readOnlyReason ?? fileWriteReason(table, column);\n\tif (reason) return { status: 'unavailable', reason };\n\tif (error) return { status: 'unavailable', reason: error.message || 'The storage service could not be reached.' };\n\tif (isLoading || !storage) return { status: 'loading' };\n\treturn storage.upload;\n}\n\n// ============================================================================\n// Cell writes\n// ============================================================================\n\nexport interface FileCellWriteJob {\n\ttable: TableModel;\n\tcolumn: ColumnModel;\n\t/** Primary-key identity of the row. */\n\trowKey: SheetsRowIdentifier;\n\t/** Grid row id, which keys the cell's pending state. */\n\trowId: string;\n\tvalue: unknown;\n\t/** Called when the server first answers that the file is still processing. */\n\tonProcessing?: () => void;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Write a file cell. While the server confirms the file the cell shows\n * \"Processing file…\"; a failure stays on the cell with a retry, even when the\n * editor has closed, so an uploaded file is never dropped silently.\n */\nexport function useFileCellWriter(): (job: FileCellWriteJob) => Promise<unknown> {\n\tconst { execute, scopeKey, config } = useSheetsContext();\n\tconst adapter = useSheetsAdapter();\n\tconst queryClient = useQueryClient();\n\tconst policy = processingPolicyOf(config.upload);\n\n\treturn useCallback((job: FileCellWriteJob) => {\n\t\tconst key = pendingWriteKey(job.table.key, job.rowId, job.column.name);\n\t\tconst run = async (): Promise<unknown> => {\n\t\t\tsetPendingFileWrite(scopeKey, key, null);\n\t\t\ttry {\n\t\t\t\tconst saved = await writeFileCell({\n\t\t\t\t\tadapter,\n\t\t\t\t\texecute,\n\t\t\t\t\tmodel: job.table,\n\t\t\t\t\tcolumn: job.column,\n\t\t\t\t\trowKey: job.rowKey,\n\t\t\t\t\tvalue: job.value,\n\t\t\t\t\tpolicy,\n\t\t\t\t\tsignal: job.signal,\n\t\t\t\t\tonProcessing: () => {\n\t\t\t\t\t\tsetPendingFileWrite(scopeKey, key, { status: 'processing' });\n\t\t\t\t\t\tjob.onProcessing?.();\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tsetPendingFileWrite(scopeKey, key, null);\n\t\t\t\tvoid queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.table(scopeKey, job.table.name) });\n\t\t\t\tvoid queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, job.table.name) });\n\t\t\t\treturn saved;\n\t\t\t} catch (error) {\n\t\t\t\tif (job.signal?.aborted) {\n\t\t\t\t\tsetPendingFileWrite(scopeKey, key, null);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tsetPendingFileWrite(scopeKey, key, {\n\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\tmessage: fileWriteMessage(error),\n\t\t\t\t\tretry: () => void run().catch((): undefined => undefined),\n\t\t\t\t\tdismiss: () => setPendingFileWrite(scopeKey, key, null),\n\t\t\t\t});\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t};\n\t\treturn run();\n\t}, [adapter, execute, policy, queryClient, scopeKey]);\n}\n\n// ============================================================================\n// One-call upload for single-file columns\n// ============================================================================\n\nexport interface FieldUploadTarget {\n\ttable: TableModel;\n\t/** Column name. */\n\tcolumn: string;\n\trowKey: SheetsRowIdentifier;\n}\n\nexport interface FieldUploadTransport {\n\t/** Data executor for the cell write. */\n\texecute: SheetsExecuteFn;\n\tadapter: Pick<SheetsBackendAdapter, 'updateRow'>;\n\t/** Sends the file to storage (from `useColumnStorage(...).storage.upload`). */\n\tsend: SendFile;\n\tpolicy?: ProcessingPolicy;\n\tonProgress?: (progress: UploadProgress) => void;\n\tonProcessing?: () => void;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Upload one file into a single-file column, or clear it with null, and write\n * the cell. A list column takes its whole list: write it with\n * {@link useFileCellWriter}.\n */\nexport async function executeFieldUpload(\n\ttarget: FieldUploadTarget,\n\tfile: File | null,\n\ttransport: FieldUploadTransport,\n): Promise<UploadResponse> {\n\tconst column = target.table.columns.find((candidate) => candidate.name === target.column);\n\tif (!column?.value.file) throw new Error(`\"${target.column}\" is not a file column of this table.`);\n\tif (column.value.file.multiple) throw new Error(`\"${target.column}\" holds several files; write the whole list.`);\n\t// A key that cannot address the row fails here, before anything is uploaded.\n\tconst rowKey = sheetsIdentifierToRowKey(target.table, target.rowKey);\n\tconst missing = target.table.primaryKey.filter((field) => rowKey[field] === undefined || rowKey[field] === null);\n\tif (missing.length > 0) throw new Error(`The row key has no value for ${missing.join(', ')}.`);\n\tconst value = file\n\t\t? cellElementFor(column, await transport.send(file, { onProgress: transport.onProgress, signal: transport.signal }), file)\n\t\t: null;\n\treturn writeFileCell({\n\t\tadapter: transport.adapter,\n\t\texecute: transport.execute,\n\t\tmodel: target.table,\n\t\tcolumn,\n\t\trowKey: target.rowKey,\n\t\tvalue,\n\t\tpolicy: transport.policy ?? processingPolicyOf(undefined),\n\t\tonProcessing: transport.onProcessing,\n\t\tsignal: transport.signal,\n\t});\n}\n\n// ============================================================================\n// Earlier hook, kept as a thin wrapper\n// ============================================================================\n\n/** @deprecated Options of {@link useSheetsFieldUpload}. */\nexport interface UseFieldUploadOptions {\n\tonProgress?: (progress: UploadProgress) => void;\n\tonSuccess?: (data: UploadResponse) => void;\n\tonError?: (error: Error) => void;\n\t/** Ignored, as before. */\n\tshowToast?: boolean;\n\t/** Ignored, as before. */\n\tsuccessMessage?: string;\n\t/** Ignored, as before. */\n\tsuccessToastDelayMs?: number;\n}\n\n/**\n * @deprecated Use {@link useFileUploadState} with {@link useFileCellWriter}, or\n * {@link executeFieldUpload}. Uploads one file into a single-file column (or\n * clears it with null) through the model-driven path.\n */\nexport function useSheetsFieldUpload(\n\ttableName: string,\n\tfieldName: string,\n\trecordId: SheetsRowIdentifier | null,\n\toptions: UseFieldUploadOptions = {},\n) {\n\tconst { scopeKey } = useSheetsContext();\n\tconst { model: table } = useTableModel(tableName);\n\tconst column = table?.columns.find((candidate) => candidate.name === fieldName) ?? null;\n\tconst upload = useFileUploadState(table, column);\n\tconst writeCell = useFileCellWriter();\n\n\tasync function write(id: SheetsRowIdentifier, file: File | null): Promise<UploadResponse> {\n\t\tif (!table || !column) throw new Error(`Field '${fieldName}' not found in table '${tableName}'.`);\n\t\tlet value: unknown = null;\n\t\tif (file) {\n\t\t\tif (upload.status !== 'ready') throw new Error(upload.status === 'unavailable' ? upload.reason : 'Storage is not ready yet.');\n\t\t\tconst projection = await upload.send(file, { onProgress: options.onProgress, recordId: typeof id === 'object' ? undefined : id });\n\t\t\tvalue = cellElementFor(column, projection, file);\n\t\t}\n\t\treturn writeCell({ table, column, rowKey: id, rowId: typeof id === 'object' ? JSON.stringify(id) : String(id), value });\n\t}\n\n\tconst mutation = useMutation<UploadResponse, Error, File | null>({\n\t\t// Under the 'sheets' prefix and the table's entries, like every Sheets query and\n\t\t// mutation, so a host's global mutation handlers can tell Sheets' own writes apart.\n\t\tmutationKey: sheetsMutationKeys.table(scopeKey, table?.key ?? tableName, 'field-upload', fieldName),\n\t\tmutationFn: (file) => {\n\t\t\tif (recordId == null) throw new Error('Missing record context for upload');\n\t\t\treturn write(recordId, file);\n\t\t},\n\t\tonSuccess: options.onSuccess,\n\t\tonError: options.onError,\n\t});\n\n\tconst resolveRowIdentifier = (row: Readonly<Record<string, unknown>>) => (table ? rowKeyOfRow(table, row) : null);\n\treturn { ...mutation, write, resolveRowIdentifier };\n}\n\nexport { FILE_NOT_LIVE_CODE };\n","// Everything a file column needs from storage, resolved once per column:\n// whether it can upload (and how), and how its previews are signed.\n//\n// Order of authority:\n// 1. A host-injected uploader (`SheetsConfig.executeUpload`) owns uploads.\n// 2. Otherwise the storage service's `_meta` names the upload mutation of\n// the column's files table (see `upload-binding.ts`).\n// 3. A storage service whose `_meta` names none falls back to shape\n// discovery, and only when it finds exactly one upload mutation.\n\nimport { createError, type ColumnModel } from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport type { SheetsStorageTransport } from '../context/sheets-context';\nimport type { SheetsUploadFn } from '../context/sheets-execute';\nimport {\n\tdiscoverSoleUploadCapability,\n\tfetchMediaDownloadUrls,\n\trequestDiscoveredUpload,\n} from '../context/sheets-upload-discovery';\nimport { transferFile, withUnfinishedUpload, type FileProjection, type TransferOptions } from '../context/sheets-upload-presigned';\nimport { downloadUrlSourceOf, fetchDownloadUrls } from './download-urls';\nimport { planeUpload } from './plane-upload';\nimport { loadPlaneDetails, loadStorageCatalog } from './storage-catalog';\nimport { resolveUploadBinding } from './upload-binding';\nimport { uploadChoicesFor, type ResolvedUploadChoices, type SheetsUploadConfig } from './upload-config';\n\nexport interface SendFileOptions extends TransferOptions {\n\t/** The row the file is for, passed to a host-injected uploader. */\n\trecordId?: string | number;\n}\n\n/** Sends one file to storage and resolves to its projection. */\nexport type SendFile = (file: File, options?: SendFileOptions) => Promise<FileProjection>;\n\nexport type ColumnUploadState =\n\t| { status: 'ready'; send: SendFile }\n\t| { status: 'unavailable'; reason: string };\n\nexport interface ColumnStorage {\n\tchoices: ResolvedUploadChoices;\n\tupload: ColumnUploadState;\n\t/** Resolves download URLs by file id, or null when this column's previews cannot be signed. */\n\tresolveUrls: ((ids: readonly string[]) => Promise<Map<string, string>>) | null;\n\t/** Identity of the URL resolver, for batching and caching. */\n\tpreviewKey: string | null;\n}\n\nexport interface ColumnStorageTarget {\n\tstorage: SheetsStorageTransport | undefined;\n\tadapter: Pick<SheetsBackendAdapter, 'fetchMeta' | 'fetchTableModel' | 'listRows'>;\n\t/** The data table that holds the column. */\n\ttable: { key: string; name: string };\n\tcolumn: Pick<ColumnModel, 'name' | 'value'>;\n\tconfig: SheetsUploadConfig | undefined;\n\tdatabaseId: string | null;\n\t/** Host-injected uploader, when the host supplies one. */\n\texecuteUpload?: SheetsUploadFn;\n}\n\nexport const NO_STORAGE_REASON = 'Uploads need a storage endpoint';\n\nconst LINK_NEEDS_PUBLIC_REASON = 'This column stores a link to each file, so it needs a public bucket.';\n\nfunction hostUpload(executeUpload: SheetsUploadFn, target: ColumnStorageTarget): SendFile {\n\treturn async (file, options) => {\n\t\tconst { file: projection } = await executeUpload(file, undefined, {\n\t\t\ttableName: target.table.name,\n\t\t\tfieldName: target.column.name,\n\t\t\trecordId: options?.recordId,\n\t\t\tonProgress: options?.onProgress,\n\t\t});\n\t\treturn projection;\n\t};\n}\n\nfunction discoveryStorage(storage: SheetsStorageTransport, choices: ResolvedUploadChoices, databaseId: string | null): ColumnStorage {\n\tconst send: SendFile = async (file, options) => {\n\t\tconst cap = await discoverSoleUploadCapability(storage);\n\t\tif (!cap.hasFileProjection) throw createError.badRequest('The storage service does not return the file details an upload needs.');\n\t\ttry {\n\t\t\tconst payload = await transferFile(file, (input, signal) => requestDiscoveredUpload(storage.execute, cap, {\n\t\t\t\t...input,\n\t\t\t\t...(choices.bucketKey ? { bucketKey: choices.bucketKey } : { isPublic: choices.isPublic }),\n\t\t\t\t...(databaseId ? { databaseId } : {}),\n\t\t\t}, signal), options);\n\t\t\treturn payload.file;\n\t\t} catch (error) {\n\t\t\tthrow withUnfinishedUpload(error, { filesType: cap.download?.fileTypeName ?? null });\n\t\t}\n\t};\n\treturn {\n\t\tchoices,\n\t\tupload: { status: 'ready', send },\n\t\tresolveUrls: (ids) => fetchMediaDownloadUrls(storage, () => ids),\n\t\tpreviewKey: `${storage.endpoint}|discovery`,\n\t};\n}\n\n/** Resolve the column's storage. Never throws for a deterministic \"cannot\": that is an unavailable state. */\nexport async function loadColumnStorage(target: ColumnStorageTarget): Promise<ColumnStorage> {\n\tconst { storage, adapter, table, column, config, databaseId, executeUpload } = target;\n\tconst choices = uploadChoicesFor(config, table, column.name);\n\tconst file = column.value.file;\n\tconst unavailable = (reason: string, resolveUrls: ColumnStorage['resolveUrls'] = null, previewKey: string | null = null): ColumnStorage =>\n\t\t({ choices, upload: { status: 'unavailable', reason }, resolveUrls, previewKey });\n\n\tif (file?.kind === 'attachment' && !choices.bucketKey && !choices.isPublic) return unavailable(LINK_NEEDS_PUBLIC_REASON);\n\tif (!storage) {\n\t\treturn executeUpload\n\t\t\t? { choices, upload: { status: 'ready', send: hostUpload(executeUpload, target) }, resolveUrls: null, previewKey: null }\n\t\t\t: unavailable(NO_STORAGE_REASON);\n\t}\n\n\tconst catalog = await loadStorageCatalog(storage, adapter);\n\tconst binding = resolveUploadBinding(column, catalog, choices);\n\tif (binding.status === 'discovery') {\n\t\tconst discovered = discoveryStorage(storage, choices, databaseId);\n\t\treturn executeUpload ? { ...discovered, upload: { status: 'ready', send: hostUpload(executeUpload, target) } } : discovered;\n\t}\n\tif (binding.status === 'unavailable' || catalog.source !== 'meta') {\n\t\t// A host uploader decides where the file goes itself; only previews need the binding.\n\t\tif (executeUpload) return { choices, upload: { status: 'ready', send: hostUpload(executeUpload, target) }, resolveUrls: null, previewKey: null };\n\t\treturn unavailable(binding.status === 'unavailable' ? binding.reason : 'Uploads are not enabled for this storage service.');\n\t}\n\n\tconst details = await loadPlaneDetails(storage, adapter, catalog, binding.plane);\n\tconst previewKey = `${storage.endpoint}|${details.plane.filesTableKey}`;\n\tconst urlSource = downloadUrlSourceOf(storage, details);\n\tconst resolveUrls = urlSource ? (ids: readonly string[]) => fetchDownloadUrls(urlSource, ids) : null;\n\tif (executeUpload) return { choices, upload: { status: 'ready', send: hostUpload(executeUpload, target) }, resolveUrls, previewKey };\n\n\tconst upload = planeUpload(storage, adapter, details, { choices, databaseId });\n\tif (upload.status === 'unavailable') return unavailable(upload.reason, resolveUrls, previewKey);\n\tconst send: SendFile = async (file, options) => (await upload.send(file, options)).file;\n\treturn { choices, upload: { status: 'ready', send }, resolveUrls, previewKey };\n}\n","// The storage planes a storage service offers, read from that service's own\n// `_meta` and checked with targeted introspection on the same service.\n//\n// Uploads, download URL lookups and bucket reads all run on the storage\n// endpoint, so every name they use comes from the storage endpoint too: the\n// files table and its upload mutation from `_meta.storage`, the mutation's\n// input fields and payload fields from `__type` lookups, the files and buckets\n// tables' list fields and keys from their table models.\n//\n// A storage service whose `_meta` names no upload mutation (a server older than\n// `MetaStorage.upload`, or one without `_meta`) falls back to the shape\n// discovery in `context/sheets-upload-discovery.ts`. That fallback is the only\n// place names are found by shape.\n\nimport {\n\tMetaContractError,\n\tcreateSchemaTypeLoader,\n\tmetaTablesOf,\n\tnamedTypeOf,\n\tprintTypeRef,\n\ttableKeyOf,\n\ttype IntrospectedInputValue,\n\ttype MetaQuery,\n\ttype SchemaTypeLoader,\n\ttype TableModel,\n} from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport type { SheetsStorageTransport } from '../context/sheets-context';\n\n/** A files table on the storage service and the operation that uploads into it. */\nexport interface StoragePlane {\n\t/** GraphQL type name of the files table. */\n\tfilesType: string;\n\t/** `TableModel.key` of the files table on the storage service. */\n\tfilesTableKey: string;\n\t/** `TableModel.key` of the paired buckets table, or null when the server does not say. */\n\tbucketsTableKey: string | null;\n\t/** Field on the files type that returns a download URL, or null. */\n\tdownloadUrlField: string | null;\n\t/** Root mutation that uploads one file. */\n\tuploadMutation: string;\n\t/** Input type of that mutation, as `_meta` names it, or null. */\n\tuploadInputType: string | null;\n\t/** Payload type of that mutation, as `_meta` names it, or null. */\n\tuploadPayloadType: string | null;\n}\n\nexport type StorageCatalog =\n\t| { source: 'meta'; planes: readonly StoragePlane[]; meta: MetaQuery }\n\t/** The storage `_meta` names no upload mutation; uploads use shape discovery. */\n\t| { source: 'discovery' };\n\nconst catalogs = new WeakMap<SheetsStorageTransport, Promise<StorageCatalog>>();\n\nfunction planesOf(meta: MetaQuery): StoragePlane[] {\n\tconst tables = metaTablesOf(meta);\n\tconst keyByName = new Map(tables.map((table) => [table.name, tableKeyOf(table)] as const));\n\treturn tables.flatMap((table) => {\n\t\tconst storage = table.storage;\n\t\tconst mutation = storage?.upload?.mutation;\n\t\tif (!storage?.isFilesTable || !mutation) return [];\n\t\treturn [{\n\t\t\tfilesType: table.name,\n\t\t\tfilesTableKey: tableKeyOf(table),\n\t\t\tbucketsTableKey: storage.bucketsType ? keyByName.get(storage.bucketsType) ?? null : null,\n\t\t\tdownloadUrlField: storage.downloadUrlField ?? null,\n\t\t\tuploadMutation: mutation,\n\t\t\tuploadInputType: storage.upload?.inputType ?? null,\n\t\t\tuploadPayloadType: storage.upload?.payloadType ?? null,\n\t\t}];\n\t});\n}\n\n/**\n * The storage catalog of one storage transport, loaded once. A deterministic\n * answer (planes, or \"use discovery\") is kept; a failed request is not, so the\n * next caller tries again.\n */\nexport function loadStorageCatalog(\n\tstorage: SheetsStorageTransport,\n\tadapter: Pick<SheetsBackendAdapter, 'fetchMeta'>,\n): Promise<StorageCatalog> {\n\tconst cached = catalogs.get(storage);\n\tif (cached) return cached;\n\tconst request = (async (): Promise<StorageCatalog> => {\n\t\ttry {\n\t\t\tconst meta = await adapter.fetchMeta(storage.execute);\n\t\t\tconst planes = planesOf(meta);\n\t\t\treturn planes.length > 0 ? { source: 'meta', planes, meta } : { source: 'discovery' };\n\t\t} catch (error) {\n\t\t\t// An endpoint whose `_meta` contract does not match is answered by discovery.\n\t\t\tif (error instanceof MetaContractError) return { source: 'discovery' };\n\t\t\tthrow error;\n\t\t}\n\t})();\n\tcatalogs.set(storage, request);\n\trequest.catch(() => {\n\t\tif (catalogs.get(storage) === request) catalogs.delete(storage);\n\t});\n\treturn request;\n}\n\n// ============================================================================\n// Plane details: the upload operation as the storage schema declares it\n// ============================================================================\n\n/** The upload mutation of a plane, checked against the storage schema. */\nexport interface UploadOperation {\n\t/** Root mutation field. */\n\tfield: string;\n\t/** Argument that carries the input object. */\n\targName: string;\n\t/** Printed type of that argument, for the variable definition. */\n\targType: string;\n\t/** Input fields the mutation really accepts. */\n\tinputFields: readonly IntrospectedInputValue[];\n\t/** Payload fields the mutation really returns. */\n\tpayloadFields: ReadonlySet<string>;\n}\n\nexport interface PlaneDetails {\n\tplane: StoragePlane;\n\t/** The upload operation, or null with `uploadReason`. */\n\tupload: UploadOperation | null;\n\tuploadReason: string | null;\n\t/** True when the files type really has `downloadUrlField`. */\n\thasDownloadUrl: boolean;\n\t/** Storage-side model of the files table, or null when it could not be built. */\n\tfiles: TableModel | null;\n\t/** Storage-side model of the buckets table, or null. */\n\tbuckets: TableModel | null;\n}\n\nconst NO_UPLOAD_REASON = 'The storage service does not offer uploads for this file table.';\n\nconst loaders = new WeakMap<SheetsStorageTransport, SchemaTypeLoader>();\nconst details = new WeakMap<SheetsStorageTransport, Map<string, Promise<PlaneDetails>>>();\n\nfunction loaderFor(storage: SheetsStorageTransport): SchemaTypeLoader {\n\tlet loader = loaders.get(storage);\n\tif (!loader) {\n\t\tloader = createSchemaTypeLoader();\n\t\tloaders.set(storage, loader);\n\t}\n\treturn loader;\n}\n\nasync function tableModel(\n\tstorage: SheetsStorageTransport,\n\tadapter: Pick<SheetsBackendAdapter, 'fetchTableModel'>,\n\tmeta: MetaQuery,\n\ttableKey: string | null,\n): Promise<TableModel | null> {\n\tif (!tableKey) return null;\n\ttry {\n\t\treturn await adapter.fetchTableModel(storage.execute, meta, tableKey);\n\t} catch {\n\t\t// Without the model the plane still uploads; previews and limits degrade.\n\t\treturn null;\n\t}\n}\n\nasync function readPlaneDetails(\n\tstorage: SheetsStorageTransport,\n\tadapter: Pick<SheetsBackendAdapter, 'fetchTableModel'>,\n\tmeta: MetaQuery,\n\tplane: StoragePlane,\n): Promise<PlaneDetails> {\n\tconst loader = loaderFor(storage);\n\tconst { execute } = storage;\n\tconst roots = await loader.loadRoots(execute);\n\tconst field = roots.mutation?.fields?.find((candidate) => candidate.name === plane.uploadMutation) ?? null;\n\tconst arg = field\n\t\t? field.args.find((candidate) => namedTypeOf(candidate.type)?.name === plane.uploadInputType) ??\n\t\t\t(field.args.length === 1 ? field.args[0] : undefined)\n\t\t: undefined;\n\tconst inputType = arg ? namedTypeOf(arg.type)?.name ?? null : null;\n\tconst payloadType = field ? namedTypeOf(field.type)?.name ?? null : null;\n\tawait loader.loadTypes(execute, [inputType, payloadType, plane.filesType].filter((name): name is string => Boolean(name)));\n\n\tconst input = inputType ? loader.index.get(inputType) : null;\n\tconst payload = payloadType ? loader.index.get(payloadType) : null;\n\tconst filesType = loader.index.get(plane.filesType);\n\tconst upload: UploadOperation | null = field && arg && input?.inputFields && payload?.fields\n\t\t? {\n\t\t\tfield: field.name,\n\t\t\targName: arg.name,\n\t\t\targType: printTypeRef(arg.type),\n\t\t\tinputFields: input.inputFields,\n\t\t\tpayloadFields: new Set(payload.fields.map((candidate) => candidate.name)),\n\t\t}\n\t\t: null;\n\n\tconst [files, buckets] = await Promise.all([\n\t\ttableModel(storage, adapter, meta, plane.filesTableKey),\n\t\ttableModel(storage, adapter, meta, plane.bucketsTableKey),\n\t]);\n\treturn {\n\t\tplane,\n\t\tupload,\n\t\tuploadReason: upload ? null : NO_UPLOAD_REASON,\n\t\thasDownloadUrl: Boolean(\n\t\t\tplane.downloadUrlField && filesType?.fields?.some((candidate) => candidate.name === plane.downloadUrlField),\n\t\t),\n\t\tfiles,\n\t\tbuckets,\n\t};\n}\n\n/** Details of one plane, loaded once per storage transport. A failed load is retried by the next caller. */\nexport function loadPlaneDetails(\n\tstorage: SheetsStorageTransport,\n\tadapter: Pick<SheetsBackendAdapter, 'fetchTableModel'>,\n\tcatalog: Extract<StorageCatalog, { source: 'meta' }>,\n\tplane: StoragePlane,\n): Promise<PlaneDetails> {\n\tlet byPlane = details.get(storage);\n\tif (!byPlane) {\n\t\tbyPlane = new Map();\n\t\tdetails.set(storage, byPlane);\n\t}\n\tconst cached = byPlane.get(plane.filesTableKey);\n\tif (cached) return cached;\n\tconst request = readPlaneDetails(storage, adapter, catalog.meta, plane);\n\tbyPlane.set(plane.filesTableKey, request);\n\trequest.catch(() => {\n\t\tif (byPlane.get(plane.filesTableKey) === request) byPlane.delete(plane.filesTableKey);\n\t});\n\treturn request;\n}\n\n/** The single primary-key field of a files table, or null when the key is composite or unknown. */\nexport function fileKeyField(files: TableModel | null): string | null {\n\treturn files?.primaryKey.length === 1 ? files.primaryKey[0]! : null;\n}\n","// Download URLs for stored files, read in batches through the model of the\n// files table: its list field, its filter argument, its key column and the\n// download URL field `_meta.storage` names. One request per batch with the\n// key's `in` operator; one request per file when the key filter has only\n// `equalTo`. A file the reader cannot see, or a field the schema lacks, simply\n// has no URL: the cell then shows the file's name.\n\nimport type { ColumnModel, TableModel } from '@constructive-io/data';\n\nimport type { SheetsStorageTransport } from '../context/sheets-context';\nimport type { SheetsExecuteFn } from '../context/sheets-execute';\nimport { fileKeyField, type PlaneDetails } from './storage-catalog';\n\n/** Where download URLs are read: an executor and the files table model on that API. */\nexport interface DownloadUrlSource {\n\texecute: SheetsExecuteFn;\n\tfiles: TableModel;\n\t/** Field on the files type that returns the URL; checked against the schema by the caller. */\n\tdownloadUrlField: string;\n}\n\n/** The download URL source of a storage plane, or null when its previews cannot be signed. */\nexport function downloadUrlSourceOf(storage: SheetsStorageTransport, details: PlaneDetails): DownloadUrlSource | null {\n\tif (!details.files || !details.hasDownloadUrl || !details.plane.downloadUrlField) return null;\n\tconst source = { execute: storage.execute, files: details.files, downloadUrlField: details.plane.downloadUrlField };\n\treturn urlQueryFor(source) ? source : null;\n}\n\ninterface UrlQuery {\n\tkeyColumn: ColumnModel;\n\toperator: 'in' | 'equalTo';\n\tsource: string;\n\tvariables: (ids: readonly string[]) => Record<string, unknown>;\n\tread: (data: unknown) => Array<Record<string, unknown> | null>;\n}\n\nfunction urlQueryFor({ files, downloadUrlField }: Omit<DownloadUrlSource, 'execute'>): UrlQuery | null {\n\tconst keyField = fileKeyField(files);\n\tconst keyColumn = files.columns.find((column) => column.name === keyField && column.readable);\n\tconst list = files.operations.list;\n\tconst filter = keyColumn?.filter;\n\tif (!keyColumn || !list?.filter || !filter) return null;\n\tconst operators = new Set(filter.operators.map((operator) => operator.name));\n\tconst operator = operators.has('in') ? 'in' : operators.has('equalTo') ? 'equalTo' : null;\n\tif (!operator) return null;\n\tconst first = list.first ? `, $first: ${list.first.type}` : '';\n\tconst firstArg = list.first ? `, ${list.first.name}: $first` : '';\n\tconst nodes = `{ ${keyColumn.name} ${downloadUrlField} }`;\n\tconst selection = list.shape === 'connection' ? `{ nodes ${nodes} }` : nodes;\n\treturn {\n\t\tkeyColumn,\n\t\toperator,\n\t\tsource: `query SheetsFileDownloadUrls($where: ${list.filter.type}${first}) { ${list.field}(${list.filter.name}: $where${firstArg}) ${selection} }`,\n\t\tvariables: (ids) => ({\n\t\t\twhere: { [filter.field]: operator === 'in' ? { in: ids } : { equalTo: ids[0] } },\n\t\t\t...(list.first ? { first: ids.length } : {}),\n\t\t}),\n\t\tread: (data) => {\n\t\t\tconst value = (data as Record<string, unknown> | null)?.[list.field];\n\t\t\tconst rows = list.shape === 'connection' ? (value as { nodes?: unknown } | null)?.nodes : value;\n\t\t\treturn Array.isArray(rows) ? (rows as Array<Record<string, unknown> | null>) : [];\n\t\t},\n\t};\n}\n\n/** Download URLs by file id. Ids without a URL have no entry. */\nexport async function fetchDownloadUrls(source: DownloadUrlSource, ids: readonly string[]): Promise<Map<string, string>> {\n\tconst urls = new Map<string, string>();\n\tconst query = urlQueryFor(source);\n\tif (ids.length === 0 || !query) return urls;\n\tconst collect = (data: unknown) => {\n\t\tfor (const row of query.read(data)) {\n\t\t\tconst id = row?.[query.keyColumn.name];\n\t\t\tconst url = row?.[source.downloadUrlField];\n\t\t\tif (typeof id === 'string' && typeof url === 'string' && url) urls.set(id, url);\n\t\t}\n\t};\n\tif (query.operator === 'in') {\n\t\tcollect(await source.execute(query.source, query.variables(ids)));\n\t} else {\n\t\tconst results = await Promise.allSettled(ids.map((id) => source.execute(query.source, query.variables([id]))));\n\t\tfor (const result of results) if (result.status === 'fulfilled') collect(result.value);\n\t}\n\treturn urls;\n}\n","// Upload into one storage plane through the model: the plane's upload mutation\n// as the storage schema declares it, the bucket's limits checked first, then the\n// shared transfer (hash, request, PUT with the returned headers, one renewal of\n// an expired URL). Both the grid's file columns and `uploadToFilesTable` use it.\n// A file row an unfinished upload leaves is never deleted here; the error names\n// it and its files table (`unfinishedUploadOf`), and the storage service expires it.\n\nimport { createError } from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport type { SheetsStorageTransport } from '../context/sheets-context';\nimport { transferFile, withUnfinishedUpload, type TransferOptions, type UploadPayload } from '../context/sheets-upload-presigned';\nimport { bucketLimitsFor, bucketRefusal, rememberLandedBucket } from './bucket-limits';\nimport type { PlaneDetails } from './storage-catalog';\nimport { createUploadRequester, uploadOperationProblem, type UploadRequestContext } from './upload-request';\n\nexport type PlaneUpload =\n\t| { status: 'ready'; send: (file: File, options?: TransferOptions) => Promise<UploadPayload> }\n\t| { status: 'unavailable'; reason: string };\n\nconst NOT_ENABLED_REASON = 'Uploads are not enabled for this storage service.';\n\n/** The plane's uploader with these choices, or why it cannot upload. Never throws. */\nexport function planeUpload(\n\tstorage: SheetsStorageTransport,\n\tadapter: Pick<SheetsBackendAdapter, 'listRows'>,\n\tdetails: PlaneDetails,\n\tcontext: UploadRequestContext,\n): PlaneUpload {\n\tconst op = details.upload;\n\tif (!op) return { status: 'unavailable', reason: details.uploadReason ?? NOT_ENABLED_REASON };\n\tconst problem = uploadOperationProblem(op, context);\n\tif (problem) return { status: 'unavailable', reason: problem };\n\n\tconst request = createUploadRequester(storage.execute, op, context);\n\tconst requiresOwner = op.inputFields.some((field) => field.name === 'ownerId');\n\tconst send = async (file: File, options?: TransferOptions): Promise<UploadPayload> => {\n\t\tconst refusal = bucketRefusal(file, await bucketLimitsFor(storage, adapter, details, context.choices, requiresOwner));\n\t\tif (refusal) throw createError.badRequest(refusal);\n\t\tlet payload: UploadPayload;\n\t\ttry {\n\t\t\tpayload = await transferFile(file, request, options);\n\t\t} catch (error) {\n\t\t\t// Name the files table beside the file id the error may carry.\n\t\t\tthrow withUnfinishedUpload(error, { filesType: details.plane.filesType, filesTableKey: details.plane.filesTableKey });\n\t\t}\n\t\trememberLandedBucket(storage, details, context.choices, payload.file.bucket_id);\n\t\treturn payload;\n\t};\n\treturn { status: 'ready', send };\n}\n","// Bucket limits checked before an upload, so a file the bucket would refuse is\n// refused in the browser with a precise message and no request.\n//\n// The limits are columns of the storage module's buckets table, read through\n// the storage-side table model. The storage module generates these columns\n// with fixed names (`key`, `is_public`, `max_file_size`, `allowed_mime_types`;\n// the upload mutation reads them by the same names), so they are looked up by\n// their API field names. A missing column skips that check; the server still\n// enforces every limit, so a skipped check only costs a round trip.\n//\n// The bucket rows are read once per storage plane and cached. Which row applies:\n// 1. the configured bucket key;\n// 2. the bucket an earlier upload of this plane and access landed in;\n// 3. the only visible bucket with the requested access (the server resolves\n// the default bucket under the caller's visibility, so with one visible\n// candidate it is that one).\n// Otherwise nothing is checked before the upload.\n\nimport type { ColumnModel, TableModel } from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport type { SheetsStorageTransport } from '../context/sheets-context';\nimport { formatFileSize } from '../utils/file.utils';\nimport type { PlaneDetails } from './storage-catalog';\nimport type { ResolvedUploadChoices } from './upload-config';\n\nconst BUCKET_COLUMNS = {\n\tkey: 'key',\n\tisPublic: 'isPublic',\n\tmaxFileSize: 'maxFileSize',\n\tallowedMimeTypes: 'allowedMimeTypes',\n} as const;\n\n/** Most bucket rows read for one plane. */\nconst BUCKET_PAGE_SIZE = 100;\n\nexport interface BucketLimits {\n\t/** Bucket key, for messages. */\n\tkey: string | null;\n\tmaxFileSize: number | null;\n\tallowedMimeTypes: readonly string[] | null;\n}\n\ninterface BucketRow extends BucketLimits {\n\tid: unknown;\n\tisPublic: boolean | null;\n}\n\nconst bucketRows = new WeakMap<SheetsStorageTransport, Map<string, Promise<BucketRow[] | null>>>();\n/** Bucket id of the last upload per storage plane and access. */\nconst landedBuckets = new WeakMap<SheetsStorageTransport, Map<string, unknown>>();\n\nfunction column(model: TableModel, name: string): ColumnModel | null {\n\treturn model.columns.find((candidate) => candidate.name === name && candidate.readable) ?? null;\n}\n\nfunction numberOf(value: unknown): number | null {\n\tif (typeof value === 'number' && Number.isFinite(value)) return value;\n\tif (typeof value === 'string' && /^\\d+$/.test(value)) return Number(value);\n\treturn null;\n}\n\nasync function readBucketRows(\n\tstorage: SheetsStorageTransport,\n\tadapter: Pick<SheetsBackendAdapter, 'listRows'>,\n\tbuckets: TableModel,\n): Promise<BucketRow[] | null> {\n\tconst keyField = buckets.primaryKey.length === 1 ? buckets.primaryKey[0]! : null;\n\tconst hasLimits = column(buckets, BUCKET_COLUMNS.maxFileSize) || column(buckets, BUCKET_COLUMNS.allowedMimeTypes);\n\tif (!keyField || !hasLimits || !buckets.operations.list) return null;\n\tconst { rows } = await adapter.listRows<Record<string, unknown>>(\n\t\t{ model: buckets, tableName: buckets.key },\n\t\t{ limit: BUCKET_PAGE_SIZE, includeTotalCount: false },\n\t\tstorage.execute,\n\t);\n\treturn rows.map((row) => ({\n\t\tid: row[keyField],\n\t\tkey: typeof row[BUCKET_COLUMNS.key] === 'string' ? (row[BUCKET_COLUMNS.key] as string) : null,\n\t\tisPublic: typeof row[BUCKET_COLUMNS.isPublic] === 'boolean' ? (row[BUCKET_COLUMNS.isPublic] as boolean) : null,\n\t\tmaxFileSize: numberOf(row[BUCKET_COLUMNS.maxFileSize]),\n\t\tallowedMimeTypes: Array.isArray(row[BUCKET_COLUMNS.allowedMimeTypes])\n\t\t\t? (row[BUCKET_COLUMNS.allowedMimeTypes] as unknown[]).filter((type): type is string => typeof type === 'string')\n\t\t\t: null,\n\t}));\n}\n\nfunction rowsFor(\n\tstorage: SheetsStorageTransport,\n\tadapter: Pick<SheetsBackendAdapter, 'listRows'>,\n\tdetails: PlaneDetails,\n): Promise<BucketRow[] | null> {\n\tif (!details.buckets) return Promise.resolve(null);\n\tlet byPlane = bucketRows.get(storage);\n\tif (!byPlane) {\n\t\tbyPlane = new Map();\n\t\tbucketRows.set(storage, byPlane);\n\t}\n\tconst planeKey = details.plane.filesTableKey;\n\tconst cached = byPlane.get(planeKey);\n\tif (cached) return cached;\n\tconst request = readBucketRows(storage, adapter, details.buckets).catch((): null => {\n\t\t// Unreadable limits skip the pre-check; the next upload tries again.\n\t\tbyPlane.delete(planeKey);\n\t\treturn null;\n\t});\n\tbyPlane.set(planeKey, request);\n\treturn request;\n}\n\nfunction accessKey(details: PlaneDetails, choices: ResolvedUploadChoices): string {\n\treturn `${details.plane.filesTableKey}|${choices.bucketKey ?? (choices.isPublic ? 'public' : 'private')}`;\n}\n\n/** Remember which bucket an upload landed in, so the next one is checked against it. */\nexport function rememberLandedBucket(\n\tstorage: SheetsStorageTransport,\n\tdetails: PlaneDetails,\n\tchoices: ResolvedUploadChoices,\n\tbucketId: unknown,\n): void {\n\tif (bucketId == null) return;\n\tlet byAccess = landedBuckets.get(storage);\n\tif (!byAccess) {\n\t\tbyAccess = new Map();\n\t\tlandedBuckets.set(storage, byAccess);\n\t}\n\tbyAccess.set(accessKey(details, choices), bucketId);\n}\n\n/** The limits of the bucket an upload will land in, or null when that bucket is not known. */\nexport async function bucketLimitsFor(\n\tstorage: SheetsStorageTransport,\n\tadapter: Pick<SheetsBackendAdapter, 'listRows'>,\n\tdetails: PlaneDetails,\n\tchoices: ResolvedUploadChoices,\n\trequiresOwner: boolean,\n): Promise<BucketLimits | null> {\n\tconst rows = await rowsFor(storage, adapter, details);\n\tif (!rows) return null;\n\tif (choices.bucketKey) return rows.find((row) => row.key === choices.bucketKey) ?? null;\n\tconst landed = landedBuckets.get(storage)?.get(accessKey(details, choices));\n\tif (landed != null) {\n\t\tconst row = rows.find((candidate) => candidate.id === landed);\n\t\tif (row) return row;\n\t}\n\t// Owner-scoped buckets repeat per owner, so \"the only one\" proves nothing there.\n\tif (requiresOwner) return null;\n\tconst candidates = rows.filter((row) => row.isPublic === choices.isPublic);\n\treturn candidates.length === 1 ? candidates[0]! : null;\n}\n\nfunction typeAllowed(contentType: string, allowed: readonly string[]): boolean {\n\treturn allowed.some((pattern) => {\n\t\tif (pattern === '*/*') return true;\n\t\tif (pattern.endsWith('/*')) return contentType.startsWith(pattern.slice(0, -1));\n\t\treturn contentType === pattern;\n\t});\n}\n\n/** Why the bucket would refuse this file, in the server's own terms, or null when it would accept it. */\nexport function bucketRefusal(file: File, limits: BucketLimits | null): string | null {\n\tif (!limits) return null;\n\tif (limits.maxFileSize != null && file.size > limits.maxFileSize) {\n\t\treturn `\"${file.name}\" is ${formatFileSize(file.size)}. This bucket accepts files up to ${formatFileSize(limits.maxFileSize)}.`;\n\t}\n\tconst contentType = file.type || 'application/octet-stream';\n\tif (limits.allowedMimeTypes && limits.allowedMimeTypes.length > 0 && !typeAllowed(contentType, limits.allowedMimeTypes)) {\n\t\treturn `\"${file.name}\" is a ${contentType} file. This bucket accepts ${limits.allowedMimeTypes.join(', ')}.`;\n\t}\n\treturn null;\n}\n","// The upload mutation for one file, built from the operation the storage\n// schema declares. Only input fields the mutation really has are sent, and a\n// required field the grid cannot fill (an owner id nobody configured) stops the\n// upload before any request with a reason.\n\nimport { createError, isRequiredInput } from '@constructive-io/data';\n\nimport type { SheetsExecuteFn } from '../context/sheets-execute';\nimport {\n\tUPLOAD_PAYLOAD_FIELDS,\n\treadUploadPayload,\n\ttype UploadPayload,\n\ttype UploadRequestInput,\n\ttype UploadRequester,\n} from '../context/sheets-upload-presigned';\nimport type { UploadOperation } from './storage-catalog';\nimport type { ResolvedUploadChoices } from './upload-config';\n\n/** Values the host or the session supplies beside the file itself. */\nexport interface UploadRequestContext {\n\tchoices: ResolvedUploadChoices;\n\t/** `SheetsConfig.databaseId`, sent when the input has `databaseId`. */\n\tdatabaseId: string | null;\n}\n\n/** Payload fields the grid needs to complete an upload. */\nconst REQUIRED_PAYLOAD_FIELDS = ['deduplicated', 'file'] as const;\n\n/** Why an upload operation cannot be called with this context, or null when it can. */\nexport function uploadOperationProblem(op: UploadOperation, context: UploadRequestContext): string | null {\n\tif (!REQUIRED_PAYLOAD_FIELDS.every((name) => op.payloadFields.has(name))) {\n\t\treturn 'The storage service does not return the file details an upload needs.';\n\t}\n\tconst ownerId = op.inputFields.find((field) => field.name === 'ownerId');\n\tif (ownerId && isRequiredInput(ownerId) && !context.choices.ownerId) {\n\t\treturn 'Uploads to this file store need an owner, and none is set.';\n\t}\n\treturn null;\n}\n\nfunction inputValues(op: UploadOperation, file: UploadRequestInput, context: UploadRequestContext): Record<string, unknown> {\n\tconst accepted = new Set(op.inputFields.map((field) => field.name));\n\tconst { choices } = context;\n\tconst values: Record<string, unknown> = {\n\t\tcontentHash: file.contentHash,\n\t\tcontentType: file.contentType,\n\t\tsize: file.size,\n\t\tfilename: file.filename,\n\t\t// A bucket key names the bucket; without one, `isPublic` picks the default bucket.\n\t\t...(choices.bucketKey ? { bucketKey: choices.bucketKey } : { isPublic: choices.isPublic }),\n\t\t...(choices.ownerId ? { ownerId: choices.ownerId } : {}),\n\t\t...(context.databaseId ? { databaseId: context.databaseId } : {}),\n\t};\n\tconst input = Object.fromEntries(Object.entries(values).filter(([name]) => accepted.has(name)));\n\tconst missing = op.inputFields.find((field) => isRequiredInput(field) && !(field.name in input));\n\tif (missing) {\n\t\tthrow createError.badRequest(`The upload cannot be sent: the storage service needs \"${missing.name}\".`);\n\t}\n\treturn input;\n}\n\n/** A requester that sends the operation's mutation on the storage executor. */\nexport function createUploadRequester(\n\texecute: SheetsExecuteFn,\n\top: UploadOperation,\n\tcontext: UploadRequestContext,\n): UploadRequester {\n\tconst selection = UPLOAD_PAYLOAD_FIELDS.filter((name) => op.payloadFields.has(name)).join(' ');\n\tconst source = `mutation SheetsUploadFile($input: ${op.argType}) { ${op.field}(${op.argName}: $input) { ${selection} } }`;\n\treturn async (file, signal): Promise<UploadPayload> => {\n\t\tconst data = await execute<Record<string, unknown>>(source, { input: inputValues(op, file, context) }, { signal });\n\t\treturn readUploadPayload(data?.[op.field]);\n\t};\n}\n","// Which files table a file column uploads into. Pure: no requests.\n//\n// The server binds a column to its files table (`MetaField.file.filesType`)\n// when the API has exactly one. Otherwise the storage service's only files\n// table is used, and with several the host must choose one\n// (`SheetsConfig.upload.columns[table][column].filesType`, or\n// `upload.filesType` for every column). Without a choice the column is\n// read-only: the grid never picks a files table by name.\n\nimport type { ColumnModel } from '@constructive-io/data';\n\nimport type { ResolvedUploadChoices } from './upload-config';\nimport type { StorageCatalog, StoragePlane } from './storage-catalog';\n\nexport type UploadBinding =\n\t| { status: 'plane'; plane: StoragePlane }\n\t/** The storage `_meta` names no upload mutation: the fallback discovery decides (one plane only). */\n\t| { status: 'discovery' }\n\t| { status: 'unavailable'; reason: string };\n\nexport const SEVERAL_FILE_STORES_REASON =\n\t'The storage service has several file stores, and none is chosen for this column.';\n\nexport function resolveUploadBinding(\n\tcolumn: Pick<ColumnModel, 'value'>,\n\tcatalog: StorageCatalog,\n\tchoices: ResolvedUploadChoices,\n): UploadBinding {\n\tconst file = column.value.file;\n\tif (!file) return { status: 'unavailable', reason: 'This column does not hold files.' };\n\tif (catalog.source === 'discovery') return { status: 'discovery' };\n\n\tconst wanted = file.filesType ?? choices.filesType;\n\tif (wanted) {\n\t\tconst plane = catalog.planes.find((candidate) => candidate.filesType === wanted);\n\t\treturn plane\n\t\t\t? { status: 'plane', plane }\n\t\t\t: { status: 'unavailable', reason: `The storage service does not offer the file store \"${wanted}\" this column uses.` };\n\t}\n\tif (catalog.planes.length === 1) return { status: 'plane', plane: catalog.planes[0]! };\n\treturn { status: 'unavailable', reason: SEVERAL_FILE_STORES_REASON };\n}\n","// Host configuration for file uploads (`SheetsConfig.upload`).\n//\n// Every field is optional. A server that names the files table of each file\n// column needs none of them: Sheets reads the upload operation from the\n// storage service's own `_meta`. The fields below choose a bucket, supply an\n// owner for entity-scoped storage, and bind columns the server leaves open.\n\n/** Per-column upload choices. Each field overrides the matching top-level field. */\nexport interface SheetsUploadColumnConfig {\n\t/** Files table (GraphQL type name) to upload into, when the server does not bind the column to one. */\n\tfilesType?: string;\n\t/** Bucket key to upload into. */\n\tbucketKey?: string;\n\t/** Which default bucket to use when no bucket key is set: the public one (true) or the private one (false). */\n\tisPublic?: boolean;\n\t/** Owner id for a files table whose uploads need one. */\n\townerId?: string;\n}\n\n/** How long Sheets keeps retrying a cell write while the server confirms a new file. */\nexport interface SheetsUploadProcessingConfig {\n\t/** Give up and offer a manual retry after this long. Default 120 000 ms. */\n\ttimeoutMs?: number;\n\t/** First wait between attempts. Doubles up to `maxDelayMs`. Default 1 000 ms. */\n\tinitialDelayMs?: number;\n\t/** Longest wait between attempts. Default 8 000 ms. */\n\tmaxDelayMs?: number;\n}\n\nexport interface SheetsUploadConfig {\n\t/** Bucket key to upload into. Omit to use the default bucket chosen by `isPublic`. */\n\tbucketKey?: string;\n\t/** Which default bucket to use when no bucket key is set. Default true (the public default bucket). */\n\tisPublic?: boolean;\n\t/** Owner id sent when a files table needs one (entity-scoped storage). */\n\townerId?: string;\n\t/**\n\t * Files table (GraphQL type name) for file columns the server does not bind,\n\t * when the storage service has several files tables.\n\t */\n\tfilesType?: string;\n\t/** Per-column choices, keyed by `TableModel.key` or table name, then by column name. */\n\tcolumns?: Readonly<Record<string, Readonly<Record<string, SheetsUploadColumnConfig>>>>;\n\t/** Retry window for a write that waits on the server's file confirmation. */\n\tprocessing?: SheetsUploadProcessingConfig;\n}\n\n/** The choices that apply to one column, after per-column entries are merged over the top level. */\nexport interface ResolvedUploadChoices {\n\tfilesType: string | null;\n\tbucketKey: string | null;\n\t/** The access the default bucket is chosen by. Ignored by the server when a bucket key is set. */\n\tisPublic: boolean;\n\townerId: string | null;\n}\n\n/** Choices for one column: the per-column entry (by table key first, then table name) over the top level. */\nexport function uploadChoicesFor(\n\tconfig: SheetsUploadConfig | undefined,\n\ttable: { key: string; name: string },\n\tcolumnName: string,\n): ResolvedUploadChoices {\n\tconst byTable = config?.columns?.[table.key] ?? config?.columns?.[table.name];\n\tconst column = byTable?.[columnName];\n\treturn {\n\t\tfilesType: column?.filesType ?? config?.filesType ?? null,\n\t\tbucketKey: column?.bucketKey ?? config?.bucketKey ?? null,\n\t\tisPublic: column?.isPublic ?? config?.isPublic ?? true,\n\t\townerId: column?.ownerId ?? config?.ownerId ?? null,\n\t};\n}\n\nexport interface ProcessingPolicy {\n\ttimeoutMs: number;\n\tinitialDelayMs: number;\n\tmaxDelayMs: number;\n}\n\nconst DEFAULT_PROCESSING: ProcessingPolicy = { timeoutMs: 120_000, initialDelayMs: 1_000, maxDelayMs: 8_000 };\n\nexport function processingPolicyOf(config: SheetsUploadConfig | undefined): ProcessingPolicy {\n\tconst processing = config?.processing;\n\treturn {\n\t\ttimeoutMs: processing?.timeoutMs ?? DEFAULT_PROCESSING.timeoutMs,\n\t\tinitialDelayMs: processing?.initialDelayMs ?? DEFAULT_PROCESSING.initialDelayMs,\n\t\tmaxDelayMs: processing?.maxDelayMs ?? DEFAULT_PROCESSING.maxDelayMs,\n\t};\n}\n","// Writing a file cell, including the wait for the server's file confirmation.\n//\n// A managed file column checks every new file document as it is written: the\n// files row must be live (`uploaded` or `processed`). The upload mutation\n// creates the row as `requested`, and a background job confirms the PUT later\n// (by default about 30 seconds after the request). Until then the write is\n// refused with the error code FILE_REF_FILE_NOT_LIVE and the context\n// `{ field, file_id, status }` (constructive-db\n// `ast_plpgsql_helpers.file_ref_guard_body`, raised through\n// `errors.raise_error`; the GraphQL error carries the code as its message and\n// in `extensions.code`). So the write is retried with backoff for a bounded\n// time. A row the job `rejected` never becomes live, so that answer stops at once.\n\nimport { getErrorCode, toError, type ColumnModel, type TableModel } from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport { responseErrorsOf, type SheetsExecuteFn } from '../context/sheets-execute';\nimport type { SheetsRowIdentifier } from '../row-identity';\nimport type { ProcessingPolicy } from './upload-config';\n\nexport const FILE_NOT_LIVE_CODE = 'FILE_REF_FILE_NOT_LIVE';\n\n/** The write is waiting for the server to confirm the file. */\nexport class FileProcessingTimeoutError extends Error {\n\tconstructor() {\n\t\tsuper('The file is still being processed, so it was not saved to this cell yet.');\n\t\tthis.name = 'FileProcessingTimeoutError';\n\t}\n}\n\n/** Friendlier text for the file-reference refusals a managed file column raises. */\nconst FILE_REF_MESSAGES: Record<string, string> = {\n\tFILE_REF_FILE_NOT_LIVE: 'The storage service has not accepted this file.',\n\tFILE_REF_FILE_NOT_FOUND: 'This file could not be found, or you cannot see it.',\n\tFILE_REF_BUCKET_MISMATCH: 'This column keeps its files in a different bucket.',\n\tFILE_REF_ID_INVALID: 'This file reference is not valid.',\n};\n\n/** The status the server reported for a file that is not live, when it said. */\nfunction notLiveStatus(error: unknown): string | null {\n\tconst fromContext = toError(error).context?.status;\n\tif (typeof fromContext === 'string') return fromContext;\n\tconst response = responseErrorsOf(error)?.find((candidate) => candidate.extensions?.code === FILE_NOT_LIVE_CODE);\n\tconst status = response?.extensions?.context?.status;\n\treturn typeof status === 'string' ? status : null;\n}\n\nfunction isNotLive(error: unknown): boolean {\n\tif (getErrorCode(error) === FILE_NOT_LIVE_CODE) return true;\n\treturn Boolean(responseErrorsOf(error)?.some((candidate) =>\n\t\tcandidate.extensions?.code === FILE_NOT_LIVE_CODE || candidate.message === FILE_NOT_LIVE_CODE));\n}\n\n/** A user-facing message for a failed file write. */\nexport function fileWriteMessage(error: unknown): string {\n\tif (error instanceof FileProcessingTimeoutError) return error.message;\n\tconst code = getErrorCode(error);\n\tif (code === FILE_NOT_LIVE_CODE && notLiveStatus(error) === 'rejected') {\n\t\treturn 'The storage service rejected this file (its contents did not match what was uploaded).';\n\t}\n\tif (code && FILE_REF_MESSAGES[code]) return FILE_REF_MESSAGES[code]!;\n\treturn error instanceof Error && error.message ? error.message : 'The file could not be saved.';\n}\n\nfunction wait(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(signal.reason ?? new Error('Cancelled'));\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal?.removeEventListener('abort', onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(signal?.reason ?? new Error('Cancelled'));\n\t\t};\n\t\tsignal?.addEventListener('abort', onAbort, { once: true });\n\t});\n}\n\nexport interface FileCellWrite {\n\tadapter: Pick<SheetsBackendAdapter, 'updateRow'>;\n\texecute: SheetsExecuteFn;\n\tmodel: TableModel;\n\tcolumn: ColumnModel;\n\trowKey: SheetsRowIdentifier;\n\t/** The value to store: a projection, a link, a list, or null to clear. */\n\tvalue: unknown;\n\tpolicy: ProcessingPolicy;\n\t/** Called once when the first write is refused because the file is still processing. */\n\tonProcessing?: () => void;\n\tsignal?: AbortSignal;\n}\n\n/** Write the cell and return the stored value. Waits out FILE_REF_FILE_NOT_LIVE within the policy. */\nexport async function writeFileCell(write: FileCellWrite): Promise<unknown> {\n\tconst { adapter, execute, model, column, rowKey, value, policy, signal } = write;\n\tconst started = Date.now();\n\tlet delay = policy.initialDelayMs;\n\tlet announced = false;\n\tfor (;;) {\n\t\ttry {\n\t\t\tconst row = await adapter.updateRow<Record<string, unknown>>(\n\t\t\t\t{ model, tableName: model.key },\n\t\t\t\trowKey,\n\t\t\t\t{ [column.name]: value },\n\t\t\t\texecute,\n\t\t\t\t{ returning: [column.name] },\n\t\t\t);\n\t\t\tif (!row || !Object.prototype.hasOwnProperty.call(row, column.name)) {\n\t\t\t\tthrow new Error(`The update did not return \"${column.name}\".`);\n\t\t\t}\n\t\t\treturn row[column.name];\n\t\t} catch (error) {\n\t\t\tif (!isNotLive(error) || notLiveStatus(error) === 'rejected') throw error;\n\t\t\tif (Date.now() - started + delay > policy.timeoutMs) throw new FileProcessingTimeoutError();\n\t\t\tif (!announced) {\n\t\t\t\tannounced = true;\n\t\t\t\twrite.onProcessing?.();\n\t\t\t}\n\t\t\tawait wait(delay, signal);\n\t\t\tdelay = Math.min(delay * 2, policy.maxDelayMs);\n\t\t}\n\t}\n}\n","// File cell writes that outlive the editor: while the server confirms a new\n// file, the cell shows \"Processing file…\"; if the wait runs out or the write\n// fails, the cell shows that the file was not saved and offers a retry. The\n// uploaded file is never dropped silently.\n//\n// One store per Sheets scope (endpoint, database, user), keyed by table, grid\n// row id and column.\n\nimport { useCallback, useSyncExternalStore } from 'react';\n\nimport type { SheetsScopeKey } from '../context/sheets-context';\n\nexport type PendingFileWrite =\n\t| { status: 'processing' }\n\t| { status: 'failed'; message: string; retry: () => void; dismiss: () => void };\n\ntype Listener = () => void;\n\nclass PendingFileWrites {\n\tprivate readonly entries = new Map<string, PendingFileWrite>();\n\tprivate readonly listeners = new Set<Listener>();\n\n\tget(key: string): PendingFileWrite | null {\n\t\treturn this.entries.get(key) ?? null;\n\t}\n\n\tset(key: string, entry: PendingFileWrite | null): void {\n\t\tif (entry) this.entries.set(key, entry);\n\t\telse this.entries.delete(key);\n\t\tfor (const listener of this.listeners) listener();\n\t}\n\n\tsubscribe = (listener: Listener): (() => void) => {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t};\n}\n\nconst stores = new WeakMap<SheetsScopeKey, PendingFileWrites>();\n\nfunction storeFor(scope: SheetsScopeKey): PendingFileWrites {\n\tlet store = stores.get(scope);\n\tif (!store) {\n\t\tstore = new PendingFileWrites();\n\t\tstores.set(scope, store);\n\t}\n\treturn store;\n}\n\nexport function pendingWriteKey(tableKey: string, rowId: string, column: string): string {\n\treturn JSON.stringify([tableKey, rowId, column]);\n}\n\nexport function setPendingFileWrite(scope: SheetsScopeKey, key: string, entry: PendingFileWrite | null): void {\n\tstoreFor(scope).set(key, entry);\n}\n\nexport function getPendingFileWrite(scope: SheetsScopeKey, key: string): PendingFileWrite | null {\n\treturn storeFor(scope).get(key);\n}\n\n/** The pending write of one cell, or null. */\nexport function usePendingFileWrite(scope: SheetsScopeKey, key: string | null): PendingFileWrite | null {\n\tconst store = storeFor(scope);\n\tconst read = useCallback(() => (key ? store.get(key) : null), [store, key]);\n\treturn useSyncExternalStore(store.subscribe, read, read);\n}\n","import React, { useLayoutEffect, useMemo, useRef } from 'react';\n\nimport { sheetsLogger } from '../../utils/sheets-logger';\n\ntype TargetRect = {\n\tx: number;\n\ty: number;\n\twidth: number;\n\theight: number;\n};\n\ntype Props = {\n\tchildren?: React.ReactNode;\n\tdebugName?: string;\n\tmarginPx?: number;\n\tminBelowPx?: number;\n\ttarget?: TargetRect;\n};\n\nexport const OverlayMeasureContext = React.createContext<{\n\tmaxHeight: number;\n\tshouldFlip: boolean;\n}>({ maxHeight: 0, shouldFlip: false });\n\nexport function computeOverlayGeometry(\n\tviewportHeight: number,\n\ttargetY: number | undefined,\n\ttargetH: number | undefined,\n\tmarginPx: number,\n\tminBelowPx: number,\n) {\n\tconst maxHeightPx = Math.max(0, viewportHeight - marginPx * 2);\n\tconst hasTarget = targetY != null && targetH != null;\n\tconst targetBottom = hasTarget ? targetY + targetH : 0;\n\tconst spaceBelow = viewportHeight - targetBottom - marginPx;\n\tconst spaceAbove = hasTarget ? targetY - marginPx : 0;\n\t// Open above only when the room below is short AND there is more room above; the\n\t// overlay then gets the side's own room as its budget, so it never covers its cell.\n\tconst shouldFlip = hasTarget && spaceBelow < minBelowPx && spaceAbove > spaceBelow;\n\tconst maxHeight = Math.max(0, shouldFlip ? spaceAbove : spaceBelow);\n\treturn { shouldFlip, maxHeight, targetBottom, spaceBelow, spaceAbove, maxHeightPx };\n}\n\nexport function OverlayViewportGuard({ children, debugName, marginPx = 12, minBelowPx = 320, target }: Props) {\n\tconst ref = useRef<HTMLDivElement | null>(null);\n\tconst overlayRootRef = useRef<HTMLElement | null>(null);\n\tconst clipRegionRef = useRef<HTMLElement | null>(null);\n\tconst restoreRef = useRef<{ top: string; maxHeight: string; clipOverflow: string } | null>(null);\n\n\tconst targetY = target?.y;\n\tconst targetH = target?.height;\n\tconst computed = useMemo(() => {\n\t\tconst vh = typeof window !== 'undefined' ? window.innerHeight : 800;\n\t\tconst { shouldFlip, maxHeight } = computeOverlayGeometry(vh, targetY, targetH, marginPx, minBelowPx);\n\t\treturn { shouldFlip, maxHeight };\n\t}, [marginPx, minBelowPx, targetY, targetH]);\n\n\tconst positionRef = useRef<() => void>(null);\n\tpositionRef.current = () => {\n\t\tconst el = ref.current;\n\t\tif (!el) return;\n\n\t\t// Use cached clipRegion/overlayRoot when still connected, re-query otherwise\n\t\tlet clipRegion = clipRegionRef.current;\n\t\tif (!clipRegion?.isConnected) {\n\t\t\tclipRegion = el.closest('.gdg-clip-region') as HTMLElement | null;\n\t\t\tclipRegionRef.current = clipRegion;\n\t\t}\n\n\t\tconst cachedRoot = overlayRootRef.current;\n\t\tconst overlayRoot =\n\t\t\t(cachedRoot?.isConnected ? cachedRoot : null) ??\n\t\t\t(clipRegion?.parentElement as HTMLElement | null) ?? null;\n\t\tif (!overlayRoot) return;\n\t\toverlayRootRef.current = overlayRoot;\n\n\t\tif (!restoreRef.current) {\n\t\t\trestoreRef.current = {\n\t\t\t\ttop: overlayRoot.style.top,\n\t\t\t\tmaxHeight: overlayRoot.style.maxHeight,\n\t\t\t\tclipOverflow: clipRegion?.style.overflow ?? '',\n\t\t\t};\n\t\t}\n\n\t\tif (clipRegion && clipRegion.style.overflow !== 'visible') {\n\t\t\tclipRegion.style.overflow = 'visible';\n\t\t}\n\n\t\tconst { shouldFlip, spaceBelow, targetBottom, maxHeightPx } = computeOverlayGeometry(\n\t\t\twindow.innerHeight, target?.y, target?.height, marginPx, minBelowPx,\n\t\t);\n\n\t\tif (!shouldFlip) {\n\t\t\tconst restoreTop = restoreRef.current?.top ?? '';\n\t\t\tif (overlayRoot.style.top !== restoreTop) {\n\t\t\t\toverlayRoot.style.top = restoreTop;\n\t\t\t}\n\t\t\tconst newMaxHeight = `${Math.max(0, spaceBelow)}px`;\n\t\t\tif (overlayRoot.style.maxHeight !== newMaxHeight) {\n\t\t\t\toverlayRoot.style.maxHeight = newMaxHeight;\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Flip path: set maxHeight, force reflow, set top synchronously.\n\t\tconst newFlipMaxHeight = `${maxHeightPx}px`;\n\t\tif (overlayRoot.style.maxHeight !== newFlipMaxHeight) {\n\t\t\toverlayRoot.style.maxHeight = newFlipMaxHeight;\n\t\t}\n\n\t\tconst h = overlayRoot.getBoundingClientRect().height;\n\t\tlet nextTop = targetBottom - h;\n\t\tnextTop = Math.max(marginPx, Math.min(nextTop, window.innerHeight - marginPx - h));\n\t\tif (!Number.isFinite(nextTop)) nextTop = marginPx;\n\t\tconst newTop = `${nextTop}px`;\n\t\tif (overlayRoot.style.top !== newTop) {\n\t\t\toverlayRoot.style.top = newTop;\n\t\t}\n\n\t\tif (typeof globalThis !== 'undefined' && (globalThis as Record<string, unknown>).__DEV__) {\n\t\t\tsheetsLogger().debug?.('[data-grid][overlay-flip]', { debugName, shouldFlip, spaceBelow });\n\t\t}\n\t};\n\n\tuseLayoutEffect(() => {\n\t\tpositionRef.current?.();\n\n\t\t// Reveal via Web Animations API — immune to React Strict Mode and Glide style overwrites.\n\t\t// Only delay when Glide's async useStayOnScreen needs to adjust horizontal position\n\t\t// (~100ms via IntersectionObserver + rAF). For overlays that fit within the viewport,\n\t\t// reveal immediately with a short fade for polish.\n\t\tconst el = ref.current;\n\t\tconst overlayRoot = overlayRootRef.current;\n\t\tconst clipsRight = overlayRoot ? overlayRoot.getBoundingClientRect().right > window.innerWidth : false;\n\t\tconst animation = el?.animate(\n\t\t\t[{ opacity: 0 }, { opacity: 1 }],\n\t\t\t{ duration: 50, delay: clipsRight ? 50 : 0, easing: 'ease-out', fill: 'both' },\n\t\t);\n\n\t\tconst handleResize = () => positionRef.current?.();\n\t\twindow.addEventListener('resize', handleResize);\n\n\t\tlet ro: ResizeObserver | undefined;\n\t\tlet roRaf = 0;\n\t\tif ('ResizeObserver' in window && el) {\n\t\t\tro = new ResizeObserver(() => {\n\t\t\t\tcancelAnimationFrame(roRaf);\n\t\t\t\troRaf = requestAnimationFrame(() => positionRef.current?.());\n\t\t\t});\n\t\t\tro.observe(el);\n\t\t}\n\n\t\treturn () => {\n\t\t\tanimation?.cancel();\n\t\t\tcancelAnimationFrame(roRaf);\n\t\t\twindow.removeEventListener('resize', handleResize);\n\t\t\tro?.disconnect();\n\t\t\tconst root = overlayRootRef.current;\n\t\t\tif (root && restoreRef.current) {\n\t\t\t\troot.style.top = restoreRef.current.top;\n\t\t\t\troot.style.maxHeight = restoreRef.current.maxHeight;\n\t\t\t}\n\t\t\tconst clip = clipRegionRef.current;\n\t\t\tif (clip && restoreRef.current) {\n\t\t\t\tclip.style.overflow = restoreRef.current.clipOverflow;\n\t\t\t}\n\t\t};\n\t}, []);\n\n\treturn (\n\t\t<OverlayMeasureContext.Provider value={computed}>\n\t\t\t<div ref={ref}>\n\t\t\t\t{children}\n\t\t\t</div>\n\t\t</OverlayMeasureContext.Provider>\n\t);\n}\n","'use client';\n\n// Native array editor — a thin EditorProps adapter that RE-HOSTS the value-native\n// `ArrayEditor` ({ value, onChange, onFinished }). Each item is checked by the\n// column's element rules (`parseColumnInput`): a whole-number list takes whole\n// numbers, a date list takes dates, a choice list takes its choices. The committed\n// value is the parsed list (numbers stay numbers, exact decimals stay strings).\n// `onFinished(undefined)` (cancel / Escape) -> `onCancel()`.\n\nimport { useCallback } from 'react';\n\nimport { parseColumnInput } from '../../cell-types/column-value';\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { ArrayEditor } from '../../grid/editors/array-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function ArrayEditorDom({ value, column, colKey, onCommit, onCancel }: EditorProps) {\n\tconst initial = Array.isArray(value) ? value : [];\n\tconst validate = useCallback(\n\t\t(next: unknown[]) => {\n\t\t\tif (!column) return null;\n\t\t\tconst parsed = parseColumnInput(column, next);\n\t\t\treturn parsed.ok === false ? parsed.reason : null;\n\t\t},\n\t\t[column],\n\t);\n\treturn (\n\t\t<div data-slot='array-editor'>\n\t\t\t<ArrayEditor\n\t\t\t\tvalue={initial}\n\t\t\t\tonChange={() => {}}\n\t\t\t\tvalidate={validate}\n\t\t\t\ttitle={fieldLabel(column?.name ?? colKey)}\n\t\t\t\tnullable={Boolean(column?.nullable)}\n\t\t\t\tonFinished={(next) => {\n\t\t\t\t\tif (next === undefined) {\n\t\t\t\t\t\tonCancel();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (next === null) {\n\t\t\t\t\t\tonCommit(null);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst parsed = column ? parseColumnInput(column, next) : null;\n\t\t\t\t\tonCommit(parsed?.ok ? parsed.value : next);\n\t\t\t\t}}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { Badge } from '@constructive-io/ui/badge';\nimport { XIcon } from 'lucide-react';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { EditorFooter, EditorHeader, editorClear, modifierKeyLabel } from './editor-frame';\nimport { OVERLAY } from './overlay-presets';\n\n\n// Minimal editor component for scalar arrays using tag chips UI\n// It works with Glide's provideEditor by emitting a Text cell with JSON string\n\ntype Props = {\n\tvalue: unknown[];\n\tonChange: (next: unknown[]) => void;\n\t/** The saved list, null when cleared, or undefined when cancelled. */\n\tonFinished: (next?: unknown[] | null) => void;\n\t/** Check the list before it is saved; return the reason it cannot be saved, or null. */\n\tvalidate?: (next: unknown[]) => string | null;\n\t/** The field's readable name, shown as the title. */\n\ttitle?: string;\n\t/** The column takes no value, so Clear is offered. */\n\tnullable?: boolean;\n};\n\n// One item per line: a comma is part of an item (\"Smith, Jane\"), never a separator.\nfunction parsePendingItems(input: string): string[] {\n\tif (!input) return [];\n\treturn input\n\t\t.split(/\\n/g)\n\t\t.map((token) => token.trim())\n\t\t.filter((token) => token.length > 0);\n}\n\nexport function mergeArrayEditorValues(list: unknown[], pendingInput: string): unknown[] {\n\tconst pendingItems = parsePendingItems(pendingInput);\n\tif (!pendingItems.length) return list;\n\treturn [...list, ...pendingItems];\n}\n\nexport function ArrayEditor({ value, onChange, onFinished, validate, title = 'List', nullable = false }: Props) {\n\tconst items = useMemo(() => (Array.isArray(value) ? value : []), [value]);\n\tconst [list, setList] = useState<unknown[]>(items);\n\tconst [input, setInput] = useState('');\n\tconst [error, setError] = useState<string | null>(null);\n\tconst inputRef = useRef<HTMLInputElement>(null);\n\tconst keyContainerRef = useRef<HTMLDivElement>(null);\n\n\tconst handleCancel = useCallback(() => onFinished(undefined), [onFinished]);\n\tconst handleSave = useCallback(() => {\n\t\tconst next = mergeArrayEditorValues(list, input);\n\t\tsetList(next);\n\t\tsetInput('');\n\t\tconst problem = validate?.(next) ?? null;\n\t\tsetError(problem);\n\t\tif (problem) return;\n\t\tonChange(next);\n\t\tonFinished(next);\n\t}, [input, list, onChange, onFinished, validate]);\n\n\tconst add = useCallback(() => {\n\t\tconst next = mergeArrayEditorValues(list, input);\n\t\tif (next.length === list.length) return;\n\t\tsetList(next);\n\t\tsetInput('');\n\t\tsetError(null);\n\t\tonChange(next);\n\t}, [input, list, onChange]);\n\n\tconst remove = useCallback(\n\t\t(idx: number) => {\n\t\t\tconst next = list.filter((_, i) => i !== idx);\n\t\t\tsetList(next);\n\t\t\tonChange(next);\n\t\t\t// Refocus input after removing a tag\n\t\t\tinputRef.current?.focus();\n\t\t},\n\t\t[list, onChange],\n\t);\n\n\t// Keep refs to latest callbacks/state so the native handler always has fresh values.\n\tconst actionsRef = useRef({ add, handleSave, remove, handleCancel });\n\tactionsRef.current = { add, handleSave, remove, handleCancel };\n\tconst stateRef = useRef({ input, listLength: list.length });\n\tstateRef.current = { input, listLength: list.length };\n\n\t// Native DOM keydown listener on a wrapper div.\n\t// Glide's overlay intercepts Enter/Tab/Escape via React onKeyDown on .gdg-clip-region.\n\t// React's stopPropagation doesn't reliably prevent this in portal contexts.\n\t// A native listener fires before React's root delegation, so we handle keys here\n\t// and stopPropagation to prevent Glide from closing the overlay.\n\tuseEffect(() => {\n\t\tconst el = keyContainerRef.current;\n\t\tif (!el) return;\n\t\tconst handler = (e: KeyboardEvent) => {\n\t\t\tconst { add, handleSave, remove, handleCancel } = actionsRef.current;\n\t\t\tconst { input, listLength } = stateRef.current;\n\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\thandleCancel();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'Backspace' && !input && listLength > 0) {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\tremove(listLength - 1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'Enter' && !e.metaKey && !e.ctrlKey) {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\tadd();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ((e.key === 'Enter' && (e.metaKey || e.ctrlKey)) || (e.key === 's' && (e.metaKey || e.ctrlKey))) {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\thandleSave();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'Tab') {\n\t\t\t\te.stopPropagation();\n\t\t\t}\n\t\t};\n\t\tel.addEventListener('keydown', handler);\n\t\treturn () => el.removeEventListener('keydown', handler);\n\t}, []);\n\n\treturn (\n\t\t<EditorFocusTrap\n\t\t\tonEscape={handleCancel}\n\t\t\tclassName={`bg-popover ${OVERLAY.sm} rounded-lg border p-2.5 shadow-lg`}\n\t\t>\n\t\t\t{/* Key event boundary — native listener prevents Glide from intercepting */}\n\t\t\t<div ref={keyContainerRef} className='flex flex-col gap-2'>\n\t\t\t\t<EditorHeader title={title} className='px-1' />\n\t\t\t\t{/* Unified tag surface — tags and input share one container */}\n\t\t\t\t<div\n\t\t\t\t\tclassName='flex min-h-[2.5rem] cursor-text flex-wrap items-center gap-2 rounded-md px-1 py-1'\n\t\t\t\t\tonClick={() => inputRef.current?.focus()}\n\t\t\t\t>\n\t\t\t\t\t{list.map((item, i) => (\n\t\t\t\t\t\t<Badge\n\t\t\t\t\t\t\tkey={i}\n\t\t\t\t\t\t\tvariant='outline'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tclassName='group/tag !animate-none !transition-none gap-0.5 pe-0.5'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<span className='max-w-[180px] truncate tabular-nums' title={item === null ? 'Empty item' : String(item)}>\n\t\t\t\t\t\t\t\t{item === null ? '(empty)' : String(item)}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\tclassName='text-muted-foreground/60 hover:bg-muted hover:text-foreground -me-px inline-flex size-4 items-center justify-center rounded-xs'\n\t\t\t\t\t\t\t\tonClick={(e) => {\n\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\t\tremove(i);\n\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\taria-label={`Remove ${String(item)}`}\n\t\t\t\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<XIcon className='size-3' />\n\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t</Badge>\n\t\t\t\t\t))}\n\n\t\t\t\t\t<input\n\t\t\t\t\t\tref={inputRef}\n\t\t\t\t\t\tvalue={input}\n\t\t\t\t\t\tonChange={(e) => setInput(e.target.value)}\n\t\t\t\t\t\tplaceholder={list.length === 0 ? 'Type and press Enter...' : 'Add more...'}\n\t\t\t\t\t\tclassName='placeholder:text-muted-foreground/50 min-w-[80px] flex-1 bg-transparent py-0.5 text-sm outline-none'\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\n\t\t\t\t{error ? (\n\t\t\t\t\t<p role='alert' className='text-destructive px-1 text-xs'>\n\t\t\t\t\t\t{error}\n\t\t\t\t\t</p>\n\t\t\t\t) : null}\n\n\t\t\t\t<EditorFooter\n\t\t\t\t\tclassName='px-1'\n\t\t\t\t\tonSave={handleSave}\n\t\t\t\t\tsaveShortcut={`${modifierKeyLabel()} Enter`}\n\t\t\t\t\tclear={editorClear(nullable, () => onFinished(null))}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n}\n","'use client';\n\n// Native date editor — a thin EditorProps adapter that RE-HOSTS the (now value-\n// native) `DateEditor` verbatim. The UI (calendar, time input, footer, OVERLAY.sm\n// width, own EditorFocusTrap) is reused as-is; only the contract is mapped:\n// • initial value — the raw EditorProps.value is read directly by the source.\n// • dateType — narrowed from EditorProps.cell.meta?.cellType via DATE_TIME_TYPES,\n// mirroring the original `createDateEditorFactory` precedence.\n// • commit — `onFinishedEditing(next)` -> `onCommit(next)` (the RAW serialized\n// value; the host builds the cell). `onFinishedEditing(undefined)` -> `onCancel()`.\n//\n// DateEditor stays in its own chunk (it pulls @internationalized/date and\n// react-aria-components). The grid preloads it in idle time when its table has a\n// date or time column (`useDateEditorPreload`), so it is normally ready before the\n// first open. When it is not, the editor waits behind `OverlayPending`: the overlay\n// stays hidden until the editor has rendered, then appears once at its final size and\n// place. A placeholder cannot reserve that size, because the calendar's height depends\n// on how many weeks the month spans.\n\nimport { lazy, Suspense, useState } from 'react';\n\nimport { DATE_TIME_TYPES } from '../../cell-types/cell-type-groups';\nimport { fieldLabel } from '../../cell-types/field-label';\nimport type { DateEditorType } from '../../grid/editors/date-editor';\nimport { OverlayPending } from '../overlay/overlay-pending';\nimport type { EditorProps } from './editor-props';\n\ntype DateEditorModule = typeof import('../../grid/editors/date-editor');\n\nlet loading: Promise<DateEditorModule> | null = null;\nlet loaded: DateEditorModule | null = null;\n\n/** Load the date editor's chunk once. A failed load is retried on the next call. */\nexport function loadDateEditor(): Promise<DateEditorModule> {\n\tloading ??= import('../../grid/editors/date-editor').then(\n\t\t(module) => (loaded = module),\n\t\t(error: unknown) => {\n\t\t\tloading = null;\n\t\t\tthrow error;\n\t\t},\n\t);\n\treturn loading;\n}\n\nconst LazyDateEditor = lazy(() => loadDateEditor().then((module) => ({ default: module.DateEditor })));\n\nexport function DateEditorDom({ value, initialText, cell, column, colKey, onCommit, onCancel }: EditorProps) {\n\tconst cellType = cell.meta?.cellType;\n\tconst dateType: DateEditorType | undefined =\n\t\tcellType && DATE_TIME_TYPES.has(cellType) ? (cellType as DateEditorType) : undefined;\n\t// Chosen once per open: an editor that started behind Suspense keeps that path, so a\n\t// later re-render never remounts it (and never drops what the user typed).\n\tconst [ReadyEditor] = useState(() => loaded?.DateEditor ?? null);\n\tconst editorProps = {\n\t\tvalue,\n\t\tdateType,\n\t\tcanClear: Boolean(column?.nullable),\n\t\ttitle: fieldLabel(column?.name ?? colKey),\n\t\tinitialText,\n\t\tonFinishedEditing: (next?: unknown) => (next === undefined ? onCancel() : onCommit(next)),\n\t};\n\n\treturn (\n\t\t<div data-slot='date-editor'>\n\t\t\t{ReadyEditor ? (\n\t\t\t\t<ReadyEditor {...editorProps} />\n\t\t\t) : (\n\t\t\t\t<Suspense fallback={<OverlayPending />}>\n\t\t\t\t\t<LazyDateEditor {...editorProps} />\n\t\t\t\t</Suspense>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n","'use client';\n\n// A Suspense fallback for an overlay editor whose code is still loading. While it is in\n// the overlay, the OverlayManager keeps the overlay hidden, so the editor appears once,\n// at its final size and place, when its code arrives. It draws nothing itself.\n\n/** Marks an overlay whose editor is not ready to be shown yet. */\nexport const OVERLAY_PENDING_ATTRIBUTE = 'data-overlay-pending';\n\nexport function OverlayPending() {\n\treturn <div {...{ [OVERLAY_PENDING_ATTRIBUTE]: '' }} aria-busy='true' />;\n}\n","import React, { useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { AlertCircle, FileText, Map } from 'lucide-react';\n\nimport { cn } from '../../utils/cn';\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from '@constructive-io/ui/tabs';\nimport { Textarea } from '@constructive-io/ui/textarea';\n\nimport { shapeKindName } from '../../cell-types/shape-kind';\nimport { MapPicker } from '../../utils/map-picker';\nimport { useMapSettings } from '../../utils/map-settings';\nimport { sheetsLogger } from '../../utils/sheets-logger';\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { EditorFooter, EditorHeader, editorClear, modifierKeyLabel } from './editor-frame';\nimport { MapLoadBoundary } from './map-load-boundary';\nimport { OVERLAY } from './overlay-presets';\nimport { OverlayMeasureContext } from './overlay-viewport-guard';\n\n\n// GeoJSON validation according to RFC 7946\nconst VALID_GEOJSON_TYPES = [\n\t'Point',\n\t'LineString',\n\t'Polygon',\n\t'MultiPoint',\n\t'MultiLineString',\n\t'MultiPolygon',\n\t'GeometryCollection',\n];\n\ninterface GeometryType {\n\tgeojson: any; // GeoJSON object\n\tsrid: number; // Integer\n\tx: number; // Float\n\ty: number; // Float\n}\n\ninterface MapPickerValue {\n\tgeojson: {\n\t\ttype: 'Point';\n\t\tcoordinates: [number, number];\n\t};\n\tsrid: number;\n\tx: number;\n\ty: number;\n}\n\nfunction isValidGeoJSON(obj: any): boolean {\n\tif (!obj || typeof obj !== 'object') return false;\n\n\t// Must have a type property\n\tif (!obj.type || typeof obj.type !== 'string') return false;\n\n\t// Feature/FeatureCollection are valid GeoJSON per RFC 7946 but PostGIS\n\t// ST_GeomFromGeoJSON only accepts geometry types — reject them here.\n\tif (obj.type === 'Feature' || obj.type === 'FeatureCollection') return false;\n\n\t// Type must be one of the valid GeoJSON geometry types\n\tif (!VALID_GEOJSON_TYPES.includes(obj.type)) return false;\n\n\t// Structural validation for types with well-defined coordinate shapes.\n\t// Multi* and GeometryCollection are accepted with a type-name check only.\n\tswitch (obj.type) {\n\t\tcase 'Point':\n\t\t\treturn Array.isArray(obj.coordinates) && obj.coordinates.length >= 2;\n\t\tcase 'LineString':\n\t\t\treturn (\n\t\t\t\tArray.isArray(obj.coordinates) &&\n\t\t\t\tobj.coordinates.length >= 2 &&\n\t\t\t\tobj.coordinates.every((coord: any) => Array.isArray(coord) && coord.length >= 2)\n\t\t\t);\n\t\tcase 'Polygon':\n\t\t\treturn (\n\t\t\t\tArray.isArray(obj.coordinates) &&\n\t\t\t\tobj.coordinates.length >= 1 &&\n\t\t\t\tobj.coordinates.every((ring: any) => Array.isArray(ring) && ring.length >= 4)\n\t\t\t);\n\t\tdefault:\n\t\t\treturn true;\n\t}\n}\n\n/** Returns a helpful hint when the GeoJSON type is recognized but unsupported by PostGIS. */\nfunction getGeoJSONHint(obj: any): string | undefined {\n\tif (!obj || typeof obj !== 'object' || typeof obj.type !== 'string') return undefined;\n\tif (obj.type === 'Feature') return 'Feature type is not supported by PostGIS. Extract the geometry property first.';\n\tif (obj.type === 'FeatureCollection') return 'FeatureCollection type is not supported by PostGIS. Extract individual geometries first.';\n\treturn undefined;\n}\n\nfunction isValidGeometry(obj: any): boolean {\n\tif (!obj || typeof obj !== 'object') return false;\n\n\t// Must have all required properties\n\tif (!('geojson' in obj) || !('srid' in obj) || !('x' in obj) || !('y' in obj)) {\n\t\treturn false;\n\t}\n\n\t// Validate geojson\n\tif (!isValidGeoJSON(obj.geojson)) return false;\n\n\t// Validate srid (must be integer)\n\tif (!Number.isInteger(obj.srid)) return false;\n\n\t// Validate x and y (must be finite numbers)\n\tif (!Number.isFinite(obj.x) || !Number.isFinite(obj.y)) return false;\n\n\treturn true;\n}\n\n// Accept wrapped objects which only contain a valid `geojson` property (no srid/x/y)\nfunction isWrappedGeoJSON(obj: any): boolean {\n\tif (!obj || typeof obj !== 'object') return false;\n\tif (!('geojson' in obj)) return false;\n\treturn isValidGeoJSON(obj.geojson);\n}\n\n// Detect bare {x, y} point format (e.g., from GeometryPoint query returning { x, y } subfields)\nfunction isBarePoint(obj: any): obj is { x: number; y: number } {\n\treturn (\n\t\tobj && typeof obj === 'object' &&\n\t\t'x' in obj && 'y' in obj &&\n\t\ttypeof obj.x === 'number' && typeof obj.y === 'number' &&\n\t\t!('type' in obj) && !('geojson' in obj)\n\t);\n}\n\n/** Extract raw GeoJSON geometry from any accepted format, or null if unrecognized. */\nfunction extractRawGeoJSON(obj: any): any | null {\n\tif (isValidGeoJSON(obj)) return obj;\n\tif (obj?.geojson && isValidGeoJSON(obj.geojson)) return obj.geojson;\n\tif (isBarePoint(obj)) return { type: 'Point', coordinates: [obj.x, obj.y] };\n\treturn null;\n}\n\n/** Extract Point coordinates from a GeoJSON geometry, defaulting to (0,0) for non-Point types. */\nfunction extractPointCoords(geojson: any): { x: number; y: number } {\n\tif (geojson?.type === 'Point' && Array.isArray(geojson.coordinates)) {\n\t\treturn { x: Number(geojson.coordinates[0]), y: Number(geojson.coordinates[1]) };\n\t}\n\treturn { x: 0, y: 0 };\n}\n\nfunction validateGeometry(jsonString: string, expectedType?: string): true | string {\n\tif (!jsonString.trim()) return true; // Allow empty\n\n\ttry {\n\t\tconst parsed = JSON.parse(jsonString);\n\n\t\tif (!isValidGeometry(parsed) && !isValidGeoJSON(parsed) && !isWrappedGeoJSON(parsed) && !isBarePoint(parsed)) {\n\t\t\tconst hint = getGeoJSONHint(parsed?.geojson ?? parsed);\n\t\t\tif (hint) return hint;\n\t\t\treturn 'Invalid geometry. Expected GeoJSON (e.g., {\"type\": \"Point\", \"coordinates\": [0, 0]}).';\n\t\t}\n\n\t\t// Validate geometry type matches column constraint\n\t\tif (expectedType) {\n\t\t\tconst geojson = extractRawGeoJSON(parsed) ?? parsed;\n\t\t\tconst actualType = geojson?.type as string | undefined;\n\t\t\tif (actualType && actualType !== expectedType) {\n\t\t\t\treturn `Column expects ${expectedType} but got ${actualType}.`;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t} catch {\n\t\treturn 'Invalid JSON format';\n\t}\n}\n\n// Helper functions for map integration\nfunction isPointGeometry(geometry: GeometryType | null | undefined): boolean {\n\treturn !!(geometry?.geojson?.type === 'Point' && Array.isArray(geometry.geojson.coordinates));\n}\n\nfunction formatGeometry(val: any): string {\n\tif (val == null) return '';\n\ttry {\n\t\tconst obj = typeof val === 'string' ? JSON.parse(val) : val;\n\t\treturn prettyGeoJson(obj);\n\t} catch {\n\t\treturn String(val);\n\t}\n}\n\nfunction parseGeometryValue(value: any): GeometryType | null {\n\tif (!value) return null;\n\n\ttry {\n\t\tconst parsed = typeof value === 'string' ? JSON.parse(value) : value;\n\n\t\tif (isValidGeometry(parsed)) return parsed;\n\n\t\tif (isValidGeoJSON(parsed)) {\n\t\t\treturn { geojson: parsed, srid: 4326, ...extractPointCoords(parsed) };\n\t\t}\n\n\t\tif (isWrappedGeoJSON(parsed)) {\n\t\t\tconst gj = parsed.geojson;\n\t\t\treturn { geojson: gj, srid: Number(parsed.srid) || 4326, ...extractPointCoords(gj) };\n\t\t}\n\n\t\tif (isBarePoint(parsed)) {\n\t\t\tconst geojson = { type: 'Point' as const, coordinates: [parsed.x, parsed.y] };\n\t\t\treturn { geojson, srid: 4326, x: parsed.x, y: parsed.y };\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * GeoJSON text for editing: indented like JSON.stringify(…, null, 2), but each position\n * (an array of numbers) stays on one line, so a polygon reads as one corner per line.\n */\nfunction prettyGeoJson(value: unknown): string {\n\treturn JSON.stringify(value, null, 2).replace(/\\[\\s*(-?[\\d.eE+-]+(?:,\\s*-?[\\d.eE+-]+)*)\\s*\\]/g, (_match, numbers: string) =>\n\t\t`[${numbers.split(/,\\s*/).join(', ')}]`,\n\t);\n}\n\n// Geometry placeholder examples by type\nconst GEOMETRY_PLACEHOLDERS: Record<string, string> = {\n\tPoint: prettyGeoJson({ type: 'Point', coordinates: [0, 0] }),\n\tPolygon: prettyGeoJson({ type: 'Polygon', coordinates: [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]] }),\n\tLineString: prettyGeoJson({ type: 'LineString', coordinates: [[0, 0], [1, 1], [2, 0]] }),\n\tMultiPoint: prettyGeoJson({ type: 'MultiPoint', coordinates: [[0, 0], [1, 1]] }),\n\tMultiPolygon: prettyGeoJson({ type: 'MultiPolygon', coordinates: [[[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]] }),\n\tMultiLineString: prettyGeoJson({ type: 'MultiLineString', coordinates: [[[0, 0], [1, 1]], [[2, 2], [3, 3]]] }),\n};\nconst DEFAULT_GEOMETRY_PLACEHOLDER = GEOMETRY_PLACEHOLDERS.Point;\n\ninterface GeometryEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n\t/** Expected geometry type from column definition (e.g., \"Point\", \"Polygon\", \"LineString\") */\n\texpectedType?: string;\n\t/** The field's readable name, shown as the title. */\n\ttitle?: string;\n\t/** The column takes no value, so Clear is offered. */\n\tnullable?: boolean;\n}\n\n// The Map / GeoJSON switch, sized for this 28px header. The shared tab sizes are for page\n// tabs (a 40px minimum height for touch), so here every tab is 24px inside a 28px track:\n// a 2px inset on all sides, and the tab corners are the track's 8px minus that inset (the\n// shared tab already uses radius-md - 2px). The focus ring is drawn inside the tab so it\n// stays within the track. Icons are 12px with a little less padding on their side.\nconst SWITCH_TRACK = 'h-7 p-0.5';\nconst SWITCH_TAB =\n\t'h-6 min-h-0 min-w-0 gap-1.5 ps-2 pe-2.5 text-xs pointer-coarse:min-h-0 focus-visible:ring-2 focus-visible:ring-inset [&_svg]:size-3';\n\nexport const GeometryEditor: React.FC<GeometryEditorProps> = ({ value, onFinishedEditing, expectedType, title = 'Shape', nullable = false }) => {\n\tconst currentGeometryData = value;\n\tconst geometryValue = useMemo(() => parseGeometryValue(currentGeometryData), [currentGeometryData]);\n\n\tconst [editingValue, setEditingValue] = useState<string>(() => {\n\t\tif (!currentGeometryData) return '';\n\t\t// Normalize to raw GeoJSON — the backend GeoJSON scalar only accepts { type, coordinates }\n\t\tconst geo = parseGeometryValue(currentGeometryData);\n\t\tif (geo?.geojson) return prettyGeoJson(geo.geojson);\n\t\treturn formatGeometry(currentGeometryData);\n\t});\n\n\t// Only show map when we KNOW it's a Point: either expectedType says so, or existing value is a Point.\n\t// For empty cells without expectedType, default to JSON tab (prevents Point-on-Polygon errors).\n\t// A host that turns the map tiles off (SheetsConfig.map.tiles: 'off') gets the GeoJSON text editor.\n\tconst mapSettings = useMapSettings();\n\tconst canShowMap =\n\t\tmapSettings.tiles !== null &&\n\t\t(expectedType === 'Point' || (!expectedType && geometryValue != null && isPointGeometry(geometryValue)));\n\t// The map is optional (leaflet peers): when it cannot load, the shape is edited as GeoJSON text.\n\tconst [mapUnavailable, setMapUnavailable] = useState(false);\n\tconst showMap = canShowMap && !mapUnavailable;\n\n\tconst validationResult = useMemo(() => validateGeometry(editingValue, expectedType), [editingValue, expectedType]);\n\tconst isValid = validationResult === true;\n\tconst validationError = typeof validationResult === 'string' ? validationResult : undefined;\n\tconst [activeTab, setActiveTab] = useState<'map' | 'json'>(() => (canShowMap ? 'map' : 'json'));\n\n\tconst handleMapUnavailable = useCallback((error: unknown) => {\n\t\tsheetsLogger().warn('The map editor could not load; editing the shape as GeoJSON.', error);\n\t\tsetMapUnavailable(true);\n\t\tsetActiveTab('json');\n\t}, []);\n\n\tconst handleMapChange = useCallback((mapValue: MapPickerValue | undefined) => {\n\t\tif (mapValue?.geojson?.type) {\n\t\t\tsetEditingValue(prettyGeoJson(mapValue.geojson));\n\t\t} else {\n\t\t\tsetEditingValue('');\n\t\t}\n\t}, []);\n\n\tconst handleSave = useCallback(() => {\n\t\tif (!isValid) return;\n\n\t\tlet finalValue: string;\n\n\t\tif (!editingValue.trim()) {\n\t\t\tfinalValue = '';\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(editingValue);\n\t\t\t\t// Backend GeoJSON scalar requires { type: \"Point\", ... } at the top level\n\t\t\t\tfinalValue = JSON.stringify(extractRawGeoJSON(parsed) ?? parsed);\n\t\t\t} catch {\n\t\t\t\tfinalValue = editingValue;\n\t\t\t}\n\t\t}\n\n\t\tonFinishedEditing(finalValue);\n\t}, [editingValue, isValid, onFinishedEditing]);\n\n\tconst handleCancel = useCallback(() => {\n\t\tonFinishedEditing();\n\t}, [onFinishedEditing]);\n\n\tconst handleEditorKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent) => {\n\t\t\tif (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {\n\t\t\t\te.preventDefault();\n\t\t\t\tif (isValid) handleSave();\n\t\t\t}\n\t\t},\n\t\t[isValid, handleSave],\n\t);\n\n\tconst mapPickerValue = useMemo(() => {\n\t\ttry {\n\t\t\tif (editingValue) {\n\t\t\t\tconst raw = extractRawGeoJSON(JSON.parse(editingValue));\n\t\t\t\tif (raw) return raw;\n\t\t\t}\n\t\t} catch {\n\t\t\t// fall back to initial value on parse error\n\t\t}\n\t\tif (geometryValue && isPointGeometry(geometryValue)) {\n\t\t\treturn geometryValue.geojson;\n\t\t}\n\t\treturn undefined;\n\t}, [editingValue, geometryValue]);\n\n\t// Viewport-aware scroll budget (same pattern as relation-editor)\n\tconst { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);\n\tconst editorRef = useRef<HTMLDivElement>(null);\n\tconst contentRef = useRef<HTMLDivElement>(null);\n\tconst [scrollBudget, setScrollBudget] = useState<number | undefined>();\n\n\tuseLayoutEffect(() => {\n\t\tconst editor = editorRef.current;\n\t\tconst content = contentRef.current;\n\t\tif (!editor || !content || overlayMaxHeight <= 0) return;\n\t\tconst fixedUI = editor.scrollHeight - content.scrollHeight;\n\t\tsetScrollBudget(Math.max(0, overlayMaxHeight - fixedUI));\n\t}, [overlayMaxHeight]);\n\n\tconst shapeKind = expectedType ? shapeKindName(expectedType) : null;\n\t// Shared header: the field's name and the kind of shape, like the other editors' titles,\n\t// with the Map / GeoJSON switch when the map can be used.\n\tconst header = (\n\t\t<EditorHeader title={title} chip={shapeKind} className='px-3 pt-3 pb-2'>\n\t\t\t{showMap && (\n\t\t\t\t<TabsList className={SWITCH_TRACK}>\n\t\t\t\t\t<TabsTrigger value='map' className={SWITCH_TAB}>\n\t\t\t\t\t\t<Map aria-hidden />\n\t\t\t\t\t\tMap\n\t\t\t\t\t</TabsTrigger>\n\t\t\t\t\t<TabsTrigger value='json' className={SWITCH_TAB}>\n\t\t\t\t\t\t<FileText aria-hidden />\n\t\t\t\t\t\tGeoJSON\n\t\t\t\t\t</TabsTrigger>\n\t\t\t\t</TabsList>\n\t\t\t)}\n\t\t</EditorHeader>\n\t);\n\n\t// Shared JSON content\n\tconst jsonContent = (\n\t\t<div className='space-y-3 p-3'>\n\t\t\t{mapUnavailable ? (\n\t\t\t\t<p role='status' className='text-muted-foreground text-xs'>\n\t\t\t\t\tThe map is not available here. Edit the shape as GeoJSON.\n\t\t\t\t</p>\n\t\t\t) : null}\n\t\t\t<Textarea\n\t\t\t\tid='geometry-json'\n\t\t\t\tvalue={editingValue}\n\t\t\t\tonChange={(e) => setEditingValue(e.target.value)}\n\t\t\t\tclassName={cn('min-h-[200px] resize-none font-mono text-sm', !isValid && 'border-destructive')}\n\t\t\t\tplaceholder={GEOMETRY_PLACEHOLDERS[expectedType ?? ''] ?? DEFAULT_GEOMETRY_PLACEHOLDER}\n\t\t\t\tautoFocus={!showMap || activeTab === 'json'}\n\t\t\t/>\n\n\t\t\t{validationError && (\n\t\t\t\t<div className='text-destructive flex items-center gap-2 text-sm'>\n\t\t\t\t\t<AlertCircle className='h-4 w-4 shrink-0' />\n\t\t\t\t\t{validationError}\n\t\t\t\t</div>\n\t\t\t)}\n\n\t\t</div>\n\t);\n\n\t// Shared footer: Clear (when the column takes no value) and Save, like every value editor.\n\tconst footer = (\n\t\t<EditorFooter\n\t\t\tclassName='px-3 py-2'\n\t\t\tonSave={handleSave}\n\t\t\tsaveShortcut={`${modifierKeyLabel()} Enter`}\n\t\t\tsaveBlockedReason={isValid ? null : (validationError ?? 'Enter a valid GeoJSON shape.')}\n\t\t\tclear={editorClear(nullable, () => onFinishedEditing(null))}\n\t\t/>\n\t);\n\n\treturn (\n\t\t<EditorFocusTrap\n\t\t\tonEscape={handleCancel}\n\t\t\tclassName={`bg-popover flex w-full ${OVERLAY.xl} flex-col overflow-hidden rounded-lg border shadow-lg`}\n\t\t>\n\t\t\t<div ref={editorRef} onKeyDown={handleEditorKeyDown} className='flex min-h-0 flex-1 flex-col'>\n\t\t\t\t{showMap ? (\n\t\t\t\t\t<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'map' | 'json')} className='flex min-h-0 flex-1 flex-col'>\n\t\t\t\t\t\t{header}\n\t\t\t\t\t\t<div ref={contentRef} className='min-h-0 flex-1 overflow-y-auto border-t' style={{ maxHeight: scrollBudget }}>\n\t\t\t\t\t\t\t<TabsContent value='map' className='mt-0 p-3'>\n\t\t\t\t\t\t\t\t<MapLoadBoundary onUnavailable={handleMapUnavailable}>\n\t\t\t\t\t\t\t\t\t{/* The picker's search row, frame and location line render at once; only the map\n\t\t\t\t\t\t\t\t\t itself (Leaflet, loaded on first use) waits, in a placeholder of the map's own\n\t\t\t\t\t\t\t\t\t height, so the editor opens at its final size. */}\n\t\t\t\t\t\t\t\t\t<MapPicker\n\t\t\t\t\t\t\t\t\t\tvalue={mapPickerValue}\n\t\t\t\t\t\t\t\t\t\tonChange={handleMapChange}\n\t\t\t\t\t\t\t\t\t\theight={280}\n\t\t\t\t\t\t\t\t\t\tplaceholder='Search for a location or click on the map...'\n\t\t\t\t\t\t\t\t\t\ttiles={mapSettings.tiles ?? undefined}\n\t\t\t\t\t\t\t\t\t\tplaceSearch={mapSettings.placeSearch}\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t</MapLoadBoundary>\n\t\t\t\t\t\t\t</TabsContent>\n\t\t\t\t\t\t\t<TabsContent value='json' className='mt-0'>\n\t\t\t\t\t\t\t\t{jsonContent}\n\t\t\t\t\t\t\t</TabsContent>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{footer}\n\t\t\t\t\t</Tabs>\n\t\t\t\t) : (\n\t\t\t\t\t<>\n\t\t\t\t\t\t{header}\n\t\t\t\t\t\t<div ref={contentRef} className='min-h-0 flex-1 overflow-y-auto border-t' style={{ maxHeight: scrollBudget }}>\n\t\t\t\t\t\t\t{jsonContent}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t{footer}\n\t\t\t\t\t</>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","'use client';\n\nimport React, { lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react';\nimport type { LeafletMouseEvent } from 'leaflet';\nimport { MapPinIcon, SearchIcon, XIcon, Loader2 } from 'lucide-react';\n\nimport { cn } from './cn';\nimport { moduleExports } from './module-interop';\nimport { DEFAULT_MAP_TILES, DEFAULT_PLACE_SEARCH, type MapSettings, type SheetsMapPlaceSearch } from './map-settings';\nimport { sheetsLogger } from './sheets-logger';\nimport { Button } from '@constructive-io/ui/button';\nimport { Card, CardContent } from '@constructive-io/ui/card';\nimport { InputGroup, InputGroupAddon, InputGroupInput } from '@constructive-io/ui/input-group';\n\n// TypeScript interfaces\ninterface GeoJSONPoint {\n\ttype: 'Point';\n\tcoordinates: [number, number]; // [longitude, latitude]\n}\n\ninterface MapPickerValue {\n\tgeojson: GeoJSONPoint;\n\tsrid: number;\n\tx: number;\n\ty: number;\n}\n\ntype MapTiles = NonNullable<MapSettings['tiles']>;\n\ninterface MapPickerProps {\n\tvalue?: MapPickerValue | GeoJSONPoint | any;\n\tonChange?: (value: MapPickerValue | undefined) => void;\n\tclassName?: string;\n\tplaceholder?: string;\n\tdisabled?: boolean;\n\theight?: number;\n\tmarkerColor?: string;\n\t/** Where the map tiles come from (`SheetsConfig.map.tiles`). Default: OpenStreetMap. */\n\ttiles?: MapTiles;\n\t/** The place search endpoint, or null for no search box (`SheetsConfig.map.placeSearch`). */\n\tplaceSearch?: SheetsMapPlaceSearch | null;\n}\n\ninterface SearchResult {\n\tdisplay_name: string;\n\tlat: string;\n\tlon: string;\n\tplace_id: string;\n}\n\n// Utility functions\nconst createMapValue = (lat: number, lng: number): MapPickerValue => ({\n\tgeojson: {\n\t\ttype: 'Point',\n\t\tcoordinates: [lng, lat],\n\t},\n\tsrid: 4326,\n\tx: lng,\n\ty: lat,\n});\n\nconst extractPosition = (value: any): [number, number] | null => {\n\tif (!value) return null;\n\n\tlet coordinates: [number, number] | undefined;\n\n\tif (value.type === 'Point' && Array.isArray(value.coordinates)) {\n\t\tcoordinates = value.coordinates;\n\t} else if (value.geojson?.type === 'Point' && Array.isArray(value.geojson.coordinates)) {\n\t\tcoordinates = value.geojson.coordinates;\n\t}\n\n\tif (!coordinates || coordinates.length < 2) return null;\n\n\tconst [lng, lat] = coordinates;\n\n\tif (typeof lng !== 'number' || typeof lat !== 'number') return null;\n\tif (!isFinite(lng) || !isFinite(lat)) return null;\n\n\treturn [lat, lng];\n};\n\n/** Ask the place search endpoint (Nominatim's `/search` form) for up to five places. */\nconst searchLocation = async (endpoint: string, query: string): Promise<SearchResult[]> => {\n\tif (!query.trim()) return [];\n\n\ttry {\n\t\tconst url = new URL(endpoint);\n\t\turl.searchParams.set('format', 'json');\n\t\turl.searchParams.set('q', query);\n\t\turl.searchParams.set('limit', '5');\n\t\turl.searchParams.set('addressdetails', '1');\n\t\tconst response = await fetch(url.toString());\n\t\tconst results = await response.json();\n\t\treturn results || [];\n\t} catch (error) {\n\t\tsheetsLogger().error('Search error:', error);\n\t\treturn [];\n\t}\n};\n\n/**\n * Inner map component that uses react-leaflet.\n * Lazy-loaded to avoid bundling ~270KB Leaflet in main chunk.\n */\nconst LeafletMapInner = lazy(() =>\n\tPromise.all([import('react-leaflet'), import('leaflet')]).then(([reactLeafletModule, leafletModule]) => {\n\t\t// Leaflet is UMD-only, so a bundler may hand back `{ default: L }`; read both through the same boundary.\n\t\tconst reactLeaflet = moduleExports(reactLeafletModule);\n\t\tconst L = moduleExports(leafletModule);\n\t\tconst { MapContainer, TileLayer, Marker, useMapEvents, useMap } = reactLeaflet;\n\n\t\tconst createCustomIcon = (color: string = '#3b82f6') => {\n\t\t\treturn L.divIcon({\n\t\t\t\thtml: `\n\t\t\t\t\t<div style=\"\n\t\t\t\t\t\twidth: 32px;\n\t\t\t\t\t\theight: 32px;\n\t\t\t\t\t\tdisplay: flex;\n\t\t\t\t\t\talign-items: center;\n\t\t\t\t\t\tjustify-content: center;\n\t\t\t\t\t\tbackground: ${color};\n\t\t\t\t\t\tborder: 3px solid white;\n\t\t\t\t\t\tborder-radius: 50% 50% 50% 0;\n\t\t\t\t\t\ttransform: rotate(-45deg);\n\t\t\t\t\t\tbox-shadow: 0 2px 8px rgba(0,0,0,0.3);\n\t\t\t\t\t\">\n\t\t\t\t\t\t<svg width=\"16\" height=\"16\" viewBox=\"0 0 24 24\" fill=\"white\" style=\"transform: rotate(45deg);\">\n\t\t\t\t\t\t\t<path d=\"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z\"/>\n\t\t\t\t\t\t</svg>\n\t\t\t\t\t</div>\n\t\t\t\t`,\n\t\t\t\tclassName: 'custom-marker',\n\t\t\t\ticonSize: [32, 32],\n\t\t\t\ticonAnchor: [16, 32],\n\t\t\t\tpopupAnchor: [0, -32],\n\t\t\t});\n\t\t};\n\n\t\tfunction MapEventHandler({\n\t\t\tonMapClick,\n\t\t\tposition,\n\t\t}: {\n\t\t\tonMapClick: (lat: number, lng: number) => void;\n\t\t\tposition: [number, number] | null;\n\t\t}): React.ReactElement | null {\n\t\t\tconst map = useMap();\n\n\t\t\tuseMapEvents({\n\t\t\t\tclick(e: LeafletMouseEvent) {\n\t\t\t\t\tonMapClick(e.latlng.lat, e.latlng.lng);\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tReact.useEffect(() => {\n\t\t\t\tif (position && map) {\n\t\t\t\t\tmap.setView(position, 15);\n\t\t\t\t}\n\t\t\t}, [position, map]);\n\n\t\t\treturn null;\n\t\t}\n\n\t\tfunction LeafletMap({\n\t\t\tposition,\n\t\t\tonMapClick,\n\t\t\tdisabled,\n\t\t\theight,\n\t\t\tmarkerColor,\n\t\t\ttiles,\n\t\t}: {\n\t\t\ttiles: MapTiles;\n\t\t\tposition: [number, number] | null;\n\t\t\tonMapClick: (lat: number, lng: number) => void;\n\t\t\tdisabled: boolean;\n\t\t\theight: number;\n\t\t\tmarkerColor: string;\n\t\t}) {\n\t\t\tconst defaultCenter: [number, number] = [40.7128, -74.006];\n\n\t\t\treturn (\n\t\t\t\t<div style={{ height: `${height}px` }} className='relative'>\n\t\t\t\t\t<MapContainer\n\t\t\t\t\t\tcenter={position || defaultCenter}\n\t\t\t\t\t\tzoom={position ? 15 : 10}\n\t\t\t\t\t\tstyle={{ height: '100%', width: '100%' }}\n\t\t\t\t\t\tclassName={cn('z-0', disabled && 'pointer-events-none opacity-64')}\n\t\t\t\t\t>\n\t\t\t\t\t\t<TileLayer\n\t\t\t\t\t\t\tattribution={tiles.attribution}\n\t\t\t\t\t\t\turl={tiles.url}\n\t\t\t\t\t\t\t{...(tiles.subdomains ? { subdomains: tiles.subdomains } : {})}\n\t\t\t\t\t\t/>\n\n\t\t\t\t\t\t{position && <Marker position={position} icon={createCustomIcon(markerColor)} />}\n\n\t\t\t\t\t\t<MapEventHandler onMapClick={onMapClick} position={position} />\n\t\t\t\t\t</MapContainer>\n\n\t\t\t\t\t{disabled && <div className='bg-background/50 absolute inset-0 z-10' />}\n\t\t\t\t</div>\n\t\t\t);\n\t\t}\n\n\t\treturn { default: LeafletMap };\n\t})\n);\n\nfunction MapLoading({ height }: { height: number }) {\n\treturn (\n\t\t<div style={{ height: `${height}px` }} className='bg-muted flex items-center justify-center rounded-lg border'>\n\t\t\t<Loader2 className='h-6 w-6 animate-spin text-muted-foreground' />\n\t\t</div>\n\t);\n}\n\nexport function MapPicker({\n\tvalue,\n\tonChange,\n\tclassName,\n\tplaceholder = 'Search for a location...',\n\tdisabled = false,\n\theight = 300,\n\tmarkerColor = '#3b82f6',\n\ttiles = DEFAULT_MAP_TILES,\n\tplaceSearch = DEFAULT_PLACE_SEARCH,\n}: MapPickerProps) {\n\tconst [searchQuery, setSearchQuery] = useState('');\n\tconst [searchResults, setSearchResults] = useState<SearchResult[]>([]);\n\tconst [isSearching, setIsSearching] = useState(false);\n\tconst [showResults, setShowResults] = useState(false);\n\tconst searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n\tconst position = extractPosition(value);\n\n\tconst handleMapClick = useCallback(\n\t\t(lat: number, lng: number) => {\n\t\t\tif (disabled) return;\n\t\t\tconst newValue = createMapValue(lat, lng);\n\t\t\tonChange?.(newValue);\n\t\t\tsetSearchQuery('');\n\t\t\tsetShowResults(false);\n\t\t},\n\t\t[disabled, onChange],\n\t);\n\n\tconst handleSearchChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n\t\tconst query = e.target.value;\n\t\tsetSearchQuery(query);\n\n\t\tif (searchTimeoutRef.current) {\n\t\t\tclearTimeout(searchTimeoutRef.current);\n\t\t}\n\n\t\tsearchTimeoutRef.current = setTimeout(async () => {\n\t\t\tif (!placeSearch) return;\n\t\t\tif (query.trim()) {\n\t\t\t\tsetIsSearching(true);\n\t\t\t\tsetShowResults(true);\n\t\t\t\tconst results = await searchLocation(placeSearch.url, query);\n\t\t\t\tsetSearchResults(results);\n\t\t\t\tsetIsSearching(false);\n\t\t\t} else {\n\t\t\t\tsetShowResults(false);\n\t\t\t\tsetSearchResults([]);\n\t\t\t}\n\t\t}, 300);\n\t}, [placeSearch]);\n\n\tconst handleResultSelect = useCallback(\n\t\t(result: SearchResult) => {\n\t\t\tif (disabled) return;\n\t\t\tconst lat = parseFloat(result.lat);\n\t\t\tconst lng = parseFloat(result.lon);\n\t\t\tconst newValue = createMapValue(lat, lng);\n\t\t\tonChange?.(newValue);\n\t\t\tsetSearchQuery(result.display_name);\n\t\t\tsetShowResults(false);\n\t\t},\n\t\t[disabled, onChange],\n\t);\n\n\tconst clearSearch = useCallback(() => {\n\t\tsetSearchQuery('');\n\t\tsetShowResults(false);\n\t\tsetSearchResults([]);\n\t}, []);\n\n\tconst clearLocation = useCallback(() => {\n\t\tif (disabled) return;\n\t\tonChange?.(undefined);\n\t\tsetSearchQuery('');\n\t}, [disabled, onChange]);\n\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tif (searchTimeoutRef.current) {\n\t\t\t\tclearTimeout(searchTimeoutRef.current);\n\t\t\t}\n\t\t};\n\t}, []);\n\n\treturn (\n\t\t<div className={cn('relative w-full', className)}>\n\t\t\t{/* Search Input (only with a place search; SheetsConfig.map.placeSearch can turn it off) */}\n\t\t\t{placeSearch ? (\n\t\t\t\t<div className='relative mb-2'>\n\t\t\t\t\t<InputGroup>\n\t\t\t\t\t\t<InputGroupAddon>\n\t\t\t\t\t\t\t<SearchIcon />\n\t\t\t\t\t\t</InputGroupAddon>\n\t\t\t\t\t\t<InputGroupInput\n\t\t\t\t\t\t\ttype='text'\n\t\t\t\t\t\t\tplaceholder={placeholder}\n\t\t\t\t\t\t\tvalue={searchQuery}\n\t\t\t\t\t\t\tonChange={handleSearchChange}\n\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t<InputGroupAddon align='inline-end'>\n\t\t\t\t\t\t\t{searchQuery && (\n\t\t\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\t\t\tonClick={clearSearch}\n\t\t\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t\t\t\tclassName='h-7 w-7 p-0'\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<XIcon className='h-3 w-3' />\n\t\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{position && (\n\t\t\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\t\t\tonClick={clearLocation}\n\t\t\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t\t\t\tclassName='h-7 w-7 p-0'\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<MapPinIcon className='h-3 w-3' />\n\t\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t</InputGroupAddon>\n\t\t\t\t\t</InputGroup>\n\n\t\t\t\t\t{/* Search Results */}\n\t\t\t\t\t{showResults && (\n\t\t\t\t\t\t<Card className='absolute top-full right-0 left-0 z-50 mt-1 max-h-60 overflow-y-auto'>\n\t\t\t\t\t\t\t<CardContent className='p-0'>\n\t\t\t\t\t\t\t\t{isSearching && <div className='text-muted-foreground px-3 py-2 text-sm'>Searching...</div>}\n\t\t\t\t\t\t\t\t{!isSearching && searchResults.length === 0 && searchQuery && (\n\t\t\t\t\t\t\t\t\t<div className='text-muted-foreground px-3 py-2 text-sm'>No results found</div>\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t{!isSearching &&\n\t\t\t\t\t\t\t\t\tsearchResults.map((result) => (\n\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\tkey={result.place_id}\n\t\t\t\t\t\t\t\t\t\t\tonClick={() => handleResultSelect(result)}\n\t\t\t\t\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t\t\t\t\t\tclassName='hover:bg-accent hover:text-accent-foreground w-full px-3 py-2 text-left text-sm\n\t\t\t\t\t\t\t\t\t\t\t\tdisabled:cursor-not-allowed disabled:opacity-64'\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{result.display_name}\n\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t</CardContent>\n\t\t\t\t\t\t</Card>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t) : null}\n\n\t\t\t{/* Map Container: the map fills the frame (no card padding bands above and below it). */}\n\t\t\t<Card className='overflow-hidden py-0'>\n\t\t\t\t<CardContent className='p-0'>\n\t\t\t\t\t<Suspense fallback={<MapLoading height={height} />}>\n\t\t\t\t\t\t<LeafletMapInner\n\t\t\t\t\t\t\ttiles={tiles}\n\t\t\t\t\t\t\tposition={position}\n\t\t\t\t\t\t\tonMapClick={handleMapClick}\n\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t\theight={height}\n\t\t\t\t\t\t\tmarkerColor={markerColor}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</Suspense>\n\t\t\t\t</CardContent>\n\t\t\t</Card>\n\n\t\t\t{/* Current Location Info */}\n\t\t\t{position && (\n\t\t\t\t<div className='text-muted-foreground mt-2 text-xs'>\n\t\t\t\t\t<div className='flex items-center gap-1'>\n\t\t\t\t\t\t<MapPinIcon className='h-3 w-3' />\n\t\t\t\t\t\t<span>\n\t\t\t\t\t\t\tLatitude: {position[0].toFixed(6)}, Longitude: {position[1].toFixed(6)}\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t)}\n\t\t</div>\n\t);\n}\n","/**\n * The real exports of a dynamically imported package, whatever shape the bundler\n * gives it. A CommonJS or UMD package (leaflet 1.9 ships only a UMD `main`) can\n * arrive as a namespace whose only member is `default`; an ES module arrives with\n * its named exports. A namespace that has named exports is used as it is, even when\n * it also has a default export.\n */\nexport function moduleExports<T extends object>(namespace: T): T {\n\tconst named = Object.keys(namespace).filter((key) => key !== 'default' && key !== '__esModule');\n\tif (named.length > 0) return namespace;\n\tconst inner: unknown = (namespace as { default?: unknown }).default;\n\tif ((typeof inner === 'object' && inner !== null) || typeof inner === 'function') return inner as T;\n\treturn namespace;\n}\n","// Where the geometry editor's map gets its tiles and its place search, from\n// `SheetsConfig.map`. The defaults are OpenStreetMap's public tile server and its\n// Nominatim search, as before. A host can point either at its own service, or turn it\n// off: with no tiles, shapes are edited as GeoJSON text; with no place search, the map\n// has no search box.\n//\n// Content security: the browser loads tile images from the tile URL's host (`img-src`)\n// and calls the place search with fetch (`connect-src`). A host with a\n// Content-Security-Policy must allow both, or turn them off.\n\nimport { useContext, useMemo } from 'react';\n\nimport { SheetsContext } from '../context/sheets-context';\nimport { sheetsLogger } from './sheets-logger';\n\n/** Map tiles: an `https` URL template with `{z}`, `{x}` and `{y}` (and `{s}` for subdomains), and the attribution the provider requires. */\nexport interface SheetsMapTiles {\n\turl: string;\n\t/** Attribution HTML shown on the map, as the tile provider requires. It is host-supplied, trusted markup. */\n\tattribution: string;\n\t/** Letters for `{s}` in the URL (default \"abc\"). */\n\tsubdomains?: string;\n}\n\n/** Place search: an endpoint that answers like Nominatim's `/search` (`format=json`: `display_name`, `lat`, `lon`, `place_id`). */\nexport interface SheetsMapPlaceSearch {\n\turl: string;\n}\n\nexport interface SheetsMapConfig {\n\t/** Map tiles, or `'off'` to edit shapes as GeoJSON text only. Default: OpenStreetMap. */\n\ttiles?: SheetsMapTiles | 'off';\n\t/** Place search for the map's search box, or `'off'` for no search box. Default: OpenStreetMap Nominatim. */\n\tplaceSearch?: SheetsMapPlaceSearch | 'off';\n}\n\nexport interface MapSettings {\n\t/** Null: no map; shapes are edited as GeoJSON text. */\n\ttiles: Required<Pick<SheetsMapTiles, 'url' | 'attribution'>> & Pick<SheetsMapTiles, 'subdomains'> | null;\n\t/** Null: no search box. */\n\tplaceSearch: SheetsMapPlaceSearch | null;\n}\n\nexport const DEFAULT_MAP_TILES: SheetsMapTiles = {\n\turl: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',\n\tattribution: '© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors',\n};\n\nexport const DEFAULT_PLACE_SEARCH: SheetsMapPlaceSearch = { url: 'https://nominatim.openstreetmap.org/search' };\n\nconst HTTP_URL_RE = /^https?:\\/\\/[^\\s]+$/i;\n\nfunction tilesFrom(tiles: SheetsMapConfig['tiles']): MapSettings['tiles'] {\n\tif (tiles === 'off') return null;\n\tif (tiles === undefined) return DEFAULT_MAP_TILES;\n\tconst usable =\n\t\ttypeof tiles.url === 'string' && HTTP_URL_RE.test(tiles.url) && ['{z}', '{x}', '{y}'].every((part) => tiles.url.includes(part));\n\tif (!usable) {\n\t\t// A broken template would show an empty map; GeoJSON text still edits the shape.\n\t\tsheetsLogger().warn('SheetsConfig.map.tiles needs an http(s) URL template with {z}, {x} and {y}; the map is turned off.', tiles);\n\t\treturn null;\n\t}\n\treturn { url: tiles.url, attribution: typeof tiles.attribution === 'string' ? tiles.attribution : '', subdomains: tiles.subdomains };\n}\n\nfunction placeSearchFrom(search: SheetsMapConfig['placeSearch']): MapSettings['placeSearch'] {\n\tif (search === 'off') return null;\n\tif (search === undefined) return DEFAULT_PLACE_SEARCH;\n\tif (typeof search.url !== 'string' || !HTTP_URL_RE.test(search.url)) {\n\t\tsheetsLogger().warn('SheetsConfig.map.placeSearch needs an http(s) URL; the search box is turned off.', search);\n\t\treturn null;\n\t}\n\treturn { url: search.url };\n}\n\n/** The map settings for a `SheetsConfig.map` value. A setting that is not usable is turned off, never sent to a default service. */\nexport function resolveMapSettings(config: SheetsMapConfig | undefined): MapSettings {\n\treturn { tiles: tilesFrom(config?.tiles), placeSearch: placeSearchFrom(config?.placeSearch) };\n}\n\n/** The map settings of the nearest Sheets provider (the defaults outside one). */\nexport function useMapSettings(): MapSettings {\n\tconst map = useContext(SheetsContext)?.config.map;\n\treturn useMemo(() => resolveMapSettings(map), [map]);\n}\n","'use client';\n\n// Catches a map that cannot load (the optional `leaflet` / `react-leaflet` peers are\n// not installed, or their import or first render fails) so the geometry editor can\n// switch to GeoJSON text instead of failing as a whole.\n\nimport React from 'react';\n\ninterface MapLoadBoundaryProps {\n\t/** The map could not load; the editor falls back to text. */\n\tonUnavailable: (error: unknown) => void;\n\tchildren: React.ReactNode;\n}\n\ninterface MapLoadBoundaryState {\n\tfailed: boolean;\n}\n\nexport class MapLoadBoundary extends React.Component<MapLoadBoundaryProps, MapLoadBoundaryState> {\n\tstate: MapLoadBoundaryState = { failed: false };\n\n\tstatic getDerivedStateFromError(): MapLoadBoundaryState {\n\t\treturn { failed: true };\n\t}\n\n\tcomponentDidCatch(error: unknown): void {\n\t\tthis.props.onUnavailable(error);\n\t}\n\n\trender(): React.ReactNode {\n\t\treturn this.state.failed ? null : this.props.children;\n\t}\n}\n","'use client';\n\n// Native geometry editor — a thin EditorProps adapter that RE-HOSTS the (now value-\n// native) `GeometryEditor` verbatim. The UI (map/JSON tabs, randomizer, OVERLAY.xl\n// width, own EditorFocusTrap, internally-lazy MapPicker) is reused as-is; the contract\n// maps directly to value-native EditorProps:\n// • value (raw geojson string or object) -> read directly by the source.\n// • expectedType <- EditorProps.column.value.geometrySubtype (the declared shape).\n// • onFinishedEditing(next) -> onCommit(next) (raw geojson string; host builds the\n// cell), onFinishedEditing(undefined) -> onCancel().\n// Leaflet loads on first use inside the map picker, behind a placeholder of the map's own\n// height, so the editor needs no loading state of its own. Escape is handled by the\n// reused editor's EditorFocusTrap -> handleCancel -> onFinishedEditing(undefined).\n\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { GeometryEditor } from '../../grid/editors/geometry-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function GeometryEditorDom({ value, column, colKey, fieldMeta, onCommit, onCancel }: EditorProps) {\n\t// The declared shape (Point, Polygon, ...) from the table model; raw metadata only without a model.\n\tconst expectedType = column?.value.geometrySubtype || fieldMeta?.type?.subtype || undefined;\n\treturn (\n\t\t<div data-slot='geometry-editor'>\n\t\t\t<GeometryEditor\n\t\t\t\tvalue={value}\n\t\t\t\texpectedType={expectedType}\n\t\t\t\ttitle={fieldLabel(column?.name ?? colKey)}\n\t\t\t\tnullable={Boolean(column?.nullable)}\n\t\t\t\tonFinishedEditing={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","'use client';\n\n// Native file editor: a thin EditorProps adapter over the self-committing\n// `ImageEditor` (image, upload, upload lists, attachment links). The contract\n// maps onto EditorProps:\n// • value -> the raw row value, read directly by the editor.\n// • column / table -> the table model (kind, list or single, write rules).\n// • recordId -> typed EditorProps.rowIdentifier; rowId keys the cell's pending state.\n// • isDraftRow -> no server identity and a draft rowId.\n// • onSaveComplete -> onCommitPatch({ [colKey]: saveData.imageData }) (single field).\n// • onSubmitDraft -> onSubmitDraftRow(draftRowId).\n// • onDraftUploadComplete -> onInvalidateData.\n// • onFinishedEditing(next?) -> onCancel() (a CLOSE; the editor self-commits).\n// Suspense is preserved (the source editor is lazy-loaded under <Suspense fallback={null}>).\n\nimport { Suspense } from 'react';\n\nimport { ImageEditor, type ImageSaveData } from '../../grid/editors/image-editor';\nimport type { EditorProps } from './editor-props';\n\nconst DRAFT_PREFIX = 'draft:';\n\nexport function ImageEditorDom({\n\tvalue,\n\tcell,\n\tcolKey,\n\trowId,\n\trowIdentifier,\n\ttableName,\n\tcolumn,\n\ttable,\n\treadOnlyReason,\n\tonCommitPatch,\n\tonCancel,\n\tonSubmitDraftRow,\n\tonInvalidateData,\n}: EditorProps) {\n\tconst isDraftRow = rowIdentifier == null && rowId.startsWith(DRAFT_PREFIX);\n\t// Without a column model, only the `image` cell type is image-only; every other\n\t// media type accepts any file. A missing cellType defaults to image-only.\n\tconst cellType = cell.meta?.cellType;\n\tconst acceptAnyFile = cellType != null && cellType !== 'image';\n\n\t// Self-commit: the editor uploads and writes the cell, then hands back the saved\n\t// value as a single-field optimistic patch.\n\tconst handleSaveComplete = onCommitPatch\n\t\t? (saveData: ImageSaveData) => onCommitPatch({ [colKey]: saveData.imageData })\n\t\t: undefined;\n\n\tconst handleSubmitDraft = isDraftRow && onSubmitDraftRow\n\t\t? () => onSubmitDraftRow(rowId)\n\t\t: undefined;\n\n\treturn (\n\t\t<div data-slot=\"image-editor\">\n\t\t\t<Suspense fallback={<div className='h-64 w-full min-w-[480px] animate-pulse rounded-lg bg-muted' />}>\n\t\t\t\t<ImageEditor\n\t\t\t\t\tvalue={value}\n\t\t\t\t\tacceptAnyFile={acceptAnyFile}\n\t\t\t\t\tonFinishedEditing={() => onCancel()}\n\t\t\t\t\ttableName={tableName}\n\t\t\t\t\tfieldName={colKey}\n\t\t\t\t\trecordId={rowIdentifier ?? null}\n\t\t\t\t\trowId={rowId}\n\t\t\t\t\tcolumn={column ?? null}\n\t\t\t\t\ttable={table ?? null}\n\t\t\t\t\treadOnlyReason={readOnlyReason ?? null}\n\t\t\t\t\tonSaveComplete={handleSaveComplete}\n\t\t\t\t\tisDraftRow={isDraftRow}\n\t\t\t\t\tonSubmitDraft={handleSubmitDraft}\n\t\t\t\t\tonDraftUploadComplete={onInvalidateData}\n\t\t\t\t/>\n\t\t\t</Suspense>\n\t\t</div>\n\t);\n}\n","// The file editor for image, upload, upload-list and attachment cells.\n//\n// It reads the column from the table model (`column.value.file`: kind and\n// whether the cell holds several files) and saves through the model-driven\n// upload path: pick, drop or paste files; replace or remove them; reorder a\n// list; open or download a stored file; watch each upload and cancel it. A\n// draft row is created first. The cell write waits out the server's file\n// confirmation and, if the editor closes, keeps going on the cell.\n//\n// State and the save sequence live in `uploads/editor/use-file-editor.ts`.\n\nimport React, { useCallback, useContext, useMemo, useRef } from 'react';\nimport { Loader2, LockIcon } from 'lucide-react';\nimport { Button } from '@constructive-io/ui/button';\nimport { toast } from '@constructive-io/ui/toast';\n\nimport type { ColumnModel, TableModel } from '@constructive-io/data';\n\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { useTableModel } from '../../hooks/use-table-model';\nimport {\n\tfileWriteReason,\n\trowKeyOfRow,\n\tuseColumnMediaResolver,\n\tuseFileCellWriter,\n\tuseFileUploadState,\n\ttype UploadResponse,\n} from '../../hooks/use-sheets-upload';\nimport { sheetsRowKey, type SheetsRowIdentifier } from '../../row-identity';\nimport { FileDropzone } from '../../uploads/editor/file-dropzone';\nimport { FileEntryRow } from '../../uploads/editor/file-entry-row';\nimport { ADD_CONTROL, CLOSE_CONTROL, useEditorFocus } from '../../uploads/editor/use-editor-focus';\nimport { useFileEditor, type FileEditorPhase, type SaveTarget } from '../../uploads/editor/use-file-editor';\nimport { useOptionalFeedback } from '../feedback/feedback-context';\nimport { EditorHeader, modifierKeyLabel } from './editor-frame';\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\nimport { OverlayMeasureContext } from './overlay-viewport-guard';\nimport type { DraftSubmitResult } from '../draft-types';\n\n/** Data passed to onSaveComplete for the optimistic cell update. */\nexport interface ImageSaveData {\n\timageData: UploadResponse;\n}\n\ninterface ImageEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n\ttableName?: string;\n\tfieldName?: string;\n\trecordId?: SheetsRowIdentifier | null;\n\t/** Grid row id of the cell (keys its pending state). Defaults to the record id. */\n\trowId?: string;\n\tonSaveComplete?: (data: ImageSaveData) => void;\n\tisDraftRow?: boolean;\n\tonSubmitDraft?: () => Promise<DraftSubmitResult>;\n\tonDraftUploadComplete?: () => void;\n\t/** Without a column model: accept any file (true) or images only (false). */\n\tacceptAnyFile?: boolean;\n\t/** The column model; resolved from `tableName` and `fieldName` when absent. */\n\tcolumn?: ColumnModel | null;\n\t/** The table model; resolved from `tableName` when absent. */\n\ttable?: TableModel | null;\n\t/** Why the cell cannot be written, from the grid; null when it can. */\n\treadOnlyReason?: string | null;\n}\n\nfunction phaseText(phase: FileEditorPhase, noun: string): string | null {\n\tswitch (phase.name) {\n\t\tcase 'creating-row': return 'Creating row…';\n\t\tcase 'uploading': return `Uploading ${noun}…`;\n\t\tcase 'saving': return 'Saving…';\n\t\tcase 'processing': return 'Processing file… The cell is saved as soon as the storage service accepts the file. You can close this.';\n\t\tcase 'failed': return phase.message;\n\t\tdefault: return null;\n\t}\n}\n\nexport const ImageEditor: React.FC<ImageEditorProps> = ({\n\tvalue,\n\tonFinishedEditing,\n\ttableName,\n\tfieldName,\n\trecordId,\n\trowId,\n\tonSaveComplete,\n\tisDraftRow = false,\n\tonSubmitDraft,\n\tonDraftUploadComplete,\n\tacceptAnyFile = false,\n\tcolumn: columnProp,\n\ttable: tableProp,\n\treadOnlyReason,\n}) => {\n\tconst { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);\n\tconst inputRef = useRef<HTMLInputElement>(null);\n\tconst editorRef = useRef<HTMLDivElement>(null);\n\n\tconst resolved = useTableModel(tableName ?? null);\n\tconst table = tableProp ?? resolved.model;\n\tconst column = columnProp ?? table?.columns.find((candidate) => candidate.name === fieldName) ?? null;\n\tconst fileModel = column?.value.file ?? null;\n\tconst kind = fileModel?.kind ?? (acceptAnyFile ? 'upload' : 'image');\n\tconst multiple = Boolean(fileModel?.multiple);\n\tconst noun = multiple ? 'files' : kind === 'image' ? 'image' : 'file';\n\tconst Noun = kind === 'attachment' ? 'Link' : multiple ? 'Files' : kind === 'image' ? 'Image' : 'File';\n\t// The shared frame's title: the field's readable name (the raw name in the tooltip), the kind as its chip.\n\tconst rawName = column?.name ?? fieldName ?? '';\n\n\tconst writeReason = readOnlyReason ?? fileWriteReason(table, column);\n\tconst upload = useFileUploadState(table, column, writeReason);\n\tconst media = useColumnMediaResolver(table, column);\n\tconst write = useFileCellWriter();\n\n\tconst target = useMemo<SaveTarget | null>(\n\t\t() => (recordId != null && !isDraftRow ? { rowKey: recordId, rowId: rowId ?? String(recordId) } : null),\n\t\t[isDraftRow, recordId, rowId],\n\t);\n\tconst metaTable = resolved.metaTable;\n\tconst targetOfCreatedRow = useCallback((row: Record<string, unknown>): SaveTarget | null => {\n\t\tif (!table) return null;\n\t\tconst rowKey = rowKeyOfRow(table, row);\n\t\tif (rowKey == null) return null;\n\t\treturn { rowKey, rowId: metaTable ? sheetsRowKey(metaTable, row, 0) : typeof rowKey === 'object' ? JSON.stringify(rowKey) : String(rowKey) };\n\t}, [metaTable, table]);\n\n\t// The grid's save status reports the save once the editor closes; outside a grid, a toast does.\n\tconst noteWrite = useOptionalFeedback()?.noteWrite;\n\tconst onSaved = useCallback((saved: unknown, info: { createdRow: boolean }) => {\n\t\tif (info.createdRow) onDraftUploadComplete?.();\n\t\telse onSaveComplete?.({ imageData: saved });\n\t\tconst message = saved == null || (Array.isArray(saved) && saved.length === 0) ? `${Noun} cleared` : `${Noun} saved`;\n\t\tif (noteWrite) noteWrite('update', 'success', message);\n\t\telse toast.success({ message });\n\t\tonFinishedEditing();\n\t}, [Noun, noteWrite, onDraftUploadComplete, onFinishedEditing, onSaveComplete]);\n\n\tconst editor = useFileEditor({\n\t\tvalue,\n\t\ttable,\n\t\tcolumn,\n\t\tmultiple,\n\t\tupload,\n\t\twrite,\n\t\ttarget,\n\t\tsubmitDraft: isDraftRow ? onSubmitDraft : undefined,\n\t\ttargetOfCreatedRow,\n\t\tonUploadError: (message) => toast.error({ message }),\n\t\tonRowCreated: onDraftUploadComplete,\n\t\tonSaved,\n\t});\n\tconst { entries, phase, busy, dirty, addFiles } = editor;\n\n\tconst writeBlocked = writeReason != null;\n\tconst uploadBlocked = upload.status !== 'ready';\n\tconst uploadReason = upload.status === 'unavailable' ? upload.reason : null;\n\tconst canAdd = !writeBlocked && !uploadBlocked && !busy;\n\tuseEditorFocus(editorRef, canAdd);\n\n\tconst takeFiles = useCallback((files: readonly File[]) => {\n\t\tif (!canAdd || files.length === 0) return;\n\t\tif (kind === 'image') {\n\t\t\tconst images = files.filter((file) => file.type.startsWith('image/'));\n\t\t\tif (images.length < files.length) toast.error({ message: 'Please select an image file' });\n\t\t\taddFiles(images);\n\t\t\treturn;\n\t\t}\n\t\taddFiles(files);\n\t}, [addFiles, canAdd, kind]);\n\n\tconst openPicker = useCallback(() => inputRef.current?.click(), []);\n\tconst hasNewFiles = entries.some((entry) => entry.file && entry.status !== 'uploaded');\n\tconst save = editor.save;\n\tconst close = useCallback(() => {\n\t\t// A write already sent keeps going on the cell; only uploads in flight stop.\n\t\teditor.cancelUploads();\n\t\tonFinishedEditing();\n\t}, [editor, onFinishedEditing]);\n\n\tconst primaryLabel = phase.name === 'creating-row' ? 'Creating…'\n\t\t: phase.name === 'uploading' ? 'Uploading…'\n\t\t: phase.name === 'saving' ? 'Saving…'\n\t\t: phase.name === 'processing' ? 'Processing file…'\n\t\t: hasNewFiles ? (editor.needsRowCreation ? 'Create Row & Upload' : 'Upload & Save')\n\t\t: phase.name === 'failed' ? 'Retry saving'\n\t\t: dirty ? 'Save' : 'Done';\n\tconst primaryAction = () => (hasNewFiles || dirty || phase.name === 'failed' ? void save() : onFinishedEditing());\n\n\tconst status = phaseText(phase, noun);\n\t// While storage is still resolving the dropzone shows, disabled; a reason hides it.\n\tconst showDropzone = !writeBlocked && upload.status !== 'unavailable' && (multiple || entries.length === 0);\n\tconst hint = upload.status === 'loading'\n\t\t? 'Checking storage…'\n\t\t: kind === 'image' ? 'Images only' : kind === 'attachment' ? 'Any file; the cell keeps a link to it' : 'Any file type';\n\n\treturn (\n\t\t<EditorFocusTrap\n\t\t\tonEscape={close}\n\t\t\tclassName={`bg-popover flex ${OVERLAY.lg} flex-col gap-0 overflow-hidden rounded-lg border p-0 shadow-lg`}\n\t\t\tstyle={overlayMaxHeight > 0 ? { maxHeight: overlayMaxHeight } : undefined}\n\t\t>\n\t\t\t<div\n\t\t\t\tref={editorRef}\n\t\t\t\tclassName=\"flex min-h-0 flex-1 flex-col\"\n\t\t\t\tdata-upload-state={upload.status}\n\t\t\t\tonKeyDown={(event) => {\n\t\t\t\t\tif (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {\n\t\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\t\tprimaryAction();\n\t\t\t\t\t}\n\t\t\t\t}}\n\t\t\t\tonPaste={(event) => {\n\t\t\t\t\tconst files = Array.from(event.clipboardData?.files ?? []);\n\t\t\t\t\tif (files.length === 0) return;\n\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\ttakeFiles(files);\n\t\t\t\t}}\n\t\t\t>\n\t\t\t\t<EditorHeader\n\t\t\t\t\ttitle={rawName ? fieldLabel(rawName) : Noun}\n\t\t\t\t\ttitleHint={rawName || undefined}\n\t\t\t\t\tchip={Noun}\n\t\t\t\t\tclassName=\"shrink-0 px-3 pt-3 pb-2\"\n\t\t\t\t/>\n\n\t\t\t\t<input\n\t\t\t\t\tref={inputRef}\n\t\t\t\t\ttype=\"file\"\n\t\t\t\t\tmultiple={multiple}\n\t\t\t\t\taccept={kind === 'image' ? 'image/*' : undefined}\n\t\t\t\t\tclassName=\"hidden\"\n\t\t\t\t\taria-label={`Upload ${noun}`}\n\t\t\t\t\ttabIndex={-1}\n\t\t\t\t\tonChange={(event) => {\n\t\t\t\t\t\ttakeFiles(Array.from(event.target.files ?? []));\n\t\t\t\t\t\tevent.target.value = '';\n\t\t\t\t\t}}\n\t\t\t\t/>\n\n\t\t\t\t<div className=\"min-h-0 flex-1 overflow-y-auto border-t\">\n\t\t\t\t\t<div className=\"flex flex-col gap-3 p-3\">\n\t\t\t\t\t\t{writeReason || uploadReason ? (\n\t\t\t\t\t\t\t<p role=\"note\" className=\"flex items-start gap-2 rounded-md bg-muted/40 px-3 py-2 text-xs text-muted-foreground\">\n\t\t\t\t\t\t\t\t<LockIcon className=\"mt-0.5 size-3 shrink-0\" aria-hidden=\"true\" />\n\t\t\t\t\t\t\t\t<span>{writeReason ?? uploadReason}</span>\n\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t) : null}\n\n\t\t\t\t\t\t{entries.length > 0 ? (\n\t\t\t\t\t\t\t<ul className=\"flex flex-col gap-1.5\" aria-label={Noun}>\n\t\t\t\t\t\t\t\t{entries.map((entry, index) => (\n\t\t\t\t\t\t\t\t\t<FileEntryRow\n\t\t\t\t\t\t\t\t\t\tkey={entry.key}\n\t\t\t\t\t\t\t\t\t\tentry={entry}\n\t\t\t\t\t\t\t\t\t\tkind={kind}\n\t\t\t\t\t\t\t\t\t\tresolver={media.resolver}\n\t\t\t\t\t\t\t\t\t\treorder={multiple ? { index, count: entries.length } : null}\n\t\t\t\t\t\t\t\t\t\tdisabled={busy}\n\t\t\t\t\t\t\t\t\t\treadOnly={writeBlocked}\n\t\t\t\t\t\t\t\t\t\tonMove={(delta) => editor.move(entry.key, delta)}\n\t\t\t\t\t\t\t\t\t\tonRemove={() => editor.remove(entry.key)}\n\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t) : !showDropzone ? (\n\t\t\t\t\t\t\t<p className=\"py-6 text-center text-sm text-muted-foreground\">No {noun}</p>\n\t\t\t\t\t\t) : null}\n\n\t\t\t\t\t\t{showDropzone ? (\n\t\t\t\t\t\t\t<FileDropzone\n\t\t\t\t\t\t\t\tnoun={noun}\n\t\t\t\t\t\t\t\thint={hint}\n\t\t\t\t\t\t\t\tdisabled={!canAdd}\n\t\t\t\t\t\t\t\tcompact={entries.length > 0}\n\t\t\t\t\t\t\t\tonPick={openPicker}\n\t\t\t\t\t\t\t\tonFiles={takeFiles}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t) : canAdd && !multiple && entries.length > 0 ? (\n\t\t\t\t\t\t\t<Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"self-start\" onClick={openPicker} data-initial-focus={ADD_CONTROL}>\n\t\t\t\t\t\t\t\tReplace {noun}\n\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t) : null}\n\n\t\t\t\t\t\t{status ? (\n\t\t\t\t\t\t\t<p\n\t\t\t\t\t\t\t\trole={phase.name === 'failed' ? 'alert' : 'status'}\n\t\t\t\t\t\t\t\tclassName={phase.name === 'failed' ? 'text-xs text-destructive' : 'flex items-center gap-1.5 text-xs text-muted-foreground'}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{phase.name !== 'failed' ? <Loader2 className=\"size-3 shrink-0 animate-spin\" aria-hidden=\"true\" /> : null}\n\t\t\t\t\t\t\t\t<span>{status}</span>\n\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t) : null}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n\t\t\t\t<div className=\"flex shrink-0 justify-end gap-2 border-t px-3 py-2\">\n\t\t\t\t\t<Button type=\"button\" variant=\"outline\" size=\"xs\" onClick={close} data-initial-focus={CLOSE_CONTROL}>\n\t\t\t\t\t\t{writeBlocked || phase.name === 'processing' || phase.name === 'saving' ? 'Close' : 'Cancel'}\n\t\t\t\t\t</Button>\n\t\t\t\t\t{!writeBlocked ? (\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tsize=\"xs\"\n\t\t\t\t\t\t\tonClick={primaryAction}\n\t\t\t\t\t\t\tdisabled={busy || (hasNewFiles && uploadBlocked)}\n\t\t\t\t\t\t\ttitle={busy ? undefined : `${primaryLabel} (${modifierKeyLabel()} Enter)`}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{busy ? <Loader2 className=\"size-3.5 animate-spin\" aria-hidden=\"true\" /> : null}\n\t\t\t\t\t\t\t{primaryLabel}\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t) : null}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","// The drop target of the file editor: drop files, or press Enter or Space (or\n// click) to pick them. Paste is handled by the editor around it.\n\nimport { useState } from 'react';\nimport type React from 'react';\nimport { UploadIcon } from 'lucide-react';\n\nimport { cn } from '../../utils/cn';\nimport { ADD_CONTROL } from './use-editor-focus';\n\ninterface FileDropzoneProps {\n\t/** What to call the files: \"image\", \"file\", \"files\". */\n\tnoun: string;\n\thint: string;\n\tdisabled: boolean;\n\tonPick: () => void;\n\tonFiles: (files: File[]) => void;\n\tcompact: boolean;\n}\n\nexport function FileDropzone({ noun, hint, disabled, onPick, onFiles, compact }: FileDropzoneProps) {\n\tconst [dragging, setDragging] = useState(false);\n\n\tconst onDrag = (event: React.DragEvent, active: boolean) => {\n\t\tevent.preventDefault();\n\t\tevent.stopPropagation();\n\t\tif (!disabled) setDragging(active);\n\t};\n\n\treturn (\n\t\t<div\n\t\t\trole=\"button\"\n\t\t\ttabIndex={disabled ? -1 : 0}\n\t\t\taria-disabled={disabled || undefined}\n\t\t\taria-label={`Drop ${noun} here or press Enter to browse`}\n\t\t\tdata-slot=\"file-dropzone\"\n\t\t\tdata-initial-focus={ADD_CONTROL}\n\t\t\tdata-dragging={dragging || undefined}\n\t\t\tclassName={cn(\n\t\t\t\t// Same corner as the file rows above it; the full border token keeps the dashed edge visible in dark mode.\n\t\t\t\t'flex w-full cursor-pointer flex-col items-center justify-center rounded-md border border-dashed border-border',\n\t\t\t\t// Hover is instant: no transition on the highlight.\n\t\t\t\t'bg-muted/20 text-center outline-hidden hover:bg-muted/30',\n\t\t\t\t'focus-visible:ring-[3px] focus-visible:ring-ring/50',\n\t\t\t\t'data-[dragging=true]:border-primary/40 data-[dragging=true]:bg-accent/50',\n\t\t\t\tcompact ? 'gap-1 px-4 py-3' : 'gap-2 px-4 py-6',\n\t\t\t\tdisabled && 'pointer-events-none opacity-50',\n\t\t\t)}\n\t\t\tonClick={disabled ? undefined : onPick}\n\t\t\tonKeyDown={(event) => {\n\t\t\t\tif (disabled || (event.key !== 'Enter' && event.key !== ' ')) return;\n\t\t\t\tif (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) return;\n\t\t\t\tevent.preventDefault();\n\t\t\t\tonPick();\n\t\t\t}}\n\t\t\tonDragEnter={(event) => onDrag(event, true)}\n\t\t\tonDragOver={(event) => onDrag(event, true)}\n\t\t\tonDragLeave={(event) => onDrag(event, false)}\n\t\t\tonDrop={(event) => {\n\t\t\t\tonDrag(event, false);\n\t\t\t\tif (disabled) return;\n\t\t\t\tconst files = Array.from(event.dataTransfer.files);\n\t\t\t\tif (files.length > 0) onFiles(files);\n\t\t\t}}\n\t\t>\n\t\t\t{!compact ? (\n\t\t\t\t<span className=\"flex size-10 shrink-0 items-center justify-center rounded-full bg-muted/60\" aria-hidden=\"true\">\n\t\t\t\t\t<UploadIcon className=\"size-4 text-muted-foreground\" />\n\t\t\t\t</span>\n\t\t\t) : null}\n\t\t\t<span className=\"text-sm font-medium\">Drop {noun} here or browse</span>\n\t\t\t<span className=\"text-xs text-muted-foreground\">{hint}</span>\n\t\t</div>\n\t);\n}\n","// Keyboard focus in the file editor.\n//\n// First focus goes to the control that adds a file (the dropzone, or \"Replace\"),\n// or to Close or Cancel when the editor cannot take a file. Not to the first\n// file's first action: that is an \"Open\" link, which a held Enter would follow.\n//\n// Focus also comes back when the focused control goes away: a removed file row,\n// or a button that turns disabled while an upload runs. The browser then moves\n// focus to the page body, where Escape and Tab no longer reach the editor.\n\nimport { useCallback, useEffect, useRef, type RefObject } from 'react';\n\n/** Marks the control that adds a file. */\nexport const ADD_CONTROL = 'add';\n/** Marks the Close or Cancel button. */\nexport const CLOSE_CONTROL = 'close';\n\nfunction focusTarget(root: HTMLElement): HTMLElement | null {\n\treturn root.querySelector<HTMLElement>(`[data-initial-focus=\"${ADD_CONTROL}\"]:not([aria-disabled=\"true\"]):not([disabled])`)\n\t\t?? root.querySelector<HTMLElement>(`[data-initial-focus=\"${CLOSE_CONTROL}\"]:not([disabled])`);\n}\n\nfunction focusIsLost(): boolean {\n\tconst active = document.activeElement;\n\treturn !active || active === document.body || active === document.documentElement;\n}\n\n/**\n * `canAdd` is true once the editor can take a file (storage resolved, nothing\n * running). An editor that opened before that has focus on Close or Cancel; it\n * moves to the add control when it appears, unless the user has moved on.\n */\nexport function useEditorFocus(rootRef: RefObject<HTMLElement | null>, canAdd: boolean): void {\n\tconst placed = useRef<HTMLElement | null>(null);\n\n\tconst recover = useCallback(() => {\n\t\tconst root = rootRef.current;\n\t\tif (root?.isConnected && focusIsLost()) focusTarget(root)?.focus();\n\t}, [rootRef]);\n\n\t// A passive effect, so it runs after the focus traps' own first focus.\n\tuseEffect(() => {\n\t\tconst root = rootRef.current;\n\t\tconst target = root ? focusTarget(root) : null;\n\t\ttarget?.focus();\n\t\tplaced.current = target;\n\t}, [rootRef]);\n\n\tuseEffect(() => {\n\t\tconst root = rootRef.current;\n\t\tconst first = placed.current;\n\t\tif (!canAdd || !root || !first || document.activeElement !== first || first.dataset.initialFocus !== CLOSE_CONTROL) return;\n\t\tconst target = focusTarget(root);\n\t\tif (target && target !== first) {\n\t\t\ttarget.focus();\n\t\t\tplaced.current = target;\n\t\t}\n\t}, [canAdd, rootRef]);\n\n\tuseEffect(() => {\n\t\tconst root = rootRef.current;\n\t\tif (!root) return;\n\t\t// Focus leaving for nowhere (no related target): a removed control leaves at once,\n\t\t// a disabled one on the browser's next rendering step. Check once it has settled.\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst onFocusOut = (event: FocusEvent) => {\n\t\t\tif (event.relatedTarget) return;\n\t\t\tclearTimeout(timer);\n\t\t\ttimer = setTimeout(recover, 0);\n\t\t};\n\t\troot.addEventListener('focusout', onFocusOut);\n\t\treturn () => {\n\t\t\troot.removeEventListener('focusout', onFocusOut);\n\t\t\tclearTimeout(timer);\n\t\t};\n\t}, [recover, rootRef]);\n}\n","// One file in the file editor: preview, name, type and size, upload progress,\n// and its actions (open, move, remove or cancel). Every action is a button or\n// a link, so it works with Tab, Enter and Space.\n\nimport { AlertCircleIcon, ArrowDownIcon, ArrowUpIcon, ExternalLinkIcon, FileIcon, LinkIcon, XIcon } from 'lucide-react';\n\nimport type { ColumnFileModel } from '@constructive-io/data';\n\nimport { useSheetsMediaUrl, type MediaUrlResolver } from '../../hooks/use-sheets-media-url';\nimport { cn } from '../../utils/cn';\nimport { fileDetails, fileLabel, fileTypeLabel, formatFileSize, isImageFile } from '../../utils/file.utils';\nimport type { FileEntry } from './use-file-editor';\n\ninterface FileEntryRowProps {\n\tentry: FileEntry;\n\tkind: ColumnFileModel['kind'];\n\tresolver: MediaUrlResolver | null | undefined;\n\t/** List columns can reorder; a single-file column has no position. */\n\treorder: { index: number; count: number } | null;\n\tdisabled: boolean;\n\treadOnly: boolean;\n\tonMove: (delta: -1 | 1) => void;\n\tonRemove: () => void;\n}\n\nconst ICON_BUTTON = cn(\n\t// Hover is instant: no transition on the highlight.\n\t'flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-hidden',\n\t'hover:bg-muted hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50',\n\t'disabled:pointer-events-none disabled:opacity-40',\n);\n\nfunction details(entry: FileEntry): string {\n\tif (entry.file) {\n\t\treturn [fileTypeLabel(entry.file.type || null, entry.file.name), formatFileSize(entry.file.size)].filter(Boolean).join(' • ');\n\t}\n\tif (!entry.stored) return '';\n\treturn [fileTypeLabel(entry.stored.mime, fileLabel(entry.stored)), entry.stored.size != null ? formatFileSize(entry.stored.size) : null]\n\t\t.filter(Boolean)\n\t\t.join(' • ');\n}\n\nexport function FileEntryRow({ entry, kind, resolver, reorder, disabled, readOnly, onMove, onRemove }: FileEntryRowProps) {\n\tconst stored = entry.stored;\n\tconst name = entry.file?.name ?? (stored ? fileLabel(stored) : 'File');\n\tconst showsImage = entry.file ? entry.file.type.startsWith('image/') : stored ? kind !== 'attachment' && isImageFile(stored, kind) : false;\n\t// A stored file resolves its URL for opening even when it is not an image.\n\tconst media = useSheetsMediaUrl(stored?.raw ?? null, { previewImage: Boolean(stored), resolver });\n\tconst openUrl = stored ? media.url : null;\n\tconst previewUrl = entry.previewUrl ?? (showsImage ? media.url : null);\n\tconst Icon = kind === 'attachment' ? LinkIcon : FileIcon;\n\tconst uploading = entry.status === 'uploading';\n\t// A single-file cell keeps the short labels; a list names each file.\n\tconst removeLabel = uploading\n\t\t? `Cancel upload of ${name}`\n\t\t: reorder ? `Remove ${name}` : previewUrl ? 'Remove image' : 'Remove file';\n\n\treturn (\n\t\t<li\n\t\t\tdata-slot=\"file-entry\"\n\t\t\tdata-status={entry.status}\n\t\t\tclassName=\"flex items-center gap-3 rounded-md border border-border/60 bg-background py-1 ps-1 pe-2\"\n\t\t>\n\t\t\t{/* The preview sits 5px inside the row (4px padding and the border), so its corner is the row's 8px less 5px. */}\n\t\t\t<div className=\"relative flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-[3px] bg-muted\" aria-hidden=\"true\">\n\t\t\t\t{previewUrl ? (\n\t\t\t\t\t<img\n\t\t\t\t\t\tsrc={previewUrl}\n\t\t\t\t\t\talt=\"\"\n\t\t\t\t\t\tclassName=\"absolute inset-0 size-full rounded-[3px] object-cover outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10\"\n\t\t\t\t\t\tonError={entry.previewUrl ? undefined : media.onImageError}\n\t\t\t\t\t\tonLoad={entry.previewUrl ? undefined : media.onImageLoad}\n\t\t\t\t\t/>\n\t\t\t\t) : (\n\t\t\t\t\t<Icon className=\"size-4 text-muted-foreground\" />\n\t\t\t\t)}\n\t\t\t</div>\n\t\t\t<div className=\"min-w-0 flex-1\">\n\t\t\t\t<p className=\"truncate text-sm font-medium\" title={stored ? fileDetails(stored) : name}>{name}</p>\n\t\t\t\t{entry.status === 'failed' ? (\n\t\t\t\t\t<p className=\"mt-0.5 flex items-center gap-1 text-xs text-destructive\" role=\"alert\">\n\t\t\t\t\t\t<AlertCircleIcon className=\"size-3 shrink-0\" aria-hidden=\"true\" />\n\t\t\t\t\t\t<span className=\"truncate\" title={entry.error ?? undefined}>{entry.error ?? 'Upload failed'}</span>\n\t\t\t\t\t</p>\n\t\t\t\t) : uploading ? (\n\t\t\t\t\t<div\n\t\t\t\t\t\trole=\"progressbar\"\n\t\t\t\t\t\taria-label={`Uploading ${name}`}\n\t\t\t\t\t\taria-valuemin={0}\n\t\t\t\t\t\taria-valuemax={100}\n\t\t\t\t\t\taria-valuenow={entry.progress ?? 0}\n\t\t\t\t\t\tclassName=\"mt-1.5 h-1 overflow-hidden rounded-full bg-muted\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclassName=\"h-1 rounded-full bg-primary transition-[width] duration-(--duration-slow)\"\n\t\t\t\t\t\t\tstyle={{ width: `${entry.progress ?? 0}%` }}\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\t\t\t\t) : (\n\t\t\t\t\t<p className=\"mt-0.5 truncate text-xs text-muted-foreground tabular-nums\">\n\t\t\t\t\t\t{entry.status === 'selected' ? `${details(entry)} • Not uploaded yet` : details(entry)}\n\t\t\t\t\t</p>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t\t<div className=\"flex shrink-0 items-center gap-0.5\">\n\t\t\t\t{openUrl ? (\n\t\t\t\t\t<a\n\t\t\t\t\t\thref={openUrl}\n\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\trel=\"noreferrer\"\n\t\t\t\t\t\tdownload={stored?.filename ?? undefined}\n\t\t\t\t\t\tclassName={ICON_BUTTON}\n\t\t\t\t\t\taria-label={`Open ${name}`}\n\t\t\t\t\t\ttitle=\"Open or download\"\n\t\t\t\t\t>\n\t\t\t\t\t\t<ExternalLinkIcon className=\"size-3.5\" aria-hidden=\"true\" />\n\t\t\t\t\t</a>\n\t\t\t\t) : null}\n\t\t\t\t{reorder && !readOnly ? (\n\t\t\t\t\t<>\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tclassName={ICON_BUTTON}\n\t\t\t\t\t\t\taria-label={`Move ${name} up`}\n\t\t\t\t\t\t\tdisabled={disabled || reorder.index === 0}\n\t\t\t\t\t\t\tonClick={() => onMove(-1)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<ArrowUpIcon className=\"size-3.5\" aria-hidden=\"true\" />\n\t\t\t\t\t\t</button>\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\tclassName={ICON_BUTTON}\n\t\t\t\t\t\t\taria-label={`Move ${name} down`}\n\t\t\t\t\t\t\tdisabled={disabled || reorder.index === reorder.count - 1}\n\t\t\t\t\t\t\tonClick={() => onMove(1)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<ArrowDownIcon className=\"size-3.5\" aria-hidden=\"true\" />\n\t\t\t\t\t\t</button>\n\t\t\t\t\t</>\n\t\t\t\t) : null}\n\t\t\t\t{!readOnly ? (\n\t\t\t\t\t<button\n\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\tclassName={ICON_BUTTON}\n\t\t\t\t\t\taria-label={removeLabel}\n\t\t\t\t\t\ttitle={uploading ? 'Cancel upload' : 'Remove'}\n\t\t\t\t\t\tdisabled={disabled && !uploading}\n\t\t\t\t\t\tonClick={onRemove}\n\t\t\t\t\t>\n\t\t\t\t\t\t<XIcon className=\"size-3.5\" aria-hidden=\"true\" />\n\t\t\t\t\t</button>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t</li>\n\t);\n}\n","// Preview URLs for stored files.\n//\n// A projection with a durable public `url` is shown as is. Otherwise the file\n// id is resolved to a signed download URL, batched across the visible cells\n// (one request per 100 ids), and cached in the authenticated query cache. A\n// signed URL never enters a cell value: it expires.\n//\n// The caller passes the column's URL resolver (`ColumnStorage.resolveUrls`,\n// built from the storage-side files table model). Without one, the fallback\n// shape discovery resolves the id on the storage endpoint.\n\nimport { useCallback, useMemo, useRef, useState } from 'react';\nimport { skipToken, useQuery } from '@tanstack/react-query';\n\nimport { useSheetsContext, type SheetsScopeKey, type SheetsStorageTransport } from '../context/sheets-context';\nimport { fetchMediaDownloadUrls } from '../context/sheets-upload-presigned';\nimport { storedFilesOf } from '../utils/file.utils';\nimport { sheetsQueryKeys } from './query-keys';\n\nconst MAX_BATCH_SIZE = 100;\nconst REFRESH_INTERVAL = 50 * 60 * 1000;\n// A file with no signed URL stays unresolved for a while, so remounts and focus\n// don't send the same lookup again on every scroll pass.\nconst UNRESOLVED_STALE_TIME = 60 * 1000;\n// A file can have no URL yet because the storage service confirms an upload in the\n// background. Such a file is looked up again on a short backoff, then left alone, so\n// a fresh upload shows its preview once confirmed and a file the reader cannot see\n// costs only these few batched lookups.\nconst UNRESOLVED_RETRY_DELAYS = [2_000, 4_000, 8_000, 16_000, 30_000];\n\n/** Resolves download URLs for file ids; ids without a URL have no entry. */\nexport type ResolveDownloadUrls = (ids: readonly string[]) => Promise<Map<string, string>>;\n\nexport interface MediaUrlResolver {\n\t/** Identity of the resolver (the files table it reads), for batching and caching. */\n\tkey: string;\n\tresolve: ResolveDownloadUrls;\n}\n\ninterface PendingLookup {\n\tid: string;\n\tsignal: AbortSignal;\n\tresolve: (url: string | null) => void;\n\treject: (error: unknown) => void;\n}\n\ntype MediaLoader = (id: string, signal: AbortSignal) => Promise<string | null>;\n/** One batching loader per scope and resolver; the fallback discovery has one per storage transport. */\nconst loaders = new WeakMap<SheetsScopeKey, Map<string, MediaLoader>>();\nconst fallbackLoaders = new WeakMap<SheetsStorageTransport, WeakMap<SheetsScopeKey, MediaLoader>>();\n\nfunction createMediaLoader(resolve: (getActiveIds: () => readonly string[]) => Promise<Map<string, string>>): MediaLoader {\n\tlet pending: PendingLookup[] = [];\n\n\tasync function fetchBatch(requests: PendingLookup[]) {\n\t\t// Read the active ids late so a canceled scope cannot send a lookup through\n\t\t// an executor whose auth has since changed.\n\t\tconst getActiveIds = () => [...new Set(requests.filter(({ signal }) => !signal.aborted).map(({ id }) => id))];\n\t\ttry {\n\t\t\tconst urls = getActiveIds().length ? await resolve(getActiveIds) : null;\n\t\t\tfor (const request of requests) {\n\t\t\t\trequest.resolve(request.signal.aborted ? null : urls?.get(request.id) ?? null);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfor (const request of requests) request.reject(error);\n\t\t}\n\t}\n\n\tfunction flush() {\n\t\tconst requests = pending;\n\t\tpending = [];\n\t\tfor (let start = 0; start < requests.length; start += MAX_BATCH_SIZE) {\n\t\t\tvoid fetchBatch(requests.slice(start, start + MAX_BATCH_SIZE));\n\t\t}\n\t}\n\n\treturn (id, signal) => new Promise((resolve, reject) => {\n\t\tif (pending.length === 0) queueMicrotask(flush);\n\t\tpending.push({ id, signal, resolve, reject });\n\t});\n}\n\nconst FALLBACK_KEY = 'discovery';\n\nfunction getMediaLoader(scopeKey: SheetsScopeKey, resolver: MediaUrlResolver): MediaLoader {\n\tlet byResolver = loaders.get(scopeKey);\n\tif (!byResolver) {\n\t\tbyResolver = new Map();\n\t\tloaders.set(scopeKey, byResolver);\n\t}\n\tlet load = byResolver.get(resolver.key);\n\tif (!load) {\n\t\tload = createMediaLoader((getActiveIds) => resolver.resolve(getActiveIds()));\n\t\tbyResolver.set(resolver.key, load);\n\t}\n\treturn load;\n}\n\nfunction getFallbackLoader(storage: SheetsStorageTransport, scopeKey: SheetsScopeKey): MediaLoader {\n\tlet scopes = fallbackLoaders.get(storage);\n\tif (!scopes) {\n\t\tscopes = new WeakMap();\n\t\tfallbackLoaders.set(storage, scopes);\n\t}\n\tlet load = scopes.get(scopeKey);\n\tif (!load) {\n\t\tload = createMediaLoader((getActiveIds) => fetchMediaDownloadUrls(storage, getActiveIds));\n\t\tscopes.set(scopeKey, load);\n\t}\n\treturn load;\n}\n\nexport interface UseSheetsMediaUrlOptions {\n\t/** Resolve a preview at all. False for a file that is not an image. Default true. */\n\tpreviewImage?: boolean;\n\t/** The column's URL resolver. Null means previews cannot be signed; undefined uses the fallback discovery. */\n\tresolver?: MediaUrlResolver | null;\n}\n\n/**\n * Preview URL for one stored file (a projection or a link). Keeps signed URLs\n * in the authenticated preview cache, separate from cell values.\n */\nexport function useSheetsMediaUrl(value: unknown, options: UseSheetsMediaUrlOptions = {}) {\n\tconst { previewImage = true, resolver } = options;\n\tconst { storage, scopeKey } = useSheetsContext();\n\tconst file = storedFilesOf(value)[0] ?? null;\n\tconst durableUrl = file?.url ?? null;\n\tconst id = file?.id ?? null;\n\tconst endpoint = storage?.endpoint;\n\tconst resolverKey = resolver === undefined ? FALLBACK_KEY : resolver?.key ?? null;\n\tconst resource = useMemo(() => ({ scopeKey, endpoint, id, resolverKey }), [scopeKey, endpoint, id, resolverKey]);\n\tconst load = !id || !previewImage || durableUrl\n\t\t? null\n\t\t: resolver\n\t\t\t? getMediaLoader(scopeKey, resolver)\n\t\t\t: resolver === undefined && storage ? getFallbackLoader(storage, scopeKey) : null;\n\n\tconst query = useQuery({\n\t\tqueryKey: [...sheetsQueryKeys.mediaUrl(scopeKey, endpoint, id), resolverKey],\n\t\tqueryFn: load ? ({ signal }) => load(id!, signal) : skipToken,\n\t\tstaleTime: (query) => query.state.data ? REFRESH_INTERVAL : UNRESOLVED_STALE_TIME,\n\t\tgcTime: REFRESH_INTERVAL,\n\t\trefetchInterval: (query) => {\n\t\t\tif (query.state.status !== 'success') return false;\n\t\t\tif (query.state.data) return REFRESH_INTERVAL;\n\t\t\t// `dataUpdateCount` counts the finished lookups: the first one, then each retry.\n\t\t\treturn UNRESOLVED_RETRY_DELAYS[query.state.dataUpdateCount - 1] ?? false;\n\t\t},\n\t\trefetchOnWindowFocus: true,\n\t\tretry: false,\n\t});\n\tconst signedUrl = previewImage && !durableUrl && !query.isPlaceholderData ? query.data ?? null : null;\n\tconst [failed, setFailed] = useState<{ resource: typeof resource; url: string } | null>(null);\n\tconst retried = useRef<typeof resource | null>(null);\n\tconst { refetch } = query;\n\n\tconst onImageError = useCallback(() => {\n\t\tif (!signedUrl) return;\n\t\tsetFailed({ resource, url: signedUrl });\n\t\tif (retried.current === resource) return;\n\t\tretried.current = resource;\n\t\tvoid refetch({ cancelRefetch: false });\n\t}, [refetch, resource, signedUrl]);\n\n\tconst onImageLoad = useCallback(() => {\n\t\tif (retried.current !== resource) return;\n\t\tretried.current = null;\n\t\tsetFailed(null);\n\t}, [resource]);\n\n\tconst url = durableUrl ?? (failed?.resource === resource && failed.url === signedUrl ? null : signedUrl);\n\treturn { url, durableUrl, id, isLoading: query.isFetching && !url, onImageError, onImageLoad };\n}\n","// State of the file editor: the files a cell will hold, the uploads in flight,\n// and the save sequence.\n//\n// Save runs in order:\n// 1. a draft row is created first, and its key is read from the created row\n// with the table model's primary key (so a key without a default works);\n// 2. new files upload, at most UPLOAD_CONCURRENCY at a time, each with its own\n// progress and cancel; a failed file keeps its error and a retry, and the\n// others keep their uploads;\n// 3. the cell is written once with the whole value (one file, a list in the\n// order shown, or null), waiting out the server's file confirmation.\n// Cancel aborts the uploads in flight. The server expires a file row whose PUT\n// never finished, so a cancelled upload leaves nothing behind.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport type { ColumnModel, TableModel } from '@constructive-io/data';\n\nimport { isAbortError } from '../../context/sheets-upload-presigned';\nimport type { DraftSubmitResult } from '../../grid/draft-types';\nimport { cellElementFor, type FileCellWriteJob, type FileUploadState } from '../../hooks/use-sheets-upload';\nimport type { SheetsRowIdentifier } from '../../row-identity';\nimport { fileWriteMessage } from '../file-cell-write';\nimport { storedFilesOf, type StoredFile } from '../../utils/file.utils';\n\n/** Uploads in flight at once, per editor. */\nexport const UPLOAD_CONCURRENCY = 3;\n\nexport type FileEntryStatus = 'stored' | 'selected' | 'uploading' | 'uploaded' | 'failed';\n\nexport interface FileEntry {\n\t/** Local key. */\n\tkey: string;\n\t/** The stored file, for a file the cell already holds. */\n\tstored: StoredFile | null;\n\t/** The picked file, for a new one. */\n\tfile: File | null;\n\t/** Object URL of a picked image, for its preview. */\n\tpreviewUrl: string | null;\n\tstatus: FileEntryStatus;\n\t/** Upload progress in percent, while uploading. */\n\tprogress: number | null;\n\terror: string | null;\n\t/** The element the cell stores for this file, once known. */\n\telement: unknown;\n}\n\nexport type FileEditorPhase =\n\t| { name: 'idle' }\n\t| { name: 'creating-row' }\n\t| { name: 'uploading' }\n\t| { name: 'saving' }\n\t| { name: 'processing' }\n\t| { name: 'failed'; message: string };\n\nexport interface SaveTarget {\n\trowKey: SheetsRowIdentifier;\n\t/** Grid row id, which keys the cell's pending state. */\n\trowId: string;\n}\n\nexport interface UseFileEditorArgs {\n\tvalue: unknown;\n\ttable: TableModel | null;\n\tcolumn: ColumnModel | null;\n\tmultiple: boolean;\n\tupload: FileUploadState;\n\twrite: (job: FileCellWriteJob) => Promise<unknown>;\n\t/** The row, or null for a draft row that has not been created. */\n\ttarget: SaveTarget | null;\n\tsubmitDraft?: () => Promise<DraftSubmitResult>;\n\t/** The key and grid row id of a row the draft created, or null when its key cannot be read. */\n\ttargetOfCreatedRow: (row: Record<string, unknown>) => SaveTarget | null;\n\tonUploadError?: (message: string) => void;\n\t/** Called once the draft row exists on the server. */\n\tonRowCreated?: () => void;\n\tonSaved: (saved: unknown, info: { createdRow: boolean }) => void;\n}\n\nlet nextKey = 1;\nconst entryKey = () => `entry-${nextKey++}`;\n\nfunction storedEntries(value: unknown, column: ColumnModel | null): FileEntry[] {\n\treturn storedFilesOf(value, column?.value.file).map((stored): FileEntry => ({\n\t\tkey: entryKey(),\n\t\tstored,\n\t\tfile: null,\n\t\tpreviewUrl: null,\n\t\tstatus: 'stored',\n\t\tprogress: null,\n\t\terror: null,\n\t\telement: stored.raw,\n\t}));\n}\n\nfunction isImageUpload(file: File): boolean {\n\treturn file.type.startsWith('image/');\n}\n\nasync function runPool<T>(items: readonly T[], limit: number, worker: (item: T) => Promise<void>): Promise<void> {\n\tlet next = 0;\n\tconst lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {\n\t\twhile (next < items.length) {\n\t\t\tconst item = items[next]!;\n\t\t\tnext += 1;\n\t\t\tawait worker(item);\n\t\t}\n\t});\n\tawait Promise.all(lanes);\n}\n\nexport function useFileEditor(args: UseFileEditorArgs) {\n\tconst { value, table, column, multiple, upload, write, target, submitDraft, targetOfCreatedRow, onUploadError, onRowCreated, onSaved } = args;\n\t// The files the cell held when the editor opened; a refetch while it is open does not reset the edit.\n\tconst [initial] = useState(() => storedEntries(value, column));\n\tconst [entries, setEntriesState] = useState<FileEntry[]>(initial);\n\tconst [phase, setPhase] = useState<FileEditorPhase>({ name: 'idle' });\n\tconst entriesRef = useRef(entries);\n\tconst controllers = useRef(new Map<string, AbortController>());\n\tconst committed = useRef<SaveTarget | null>(null);\n\tconst mounted = useRef(true);\n\t/** Set when the user cancels an upload during a save: that save stops before writing. */\n\tconst cancelled = useRef(false);\n\n\tconst setEntries = useCallback((update: (current: FileEntry[]) => FileEntry[]) => {\n\t\tentriesRef.current = update(entriesRef.current);\n\t\tif (mounted.current) setEntriesState(entriesRef.current);\n\t}, []);\n\tconst patch = useCallback((key: string, change: Partial<FileEntry>) => {\n\t\tsetEntries((current) => current.map((entry) => (entry.key === key ? { ...entry, ...change } : entry)));\n\t}, [setEntries]);\n\n\tuseEffect(() => {\n\t\tmounted.current = true;\n\t\tconst active = controllers.current;\n\t\treturn () => {\n\t\t\tmounted.current = false;\n\t\t\tfor (const controller of active.values()) controller.abort();\n\t\t\tfor (const entry of entriesRef.current) if (entry.previewUrl) URL.revokeObjectURL(entry.previewUrl);\n\t\t};\n\t}, []);\n\n\tconst busy = phase.name === 'creating-row' || phase.name === 'uploading' || phase.name === 'saving' || phase.name === 'processing';\n\n\tconst dirty = useMemo(() => {\n\t\tif (entries.length !== initial.length) return true;\n\t\treturn entries.some((entry, index) => entry.file !== null || entry.stored !== initial[index]?.stored);\n\t}, [entries, initial]);\n\n\tconst discard = useCallback((entry: FileEntry) => {\n\t\tconst controller = controllers.current.get(entry.key);\n\t\tif (controller) {\n\t\t\tcancelled.current = true;\n\t\t\tcontroller.abort();\n\t\t}\n\t\tcontrollers.current.delete(entry.key);\n\t\tif (entry.previewUrl) URL.revokeObjectURL(entry.previewUrl);\n\t}, []);\n\n\tconst addFiles = useCallback((files: readonly File[]) => {\n\t\tif (files.length === 0) return;\n\t\tconst picked = (multiple ? files : files.slice(0, 1)).map((file): FileEntry => ({\n\t\t\tkey: entryKey(),\n\t\t\tstored: null,\n\t\t\tfile,\n\t\t\tpreviewUrl: isImageUpload(file) && typeof URL.createObjectURL === 'function' ? URL.createObjectURL(file) : null,\n\t\t\tstatus: 'selected',\n\t\t\tprogress: null,\n\t\t\terror: null,\n\t\t\telement: undefined,\n\t\t}));\n\t\tsetEntries((current) => {\n\t\t\tif (multiple) return [...current, ...picked];\n\t\t\tcurrent.forEach(discard);\n\t\t\treturn picked;\n\t\t});\n\t\tsetPhase((current) => (current.name === 'failed' ? { name: 'idle' } : current));\n\t}, [discard, multiple, setEntries]);\n\n\tconst remove = useCallback((key: string) => {\n\t\tsetEntries((current) => {\n\t\t\tconst entry = current.find((candidate) => candidate.key === key);\n\t\t\tif (entry) discard(entry);\n\t\t\treturn current.filter((candidate) => candidate.key !== key);\n\t\t});\n\t}, [discard, setEntries]);\n\n\tconst move = useCallback((key: string, delta: -1 | 1) => {\n\t\tsetEntries((current) => {\n\t\t\tconst index = current.findIndex((entry) => entry.key === key);\n\t\t\tconst to = index + delta;\n\t\t\tif (index < 0 || to < 0 || to >= current.length) return current;\n\t\t\tconst next = [...current];\n\t\t\t[next[index], next[to]] = [next[to]!, next[index]!];\n\t\t\treturn next;\n\t\t});\n\t}, [setEntries]);\n\n\tconst uploadEntry = useCallback(async (entry: FileEntry, recordId: string | number | undefined) => {\n\t\tif (upload.status !== 'ready' || !entry.file || !column) return;\n\t\tconst controller = new AbortController();\n\t\tcontrollers.current.set(entry.key, controller);\n\t\tpatch(entry.key, { status: 'uploading', progress: 0, error: null });\n\t\ttry {\n\t\t\tconst projection = await upload.send(entry.file, {\n\t\t\t\trecordId,\n\t\t\t\tsignal: controller.signal,\n\t\t\t\tonProgress: ({ percentage }) => patch(entry.key, { progress: percentage }),\n\t\t\t});\n\t\t\tpatch(entry.key, { status: 'uploaded', progress: 100, element: cellElementFor(column, projection, entry.file) });\n\t\t} catch (error) {\n\t\t\tif (controller.signal.aborted || isAbortError(error)) return;\n\t\t\tconst message = error instanceof Error && error.message ? error.message : 'Upload failed';\n\t\t\tpatch(entry.key, { status: 'failed', progress: null, error: message });\n\t\t\tonUploadError?.(message);\n\t\t} finally {\n\t\t\tcontrollers.current.delete(entry.key);\n\t\t}\n\t}, [column, onUploadError, patch, upload]);\n\n\tconst save = useCallback(async () => {\n\t\tif (busy || !table || !column) return;\n\t\ttry {\n\t\t\tlet saveTarget = committed.current ?? target;\n\t\t\tif (!saveTarget) {\n\t\t\t\tif (!submitDraft) throw new Error('Save the row before adding a file.');\n\t\t\t\tsetPhase({ name: 'creating-row' });\n\t\t\t\tconst { createdRow: row } = await submitDraft();\n\t\t\t\t// The draft is gone from here on: the host refetches whatever happens next.\n\t\t\t\tonRowCreated?.();\n\t\t\t\tsaveTarget = row ? targetOfCreatedRow(row) : null;\n\t\t\t\tif (!saveTarget) throw new Error('The row was created, but its key could not be read, so the file was not saved.');\n\t\t\t\tcommitted.current = saveTarget;\n\t\t\t}\n\n\t\t\tconst pending = entriesRef.current.filter((entry) => entry.file && entry.status !== 'uploaded');\n\t\t\tif (pending.length > 0) {\n\t\t\t\tif (upload.status !== 'ready') {\n\t\t\t\t\tthrow new Error(upload.status === 'unavailable' ? upload.reason : 'Storage is not ready yet.');\n\t\t\t\t}\n\t\t\t\tsetPhase({ name: 'uploading' });\n\t\t\t\tcancelled.current = false;\n\t\t\t\tconst recordId = typeof saveTarget.rowKey === 'object' ? undefined : saveTarget.rowKey;\n\t\t\t\tawait runPool(pending, UPLOAD_CONCURRENCY, (entry) => uploadEntry(entry, recordId));\n\t\t\t\tif (!mounted.current) return;\n\t\t\t\tif (cancelled.current) {\n\t\t\t\t\t// A cancelled upload is not a request to save without it.\n\t\t\t\t\tcancelled.current = false;\n\t\t\t\t\tsetPhase({ name: 'idle' });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst failed = entriesRef.current.filter((entry) => entry.status === 'failed').length;\n\t\t\t\tconst unfinished = entriesRef.current.some((entry) => entry.file && entry.status !== 'uploaded');\n\t\t\t\tif (unfinished) {\n\t\t\t\t\tsetPhase(failed\n\t\t\t\t\t\t? { name: 'failed', message: failed === 1 ? 'A file could not be uploaded.' : `${failed} files could not be uploaded.` }\n\t\t\t\t\t\t: { name: 'idle' });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst elements = entriesRef.current.map((entry) => entry.element);\n\t\t\tconst nextValue = multiple ? elements : elements[0] ?? null;\n\t\t\tsetPhase({ name: 'saving' });\n\t\t\tconst saved = await write({\n\t\t\t\ttable,\n\t\t\t\tcolumn,\n\t\t\t\trowKey: saveTarget.rowKey,\n\t\t\t\trowId: saveTarget.rowId,\n\t\t\t\tvalue: nextValue,\n\t\t\t\tonProcessing: () => {\n\t\t\t\t\tif (mounted.current) setPhase({ name: 'processing' });\n\t\t\t\t},\n\t\t\t});\n\t\t\t// After the editor closed, the cell shows the saved value from the refetch.\n\t\t\tif (!mounted.current) return;\n\t\t\tsetPhase({ name: 'idle' });\n\t\t\tonSaved(saved, { createdRow: committed.current !== null });\n\t\t} catch (error) {\n\t\t\tif (isAbortError(error) || !mounted.current) return;\n\t\t\tsetPhase({ name: 'failed', message: fileWriteMessage(error) });\n\t\t}\n\t}, [busy, column, multiple, onRowCreated, onSaved, submitDraft, table, target, targetOfCreatedRow, upload, uploadEntry, write]);\n\n\t/** Stop the uploads in flight. A write already sent keeps going and shows on the cell. */\n\tconst cancelUploads = useCallback(() => {\n\t\tif (controllers.current.size > 0) cancelled.current = true;\n\t\tfor (const controller of controllers.current.values()) controller.abort();\n\t\tcontrollers.current.clear();\n\t}, []);\n\n\treturn {\n\t\tentries,\n\t\tphase,\n\t\tbusy,\n\t\tdirty,\n\t\t/** True when the draft row still has to be created by the save. */\n\t\tneedsRowCreation: !target && committed.current === null,\n\t\taddFiles,\n\t\tremove,\n\t\tmove,\n\t\tsave,\n\t\tcancelUploads,\n\t};\n}\n","import React, { useCallback, useEffect, useRef, useState } from 'react';\n\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { EditorFooter, EditorHeader, editorClear } from './editor-frame';\nimport { OVERLAY } from './overlay-presets';\n\nconst IPV4_RE = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;\nconst IPV6_FULL_RE = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$/;\nconst IPV6_COMPRESSED_RE =\n\t/^([0-9a-fA-F]{1,4}:)*::([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:)*::[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:)*::$/;\n\ninterface InetEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n\t/** The field's readable name, shown as the title. */\n\ttitle?: string;\n\t/** The column takes no value, so Clear is offered. */\n\tnullable?: boolean;\n}\n\nfunction isValidIPv4(ip: string): boolean {\n\treturn IPV4_RE.test(ip);\n}\n\nfunction isValidIPv6(ip: string): boolean {\n\treturn IPV6_FULL_RE.test(ip) || IPV6_COMPRESSED_RE.test(ip);\n}\n\nfunction isValidCIDR(cidr: string): boolean {\n\tconst parts = cidr.split('/');\n\tif (parts.length !== 2) return false;\n\n\tconst [ip, prefix] = parts;\n\tconst prefixNum = parseInt(prefix, 10);\n\n\tif (isValidIPv4(ip)) {\n\t\treturn prefixNum >= 0 && prefixNum <= 32;\n\t} else if (isValidIPv6(ip)) {\n\t\treturn prefixNum >= 0 && prefixNum <= 128;\n\t}\n\n\treturn false;\n}\n\nfunction isValidInet(value: string): boolean {\n\tif (!value || typeof value !== 'string') return false;\n\n\tconst trimmed = value.trim();\n\n\tif (trimmed.includes('/')) {\n\t\treturn isValidCIDR(trimmed);\n\t}\n\n\treturn isValidIPv4(trimmed) || isValidIPv6(trimmed);\n}\n\nfunction getInetType(value: string): string {\n\tif (!value) return '';\n\n\tconst trimmed = value.trim();\n\n\tif (trimmed.includes('/')) {\n\t\tconst [ip] = trimmed.split('/');\n\t\tif (isValidIPv4(ip)) return 'IPv4 Network';\n\t\tif (isValidIPv6(ip)) return 'IPv6 Network';\n\t} else {\n\t\tif (isValidIPv4(trimmed)) return 'IPv4 Address';\n\t\tif (isValidIPv6(trimmed)) return 'IPv6 Address';\n\t}\n\n\treturn 'Invalid';\n}\n\nexport const InetEditor: React.FC<InetEditorProps> = ({ value, onFinishedEditing, title = 'Network address', nullable = false }) => {\n\tconst currentInetData = typeof value === 'string' ? value : '';\n\tconst [editingValue, setEditingValue] = useState<string>(currentInetData);\n\tconst [validationError, setValidationError] = useState<string>('');\n\tconst keyContainerRef = useRef<HTMLDivElement>(null);\n\n\tconst handleSave = useCallback(() => {\n\t\tif (editingValue.trim() && !isValidInet(editingValue.trim())) {\n\t\t\tsetValidationError('Invalid IP address or CIDR');\n\t\t\treturn;\n\t\t}\n\n\t\tonFinishedEditing(editingValue.trim());\n\t}, [editingValue, onFinishedEditing]);\n\n\tconst handleCancel = useCallback(() => {\n\t\tonFinishedEditing();\n\t}, [onFinishedEditing]);\n\n\tconst handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {\n\t\tsetEditingValue(e.target.value);\n\t\tsetValidationError('');\n\t}, []);\n\n\t// Refs for native key handler\n\tconst actionsRef = useRef({ handleSave, handleCancel });\n\tactionsRef.current = { handleSave, handleCancel };\n\n\t// Native DOM keydown listener — prevents Glide from intercepting keys in portal context\n\tuseEffect(() => {\n\t\tconst el = keyContainerRef.current;\n\t\tif (!el) return;\n\t\tconst handler = (e: KeyboardEvent) => {\n\t\t\tconst { handleSave, handleCancel } = actionsRef.current;\n\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\thandleCancel();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.key === 'Enter' && !e.metaKey && !e.ctrlKey) {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\thandleSave();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ((e.key === 'Enter' && (e.metaKey || e.ctrlKey)) || (e.key === 's' && (e.metaKey || e.ctrlKey))) {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\thandleSave();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Stop Tab from reaching Glide\n\t\t\tif (e.key === 'Tab') {\n\t\t\t\te.stopPropagation();\n\t\t\t}\n\t\t};\n\t\tel.addEventListener('keydown', handler);\n\t\treturn () => el.removeEventListener('keydown', handler);\n\t}, []);\n\n\tconst trimmed = editingValue.trim();\n\tconst isValid = !trimmed || isValidInet(trimmed);\n\tconst inetType = trimmed ? getInetType(trimmed) : '';\n\n\treturn (\n\t\t<EditorFocusTrap\n\t\t\tonEscape={handleCancel}\n\t\t\tclassName={`bg-popover ${OVERLAY.sm} rounded-lg border p-2.5 shadow-lg`}\n\t\t>\n\t\t\t<div ref={keyContainerRef} className='flex flex-col gap-2'>\n\t\t\t\t<EditorHeader title={title} className='px-1' />\n\t\t\t\t{/* Input + inline type badge */}\n\t\t\t\t<div className='space-y-1.5'>\n\t\t\t\t\t<div className='relative'>\n\t\t\t\t\t\t<input\n\t\t\t\t\t\t\ttype='text'\n\t\t\t\t\t\t\tvalue={editingValue}\n\t\t\t\t\t\t\tonChange={handleInputChange}\n\t\t\t\t\t\t\tplaceholder='192.168.1.1 or 10.0.0.0/24'\n\t\t\t\t\t\t\tclassName='bg-muted/40 border-border/40 text-foreground w-full rounded-md border px-3 py-2 font-mono text-sm outline-none focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/35'\n\t\t\t\t\t\t\tautoFocus\n\t\t\t\t\t\t/>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t{/* Inline type indicator + validation */}\n\t\t\t\t\t<div className='flex items-center gap-2 px-0.5'>\n\t\t\t\t\t\t{validationError ? (\n\t\t\t\t\t\t\t<span className='text-destructive text-xs'>{validationError}</span>\n\t\t\t\t\t\t) : trimmed && isValid && inetType ? (\n\t\t\t\t\t\t\t<span className='text-muted-foreground text-xs tabular-nums'>{inetType}</span>\n\t\t\t\t\t\t) : trimmed && !isValid ? (\n\t\t\t\t\t\t\t<span className='text-destructive text-xs'>Invalid format</span>\n\t\t\t\t\t\t) : null}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n\t\t\t\t<EditorFooter\n\t\t\t\t\tclassName='px-1'\n\t\t\t\t\tonSave={handleSave}\n\t\t\t\t\tsaveShortcut='Enter'\n\t\t\t\t\tsaveBlockedReason={validationError || null}\n\t\t\t\t\tclear={editorClear(nullable, () => onFinishedEditing(null))}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","'use client';\n\n// Native inet editor — a thin EditorProps adapter that RE-HOSTS the (now value-\n// native) `InetEditor` verbatim. The UI (input, inline type badge, validation,\n// footer, OVERLAY.sm width, own EditorFocusTrap + native keydown listener) is\n// reused as-is; the contract maps directly to value-native EditorProps.\n//\n// The source reads its seed from the raw `value` and, on save, emits the raw\n// trimmed value — so the raw row value flows straight through:\n// `onFinishedEditing(next)` -> `onCommit(next)`, `onFinishedEditing(undefined)` ->\n// `onCancel()`.\n\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { InetEditor } from '../../grid/editors/inet-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function InetEditorDom({ value, column, colKey, onCommit, onCancel }: EditorProps) {\n\treturn (\n\t\t<div data-slot='inet-editor'>\n\t\t\t<InetEditor\n\t\t\t\tvalue={value}\n\t\t\t\ttitle={fieldLabel(column?.name ?? colKey)}\n\t\t\t\tnullable={Boolean(column?.nullable)}\n\t\t\t\tonFinishedEditing={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","import React, { useCallback, useState } from 'react';\n\nimport { Input } from '@constructive-io/ui/input';\nimport { Label } from '@constructive-io/ui/label';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { EditorFooter, EditorHeader, editorClear, modifierKeyLabel } from './editor-frame';\nimport { OVERLAY } from './overlay-presets';\n\ninterface IntervalValue {\n\tdays?: number;\n\thours?: number;\n\tminutes?: number;\n\tseconds?: number;\n}\n\ninterface IntervalEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n\t/** The field's readable name, shown as the title. */\n\ttitle?: string;\n\t/** The column takes no value, so Clear is offered. */\n\tnullable?: boolean;\n}\n\nconst INTERVAL_PATTERNS: { regex: RegExp; key: keyof IntervalValue }[] = [\n\t{ regex: /(\\d+)\\s*d(ays?)?/i, key: 'days' },\n\t{ regex: /(\\d+)\\s*h(ours?)?/i, key: 'hours' },\n\t{ regex: /(\\d+)\\s*m(in(utes?)?)?/i, key: 'minutes' },\n\t{ regex: /(\\d+)\\s*s(ec(onds?)?)?/i, key: 'seconds' },\n];\n\nfunction parseIntervalValue(data: string): IntervalValue {\n\tif (!data || typeof data !== 'string') {\n\t\treturn { days: 0, hours: 0, minutes: 0, seconds: 0 };\n\t}\n\n\ttry {\n\t\tconst parsed = JSON.parse(data);\n\t\tif (typeof parsed === 'object' && parsed !== null) {\n\t\t\treturn {\n\t\t\t\tdays: parsed.days || 0,\n\t\t\t\thours: parsed.hours || 0,\n\t\t\t\tminutes: parsed.minutes || 0,\n\t\t\t\tseconds: parsed.seconds || 0,\n\t\t\t};\n\t\t}\n\t} catch {\n\t\t// Try to parse text format like \"1d 2h 30m 45s\"\n\t\tconst interval: IntervalValue = { days: 0, hours: 0, minutes: 0, seconds: 0 };\n\n\t\tINTERVAL_PATTERNS.forEach(({ regex, key }) => {\n\t\t\tconst match = data.match(regex);\n\t\t\tif (match) {\n\t\t\t\tinterval[key] = parseInt(match[1], 10);\n\t\t\t}\n\t\t});\n\n\t\treturn interval;\n\t}\n\n\treturn { days: 0, hours: 0, minutes: 0, seconds: 0 };\n}\n\nfunction formatIntervalValue(interval: IntervalValue): string {\n\tconst parts = [];\n\tif (interval.days && interval.days > 0) parts.push(`${interval.days}d`);\n\tif (interval.hours && interval.hours > 0) parts.push(`${interval.hours}h`);\n\tif (interval.minutes && interval.minutes > 0) parts.push(`${interval.minutes}m`);\n\tif (interval.seconds && interval.seconds > 0) parts.push(`${interval.seconds}s`);\n\treturn parts.join(' ') || '0s';\n}\n\nexport const IntervalEditor: React.FC<IntervalEditorProps> = ({ value, onFinishedEditing, title = 'Duration', nullable = false }) => {\n\t// Extract current interval data from the raw value\n\tconst currentIntervalData = typeof value === 'string' ? value : '';\n\n\tconst [editingValue, setEditingValue] = useState<IntervalValue>(() => parseIntervalValue(currentIntervalData));\n\n\tconst handleSave = useCallback(() => {\n\t\tonFinishedEditing(JSON.stringify(editingValue));\n\t}, [editingValue, onFinishedEditing]);\n\n\tconst handleCancel = useCallback(() => {\n\t\tonFinishedEditing();\n\t}, [onFinishedEditing]);\n\n\tconst handleInputChange = useCallback((field: keyof IntervalValue, newValue: string) => {\n\t\tconst numValue = parseInt(newValue) || 0;\n\t\tsetEditingValue((prev) => ({\n\t\t\t...prev,\n\t\t\t[field]: Math.max(0, numValue), // Ensure non-negative values\n\t\t}));\n\t}, []);\n\n\t// Handle Ctrl+Enter to save\n\tconst handleEditorKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent) => {\n\t\t\tif (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {\n\t\t\t\te.preventDefault();\n\t\t\t\thandleSave();\n\t\t\t}\n\t\t},\n\t\t[handleSave],\n\t);\n\n\tconst previewText = formatIntervalValue(editingValue);\n\n\treturn (\n\t\t<EditorFocusTrap onEscape={handleCancel} className={`bg-popover flex ${OVERLAY.sm} flex-col gap-3 rounded-lg border p-3 shadow-lg`}>\n\t\t\t<div onKeyDown={handleEditorKeyDown} className='flex flex-col gap-3'>\n\t\t\t<EditorHeader title={title} />\n\n\t\t\t{/* Input Fields */}\n\t\t\t<div className='grid grid-cols-2 gap-3'>\n\t\t\t\t<div className='space-y-1'>\n\t\t\t\t\t<Label htmlFor='days' className='text-muted-foreground text-xs'>\n\t\t\t\t\t\tDays\n\t\t\t\t\t</Label>\n\t\t\t\t\t<Input\n\t\t\t\t\t\tid='days'\n\t\t\t\t\t\ttype='number'\n\t\t\t\t\t\tmin='0'\n\t\t\t\t\t\tvalue={editingValue.days || ''}\n\t\t\t\t\t\tonChange={(e) => handleInputChange('days', e.target.value)}\n\t\t\t\t\t\tclassName='h-8 text-sm'\n\t\t\t\t\t\tplaceholder='0'\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t\t<div className='space-y-1'>\n\t\t\t\t\t<Label htmlFor='hours' className='text-muted-foreground text-xs'>\n\t\t\t\t\t\tHours\n\t\t\t\t\t</Label>\n\t\t\t\t\t<Input\n\t\t\t\t\t\tid='hours'\n\t\t\t\t\t\ttype='number'\n\t\t\t\t\t\tmin='0'\n\t\t\t\t\t\tmax='23'\n\t\t\t\t\t\tvalue={editingValue.hours || ''}\n\t\t\t\t\t\tonChange={(e) => handleInputChange('hours', e.target.value)}\n\t\t\t\t\t\tclassName='h-8 text-sm'\n\t\t\t\t\t\tplaceholder='0'\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t\t<div className='space-y-1'>\n\t\t\t\t\t<Label htmlFor='minutes' className='text-muted-foreground text-xs'>\n\t\t\t\t\t\tMinutes\n\t\t\t\t\t</Label>\n\t\t\t\t\t<Input\n\t\t\t\t\t\tid='minutes'\n\t\t\t\t\t\ttype='number'\n\t\t\t\t\t\tmin='0'\n\t\t\t\t\t\tmax='59'\n\t\t\t\t\t\tvalue={editingValue.minutes || ''}\n\t\t\t\t\t\tonChange={(e) => handleInputChange('minutes', e.target.value)}\n\t\t\t\t\t\tclassName='h-8 text-sm'\n\t\t\t\t\t\tplaceholder='0'\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t\t<div className='space-y-1'>\n\t\t\t\t\t<Label htmlFor='seconds' className='text-muted-foreground text-xs'>\n\t\t\t\t\t\tSeconds\n\t\t\t\t\t</Label>\n\t\t\t\t\t<Input\n\t\t\t\t\t\tid='seconds'\n\t\t\t\t\t\ttype='number'\n\t\t\t\t\t\tmin='0'\n\t\t\t\t\t\tmax='59'\n\t\t\t\t\t\tvalue={editingValue.seconds || ''}\n\t\t\t\t\t\tonChange={(e) => handleInputChange('seconds', e.target.value)}\n\t\t\t\t\t\tclassName='h-8 text-sm'\n\t\t\t\t\t\tplaceholder='0'\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{/* Preview */}\n\t\t\t<div className='space-y-1'>\n\t\t\t\t<Label className='text-muted-foreground text-xs'>Preview</Label>\n\t\t\t\t<div className='bg-muted rounded px-3 py-2 font-mono text-sm'>{previewText}</div>\n\t\t\t</div>\n\n\t\t\t<EditorFooter\n\t\t\t\tonSave={handleSave}\n\t\t\t\tsaveShortcut={`${modifierKeyLabel()} Enter`}\n\t\t\t\tclear={editorClear(nullable, () => onFinishedEditing(null))}\n\t\t\t/>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","'use client';\n\n// Small form for values made of named fields: records (composite values), plain x/y\n// points and durations. The fields come from the column's write input\n// (`column.value.input.fields`), so the form matches what the API accepts. The whole\n// value is checked by `parseColumnInput` before it is committed; a problem shows in\n// the form and nothing is written.\n\nimport { useMemo, useState } from 'react';\n\nimport type { ColumnModel, InputFieldModel } from '@constructive-io/data';\nimport { Button } from '@constructive-io/ui/button';\n\nimport { EditorFooter, EditorHeader, editorClear } from '../../grid/editors/editor-frame';\nimport { OVERLAY_SM } from '../../grid/editors/overlay-presets';\nimport { parseColumnInput } from '../../cell-types/column-value';\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { cn } from '../../utils/cn';\nimport type { EditorProps } from './editor-props';\n\nfunction fieldText(value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\treturn typeof value === 'object' ? JSON.stringify(value) : String(value);\n}\n\nfunction seedFields(fields: readonly InputFieldModel[], value: unknown): Record<string, string> {\n\tconst record = value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : {};\n\treturn Object.fromEntries(fields.map((field) => [field.name, fieldText(record[field.name])]));\n}\n\n/** Plain-language hint for a field's value, from its standard GraphQL type. */\nfunction fieldHint(field: InputFieldModel): string | undefined {\n\tswitch (field.value.typeName) {\n\t\tcase 'Int':\n\t\tcase 'BigInt':\n\t\t\treturn 'Whole number';\n\t\tcase 'Float':\n\t\tcase 'BigFloat':\n\t\t\treturn 'Number';\n\t\tcase 'Date':\n\t\t\treturn 'Date, for example 2024-01-31';\n\t\tcase 'Datetime':\n\t\t\treturn 'Date and time';\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\ninterface RecordFormProps {\n\tcolumn: ColumnModel;\n\tvalue: unknown;\n\ttitle: string;\n\tonCommit: (next: unknown) => void;\n\t/** Field names in the order to show them; fields not listed follow in the API's order. */\n\tfieldOrder?: readonly string[];\n}\n\nfunction orderFields(fields: readonly InputFieldModel[], order: readonly string[] | undefined): readonly InputFieldModel[] {\n\tif (!order) return fields;\n\tconst rank = (name: string) => {\n\t\tconst index = order.indexOf(name);\n\t\treturn index === -1 ? order.length : index;\n\t};\n\treturn [...fields].sort((a, b) => rank(a.name) - rank(b.name));\n}\n\n/** The form itself, for a column whose write input lists its fields. */\nexport function RecordForm({ column, value, title, onCommit, fieldOrder }: RecordFormProps) {\n\tconst fields = useMemo(() => orderFields(column.value.input?.fields ?? [], fieldOrder), [column, fieldOrder]);\n\tconst [texts, setTexts] = useState<Record<string, string>>(() => seedFields(fields, value));\n\tconst [error, setError] = useState<string | null>(null);\n\n\tfunction save() {\n\t\tconst draft: Record<string, unknown> = {};\n\t\tfor (const field of fields) {\n\t\t\tconst text = texts[field.name] ?? '';\n\t\t\tdraft[field.name] = text.trim() === '' ? null : field.value.typeName === 'Boolean' ? text === 'true' : text;\n\t\t}\n\t\tconst parsed = parseColumnInput(column, draft);\n\t\tif (parsed.ok === false) {\n\t\t\tsetError(parsed.reason);\n\t\t\treturn;\n\t\t}\n\t\tonCommit(parsed.value);\n\t}\n\n\tfunction handleKeyDown(e: React.KeyboardEvent) {\n\t\tif (e.key === 'Enter' && !e.shiftKey) {\n\t\t\te.preventDefault();\n\t\t\tsave();\n\t\t}\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot='record-editor'\n\t\t\tclassName={cn('bg-popover flex flex-col gap-3 rounded-lg border p-3 shadow-lg', OVERLAY_SM)}\n\t\t\tonKeyDown={handleKeyDown}\n\t\t>\n\t\t\t<EditorHeader title={title} />\n\t\t\t<div className='grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-2'>\n\t\t\t\t{fields.map((field, index) => {\n\t\t\t\t\tconst id = `record-field-${column.name}-${field.name}`;\n\t\t\t\t\tconst hint = fieldHint(field);\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<div key={field.name} className='contents'>\n\t\t\t\t\t\t\t<label htmlFor={id} className='text-muted-foreground text-xs'>\n\t\t\t\t\t\t\t\t{fieldLabel(field.name)}\n\t\t\t\t\t\t\t\t{field.required ? <span aria-hidden> *</span> : null}\n\t\t\t\t\t\t\t</label>\n\t\t\t\t\t\t\t{field.value.typeName === 'Boolean' ? (\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\tid={id}\n\t\t\t\t\t\t\t\t\ttype='checkbox'\n\t\t\t\t\t\t\t\t\tchecked={texts[field.name] === 'true'}\n\t\t\t\t\t\t\t\t\tonChange={(e) => setTexts((current) => ({ ...current, [field.name]: String(e.target.checked) }))}\n\t\t\t\t\t\t\t\t\tclassName='justify-self-start'\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\tid={id}\n\t\t\t\t\t\t\t\t\tvalue={texts[field.name] ?? ''}\n\t\t\t\t\t\t\t\t\tplaceholder={hint}\n\t\t\t\t\t\t\t\t\tonChange={(e) => {\n\t\t\t\t\t\t\t\t\t\tsetError(null);\n\t\t\t\t\t\t\t\t\t\tsetTexts((current) => ({ ...current, [field.name]: e.target.value }));\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\tspellCheck={false}\n\t\t\t\t\t\t\t\t\tautoFocus={index === 0}\n\t\t\t\t\t\t\t\t\tclassName='bg-muted/40 border-border/40 min-w-0 rounded-md border px-2.5 py-1.5 text-sm outline-none focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/35'\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t);\n\t\t\t\t})}\n\t\t\t</div>\n\t\t\t{error ? (\n\t\t\t\t<p role='alert' className='text-destructive text-xs'>\n\t\t\t\t\t{error}\n\t\t\t\t</p>\n\t\t\t) : null}\n\t\t\t<EditorFooter onSave={save} saveShortcut='Enter' clear={editorClear(column.nullable, () => onCommit(null))} />\n\t\t</div>\n\t);\n}\n\n/** Overlay editor for record, point and duration cells. */\nexport function RecordEditorDom({ value, column, colKey, onCancel, onCommit }: EditorProps) {\n\tif (!column?.value.input?.fields?.length) {\n\t\t// Routing makes such a cell read-only; this guards a consumer that routes here anyway.\n\t\treturn (\n\t\t\t<div data-slot='record-editor' className={cn('bg-popover flex flex-col gap-2 rounded-lg border p-3 text-sm shadow-lg', OVERLAY_SM)}>\n\t\t\t\t<p>The parts of this value are not known, so it cannot be changed here.</p>\n\t\t\t\t<div className='flex justify-end'>\n\t\t\t\t\t<Button size='xs' variant='outline' onClick={onCancel}>\n\t\t\t\t\t\tClose\n\t\t\t\t\t</Button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t);\n\t}\n\treturn <RecordForm column={column} value={value} title={fieldLabel(column.name ?? colKey)} onCommit={onCommit} />;\n}\n","'use client';\n\n// Native interval editor. With a table-model column whose write input lists the\n// duration fields (years, months, days, hours, minutes, seconds), it renders the\n// shared field form, so every part of the duration round-trips as an object. Without\n// one (a host grid with no table model) it re-hosts the legacy `IntervalEditor`.\n\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { IntervalEditor } from '../../grid/editors/interval-editor';\nimport type { EditorProps } from './editor-props';\nimport { RecordForm } from './record-editor';\n\n/** A duration's parts, largest first, the way the cell reads (\"1y 2mo 3d 4h 5m 6.789s\"). */\nconst DURATION_ORDER = ['years', 'months', 'days', 'hours', 'minutes', 'seconds'] as const;\n\nexport function IntervalEditorDom({ value, column, colKey, onCommit, onCancel }: EditorProps) {\n\tif (column?.value.input?.fields?.length) {\n\t\treturn <RecordForm column={column} value={value} title={fieldLabel(column.name ?? colKey)} onCommit={onCommit} fieldOrder={DURATION_ORDER} />;\n\t}\n\treturn (\n\t\t<IntervalEditor\n\t\t\tvalue={value}\n\t\t\ttitle={fieldLabel(column?.name ?? colKey)}\n\t\t\tnullable={Boolean(column?.nullable)}\n\t\t\tonFinishedEditing={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t/>\n\t);\n}\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { EditorFooter, EditorHeader, editorClear, modifierKeyLabel } from './editor-frame';\nimport { OVERLAY } from './overlay-presets';\n\n\nconst JSON_HIGHLIGHT_STYLES = `\n.json-highlight .jh-key { color: var(--color-foreground); }\n.json-highlight .jh-str { color: oklch(0.72 0.14 168); }\n.json-highlight .jh-num { color: oklch(0.7 0.14 250); }\n.json-highlight .jh-bool { color: oklch(0.75 0.14 55); }\n.json-highlight .jh-punct { color: var(--color-muted-foreground); }\n@media (prefers-color-scheme: light) {\n\t.json-highlight .jh-str { color: oklch(0.5 0.16 168); }\n\t.json-highlight .jh-num { color: oklch(0.48 0.16 250); }\n\t.json-highlight .jh-bool { color: oklch(0.55 0.16 55); }\n}\n`;\n\n// Zero-dependency JSON syntax highlighter using regex tokenisation.\n// Returns HTML string with spans for: strings, numbers, booleans/null, keys, punctuation.\nfunction highlightJson(json: string): string {\n\t// Escape HTML entities first\n\tconst escaped = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\n\treturn escaped.replace(\n\t\t// Match JSON tokens: strings, numbers, booleans, null, structural chars\n\t\t/(\"(?:[^\"\\\\]|\\\\.)*\")\\s*(?=:)|(\"(?:[^\"\\\\]|\\\\.)*\")|(-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)\\b|(true|false|null)\\b|([{}[\\]:,])/g,\n\t\t(match, key, str, num, bool, punct) => {\n\t\t\tif (key !== undefined) return `<span class=\"jh-key\">${key}</span>`;\n\t\t\tif (str !== undefined) return `<span class=\"jh-str\">${str}</span>`;\n\t\t\tif (num !== undefined) return `<span class=\"jh-num\">${num}</span>`;\n\t\t\tif (bool !== undefined) return `<span class=\"jh-bool\">${bool}</span>`;\n\t\t\tif (punct !== undefined) return `<span class=\"jh-punct\">${punct}</span>`;\n\t\t\treturn match;\n\t\t},\n\t);\n}\n\ntype Props = {\n\tvalue: unknown;\n\tonChange: (next: unknown) => void;\n\tonFinished: (next?: unknown) => void;\n\t/** The field's readable name, shown as the title. */\n\ttitle?: string;\n\t/** The column takes no value, so Clear is offered. */\n\tnullable?: boolean;\n};\n\nexport function JsonEditor({ value, onChange, onFinished, title = 'JSON value', nullable = false }: Props) {\n\tconst [text, setText] = useState(() => (typeof value === 'string' ? value : JSON.stringify(value, null, 2)));\n\tconst textareaRef = useRef<HTMLTextAreaElement>(null);\n\tconst preRef = useRef<HTMLPreElement>(null);\n\tconst keyContainerRef = useRef<HTMLDivElement>(null);\n\n\tconst { parsed, valid } = useMemo(() => {\n\t\t// An empty text is a valid \"no value\".\n\t\tif (text.trim() === '') return { parsed: null, valid: true };\n\t\ttry {\n\t\t\treturn { parsed: JSON.parse(text), valid: true };\n\t\t} catch {\n\t\t\treturn { parsed: text, valid: false };\n\t\t}\n\t}, [text]);\n\n\tconst handleChange = useCallback(\n\t\t(e: React.ChangeEvent<HTMLTextAreaElement>) => {\n\t\t\tconst next = e.target.value;\n\t\t\tsetText(next);\n\t\t\ttry {\n\t\t\t\tonChange(JSON.parse(next));\n\t\t\t} catch {\n\t\t\t\t// invalid JSON — don't propagate\n\t\t\t}\n\t\t},\n\t\t[onChange],\n\t);\n\n\tconst handleCancel = useCallback(() => onFinished(undefined), [onFinished]);\n\tconst handleSave = useCallback(() => {\n\t\tif (valid) onFinished(parsed);\n\t}, [onFinished, parsed, valid]);\n\n\t// Sync scroll between textarea and highlighted pre\n\tconst handleScroll = useCallback(() => {\n\t\tconst ta = textareaRef.current;\n\t\tconst pre = preRef.current;\n\t\tif (ta && pre) {\n\t\t\tpre.scrollTop = ta.scrollTop;\n\t\t\tpre.scrollLeft = ta.scrollLeft;\n\t\t}\n\t}, []);\n\n\t// Refs for native key handler\n\tconst actionsRef = useRef({ handleSave, handleCancel });\n\tactionsRef.current = { handleSave, handleCancel };\n\n\t// Native DOM keydown listener — prevents Glide from intercepting keys\n\tuseEffect(() => {\n\t\tconst el = keyContainerRef.current;\n\t\tif (!el) return;\n\t\tconst handler = (e: KeyboardEvent) => {\n\t\t\tconst { handleSave, handleCancel } = actionsRef.current;\n\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\thandleCancel();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ((e.key === 'Enter' && (e.metaKey || e.ctrlKey)) || (e.key === 's' && (e.metaKey || e.ctrlKey))) {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\thandleSave();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Stop Tab from reaching Glide (allow default tab-indent behavior)\n\t\t\tif (e.key === 'Tab') {\n\t\t\t\te.stopPropagation();\n\t\t\t\t// Insert tab character at cursor\n\t\t\t\te.preventDefault();\n\t\t\t\tconst ta = textareaRef.current;\n\t\t\t\tif (ta) {\n\t\t\t\t\tconst start = ta.selectionStart;\n\t\t\t\t\tconst end = ta.selectionEnd;\n\t\t\t\t\tconst val = ta.value;\n\t\t\t\t\tconst newVal = val.substring(0, start) + ' ' + val.substring(end);\n\t\t\t\t\tta.value = newVal;\n\t\t\t\t\tta.selectionStart = ta.selectionEnd = start + 2;\n\t\t\t\t\tta.dispatchEvent(new Event('input', { bubbles: true }));\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tel.addEventListener('keydown', handler);\n\t\treturn () => el.removeEventListener('keydown', handler);\n\t}, []);\n\n\t// Memoize highlighted HTML\n\tconst highlighted = useMemo(() => highlightJson(text), [text]);\n\n\n\treturn (\n\t\t<EditorFocusTrap onEscape={handleCancel} className={`bg-popover ${OVERLAY.lg} rounded-lg border p-2.5 shadow-lg`}>\n\t\t\t<div ref={keyContainerRef} className='flex flex-col gap-2'>\n\t\t\t\t<EditorHeader title={title} className='px-1' />\n\t\t\t\t{/* Editor area — grid overlay technique for matched sizing */}\n\t\t\t\t<div\n\t\t\t\t\tclassName='bg-muted/40 grid cursor-text overflow-hidden rounded-md border border-border/40'\n\t\t\t\t\tstyle={{ height: 300 }}\n\t\t\t\t\tonClick={() => textareaRef.current?.focus()}\n\t\t\t\t>\n\t\t\t\t\t{/* Both layers occupy the same grid cell */}\n\t\t\t\t\t<pre\n\t\t\t\t\t\tref={preRef}\n\t\t\t\t\t\tclassName='json-highlight pointer-events-none col-start-1 row-start-1 m-0 overflow-hidden whitespace-pre-wrap break-words bg-transparent p-3 font-mono text-sm leading-relaxed [word-break:break-all]'\n\t\t\t\t\t\taria-hidden='true'\n\t\t\t\t\t\tdangerouslySetInnerHTML={{ __html: highlighted + '\\n' }}\n\t\t\t\t\t/>\n\t\t\t\t\t<textarea\n\t\t\t\t\t\tref={textareaRef}\n\t\t\t\t\t\tvalue={text}\n\t\t\t\t\t\tonChange={handleChange}\n\t\t\t\t\t\tonScroll={handleScroll}\n\t\t\t\t\t\tspellCheck={false}\n\t\t\t\t\t\tclassName='col-start-1 row-start-1 m-0 resize-none overflow-auto whitespace-pre-wrap break-words bg-transparent p-3 font-mono text-sm leading-relaxed text-transparent outline-none [word-break:break-all]'\n\t\t\t\t\t\tstyle={{ caretColor: 'var(--color-foreground)' }}\n\t\t\t\t\t\tautoFocus\n\t\t\t\t\t/>\n\t\t\t\t</div>\n\n\t\t\t\t<EditorFooter\n\t\t\t\t\tclassName='px-1'\n\t\t\t\t\tonSave={handleSave}\n\t\t\t\t\tsaveShortcut={`${modifierKeyLabel()} Enter`}\n\t\t\t\t\tsaveBlockedReason={valid ? null : 'Enter valid JSON.'}\n\t\t\t\t\tstatus={valid ? null : <span className='text-destructive'>Not valid JSON</span>}\n\t\t\t\t\tclear={editorClear(nullable, () => onFinished(null))}\n\t\t\t\t/>\n\n\t\t\t\t{/* Syntax highlighting styles — uses CSS variables for theme compatibility */}\n\t\t\t\t<style>{JSON_HIGHLIGHT_STYLES}</style>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n}\n","'use client';\n\n// Native JSON editor — a thin EditorProps adapter that RE-HOSTS the value-native\n// `JsonEditor` ({ value, onChange, onFinished }). The editor edits JSON text: the\n// cell value (any JSON value, including a string or a number at the top level) is\n// seeded as its JSON text, and an empty text clears the cell. `onFinished(next)` ->\n// `onCommit(next)`, `onFinished(undefined)` -> `onCancel()`.\n\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { JsonEditor } from '../../grid/editors/json-editor';\nimport type { EditorProps } from './editor-props';\n\n/** JSON text of the stored value; '' for no value. */\nfunction seedText(value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\treturn JSON.stringify(value, null, 2) ?? '';\n}\n\nexport function JsonEditorDom({ value, column, colKey, onCommit, onCancel }: EditorProps) {\n\treturn (\n\t\t<JsonEditor\n\t\t\tvalue={seedText(value)}\n\t\t\ttitle={fieldLabel(column?.name ?? colKey)}\n\t\t\tnullable={Boolean(column?.nullable)}\n\t\t\tonChange={() => {}}\n\t\t\tonFinished={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t/>\n\t);\n}\n","'use client';\n\n// Native number editor — value-native single-line numeric <input> for the\n// NUMBER_TYPES family (number/integer/smallint/decimal/currency/percentage/\n// rating). Sibling of TextEditor: dependency-light (no glide cell types), the\n// OverlayManager hosts the focus-trap + error-guard + width sizing, so this is\n// just the input + a Save affordance. Glide-free by construction.\n//\n// VALUE editor (no server mutation): seeds from EditorProps.value, parses the\n// text on commit and pushes a `number` (or `null` for empty) down the glide\n// value-commit path (onCommit). Non-numeric text is rejected — Save is disabled\n// and Enter is a no-op while the field cannot parse — so the last committed\n// value is never clobbered by garbage.\n\nimport { useRef, useState } from 'react';\n\nimport type { ColumnModel } from '@constructive-io/data';\nimport { Button } from '@constructive-io/ui/button';\n\nimport { parseColumnInput, type ColumnInputResult } from '../../cell-types/column-value';\n\nimport { OVERLAY_SM } from '../../grid/editors/overlay-presets';\nimport { cn } from '../../utils/cn';\nimport type { EditorProps } from './editor-props';\n\n/** Seed the input text from the raw value (number or numeric string), else ''. */\nfunction seedText(value: unknown): string {\n\tif (value === null || value === undefined) return '';\n\tif (typeof value === 'number') return Number.isFinite(value) ? String(value) : '';\n\treturn String(value);\n}\n\n/**\n * Parse the input text. With a table-model column its rules decide (whole numbers and\n * exact decimals stay exact strings); without one, '' -> null, else a finite number.\n */\nfunction parseValue(text: string, column: ColumnModel | null | undefined): ColumnInputResult {\n\tif (column) return parseColumnInput(column, text, { fromText: true });\n\tconst trimmed = text.trim();\n\tif (trimmed === '') return { ok: true, value: null };\n\tconst n = Number(trimmed);\n\treturn Number.isFinite(n) ? { ok: true, value: n } : { ok: false, reason: 'Enter a number.' };\n}\n\nexport function NumberEditorDom({ value, initialText, colKey, fieldMeta, column, onCommit, onCancel }: EditorProps) {\n\t// Type-to-edit seed (OVERWRITE): a typed printable char replaces the cell value; the\n\t// parse/canSave guard below still rejects non-numeric content (e.g. a typed letter).\n\tconst [text, setText] = useState(() => (initialText != null ? initialText : seedText(value)));\n\t// COMMIT-ON-BLUR GUARD (Stage B): an Escape-cancel also blurs the input as it unmounts —\n\t// `escapedRef` tells the blur handler to skip its commit so Escape never double-fires.\n\tconst escapedRef = useRef(false);\n\n\tconst parsed = parseValue(text, column);\n\t// Save is blocked while the text does not fit the column; an empty field clears it.\n\tconst canSave = parsed.ok;\n\n\tfunction commit() {\n\t\tif (!parsed.ok) return;\n\t\tonCommit(parsed.value);\n\t}\n\n\tfunction handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {\n\t\tif (e.key === 'Enter') {\n\t\t\te.preventDefault();\n\t\t\tcommit();\n\t\t\treturn;\n\t\t}\n\t\tif (e.key === 'Escape') {\n\t\t\te.preventDefault();\n\t\t\tescapedRef.current = true;\n\t\t\tonCancel();\n\t\t}\n\t}\n\n\t// Commit-on-click-away: commit only when focus genuinely leaves the whole overlay (the\n\t// focus-trap `[role=\"dialog\"]`) — testing the element focus actually moved to (relatedTarget,\n\t// else post-blur document.activeElement) against the dialog root, NOT the slot. This avoids a\n\t// spurious commit on the open-time focus churn (focus momentarily lands on the trap container,\n\t// inside the dialog), while the in-overlay Save button (focus stays inside) does NOT\n\t// double-commit. Non-numeric garbage is still rejected (`commit()` no-ops when !canSave,\n\t// mirroring the Enter no-op). Skipped right after an Escape-cancel.\n\tfunction handleBlur(e: React.FocusEvent<HTMLInputElement>) {\n\t\tif (escapedRef.current) return;\n\t\t// Containment root: the focus-trap dialog in production (so the trap container counts as\n\t\t// \"inside\"); the editor slot when rendered bare (tests). Use whichever encloses the input.\n\t\tconst root = e.currentTarget.closest('[role=\"dialog\"]') ?? e.currentTarget.closest('[data-slot=\"number-editor\"]');\n\t\tconst landed = (e.relatedTarget as Node | null) ?? document.activeElement;\n\t\tif (root && landed && root.contains(landed)) return;\n\t\tcommit();\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot='number-editor'\n\t\t\tclassName={cn('bg-popover flex flex-wrap items-center gap-2 rounded-lg border p-2.5 shadow-lg', OVERLAY_SM)}\n\t\t>\n\t\t\t<input\n\t\t\t\taria-label={`Edit ${fieldMeta?.name ?? colKey}`}\n\t\t\t\tvalue={text}\n\t\t\t\tonChange={(e) => setText(e.target.value)}\n\t\t\t\tonKeyDown={handleKeyDown}\n\t\t\t\tonBlur={handleBlur}\n\t\t\t\tinputMode='decimal'\n\t\t\t\tspellCheck={false}\n\t\t\t\tclassName='bg-muted/40 border-border/40 min-w-0 flex-1 rounded-md border px-2.5 py-1.5 font-sans text-sm tabular-nums outline-none focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/35'\n\t\t\t\tautoFocus\n\t\t\t/>\n\t\t\t<Button onClick={commit} disabled={!canSave} size='xs' variant='default' className='shrink-0'>\n\t\t\t\tSave\n\t\t\t</Button>\n\t\t\t{parsed.ok === false && text.trim() !== '' ? (\n\t\t\t\t<p role='alert' className='text-destructive basis-full text-xs'>\n\t\t\t\t\t{parsed.reason}\n\t\t\t\t</p>\n\t\t\t) : null}\n\t\t</div>\n\t);\n}\n\n// Opt into commit-on-click-away (Stage B) — see TextEditor.commitsOnBlur. The OverlayManager\n// reads this to pick `dismissMode='commit'` (blur → onBlur commits) instead of cancelling.\nNumberEditorDom.commitsOnBlur = true as const;\n","'use client';\n\n// Range editor: a start and an end, each with a value, whether it is included, and\n// whether that end is open (no limit). The bound values are checked by the column's\n// own rules (`parseColumnInput`), so a whole-number range takes whole numbers and a\n// date range takes dates. The API cannot tell an empty range from one with both ends\n// open, so both ends open is shown as \"any value\".\n//\n// Date and date-time ranges use the browser's date and date-time fields, stacked so\n// each shows its whole value; a date-time field shows the local time, as the date\n// editor does. A bound the user does not change is written back exactly as stored.\n\nimport { useState } from 'react';\n\nimport type { ColumnModel } from '@constructive-io/data';\n\nimport { EditorFooter, EditorHeader, editorClear } from '../../grid/editors/editor-frame';\nimport { OVERLAY_SM } from '../../grid/editors/overlay-presets';\nimport { parseColumnInput } from '../../cell-types/column-value';\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { localInputToTimestamp, timestampToLocalInput } from '../../cell-types/timestamp-text';\nimport { cn } from '../../utils/cn';\nimport type { EditorProps } from './editor-props';\n\n/** How a bound's value is entered: a date field, a date-time field, or text (numbers). */\ntype BoundField = 'date' | 'datetime' | 'text';\n\n/** The bound value's type, from the range input's `start.value` field. */\nfunction boundField(column: ColumnModel | null | undefined): BoundField {\n\tconst start = column?.value.input?.fields?.find((field) => field.name === 'start');\n\tconst typeName = start?.value.fields?.find((field) => field.name === 'value')?.value.typeName;\n\tif (typeName === 'Date') return 'date';\n\tif (typeName === 'Datetime') return 'datetime';\n\treturn 'text';\n}\n\ninterface BoundDraft {\n\t/** The value as it is written: the stored text until the user changes it. */\n\ttext: string;\n\tinclusive: boolean;\n\topen: boolean;\n}\n\nfunction seedBound(bound: unknown, defaultInclusive: boolean): BoundDraft {\n\tif (!bound || typeof bound !== 'object') return { text: '', inclusive: defaultInclusive, open: true };\n\tconst record = bound as { value?: unknown; inclusive?: unknown };\n\tif (record.value === null || record.value === undefined) return { text: '', inclusive: defaultInclusive, open: true };\n\treturn { text: String(record.value), inclusive: record.inclusive !== false, open: false };\n}\n\nfunction seedRange(value: unknown): { start: BoundDraft; end: BoundDraft } {\n\tconst record = value && typeof value === 'object' ? (value as { start?: unknown; end?: unknown }) : {};\n\treturn { start: seedBound(record.start, true), end: seedBound(record.end, false) };\n}\n\nconst INPUT =\n\t'bg-muted/40 border-border/40 w-full min-w-0 rounded-md border px-2.5 py-1.5 text-sm tabular-nums outline-none disabled:opacity-50 focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/35';\n\ninterface BoundFieldsProps {\n\tid: string;\n\tlabel: string;\n\tfield: BoundField;\n\tbound: BoundDraft;\n\tonChange: (next: BoundDraft) => void;\n\tautoFocus?: boolean;\n}\n\nfunction BoundFields({ id, label, field, bound, onChange, autoFocus }: BoundFieldsProps) {\n\tconst common = {\n\t\tid: `${id}-value`,\n\t\t'aria-label': `${label} value`,\n\t\tdisabled: bound.open,\n\t\tautoFocus: autoFocus && !bound.open,\n\t\tclassName: INPUT,\n\t};\n\treturn (\n\t\t<fieldset className='flex min-w-0 flex-col gap-1.5'>\n\t\t\t<legend className='text-muted-foreground mb-1 text-xs'>{label}</legend>\n\t\t\t{field === 'date' ? (\n\t\t\t\t<input {...common} type='date' value={bound.text.slice(0, 10)} onChange={(e) => onChange({ ...bound, text: e.target.value })} />\n\t\t\t) : field === 'datetime' ? (\n\t\t\t\t<input\n\t\t\t\t\t{...common}\n\t\t\t\t\ttype='datetime-local'\n\t\t\t\t\tstep='1'\n\t\t\t\t\tvalue={timestampToLocalInput(bound.text)}\n\t\t\t\t\tonChange={(e) => onChange({ ...bound, text: e.target.value ? localInputToTimestamp(e.target.value) : '' })}\n\t\t\t\t/>\n\t\t\t) : (\n\t\t\t\t<input {...common} value={bound.text} spellCheck={false} onChange={(e) => onChange({ ...bound, text: e.target.value })} />\n\t\t\t)}\n\t\t\t<div className='flex items-center gap-3 text-xs'>\n\t\t\t\t<label className='flex items-center gap-1.5'>\n\t\t\t\t\t<input\n\t\t\t\t\t\ttype='checkbox'\n\t\t\t\t\t\tchecked={bound.inclusive}\n\t\t\t\t\t\tdisabled={bound.open}\n\t\t\t\t\t\tonChange={(e) => onChange({ ...bound, inclusive: e.target.checked })}\n\t\t\t\t\t/>\n\t\t\t\t\tIncluded\n\t\t\t\t</label>\n\t\t\t\t<label className='flex items-center gap-1.5'>\n\t\t\t\t\t<input type='checkbox' checked={bound.open} onChange={(e) => onChange({ ...bound, open: e.target.checked })} />\n\t\t\t\t\tNo limit\n\t\t\t\t</label>\n\t\t\t</div>\n\t\t</fieldset>\n\t);\n}\n\nexport function RangeEditorDom({ value, column, colKey, onCommit }: EditorProps) {\n\tconst [range, setRange] = useState(() => seedRange(value));\n\tconst [error, setError] = useState<string | null>(null);\n\tconst id = `range-${column?.name ?? colKey}`;\n\tconst field = boundField(column);\n\n\tfunction save() {\n\t\tif (!column) return;\n\t\tconst bound = (draft: BoundDraft) => (draft.open ? null : { value: draft.text, inclusive: draft.inclusive });\n\t\tconst parsed = parseColumnInput(column, { start: bound(range.start), end: bound(range.end) });\n\t\tif (parsed.ok === false) {\n\t\t\tsetError(parsed.reason);\n\t\t\treturn;\n\t\t}\n\t\tonCommit(parsed.value);\n\t}\n\n\tfunction update(side: 'start' | 'end', next: BoundDraft) {\n\t\tsetError(null);\n\t\tsetRange((current) => ({ ...current, [side]: next }));\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot='range-editor'\n\t\t\tclassName={cn('bg-popover flex flex-col gap-3 rounded-lg border p-3 shadow-lg', OVERLAY_SM)}\n\t\t\tonKeyDown={(e) => {\n\t\t\t\tif (e.key === 'Enter') {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tsave();\n\t\t\t\t}\n\t\t\t}}\n\t\t>\n\t\t\t<EditorHeader title={fieldLabel(column?.name ?? colKey)} />\n\t\t\t{/* Numbers fit side by side; date and date-time fields need the full width to show their value. */}\n\t\t\t<div className={cn('grid gap-3', field === 'text' ? 'grid-cols-2' : 'grid-cols-1')}>\n\t\t\t\t<BoundFields id={`${id}-start`} label='Start' field={field} bound={range.start} onChange={(next) => update('start', next)} autoFocus />\n\t\t\t\t<BoundFields id={`${id}-end`} label='End' field={field} bound={range.end} onChange={(next) => update('end', next)} />\n\t\t\t</div>\n\t\t\t{range.start.open && range.end.open ? (\n\t\t\t\t<p className='text-muted-foreground text-xs'>Both ends open means any value.</p>\n\t\t\t) : null}\n\t\t\t{error ? (\n\t\t\t\t<p role='alert' className='text-destructive text-xs'>\n\t\t\t\t\t{error}\n\t\t\t\t</p>\n\t\t\t) : null}\n\t\t\t<EditorFooter\n\t\t\t\tonSave={save}\n\t\t\t\tsaveShortcut='Enter'\n\t\t\t\tsaveBlockedReason={column ? null : 'This range cannot be changed here.'}\n\t\t\t\tclear={editorClear(column?.nullable, () => onCommit(null))}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","// Timestamp text as the API sends it (\"2024-01-01T00:00:00.000000+00:00\") and the value\n// a `datetime-local` field takes, in both directions. (How timestamps read in cells is\n// `date-time-format.ts`.)\n\nconst TIMESTAMP_RE = /^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}:\\d{2})(?::(\\d{2})(\\.\\d+)?)?(Z|[+-]\\d{2}(?::?\\d{2})?)?$/;\n\nfunction pad2(value: number): string {\n\treturn String(value).padStart(2, '0');\n}\n\n/**\n * The value a `datetime-local` field shows for stored timestamp text: the local wall\n * time when the text has an offset (the same reading the date editor uses), otherwise\n * the stored wall time. Seconds are kept; fractions are not.\n */\nexport function timestampToLocalInput(text: string): string {\n\tconst match = TIMESTAMP_RE.exec(text);\n\tif (!match) return '';\n\tconst [, date, hoursMinutes, seconds = '00', , zone] = match;\n\tif (!zone) return `${date}T${hoursMinutes}:${seconds}`;\n\tconst instant = new Date(text.replace(' ', 'T').replace(/(\\.\\d{3})\\d+/, '$1'));\n\tif (Number.isNaN(instant.getTime())) return `${date}T${hoursMinutes}:${seconds}`;\n\treturn `${instant.getFullYear()}-${pad2(instant.getMonth() + 1)}-${pad2(instant.getDate())}T${pad2(instant.getHours())}:${pad2(\n\t\tinstant.getMinutes(),\n\t)}:${pad2(instant.getSeconds())}`;\n}\n\n/**\n * Timestamp text for what a `datetime-local` field holds: the wall time with this\n * browser's offset for that moment (\"2024-01-01T09:30:00+07:00\"). A column with a time\n * zone stores that instant; one without keeps the wall time as typed.\n */\nexport function localInputToTimestamp(local: string): string {\n\tconst withSeconds = /T\\d{2}:\\d{2}$/.test(local) ? `${local}:00` : local;\n\tconst instant = new Date(withSeconds);\n\tif (Number.isNaN(instant.getTime())) return withSeconds;\n\tconst offsetMinutes = -instant.getTimezoneOffset();\n\tconst sign = offsetMinutes >= 0 ? '+' : '-';\n\tconst absolute = Math.abs(offsetMinutes);\n\treturn `${withSeconds}${sign}${pad2(Math.floor(absolute / 60))}:${pad2(absolute % 60)}`;\n}\n","'use client';\n\n/**\n * The grid's relation cell editor: an overlay around the shared relation\n * editor (`relations/use-relation-editor.ts`, `relations/relation-editor-body.tsx`).\n * Save writes the pending choices and closes; a draft row keeps a belongsTo\n * choice locally through `onCommitPatch`; a failure keeps the overlay open\n * with the server's message.\n */\nimport { useCallback, useContext, type KeyboardEvent } from 'react';\n\nimport type { RelationModel, TableModel } from '@constructive-io/data';\n\nimport { relationLabelIn } from '../../cell-types/field-label';\nimport type { SheetsRowIdentifier } from '../../row-identity';\nimport type { RecordValues } from '../../relations/relation-keys';\nimport { RelationEditorBody } from '../../relations/relation-editor-body';\nimport { useRelationEditor } from '../../relations/use-relation-editor';\nimport { useOptionalFeedback } from '../feedback/feedback-context';\nimport { EditorFooter, EditorHeader, modifierKeyLabel, type EditorClear } from './editor-frame';\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\nimport { OverlayMeasureContext } from './overlay-viewport-guard';\n\nexport interface RelationEditorProps {\n\trelation: RelationModel;\n\t/** The grid table. */\n\ttable: TableModel;\n\t/** The row being edited, or null when the grid has not handed it over. */\n\trow: RecordValues | null;\n\t/** The server row's primary key, or null for a draft row or a row that cannot be identified. */\n\trowIdentifier: SheetsRowIdentifier | null;\n\tisDraft: boolean;\n\t/** The value of the relation field on the row. */\n\tvalue: unknown;\n\t/** Patch the grid row after a belongsTo change (draft value or the saved link). Closes the editor. */\n\tonCommitPatch?: (patch: Record<string, unknown>) => void;\n\t/** Ask the grid to refetch after an out-of-band write. */\n\tonInvalidateData?: () => void;\n\t/** Close without writing. */\n\tonClose: () => void;\n}\n\nexport function RelationEditor({\n\trelation,\n\ttable,\n\trow,\n\trowIdentifier,\n\tisDraft,\n\tvalue,\n\tonCommitPatch,\n\tonInvalidateData,\n\tonClose,\n}: RelationEditorProps) {\n\tconst editor = useRelationEditor({ relation, table, row, rowIdentifier, isDraft, value, onInvalidateData });\n\tconst { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);\n\tconst { editable, saving, save } = editor;\n\t// A saved link reports to the grid's save status; a failure stays in the editor, where it is read.\n\tconst noteWrite = useOptionalFeedback()?.noteWrite;\n\n\tconst handleSave = useCallback(async (options?: { clear?: boolean }) => {\n\t\tconst result = await save(options);\n\t\tif (result.status === 'unchanged') onClose();\n\t\telse if (result.status === 'draft') onCommitPatch?.(result.patch);\n\t\telse if (result.status === 'saved') {\n\t\t\tnoteWrite?.('update', 'success', 'Saved');\n\t\t\tif (result.patch && onCommitPatch) onCommitPatch(result.patch);\n\t\t\telse onClose();\n\t\t}\n\t}, [noteWrite, onClose, onCommitPatch, save]);\n\n\tconst handleKeyDown = useCallback(\n\t\t(event: KeyboardEvent) => {\n\t\t\tif (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {\n\t\t\t\tevent.preventDefault();\n\t\t\t\tif (editable) void handleSave();\n\t\t\t}\n\t\t},\n\t\t[editable, handleSave],\n\t);\n\n\tconst isList = relation.kind === 'hasMany' || relation.kind === 'manyToMany';\n\tconst hasLink = editor.current.length > 0;\n\tconst saveBlockedReason = saving\n\t\t? 'Saving…'\n\t\t: editor.linkPending\n\t\t\t? 'Loading the linked table…'\n\t\t\t: !editable\n\t\t\t\t? editor.blockedReason ?? editor.capability.linkReason\n\t\t\t\t: null;\n\t// To-one relations clear their link here; a to-many relation removes links one by one in the list.\n\t// Reasons the model gives at open come first, so the button does not change its reason after loading.\n\tconst clear: EditorClear | null = isList\n\t\t? null\n\t\t: !hasLink\n\t\t\t? { reason: 'There is no link to remove.' }\n\t\t\t: !relation.unlinkable\n\t\t\t\t? { reason: relation.reason ?? 'This link cannot be removed.' }\n\t\t\t\t: editor.linkPending\n\t\t\t\t\t? { reason: 'Loading the linked table…' }\n\t\t\t\t\t: editable && editor.capability.canUnlink\n\t\t\t\t\t\t? { onClear: () => void handleSave({ clear: true }) }\n\t\t\t\t\t\t: { reason: editor.capability.unlinkReason ?? 'This link cannot be removed.' };\n\n\treturn (\n\t\t<EditorFocusTrap\n\t\t\tonEscape={onClose}\n\t\t\tonKeyDown={handleKeyDown}\n\t\t\t// A fixed width: the overlay sizes to its content, and labels that load later must not widen it.\n\t\t\t// No padding of its own: header, body and footer carry the shared editor insets and dividers.\n\t\t\tclassName={`bg-popover flex ${OVERLAY.md} w-[400px] flex-col gap-0 overflow-hidden rounded-lg border p-0 shadow-lg`}\n\t\t\t// Never taller than the room the overlay has on its side of the cell: the body scrolls,\n\t\t\t// the header and the footer (Clear, Save) stay in view.\n\t\t\tstyle={overlayMaxHeight > 0 ? { maxHeight: overlayMaxHeight } : undefined}\n\t\t>\n\t\t\t{/* The shared header (48px with its insets): readable title, the raw field name as its tooltip. */}\n\t\t\t<EditorHeader\n\t\t\t\ttitle={relationLabelIn(table, relation)}\n\t\t\t\ttitleHint={relation.fieldName}\n\t\t\t\tchip={isList ? `Linked ${relation.targetName} records` : `One linked ${relation.targetName} record`}\n\t\t\t\tclassName='shrink-0 px-3 pt-3 pb-2'\n\t\t\t/>\n\n\t\t\t<div className='flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto overscroll-contain border-t p-3'>\n\t\t\t\t<RelationEditorBody editor={editor} />\n\t\t\t</div>\n\n\t\t\t{/* The shared editor footer: Escape or a press outside cancels; Clear (to-one only) then\n\t\t\t Save. Shown whenever the model lets this relation be edited, from the first frame. */}\n\t\t\t{relation.editable ? (\n\t\t\t\t<EditorFooter\n\t\t\t\t\tonSave={() => void handleSave()}\n\t\t\t\t\tsaveShortcut={`${modifierKeyLabel()} Enter`}\n\t\t\t\t\tsaveBlockedReason={saveBlockedReason}\n\t\t\t\t\tclear={clear}\n\t\t\t\t\tclassName='shrink-0 px-3 pb-2'\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t</EditorFocusTrap>\n\t);\n}\n","'use client';\n\n/**\n * The content of a relation editor, shared by the grid's cell editor and the\n * record panel's relation section: the model's reason when nothing can change,\n * the current links, \"Open {table}\" for links that need more fields, the\n * picker, the create form, messages, and the \"Create new\" / \"Clear link\"\n * actions. The host adds its own header and its Save/Cancel footer.\n */\nimport { useState, type RefObject } from 'react';\nimport { ExternalLink, Link, Plus } from 'lucide-react';\n\nimport { Button } from '@constructive-io/ui/button';\n\nimport { RelationCreateForm } from './relation-create-form';\nimport { RelationLinkList } from './relation-link-list';\nimport { RelationPicker } from './relation-picker';\nimport type { RelationEditor } from './use-relation-editor';\n\nexport interface RelationEditorBodyProps {\n\teditor: RelationEditor;\n\t/**\n\t * 'overlay' (the cell editor): the picker shows at once. 'section' (a record panel\n\t * listing several relations): the picker appears after \"Add link\" (\"Change link\" for a\n\t * to-one relation that has one), and the host's heading carries the link count. The\n\t * search box takes focus when the picker appears.\n\t */\n\tlayout?: 'overlay' | 'section';\n\t/**\n\t * Section layout: the host controls whether the picker is open, so it can close it\n\t * after a save and give focus back to the \"Add link\" / \"Change link\" button\n\t * (`toggleRef`). Escape in the search box closes the picker.\n\t */\n\tpicker?: {\n\t\topen: boolean;\n\t\tsetOpen: (open: boolean) => void;\n\t\ttoggleRef: RefObject<HTMLButtonElement | null>;\n\t};\n}\n\nexport function RelationEditorBody({ editor, layout = 'overlay', picker }: RelationEditorBodyProps) {\n\tconst [creating, setCreating] = useState(false);\n\tconst [ownPickerOpen, setOwnPickerOpen] = useState(layout === 'overlay');\n\tconst showPicker = picker ? picker.open : ownPickerOpen;\n\tconst setPickerOpen = picker ? picker.setOpen : setOwnPickerOpen;\n\tconst { relation, capability, editable, selection, saving, create } = editor;\n\tconst isList = relation.kind === 'hasMany' || relation.kind === 'manyToMany';\n\tconst hasLink = selection.pending.some((link) => link.state !== 'removed');\n\t// A to-one relation with a link replaces it; a hasOne whose link must stay cannot be replaced.\n\tconst replaces = !isList && editor.current.length > 0;\n\tconst replaceReason = replaces && relation.kind === 'hasOne' && !capability.canUnlink ? capability.unlinkReason : null;\n\n\treturn (\n\t\t<>\n\t\t\t{editor.blockedReason ? (\n\t\t\t\t<p role='note' className='bg-muted text-muted-foreground rounded-md px-3 py-2 text-xs' data-testid='relation-readonly-reason'>\n\t\t\t\t\t{editor.blockedReason}\n\t\t\t\t</p>\n\t\t\t) : null}\n\t\t\t<RelationLinkList\n\t\t\t\trelation={relation}\n\t\t\t\tpending={selection.pending}\n\t\t\t\ttotal={editor.links.total}\n\t\t\t\tisLoading={editor.links.isLoading || (editor.modelsLoading && editor.current.length === 0 && relation.kind !== 'belongsTo')}\n\t\t\t\terror={editor.links.error}\n\t\t\t\thasNextPage={editor.links.hasNextPage}\n\t\t\t\tisFetchingNextPage={editor.links.isFetchingNextPage}\n\t\t\t\tonLoadMore={editor.links.fetchNextPage}\n\t\t\t\tonToggle={editor.toggle}\n\t\t\t\t// While the related table loads, the model already says whether links can be removed:\n\t\t\t\t// show that now, so the reason line and the remove controls do not appear later.\n\t\t\t\tremoveReason={\n\t\t\t\t\teditor.linkPending\n\t\t\t\t\t\t? relation.unlinkable\n\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t: relation.reason\n\t\t\t\t\t\t: editable\n\t\t\t\t\t\t\t? capability.canUnlink\n\t\t\t\t\t\t\t\t? null\n\t\t\t\t\t\t\t\t: capability.unlinkReason\n\t\t\t\t\t\t\t: null\n\t\t\t\t}\n\t\t\t\treadOnly={!editable && !editor.linkPending}\n\t\t\t\tdisabled={saving || editor.linkPending}\n\t\t\t\tplaceholderCount={editor.links.placeholderCount}\n\t\t\t\tmoveHint={editor.moveHint}\n\t\t\t\tonOpen={editor.openRecord ?? undefined}\n\t\t\t\topenReason={editor.openRecordReason}\n\t\t\t\tshowSummary={layout === 'overlay'}\n\t\t\t/>\n\n\t\t\t{!editable && editor.junctionAction ? (\n\t\t\t\t<Button type='button' variant='outline' size='sm' className='self-start' onClick={editor.junctionAction.open}>\n\t\t\t\t\t<ExternalLink className='mr-1 h-3 w-3' aria-hidden />\n\t\t\t\t\tOpen {editor.junctionAction.tableName}\n\t\t\t\t</Button>\n\t\t\t) : null}\n\n\t\t\t{(capability.canLink || editor.linkPending) && !creating && showPicker ? (\n\t\t\t\t<RelationPicker\n\t\t\t\t\trelation={relation}\n\t\t\t\t\ttargetName={relation.targetName}\n\t\t\t\t\tsearch={editor.search}\n\t\t\t\t\tonSearchChange={editor.setSearch}\n\t\t\t\t\tsearchReason={editor.searchReason}\n\t\t\t\t\tcandidates={editor.candidates.rows}\n\t\t\t\t\ttotal={editor.candidates.total}\n\t\t\t\t\tisLoading={editor.candidates.isLoading || editor.linkPending}\n\t\t\t\t\terror={editor.candidates.error ?? editor.targetError}\n\t\t\t\t\thasNextPage={editor.candidates.hasNextPage}\n\t\t\t\t\tisFetchingNextPage={editor.candidates.isFetchingNextPage}\n\t\t\t\t\tonLoadMore={editor.candidates.fetchNextPage}\n\t\t\t\t\tisSelected={selection.isSelected}\n\t\t\t\t\tonToggle={editor.toggle}\n\t\t\t\t\tdisabled={saving || editor.linkPending}\n\t\t\t\t\tmoveHint={editor.moveHint}\n\t\t\t\t\tonEscape={layout === 'section' ? () => setPickerOpen(false) : undefined}\n\t\t\t\t/>\n\t\t\t) : null}\n\n\t\t\t{creating && create.plan?.ok ? (\n\t\t\t\t<RelationCreateForm\n\t\t\t\t\ttargetName={relation.targetName}\n\t\t\t\t\tplan={create.plan}\n\t\t\t\t\tonSubmit={async (values) => {\n\t\t\t\t\t\tconst message = await create.submit(values);\n\t\t\t\t\t\tif (!message) setCreating(false);\n\t\t\t\t\t\treturn message;\n\t\t\t\t\t}}\n\t\t\t\t\tonCancel={() => setCreating(false)}\n\t\t\t\t/>\n\t\t\t) : null}\n\n\t\t\t{editor.notice ? (\n\t\t\t\t<p role='status' className='text-muted-foreground text-xs'>\n\t\t\t\t\t{editor.notice}\n\t\t\t\t</p>\n\t\t\t) : null}\n\t\t\t{editor.errors.length > 0 ? (\n\t\t\t\t<div role='alert' className='border-destructive/40 text-destructive space-y-0.5 rounded-md border px-3 py-2 text-xs'>\n\t\t\t\t\t{editor.errors.map((line) => (\n\t\t\t\t\t\t<p key={line}>{line}</p>\n\t\t\t\t\t))}\n\t\t\t\t</div>\n\t\t\t) : null}\n\n\t\t\t{/* One action row, so the link actions line up and share spacing. */}\n\t\t\t{(editable || editor.linkPending) && !creating ? (\n\t\t\t\t<div className='flex flex-wrap items-center gap-2'>\n\t\t\t\t\t{(capability.canLink || editor.linkPending) && !showPicker ? (\n\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\tref={picker?.toggleRef}\n\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\tvariant='outline'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\tdisabled={Boolean(replaceReason) || editor.linkPending}\n\t\t\t\t\t\t\ttitle={replaceReason ?? undefined}\n\t\t\t\t\t\t\tonClick={() => setPickerOpen(true)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<Link className='mr-1 h-3 w-3' aria-hidden />\n\t\t\t\t\t\t\t{replaces ? 'Change link' : 'Add link'}\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t) : null}\n\t\t\t\t\t<Button\n\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t// A leading ghost button has no visible box: pull it out by its padding so its\n\t\t\t\t\t\t// icon lines up with the content above.\n\t\t\t\t\t\tclassName={(capability.canLink || editor.linkPending) && !showPicker ? undefined : '-ms-2'}\n\t\t\t\t\t\tdisabled={editor.linkPending || Boolean(create.blocked) || saving}\n\t\t\t\t\t\ttitle={editor.linkPending ? 'Loading the linked table…' : (create.blocked ?? undefined)}\n\t\t\t\t\t\tonClick={() => setCreating(true)}\n\t\t\t\t\t>\n\t\t\t\t\t\t<Plus className='mr-1 h-3 w-3' aria-hidden />\n\t\t\t\t\t\tCreate new\n\t\t\t\t\t</Button>\n\t\t\t\t\t{/* In the cell editor, Clear is in the shared footer. */}\n\t\t\t\t\t{layout === 'section' && !isList && capability.canUnlink && hasLink ? (\n\t\t\t\t\t\t<Button type='button' variant='ghost' size='sm' disabled={saving} onClick={editor.clear}>\n\t\t\t\t\t\t\tClear link\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t) : null}\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t</>\n\t);\n}\n","'use client';\n\n/**\n * Create a related record from the relation editor with the record form\n * (`forms/model-form.ts`): the required and label fields first, the rest\n * behind \"More fields\". Every value is checked and parsed by the column's own\n * rules (`readRelatedCreate`); the parent links the result.\n */\nimport { useId, useState, type FormEvent } from 'react';\n\nimport { Button } from '@constructive-io/ui/button';\nimport { Input } from '@constructive-io/ui/input';\nimport { Label } from '@constructive-io/ui/label';\n\nimport type { ModelFormField } from '../forms/model-form';\nimport { readRelatedCreate, type RelatedCreatePlan } from './relation-create';\nimport type { FieldValues } from './relation-keys';\n\nexport interface RelationCreateFormProps {\n\ttargetName: string;\n\tplan: Extract<RelatedCreatePlan, { ok: true }>;\n\t/** Create the record; resolves to an error message, or null on success. */\n\tonSubmit: (values: FieldValues) => Promise<string | null>;\n\tonCancel: () => void;\n}\n\ntype RawValues = Record<string, unknown>;\n\nfunction FieldInput({\n\tfield,\n\tid,\n\tvalue,\n\terror,\n\tonChange,\n}: {\n\tfield: ModelFormField;\n\tid: string;\n\tvalue: unknown;\n\terror: string | undefined;\n\tonChange: (value: unknown) => void;\n}) {\n\tif (field.cellType === 'boolean') {\n\t\treturn (\n\t\t\t<label htmlFor={id} className='flex items-center gap-2 text-sm'>\n\t\t\t\t<input id={id} type='checkbox' checked={value === true} onChange={(event) => onChange(event.target.checked)} />\n\t\t\t\t{field.label}\n\t\t\t</label>\n\t\t);\n\t}\n\tconst label = (\n\t\t<Label htmlFor={id} className='text-xs' title={field.description ?? undefined}>\n\t\t\t{field.label}\n\t\t\t{field.required ? <span aria-hidden> *</span> : null}\n\t\t</Label>\n\t);\n\tif (field.options && field.options.length > 0) {\n\t\treturn (\n\t\t\t<>\n\t\t\t\t{label}\n\t\t\t\t<select\n\t\t\t\t\tid={id}\n\t\t\t\t\tclassName='border-input bg-background h-8 w-full rounded-md border px-2 text-sm'\n\t\t\t\t\tvalue={typeof value === 'string' ? value : ''}\n\t\t\t\t\taria-invalid={Boolean(error) || undefined}\n\t\t\t\t\tonChange={(event) => onChange(event.target.value === '' ? undefined : event.target.value)}\n\t\t\t\t>\n\t\t\t\t\t<option value=''>Choose…</option>\n\t\t\t\t\t{field.options.map((option) => (\n\t\t\t\t\t\t<option key={option.value} value={option.value}>\n\t\t\t\t\t\t\t{option.label}\n\t\t\t\t\t\t</option>\n\t\t\t\t\t))}\n\t\t\t\t</select>\n\t\t\t</>\n\t\t);\n\t}\n\treturn (\n\t\t<>\n\t\t\t{label}\n\t\t\t<Input\n\t\t\t\tid={id}\n\t\t\t\tsize='sm'\n\t\t\t\tvalue={typeof value === 'string' ? value : ''}\n\t\t\t\tmaxLength={field.maxLength ?? undefined}\n\t\t\t\taria-invalid={Boolean(error) || undefined}\n\t\t\t\tonChange={(event) => onChange(event.target.value === '' ? undefined : event.target.value)}\n\t\t\t/>\n\t\t</>\n\t);\n}\n\nexport function RelationCreateForm({ targetName, plan, onSubmit, onCancel }: RelationCreateFormProps) {\n\tconst baseId = useId();\n\tconst [raw, setRaw] = useState<RawValues>({});\n\tconst [errors, setErrors] = useState<Record<string, string>>({});\n\tconst [submitError, setSubmitError] = useState<string | null>(null);\n\tconst [submitting, setSubmitting] = useState(false);\n\tconst [showAll, setShowAll] = useState(false);\n\n\tconst fields = showAll ? [...plan.primary, ...plan.secondary] : plan.primary;\n\n\tconst handleSubmit = async (event: FormEvent<HTMLFormElement>) => {\n\t\tevent.preventDefault();\n\t\tevent.stopPropagation();\n\t\tconst read = readRelatedCreate(plan, raw);\n\t\tif (read.ok === false) {\n\t\t\tsetErrors(read.errors);\n\t\t\t// A message on a hidden field must be visible.\n\t\t\tif (Object.keys(read.errors).some((name) => plan.secondary.some((field) => field.name === name))) setShowAll(true);\n\t\t\treturn;\n\t\t}\n\t\tsetErrors({});\n\t\tsetSubmitError(null);\n\t\tsetSubmitting(true);\n\t\tconst message = await onSubmit(read.values);\n\t\tsetSubmitting(false);\n\t\tif (message) setSubmitError(message);\n\t};\n\n\treturn (\n\t\t<form aria-label={`New ${targetName}`} className='space-y-2 rounded-md border p-2' onSubmit={(event) => void handleSubmit(event)}>\n\t\t\t<div className='text-xs font-medium'>New {targetName}</div>\n\t\t\t{fields.length === 0 ? <p className='text-muted-foreground text-xs'>No fields are needed.</p> : null}\n\t\t\t{fields.map((field) => {\n\t\t\t\tconst id = `${baseId}-${field.name}`;\n\t\t\t\tconst error = errors[field.name];\n\t\t\t\treturn (\n\t\t\t\t\t<div key={field.name} className='space-y-1'>\n\t\t\t\t\t\t<FieldInput\n\t\t\t\t\t\t\tfield={field}\n\t\t\t\t\t\t\tid={id}\n\t\t\t\t\t\t\tvalue={raw[field.name]}\n\t\t\t\t\t\t\terror={error}\n\t\t\t\t\t\t\tonChange={(next) => setRaw((current) => ({ ...current, [field.name]: next }))}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t{error ? <p className='text-destructive text-xs'>{error}</p> : null}\n\t\t\t\t\t</div>\n\t\t\t\t);\n\t\t\t})}\n\t\t\t{plan.secondary.length > 0 ? (\n\t\t\t\t// Ghost: pulled out by its padding so its text lines up with the field labels.\n\t\t\t\t<Button type='button' variant='ghost' size='sm' className='-ms-2' onClick={() => setShowAll((value) => !value)}>\n\t\t\t\t\t{showAll ? 'Fewer fields' : `More fields (${plan.secondary.length})`}\n\t\t\t\t</Button>\n\t\t\t) : null}\n\t\t\t{submitError ? (\n\t\t\t\t<p role='alert' className='text-destructive text-xs'>\n\t\t\t\t\t{submitError}\n\t\t\t\t</p>\n\t\t\t) : null}\n\t\t\t<div className='flex justify-end gap-2'>\n\t\t\t\t<Button type='button' variant='outline' size='sm' onClick={onCancel} disabled={submitting}>\n\t\t\t\t\tBack\n\t\t\t\t</Button>\n\t\t\t\t<Button type='submit' size='sm' disabled={submitting}>\n\t\t\t\t\t{submitting ? 'Creating…' : 'Create'}\n\t\t\t\t</Button>\n\t\t\t</div>\n\t\t</form>\n\t);\n}\n","/**\n * Creating a related record from the relation editor, with the record form\n * the grid and the record panel use (`forms/model-form.ts`): the same fields,\n * read-only reasons, parsers and required checks. The fields the link itself\n * fills (hasOne/hasMany: the related table's `keys[].remote` = this record's\n * values) are fixed and not shown.\n */\nimport type { RelationModel, TableModel } from '@constructive-io/data';\n\nimport { buildModelFormSchema, buildModelFormSpec, type ModelFormField, type ModelFormSpec } from '../forms/model-form';\nimport { hasLinkPatch, type FieldValues, type RecordValues } from './relation-keys';\n\nexport type RelatedCreatePlan =\n\t| {\n\t\t\tok: true;\n\t\t\tspec: ModelFormSpec;\n\t\t\t/** Fields shown first: required ones and the label fields. */\n\t\t\tprimary: ModelFormField[];\n\t\t\t/** Other fields the form can set. */\n\t\t\tsecondary: ModelFormField[];\n\t\t\t/** Values the link fills, sent with the create. */\n\t\t\tfixed: FieldValues;\n\t }\n\t| { ok: false; reason: string };\n\n/** Plan the create form for a record of `target` linked through `relation` to `row`. */\nexport function planRelatedCreate(relation: RelationModel, target: TableModel, row: RecordValues | null): RelatedCreatePlan {\n\tconst spec = buildModelFormSpec(target, 'create');\n\tif (!target.operations.create) {\n\t\treturn { ok: false, reason: spec.fields.find((field) => field.readOnlyReason)?.readOnlyReason ?? 'New records cannot be added to the linked table.' };\n\t}\n\n\tlet fixed: FieldValues = {};\n\tif (relation.kind === 'hasOne' || relation.kind === 'hasMany') {\n\t\tconst link = row ? hasLinkPatch(relation, row) : null;\n\t\tif (!link) return { ok: false, reason: 'This record has no value to link by yet.' };\n\t\tfixed = link;\n\t}\n\tfor (const name of Object.keys(fixed)) {\n\t\tconst field = spec.fields.find((candidate) => candidate.name === name);\n\t\tif (!field?.writable) return { ok: false, reason: field?.readOnlyReason ?? 'A new linked record cannot be given this link.' };\n\t}\n\n\tconst blocking = spec.fields.find((field) => !field.writable && field.column.write.requiredOnCreate && !(field.name in fixed));\n\tif (blocking) return { ok: false, reason: `A new record needs \"${blocking.label}\": ${blocking.readOnlyReason ?? 'it cannot be entered here.'}` };\n\n\tconst open = spec.fields.filter((field) => field.writable && !(field.name in fixed));\n\tconst isPrimary = (field: ModelFormField) => field.required || relation.target.labelFields.includes(field.name);\n\treturn { ok: true, spec, primary: open.filter(isPrimary), secondary: open.filter((field) => !isPrimary(field)), fixed };\n}\n\n/**\n * Check and parse the form values (plus the fixed link values) with the record\n * form's schema. Untouched fields are left out, so their defaults apply.\n */\nexport function readRelatedCreate(\n\tplan: Extract<RelatedCreatePlan, { ok: true }>,\n\traw: Readonly<Record<string, unknown>>,\n): { ok: true; values: FieldValues } | { ok: false; errors: Record<string, string> } {\n\tconst result = buildModelFormSchema(plan.spec).safeParse({ ...raw, ...plan.fixed });\n\tif (!result.success) {\n\t\tconst errors: Record<string, string> = {};\n\t\tfor (const issue of result.error.issues) {\n\t\t\tconst name = String(issue.path[0] ?? '');\n\t\t\tif (name && !errors[name]) errors[name] = issue.message;\n\t\t}\n\t\treturn { ok: false, errors };\n\t}\n\tconst values: FieldValues = {};\n\tfor (const [name, value] of Object.entries(result.data)) if (value !== undefined) values[name] = value;\n\treturn { ok: true, values };\n}\n","'use client';\n\n/**\n * The links a row has, as they will be after Save: current links, links the\n * user removed (struck through, with Undo) and records the user added.\n */\nimport { useMemo } from 'react';\nimport { ExternalLink, Loader2, RotateCcw, X } from 'lucide-react';\n\nimport type { RelationModel } from '@constructive-io/data';\nimport { Badge } from '@constructive-io/ui/badge';\nimport { Button } from '@constructive-io/ui/button';\n\nimport { cn } from '../utils/cn';\nimport { relationRecordDistinction, relationRecordLabel, sharedLabels } from './relation-label';\nimport type { RecordValues } from './relation-keys';\nimport type { PendingLink } from './use-relation-selection';\n\n/** The list shows about five rows before it scrolls; more placeholders would only overflow. */\nconst MAX_PLACEHOLDER_ROWS = 5;\n\nexport interface RelationLinkListProps {\n\trelation: RelationModel;\n\tpending: readonly PendingLink[];\n\t/** Every current link on the server, or null when unknown. */\n\ttotal: number | null;\n\tisLoading: boolean;\n\terror: Error | null;\n\thasNextPage: boolean;\n\tisFetchingNextPage: boolean;\n\tonLoadMore: () => void;\n\tonToggle: (record: RecordValues) => void;\n\t/** Why a current link cannot be removed, or null when it can. Its remove control is then not shown; the reason is. */\n\tremoveReason: string | null;\n\t/** Nothing can change: no remove or undo controls. */\n\treadOnly: boolean;\n\t/** Controls are shown but not usable for now (a save is running). */\n\tdisabled: boolean;\n\t/** Text for a record that is linked elsewhere and will move here, or null. */\n\tmoveHint?: (record: RecordValues) => string | null;\n\t/** Open a linked record (the record panel); omit to hide the control. */\n\tonOpen?: (record: RecordValues) => void;\n\t/** Why a record cannot be opened, or null when it can. */\n\topenReason?: (record: RecordValues) => string | null;\n\t/** Show the \"Linked N\" line above the list. Default true. */\n\tshowSummary?: boolean;\n\t/** While loading: rows to hold space for (the links the record already shows), so the list does not grow when they arrive. */\n\tplaceholderCount?: number;\n}\n\nexport function RelationLinkList({\n\trelation,\n\tpending,\n\ttotal,\n\tisLoading,\n\terror,\n\thasNextPage,\n\tisFetchingNextPage,\n\tonLoadMore,\n\tonToggle,\n\tremoveReason,\n\treadOnly,\n\tdisabled,\n\tmoveHint,\n\tonOpen,\n\topenReason,\n\tshowSummary = true,\n\tplaceholderCount = 0,\n}: RelationLinkListProps) {\n\tconst linkedCount = total ?? pending.filter((link) => link.state === 'linked').length;\n\tconst labels = useMemo(() => pending.map((link) => relationRecordLabel(relation, link.record) || 'Unnamed record'), [pending, relation]);\n\tconst shared = useMemo(() => sharedLabels(labels), [labels]);\n\n\treturn (\n\t\t<section aria-label='Linked records' className='space-y-1.5'>\n\t\t\t{showSummary ? (\n\t\t\t\t<div className='text-muted-foreground flex items-center gap-2 text-xs'>\n\t\t\t\t\t<span>Linked</span>\n\t\t\t\t\t<Badge variant='outline' size='sm' className='tabular-nums' data-testid='relation-linked-count'>\n\t\t\t\t\t\t{linkedCount}\n\t\t\t\t\t</Badge>\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t\t<div className='max-h-44 overflow-y-auto rounded-md border' data-testid='relation-links'>\n\t\t\t\t{isLoading && placeholderCount > 0 ? (\n\t\t\t\t\t<ul className='space-y-1 p-1' role='status' aria-label='Loading links'>\n\t\t\t\t\t\t{Array.from({ length: Math.min(placeholderCount, MAX_PLACEHOLDER_ROWS) }, (_, index) => (\n\t\t\t\t\t\t\t<li key={index} aria-hidden className='bg-muted/40 h-8 animate-pulse rounded-[calc(var(--radius-md)-5px)]' />\n\t\t\t\t\t\t))}\n\t\t\t\t\t</ul>\n\t\t\t\t) : isLoading ? (\n\t\t\t\t\t<div className='text-muted-foreground flex items-center justify-center gap-2 py-4 text-sm'>\n\t\t\t\t\t\t<Loader2 className='h-3.5 w-3.5 animate-spin' aria-hidden />\n\t\t\t\t\t\tLoading links…\n\t\t\t\t\t</div>\n\t\t\t\t) : error ? (\n\t\t\t\t\t<div role='alert' className='text-destructive px-3 py-3 text-sm'>\n\t\t\t\t\t\tThe links could not be loaded: {error.message}\n\t\t\t\t\t</div>\n\t\t\t\t) : pending.length === 0 ? (\n\t\t\t\t\t<div className='text-muted-foreground py-4 text-center text-sm'>No linked records</div>\n\t\t\t\t) : (\n\t\t\t\t\t// Rows nest in the bordered list: radius = list radius - (border 1px + padding 4px).\n\t\t\t\t\t<ul className='space-y-1 p-1'>\n\t\t\t\t\t\t{pending.map((link, index) => {\n\t\t\t\t\t\t\tconst label = labels[index]!;\n\t\t\t\t\t\t\tconst removing = link.state === 'removed';\n\t\t\t\t\t\t\tconst adding = link.state === 'added';\n\t\t\t\t\t\t\t// Links that share a label say what tells them apart.\n\t\t\t\t\t\t\tconst distinction = shared.has(label) ? relationRecordDistinction(relation, link.record) : '';\n\t\t\t\t\t\t\tconst hint = [distinction, adding ? moveHint?.(link.record) ?? null : null].filter(Boolean).join(' · ') || null;\n\t\t\t\t\t\t\t// A link that cannot be removed gets no remove control (the reason shows below the list).\n\t\t\t\t\t\t\tconst showToggle = !readOnly && (adding || removing || !removeReason);\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<li\n\t\t\t\t\t\t\t\t\tkey={`${link.state}:${link.key}`}\n\t\t\t\t\t\t\t\t\tdata-state={link.state}\n\t\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t\t'bg-muted/60 flex items-center gap-2 rounded-[calc(var(--radius-md)-5px)] px-2 py-1',\n\t\t\t\t\t\t\t\t\t\tremoving && 'opacity-64',\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<div className='min-w-0 flex-1'>\n\t\t\t\t\t\t\t\t\t\t<div className={cn('truncate text-sm', removing && 'line-through')} title={label}>\n\t\t\t\t\t\t\t\t\t\t\t{label}\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{hint ? <div className='text-muted-foreground truncate text-xs'>{hint}</div> : null}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t{onOpen && !removing ? (\n\t\t\t\t\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\t\t\t\t\tclassName='h-6 w-6 shrink-0 p-0'\n\t\t\t\t\t\t\t\t\t\t\tdisabled={Boolean(openReason?.(link.record))}\n\t\t\t\t\t\t\t\t\t\t\ttitle={openReason?.(link.record) ?? `Open ${label}`}\n\t\t\t\t\t\t\t\t\t\t\taria-label={`Open ${label}`}\n\t\t\t\t\t\t\t\t\t\t\tonClick={() => onOpen(link.record)}\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t<ExternalLink className='h-3 w-3' />\n\t\t\t\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t{adding ? <Badge variant='secondary' size='sm'>New</Badge> : null}\n\t\t\t\t\t\t\t\t\t{removing ? <Badge variant='outline' size='sm'>Removed</Badge> : null}\n\t\t\t\t\t\t\t\t\t{showToggle ? (\n\t\t\t\t\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\t\t\t\t\tclassName='h-6 w-6 shrink-0 p-0'\n\t\t\t\t\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t\t\t\t\t\ttitle={removing ? `Keep ${label}` : adding ? `Don't link ${label}` : `Remove ${label}`}\n\t\t\t\t\t\t\t\t\t\t\taria-label={removing ? `Keep ${label}` : adding ? `Don't link ${label}` : `Remove ${label}`}\n\t\t\t\t\t\t\t\t\t\t\tonClick={() => onToggle(link.record)}\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{removing ? <RotateCcw className='h-3 w-3' /> : <X className='h-3 w-3' />}\n\t\t\t\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})}\n\t\t\t\t\t</ul>\n\t\t\t\t)}\n\t\t\t\t{hasNextPage ? (\n\t\t\t\t\t<div className='flex justify-center py-1'>\n\t\t\t\t\t\t<Button type='button' variant='ghost' size='sm' onClick={onLoadMore} disabled={isFetchingNextPage}>\n\t\t\t\t\t\t\t{isFetchingNextPage ? 'Loading…' : 'Show more links'}\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</div>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t\t{removeReason && pending.some((link) => link.state === 'linked') ? (\n\t\t\t\t<p className='text-muted-foreground text-xs'>{removeReason}</p>\n\t\t\t) : null}\n\t\t</section>\n\t);\n}\n","'use client';\n\n/**\n * Search and pick related records. The search box drives a listbox\n * (combobox pattern): ArrowUp/ArrowDown/Home/End move the highlight, Enter\n * picks or unpicks it, and focus stays in the search box. Records load page\n * by page from the related table.\n */\nimport { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type UIEvent } from 'react';\nimport { Check, Loader2, Search } from 'lucide-react';\n\nimport type { RelationModel } from '@constructive-io/data';\nimport { Badge } from '@constructive-io/ui/badge';\nimport { Button } from '@constructive-io/ui/button';\nimport { InputGroup, InputGroupAddon, InputGroupInput } from '@constructive-io/ui/input-group';\n\nimport { cn } from '../utils/cn';\nimport { linkKey, type RecordValues } from './relation-keys';\nimport { relationRecordDistinction, relationRecordLabel, sharedLabels } from './relation-label';\n\nexport interface RelationPickerProps {\n\trelation: RelationModel;\n\t/** Name of the related table, for the heading. */\n\ttargetName: string;\n\tsearch: string;\n\tonSearchChange: (text: string) => void;\n\t/** Why the records cannot be searched, or null when they can. */\n\tsearchReason: string | null;\n\tcandidates: readonly RecordValues[];\n\ttotal: number | null;\n\tisLoading: boolean;\n\terror: Error | null;\n\thasNextPage: boolean;\n\tisFetchingNextPage: boolean;\n\tonLoadMore: () => void;\n\tisSelected: (record: RecordValues) => boolean;\n\tonToggle: (record: RecordValues) => void;\n\tdisabled: boolean;\n\t/** Text for a record that is linked elsewhere and will move here, or null. */\n\tmoveHint?: (record: RecordValues) => string | null;\n\t/** Focus the search box when the picker mounts. Default true. */\n\tautoFocus?: boolean;\n\t/** Escape in the search box: close the picker (a record panel section). Omit to let Escape reach the host (the cell editor closes). */\n\tonEscape?: () => void;\n}\n\nconst LOAD_MORE_MARGIN_PX = 48;\n\nexport function RelationPicker({\n\trelation,\n\ttargetName,\n\tsearch,\n\tonSearchChange,\n\tsearchReason,\n\tcandidates,\n\ttotal,\n\tisLoading,\n\terror,\n\thasNextPage,\n\tisFetchingNextPage,\n\tonLoadMore,\n\tisSelected,\n\tonToggle,\n\tdisabled,\n\tmoveHint,\n\tautoFocus = true,\n\tonEscape,\n}: RelationPickerProps) {\n\tconst baseId = useId();\n\tconst listId = `${baseId}-options`;\n\tconst [active, setActive] = useState(0);\n\tconst inputRef = useRef<HTMLInputElement>(null);\n\tconst count = candidates.length;\n\tconst labels = useMemo(() => candidates.map((record) => relationRecordLabel(relation, record) || 'Unnamed record'), [candidates, relation]);\n\tconst shared = useMemo(() => sharedLabels(labels), [labels]);\n\n\t// The picker mounts once the related table is known; start typing right away.\n\tuseEffect(() => {\n\t\tif (autoFocus) inputRef.current?.focus();\n\t\t// Only on mount: a later prop change must not steal focus.\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, []);\n\n\tuseEffect(() => {\n\t\tsetActive((index) => (count === 0 ? 0 : Math.min(index, count - 1)));\n\t}, [count]);\n\tuseEffect(() => {\n\t\tsetActive(0);\n\t}, [search]);\n\n\t// A to-one relation picks one record; a to-many relation adds records.\n\tconst verb = relation.kind === 'belongsTo' || relation.kind === 'hasOne' ? 'Choose from' : 'Add from';\n\tconst optionId = (index: number) => `${baseId}-option-${index}`;\n\tconst activeRecord = candidates[active];\n\n\tconst handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n\t\tif (event.key === 'Escape' && onEscape) {\n\t\t\tevent.preventDefault();\n\t\t\tevent.stopPropagation();\n\t\t\tonEscape();\n\t\t\treturn;\n\t\t}\n\t\tif (count === 0) return;\n\t\tif (event.key === 'ArrowDown') {\n\t\t\tevent.preventDefault();\n\t\t\tsetActive((index) => {\n\t\t\t\tconst next = Math.min(index + 1, count - 1);\n\t\t\t\tif (next === count - 1 && hasNextPage && !isFetchingNextPage) onLoadMore();\n\t\t\t\treturn next;\n\t\t\t});\n\t\t} else if (event.key === 'ArrowUp') {\n\t\t\tevent.preventDefault();\n\t\t\tsetActive((index) => Math.max(index - 1, 0));\n\t\t} else if (event.key === 'Home') {\n\t\t\tevent.preventDefault();\n\t\t\tsetActive(0);\n\t\t} else if (event.key === 'End') {\n\t\t\tevent.preventDefault();\n\t\t\tsetActive(count - 1);\n\t\t} else if (event.key === 'Enter' && !event.ctrlKey && !event.metaKey) {\n\t\t\tevent.preventDefault();\n\t\t\tif (activeRecord && !disabled) onToggle(activeRecord);\n\t\t}\n\t};\n\n\tuseEffect(() => {\n\t\tif (typeof document === 'undefined') return;\n\t\tdocument.getElementById(optionId(active))?.scrollIntoView?.({ block: 'nearest' });\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, [active]);\n\n\tconst handleScroll = (event: UIEvent<HTMLDivElement>) => {\n\t\tconst element = event.currentTarget;\n\t\tif (!hasNextPage || isFetchingNextPage) return;\n\t\tif (element.scrollTop + element.clientHeight >= element.scrollHeight - LOAD_MORE_MARGIN_PX) onLoadMore();\n\t};\n\n\treturn (\n\t\t<section aria-label={`${verb} ${targetName}`} className='flex flex-col gap-1.5'>\n\t\t\t<div className='text-muted-foreground flex items-center gap-2 text-xs'>\n\t\t\t\t<span>{verb}</span>\n\t\t\t\t<Badge variant='outline' size='sm' className='max-w-[12rem] truncate' title={targetName}>\n\t\t\t\t\t{targetName}\n\t\t\t\t</Badge>\n\t\t\t\t{total !== null ? (\n\t\t\t\t\t<Badge variant='secondary' size='sm' className='ml-auto tabular-nums'>\n\t\t\t\t\t\t{count} / {total}\n\t\t\t\t\t</Badge>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t\t<InputGroup>\n\t\t\t\t<InputGroupAddon>\n\t\t\t\t\t<Search />\n\t\t\t\t</InputGroupAddon>\n\t\t\t\t<InputGroupInput\n\t\t\t\t\tref={inputRef}\n\t\t\t\t\trole='combobox'\n\t\t\t\t\taria-expanded='true'\n\t\t\t\t\taria-controls={listId}\n\t\t\t\t\taria-autocomplete='list'\n\t\t\t\t\taria-activedescendant={activeRecord ? optionId(active) : undefined}\n\t\t\t\t\taria-label={`Search ${targetName}`}\n\t\t\t\t\tvalue={search}\n\t\t\t\t\tonChange={(event) => onSearchChange(event.target.value)}\n\t\t\t\t\tonKeyDown={handleKeyDown}\n\t\t\t\t\t// The reason sits in the box itself, so no extra line appears once it is known.\n\t\t\t\t\tplaceholder={searchReason ?? 'Type to search…'}\n\t\t\t\t\tdisabled={Boolean(searchReason)}\n\t\t\t\t\ttitle={searchReason ?? undefined}\n\t\t\t\t\tsize='sm'\n\t\t\t\t/>\n\t\t\t</InputGroup>\n\t\t\t{/* A fixed height, so the editor does not change size as records load or a search narrows them. */}\n\t\t\t<div className='h-48 overflow-y-auto rounded-md border' onScroll={handleScroll}>\n\t\t\t\t<div id={listId} role='listbox' aria-label={targetName} aria-multiselectable={relation.kind === 'hasMany' || relation.kind === 'manyToMany'} data-testid='relation-options' className='space-y-0.5 p-1'>\n\t\t\t\t\t{isLoading ? (\n\t\t\t\t\t\t<div className='text-muted-foreground flex items-center justify-center gap-2 py-5 text-sm'>\n\t\t\t\t\t\t\t<Loader2 className='h-3.5 w-3.5 animate-spin' aria-hidden />\n\t\t\t\t\t\t\tLoading…\n\t\t\t\t\t\t</div>\n\t\t\t\t\t) : error ? (\n\t\t\t\t\t\t<div role='alert' className='text-destructive px-2 py-4 text-sm'>\n\t\t\t\t\t\t\tThe records could not be loaded: {error.message}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t) : count === 0 ? (\n\t\t\t\t\t\t<div className='text-muted-foreground py-5 text-center text-sm'>{search.trim() ? 'No matching records' : 'No records yet'}</div>\n\t\t\t\t\t) : (\n\t\t\t\t\t\tcandidates.map((record, index) => {\n\t\t\t\t\t\t\tconst label = labels[index]!;\n\t\t\t\t\t\t\tconst selected = isSelected(record);\n\t\t\t\t\t\t\t// Records that share a label say what tells them apart.\n\t\t\t\t\t\t\tconst distinction = shared.has(label) ? relationRecordDistinction(relation, record) : '';\n\t\t\t\t\t\t\tconst hint = [distinction, selected ? null : moveHint?.(record) ?? null].filter(Boolean).join(' · ') || null;\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<div\n\t\t\t\t\t\t\t\t\tkey={linkKey(relation, record) ?? `row-${index}`}\n\t\t\t\t\t\t\t\t\tid={optionId(index)}\n\t\t\t\t\t\t\t\t\trole='option'\n\t\t\t\t\t\t\t\t\taria-selected={selected}\n\t\t\t\t\t\t\t\t\taria-disabled={disabled}\n\t\t\t\t\t\t\t\t\tdata-active={index === active || undefined}\n\t\t\t\t\t\t\t\t\tonMouseDown={(event) => event.preventDefault()}\n\t\t\t\t\t\t\t\t\tonMouseEnter={() => setActive(index)}\n\t\t\t\t\t\t\t\t\tonClick={() => {\n\t\t\t\t\t\t\t\t\t\tif (!disabled) onToggle(record);\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t\t// Options nest in the bordered list: radius = list radius - (border 1px + padding 4px).\n\t\t\t\t\t\t\t\t\t\t'flex items-center gap-2 rounded-[calc(var(--radius-md)-5px)] px-2 py-1.5',\n\t\t\t\t\t\t\t\t\t\tdisabled ? 'cursor-not-allowed opacity-64' : 'cursor-pointer',\n\t\t\t\t\t\t\t\t\t\tindex === active && 'bg-accent/60',\n\t\t\t\t\t\t\t\t\t\tselected && 'text-link',\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<div className='min-w-0 flex-1'>\n\t\t\t\t\t\t\t\t\t\t<div className='truncate text-sm' title={label}>\n\t\t\t\t\t\t\t\t\t\t\t{label}\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t{hint ? <div className='text-muted-foreground truncate text-xs'>{hint}</div> : null}\n\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t{selected ? <Check className='text-primary h-3.5 w-3.5 shrink-0' aria-hidden /> : null}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t\t{hasNextPage && !isLoading ? (\n\t\t\t\t\t<div className='flex justify-center py-1'>\n\t\t\t\t\t\t<Button type='button' variant='ghost' size='sm' onClick={onLoadMore} disabled={isFetchingNextPage}>\n\t\t\t\t\t\t\t{isFetchingNextPage ? 'Loading…' : 'Show more'}\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t</div>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t</section>\n\t);\n}\n","/**\n * The state and actions of editing one relation of one record, shared by the\n * grid's cell editor and the record panel's relation section. Driven only by\n * the relation model: belongsTo writes the record's local key fields,\n * hasOne/hasMany write the related records' key fields, manyToMany creates\n * and deletes junction rows. Nothing is written until `save`; a failure keeps\n * the user's choices with the server's message; after a write the affected\n * tables refetch.\n */\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useQueryClient } from '@tanstack/react-query';\n\nimport type { RelationModel, TableModel } from '@constructive-io/data';\n\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsContext } from '../context/sheets-context';\nimport { equalityFilterGroup } from '../grid/filters/equality-filter';\nimport { useOptionalFeedback } from '../grid/feedback/feedback-context';\nimport { useRecordHistory } from '../grid/hooks/history-context';\nimport { sheetsQueryKeys } from '../hooks/query-keys';\nimport { useTableModel } from '../hooks/use-table-model';\nimport type { SheetsRowIdentifier } from '../row-identity';\nimport { relationEditCapability, type RelationEditCapability } from './relation-capability';\nimport {\n\tadapterChangeRunner,\n\tapplyRelationChanges,\n\tdescribeFailures,\n\tplanBelongsTo,\n\tplanHasLinks,\n\tplanJunctionLinks,\n\ttype LinkedRecord,\n\ttype RelationPlan,\n} from './relation-changes';\nimport { planRelatedCreate, type RelatedCreatePlan } from './relation-create';\nimport { relationHistoryEntry } from './relation-undo';\nimport {\n\tbelongsToClearPatch,\n\tbelongsToCurrentKey,\n\tbelongsToLinkPatch,\n\tfieldValues,\n\thasLinkOwner,\n\tjunctionLeftValues,\n\tlinkKey,\n\ttype FieldValues,\n\ttype RecordValues,\n} from './relation-keys';\nimport { relationRecordLabel } from './relation-label';\nimport { useOpenRecordHandler, useOpenTableHandler, type SheetsOpenRecordHandler } from './relation-navigation';\nimport { searchClauses, searchFilter } from './relation-search';\nimport { useModelPages, type ModelPages } from './use-model-pages';\nimport { useRelationLinks, type RelationLinks } from './use-relation-links';\nimport { useRelationSelection, type RelationSelection } from './use-relation-selection';\n\nexport interface RelationEditorOptions {\n\trelation: RelationModel;\n\t/** The record's table. */\n\ttable: TableModel;\n\t/** The record (server row or draft values), or null when it is not known. */\n\trow: RecordValues | null;\n\t/** The saved record's primary key, or null for a draft or a record that cannot be identified. */\n\trowIdentifier: SheetsRowIdentifier | null;\n\t/** True for a record that does not exist on the server yet. */\n\tisDraft: boolean;\n\t/** The value of the relation field on the record. */\n\tvalue: unknown;\n\t/** Ask the host to refetch after an out-of-band write. */\n\tonInvalidateData?: () => void;\n\t/** A reason the host already holds for keeping the relation read-only (it wins over the model's rules). */\n\treadOnlyReason?: string | null;\n\t/** Open a linked record; defaults to the nearest `SheetsOpenRecordContext` handler. */\n\tonOpenRecord?: SheetsOpenRecordHandler | null;\n}\n\n/** What `save` did. `patch` is the belongsTo change for the record (local key fields plus the record under the relation field). */\nexport type RelationSaveResult =\n\t| { status: 'unchanged' }\n\t| { status: 'draft'; patch: Record<string, unknown> }\n\t| { status: 'saved'; patch: Record<string, unknown> | null }\n\t| { status: 'failed' };\n\nexport interface RelationEditor {\n\trelation: RelationModel;\n\ttarget: TableModel | null;\n\tjunction: TableModel | null;\n\t/** True while the related or junction table model loads. */\n\tmodelsLoading: boolean;\n\t/** The related table could not be loaded. */\n\ttargetError: Error | null;\n\tcapability: RelationEditCapability;\n\t/** Links can be added or removed. */\n\teditable: boolean;\n\t/**\n\t * The related table is still loading and links will most likely be addable: the\n\t * picker can show its frame (disabled) now, so the editor keeps its height when\n\t * the table arrives.\n\t */\n\tlinkPending: boolean;\n\t/** Why nothing can be changed, shown once the models are known; null when something can. */\n\tblockedReason: string | null;\n\tlinks: RelationLinks;\n\t/** Current links (belongsTo: from the record's own key fields). */\n\tcurrent: readonly LinkedRecord[];\n\tselection: RelationSelection;\n\t/** For hasOne/hasMany: text for a record linked elsewhere, which linking moves here. */\n\tmoveHint: ((record: RecordValues) => string | null) | undefined;\n\tsearch: string;\n\tsetSearch: (text: string) => void;\n\tsearchReason: string | null;\n\tcandidates: ModelPages;\n\tsaving: boolean;\n\terrors: string[];\n\tnotice: string | null;\n\t/** Pick or unpick a record; a refusal is shown as the notice. */\n\ttoggle: (record: RecordValues) => void;\n\t/** Single relation: remove the link; a refusal is shown as the notice. */\n\tclear: () => void;\n\t/** Write the pending choices (or hand a draft belongsTo choice back). `clear` writes \"no link\" for a to-one relation instead. */\n\tsave: (options?: { clear?: boolean }) => Promise<RelationSaveResult>;\n\t/** Forget the pending choices and messages. */\n\tdiscard: () => void;\n\tcreate: {\n\t\t/** Why a related record cannot be created here, or null. */\n\t\tblocked: string | null;\n\t\t/** The create form plan, or null while the related model loads. */\n\t\tplan: RelatedCreatePlan | null;\n\t\t/** Create the record from parsed form values; resolves to an error message or null. */\n\t\tsubmit: (values: FieldValues) => Promise<string | null>;\n\t};\n\t/** \"Open {table}\" for links that live in a table with more fields than the editor fills, or null. */\n\tjunctionAction: { tableName: string; open: () => void } | null;\n\t/** Open a linked record in the host (record panel), or null when the host has no handler. */\n\topenRecord: ((record: RecordValues) => void) | null;\n\t/** Why a linked record cannot be opened, or null when it can. */\n\topenRecordReason: (record: RecordValues) => string | null;\n}\n\nconst SEARCH_DELAY_MS = 250;\n\nfunction useDebounced<T>(value: T, delay: number): T {\n\tconst [debounced, setDebounced] = useState(value);\n\tuseEffect(() => {\n\t\tconst timer = setTimeout(() => setDebounced(value), delay);\n\t\treturn () => clearTimeout(timer);\n\t}, [value, delay]);\n\treturn debounced;\n}\n\n/** belongsTo: the current link, keyed by the record's own key fields. */\nfunction belongsToCurrent(relation: RelationModel, row: RecordValues | null, value: unknown): LinkedRecord[] {\n\tconst nested = value && typeof value === 'object' && !Array.isArray(value) ? (value as RecordValues) : null;\n\tconst fromRow = row ? Object.fromEntries(relation.keys.map((pair) => [pair.remote, row[pair.local]])) : {};\n\tconst key = belongsToCurrentKey(relation, row) ?? linkKey(relation, nested);\n\tif (!key) return [];\n\treturn [{ key, record: nested ? { ...fromRow, ...nested } : fromRow }];\n}\n\nexport function useRelationEditor(options: RelationEditorOptions): RelationEditor {\n\tconst { relation, table, row, rowIdentifier, isDraft, value, onInvalidateData, readOnlyReason = null } = options;\n\tconst queryClient = useQueryClient();\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst adapter = useSheetsAdapter();\n\tconst openTable = useOpenTableHandler();\n\tconst contextOpenRecord = useOpenRecordHandler();\n\tconst openRecordHandler = options.onOpenRecord ?? contextOpenRecord;\n\n\tconst targetModel = useTableModel(relation.targetKey);\n\tconst junctionModel = useTableModel(relation.junction?.tableKey ?? null, { enabled: relation.kind === 'manyToMany' });\n\tconst target = targetModel.model;\n\tconst junction = junctionModel.model;\n\tconst modelsLoading =\n\t\t(!target && targetModel.isLoading) || (relation.kind === 'manyToMany' && !junction && junctionModel.isLoading);\n\n\tconst capability = useMemo<RelationEditCapability>(\n\t\t() =>\n\t\t\treadOnlyReason\n\t\t\t\t? { canLink: false, linkReason: readOnlyReason, canUnlink: false, unlinkReason: readOnlyReason }\n\t\t\t\t: relationEditCapability({ relation, table, target, junction, row, isDraft, rowIdentified: rowIdentifier != null }),\n\t\t[readOnlyReason, relation, table, target, junction, row, isDraft, rowIdentifier],\n\t);\n\tconst editable = capability.canLink || capability.canUnlink;\n\tconst linkPending =\n\t\t!capability.canLink &&\n\t\tmodelsLoading &&\n\t\trelation.editable &&\n\t\t!readOnlyReason &&\n\t\t!(isDraft && relation.kind !== 'belongsTo');\n\n\tconst links = useRelationLinks({\n\t\trelation,\n\t\trow,\n\t\trowValue: value,\n\t\ttarget,\n\t\tjunction,\n\t\tmodelsLoading,\n\t\tenabled: relation.kind !== 'belongsTo' && !isDraft,\n\t});\n\tconst current = useMemo(\n\t\t() => (relation.kind === 'belongsTo' ? belongsToCurrent(relation, row, value) : links.links),\n\t\t[links.links, relation, row, value],\n\t);\n\n\tconst linkedHere = useMemo(\n\t\t() => (relation.kind === 'hasMany' && row ? (record: RecordValues) => hasLinkOwner(relation, row, record) === 'here' : undefined),\n\t\t[relation, row],\n\t);\n\tconst selection = useRelationSelection({ relation, current, capability, linkedHere });\n\n\tconst moveHint = useMemo(() => {\n\t\tif ((relation.kind !== 'hasMany' && relation.kind !== 'hasOne') || !row) return undefined;\n\t\treturn (record: RecordValues) =>\n\t\t\thasLinkOwner(relation, row, record) === 'elsewhere' ? 'Linked to another record; choosing it moves it here.' : null;\n\t}, [relation, row]);\n\n\tconst [search, setSearch] = useState('');\n\tconst debouncedSearch = useDebounced(search, SEARCH_DELAY_MS);\n\tconst labelFields = relation.target.labelFields;\n\tconst searchReason = target && searchClauses(target, labelFields).length === 0 ? 'These records cannot be searched by their label.' : null;\n\tconst where = useMemo(\n\t\t() => (target ? searchFilter(target, labelFields, debouncedSearch) : null),\n\t\t[target, labelFields, debouncedSearch],\n\t);\n\tconst candidates = useModelPages({\n\t\tmodel: target,\n\t\tpurpose: 'relation-candidates',\n\t\tkeyParts: [debouncedSearch.trim()],\n\t\twhere,\n\t\tenabled: capability.canLink,\n\t});\n\n\tconst [saving, setSaving] = useState(false);\n\tconst [errors, setErrors] = useState<string[]>([]);\n\tconst [notice, setNotice] = useState<string | null>(null);\n\n\tconst toggle = useCallback(\n\t\t(record: RecordValues) => {\n\t\t\tsetErrors([]);\n\t\t\tsetNotice(selection.toggle(record));\n\t\t},\n\t\t[selection],\n\t);\n\n\tconst clear = useCallback(() => {\n\t\tconst refused = selection.clear();\n\t\tif (refused) setNotice(refused);\n\t}, [selection]);\n\n\tconst refresh = useCallback(async () => {\n\t\tconst models = [table, target, junction].filter((model): model is TableModel => Boolean(model));\n\t\tawait Promise.all(\n\t\t\tmodels.flatMap((model) => [\n\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.table(scopeKey, model.key) }),\n\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, model.key) }),\n\t\t\t]),\n\t\t);\n\t\tonInvalidateData?.();\n\t}, [junction, onInvalidateData, queryClient, scopeKey, table, target]);\n\n\tconst run = useMemo(() => adapterChangeRunner(adapter, execute), [adapter, execute]);\n\t// A saved change takes a step in the grid's undo history; undoing it reports like any save.\n\tconst recordHistory = useRecordHistory();\n\tconst feedback = useOptionalFeedback();\n\n\tconst planSave = useCallback((choice: RecordValues | null): RelationPlan => {\n\t\tif (relation.kind === 'belongsTo') {\n\t\t\tif (rowIdentifier == null) return { ok: false, reason: 'This record cannot be identified, so its links cannot be changed.' };\n\t\t\treturn planBelongsTo(relation, table, rowIdentifier, choice, row);\n\t\t}\n\t\tif (!row) return { ok: false, reason: 'This record has no value to link by yet.' };\n\t\tif (relation.kind === 'manyToMany') {\n\t\t\tif (!junction) return { ok: false, reason: 'The table that stores these links could not be loaded.' };\n\t\t\treturn planJunctionLinks(relation, junction, row, { added: selection.added, removed: selection.removed });\n\t\t}\n\t\tif (!target) return { ok: false, reason: 'The linked table could not be loaded.' };\n\t\tif (relation.kind === 'hasOne') {\n\t\t\tconst chosen = choice;\n\t\t\tconst added = chosen ? [{ key: linkKey(relation, chosen) ?? '', record: chosen }] : [];\n\t\t\tconst removed = current[0] ? [current[0]] : [];\n\t\t\treturn planHasLinks(relation, target, row, { added, removed });\n\t\t}\n\t\treturn planHasLinks(relation, target, row, { added: selection.added, removed: selection.removed });\n\t}, [current, junction, relation, row, rowIdentifier, selection, table, target]);\n\n\t/** belongsTo: the record's new key fields plus the chosen record under the relation field. */\n\tconst belongsToPatch = useCallback(\n\t\t(record: RecordValues | null): Record<string, unknown> | null => {\n\t\t\tconst patch = record ? belongsToLinkPatch(relation, record) : belongsToClearPatch(relation);\n\t\t\treturn patch ? { ...patch, [relation.fieldName]: record } : null;\n\t\t},\n\t\t[relation],\n\t);\n\n\tconst save = useCallback(async (options: { clear?: boolean } = {}): Promise<RelationSaveResult> => {\n\t\tif (saving) return { status: 'failed' };\n\t\t// Clear (to-one): write \"no link\" now, whatever is pending.\n\t\tconst clearing = Boolean(options.clear) && (relation.kind === 'belongsTo' || relation.kind === 'hasOne');\n\t\tconst choice = clearing ? null : selection.choice ?? null;\n\t\tif (clearing ? current.length === 0 : !selection.dirty) return { status: 'unchanged' };\n\t\tsetErrors([]);\n\t\tsetNotice(null);\n\n\t\tconst patch = relation.kind === 'belongsTo' ? belongsToPatch(choice) : null;\n\t\tif (relation.kind === 'belongsTo' && !patch) {\n\t\t\tsetErrors(['The chosen record has no value to link by.']);\n\t\t\treturn { status: 'failed' };\n\t\t}\n\t\tif (patch && isDraft) {\n\t\t\tselection.settle(new Set(selection.pending.map((link) => link.key)));\n\t\t\treturn { status: 'draft', patch };\n\t\t}\n\n\t\tconst plan = planSave(choice);\n\t\tif (plan.ok === false) {\n\t\t\tsetErrors([plan.reason]);\n\t\t\treturn { status: 'failed' };\n\t\t}\n\t\tsetSaving(true);\n\t\tconst outcome = await applyRelationChanges(plan.changes, run, {\n\t\t\tdependent: relation.kind === 'belongsTo' || relation.kind === 'hasOne',\n\t\t});\n\t\tif (outcome.applied.length > 0) await refresh();\n\t\tsetSaving(false);\n\t\tconst step =\n\t\t\trecordHistory &&\n\t\t\trelationHistoryEntry(outcome, {\n\t\t\t\trun,\n\t\t\t\trefresh,\n\t\t\t\tonDone: (message) => feedback?.noteWrite('update', 'success', message),\n\t\t\t\tonFailed: (title, messages) => feedback?.reportWriteError(title, messages),\n\t\t\t});\n\t\tif (step) recordHistory(step);\n\n\t\tif (outcome.failed.length === 0) {\n\t\t\tselection.settle(new Set(outcome.applied.map((change) => change.linkKey)));\n\t\t\treturn { status: 'saved', patch };\n\t\t}\n\t\tconst lines = describeFailures(outcome);\n\t\tif (outcome.applied.length > 0) {\n\t\t\tlines.unshift(`Saved ${outcome.applied.length} of ${plan.changes.length} changes.`);\n\t\t\tselection.settle(new Set(outcome.applied.map((change) => change.linkKey)));\n\t\t}\n\t\tsetErrors(lines);\n\t\treturn { status: 'failed' };\n\t}, [belongsToPatch, current.length, feedback, isDraft, planSave, recordHistory, refresh, relation.kind, run, saving, selection]);\n\n\tconst discard = useCallback(() => {\n\t\tselection.reset();\n\t\tsetErrors([]);\n\t\tsetNotice(null);\n\t\tsetSearch('');\n\t}, [selection]);\n\n\tconst plan = useMemo(() => (target ? planRelatedCreate(relation, target, row) : null), [relation, row, target]);\n\tconst createBlocked = !capability.canLink\n\t\t? capability.linkReason\n\t\t: isDraft && relation.kind !== 'belongsTo'\n\t\t\t? 'Save this record first, then link records to it.'\n\t\t\t: relation.kind === 'hasOne' && current.length > 0\n\t\t\t\t? 'Remove the current link first.'\n\t\t\t\t: plan && plan.ok === false\n\t\t\t\t\t? plan.reason\n\t\t\t\t\t: null;\n\n\tconst submitCreate = useCallback(\n\t\tasync (values: FieldValues): Promise<string | null> => {\n\t\t\tif (!target || !plan?.ok) return 'The linked table could not be loaded.';\n\t\t\ttry {\n\t\t\t\tconst created = await adapter.createRow<RecordValues>(\n\t\t\t\t\t{ model: target, tableName: target.key },\n\t\t\t\t\t{ ...plan.fixed, ...values },\n\t\t\t\t\texecute,\n\t\t\t\t);\n\t\t\t\tconst label = relationRecordLabel(relation, created ?? values) || 'the new record';\n\t\t\t\tif (relation.kind === 'hasOne' || relation.kind === 'hasMany') {\n\t\t\t\t\tawait refresh();\n\t\t\t\t\tsetNotice(`Created and linked \"${label}\".`);\n\t\t\t\t} else {\n\t\t\t\t\tawait queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.table(scopeKey, target.key) });\n\t\t\t\t\tif (created) {\n\t\t\t\t\t\tconst refused = selection.toggle(created);\n\t\t\t\t\t\tsetNotice(refused ?? `Created \"${label}\". Save to link it.`);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsetNotice(`Created \"${label}\". Find it in the list to link it.`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t} catch (error) {\n\t\t\t\treturn error instanceof Error ? error.message : 'The record could not be created.';\n\t\t\t}\n\t\t},\n\t\t[adapter, execute, plan, queryClient, refresh, relation, scopeKey, selection, target],\n\t);\n\n\tconst junctionInfo = relation.junction;\n\tconst junctionAction = useMemo(() => {\n\t\tif (!openTable || !junctionInfo || junctionInfo.pure) return null;\n\t\treturn {\n\t\t\ttableName: junctionInfo.tableName,\n\t\t\topen: () => {\n\t\t\t\tconst leftValues = row ? junctionLeftValues(relation, row) : null;\n\t\t\t\topenTable({\n\t\t\t\t\ttableKey: junctionInfo.tableKey,\n\t\t\t\t\ttableName: junctionInfo.tableName,\n\t\t\t\t\tfilters: junction && leftValues ? equalityFilterGroup(junction, leftValues) : null,\n\t\t\t\t\treason: 'linked-records',\n\t\t\t\t});\n\t\t\t},\n\t\t};\n\t}, [junction, junctionInfo, openTable, relation, row]);\n\n\tconst openRecordReason = useCallback(\n\t\t(record: RecordValues): string | null => {\n\t\t\tif (!relation.targetKey) return 'The linked table is not available.';\n\t\t\treturn fieldValues(record, relation.target.primaryKey) ? null : 'This record cannot be identified, so it cannot be opened.';\n\t\t},\n\t\t[relation],\n\t);\n\tconst openRecord = useMemo(() => {\n\t\tif (!openRecordHandler || !relation.targetKey) return null;\n\t\tconst tableKey = relation.targetKey;\n\t\treturn (record: RecordValues) => {\n\t\t\tconst key = fieldValues(record, relation.target.primaryKey);\n\t\t\tif (!key) return;\n\t\t\topenRecordHandler({ tableKey, tableName: relation.targetName, key, label: relationRecordLabel(relation, record) });\n\t\t};\n\t}, [openRecordHandler, relation]);\n\n\treturn {\n\t\trelation,\n\t\ttarget,\n\t\tjunction,\n\t\tmodelsLoading,\n\t\ttargetError: targetModel.error,\n\t\tcapability,\n\t\teditable,\n\t\tlinkPending,\n\t\t// Shown from the first frame when the relation or the host already decides it; a reason\n\t\t// that needs the related table waits for it (the picker frame holds its place meanwhile).\n\t\tblockedReason:\n\t\t\t!editable && (!modelsLoading || !relation.editable || Boolean(readOnlyReason))\n\t\t\t\t? capability.linkReason ?? capability.unlinkReason\n\t\t\t\t: null,\n\t\tlinks,\n\t\tcurrent,\n\t\tselection,\n\t\tmoveHint,\n\t\tsearch,\n\t\tsetSearch,\n\t\tsearchReason,\n\t\tcandidates,\n\t\tsaving,\n\t\terrors,\n\t\tnotice,\n\t\ttoggle,\n\t\tclear,\n\t\tsave,\n\t\tdiscard,\n\t\tcreate: { blocked: createBlocked, plan, submit: submitCreate },\n\t\tjunctionAction,\n\t\topenRecord,\n\t\topenRecordReason,\n\t};\n}\n","/**\n * Filter values: from what the user entered to what the filter input takes.\n *\n * Big whole numbers and decimals stay exact text (never `Number()`), dates and\n * times stay ISO text, and an object operand is built field by field. A value\n * the control cannot accept is `invalid` with a message for the user; a value\n * not entered yet is `incomplete`, and the condition is simply not applied.\n */\nimport type { FilterValueControl, ScalarValueControl } from '../filter-operators';\nimport type { SheetsFilterValue } from '../view-state/view-state.types';\n\nexport type FilterValueResult =\n\t| { status: 'ready'; value: unknown }\n\t| { status: 'incomplete' }\n\t| { status: 'invalid'; message: string };\n\nconst INCOMPLETE: FilterValueResult = { status: 'incomplete' };\n\nconst invalid = (message: string): FilterValueResult => ({ status: 'invalid', message });\nconst ready = (value: unknown): FilterValueResult => ({ status: 'ready', value });\n\nconst WHOLE_NUMBER = /^[+-]?\\d+$/;\nconst DECIMAL = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst TIME = /^(\\d{2}):(\\d{2})(?::(\\d{2})(\\.\\d+)?)?$/;\n\n/** Exact decimal text without a leading `+`. */\nfunction exactText(text: string): string {\n\treturn text.startsWith('+') ? text.slice(1) : text;\n}\n\nfunction encodeText(control: ScalarValueControl, raw: string): FilterValueResult {\n\tconst text = control.kind === 'text' || control.kind === 'json' ? raw : raw.trim();\n\tif (text.trim() === '') return INCOMPLETE;\n\tswitch (control.kind) {\n\t\tcase 'text':\n\t\t\treturn ready(text);\n\t\tcase 'integer': {\n\t\t\tconst value = Number(text);\n\t\t\treturn WHOLE_NUMBER.test(text) && Number.isSafeInteger(value) ? ready(value) : invalid('Enter a whole number.');\n\t\t}\n\t\tcase 'number': {\n\t\t\tconst value = Number(text);\n\t\t\treturn DECIMAL.test(text) && Number.isFinite(value) ? ready(value) : invalid('Enter a number.');\n\t\t}\n\t\tcase 'exact-integer':\n\t\t\treturn WHOLE_NUMBER.test(text) ? ready(exactText(text)) : invalid('Enter a whole number.');\n\t\tcase 'exact-decimal':\n\t\t\treturn DECIMAL.test(text) ? ready(exactText(text)) : invalid('Enter a number.');\n\t\tcase 'date':\n\t\t\treturn DATE.test(text) && !Number.isNaN(Date.parse(text)) ? ready(text) : invalid('Enter a date.');\n\t\tcase 'datetime':\n\t\t\treturn Number.isNaN(Date.parse(text)) ? invalid('Enter a date and time.') : ready(new Date(text).toISOString());\n\t\tcase 'time': {\n\t\t\tconst match = TIME.exec(text);\n\t\t\tif (!match) return invalid('Enter a time.');\n\t\t\treturn ready(`${match[1]}:${match[2]}:${match[3] ?? '00'}${match[4] ?? ''}`);\n\t\t}\n\t\tcase 'choice':\n\t\t\treturn control.options.some((option) => option.value === text)\n\t\t\t\t? ready(text)\n\t\t\t\t: invalid('Choose one of the listed values.');\n\t\tcase 'json':\n\t\t\ttry {\n\t\t\t\treturn ready(JSON.parse(text));\n\t\t\t} catch {\n\t\t\t\treturn invalid('Enter valid JSON.');\n\t\t\t}\n\t\tcase 'boolean':\n\t\t\treturn text === 'true' ? ready(true) : text === 'false' ? ready(false) : invalid('Choose true or false.');\n\t}\n}\n\nfunction encodeScalar(control: ScalarValueControl, value: SheetsFilterValue): FilterValueResult {\n\tif (value === null || value === undefined) return INCOMPLETE;\n\tif (control.kind === 'boolean') {\n\t\tif (typeof value === 'boolean') return ready(value);\n\t\treturn typeof value === 'string' ? encodeText(control, value) : invalid('Choose true or false.');\n\t}\n\treturn typeof value === 'string' ? encodeText(control, value) : invalid('This value does not fit this condition.');\n}\n\n/**\n * The operand for a condition, from its value control and the entered value.\n * `fixedValue` is the operand of an operator that takes no value (`isNull`).\n */\nexport function encodeFilterValue(\n\tcontrol: FilterValueControl,\n\tvalue: SheetsFilterValue,\n\tfixedValue?: boolean,\n): FilterValueResult {\n\tswitch (control.kind) {\n\t\tcase 'none':\n\t\t\treturn fixedValue === undefined ? invalid('This condition has no value.') : ready(fixedValue);\n\t\tcase 'unsupported':\n\t\t\treturn invalid(control.reason);\n\t\tcase 'multi': {\n\t\t\tif (!Array.isArray(value)) return value === null || value === '' ? INCOMPLETE : invalid('This value does not fit this condition.');\n\t\t\tconst items = (value as readonly string[]).filter((item) => typeof item === 'string' && item.trim() !== '');\n\t\t\tif (items.length === 0) return INCOMPLETE;\n\t\t\tconst encoded: unknown[] = [];\n\t\t\tfor (const item of items) {\n\t\t\t\tconst result = encodeScalar(control.item, item);\n\t\t\t\tif (result.status === 'invalid') return invalid(`\"${item}\": ${result.message}`);\n\t\t\t\tif (result.status === 'ready') encoded.push(result.value);\n\t\t\t}\n\t\t\treturn ready(encoded);\n\t\t}\n\t\tcase 'fields': {\n\t\t\tif (!value || typeof value !== 'object' || Array.isArray(value)) return INCOMPLETE;\n\t\t\tconst entered = value as Readonly<Record<string, string>>;\n\t\t\tconst operand: Record<string, unknown> = {};\n\t\t\tlet missingRequired = false;\n\t\t\tfor (const field of control.fields) {\n\t\t\t\tconst raw = entered[field.name];\n\t\t\t\tconst result = typeof raw === 'string' ? encodeScalar(field.control, raw) : INCOMPLETE;\n\t\t\t\tif (result.status === 'invalid') return invalid(`${field.label}: ${result.message}`);\n\t\t\t\tif (result.status === 'ready') operand[field.name] = result.value;\n\t\t\t\telse if (field.required) missingRequired = true;\n\t\t\t}\n\t\t\treturn missingRequired || Object.keys(operand).length === 0 ? INCOMPLETE : ready(operand);\n\t\t}\n\t\tdefault:\n\t\t\treturn encodeScalar(control, value);\n\t}\n}\n\n/** The value a new condition starts with for a control. */\nexport function emptyFilterValue(control: FilterValueControl): SheetsFilterValue {\n\tswitch (control.kind) {\n\t\tcase 'none':\n\t\tcase 'unsupported':\n\t\t\treturn null;\n\t\tcase 'multi':\n\t\t\treturn [];\n\t\tcase 'fields':\n\t\t\treturn {};\n\t\tcase 'boolean':\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn '';\n\t}\n}\n\n/**\n * Whether a value entered for one control can carry over to another, so a\n * condition keeps its value when the operator changes within the same shape.\n */\nexport function valueFitsControl(control: FilterValueControl, value: SheetsFilterValue): boolean {\n\tswitch (control.kind) {\n\t\tcase 'none':\n\t\tcase 'unsupported':\n\t\t\treturn value === null;\n\t\tcase 'multi':\n\t\t\treturn Array.isArray(value);\n\t\tcase 'fields':\n\t\t\treturn Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n\t\tcase 'boolean':\n\t\t\treturn typeof value === 'boolean';\n\t\tcase 'choice':\n\t\t\treturn typeof value === 'string' && (value === '' || control.options.some((option) => option.value === value));\n\t\tdefault:\n\t\t\treturn typeof value === 'string';\n\t}\n}\n","/**\n * A filter group that matches the rows whose columns equal given values, for\n * opening a table on the rows that belong to one record (for example the\n * junction rows of a project: `projectId = 1`). A host can pass the group\n * straight to `<Sheets filters>`.\n */\nimport type { TableModel } from '@constructive-io/data';\n\nimport { filterValueControl } from '../filter-operators';\nimport { createFilterGroup, createFilterNodeId } from '../view-state/view-state';\nimport type { SheetsColumnCondition, SheetsFilterGroup } from '../view-state/view-state.types';\nimport { encodeFilterValue } from './filter-value';\n\n/** A value as the server sends it, in the form the filter editor holds: numbers as their text. */\nfunction enteredValue(wire: unknown): string | boolean | null {\n\tif (typeof wire === 'string' || typeof wire === 'boolean') return wire;\n\tif (typeof wire === 'number' && Number.isFinite(wire)) return String(wire);\n\treturn null;\n}\n\n/**\n * One `equalTo` condition per column, combined with \"and\". Null when a column is\n * not in the model, cannot be filtered by `equalTo`, or holds a value the filter\n * would not send back exactly as given (a timestamp the editor normalizes, an\n * object, null), so a caller never opens a table on the wrong rows.\n */\nexport function equalityFilterGroup(model: TableModel, values: Readonly<Record<string, unknown>>): SheetsFilterGroup | null {\n\tconst entries = Object.entries(values);\n\tif (entries.length === 0 || !model.operations.list?.filter) return null;\n\tconst conditions: SheetsColumnCondition[] = [];\n\tfor (const [name, wire] of entries) {\n\t\tconst column = model.columns.find((candidate) => candidate.name === name);\n\t\tconst operator = column?.readable ? column.filter?.operators.find((candidate) => candidate.name === 'equalTo') : undefined;\n\t\tconst value = enteredValue(wire);\n\t\tif (!column || !operator || value === null) return null;\n\t\tconst encoded = encodeFilterValue(filterValueControl(column, operator), value);\n\t\tif (encoded.status !== 'ready' || String(encoded.value) !== String(wire)) return null;\n\t\tconditions.push({ kind: 'column', id: createFilterNodeId(), column: name, operator: 'equalTo', value });\n\t}\n\treturn createFilterGroup('and', conditions);\n}\n","// The grid's undo history, for parts that write on their own (the link editor, in a cell or the\n// record panel) so their changes take a step in it too. Null outside a grid.\nimport { createContext, useContext } from 'react';\n\nimport type { HistoryEntry } from './use-undo-redo';\n\nexport const SheetsHistoryContext = createContext<((entry: HistoryEntry) => void) | null>(null);\n\n/** Add a step to the grid's undo history, or null outside a grid. */\nexport function useRecordHistory(): ((entry: HistoryEntry) => void) | null {\n\treturn useContext(SheetsHistoryContext);\n}\n","/**\n * What the relation editor may do for one relation of one row, with a\n * human-readable reason for everything it may not do. Decided only from the\n * table models: a write the models cannot prove is not offered.\n */\nimport type { RelationModel, TableModel } from '@constructive-io/data';\n\nimport { hasLinkPatch, junctionLeftValues, linkFields, type RecordValues } from './relation-keys';\n\nexport interface RelationEditContext {\n\trelation: RelationModel;\n\t/** The grid table. */\n\ttable: TableModel;\n\t/** The related table, or null while it loads or when it failed. */\n\ttarget: TableModel | null;\n\t/** The junction table of a manyToMany relation, or null. */\n\tjunction: TableModel | null;\n\t/** The row being edited (server or draft). */\n\trow: RecordValues | null;\n\t/** True for a draft row that does not exist on the server yet. */\n\tisDraft: boolean;\n\t/** True when the server row can be addressed by its primary key. */\n\trowIdentified: boolean;\n}\n\nexport interface RelationEditCapability {\n\t/** Links can be added (or, for a single link, chosen). */\n\tcanLink: boolean;\n\t/** Why links cannot be added, or null. */\n\tlinkReason: string | null;\n\t/** Links can be removed (or, for a single link, cleared). */\n\tcanUnlink: boolean;\n\t/** Why links cannot be removed, or null. */\n\tunlinkReason: string | null;\n}\n\nconst SAVE_FIRST = 'Save this record first, then link records to it.';\nconst TARGET_UNAVAILABLE = 'The linked table could not be loaded, so these links cannot be changed.';\nconst JUNCTION_UNAVAILABLE = 'The table that stores these links could not be loaded, so they cannot be changed.';\nconst ROW_UNIDENTIFIED = 'This record cannot be identified, so its links cannot be changed.';\n\nfunction blocked(reason: string): RelationEditCapability {\n\treturn { canLink: false, linkReason: reason, canUnlink: false, unlinkReason: reason };\n}\n\nfunction operationIssue(model: TableModel, operation: 'create' | 'update' | 'delete'): string | null {\n\treturn model.issues.find((issue) => issue.scope === 'operation' && issue.target === operation)?.message ?? null;\n}\n\n/** The first column of `fields` that `operation` cannot write, with its reason. */\nfunction unwritable(model: TableModel, fields: readonly string[], operation: 'create' | 'update'): string | null {\n\tfor (const field of fields) {\n\t\tconst column = model.columns.find((candidate) => candidate.name === field);\n\t\tif (!column) return 'A field this link needs is not available.';\n\t\tif (!column.write[operation]) {\n\t\t\treturn (operation === 'create' ? column.write.createReason : column.write.updateReason) ?? 'A field this link needs cannot be changed.';\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction unlinkState(relation: RelationModel, link: RelationEditCapability): RelationEditCapability {\n\tif (!link.canLink && link.linkReason) return { ...link, canUnlink: false, unlinkReason: link.linkReason };\n\tif (!relation.unlinkable) {\n\t\treturn { ...link, canUnlink: false, unlinkReason: relation.reason ?? 'These links cannot be removed.' };\n\t}\n\treturn { ...link, canUnlink: true, unlinkReason: null };\n}\n\nfunction belongsTo(ctx: RelationEditContext): RelationEditCapability {\n\tconst { relation, table, isDraft } = ctx;\n\tconst fields = relation.keys.map((pair) => pair.local);\n\tif (isDraft) {\n\t\tif (!table.operations.create) return blocked(operationIssue(table, 'create') ?? 'New records cannot be added to this table.');\n\t\tconst reason = unwritable(table, fields, 'create');\n\t\treturn reason ? blocked(reason) : unlinkState(relation, { canLink: true, linkReason: null, canUnlink: true, unlinkReason: null });\n\t}\n\tif (!table.operations.update) return blocked(operationIssue(table, 'update') ?? 'Records in this table cannot be changed.');\n\tif (!ctx.rowIdentified) return blocked(ROW_UNIDENTIFIED);\n\tconst reason = unwritable(table, fields, 'update');\n\tif (reason) return blocked(reason);\n\treturn unlinkState(relation, { canLink: true, linkReason: null, canUnlink: true, unlinkReason: null });\n}\n\nfunction hasRelated(ctx: RelationEditContext, target: TableModel): RelationEditCapability {\n\tconst { relation, row } = ctx;\n\tif (!target.operations.update) return blocked('The linked table does not allow changes, so these links cannot be changed.');\n\tif (target.primaryKey.length === 0) return blocked('The linked records cannot be identified, so these links cannot be changed.');\n\tconst reason = unwritable(target, relation.keys.map((pair) => pair.remote), 'update');\n\tif (reason) return blocked(reason);\n\tif (!row || !hasLinkPatch(relation, row)) return blocked('This record has no value to link by yet.');\n\treturn unlinkState(relation, { canLink: true, linkReason: null, canUnlink: true, unlinkReason: null });\n}\n\nfunction manyToMany(ctx: RelationEditContext, junctionModel: TableModel): RelationEditCapability {\n\tconst { relation, row } = ctx;\n\tconst junction = relation.junction;\n\tif (!junction) return blocked(relation.reason ?? 'These links cannot be changed here.');\n\tif (!row || !junctionLeftValues(relation, row)) return blocked('This record has no value to link by yet.');\n\n\tconst fields = [...junction.left.map((pair) => pair.junction), ...junction.right.map((pair) => pair.junction)];\n\tconst createReason = !junctionModel.operations.create\n\t\t? 'The table that stores these links does not allow new links.'\n\t\t: unwritable(junctionModel, fields, 'create');\n\tconst deleteReason = !junctionModel.operations.delete || junctionModel.primaryKey.length === 0\n\t\t? 'The table that stores these links does not allow removing links.'\n\t\t: null;\n\tconst link: RelationEditCapability = {\n\t\tcanLink: createReason === null,\n\t\tlinkReason: createReason,\n\t\tcanUnlink: true,\n\t\tunlinkReason: null,\n\t};\n\tif (!relation.unlinkable) return { ...link, canUnlink: false, unlinkReason: relation.reason ?? 'These links cannot be removed.' };\n\tif (deleteReason) return { ...link, canUnlink: false, unlinkReason: deleteReason };\n\treturn link;\n}\n\n/** True when every field is a column the related table's list can return. */\nfunction readable(model: TableModel, fields: readonly string[]): boolean {\n\treturn fields.length > 0 && fields.every((field) => model.columns.some((column) => column.name === field && column.readable));\n}\n\n/** Decide what the editor may do for this relation and row. */\nexport function relationEditCapability(ctx: RelationEditContext): RelationEditCapability {\n\tconst { relation, target } = ctx;\n\tif (!relation.editable) return blocked(relation.reason ?? 'These links cannot be changed here.');\n\tif (ctx.isDraft && relation.kind !== 'belongsTo') return blocked(SAVE_FIRST);\n\tif (!target) return blocked(TARGET_UNAVAILABLE);\n\tif (!readable(target, linkFields(relation))) {\n\t\treturn blocked('The linked records do not show the fields this link needs, so these links cannot be changed.');\n\t}\n\tif (relation.kind === 'belongsTo') return belongsTo(ctx);\n\tif (relation.kind === 'manyToMany') return ctx.junction ? manyToMany(ctx, ctx.junction) : blocked(JUNCTION_UNAVAILABLE);\n\treturn hasRelated(ctx, target);\n}\n","/**\n * The writes that turn an edited link set into server state, and running\n * them one by one so a partial failure can be reported per change. Every\n * write names its table model and the exact key and values; the adapter\n * builds the documents from the model.\n */\nimport { getHumanReadableError, type RelationModel, type TableModel } from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport type { SheetsExecuteFn } from '../context/sheets-execute';\nimport type { SheetsRowIdentifier } from '../row-identity';\nimport {\n\tbelongsToClearPatch,\n\tbelongsToLinkPatch,\n\thasLinkPatch,\n\thasUnlinkPatch,\n\tjunctionLinkValues,\n\tlinkKey,\n\tprimaryKeyValues,\n\ttype FieldValues,\n\ttype RecordValues,\n} from './relation-keys';\nimport { relationRecordLabel } from './relation-label';\n\ninterface ChangeBase {\n\t/** The table the write goes to. */\n\tmodel: TableModel;\n\t/** Whether the write adds or removes a link. */\n\taction: 'link' | 'unlink';\n\t/** Label of the related record, for messages. */\n\tlabel: string;\n\t/** Identity of the related record (see `linkKey`), or '' when a link is cleared. */\n\tlinkKey: string;\n}\n\n/**\n * `prior` is what the write replaces (the patched fields' values before an update, the whole\n * row before a delete), so the change can be undone; null or absent when it was not known.\n */\nexport type RelationChange =\n\t| (ChangeBase & { op: 'update'; key: SheetsRowIdentifier; patch: FieldValues; prior?: FieldValues | null })\n\t| (ChangeBase & { op: 'create'; values: FieldValues })\n\t| (ChangeBase & { op: 'delete'; key: SheetsRowIdentifier; prior?: RecordValues | null });\n\n/** A planned set of writes, or why the edit cannot be written. */\nexport type RelationPlan = { ok: true; changes: RelationChange[] } | { ok: false; reason: string };\n\nexport interface RelationChangeFailure {\n\tchange: RelationChange;\n\tmessage: string;\n}\n\nexport interface RelationChangeOutcome {\n\tapplied: RelationChange[];\n\tfailed: RelationChangeFailure[];\n\t/** Changes not attempted because an earlier one they depend on failed. */\n\tskipped: RelationChange[];\n\t/** The row each applied create made, when the server returned it. */\n\tcreated: Map<RelationChange, RecordValues>;\n}\n\n/** The values of `fields` on `record`, or null when one of them was not read. */\nfunction priorValues(record: RecordValues | null | undefined, fields: readonly string[]): FieldValues | null {\n\tif (!record) return null;\n\tconst prior: FieldValues = {};\n\tfor (const field of fields) {\n\t\tif (!(field in record)) return null;\n\t\tprior[field] = record[field];\n\t}\n\treturn prior;\n}\n\n/** A record removed from or added to a list relation. */\nexport interface LinkedRecord {\n\t/** Comparable identity (see `linkKey`). */\n\tkey: string;\n\t/** The related record. */\n\trecord: RecordValues;\n\t/** For manyToMany: the junction row that holds the link. */\n\tjunctionRow?: RecordValues | null;\n}\n\n/** belongsTo on a server row: one update of this row's local key fields. `row` holds their values now. */\nexport function planBelongsTo(\n\trelation: RelationModel,\n\ttable: TableModel,\n\trowKey: SheetsRowIdentifier,\n\trecord: RecordValues | null,\n\trow: RecordValues | null = null,\n): RelationPlan {\n\tif (!record) {\n\t\tconst patch = belongsToClearPatch(relation);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tchanges: [\n\t\t\t\t{ op: 'update', model: table, key: rowKey, patch, prior: priorValues(row, Object.keys(patch)), action: 'unlink', label: '', linkKey: '' },\n\t\t\t],\n\t\t};\n\t}\n\tconst patch = belongsToLinkPatch(relation, record);\n\tif (!patch) return { ok: false, reason: 'The chosen record has no value to link by.' };\n\treturn {\n\t\tok: true,\n\t\tchanges: [\n\t\t\t{\n\t\t\t\top: 'update',\n\t\t\t\tmodel: table,\n\t\t\t\tkey: rowKey,\n\t\t\t\tpatch,\n\t\t\t\tprior: priorValues(row, Object.keys(patch)),\n\t\t\t\taction: 'link',\n\t\t\t\tlabel: relationRecordLabel(relation, record),\n\t\t\t\tlinkKey: linkKey(relation, record) ?? '',\n\t\t\t},\n\t\t],\n\t};\n}\n\n/**\n * hasOne/hasMany: detach the removed records, then point the added records\n * at this row. Each write updates one related record by its primary key.\n */\nexport function planHasLinks(\n\trelation: RelationModel,\n\ttarget: TableModel,\n\trow: RecordValues,\n\tchange: { added: readonly LinkedRecord[]; removed: readonly LinkedRecord[] },\n): RelationPlan {\n\tconst linkPatch = hasLinkPatch(relation, row);\n\tif (!linkPatch) return { ok: false, reason: 'This record has no value to link by yet.' };\n\tconst changes: RelationChange[] = [];\n\tfor (const entry of [...change.removed, ...change.added]) {\n\t\tconst key = primaryKeyValues(target, entry.record);\n\t\tconst label = relationRecordLabel(relation, entry.record);\n\t\tif (!key) return { ok: false, reason: `\"${label || 'A record'}\" cannot be identified, so its link cannot be changed.` };\n\t\tconst removing = change.removed.includes(entry);\n\t\tconst patch = removing ? hasUnlinkPatch(relation) : linkPatch;\n\t\tchanges.push({\n\t\t\top: 'update',\n\t\t\tmodel: target,\n\t\t\tkey: key as SheetsRowIdentifier,\n\t\t\tpatch,\n\t\t\t// A record linked elsewhere goes back to its old owner on undo.\n\t\t\tprior: priorValues(entry.record, Object.keys(patch)),\n\t\t\taction: removing ? 'unlink' : 'link',\n\t\t\tlabel,\n\t\t\tlinkKey: entry.key,\n\t\t});\n\t}\n\treturn { ok: true, changes };\n}\n\n/**\n * manyToMany: delete the junction rows of removed links (by the junction's\n * primary key), then create one junction row per added link.\n */\nexport function planJunctionLinks(\n\trelation: RelationModel,\n\tjunction: TableModel,\n\trow: RecordValues,\n\tchange: { added: readonly LinkedRecord[]; removed: readonly LinkedRecord[] },\n): RelationPlan {\n\tconst changes: RelationChange[] = [];\n\tfor (const entry of change.removed) {\n\t\tconst label = relationRecordLabel(relation, entry.record);\n\t\tconst key = entry.junctionRow ? primaryKeyValues(junction, entry.junctionRow) : null;\n\t\tif (!key) return { ok: false, reason: `The link to \"${label || 'a record'}\" cannot be identified, so it cannot be removed.` };\n\t\tchanges.push({ op: 'delete', model: junction, key: key as SheetsRowIdentifier, prior: entry.junctionRow, action: 'unlink', label, linkKey: entry.key });\n\t}\n\tfor (const entry of change.added) {\n\t\tconst label = relationRecordLabel(relation, entry.record);\n\t\tconst values = junctionLinkValues(relation, row, entry.record);\n\t\tif (!values) return { ok: false, reason: `\"${label || 'A record'}\" has no value to link by.` };\n\t\tchanges.push({ op: 'create', model: junction, values, action: 'link', label, linkKey: entry.key });\n\t}\n\treturn { ok: true, changes };\n}\n\n/** Runs one change; a create resolves to the row it made, when the server returns it. */\nexport type RelationChangeRunner = (change: RelationChange) => Promise<RecordValues | null | void>;\n\n/** Run one change through the host's adapter. */\nexport function adapterChangeRunner(adapter: SheetsBackendAdapter, execute: SheetsExecuteFn): RelationChangeRunner {\n\treturn async (change) => {\n\t\tconst ctx = { model: change.model, tableName: change.model.key };\n\t\tif (change.op === 'update') await adapter.updateRow(ctx, change.key, change.patch, execute);\n\t\telse if (change.op === 'create') return adapter.createRow<RecordValues>(ctx, change.values, execute);\n\t\telse await adapter.deleteRow(ctx, change.key, execute);\n\t};\n}\n\n/**\n * Run changes in order. With `dependent`, the first failure stops the rest\n * (a single link is replaced by removing the old one first); otherwise every\n * change is tried and each failure is reported.\n */\nexport async function applyRelationChanges(\n\tchanges: readonly RelationChange[],\n\trun: RelationChangeRunner,\n\toptions: { dependent?: boolean } = {},\n): Promise<RelationChangeOutcome> {\n\tconst outcome: RelationChangeOutcome = { applied: [], failed: [], skipped: [], created: new Map() };\n\tfor (const change of changes) {\n\t\tif (options.dependent && outcome.failed.length > 0) {\n\t\t\toutcome.skipped.push(change);\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst row = await run(change);\n\t\t\toutcome.applied.push(change);\n\t\t\tif (change.op === 'create' && row) outcome.created.set(change, row);\n\t\t} catch (error) {\n\t\t\toutcome.failed.push({ change, message: getHumanReadableError(error) });\n\t\t}\n\t}\n\treturn outcome;\n}\n\n/** One sentence per failure, naming the record and the server's message. */\nexport function describeFailures(outcome: RelationChangeOutcome): string[] {\n\tconst lines = outcome.failed.map(({ change, message }) => {\n\t\tconst verb = change.action === 'link' ? 'link' : 'unlink';\n\t\treturn change.label ? `Could not ${verb} \"${change.label}\": ${message}` : `Could not ${verb}: ${message}`;\n\t});\n\tif (outcome.skipped.length > 0) lines.push(`${outcome.skipped.length} more change${outcome.skipped.length === 1 ? ' was' : 's were'} not tried.`);\n\treturn lines;\n}\n\nconst flip = (action: RelationChange['action']): RelationChange['action'] => (action === 'link' ? 'unlink' : 'link');\n\n/**\n * The writes that undo applied changes, last first: an update writes back what it replaced, a\n * removed link row is created again from its old values, and a created one is deleted. Not\n * possible (with the reason) when a change did not keep what it replaced.\n */\nexport function invertRelationChanges(outcome: Pick<RelationChangeOutcome, 'applied' | 'created'>): RelationPlan {\n\tconst changes: RelationChange[] = [];\n\tfor (const change of [...outcome.applied].reverse()) {\n\t\tconst base = { model: change.model, action: flip(change.action), label: change.label, linkKey: change.linkKey };\n\t\tif (change.op === 'update') {\n\t\t\tif (!change.prior) return { ok: false, reason: 'The values this link change replaced are not known.' };\n\t\t\tchanges.push({ ...base, op: 'update', key: change.key, patch: change.prior, prior: change.patch });\n\t\t} else if (change.op === 'delete') {\n\t\t\tif (!change.prior) return { ok: false, reason: 'The removed link is not known, so it cannot be added again.' };\n\t\t\tconst values: FieldValues = {};\n\t\t\tfor (const column of change.model.columns) {\n\t\t\t\tif (column.write.create && change.prior[column.name] !== undefined) values[column.name] = change.prior[column.name];\n\t\t\t}\n\t\t\tchanges.push({ ...base, op: 'create', values });\n\t\t} else {\n\t\t\tconst row = outcome.created.get(change) ?? change.values;\n\t\t\tconst key = primaryKeyValues(change.model, row);\n\t\t\tif (!key) return { ok: false, reason: 'The added link cannot be identified, so it cannot be removed.' };\n\t\t\tchanges.push({ ...base, op: 'delete', key: key as SheetsRowIdentifier, prior: row });\n\t\t}\n\t}\n\treturn { ok: true, changes };\n}\n","// Undo for a saved link change. Each step runs the inverse of the writes the step before it\n// made (see `invertRelationChanges`), so undo and redo take turns over the same links. A step\n// that changes nothing throws after it says why, and the history keeps it to try again.\nimport type { HistoryEntry } from '../grid/hooks/use-undo-redo';\nimport {\n\tapplyRelationChanges,\n\tdescribeFailures,\n\tinvertRelationChanges,\n\ttype RelationChangeOutcome,\n\ttype RelationChangeRunner,\n} from './relation-changes';\n\nexport interface RelationUndoDeps {\n\trun: RelationChangeRunner;\n\t/** Read the changed tables again. */\n\trefresh: () => Promise<void>;\n\t/** The step ran. */\n\tonDone?: (message: string) => void;\n\t/** The step, or part of it, did not run: why. */\n\tonFailed: (title: string, messages: readonly string[]) => void;\n}\n\n/** Thrown by a step that changed nothing; its reason was already reported. */\nclass RelationUndoRefused extends Error {}\n\n/** The history entry for `outcome`, or null when it applied nothing. */\nexport function relationHistoryEntry(outcome: RelationChangeOutcome, deps: RelationUndoDeps): HistoryEntry | null {\n\tif (outcome.applied.length === 0) return null;\n\tlet last: Pick<RelationChangeOutcome, 'applied' | 'created'> = outcome;\n\tlet running = false;\n\n\tconst step = (done: string, failed: string) => async () => {\n\t\tif (running) throw new RelationUndoRefused();\n\t\tconst plan = invertRelationChanges(last);\n\t\tif (plan.ok === false) {\n\t\t\tdeps.onFailed(failed, [plan.reason]);\n\t\t\tthrow new RelationUndoRefused(plan.reason);\n\t\t}\n\t\trunning = true;\n\t\ttry {\n\t\t\t// In order, stopping at the first refusal: a single link is freed before it is taken again.\n\t\t\tconst result = await applyRelationChanges(plan.changes, deps.run, { dependent: true });\n\t\t\tif (result.applied.length > 0) await deps.refresh();\n\t\t\tif (result.failed.length > 0) deps.onFailed(failed, describeFailures(result));\n\t\t\tif (result.applied.length === 0) throw new RelationUndoRefused();\n\t\t\t// What ran is what the next step turns back.\n\t\t\tlast = result;\n\t\t\tif (result.failed.length === 0) deps.onDone?.(done);\n\t\t} finally {\n\t\t\trunning = false;\n\t\t}\n\t};\n\n\treturn {\n\t\tlabel: 'Change links',\n\t\tundo: step('Link change undone', 'The link change could not be undone'),\n\t\tredo: step('Link change redone', 'The link change could not be redone'),\n\t};\n}\n","/**\n * Searching related records by their label fields, with only the filter\n * fields and operators the related table's filter model really has.\n */\nimport type { TableModel } from '@constructive-io/data';\n\n/** Text operators in order of preference. */\nconst TEXT_OPERATORS = ['includesInsensitive', 'includes'] as const;\n\ninterface SearchClause {\n\t/** Filter input field. */\n\tfield: string;\n\t/** Operator to use. */\n\toperator: (typeof TEXT_OPERATORS)[number];\n}\n\n/** The label fields that can be searched as text, with the operator each uses. */\nexport function searchClauses(target: TableModel, fields: readonly string[]): SearchClause[] {\n\tconst clauses: SearchClause[] = [];\n\tfor (const name of fields) {\n\t\tconst column = target.columns.find((candidate) => candidate.name === name);\n\t\tconst filter = column?.filter;\n\t\tif (!filter || column.value.isArray) continue;\n\t\tconst operator = TEXT_OPERATORS.find((candidate) => filter.operators.some((entry) => entry.name === candidate));\n\t\tif (operator) clauses.push({ field: filter.field, operator });\n\t}\n\treturn clauses;\n}\n\n/**\n * The filter for a search text, or null when the text is empty or nothing\n * can be searched. Several fields are combined with `or` only when the\n * related table's filter has it; otherwise the first searchable field is used.\n */\nexport function searchFilter(\n\ttarget: TableModel,\n\tfields: readonly string[],\n\ttext: string,\n): Record<string, unknown> | null {\n\tconst query = text.trim();\n\tif (!query) return null;\n\tconst clauses = searchClauses(target, fields);\n\tif (clauses.length === 0) return null;\n\tconst parts = clauses.map((clause) => ({ [clause.field]: { [clause.operator]: query } }));\n\tconst canCombine = target.operations.list?.logicalOperators.includes('or') ?? false;\n\tif (parts.length > 1 && canCombine) return { or: parts };\n\treturn parts[0] ?? null;\n}\n","/**\n * Page through one table's rows with the paging its list field really has\n * (cursor, offset, or one page), through the host's adapter. Cache entries\n * live under the table's cache key, so invalidating a table after a write\n * refreshes these lists too.\n */\nimport { useMemo } from 'react';\nimport { useInfiniteQuery } from '@tanstack/react-query';\n\nimport type { TableModel } from '@constructive-io/data';\n\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsContext } from '../context/sheets-context';\nimport { sheetsQueryKeys } from '../hooks/query-keys';\nimport type { RecordValues } from './relation-keys';\n\n/** Rows per page in the relation editor. */\nexport const RELATION_PAGE_SIZE = 25;\n\nexport interface ModelPagesOptions {\n\t/** The table to read, or null while it loads. */\n\tmodel: TableModel | null;\n\t/** What the list is for; part of the cache key. */\n\tpurpose: 'relation-candidates' | 'relation-links' | 'relation-junction-links';\n\t/** Extra cache-key parts that change the result (filter inputs). */\n\tkeyParts: readonly unknown[];\n\t/** A filter in the server's filter input shape, or null for every row. */\n\twhere: Readonly<Record<string, unknown>> | null;\n\t/** Relation fields to select with each row. */\n\trelations?: readonly string[];\n\tenabled?: boolean;\n\tpageSize?: number;\n}\n\nexport interface ModelPages {\n\trows: RecordValues[];\n\t/** Every matching row, or null when the list does not count. */\n\ttotal: number | null;\n\tisLoading: boolean;\n\tisFetchingNextPage: boolean;\n\thasNextPage: boolean;\n\tfetchNextPage: () => void;\n\terror: Error | null;\n}\n\ntype PageParam = { after?: string; offset?: number } | null;\n\ninterface Page {\n\trows: RecordValues[];\n\ttotal: number | null;\n\tnextAfter: string | null;\n\thasNextPage: boolean;\n}\n\ntype PagingMode = 'cursor' | 'offset' | 'single';\n\nfunction pagingMode(model: TableModel): PagingMode {\n\tconst list = model.operations.list;\n\tif (!list?.first) return 'single';\n\tif (list.after && list.pageInfo) return 'cursor';\n\tif (list.offset) return 'offset';\n\treturn 'single';\n}\n\nexport function useModelPages(options: ModelPagesOptions): ModelPages {\n\tconst { model, purpose, keyParts, where, relations, enabled = true, pageSize = RELATION_PAGE_SIZE } = options;\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst adapter = useSheetsAdapter();\n\tconst mode = model ? pagingMode(model) : 'single';\n\tconst counts = Boolean(model?.operations.list?.totalCount);\n\n\tconst query = useInfiniteQuery<Page, Error>({\n\t\tqueryKey: [...sheetsQueryKeys.table(scopeKey, model?.key ?? ''), purpose, mode, pageSize, where, relations ?? null, ...keyParts],\n\t\tqueryFn: async ({ pageParam }) => {\n\t\t\tif (!model) throw new Error('The table is not ready.');\n\t\t\tconst param = pageParam as PageParam;\n\t\t\tconst result = await adapter.listRows(\n\t\t\t\t{ model, tableName: model.key },\n\t\t\t\t{\n\t\t\t\t\twhere: where ?? undefined,\n\t\t\t\t\tlimit: mode === 'single' ? undefined : pageSize,\n\t\t\t\t\tafter: param?.after,\n\t\t\t\t\toffset: param?.offset,\n\t\t\t\t\trelations: relations && relations.length > 0 ? relations : 'none',\n\t\t\t\t\tincludeTotalCount: counts,\n\t\t\t\t},\n\t\t\t\texecute,\n\t\t\t);\n\t\t\tconst loadedBefore = param?.offset ?? 0;\n\t\t\tconst hasNextPage =\n\t\t\t\tmode === 'cursor'\n\t\t\t\t\t? Boolean(result.pageInfo?.hasNextPage && result.pageInfo.endCursor)\n\t\t\t\t\t: mode === 'offset'\n\t\t\t\t\t\t? result.rows.length === pageSize && (!counts || loadedBefore + result.rows.length < result.totalCount)\n\t\t\t\t\t\t: false;\n\t\t\treturn {\n\t\t\t\trows: result.rows,\n\t\t\t\ttotal: counts ? result.totalCount : null,\n\t\t\t\tnextAfter: result.pageInfo?.endCursor ?? null,\n\t\t\t\thasNextPage,\n\t\t\t};\n\t\t},\n\t\tinitialPageParam: null as PageParam,\n\t\tgetNextPageParam: (last, pages): PageParam | undefined => {\n\t\t\tif (!last.hasNextPage) return undefined;\n\t\t\tif (mode === 'cursor') return last.nextAfter ? { after: last.nextAfter } : undefined;\n\t\t\treturn { offset: pages.reduce((sum, page) => sum + page.rows.length, 0) };\n\t\t},\n\t\tenabled: enabled && Boolean(model),\n\t\tstaleTime: 30 * 1000,\n\t});\n\n\tconst rows = useMemo(() => query.data?.pages.flatMap((page) => page.rows) ?? [], [query.data]);\n\tconst pages = query.data?.pages;\n\tconst total = pages && pages.length > 0 ? (pages[pages.length - 1]?.total ?? null) : null;\n\n\treturn {\n\t\trows,\n\t\ttotal,\n\t\tisLoading: enabled && Boolean(model) && query.isPending,\n\t\tisFetchingNextPage: query.isFetchingNextPage,\n\t\thasNextPage: Boolean(query.hasNextPage),\n\t\tfetchNextPage: () => {\n\t\t\tvoid query.fetchNextPage();\n\t\t},\n\t\terror: query.error ?? null,\n\t};\n}\n","/**\n * The full current link set of one row's hasOne, hasMany or manyToMany\n * relation, read page by page through a filtered query instead of the\n * capped nested list the grid row carries.\n *\n * - hasOne/hasMany: the related table, filtered by `keys[].remote` = this row's `keys[].local`.\n * - manyToMany: the junction table, filtered by `junction.left`, with the\n * junction's own belongsTo relation to the related table for labels.\n */\nimport { useMemo } from 'react';\n\nimport type { RelationModel, TableModel } from '@constructive-io/data';\n\nimport {\n\tequalityFilter,\n\thasLinkPatch,\n\tjunctionLeftValues,\n\tjunctionRightKey,\n\tjunctionRightRecord,\n\tlinkKey,\n\ttype RecordValues,\n} from './relation-keys';\nimport type { LinkedRecord } from './relation-changes';\nimport { useModelPages } from './use-model-pages';\n\nexport interface RelationLinks {\n\t/** Current links, in server order, as loaded so far. */\n\tlinks: LinkedRecord[];\n\t/** Every current link, or null when the server does not count them. */\n\ttotal: number | null;\n\tisLoading: boolean;\n\tisFetchingNextPage: boolean;\n\thasNextPage: boolean;\n\tfetchNextPage: () => void;\n\terror: Error | null;\n\t/** False when the link set cannot be queried; `links` then come from the row itself. */\n\tqueried: boolean;\n\t/** While loading: how many links the row itself already shows (its first page), to hold their space. */\n\tplaceholderCount: number;\n}\n\n/** The junction's belongsTo relation that points at the related table through `junction.right`. */\nexport function junctionTargetRelation(relation: RelationModel, junction: TableModel): RelationModel | null {\n\tconst right = relation.junction?.right ?? [];\n\treturn (\n\t\tjunction.relations.find(\n\t\t\t(candidate) =>\n\t\t\t\tcandidate.kind === 'belongsTo' &&\n\t\t\t\tcandidate.readable &&\n\t\t\t\tcandidate.targetKey === relation.targetKey &&\n\t\t\t\tcandidate.keys.length === right.length &&\n\t\t\t\tright.every((pair) => candidate.keys.some((key) => key.local === pair.junction && key.remote === pair.remote)),\n\t\t) ?? null\n\t);\n}\n\nfunction asRecords(value: unknown): RecordValues[] {\n\tif (!Array.isArray(value)) return value && typeof value === 'object' ? [value as RecordValues] : [];\n\treturn value.filter((entry): entry is RecordValues => Boolean(entry) && typeof entry === 'object');\n}\n\nexport function useRelationLinks(options: {\n\trelation: RelationModel;\n\trow: RecordValues | null;\n\t/** The value of the relation field on the row, used when the link set cannot be queried. */\n\trowValue: unknown;\n\ttarget: TableModel | null;\n\tjunction: TableModel | null;\n\t/** True while the related or junction table model is still loading. */\n\tmodelsLoading: boolean;\n\tenabled: boolean;\n}): RelationLinks {\n\tconst { relation, row, rowValue, target, junction, modelsLoading, enabled } = options;\n\tconst isJunction = relation.kind === 'manyToMany';\n\tconst listModel = isJunction ? junction : target;\n\n\tconst where = useMemo(() => {\n\t\tif (!row || !listModel) return null;\n\t\tconst values = isJunction ? junctionLeftValues(relation, row) : hasLinkPatch(relation, row);\n\t\treturn values ? equalityFilter(listModel, values) : null;\n\t}, [isJunction, listModel, relation, row]);\n\n\tconst throughRelation = useMemo(\n\t\t() => (isJunction && junction ? junctionTargetRelation(relation, junction) : null),\n\t\t[isJunction, junction, relation],\n\t);\n\n\tconst listed = enabled && relation.kind !== 'belongsTo';\n\tconst queried = listed && Boolean(listModel && where);\n\t// Until the model that lists the links is known, show nothing rather than the capped\n\t// nested list: a link taken from it has no junction row, so it could not be removed.\n\tconst waiting = listed && !listModel && modelsLoading;\n\tconst pages = useModelPages({\n\t\tmodel: listModel,\n\t\tpurpose: isJunction ? 'relation-junction-links' : 'relation-links',\n\t\tkeyParts: [relation.fieldName],\n\t\twhere,\n\t\trelations: throughRelation ? [throughRelation.fieldName] : undefined,\n\t\tenabled: queried,\n\t});\n\n\tconst links = useMemo<LinkedRecord[]>(() => {\n\t\tif (waiting) return [];\n\t\tif (!queried) {\n\t\t\treturn asRecords(rowValue).flatMap((record): LinkedRecord[] => {\n\t\t\t\tconst key = linkKey(relation, record);\n\t\t\t\treturn key ? [{ key, record, junctionRow: null }] : [];\n\t\t\t});\n\t\t}\n\t\treturn pages.rows.flatMap((entry) => {\n\t\t\tif (!isJunction) {\n\t\t\t\tconst key = linkKey(relation, entry);\n\t\t\t\treturn key ? [{ key, record: entry }] : [];\n\t\t\t}\n\t\t\tconst key = junctionRightKey(relation, entry);\n\t\t\tif (!key) return [];\n\t\t\tconst nested = throughRelation ? entry[throughRelation.fieldName] : null;\n\t\t\tconst record = nested && typeof nested === 'object'\n\t\t\t\t? { ...junctionRightRecord(relation, entry), ...(nested as RecordValues) }\n\t\t\t\t: junctionRightRecord(relation, entry);\n\t\t\treturn [{ key, record, junctionRow: entry }];\n\t\t});\n\t}, [isJunction, pages.rows, queried, relation, rowValue, throughRelation, waiting]);\n\n\treturn {\n\t\tlinks,\n\t\ttotal: queried ? pages.total : null,\n\t\tisLoading: waiting || (queried && pages.isLoading),\n\t\tisFetchingNextPage: pages.isFetchingNextPage,\n\t\thasNextPage: queried && pages.hasNextPage,\n\t\tfetchNextPage: pages.fetchNextPage,\n\t\terror: queried ? pages.error : null,\n\t\tqueried,\n\t\tplaceholderCount: asRecords(rowValue).length,\n\t};\n}\n","/**\n * The user's pending link choices in the relation editor, kept apart from\n * server state until Save. A single relation (belongsTo, hasOne) holds one\n * choice; a list relation (hasMany, manyToMany) holds the records to add and\n * the links to remove. Refused choices return the model's reason.\n */\nimport { useCallback, useMemo, useState } from 'react';\n\nimport type { RelationModel } from '@constructive-io/data';\n\nimport type { RelationEditCapability } from './relation-capability';\nimport type { LinkedRecord } from './relation-changes';\nimport { linkKey, type RecordValues } from './relation-keys';\n\nexport type LinkState = 'linked' | 'added' | 'removed';\n\nexport interface PendingLink extends LinkedRecord {\n\tstate: LinkState;\n}\n\nexport interface RelationSelection {\n\t/** One link (belongsTo, hasOne) or many (hasMany, manyToMany). */\n\tmode: 'single' | 'multi';\n\t/** Links as they will be after Save: current ones (some marked removed) and added ones. */\n\tpending: PendingLink[];\n\t/** Whether a record is linked after Save. */\n\tisSelected: (record: RecordValues) => boolean;\n\t/** Pick or unpick a record. Returns the reason when the model forbids it. */\n\ttoggle: (record: RecordValues) => string | null;\n\t/** Single relation: remove the link. Returns the reason when the model forbids it. */\n\tclear: () => string | null;\n\t/** True when Save would write something. */\n\tdirty: boolean;\n\t/** Single relation: the chosen record (null to clear), or undefined when unchanged. */\n\tchoice: RecordValues | null | undefined;\n\t/** List relation: records to link. */\n\tadded: LinkedRecord[];\n\t/** List relation: links to remove. */\n\tremoved: LinkedRecord[];\n\t/** Drop pending choices that the server now holds. */\n\tsettle: (keys: ReadonlySet<string>) => void;\n\t/** Drop every pending choice. */\n\treset: () => void;\n}\n\nconst NO_KEY = 'This record has no value to link by.';\n\nexport function useRelationSelection(options: {\n\trelation: RelationModel;\n\t/** Current links from the server (or the row), first page first. */\n\tcurrent: readonly LinkedRecord[];\n\tcapability: RelationEditCapability;\n\t/** hasMany: true when a record already points at this row although its link is not loaded yet. */\n\tlinkedHere?: (record: RecordValues) => boolean;\n}): RelationSelection {\n\tconst { relation, current, capability, linkedHere } = options;\n\tconst mode = relation.kind === 'belongsTo' || relation.kind === 'hasOne' ? 'single' : 'multi';\n\n\tconst [choice, setChoice] = useState<{ record: RecordValues | null } | null>(null);\n\tconst [added, setAdded] = useState<ReadonlyMap<string, LinkedRecord>>(() => new Map());\n\tconst [removed, setRemoved] = useState<ReadonlyMap<string, LinkedRecord>>(() => new Map());\n\n\tconst currentByKey = useMemo(() => new Map(current.map((link) => [link.key, link])), [current]);\n\tconst currentKey = current[0]?.key ?? null;\n\tconst choiceKey = choice ? (choice.record ? linkKey(relation, choice.record) : null) : currentKey;\n\n\tconst isLinkedNow = useCallback(\n\t\t(key: string, record: RecordValues) => currentByKey.has(key) || Boolean(linkedHere?.(record)),\n\t\t[currentByKey, linkedHere],\n\t);\n\n\tconst isSelected = useCallback(\n\t\t(record: RecordValues) => {\n\t\t\tconst key = linkKey(relation, record);\n\t\t\tif (!key) return false;\n\t\t\tif (mode === 'single') return key === choiceKey;\n\t\t\treturn added.has(key) || (isLinkedNow(key, record) && !removed.has(key));\n\t\t},\n\t\t[added, choiceKey, isLinkedNow, mode, relation, removed],\n\t);\n\n\tconst toggle = useCallback(\n\t\t(record: RecordValues): string | null => {\n\t\t\tconst key = linkKey(relation, record);\n\t\t\tif (!key) return NO_KEY;\n\t\t\tif (mode === 'single') {\n\t\t\t\tif (key === choiceKey) {\n\t\t\t\t\t// Unpicking a new choice goes back to the current link; unpicking the current link clears it.\n\t\t\t\t\tif (choice) {\n\t\t\t\t\t\tsetChoice(null);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\tif (!capability.canUnlink) return capability.unlinkReason;\n\t\t\t\t\tsetChoice({ record: null });\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tif (!capability.canLink) return capability.linkReason;\n\t\t\t\tif (currentKey !== null && !capability.canUnlink && relation.kind === 'hasOne') return capability.unlinkReason;\n\t\t\t\tsetChoice(key === currentKey ? null : { record });\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (added.has(key)) {\n\t\t\t\tsetAdded((map) => withoutKey(map, key));\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (removed.has(key)) {\n\t\t\t\tsetRemoved((map) => withoutKey(map, key));\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (isLinkedNow(key, record)) {\n\t\t\t\tif (!capability.canUnlink) return capability.unlinkReason;\n\t\t\t\tconst link = currentByKey.get(key) ?? { key, record, junctionRow: null };\n\t\t\t\tsetRemoved((map) => withKey(map, key, link));\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!capability.canLink) return capability.linkReason;\n\t\t\tsetAdded((map) => withKey(map, key, { key, record }));\n\t\t\treturn null;\n\t\t},\n\t\t[added, capability, choice, choiceKey, currentByKey, currentKey, isLinkedNow, mode, relation, removed],\n\t);\n\n\tconst clear = useCallback((): string | null => {\n\t\tif (choiceKey === null) return null;\n\t\tif (!capability.canUnlink) return capability.unlinkReason;\n\t\tsetChoice(currentKey === null ? null : { record: null });\n\t\treturn null;\n\t}, [capability, choiceKey, currentKey]);\n\n\tconst settle = useCallback((keys: ReadonlySet<string>) => {\n\t\tsetAdded((map) => withoutKeys(map, keys));\n\t\tsetRemoved((map) => withoutKeys(map, keys));\n\t\tsetChoice(null);\n\t}, []);\n\n\tconst reset = useCallback(() => {\n\t\tsetAdded(new Map());\n\t\tsetRemoved(new Map());\n\t\tsetChoice(null);\n\t}, []);\n\n\tconst pending = useMemo<PendingLink[]>(() => {\n\t\tif (mode === 'single') {\n\t\t\tconst now = current[0] ?? null;\n\t\t\tif (!choice) return now ? [{ ...now, state: 'linked' }] : [];\n\t\t\tconst next = choice.record && choiceKey ? [{ key: choiceKey, record: choice.record, state: 'added' as const }] : [];\n\t\t\treturn now ? [...next, { ...now, state: 'removed' }] : next;\n\t\t}\n\t\treturn [\n\t\t\t...current.map((link) => ({ ...link, state: removed.has(link.key) ? ('removed' as const) : ('linked' as const) })),\n\t\t\t...[...removed.values()].filter((link) => !currentByKey.has(link.key)).map((link) => ({ ...link, state: 'removed' as const })),\n\t\t\t...[...added.values()].map((link) => ({ ...link, state: 'added' as const })),\n\t\t];\n\t}, [added, choice, choiceKey, current, currentByKey, mode, removed]);\n\n\tconst dirty = mode === 'single' ? choice !== null && choiceKey !== currentKey : added.size + removed.size > 0;\n\n\treturn {\n\t\tmode,\n\t\tpending,\n\t\tisSelected,\n\t\ttoggle,\n\t\tclear,\n\t\tdirty,\n\t\tchoice: choice ? choice.record : undefined,\n\t\tadded: [...added.values()],\n\t\tremoved: [...removed.values()],\n\t\tsettle,\n\t\treset,\n\t};\n}\n\nfunction withKey<T>(map: ReadonlyMap<string, T>, key: string, value: T): ReadonlyMap<string, T> {\n\tconst next = new Map(map);\n\tnext.set(key, value);\n\treturn next;\n}\n\nfunction withoutKey<T>(map: ReadonlyMap<string, T>, key: string): ReadonlyMap<string, T> {\n\tconst next = new Map(map);\n\tnext.delete(key);\n\treturn next;\n}\n\nfunction withoutKeys<T>(map: ReadonlyMap<string, T>, keys: ReadonlySet<string>): ReadonlyMap<string, T> {\n\tif (![...keys].some((key) => map.has(key))) return map;\n\tconst next = new Map(map);\n\tfor (const key of keys) next.delete(key);\n\treturn next;\n}\n","'use client';\n\n// Native relation editor: maps EditorProps onto the model-driven RelationEditor.\n// • relation / table -> EditorProps.relation / .table (the table model of the grid);\n// resolved from the grid's model when a host renders the editor\n// without them.\n// • row -> EditorProps.row: the editor reads this row's own key values\n// (they need not be the primary key).\n// • rowIdentifier -> the server row's primary key; a draft row has none.\n// • onCommitPatch -> belongsTo only: the local key fields plus the chosen record under\n// the relation field (a draft keeps them locally; a server row gets\n// the saved link). Other kinds write the related tables and refetch.\n// • onCancel -> close without writing.\n\nimport type { RelationModel, TableModel } from '@constructive-io/data';\n\nimport { EditorFocusTrap } from '../../grid/editors/editor-focus-trap';\nimport { OVERLAY } from '../../grid/editors/overlay-presets';\nimport { RelationEditor } from '../../grid/editors/relation-editor';\nimport { useTableModel } from '../../hooks/use-table-model';\nimport type { RecordValues } from '../../relations/relation-keys';\nimport type { EditorProps } from './editor-props';\n\nconst DRAFT_PREFIX = 'draft:';\n\n/** The relation behind a column: the relation field itself, or a belongsTo through one of its key fields. */\nfunction relationForColumn(table: TableModel, colKey: string): RelationModel | null {\n\treturn (\n\t\ttable.relations.find((relation) => relation.fieldName === colKey) ??\n\t\ttable.relations.find((relation) => relation.kind === 'belongsTo' && relation.keys.some((pair) => pair.local === colKey)) ??\n\t\tnull\n\t);\n}\n\nexport function RelationEditorDom({\n\tvalue,\n\tcolKey,\n\trowId,\n\trowIdentifier,\n\trow,\n\ttableName,\n\trelation: relationProp,\n\ttable: tableProp,\n\tonCommitPatch,\n\tonInvalidateData,\n\tonCancel,\n}: EditorProps) {\n\tconst fallback = useTableModel(tableProp ? null : (tableName ?? null));\n\tconst table = tableProp ?? fallback.model;\n\tconst relation = relationProp ?? (table ? relationForColumn(table, colKey) : null);\n\tconst isDraft = rowIdentifier == null && rowId.startsWith(DRAFT_PREFIX);\n\tconst record = (row ?? null) as RecordValues | null;\n\n\tif (!table || !relation) {\n\t\tconst message = fallback.error ? fallback.error.message : fallback.isLoading ? 'Loading…' : 'This field is not a link.';\n\t\treturn (\n\t\t\t<div data-slot='relation-editor'>\n\t\t\t\t<EditorFocusTrap onEscape={onCancel} className={`bg-popover ${OVERLAY.md} rounded-lg border p-4 text-sm shadow-lg`}>\n\t\t\t\t\t<p role='status' className='text-muted-foreground'>\n\t\t\t\t\t\t{message}\n\t\t\t\t\t</p>\n\t\t\t\t</EditorFocusTrap>\n\t\t\t</div>\n\t\t);\n\t}\n\n\tconst relationValue = record && relation.fieldName in record ? record[relation.fieldName] : colKey === relation.fieldName ? value : null;\n\n\treturn (\n\t\t<div data-slot='relation-editor'>\n\t\t\t<RelationEditor\n\t\t\t\trelation={relation}\n\t\t\t\ttable={table}\n\t\t\t\trow={record}\n\t\t\t\trowIdentifier={rowIdentifier ?? null}\n\t\t\t\tisDraft={isDraft}\n\t\t\t\tvalue={relationValue}\n\t\t\t\tonCommitPatch={onCommitPatch}\n\t\t\t\tonInvalidateData={onInvalidateData}\n\t\t\t\tonClose={onCancel}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","'use client';\n\n// Option picker for choice columns (enums and text with an allowed-values list).\n// Shows each option's label and writes its wire value. A single choice commits on\n// pick; a list of choices toggles options and commits with Save. A long list gets a\n// search box. A stored value that is not in the option list still shows, so the user\n// can see it and remove it. Keyboard: arrows move, Enter picks, Escape cancels.\n\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { Check } from 'lucide-react';\n\nimport type { ColumnOption } from '@constructive-io/data';\nimport { Button } from '@constructive-io/ui/button';\n\nimport { EditorHeader, modifierKeyLabel, VALUE_REQUIRED_REASON } from '../../grid/editors/editor-frame';\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { OVERLAY_SM } from '../../grid/editors/overlay-presets';\nimport { choiceLabel } from '../../cell-types/column-value';\nimport { cn } from '../../utils/cn';\nimport type { EditorProps } from './editor-props';\n\n/** Option lists longer than this get a search box. */\nconst SEARCH_THRESHOLD = 7;\n/** The footer buttons sit 5px inside the editor's 10px corners, like the options. */\nconst FOOTER_BUTTON_RADIUS = 'rounded-[calc(var(--radius-lg)-5px)] before:rounded-[calc(var(--radius-lg)-6px)]';\n\nfunction initialSelection(value: unknown, multiple: boolean): string[] {\n\tif (value === null || value === undefined) return [];\n\tconst values = multiple && Array.isArray(value) ? value : [value];\n\treturn values.filter((entry): entry is string => typeof entry === 'string');\n}\n\nexport function SelectEditorDom({ value, column, colKey, cell, onCommit }: EditorProps) {\n\tconst multiple = column ? column.value.isArray : cell.meta?.cellType === 'multi-select';\n\tconst options = useMemo<readonly ColumnOption[]>(() => column?.value.options ?? [], [column]);\n\tconst [selected, setSelected] = useState<string[]>(() => initialSelection(value, multiple));\n\tconst [query, setQuery] = useState('');\n\tconst [active, setActive] = useState(0);\n\tconst listRef = useRef<HTMLUListElement | null>(null);\n\n\tconst searchable = options.length > SEARCH_THRESHOLD;\n\t// Stored values that are not options stay visible so they can be seen and removed.\n\tconst unknownSelected = selected.filter((entry) => !options.some((option) => option.value === entry));\n\tconst visible = useMemo(() => {\n\t\tconst needle = query.trim().toLowerCase();\n\t\tconst all: ColumnOption[] = [...unknownSelected.map((entry) => ({ value: entry, label: entry })), ...options];\n\t\tif (!needle) return all;\n\t\treturn all.filter((option) => option.label.toLowerCase().includes(needle) || option.value.toLowerCase().includes(needle));\n\t}, [options, query, unknownSelected]);\n\n\t// Without a search box the list itself takes focus, after the focus trap's own pass.\n\tuseEffect(() => {\n\t\tif (!searchable) listRef.current?.focus();\n\t}, [searchable]);\n\n\tconst label = fieldLabel(column?.name ?? colKey);\n\tconst clampedActive = Math.min(active, Math.max(visible.length - 1, 0));\n\n\tfunction pick(option: ColumnOption) {\n\t\tif (!multiple) {\n\t\t\tonCommit(option.value);\n\t\t\treturn;\n\t\t}\n\t\tsetSelected((current) =>\n\t\t\tcurrent.includes(option.value) ? current.filter((entry) => entry !== option.value) : [...current, option.value],\n\t\t);\n\t}\n\n\tfunction save() {\n\t\tonCommit(multiple ? selected : selected[0] ?? null);\n\t}\n\n\tfunction handleKeyDown(e: React.KeyboardEvent) {\n\t\tif (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n\t\t\te.preventDefault();\n\t\t\tconst step = e.key === 'ArrowDown' ? 1 : -1;\n\t\t\tsetActive((current) => (visible.length ? (Math.min(current, visible.length - 1) + step + visible.length) % visible.length : 0));\n\t\t\treturn;\n\t\t}\n\t\tif (e.key === 'Enter') {\n\t\t\te.preventDefault();\n\t\t\tif (multiple && (e.metaKey || e.ctrlKey)) {\n\t\t\t\tsave();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst option = visible[clampedActive];\n\t\t\tif (option) pick(option);\n\t\t}\n\t\t// Escape is handled by the overlay's focus trap (onCancel).\n\t}\n\n\treturn (\n\t\t<div\n\t\t\tdata-slot='select-editor'\n\t\t\t// The options, the search field and the footer buttons sit 5px inside the 10px corners\n\t\t\t// (1px border + 4px padding), so their radius is 10px - 5px and the curves stay parallel.\n\t\t\tclassName={cn('bg-popover flex flex-col gap-1 rounded-lg border p-1 shadow-lg', OVERLAY_SM)}\n\t\t\tonKeyDown={handleKeyDown}\n\t\t>\n\t\t\t{/* The field's name, like every value editor's title; inset to line up with the options' text. */}\n\t\t\t<EditorHeader title={label} className='px-2 pt-1' />\n\t\t\t{searchable ? (\n\t\t\t\t<input\n\t\t\t\t\taria-label={`Search ${label} options`}\n\t\t\t\t\tvalue={query}\n\t\t\t\t\tonChange={(e) => {\n\t\t\t\t\t\tsetQuery(e.target.value);\n\t\t\t\t\t\tsetActive(0);\n\t\t\t\t\t}}\n\t\t\t\t\tplaceholder='Search options'\n\t\t\t\t\tspellCheck={false}\n\t\t\t\t\tclassName='bg-muted/40 border-border/40 rounded-[calc(var(--radius-lg)-5px)] border px-2.5 py-1.5 text-sm outline-none focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/35'\n\t\t\t\t\tautoFocus\n\t\t\t\t/>\n\t\t\t) : null}\n\t\t\t<ul\n\t\t\t\tref={listRef}\n\t\t\t\trole='listbox'\n\t\t\t\taria-label={`${label} options`}\n\t\t\t\taria-multiselectable={multiple || undefined}\n\t\t\t\taria-activedescendant={visible[clampedActive] ? `select-option-${clampedActive}` : undefined}\n\t\t\t\ttabIndex={searchable ? -1 : 0}\n\t\t\t\tclassName='max-h-64 overflow-y-auto outline-none'\n\t\t\t>\n\t\t\t\t{visible.length === 0 ? (\n\t\t\t\t\t<li className='text-muted-foreground px-2 py-1.5 text-sm'>No matching options</li>\n\t\t\t\t) : (\n\t\t\t\t\tvisible.map((option, index) => {\n\t\t\t\t\t\tconst isSelected = selected.includes(option.value);\n\t\t\t\t\t\tconst isUnknown = !options.some((entry) => entry.value === option.value);\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t<li\n\t\t\t\t\t\t\t\tkey={option.value}\n\t\t\t\t\t\t\t\tid={`select-option-${index}`}\n\t\t\t\t\t\t\t\trole='option'\n\t\t\t\t\t\t\t\taria-selected={isSelected}\n\t\t\t\t\t\t\t\tonMouseEnter={() => setActive(index)}\n\t\t\t\t\t\t\t\tonClick={() => pick(option)}\n\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t'flex cursor-pointer items-center justify-between gap-2 rounded-[calc(var(--radius-lg)-5px)] px-2 py-1.5 text-sm',\n\t\t\t\t\t\t\t\t\tindex === clampedActive && 'bg-muted',\n\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{/* The chip swaps surfaces with the highlighted row (popover on muted), so its shape stays visible. */}\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t\t'text-muted-foreground truncate rounded-md px-2 py-0.5 text-xs font-medium',\n\t\t\t\t\t\t\t\t\t\tindex === clampedActive ? 'bg-popover' : 'bg-muted',\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\ttitle={option.label}\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t{isUnknown ? choiceLabel(column, option.value) : option.label}\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t{isUnknown ? <span className='text-muted-foreground text-xs'>Not in the list</span> : null}\n\t\t\t\t\t\t\t\t{isSelected ? <Check aria-hidden className='size-4 shrink-0' /> : null}\n\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t);\n\t\t\t\t\t})\n\t\t\t\t)}\n\t\t\t</ul>\n\t\t\t{multiple || (column?.nullable && selected.length > 0) ? (\n\t\t\t\t<div className='-mx-1 flex items-center justify-end gap-2 border-t px-1 pt-1'>\n\t\t\t\t\t{/* The value editors' footer: Clear when the column takes no value (a list of choices\n\t\t\t\t\t shows it disabled, with the reason, when it must have one), then Save. */}\n\t\t\t\t\t{column?.nullable ? (\n\t\t\t\t\t\t<Button size='xs' variant='ghost' className={FOOTER_BUTTON_RADIUS} onClick={() => onCommit(null)} title='Remove the value'>\n\t\t\t\t\t\t\tClear\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<Button size='xs' variant='ghost' className={FOOTER_BUTTON_RADIUS} disabled focusableWhenDisabled title={VALUE_REQUIRED_REASON}>\n\t\t\t\t\t\t\tClear\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t)}\n\t\t\t\t\t{multiple ? (\n\t\t\t\t\t\t<Button size='xs' className={FOOTER_BUTTON_RADIUS} onClick={save} title={`Save (${modifierKeyLabel()} Enter)`}>\n\t\t\t\t\t\t\tSave\n\t\t\t\t\t\t</Button>\n\t\t\t\t\t) : null}\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t</div>\n\t);\n}\n","'use client';\n\n// Native text editor — value-native single-line <input> for text/varchar cells.\n// The Phase-4 analogue of glide's built-in text overlay (text/varchar return\n// `undefined` from the glide factory to use it). Dependency-light: no UI-package\n// Button, no glide types. Commit/cancel flow through EditorProps; the\n// OverlayManager already hosts the focus-trap + error-guard + width sizing, so\n// this is just the input + a Save affordance.\n\nimport { useRef, useState } from 'react';\n\nimport { Button } from '@constructive-io/ui/button';\n\nimport { OVERLAY_SM } from '../../grid/editors/overlay-presets';\nimport { cn } from '../../utils/cn';\nimport type { EditorProps } from './editor-props';\n\nexport function TextEditor({ value, initialText, colKey, fieldMeta, onCommit, onCancel }: EditorProps) {\n\t// Type-to-edit seed (OVERWRITE): when opened by typing a printable char, start from that\n\t// char instead of the cell value; otherwise seed from the cell value as usual.\n\tconst [text, setText] = useState(() => (initialText != null ? initialText : String(value ?? '')));\n\t// COMMIT-ON-BLUR GUARD (Stage B): Escape cancels WITHOUT committing, but the cancel also\n\t// blurs the input as it unmounts — `escapedRef` tells the blur handler to skip its commit\n\t// so an Escape never double-fires as a commit.\n\tconst escapedRef = useRef(false);\n\n\tfunction handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {\n\t\tif (e.key === 'Enter') {\n\t\t\te.preventDefault();\n\t\t\tonCommit(text);\n\t\t\treturn;\n\t\t}\n\t\tif (e.key === 'Escape') {\n\t\t\te.preventDefault();\n\t\t\tescapedRef.current = true;\n\t\t\tonCancel();\n\t\t}\n\t}\n\n\t// Commit-on-click-away: commit the current value only when focus genuinely leaves the whole\n\t// overlay (the focus-trap `[role=\"dialog\"]`). We test the element focus actually MOVED TO —\n\t// `e.relatedTarget` when set, else the post-blur `document.activeElement` — against the\n\t// dialog root, NOT the text-editor slot. This is what distinguishes a real click-away (focus\n\t// lands on body / an outside element) from the open-time focus churn the EditorFocusTrap\n\t// causes (focus momentarily lands on the trap CONTAINER, which is inside the dialog but\n\t// outside the slot — committing on that would fire a spurious commit on mount). Clicking the\n\t// in-overlay Save button keeps focus inside the dialog, so it does NOT double-commit either.\n\t// Skipped right after an Escape-cancel (escapedRef).\n\tfunction handleBlur(e: React.FocusEvent<HTMLInputElement>) {\n\t\tif (escapedRef.current) return;\n\t\t// Containment root: the focus-trap dialog in production (so the trap container counts as\n\t\t// \"inside\"); the editor slot when rendered bare (tests). Use whichever encloses the input.\n\t\tconst root = e.currentTarget.closest('[role=\"dialog\"]') ?? e.currentTarget.closest('[data-slot=\"text-editor\"]');\n\t\tconst landed = (e.relatedTarget as Node | null) ?? document.activeElement;\n\t\tif (root && landed && root.contains(landed)) return;\n\t\tonCommit(text);\n\t}\n\n\treturn (\n\t\t<div data-slot='text-editor' className={cn('bg-popover flex items-center gap-2 rounded-lg border p-2.5 shadow-lg', OVERLAY_SM)}>\n\t\t\t<input\n\t\t\t\taria-label={`Edit ${fieldMeta?.name ?? colKey}`}\n\t\t\t\tvalue={text}\n\t\t\t\tonChange={(e) => setText(e.target.value)}\n\t\t\t\tonKeyDown={handleKeyDown}\n\t\t\t\tonBlur={handleBlur}\n\t\t\t\tspellCheck={false}\n\t\t\t\tclassName='bg-muted/40 border-border/40 min-w-0 flex-1 rounded-md border px-2.5 py-1.5 font-sans text-sm outline-none focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/35'\n\t\t\t\tautoFocus\n\t\t\t/>\n\t\t\t<Button onClick={() => onCommit(text)} size='xs' variant='default' className='shrink-0'>\n\t\t\t\tSave\n\t\t\t</Button>\n\t\t</div>\n\t);\n}\n\n// Opt this editor into commit-on-click-away (Stage B): the OverlayManager reads this off the\n// resolved component to pick `dismissMode='commit'` (blur the input → onBlur commits) instead\n// of cancelling. Only editors with a real `onBlur → onCommit` set this.\nTextEditor.commitsOnBlur = true as const;\n","// Read-only viewer for a full-text search value: the keywords it holds as chips, the\n// stored value as text, and why it cannot be changed here. The host (the grid overlay\n// or the record panel) owns focus, Escape and a press outside; Close is the only\n// control, so it takes focus first.\n\nimport { useMemo } from 'react';\n\nimport { Button } from '@constructive-io/ui/button';\n\nimport { cn } from '../../utils/cn';\nimport { OVERLAY } from './overlay-presets';\n\ntype Weight = 'A' | 'B' | 'C' | 'D';\ninterface Keyword {\n\tword: string;\n\tweights: Weight[];\n}\n\n/** The keywords of a stored search value (`'cat':1A 'fast':2B`), or its words when it is plain text. */\nfunction parseKeywords(stored: string): Keyword[] {\n\tconst keywords: Keyword[] = [];\n\tconst pattern = /'([^']+)':([0-9A-D,]+)/g;\n\tlet match: RegExpExecArray | null;\n\twhile ((match = pattern.exec(stored)) !== null) {\n\t\tconst weights = new Set<Weight>();\n\t\tfor (const position of match[2]!.split(',')) {\n\t\t\tconst weight = /[A-D]$/.exec(position)?.[0] as Weight | undefined;\n\t\t\tif (weight) weights.add(weight);\n\t\t}\n\t\tkeywords.push({ word: match[1]!, weights: [...weights].sort() });\n\t}\n\tif (keywords.length > 0) return keywords;\n\treturn stored\n\t\t.split(/\\s+/)\n\t\t.filter(Boolean)\n\t\t.map((word): Keyword => ({ word, weights: [] }));\n}\n\ninterface TsvectorViewerProps {\n\tvalue: unknown;\n\t/** The field's readable name. */\n\ttitle: string;\n\t/** Why the value cannot be changed here. */\n\tnote: string;\n\tonClose: () => void;\n}\n\nexport function TsvectorViewer({ value, title, note, onClose }: TsvectorViewerProps) {\n\tconst stored = typeof value === 'string' ? value : '';\n\tconst keywords = useMemo(() => parseKeywords(stored), [stored]);\n\tconst weighted = keywords.some((keyword) => keyword.weights.length > 0);\n\n\treturn (\n\t\t<div data-slot='tsvector-viewer' className={cn('bg-popover flex flex-col gap-2 rounded-lg border p-3 shadow-lg', OVERLAY.md)}>\n\t\t\t<div className='flex items-baseline justify-between gap-2'>\n\t\t\t\t<h3 className='text-sm font-medium'>{title}</h3>\n\t\t\t\t<span className='text-muted-foreground text-xs tabular-nums'>\n\t\t\t\t\t{keywords.length} {keywords.length === 1 ? 'keyword' : 'keywords'}\n\t\t\t\t</span>\n\t\t\t</div>\n\t\t\t{keywords.length > 0 ? (\n\t\t\t\t// Chips sit 4px inside the 8px box, so their corners are 8px - 4px.\n\t\t\t\t<ul aria-label='Search keywords' className='bg-muted/40 flex max-h-32 flex-wrap gap-1 overflow-y-auto rounded-md p-1'>\n\t\t\t\t\t{keywords.map((keyword, index) => (\n\t\t\t\t\t\t<li\n\t\t\t\t\t\t\tkey={`${index}-${keyword.word}`}\n\t\t\t\t\t\t\tclassName='bg-muted text-muted-foreground rounded-[calc(var(--radius-md)-4px)] px-2 py-0.5 text-xs font-medium'\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{keyword.word}\n\t\t\t\t\t\t\t{keyword.weights.length > 0 ? <span className='text-muted-foreground/70 ms-1'>{keyword.weights.join(' ')}</span> : null}\n\t\t\t\t\t\t</li>\n\t\t\t\t\t))}\n\t\t\t\t</ul>\n\t\t\t) : (\n\t\t\t\t<p className='text-muted-foreground text-sm'>No keywords</p>\n\t\t\t)}\n\t\t\t{stored ? (\n\t\t\t\t<div className='flex flex-col gap-1'>\n\t\t\t\t\t<span className='text-muted-foreground text-xs font-medium'>Stored value</span>\n\t\t\t\t\t<pre className='bg-muted/40 m-0 max-h-24 overflow-auto rounded-md p-2 font-mono text-xs break-all whitespace-pre-wrap'>{stored}</pre>\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t\t<p className='text-muted-foreground text-xs'>\n\t\t\t\t{weighted ? 'A letter after a keyword shows how much it counts in a search, from A (most) to D (least). ' : null}\n\t\t\t\t{note}\n\t\t\t</p>\n\t\t\t<div className='flex justify-end border-t pt-2'>\n\t\t\t\t<Button size='xs' variant='outline' onClick={onClose} autoFocus>\n\t\t\t\t\tClose\n\t\t\t\t</Button>\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n","'use client';\n\n// Native viewer for a full-text search value: an EditorProps adapter for the read-only\n// `TsvectorViewer`. There is no write path: Close, Escape and a press outside all cancel.\n// The host (overlay or record panel) provides the focus trap.\n\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { VIEW_ONLY_REASON } from '../../cell-types/column-value';\nimport { TsvectorViewer } from '../../grid/editors/tsvector-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function TsvectorEditorDom({ value, column, colKey, readOnlyReason, onCancel }: EditorProps) {\n\treturn (\n\t\t<TsvectorViewer\n\t\t\tvalue={value}\n\t\t\ttitle={fieldLabel(column?.name ?? colKey)}\n\t\t\tnote={readOnlyReason ?? VIEW_ONLY_REASON}\n\t\t\tonClose={() => onCancel()}\n\t\t/>\n\t);\n}\n","import React, { useCallback, useState } from 'react';\nimport { ExternalLink } from 'lucide-react';\n\nimport { cn } from '../../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\nimport { Input } from '@constructive-io/ui/input';\n\nimport { openUriCellLink } from '../../cell-model/uri-link';\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { EditorFooter, EditorHeader, editorClear, modifierKeyLabel } from './editor-frame';\nimport { OVERLAY } from './overlay-presets';\n\ninterface UrlEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n\t/** The field's readable name, shown as the title. */\n\ttitle?: string;\n\t/** The column takes no value, so Clear is offered. */\n\tnullable?: boolean;\n}\n\nfunction isValidUrl(string: string): boolean {\n\tif (!string || typeof string !== 'string') return false;\n\n\ttry {\n\t\t// Add protocol if missing for validation\n\t\tconst urlToTest = string.startsWith('http') ? string : `https://${string}`;\n\t\tnew URL(urlToTest);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction formatUrl(url: string): string {\n\tif (!url) return '';\n\n\t// Add https:// if no protocol is specified\n\tif (url && !url.startsWith('http://') && !url.startsWith('https://')) {\n\t\treturn `https://${url}`;\n\t}\n\n\treturn url;\n}\n\nfunction displayUrl(url: string): string {\n\tif (!url) return '';\n\n\t// Remove protocol for display to save space\n\treturn url.replace(/^https?:\\/\\//, '');\n}\n\nexport const UrlEditor: React.FC<UrlEditorProps> = ({ value, onFinishedEditing, title = 'Web address', nullable = false }) => {\n\t// Extract current URL data from the raw value\n\tconst currentUrlData = typeof value === 'string' ? value : '';\n\tconst [editingValue, setEditingValue] = useState<string>(currentUrlData);\n\tconst [validationError, setValidationError] = useState<string>('');\n\n\tconst handleSave = useCallback(() => {\n\t\t// Validate URL before saving\n\t\tif (editingValue.trim() && !isValidUrl(editingValue.trim())) {\n\t\t\tsetValidationError('Please enter a valid URL');\n\t\t\treturn;\n\t\t}\n\n\t\tconst formattedUrl = editingValue.trim() ? formatUrl(editingValue.trim()) : '';\n\t\tonFinishedEditing(formattedUrl);\n\t}, [editingValue, onFinishedEditing]);\n\n\tconst handleCancel = useCallback(() => {\n\t\tonFinishedEditing();\n\t}, [onFinishedEditing]);\n\n\tconst handleInputChange = useCallback(\n\t\t(e: React.ChangeEvent<HTMLInputElement>) => {\n\t\t\tconst newValue = e.target.value;\n\t\t\tsetEditingValue(newValue);\n\n\t\t\t// Clear validation error when user starts typing\n\t\t\tif (validationError) {\n\t\t\t\tsetValidationError('');\n\t\t\t}\n\t\t},\n\t\t[validationError],\n\t);\n\n\t// Handle Ctrl+Enter to save\n\tconst handleEditorKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent) => {\n\t\t\tif (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {\n\t\t\t\te.preventDefault();\n\t\t\t\thandleSave();\n\t\t\t}\n\t\t},\n\t\t[handleSave],\n\t);\n\n\tconst isValid = !editingValue.trim() || isValidUrl(editingValue.trim());\n\tconst displayText = editingValue.trim() ? displayUrl(editingValue.trim()) : '';\n\t// Opened through the grid's link rule (http and https only, no opener).\n\tconst openable = editingValue.trim() && isValid ? formatUrl(editingValue.trim()) : null;\n\n\treturn (\n\t\t<EditorFocusTrap onEscape={handleCancel} className={`bg-popover flex ${OVERLAY.md} flex-col gap-3 rounded-lg border p-3 shadow-lg`}>\n\t\t\t<div onKeyDown={handleEditorKeyDown} className='flex flex-col gap-3'>\n\t\t\t\t<EditorHeader title={title} />\n\t\t\t\t<div className='flex flex-col gap-1.5'>\n\t\t\t\t\t<Input\n\t\t\t\t\t\tid='url'\n\t\t\t\t\t\ttype='url'\n\t\t\t\t\t\taria-label={title}\n\t\t\t\t\t\tvalue={editingValue}\n\t\t\t\t\t\tonChange={handleInputChange}\n\t\t\t\t\t\tplaceholder='https://example.com'\n\t\t\t\t\t\tclassName={cn('text-sm', validationError && 'border-destructive focus-visible:ring-destructive')}\n\t\t\t\t\t\tautoFocus\n\t\t\t\t\t/>\n\t\t\t\t\t{validationError ? (\n\t\t\t\t\t\t<p className='text-destructive text-xs'>{validationError}</p>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<p className='text-muted-foreground text-xs'>https:// is added when the address has no scheme.</p>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t\t{displayText ? (\n\t\t\t\t\t<div className='bg-muted/40 flex min-w-0 items-center gap-2 rounded-md px-2.5 py-1.5 text-sm'>\n\t\t\t\t\t\t{isValid ? (\n\t\t\t\t\t\t\t<>\n\t\t\t\t\t\t\t\t<span className='text-link min-w-0 flex-1 truncate'>{displayText}</span>\n\t\t\t\t\t\t\t\t{openable ? (\n\t\t\t\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\t\t\t\t\tsize='icon-xs'\n\t\t\t\t\t\t\t\t\t\tonClick={() => openUriCellLink(openable)}\n\t\t\t\t\t\t\t\t\t\taria-label='Open link in a new tab'\n\t\t\t\t\t\t\t\t\t\ttitle='Open link in a new tab'\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<ExternalLink aria-hidden />\n\t\t\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t</>\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<span className='text-destructive min-w-0 truncate'>Not a valid web address</span>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</div>\n\t\t\t\t) : null}\n\t\t\t\t<EditorFooter\n\t\t\t\t\tonSave={handleSave}\n\t\t\t\t\tsaveShortcut={`${modifierKeyLabel()} Enter`}\n\t\t\t\t\tsaveBlockedReason={validationError || null}\n\t\t\t\t\tclear={editorClear(nullable, () => onFinishedEditing(null))}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","// The one rule for opening the address in an email or web address cell, shared by the\n// cell view (its link) and the grid's \"Open link\" command. A web address cell holds text\n// that people typed, so only http, https and mailto addresses ever open: a typed\n// `javascript:` or `data:` address must never run, and text that is not a full address\n// (`example.com`) is not a link.\n\nimport type { SheetsCell } from './sheets-cell';\n\nconst OPENABLE_PROTOCOLS: ReadonlySet<string> = new Set(['http:', 'https:', 'mailto:']);\n\n/** The address as the browser would open it, or null when it is not a full http, https or mailto address. */\nfunction openableHref(text: string): string | null {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(text);\n\t} catch {\n\t\treturn null;\n\t}\n\treturn OPENABLE_PROTOCOLS.has(url.protocol) ? url.href : null;\n}\n\n/** The address a link cell (`kind: 'uri'`) opens, or null: an empty cell, another kind, or an address that may not open. */\nexport function uriCellHref(cell: SheetsCell): string | null {\n\tif (cell.kind !== 'uri' || typeof cell.data !== 'string' || cell.data === '') return null;\n\treturn openableHref(cell.data);\n}\n\n/**\n * Open a link cell's address: a web address in a new tab (no opener, no referrer), an\n * email address in the mail app. An address that may not open is ignored.\n */\nexport function openUriCellLink(href: string): void {\n\tconst safe = openableHref(href);\n\tif (!safe) return;\n\t// A mailto address hands off to the mail app without leaving the page; in a new tab it\n\t// would leave an empty tab behind.\n\tif (safe.startsWith('mailto:')) window.open(safe, '_self');\n\telse window.open(safe, '_blank', 'noopener,noreferrer');\n}\n","'use client';\n\n// Native URL editor — a thin EditorProps adapter that RE-HOSTS the (now value-\n// native) `UrlEditor` verbatim. Its UI (input + preview + test-link + OVERLAY.md\n// width + own EditorFocusTrap) is reused as-is; the contract maps directly to\n// value-native EditorProps.\n//\n// VALUE editor (no server mutation): the editor reads the raw row value and emits\n// the formatted URL string back, so the value flows straight through:\n// `onFinishedEditing(next)` -> `onCommit(next)`, `onFinishedEditing(undefined)`\n// (cancel / Escape) -> `onCancel()`. Parity note: glide url cells fell back to the\n// built-in text overlay, so this is a ported, consumer-overridable editor (not\n// registry-wired by default).\n\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { UrlEditor } from '../../grid/editors/url-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function UrlEditorDom({ value, column, colKey, onCommit, onCancel }: EditorProps) {\n\treturn (\n\t\t<div data-slot='url-editor'>\n\t\t\t<UrlEditor\n\t\t\t\tvalue={value}\n\t\t\t\ttitle={fieldLabel(column?.name ?? colKey)}\n\t\t\t\tnullable={Boolean(column?.nullable)}\n\t\t\t\tonFinishedEditing={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t\t/>\n\t\t</div>\n\t);\n}\n","'use client';\n\n// Read-only viewer for values the grid shows but does not edit: raw bytes, number\n// vectors and values of a kind the grid does not know. It shows the whole value and\n// a short summary (size or length), says why the value cannot be changed here, and\n// copies the value as text.\n\nimport { useState } from 'react';\n\nimport { Button } from '@constructive-io/ui/button';\n\nimport { OVERLAY_MD } from '../../grid/editors/overlay-presets';\nimport { formatColumnValue, VIEW_ONLY_REASON } from '../../cell-types/column-value';\nimport { fieldLabel } from '../../cell-types/field-label';\nimport { cn } from '../../utils/cn';\nimport type { EditorProps } from './editor-props';\n\nfunction summary(cellType: string | undefined, value: unknown): string | null {\n\tif (value === null || value === undefined) return 'No value';\n\tif (cellType === 'binary' && typeof value === 'string') {\n\t\tconst clean = value.replace(/\\s/g, '');\n\t\tconst padding = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;\n\t\tconst size = Math.max(0, Math.floor((clean.length * 3) / 4) - padding);\n\t\treturn `${size} ${size === 1 ? 'byte' : 'bytes'}, shown as base64`;\n\t}\n\tif (Array.isArray(value)) return `${value.length} ${value.length === 1 ? 'item' : 'items'}`;\n\treturn null;\n}\n\nexport function ValueViewerDom({ value, column, colKey, cell, readOnlyReason, onCancel }: EditorProps) {\n\tconst [copied, setCopied] = useState(false);\n\tconst text = formatColumnValue(column, value);\n\tconst detail = summary(cell.meta?.cellType, value);\n\n\tfunction copy() {\n\t\tconst clipboard = typeof navigator !== 'undefined' ? navigator.clipboard : undefined;\n\t\tif (!clipboard) return;\n\t\tvoid clipboard.writeText(text).then(() => setCopied(true)).catch(() => setCopied(false));\n\t}\n\n\treturn (\n\t\t<div data-slot='value-viewer' className={cn('bg-popover flex flex-col gap-2 rounded-lg border p-3 shadow-lg', OVERLAY_MD)}>\n\t\t\t<div className='flex items-baseline justify-between gap-2'>\n\t\t\t\t<h3 className='text-sm font-medium'>{fieldLabel(column?.name ?? colKey)}</h3>\n\t\t\t\t{detail ? <span className='text-muted-foreground text-xs'>{detail}</span> : null}\n\t\t\t</div>\n\t\t\t<pre className='bg-muted/40 max-h-64 overflow-auto rounded-md p-2 text-xs break-all whitespace-pre-wrap'>{text}</pre>\n\t\t\t<p className='text-muted-foreground text-xs'>{readOnlyReason ?? VIEW_ONLY_REASON}</p>\n\t\t\t<div className='flex justify-end gap-2 border-t pt-2'>\n\t\t\t\t<Button size='xs' variant='outline' onClick={copy} disabled={!text} autoFocus>\n\t\t\t\t\t{copied ? 'Copied' : 'Copy'}\n\t\t\t\t</Button>\n\t\t\t\t<Button size='xs' variant='ghost' onClick={onCancel}>\n\t\t\t\t\tClose\n\t\t\t\t</Button>\n\t\t\t</div>\n\t\t</div>\n\t);\n}\n","// Native (DOM React-portal) editor registry — the Phase-4 analogue of the glide\n// `grid/editor-registry.ts` `EDITOR_REGISTRY` + `createEditor`, but value-native.\n//\n// The OverlayManager already supplies the focus-trap, error-guard, flip geometry\n// and overlay-preset width class, so a native editor is just a `ComponentType<\n// EditorProps>` — no glide `ProvideEditorCallbackResult`/`disableStyling` wrapper.\n// `wrapNativeEditor` is therefore a thin passthrough that only TAGS a preset width\n// class (so the OverlayManager can read it) — it does NOT re-wrap the trap/guard.\n//\n// `resolveNativeEditor` mirrors the glide precedence: a consumer override\n// (`def.editor`, looked up via the injected `consumer` fn) wins, else the\n// built-in `DOM_EDITOR_REGISTRY` entry. The `consumer` lookup is injected (not the\n// CellTypeRegistry directly) so this module stays decoupled from the registry\n// shape; Stage 3+ wires `registry.getEditorComponent` in at the call site.\n//\n// PER-EDITOR COMMIT PATTERN (Phase 5 fan-out — every native re-host must follow one):\n// • VALUE editors (text/json/date/geometry/interval/inet/array/tsvector/url):\n// read the initial value from `EditorProps.value`; on save call\n// `onCommit(nextRawValue)` (the host serialises + builds the cell). Cancel ->\n// `onCancel()`. These DO NOT mutate the server.\n// • IMAGE/upload (self-committing): the editor uploads, then\n// `onCommitPatch({ [colKey]: imageData })` (single field). On a DRAFT row it\n// must first `onSubmitDraftRow(draftRowId)` to obtain a real id, and use\n// `onInvalidateData` as the post-upload `onDraftUploadComplete`.\n// • RELATION (self-committing): the editor mutates, then\n// `onCommitPatch({ [foreignKeyField]: fkValue, [relationField ?? colKey]: relationData })`\n// (MULTI field for belongsTo). FK/display fields come from EditorProps.relationInfo.\n// The host wires onCommit/onCommitPatch/onSubmitDraftRow/onInvalidateData/onCancel\n// in SheetsDomInner; an editor only PICKS the matching callback(s) for its kind.\n\nimport type { ComponentType } from 'react';\n\nimport { ArrayEditorDom } from './array-editor';\nimport { DateEditorDom } from './date-editor';\nimport type { EditorProps } from './editor-props';\nimport { GeometryEditorDom } from './geometry-editor';\nimport { ImageEditorDom } from './image-editor';\nimport { InetEditorDom } from './inet-editor';\nimport { IntervalEditorDom } from './interval-editor';\nimport { JsonEditorDom } from './json-editor';\nimport { NumberEditorDom } from './number-editor';\nimport { RangeEditorDom } from './range-editor';\nimport { RecordEditorDom } from './record-editor';\nimport { RelationEditorDom } from './relation-editor';\nimport { SelectEditorDom } from './select-editor';\nimport { TextEditor } from './text-editor';\nimport { TsvectorEditorDom } from './tsvector-editor';\nimport { UrlEditorDom } from './url-editor';\nimport { ValueViewerDom } from './value-viewer';\n\n/**\n * A native editor that optionally advertises its overlay-preset width class and whether it\n * commits-on-click-away (Stage B): `commitsOnBlur` editors own an `onBlur → onCommit` path,\n * so the OverlayManager dismisses them with `dismissMode='commit'` (blur the input → commit)\n * instead of cancelling. Editors without it keep cancel-on-outside.\n */\nexport type NativeEditor = ComponentType<EditorProps> & { overlayPresetClass?: string; commitsOnBlur?: boolean };\n\n/**\n * Tag a native editor with an overlay-preset width class so the OverlayManager can\n * size the portal. Thin passthrough — the trap/guard/geometry are the manager's job.\n */\nexport function wrapNativeEditor(Editor: ComponentType<EditorProps>, presetClass?: string): NativeEditor {\n\tif (!presetClass) return Editor;\n\tconst wrapped = Editor as NativeEditor;\n\t// Tag in place — no re-render wrapper needed; the manager reads the class off\n\t// the resolved component. (A fresh object would break referential identity of\n\t// memoised editors, so we annotate the component the registry already holds.)\n\twrapped.overlayPresetClass = presetClass;\n\treturn wrapped;\n}\n\n// Built-in native editors, keyed by cell-type key. This is the CONSUMER-FACING\n// overlay-editor table — the type->component map `resolveEditIntent` reads when it\n// decides a type opens an overlay. It now covers EVERY type the authoritative\n// edit-intent enumeration routes to an overlay (edit-intent.ts), so the host never\n// falls back to TextEditor for a typed cell:\n// • number/integer/smallint/decimal/currency/percentage/rating -> NumberEditorDom.\n// • url -> UrlEditorDom (native, wired here — went through the text overlay before\n// the routing fix). NOTE: `color` is NOT here — it is not a real backend data\n// type (just a hex/text string), so it routes to the plain TextEditor via the\n// edit-intent text-like default; there is no dedicated color editor.\n// • image/file/video/audio/upload -> ImageEditorDom (the media family).\n// (Booleans are NOT here — they are an inline toggle with no overlay; see edit-intent.)\nexport const DOM_EDITOR_REGISTRY: Record<string, NativeEditor> = {\n\t// Text types\n\ttext: TextEditor,\n\tvarchar: TextEditor,\n\tbitstring: TextEditor,\n\tpath: TextEditor,\n\t// Choices (enums, allowed-values text)\n\tselect: SelectEditorDom,\n\t'multi-select': SelectEditorDom,\n\t// Number types (the whole NUMBER_TYPES family, incl. rating)\n\tnumber: NumberEditorDom,\n\tinteger: NumberEditorDom,\n\tsmallint: NumberEditorDom,\n\tbigint: NumberEditorDom,\n\tdecimal: NumberEditorDom,\n\tcurrency: NumberEditorDom,\n\tpercentage: NumberEditorDom,\n\trating: NumberEditorDom,\n\t// Media types (the whole MEDIA_TYPES family reuses the image editor, as in glide)\n\timage: ImageEditorDom,\n\tfile: ImageEditorDom,\n\tvideo: ImageEditorDom,\n\taudio: ImageEditorDom,\n\tupload: ImageEditorDom,\n\tattachment: ImageEditorDom,\n\t// Date/time types\n\tdate: DateEditorDom,\n\tdatetime: DateEditorDom,\n\ttimestamptz: DateEditorDom,\n\ttime: DateEditorDom,\n\t// Geometry types\n\tgeometry: GeometryEditorDom,\n\t'geometry-point': GeometryEditorDom,\n\t'geometry-collection': GeometryEditorDom,\n\t// Other complex types\n\tinterval: IntervalEditorDom,\n\trange: RangeEditorDom,\n\tcomposite: RecordEditorDom,\n\tpoint: RecordEditorDom,\n\t// View-only kinds open a viewer that shows and copies the value\n\tbinary: ValueViewerDom,\n\tvector: ValueViewerDom,\n\tunknown: ValueViewerDom,\n\trelation: RelationEditorDom,\n\ttsvector: TsvectorEditorDom,\n\tinet: InetEditorDom,\n\turl: UrlEditorDom,\n\t// Array types\n\tarray: ArrayEditorDom,\n\t'text-array': ArrayEditorDom,\n\t'uuid-array': ArrayEditorDom,\n\t'number-array': ArrayEditorDom,\n\t'integer-array': ArrayEditorDom,\n\t'date-array': ArrayEditorDom,\n\ttags: ArrayEditorDom,\n\t// JSON types\n\tjson: JsonEditorDom,\n\tjsonb: JsonEditorDom,\n};\n\n/**\n * Resolve the native editor for a type key. A consumer override wins (mirrors the\n * glide `def.editor` precedence), else the built-in `DOM_EDITOR_REGISTRY` entry.\n *\n * @param typeKey - resolved cell-type key (e.g. `text`, `json`).\n * @param consumer - optional per-instance override lookup (`registry.getEditorComponent`).\n */\nexport function resolveNativeEditor(\n\ttypeKey: string,\n\tconsumer?: (typeKey: string) => ComponentType<EditorProps> | undefined,\n): NativeEditor | undefined {\n\treturn consumer?.(typeKey) ?? DOM_EDITOR_REGISTRY[typeKey];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,eAAe,kBAAkB;AAqBnC,IAAM,yBAAyB,cAA6C,IAAI;AAGhF,SAAS,sBAAqD;AACpE,SAAO,WAAW,sBAAsB;AACzC;AAgBO,IAAM,0BAA0B,cAA8C,IAAI;AAGlF,SAAS,uBAAuD;AACtE,SAAO,WAAW,uBAAuB;AAC1C;;;ACrBO,IAAM,mBAAmB;AAEhC,IAAM,KAAK,CAAC,WAAuC,EAAE,IAAI,MAAM,MAAM;AACrE,IAAM,OAAO,CAAC,YAAuC,EAAE,IAAI,OAAO,OAAO;AAEzE,IAAM,kBAAgD,oBAAI,IAAI,CAAC,UAAU,UAAU,YAAY,SAAS,CAAC;AACzG,IAAM,kBAAgD,oBAAI,IAAI,CAAC,QAAQ,aAAa,WAAW,MAAM,CAAC;AAEtG,IAAM,YAAY;AAClB,IAAM,YAAY;AAElB,IAAM,YAAY,OAAO,sBAAsB;AAC/C,IAAM,YAAY,OAAO,qBAAqB;AAE9C,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,UAAU;AAChB,IAAM,UAAU;AAChB,IAAM,UAAU;AAChB,IAAM,cAAc;AACpB,IAAM,UAAU;AAChB,IAAM,kBAAkB,CAAC,SAAS,UAAU,QAAQ,SAAS,WAAW,SAAS;AACjF,IAAM,sBAAwE;AAA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Y;AAAA,EACZ,QAAQ;AAAA;AAAA,EAER,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,YAAY;AAAA;AAAA,EAEZ,MAAM;AAAA,EACN,UAAU;AAAA,EACV,aAAa;AAAA,EACb,MAAM;AAAA;AAAA,EAEN,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,uBAAuB;AAAA;AAAA,EAEvB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,WAAW;AAAA,EACX,OAAO;AAAA;AAAA,EAEP,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AAAA,EACV,MAAM;AAAA,EACN,KAAK;AAAA;AAAA,EAEL,OAAO;AAAA,EACP,cAAc;AAAA,EACd,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,cAAc;AAAA,EACd,MAAM;AAAA;AAAA,EAEN,MAAM;AAAA,EACN,OAAO;AACR;AASO,SAAS,oBACf,SACA,UAC2B;AAC3B,SAAO,WAAW,OAAO,KAAK,oBAAoB,OAAO;AAC1D;","names":["column","text","baseType","column","column","column","column","TableModelError","TableModelError","document","text","column","column","column","column","createContext","useContext","plural","ok","createContext","dismissAfter","useContext","createContext","useContext","jsx","column","useCallback","useMemo","useQuery","TableModelError","TableModelError","useMemo","useQuery","useCallback","canHandle","create","canHandle","create","text","canHandle","create","summary","display","file","column","canHandle","create","canHandle","create","column","text","recordLabel","canHandle","create","relationLinks","label","isRecord","end","display","text","size","summary","canHandle","create","canHandle","create","display","canHandle","create","useCallback","useMemo","useQuery","createError","MetaContractError","metaTablesOf","tableKeyOf","details","column","operator","createError","details","details","createError","column","column","createError","column","resolveUrls","previewKey","details","file","getErrorCode","getErrorCode","column","useCallback","column","useCallback","column","useQuery","loaded","useMemo","useCallback","useMemo","jsx","useMemo","useCallback","useCallback","useEffect","useMemo","useRef","jsx","useMemo","useRef","useCallback","useEffect","add","handleSave","remove","handleCancel","input","jsx","column","useCallback","useState","jsx","jsx","column","useState","useCallback","useContext","useLayoutEffect","useMemo","useRef","useState","Map","React","lazy","Suspense","useCallback","useEffect","useRef","useState","XIcon","useContext","useMemo","useContext","useMemo","jsx","jsxs","lazy","React","useState","useRef","useCallback","useEffect","XIcon","Suspense","React","jsx","jsxs","useMemo","useState","useCallback","useContext","useRef","useLayoutEffect","Map","jsx","column","Suspense","useCallback","useContext","useMemo","useRef","Loader2","Button","useState","useCallback","useEffect","useRef","jsx","jsxs","useState","XIcon","useCallback","useMemo","useRef","useState","useQuery","loaders","resolve","useMemo","useQuery","query","useState","useRef","useCallback","Fragment","jsx","jsxs","details","XIcon","useCallback","useEffect","useMemo","useRef","useState","column","useState","useRef","useCallback","useEffect","useMemo","jsx","jsxs","useContext","useRef","column","useMemo","useCallback","Button","Loader2","jsx","DRAFT_PREFIX","column","Suspense","useCallback","useEffect","useRef","useState","jsx","jsxs","useState","useRef","useCallback","useEffect","handleSave","handleCancel","jsx","column","useCallback","useState","jsx","jsxs","useState","useCallback","useMemo","useState","Button","jsx","jsxs","column","useMemo","useState","text","Button","jsx","column","useCallback","useEffect","useMemo","useRef","useState","jsx","jsxs","text","useState","useRef","useMemo","useCallback","useEffect","handleSave","handleCancel","jsx","column","useRef","useState","Button","jsx","jsxs","seedText","text","column","useState","useRef","Button","useState","text","jsx","jsxs","column","useState","useCallback","useContext","useState","ExternalLink","Button","useState","Button","Input","Label","Fragment","jsx","jsxs","Label","Input","useState","Button","useMemo","Loader2","Badge","Button","jsx","jsxs","useMemo","Badge","Loader2","Button","useEffect","useId","useMemo","useRef","useState","Loader2","Badge","Button","InputGroup","InputGroupAddon","InputGroupInput","jsx","jsxs","useId","useState","useRef","useMemo","useEffect","Badge","InputGroup","InputGroupAddon","InputGroupInput","Loader2","Button","Fragment","jsx","jsxs","useState","create","Button","ExternalLink","useCallback","useEffect","useMemo","useState","useQueryClient","invalid","text","column","createContext","useContext","operationIssue","column","reason","patch","column","column","text","useMemo","pages","useMemo","useMemo","useMemo","key","useCallback","useMemo","useState","useState","useMemo","useCallback","useState","useEffect","useQueryClient","useMemo","useCallback","options","plan","jsx","jsxs","useContext","useCallback","jsx","DRAFT_PREFIX","useEffect","useMemo","useRef","useState","Check","Button","jsx","jsxs","column","useMemo","useState","useRef","useEffect","Check","Button","useRef","useState","Button","jsx","jsxs","text","useState","useRef","Button","useMemo","Button","jsx","jsxs","useMemo","Button","jsx","column","useCallback","useState","ExternalLink","Button","Input","text","Fragment","jsx","jsxs","useState","useCallback","Input","Button","ExternalLink","jsx","column","useState","Button","jsx","jsxs","size","column","useState","text","Button"]}
|