@constructive-io/sheets 0.14.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 -157
- package/dist/advanced.cjs +7192 -3840
- 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-BYAYBXVB.js → chunk-J7KK4UWI.js} +6 -6
- package/dist/chunk-MBSHDF55.js +839 -0
- package/dist/chunk-MBSHDF55.js.map +1 -0
- package/dist/chunk-MOFFS5WQ.js +128 -0
- 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-YJZFHL2D.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-C2-ocDS7.d.cts → grid-cell-types-YNIVK4hN.d.cts} +71 -18
- package/dist/{grid-cell-types-C2-ocDS7.d.ts → grid-cell-types-YNIVK4hN.d.ts} +71 -18
- package/dist/index.cjs +22733 -12052
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1432 -266
- package/dist/index.d.ts +1432 -266
- package/dist/index.js +12688 -6097
- 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 +1170 -589
- 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 +778 -147
- package/dist/testing.js.map +1 -1
- package/package.json +4 -5
- package/dist/chunk-4EZ6A23C.js +0 -44
- package/dist/chunk-4EZ6A23C.js.map +0 -1
- package/dist/chunk-6Y7CZ5VS.js +0 -168
- package/dist/chunk-6Y7CZ5VS.js.map +0 -1
- package/dist/chunk-BGL6EBTE.js +0 -446
- package/dist/chunk-BGL6EBTE.js.map +0 -1
- package/dist/chunk-ER3FIDK7.js +0 -4383
- package/dist/chunk-ER3FIDK7.js.map +0 -1
- package/dist/chunk-GZM2CSTR.js +0 -279
- package/dist/chunk-GZM2CSTR.js.map +0 -1
- package/dist/chunk-X7DHTSOX.js +0 -21
- package/dist/chunk-X7DHTSOX.js.map +0 -1
- package/dist/chunk-YJZFHL2D.js.map +0 -1
- package/dist/date-editor-G26WKILO.js +0 -358
- package/dist/date-editor-G26WKILO.js.map +0 -1
- package/dist/map-picker-ZUGGOIZS.js +0 -290
- package/dist/map-picker-ZUGGOIZS.js.map +0 -1
- package/dist/sheets-context-CHUVJCff.d.ts +0 -245
- package/dist/sheets-context-C_MkTxXm.d.cts +0 -245
- /package/dist/{chunk-BYAYBXVB.js.map → chunk-J7KK4UWI.js.map} +0 -0
package/dist/advanced.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/grid/editors/editor-focus-trap.tsx","../src/grid/editors/overlay-presets.ts","../src/cell-types/cell-type-groups.ts","../src/utils/sheets-i18n.ts","../src/grid/editors/date-editor.tsx","../src/utils/cn.ts","../src/utils/sheets-logger.ts","../src/utils/map-picker.tsx","../src/advanced.ts","../src/grid/editors/array-editor.tsx","../src/grid-dom/editors/array-editor.tsx","../src/grid-dom/editors/date-editor.tsx","../src/grid-dom/editors/geometry-editor.tsx","../src/grid/editors/geometry-editor.tsx","../src/grid/editors/overlay-viewport-guard.tsx","../src/grid-dom/editors/image-editor.tsx","../src/grid/editors/image-editor.tsx","../src/hooks/use-sheets-upload.ts","../src/adapter/postgraphile-adapter.ts","../src/hooks/use-sheets-table.ts","../src/hooks/use-sheets-meta.ts","../src/context/sheets-context.ts","../src/hooks/query-keys.ts","../src/hooks/relation-field-resolution.ts","../src/hooks/orderby-enum-resolution.ts","../src/row-identity.ts","../src/adapter/use-sheets-adapter.ts","../src/hooks/use-sheets-media-url.ts","../src/context/sheets-upload-presigned.ts","../src/utils/file.utils.ts","../src/utils/use-image-status.ts","../src/utils/image-with-fallback.tsx","../src/grid/editors/inet-editor.tsx","../src/grid-dom/editors/inet-editor.tsx","../src/grid/editors/interval-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/editors/relation-editor.tsx","../src/hooks/use-sheets-table-cursor.ts","../src/store/sheets-store.ts","../src/grid/editors/relation-record-tooltip.tsx","../src/grid-dom/editors/relation-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/grid-dom/editors/url-editor.tsx","../src/grid-dom/editors/editor-registry-dom.ts","../src/cell-model/factories/badges.ts","../src/cell-model/factories/boolean.ts","../src/cell-model/factories/datetime.ts","../src/cell-model/factories/geometry.ts","../src/grid/sheets.formatters.ts","../src/cell-model/factories/image.ts","../src/cell-model/factories/interval.ts","../src/cell-model/factories/number.ts","../src/cell-model/factories/relation.ts","../src/cell-model/factories/text.ts","../src/cell-model/factories/uri.ts","../src/cell-model/create-sheets-cell.ts"],"sourcesContent":["import React, { useCallback, useEffect, useLayoutEffect, useRef } from 'react';\n\ninterface EditorFocusTrapProps {\n\tchildren: React.ReactNode;\n\tonEscape?: () => void;\n\tonKeyDown?: (e: React.KeyboardEvent) => void;\n\tclassName?: string;\n\tstyle?: React.CSSProperties;\n}\n\nconst FOCUSABLE_SELECTOR = [\n\t'button:not([disabled])',\n\t'input:not([disabled])',\n\t'textarea:not([disabled])',\n\t'select:not([disabled])',\n\t'a[href]',\n\t'[tabindex]:not([tabindex=\"-1\"])',\n].join(', ');\n\n/** Filter to only truly visible focusable elements */\nfunction getVisibleFocusable(container: HTMLElement): HTMLElement[] {\n\treturn Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(\n\t\t(el) => el.offsetParent !== null,\n\t);\n}\n\nexport function EditorFocusTrap({ children, onEscape, onKeyDown, className, style }: EditorFocusTrapProps) {\n\tconst containerRef = useRef<HTMLDivElement>(null);\n\tconst previousActiveElement = useRef<Element | null>(null);\n\n\t// Focus the first visible focusable element synchronously before paint, so the\n\t// editor input is focused instantly on open (no setTimeout settle, no focus-jump\n\t// off an input the user already started typing in). Runs once on mount.\n\tuseLayoutEffect(() => {\n\t\tpreviousActiveElement.current = document.activeElement;\n\n\t\tif (!containerRef.current) return;\n\n\t\tconst visibleElements = getVisibleFocusable(containerRef.current);\n\t\tif (visibleElements.length > 0) {\n\t\t\tvisibleElements[0].focus();\n\t\t} else {\n\t\t\t// If no visible focusable elements, focus the container itself\n\t\t\tcontainerRef.current.focus();\n\t\t}\n\t}, []);\n\n\t// Restore focus to the previously active element when unmounting (only if still\n\t// in DOM).\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tif (previousActiveElement.current instanceof HTMLElement && previousActiveElement.current.isConnected) {\n\t\t\t\tpreviousActiveElement.current.focus();\n\t\t\t}\n\t\t};\n\t}, []);\n\n\t// Handle keyboard events — forward all keys to parent, then handle Escape/Tab\n\tconst handleKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent) => {\n\t\t\t// Forward all key events to parent before handling\n\t\t\tonKeyDown?.(e);\n\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\tonEscape?.();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (e.key !== 'Tab') return;\n\n\t\t\tconst container = containerRef.current;\n\t\t\tif (!container) return;\n\n\t\t\tconst focusableElements = getVisibleFocusable(container);\n\t\t\tif (focusableElements.length === 0) return;\n\n\t\t\tconst firstElement = focusableElements[0];\n\t\t\tconst lastElement = focusableElements[focusableElements.length - 1];\n\t\t\tconst activeElement = document.activeElement;\n\n\t\t\tif (e.shiftKey) {\n\t\t\t\t// Shift+Tab: going backwards\n\t\t\t\tif (activeElement === firstElement) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tlastElement.focus();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Tab: going forwards\n\t\t\t\tif (activeElement === lastElement) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tfirstElement.focus();\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[onEscape, onKeyDown],\n\t);\n\n\treturn (\n\t\t<div\n\t\t\tref={containerRef}\n\t\t\tclassName={className}\n\t\t\tstyle={style}\n\t\t\tonKeyDown={handleKeyDown}\n\t\t\ttabIndex={-1}\n\t\t\trole=\"dialog\"\n\t\t\taria-modal=\"true\"\n\t\t>\n\t\t\t{children}\n\t\t</div>\n\t);\n}\n","/**\n * Standardised overlay width presets for cell editors.\n *\n * Each preset defines `min-w` / `max-w` Tailwind classes so every overlay\n * feels consistent while still fitting its content naturally.\n *\n * Usage:\n * import { OVERLAY } from './overlay-presets';\n * <EditorFocusTrap className={cn(OVERLAY.sm, 'bg-popover …')} />\n */\n\n/** Single-input editors — inet, date, interval, time */\nexport const OVERLAY_SM = 'min-w-[320px] max-w-[480px]';\n\n/** Tag chips / expandable lists — array, url, relation, upload, tsvector */\nexport const OVERLAY_MD = 'min-w-[400px] max-w-[560px]';\n\n/** Rich editors — JSON, image */\nexport const OVERLAY_LG = 'min-w-[480px] max-w-[720px]';\n\n/** Full-width editors — geometry / map */\nexport const OVERLAY_XL = 'min-w-[600px] max-w-4xl';\n\nexport const OVERLAY = {\n\tsm: OVERLAY_SM,\n\tmd: OVERLAY_MD,\n\tlg: OVERLAY_LG,\n\txl: OVERLAY_XL,\n} as const;\n","/**\n * Canonical cell-type group constants.\n *\n * Every file that needs to check \"is this cell type a date?\" or \"is this a\n * geometry?\" should import from here instead of maintaining inline arrays.\n *\n * All Sets are typed as `Set<string>` so `.has(cellType)` works without casts.\n */\n\n// ─── Date / Time ────────────────────────────────────────────────────────────\nexport const DATE_TIME_TYPES: Set<string> = new Set(['date', 'datetime', 'timestamptz', 'time']);\n\n// ─── Geometry ───────────────────────────────────────────────────────────────\nexport const GEOMETRY_TYPES: Set<string> = new Set(['geometry', 'geometry-point', 'geometry-collection']);\n\n// ─── Numeric ────────────────────────────────────────────────────────────────\nexport const NUMBER_TYPES: Set<string> = new Set([\n\t'number',\n\t'integer',\n\t'decimal',\n\t'currency',\n\t'smallint',\n\t'percentage',\n\t'rating',\n]);\n\n// ─── Boolean ────────────────────────────────────────────────────────────────\nexport const BOOLEAN_TYPES: Set<string> = new Set(['boolean', 'bit', 'toggle']);\n\n// ─── Array / Collection ─────────────────────────────────────────────────────\nexport const TYPED_ARRAY_TYPES: Set<string> = new Set([\n\t'array',\n\t'text-array',\n\t'uuid-array',\n\t'number-array',\n\t'integer-array',\n\t'date-array',\n\t'tags',\n]);\n\n/** Check for any array-like cell type (typed arrays + generic `-array` suffix) */\nexport function isArrayCellType(cellType: string): boolean {\n\treturn TYPED_ARRAY_TYPES.has(cellType) || cellType.endsWith('-array');\n}\n\n// ─── Structured data (JSON, arrays, interval) ──────────────────────────────\nexport const STRUCTURED_DATA_TYPES: Set<string> = new Set([\n\t'json',\n\t'jsonb',\n\t'array',\n\t'text-array',\n\t'uuid-array',\n\t'number-array',\n\t'integer-array',\n\t'date-array',\n\t'interval',\n]);\n\n// ─── Media ──────────────────────────────────────────────────────────────────\nexport const MEDIA_TYPES: Set<string> = new Set(['image', 'file', 'video', 'audio', 'upload', 'attachment']);\n\n// ─── Enhanced scalar types ──────────────────────────────────────────────────\nexport const ENHANCED_TYPES: Set<string> = new Set([\n\t'email',\n\t'url',\n\t'phone',\n\t'currency',\n\t'percentage',\n\t'color',\n\t'rating',\n\t'tags',\n]);\n\n// ─── Editor behaviour ───────────────────────────────────────────────────────\n\n/** Cell types that use Glide's built-in text editor (no custom overlay). */\nexport const BUILTIN_EDITOR_TYPES: Set<string> = new Set(['text', 'varchar']);\n\n/** Cell types that are never editable (always read-only). */\nexport const NON_EDITABLE_TYPES: Set<string> = new Set(['tsvector']);\n\n/** Cell types that can be activated for viewing but not editing. */\nexport const VIEWER_ONLY_TYPES: Set<string> = new Set(['tsvector']);\n","/**\n * Locale seam for @constructive-io/sheets.\n *\n * The host app may set a BCP-47 locale via SheetsConfig.locale. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any cell\n * renderer / editor can format dates and numbers locale-aware without threading\n * the locale through props/context. Defaults to 'en-US' (the prior hardcoded\n * behavior), so omitting `locale` changes nothing.\n */\nconst DEFAULT_LOCALE = 'en-US';\n\nlet active: string = DEFAULT_LOCALE;\n\n/** Install (or reset) the active locale. Pass null/undefined to restore the default. */\nexport function setSheetsLocale(locale?: string | null): void {\n\tactive = locale || DEFAULT_LOCALE;\n}\n\n/** Get the active locale (BCP-47). Safe to call anywhere; returns 'en-US' until set. */\nexport function sheetsLocale(): string {\n\treturn active;\n}\n","import React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { parseDate as parseAriaDate } from '@internationalized/date';\nimport type { DateValue as DateValueType } from 'react-aria-components';\n\nimport { Button } from '@constructive-io/ui/button';\nimport { Calendar } from '@constructive-io/ui/calendar-rac';\n\nimport { DATE_TIME_TYPES } from '../../cell-types/cell-type-groups';\nimport { sheetsLocale } from '../../utils/sheets-i18n';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\n\nconst TIME_RE = /(\\d{1,2}):(\\d{2})(?::(\\d{2}))?(?:\\.\\d+)?/;\nconst MAC_UA_RE = /Mac|iPod|iPhone|iPad/;\n\nexport type DateEditorType = 'date' | 'datetime' | 'timestamptz' | 'time';\n\nconst DATE_ONLY_RE = /^\\d{4}-\\d{2}-\\d{2}/;\n\nfunction pad2(value: number): string {\n\treturn String(value).padStart(2, '0');\n}\n\n// Format a Date as a calendar date string using LOCAL getters (never UTC).\n// This is the correct serialization for date-only values: the wall-clock day\n// the user picked is preserved regardless of timezone.\nexport function toLocalDateString(d: Date): string {\n\treturn `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;\n}\n\n// If the value is a string whose literal calendar date is already known\n// (starts with YYYY-MM-DD), return that 10-char slice verbatim. Otherwise null.\n// Date-only strings must never round-trip through a Date object.\nexport function extractDateOnly(v: unknown): string | null {\n\tif (typeof v === 'string' && DATE_ONLY_RE.test(v)) {\n\t\treturn v.slice(0, 10);\n\t}\n\treturn null;\n}\n\nfunction normalizeTimeValue(value: unknown): string {\n\tif (value == null) return '';\n\n\tif (value instanceof Date) {\n\t\tif (isNaN(value.getTime())) return '';\n\t\treturn `${pad2(value.getHours())}:${pad2(value.getMinutes())}:${pad2(value.getSeconds())}`;\n\t}\n\n\tconst asString = String(value).trim();\n\tif (!asString) return '';\n\n\t// Match both time-only values and datetime-like values with a time component.\n\tconst match = asString.match(TIME_RE);\n\tif (!match) return '';\n\n\tconst hours = Number(match[1] ?? 0);\n\tconst minutes = Number(match[2] ?? 0);\n\tconst seconds = Number(match[3] ?? 0);\n\tif (\n\t\t!Number.isFinite(hours) ||\n\t\t!Number.isFinite(minutes) ||\n\t\t!Number.isFinite(seconds) ||\n\t\thours < 0 ||\n\t\thours > 23 ||\n\t\tminutes < 0 ||\n\t\tminutes > 59 ||\n\t\tseconds < 0 ||\n\t\tseconds > 59\n\t) {\n\t\treturn '';\n\t}\n\n\treturn `${pad2(hours)}:${pad2(minutes)}:${pad2(seconds)}`;\n}\n\n// Determine date type from cell data or explicit context\nexport const getDateType = (value: any): DateEditorType => {\n\t// Try to infer from the value format\n\tif (typeof value === 'string') {\n\t\tif (value.includes('T') || value.includes(' ')) {\n\t\t\treturn value.includes('+') || value.includes('Z') ? 'timestamptz' : 'datetime';\n\t\t}\n\t\tif (value.includes(':') && !value.includes('-')) {\n\t\t\treturn 'time';\n\t\t}\n\t}\n\treturn 'date'; // Default fallback\n};\n\nexport function resolveDateType(value: unknown, explicitType?: string): DateEditorType {\n\tif (explicitType && DATE_TIME_TYPES.has(explicitType)) {\n\t\treturn explicitType as DateEditorType;\n\t}\n\treturn getDateType(value);\n}\n\n// Format date for display based on type\nexport const formatDate = (val: unknown, dateType: DateEditorType): string => {\n\tif (!val) return '';\n\n\tif (dateType === 'time') {\n\t\tif (typeof val === 'string') {\n\t\t\treturn val.trim();\n\t\t}\n\t\tconst normalized = normalizeTimeValue(val);\n\t\treturn normalized || String(val);\n\t}\n\n\ttry {\n\t\t// Date-only display must use the literal calendar date, never a UTC\n\t\t// conversion (which shifts the day in any UTC+ zone). Prefer the literal\n\t\t// slice and never round-trip a Date.\n\t\tif (dateType === 'date') {\n\t\t\tconst literal = extractDateOnly(val);\n\t\t\tif (literal) return literal;\n\t\t\tif (val instanceof Date) {\n\t\t\t\treturn isNaN(val.getTime()) ? String(val) : toLocalDateString(val);\n\t\t\t}\n\t\t\treturn String(val);\n\t\t}\n\n\t\tlet date: Date;\n\t\tif (val instanceof Date) {\n\t\t\tdate = val;\n\t\t} else if (typeof val === 'string') {\n\t\t\tdate = new Date(val);\n\t\t} else {\n\t\t\treturn String(val);\n\t\t}\n\n\t\tif (isNaN(date.getTime())) return String(val);\n\n\t\tswitch (dateType) {\n\t\t\tcase 'datetime':\n\t\t\tcase 'timestamptz':\n\t\t\t\treturn date.toLocaleDateString(sheetsLocale(), {\n\t\t\t\t\tyear: 'numeric',\n\t\t\t\t\tmonth: 'short',\n\t\t\t\t\tday: 'numeric',\n\t\t\t\t\thour: '2-digit',\n\t\t\t\t\tminute: '2-digit',\n\t\t\t\t\thour12: false,\n\t\t\t\t});\n\t\t\tdefault: {\n\t\t\t\t// Default branch is treated as date-only semantics.\n\t\t\t\tconst literal = extractDateOnly(val);\n\t\t\t\tif (literal) return literal;\n\t\t\t\treturn toLocalDateString(date);\n\t\t\t}\n\t\t}\n\t} catch {\n\t\treturn String(val);\n\t}\n};\n\n// Format date for input based on type\nexport const formatForInput = (val: unknown, inputType: string): string => {\n\tif (!val) return '';\n\n\tif (inputType === 'time') {\n\t\treturn normalizeTimeValue(val);\n\t}\n\n\t// Date-only input must reflect the literal calendar date, never a UTC shift.\n\tif (inputType === 'date') {\n\t\tconst literal = extractDateOnly(val);\n\t\tif (literal) return literal;\n\t\tif (val instanceof Date) {\n\t\t\treturn isNaN(val.getTime()) ? '' : toLocalDateString(val);\n\t\t}\n\t\treturn '';\n\t}\n\n\ttry {\n\t\tlet date: Date;\n\t\tif (val instanceof Date) {\n\t\t\tdate = val;\n\t\t} else if (typeof val === 'string') {\n\t\t\tdate = new Date(val);\n\t\t} else {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (isNaN(date.getTime())) return '';\n\n\t\tswitch (inputType) {\n\t\t\tcase 'datetime-local':\n\t\t\t\treturn date.toISOString().slice(0, 16);\n\t\t\tdefault:\n\t\t\t\treturn '';\n\t\t}\n\t} catch {\n\t\treturn '';\n\t}\n};\n\n// Convert a date input to a DateValue for the calendar.\n// Date-only strings are parsed by their literal calendar date (no Date round-trip),\n// so the calendar seeds on exactly the stored day in any timezone.\nconst dateToDateValue = (date: Date | string | null): DateValueType | null => {\n\tif (!date) return null;\n\n\ttry {\n\t\tconst literal = extractDateOnly(date);\n\t\tif (literal) {\n\t\t\treturn parseAriaDate(literal);\n\t\t}\n\n\t\tconst jsDate = date instanceof Date ? date : new Date(date);\n\t\tif (isNaN(jsDate.getTime())) return null;\n\n\t\treturn parseAriaDate(toLocalDateString(jsDate));\n\t} catch {\n\t\treturn null;\n\t}\n};\n\n// Convert DateValue to JavaScript Date\nconst dateValueToDate = (dateValue: DateValueType | null): Date | null => {\n\tif (!dateValue) return null;\n\n\ttry {\n\t\treturn new Date(dateValue.year, dateValue.month - 1, dateValue.day);\n\t} catch {\n\t\treturn null;\n\t}\n};\n\ninterface DateEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n\tdateType?: DateEditorType;\n}\n\nexport const DateEditor: React.FC<DateEditorProps> = ({ value, onFinishedEditing, dateType: forcedDateType }) => {\n\t// Extract current date data from the raw value\n\tconst currentDateValue = typeof value === 'string' ? value : '';\n\tconst dateType = resolveDateType(currentDateValue, forcedDateType);\n\n\tconst [dateValue, setDateValue] = useState<string | Date | null>(currentDateValue);\n\tconst [selectedDate, setSelectedDate] = useState<DateValueType | null>(\n\t\tdateToDateValue(currentDateValue || new Date()),\n\t);\n\n\tconst keyContainerRef = useRef<HTMLDivElement>(null);\n\n\tconst isTimeOnly = dateType === 'time';\n\tconst isDateTimeType = dateType === 'datetime' || dateType === 'timestamptz';\n\n\tconst handleDateSelect = useCallback(\n\t\t(dateValue: DateValueType | readonly DateValueType[] | null) => {\n\t\t\t// The shared Calendar also supports multi-select, so its public\n\t\t\t// callback includes arrays. This editor is intentionally single-date.\n\t\t\tif (Array.isArray(dateValue)) return;\n\t\t\tconst selectedValue = dateValue as DateValueType | null;\n\t\t\tsetSelectedDate(selectedValue);\n\t\t\tconst jsDate = dateValueToDate(selectedValue);\n\n\t\t\tif (jsDate) {\n\t\t\t\t// For datetime types, preserve existing time if available\n\t\t\t\tif (isDateTimeType && currentDateValue) {\n\t\t\t\t\tconst currentDate = new Date(currentDateValue);\n\t\t\t\t\tif (!isNaN(currentDate.getTime())) {\n\t\t\t\t\t\tjsDate.setHours(currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsetDateValue(jsDate);\n\t\t\t}\n\t\t},\n\t\t[isDateTimeType, currentDateValue],\n\t);\n\n\tconst handleTimeChange = useCallback(\n\t\t(timeValue: string) => {\n\t\t\tif (!timeValue) return;\n\n\t\t\tif (isTimeOnly) {\n\t\t\t\tconst normalizedTime = normalizeTimeValue(timeValue);\n\t\t\t\tsetDateValue(normalizedTime);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst [hours, minutes, seconds = 0] = timeValue.split(':').map(Number);\n\t\t\tconst targetDate: Date = selectedDate\n\t\t\t\t? dateValueToDate(selectedDate) || new Date()\n\t\t\t\t: currentDateValue\n\t\t\t\t\t? new Date(currentDateValue)\n\t\t\t\t\t: new Date();\n\n\t\t\ttargetDate.setHours(hours || 0, minutes || 0, seconds || 0, 0);\n\t\t\tsetDateValue(targetDate);\n\t\t},\n\t\t[isTimeOnly, selectedDate, currentDateValue],\n\t);\n\n\tconst handleSave = useCallback(() => {\n\t\tlet finalValue: string;\n\n\t\tif (!dateValue) {\n\t\t\tfinalValue = '';\n\t\t} else {\n\t\t\tif (dateType === 'time') {\n\t\t\t\tfinalValue = normalizeTimeValue(dateValue);\n\t\t\t\tif (!finalValue) {\n\t\t\t\t\tfinalValue = String(dateValue).trim();\n\t\t\t\t}\n\t\t\t\treturn onFinishedEditing(finalValue);\n\t\t\t}\n\n\t\t\t// Date-only path: serialize the literal calendar date with LOCAL getters.\n\t\t\t// A UTC conversion (toISOString) shifts the day backwards in any UTC+\n\t\t\t// zone — that is the write corruption this guards against.\n\t\t\tif (dateType === 'date') {\n\t\t\t\tconst literal = extractDateOnly(dateValue);\n\t\t\t\tif (literal) {\n\t\t\t\t\tfinalValue = literal;\n\t\t\t\t} else if (dateValue instanceof Date) {\n\t\t\t\t\tfinalValue = isNaN(dateValue.getTime()) ? '' : toLocalDateString(dateValue);\n\t\t\t\t} else {\n\t\t\t\t\tfinalValue = '';\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst date = dateValue instanceof Date ? dateValue : new Date(dateValue);\n\n\t\t\t\tif (isNaN(date.getTime())) {\n\t\t\t\t\tfinalValue = '';\n\t\t\t\t} else {\n\t\t\t\t\tswitch (dateType) {\n\t\t\t\t\t\tcase 'datetime':\n\t\t\t\t\t\t\tfinalValue = date.toISOString().slice(0, 19); // Remove Z\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 'timestamptz':\n\t\t\t\t\t\t\tfinalValue = date.toISOString();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault: {\n\t\t\t\t\t\t\t// Default branch is treated as date-only semantics.\n\t\t\t\t\t\t\tconst literal = extractDateOnly(dateValue);\n\t\t\t\t\t\t\tfinalValue = literal ?? toLocalDateString(date);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Emit the raw formatted date string\n\t\tonFinishedEditing(finalValue);\n\t}, [dateValue, dateType, onFinishedEditing]);\n\n\tconst handleCancel = useCallback(() => {\n\t\tonFinishedEditing();\n\t}, [onFinishedEditing]);\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)) || (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 displayValue = formatDate(dateValue, dateType);\n\n\tconst isMac = typeof navigator !== 'undefined' && MAC_UA_RE.test(navigator.userAgent);\n\tconst modKey = isMac ? '⌘' : 'Ctrl';\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}>\n\t\t\t\t{isTimeOnly ? (\n\t\t\t\t\t// Time-only: compact input\n\t\t\t\t\t<div className='space-y-2'>\n\t\t\t\t\t\t<input\n\t\t\t\t\t\t\ttype='time'\n\t\t\t\t\t\t\tstep='1'\n\t\t\t\t\t\t\tvalue={formatForInput(dateValue, 'time')}\n\t\t\t\t\t\t\tonChange={(e) => handleTimeChange(e.target.value)}\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 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\t\t\t\t) : (\n\t\t\t\t\t// Date / DateTime: calendar + optional time\n\t\t\t\t\t<div>\n\t\t\t\t\t\t{/* Selected date display */}\n\t\t\t\t\t\t<div className='text-muted-foreground mb-1 px-1 text-xs font-medium tabular-nums'>\n\t\t\t\t\t\t\t{displayValue || 'No date selected'}\n\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t{/* Calendar */}\n\t\t\t\t\t\t<Calendar\n\t\t\t\t\t\t\tvalue={selectedDate}\n\t\t\t\t\t\t\tonChange={handleDateSelect}\n\t\t\t\t\t\t\taria-label='Select date'\n\t\t\t\t\t\t/>\n\n\t\t\t\t\t\t{/* Time input for datetime types */}\n\t\t\t\t\t\t{isDateTimeType && (\n\t\t\t\t\t\t\t<div className='mt-2 px-1'>\n\t\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\t\ttype='time'\n\t\t\t\t\t\t\t\t\tstep='1'\n\t\t\t\t\t\t\t\t\tvalue={dateValue ? new Date(dateValue).toTimeString().split(' ')[0].slice(0, 8) : ''}\n\t\t\t\t\t\t\t\t\tonChange={(e) => handleTimeChange(e.target.value)}\n\t\t\t\t\t\t\t\t\tclassName='bg-muted/40 border-border/40 text-foreground w-full 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</div>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</div>\n\t\t\t\t)}\n\n\t\t\t\t{/* Footer — hints + save */}\n\t\t\t\t<div className='mt-3 flex items-center justify-between gap-4 border-t px-1 pt-2.5'>\n\t\t\t\t\t<div className='text-muted-foreground flex items-center gap-3 text-xs'>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>{modKey}</kbd>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>↵</kbd>\n\t\t\t\t\t\t\t<span>save</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight'>Esc</kbd>\n\t\t\t\t\t\t\t<span>cancel</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t<Button onClick={handleSave} size='xs' variant='default' className='shrink-0'>\n\t\t\t\t\t\tSave\n\t\t\t\t\t</Button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","import { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\nexport function cn(...inputs: ClassValue[]) {\n\treturn twMerge(clsx(inputs));\n}\n","/**\n * Injectable logger seam for @constructive-io/sheets.\n *\n * The host app may provide a custom logger via SheetsConfig.logger. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any module\n * or hook can log without threading the logger through props/context.\n *\n * Default behaviour matches the prior console.* calls. `debug` is omitted from the\n * default logger (no-op) so verbose diagnostics stay silent unless a host opts in.\n */\nexport interface SheetsLogger {\n\tdebug?(msg: string, ctx?: unknown): void;\n\twarn(msg: string, ctx?: unknown): void;\n\terror(msg: string, ctx?: unknown): void;\n}\n\nconst defaultLogger: SheetsLogger = {\n\twarn: (...a) => console.warn(...a),\n\terror: (...a) => console.error(...a),\n\t// debug omitted = no-op\n};\n\nlet active: SheetsLogger = defaultLogger;\n\n/**\n * Install (or reset) the active logger. Pass a host logger to override; pass\n * null/undefined to restore the default. Host overrides are merged over the\n * default so a partial logger still gets working warn/error.\n */\nexport function setSheetsLogger(l?: SheetsLogger | null): void {\n\tactive = l ? { ...defaultLogger, ...l } : defaultLogger;\n}\n\n/** Get the active logger. Safe to call anywhere (returns the default until set). */\nexport function sheetsLogger(): SheetsLogger {\n\treturn active;\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 { 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\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}\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\nconst searchLocation = async (query: string): Promise<SearchResult[]> => {\n\tif (!query.trim()) return [];\n\n\ttry {\n\t\tconst response = await fetch(\n\t\t\t`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=5&addressdetails=1`,\n\t\t);\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(([reactLeaflet, L]) => {\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}: {\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='© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors'\n\t\t\t\t\t\t\turl='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'\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}: 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 (query.trim()) {\n\t\t\t\tsetIsSearching(true);\n\t\t\t\tsetShowResults(true);\n\t\t\t\tconst results = await searchLocation(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}, []);\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 */}\n\t\t\t<div className='relative mb-2'>\n\t\t\t\t<InputGroup>\n\t\t\t\t\t<InputGroupAddon>\n\t\t\t\t\t\t<SearchIcon />\n\t\t\t\t\t</InputGroupAddon>\n\t\t\t\t\t<InputGroupInput\n\t\t\t\t\t\ttype='text'\n\t\t\t\t\t\tplaceholder={placeholder}\n\t\t\t\t\t\tvalue={searchQuery}\n\t\t\t\t\t\tonChange={handleSearchChange}\n\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t/>\n\t\t\t\t\t<InputGroupAddon align='inline-end'>\n\t\t\t\t\t\t{searchQuery && (\n\t\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\t\tonClick={clearSearch}\n\t\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t\t\tclassName='h-7 w-7 p-0'\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<XIcon className='h-3 w-3' />\n\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t{position && (\n\t\t\t\t\t\t\t<Button\n\t\t\t\t\t\t\t\ttype='button'\n\t\t\t\t\t\t\t\tvariant='ghost'\n\t\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t\t\tonClick={clearLocation}\n\t\t\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\t\t\tclassName='h-7 w-7 p-0'\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t<MapPinIcon className='h-3 w-3' />\n\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</InputGroupAddon>\n\t\t\t\t</InputGroup>\n\n\t\t\t\t{/* Search Results */}\n\t\t\t\t{showResults && (\n\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<CardContent className='p-0'>\n\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{!isSearching && searchResults.length === 0 && searchQuery && (\n\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)}\n\t\t\t\t\t\t\t{!isSearching &&\n\t\t\t\t\t\t\t\tsearchResults.map((result) => (\n\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\tkey={result.place_id}\n\t\t\t\t\t\t\t\t\t\tonClick={() => handleResultSelect(result)}\n\t\t\t\t\t\t\t\t\t\tdisabled={disabled}\n\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\tdisabled:cursor-not-allowed disabled:opacity-64'\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{result.display_name}\n\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t))}\n\t\t\t\t\t\t</CardContent>\n\t\t\t\t\t</Card>\n\t\t\t\t)}\n\t\t\t</div>\n\n\t\t\t{/* Map Container */}\n\t\t\t<Card className='overflow-hidden'>\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\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// @constructive-io/sheets/advanced — Power-user / extension primitives\n// =============================================================================\n// Lower-level building blocks for consumers composing their own editors and\n// cells. Everything here is optional; the root entry stays sufficient for\n// ordinary usage. Importing from this subpath keeps the core surface slim.\n\n// -- Native editor registry (DOM overlay editors) -----------------------------\nexport type { NativeEditor } from './grid-dom/editors/editor-registry-dom';\nexport { DOM_EDITOR_REGISTRY, resolveNativeEditor, wrapNativeEditor } from './grid-dom/editors/editor-registry-dom';\nexport type { EditorProps } from './grid-dom/editors/editor-props';\n\n// -- Overlay editor primitives ------------------------------------------------\nexport { OVERLAY, OVERLAY_SM, OVERLAY_MD, OVERLAY_LG, OVERLAY_XL } from './grid/editors/overlay-presets';\nexport { EditorFocusTrap } from './grid/editors/editor-focus-trap';\nexport { OverlayViewportGuard } from './grid/editors/overlay-viewport-guard';\n\n// -- Native cell content (DOM render payload) ---------------------------------\nexport { createSheetsCell } from './cell-model/create-sheets-cell';\nexport type { SheetsCell, SheetsCellKind } from './cell-model/sheets-cell';\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\nimport { Badge } from '@constructive-io/ui/badge';\nimport { Button } from '@constructive-io/ui/button';\nimport { XIcon } from 'lucide-react';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\n\nconst MAC_UA_RE = /Mac|iPod|iPhone|iPad/;\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\tonFinished: (next?: unknown[]) => void;\n};\n\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 }: Props) {\n\tconst items = useMemo(() => (Array.isArray(value) ? value : []), [value]);\n\tconst [list, setList] = useState<unknown[]>(items);\n\tconst [input, setInput] = useState('');\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\tonChange(next);\n\t\tonFinished(next);\n\t}, [input, list, onChange, onFinished]);\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\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\tconst isMac = typeof navigator !== 'undefined' && MAC_UA_RE.test(navigator.userAgent);\n\tconst modKey = isMac ? '⌘' : 'Ctrl';\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}>\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'>{String(item)}</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 transition-colors'\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{/* Footer — hints + save */}\n\t\t\t\t<div className='mt-3 flex items-center justify-between gap-4 border-t px-1 pt-2.5'>\n\t\t\t\t\t<div className='text-muted-foreground flex items-center gap-3 text-xs'>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight'>Enter</kbd>\n\t\t\t\t\t\t\t<span>add</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<span className='text-border'>|</span>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>{modKey}</kbd>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>↵</kbd>\n\t\t\t\t\t\t\t<span>save</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>⌫</kbd>\n\t\t\t\t\t\t\t<span>remove</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t<Button onClick={handleSave} size='xs' variant='default' className='shrink-0'>\n\t\t\t\t\t\tSave\n\t\t\t\t\t</Button>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n}\n","'use client';\n\n// Native array editor — a thin EditorProps adapter that RE-HOSTS the existing\n// value-native `ArrayEditor` ({ value, onChange, onFinished }) verbatim. The UI\n// (tag chips, native keydown boundary, footer, own EditorFocusTrap + OVERLAY.sm\n// width) is reused as-is; only the commit/cancel contract is mapped:\n// `onFinished(next)` -> `onCommit(next)`, `onFinished(undefined)` -> `onCancel()`.\n// `onChange` is a no-op because the native value-commit path reads only the\n// committed value (parity with the glide `createArrayEditorFactory`, which also\n// passes `onChange: () => {}`). The initial value comes from `EditorProps.value`\n// (the raw row value); the host serialises + builds the cell on commit.\n\nimport { ArrayEditor } from '../../grid/editors/array-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function ArrayEditorDom({ value, onCommit, onCancel }: EditorProps) {\n\tconst initial = Array.isArray(value) ? value : [];\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\tonFinished={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t\t/>\n\t\t</div>\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// DateEditor is lazy (pulls @internationalized/date + react-aria-components); the\n// lazy/Suspense boundary is preserved here.\n\nimport { lazy, Suspense } from 'react';\n\nimport { DATE_TIME_TYPES } from '../../cell-types/cell-type-groups';\nimport type { DateEditorType } from '../../grid/editors/date-editor';\nimport type { EditorProps } from './editor-props';\n\nconst DateEditor = lazy(() => import('../../grid/editors/date-editor').then((m) => ({ default: m.DateEditor })));\n\nexport function DateEditorDom({ value, cell, 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\n\treturn (\n\t\t<div data-slot='date-editor'>\n\t\t\t<Suspense fallback={<div className='h-9 w-full min-w-[320px] animate-pulse rounded-sm bg-muted' />}>\n\t\t\t\t<DateEditor\n\t\t\t\t\tvalue={value}\n\t\t\t\t\tdateType={dateType}\n\t\t\t\t\tonFinishedEditing={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t\t\t/>\n\t\t\t</Suspense>\n\t\t</div>\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.fieldMeta?.type?.subtype (column geometry subtype).\n// • onFinishedEditing(next) -> onCommit(next) (raw geojson string; host builds the\n// cell), onFinishedEditing(undefined) -> onCancel().\n// The Suspense wrapper preserves the source's lazy-loaded Leaflet MapPicker. Escape is\n// handled by the reused editor's EditorFocusTrap -> handleCancel ->\n// onFinishedEditing(undefined).\n\nimport { Suspense } from 'react';\n\nimport { GeometryEditor } from '../../grid/editors/geometry-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function GeometryEditorDom({ value, fieldMeta, onCommit, onCancel }: EditorProps) {\n\tconst expectedType = fieldMeta?.type?.subtype || undefined;\n\treturn (\n\t\t<div data-slot='geometry-editor'>\n\t\t\t<Suspense fallback={<div className='h-80 w-full min-w-[600px] animate-pulse rounded-lg bg-muted' />}>\n\t\t\t\t<GeometryEditor\n\t\t\t\t\tvalue={value}\n\t\t\t\t\texpectedType={expectedType}\n\t\t\t\t\tonFinishedEditing={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t\t\t/>\n\t\t\t</Suspense>\n\t\t</div>\n\t);\n}\n","import React, { lazy, Suspense, useCallback, useContext, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { AlertCircle, FileText, Loader2, Map, MapPin, Shuffle } from 'lucide-react';\n\nimport { cn } from '../../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from '@constructive-io/ui/tabs';\nimport { Textarea } from '@constructive-io/ui/textarea';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\nimport { OverlayMeasureContext } from './overlay-viewport-guard';\n\n// Lazy load MapPicker to avoid bundling ~270KB Leaflet in main chunk\nconst MapPicker = lazy(() =>\n\timport('../../utils/map-picker').then((m) => ({ default: m.MapPicker }))\n);\n\nfunction MapPickerLoading() {\n\treturn (\n\t\t<div className=\"flex h-[280px] w-full items-center justify-center rounded-lg border bg-muted/30\">\n\t\t\t<Loader2 className=\"h-6 w-6 animate-spin text-muted-foreground\" />\n\t\t</div>\n\t);\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 JSON.stringify(obj, null, 2);\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// Geometry placeholder examples by type\nconst GEOMETRY_PLACEHOLDERS: Record<string, string> = {\n\tPoint: JSON.stringify({ type: 'Point', coordinates: [0, 0] }, null, 2),\n\tPolygon: JSON.stringify({ type: 'Polygon', coordinates: [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]] }, null, 2),\n\tLineString: JSON.stringify({ type: 'LineString', coordinates: [[0, 0], [1, 1], [2, 0]] }, null, 2),\n\tMultiPoint: JSON.stringify({ type: 'MultiPoint', coordinates: [[0, 0], [1, 1]] }, null, 2),\n\tMultiPolygon: JSON.stringify({ type: 'MultiPolygon', coordinates: [[[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]] }, null, 2),\n\tMultiLineString: JSON.stringify({ type: 'MultiLineString', coordinates: [[[0, 0], [1, 1]], [[2, 2], [3, 3]]] }, null, 2),\n};\nconst DEFAULT_GEOMETRY_PLACEHOLDER = GEOMETRY_PLACEHOLDERS.Point;\n\nconst IS_MAC = typeof navigator !== 'undefined' && /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);\nconst MOD_KEY = IS_MAC ? '⌘' : 'Ctrl';\n\nconst RANDOMIZABLE_TYPES = ['Point', 'LineString', 'Polygon'];\n\n// Module-level random geometry generator — no component state deps\nfunction generateRandomGeometry(constrainedType?: string): GeometryType {\n\tconst sampleLocations = [\n\t\t{ name: 'Times Square, NYC', lng: -73.985, lat: 40.758 },\n\t\t{ name: 'Eiffel Tower, Paris', lng: 2.294, lat: 48.858 },\n\t\t{ name: 'Big Ben, London', lng: -0.124, lat: 51.499 },\n\t\t{ name: 'Golden Gate Bridge, SF', lng: -122.478, lat: 37.819 },\n\t\t{ name: 'Sydney Opera House', lng: 151.215, lat: -33.857 },\n\t];\n\n\tconst randomType = constrainedType && RANDOMIZABLE_TYPES.includes(constrainedType)\n\t\t? constrainedType\n\t\t: RANDOMIZABLE_TYPES[Math.floor(Math.random() * RANDOMIZABLE_TYPES.length)];\n\tconst baseLocation = sampleLocations[Math.floor(Math.random() * sampleLocations.length)];\n\tconst baseLng = baseLocation.lng;\n\tconst baseLat = baseLocation.lat;\n\n\tlet geojson: any;\n\n\tswitch (randomType) {\n\t\tcase 'Point':\n\t\t\tgeojson = {\n\t\t\t\ttype: 'Point',\n\t\t\t\tcoordinates: [baseLng, baseLat],\n\t\t\t};\n\t\t\tbreak;\n\n\t\tcase 'LineString': {\n\t\t\tconst pathPoints = [];\n\t\t\tfor (let i = 0; i < 4; i++) {\n\t\t\t\tpathPoints.push([\n\t\t\t\t\tbaseLng + (Math.random() - 0.5) * 0.01,\n\t\t\t\t\tbaseLat + (Math.random() - 0.5) * 0.01,\n\t\t\t\t]);\n\t\t\t}\n\t\t\tgeojson = {\n\t\t\t\ttype: 'LineString',\n\t\t\t\tcoordinates: pathPoints,\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\n\t\tcase 'Polygon': {\n\t\t\tconst offset = 0.005;\n\t\t\tgeojson = {\n\t\t\t\ttype: 'Polygon',\n\t\t\t\tcoordinates: [\n\t\t\t\t\t[\n\t\t\t\t\t\t[baseLng - offset, baseLat - offset],\n\t\t\t\t\t\t[baseLng + offset, baseLat - offset],\n\t\t\t\t\t\t[baseLng + offset, baseLat + offset],\n\t\t\t\t\t\t[baseLng - offset, baseLat + offset],\n\t\t\t\t\t\t[baseLng - offset, baseLat - offset],\n\t\t\t\t\t],\n\t\t\t\t],\n\t\t\t};\n\t\t\tbreak;\n\t\t}\n\n\t}\n\n\tlet x = baseLng,\n\t\ty = baseLat;\n\tif (geojson.type === 'Point') {\n\t\tx = geojson.coordinates[0];\n\t\ty = geojson.coordinates[1];\n\t}\n\n\treturn { geojson, srid: 4326, x, y };\n}\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}\n\nexport const GeometryEditor: React.FC<GeometryEditorProps> = ({ value, onFinishedEditing, expectedType }) => {\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 JSON.stringify(geo.geojson, null, 2);\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\tconst canShowMap = expectedType === 'Point' || (!expectedType && geometryValue != null && isPointGeometry(geometryValue));\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 handleMapChange = useCallback((mapValue: MapPickerValue | undefined) => {\n\t\tif (mapValue?.geojson?.type) {\n\t\t\tsetEditingValue(JSON.stringify(mapValue.geojson, null, 2));\n\t\t} else {\n\t\t\tsetEditingValue('');\n\t\t}\n\t}, []);\n\n\tconst handleRandomize = useCallback(() => {\n\t\tsetEditingValue(JSON.stringify(generateRandomGeometry(expectedType).geojson, null, 2));\n\t}, [expectedType]);\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\t// Shared header\n\tconst header = (\n\t\t<div className='flex items-center justify-between px-3 py-2'>\n\t\t\t<div className='flex items-center gap-2'>\n\t\t\t\t<MapPin className='text-muted-foreground h-3.5 w-3.5' />\n\t\t\t\t<span className='text-sm font-medium'>Geometry</span>\n\t\t\t\t{expectedType && (\n\t\t\t\t\t<span className='bg-muted text-muted-foreground rounded px-1.5 py-0.5 text-xs'>{expectedType}</span>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t\t{canShowMap && (\n\t\t\t\t<TabsList className='h-7'>\n\t\t\t\t\t<TabsTrigger value='map' className='flex items-center gap-1.5 px-2.5 text-xs'>\n\t\t\t\t\t\t<Map className='h-3 w-3' />\n\t\t\t\t\t\tMap\n\t\t\t\t\t</TabsTrigger>\n\t\t\t\t\t<TabsTrigger value='json' className='flex items-center gap-1.5 px-2.5 text-xs'>\n\t\t\t\t\t\t<FileText className='h-3 w-3' />\n\t\t\t\t\t\tJSON\n\t\t\t\t\t</TabsTrigger>\n\t\t\t\t</TabsList>\n\t\t\t)}\n\t\t</div>\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<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={!canShowMap || 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\t{(!expectedType || RANDOMIZABLE_TYPES.includes(expectedType)) && (\n\t\t\t\t<Button variant='ghost' size='xs' onClick={handleRandomize} title='Generate random geometry'>\n\t\t\t\t\t<Shuffle className='mr-1 h-3 w-3' />\n\t\t\t\t\tRandomize\n\t\t\t\t</Button>\n\t\t\t)}\n\t\t</div>\n\t);\n\n\t// Shared footer\n\tconst footer = (\n\t\t<div className='flex items-center justify-between border-t px-3 py-2'>\n\t\t\t<div className='text-muted-foreground flex items-center gap-3 text-xs'>\n\t\t\t\t{isValid ? (\n\t\t\t\t\t<span className='text-muted-foreground/60 shrink-0'>Valid</span>\n\t\t\t\t) : (\n\t\t\t\t\t<span className='text-destructive shrink-0'>Invalid</span>\n\t\t\t\t)}\n\t\t\t\t<span className='text-border'>|</span>\n\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>{MOD_KEY}</kbd>\n\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>↵</kbd>\n\t\t\t\t\t<span>save</span>\n\t\t\t\t</span>\n\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight'>Esc</kbd>\n\t\t\t\t\t<span>cancel</span>\n\t\t\t\t</span>\n\t\t\t</div>\n\t\t\t<Button onClick={handleSave} size='xs' variant='default' className='shrink-0' disabled={!isValid}>\n\t\t\t\tSave\n\t\t\t</Button>\n\t\t</div>\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{canShowMap ? (\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<Suspense fallback={<MapPickerLoading />}>\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/>\n\t\t\t\t\t\t\t\t</Suspense>\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","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 shouldFlip = hasTarget && spaceBelow < minBelowPx;\n\tconst maxHeight = shouldFlip ? maxHeightPx : Math.max(0, spaceBelow);\n\treturn { shouldFlip, maxHeight, targetBottom, spaceBelow, 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 image editor — a thin EditorProps adapter that RE-HOSTS the (now value-\n// native) SELF-COMMITTING `ImageEditor` verbatim. The UI (dropzone, upload flow,\n// OVERLAY_LG width, own EditorFocusTrap, motion crossfade) is reused as-is; the\n// contract maps directly onto EditorProps:\n// • value -> the raw row value, read directly by the editor.\n// • recordId -> typed EditorProps.rowIdentifier.\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 upload self-commits via\n// onSaveComplete, so the value path is never used for image).\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\tonCommitPatch,\n\tonCancel,\n\tonSubmitDraftRow,\n\tonInvalidateData,\n}: EditorProps) {\n\tconst isDraftRow = rowIdentifier == null && rowId.startsWith(DRAFT_PREFIX);\n\t// The whole MEDIA family routes here (image/file/video/audio/upload). Only `image`\n\t// stays image-only; every other media type accepts ANY file (no image guard/cap),\n\t// so e.g. an `upload` column can take a PDF. The upload transport is already\n\t// content-agnostic — this only relaxes the editor's UI guards + preview.\n\t// A missing cellType (only reachable via a custom consumer cell whose toSheetsCell\n\t// drops `meta`) defaults to image-only — the safe direction, never regressing `image`.\n\tconst cellType = cell.meta?.cellType;\n\tconst acceptAnyFile = cellType != null && cellType !== 'image';\n\n\t// Self-commit: the editor uploads server-side, then hands back the saved image\n\t// data — route it 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\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","import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';\nimport { AlertCircleIcon, FileIcon, ImageIcon, ImageOff, Loader2, UploadIcon, XIcon } from 'lucide-react';\nimport { AnimatePresence, motion } from 'motion/react';\nimport { toast } from '@constructive-io/ui/toast';\n\nimport {\n\tuseSheetsFieldUpload,\n\ttype UploadProgress,\n\ttype UploadResponse,\n} from '../../hooks/use-sheets-upload';\nimport { useSheetsMediaUrl } from '../../hooks/use-sheets-media-url';\nimport { formatFileSize, getImageMetadata } from '../../utils/file.utils';\nimport { sheetsLogger } from '../../utils/sheets-logger';\nimport { useImageStatus } from '../../utils/use-image-status';\nimport { Button } from '@constructive-io/ui/button';\nimport { Skeleton } from '@constructive-io/ui/skeleton';\nimport { ImageWithFallback } from '../../utils/image-with-fallback';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\nimport { OverlayMeasureContext } from './overlay-viewport-guard';\nimport type { DraftSubmitResult } from '../draft-types';\nimport type { SheetsRowIdentifier } from '../../row-identity';\n\n/** Data passed to onSaveComplete for optimistic updates */\nexport interface ImageSaveData {\n imageData: UploadResponse;\n}\n\ntype UploadState = 'idle' | 'submitting-draft' | 'uploading' | 'clearing';\n\n/** Snappy crossfade for dropzone content transitions */\nconst dropzoneTransition = { duration: 0.15, ease: [0.2, 0, 0, 1] as [number, number, number, number] };\n\n/** Dismiss button overlaid on image previews — frosted glass, theme-aware */\nfunction RemoveButton({ onClick, label }: { onClick: () => void; label: string }) {\n return (\n <div className='absolute top-2 right-2'>\n <button\n type='button'\n className='flex size-7 cursor-pointer items-center justify-center rounded-full\n border border-black/10 bg-white/70 text-black/50 shadow-xs backdrop-blur-sm\n transition-[color,background-color,border-color,box-shadow] outline-hidden hover:bg-white/90 hover:text-black/70\n dark:border-white/10 dark:bg-black/50 dark:text-white/70\n dark:hover:bg-black/70 dark:hover:text-white/90\n focus-visible:ring-ring/50 focus-visible:ring-[3px]'\n onClick={(e) => {\n e.stopPropagation();\n onClick();\n }}\n aria-label={label}\n >\n <XIcon className='size-3.5' aria-hidden='true' />\n </button>\n </div>\n );\n}\n\n/** Centered file chip for non-image files (selected or stored) — icon + name + size/mime. */\nfunction FilePreview({ name, size, mime }: { name?: string; size?: number; mime?: string }) {\n const hasMime = !!mime && mime !== 'unknown';\n const hasSize = size !== undefined;\n return (\n <div className='flex size-full flex-col items-center justify-center gap-2 p-4 text-center'>\n <div className='bg-muted/60 flex size-12 shrink-0 items-center justify-center rounded-lg' aria-hidden='true'>\n <FileIcon className='text-muted-foreground size-6' />\n </div>\n <div className='min-w-0 max-w-full'>\n <p className='truncate text-sm font-medium' title={name}>\n {name || 'File'}\n </p>\n {(hasSize || hasMime) && (\n <p className='text-muted-foreground mt-0.5 text-xs'>\n {hasSize ? formatFileSize(size) : null}\n {hasSize && hasMime ? ' • ' : null}\n {hasMime ? <span className='uppercase'>{mime}</span> : null}\n </p>\n )}\n </div>\n </div>\n );\n}\n\ninterface ImageEditorProps {\n value: unknown;\n onFinishedEditing: (next?: unknown) => void;\n tableName?: string;\n fieldName?: string;\n recordId?: SheetsRowIdentifier | null;\n onSaveComplete?: (data: ImageSaveData) => void;\n isDraftRow?: boolean;\n onSubmitDraft?: () => Promise<DraftSubmitResult>;\n onDraftUploadComplete?: () => void;\n /**\n * Accept ANY file type (not just images): drops the image-only guard, the 10MB cap and\n * `accept='image/*'`, and renders non-image files as a labelled chip instead of an <img>.\n * Default false keeps the image-only behaviour byte-identical. Enabled by the host for the\n * non-`image` MEDIA types (file/video/audio/upload). The upload transport is already\n * content-agnostic, so only the UI guards/preview/labels change.\n */\n acceptAnyFile?: boolean;\n}\n\nexport const ImageEditor: React.FC<ImageEditorProps> = ({\n value,\n onFinishedEditing,\n tableName,\n fieldName,\n recordId,\n onSaveComplete,\n isDraftRow = false,\n onSubmitDraft,\n onDraftUploadComplete,\n acceptAnyFile = false,\n}) => {\n const noun = acceptAnyFile ? 'file' : 'image';\n const Noun = acceptAnyFile ? 'File' : 'Image';\n const [uploadState, setUploadState] = useState<UploadState>('idle');\n const { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);\n\n const fileInputRef = useRef<HTMLInputElement>(null);\n const previewUrlRef = useRef<string | null>(null);\n // Set once a draft row has been persisted server-side. If the subsequent\n // upload fails, retries must target this real id directly (the draft is gone).\n const committedRecordIdRef = useRef<SheetsRowIdentifier | null>(null);\n\n const currentImageData = value ?? null;\n const [imageValue, setImageValue] = useState<unknown>(currentImageData);\n const [selectedFile, setSelectedFile] = useState<File | null>(null);\n const [previewUrl, setPreviewUrl] = useState<string | null>(null);\n const [uploadProgress, setUploadProgress] = useState<UploadProgress | null>(null);\n const [isDragging, setIsDragging] = useState(false);\n const [dragErrors, setDragErrors] = useState<string[]>([]);\n\n const isSubmittingDraft = uploadState === 'submitting-draft';\n const isUploading = uploadState === 'uploading';\n const isClearing = uploadState === 'clearing';\n const isBusy = uploadState !== 'idle';\n\n const imageMetadata = useMemo(() => getImageMetadata(imageValue), [imageValue]);\n // In any-file mode a stored value is only shown as a thumbnail when its mime says image/*;\n // anything else renders as a labelled file chip. Image mode stays unconditional (unchanged).\n const storedMime = imageMetadata?.mime;\n const storedIsImage = !acceptAnyFile || (!!storedMime && storedMime.startsWith('image/'));\n const { url: imageUrl, durableUrl, id: storedFileId, isLoading: isResolvingImage, onImageError, onImageLoad } =\n useSheetsMediaUrl(imageValue, storedIsImage);\n // Only probe the URL as an <img> when a thumbnail will actually be shown — probing a\n // non-image url (PDF/doc) would flip status to 'error' and hit the unavailable branch.\n const imageStatus = useImageStatus(storedIsImage ? imageUrl || undefined : undefined);\n useEffect(() => {\n if (imageStatus === 'error') onImageError();\n if (imageStatus === 'loaded') onImageLoad();\n }, [imageStatus, onImageError, onImageLoad]);\n const imageLoadFailed = storedIsImage && durableUrl != null && imageStatus === 'error';\n const hasImage = (imageUrl != null || isResolvingImage) && !imageLoadFailed && storedIsImage;\n const hasStoredMedia = Boolean(storedFileId || durableUrl);\n const clearPending = value != null && imageValue == null;\n const needsDraftCreation = isDraftRow && committedRecordIdRef.current == null;\n // A selected non-image file already shows its details in the dropzone chip.\n const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith('image/') ?? false);\n\n // --- Helpers -----------------------------------------------------------\n\n const revokePreviewUrl = useCallback(() => {\n if (previewUrlRef.current) {\n URL.revokeObjectURL(previewUrlRef.current);\n previewUrlRef.current = null;\n }\n }, []);\n\n const resetFileState = useCallback(() => {\n revokePreviewUrl();\n setUploadProgress(null);\n setSelectedFile(null);\n setPreviewUrl(null);\n setUploadState('idle');\n }, [revokePreviewUrl]);\n\n // --- Upload handlers ---------------------------------------------------\n\n const finishSave = useCallback((data: UploadResponse, message: string) => {\n resetFileState();\n setImageValue(data);\n if (committedRecordIdRef.current == null) {\n onSaveComplete?.({ imageData: data });\n } else {\n onDraftUploadComplete?.();\n }\n onFinishedEditing();\n toast.success({ message });\n }, [resetFileState, onSaveComplete, onDraftUploadComplete, onFinishedEditing]);\n\n // Keep the editor and staged file available when a write fails.\n const handleWriteError = useCallback((error: Error) => {\n setUploadState('idle');\n setUploadProgress(null);\n sheetsLogger().error('[image-editor] media update failed:', error);\n toast.error({ message: error.message || 'Could not save the file' });\n }, []);\n\n const uploadMutation = useSheetsFieldUpload(tableName || '', fieldName || '', recordId ?? null, {\n onProgress: setUploadProgress,\n onSuccess: (data) => finishSave(data, data === null ? `${Noun} cleared` : `${Noun} uploaded successfully`),\n onError: handleWriteError,\n showToast: false,\n });\n\n // --- File selection & drag/drop ----------------------------------------\n\n const handleRemoveImage = useCallback(() => {\n setImageValue(null);\n setSelectedFile(null);\n setPreviewUrl(null);\n }, []);\n\n const handleFileSelection = useCallback((acceptedFiles: File[]) => {\n if (acceptedFiles.length === 0) return;\n const file = acceptedFiles[0];\n\n // Image mode enforces an image type + 10MB cap; any-file mode accepts anything and\n // leaves size validation to the server (the bucket's max_file_size).\n if (!acceptAnyFile) {\n if (!file.type.startsWith('image/')) {\n toast.error({ message: 'Please select an image file' });\n return;\n }\n if (file.size > 10 * 1024 * 1024) {\n toast.error({ message: 'File size must be less than 10MB' });\n return;\n }\n }\n\n revokePreviewUrl();\n setSelectedFile(file);\n const url = URL.createObjectURL(file);\n previewUrlRef.current = url;\n setPreviewUrl(url);\n }, [revokePreviewUrl, acceptAnyFile]);\n\n const handleDragEnter = useCallback((e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n setIsDragging(true);\n }, []);\n\n const handleDragLeave = useCallback((e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n setIsDragging(false);\n }, []);\n\n const handleDragOver = useCallback((e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n }, []);\n\n const handleDrop = useCallback((e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n setIsDragging(false);\n setDragErrors([]);\n const files = Array.from(e.dataTransfer.files);\n if (files.length > 0) handleFileSelection(files);\n }, [handleFileSelection]);\n\n const openFileDialog = useCallback(() => fileInputRef.current?.click(), []);\n\n const removeFile = useCallback(() => {\n revokePreviewUrl();\n setSelectedFile(null);\n setPreviewUrl(null);\n setDragErrors([]);\n }, [revokePreviewUrl]);\n\n // --- Upload confirmation -----------------------------------------------\n\n const handleConfirmUpload = useCallback(async () => {\n if (isBusy || !tableName || !fieldName || !selectedFile) return;\n\n if (!isDraftRow) {\n if (recordId == null) {\n toast.error({ message: 'Missing record context for upload' });\n return;\n }\n setUploadState('uploading');\n uploadMutation.mutate(selectedFile);\n return;\n }\n\n let rowPersisted = committedRecordIdRef.current != null;\n try {\n const createRow = committedRecordIdRef.current == null;\n if (createRow) {\n if (!onSubmitDraft) throw new Error('Cannot upload to draft row - save the row first');\n\n toast.info({ message: 'Creating row...' });\n setUploadState('submitting-draft');\n const { createdRow } = await onSubmitDraft();\n rowPersisted = true;\n committedRecordIdRef.current = createdRow ? uploadMutation.resolveRowIdentifier(createdRow) : null;\n }\n\n // Creating the row removes the draft. Subsequent attempts use the persisted identity.\n const committedId = committedRecordIdRef.current;\n if (committedId == null) throw new Error('Uploads require a primary-key identity for the created row.');\n\n toast.info({ message: `Uploading ${noun}...` });\n setUploadState('uploading');\n const saved = await uploadMutation.write(committedId, selectedFile);\n finishSave(saved, createRow ? `Row created and ${noun} uploaded` : `${Noun} uploaded successfully`);\n } catch (error) {\n if (rowPersisted) onDraftUploadComplete?.();\n handleWriteError(error instanceof Error ? error : new Error('Upload failed'));\n }\n }, [isBusy, tableName, fieldName, selectedFile, isDraftRow, recordId, uploadMutation, onSubmitDraft,\n noun, Noun, finishSave, onDraftUploadComplete, handleWriteError]);\n\n // --- Save / Cancel -----------------------------------------------------\n\n const handleSave = useCallback(async () => {\n if (isBusy) return;\n if (!clearPending) {\n onFinishedEditing();\n return;\n }\n\n const targetId = committedRecordIdRef.current ?? recordId;\n if (targetId == null) {\n if (isDraftRow) {\n finishSave(null, `${Noun} cleared`);\n } else {\n handleWriteError(new Error('Missing record context for clear'));\n }\n return;\n }\n\n setUploadState('clearing');\n if (committedRecordIdRef.current == null) {\n uploadMutation.mutate(null);\n return;\n }\n try {\n const saved = await uploadMutation.write(targetId, null);\n finishSave(saved, `${Noun} cleared`);\n } catch (error) {\n handleWriteError(error instanceof Error ? error : new Error('Clear failed'));\n }\n }, [isBusy, clearPending, onFinishedEditing, recordId, isDraftRow, finishSave, Noun, handleWriteError, uploadMutation]);\n\n const handleCancel = useCallback(() => {\n revokePreviewUrl();\n onFinishedEditing();\n }, [revokePreviewUrl, onFinishedEditing]);\n\n useEffect(() => () => revokePreviewUrl(), [revokePreviewUrl]);\n\n const handleEditorKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {\n e.preventDefault();\n if (selectedFile) void handleConfirmUpload();\n else void handleSave();\n }\n }, [handleConfirmUpload, handleSave, selectedFile]);\n\n // --- Dropzone content --------------------------------------------------\n\n const hasStoredFile = hasStoredMedia && !hasImage && !imageLoadFailed;\n const dropzoneKey = isBusy\n ? 'busy'\n : previewUrl\n ? 'preview'\n : hasImage\n ? 'loaded'\n : hasStoredFile\n ? 'file'\n : imageLoadFailed\n ? 'broken'\n : 'empty';\n\n const renderDropzoneContent = () => {\n // Busy — creating row or uploading file\n if (isBusy) {\n return (\n <div data-state={uploadState} className='text-muted-foreground flex w-full flex-col items-center justify-center p-6'>\n <Loader2 className='mb-2 size-6 animate-spin' />\n <p role='status' className='text-sm'>{isSubmittingDraft ? 'Creating row...' : isClearing ? `Clearing ${noun}...` : `Uploading ${noun}...`}</p>\n {isUploading && uploadProgress && (\n <div className='mt-3 w-full max-w-xs'>\n <div\n role='progressbar'\n aria-label={`Uploading ${noun}`}\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={Math.round(uploadProgress.percentage)}\n className='bg-muted h-1.5 overflow-hidden rounded-full'\n >\n <div\n className='bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)'\n style={{ width: `${uploadProgress.percentage}%` }}\n />\n </div>\n <p aria-hidden='true' className='text-muted-foreground mt-1.5 text-center text-xs tabular-nums'>\n {Math.round(uploadProgress.percentage)}%\n </p>\n </div>\n )}\n </div>\n );\n }\n\n // Selected file preview (not yet uploaded) — image files show a thumbnail; any other\n // file (any-file mode) shows a labelled chip.\n if (previewUrl) {\n return (\n <div className='relative w-full' style={{ height: '13rem' }}>\n {selectedIsImage ? (\n <img src={previewUrl} alt={selectedFile?.name || 'Selected file'} className='size-full object-contain p-2' />\n ) : (\n <FilePreview name={selectedFile?.name} size={selectedFile?.size} mime={selectedFile?.type} />\n )}\n <RemoveButton onClick={removeFile} label='Remove selected file' />\n </div>\n );\n }\n\n // Existing loaded image\n if (hasImage) {\n return (\n <div className='relative w-full' style={{ height: '13rem' }}>\n <ImageWithFallback\n src={imageUrl}\n alt={imageMetadata?.filename || 'Preview'}\n className='size-full object-contain p-2'\n wrapperClassName='w-full h-full'\n loadingElement={<Skeleton className='absolute inset-0 h-full w-full rounded-md' />}\n />\n <RemoveButton onClick={handleRemoveImage} label='Remove image' />\n </div>\n );\n }\n\n // Stored non-image file (any-file mode) — labelled chip with the saved metadata.\n if (hasStoredFile) {\n return (\n <div className='relative w-full' style={{ height: '13rem' }}>\n <FilePreview name={imageMetadata?.filename ?? durableUrl ?? undefined} size={imageMetadata?.size} mime={imageMetadata?.mime} />\n <RemoveButton onClick={handleRemoveImage} label='Remove file' />\n </div>\n );\n }\n\n // Value exists but image failed to load — diagnostic placeholder\n if (imageLoadFailed) {\n return (\n <div className='flex w-full flex-col items-center justify-center px-4 py-6 text-center'>\n <div\n className='mb-3 flex size-10 shrink-0 items-center justify-center rounded-full\n border border-dashed border-amber-500/25 bg-amber-500/[0.06]'\n aria-hidden='true'\n >\n <ImageOff className='size-4 text-amber-500/50' />\n </div>\n <p className='text-sm font-medium'>Image unavailable</p>\n {durableUrl && (\n <p\n className='text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50'\n title={durableUrl}\n >\n {durableUrl}\n </p>\n )}\n <div className='mt-3 flex items-center gap-2'>\n <Button\n variant='outline'\n size='sm'\n onClick={(e) => {\n e.stopPropagation();\n openFileDialog();\n }}\n >\n <UploadIcon className='-ms-0.5 opacity-60' aria-hidden='true' />\n Replace\n </Button>\n <Button\n variant='ghost'\n size='sm'\n className='text-muted-foreground'\n onClick={(e) => {\n e.stopPropagation();\n handleRemoveImage();\n }}\n >\n Clear\n </Button>\n </div>\n </div>\n );\n }\n\n // Truly empty — upload prompt\n return (\n <div className='flex w-full flex-col items-center justify-center px-4 py-6 text-center'>\n <div className='bg-muted/60 mb-3 flex size-10 shrink-0 items-center justify-center rounded-full' aria-hidden='true'>\n <UploadIcon className='text-muted-foreground size-4' />\n </div>\n <p className='text-sm font-medium'>Drop {noun} here or browse</p>\n <p className='text-muted-foreground mt-1 text-xs'>\n {acceptAnyFile ? 'Any file type' : 'SVG, PNG, JPG or GIF (max. 10MB)'}\n </p>\n <Button\n variant='outline'\n size='sm'\n className='mt-3'\n onClick={(e) => {\n e.stopPropagation();\n openFileDialog();\n }}\n disabled={isBusy}\n >\n <UploadIcon className='-ms-0.5 opacity-60' aria-hidden='true' />\n Select {noun}\n </Button>\n </div>\n );\n };\n\n // --- Footer label ------------------------------------------------------\n\n const saveLabel = isSubmittingDraft\n ? 'Creating...'\n : isClearing\n ? 'Clearing...'\n : isUploading\n ? 'Uploading...'\n : hasStoredMedia || clearPending\n ? 'Save'\n : 'Done';\n\n // --- Render ------------------------------------------------------------\n\n return (\n <EditorFocusTrap\n onEscape={handleCancel}\n className={`bg-popover flex ${OVERLAY.lg} flex-col gap-0 overflow-hidden rounded-lg border p-0 shadow-lg`}\n style={overlayMaxHeight > 0 ? { maxHeight: overlayMaxHeight } : undefined}\n >\n <div onKeyDown={handleEditorKeyDown} className='flex min-h-0 flex-1 flex-col'>\n {/* Header */}\n <div className='flex shrink-0 items-center gap-2 border-b px-6 py-3'>\n {acceptAnyFile ? (\n <FileIcon className='text-muted-foreground size-4' />\n ) : (\n <ImageIcon className='text-muted-foreground size-4' />\n )}\n <h3 className='text-sm font-medium'>{hasStoredMedia ? `Edit ${Noun}` : `Add ${Noun}`}</h3>\n </div>\n\n {/* Hidden file input — outside dropzone so EditorFocusTrap cannot auto-focus it */}\n <input\n ref={fileInputRef}\n type='file'\n accept={acceptAnyFile ? undefined : 'image/*'}\n className='hidden'\n aria-label={`Upload ${noun}`}\n tabIndex={-1}\n onChange={(e) => {\n const files = Array.from(e.target.files || []);\n if (files.length > 0) handleFileSelection(files);\n e.target.value = '';\n }}\n />\n\n {/* Scrollable body */}\n <div className='min-h-0 flex-1 overflow-y-auto'>\n <div className='p-4'>\n {/* Dropzone */}\n <div\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n data-dragging={isDragging || undefined}\n className='bg-muted/20 hover:bg-muted/30 data-[dragging=true]:bg-accent/50 data-[dragging=true]:border-primary/40\n relative flex cursor-pointer flex-col items-center justify-center overflow-hidden rounded-lg\n border border-dashed border-border/60 transition-colors'\n style={{ height: '13rem' }}\n onClick={isBusy ? undefined : openFileDialog}\n >\n <AnimatePresence mode='wait' initial={false}>\n <motion.div\n key={dropzoneKey}\n initial={{ opacity: 0 }}\n animate={{ opacity: 1 }}\n exit={{ opacity: 0 }}\n transition={dropzoneTransition}\n className='w-full'\n >\n {renderDropzoneContent()}\n </motion.div>\n </AnimatePresence>\n </div>\n\n {/* Drag errors */}\n {dragErrors.length > 0 && (\n <div className='text-destructive mt-2 flex items-center gap-1.5 text-xs' role='alert'>\n <AlertCircleIcon className='size-3 shrink-0' />\n <span>{dragErrors[0]}</span>\n </div>\n )}\n\n {/* File / image metadata */}\n {!isBusy && (selectedFile ? selectedIsImage : imageMetadata && hasImage) && (\n <div className='text-muted-foreground mt-2 text-center text-xs'>\n {selectedFile ? (\n <>\n <span className='font-medium'>{selectedFile.name}</span>\n {' \\u2022 '}\n <span>{formatFileSize(selectedFile.size)}</span>\n {' \\u2022 '}\n <span className='uppercase'>{selectedFile.type}</span>\n </>\n ) : imageMetadata ? (\n <>\n <span className='font-medium'>{imageMetadata.filename}</span>\n {imageMetadata.size ? (\n <>\n {' \\u2022 '}\n <span>{formatFileSize(imageMetadata.size)}</span>\n </>\n ) : null}\n {imageMetadata.mime ? (\n <>\n {' \\u2022 '}\n <span className='uppercase'>{imageMetadata.mime}</span>\n </>\n ) : null}\n </>\n ) : null}\n </div>\n )}\n </div>\n </div>\n\n {/* Footer */}\n <div className='flex shrink-0 justify-end gap-2 border-t px-6 py-3'>\n <Button type='button' variant='outline' size='sm' onClick={handleCancel} disabled={isBusy}>\n Cancel\n </Button>\n {selectedFile && !isBusy ? (\n <Button type='button' size='sm' onClick={handleConfirmUpload}>\n {needsDraftCreation ? 'Create Row & Upload' : 'Upload & Save'}\n </Button>\n ) : (\n <Button type='button' size='sm' onClick={handleSave} disabled={isBusy}>\n {isBusy && <Loader2 className='size-3.5 animate-spin' />}\n {saveLabel}\n </Button>\n )}\n </div>\n </div>\n </EditorFocusTrap>\n );\n};\n","import { useMutation, useQueryClient } from '@tanstack/react-query';\n\nimport { cleanTable, type MetaTable } from '@constructive-io/data';\n\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsContext } from '../context/sheets-context';\nimport type { SheetsExecuteFn, SheetsFileValue, SheetsUploadFn } from '../context/sheets-execute';\nimport { assertSheetsMutationAllowed, resolveSheetsIdentifier, resolveSheetsRowIdentity } from '../row-identity';\nimport type { SheetsRowIdentifier } from '../row-identity';\nimport { sheetsQueryKeys } from './query-keys';\nimport { useSheetsMeta } from './use-sheets-meta';\n\nexport interface UploadProgress {\n\tloaded: number;\n\ttotal: number;\n\tpercentage: number;\n}\n\n/** The value confirmed by the row update. Attachments store a public URL as text. */\nexport type UploadResponse = SheetsFileValue | string | null;\n\nexport interface UseFieldUploadOptions {\n\tonProgress?: (progress: UploadProgress) => void;\n\tonSuccess?: (data: UploadResponse) => void;\n\tonError?: (error: Error) => void;\n\tshowToast?: boolean;\n\tsuccessMessage?: string;\n\tsuccessToastDelayMs?: number;\n}\n\ninterface FieldUploadTarget {\n\ttable: MetaTable;\n\tallTables?: readonly MetaTable[];\n\tfieldName: string;\n\trecordId: SheetsRowIdentifier;\n}\n\ninterface FieldUploadTransport {\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tadapter: Pick<SheetsBackendAdapter, 'updateRow'>;\n\tonProgress?: (progress: UploadProgress) => void;\n}\n\n/** Upload and persist a media value, or pass null to clear the cell. */\nexport async function executeFieldUpload(\n\t{ table: meta, allTables, fieldName, recordId }: FieldUploadTarget,\n\tfile: File | null,\n\t{ execute, executeUpload, adapter, onProgress }: FieldUploadTransport,\n): Promise<UploadResponse> {\n\tassertSheetsMutationAllowed(meta, 'update');\n\tconst identity = resolveSheetsIdentifier(meta, recordId);\n\tif (identity.status !== 'identified') {\n\t\tthrow new Error(`Cannot resolve a primary-key identity for table '${meta.name}'.`);\n\t}\n\n\tconst table = cleanTable(meta);\n\tconst field = table.fields.find(({ name }) => name === fieldName);\n\tif (!field) throw new Error(`Field '${fieldName}' not found in table '${meta.name}'.`);\n\tconst isAttachment = field.type.pgAlias?.toLowerCase() === 'attachment' || field.type.pgType?.toLowerCase() === 'attachment';\n\n\tlet value: UploadResponse = null;\n\tif (file) {\n\t\tconst { file: projection } = await executeUpload(file, undefined, {\n\t\t\ttableName: meta.name,\n\t\t\tfieldName,\n\t\t\trecordId: typeof identity.identifier === 'object' ? undefined : identity.identifier,\n\t\t\tonProgress,\n\t\t});\n\t\tif (isAttachment) {\n\t\t\tif (!projection.url) throw new Error('attachment columns need a public bucket with a public URL prefix');\n\t\t\tvalue = projection.url;\n\t\t} else {\n\t\t\tvalue = {\n\t\t\t\t...projection,\n\t\t\t\tfilename: projection.filename ?? file.name,\n\t\t\t\tmime: projection.mime ?? (file.type || 'application/octet-stream'),\n\t\t\t};\n\t\t}\n\t}\n\n\tconst updatedRow = await adapter.updateRow(\n\t\t{ table, tableName: meta.name, allTables: allTables?.map(cleanTable) ?? [table] },\n\t\tidentity.identifier,\n\t\t{ [fieldName]: value },\n\t\texecute,\n\t\t{ returning: [fieldName] },\n\t);\n\tif (!updatedRow || !Object.hasOwn(updatedRow, fieldName)) {\n\t\tthrow new Error(`Update did not return '${fieldName}'.`);\n\t}\n\tconst saved = updatedRow[fieldName];\n\tif (value === null) {\n\t\tif (saved === null) return null;\n\t} else if (isAttachment) {\n\t\tif (typeof saved === 'string' && saved) return saved;\n\t} else if (saved && typeof saved === 'object' && !Array.isArray(saved)) {\n\t\treturn saved as SheetsFileValue;\n\t}\n\tthrow new Error(`Update returned an unexpected value for '${fieldName}'.`);\n}\n\nexport function useSheetsFieldUpload(\n\ttableName: string,\n\tfieldName: string,\n\trecordId: SheetsRowIdentifier | null,\n\toptions: UseFieldUploadOptions = {},\n) {\n\tconst queryClient = useQueryClient();\n\tconst { execute, executeUpload, scopeKey } = useSheetsContext();\n\tconst { data: meta } = useSheetsMeta();\n\tconst adapter = useSheetsAdapter();\n\tconst allTables = meta?._meta?.tables?.filter((entry): entry is MetaTable => entry != null);\n\tconst table = allTables?.find(({ name }) => name === tableName);\n\n\tfunction resolveRowIdentifier(row: Readonly<Record<string, unknown>>): SheetsRowIdentifier | null {\n\t\tif (!table) return null;\n\t\tconst identity = resolveSheetsRowIdentity(table, row);\n\t\treturn identity.status === 'identified' ? identity.identifier : null;\n\t}\n\n\tasync function persist(id: SheetsRowIdentifier, file: File | null) {\n\t\tif (!table) throw new Error(`Table '${tableName}' not found.`);\n\t\treturn executeFieldUpload(\n\t\t\t{ table, allTables, fieldName, recordId: id },\n\t\t\tfile,\n\t\t\t{ execute, executeUpload, adapter, onProgress: options.onProgress },\n\t\t);\n\t}\n\n\tfunction invalidate() {\n\t\tvoid queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.table(scopeKey, tableName) });\n\t}\n\n\tasync function write(id: SheetsRowIdentifier, file: File | null) {\n\t\tconst value = await persist(id, file);\n\t\tinvalidate();\n\t\treturn value;\n\t}\n\n\tconst mutation = useMutation<UploadResponse, Error, File | null>({\n\t\tmutationKey: [...sheetsQueryKeys.table(scopeKey, tableName), 'field-upload', fieldName, recordId],\n\t\tmutationFn: (file) => {\n\t\t\tif (recordId == null) throw new Error('Missing record context for upload');\n\t\t\treturn persist(recordId, file);\n\t\t},\n\t\tonSuccess: (value) => {\n\t\t\toptions.onSuccess?.(value);\n\t\t\tinvalidate();\n\t\t},\n\t\tonError: options.onError,\n\t});\n\n\treturn { ...mutation, write, resolveRowIdentifier };\n}\n","import { print } from 'graphql';\n\nimport {\n\tMETA_CONTRACT_INTROSPECTION_DOCUMENT,\n\tMETA_DOCUMENT,\n\tSCHEMA_INTROSPECTION_QUERY,\n\tanalyzeSchemaIntrospectionCompatibility,\n\tassertMetaContract,\n\tassertMetaQuery,\n\tbuildPostGraphileCreate,\n\tbuildPostGraphileDelete,\n\tbuildPostGraphileUpdate,\n\tbuildSelect,\n\tcreateError,\n\tgetCustomAstForCleanField,\n\tnormalizeSchemaEnumInputValues,\n\tprepareCreateInput,\n\tprepareUpdateInput,\n\ttoCamelCasePlural,\n\ttoCamelCaseSingular,\n\ttoCreateMutationName,\n\ttoPatchFieldName,\n\ttoUpdateMutationName,\n} from '@constructive-io/data';\nimport type {\n\tIntrospectionQueryResponse,\n\tMetaContractIntrospectionQuery,\n\tMetaQuery,\n\tMutationOptions,\n\tQueryOptions,\n\tSchemaEnumFieldMapping,\n} from '@constructive-io/data';\n\nimport type { SheetsExecuteFn } from '../context/sheets-execute';\nimport { transformRelationData, transformToPostGraphileVariables } from '../hooks/use-sheets-table';\nimport type {\n\tAdapterListQuery,\n\tAdapterListResult,\n\tAdapterTableContext,\n\tSheetsBackendAdapter,\n} from './sheets-adapter';\n\nconst compatibilityChecks = new WeakMap<SheetsExecuteFn, Promise<void>>();\nconst enumMappings = new WeakMap<SheetsExecuteFn, readonly SchemaEnumFieldMapping[]>();\n\nasync function ensureCurrentMetaContract(execute: SheetsExecuteFn): Promise<void> {\n\tconst cached = compatibilityChecks.get(execute);\n\tif (cached) return cached;\n\n\tconst check = execute<MetaContractIntrospectionQuery>(META_CONTRACT_INTROSPECTION_DOCUMENT).then(\n\t\t(result) => {\n\t\t\tassertMetaContract(result);\n\t\t},\n\t);\n\tcompatibilityChecks.set(execute, check);\n\n\ttry {\n\t\tawait 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 (compatibilityChecks.get(execute) === check) compatibilityChecks.delete(execute);\n\t\tthrow error;\n\t}\n}\n\nfunction hasDeclaredEnums(meta: MetaQuery): boolean {\n\treturn Boolean(meta._meta?.tables?.some((table) =>\n\t\ttable?.fields?.some((field) => Boolean(field?.enumValues?.name)),\n\t));\n}\n\nfunction schemaCompatibilityError(missingPaths: readonly string[]): Error {\n\tconst detail = missingPaths.length > 0 ? ` Missing: ${missingPaths.join(', ')}.` : '';\n\treturn createError.graphql(\n\t\t`The GraphQL schema does not match the enum values declared by Constructive _meta.${detail}`,\n\t\t'SCHEMA_INTROSPECTION_INCOMPATIBLE',\n\t);\n}\n\nfunction normalizeMutationEnums(\n\tctx: AdapterTableContext,\n\tinput: Record<string, unknown>,\n\texecute: SheetsExecuteFn,\n): Record<string, unknown> {\n\tconst hasEnumInput = ctx.table.fields.some(\n\t\t(field) =>\n\t\t\tBoolean(field.enumValues?.length) &&\n\t\t\tObject.prototype.hasOwnProperty.call(input, field.name),\n\t);\n\tif (!hasEnumInput) return input;\n\n\tconst mappings = enumMappings.get(execute);\n\tif (!mappings) {\n\t\tthrow createError.graphql(\n\t\t\t'Enum schema mappings are unavailable. Load table metadata before mutating enum fields.',\n\t\t\t'ENUM_MAPPING_UNAVAILABLE',\n\t\t);\n\t}\n\treturn normalizeSchemaEnumInputValues(input, ctx.table, mappings);\n}\n\n/**\n * Create the default PostGraphile-backed adapter. The metadata preflight makes\n * an outdated endpoint distinguishable from an ordinary transport failure,\n * while the WeakMap deduplicates that introspection for each executor/session.\n */\nexport function createPostGraphileAdapter(): SheetsBackendAdapter {\n\treturn {\n\t\tasync fetchMeta(execute: SheetsExecuteFn): Promise<MetaQuery> {\n\t\t\tawait ensureCurrentMetaContract(execute);\n\t\t\tconst meta = await execute<MetaQuery>(META_DOCUMENT);\n\t\t\tassertMetaQuery(meta);\n\t\t\tif (!hasDeclaredEnums(meta)) {\n\t\t\t\tenumMappings.set(execute, []);\n\t\t\t\treturn meta;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst introspection = await execute<IntrospectionQueryResponse>(SCHEMA_INTROSPECTION_QUERY);\n\t\t\t\tconst analysis = analyzeSchemaIntrospectionCompatibility(introspection, meta);\n\t\t\t\tif (analysis.status !== 'compatible') {\n\t\t\t\t\tthrow schemaCompatibilityError(analysis.missingPaths);\n\t\t\t\t}\n\t\t\t\tenumMappings.set(execute, analysis.enumMappings);\n\t\t\t} catch (error) {\n\t\t\t\tenumMappings.delete(execute);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\treturn meta;\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 { table, allTables, tableName } = ctx;\n\t\t\tconst { relationFieldMap, ...queryOptions } = query;\n\t\t\tconst variables = transformToPostGraphileVariables(table, queryOptions as QueryOptions);\n\t\t\tconst doc = buildSelect(table, allTables, {\n\t\t\t\t...(queryOptions as QueryOptions),\n\t\t\t\trelationFieldMap,\n\t\t\t});\n\t\t\tconst result = (await execute(doc, variables)) as Record<string, unknown>;\n\t\t\tconst queryTableName = toCamelCasePlural(tableName, table);\n\t\t\tconst connection = result[queryTableName];\n\n\t\t\tif (connection && typeof connection === 'object' && 'nodes' in connection) {\n\t\t\t\tconst nodes = (connection as { nodes: unknown[] }).nodes || [];\n\t\t\t\treturn {\n\t\t\t\t\trows: transformRelationData<T & Record<string, unknown>>(nodes, table),\n\t\t\t\t\ttotalCount: ((connection as { totalCount?: unknown }).totalCount as number) ?? 0,\n\t\t\t\t\tpageInfo: (connection as { pageInfo?: AdapterListResult<T>['pageInfo'] }).pageInfo,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst directData = (connection as unknown[]) || [];\n\t\t\treturn {\n\t\t\t\trows: transformRelationData<T & Record<string, unknown>>(directData, table),\n\t\t\t\ttotalCount: directData.length,\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\tconst { table, allTables, tableName } = ctx;\n\t\t\tconst doc = buildPostGraphileCreate(table, allTables, {\n\t\t\t\t...options,\n\t\t\t\tfieldSelection: options.fieldSelection || 'display',\n\t\t\t});\n\t\t\tconst singularName = toCamelCaseSingular(tableName, table);\n\t\t\tconst sanitizedData = normalizeMutationEnums(\n\t\t\t\tctx,\n\t\t\t\tprepareCreateInput(data),\n\t\t\t\texecute,\n\t\t\t);\n\t\t\tconst variables = {\n\t\t\t\tinput: {\n\t\t\t\t\t[singularName]: sanitizedData,\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst result = (await execute(doc, variables)) as Record<string, unknown>;\n\t\t\tconst mutationName = toCreateMutationName(tableName, table);\n\t\t\tconst createdRow = (result[mutationName] as Record<string, unknown>)?.[singularName] ?? null;\n\t\t\treturn createdRow as T | null;\n\t\t},\n\n\t\tasync updateRow<T = Record<string, unknown>>(\n\t\t\tctx: AdapterTableContext,\n\t\t\tid: string | number | Record<string, unknown>,\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\tconst { table, allTables, tableName } = ctx;\n\t\t\tconst mutationName = toUpdateMutationName(tableName, table);\n\t\t\tconst returning = options.returning && table.fields\n\t\t\t\t.filter((field) => options.returning?.includes(field.name))\n\t\t\t\t.map((field) => print(getCustomAstForCleanField(field)))\n\t\t\t\t.join(' ');\n\t\t\t// The root lookup field can have a ByKey suffix. The update payload\n\t\t\t// and patch fields use the table's singular field name instead.\n\t\t\tconst payloadTable = returning && table.query\n\t\t\t\t? { ...table, query: { ...table.query, one: null } }\n\t\t\t\t: table;\n\t\t\tconst singularName = toCamelCaseSingular(tableName, payloadTable);\n\t\t\tconst patchFieldName = toPatchFieldName(tableName, payloadTable);\n\t\t\t// The current data builder ignores returning fields and derives the\n\t\t\t// input type from the table name. Key mutations name it after the operation.\n\t\t\tconst doc = returning\n\t\t\t\t? `mutation SheetsUpdateFields($input: ${mutationName[0].toUpperCase()}${mutationName.slice(1)}Input!) {\n\t\t\t\t\t${mutationName}(input: $input) { ${singularName} { ${returning} } }\n\t\t\t\t}`\n\t\t\t\t: buildPostGraphileUpdate(table, allTables, {\n\t\t\t\t\t...options,\n\t\t\t\t\tfieldSelection: options.fieldSelection || 'display',\n\t\t\t\t});\n\t\t\tconst sanitizedPatch = prepareUpdateInput(patch);\n\t\t\tif (Object.keys(sanitizedPatch).length === 0) return null;\n\t\t\tconst normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);\n\n\t\t\tconst variables = {\n\t\t\t\tinput: {\n\t\t\t\t\t...(typeof id === 'object' ? id : { id }),\n\t\t\t\t\t[patchFieldName]: normalizedPatch,\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst result = (await execute(doc, variables)) as Record<string, unknown>;\n\t\t\tconst updatedRow = (result[mutationName] as Record<string, unknown>)?.[singularName] ?? null;\n\t\t\treturn updatedRow as T | null;\n\t\t},\n\n\t\tasync deleteRow(\n\t\t\tctx: AdapterTableContext,\n\t\t\tid: string | number | Record<string, unknown>,\n\t\t\texecute: SheetsExecuteFn,\n\t\t\toptions: MutationOptions = {},\n\t\t): Promise<void> {\n\t\t\tconst { table, allTables } = ctx;\n\t\t\tconst doc = buildPostGraphileDelete(table, allTables, options);\n\t\t\tconst variables = {\n\t\t\t\tinput: typeof id === 'object' ? id : { id },\n\t\t\t};\n\t\t\tawait execute(doc, variables);\n\t\t},\n\t};\n}\n","/**\n * Unified hooks system for table operations\n * Consolidates all table operations into a single, powerful hook\n *\n * Ported from apps/admin use-table.ts with context injection.\n */\nimport { useMemo } from 'react';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { useSheetsMeta } from './use-sheets-meta';\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsContext } from '../context/sheets-context';\nimport type { SheetsScopeKey } from '../context/sheets-context';\n\nimport { cleanTable, type CleanTable, type MetaTable, type MutationOptions, type QueryOptions } from '@constructive-io/data';\nimport { createError } from '@constructive-io/data';\nimport type { FieldSelection } from '@constructive-io/data';\nimport {\n\tbuildSelect,\n\ttoCamelCasePlural,\n\ttoCamelCaseSingular,\n\ttoOrderByEnumValue,\n} from '@constructive-io/data';\nimport { reuseSheetsPlaceholderData, sheetsQueryKeys } from './query-keys';\nimport { resolveRelationFieldMap } from './relation-field-resolution';\nimport { validateOrderByVariables } from './orderby-enum-resolution';\nimport {\n\tassertSheetsMutationAllowed,\n\tresolveSheetsIdentifier,\n\tresolveSheetsRowIdentity,\n\tsheetsIdentifierCacheKey,\n\tsheetsIdentifierToWhere,\n\ttype SheetsRowIdentifier,\n} from '../row-identity';\n\ntype RowRecord = Record<string, unknown>;\ntype DeleteIdentifier = SheetsRowIdentifier;\n\n/**\n * Transform relation data by extracting nodes from hasMany/manyToMany connections\n */\nexport function transformRelationData<TData extends RowRecord>(data: unknown, table: CleanTable): TData[] {\n\tif (!data) return [] as TData[];\n\tif (!Array.isArray(data)) return data as TData[];\n\n\tconst transformed = data.map((row) => {\n\t\tif (!row || typeof row !== 'object') return row as TData;\n\n\t\tconst transformedRow: RowRecord = { ...(row as RowRecord) };\n\n\t\tconst hasManyRelations = table.relations.hasMany || [];\n\t\tconst manyToManyRelations = table.relations.manyToMany || [];\n\t\tconst connectionRelations = [...hasManyRelations, ...manyToManyRelations];\n\n\t\tconnectionRelations.forEach((relation) => {\n\t\t\tconst fieldName = relation.fieldName;\n\t\t\tif (!fieldName || !(fieldName in transformedRow)) return;\n\n\t\t\tconst relationValue = transformedRow[fieldName];\n\t\t\tif (relationValue && typeof relationValue === 'object' && 'nodes' in (relationValue as RowRecord)) {\n\t\t\t\tconst connectionData = relationValue as { nodes?: unknown[] };\n\t\t\t\ttransformedRow[fieldName] = connectionData.nodes || [];\n\t\t\t}\n\t\t});\n\n\t\treturn transformedRow as TData;\n\t});\n\n\treturn transformed as TData[];\n}\n\n/**\n * Unified table hook options\n */\nexport interface UseTableOptions extends QueryOptions {\n\t/** Enable/disable automatic data fetching */\n\tenabled?: boolean;\n\t/** Field selection for queries */\n\tselect?: FieldSelection;\n\t/** Mutation options */\n\tmutationOptions?: MutationOptions;\n}\n\n/**\n * Unified table hook result\n */\nexport interface UseTableResult<TData extends RowRecord = RowRecord> {\n\t// Data\n\tdata: TData[];\n\ttotalCount: number;\n\tisLoading: boolean;\n\terror: Error | null;\n\n\t// Single row operations\n\tfindOne: (id: SheetsRowIdentifier) => Promise<TData | null>;\n\n\t// Mutations\n\tcreate: (data: RowRecord) => Promise<{ createdRow: TData | null }>;\n\tupdate: (id: SheetsRowIdentifier, patch: RowRecord) => Promise<{ updatedRow: TData | null }>;\n\tdelete: (id: DeleteIdentifier) => Promise<{ deletedId: DeleteIdentifier }>;\n\n\t// Mutation states\n\tisCreating: boolean;\n\tisUpdating: boolean;\n\tisDeleting: boolean;\n\n\t// Mutation errors\n\tcreateError: Error | null;\n\tupdateError: Error | null;\n\tdeleteError: Error | null;\n\n\t// Utilities\n\trefetch: () => Promise<unknown>;\n\tinvalidate: () => void;\n}\n\n/**\n * Generate query keys for consistent cache management\n */\nexport const sheetsTableQueryKeys = {\n\tscope: (scope: SheetsScopeKey) => sheetsQueryKeys.scope(scope),\n\ttable: (scope: SheetsScopeKey, tableName: string) => sheetsQueryKeys.table(scope, tableName),\n\ttableRows: (scope: SheetsScopeKey, tableName: string, options?: QueryOptions) =>\n\t\tsheetsQueryKeys.tableRows(scope, tableName, options),\n\ttableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) =>\n\t\tsheetsQueryKeys.tableRow(scope, tableName, id),\n\ttableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) =>\n\t\tsheetsQueryKeys.tableCount(scope, tableName, where),\n};\n\nconst sheetsTableMutationKeys = {\n\tcreate: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsTableQueryKeys.table(scope, tableName), 'mutation', 'create'] as const,\n\tupdate: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsTableQueryKeys.table(scope, tableName), 'mutation', 'update'] as const,\n\tdelete: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsTableQueryKeys.table(scope, tableName), 'mutation', 'delete'] as const,\n};\n\n/**\n * Transform QueryOptions to PostGraphile pagination variables\n */\nexport function transformToPostGraphileVariables(table: CleanTable, options: QueryOptions = {}): Record<string, unknown> {\n\tconst variables: Record<string, unknown> = {};\n\n\t// Transform limit to first (PostGraphile uses first for forward pagination)\n\tconst limitValue = options.limit ?? options.first;\n\tif (limitValue !== undefined) {\n\t\tvariables.first = limitValue;\n\t}\n\n\t// Keep offset as is (PostGraphile supports offset-based pagination)\n\tif (options.offset !== undefined) {\n\t\tvariables.offset = options.offset;\n\t}\n\n\t// Add cursor-based pagination variables (for infinite scroll)\n\tif (options.after !== undefined) {\n\t\tvariables.after = options.after;\n\t}\n\tif (options.before !== undefined) {\n\t\tvariables.before = options.before;\n\t}\n\n\t// Transform orderBy to PostGraphile format\n\t// PostGraphile expects format like: [\"ID_ASC\", \"NAME_DESC\"]\n\tif (options.orderBy && options.orderBy.length > 0) {\n\t\tconst availableFields = new Set(table.fields.map((field) => field.name));\n\t\tvariables.orderBy = options.orderBy\n\t\t\t.filter(({ field }) => availableFields.has(field))\n\t\t\t.map(({ field, direction }) => toOrderByEnumValue(field, direction));\n\t}\n\n\t// Add where/filter conditions if present\n\tif (options.where) {\n\t\t// constructive APIs expose the connection filter as `where` (buildSelect emits `$where`).\n\t\t// Naming this variable `filter` left `$where` unbound → server-side filtering was\n\t\t// silently dropped (every `where` returned all rows). Must match buildSelect's `$where`.\n\t\tvariables.where = options.where;\n\t}\n\n\treturn variables;\n}\n\n/**\n * Main unified table hook\n * Returns all table operations in a single hook\n */\nexport function useSheetsTable<TData extends RowRecord = RowRecord>(\n\ttableName: string,\n\toptions: UseTableOptions = {},\n): UseTableResult<TData> {\n\tconst queryClient = useQueryClient();\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst { data: meta } = useSheetsMeta();\n\tconst adapter = useSheetsAdapter();\n\n\tconst metaTables = useMemo<MetaTable[]>(() => {\n\t\tif (!meta?._meta?.tables) return [];\n\n\t\treturn meta._meta.tables.filter((candidate): candidate is MetaTable => candidate != null);\n\t}, [meta]);\n\n\tconst tables = useMemo<CleanTable[]>(() => metaTables.map(cleanTable), [metaTables]);\n\n\tconst table = useMemo<CleanTable | null>(\n\t\t() => tables.find((candidate) => candidate.name === tableName) ?? null,\n\t\t[tables, tableName],\n\t);\n\tconst tableMeta = useMemo<MetaTable | null>(\n\t\t() => metaTables.find((candidate) => candidate.name === tableName) ?? null,\n\t\t[metaTables, tableName],\n\t);\n\n\tconst resolveIdentifier = (identifier: SheetsRowIdentifier): SheetsRowIdentifier => {\n\t\tif (!tableMeta) throw createError.notFound(`Table '${tableName}' not found`);\n\t\tconst resolution = resolveSheetsIdentifier(tableMeta, identifier);\n\t\tif (resolution.status !== 'identified') {\n\t\t\tthrow createError.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);\n\t\t}\n\t\treturn resolution.identifier;\n\t};\n\n\tconst rowCacheKey = (row: RowRecord | null | undefined): string | number | null => {\n\t\tif (!tableMeta || !row) return null;\n\t\tconst resolution = resolveSheetsRowIdentity(tableMeta, row);\n\t\tif (resolution.status !== 'identified') return null;\n\t\treturn typeof resolution.identifier === 'object' ? resolution.key : resolution.identifier;\n\t};\n\n\t// Extract options\n\tconst { enabled = true, select: fieldSelection, mutationOptions = {}, ...queryOptions } = options;\n\n\t// Update query options with field selection\n\tconst finalQueryOptions: QueryOptions = {\n\t\t...queryOptions,\n\t\tfieldSelection,\n\t};\n\n\t// Data fetching with error handling\n\tconst {\n\t\tdata,\n\t\tisLoading,\n\t\terror,\n\t\trefetch,\n\t\t} = useQuery<{ rows: TData[]; totalCount: number }>({\n\t\t\tqueryKey: sheetsTableQueryKeys.tableRows(scopeKey, tableName, finalQueryOptions),\n\t\t\tqueryFn: async () => {\n\t\t\t\tif (!table) {\n\t\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t\t}\n\n\t\t\t\t// Cache-bound resolution stays in the hook. The orderBy validation mutates\n\t\t\t\t// `variables.orderBy` (PostGraphile enum strings) in place; we fold that\n\t\t\t\t// result back into the `{ field, direction }[]` orderBy we hand the adapter,\n\t\t\t\t// so the adapter rebuilds an identical (validated) variables payload.\n\t\t\t\tconst variables = transformToPostGraphileVariables(table, finalQueryOptions);\n\n\t\t\t\tconst [relationFieldMap] = await Promise.all([\n\t\t\t\t\tresolveRelationFieldMap({\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tfieldSelection: finalQueryOptions.fieldSelection,\n\t\t\t\t\t\tscopeKey,\n\t\t\t\t\t\tqueryClient,\n\t\t\t\t\t\texecute,\n\t\t\t\t\t}),\n\t\t\t\t\tvalidateOrderByVariables(variables, table, scopeKey, queryClient, execute),\n\t\t\t\t]);\n\n\t\t\t\tconst validatedOrderByEnum = new Set((variables.orderBy as string[] | undefined) ?? []);\n\t\t\t\tconst availableOrderByFields = new Set(table.fields.map((field) => field.name));\n\t\t\t\tconst validatedOrderBy = finalQueryOptions.orderBy?.filter(\n\t\t\t\t\t({ field, direction }) =>\n\t\t\t\t\t\tavailableOrderByFields.has(field) && validatedOrderByEnum.has(toOrderByEnumValue(field, direction)),\n\t\t\t\t);\n\n\t\t\t\tconst { rows, totalCount } = await adapter.listRows<TData>(\n\t\t\t\t\t{ table, allTables: tables, tableName },\n\t\t\t\t\t{\n\t\t\t\t\t\t...finalQueryOptions,\n\t\t\t\t\t\torderBy: validatedOrderBy,\n\t\t\t\t\t\t// resolveRelationFieldMap yields `string | null` (null = omit field). The\n\t\t\t\t\t\t// contract narrows to `string`, but the null values are passed through to\n\t\t\t\t\t\t// buildSelect unchanged at runtime — behavior is identical to before.\n\t\t\t\t\t\trelationFieldMap: relationFieldMap as Record<string, string>,\n\t\t\t\t\t},\n\t\t\t\t\texecute,\n\t\t\t\t);\n\t\t\t\treturn { rows, totalCount };\n\t\t},\n\t\tenabled: enabled && !!table,\n\t\tplaceholderData: (previousData, previousQuery) =>\n\t\t\treuseSheetsPlaceholderData(previousData, previousQuery?.queryKey, scopeKey),\n\t\tstaleTime: 5 * 60 * 1000, // 5 minutes\n\t});\n\n\tconst rowsData = data?.rows ?? [];\n\tconst totalCount = data?.totalCount ?? 0;\n\n\t// Create mutation with error handling\n\tconst createMutation = useMutation<\n\t\t{ createdRow: TData | null; __rawResult: Record<string, unknown> },\n\t\tError,\n\t\tRowRecord\n\t>({\n\t\tmutationKey: sheetsTableMutationKeys.create(scopeKey, tableName),\n\t\tmutationFn: async (data: RowRecord) => {\n\t\t\tif (!table || !tableMeta) {\n\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t}\n\t\t\tassertSheetsMutationAllowed(tableMeta, 'create');\n\n\t\t\t// Get all tables for AST generation\n\t\t\tconst allTables = meta?._meta?.tables\n\t\t\t\t? meta._meta.tables.filter((t): t is NonNullable<typeof t> => t != null).map(cleanTable)\n\t\t\t\t: [];\n\n\t\t\tconst createdRow = await adapter.createRow<TData>({ table, allTables, tableName }, data, execute, {\n\t\t\t\t...mutationOptions,\n\t\t\t\tfieldSelection: mutationOptions.fieldSelection || fieldSelection || 'display',\n\t\t\t});\n\n\t\t\treturn { createdRow, __rawResult: {} };\n\t\t},\n\t\tonSuccess: ({ createdRow }: { createdRow: TData | null; __rawResult: Record<string, unknown> }) => {\n\t\t\t// Invalidate all related queries for paginated mode\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });\n\n\t\t\t// Cross-invalidate infinite scroll queries to ensure both modes stay in sync\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });\n\n\t\t\t// Update individual row cache\n\t\t\tconst createdRowKey = rowCacheKey(createdRow as RowRecord | null);\n\t\t\tif (createdRowKey !== null) {\n\t\t\t\tqueryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, createdRowKey), createdRow);\n\t\t\t}\n\t\t},\n\t});\n\n\t// Update mutation with error handling\n\tconst updateMutation = useMutation<\n\t\t{ updatedRow: TData | null; __rawResult: Record<string, unknown> },\n\t\tError,\n\t\t{ id: SheetsRowIdentifier; patch: RowRecord },\n\t\t{ previousRows: Array<[readonly unknown[], { rows: TData[]; totalCount: number } | undefined]> }\n\t>({\n\t\tmutationKey: sheetsTableMutationKeys.update(scopeKey, tableName),\n\t\tmutationFn: async ({ id, patch }) => {\n\t\t\tif (!table || !tableMeta) {\n\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t}\n\t\t\tassertSheetsMutationAllowed(tableMeta, 'update');\n\t\t\tconst mutationIdentifier = resolveIdentifier(id);\n\n\t\t\t// Get all tables for AST generation\n\t\t\tconst allTables = meta?._meta?.tables\n\t\t\t\t? meta._meta.tables.filter((t): t is NonNullable<typeof t> => t != null).map(cleanTable)\n\t\t\t\t: [];\n\n\t\t\tconst updatedRow = await adapter.updateRow<TData>({ table, allTables, tableName }, mutationIdentifier, patch, execute, {\n\t\t\t\t...mutationOptions,\n\t\t\t\tfieldSelection: mutationOptions.fieldSelection || fieldSelection || 'display',\n\t\t\t});\n\n\t\t\treturn { updatedRow, __rawResult: {} };\n\t\t},\n\t\t// Optimistic patch: an inline cell edit must show the new value instantly,\n\t\t// not after the server round-trip + the onSuccess refetch round-trip. The\n\t\t// active rows cache is `{ rows, totalCount }` keyed by `tableRows(...options)`;\n\t\t// patch every cached `tableRows` variant that holds the row (the active query\n\t\t// key embeds `finalQueryOptions`, but other option permutations may be cached\n\t\t// too), matching the row by its scalar `id`.\n\t\tonMutate: async ({ id, patch }) => {\n\t\t\tconst tablePrefix = sheetsTableQueryKeys.table(scopeKey, tableName);\n\t\t\tawait queryClient.cancelQueries({ queryKey: tablePrefix });\n\t\t\tconst targetKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, id) : null;\n\n\t\t\tconst isRowsKey = (key: readonly unknown[]) => key[key.length - 2] === 'rows';\n\t\t\tconst previousRows = queryClient\n\t\t\t\t.getQueriesData<{ rows: TData[]; totalCount: number }>({ queryKey: tablePrefix })\n\t\t\t\t.filter(([key]) => isRowsKey(key)) as Array<\n\t\t\t\t[readonly unknown[], { rows: TData[]; totalCount: number } | undefined]\n\t\t\t>;\n\n\t\t\tfor (const [key] of previousRows) {\n\t\t\t\tqueryClient.setQueryData<{ rows: TData[]; totalCount: number }>(key, (old) => {\n\t\t\t\t\tif (!old) return old;\n\t\t\t\t\tlet changed = false;\n\t\t\t\t\tconst rows = old.rows.map((row) => {\n\t\t\t\t\t\tif (targetKey !== null && rowCacheKey(row as RowRecord) === targetKey) {\n\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t\treturn { ...(row as RowRecord), ...patch } as TData;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn row;\n\t\t\t\t\t});\n\t\t\t\t\treturn changed ? { ...old, rows } : old;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn { previousRows };\n\t\t},\n\t\tonError: (_err, _vars, ctx) => {\n\t\t\t// Roll the optimistic patch back to the snapshot on failure.\n\t\t\tctx?.previousRows.forEach(([key, data]) => queryClient.setQueryData(key, data));\n\t\t},\n\t\tonSuccess: ({ updatedRow }: { updatedRow: TData | null; __rawResult: Record<string, unknown> }) => {\n\t\t\t// Invalidate all related queries for paginated mode\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });\n\n\t\t\t// NOTE: deliberately NOT invalidating the infinite-scroll cache here.\n\t\t\t// An inline field update never changes row membership/ordering/count, so:\n\t\t\t// - infinite mode reconciles via the caller's optimistic `updateRowAtIndex`\n\t\t\t// (+ self-heal refetch on a cache miss) in use-sheets.ts;\n\t\t\t// - paginated mode is covered by the `table` invalidation above.\n\t\t\t// A blanket `infiniteTable` invalidation would refetch EVERY loaded page\n\t\t\t// (the live-observed 2x refetch on each edit) and clobber the optimistic\n\t\t\t// patch on the active page. The create/delete mutations still\n\t\t\t// cross-invalidate the infinite cache since no per-cell optimistic patch\n\t\t\t// covers a membership change.\n\n\t\t\t// Update individual row cache\n\t\t\tconst updatedRowKey = rowCacheKey(updatedRow as RowRecord | null);\n\t\t\tif (updatedRowKey !== null) {\n\t\t\t\tqueryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, updatedRowKey), updatedRow);\n\t\t\t}\n\t\t},\n\t});\n\n\t// Delete mutation with error handling\n\tconst deleteMutation = useMutation<\n\t\t{ deletedId: DeleteIdentifier; __rawResult: Record<string, unknown> },\n\t\tError,\n\t\tDeleteIdentifier\n\t>({\n\t\tmutationKey: sheetsTableMutationKeys.delete(scopeKey, tableName),\n\t\tmutationFn: async (idOrPk) => {\n\t\t\tif (!table || !tableMeta) {\n\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t}\n\t\t\tassertSheetsMutationAllowed(tableMeta, 'delete');\n\t\t\tconst mutationIdentifier = resolveIdentifier(idOrPk);\n\n\t\t\t// Get all tables for AST generation\n\t\t\tconst allTables = meta?._meta?.tables\n\t\t\t\t? meta._meta.tables.filter((t): t is NonNullable<typeof t> => t != null).map(cleanTable)\n\t\t\t\t: [];\n\n\t\t\tawait adapter.deleteRow({ table, allTables, tableName }, mutationIdentifier, execute, mutationOptions);\n\n\t\t\treturn { deletedId: idOrPk, __rawResult: {} };\n\t\t},\n\t\tonSuccess: ({ deletedId }: { deletedId: DeleteIdentifier; __rawResult: Record<string, unknown> }) => {\n\t\t\t// Invalidate all related queries for paginated mode\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });\n\n\t\t\t// Cross-invalidate infinite scroll queries to ensure both modes stay in sync\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });\n\n\t\t\tconst deletedRowKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, deletedId) : null;\n\t\t\tif (deletedRowKey !== null) {\n\t\t\t\tqueryClient.removeQueries({\n\t\t\t\t\tqueryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableName, deletedRowKey),\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t});\n\n\t// Find one function with error handling\n\tconst findOne = async (id: SheetsRowIdentifier) => {\n\t\tif (!table || !tableMeta) {\n\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t}\n\t\tconst where = sheetsIdentifierToWhere(tableMeta, id);\n\t\tif (!where) {\n\t\t\tthrow createError.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);\n\t\t}\n\n\t\tconst doc = buildSelect(table, tables, {\n\t\t\twhere,\n\t\t\tlimit: 1,\n\t\t});\n\t\tconst variables = transformToPostGraphileVariables(table, {\n\t\t\twhere,\n\t\t\tlimit: 1,\n\t\t});\n\t\tconst result = (await execute(doc, variables)) as Record<string, unknown>;\n\n\t\t// Some schemas expose a singular root field; keep this as a compatibility fallback.\n\t\tconst singularName = toCamelCaseSingular(tableName, table);\n\t\tconst singularData = result[singularName];\n\t\tif (singularData && typeof singularData === 'object') {\n\t\t\treturn singularData as TData;\n\t\t}\n\n\t\t// Handle Relay-style response structure (connection fallback)\n\t\tconst queryTableName = toCamelCasePlural(tableName, table);\n\t\tconst data = result[queryTableName];\n\n\t\tif (data && typeof data === 'object' && 'nodes' in data) {\n\t\t\tconst nodes = (data as { nodes: unknown[] }).nodes || [];\n\t\t\tconst transformedNodes = transformRelationData<TData>(nodes, table);\n\t\t\treturn transformedNodes[0] || null;\n\t\t}\n\n\t\t// Fallback for direct array response\n\t\tconst rows = (result[tableName] as unknown[]) || [];\n\t\tconst transformedRows = transformRelationData<TData>(rows, table);\n\t\treturn transformedRows[0] || null;\n\t};\n\n\t// Invalidate function\n\tconst invalidate = () => {\n\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });\n\t};\n\n\treturn {\n\t\t// Data\n\t\tdata: rowsData,\n\t\ttotalCount,\n\t\tisLoading,\n\t\terror,\n\n\t\t// Single row operations\n\t\tfindOne,\n\n\t\t// Mutations\n\t\tcreate: (data: RowRecord) => createMutation.mutateAsync(data),\n\t\tupdate: (id: SheetsRowIdentifier, patch: RowRecord) => updateMutation.mutateAsync({ id, patch }),\n\t\tdelete: (id: DeleteIdentifier) => deleteMutation.mutateAsync(id),\n\n\t\t// Mutation states\n\t\tisCreating: createMutation.isPending,\n\t\tisUpdating: updateMutation.isPending,\n\t\tisDeleting: deleteMutation.isPending,\n\n\t\t// Mutation errors\n\t\tcreateError: createMutation.error,\n\t\tupdateError: updateMutation.error,\n\t\tdeleteError: deleteMutation.error,\n\n\t\t// Utilities\n\t\trefetch,\n\t\tinvalidate,\n\t};\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","import { createContext, useContext } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\n\nimport type { SheetsExecuteFn, SheetsUploadFn } from './sheets-execute';\nimport type { SheetsLogger } from '../utils/sheets-logger';\nimport type { CellTypePlugin } from '../cell-types/define-cell-type';\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\n\nexport interface SheetsAuthEmbedded {\n\tmode: 'embedded';\n\tgetToken: () => string | null;\n\t/**\n\t * Stable, non-secret identity used to isolate cached data between users.\n\t * Hosts should return the authenticated user/session id, never the token.\n\t * When omitted, the provider uses an opaque key that changes with the token.\n\t */\n\tgetIdentityKey?: () => string | null;\n}\n\nexport interface SheetsAuthStandalone {\n\tmode: 'standalone';\n}\n\nexport interface SheetsStorageTransport {\n\tendpoint: string;\n\texecute: SheetsExecuteFn;\n}\n\nexport interface SheetsConfig {\n\t/** Data endpoint (app-public GraphQL) */\n\tendpoint: string;\n\t/** Auth endpoint (auth GraphQL) — required for standalone mode */\n\tauthEndpoint?: string;\n\t/** Database ID for multi-tenant scoping */\n\tdatabaseId?: string;\n\t/** Auth mode */\n\tauth: SheetsAuthEmbedded | SheetsAuthStandalone;\n\t/** Field type overrides (replaces schema-builder smart tags) */\n\tfieldTypeOverrides?: Record<string, string>;\n\t/** Optional: BCP-47 locale for locale-aware date/number formatting (default 'en-US'). */\n\tlocale?: string;\n\t/** Optional: inject custom execute function */\n\texecute?: SheetsExecuteFn;\n\t/** Optional: inject custom upload function */\n\texecuteUpload?: SheetsUploadFn;\n\t/** Storage endpoint for media uploads and download URL lookups. */\n\tstorage?: { endpoint: string; execute?: SheetsExecuteFn };\n\t/** Explicit bucket override. Omit to use the tenant's public default. */\n\tupload?: { bucketKey?: string };\n\t/** Optional: inject existing QueryClient */\n\tqueryClient?: QueryClient;\n\t/** Optional: inject a custom backend adapter. Defaults to the PostGraphile adapter. */\n\tadapter?: SheetsBackendAdapter;\n\t/** Optional: provider-level cell-type plugins (consumer override layer). */\n\tplugins?: CellTypePlugin[];\n\t/** Called on 401/UNAUTHENTICATED before the error is thrown. Host app handles token cleanup. */\n\tonAuthError?: () => void;\n\t/** Optional: inject a custom logger. Installed into the module logger singleton by the provider. */\n\tlogger?: SheetsLogger;\n\t/** Optional: called when a grid/editor/mutation/upload error surfaces. Host app handles reporting. */\n\tonError?: (\n\t\terror: unknown,\n\t\tctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string },\n\t) => void;\n}\n\nexport interface SheetsContextValue {\n\tconfig: SheetsConfig;\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tstorage?: SheetsStorageTransport;\n\tcanUpload: boolean;\n\tscopeKey: SheetsScopeKey;\n}\n\nexport interface SheetsScopeKey {\n\tdatabaseId: string | null;\n\tendpoint: string;\n\tidentityKey: string | null;\n}\n\nexport const SheetsContext = createContext<SheetsContextValue | null>(null);\n\nexport function useSheetsContext(): SheetsContextValue {\n\tconst ctx = useContext(SheetsContext);\n\tif (!ctx) {\n\t\tthrow new Error('useSheetsContext must be used within a <SheetsProvider>');\n\t}\n\treturn ctx;\n}\n","import type { SheetsScopeKey } from '../context/sheets-context';\n\nexport function isSheetsScopeKey(value: unknown): value is SheetsScopeKey {\n\tif (!value || typeof value !== 'object') return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn 'databaseId' in candidate && 'endpoint' in candidate && 'identityKey' in candidate;\n}\n\nexport function reuseSheetsPlaceholderData<T>(\n\tpreviousData: T | undefined,\n\tpreviousQueryKey: readonly unknown[] | undefined,\n\tcurrentScope: SheetsScopeKey,\n): T | undefined {\n\tconst previousScope = previousQueryKey?.[1];\n\tif (!isSheetsScopeKey(previousScope)) return undefined;\n\tif (previousScope.databaseId !== currentScope.databaseId) return undefined;\n\tif (previousScope.endpoint !== currentScope.endpoint) return undefined;\n\tif (previousScope.identityKey !== currentScope.identityKey) return undefined;\n\treturn previousData;\n}\n\nexport const sheetsQueryKeys = {\n\troot: ['sheets'] as const,\n\tscope: (scope: SheetsScopeKey) => ['sheets', scope] as const,\n\tmeta: (scope: SheetsScopeKey) => [...sheetsQueryKeys.scope(scope), 'meta'] as const,\n\tmediaUrl: (scope: SheetsScopeKey, endpoint: string | undefined, id: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'media-url', endpoint, id] as const,\n\ttypeFields: (scope: SheetsScopeKey, typeName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'type-fields', typeName] as const,\n\tenumValues: (scope: SheetsScopeKey, typeName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'enum-values', typeName] as const,\n\trelations: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'relations', tableName] as const,\n\ttable: (scope: SheetsScopeKey, tableName: string) => [...sheetsQueryKeys.scope(scope), 'table', tableName] as const,\n\ttableRows: (scope: SheetsScopeKey, tableName: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'rows', options] as const,\n\ttableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'row', id] as const,\n\ttableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown> | null) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'count', where] as const,\n\tinfiniteTable: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'infinite-table', tableName] as const,\n\tinfiniteTablePage: (scope: SheetsScopeKey, tableName: string, pageIndex: number, options: unknown) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'page', pageIndex, options] as const,\n\tinfiniteTableTotalCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'totalCount', where] as const,\n\tcursorTable: (scope: SheetsScopeKey, tableName: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'cursor-table', tableName, options] as const,\n} as const;\n","import type { QueryClient } from '@tanstack/react-query';\nimport { toCamelCase, toPascalCase, pluralize, singularize } from 'inflekt';\n\nimport { TypedDocumentString } from '@constructive-io/data';\n\nimport type { CleanTable } from '@constructive-io/data';\nimport type { FieldSelection, SimpleFieldSelection } from '@constructive-io/data';\nimport type { SheetsExecuteFn } from '../context/sheets-execute';\nimport type { SheetsScopeKey } from '../context/sheets-context';\nimport { sheetsQueryKeys } from './query-keys';\n\ninterface TypeFieldsQuery {\n\t__type: {\n\t\tfields: Array<{ name: string } | null> | null;\n\t} | null;\n}\n\ninterface TypeFieldsQueryVariables {\n\ttypeName: string;\n}\n\nconst TypeFieldsDoc = new TypedDocumentString<TypeFieldsQuery, TypeFieldsQueryVariables>(`\n\tquery TypeFields($typeName: String!) {\n\t\t__type(name: $typeName) {\n\t\t\tfields {\n\t\t\t\tname\n\t\t\t}\n\t\t}\n\t}\n`);\n\ntype RelationDescriptor = {\n\tfieldName: string;\n\tkind: 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\treferencedTableName?: string;\n\tkeyNames: string[];\n};\n\ntype ResolveRelationFieldMapArgs = {\n\ttable: CleanTable;\n\tfieldSelection?: FieldSelection;\n\tscopeKey: SheetsScopeKey;\n\tqueryClient: QueryClient;\n\texecute: SheetsExecuteFn;\n};\n\nexport async function resolveRelationFieldMap({\n\ttable,\n\tfieldSelection,\n\tscopeKey,\n\tqueryClient,\n\texecute,\n}: ResolveRelationFieldMapArgs): Promise<Record<string, string | null>> {\n\tconst requestedRelationFields = getRequestedRelationFields(fieldSelection);\n\tif (requestedRelationFields.length === 0) {\n\t\treturn {};\n\t}\n\n\tconst relations = collectRelationDescriptors(table);\n\tif (relations.length === 0) {\n\t\treturn {};\n\t}\n\n\tconst relationByFieldName = new Map(relations.map((relation) => [relation.fieldName, relation] as const));\n\tconst relationFieldsSet = new Set(relations.map((relation) => relation.fieldName));\n\tconst candidateFields = requestedRelationFields.filter((fieldName) => relationFieldsSet.has(fieldName));\n\n\tif (candidateFields.length === 0) {\n\t\treturn {};\n\t}\n\n\tconst availableFields = await getTypeFieldSet(table, scopeKey, queryClient, execute);\n\n\tconst relationFieldMap: Record<string, string | null> = {};\n\n\t// Best effort fallback if introspection fields are unavailable.\n\tif (!availableFields || availableFields.size === 0) {\n\t\tcandidateFields.forEach((fieldName) => {\n\t\t\tif (fieldName.includes('ByMy')) {\n\t\t\t\trelationFieldMap[fieldName] = fieldName.replace('ByMy', 'By');\n\t\t\t}\n\t\t});\n\t\treturn relationFieldMap;\n\t}\n\n\tcandidateFields.forEach((fieldName) => {\n\t\tif (availableFields.has(fieldName)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst relation = relationByFieldName.get(fieldName);\n\t\tconst candidates = buildRelationFieldCandidates(fieldName, relation);\n\t\tconst match = candidates.find((candidate) => availableFields.has(candidate));\n\n\t\t// Null means \"omit this field from selection\" to avoid query failure.\n\t\trelationFieldMap[fieldName] = match ?? null;\n\t});\n\n\treturn relationFieldMap;\n}\n\nfunction getRequestedRelationFields(fieldSelection?: FieldSelection): string[] {\n\tif (!fieldSelection || typeof fieldSelection === 'string') {\n\t\treturn [];\n\t}\n\n\tconst requested = new Set<string>();\n\tconst selection = fieldSelection as SimpleFieldSelection;\n\n\t(selection.includeRelations ?? []).forEach((fieldName) => requested.add(fieldName));\n\n\tif (selection.include) {\n\t\tObject.entries(selection.include).forEach(([fieldName, value]) => {\n\t\t\tif (value) {\n\t\t\t\trequested.add(fieldName);\n\t\t\t}\n\t\t});\n\t}\n\n\treturn Array.from(requested);\n}\n\nfunction collectRelationDescriptors(table: CleanTable): RelationDescriptor[] {\n\tconst descriptors: RelationDescriptor[] = [];\n\n\ttable.relations.belongsTo.forEach((relation) => {\n\t\tif (!relation.fieldName) return;\n\t\tdescriptors.push({\n\t\t\tfieldName: relation.fieldName,\n\t\t\tkind: 'belongsTo',\n\t\t\treferencedTableName: relation.referencesTable || undefined,\n\t\t\tkeyNames: relation.keys.map((key) => key.name).filter(Boolean),\n\t\t});\n\t});\n\n\ttable.relations.hasOne.forEach((relation) => {\n\t\tif (!relation.fieldName) return;\n\t\tdescriptors.push({\n\t\t\tfieldName: relation.fieldName,\n\t\t\tkind: 'hasOne',\n\t\t\treferencedTableName: relation.referencedByTable || undefined,\n\t\t\tkeyNames: relation.keys.map((key) => key.name).filter(Boolean),\n\t\t});\n\t});\n\n\ttable.relations.hasMany.forEach((relation) => {\n\t\tif (!relation.fieldName) return;\n\t\tdescriptors.push({\n\t\t\tfieldName: relation.fieldName,\n\t\t\tkind: 'hasMany',\n\t\t\treferencedTableName: relation.referencedByTable || undefined,\n\t\t\tkeyNames: relation.keys.map((key) => key.name).filter(Boolean),\n\t\t});\n\t});\n\n\ttable.relations.manyToMany.forEach((relation) => {\n\t\tif (!relation.fieldName) return;\n\t\tdescriptors.push({\n\t\t\tfieldName: relation.fieldName,\n\t\t\tkind: 'manyToMany',\n\t\t\treferencedTableName: relation.rightTable || undefined,\n\t\t\tkeyNames: [],\n\t\t});\n\t});\n\n\treturn descriptors;\n}\n\nfunction buildRelationFieldCandidates(fieldName: string, relation?: RelationDescriptor): string[] {\n\tconst candidates = new Set<string>();\n\tconst add = (value: string | null | undefined) => {\n\t\tif (!value) return;\n\t\tcandidates.add(value);\n\t};\n\n\tadd(fieldName);\n\tadd(fieldName.replace(/ByMy([A-Z])/g, 'By$1'));\n\tadd(fieldName.replace(/My([A-Z])/g, '$1'));\n\n\tconst byMatch = /^(.*)By(.+)$/.exec(fieldName);\n\tif (byMatch) {\n\t\tconst [, prefixRaw, suffixRaw] = byMatch;\n\t\tconst cleanedSuffix = suffixRaw.replace(/^My/, '');\n\t\tconst prefixSingular = singularize(prefixRaw);\n\t\tconst prefixPlural = pluralize(prefixSingular);\n\n\t\tadd(`${prefixRaw}By${cleanedSuffix}`);\n\t\tadd(`${prefixSingular}By${cleanedSuffix}`);\n\t\tadd(`${prefixPlural}By${cleanedSuffix}`);\n\t}\n\n\tif (!relation) {\n\t\treturn Array.from(candidates);\n\t}\n\n\tconst firstKey = relation.keyNames[0];\n\tconst keyPascalCase = firstKey ? toPascalCase(firstKey) : null;\n\tconst relationTable = relation.referencedTableName;\n\n\tif (relationTable) {\n\t\tconst singularRef = toCamelCase(relationTable);\n\t\tconst pluralRef = pluralize(singularRef);\n\n\t\tadd(singularRef);\n\t\tadd(pluralRef);\n\n\t\tif (keyPascalCase) {\n\t\t\tadd(`${singularRef}By${keyPascalCase}`);\n\t\t\tadd(`${pluralRef}By${keyPascalCase}`);\n\t\t}\n\t}\n\n\tif (relation.kind === 'hasMany' || relation.kind === 'manyToMany') {\n\t\tconst fieldPrefix = fieldName.split('By')[0];\n\t\tadd(pluralize(singularize(fieldPrefix)));\n\t}\n\n\treturn Array.from(candidates);\n}\n\nasync function getTypeFieldSet(\n\ttable: CleanTable,\n\tscopeKey: SheetsScopeKey,\n\tqueryClient: QueryClient,\n\texecute: SheetsExecuteFn,\n): Promise<Set<string> | null> {\n\tconst typeNames = [table.inflection?.tableType, table.name]\n\t\t.filter((candidate): candidate is string => typeof candidate === 'string' && candidate.trim().length > 0)\n\t\t.filter((candidate, index, values) => values.indexOf(candidate) === index);\n\n\tfor (const typeName of typeNames) {\n\t\tconst fields = await queryClient.fetchQuery<string[]>({\n\t\t\tqueryKey: sheetsQueryKeys.typeFields(scopeKey, typeName),\n\t\t\tqueryFn: async () => {\n\t\t\t\tconst response = await execute<TypeFieldsQuery>(TypeFieldsDoc, { typeName });\n\n\t\t\t\treturn (response.__type?.fields ?? [])\n\t\t\t\t\t.map((field) => field?.name)\n\t\t\t\t\t.filter((name): name is string => typeof name === 'string' && name.length > 0);\n\t\t\t},\n\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\tgcTime: 30 * 60 * 1000,\n\t\t});\n\n\t\tif (fields.length > 0) {\n\t\t\treturn new Set(fields);\n\t\t}\n\t}\n\n\treturn null;\n}\n","import type { QueryClient } from '@tanstack/react-query';\n\nimport { TypedDocumentString } from '@constructive-io/data';\nimport type { CleanTable } from '@constructive-io/data';\n\nimport type { SheetsExecuteFn } from '../context/sheets-execute';\nimport type { SheetsScopeKey } from '../context/sheets-context';\nimport { sheetsQueryKeys } from './query-keys';\n\ninterface EnumValuesQuery {\n\t__type: {\n\t\tenumValues: Array<{ name: string } | null> | null;\n\t} | null;\n}\n\ninterface EnumValuesQueryVariables {\n\ttypeName: string;\n}\n\nconst EnumValuesDoc = new TypedDocumentString<EnumValuesQuery, EnumValuesQueryVariables>(`\n\tquery EnumValues($typeName: String!) {\n\t\t__type(name: $typeName) {\n\t\t\tenumValues {\n\t\t\t\tname\n\t\t\t}\n\t\t}\n\t}\n`);\n\n/**\n * Fetch and cache the valid orderBy enum values for a table.\n * Returns a Set of valid enum strings (e.g. \"NOTES_ASC\", \"ID_DESC\"),\n * or null if the type cannot be resolved.\n */\nasync function getOrderByEnumValues(\n\torderByTypeName: string,\n\tscopeKey: SheetsScopeKey,\n\tqueryClient: QueryClient,\n\texecute: SheetsExecuteFn,\n): Promise<Set<string> | null> {\n\tconst values = await queryClient.fetchQuery<Set<string>>({\n\t\tqueryKey: sheetsQueryKeys.enumValues(scopeKey, orderByTypeName),\n\t\tqueryFn: async () => {\n\t\t\tconst response = await execute<EnumValuesQuery>(EnumValuesDoc, { typeName: orderByTypeName });\n\n\t\t\tconst names = (response.__type?.enumValues ?? [])\n\t\t\t\t.map((v) => v?.name)\n\t\t\t\t.filter((name): name is string => typeof name === 'string' && name.length > 0);\n\n\t\t\treturn new Set(names);\n\t\t},\n\t\tstaleTime: 5 * 60 * 1000,\n\t\tgcTime: 30 * 60 * 1000,\n\t});\n\n\treturn values.size > 0 ? values : null;\n}\n\n/**\n * Filter orderBy variables to only include values that exist in the schema.\n * Mutates the variables object in place — removes invalid values and deletes\n * the orderBy key entirely if no valid values remain.\n */\nexport async function validateOrderByVariables(\n\tvariables: Record<string, unknown>,\n\ttable: CleanTable,\n\tscopeKey: SheetsScopeKey,\n\tqueryClient: QueryClient,\n\texecute: SheetsExecuteFn,\n): Promise<void> {\n\tif (!variables.orderBy || !Array.isArray(variables.orderBy) || !table.inflection?.orderByType) {\n\t\treturn;\n\t}\n\n\tconst validValues = await getOrderByEnumValues(table.inflection.orderByType, scopeKey, queryClient, execute);\n\tif (!validValues) return;\n\n\tvariables.orderBy = (variables.orderBy as string[]).filter((v) => validValues.has(v));\n\tif ((variables.orderBy as string[]).length === 0) {\n\t\tdelete variables.orderBy;\n\t}\n}\n","import {\n\tassessTableWriteCapability,\n\tresolveRowIdentity,\n\trowIdentityToPrimaryKey,\n\tserializeRowIdentity,\n\ttype MetaTable,\n\ttype RowIdentityValue,\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/** 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 { 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","import { 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 { getImageUrl, getMediaFileId } 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\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>;\nconst loaders = new WeakMap<SheetsStorageTransport, WeakMap<SheetsScopeKey, MediaLoader>>();\n\nfunction createMediaLoader(storage: SheetsStorageTransport): MediaLoader {\n\tlet pending: PendingLookup[] = [];\n\n\tasync function fetchBatch(requests: PendingLookup[]) {\n\t\t// Check again after introspection so a canceled scope cannot send a\n\t\t// preview request through 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 fetchMediaDownloadUrls(storage, 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\nfunction getMediaLoader(storage: SheetsStorageTransport, scopeKey: SheetsScopeKey): MediaLoader {\n\tlet scopes = loaders.get(storage);\n\tif (!scopes) {\n\t\tscopes = new WeakMap();\n\t\tloaders.set(storage, scopes);\n\t}\n\tlet load = scopes.get(scopeKey);\n\tif (!load) {\n\t\tload = createMediaLoader(storage);\n\t\tscopes.set(scopeKey, load);\n\t}\n\treturn load;\n}\n\n/** Keep signed URLs in the authenticated preview cache, separate from cell values. */\nexport function useSheetsMediaUrl(value: unknown, previewImage = true) {\n\tconst { storage, scopeKey } = useSheetsContext();\n\tconst durableUrl = getImageUrl(value);\n\tconst id = getMediaFileId(value);\n\tconst endpoint = storage?.endpoint;\n\tconst resource = useMemo(() => ({ scopeKey, endpoint, id }), [scopeKey, endpoint, id]);\n\n\tconst query = useQuery({\n\t\tqueryKey: sheetsQueryKeys.mediaUrl(scopeKey, endpoint, id),\n\t\tqueryFn: storage && id && previewImage && !durableUrl\n\t\t\t? ({ signal }) => getMediaLoader(storage, scopeKey)(id, signal)\n\t\t\t: skipToken,\n\t\tstaleTime: (query) => query.state.data ? REFRESH_INTERVAL : UNRESOLVED_STALE_TIME,\n\t\tgcTime: REFRESH_INTERVAL,\n\t\trefetchInterval: (query) => query.state.data && query.state.status === 'success' ? REFRESH_INTERVAL : false,\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","/**\n * Presigned-URL upload helpers for the sheets cell-upload seam.\n *\n * Replaces the legacy multipart `<endpoint>/upload` POST. The flow is:\n * 1. SHA-256 hash the file bytes (Web Crypto, zero new deps)\n * 2. Call the presigned upload op (discovered via introspection) to get a\n * presigned PUT url + fileId\n * 3. PUT the raw bytes to that url (only Content-Type, NO Authorization)\n * 4. Return the file projection and try to resolve an optional download URL\n *\n * The server confirms PUTs and expires rows that never received one.\n *\n * Runtime introspection finds root mutations with the presigned upload shape\n * and prefers `uploadAppFile` when multiple storage planes are exposed.\n *\n * The downloadUrl-by-id field is likewise shape-discovered. Three read shapes,\n * preferred in order: the inflected singular `appFile(id:)`; a filtered\n * connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`\n * (Relay-disabled backends); and the Relay `node(nodeId:)` fallback.\n */\n\nimport { getIntrospectionQuery } from 'graphql';\n\nimport { createError } from '@constructive-io/data';\n\nimport type { SheetsStorageTransport } from './sheets-context';\nimport type { SheetsExecuteFn, SheetsFileValue } from './sheets-execute';\n\n// ============================================================================\n// Capability discovery types\n// ============================================================================\n\nexport interface UploadCapability {\n\t/** Upload mutation field name, discovered by shape, e.g. 'uploadAppFile'. */\n\tuploadFieldName: string;\n\t/** The upload input object type name, e.g. 'UploadAppFileInput'. */\n\tinputTypeName: string;\n\thasFileProjection: boolean;\n\tdownload: DownloadByIdResult | null;\n}\n\ninterface DownloadByIdResult {\n\t/** Query field used to resolve downloadUrl by id, e.g. 'appFile' | 'node' | 'appFiles'. */\n\tfileByIdField: string;\n\t/**\n\t * Which downloadUrl-by-id resolution shape was discovered:\n\t * - 'id' inflected singular `appFile(id:)`\n\t * - 'connection' filtered connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`\n\t * - 'nodeId' Relay `node(nodeId:)` (last-resort fallback)\n\t */\n\tfileByIdArgName: 'id' | 'nodeId' | 'connection';\n\t/** The file object type name (used to spread `... on <Type>` on the Relay node path). */\n\tfileTypeName: string;\n\t/** The GraphQL scalar type name for the `$id` variable (e.g. 'UUID'), discovered by shape. */\n\tidScalarName?: string;\n\t/** connection kind only — the filter arg name on the connection field, e.g. 'where' | 'filter' | 'condition'. */\n\tconnectionFilterArgName?: string;\n\t/** connection kind only — the id field name inside the filter input, e.g. 'id'. */\n\tconnectionIdField?: string;\n\t/** connection kind only — the equality operator field for style (a), e.g. 'equalTo'. Absent for condition style (b). */\n\tconnectionIdOperator?: string;\n\t/** connection kind only — the field on the connection object holding the file rows, e.g. 'nodes'. */\n\tconnectionNodesField?: string;\n\tconnectionHasFirst?: boolean;\n}\n\ninterface StorageCapabilities {\n\tupload: UploadCapability | null;\n\tdownload: DownloadByIdResult | null;\n\tbatch: DownloadByIdResult | null;\n}\n\ninterface UploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\tfile: Omit<SheetsFileValue, 'filename'> & { filename?: string | null };\n}\n\n// ============================================================================\n// SHA-256 (Web Crypto)\n// ============================================================================\n\n/**\n * SHA-256 hex digest of an already-read ArrayBuffer. Lowercase, 64 chars —\n * matches the server regex `^[a-f0-9]{64}$`. We reuse the same buffer for the\n * PUT body to avoid a second `file.arrayBuffer()` read.\n */\nexport async function sha256HexFromBuffer(buffer: ArrayBuffer): Promise<string> {\n\tif (!globalThis.crypto?.subtle) {\n\t\tthrow createError.badRequest('Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.');\n\t}\n\tconst digest = await crypto.subtle.digest('SHA-256', buffer);\n\tconst bytes = new Uint8Array(digest);\n\tlet hex = '';\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\thex += bytes[i].toString(16).padStart(2, '0');\n\t}\n\treturn hex;\n}\n\n// ============================================================================\n// Introspection-based capability discovery (cached per endpoint)\n// ============================================================================\n\nlet capabilityCache = new WeakMap<SheetsExecuteFn, Map<string, Promise<StorageCapabilities>>>();\n\n/** Test-only: clear cached storage capabilities between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache = new WeakMap();\n}\n\n/**\n * Share storage introspection across uploads and previews using this executor\n * and endpoint. A read-only storage endpoint can still resolve previews.\n */\nasync function discoverStorageCapabilities(endpoint: string, execute: SheetsExecuteFn): Promise<StorageCapabilities> {\n\tlet endpoints = capabilityCache.get(execute);\n\tif (!endpoints) {\n\t\tendpoints = new Map();\n\t\tcapabilityCache.set(execute, endpoints);\n\t}\n\tconst cached = endpoints.get(endpoint);\n\tif (cached) return cached;\n\n\tconst promise = (async () => {\n\t\tconst data = await execute<{ __schema: IntrospectionSchema }>(getIntrospectionQuery());\n\t\tconst schema = data?.__schema;\n\t\tif (!schema) {\n\t\t\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n\t\t}\n\t\treturn resolveStorageCapabilities(schema);\n\t})();\n\n\t// Don't cache a rejected discovery — let the next attempt retry.\n\tpromise.catch(() => endpoints.delete(endpoint));\n\tendpoints.set(endpoint, promise);\n\treturn promise;\n}\n\nexport async function discoverUploadCapability(endpoint: string, execute: SheetsExecuteFn): Promise<UploadCapability> {\n\tconst { upload } = await discoverStorageCapabilities(endpoint, execute);\n\tif (!upload) capabilityCache.get(execute)?.delete(endpoint);\n\treturn requireUploadCapability(upload);\n}\n\nfunction requireUploadCapability(upload: UploadCapability | null): UploadCapability {\n\tif (!upload) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\treturn upload;\n}\n\n// --- Minimal introspection shapes (only what discovery reads) ---\n\n// Loose, structural shapes for the slice of introspection that discovery\n// reads. `ofType` recurses with `any` so hand-built fixtures and the real\n// `IntrospectionQuery['__schema']` (from `graphql`) both satisfy these without\n// exact-match friction — discovery validates by runtime shape regardless.\ninterface IntrospectionTypeRef {\n\tkind: string;\n\tname?: string | null;\n\tofType?: any;\n}\n\ninterface IntrospectionInputValue {\n\tname: string;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionField {\n\tname: string;\n\targs: ReadonlyArray<IntrospectionInputValue>;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionType {\n\tkind: string;\n\tname?: string | null;\n\tfields?: ReadonlyArray<IntrospectionField> | null;\n\tinputFields?: ReadonlyArray<IntrospectionInputValue> | null;\n}\n\n/** Loose structural shape of an introspection `__schema` (accepts fixtures + real). */\nexport interface IntrospectionSchema {\n\tqueryType?: { name: string } | null;\n\tmutationType?: { name: string } | null;\n\ttypes: ReadonlyArray<IntrospectionType>;\n}\n\n/** Unwrap NON_NULL / LIST wrappers down to the named type. */\nfunction namedTypeName(ref: IntrospectionTypeRef | null | undefined): string | null {\n\tlet cur = ref;\n\twhile (cur && (cur.kind === 'NON_NULL' || cur.kind === 'LIST')) {\n\t\tcur = cur.ofType ?? null;\n\t}\n\treturn cur?.name ?? null;\n}\n\n/**\n * True if `ref` is a LIST (optionally NON_NULL-wrapped) at the outer level, i.e.\n * the field is plural. Unwraps only leading NON_NULL wrappers (e.g. `[AppFile]!`)\n * before checking for the LIST — distinguishes `nodes: [AppFile]` from a singular\n * `appFile: AppFile`.\n */\nfunction isListTypeRef(ref: IntrospectionTypeRef | null | undefined): boolean {\n\tlet cur = ref;\n\twhile (cur && cur.kind === 'NON_NULL') {\n\t\tcur = cur.ofType ?? null;\n\t}\n\treturn cur?.kind === 'LIST';\n}\n\n/**\n * PostGraphile names the primary-key column `id` on every row type, so the\n * filter input field that selects a single file by primary key is `id`. This is\n * the same convention the singular by-id branch (`appFile(id:)`) relies on.\n */\nconst PK_FIELD_NAME = 'id';\n\n/**\n * Pure resolver over an introspection __schema. Exported for direct unit tests\n * (no fetch). Matches by field/type shape, with an AppFile preference.\n */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\n\treturn requireUploadCapability(resolveStorageCapabilities(schema).upload);\n}\n\nfunction resolveStorageCapabilities(schema: IntrospectionSchema): StorageCapabilities {\n\tconst typeByName = new Map<string, IntrospectionType>();\n\tfor (const t of schema.types) {\n\t\tif (t.name) typeByName.set(t.name, t);\n\t}\n\n\tconst objectHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tif (!typeName) return false;\n\t\tconst t = typeByName.get(typeName);\n\t\tif (!t?.fields) return false;\n\t\tconst present = new Set(t.fields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst inputHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tif (!typeName) return false;\n\t\tconst t = typeByName.get(typeName);\n\t\tif (!t?.inputFields) return false;\n\t\tconst present = new Set(t.inputFields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'key', 'deduplicated'];\n\tconst INPUT_FIELDS = ['contentHash', 'bucketKey', 'contentType', 'size'];\n\n\tconst mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;\n\tconst queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;\n\n\t// rootUpload discovery: a Mutation field with a single `input` arg whose input\n\t// type carries the upload-input shape and whose payload carries the\n\t// upload-payload shape. (The legacy bucket-centric `requestUploadUrl` shape was\n\t// removed from the backend on 2026-05-08; only the root upload mutation exists.)\n\tlet upload: Omit<UploadCapability, 'download'> | null = null;\n\n\tfor (const field of mutationType?.fields ?? []) {\n\t\tconst inputArg = field.args.find((a) => a.name === 'input');\n\t\tif (!inputArg) continue;\n\t\tconst inputTypeName = namedTypeName(inputArg.type);\n\t\tconst payloadTypeName = namedTypeName(field.type);\n\t\tif (\n\t\t\tinputTypeName &&\n\t\t\tinputHasFields(inputTypeName, INPUT_FIELDS) &&\n\t\t\tobjectHasFields(payloadTypeName, PAYLOAD_FIELDS)\n\t\t) {\n\t\t\tconst payloadFields = typeByName.get(payloadTypeName ?? '')?.fields;\n\t\t\tconst candidate = {\n\t\t\t\tuploadFieldName: field.name,\n\t\t\t\tinputTypeName,\n\t\t\t\thasFileProjection: payloadFields?.some(\n\t\t\t\t\t(f) => f.name === 'file' && !isListTypeRef(f.type) && namedTypeName(f.type) === 'JSON',\n\t\t\t\t) ?? false,\n\t\t\t};\n\t\t\tif (field.name === 'uploadAppFile') {\n\t\t\t\tupload = candidate;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tupload ??= candidate;\n\t\t}\n\t}\n\n\tconst fileTypes = new Set<string>();\n\tfor (const t of schema.types) {\n\t\tif (t.kind === 'OBJECT' && t.name && t.fields?.some((f) => f.name === 'downloadUrl')) {\n\t\t\tfileTypes.add(t.name);\n\t\t}\n\t}\n\n\tconst uploadType = upload?.uploadFieldName.replace(/^upload/, '') ?? 'AppFile';\n\tconst uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);\n\tconst preferredPreviewType = fileTypes.has('AppFile') ? 'AppFile' : uploadType;\n\tconst previewType = fileTypes.has(preferredPreviewType)\n\t\t? preferredPreviewType\n\t\t: uploadDownload?.fileTypeName ?? preferredPreviewType;\n\tconst download = previewType === uploadType\n\t\t? uploadDownload\n\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);\n\tconst batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);\n\n\treturn {\n\t\tupload: upload ? { ...upload, download: uploadDownload } : null,\n\t\tdownload,\n\t\tbatch,\n\t};\n}\n\nfunction resolveDownloadByIdField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n): DownloadByIdResult | null {\n\t// 1. Look for an inflected by-id form: a Query field whose return type has a\n\t// `downloadUrl` field and that takes a single `id` arg. e.g. appFile(id:).\n\t// The `$id` variable type is the actual scalar of that id arg (NOT a\n\t// hardcoded UUID) — derived by shape.\n\tlet singular: DownloadByIdResult | null = null;\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst returnTypeName = namedTypeName(field.type);\n\t\tif (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;\n\t\tif (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {\n\t\t\tconst candidate: DownloadByIdResult = {\n\t\t\t\tfileByIdField: field.name,\n\t\t\t\tfileByIdArgName: 'id',\n\t\t\t\tfileTypeName: returnTypeName,\n\t\t\t\tidScalarName: namedTypeName(field.args[0].type) ?? undefined,\n\t\t\t};\n\t\t\tif (returnTypeName === preferred) return candidate;\n\t\t\tsingular ??= candidate;\n\t\t}\n\t}\n\n\t// 2. Connection fallback (Relay-disabled backends, incl. the live tenant API):\n\t// a Query field returning a connection whose `nodes` element is a\n\t// downloadUrl-bearing file type, filtered by id. e.g.\n\t// appFiles(where: { id: { equalTo: $id } }, first: 1) { nodes { downloadUrl } }\n\t// All names (connection field, filter arg, id field, equality operator,\n\t// nodes field, id scalar) are discovered by SHAPE, never hardcoded.\n\t// Preferred over the Relay node path: it consumes the raw fileId directly,\n\t// so it needs no client-side global-id construction.\n\tconst connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);\n\tif (connection?.fileTypeName === preferred) return connection;\n\tif (singular || connection) return singular ?? connection;\n\n\t// 3. Relay fallback: `node(nodeId: ID!)`. Last resort — only when neither a\n\t// singular `id` accessor nor a filtered connection exists. Caller spreads\n\t// `... on <FileType> { downloadUrl }` and encodes the global id.\n\tconst nodeField = queryType?.fields?.find(\n\t\t(f) => f.name === 'node' && f.args.some((a) => a.name === 'nodeId'),\n\t);\n\tif (nodeField && fileTypesWithDownloadUrl.size > 0) {\n\t\t// Deterministic file type for the inline fragment: prefer the type named\n\t\t// after the upload op (uploadAppFile → AppFile); else the first-declared\n\t\t// downloadUrl-bearing type. (Was alphabetical `.sort()[0]`, which could pick\n\t\t// the wrong type when several expose downloadUrl, e.g. DataRoomFile.)\n\t\tconst fileTypeName = fileTypesWithDownloadUrl.has(preferred)\n\t\t\t? preferred\n\t\t\t: [...fileTypesWithDownloadUrl][0];\n\t\treturn { fileByIdField: 'node', fileByIdArgName: 'nodeId', fileTypeName };\n\t}\n\n\treturn null;\n}\n\n/**\n * Discover a filtered connection for single or batched download lookups.\n * The single-file path supports two filter input styles:\n * (a) operator filter — `where: { id: { equalTo: $id } }` (connection-filter\n * plugin): the id field's input type carries an equality operator.\n * (b) condition filter — `condition: { id: $id }`: the id field is the scalar\n * directly.\n */\nfunction resolveConnectionDownloadField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n\tbatch = false,\n): DownloadByIdResult | null {\n\t// Equality operator names we recognize on a filter-input field, in priority\n\t// order (exact-match equality first).\n\tconst EQUALITY_OPERATORS = ['equalTo', 'eq'];\n\n\t// Collect every matching connection, then pick deterministically — a tenant\n\t// with multiple @storageFiles tables exposes several file connections\n\t// (appFiles, dataRoomFiles, …), all carrying downloadUrl-bearing nodes.\n\tconst candidates: DownloadByIdResult[] = [];\n\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst connTypeName = namedTypeName(field.type);\n\t\tif (!connTypeName) continue;\n\t\tconst connType = typeByName.get(connTypeName);\n\t\tif (connType?.kind !== 'OBJECT' || !connType.fields) continue;\n\n\t\t// Find the `nodes` field whose element type is a downloadUrl-bearing file.\n\t\t// Require it to be a LIST (plural) so a singular `appFile: AppFile` field on\n\t\t// some object does NOT false-match as a connection (fetchDownloadUrl indexes\n\t\t// [nodesField][0], which only makes sense on an array).\n\t\tconst nodesField = connType.fields.find((f) => {\n\t\t\tif (!isListTypeRef(f.type)) return false;\n\t\t\tconst elem = namedTypeName(f.type);\n\t\t\treturn elem != null && fileTypesWithDownloadUrl.has(elem);\n\t\t});\n\t\tif (!nodesField) continue;\n\t\tconst fileTypeName = namedTypeName(nodesField.type) as string;\n\t\tif (batch && (fileTypeName !== preferred ||\n\t\t\t!typeByName.get(fileTypeName)?.fields?.some((field) => field.name === PK_FIELD_NAME))) continue;\n\t\tconst connectionHasFirst = field.args.some((arg) => arg.name === 'first');\n\n\t\t// Find a filter arg whose input type has an `id` field.\n\t\tfor (const arg of field.args) {\n\t\t\tconst filterTypeName = namedTypeName(arg.type);\n\t\t\tconst filterType = filterTypeName ? typeByName.get(filterTypeName) : null;\n\t\t\tif (filterType?.kind !== 'INPUT_OBJECT' || !filterType.inputFields) continue;\n\t\t\tconst idField = filterType.inputFields.find((f) => f.name === PK_FIELD_NAME);\n\t\t\tif (!idField) continue;\n\n\t\t\tconst idFieldTypeName = namedTypeName(idField.type);\n\t\t\tconst idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;\n\n\t\t\t// Style (a): the id field is itself an input type carrying an equality\n\t\t\t// operator (e.g. UUIDFilter.equalTo). The `$id` scalar is the operator's\n\t\t\t// type.\n\t\t\tif (idFieldType?.kind === 'INPUT_OBJECT' && idFieldType.inputFields) {\n\t\t\t\tconst opField = batch\n\t\t\t\t\t? idFieldType.inputFields.find((f) => f.name === 'in' && isListTypeRef(f.type))\n\t\t\t\t\t: EQUALITY_OPERATORS.map((op) =>\n\t\t\t\t\t\tidFieldType.inputFields!.find((f) => f.name === op),\n\t\t\t\t\t).find((f) => f != null);\n\t\t\t\tif (opField) {\n\t\t\t\t\tcandidates.push({\n\t\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\t\tfileTypeName,\n\t\t\t\t\t\tidScalarName: namedTypeName(opField.type) ?? undefined,\n\t\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\t\tconnectionIdOperator: opField.name,\n\t\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// This filter lacks the operator needed for this lookup.\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Style (b): the id field is a scalar directly (condition style). The\n\t\t\t// `$id` scalar is that field's type.\n\t\t\tif (!batch && (idFieldType?.kind === 'SCALAR' || (!idFieldType && idFieldTypeName))) {\n\t\t\t\tcandidates.push({\n\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\tfileTypeName,\n\t\t\t\t\tidScalarName: idFieldTypeName ?? undefined,\n\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (candidates.length === 0) return null;\n\n\t// Deterministic pick: prefer the connection whose file type matches the upload\n\t// op (uploadAppFile → AppFile), else the first-declared. This is the LIVE\n\t// production path — the only downloadUrl shape on a Relay-disabled, unique-\n\t// lookup-disabled tenant API — so resolving the WRONG file connection (e.g.\n\t// reading a DataRoomFile id through appFiles) yields 0 nodes and fails every\n\t// upload. Mirrors the node-branch determinism, where it matters far more.\n\treturn candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];\n}\n\n// ============================================================================\n// Upload op call\n// ============================================================================\n\ninterface UploadOpInput {\n\tbucketKey?: string;\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/**\n * Invoke the discovered upload op and normalize its payload.\n * App-scoped buckets have NO owner_id column, so `ownerId` is NEVER sent.\n */\nexport async function callUploadOp(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n): Promise<UploadPayload> {\n\tconst mutation = `\n\t\tmutation SheetsUpload($input: ${cap.inputTypeName}!) {\n\t\t\t${cap.uploadFieldName}(input: $input) {\n\t\t\t\tuploadUrl\n\t\t\t\tfileId\n\t\t\t\tkey\n\t\t\t\tdeduplicated\n\t\t\t\tfile\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, UploadPayload | null>>(mutation, {\n\t\tinput: {\n\t\t\t...(input.bucketKey === undefined ? { isPublic: true } : { bucketKey: input.bucketKey }),\n\t\t\tcontentHash: input.contentHash,\n\t\t\tcontentType: input.contentType,\n\t\t\tsize: input.size,\n\t\t\tfilename: input.filename,\n\t\t},\n\t});\n\tconst payload = data?.[cap.uploadFieldName];\n\tif (!payload) {\n\t\tthrow createError.badRequest('Upload failed: no payload returned from upload mutation.');\n\t}\n\tconst file = payload.file;\n\tif (\n\t\t!file || typeof file.id !== 'string' || typeof file.key !== 'string' ||\n\t\ttypeof file.bucket_id !== 'string' || typeof file.mime !== 'string' || typeof file.size !== 'number'\n\t) {\n\t\tthrow createError.badRequest('Upload failed: server returned an invalid file projection.');\n\t}\n\treturn payload;\n}\n\n// ============================================================================\n// Presigned PUT\n// ============================================================================\n\n/**\n * PUT the raw bytes to the presigned url. Sends ONLY the signed `Content-Type`\n * header — NO Authorization (the signature lives in the url query string), no\n * cookies, no Accept override. The browser supplies Content-Length from the body.\n *\n * When `onProgress` is provided and XHR is available, uses XHR for byte\n * progress; otherwise a plain fetch PUT.\n */\n/**\n * A PUT the browser could not complete. The GraphQL API answered moments ago, so\n * the usual cause is the bucket's CORS rule (no allowed origin for this site) rather\n * than the connection; browsers do not expose which.\n */\nexport const STORAGE_UPLOAD_BLOCKED_MESSAGE =\n\t\"Upload failed: the storage server didn't accept the upload from this site. Check the bucket's allowed origins (CORS) and your connection.\";\n\nfunction storageUnreachableError() {\n\treturn createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, 'STORAGE_UPLOAD_BLOCKED');\n}\n\nexport async function presignedPut(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void,\n): Promise<void> {\n\tconst total = buffer.byteLength;\n\n\tif (onProgress && typeof XMLHttpRequest !== 'undefined') {\n\t\tawait putWithXHR(url, buffer, contentType, total, onProgress);\n\t\treturn;\n\t}\n\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: 'PUT',\n\t\t\theaders: { 'Content-Type': contentType },\n\t\t\tbody: buffer,\n\t\t});\n\t} catch {\n\t\tthrow storageUnreachableError();\n\t}\n\n\tif (!response.ok) {\n\t\tconst body = await response.text().catch(() => '');\n\t\tthrow createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`);\n\t}\n\tonProgress?.({ loaded: total, total, percentage: 100 });\n}\n\nfunction putWithXHR(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\ttotal: number,\n\tonProgress: (progress: { loaded: number; total: number; percentage: number }) => void,\n): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst xhr = new XMLHttpRequest();\n\t\txhr.open('PUT', url);\n\t\txhr.setRequestHeader('Content-Type', contentType);\n\n\t\txhr.upload.addEventListener('progress', (event) => {\n\t\t\tif (event.lengthComputable) {\n\t\t\t\tonProgress({\n\t\t\t\t\tloaded: event.loaded,\n\t\t\t\t\ttotal: event.total,\n\t\t\t\t\tpercentage: Math.round((event.loaded / event.total) * 100),\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\txhr.addEventListener('load', () => {\n\t\t\tif (xhr.status >= 200 && xhr.status < 300) {\n\t\t\t\tonProgress({ loaded: total, total, percentage: 100 });\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` — ${xhr.responseText}` : ''}`));\n\t\t\t}\n\t\t});\n\n\t\txhr.addEventListener('error', () => reject(storageUnreachableError()));\n\n\t\txhr.send(buffer);\n\t});\n}\n\n// ============================================================================\n// downloadUrl resolution\n// ============================================================================\n\n/**\n * Encode a PostGraphile global id (Relay `node` id) from a row's primary key,\n * using the default base64JSON codec: `base64(JSON.stringify([typeName, pk]))`.\n */\nfunction toGlobalId(typeName: string, id: string): string {\n\tif (typeof btoa !== 'function') {\n\t\tthrow createError.badRequest('Cannot encode the file node id: btoa is unavailable in this environment.');\n\t}\n\treturn btoa(JSON.stringify([typeName, id]));\n}\n\n/**\n * Resolve a file's download URL for immediate use. It can be a signed URL\n * with an expiration, so only the storage projection belongs in the cell.\n */\nexport async function fetchDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tcap: DownloadByIdResult,\n\tfileId: string,\n): Promise<string> {\n\tif (cap.fileByIdArgName === 'nodeId') {\n\t\t// The upload payload returns the RAW primary key as `fileId`, but\n\t\t// `node(nodeId:)` expects the opaque PostGraphile global id. Encode it with\n\t\t// the default base64JSON codec (`base64([typeName, pk])`). NOTE: the live\n\t\t// tenant API is Relay-disabled and resolves via the connection branch; this\n\t\t// path is mock-covered only and assumes the default node-id codec.\n\t\tconst nodeId = toGlobalId(cap.fileTypeName, fileId);\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($nodeId: ID!) {\n\t\t\t\t${cap.fileByIdField}(nodeId: $nodeId) {\n\t\t\t\t\t... on ${cap.fileTypeName} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { nodeId });\n\t\tconst node = data?.[cap.fileByIdField];\n\t\tconst url = node?.downloadUrl;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t\t}\n\t\treturn url;\n\t}\n\n\t// Connection fallback (Relay-disabled): filter the connection by id and read\n\t// the first node's downloadUrl. The filter literal is built per the discovered\n\t// style — operator (`{ id: { equalTo: $id } }`) or condition (`{ id: $id }`).\n\tif (cap.fileByIdArgName === 'connection') {\n\t\tconst idScalar = cap.idScalarName ?? 'ID';\n\t\tconst filterArg = cap.connectionFilterArgName as string;\n\t\tconst idField = cap.connectionIdField as string;\n\t\tconst nodesField = cap.connectionNodesField as string;\n\t\tconst filterLiteral = cap.connectionIdOperator\n\t\t\t? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }`\n\t\t\t: `{ ${idField}: $id }`;\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t\t${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ', first: 1' : ''}) {\n\t\t\t\t\t${nodesField} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, Record<string, Array<{ downloadUrl?: string | null }> | null> | null>>(\n\t\t\tquery,\n\t\t\t{ id: fileId },\n\t\t);\n\t\tconst conn = data?.[cap.fileByIdField];\n\t\tconst url = conn?.[nodesField]?.[0]?.downloadUrl;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t\t}\n\t\treturn url;\n\t}\n\n\tconst idScalar = cap.idScalarName ?? 'ID';\n\tconst query = `\n\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t${cap.fileByIdField}(id: $id) {\n\t\t\t\tid\n\t\t\t\tdownloadUrl\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { id: fileId });\n\tconst file = data?.[cap.fileByIdField];\n\tconst url = file?.downloadUrl;\n\tif (!url) {\n\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t}\n\treturn url;\n}\n\n/** Resolve URLs for one batch of visible images. Missing or unreadable IDs have no entry. */\nexport async function fetchMediaDownloadUrls(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tgetActiveIds: () => readonly string[],\n): Promise<Map<string, string>> {\n\tconst { batch, download } = await discoverStorageCapabilities(endpoint, execute);\n\tconst ids = getActiveIds();\n\tconst urls = new Map<string, string>();\n\tif (ids.length === 0) return urls;\n\tif (batch) {\n\t\tconst first = batch.connectionHasFirst ? `, first: ${ids.length}` : '';\n\t\tconst query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? 'ID'}!]!) {\n\t\t\t${batch.fileByIdField}(${batch.connectionFilterArgName}: {\n\t\t\t\t${batch.connectionIdField}: { in: $ids }\n\t\t\t}${first}) { ${batch.connectionNodesField} { id downloadUrl } }\n\t\t}`;\n\t\ttype FileNode = { id: string; downloadUrl: string | null };\n\t\tconst data = await execute<Record<string, Record<string, (FileNode | null)[] | null> | null>>(query, { ids });\n\t\tfor (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField!] ?? []) {\n\t\t\tif (row?.downloadUrl) urls.set(row.id, row.downloadUrl);\n\t\t}\n\t} else if (download) {\n\t\tconst results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));\n\t\tresults.forEach((result, index) => {\n\t\t\tif (result.status === 'fulfilled') urls.set(ids[index], result.value);\n\t\t});\n\t}\n\treturn urls;\n}\n\n/**\n * Resolve a file's signed `downloadUrl` by id — the public entry point for callers\n * OUTSIDE the upload flow (e.g. a storage browser fetching the preview/copy link for\n * an already-uploaded file).\n *\n * `downloadUrl` is a Grafast computed field, so it cannot be selected through the\n * runtime query builder (`buildSelect` intersects the select against pg columns and\n * drops computed fields). This discovers the by-id field using cached introspection\n * and reads it through the SAME resolver the upload path uses. Returns null on any\n * failure — a missing url is not exceptional for the caller (it just disables\n * copy/download), so the throwing internals are swallowed here.\n */\nexport async function resolveDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tendpoint: string,\n\tfileId: string,\n): Promise<string | null> {\n\ttry {\n\t\tconst { download } = await discoverStorageCapabilities(endpoint, execute);\n\t\treturn download ? await fetchDownloadUrl(execute, download, fileId) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n","// Parse image data - handles both URL strings and image objects\nexport const getImageUrl = (imageValue: unknown): string | null => {\n\tif (!imageValue) return null;\n\n\t// If it's a string, assume it's a URL\n\tif (typeof imageValue === 'string') {\n\t\treturn imageValue;\n\t}\n\n\t// If it's an object, look for common URL properties\n\tif (typeof imageValue === 'object' && imageValue !== null) {\n\t\t// Try different possible URL properties\n\t\tconst urlCandidates = ['url', 'src', 'href', 'link', 'path'];\n\t\tfor (const candidate of urlCandidates) {\n\t\t\tconst obj = imageValue as Record<string, unknown>;\n\t\t\tif (obj[candidate] && typeof obj[candidate] === 'string') {\n\t\t\t\treturn obj[candidate] as string;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n};\n\n/** ID from a stored media projection, used only for scoped preview lookups. */\nexport function getMediaFileId(value: unknown): string | null {\n\tif (!value || typeof value !== 'object') return null;\n\tconst { id } = value as { id?: unknown };\n\treturn typeof id === 'string' && id ? id : null;\n}\n\n// Get image metadata from image object\nexport const getImageMetadata = (imageValue: unknown) => {\n\tif (!imageValue || typeof imageValue !== 'object') return null;\n\n\tconst obj = imageValue as Record<string, unknown>;\n\treturn {\n\t\tfilename: (obj.filename as string) || (obj.name as string) || 'Unknown',\n\t\tsize: typeof obj.size === 'number' ? obj.size : typeof obj.fileSize === 'number' ? obj.fileSize : undefined,\n\t\tmime: (obj.mime as string) || (obj.type as string) || (obj.contentType as string) || 'unknown',\n\t};\n};\n\n// Format file size for display\nexport const formatFileSize = (bytes: number): string => {\n\tif (bytes === 0) return '0 B';\n\tconst k = 1024;\n\tconst sizes = ['B', 'KB', 'MB', 'GB'];\n\tconst i = Math.floor(Math.log(bytes) / Math.log(k));\n\treturn parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];\n};\n","import { useEffect, useState } from 'react';\n\nexport type ImageStatus = 'idle' | 'loading' | 'loaded' | 'error';\n\nexport function useImageStatus(src?: string): ImageStatus {\n\tconst [result, setResult] = useState<{ src: string; status: 'loaded' | 'error' }>();\n\n\tuseEffect(() => {\n\t\tif (!src) return;\n\n\t\tconst img = new Image();\n\n\t\tconst onLoad = () => setResult({ src, status: 'loaded' });\n\t\tconst onError = () => setResult({ src, status: 'error' });\n\n\t\timg.addEventListener('load', onLoad);\n\t\timg.addEventListener('error', onError);\n\t\timg.src = src;\n\n\t\treturn () => {\n\t\t\timg.removeEventListener('load', onLoad);\n\t\t\timg.removeEventListener('error', onError);\n\t\t};\n\t}, [src]);\n\n\tif (!src) return 'idle';\n\treturn result?.src === src ? result.status : 'loading';\n}\n","'use client';\n\nimport React, { ImgHTMLAttributes, useMemo, useState } from 'react';\n\nimport { useImageStatus } from './use-image-status';\nimport { cn } from './cn';\n\ntype Fallback = string | React.ReactNode; // a URL or JSX (icon, initials, skeleton...)\n\n/**\n * Props mirror <img> + a few extras. Extend or omit freely.\n */\nexport interface ImageWithFallbackProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {\n\t/** Primary image source. */\n\tsrc?: string | null;\n\t/** Ordered list of fallbacks. */\n\tfallback?: Fallback | Fallback[];\n\t/** Optional class for wrappers (useful for width / height utilities). */\n\twrapperClassName?: string;\n\t/** Legacy props for backward compatibility */\n\tfallbackElement?: React.ReactNode;\n\tloadingElement?: React.ReactNode;\n}\n\nexport function ImageWithFallback({\n\tsrc,\n\talt = '',\n\tfallback,\n\tfallbackElement,\n\tloadingElement,\n\twrapperClassName,\n\tclassName,\n\t...imgProps\n}: ImageWithFallbackProps) {\n\t/* ----- flatten fallbacks into an array ---------------------------- */\n\tconst fallbacks = useMemo<Fallback[]>(() => {\n\t\tconst legacyFallbacks = [];\n\t\tif (loadingElement) legacyFallbacks.push(loadingElement);\n\t\tif (fallbackElement) legacyFallbacks.push(fallbackElement);\n\n\t\tconst primaryFallbacks = fallback === undefined ? [] : Array.isArray(fallback) ? fallback : [fallback];\n\n\t\treturn [...primaryFallbacks, ...legacyFallbacks];\n\t}, [fallback, fallbackElement, loadingElement]);\n\n\t/* ----- track which source we're currently trying ------------------ */\n\tconst [currentSrcIndex, setCurrentSrcIndex] = useState(0);\n\tconst currentSrc = currentSrcIndex === 0 ? src : (fallbacks[currentSrcIndex - 1] as string | undefined);\n\n\t/* ----- get status of the CURRENT url ------------------------------ */\n\tconst status = useImageStatus(typeof currentSrc === 'string' ? currentSrc : undefined);\n\n\t/* ----- if it errors, bump index and try the next ------------------ */\n\tif (status === 'error' && currentSrcIndex < fallbacks.length) {\n\t\t// only URLs auto-advance\n\t\tif (typeof fallbacks[currentSrcIndex] === 'string') {\n\t\t\tsetCurrentSrcIndex((i) => i + 1);\n\t\t}\n\t}\n\n\t/* ------------------------------------------------------------------ */\n\tconst renderContent = () => {\n\t\tswitch (status) {\n\t\t\tcase 'idle':\n\t\t\tcase 'loading': {\n\t\t\t\t// if the NEXT fallback is JSX (e.g. skeleton), render it early\n\t\t\t\tconst maybeJSX = fallbacks.find((f) => typeof f !== 'string');\n\t\t\t\treturn maybeJSX ?? <div className='bg-muted h-full w-full animate-pulse rounded-md' />;\n\t\t\t}\n\n\t\t\tcase 'loaded': {\n\t\t\t\treturn (\n\t\t\t\t\t<img\n\t\t\t\t\t\tsrc={currentSrc!}\n\t\t\t\t\t\talt={alt}\n\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t'object-cover outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10',\n\t\t\t\t\t\t\tclassName,\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t{...imgProps}\n\t\t\t\t\t/>\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tcase 'error': {\n\t\t\t\t// final fallback: the first JSX fallback, or a default icon\n\t\t\t\tconst jsxFallback = fallbacks.find((f) => typeof f !== 'string');\n\t\t\t\treturn (\n\t\t\t\t\tjsxFallback ?? (\n\t\t\t\t\t\t<div className='bg-muted flex h-full w-full items-center justify-center rounded-md text-sm'>\n\t\t\t\t\t\t\t{alt?.[0] ?? '?'}\n\t\t\t\t\t\t</div>\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t};\n\n\treturn <div className={cn('relative overflow-hidden', wrapperClassName)}>{renderContent()}</div>;\n}\n","import React, { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { Button } from '@constructive-io/ui/button';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\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}:)*::$/;\nconst MAC_UA_RE = /Mac|iPod|iPhone|iPad/;\n\ninterface InetEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\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 }) => {\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\tconst isMac = typeof navigator !== 'undefined' && MAC_UA_RE.test(navigator.userAgent);\n\tconst modKey = isMac ? '⌘' : 'Ctrl';\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}>\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{/* Footer — hints + save */}\n\t\t\t\t<div className='mt-3 flex items-center justify-between gap-4 border-t px-1 pt-2.5'>\n\t\t\t\t\t<div className='text-muted-foreground flex items-center gap-3 text-xs'>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight'>Enter</kbd>\n\t\t\t\t\t\t\t<span>save</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight'>Esc</kbd>\n\t\t\t\t\t\t\t<span>cancel</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t<Button onClick={handleSave} size='xs' variant='default' className='shrink-0' disabled={!!validationError}>\n\t\t\t\t\t\tSave\n\t\t\t\t\t</Button>\n\t\t\t\t</div>\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 { InetEditor } from '../../grid/editors/inet-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function InetEditorDom({ value, 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\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';\nimport { Check, Clock, X } from 'lucide-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 { EditorFocusTrap } from './editor-focus-trap';\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}\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 }) => {\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-4 rounded-lg border p-4 shadow-lg`}>\n\t\t\t<div onKeyDown={handleEditorKeyDown}>\n\t\t\t{/* Header */}\n\t\t\t<div className='flex items-center gap-2'>\n\t\t\t\t<Clock className='text-muted-foreground h-4 w-4' />\n\t\t\t\t<h3 className='text-sm font-medium'>Edit Time Interval</h3>\n\t\t\t</div>\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{/* Action Buttons */}\n\t\t\t<div className='flex justify-end gap-2'>\n\t\t\t\t<Button variant='outline' size='sm' onClick={handleCancel}>\n\t\t\t\t\t<X className='mr-1 h-3 w-3' />\n\t\t\t\t\tCancel\n\t\t\t\t</Button>\n\t\t\t\t<Button size='sm' onClick={handleSave}>\n\t\t\t\t\t<Check className='mr-1 h-3 w-3' />\n\t\t\t\t\tSave\n\t\t\t\t</Button>\n\t\t\t</div>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","'use client';\n\n// Native interval editor — a thin EditorProps adapter that RE-HOSTS the (now value-\n// native) `IntervalEditor` verbatim. The UI (days/hours/minutes/seconds inputs,\n// preview, OVERLAY.sm width, own EditorFocusTrap) is reused as-is; the contract maps\n// directly to value-native EditorProps.\n//\n// The editor reads the raw row value (the JSON-encoded interval string) and emits the\n// raw JSON string back, so the value flows straight through: `onFinishedEditing(next)`\n// -> `onCommit(next)`, `onFinishedEditing(undefined)` -> `onCancel()`.\n\nimport { IntervalEditor } from '../../grid/editors/interval-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function IntervalEditorDom({ value, onCommit, onCancel }: EditorProps) {\n\treturn (\n\t\t<IntervalEditor\n\t\t\tvalue={value}\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\nimport { Button } from '@constructive-io/ui/button';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\n\nconst MAC_UA_RE = /Mac|iPod|iPhone|iPad/;\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};\n\nexport function JsonEditor({ value, onChange, onFinished }: 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\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\tconst isMac = typeof navigator !== 'undefined' && MAC_UA_RE.test(navigator.userAgent);\n\tconst modKey = isMac ? '⌘' : 'Ctrl';\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}>\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{/* Footer — validation + hints + save */}\n\t\t\t\t<div className='mt-3 flex items-center justify-between gap-4 border-t px-1 pt-2.5'>\n\t\t\t\t\t<div className='text-muted-foreground flex items-center gap-3 text-xs'>\n\t\t\t\t\t\t{valid ? (\n\t\t\t\t\t\t\t<span className='text-muted-foreground/60 shrink-0 text-xs'>Valid</span>\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<span className='text-destructive shrink-0 text-xs'>Invalid</span>\n\t\t\t\t\t\t)}\n\t\t\t\t\t\t<span className='text-border'>|</span>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>{modKey}</kbd>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight'>↵</kbd>\n\t\t\t\t\t\t\t<span>save</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<span className='inline-flex shrink-0 items-center gap-1'>\n\t\t\t\t\t\t\t<kbd className='bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight'>Esc</kbd>\n\t\t\t\t\t\t\t<span>cancel</span>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t<Button onClick={handleSave} size='xs' variant='default' className='shrink-0' disabled={!valid}>\n\t\t\t\t\t\tSave\n\t\t\t\t\t</Button>\n\t\t\t\t</div>\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 existing\n// value-native `JsonEditor` ({ value, onChange, onFinished }) verbatim. The UI\n// (highlighter, footer, OVERLAY.lg width, own EditorFocusTrap) is reused as-is;\n// only the commit/cancel contract is mapped: `onFinished(next)` -> `onCommit(next)`,\n// `onFinished(undefined)` -> `onCancel()`. `onChange` is a no-op because the\n// native value-commit path reads only the committed value (parity with the glide\n// `createJsonEditorFactory`, which also passes `onChange: () => {}`).\n\nimport { JsonEditor } from '../../grid/editors/json-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function JsonEditorDom({ value, onCommit, onCancel }: EditorProps) {\n\treturn (\n\t\t<JsonEditor\n\t\t\tvalue={value}\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 { 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\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/** Parse the input text to the committed value: '' -> null, else a finite number or NaN. */\nfunction parseValue(text: string): number | null {\n\tconst trimmed = text.trim();\n\tif (trimmed === '') return null;\n\treturn Number(trimmed);\n}\n\nexport function NumberEditorDom({ value, initialText, colKey, fieldMeta, 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);\n\t// Save is blocked only when the field has content that does not parse to a\n\t// finite number; an empty field is a valid `null` commit.\n\tconst canSave = parsed === null || Number.isFinite(parsed);\n\n\tfunction commit() {\n\t\tif (!canSave) return;\n\t\tonCommit(parsed);\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 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 outline-none'\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</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","import React, { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { Check, Link, Loader2, Search, X } from 'lucide-react';\nimport { useQueryClient } from '@tanstack/react-query';\n\nimport { useSheetsTable, sheetsTableQueryKeys } from '../../hooks/use-sheets-table';\nimport { useSheetsTableCursor } from '../../hooks/use-sheets-table-cursor';\nimport { useSheetsContext } from '../../context/sheets-context';\nimport { useSheetsMeta } from '../../hooks/use-sheets-meta';\nimport { useSheetsStore } from '../../store/sheets-store';\nimport { sheetsQueryKeys } from '../../hooks/query-keys';\nimport { cn } from '../../utils/cn';\nimport { Badge } from '@constructive-io/ui/badge';\nimport { Button } from '@constructive-io/ui/button';\nimport { InputGroup, InputGroupAddon, InputGroupInput } from '@constructive-io/ui/input-group';\nimport { Label } from '@constructive-io/ui/label';\nimport { toast } from '@constructive-io/ui/toast';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\nimport { OverlayMeasureContext } from './overlay-viewport-guard';\nimport { RelationRecordTooltip } from './relation-record-tooltip';\nimport { sheetsLogger } from '../../utils/sheets-logger';\n\ntype RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\n/** Data passed to onSaveComplete for optimistic updates */\nexport interface RelationSaveData {\n\t/** The selected record(s) - single object for belongsTo/hasOne, array for hasMany/manyToMany */\n\trelationData: unknown;\n\t/** The foreign key value (ID) for belongsTo relations */\n\tforeignKeyValue: unknown;\n}\n\ninterface RelationEditorProps {\n\t/** Ignored — the editor reads {@link RelationEditorProps.currentValue} instead. */\n\tvalue?: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n\ttableName: string;\n\trecordId?: string | number | null;\n\tfieldName: string;\n\tcurrentValue: unknown;\n\t/** Called after successful save with data for optimistic updates */\n\tonSaveComplete?: (data: RelationSaveData) => void;\n}\n\n/**\n * Normalises a relation value into a flat array of record objects.\n *\n * The editor-registry already wraps bare FK strings into `{ id }` before\n * passing them here, but this function also handles that case defensively\n * so the editor works correctly if called from other code paths.\n */\nfunction coerceToArray(v: unknown): any[] {\n\tif (v == null) return [];\n\tif (Array.isArray(v)) return v;\n\tif (typeof v === 'object') {\n\t\tconst obj = v as Record<string, unknown>;\n\t\tif (Array.isArray(obj.nodes)) return obj.nodes;\n\t\treturn [v];\n\t}\n\t// Bare string (e.g. a UUID FK value) -- wrap as { id } defensively\n\tif (typeof v === 'string' && v) return [{ id: v }];\n\treturn [];\n}\n\nconst DISPLAY_FIELDS = ['name', 'title', 'label', 'displayName', 'fullName', 'email', 'username', 'description', 'code'];\n\nfunction getRelationDisplayText(relation: any): string {\n\tif (!relation || typeof relation !== 'object') {\n\t\treturn String(relation || '');\n\t}\n\n\t// Try common display field patterns\n\tfor (const field of DISPLAY_FIELDS) {\n\t\tif (relation[field] != null && String(relation[field]).trim()) {\n\t\t\treturn String(relation[field]);\n\t\t}\n\t}\n\n\t// Fallback to ID\n\tif (relation.id != null) {\n\t\treturn `Record ${relation.id}`;\n\t}\n\n\treturn 'Unknown Record';\n}\n\nexport const RelationEditor: React.FC<RelationEditorProps> = ({\n\tonFinishedEditing,\n\ttableName,\n\trecordId,\n\tfieldName,\n\tcurrentValue,\n\tonSaveComplete,\n}) => {\n\tconst { data: meta } = useSheetsMeta();\n\tconst { scopeKey } = useSheetsContext();\n\tconst queryClient = useQueryClient();\n\tconst ensureRelationInfo = useSheetsStore((s) => s.ensureRelationInfo);\n\tconst relationInfoForTable = useSheetsStore((s) => tableName ? s.relationInfoCache[tableName] : undefined);\n\n\tconst relationEntry = relationInfoForTable?.[fieldName];\n\tconst isDraft = typeof recordId === 'string' && recordId.startsWith('draft:');\n\n\t// Resolve relation kind/table from global cache\n\tuseEffect(() => {\n\t\tif (!tableName) return;\n\t\tif (relationInfoForTable?.[fieldName]) return;\n\t\tensureRelationInfo(tableName, meta);\n\t}, [tableName, fieldName, meta, ensureRelationInfo, relationInfoForTable]);\n\n\tconst relationDef = useMemo(() => {\n\t\tconst entry = relationEntry;\n\t\tif (!entry) return null as null | { kind: RelationKind; relatedTable?: string };\n\t\treturn { kind: entry.kind as RelationKind, relatedTable: entry.relatedTable };\n\t}, [relationEntry]);\n\n\tconst isMulti = relationDef?.kind === 'hasMany' || relationDef?.kind === 'manyToMany';\n\tconst relatedTableName = relationDef?.relatedTable;\n\tconst isManyToMany = relationDef?.kind === 'manyToMany';\n\tconst requiredMetaMissing = useMemo(() => {\n\t\tif (!relationEntry) return true;\n\t\tif (isDraft) {\n\t\t\t// Draft rows only support belongsTo (picks FK locally, no server mutation needed)\n\t\t\tif (relationEntry.kind !== 'belongsTo') return true;\n\t\t\treturn !relationEntry.relatedTable || !relationEntry.foreignKeyField;\n\t\t}\n\t\tif (recordId == null) return true;\n\t\tif (!relationEntry.relatedTable) return true;\n\t\tswitch (relationEntry.kind) {\n\t\t\tcase 'belongsTo':\n\t\t\t\treturn !relationEntry.foreignKeyField;\n\t\t\tcase 'hasOne':\n\t\t\tcase 'hasMany':\n\t\t\t\treturn !relationEntry.foreignKeyField;\n\t\t\tcase 'manyToMany':\n\t\t\t\treturn !(\n\t\t\t\t\trelationEntry.junctionTable &&\n\t\t\t\t\trelationEntry.junctionLeftKeyField &&\n\t\t\t\t\trelationEntry.junctionRightKeyField\n\t\t\t\t);\n\t\t\tdefault:\n\t\t\t\treturn true;\n\t\t}\n\t}, [relationEntry, recordId, isDraft]);\n\n\tconst canPersist = Boolean(relationEntry && !requiredMetaMissing);\n\n\tconst { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);\n\n\t// Measure actual fixed UI height from the DOM, then distribute remaining\n\t// scroll budget between the two sections. The overlay is invisible during\n\t// mount (Web Animation opacity:0), so the measurement + re-render is hidden.\n\tconst editorRef = useRef<HTMLDivElement>(null);\n\tconst currentScrollRef = useRef<HTMLDivElement>(null);\n\tconst [scrollBudgets, setScrollBudgets] = useState<{ current?: number; addFrom?: number }>({});\n\n\tuseLayoutEffect(() => {\n\t\tconst editor = editorRef.current;\n\t\tconst currentScroll = currentScrollRef.current;\n\t\tconst addFromScroll = scrollContainerRef.current;\n\t\tif (!editor || !currentScroll || !addFromScroll || overlayMaxHeight <= 0) return;\n\n\t\tconst measuredFixedUI = editor.scrollHeight - currentScroll.scrollHeight - addFromScroll.scrollHeight;\n\t\tconst budget = Math.max(0, overlayMaxHeight - measuredFixedUI);\n\n\t\tsetScrollBudgets({\n\t\t\tcurrent: Math.floor(budget * 0.35),\n\t\t\taddFrom: Math.floor(budget * 0.65),\n\t\t});\n\t}, [overlayMaxHeight]);\n\n\t// Current selected relations\n\tconst initialSelection = useMemo(() => coerceToArray(currentValue), [currentValue]);\n\tconst [editingValue, setEditingValue] = useState<any[]>(initialSelection);\n\tconst [searchQuery, setSearchQuery] = useState('');\n\n\t// Refs for values read inside async handleSave (prevents stale closures)\n\tconst editingValueRef = useRef(editingValue);\n\teditingValueRef.current = editingValue;\n\tconst initialSelectionRef = useRef(initialSelection);\n\tinitialSelectionRef.current = initialSelection;\n\n\t// Safety net: close the editor if the row context switches while the overlay is open.\n\t// This can happen if Glide re-invokes provideEditor with a reordered data array,\n\t// causing the editor to receive a different recordId without unmounting.\n\t// Use ref for onFinishedEditing to avoid re-subscribing on every render\n\t// (Glide's callback is unstable). See: advanced-event-handler-refs.\n\tconst onFinishedEditingRef = useRef(onFinishedEditing);\n\tonFinishedEditingRef.current = onFinishedEditing;\n\tconst initialRecordIdRef = useRef(recordId);\n\tuseEffect(() => {\n\t\tif (initialRecordIdRef.current != null && recordId != null && initialRecordIdRef.current !== recordId) {\n\t\t\tonFinishedEditingRef.current();\n\t\t}\n\t}, [recordId]);\n\n\t/** Set of selected record IDs for O(1) lookup */\n\tconst selectedIdSet = useMemo(() => {\n\t\tconst set = new Set<string | number>();\n\t\tfor (const r of editingValue) {\n\t\t\tconst id = r?.id;\n\t\t\tif (id != null) set.add(id);\n\t\t}\n\t\treturn set;\n\t}, [editingValue]);\n\n\t// Display candidates from global cache\n\tconst displayCandidates = useMemo(() => {\n\t\tconst entry = relationEntry;\n\t\treturn entry?.displayCandidates?.length ? entry.displayCandidates : ['name', 'displayName', 'fullName', 'title'];\n\t}, [relationEntry]);\n\n\t// Query related table options\n\tconst whereFilter = useMemo(() => {\n\t\tif (!searchQuery.trim() || displayCandidates.length === 0) return undefined;\n\t\tconst includesFilters = displayCandidates.map((f) => ({ [f]: { includesInsensitive: searchQuery } }));\n\t\treturn { or: includesFilters } as any;\n\t}, [searchQuery, displayCandidates]);\n\n\tconst {\n\t\tdata: options = [],\n\t\tisLoading,\n\t\tisFetchingNextPage,\n\t\thasNextPage,\n\t\tfetchNextPage,\n\t\ttotalCount: optionsTotalCount,\n\t} = useSheetsTableCursor(relatedTableName || '', {\n\t\tenabled: !!relatedTableName,\n\t\tselect: 'all',\n\t\tpageSize: 20,\n\t\twhere: whereFilter,\n\t});\n\n\tconst { data: junctionRows = [], isLoading: isJunctionLoading } = useSheetsTable(relationEntry?.junctionTable || '', {\n\t\tenabled:\n\t\t\tcanPersist &&\n\t\t\tisManyToMany &&\n\t\t\trecordId != null &&\n\t\t\t!!relationEntry?.junctionTable &&\n\t\t\t!!relationEntry?.junctionLeftKeyField,\n\t\tselect:\n\t\t\trelationEntry?.junctionLeftKeyField && relationEntry?.junctionRightKeyField\n\t\t\t\t? {\n\t\t\t\t\tselect: ['id', relationEntry.junctionLeftKeyField, relationEntry.junctionRightKeyField],\n\t\t\t\t}\n\t\t\t\t: 'minimal',\n\t\tlimit: 500,\n\t\twhere:\n\t\t\trelationEntry?.junctionLeftKeyField && recordId != null\n\t\t\t\t? ({ [relationEntry.junctionLeftKeyField]: { equalTo: recordId } } as any)\n\t\t\t\t: undefined,\n\t}) as any;\n\n\tconst parentTable = useSheetsTable(tableName, { enabled: false }) as any;\n\tconst relatedTable = useSheetsTable(relatedTableName || '', { enabled: false }) as any;\n\tconst junctionTable = useSheetsTable(relationEntry?.junctionTable || '', { enabled: false }) as any;\n\n\tconst [isSaving, setIsSaving] = useState(false);\n\n\t// IntersectionObserver sentinel for \"load more\" in the \"Add from\" list\n\tconst sentinelRef = useRef<HTMLDivElement>(null);\n\tconst scrollContainerRef = useRef<HTMLDivElement>(null);\n\tuseEffect(() => {\n\t\tconst sentinel = sentinelRef.current;\n\t\tconst root = scrollContainerRef.current;\n\t\tif (!sentinel || !root || !hasNextPage || isFetchingNextPage) return;\n\n\t\tconst observer = new IntersectionObserver(\n\t\t\t([entry]) => {\n\t\t\t\tif (entry.isIntersecting) fetchNextPage();\n\t\t\t},\n\t\t\t{ root, rootMargin: '100px', threshold: 0 },\n\t\t);\n\t\tobserver.observe(sentinel);\n\t\treturn () => observer.disconnect();\n\t}, [hasNextPage, isFetchingNextPage, fetchNextPage]);\n\n\t// Ref for junctionRows read inside async handler\n\tconst junctionRowsRef = useRef(junctionRows);\n\tjunctionRowsRef.current = junctionRows;\n\n\tconst handleSave = useCallback(() => {\n\t\tvoid (async () => {\n\t\t\tif (!relationEntry || recordId == null) {\n\t\t\t\tonFinishedEditing();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!canPersist) {\n\t\t\t\tonFinishedEditing();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst getRecordId = (r: any): string | number | null => {\n\t\t\t\tif (r == null) return null;\n\t\t\t\tif (typeof r === 'string' || typeof r === 'number') return r;\n\t\t\t\tif (typeof r === 'object' && (typeof r.id === 'string' || typeof r.id === 'number')) return r.id;\n\t\t\t\treturn null;\n\t\t\t};\n\n\t\t\t// Read current values from refs to avoid stale closures\n\t\t\tconst currentEditing = editingValueRef.current;\n\t\t\tconst currentInitial = initialSelectionRef.current;\n\n\t\t\tsetIsSaving(true);\n\t\t\ttry {\n\t\t\t\tconst initialIds = new Set(currentInitial.map(getRecordId).filter((id): id is string | number => id != null));\n\t\t\t\tconst nextIds = new Set(currentEditing.map(getRecordId).filter((id): id is string | number => id != null));\n\n\t\t\t\tif (relationEntry.kind === 'belongsTo') {\n\t\t\t\t\tconst selectedId = Array.from(nextIds)[0] ?? null;\n\t\t\t\t\tconst fkField = relationEntry.foreignKeyField;\n\t\t\t\t\tif (!fkField) throw new Error('Missing foreignKeyField for belongsTo relation');\n\n\t\t\t\t\tif (isDraft) {\n\t\t\t\t\t\tonSaveComplete?.({ relationData: currentEditing[0] ?? null, foreignKeyValue: selectedId });\n\t\t\t\t\t\tonFinishedEditing();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tawait parentTable.update(recordId, { [fkField]: selectedId });\n\t\t\t\t\tonSaveComplete?.({\n\t\t\t\t\t\trelationData: currentEditing[0] ?? null,\n\t\t\t\t\t\tforeignKeyValue: selectedId,\n\t\t\t\t\t});\n\t\t\t\t\tonFinishedEditing();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (relationEntry.kind === 'hasOne') {\n\t\t\t\t\tconst fkField = relationEntry.foreignKeyField;\n\t\t\t\t\tif (!fkField) throw new Error('Missing foreignKeyField for hasOne relation');\n\t\t\t\t\tconst prevId = Array.from(initialIds)[0] ?? null;\n\t\t\t\t\tconst nextId = Array.from(nextIds)[0] ?? null;\n\n\t\t\t\t\t// Parallelize independent unlink/link mutations\n\t\t\t\t\tconst mutations: Promise<unknown>[] = [];\n\t\t\t\t\tif (prevId && prevId !== nextId) {\n\t\t\t\t\t\tmutations.push(relatedTable.update(prevId, { [fkField]: null }));\n\t\t\t\t\t}\n\t\t\t\t\tif (nextId && nextId !== prevId) {\n\t\t\t\t\t\tmutations.push(relatedTable.update(nextId, { [fkField]: recordId }));\n\t\t\t\t\t}\n\t\t\t\t\tif (mutations.length > 0) await Promise.all(mutations);\n\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) }),\n\t\t\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.cursorTable(scopeKey, relatedTableName || '') }),\n\t\t\t\t\t]);\n\t\t\t\t\tonSaveComplete?.({\n\t\t\t\t\t\trelationData: currentEditing[0] ?? null,\n\t\t\t\t\t\tforeignKeyValue: null,\n\t\t\t\t\t});\n\t\t\t\t\tonFinishedEditing();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (relationEntry.kind === 'hasMany') {\n\t\t\t\t\tconst fkField = relationEntry.foreignKeyField;\n\t\t\t\t\tif (!fkField) throw new Error('Missing foreignKeyField for hasMany relation');\n\t\t\t\t\tconst toAdd = Array.from(nextIds).filter((id) => !initialIds.has(id));\n\t\t\t\t\tconst toRemove = Array.from(initialIds).filter((id) => !nextIds.has(id));\n\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\t...toAdd.map((id) => relatedTable.update(id, { [fkField]: recordId })),\n\t\t\t\t\t\t...toRemove.map((id) => relatedTable.update(id, { [fkField]: null })),\n\t\t\t\t\t]);\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) }),\n\t\t\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.cursorTable(scopeKey, relatedTableName || '') }),\n\t\t\t\t\t]);\n\t\t\t\t\tonSaveComplete?.({\n\t\t\t\t\t\trelationData: currentEditing,\n\t\t\t\t\t\tforeignKeyValue: null,\n\t\t\t\t\t});\n\t\t\t\t\tonFinishedEditing();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (relationEntry.kind === 'manyToMany') {\n\t\t\t\t\tconst jt = relationEntry.junctionTable;\n\t\t\t\t\tconst leftFk = relationEntry.junctionLeftKeyField;\n\t\t\t\t\tconst rightFk = relationEntry.junctionRightKeyField;\n\t\t\t\t\tif (!jt || !leftFk || !rightFk) throw new Error('Missing junction metadata for manyToMany relation');\n\n\t\t\t\t\tconst toAdd = Array.from(nextIds).filter((id) => !initialIds.has(id));\n\t\t\t\t\tconst toRemove = Array.from(initialIds).filter((id) => !nextIds.has(id));\n\n\t\t\t\t\tconst rows: any[] = Array.isArray(junctionRowsRef.current) ? junctionRowsRef.current : [];\n\t\t\t\t\tconst byRight = new Map<string | number, any>();\n\t\t\t\t\trows.forEach((r) => {\n\t\t\t\t\t\tconst rightId = r?.[rightFk];\n\t\t\t\t\t\tif (rightId != null) byRight.set(rightId, r);\n\t\t\t\t\t});\n\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\t...toAdd.map((id) => junctionTable.create({ [leftFk]: recordId, [rightFk]: id })),\n\t\t\t\t\t\t...toRemove\n\t\t\t\t\t\t\t.map((id) => byRight.get(id))\n\t\t\t\t\t\t\t.filter((row) => row && (row.id != null || (row[leftFk] != null && row[rightFk] != null)))\n\t\t\t\t\t\t\t.map((row) => row.id != null\n\t\t\t\t\t\t\t\t? junctionTable.delete(row.id)\n\t\t\t\t\t\t\t\t: junctionTable.delete({ [leftFk]: row[leftFk], [rightFk]: row[rightFk] })\n\t\t\t\t\t\t\t),\n\t\t\t\t\t]);\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) }),\n\t\t\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, jt) }),\n\t\t\t\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.cursorTable(scopeKey, relatedTableName || '') }),\n\t\t\t\t\t]);\n\t\t\t\t\tonSaveComplete?.({\n\t\t\t\t\t\trelationData: currentEditing,\n\t\t\t\t\t\tforeignKeyValue: null,\n\t\t\t\t\t});\n\t\t\t\t\tonFinishedEditing();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tonFinishedEditing();\n\t\t\t} catch (err) {\n\t\t\t\tsheetsLogger().error('[relation-editor] save failed:', err);\n\t\t\t\ttoast.error({ message: err instanceof Error ? err.message : 'Failed to save relation' });\n\t\t\t} finally {\n\t\t\t\tsetIsSaving(false);\n\t\t\t}\n\t\t})();\n\t}, [\n\t\tcanPersist,\n\t\tonFinishedEditing,\n\t\tonSaveComplete,\n\t\trecordId,\n\t\trelationEntry,\n\t\trelatedTable,\n\t\tjunctionTable,\n\t\tparentTable,\n\t\tqueryClient,\n\t\ttableName,\n\t\tscopeKey,\n\t\tisDraft,\n\t]);\n\n\tconst handleCancel = useCallback(() => {\n\t\tonFinishedEditing();\n\t}, [onFinishedEditing]);\n\n\tconst handleRemoveRelation = useCallback(\n\t\t(index: number) => {\n\t\t\tif (!canPersist || isSaving) return;\n\t\t\tsetEditingValue((prev) => prev.filter((_, i) => i !== index));\n\t\t},\n\t\t[canPersist, isSaving],\n\t);\n\n\tconst togglePick = useCallback(\n\t\t(record: any) => {\n\t\t\tif (!canPersist || isSaving) return;\n\t\t\tsetEditingValue((prev) => {\n\t\t\t\tconst id = record?.id;\n\t\t\t\tif (id != null) {\n\t\t\t\t\tconst exists = prev.some((r) => r?.id === id);\n\t\t\t\t\tif (exists) return prev.filter((r) => r?.id !== id);\n\t\t\t\t} else {\n\t\t\t\t\tconst key = JSON.stringify(record);\n\t\t\t\t\tconst exists = prev.some((r) => JSON.stringify(r) === key);\n\t\t\t\t\tif (exists) return prev.filter((r) => JSON.stringify(r) !== key);\n\t\t\t\t}\n\t\t\t\tif (isMulti) return [...prev, record];\n\t\t\t\treturn [record];\n\t\t\t});\n\t\t},\n\t\t[canPersist, isMulti, isSaving],\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\tif (canPersist && !isSaving) handleSave();\n\t\t\t}\n\t\t},\n\t\t[canPersist, handleSave, isSaving],\n\t);\n\n\treturn (\n\t\t<div ref={editorRef}>\n\t\t<EditorFocusTrap\n onEscape={handleCancel}\n onKeyDown={handleEditorKeyDown}\n className={`bg-popover flex ${OVERLAY.md} flex-col gap-4 rounded-lg border p-4 shadow-lg`}\n >\n\t\t\t{/* Header */}\n\t\t\t<div className='flex items-center gap-2'>\n\t\t\t\t<Link className='text-muted-foreground h-4 w-4' />\n\t\t\t\t<h3 className='text-sm font-medium'>{canPersist ? 'Edit Relations' : 'Related Records'}</h3>\n\t\t\t\t{isMulti && editingValue.length > 0 && (\n\t\t\t\t\t<Badge variant='secondary' size='sm' className='ml-auto tabular-nums'>\n\t\t\t\t\t\t{editingValue.length}\n\t\t\t\t\t</Badge>\n\t\t\t\t)}\n\t\t\t</div>\n\n\t\t\t{/* Current Relations */}\n\t\t\t<div className='space-y-2'>\n\t\t\t\t<div className='flex items-center gap-2'>\n\t\t\t\t\t<Label className='text-muted-foreground text-xs'>Current Relations</Label>\n\t\t\t\t\t{editingValue.length > 0 && (\n\t\t\t\t\t\t<Badge variant='outline' size='sm' className='tabular-nums'>\n\t\t\t\t\t\t\t{editingValue.length}\n\t\t\t\t\t\t</Badge>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t\t<div ref={currentScrollRef} className='rounded-md border' style={{ maxHeight: scrollBudgets.current, overflowY: 'auto' }}>\n\t\t\t\t\t<div className='space-y-2 p-2'>\n\t\t\t\t\t\t{editingValue.length === 0 ? (\n\t\t\t\t\t\t\t<div className='text-muted-foreground py-4 text-center text-sm'>No relations linked</div>\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\teditingValue.map((relation, index) => {\n\t\t\t\t\t\t\t\tconst displayText = getRelationDisplayText(relation);\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t<div key={index} className='bg-muted flex items-center gap-2 rounded-md p-2'>\n\t\t\t\t\t\t\t\t\t\t<RelationRecordTooltip record={relation} />\n\t\t\t\t\t\t\t\t\t\t<span className='min-w-0 flex-1 truncate text-sm'>{displayText}</span>\n\t\t\t\t\t\t\t\t\t\t<Badge variant='outline' className='text-2xs shrink-0'>\n\t\t\t\t\t\t\t\t\t\t\t{String(relation.id || index + 1).slice(0, 8)}\n\t\t\t\t\t\t\t\t\t\t</Badge>\n\t\t\t\t\t\t\t\t\t\t<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\tonClick={() => handleRemoveRelation(index)}\n\t\t\t\t\t\t\t\t\t\t\tdisabled={!canPersist}\n\t\t\t\t\t\t\t\t\t\t\tclassName='text-muted-foreground hover:text-destructive h-6 w-6 shrink-0 p-0'\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t<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</div>\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t)}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t\t\t<div className='flex flex-col space-y-2'>\n\t\t\t\t\t<Label htmlFor='search' className='flex items-center gap-1 text-muted-foreground text-xs'>\n\t\t\t\t\t\t<span>Add from</span>\n\t\t\t\t\t\t<Badge variant='outline' size='sm' className='px-1'>{relationEntry?.displayName || relatedTableName || 'related'}</Badge>\n\t\t\t\t\t\t{optionsTotalCount > 0 && (\n\t\t\t\t\t\t\t<Badge variant='secondary' size='sm' className='ml-auto tabular-nums'>\n\t\t\t\t\t\t\t\t{options.length} / {optionsTotalCount}\n\t\t\t\t\t\t\t</Badge>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</Label>\n\n\t\t\t\t\t<InputGroup>\n\t\t\t\t\t\t<InputGroupAddon>\n\t\t\t\t\t\t\t<Search />\n\t\t\t\t\t\t</InputGroupAddon>\n\t\t\t\t\t\t<InputGroupInput\n\t\t\t\t\t\t\tid='search'\n\t\t\t\t\t\t\tvalue={searchQuery}\n\t\t\t\t\t\t\tonChange={(e) => setSearchQuery(e.target.value)}\n\t\t\t\t\t\t\tplaceholder='Type to search...'\n\t\t\t\t\t\t\tsize='sm'\n\t\t\t\t\t\t/>\n\t\t\t\t\t</InputGroup>\n\n\t\t\t\t\t<div ref={scrollContainerRef} className='rounded-md border' style={{ maxHeight: scrollBudgets.addFrom, overflowY: 'auto' }}>\n\t\t\t\t\t\t<div data-testid='relation-options' className='space-y-1 p-2'>\n\t\t\t\t\t\t\t{(isLoading || (isManyToMany && isJunctionLoading)) && (\n\t\t\t\t\t\t\t\t<div className='text-muted-foreground py-6 text-center text-sm'>Loading...</div>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{!isLoading && options.length === 0 && (\n\t\t\t\t\t\t\t\t<div className='text-muted-foreground py-6 text-center text-sm'>No records found</div>\n\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t{options.map((row: any) => {\n\t\t\t\t\t\t\t\tconst id = row?.id ?? JSON.stringify(row);\n\t\t\t\t\t\t\t\tconst label = getRelationDisplayTextFromCandidates(row, displayCandidates);\n\t\t\t\t\t\t\t\tconst active = row?.id != null ? selectedIdSet.has(row.id) : editingValue.some((r) => JSON.stringify(r) === id);\n\t\t\t\t\t\t\tconst disabled = !canPersist || isSaving;\n\t\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\t\tkey={id}\n\t\t\t\t\t\t\t\t\trole='button'\n\t\t\t\t\t\t\t\t\ttabIndex={disabled ? -1 : 0}\n\t\t\t\t\t\t\t\t\taria-disabled={disabled}\n\t\t\t\t\t\t\t\t\tonClick={() => {\n\t\t\t\t\t\t\t\t\t\tif (disabled) return;\n\t\t\t\t\t\t\t\t\t\ttogglePick(row);\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\tonKeyDown={(e) => {\n\t\t\t\t\t\t\t\t\t\tif (disabled) return;\n\t\t\t\t\t\t\t\t\t\tif (e.key !== 'Enter' && e.key !== ' ') return;\n\t\t\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\t\t\ttogglePick(row);\n\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t\tclassName={cn(\n\t\t\t\t\t\t\t\t\t\t'w-full rounded-md px-2 py-1.5 text-left',\n\t\t\t\t\t\t\t\t\t\t!disabled && 'hover:bg-accent/50 cursor-pointer',\n\t\t\t\t\t\t\t\t\t\tdisabled && 'cursor-not-allowed opacity-64',\n\t\t\t\t\t\t\t\t\t\t\tactive && 'bg-accent/60',\n\t\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t<div className='flex items-center gap-2'>\n\t\t\t\t\t\t\t\t\t\t\t<RelationRecordTooltip record={row} />\n\t\t\t\t\t\t\t\t\t\t\t<span className='min-w-0 flex-1 truncate text-sm'>{label}</span>\n\t\t\t\t\t\t\t\t\t\t\t{active && <Check className='text-primary h-3.5 w-3.5 shrink-0' />}\n\t\t\t\t\t\t\t\t\t\t\t<Badge variant='outline' className={cn('text-2xs shrink-0', active && 'border-primary/40 text-link')}>\n\t\t\t\t\t\t\t\t\t\t\t\t{String(row?.id ?? '\\u2014').slice(0, 8)}\n\t\t\t\t\t\t\t\t\t\t\t</Badge>\n\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t</div>\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{hasNextPage && (\n\t\t\t\t\t\t\t\t<div ref={sentinelRef} className='flex justify-center py-2'>\n\t\t\t\t\t\t\t\t\t{isFetchingNextPage ? (\n\t\t\t\t\t\t\t\t\t\t<Loader2 className='text-muted-foreground h-4 w-4 animate-spin' />\n\t\t\t\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t\t\t\t<span className='text-muted-foreground text-xs'>Scroll for more</span>\n\t\t\t\t\t\t\t\t\t)}\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</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n\t\t\t<div className='flex justify-end gap-2'>\n\t\t\t\t<Button variant='outline' size='sm' onClick={handleCancel} disabled={isSaving}>\n\t\t\t\t\t<X className='mr-1 h-3 w-3' />\n\t\t\t\t\t{canPersist ? 'Cancel' : 'Close'}\n\t\t\t\t</Button>\n\t\t\t\t{canPersist && (\n\t\t\t\t\t<Button size='sm' onClick={handleSave} disabled={isSaving || isLoading || (isManyToMany && isJunctionLoading)}>\n\t\t\t\t\t\t<Check className='mr-1 h-3 w-3' />\n\t\t\t\t\t\tSave\n\t\t\t\t\t</Button>\n\t\t\t\t)}\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t\t</div>\n\t);\n};\n\nfunction getRelationDisplayTextFromCandidates(row: any, candidates: string[]): string {\n\tif (!row || typeof row !== 'object') return String(row ?? '');\n\tfor (const c of candidates) {\n\t\tif (row[c] != null && String(row[c]).trim()) return String(row[c]);\n\t}\n\tif ('id' in row) return `Record ${row.id}`;\n\treturn 'Unknown Record';\n}\n","/**\n * Cursor-based paginated table hook for \"load more\" patterns.\n *\n * Uses TanStack Query v5 `useInfiniteQuery` with PostGraphile Relay Connection\n * cursor pagination (first/after + pageInfo).\n *\n * Designed for sequential \"load more\" use cases (e.g., relation picker overlays).\n * For non-sequential virtual grid scrolling, see `useSheetsInfiniteTable`.\n */\nimport { useMemo } from 'react';\nimport { useInfiniteQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { useSheetsMeta } from './use-sheets-meta';\nimport { useSheetsContext } from '../context/sheets-context';\n\nimport {\n\tcleanTable,\n\ttype CleanTable,\n\ttype Filter,\n\ttype MetaTable,\n\ttype PageInfo,\n\ttype QueryOptions,\n} from '@constructive-io/data';\nimport { createError } from '@constructive-io/data';\nimport type { FieldSelection } from '@constructive-io/data';\nimport { toOrderByEnumValue } from '@constructive-io/data';\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { sheetsQueryKeys } from './query-keys';\nimport { resolveRelationFieldMap } from './relation-field-resolution';\nimport { validateOrderByVariables } from './orderby-enum-resolution';\nimport { transformToPostGraphileVariables } from './use-sheets-table';\n\ntype RowRecord = Record<string, unknown>;\n\nexport interface UseSheetsTableCursorOptions {\n\tenabled?: boolean;\n\tselect?: FieldSelection;\n\tpageSize?: number;\n\twhere?: Filter;\n\torderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>;\n}\n\nexport interface UseSheetsTableCursorResult<TData extends RowRecord = RowRecord> {\n\tdata: TData[];\n\ttotalCount: number;\n\tisLoading: boolean;\n\tisFetchingNextPage: boolean;\n\thasNextPage: boolean;\n\tfetchNextPage: () => void;\n\terror: Error | null;\n}\n\ninterface CursorPage<TData = RowRecord> {\n\trows: TData[];\n\ttotalCount: number;\n\tpageInfo: PageInfo;\n}\n\nexport function useSheetsTableCursor<TData extends RowRecord = RowRecord>(\n\ttableName: string,\n\toptions: UseSheetsTableCursorOptions = {},\n): UseSheetsTableCursorResult<TData> {\n\tconst queryClient = useQueryClient();\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst { data: meta } = useSheetsMeta();\n\tconst adapter = useSheetsAdapter();\n\n\tconst tables = useMemo<CleanTable[]>(() => {\n\t\tif (!meta?._meta?.tables) return [];\n\t\treturn meta._meta.tables\n\t\t\t.filter((candidate): candidate is MetaTable => candidate != null)\n\t\t\t.map((metaTable) => cleanTable(metaTable));\n\t}, [meta]);\n\n\tconst table = useMemo<CleanTable | null>(\n\t\t() => tables.find((candidate) => candidate.name === tableName) ?? null,\n\t\t[tables, tableName],\n\t);\n\n\tconst { enabled = true, select: fieldSelection, pageSize = 20, where, orderBy } = options;\n\n\t// Stable options key for query cache (excludes enabled/pageSize which don't affect data identity)\n\tconst stableOptions = useMemo(\n\t\t() => ({ fieldSelection, where, orderBy }),\n\t\t[fieldSelection, where, orderBy],\n\t);\n\n\tconst queryOptions: QueryOptions = useMemo(\n\t\t() => ({\n\t\t\tfieldSelection,\n\t\t\twhere,\n\t\t\torderBy,\n\t\t\tlimit: pageSize,\n\t\t\tincludePageInfo: true,\n\t\t}),\n\t\t[fieldSelection, where, orderBy, pageSize],\n\t);\n\n\tconst {\n\t\tdata,\n\t\tisLoading,\n\t\tisFetchingNextPage,\n\t\thasNextPage,\n\t\tfetchNextPage,\n\t\terror,\n\t} = useInfiniteQuery<CursorPage<TData>, Error>({\n\t\tqueryKey: sheetsQueryKeys.cursorTable(scopeKey, tableName, stableOptions),\n\t\tqueryFn: async ({ pageParam }) => {\n\t\t\tif (!table) {\n\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t}\n\n\t\t\tconst cursor = pageParam as string | undefined;\n\n\t\t\tconst variableOptions: QueryOptions = {\n\t\t\t\tlimit: pageSize,\n\t\t\t\twhere,\n\t\t\t\torderBy,\n\t\t\t\t...(cursor ? { after: cursor } : {}),\n\t\t\t};\n\t\t\t// Cache-bound resolution stays in the hook. The orderBy validation mutates\n\t\t\t// `variables.orderBy` (PostGraphile enum strings) in place; we fold that\n\t\t\t// result back into the `{ field, direction }[]` orderBy we hand the adapter,\n\t\t\t// so the adapter rebuilds an identical (validated) variables payload.\n\t\t\tconst variables = transformToPostGraphileVariables(table, variableOptions);\n\n\t\t\tconst [relationFieldMap] = await Promise.all([\n\t\t\t\tresolveRelationFieldMap({\n\t\t\t\t\ttable,\n\t\t\t\t\tfieldSelection,\n\t\t\t\t\tscopeKey,\n\t\t\t\t\tqueryClient,\n\t\t\t\t\texecute,\n\t\t\t\t}),\n\t\t\t\tvalidateOrderByVariables(variables, table, scopeKey, queryClient, execute),\n\t\t\t]);\n\n\t\t\tconst validatedOrderByEnum = new Set((variables.orderBy as string[] | undefined) ?? []);\n\t\t\tconst availableOrderByFields = new Set(table.fields.map((field) => field.name));\n\t\t\tconst validatedOrderBy = orderBy?.filter(\n\t\t\t\t({ field, direction }) =>\n\t\t\t\t\tavailableOrderByFields.has(field) && validatedOrderByEnum.has(toOrderByEnumValue(field, direction)),\n\t\t\t);\n\n\t\t\tconst res = await adapter.listRows<TData>(\n\t\t\t\t{ table, allTables: tables, tableName },\n\t\t\t\t{\n\t\t\t\t\t...queryOptions,\n\t\t\t\t\torderBy: validatedOrderBy,\n\t\t\t\t\t// resolveRelationFieldMap yields `string | null` (null = omit field). The\n\t\t\t\t\t// contract narrows to `string`, but the null values are passed through to\n\t\t\t\t\t// buildSelect unchanged at runtime — behavior is identical to before.\n\t\t\t\t\trelationFieldMap: relationFieldMap as Record<string, string>,\n\t\t\t\t\t...(cursor ? { after: cursor } : {}),\n\t\t\t\t},\n\t\t\t\texecute,\n\t\t\t);\n\n\t\t\t// The adapter's AdapterPageInfo marks booleans optional; the underlying\n\t\t\t// PostGraphile connection always populates them, so this narrows to PageInfo\n\t\t\t// exactly as the inline connection cast did. The fallback default mirrors the\n\t\t\t// prior direct-array branch byte-for-byte.\n\t\t\tconst pageInfo: PageInfo = (res.pageInfo as PageInfo | undefined) ?? {\n\t\t\t\thasNextPage: false,\n\t\t\t\thasPreviousPage: false,\n\t\t\t};\n\n\t\t\treturn {\n\t\t\t\trows: res.rows,\n\t\t\t\ttotalCount: res.totalCount,\n\t\t\t\tpageInfo,\n\t\t\t};\n\t\t},\n\t\tinitialPageParam: undefined as string | undefined,\n\t\tgetNextPageParam: (lastPage) =>\n\t\t\tlastPage.pageInfo.hasNextPage && lastPage.pageInfo.endCursor\n\t\t\t\t? lastPage.pageInfo.endCursor\n\t\t\t\t: undefined,\n\t\tenabled: enabled && !!table,\n\t\tstaleTime: 5 * 60 * 1000,\n\t});\n\n\tconst flatData = useMemo<TData[]>(\n\t\t() => data?.pages.flatMap((page) => page.rows) ?? [],\n\t\t[data],\n\t);\n\n\tconst totalCount = useMemo(\n\t\t() => data?.pages[data.pages.length - 1]?.totalCount ?? 0,\n\t\t[data],\n\t);\n\n\treturn {\n\t\tdata: flatData,\n\t\ttotalCount,\n\t\tisLoading,\n\t\tisFetchingNextPage,\n\t\thasNextPage: hasNextPage ?? false,\n\t\tfetchNextPage,\n\t\terror,\n\t};\n}\n","import { createContext, useContext } from 'react';\nimport { createStore, useStore as useZustandStore, type StoreApi } from 'zustand';\n\nimport { createDraftRowsSlice, type DraftRowsSlice } from './draft-rows-slice';\nimport { createRelationInfoSlice, type RelationInfoSlice } from './relation-info-slice';\n\nexport interface SheetsAuthState {\n isAuthenticated: boolean;\n accessToken: string | null;\n expiresAt: string | null;\n identityKey: string | null;\n setAuthenticated: (token: string, expiresAt: string, identityKey?: string | null) => void;\n setUnauthenticated: () => void;\n}\n\nexport type SheetsStoreState = DraftRowsSlice & RelationInfoSlice & SheetsAuthState;\n\nexport function createSheetsStore(): StoreApi<SheetsStoreState> {\n return createStore<SheetsStoreState>((set, get) => ({\n // Draft rows\n ...createDraftRowsSlice(set),\n\n // Relation info cache\n ...createRelationInfoSlice(set, get),\n\n // Auth state (standalone mode)\n isAuthenticated: false,\n accessToken: null,\n expiresAt: null,\n identityKey: null,\n setAuthenticated: (token: string, expiresAt: string, identityKey = null) =>\n set({ isAuthenticated: true, accessToken: token, expiresAt, identityKey }),\n setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null, identityKey: null }),\n }));\n}\n\nexport const SheetsStoreContext = createContext<StoreApi<SheetsStoreState> | null>(null);\n\nexport function useSheetsStore<T>(selector: (state: SheetsStoreState) => T): T {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStore must be used within a <SheetsProvider>');\n }\n return useZustandStore(store, selector);\n}\n\nexport function useSheetsStoreApi(): StoreApi<SheetsStoreState> {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStoreApi must be used within a <SheetsProvider>');\n }\n return store;\n}\n","import { useRef, useState } from 'react';\nimport { RiCodeLine } from '@remixicon/react';\n\nimport { cn } from '../../utils/cn';\nimport { Popover, PopoverContent, PopoverTrigger } from '@constructive-io/ui/popover';\n\ninterface RelationRecordTooltipProps {\n\trecord: unknown;\n}\n\n/**\n * Renders a subtle code icon that shows record data on hover.\n * Matches the visual style used in related-records.tsx.\n */\nexport function RelationRecordTooltip({ record }: RelationRecordTooltipProps) {\n\tconst [open, setOpen] = useState(false);\n\tconst closeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n\tif (!record || typeof record !== 'object') {\n\t\treturn null;\n\t}\n\n\t// Format record fields nicely\n\tconst entries = Object.entries(record as Record<string, unknown>).filter(\n\t\t([, value]) => value !== null && value !== undefined\n\t);\n\n\tconst MAX_VISIBLE_FIELDS = 12;\n\tconst visibleEntries = entries.slice(0, MAX_VISIBLE_FIELDS);\n\tconst hiddenCount = entries.length - visibleEntries.length;\n\n\t// Cancel any pending close timeout and open\n\tconst handleMouseEnter = () => {\n\t\tif (closeTimeoutRef.current) {\n\t\t\tclearTimeout(closeTimeoutRef.current);\n\t\t\tcloseTimeoutRef.current = null;\n\t\t}\n\t\tsetOpen(true);\n\t};\n\n\t// Delay close to allow mouse to travel to popover\n\tconst handleMouseLeave = () => {\n\t\tcloseTimeoutRef.current = setTimeout(() => {\n\t\t\tsetOpen(false);\n\t\t}, 100);\n\t};\n\n\treturn (\n\t\t<Popover open={open} onOpenChange={setOpen}>\n\t\t\t<PopoverTrigger asChild>\n\t\t\t\t<button\n\t\t\t\t\ttype=\"button\"\n\t\t\t\t\tclassName=\"text-muted-foreground/50 hover:text-muted-foreground relative flex shrink-0 cursor-help items-center justify-center rounded p-1 transition-colors before:absolute before:-inset-2 before:content-['']\"\n\t\t\t\t\tonMouseEnter={handleMouseEnter}\n\t\t\t\t\tonMouseLeave={handleMouseLeave}\n\t\t\t\t\tonClick={(e) => e.stopPropagation()}\n\t\t\t\t>\n\t\t\t\t\t<RiCodeLine className=\"h-3.5 w-3.5\" />\n\t\t\t\t</button>\n\t\t\t</PopoverTrigger>\n\t\t\t<PopoverContent\n\t\t\t\tside=\"right\"\n\t\t\t\talign=\"start\"\n\t\t\t\tsideOffset={4}\n\t\t\t\tclassName=\"z-[10000] w-[300px] max-h-[min(50vh,320px)] overflow-hidden p-0 shadow-lg\"\n\t\t\t\tonMouseEnter={handleMouseEnter}\n\t\t\t\tonMouseLeave={handleMouseLeave}\n\t\t\t\tonOpenAutoFocus={(e) => e.preventDefault()}\n\t\t\t\tonCloseAutoFocus={(e) => e.preventDefault()}\n\t\t\t>\n\t\t\t\t{/* Header */}\n\t\t\t\t<div className=\"border-border/40 flex items-center gap-2 border-b px-3 py-2\">\n\t\t\t\t\t<RiCodeLine className=\"text-muted-foreground h-4 w-4\" />\n\t\t\t\t\t<span className=\"text-sm font-medium\">Record Data</span>\n\t\t\t\t\t<span className=\"text-muted-foreground bg-muted/40 ml-auto rounded px-1.5 py-0.5 text-xs\">\n\t\t\t\t\t\t{entries.length} fields\n\t\t\t\t\t</span>\n\t\t\t\t</div>\n\n\t\t\t\t{/* Content — NATIVE scroll (max-height + overflow-y:auto) rather than the Base UI\n\t\t\t\t ScrollArea: that primitive's viewport is `height:100%`, which needs a DEFINITE\n\t\t\t\t parent height, but the popover is auto-height (only max-h), so the viewport\n\t\t\t\t collapsed to content height and the popover's overflow-hidden CLIPPED the fields\n\t\t\t\t instead of scrolling. A block with max-height + overflow-y:auto scrolls reliably\n\t\t\t\t regardless of ancestor height (same pattern as the relation editor's own lists). */}\n\t\t\t\t<div className=\"max-h-[240px] overflow-y-auto overscroll-contain\">\n\t\t\t\t\t<div className=\"space-y-0\">\n\t\t\t\t\t\t{visibleEntries.map(([key, value]) => (\n\t\t\t\t\t\t\t<div key={key} className=\"border-border/20 border-b px-3 py-2 last:border-b-0\">\n\t\t\t\t\t\t\t\t<div className=\"text-muted-foreground text-xs\">{key}</div>\n\t\t\t\t\t\t\t\t<div className={cn(\n\t\t\t\t\t\t\t\t\t\"text-sm break-all line-clamp-3\",\n\t\t\t\t\t\t\t\t\tvalue === null || value === undefined ? \"text-muted-foreground/50 italic\" : \"text-foreground\"\n\t\t\t\t\t\t\t\t)}>\n\t\t\t\t\t\t\t\t\t{formatValue(value)}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t))}\n\t\t\t\t\t\t{hiddenCount > 0 && (\n\t\t\t\t\t\t\t<div className=\"text-muted-foreground px-3 py-2 text-xs italic\">\n\t\t\t\t\t\t\t\t... and {hiddenCount} more field{hiddenCount > 1 ? 's' : ''}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</PopoverContent>\n\t\t</Popover>\n\t);\n}\n\nconst MAX_VALUE_LENGTH = 120;\n\nfunction formatValue(value: unknown): string {\n\tif (value === null || value === undefined) return 'null';\n\tconst str = typeof value === 'object' ? JSON.stringify(value) : String(value);\n\treturn str.length > MAX_VALUE_LENGTH ? str.slice(0, MAX_VALUE_LENGTH) + '\\u2026' : str;\n}\n","'use client';\n\n// Native relation editor — a thin EditorProps adapter that RE-HOSTS the (now value-\n// native) SELF-COMMITTING `RelationEditor` verbatim. The UI (current-relations list,\n// search + \"Add from\" picker, OVERLAY_MD width, own EditorFocusTrap, Ctrl+Enter save)\n// is reused as-is; the contract maps directly onto EditorProps:\n// • value -> resolved `currentValue`, replicating the original factory's\n// bare-string -> { id } wrap (draft FK values are left untouched).\n// • tableName -> EditorProps.tableName.\n// • recordId -> EditorProps.rowId (may be a \"draft:\" id; the editor handles it).\n// • fieldName -> EditorProps.colKey.\n// • onSaveComplete(RelationSaveData) -> onCommitPatch(patch) — a MULTI-field patch:\n// belongsTo sets [foreignKeyField] = foreignKeyValue, and [relationField || colKey]\n// = relationData (the display field).\n// • onFinishedEditing() -> onCancel() (a CLOSE; the mutation self-commits via\n// onSaveComplete, so the value path is never used for relation).\n// The reused RelationEditor ignores its `value` prop (it reads `currentValue`), so it\n// is not passed. No Suspense: the editor renders eagerly.\n\nimport { RelationEditor, type RelationSaveData } from '../../grid/editors/relation-editor';\nimport type { EditorProps } from './editor-props';\n\nconst DRAFT_PREFIX = 'draft:';\n\n/**\n * Resolve the raw relation value into the shape the reused editor matches against,\n * replicating the original factory: a bare (non-draft) FK string is wrapped into\n * `{ id }`; everything else (object / array / null) is passed through and the editor's\n * `coerceToArray` normalises it.\n */\nfunction resolveCurrentValue(value: unknown): unknown {\n\tif (typeof value === 'string' && value && !value.startsWith(DRAFT_PREFIX)) {\n\t\treturn { id: value };\n\t}\n\treturn value;\n}\n\nexport function RelationEditorDom({\n\tvalue,\n\tcolKey,\n\trowId,\n\ttableName,\n\trelationInfo,\n\tonCommitPatch,\n\tonCancel,\n}: EditorProps) {\n\t// Self-commit: the editor mutates server-side (or, for draft belongsTo, resolves\n\t// the FK locally), then hands back the saved data — route it as a MULTI-field\n\t// optimistic patch.\n\tconst handleSaveComplete = onCommitPatch\n\t\t? (saveData: RelationSaveData) => {\n\t\t\t\tconst patch: Record<string, unknown> = {};\n\t\t\t\tif (relationInfo?.kind === 'belongsTo' && relationInfo.foreignKeyField) {\n\t\t\t\t\tpatch[relationInfo.foreignKeyField] = saveData.foreignKeyValue;\n\t\t\t\t}\n\t\t\t\tconst displayField = relationInfo?.relationField || colKey;\n\t\t\t\tpatch[displayField] = saveData.relationData;\n\t\t\t\tonCommitPatch(patch);\n\t\t\t}\n\t\t: undefined;\n\n\treturn (\n\t\t<div data-slot='relation-editor'>\n\t\t\t<RelationEditor\n\t\t\t\tonFinishedEditing={() => onCancel()}\n\t\t\t\ttableName={tableName ?? ''}\n\t\t\t\trecordId={rowId}\n\t\t\t\tfieldName={colKey}\n\t\t\t\tcurrentValue={resolveCurrentValue(value)}\n\t\t\t\tonSaveComplete={handleSaveComplete}\n\t\t\t/>\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'\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","import React, { useCallback, useMemo } from 'react';\nimport { Info, Search, X } from 'lucide-react';\n\nimport { cn } from '../../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\nimport { Label } from '@constructive-io/ui/label';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\n\ninterface TsvectorEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n}\ntype Weight = 'A' | 'B' | 'C' | 'D';\ntype ParsedToken = { lexeme: string; weights: Weight[] };\n\nfunction parseTsvector(tsvectorString: string): ParsedToken[] {\n\tif (!tsvectorString || typeof tsvectorString !== 'string') return [];\n\ttry {\n\t\tconst out: ParsedToken[] = [];\n\t\tconst regex = /'([^']+)':([0-9A-D,]+)/g;\n\t\tlet match: RegExpExecArray | null;\n\t\twhile ((match = regex.exec(tsvectorString)) !== 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 Weight | undefined)\n\t\t\t\t\t\t.filter((w): w is Weight => !!w),\n\t\t\t\t),\n\t\t\t).sort();\n\t\t\tout.push({ lexeme, weights });\n\t\t}\n\t\tif (out.length) return out;\n\t} catch {\n\t\t// ignore\n\t}\n\treturn tsvectorString\n\t\t.split(/\\s+/)\n\t\t.filter(Boolean)\n\t\t.map((w): ParsedToken => ({ lexeme: w, weights: [] }));\n}\n\nexport const TsvectorEditor: React.FC<TsvectorEditorProps> = ({ value, onFinishedEditing }) => {\n\tconst rawValue = typeof value === 'string' ? value : String(value ?? '');\n\tconst parsedTokens = useMemo(() => parseTsvector(rawValue), [rawValue]);\n\n\tconst handleClose = useCallback(() => onFinishedEditing(), [onFinishedEditing]);\n\n\treturn (\n\t\t<EditorFocusTrap onEscape={handleClose} className={`bg-popover flex ${OVERLAY.md} flex-col gap-4 rounded-lg border p-4 shadow-lg`}>\n\t\t\t{/* Header */}\n\t\t\t<div className='flex items-center gap-2'>\n\t\t\t\t<Search className='text-muted-foreground h-4 w-4' />\n\t\t\t\t<h3 className='text-sm font-medium'>View Text Search Vector</h3>\n\t\t\t</div>\n\n\t\t\t{/* Parsed Tokens Preview */}\n\t\t\t{parsedTokens.length > 0 && (\n\t\t\t\t<div className='space-y-2'>\n\t\t\t\t\t<Label className='text-muted-foreground text-xs'>Parsed Tokens ({parsedTokens.length})</Label>\n\t\t\t\t\t<div className='bg-muted flex max-h-[120px] flex-wrap gap-1 overflow-y-auto rounded p-2 text-sm'>\n\t\t\t\t\t\t{parsedTokens.map((t, index) => {\n\t\t\t\t\t\t\tconst weight = t.weights[0];\n\t\t\t\t\t\t\tconst color =\n\t\t\t\t\t\t\t\tweight === 'A'\n\t\t\t\t\t\t\t\t\t? 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-200'\n\t\t\t\t\t\t\t\t\t: weight === 'B'\n\t\t\t\t\t\t\t\t\t\t? 'bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-200'\n\t\t\t\t\t\t\t\t\t\t: weight === 'C'\n\t\t\t\t\t\t\t\t\t\t\t? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/40 dark:text-yellow-200'\n\t\t\t\t\t\t\t\t\t\t\t: weight === 'D'\n\t\t\t\t\t\t\t\t\t\t\t\t? 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-200'\n\t\t\t\t\t\t\t\t\t\t\t\t: 'bg-primary/10 text-link';\n\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t<span key={index} className={cn('inline-flex items-center rounded px-2 py-1 text-xs', color)}>\n\t\t\t\t\t\t\t\t\t{t.lexeme}\n\t\t\t\t\t\t\t\t\t{t.weights.length > 0 && <span className='ml-1 font-mono opacity-80'>{t.weights.join(',')}</span>}\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t})}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t)}\n\n\t\t\t{/* Raw tsvector */}\n\t\t\t<div className='space-y-2'>\n\t\t\t\t<Label className='text-muted-foreground text-xs'>Raw TSVector</Label>\n\t\t\t\t<div className='bg-muted/30 max-h-40 overflow-auto rounded-md p-2'>\n\t\t\t\t\t<pre className='m-0 font-mono text-xs break-all whitespace-pre-wrap'>{rawValue}</pre>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{/* Help Text */}\n\t\t\t<div className='text-muted-foreground flex items-start gap-2 text-xs'>\n\t\t\t\t<Info className='mt-0.5 h-3 w-3 flex-shrink-0' />\n\t\t\t\t<div>\n\t\t\t\t\t<p>Values are generated server-side from your full-text configuration.</p>\n\t\t\t\t\t<p className='mt-1'>Weights: A (highest), B, C, D (lowest).</p>\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t{/* Action Buttons */}\n\t\t\t<div className='flex justify-end gap-2'>\n\t\t\t\t<Button variant='outline' size='sm' onClick={handleClose}>\n\t\t\t\t\t<X className='mr-1 h-3 w-3' />\n\t\t\t\t\tClose\n\t\t\t\t</Button>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","'use client';\n\n// Native tsvector editor — a thin EditorProps adapter that RE-HOSTS the (now value-\n// native) `TsvectorEditor` verbatim. The UI (parsed-token chips, raw view, OVERLAY.md\n// width, own EditorFocusTrap) is reused as-is. tsvector is READ-ONLY display: the\n// source only ever calls `onFinishedEditing()` with no arg (Close / Escape), so the\n// contract maps purely to `onCancel()` — there is no value-commit path.\n// `EditorProps.value` is the raw row value, read directly by the source.\n\nimport { TsvectorEditor } from '../../grid/editors/tsvector-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function TsvectorEditorDom({ value, onCancel }: EditorProps) {\n\treturn <TsvectorEditor value={value} onFinishedEditing={() => onCancel()} />;\n}\n","import React, { useCallback, useState } from 'react';\nimport { Check, ExternalLink, Link, X } from 'lucide-react';\n\nimport { cn } from '../../utils/cn';\nimport { Button } from '@constructive-io/ui/button';\nimport { Input } from '@constructive-io/ui/input';\nimport { Label } from '@constructive-io/ui/label';\n\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { OVERLAY } from './overlay-presets';\n\ninterface UrlEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\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 }) => {\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\tconst handleTestUrl = useCallback(() => {\n\t\tif (editingValue.trim() && isValidUrl(editingValue.trim())) {\n\t\t\tconst fullUrl = formatUrl(editingValue.trim());\n\t\t\twindow.open(fullUrl, '_blank', 'noopener,noreferrer');\n\t\t}\n\t}, [editingValue]);\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\n\treturn (\n\t\t<EditorFocusTrap onEscape={handleCancel} className={`bg-popover flex ${OVERLAY.md} flex-col gap-4 rounded-lg border p-4 shadow-lg`}>\n\t\t\t<div onKeyDown={handleEditorKeyDown}>\n\t\t\t{/* Header */}\n\t\t\t<div className='flex items-center gap-2'>\n\t\t\t\t<Link className='text-muted-foreground h-4 w-4' />\n\t\t\t\t<h3 className='text-sm font-medium'>Edit URL</h3>\n\t\t\t</div>\n\n\t\t\t{/* URL Input */}\n\t\t\t<div className='space-y-2'>\n\t\t\t\t<Label htmlFor='url' className='text-muted-foreground text-xs'>\n\t\t\t\t\tURL\n\t\t\t\t</Label>\n\t\t\t\t<Input\n\t\t\t\t\tid='url'\n\t\t\t\t\ttype='url'\n\t\t\t\t\tvalue={editingValue}\n\t\t\t\t\tonChange={handleInputChange}\n\t\t\t\t\tplaceholder='https://example.com'\n\t\t\t\t\tclassName={cn('text-sm', validationError && 'border-destructive focus-visible:ring-destructive')}\n\t\t\t\t\tautoFocus\n\t\t\t\t/>\n\t\t\t\t{validationError && <p className='text-destructive text-xs'>{validationError}</p>}\n\t\t\t</div>\n\n\t\t\t{/* Preview */}\n\t\t\t{editingValue.trim() && (\n\t\t\t\t<div className='space-y-2'>\n\t\t\t\t\t<Label className='text-muted-foreground text-xs'>Preview</Label>\n\t\t\t\t\t<div className='bg-muted flex items-center gap-2 rounded p-2 text-sm'>\n\t\t\t\t\t\t<Link className='text-muted-foreground h-3 w-3 flex-shrink-0' />\n\t\t\t\t\t\t{isValid ? (\n\t\t\t\t\t\t\t<div className='flex min-w-0 flex-1 items-center gap-2'>\n\t\t\t\t\t\t\t\t<span className='text-link truncate'>{displayText}</span>\n\t\t\t\t\t\t\t\t<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={handleTestUrl}\n\t\t\t\t\t\t\t\t\tclassName='text-muted-foreground hover:text-link h-6 w-6 p-0'\n\t\t\t\t\t\t\t\t\ttitle='Test URL'\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t<ExternalLink className='h-3 w-3' />\n\t\t\t\t\t\t\t\t</Button>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<span className='text-destructive truncate'>{editingValue}</span>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t)}\n\n\t\t\t{/* URL Format Help */}\n\t\t\t<div className='text-muted-foreground text-xs'>\n\t\t\t\t<p>Examples:</p>\n\t\t\t\t<ul className='mt-1 list-inside list-disc space-y-1'>\n\t\t\t\t\t<li>https://example.com</li>\n\t\t\t\t\t<li>example.com (https:// will be added automatically)</li>\n\t\t\t\t\t<li>subdomain.example.com/path</li>\n\t\t\t\t</ul>\n\t\t\t</div>\n\n\t\t\t{/* Action Buttons */}\n\t\t\t<div className='flex justify-end gap-2'>\n\t\t\t\t<Button variant='outline' size='sm' onClick={handleCancel}>\n\t\t\t\t\t<X className='mr-1 h-3 w-3' />\n\t\t\t\t\tCancel\n\t\t\t\t</Button>\n\t\t\t\t<Button size='sm' onClick={handleSave} disabled={!!validationError}>\n\t\t\t\t\t<Check className='mr-1 h-3 w-3' />\n\t\t\t\t\tSave\n\t\t\t\t</Button>\n\t\t\t</div>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\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 { UrlEditor } from '../../grid/editors/url-editor';\nimport type { EditorProps } from './editor-props';\n\nexport function UrlEditorDom({ value, 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\tonFinishedEditing={(next) => (next === undefined ? onCancel() : onCommit(next))}\n\t\t\t/>\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 { RelationEditorDom } from './relation-editor';\nimport { TextEditor } from './text-editor';\nimport { TsvectorEditorDom } from './tsvector-editor';\nimport { UrlEditorDom } from './url-editor';\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\t// Number types (the whole NUMBER_TYPES family, incl. rating)\n\tnumber: NumberEditorDom,\n\tinteger: NumberEditorDom,\n\tsmallint: 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\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","// 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, bit, toggle).\n//\n// The BooleanCell keeps the boolean in `data` for copying and leaves\n// `displayData` empty because the view owns its visual representation.\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 ? false : typeof value === 'boolean' ? value : Boolean(value);\n\treturn { kind: 'boolean', data: boolValue, displayData: '', readonly: false };\n}\n\nexport const booleanSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// SheetsCell factory for the datetime family — native analogue of v1's\n// DateTimeCellFactory (cell-content-factory.ts). Claims the DATE_TIME_TYPES\n// (date, datetime, time, timestamptz) and emits a neutral `text` cell carrying\n// the value's string form. v1 renders the raw value as formatted text: non-null\n// -> data/displayData = String(value); null/undefined -> both ''. This factory\n// preserves that display and copy behavior.\n\nimport type { CellType } from '../../cell-types/types';\nimport { DATE_TIME_TYPES } 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\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\treturn { kind: 'text', data: text, displayData: text, readonly: false, meta };\n}\n\nexport const dateTimeSheetsCellFactory: SheetsCellFactory = { canHandle, create };\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 { 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\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};\n}\n\nexport const geometrySheetsCellFactory: SheetsCellFactory = { canHandle, create };\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","// Native SheetsCell factory for the MEDIA family (image/file/video/audio/upload).\n// Attachment columns hold URL text and use the text factory instead.\n//\n// `data` is a single-element array holding the durable URL (`['']` when there is\n// none), so copyText === JSON.stringify([url]) as before; `displayData` is the string\n// form of that array. A signed preview URL never enters this payload: it expires, so\n// copy/export only ever carry the stored URL.\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 { getImageUrl } from '../../utils/file.utils';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nexport const imageSheetsCellFactory: SheetsCellFactory = {\n\tcanHandle(cellType: string): boolean {\n\t\treturn cellType !== 'attachment' && MEDIA_TYPES.has(cellType);\n\t},\n\n\tcreate(value: unknown, metadata: CellCreationMetadata): SheetsCell {\n\t\t// Keep the legacy copy/export representation and its durable URL.\n\t\tconst data = [getImageUrl(value) ?? ''];\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: { cellType: metadata.cellType as CellType }\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\tconst secs = interval.seconds;\n\t\tif (Number.isInteger(secs)) {\n\t\t\tparts.push(`${secs}s`);\n\t\t} else {\n\t\t\tparts.push(`${secs.toFixed(1)}s`);\n\t\t}\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// decimal, currency, percentage, AND `rating` — `rating` lives in NUMBER_TYPES so\n// the number family wins it before the text fallback; this is a deliberate v1\n// quirk preserved for parity).\n//\n// Null, undefined, and invalid values become an empty cell. Valid values keep\n// the numeric data and a string display value.\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) {\n\t\treturn { kind: 'number', data: undefined, displayData: '', readonly: false };\n\t}\n\n\tconst numValue = typeof value === 'number' ? value : parseFloat(value as string);\n\tif (isNaN(numValue)) {\n\t\treturn { kind: 'number', data: undefined, displayData: '', readonly: false };\n\t}\n\n\treturn { kind: 'number', data: numValue, displayData: String(numValue), readonly: false };\n}\n\nexport const numberSheetsCellFactory: SheetsCellFactory = { canHandle, create };\n","// Native SheetsCell factory for the `relation` family — the port of v1's glide\n// `RelationCellFactory` (grid/cell-content-factory.ts). Owns BOTH single relations\n// (belongsTo/hasOne — glide emitted a Text cell) and list relations\n// (hasMany/manyToMany — glide emitted a Bubble cell); both collapse to the single\n// neutral kind `relation`. All label-derivation + chip-overflow domain logic is\n// copied verbatim from v1 (no import from cell-content-factory.ts — that module\n// stays glide-only and is deleted at cutover).\n//\n// Single relations use their label for data and display. List relations keep\n// their final chips in data while the relation view owns their visual display.\n\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\n// ─── Domain constants (copied verbatim from v1 RelationCellFactory) ──────────\nconst DEFAULT_MAX_RELATION_CHIPS = 3;\nconst DEFAULT_RELATION_LABEL_MAX_LEN = 24;\n\nconst RELATION_ID_KEYS = new Set(['id', 'uuid', 'rowId', 'nodeId']);\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\n// Copied verbatim from v1 `RelationCellFactory.deriveRelationLabel`, lifted from a\n// private method to a pure function (metadata threaded as an explicit argument).\nfunction deriveRelationLabel(relationValue: any, metadata: CellCreationMetadata, maxLength: number): string {\n\tif (relationValue == null) return '';\n\n\t// Suppress draft placeholder IDs from being displayed as relation labels\n\tif (typeof relationValue === 'string' && relationValue.startsWith('draft:')) return '';\n\tif (\n\t\ttypeof relationValue === 'object' &&\n\t\t!Array.isArray(relationValue) &&\n\t\ttypeof (relationValue as Record<string, unknown>).id === 'string' &&\n\t\t((relationValue as Record<string, unknown>).id as string).startsWith('draft:')\n\t)\n\t\treturn '';\n\n\tconst ensureString = (val: unknown): string => {\n\t\tif (val == null) return '';\n\t\tconst str = String(val).trim();\n\t\tif (!str || str.toLowerCase() === 'null') return '';\n\t\treturn str;\n\t};\n\n\tif (typeof relationValue === 'string' || typeof relationValue === 'number') {\n\t\treturn truncateLabel(ensureString(relationValue), maxLength);\n\t}\n\n\tif (Array.isArray(relationValue)) {\n\t\tconst labels = relationValue\n\t\t\t.map((item) => deriveRelationLabel(item, metadata, maxLength))\n\t\t\t.filter((label) => label.length > 0);\n\t\treturn labels.join(', ');\n\t}\n\n\tif (typeof relationValue !== 'object') {\n\t\treturn truncateLabel(ensureString(relationValue), maxLength);\n\t}\n\n\tconst relInfo = metadata.relationInfo;\n\tconst candidatesFromMeta: string[] = relInfo?.displayCandidates ?? [];\n\tconst objectValue = relationValue as Record<string, unknown>;\n\tconst keys = Object.keys(objectValue);\n\n\t// Try name-like display candidates first (exclude id/uuid — those are last resort)\n\tconst meaningfulCandidates = candidatesFromMeta.filter((k) => !RELATION_ID_KEYS.has(k));\n\n\tconst heuristicKeys = Array.from(\n\t\tnew Set([\n\t\t\t...meaningfulCandidates,\n\t\t\t...keys.filter((key) => /(name|label|title|display|email)/i.test(key)),\n\t\t\t'displayName',\n\t\t\t'fullName',\n\t\t\t'name',\n\t\t\t'title',\n\t\t\t'label',\n\t\t\t'description',\n\t\t\t'username',\n\t\t\t'email',\n\t\t\t'code',\n\t\t]),\n\t);\n\n\tfor (const candidate of heuristicKeys) {\n\t\tif (!candidate) continue;\n\t\tconst candidateValue = ensureString(objectValue[candidate]);\n\t\tif (candidateValue) {\n\t\t\treturn truncateLabel(candidateValue, maxLength);\n\t\t}\n\t}\n\n\t// Last resort: id/uuid\n\tfor (const idKey of ['id', 'uuid']) {\n\t\tconst idVal = ensureString(objectValue[idKey]);\n\t\tif (idVal) {\n\t\t\treturn truncateLabel(idVal, maxLength);\n\t\t}\n\t}\n\n\tconst firstPrimitive = keys\n\t\t.map((key) => objectValue[key])\n\t\t.find((val) => val != null && ['string', 'number', 'boolean'].includes(typeof val));\n\tif (firstPrimitive !== undefined) {\n\t\treturn truncateLabel(ensureString(firstPrimitive), maxLength);\n\t}\n\n\treturn truncateLabel(compactJsonPreview(objectValue, 80), maxLength);\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 relInfo = metadata.relationInfo;\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\n\tconst isListRelation = relInfo?.kind === 'hasMany' || relInfo?.kind === 'manyToMany';\n\n\tif (isListRelation) {\n\t\tconst arr = Array.isArray(value) ? value : [];\n\t\tconst labelsAll = arr\n\t\t\t.map((entry) => deriveRelationLabel(entry, metadata, labelMax))\n\t\t\t.filter((label) => label.length > 0);\n\t\tconst labels = labelsAll.slice(0, chipLimit);\n\t\tconst remaining = labelsAll.length - labels.length;\n\t\tconst finalData = remaining > 0 ? [...labels, `+${remaining}`] : labels;\n\t\t// glide emitted a Bubble cell (no displayData) -> displayData projects to ''.\n\t\treturn {\n\t\t\tkind: 'relation',\n\t\t\tdata: finalData,\n\t\t\tdisplayData: '',\n\t\t\treadonly: false,\n\t\t};\n\t}\n\n\tconst label = deriveRelationLabel(value, metadata, labelMax);\n\t// glide emitted a Text cell -> data = displayData = label.\n\treturn {\n\t\tkind: 'relation',\n\t\tdata: label,\n\t\tdisplayData: label,\n\t\treadonly: false,\n\t};\n}\n\nexport const relationSheetsCellFactory: 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 { 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 { 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\tbadgesSheetsCellFactory,\n\tdateTimeSheetsCellFactory,\n\tintervalSheetsCellFactory,\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,oBAAoB,WAAuC;AACnE,SAAO,MAAM,KAAK,UAAU,iBAA8B,kBAAkB,CAAC,EAAE;AAAA,IAC9E,CAAC,OAAO,GAAG,iBAAiB;AAAA,EAC7B;AACD;AAEO,SAAS,gBAAgB,EAAE,UAAU,UAAU,WAAW,WAAW,MAAM,GAAyB;AAC1G,QAAM,mBAAe,qBAAuB,IAAI;AAChD,QAAM,4BAAwB,qBAAuB,IAAI;AAKzD,oCAAgB,MAAM;AACrB,0BAAsB,UAAU,SAAS;AAEzC,QAAI,CAAC,aAAa,QAAS;AAE3B,UAAM,kBAAkB,oBAAoB,aAAa,OAAO;AAChE,QAAI,gBAAgB,SAAS,GAAG;AAC/B,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,MAAM,aAAa,aAAa,UAAU,OAAO,MAAM,EAAE,SAAS,EAAE;AAC3F;AAEO,IAAM,uBAA0C,EAAE,WAAAD,YAAW,QAAAC,QAAO;;;ACA3E,IAAM,wBAA6C;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AACD;AAmBA,SAAS,YAAY,MAAkB,UAA8B;AACpE,SAAO,EAAE,GAAG,MAAM,MAAM,EAAE,GAAG,KAAK,MAAM,SAA+B,EAAE;AAC1E;AAEO,SAAS,iBACf,OACA,UACA,gBACa;AACb,QAAM,EAAE,SAAS,IAAI;AAErB,MAAI,UAAU,QAAQ,UAAU,QAAW;AAC1C,UAAM,eAAe,sBAAsB,KAAK,CAAC,MAAM,EAAE,UAAU,UAAU,IAAI,CAAC;AAClF,QAAI,cAAc;AACjB,aAAO,YAAY,aAAa,OAAO,MAAM,UAAU,cAAc,GAAG,QAAQ;AAAA,IACjF;AACA,WAAO,YAAY,EAAE,MAAM,QAAQ,MAAM,IAAI,aAAa,IAAI,UAAU,MAAM,GAAG,QAAQ;AAAA,EAC1F;AAEA,QAAM,UAAU,sBAAsB,KAAK,CAAC,MAAM,EAAE,UAAU,UAAU,KAAK,CAAC;AAC9E,MAAI,SAAS;AACZ,WAAO,YAAY,QAAQ,OAAO,OAAO,UAAU,cAAc,GAAG,QAAQ;AAAA,EAC7E;AAEA,SAAO;AAAA,IACN;AAAA,MACC,MAAM;AAAA,MACN,MAAM;AAAA,MACN,aAAa,OAAO,KAAK;AAAA,MACzB,UAAU;AAAA,IACX;AAAA,IACA;AAAA,EACD;AACD;","names":["import_react","import_button","import_jsx_runtime","MAC_UA_RE","parseAriaDate","dateValue","handleSave","handleCancel","active","import_react","import_lucide_react","import_button","import_jsx_runtime","React","import_react","import_jsx_runtime","add","handleSave","remove","handleCancel","input","import_jsx_runtime","import_react","import_jsx_runtime","DateEditor","import_react","import_react","import_lucide_react","import_button","import_react","import_jsx_runtime","React","import_jsx_runtime","MapPicker","import_jsx_runtime","import_react","import_react","import_lucide_react","import_react_query","import_data","import_data","import_react","import_react_query","import_react","import_data","import_data","import_data","totalCount","data","import_react","import_react_query","import_graphql","import_data","field","query","data","url","idScalar","query","import_react","import_button","import_react","import_jsx_runtime","import_jsx_runtime","import_jsx_runtime","import_react","import_button","import_jsx_runtime","MAC_UA_RE","handleSave","handleCancel","import_jsx_runtime","import_react","import_lucide_react","import_button","import_jsx_runtime","import_jsx_runtime","import_react","import_button","import_jsx_runtime","MAC_UA_RE","handleSave","handleCancel","import_jsx_runtime","import_react","import_button","import_jsx_runtime","import_react","import_lucide_react","import_react_query","import_react","import_react_query","import_data","import_react","useZustandStore","import_badge","import_button","import_input_group","import_label","import_toast","import_react","import_jsx_runtime","import_jsx_runtime","active","import_jsx_runtime","DRAFT_PREFIX","import_react","import_button","import_jsx_runtime","import_react","import_lucide_react","import_button","import_label","import_jsx_runtime","import_jsx_runtime","import_react","import_lucide_react","import_button","import_input","import_label","import_jsx_runtime","import_jsx_runtime","canHandle","create","canHandle","create","canHandle","create","canHandle","create","canHandle","create","label","canHandle","create","canHandle","create"]}
|
|
1
|
+
{"version":3,"sources":["../src/grid/editors/editor-focus-trap.tsx","../src/utils/cn.ts","../src/grid/editors/editor-frame.tsx","../src/grid/editors/overlay-presets.ts","../src/cell-types/cell-type-groups.ts","../src/utils/sheets-i18n.ts","../src/cell-types/date-time-format.ts","../src/grid/editors/date-value-parts.ts","../src/grid/editors/date-text.ts","../src/grid/editors/date-editor.tsx","../src/advanced.ts","../src/grid-dom/editors/array-editor.tsx","../src/cell-types/column-value.ts","../src/cell-types/field-label.ts","../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/cell-types/shape-kind.ts","../src/utils/map-picker.tsx","../src/utils/module-interop.ts","../src/utils/map-settings.ts","../src/context/sheets-context.ts","../src/utils/sheets-logger.ts","../src/grid/editors/map-load-boundary.tsx","../src/grid/editors/overlay-viewport-guard.tsx","../src/grid-dom/editors/geometry-editor.tsx","../src/grid-dom/editors/image-editor.tsx","../src/grid/editors/image-editor.tsx","../src/hooks/use-table-model.ts","../src/adapter/postgraphile-adapter.ts","../src/context/sheets-execute.ts","../src/context/sheets-upload-presigned.ts","../src/context/sheets-upload-discovery.ts","../src/row-identity.ts","../src/adapter/use-sheets-adapter.ts","../src/context/sheets-read-only.tsx","../src/hooks/query-keys.ts","../src/hooks/use-sheets-meta.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/utils/file.utils.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/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/feedback/feedback-context.tsx","../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-dom/editors/relation-editor.tsx","../src/grid/editors/relation-editor.tsx","../src/relations/relation-editor-body.tsx","../src/relations/relation-create-form.tsx","../src/forms/model-form.ts","../src/grid/cell-routing.ts","../src/cell-types/column-routing.ts","../src/forms/metadata-hash.ts","../src/relations/relation-keys.ts","../src/relations/relation-create.ts","../src/relations/relation-link-list.tsx","../src/relations/relation-label.ts","../src/relations/relation-picker.tsx","../src/relations/use-relation-editor.ts","../src/grid/filter-operators.ts","../src/grid/view-state/view-state.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-navigation.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/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","../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-model/factories/geometry.ts","../src/grid/sheets.formatters.ts","../src/cell-model/factories/image.ts","../src/cell-model/factories/interval.ts","../src/cell-model/factories/number.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"],"sourcesContent":["import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\n\ninterface EditorFocusTrapProps {\n\tchildren: React.ReactNode;\n\tonEscape?: () => void;\n\tonKeyDown?: (e: React.KeyboardEvent) => void;\n\tclassName?: string;\n\tstyle?: React.CSSProperties;\n}\n\nconst FOCUSABLE_SELECTOR = [\n\t'button:not([disabled])',\n\t'input:not([disabled])',\n\t'textarea:not([disabled])',\n\t'select:not([disabled])',\n\t'a[href]',\n\t'[tabindex]:not([tabindex=\"-1\"])',\n].join(', ');\n\n/** Filter to only truly visible focusable elements */\nfunction getVisibleFocusable(container: HTMLElement): HTMLElement[] {\n\treturn Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(\n\t\t(el) => el.offsetParent !== null,\n\t);\n}\n\nexport function EditorFocusTrap({ children, onEscape, onKeyDown, className, style }: EditorFocusTrapProps) {\n\tconst containerRef = useRef<HTMLDivElement>(null);\n\t// The element to give focus back to on close (the grid, or the button that opened the\n\t// editor). Read on the first render, before any child mounts: an `autoFocus` input inside\n\t// the editor takes focus during the commit, before this component's own effects run.\n\tconst [previousActiveElement] = useState<Element | null>(() => (typeof document === 'undefined' ? null : document.activeElement));\n\n\t// Focus the first visible focusable element synchronously before paint, so the\n\t// editor input is focused instantly on open (no setTimeout settle, no focus-jump\n\t// off an input the user already started typing in). Runs once on mount.\n\tuseLayoutEffect(() => {\n\t\tif (!containerRef.current) return;\n\n\t\tconst visibleElements = getVisibleFocusable(containerRef.current);\n\t\tif (visibleElements.length > 0) {\n\t\t\tvisibleElements[0].focus();\n\t\t} else {\n\t\t\t// If no visible focusable elements, focus the container itself\n\t\t\tcontainerRef.current.focus();\n\t\t}\n\t}, []);\n\n\t// Restore focus to the previously active element when unmounting (only if still\n\t// in DOM).\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tif (previousActiveElement instanceof HTMLElement && previousActiveElement.isConnected) {\n\t\t\t\tpreviousActiveElement.focus();\n\t\t\t}\n\t\t};\n\t}, [previousActiveElement]);\n\n\t// Handle keyboard events — forward all keys to parent, then handle Escape/Tab\n\tconst handleKeyDown = useCallback(\n\t\t(e: React.KeyboardEvent) => {\n\t\t\t// Forward all key events to parent before handling\n\t\t\tonKeyDown?.(e);\n\n\t\t\tif (e.key === 'Escape') {\n\t\t\t\te.preventDefault();\n\t\t\t\te.stopPropagation();\n\t\t\t\tonEscape?.();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (e.key !== 'Tab') return;\n\n\t\t\tconst container = containerRef.current;\n\t\t\tif (!container) return;\n\n\t\t\tconst focusableElements = getVisibleFocusable(container);\n\t\t\tif (focusableElements.length === 0) return;\n\n\t\t\tconst firstElement = focusableElements[0];\n\t\t\tconst lastElement = focusableElements[focusableElements.length - 1];\n\t\t\tconst activeElement = document.activeElement;\n\n\t\t\tif (e.shiftKey) {\n\t\t\t\t// Shift+Tab: going backwards\n\t\t\t\tif (activeElement === firstElement) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tlastElement.focus();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Tab: going forwards\n\t\t\t\tif (activeElement === lastElement) {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\tfirstElement.focus();\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[onEscape, onKeyDown],\n\t);\n\n\treturn (\n\t\t<div\n\t\t\tref={containerRef}\n\t\t\tclassName={className}\n\t\t\tstyle={style}\n\t\t\tonKeyDown={handleKeyDown}\n\t\t\ttabIndex={-1}\n\t\t\trole=\"dialog\"\n\t\t\taria-modal=\"true\"\n\t\t>\n\t\t\t{children}\n\t\t</div>\n\t);\n}\n","import { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\nexport function cn(...inputs: ClassValue[]) {\n\treturn twMerge(clsx(inputs));\n}\n","'use client';\n\n// The parts every value editor shares, so their frames read the same: a title row (the\n// field's readable name, an optional chip for the kind of value, optional controls on\n// the right) and a footer with Clear and Save. Keyboard shortcuts are in the buttons'\n// titles, not printed in the popover.\n\nimport type { ReactNode } from 'react';\n\nimport { Button } from '@constructive-io/ui/button';\n\nimport { cn } from '../../utils/cn';\n\nconst MAC_UA_RE = /Mac|iPod|iPhone|iPad/;\n\n/** The platform's name for the modifier key in a shortcut (\"⌘\" or \"Ctrl\"). */\nexport function modifierKeyLabel(): string {\n\treturn typeof navigator !== 'undefined' && MAC_UA_RE.test(navigator.userAgent) ? '⌘' : 'Ctrl';\n}\n\n/** Why Clear is not offered: the column requires a value. */\nexport const VALUE_REQUIRED_REASON = 'This field cannot be empty.';\n\n/** Clear for a nullable column, or the reason it cannot be cleared. */\nexport type EditorClear = { onClear: () => void } | { reason: string };\n\nexport function editorClear(nullable: boolean | undefined, onClear: () => void): EditorClear {\n\treturn nullable ? { onClear } : { reason: VALUE_REQUIRED_REASON };\n}\n\ninterface EditorHeaderProps {\n\ttitle: string;\n\t/** Extra detail on hover (the field's API name, for example). */\n\ttitleHint?: string;\n\t/** The kind of value, when it helps (a shape kind, for example). */\n\tchip?: string | null;\n\t/** Controls on the right (a mode switch). */\n\tchildren?: ReactNode;\n\tclassName?: string;\n}\n\nexport function EditorHeader({ title, titleHint, chip, children, className }: EditorHeaderProps) {\n\treturn (\n\t\t<div data-slot='editor-header' className={cn('flex items-center justify-between gap-2', className)}>\n\t\t\t{/* As tall as a small switch, so a header is the same height with or without one. */}\n\t\t\t<div className='flex min-h-7 min-w-0 items-center gap-2'>\n\t\t\t\t<h3 className='truncate text-sm font-medium' title={titleHint}>\n\t\t\t\t\t{title}\n\t\t\t\t</h3>\n\t\t\t\t{chip ? (\n\t\t\t\t\t<span className='bg-muted text-muted-foreground shrink-0 rounded-md px-2 py-0.5 text-xs font-medium'>{chip}</span>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t\t{children}\n\t\t</div>\n\t);\n}\n\ninterface EditorFooterProps {\n\tonSave: () => void;\n\t/** The keys that save, for the Save button's title (\"Enter\", or \"⌘ Enter\"). */\n\tsaveShortcut?: string;\n\t/** Why Save is not available (an invalid value), shown as its title. */\n\tsaveBlockedReason?: string | null;\n\t/** Clear, or why the value cannot be cleared; omitted when clearing does not apply. */\n\tclear?: EditorClear | null;\n\t/** A short status on the left, such as why the value is not valid. */\n\tstatus?: ReactNode;\n\tclassName?: string;\n}\n\nexport function EditorFooter({ onSave, saveShortcut, saveBlockedReason, clear, status, className }: EditorFooterProps) {\n\tconst blocked = Boolean(saveBlockedReason);\n\treturn (\n\t\t<div data-slot='editor-footer' className={cn('flex items-center justify-end gap-2 border-t pt-2', className)}>\n\t\t\t{status ? <div className='me-auto min-w-0 truncate text-xs'>{status}</div> : null}\n\t\t\t{clear ? (\n\t\t\t\t'onClear' in clear ? (\n\t\t\t\t\t<Button size='xs' variant='ghost' onClick={clear.onClear} title='Remove the value'>\n\t\t\t\t\t\tClear\n\t\t\t\t\t</Button>\n\t\t\t\t) : (\n\t\t\t\t\t<Button size='xs' variant='ghost' disabled focusableWhenDisabled title={clear.reason}>\n\t\t\t\t\t\tClear\n\t\t\t\t\t</Button>\n\t\t\t\t)\n\t\t\t) : null}\n\t\t\t<Button\n\t\t\t\tsize='xs'\n\t\t\t\tonClick={onSave}\n\t\t\t\tdisabled={blocked}\n\t\t\t\tfocusableWhenDisabled={blocked}\n\t\t\t\ttitle={blocked ? saveBlockedReason ?? undefined : saveShortcut ? `Save (${saveShortcut})` : undefined}\n\t\t\t>\n\t\t\t\tSave\n\t\t\t</Button>\n\t\t</div>\n\t);\n}\n","/**\n * Standardised overlay width presets for cell editors.\n *\n * Each preset defines `min-w` / `max-w` Tailwind classes so every overlay\n * feels consistent while still fitting its content naturally.\n *\n * Usage:\n * import { OVERLAY } from './overlay-presets';\n * <EditorFocusTrap className={cn(OVERLAY.sm, 'bg-popover …')} />\n */\n\n/** Single-input editors — inet, date, interval, time */\nexport const OVERLAY_SM = 'min-w-[320px] max-w-[480px]';\n\n/** Tag chips / expandable lists — array, url, relation, upload, tsvector */\nexport const OVERLAY_MD = 'min-w-[400px] max-w-[560px]';\n\n/** Rich editors — JSON, image */\nexport const OVERLAY_LG = 'min-w-[480px] max-w-[720px]';\n\n/** Full-width editors — geometry / map */\nexport const OVERLAY_XL = 'min-w-[600px] max-w-4xl';\n\nexport const OVERLAY = {\n\tsm: OVERLAY_SM,\n\tmd: OVERLAY_MD,\n\tlg: OVERLAY_LG,\n\txl: OVERLAY_XL,\n} as const;\n","/**\n * Canonical cell-type group constants.\n *\n * Every file that needs to check \"is this cell type a date?\" or \"is this a\n * geometry?\" should import from here instead of maintaining inline arrays.\n *\n * All Sets are typed as `Set<string>` so `.has(cellType)` works without casts.\n */\n\n// ─── Date / Time ────────────────────────────────────────────────────────────\nexport const DATE_TIME_TYPES: Set<string> = new Set(['date', 'datetime', 'timestamptz', 'time']);\n\n// ─── Geometry ───────────────────────────────────────────────────────────────\nexport const GEOMETRY_TYPES: Set<string> = new Set(['geometry', 'geometry-point', 'geometry-collection']);\n\n// ─── Numeric ────────────────────────────────────────────────────────────────\nexport const NUMBER_TYPES: Set<string> = new Set([\n\t'number',\n\t'integer',\n\t'bigint',\n\t'decimal',\n\t'currency',\n\t'smallint',\n\t'percentage',\n\t'rating',\n]);\n\n// ─── Boolean ────────────────────────────────────────────────────────────────\n// A bit string (`bit`, `bitstring`) is text of 0 and 1, never a checkbox.\nexport const BOOLEAN_TYPES: Set<string> = new Set(['boolean', 'toggle']);\n\n// ─── Exact decimal strings ──────────────────────────────────────────────────\n/** Numbers carried as exact decimal strings end to end; never parsed into a JS number. */\nexport const DECIMAL_STRING_TYPES: Set<string> = new Set(['bigint', 'decimal']);\n\n// ─── Tabular figures ────────────────────────────────────────────────────────\n/**\n * Text cell types whose values are mostly digits read down a column (dates, times,\n * durations, ranges, points, vectors, bit strings): they use tabular figures so the\n * digits line up. Number cells always do.\n */\nexport const TABULAR_TEXT_TYPES: Set<string> = new Set([\n\t'date',\n\t'datetime',\n\t'timestamptz',\n\t'time',\n\t'interval',\n\t'range',\n\t'point',\n\t'vector',\n\t'bitstring',\n\t'binary',\n]);\n\n// ─── Choices ────────────────────────────────────────────────────────────────\n/** A fixed list of values: an enum, or text with an allowed-values list. */\nexport const CHOICE_TYPES: Set<string> = new Set(['select', 'multi-select']);\n\n// ─── Array / Collection ─────────────────────────────────────────────────────\nexport const TYPED_ARRAY_TYPES: Set<string> = new Set([\n\t'array',\n\t'text-array',\n\t'uuid-array',\n\t'number-array',\n\t'integer-array',\n\t'date-array',\n\t'tags',\n]);\n\n/** Check for any array-like cell type (typed arrays + generic `-array` suffix) */\nexport function isArrayCellType(cellType: string): boolean {\n\treturn TYPED_ARRAY_TYPES.has(cellType) || cellType.endsWith('-array');\n}\n\n// ─── Structured data (JSON, arrays, interval) ──────────────────────────────\nexport const STRUCTURED_DATA_TYPES: Set<string> = new Set([\n\t'json',\n\t'jsonb',\n\t'array',\n\t'text-array',\n\t'uuid-array',\n\t'number-array',\n\t'integer-array',\n\t'date-array',\n\t'interval',\n\t'range',\n\t'composite',\n\t'point',\n]);\n\n// ─── Media ──────────────────────────────────────────────────────────────────\nexport const MEDIA_TYPES: Set<string> = new Set(['image', 'file', 'video', 'audio', 'upload', 'attachment']);\n\n// ─── Enhanced scalar types ──────────────────────────────────────────────────\nexport const ENHANCED_TYPES: Set<string> = new Set([\n\t'email',\n\t'url',\n\t'phone',\n\t'currency',\n\t'percentage',\n\t'color',\n\t'rating',\n\t'tags',\n]);\n\n// ─── Editor behaviour ───────────────────────────────────────────────────────\n\n/** Cell types that use Glide's built-in text editor (no custom overlay). */\nexport const BUILTIN_EDITOR_TYPES: Set<string> = new Set(['text', 'varchar']);\n\n/** Cell types that are never editable (always read-only). */\nexport const NON_EDITABLE_TYPES: Set<string> = new Set(['tsvector', 'binary', 'vector', 'unknown']);\n\n/** Cell types that open a read-only viewer (show and copy the value) instead of an editor. */\nexport const VIEWER_ONLY_TYPES: Set<string> = new Set(['tsvector', 'binary', 'vector', 'unknown']);\n","/**\n * Locale seam for @constructive-io/sheets.\n *\n * The host app may set a BCP-47 locale via SheetsConfig.locale. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any cell\n * renderer / editor can format dates and numbers locale-aware without threading\n * the locale through props/context. Defaults to 'en-US' (the prior hardcoded\n * behavior), so omitting `locale` changes nothing.\n */\nconst DEFAULT_LOCALE = 'en-US';\n\nlet active: string = DEFAULT_LOCALE;\n\n/** Install (or reset) the active locale. Pass null/undefined to restore the default. */\nexport function setSheetsLocale(locale?: string | null): void {\n\tactive = locale || DEFAULT_LOCALE;\n}\n\n/** Get the active locale (BCP-47). Safe to call anywhere; returns 'en-US' until set. */\nexport function sheetsLocale(): string {\n\treturn active;\n}\n","// How dates and times read in cells, range cells, the record panel and the date editor's\n// value line. One rule (team decision):\n//\n// - A date stays as stored, \"YYYY-MM-DD\": readable and exact.\n// - A time or a date and time reads \"HH:mm:ss\" / \"YYYY-MM-DD HH:mm:ss\": no \"T\", the\n// fraction of a second only when it is not zero (all its non-zero digits), no offset.\n// - A value with a zone (timestamp with zone, time with zone) is shown in the viewer's\n// zone, the same zone the date editor edits in; the element's title carries the exact\n// stored text and that zone (\"… · shown in GMT+7\").\n// - A value without a zone shows its stored wall time, unconverted.\n//\n// Only the display changes: copy, export, paste and writes keep the exact stored text.\n\nimport { sheetsLocale } from '../utils/sheets-i18n';\n\nconst DATE_RE = /^\\d{4,}-\\d{2}-\\d{2}$/;\nconst TIME_RE = /^(\\d{1,2}):(\\d{2})(?::(\\d{2})(\\.\\d+)?)?(Z|[+-]\\d{2}(?::?\\d{2})?)?$/;\nconst DATE_TIME_RE = /^(\\d{4,}-\\d{2}-\\d{2})[T ](\\d{1,2}):(\\d{2})(?::(\\d{2})(\\.\\d+)?)?(Z|[+-]\\d{2}(?::?\\d{2})?)?$/;\n\n/** The kinds of date and time text, by cell type. */\nexport type DateTimeKind = 'date' | 'time' | 'datetime';\n\nexport function dateTimeKindOf(cellType: string | undefined): DateTimeKind | null {\n\tif (cellType === 'date') return 'date';\n\tif (cellType === 'time') return 'time';\n\tif (cellType === 'datetime' || cellType === 'timestamptz') return 'datetime';\n\treturn null;\n}\n\nexport interface DateTimeDisplay {\n\t/** What the element shows. */\n\ttext: string;\n\t/** The viewer's zone the text is shown in (\"GMT+7\"), for a zoned value; else null. */\n\tzone: string | null;\n}\n\nfunction pad2(value: number | string): string {\n\treturn String(value).padStart(2, '0');\n}\n\n/** \".123400\" -> \".1234\"; \".000000\" -> \"\". */\nfunction shownFraction(fraction: string | undefined): string {\n\tconst digits = fraction ? fraction.slice(1).replace(/0+$/, '') : '';\n\treturn digits ? `.${digits}` : '';\n}\n\n/** The viewer's zone at an instant, as the locale names it briefly (\"GMT+7\", \"PST\"). */\nexport function viewerZoneName(instant: Date, locale: string = sheetsLocale()): string {\n\ttry {\n\t\tconst part = new Intl.DateTimeFormat(locale, { timeZoneName: 'short' })\n\t\t\t.formatToParts(instant)\n\t\t\t.find((entry) => entry.type === 'timeZoneName');\n\t\treturn part?.value ?? 'local time';\n\t} catch {\n\t\treturn 'local time';\n\t}\n}\n\n/** A Date for stored text with an offset; microseconds are cut to what Date holds (the shown fraction comes from the text). */\nfunction instantOf(isoLike: string): Date | null {\n\tconst instant = new Date(isoLike.replace(' ', 'T').replace(/(\\.\\d{3})\\d+/, '$1'));\n\treturn Number.isNaN(instant.getTime()) ? null : instant;\n}\n\nfunction localDate(instant: Date): string {\n\treturn `${String(instant.getFullYear()).padStart(4, '0')}-${pad2(instant.getMonth() + 1)}-${pad2(instant.getDate())}`;\n}\n\nfunction localTime(instant: Date): string {\n\treturn `${pad2(instant.getHours())}:${pad2(instant.getMinutes())}:${pad2(instant.getSeconds())}`;\n}\n\nfunction displayTime(text: string, locale: string): DateTimeDisplay | null {\n\tconst match = TIME_RE.exec(text);\n\tif (!match) return null;\n\tconst [, hours, minutes, seconds = '00', fraction, zone] = match;\n\tconst tail = shownFraction(fraction);\n\tif (!zone) return { text: `${pad2(hours!)}:${minutes}:${seconds}${tail}`, zone: null };\n\t// A time of day has no date; today's date gives the viewer's offset in effect now.\n\tconst today = new Date();\n\tconst day = `${today.getUTCFullYear()}-${pad2(today.getUTCMonth() + 1)}-${pad2(today.getUTCDate())}`;\n\tconst instant = instantOf(`${day}T${pad2(hours!)}:${minutes}:${seconds}${zone}`);\n\tif (!instant) return null;\n\treturn { text: `${localTime(instant)}${tail}`, zone: viewerZoneName(instant, locale) };\n}\n\nfunction displayDateTime(text: string, locale: string): DateTimeDisplay | null {\n\tconst match = DATE_TIME_RE.exec(text);\n\tif (!match) return null;\n\tconst [, date, hours, minutes, seconds = '00', fraction, zone] = match;\n\tconst tail = shownFraction(fraction);\n\tif (!zone) return { text: `${date} ${pad2(hours!)}:${minutes}:${seconds}${tail}`, zone: null };\n\t// Offsets are whole minutes, so the seconds and their fraction are the same in every zone.\n\tconst instant = instantOf(text);\n\tif (!instant) return null;\n\treturn { text: `${localDate(instant)} ${localTime(instant)}${tail}`, zone: viewerZoneName(instant, locale) };\n}\n\n/** Date or time text as it is shown. Text that does not match its kind is shown as it is. */\nexport function formatDateTimeText(text: string, kind: DateTimeKind, locale: string = sheetsLocale()): DateTimeDisplay {\n\ttry {\n\t\tconst shown = kind === 'date' ? (DATE_RE.test(text) ? { text, zone: null } : null) : kind === 'time' ? displayTime(text, locale) : displayDateTime(text, locale);\n\t\treturn shown ?? { text, zone: null };\n\t} catch {\n\t\treturn { text, zone: null };\n\t}\n}\n\n/** The title for a shown date or time: the exact stored text, and the zone it is shown in. */\nexport function dateTimeTitle(exact: string, zone: string | null): string {\n\treturn zone ? `${exact} · shown in ${zone}` : exact;\n}\n\n/** True for date-and-time text (\"2024-01-01T00:00:00+00:00\"); false for a date alone or other text. */\nexport function isTimestampText(text: string): boolean {\n\treturn DATE_TIME_RE.test(text);\n}\n","// The date editor works on the parts of the stored text, never on a JS Date, so\n// nothing the user did not change is lost: microseconds (\"13:45:30.123456\"), a time's\n// own zone (\"+00:00\") and a wall time without a zone all survive a save. A date and\n// time with a zone is an instant: the editor shows and edits it in the viewer's zone,\n// as the cells do, and writes it back with the viewer's offset for that moment.\n\nexport type DateEditorType = 'date' | 'datetime' | 'timestamptz' | 'time';\n\nexport interface DateValueParts {\n\t/** Calendar day, \"YYYY-MM-DD\" (in the viewer's zone for an instant); '' for a time. */\n\tdate: string;\n\t/** Time of day, \"HH:mm:ss\" (in the viewer's zone for an instant); '' for a date. */\n\ttime: string;\n\t/** Fraction of a second as stored (\".123456\"), or ''. Kept when the time changes. */\n\tfraction: string;\n\t/** A time-of-day value's own zone (\"+00:00\"), kept as stored; '' when it has none. */\n\ttimeZone: string;\n\t/** A date and time with a zone: an instant, written with the viewer's offset. */\n\tinstant: boolean;\n}\n\nconst DATE_RE = /^(\\d{4,})-(\\d{2})-(\\d{2})$/;\nconst TIME_RE = /^(\\d{1,2}):(\\d{2})(?::(\\d{2})(\\.\\d+)?)?(Z|[+-]\\d{2}(?::?\\d{2})?)?$/;\nconst DATE_TIME_RE = /^(\\d{4,}-\\d{2}-\\d{2})[T ](\\d{1,2}):(\\d{2})(?::(\\d{2})(\\.\\d+)?)?(Z|[+-]\\d{2}(?::?\\d{2})?)?$/;\n\nfunction pad2(value: number | string): string {\n\treturn String(value).padStart(2, '0');\n}\n\nfunction localDate(instant: Date): string {\n\treturn `${String(instant.getFullYear()).padStart(4, '0')}-${pad2(instant.getMonth() + 1)}-${pad2(instant.getDate())}`;\n}\n\nfunction localTime(instant: Date): string {\n\treturn `${pad2(instant.getHours())}:${pad2(instant.getMinutes())}:${pad2(instant.getSeconds())}`;\n}\n\n/** The parts of stored text, or null for no value or text that is not of this type. */\nexport function readDateValueParts(text: string, type: DateEditorType): DateValueParts | null {\n\tconst value = text.trim();\n\tif (!value) return null;\n\tif (type === 'date') {\n\t\tconst match = DATE_RE.exec(value) ?? DATE_RE.exec(value.slice(0, 10));\n\t\treturn match ? { date: value.slice(0, 10), time: '', fraction: '', timeZone: '', instant: false } : null;\n\t}\n\tif (type === 'time') {\n\t\tconst match = TIME_RE.exec(value);\n\t\tif (!match) return null;\n\t\tconst [, hours, minutes, seconds = '00', fraction = '', zone = ''] = match;\n\t\treturn { date: '', time: `${pad2(hours!)}:${minutes}:${seconds}`, fraction, timeZone: zone, instant: false };\n\t}\n\tconst match = DATE_TIME_RE.exec(value);\n\tif (!match) return null;\n\tconst [, date, hours, minutes, seconds = '00', fraction = '', zone] = match;\n\tif (!zone) return { date: date!, time: `${pad2(hours!)}:${minutes}:${seconds}`, fraction, timeZone: '', instant: false };\n\t// An instant: read in the viewer's zone. Offsets are whole minutes, so the seconds and\n\t// their fraction do not change.\n\tconst instant = new Date(value.replace(' ', 'T').replace(/(\\.\\d{3})\\d+/, '$1'));\n\tif (Number.isNaN(instant.getTime())) return null;\n\treturn { date: localDate(instant), time: localTime(instant), fraction, timeZone: '', instant: true };\n}\n\n/** The viewer's offset at this local wall time (\"+07:00\"). */\nfunction localOffset(date: string, time: string): string {\n\tconst instant = new Date(`${date}T${time}`);\n\tconst minutes = Number.isNaN(instant.getTime()) ? -new Date().getTimezoneOffset() : -instant.getTimezoneOffset();\n\tconst sign = minutes >= 0 ? '+' : '-';\n\tconst absolute = Math.abs(minutes);\n\treturn `${sign}${pad2(Math.floor(absolute / 60))}:${pad2(absolute % 60)}`;\n}\n\n/** Stored text for these parts. */\nexport function writeDateValueParts(parts: DateValueParts, type: DateEditorType): string {\n\tif (type === 'date') return parts.date;\n\tif (type === 'time') return `${parts.time}${parts.fraction}${parts.timeZone}`;\n\tconst time = parts.time || '00:00:00';\n\tconst base = `${parts.date}T${time}${parts.fraction}`;\n\treturn parts.instant ? `${base}${localOffset(parts.date, time)}` : base;\n}\n\n/** Parts for a value the user starts from nothing. A zoned type is an instant. */\nexport function emptyDateValueParts(type: DateEditorType): DateValueParts {\n\treturn { date: '', time: type === 'date' ? '' : '00:00:00', fraction: '', timeZone: '', instant: type === 'timestamptz' };\n}\n\n/** A time field's value (\"HH:mm\" or \"HH:mm:ss\") as \"HH:mm:ss\", or null when it is not a time. */\nexport function normalizeTimeInput(value: string): string | null {\n\tconst match = /^(\\d{1,2}):(\\d{2})(?::(\\d{2}))?/.exec(value.trim());\n\tif (!match) return null;\n\tconst [, hours, minutes, seconds = '00'] = match;\n\tif (Number(hours) > 23 || Number(minutes) > 59 || Number(seconds) > 59) return null;\n\treturn `${pad2(hours!)}:${minutes}:${seconds}`;\n}\n","// A date typed as text. Year first (2024-01-31, 2024/1/31) is read as year, month, day; a date\n// that ends with the year (31/01/2024, 1.31.2024) is read in the order the locale writes its\n// dates, so 03/04/2024 is 3 April where the day comes first and March 4 where the month does.\n// A two-digit year is not guessed.\n\ntype Part = 'day' | 'month' | 'year';\n\nconst YEAR_FIRST = /^(\\d{4})[-/.](\\d{1,2})[-/.](\\d{1,2})$/;\nconst YEAR_LAST = /^(\\d{1,2})[-/.](\\d{1,2})[-/.](\\d{4})$/;\n\n/** The order of day and month in the locale's numeric dates. */\nexport function dayMonthOrder(locale?: string): 'day-month' | 'month-day' {\n\tconst parts = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'numeric', day: 'numeric' })\n\t\t.formatToParts(new Date(Date.UTC(2024, 0, 31, 12)))\n\t\t.map((part) => part.type)\n\t\t.filter((type): type is Part => type === 'day' || type === 'month' || type === 'year');\n\treturn parts.indexOf('day') < parts.indexOf('month') ? 'day-month' : 'month-day';\n}\n\nconst pad = (value: number, width = 2) => String(value).padStart(width, '0');\n\nfunction isoDate(year: number, month: number, day: number): string | null {\n\tconst probe = new Date(Date.UTC(year, month - 1, day));\n\tprobe.setUTCFullYear(year);\n\tif (probe.getUTCFullYear() !== year || probe.getUTCMonth() !== month - 1 || probe.getUTCDate() !== day) return null;\n\treturn `${pad(year, 4)}-${pad(month)}-${pad(day)}`;\n}\n\n/** The date `text` names, as YYYY-MM-DD, or null when it is not a whole, real date. */\nexport function parseTypedDate(text: string, locale?: string): string | null {\n\tconst trimmed = text.trim();\n\tconst yearFirst = YEAR_FIRST.exec(trimmed);\n\tif (yearFirst) return isoDate(Number(yearFirst[1]), Number(yearFirst[2]), Number(yearFirst[3]));\n\tconst yearLast = YEAR_LAST.exec(trimmed);\n\tif (!yearLast) return null;\n\tconst [first, second, year] = [Number(yearLast[1]), Number(yearLast[2]), Number(yearLast[3])];\n\treturn dayMonthOrder(locale) === 'day-month' ? isoDate(year, second, first) : isoDate(year, first, second);\n}\n\n/** What to type, for the hint: \"2024-01-31 or 31/01/2024\" in the locale's order. */\nexport function typedDateExample(locale?: string): string {\n\treturn dayMonthOrder(locale) === 'day-month' ? '2024-01-31 or 31/01/2024' : '2024-01-31 or 01/31/2024';\n}\n","import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { getLocalTimeZone, parseDate as parseAriaDate, today } from '@internationalized/date';\nimport type { DateValue as DateValueType } from 'react-aria-components';\n\nimport { Calendar } from '@constructive-io/ui/calendar-rac';\n\nimport { DATE_TIME_TYPES } from '../../cell-types/cell-type-groups';\nimport { dateTimeTitle, formatDateTimeText, type DateTimeKind } from '../../cell-types/date-time-format';\n\nimport {\n\temptyDateValueParts,\n\tnormalizeTimeInput,\n\treadDateValueParts,\n\twriteDateValueParts,\n\ttype DateEditorType,\n\ttype DateValueParts,\n} from './date-value-parts';\nimport { parseTypedDate, typedDateExample } from './date-text';\nimport { EditorFocusTrap } from './editor-focus-trap';\nimport { EditorFooter, EditorHeader, editorClear, modifierKeyLabel } from './editor-frame';\nimport { OVERLAY } from './overlay-presets';\n\nexport type { DateEditorType } from './date-value-parts';\n\n/** The editor's type from the cell type, else guessed from the stored text. */\nexport function resolveDateType(value: unknown, explicitType?: string): DateEditorType {\n\tif (explicitType && DATE_TIME_TYPES.has(explicitType)) return explicitType as DateEditorType;\n\tif (typeof value === 'string') {\n\t\tif (value.includes('T') || value.includes(' ')) return /[+-]\\d{2}(:?\\d{2})?$|Z$/.test(value) ? 'timestamptz' : 'datetime';\n\t\tif (value.includes(':') && !value.includes('-')) return 'time';\n\t}\n\treturn 'date';\n}\n\nfunction displayKind(type: DateEditorType): DateTimeKind {\n\treturn type === 'date' ? 'date' : type === 'time' ? 'time' : 'datetime';\n}\n\nconst TIME_INPUT =\n\t'bg-muted/40 border-border/40 text-foreground w-full rounded-md border px-2.5 py-1.5 text-sm tabular-nums outline-none focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/35';\n\n// The calendar fills the editor's content box: seven equal day columns and a header whose\n// arrows sit at its two ends. The arrows' focus ring is drawn inside them, so it is no\n// larger than the button.\nconst CALENDAR_FILL = [\n\t'w-full',\n\t'[&_table]:w-full [&_table]:table-fixed',\n\t'[&_td>[role=button]]:mx-auto [&_th]:w-auto',\n\t'[&_header_button:focus-visible]:ring-2 [&_header_button:focus-visible]:ring-inset',\n].join(' ');\n\ninterface DateEditorProps {\n\tvalue: unknown;\n\tonFinishedEditing: (next?: unknown) => void;\n\tdateType?: DateEditorType;\n\t/** Offer a Clear action that commits null (the column accepts no value). */\n\tcanClear?: boolean;\n\t/** The field's readable name, shown as the title. */\n\ttitle?: string;\n\t/** Text typed on the cell to open the editor; it starts the date field. */\n\tinitialText?: string;\n}\n\n/** A date for the calendar, or null when the text is not one. */\nfunction calendarDate(iso: string | null | undefined): DateValueType | null {\n\tif (!iso) return null;\n\ttry {\n\t\treturn parseAriaDate(iso);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport const DateEditor: React.FC<DateEditorProps> = ({\n\tvalue,\n\tonFinishedEditing,\n\tdateType: forcedDateType,\n\tcanClear = false,\n\ttitle = 'Date',\n\tinitialText,\n}) => {\n\tconst stored = typeof value === 'string' ? value : '';\n\tconst dateType = resolveDateType(stored, forcedDateType);\n\tconst isTimeOnly = dateType === 'time';\n\tconst isDateTimeType = dateType === 'datetime' || dateType === 'timestamptz';\n\n\t// The parts of the stored text; nothing changes until the user picks a day or a time.\n\tconst [parts, setParts] = useState<DateValueParts | null>(() => readDateValueParts(stored, dateType));\n\tconst [dirty, setDirty] = useState(false);\n\tconst keyContainerRef = useRef<HTMLDivElement>(null);\n\n\tconst selectedDate = useMemo(() => calendarDate(parts?.date), [parts?.date]);\n\n\t// The date can also be typed. The field starts with what was typed on the cell, else the\n\t// stored day; a whole date moves the calendar there, and Save refuses text that is not one.\n\tconst [dateText, setDateText] = useState(() => initialText ?? parts?.date ?? '');\n\tconst [dateError, setDateError] = useState<string | null>(null);\n\tconst [focusedDate, setFocusedDate] = useState<DateValueType>(() => selectedDate ?? today(getLocalTimeZone()));\n\tconst dateInputRef = useRef<HTMLInputElement>(null);\n\tuseEffect(() => {\n\t\tconst input = dateInputRef.current;\n\t\tif (!input) return;\n\t\t// Typing replaces the stored day; text typed on the cell goes on where it ended.\n\t\tif (initialText == null) input.select();\n\t\telse input.setSelectionRange(input.value.length, input.value.length);\n\t\t// Only on open.\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, []);\n\n\tconst setDay = useCallback(\n\t\t(date: string) => {\n\t\t\t// Only the day changes: the time, its fraction and its zone stay as they are.\n\t\t\tsetParts((current) => ({ ...(current ?? emptyDateValueParts(dateType)), date }));\n\t\t\tsetDirty(true);\n\t\t},\n\t\t[dateType],\n\t);\n\n\tconst handleDateText = useCallback(\n\t\t(text: string) => {\n\t\t\tsetDateText(text);\n\t\t\tsetDateError(null);\n\t\t\tconst date = parseTypedDate(text);\n\t\t\tif (!date) return;\n\t\t\tsetDay(date);\n\t\t\tconst shown = calendarDate(date);\n\t\t\tif (shown) setFocusedDate(shown);\n\t\t},\n\t\t[setDay],\n\t);\n\n\tuseEffect(() => {\n\t\t// Text typed on the cell that is already a whole date counts at once.\n\t\tif (initialText != null) handleDateText(initialText);\n\t\t// Only on open.\n\t\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\t}, []);\n\n\tconst handleDateSelect = useCallback(\n\t\t(picked: DateValueType | readonly DateValueType[] | null) => {\n\t\t\t// The shared Calendar also supports multi-select; this editor picks one day.\n\t\t\tif (!picked || Array.isArray(picked)) return;\n\t\t\tconst day = picked as DateValueType;\n\t\t\tconst date = `${String(day.year).padStart(4, '0')}-${String(day.month).padStart(2, '0')}-${String(day.day).padStart(2, '0')}`;\n\t\t\tsetDay(date);\n\t\t\tsetDateText(date);\n\t\t\tsetDateError(null);\n\t\t},\n\t\t[setDay],\n\t);\n\n\tconst handleTimeChange = useCallback(\n\t\t(input: string) => {\n\t\t\tconst time = normalizeTimeInput(input);\n\t\t\tif (!time) return;\n\t\t\t// The field edits whole seconds; the stored fraction of a second is kept.\n\t\t\tsetParts((current) => ({ ...(current ?? emptyDateValueParts(dateType)), time }));\n\t\t\tsetDirty(true);\n\t\t},\n\t\t[dateType],\n\t);\n\n\tconst written = parts && dirty && (isTimeOnly || parts.date) ? writeDateValueParts(parts, dateType) : null;\n\n\tconst handleSave = useCallback(() => {\n\t\tif (!isTimeOnly) {\n\t\t\tconst text = dateText.trim();\n\t\t\t// An emptied date field clears the value where the column allows no value.\n\t\t\tif (text === '' && stored) {\n\t\t\t\tif (canClear) onFinishedEditing(null);\n\t\t\t\telse setDateError('This field needs a value.');\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (text !== '' && !parseTypedDate(text)) {\n\t\t\t\tsetDateError(`Enter a date like ${typedDateExample()}.`);\n\t\t\t\tdateInputRef.current?.focus();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t// Nothing changed: close without writing, so the stored text stays exactly as it is.\n\t\tif (!written) {\n\t\t\tonFinishedEditing();\n\t\t\treturn;\n\t\t}\n\t\tonFinishedEditing(written);\n\t}, [isTimeOnly, dateText, stored, canClear, written, onFinishedEditing]);\n\n\tconst handleCancel = useCallback(() => {\n\t\tonFinishedEditing();\n\t}, [onFinishedEditing]);\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)) || (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\t// The value as the cells show it, in the same zone; the title has the exact text.\n\tconst shownText = written ?? stored;\n\tconst shown = shownText ? formatDateTimeText(shownText, displayKind(dateType)) : null;\n\n\treturn (\n\t\t<EditorFocusTrap\n\t\t\tonEscape={handleCancel}\n\t\t\t// A calendar is as wide as its seven 36px days; the editor takes that width so the\n\t\t\t// month sits with equal space on both sides. A time alone keeps the small editor width.\n\t\t\tclassName={`bg-popover rounded-lg border p-2.5 shadow-lg ${isTimeOnly ? OVERLAY.sm : 'w-[min(20rem,calc(100vw-1.5rem))]'}`}\n\t\t>\n\t\t\t<div ref={keyContainerRef} className='flex flex-col gap-2'>\n\t\t\t\t<EditorHeader title={title} />\n\t\t\t\t{/* The value so far, as the cell shows it, on the calendar's left edge. */}\n\t\t\t\t<p\n\t\t\t\t\tdata-slot='date-editor-value'\n\t\t\t\t\tclassName='text-muted-foreground -mt-1 text-xs tabular-nums'\n\t\t\t\t\ttitle={shown && shownText ? dateTimeTitle(shownText, shown.zone) : undefined}\n\t\t\t\t>\n\t\t\t\t\t{shown?.text || 'No value'}\n\t\t\t\t</p>\n\t\t\t\t{isTimeOnly ? (\n\t\t\t\t\t<input\n\t\t\t\t\t\ttype='time'\n\t\t\t\t\t\tstep='1'\n\t\t\t\t\t\taria-label={`${title} time`}\n\t\t\t\t\t\tvalue={parts?.time ?? ''}\n\t\t\t\t\t\tonChange={(e) => handleTimeChange(e.target.value)}\n\t\t\t\t\t\tclassName={TIME_INPUT}\n\t\t\t\t\t\tautoFocus\n\t\t\t\t\t/>\n\t\t\t\t) : (\n\t\t\t\t\t<>\n\t\t\t\t\t\t<input\n\t\t\t\t\t\t\tref={dateInputRef}\n\t\t\t\t\t\t\ttype='text'\n\t\t\t\t\t\t\tautoComplete='off'\n\t\t\t\t\t\t\tspellCheck={false}\n\t\t\t\t\t\t\taria-label={`${title} date`}\n\t\t\t\t\t\t\taria-invalid={dateError ? true : undefined}\n\t\t\t\t\t\t\taria-describedby={dateError ? 'sheets-date-editor-error' : undefined}\n\t\t\t\t\t\t\tplaceholder={typedDateExample()}\n\t\t\t\t\t\t\tvalue={dateText}\n\t\t\t\t\t\t\tonChange={(e) => handleDateText(e.target.value)}\n\t\t\t\t\t\t\tonKeyDown={(e) => {\n\t\t\t\t\t\t\t\t// Enter saves what was typed, as in a cell.\n\t\t\t\t\t\t\t\tif (e.key !== 'Enter' || e.metaKey || e.ctrlKey || e.altKey || e.shiftKey) return;\n\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\te.stopPropagation();\n\t\t\t\t\t\t\t\thandleSave();\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\tclassName={TIME_INPUT}\n\t\t\t\t\t\t\tautoFocus\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t{dateError ? (\n\t\t\t\t\t\t\t<p id='sheets-date-editor-error' role='alert' className='text-destructive -mt-1 text-xs'>\n\t\t\t\t\t\t\t\t{dateError}\n\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t<Calendar\n\t\t\t\t\t\t\tvalue={selectedDate}\n\t\t\t\t\t\t\tonChange={handleDateSelect}\n\t\t\t\t\t\t\tfocusedValue={focusedDate}\n\t\t\t\t\t\t\tonFocusChange={setFocusedDate}\n\t\t\t\t\t\t\taria-label='Select date'\n\t\t\t\t\t\t\tclassName={CALENDAR_FILL}\n\t\t\t\t\t\t/>\n\t\t\t\t\t\t{isDateTimeType ? (\n\t\t\t\t\t\t\t<input\n\t\t\t\t\t\t\t\ttype='time'\n\t\t\t\t\t\t\t\tstep='1'\n\t\t\t\t\t\t\t\taria-label={`${title} time`}\n\t\t\t\t\t\t\t\tvalue={parts?.time ?? ''}\n\t\t\t\t\t\t\t\tonChange={(e) => handleTimeChange(e.target.value)}\n\t\t\t\t\t\t\t\tclassName={TIME_INPUT}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t) : null}\n\t\t\t\t\t</>\n\t\t\t\t)}\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\tclear={editorClear(canClear, () => onFinishedEditing(null))}\n\t\t\t\t/>\n\t\t\t</div>\n\t\t</EditorFocusTrap>\n\t);\n};\n","// =============================================================================\n// @constructive-io/sheets/advanced — Power-user / extension primitives\n// =============================================================================\n// Lower-level building blocks for consumers composing their own editors and\n// cells. Everything here is optional; the root entry stays sufficient for\n// ordinary usage. Importing from this subpath keeps the core surface slim.\n\n// -- Native editor registry (DOM overlay editors) -----------------------------\nexport type { NativeEditor } from './grid-dom/editors/editor-registry-dom';\nexport { DOM_EDITOR_REGISTRY, resolveNativeEditor, wrapNativeEditor } from './grid-dom/editors/editor-registry-dom';\nexport type { EditorProps } from './grid-dom/editors/editor-props';\n\n// -- Overlay editor primitives ------------------------------------------------\nexport { OVERLAY, OVERLAY_SM, OVERLAY_MD, OVERLAY_LG, OVERLAY_XL } from './grid/editors/overlay-presets';\nexport { EditorFocusTrap } from './grid/editors/editor-focus-trap';\nexport { OverlayViewportGuard } from './grid/editors/overlay-viewport-guard';\n\n// -- Native cell content (DOM render payload) ---------------------------------\nexport { createSheetsCell } from './cell-model/create-sheets-cell';\nexport type { SheetsCell, SheetsCellKind } from './cell-model/sheets-cell';\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","// 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 { 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 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","// 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","'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","import { createContext, useContext } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\n\nimport type { DisplayFieldOverrides } from '@constructive-io/data';\n\nimport type { SheetsExecuteFn, SheetsUploadFn } from './sheets-execute';\nimport type { SheetsLogger } from '../utils/sheets-logger';\nimport type { CellTypePlugin } from '../cell-types/define-cell-type';\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\nimport type { SheetsUploadConfig } from '../uploads/upload-config';\nimport type { SheetsViewStorage } from '../grid/views/view-storage';\nimport type { SheetsMapConfig } from '../utils/map-settings';\n\nexport interface SheetsAuthEmbedded {\n\tmode: 'embedded';\n\tgetToken: () => string | null;\n\t/**\n\t * Stable, non-secret identity used to isolate cached data between users.\n\t * Hosts should return the authenticated user/session id, never the token.\n\t * When omitted, the provider uses an opaque key that changes with the token.\n\t */\n\tgetIdentityKey?: () => string | null;\n}\n\nexport interface SheetsAuthStandalone {\n\tmode: 'standalone';\n}\n\nexport interface SheetsStorageTransport {\n\tendpoint: string;\n\texecute: SheetsExecuteFn;\n}\n\nexport interface SheetsConfig {\n\t/** Data endpoint (app-public GraphQL) */\n\tendpoint: string;\n\t/** Auth endpoint (auth GraphQL) — required for standalone mode */\n\tauthEndpoint?: string;\n\t/** Database ID for multi-tenant scoping */\n\tdatabaseId?: string;\n\t/** Auth mode */\n\tauth: SheetsAuthEmbedded | SheetsAuthStandalone;\n\t/** Field type overrides (replaces schema-builder smart tags) */\n\tfieldTypeOverrides?: Record<string, string>;\n\t/**\n\t * Fields that label a record of a table (relation chips, pickers, record\n\t * titles), keyed by `TableModel.key` or table name, in priority order.\n\t * Tables without an entry use the built-in display rule.\n\t */\n\tdisplayFields?: DisplayFieldOverrides;\n\t/** Optional: BCP-47 locale for locale-aware date/number formatting (default 'en-US'). */\n\tlocale?: string;\n\t/**\n\t * The geometry editor's map: tile URL and attribution, and the place search endpoint.\n\t * Default: OpenStreetMap tiles and Nominatim search. `tiles: 'off'` edits shapes as\n\t * GeoJSON text; `placeSearch: 'off'` removes the search box. With a\n\t * Content-Security-Policy, allow the tile host in `img-src` and the search endpoint in\n\t * `connect-src`.\n\t */\n\tmap?: SheetsMapConfig;\n\t/** Optional: inject custom execute function */\n\texecute?: SheetsExecuteFn;\n\t/** Optional: inject custom upload function */\n\texecuteUpload?: SheetsUploadFn;\n\t/** Storage endpoint for media uploads and download URL lookups. */\n\tstorage?: { endpoint: string; execute?: SheetsExecuteFn };\n\t/** Upload choices (bucket, owner, files table, per-column overrides); every field is optional. */\n\tupload?: SheetsUploadConfig;\n\t/**\n\t * Where saved views are kept. Default: this browser's local storage, keyed by endpoint,\n\t * database, identity and table. A host can supply server storage.\n\t */\n\tviews?: SheetsViewStorage;\n\t/** Optional: inject existing QueryClient */\n\tqueryClient?: QueryClient;\n\t/** Optional: inject a custom backend adapter. Defaults to the PostGraphile adapter. */\n\tadapter?: SheetsBackendAdapter;\n\t/** Optional: provider-level cell-type plugins (consumer override layer). */\n\tplugins?: CellTypePlugin[];\n\t/** Called on 401/UNAUTHENTICATED before the error is thrown. Host app handles token cleanup. */\n\tonAuthError?: () => void;\n\t/** Optional: inject a custom logger. Installed into the module logger singleton by the provider. */\n\tlogger?: SheetsLogger;\n\t/** Optional: called when a grid/editor/mutation/upload error surfaces. Host app handles reporting. */\n\tonError?: (\n\t\terror: unknown,\n\t\tctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string },\n\t) => void;\n}\n\nexport interface SheetsContextValue {\n\tconfig: SheetsConfig;\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tstorage?: SheetsStorageTransport;\n\tcanUpload: boolean;\n\tscopeKey: SheetsScopeKey;\n}\n\nexport interface SheetsScopeKey {\n\tdatabaseId: string | null;\n\tendpoint: string;\n\tidentityKey: string | null;\n}\n\nexport const SheetsContext = createContext<SheetsContextValue | null>(null);\n\nexport function useSheetsContext(): SheetsContextValue {\n\tconst ctx = useContext(SheetsContext);\n\tif (!ctx) {\n\t\tthrow new Error('useSheetsContext must be used within a <SheetsProvider>');\n\t}\n\treturn ctx;\n}\n","/**\n * Injectable logger seam for @constructive-io/sheets.\n *\n * The host app may provide a custom logger via SheetsConfig.logger. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any module\n * or hook can log without threading the logger through props/context.\n *\n * Default behaviour matches the prior console.* calls. `debug` is omitted from the\n * default logger (no-op) so verbose diagnostics stay silent unless a host opts in.\n */\nexport interface SheetsLogger {\n\tdebug?(msg: string, ctx?: unknown): void;\n\twarn(msg: string, ctx?: unknown): void;\n\terror(msg: string, ctx?: unknown): void;\n}\n\nconst defaultLogger: SheetsLogger = {\n\twarn: (...a) => console.warn(...a),\n\terror: (...a) => console.error(...a),\n\t// debug omitted = no-op\n};\n\nlet active: SheetsLogger = defaultLogger;\n\n/**\n * Install (or reset) the active logger. Pass a host logger to override; pass\n * null/undefined to restore the default. Host overrides are merged over the\n * default so a partial logger still gets working warn/error.\n */\nexport function setSheetsLogger(l?: SheetsLogger | null): void {\n\tactive = l ? { ...defaultLogger, ...l } : defaultLogger;\n}\n\n/** Get the active logger. Safe to call anywhere (returns the default until set). */\nexport function sheetsLogger(): SheetsLogger {\n\treturn active;\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","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 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","/**\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","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 type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { ConstructiveError, createError, isAuthenticationCode, parseGraphQLError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig, SheetsStorageTransport } from './sheets-context';\nimport { createPresignedSheetsUpload } from './sheets-upload-presigned';\n\n// The presigned uploader lives with the upload protocol; it stays importable from here.\nexport { createPresignedSheetsUpload };\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;\n\n/** Per-request options. An executor that does not support one ignores it. */\nexport interface SheetsExecuteOptions {\n\t/** Aborts the request, for example when the filter or sort it was for has changed. */\n\tsignal?: AbortSignal;\n}\n\nexport type SheetsExecuteFn = <T = unknown>(\n\tdocument: ExecutableDocument,\n\tvariables?: Record<string, unknown>,\n\toptions?: SheetsExecuteOptions,\n) => Promise<T>;\n\n/** Durable file metadata for image and upload columns. */\nexport interface SheetsFileValue {\n\tid: string;\n\tkey: string;\n\tbucket_id: string;\n\tmime: string;\n\tsize: number;\n\tfilename: string;\n\t/** Public URL supplied by storage, when available. */\n\turl?: string;\n}\n\nexport interface SheetsUploadResult {\n\tfile: SheetsFileValue;\n\t/** Optional download URL for immediate use. It can expire. */\n\turl?: string;\n}\n\n/**\n * Optional upload metadata carried through the seam (third arg). Lets an\n * injected `executeUpload` see the destination field/row and report progress.\n * All fields optional, so existing `(file, path?)` callers stay valid.\n */\nexport interface SheetsUploadOptions {\n\ttableName?: string;\n\tfieldName?: string;\n\trecordId?: string | number;\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void;\n}\n\nexport type SheetsUploadFn = (\n\tfile: File,\n\tpath?: string,\n\toptions?: SheetsUploadOptions,\n) => Promise<SheetsUploadResult>;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction documentToString(document: ExecutableDocument): string {\n\tif (typeof document === 'string') return document;\n\tif (document instanceof String) return document.toString();\n\tif (document && typeof document === 'object' && 'kind' in (document as DocumentNode)) {\n\t\treturn print(document as DocumentNode);\n\t}\n\tif (document === null || document === undefined) {\n\t\tthrow createError.badRequest('Invalid GraphQL document: null or undefined');\n\t}\n\treturn String(document);\n}\n\n// ============================================================================\n// GraphQL Response Parsing\n// ============================================================================\n\n/** One error of a GraphQL response. */\nexport interface SheetsResponseError {\n\tmessage: string;\n\tpath?: ReadonlyArray<string | number>;\n\textensions?: { code?: string; context?: Record<string, unknown> };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: SheetsResponseError[];\n}\n\n/** The data a response carried beside its errors. */\nexport interface SheetsPartialResult {\n\tdata: unknown;\n\terrors: readonly SheetsResponseError[];\n}\n\nconst PARTIAL_RESULT = 'partialResult';\nconst RESPONSE_ERRORS = 'responseErrors';\n\n/**\n * Keep a response's errors, and its data when it has some, on the error thrown\n * for it. Every error of the response stays readable (`responseErrorsOf`), and\n * a read whose rows came back with field errors (a float NaN cell) can keep\n * the rows (`partialResultOf`). Callers that only look at the thrown error see\n * it as before.\n */\nexport function withResponseErrors<E extends Error>(error: E, data: unknown, errors: readonly SheetsResponseError[]): E {\n\tObject.defineProperty(error, RESPONSE_ERRORS, { value: errors, enumerable: false, configurable: true });\n\tif (data != null) {\n\t\tObject.defineProperty(error, PARTIAL_RESULT, {\n\t\t\tvalue: { data, errors } satisfies SheetsPartialResult,\n\t\t\tenumerable: false,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn error;\n}\n\n/** Every error of the response an error was thrown for, or null when it did not come from a GraphQL response. */\nexport function responseErrorsOf(error: unknown): readonly SheetsResponseError[] | null {\n\tconst errors = error && typeof error === 'object' ? (error as Record<string, unknown>)[RESPONSE_ERRORS] : null;\n\treturn Array.isArray(errors) ? (errors as SheetsResponseError[]) : null;\n}\n\n/** The data an error's response carried, or null. */\nexport function partialResultOf(error: unknown): SheetsPartialResult | null {\n\tconst partial = error && typeof error === 'object' ? (error as Record<string, unknown>)[PARTIAL_RESULT] : null;\n\treturn partial && typeof partial === 'object' ? (partial as SheetsPartialResult) : null;\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): ConstructiveError | null {\n\tif (!response.errors?.length) return null;\n\n\t// Only an explicit code (the shared list in @constructive-io/data) means the session is\n\t// gone. A permission error that mentions \"unauthorized\" in its text must not log the user out.\n\tif (response.errors.some((candidate) => isAuthenticationCode(candidate.extensions?.code))) {\n\t\tonAuthError?.();\n\t\treturn createError.unauthorized('Authentication required. Please log in again.');\n\t}\n\n\tconst error = response.errors[0];\n\tconst code = error.extensions?.code;\n\tconst message = error.message || 'GraphQL query failed';\n\n\t// A suspended database keeps its `context.reason` (billing or admin) for the paused screen.\n\tif (code === 'ACCESS_SUSPENDED') return parseGraphQLError(error);\n\n\tif (code === 'FORBIDDEN') {\n\t\treturn createError.forbidden('You do not have permission to perform this action.');\n\t}\n\n\treturn createError.graphql(message, code);\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createSheetsExecute(\n\tconfig: SheetsConfig,\n\tgetToken: () => string | null,\n): SheetsExecuteFn {\n\treturn async <T = unknown>(\n\t\tdocument: ExecutableDocument,\n\t\tvariables?: Record<string, unknown>,\n\t\toptions?: SheetsExecuteOptions,\n\t): Promise<T> => {\n\t\tconst url = config.endpoint;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst token = getToken();\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/graphql-response+json',\n\t\t};\n\t\tif (token) {\n\t\t\theaders['Authorization'] = `Bearer ${token}`;\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await fetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tquery: documentToString(document),\n\t\t\t\t\t...(variables !== undefined && { variables }),\n\t\t\t\t}),\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow createError.network(error instanceof Error ? error : undefined);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tconst { status, statusText } = response;\n\t\t\tif (status === 401) {\n\t\t\t\tconfig.onAuthError?.();\n\t\t\t\tthrow createError.unauthorized('Authentication required. Please log in again.');\n\t\t\t}\n\t\t\tif (status === 403) {\n\t\t\t\tconst body = (await response.json().catch((): null => null)) as GraphQLResponse | null;\n\t\t\t\tconst refusal = body?.errors?.[0];\n\t\t\t\tconst forbidden = refusal?.extensions?.code === 'ACCESS_SUSPENDED'\n\t\t\t\t\t? parseGraphQLError(refusal)\n\t\t\t\t\t: createError.forbidden('You do not have permission to perform this action.');\n\t\t\t\tthrow body?.errors?.length ? withResponseErrors(forbidden, null, body.errors) : forbidden;\n\t\t\t}\n\t\t\tif (status === 404) {\n\t\t\t\tthrow createError.notFound('The requested endpoint does not exist.');\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst body = (await response.json()) as GraphQLResponse;\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tthrow withResponseErrors(\n\t\t\t\t\t\tcreateError.graphql(body.errors[0]!.message || `Request failed: ${status}`, body.errors[0]!.extensions?.code),\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tbody.errors,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof ConstructiveError) throw e;\n\t\t\t}\n\t\t\tthrow createError.badRequest(`Request failed: ${status} ${statusText}`);\n\t\t}\n\n\t\tconst result: GraphQLResponse = await response.json();\n\t\tconst graphqlError = parseGraphQLResponse(result, config.onAuthError);\n\t\tif (graphqlError) {\n\t\t\t// A lost session or a suspended database never hands back partial rows.\n\t\t\tconst keepsData = !['UNAUTHENTICATED', 'ACCESS_SUSPENDED'].includes(graphqlError.code);\n\t\t\tthrow withResponseErrors(graphqlError, keepsData ? result.data : null, result.errors ?? []);\n\t\t}\n\n\t\treturn result.data as T;\n\t};\n}\n\nexport function resolveStorageTransport(\n\tconfig: SheetsConfig,\n\tgetToken: () => string | null,\n): SheetsStorageTransport | undefined {\n\tconst endpoint = config.storage?.endpoint;\n\tif (!endpoint) return undefined;\n\n\treturn {\n\t\tendpoint,\n\t\texecute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken),\n\t};\n}\n\n/** Creates an uploader for storage. Direct callers may use the supplied endpoint as storage. */\nexport function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\tconst transport = resolveStorageTransport(config, getToken) ?? {\n\t\tendpoint: config.endpoint,\n\t\texecute: config.execute ?? createSheetsExecute(config, getToken),\n\t};\n\treturn createPresignedSheetsUpload(transport, config.upload?.bucketKey);\n}\n\nexport { ConstructiveError } from '@constructive-io/data';\n","/**\n * The presigned upload protocol, shared by every upload path.\n *\n * 1. Hash the file (SHA-256, Web Crypto). The server needs the hash before it\n * issues the URL: it names the object and is signed into the PUT.\n * 2. Ask the upload mutation for a presigned PUT URL. A `deduplicated` answer\n * means the bytes are already stored: no PUT.\n * 3. PUT the bytes with the payload's `uploadHeaders`, unchanged (the URL is\n * signed over them: Content-Type, the checksum, the file row id). No\n * Authorization header; the signature is in the URL.\n * 4. An expired URL is requested again once.\n *\n * The server confirms the PUT later (a background job) and expires rows that\n * never received one, so a cancelled or failed PUT leaves nothing behind.\n *\n * The model-driven path (`uploads/`) names the upload mutation from the storage\n * service's `_meta`. The shape discovery in `sheets-upload-discovery.ts` is the\n * FALLBACK for a storage service whose `_meta` names no upload mutation.\n */\n\nimport { createError } from '@constructive-io/data';\n\n// ============================================================================\n// Upload payload\n// ============================================================================\n\n/**\n * The file projection the upload mutation returns: what an image or upload\n * column stores. The server may add keys (image `versions`); they are kept as returned.\n */\nexport interface FileProjection {\n\tid: string;\n\tkey: string;\n\tbucket_id?: string;\n\tmime?: string;\n\tsize?: number;\n\tfilename?: string;\n\t/** Durable public URL; set only for a public bucket. */\n\turl?: string;\n}\n\n/** The upload mutation's answer, normalized. */\nexport interface UploadPayload {\n\tuploadUrl: string | null;\n\t/** Headers the PUT must send unchanged, or null on a server that does not return them. */\n\tuploadHeaders: Record<string, string> | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\t/** When the upload URL expires (ISO time), or null. */\n\texpiresAt: string | null;\n\tfile: FileProjection;\n}\n\n/** Payload fields the client selects when the payload type has them. */\nexport const UPLOAD_PAYLOAD_FIELDS = ['uploadUrl', 'uploadHeaders', 'fileId', 'key', 'deduplicated', 'expiresAt', 'file'] as const;\n\nfunction headersOf(value: unknown): Record<string, string> | null {\n\tlet parsed = value;\n\tif (typeof parsed === 'string') {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed) as unknown;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n\tconst entries = Object.entries(parsed as Record<string, unknown>);\n\tif (!entries.every(([, header]) => typeof header === 'string')) return null;\n\treturn Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction projectionOf(value: unknown): FileProjection | null {\n\tlet parsed = value;\n\tif (typeof parsed === 'string') {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed) as unknown;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n\tconst projection = parsed as Record<string, unknown>;\n\treturn isFileProjection(projection) ? projection : null;\n}\n\n/** A projection names its file by `id` and `key`; the server may add more keys, which are kept. */\nfunction isFileProjection(value: Record<string, unknown>): value is Record<string, unknown> & FileProjection {\n\treturn typeof value.id === 'string' && typeof value.key === 'string';\n}\n\n// ============================================================================\n// Unfinished uploads: the file row an upload left behind\n// ============================================================================\n\n/**\n * The file row the storage service created for an upload that did not finish\n * (a refused or blocked PUT, a cancel, an answer without an upload URL). Sheets\n * never deletes it: the storage service expires a row that never received its\n * bytes. A host with its own cleanup rule reads it from the error.\n */\nexport interface UnfinishedUpload {\n\t/** Id of the files table row. */\n\tfileId: string;\n\t/** GraphQL type name of the files table, or null when the upload path does not know it. */\n\tfilesType: string | null;\n\t/** `TableModel.key` of the files table, or null when the upload path does not know it. */\n\tfilesTableKey: string | null;\n}\n\nconst UNFINISHED_UPLOAD = 'unfinishedUpload';\n\n/** The file row an upload error left on the storage service, or null when the server issued none. */\nexport function unfinishedUploadOf(error: unknown): UnfinishedUpload | null {\n\tconst value = error && typeof error === 'object' ? (error as Record<string, unknown>)[UNFINISHED_UPLOAD] : null;\n\treturn value && typeof value === 'object' ? (value as UnfinishedUpload) : null;\n}\n\n/**\n * Record on `error` the file row its upload left. An id already recorded is kept\n * (it is the newest one); a files table is filled in when the error has none. An\n * error without a file id is returned unchanged.\n */\nexport function withUnfinishedUpload(error: unknown, upload: Partial<UnfinishedUpload>): unknown {\n\tif (!error || typeof error !== 'object') return error;\n\tconst recorded = unfinishedUploadOf(error);\n\tconst fileId = recorded?.fileId ?? upload.fileId;\n\tif (!fileId) return error;\n\tconst value: UnfinishedUpload = {\n\t\tfileId,\n\t\tfilesType: recorded?.filesType ?? upload.filesType ?? null,\n\t\tfilesTableKey: recorded?.filesTableKey ?? upload.filesTableKey ?? null,\n\t};\n\tObject.defineProperty(error, UNFINISHED_UPLOAD, { value, enumerable: false, configurable: true, writable: true });\n\treturn error;\n}\n\n/** Normalize a raw upload payload. Throws when it cannot be used. */\nexport function readUploadPayload(raw: unknown): UploadPayload {\n\tif (!raw || typeof raw !== 'object') {\n\t\tthrow createError.badRequest('Upload failed: the storage service returned no answer.');\n\t}\n\tconst payload = raw as Record<string, unknown>;\n\tconst file = projectionOf(payload.file);\n\tif (!file) {\n\t\tthrow createError.badRequest('Upload failed: the server returned an invalid file projection.');\n\t}\n\tconst deduplicated = payload.deduplicated === true;\n\tconst uploadUrl = typeof payload.uploadUrl === 'string' && payload.uploadUrl ? payload.uploadUrl : null;\n\tif (!deduplicated && !uploadUrl) {\n\t\t// The server created the row; it is left to expire, and the error names it.\n\t\tthrow withUnfinishedUpload(createError.badRequest('Upload failed: the server returned no uploadUrl for a new file.'), {\n\t\t\tfileId: typeof payload.fileId === 'string' ? payload.fileId : file.id,\n\t\t});\n\t}\n\treturn {\n\t\tuploadUrl,\n\t\tuploadHeaders: headersOf(payload.uploadHeaders),\n\t\tfileId: typeof payload.fileId === 'string' ? payload.fileId : file.id,\n\t\tkey: typeof payload.key === 'string' ? payload.key : file.key,\n\t\tdeduplicated,\n\t\texpiresAt: typeof payload.expiresAt === 'string' ? payload.expiresAt : null,\n\t\tfile,\n\t};\n}\n\n// ============================================================================\n// SHA-256 (Web Crypto)\n// ============================================================================\n\n/**\n * Largest file the browser hashes. Web Crypto has no streaming digest, so the\n * whole file is read into memory once to hash it (the digest may copy it once\n * more). The PUT then sends the `File` itself, which the browser streams from\n * disk, so no second copy is kept for the upload. A streaming digest would need\n * a JavaScript SHA-256 implementation; until one is worth a dependency, files\n * above this size are refused with a clear message.\n */\nexport const MAX_HASHED_FILE_BYTES = 512 * 1024 * 1024;\n\nfunction hex(digest: ArrayBuffer): string {\n\tconst bytes = new Uint8Array(digest);\n\tlet out = '';\n\tfor (let i = 0; i < bytes.length; i++) out += bytes[i]!.toString(16).padStart(2, '0');\n\treturn out;\n}\n\nfunction requireSubtle(): SubtleCrypto {\n\tif (!globalThis.crypto?.subtle) {\n\t\tthrow createError.badRequest('This browser cannot hash files (Web Crypto is unavailable), so it cannot upload them.');\n\t}\n\treturn globalThis.crypto.subtle;\n}\n\n/** Lowercase hex SHA-256 of an already-read buffer (64 chars, as the server expects). */\nexport async function sha256HexFromBuffer(buffer: ArrayBuffer): Promise<string> {\n\treturn hex(await requireSubtle().digest('SHA-256', buffer));\n}\n\n/** The bytes of a blob. `Blob.arrayBuffer` where the browser has it, else a FileReader. */\nfunction readBytes(file: Blob): Promise<ArrayBuffer> {\n\tif (typeof file.arrayBuffer === 'function') return file.arrayBuffer();\n\treturn new Promise((resolve, reject) => {\n\t\tconst reader = new FileReader();\n\t\treader.onload = () => resolve(reader.result as ArrayBuffer);\n\t\treader.onerror = () => reject(reader.error ?? new Error('The file could not be read.'));\n\t\treader.readAsArrayBuffer(file);\n\t});\n}\n\n/** Lowercase hex SHA-256 of a file. Refuses files above {@link MAX_HASHED_FILE_BYTES}. */\nexport async function sha256HexOfFile(file: Blob): Promise<string> {\n\tif (file.size > MAX_HASHED_FILE_BYTES) {\n\t\tthrow createError.badRequest(\n\t\t\t`This file is too large to upload from the browser (the limit is ${MAX_HASHED_FILE_BYTES / (1024 * 1024)} MB).`,\n\t\t);\n\t}\n\tconst subtle = requireSubtle();\n\treturn hex(await subtle.digest('SHA-256', await readBytes(file)));\n}\n\n// ============================================================================\n// Presigned PUT\n// ============================================================================\n\n/** Header a checksum-bound presigned PUT carries (base64 of the raw digest). */\nexport const CHECKSUM_SHA256_HEADER = 'x-amz-checksum-sha256';\n/** Header a row-bound presigned PUT carries (the file row id). */\nexport const UPLOAD_ID_HEADER = 'x-amz-meta-upload-id';\n\n/** Hex SHA-256 to base64 of the raw digest, the encoding `x-amz-checksum-sha256` carries. */\nexport function sha256HexToBase64(contentHash: string): string {\n\tconst pairs = contentHash.match(/.{2}/g) ?? [];\n\tlet binary = '';\n\tfor (const pair of pairs) binary += String.fromCharCode(parseInt(pair, 16));\n\treturn btoa(binary);\n}\n\n/**\n * Headers for a server that signs the checksum and the row id but does not\n * return `uploadHeaders` yet. A current server returns them, and they are sent\n * as returned.\n */\nexport function fallbackPutHeaders(contentType: string, contentHash?: string, uploadId?: string): Record<string, string> {\n\treturn {\n\t\t'Content-Type': contentType,\n\t\t...(contentHash ? { [CHECKSUM_SHA256_HEADER]: sha256HexToBase64(contentHash) } : {}),\n\t\t...(uploadId ? { [UPLOAD_ID_HEADER]: uploadId } : {}),\n\t};\n}\n\n/**\n * A PUT the browser could not complete. The API answered moments ago, so the\n * usual cause is the bucket's CORS rule (no allowed origin for this site);\n * browsers do not say which. The words are for the person uploading; the code\n * `STORAGE_UPLOAD_BLOCKED` is for hosts and logs.\n */\nexport const STORAGE_UPLOAD_BLOCKED_MESSAGE =\n\t\"Upload failed: file storage didn't accept uploads from this site, or the connection dropped. If it keeps failing, ask an admin to allow this site in the storage settings.\";\n\nconst PUT_RESPONSE = 'putResponse';\n\n/** The storage server answered the PUT with an error status. The response is kept on the error. */\nfunction putRejected(status: number, statusText: string, body: string) {\n\tconst error = createError.badRequest(`Upload failed: ${status} ${statusText}${body ? ` — ${body}` : ''}`);\n\tObject.defineProperty(error, PUT_RESPONSE, { value: { status, body }, enumerable: false });\n\treturn error;\n}\n\n/** The status and body of a rejected PUT, or null for any other error. */\nexport function putResponseOf(error: unknown): { status: number; body: string } | null {\n\tconst response = error && typeof error === 'object' ? (error as Record<string, unknown>)[PUT_RESPONSE] : null;\n\treturn response && typeof response === 'object' ? (response as { status: number; body: string }) : null;\n}\n\nexport interface UploadProgressEvent {\n\tloaded: number;\n\ttotal: number;\n\tpercentage: number;\n}\n\nexport interface PutFileOptions {\n\theaders: Record<string, string>;\n\tonProgress?: (progress: UploadProgressEvent) => void;\n\tsignal?: AbortSignal;\n}\n\nfunction abortError(): Error {\n\treturn typeof DOMException === 'function'\n\t\t? new DOMException('The upload was cancelled.', 'AbortError')\n\t\t: Object.assign(new Error('The upload was cancelled.'), { name: 'AbortError' });\n}\n\n/** True for the error a cancelled upload rejects with. */\nexport function isAbortError(error: unknown): boolean {\n\treturn Boolean(error && typeof error === 'object' && (error as { name?: unknown }).name === 'AbortError');\n}\n\nfunction blockedError() {\n\treturn createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, 'STORAGE_UPLOAD_BLOCKED');\n}\n\nfunction putWithXhr(url: string, body: Blob | ArrayBuffer, options: PutFileOptions, total: number): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst xhr = new XMLHttpRequest();\n\t\tconst onAbort = () => xhr.abort();\n\t\tconst done = () => options.signal?.removeEventListener('abort', onAbort);\n\t\txhr.open('PUT', url);\n\t\tfor (const [name, value] of Object.entries(options.headers)) xhr.setRequestHeader(name, value);\n\t\txhr.upload.addEventListener('progress', (event) => {\n\t\t\tif (!event.lengthComputable || event.total === 0) return;\n\t\t\toptions.onProgress?.({ loaded: event.loaded, total: event.total, percentage: Math.round((event.loaded / event.total) * 100) });\n\t\t});\n\t\txhr.addEventListener('load', () => {\n\t\t\tdone();\n\t\t\tif (xhr.status >= 200 && xhr.status < 300) {\n\t\t\t\toptions.onProgress?.({ loaded: total, total, percentage: 100 });\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(putRejected(xhr.status, xhr.statusText, xhr.responseText ?? ''));\n\t\t\t}\n\t\t});\n\t\txhr.addEventListener('error', () => {\n\t\t\tdone();\n\t\t\treject(blockedError());\n\t\t});\n\t\txhr.addEventListener('abort', () => {\n\t\t\tdone();\n\t\t\treject(abortError());\n\t\t});\n\t\toptions.signal?.addEventListener('abort', onAbort, { once: true });\n\t\txhr.send(body);\n\t});\n}\n\n/** PUT bytes to a presigned URL with exactly the given headers. Uses XHR when progress is wanted and XHR exists. */\nexport async function putFile(url: string, body: Blob | ArrayBuffer, options: PutFileOptions): Promise<void> {\n\tif (options.signal?.aborted) throw abortError();\n\tconst total = body instanceof ArrayBuffer ? body.byteLength : body.size;\n\tif (options.onProgress && typeof XMLHttpRequest !== 'undefined') {\n\t\tawait putWithXhr(url, body, options, total);\n\t\treturn;\n\t}\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: 'PUT',\n\t\t\theaders: options.headers,\n\t\t\tbody,\n\t\t\t...(options.signal ? { signal: options.signal } : {}),\n\t\t});\n\t} catch (error) {\n\t\tif (isAbortError(error)) throw abortError();\n\t\tthrow blockedError();\n\t}\n\tif (!response.ok) {\n\t\tthrow putRejected(response.status, response.statusText, await response.text().catch(() => ''));\n\t}\n\toptions.onProgress?.({ loaded: total, total, percentage: 100 });\n}\n\n/**\n * PUT an already-read buffer. Kept for callers of the earlier API; new code\n * uses {@link putFile} with the payload's `uploadHeaders`.\n */\nexport async function presignedPut(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\tonProgress?: (progress: UploadProgressEvent) => void,\n\tcontentHash?: string,\n\tuploadId?: string,\n): Promise<void> {\n\tawait putFile(url, buffer, { headers: fallbackPutHeaders(contentType, contentHash, uploadId), onProgress });\n}\n\n// ============================================================================\n// Transfer: hash, request, PUT, one renewal of an expired URL\n// ============================================================================\n\nexport interface UploadRequestInput {\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/** Sends the upload mutation for one file. The signal aborts the request when the user cancels. */\nexport type UploadRequester = (input: UploadRequestInput, signal?: AbortSignal) => Promise<UploadPayload>;\n\nfunction isExpired(payload: UploadPayload, now = Date.now()): boolean {\n\tif (!payload.expiresAt) return false;\n\tconst expiry = Date.parse(payload.expiresAt);\n\treturn Number.isFinite(expiry) && expiry <= now;\n}\n\n/** S3 answers an expired presigned URL with 403 (\"Request has expired\"). */\nfunction looksExpired(error: unknown, payload: UploadPayload): boolean {\n\tconst response = putResponseOf(error);\n\tif (response?.status !== 403) return false;\n\treturn isExpired(payload) || /expired/i.test(response.body);\n}\n\nexport interface TransferOptions {\n\tonProgress?: (progress: UploadProgressEvent) => void;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Upload one file through a requester: hash, request, PUT with the returned\n * headers. A URL that expired before or during the PUT is requested again once.\n * Any error after the server issued a file id carries it (`unfinishedUploadOf`);\n * the row itself is left for the storage service to expire.\n */\nexport async function transferFile(file: File, request: UploadRequester, options: TransferOptions = {}): Promise<UploadPayload> {\n\tconst contentType = file.type || 'application/octet-stream';\n\tconst contentHash = await sha256HexOfFile(file);\n\tif (options.signal?.aborted) throw abortError();\n\tconst input: UploadRequestInput = { contentHash, contentType, size: file.size, filename: file.name };\n\n\tlet payload = await request(input, options.signal);\n\t// From here on the server has issued a file id: the newest `payload` names it.\n\tconst putOrRenew = async (): Promise<UploadPayload> => {\n\t\tfor (let renewals = 0; ; renewals += 1) {\n\t\t\tif (payload.deduplicated) {\n\t\t\t\toptions.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\tif (options.signal?.aborted) throw abortError();\n\t\t\tif (isExpired(payload) && renewals === 0) {\n\t\t\t\tpayload = await request(input, options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait putFile(payload.uploadUrl!, file, {\n\t\t\t\t\theaders: payload.uploadHeaders ?? fallbackPutHeaders(contentType, contentHash, payload.fileId),\n\t\t\t\t\tonProgress: options.onProgress,\n\t\t\t\t\tsignal: options.signal,\n\t\t\t\t});\n\t\t\t\treturn payload;\n\t\t\t} catch (error) {\n\t\t\t\tif (renewals > 0 || !looksExpired(error, payload)) throw error;\n\t\t\t\tpayload = await request(input, options.signal);\n\t\t\t}\n\t\t}\n\t};\n\ttry {\n\t\treturn await putOrRenew();\n\t} catch (error) {\n\t\tthrow withUnfinishedUpload(error, { fileId: payload.fileId });\n\t}\n}\n\n// ============================================================================\n// The fallback discovery, re-exported for callers of the earlier API\n// ============================================================================\n\nexport {\n\t__resetUploadCapabilityCache,\n\tcallUploadOp,\n\tcreatePresignedSheetsUpload,\n\tdiscoverSoleUploadCapability,\n\tdiscoverUploadCapability,\n\tfetchDownloadUrl,\n\tfetchMediaDownloadUrls,\n\trequestDiscoveredUpload,\n\tresolveDownloadUrl,\n\tresolveUploadCapability,\n} from './sheets-upload-discovery';\nexport type { IntrospectionSchema, LegacyUploadPayload, UploadCapability } from './sheets-upload-discovery';\n","/**\n * The FALLBACK upload path: shape discovery over the full introspection.\n *\n * Used only for a storage service whose `_meta` names no upload mutation (an\n * older server), and by hosts that call `createSheetsUpload` directly. It reads\n * the full introspection once per endpoint and finds root mutations with the\n * upload input and payload shape, and the fields that resolve a download URL by\n * file id. The model-driven path in `uploads/` replaces all of this when the\n * storage `_meta` names the upload mutation.\n */\n\nimport { getIntrospectionQuery } from 'graphql';\n\nimport { createError } from '@constructive-io/data';\n\nimport type { SheetsStorageTransport } from './sheets-context';\nimport type { SheetsExecuteFn, SheetsFileValue, SheetsUploadFn, SheetsUploadResult } from './sheets-execute';\nimport {\n\tUPLOAD_PAYLOAD_FIELDS,\n\treadUploadPayload,\n\ttransferFile,\n\twithUnfinishedUpload,\n\ttype FileProjection,\n\ttype UploadPayload,\n} from './sheets-upload-presigned';\n\n// ============================================================================\n// Shape discovery over the full introspection (cached per endpoint)\n// ============================================================================\n\nexport interface UploadCapability {\n\t/** Upload mutation field name, discovered by shape. */\n\tuploadFieldName: string;\n\t/** The upload input object type name. */\n\tinputTypeName: string;\n\thasFileProjection: boolean;\n\t/** Payload fields the mutation returns. Discovery sets it; a capability built by hand may leave it out. */\n\tpayloadFieldNames?: readonly string[];\n\t/** Input fields the mutation accepts. Discovery sets it; a capability built by hand may leave it out. */\n\tinputFieldNames?: readonly string[];\n\tdownload: DownloadByIdResult | null;\n}\n\ninterface DownloadByIdResult {\n\t/** Query field used to resolve downloadUrl by id. */\n\tfileByIdField: string;\n\t/** 'id' singular accessor, 'connection' filtered connection, 'nodeId' Relay node. */\n\tfileByIdArgName: 'id' | 'nodeId' | 'connection';\n\t/** The file object type name. */\n\tfileTypeName: string;\n\tidScalarName?: string;\n\tconnectionFilterArgName?: string;\n\tconnectionIdField?: string;\n\tconnectionIdOperator?: string;\n\tconnectionNodesField?: string;\n\tconnectionHasFirst?: boolean;\n}\n\ninterface StorageCapabilities {\n\t/** The op `discoverUploadCapability(endpoint, execute)` returns: `uploadAppFile`, else the first op that takes a `bucketKey`. */\n\tupload: UploadCapability | null;\n\t/** Every root upload op the endpoint exposes, one per storage plane. */\n\tuploads: Omit<UploadCapability, 'download'>[];\n\t/** The endpoint's only upload op, with its download lookup; null when it has none or several. */\n\tsole: UploadCapability | null;\n\tdownload: DownloadByIdResult | null;\n\tbatch: DownloadByIdResult | null;\n}\n\nlet capabilityCache = new WeakMap<SheetsExecuteFn, Map<string, Promise<StorageCapabilities>>>();\n\n/** Test-only: clear cached storage capabilities between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache = new WeakMap();\n}\n\nasync function discoverStorageCapabilities(endpoint: string, execute: SheetsExecuteFn): Promise<StorageCapabilities> {\n\tlet endpoints = capabilityCache.get(execute);\n\tif (!endpoints) {\n\t\tendpoints = new Map();\n\t\tcapabilityCache.set(execute, endpoints);\n\t}\n\tconst cached = endpoints.get(endpoint);\n\tif (cached) return cached;\n\n\tconst promise = (async () => {\n\t\tconst data = await execute<{ __schema: IntrospectionSchema }>(getIntrospectionQuery());\n\t\tconst schema = data?.__schema;\n\t\tif (!schema) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\t\treturn resolveStorageCapabilities(schema);\n\t})();\n\t// Don't cache a rejected discovery: let the next attempt retry.\n\tpromise.catch(() => endpoints.delete(endpoint));\n\tendpoints.set(endpoint, promise);\n\treturn promise;\n}\n\n/**\n * The endpoint's upload op. Name it when the endpoint serves several storage\n * planes; the named op must still carry the upload shape.\n */\nexport async function discoverUploadCapability(\n\tendpoint: string,\n\texecute: SheetsExecuteFn,\n\tuploadFieldName?: string,\n): Promise<UploadCapability> {\n\tconst { upload, uploads } = await discoverStorageCapabilities(endpoint, execute);\n\tif (uploadFieldName) {\n\t\tconst named = uploads.find((candidate) => candidate.uploadFieldName === uploadFieldName);\n\t\tif (!named) throw createError.badRequest(`Uploads are not enabled for this endpoint: it has no ${uploadFieldName}.`);\n\t\treturn { ...named, download: null };\n\t}\n\tif (!upload) capabilityCache.get(execute)?.delete(endpoint);\n\treturn requireUploadCapability(upload);\n}\n\n/**\n * The fallback's upload op for the grid: exactly one plane, or a reason. The\n * grid never picks between several planes by name.\n */\nexport async function discoverSoleUploadCapability(storage: SheetsStorageTransport): Promise<UploadCapability> {\n\tconst { uploads, sole } = await discoverStorageCapabilities(storage.endpoint, storage.execute);\n\tif (uploads.length > 1) {\n\t\tthrow createError.badRequest('The storage service has several file stores, and none is chosen for this column.');\n\t}\n\tif (!sole) {\n\t\tcapabilityCache.get(storage.execute)?.delete(storage.endpoint);\n\t\tthrow createError.badRequest('Uploads are not enabled for this storage service.');\n\t}\n\treturn sole;\n}\n\nfunction requireUploadCapability(upload: UploadCapability | null): UploadCapability {\n\tif (!upload) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\treturn upload;\n}\n\n// --- Minimal introspection shapes (only what discovery reads) ---\n\ninterface IntrospectionTypeRef {\n\tkind: string;\n\tname?: string | null;\n\tofType?: IntrospectionTypeRef | null;\n}\n\ninterface IntrospectionInputValue {\n\tname: string;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionField {\n\tname: string;\n\targs: ReadonlyArray<IntrospectionInputValue>;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionType {\n\tkind: string;\n\tname?: string | null;\n\tfields?: ReadonlyArray<IntrospectionField> | null;\n\tinputFields?: ReadonlyArray<IntrospectionInputValue> | null;\n}\n\n/** Loose structural shape of an introspection `__schema` (accepts fixtures and real results). */\nexport interface IntrospectionSchema {\n\tqueryType?: { name: string } | null;\n\tmutationType?: { name: string } | null;\n\ttypes: ReadonlyArray<IntrospectionType>;\n}\n\nfunction namedTypeName(ref: IntrospectionTypeRef | null | undefined): string | null {\n\tlet cur = ref;\n\twhile (cur && (cur.kind === 'NON_NULL' || cur.kind === 'LIST')) cur = cur.ofType ?? null;\n\treturn cur?.name ?? null;\n}\n\n/** True when the outer wrapper (after NON_NULL) is a LIST. */\nfunction isListTypeRef(ref: IntrospectionTypeRef | null | undefined): boolean {\n\tlet cur = ref;\n\twhile (cur && cur.kind === 'NON_NULL') cur = cur.ofType ?? null;\n\treturn cur?.kind === 'LIST';\n}\n\n/**\n * The fallback reads the file row by an `id` field, as the projection names it.\n * The model-driven path reads the files table's real key instead.\n */\nconst PK_FIELD_NAME = 'id';\n\n/** Pure resolver over an introspection `__schema`, for direct tests. */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\n\treturn requireUploadCapability(resolveStorageCapabilities(schema).upload);\n}\n\nfunction resolveStorageCapabilities(schema: IntrospectionSchema): StorageCapabilities {\n\tconst typeByName = new Map<string, IntrospectionType>();\n\tfor (const t of schema.types) {\n\t\tif (t.name) typeByName.set(t.name, t);\n\t}\n\n\tconst objectHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tconst t = typeName ? typeByName.get(typeName) : undefined;\n\t\tif (!t?.fields) return false;\n\t\tconst present = new Set(t.fields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst inputHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tconst t = typeName ? typeByName.get(typeName) : undefined;\n\t\tif (!t?.inputFields) return false;\n\t\tconst present = new Set(t.inputFields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'key', 'deduplicated'];\n\tconst INPUT_FIELDS = ['contentHash', 'contentType', 'size'];\n\t// The earlier API only knew ops that take a `bucketKey`; its pick keeps that rule.\n\tconst LEGACY_INPUT_FIELDS = [...INPUT_FIELDS, 'bucketKey'];\n\n\tconst mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;\n\tconst queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;\n\n\tlet upload: Omit<UploadCapability, 'download'> | null = null;\n\tconst uploads: Omit<UploadCapability, 'download'>[] = [];\n\n\tfor (const field of mutationType?.fields ?? []) {\n\t\tconst inputArg = field.args.find((a) => a.name === 'input');\n\t\tif (!inputArg) continue;\n\t\tconst inputTypeName = namedTypeName(inputArg.type);\n\t\tconst payloadTypeName = namedTypeName(field.type);\n\t\tif (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {\n\t\t\tconst payloadFields = typeByName.get(payloadTypeName ?? '')?.fields ?? [];\n\t\t\tconst candidate = {\n\t\t\t\tuploadFieldName: field.name,\n\t\t\t\tinputTypeName,\n\t\t\t\thasFileProjection: payloadFields.some(\n\t\t\t\t\t(f) => f.name === 'file' && !isListTypeRef(f.type) && namedTypeName(f.type) === 'JSON',\n\t\t\t\t),\n\t\t\t\tpayloadFieldNames: payloadFields.map((f) => f.name),\n\t\t\t\tinputFieldNames: (typeByName.get(inputTypeName)?.inputFields ?? []).map((f) => f.name),\n\t\t\t};\n\t\t\tuploads.push(candidate);\n\t\t\t// The pick of the earlier API (`discoverUploadCapability` without a name, and\n\t\t\t// `createSheetsUpload`). The grid's fallback (`discoverSoleUploadCapability`)\n\t\t\t// refuses to choose between planes.\n\t\t\tif (!inputHasFields(inputTypeName, LEGACY_INPUT_FIELDS) || (upload?.uploadFieldName === 'uploadAppFile')) continue;\n\t\t\tif (field.name === 'uploadAppFile') upload = candidate;\n\t\t\telse upload ??= candidate;\n\t\t}\n\t}\n\n\tconst fileTypes = new Set<string>();\n\tfor (const t of schema.types) {\n\t\tif (t.kind === 'OBJECT' && t.name && t.fields?.some((f) => f.name === 'downloadUrl')) fileTypes.add(t.name);\n\t}\n\n\t// Legacy: the file type is read from the upload op's name (uploadAppFile → AppFile).\n\t// Only this fallback does so; the model-driven path reads it from `_meta`.\n\tconst uploadType = upload?.uploadFieldName.replace(/^upload/, '') ?? 'AppFile';\n\tconst uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);\n\tconst preferredPreviewType = fileTypes.has('AppFile') ? 'AppFile' : uploadType;\n\tconst previewType = fileTypes.has(preferredPreviewType)\n\t\t? preferredPreviewType\n\t\t: uploadDownload?.fileTypeName ?? preferredPreviewType;\n\tconst download = previewType === uploadType\n\t\t? uploadDownload\n\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);\n\tconst batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);\n\n\tconst only = uploads.length === 1 ? uploads[0]! : null;\n\tconst sole = only\n\t\t? {\n\t\t\t...only,\n\t\t\tdownload: only === upload\n\t\t\t\t? uploadDownload\n\t\t\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, only.uploadFieldName.replace(/^upload/, '')),\n\t\t}\n\t\t: null;\n\n\treturn {\n\t\tupload: upload ? { ...upload, download: uploadDownload } : null,\n\t\tuploads,\n\t\tsole,\n\t\tdownload,\n\t\tbatch,\n\t};\n}\n\nfunction resolveDownloadByIdField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n): DownloadByIdResult | null {\n\t// 1. A singular by-id accessor, e.g. appFile(id:).\n\tlet singular: DownloadByIdResult | null = null;\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst returnTypeName = namedTypeName(field.type);\n\t\tif (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;\n\t\tif (field.args.length === 1 && field.args[0]!.name === PK_FIELD_NAME) {\n\t\t\tconst candidate: DownloadByIdResult = {\n\t\t\t\tfileByIdField: field.name,\n\t\t\t\tfileByIdArgName: 'id',\n\t\t\t\tfileTypeName: returnTypeName,\n\t\t\t\tidScalarName: namedTypeName(field.args[0]!.type) ?? undefined,\n\t\t\t};\n\t\t\tif (returnTypeName === preferred) return candidate;\n\t\t\tsingular ??= candidate;\n\t\t}\n\t}\n\n\t// 2. A connection filtered by id (Relay-disabled backends).\n\tconst connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);\n\tif (connection?.fileTypeName === preferred) return connection;\n\tif (singular || connection) return singular ?? connection;\n\n\t// 3. Relay `node(nodeId:)`, last resort.\n\tconst nodeField = queryType?.fields?.find((f) => f.name === 'node' && f.args.some((a) => a.name === 'nodeId'));\n\tif (nodeField && fileTypesWithDownloadUrl.size > 0) {\n\t\tconst fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0]!;\n\t\treturn { fileByIdField: 'node', fileByIdArgName: 'nodeId', fileTypeName };\n\t}\n\treturn null;\n}\n\nfunction resolveConnectionDownloadField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n\tbatch = false,\n): DownloadByIdResult | null {\n\tconst EQUALITY_OPERATORS = ['equalTo', 'eq'];\n\tconst candidates: DownloadByIdResult[] = [];\n\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst connTypeName = namedTypeName(field.type);\n\t\tif (!connTypeName) continue;\n\t\tconst connType = typeByName.get(connTypeName);\n\t\tif (connType?.kind !== 'OBJECT' || !connType.fields) continue;\n\n\t\tconst nodesField = connType.fields.find((f) => {\n\t\t\tif (!isListTypeRef(f.type)) return false;\n\t\t\tconst elem = namedTypeName(f.type);\n\t\t\treturn elem != null && fileTypesWithDownloadUrl.has(elem);\n\t\t});\n\t\tif (!nodesField) continue;\n\t\tconst fileTypeName = namedTypeName(nodesField.type) as string;\n\t\tif (batch && (fileTypeName !== preferred ||\n\t\t\t!typeByName.get(fileTypeName)?.fields?.some((candidate) => candidate.name === PK_FIELD_NAME))) continue;\n\t\tconst connectionHasFirst = field.args.some((arg) => arg.name === 'first');\n\n\t\tfor (const arg of field.args) {\n\t\t\tconst filterTypeName = namedTypeName(arg.type);\n\t\t\tconst filterType = filterTypeName ? typeByName.get(filterTypeName) : null;\n\t\t\tif (filterType?.kind !== 'INPUT_OBJECT' || !filterType.inputFields) continue;\n\t\t\tconst idField = filterType.inputFields.find((f) => f.name === PK_FIELD_NAME);\n\t\t\tif (!idField) continue;\n\n\t\t\tconst idFieldTypeName = namedTypeName(idField.type);\n\t\t\tconst idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;\n\n\t\t\tif (idFieldType?.kind === 'INPUT_OBJECT' && idFieldType.inputFields) {\n\t\t\t\tconst inputFields = idFieldType.inputFields;\n\t\t\t\tconst opField = batch\n\t\t\t\t\t? inputFields.find((f) => f.name === 'in' && isListTypeRef(f.type))\n\t\t\t\t\t: EQUALITY_OPERATORS.map((op) => inputFields.find((f) => f.name === op)).find((f) => f != null);\n\t\t\t\tif (opField) {\n\t\t\t\t\tcandidates.push({\n\t\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\t\tfileTypeName,\n\t\t\t\t\t\tidScalarName: namedTypeName(opField.type) ?? undefined,\n\t\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\t\tconnectionIdOperator: opField.name,\n\t\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!batch && (idFieldType?.kind === 'SCALAR' || (!idFieldType && idFieldTypeName))) {\n\t\t\t\tcandidates.push({\n\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\tfileTypeName,\n\t\t\t\t\tidScalarName: idFieldTypeName ?? undefined,\n\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\tconnectionHasFirst,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (candidates.length === 0) return null;\n\treturn candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0]!;\n}\n\n// ============================================================================\n// Fallback: upload op call\n// ============================================================================\n\ninterface UploadOpInput {\n\tbucketKey?: string;\n\tisPublic?: boolean;\n\tdatabaseId?: string;\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/**\n * The upload input for a discovered op. Only input fields the op really has are\n * sent (all of them when the capability lists none); `ownerId` never is (the\n * fallback cannot know an owner, so an entity-scoped plane fails there with the\n * server's message).\n */\nfunction uploadInputOf(cap: UploadCapability, input: UploadOpInput): Record<string, unknown> {\n\tconst inputFields = new Set(cap.inputFieldNames ?? []);\n\tconst has = (name: string) => inputFields.size === 0 || inputFields.has(name);\n\tconst bucket = input.bucketKey !== undefined\n\t\t? (has('bucketKey') ? { bucketKey: input.bucketKey } : {})\n\t\t: (has('isPublic') ? { isPublic: input.isPublic ?? true } : {});\n\treturn {\n\t\t...bucket,\n\t\t...(input.databaseId !== undefined && inputFields.has('databaseId') ? { databaseId: input.databaseId } : {}),\n\t\tcontentHash: input.contentHash,\n\t\tcontentType: input.contentType,\n\t\tsize: input.size,\n\t\t...(has('filename') ? { filename: input.filename } : {}),\n\t};\n}\n\nfunction uploadMutation(cap: UploadCapability, payloadFields: readonly string[]): string {\n\treturn `\n\t\tmutation SheetsUpload($input: ${cap.inputTypeName}!) {\n\t\t\t${cap.uploadFieldName}(input: $input) {\n\t\t\t\t${payloadFields.join('\\n\\t\\t\\t\\t')}\n\t\t\t}\n\t\t}\n\t`.trim();\n}\n\n/** Payload fields of the earlier API, selected when the op's payload fields are not known. */\nconst LEGACY_PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'key', 'deduplicated', 'file'] as const;\n\n/** Invoke a discovered upload op and normalize its payload (strict: see `readUploadPayload`). */\nexport async function requestDiscoveredUpload(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n\tsignal?: AbortSignal,\n): Promise<UploadPayload> {\n\tconst payloadFields = cap.payloadFieldNames?.length\n\t\t? UPLOAD_PAYLOAD_FIELDS.filter((name) => cap.payloadFieldNames!.includes(name))\n\t\t: LEGACY_PAYLOAD_FIELDS;\n\tconst data = await execute<Record<string, unknown>>(uploadMutation(cap, payloadFields), { input: uploadInputOf(cap, input) }, { signal });\n\treturn readUploadPayload(data?.[cap.uploadFieldName]);\n}\n\n/** The payload of the earlier API: the server's answer as it was sent. */\nexport interface LegacyUploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\tfile: Omit<SheetsFileValue, 'filename'> & { filename?: string | null };\n}\n\n/**\n * Earlier API: send the discovered upload op and return its payload as the\n * server sent it. The file projection must carry an id, key, bucket, type and\n * size, and nothing is added to it. A new file without an `uploadUrl` is left\n * to the caller, which knows the `fileId` and can remove the row.\n */\nexport async function callUploadOp(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n): Promise<LegacyUploadPayload> {\n\tconst data = await execute<Record<string, LegacyUploadPayload | null>>(uploadMutation(cap, LEGACY_PAYLOAD_FIELDS), {\n\t\tinput: uploadInputOf(cap, input),\n\t});\n\tconst payload = data?.[cap.uploadFieldName];\n\tif (!payload) {\n\t\tthrow createError.badRequest('Upload failed: no payload returned from upload mutation.');\n\t}\n\tconst file = payload.file;\n\tif (\n\t\t!file || typeof file.id !== 'string' || typeof file.key !== 'string' ||\n\t\ttypeof file.bucket_id !== 'string' || typeof file.mime !== 'string' || typeof file.size !== 'number'\n\t) {\n\t\tthrow createError.badRequest('Upload failed: server returned an invalid file projection.');\n\t}\n\treturn payload;\n}\n\nfunction projectionToFileValue(file: FileProjection, fallbackName: string, fallbackMime: string): SheetsFileValue {\n\treturn {\n\t\t...file,\n\t\tbucket_id: typeof file.bucket_id === 'string' ? file.bucket_id : '',\n\t\tmime: typeof file.mime === 'string' ? file.mime : fallbackMime,\n\t\tsize: typeof file.size === 'number' ? file.size : 0,\n\t\tfilename: typeof file.filename === 'string' ? file.filename : fallbackName,\n\t};\n}\n\n/**\n * An uploader over the fallback discovery, for hosts that call\n * `createSheetsUpload` directly. The grid uses the model-driven path instead.\n */\nexport function createPresignedSheetsUpload(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tbucketKey?: string,\n): SheetsUploadFn {\n\treturn async (file, _path, options) => {\n\t\tif (!endpoint) throw createError.badRequest('No GraphQL endpoint configured.');\n\t\tconst cap = await discoverUploadCapability(endpoint, execute);\n\t\tif (!cap.hasFileProjection) {\n\t\t\tthrow createError.badRequest('Uploads require a storage mutation that returns a file projection.');\n\t\t}\n\t\tlet payload: UploadPayload;\n\t\ttry {\n\t\t\tpayload = await transferFile(\n\t\t\t\tfile,\n\t\t\t\t(input) => requestDiscoveredUpload(execute, cap, { ...input, bucketKey }),\n\t\t\t\t{ onProgress: options?.onProgress },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow withUnfinishedUpload(error, { filesType: cap.download?.fileTypeName ?? null });\n\t\t}\n\t\tconst result: SheetsUploadResult = {\n\t\t\tfile: projectionToFileValue(payload.file, file.name, file.type || 'application/octet-stream'),\n\t\t};\n\t\tif (!cap.download) return result;\n\t\ttry {\n\t\t\treturn { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };\n\t\t} catch {\n\t\t\t// The upload succeeded. The download URL can be requested again later.\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ============================================================================\n// Fallback: downloadUrl resolution\n// ============================================================================\n\n/** Encode a PostGraphile global id with the default base64JSON codec. */\nfunction toGlobalId(typeName: string, id: string): string {\n\tif (typeof btoa !== 'function') {\n\t\tthrow createError.badRequest('Cannot encode the file node id: btoa is unavailable in this environment.');\n\t}\n\treturn btoa(JSON.stringify([typeName, id]));\n}\n\n/** Resolve one file's download URL through a discovered accessor. The URL can expire. */\nexport async function fetchDownloadUrl(execute: SheetsExecuteFn, cap: DownloadByIdResult, fileId: string): Promise<string> {\n\tconst missing = () => createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\tif (cap.fileByIdArgName === 'nodeId') {\n\t\tconst nodeId = toGlobalId(cap.fileTypeName, fileId);\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($nodeId: ID!) {\n\t\t\t\t${cap.fileByIdField}(nodeId: $nodeId) {\n\t\t\t\t\t... on ${cap.fileTypeName} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { nodeId });\n\t\tconst url = data?.[cap.fileByIdField]?.downloadUrl;\n\t\tif (!url) throw missing();\n\t\treturn url;\n\t}\n\n\tif (cap.fileByIdArgName === 'connection') {\n\t\tconst idScalar = cap.idScalarName ?? 'ID';\n\t\tconst filterArg = cap.connectionFilterArgName as string;\n\t\tconst idField = cap.connectionIdField as string;\n\t\tconst nodesField = cap.connectionNodesField as string;\n\t\tconst filterLiteral = cap.connectionIdOperator\n\t\t\t? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }`\n\t\t\t: `{ ${idField}: $id }`;\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t\t${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ', first: 1' : ''}) {\n\t\t\t\t\t${nodesField} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, Record<string, Array<{ downloadUrl?: string | null }> | null> | null>>(\n\t\t\tquery,\n\t\t\t{ id: fileId },\n\t\t);\n\t\tconst url = data?.[cap.fileByIdField]?.[nodesField]?.[0]?.downloadUrl;\n\t\tif (!url) throw missing();\n\t\treturn url;\n\t}\n\n\tconst idScalar = cap.idScalarName ?? 'ID';\n\tconst query = `\n\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t${cap.fileByIdField}(id: $id) {\n\t\t\t\tid\n\t\t\t\tdownloadUrl\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { id: fileId });\n\tconst url = data?.[cap.fileByIdField]?.downloadUrl;\n\tif (!url) throw missing();\n\treturn url;\n}\n\n/** Resolve URLs for one batch of visible files through the fallback discovery. Missing IDs have no entry. */\nexport async function fetchMediaDownloadUrls(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tgetActiveIds: () => readonly string[],\n): Promise<Map<string, string>> {\n\tconst { batch, download } = await discoverStorageCapabilities(endpoint, execute);\n\tconst ids = getActiveIds();\n\tconst urls = new Map<string, string>();\n\tif (ids.length === 0) return urls;\n\tif (batch) {\n\t\tconst first = batch.connectionHasFirst ? `, first: ${ids.length}` : '';\n\t\tconst query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? 'ID'}!]!) {\n\t\t\t${batch.fileByIdField}(${batch.connectionFilterArgName}: {\n\t\t\t\t${batch.connectionIdField}: { in: $ids }\n\t\t\t}${first}) { ${batch.connectionNodesField} { id downloadUrl } }\n\t\t}`;\n\t\ttype FileNode = { id: string; downloadUrl: string | null };\n\t\tconst data = await execute<Record<string, Record<string, (FileNode | null)[] | null> | null>>(query, { ids });\n\t\tfor (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField!] ?? []) {\n\t\t\tif (row?.downloadUrl) urls.set(row.id, row.downloadUrl);\n\t\t}\n\t} else if (download) {\n\t\tconst results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));\n\t\tresults.forEach((result, index) => {\n\t\t\tif (result.status === 'fulfilled') urls.set(ids[index]!, result.value);\n\t\t});\n\t}\n\treturn urls;\n}\n\n/**\n * Resolve a file's signed `downloadUrl` by id, for callers outside the grid\n * (a storage browser's copy link). Returns null on any failure.\n */\nexport async function resolveDownloadUrl(execute: SheetsExecuteFn, endpoint: string, fileId: string): Promise<string | null> {\n\ttry {\n\t\tconst { download } = await discoverStorageCapabilities(endpoint, execute);\n\t\treturn download ? await fetchDownloadUrl(execute, download, fileId) : null;\n\t} catch {\n\t\treturn null;\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 { 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","// 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","import type { SheetsScopeKey } from '../context/sheets-context';\n\nexport function isSheetsScopeKey(value: unknown): value is SheetsScopeKey {\n\tif (!value || typeof value !== 'object') return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn 'databaseId' in candidate && 'endpoint' in candidate && 'identityKey' in candidate;\n}\n\nexport function reuseSheetsPlaceholderData<T>(\n\tpreviousData: T | undefined,\n\tpreviousQueryKey: readonly unknown[] | undefined,\n\tcurrentScope: SheetsScopeKey,\n): T | undefined {\n\tconst previousScope = previousQueryKey?.[1];\n\tif (!isSheetsScopeKey(previousScope)) return undefined;\n\tif (previousScope.databaseId !== currentScope.databaseId) return undefined;\n\tif (previousScope.endpoint !== currentScope.endpoint) return undefined;\n\tif (previousScope.identityKey !== currentScope.identityKey) return undefined;\n\treturn previousData;\n}\n\n/**\n * Cache-key segments for a table reference. A `TableModel.key`\n * (`schema.Name`) becomes `[Name, schema]`, a bare name `[Name]`. Tables in\n * different schemas get different entries, and a key built from a bare name is\n * a prefix of every schema's entry, so invalidating by name still reaches them.\n */\nexport function tableKeySegments(tableRef: string): readonly string[] {\n\tconst dot = tableRef.lastIndexOf('.');\n\treturn dot === -1 ? [tableRef] : [tableRef.slice(dot + 1), tableRef.slice(0, dot)];\n}\n\nexport const sheetsQueryKeys = {\n\troot: ['sheets'] as const,\n\tscope: (scope: SheetsScopeKey) => ['sheets', scope] as const,\n\tmeta: (scope: SheetsScopeKey) => [...sheetsQueryKeys.scope(scope), 'meta'] as const,\n\t/** One table model, per `_meta` version and display override. */\n\ttableModel: (scope: SheetsScopeKey, tableKey: string, metaVersion: number, displayKey: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'table-model', ...tableKeySegments(tableKey), metaVersion, displayKey] as const,\n\tmediaUrl: (scope: SheetsScopeKey, endpoint: string | undefined, id: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'media-url', endpoint, id] as const,\n\trelations: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'relations', ...tableKeySegments(tableName)] as const,\n\ttable: (scope: SheetsScopeKey, tableRef: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'table', ...tableKeySegments(tableRef)] as const,\n\ttableRows: (scope: SheetsScopeKey, tableRef: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'rows', options] as const,\n\ttableRow: (scope: SheetsScopeKey, tableRef: string, id: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'row', id] as const,\n\ttableCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>> | null) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'count', where] as const,\n\tinfiniteTable: (scope: SheetsScopeKey, tableRef: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'infinite-table', ...tableKeySegments(tableRef)] as const,\n\tinfiniteTablePage: (scope: SheetsScopeKey, tableRef: string, pageIndex: number, options: unknown) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableRef), 'page', pageIndex, options] as const,\n\tinfiniteTableTotalCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>>) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableRef), 'totalCount', where] as const,\n\tcursorTable: (scope: SheetsScopeKey, tableRef: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'cursor-table', ...tableKeySegments(tableRef), options] as const,\n} as const;\n\n/**\n * Mutation keys. Every mutation a Sheets hook creates sits under its table's\n * query key, `[...table(scope, tableRef), 'mutation', operation, ...detail]`, so\n * `useIsMutating({ mutationKey: sheetsMutationKeys.table(scope, ref) })` counts\n * every write in flight on that table.\n */\nexport const sheetsMutationKeys = {\n\t/** Every mutation of a table, or one operation of it when `operation` is given. */\n\ttable: (scope: SheetsScopeKey, tableRef: string, operation?: string, ...detail: readonly unknown[]) =>\n\t\toperation === undefined\n\t\t\t? ([...sheetsQueryKeys.table(scope, tableRef), 'mutation'] as const)\n\t\t\t: ([...sheetsQueryKeys.table(scope, tableRef), 'mutation', operation, ...detail] as const),\n} as const;\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","// 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","// 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","// 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","// 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","'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","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// 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/**\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","// 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 { 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","// 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","/**\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 * 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","/**\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","'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 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","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 * 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 * 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","/**\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// 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","// 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","// 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","/**\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","// 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","// 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,oBAAoB,WAAuC;AACnE,SAAO,MAAM,KAAK,UAAU,iBAA8B,kBAAkB,CAAC,EAAE;AAAA,IAC9E,CAAC,OAAO,GAAG,iBAAiB;AAAA,EAC7B;AACD;AAEO,SAAS,gBAAgB,EAAE,UAAU,UAAU,WAAW,WAAW,MAAM,GAAyB;AAC1G,QAAM,mBAAe,qBAAuB,IAAI;AAIhD,QAAM,CAAC,qBAAqB,QAAI,uBAAyB,MAAO,OAAO,aAAa,cAAc,OAAO,SAAS,aAAc;AAKhI,oCAAgB,MAAM;AACrB,QAAI,CAAC,aAAa,QAAS;AAE3B,UAAM,kBAAkB,oBAAoB,aAAa,OAAO;AAChE,QAAI,gBAAgB,SAAS,GAAG;AAC/B,sBAAgB,CAAC,EAAE,MAAM;AAAA,IAC1B,OAAO;AAEN,mBAAa,QAAQ,MAAM;AAAA,IAC5B;AAAA,EACD,GAAG,CAAC,CAAC;AAIL,8BAAU,MAAM;AACf,WAAO,MAAM;AACZ,UAAI,iCAAiC,eAAe,sBAAsB,aAAa;AACtF,8BAAsB,MAAM;AAAA,MAC7B;AAAA,IACD;AAAA,EACD,GAAG,CAAC,qBAAqB,CA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SAAS,IAAI;AAErB,MAAI,UAAU,QAAQ,UAAU,QAAW;AAC1C,UAAM,eAAe,sBAAsB,KAAK,CAAC,MAAM,EAAE,UAAU,UAAU,IAAI,CAAC;AAClF,QAAI,cAAc;AACjB,aAAO,YAAY,aAAa,OAAO,MAAM,UAAU,cAAc,GAAG,QAAQ;AAAA,IACjF;AACA,WAAO,YAAY,EAAE,MAAM,QAAQ,MAAM,IAAI,aAAa,IAAI,UAAU,MAAM,GAAG,QAAQ;AAAA,EAC1F;AAEA,QAAM,UAAU,sBAAsB,KAAK,CAAC,MAAM,EAAE,UAAU,UAAU,KAAK,CAAC;AAC9E,MAAI,SAAS;AACZ,WAAO,YAAY,QAAQ,OAAO,OAAO,UAAU,cAAc,GAAG,QAAQ;AAAA,EAC7E;AAEA,SAAO;AAAA,IACN;AAAA,MACC,MAAM;AAAA,MACN,MAAM;AAAA,MACN,aAAa,OAAO,KAAK;AAAA,MACzB,UAAU;AAAA,IACX;AAAA,IACA;AAAA,EACD;AACD;","names":["blocked","import_jsx_runtime","text","TIME_RE","today","DATE_RE","pad2","localDate","localTime","text","match","DATE_RE","TIME_RE","hours","minutes","seconds","fraction","zone","DATE_TIME_RE","text","parseAriaDate","import_react","import_jsx_runtime","text","shown","handleSave","handleCancel","import_react","column","text","column","import_react","import_jsx_runtime","add","handleSave","remove","handleCancel","input","import_jsx_runtime","column","import_react","import_jsx_runtime","import_jsx_runtime","module","column","import_react","import_lucide_react","import_react","import_lucide_react","import_react","import_react","active","active","import_button","import_jsx_runtime","React","import_react","React","import_react","import_jsx_runtime","React","import_jsx_runtime","import_jsx_runtime","column","import_react","import_react","import_lucide_react","import_button","import_react","import_react_query","import_data","import_data","import_graphql","import_data","import_data","present","query","data","url","idScalar","import_data","import_data","document","import_react","import_jsx_runtime","column","active","import_react","import_react_query","import_data","import_data","details","column","operator","import_data","file","details","import_data","details","column","column","column","resolveUrls","previewKey","details","file","import_data","column","import_react","column","column","loaded","import_react","import_lucide_react","import_react","active","import_jsx_runtime","active","import_lucide_react","import_react","import_react_query","loaders","resolve","query","import_jsx_runtime","details","import_react","column","active","import_react","import_jsx_runtime","import_jsx_runtime","column","import_jsx_runtime","column","import_react","import_jsx_runtime","handleSave","handleCancel","import_jsx_runtime","column","import_react","import_jsx_runtime","import_react","import_button","import_jsx_runtime","column","text","import_jsx_runtime","column","import_react","import_jsx_runtime","text","handleSave","handleCancel","import_jsx_runtime","column","import_react","import_button","import_jsx_runtime","seedText","text","column","import_react","pad2","text","import_jsx_runtime","column","import_react","import_react","import_lucide_react","import_button","import_react","import_button","import_input","import_label","column","column","column","column","import_jsx_runtime","import_react","import_lucide_react","import_badge","import_button","text","import_jsx_runtime","import_react","import_lucide_react","import_badge","import_button","import_input_group","import_jsx_runtime","active","import_jsx_runtime","create","import_react","import_react_query","text","column","invalid","text","column","import_react","operationIssue","column","reason","import_data","patch","column","import_react","column","text","import_react","import_react_query","pages","import_react","key","import_react","options","plan","import_jsx_runtime","import_jsx_runtime","DRAFT_PREFIX","import_react","import_lucide_react","import_button","import_jsx_runtime","column","active","import_react","import_button","import_jsx_runtime","text","import_react","import_button","import_jsx_runtime","import_jsx_runtime","column","import_react","import_lucide_react","import_button","import_input","text","import_jsx_runtime","import_jsx_runtime","column","import_react","import_button","import_jsx_runtime","size","column","text","canHandle","create","canHandle","create","text","canHandle","create","summary","display","column","canHandle","create","canHandle","create","DRAFT_PREFIX","canHandle","create","relationLinks","label","isRecord","end","display","text","size","summary","canHandle","create","canHandle","create","display","canHandle","create"]}
|