@constructive-io/sheets 0.11.0 → 0.13.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.
@@ -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/context/sheets-context.ts","../src/store/sheets-store.ts","../src/hooks/use-sheets-upload.ts","../src/hooks/use-sheets-meta.ts","../src/adapter/postgraphile-adapter.ts","../src/hooks/use-sheets-table.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/context/sheets-execute.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/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']);\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\n// Derive a date-only string from a calendar value (year/month/day) without any\n// UTC conversion. Pure and DOM-free so the write path is directly testable; it\n// mirrors handleSave's date-only serialization (local-midnight Date → local getters).\nexport function dateOnlyStringFromCalendarValue(dateValue: DateValueType | null): string {\n\tconst date = dateValueToDate(dateValue);\n\treturn date ? toLocalDateString(date) : '';\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:border-primary/60 focus:ring-2 focus:ring-primary/20'\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:border-primary/60 focus:ring-2 focus:ring-primary/20'\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-50')}\n\t\t\t\t\t>\n\t\t\t\t\t\t<TileLayer\n\t\t\t\t\t\t\tattribution='&copy; <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-50'\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 source (getImageUrl).\n// • recordId -> EditorProps.rowId.\n// • isDraftRow -> rowId startsWith 'draft:'.\n// • onSaveComplete -> onCommitPatch({ [colKey]: saveData.imageData }) (single field).\n// • onSubmitDraft -> onSubmitDraftRow(draftRowId) (mapped to a DraftSubmitResult).\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 { DraftSubmitResult } from '../../grid/draft-types';\nimport type { EditorProps } from './editor-props';\n\nconst DRAFT_PREFIX = 'draft:';\n\nexport function ImageEditorDom({\n\tvalue,\n\tcell,\n\tcolKey,\n\trowId,\n\ttableName,\n\tonCommitPatch,\n\tonCancel,\n\tonSubmitDraftRow,\n\tonInvalidateData,\n}: EditorProps) {\n\tconst isDraftRow = 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\t// Draft rows: persist first to obtain a real id. The editor expects a\n\t// DraftSubmitResult ({ createdRow }); EditorProps.onSubmitDraftRow resolves to\n\t// the raw server row, so wrap it into that shape.\n\tconst handleSubmitDraft = isDraftRow && onSubmitDraftRow\n\t\t? async (): Promise<DraftSubmitResult> => {\n\t\t\t\tconst createdRow = (await onSubmitDraftRow(rowId)) as DraftSubmitResult['createdRow'];\n\t\t\t\treturn { createdRow };\n\t\t\t}\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={rowId}\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 { useSheetsContext } from '../../context/sheets-context';\nimport { useSheetsStoreApi } from '../../store/sheets-store';\nimport {\n\tuseSheetsFieldUpload,\n\texecuteFieldUpload,\n\ttype UploadProgress,\n\ttype UploadResponse,\n} from '../../hooks/use-sheets-upload';\nimport { formatFileSize, getImageMetadata, getImageUrl } 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';\n\n/** Data passed to onSaveComplete for optimistic updates */\nexport interface ImageSaveData {\n imageData: {\n url: string;\n filename?: string;\n size?: number;\n mime?: string;\n } | null;\n}\n\ntype UploadState = 'idle' | 'submitting-draft' | 'uploading';\n\ninterface NormalizedImageData {\n url: string;\n filename: string;\n size: number;\n mime: string;\n}\n\nfunction normalizeUploadResponse(data: UploadResponse): NormalizedImageData {\n return { url: data.url, filename: data.filename, size: data.size, mime: data.mime };\n}\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-all 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 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 {(size || hasMime) && (\n <p className='text-muted-foreground mt-0.5 text-xs'>\n {size ? formatFileSize(size) : null}\n {size && 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?: string | number;\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 { config } = useSheetsContext();\n const storeApi = useSheetsStoreApi();\n const { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);\n\n const getToken = useMemo(() => {\n if (config.auth.mode === 'embedded') return config.auth.getToken;\n return () => storeApi.getState().accessToken;\n }, [config.auth, storeApi]);\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<string | number | 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 isBusy = uploadState !== 'idle';\n\n const imageUrl = useMemo(() => getImageUrl(imageValue), [imageValue]);\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 // 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 const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === 'error';\n const hasImage = imageUrl != null && !imageLoadFailed && storedIsImage;\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 handleUploadSuccess = useCallback((data: UploadResponse) => {\n const normalized = normalizeUploadResponse(data);\n resetFileState();\n setImageValue(normalized);\n onSaveComplete?.({ imageData: normalized });\n onFinishedEditing();\n toast.success({ message: `${Noun} uploaded successfully` });\n }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);\n\n // Existing-row upload failure: keep the editor open with the staged file\n // retained so the user can retry or cancel, surface the real error message\n // (canonical error messages pass through), and log at error level. Mirrors the\n // draft-row catch UX — never closes the editor on failure.\n const handleUploadError = useCallback((error: Error) => {\n setUploadState('idle');\n sheetsLogger().error('[image-editor] upload failed:', error);\n toast.error({ message: error.message || 'Upload failed' });\n }, []);\n\n const uploadMutation = useSheetsFieldUpload(tableName || '', fieldName || '', recordId || '', {\n onProgress: setUploadProgress,\n onSuccess: handleUploadSuccess,\n onError: handleUploadError,\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 (!tableName || !fieldName || !selectedFile) return;\n\n // A draft that was already persisted server-side (its upload failed earlier).\n // Retry against the real id directly — the draft is gone, so re-submitting\n // it via onSubmitDraft() would fail. Keep the selected file on failure so\n // the user can retry again.\n const committedId = committedRecordIdRef.current ?? recordId;\n if (committedRecordIdRef.current != null) {\n try {\n toast.info({ message: `Uploading ${noun}...` });\n setUploadState('uploading');\n\n const uploadResult = await executeFieldUpload(\n tableName, fieldName, committedRecordIdRef.current, selectedFile,\n config.endpoint, getToken, undefined, { onAuthError: config.onAuthError },\n );\n\n const normalized = normalizeUploadResponse(uploadResult);\n resetFileState();\n setImageValue(normalized);\n onDraftUploadComplete?.();\n toast.success({ message: `${Noun} uploaded successfully` });\n onFinishedEditing();\n } catch (error) {\n // Real row already exists — surface it to the host and keep the file\n // selected so the upload can be retried without rebuilding the row.\n onDraftUploadComplete?.();\n setUploadState('idle');\n toast.error({ message: error instanceof Error ? error.message : 'Upload failed' });\n }\n return;\n }\n\n if (isDraftRow) {\n if (!onSubmitDraft) {\n toast.error({ message: 'Cannot upload to draft row - save the row first' });\n return;\n }\n\n try {\n toast.info({ message: 'Creating row...' });\n setUploadState('submitting-draft');\n\n const result = await onSubmitDraft();\n\t\tconst createdId = result.createdRow?.id;\n\t\tif (typeof createdId !== 'string' && typeof createdId !== 'number') {\n\t\t\tthrow new Error('Image uploads require a scalar id primary key.');\n\t\t}\n\n // Row is now persisted and the draft has been removed from the store.\n // From here on, treat it as a real row: any retry must hit this id.\n\t\tcommittedRecordIdRef.current = createdId;\n\n toast.info({ message: `Uploading ${noun}...` });\n setUploadState('uploading');\n\n const uploadResult = await executeFieldUpload(\n\t\t\ttableName, fieldName, createdId, selectedFile,\n config.endpoint, getToken, undefined, { onAuthError: config.onAuthError },\n );\n\n const normalized = normalizeUploadResponse(uploadResult);\n resetFileState();\n setImageValue(normalized);\n onDraftUploadComplete?.();\n toast.success({ message: `Row created and ${noun} uploaded` });\n onFinishedEditing();\n } catch (error) {\n // The row was persisted (draft removed) but the upload failed, leaving\n // a real row with no image. Notify the host so the now-real row appears,\n // and keep the selected file so the user can retry immediately.\n onDraftUploadComplete?.();\n setUploadState('idle');\n toast.error({ message: error instanceof Error ? error.message : 'Upload failed' });\n }\n return;\n }\n\n if (!committedId) {\n toast.error({ message: 'Missing record context for upload' });\n return;\n }\n setUploadState('uploading');\n uploadMutation.mutate(selectedFile);\n }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);\n\n // --- Save / Cancel -----------------------------------------------------\n\n const handleSave = useCallback(() => {\n if (!imageValue) {\n onFinishedEditing(null);\n return;\n }\n\n const url = getImageUrl(imageValue);\n const originalUrl = getImageUrl(value);\n\n // Nothing changed — close without triggering mutation\n if (url && originalUrl === url) {\n onFinishedEditing();\n return;\n }\n\n onFinishedEditing(url ?? value);\n }, [imageValue, value, onFinishedEditing]);\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 handleSave();\n }\n }, [handleSave]);\n\n // --- Dropzone content --------------------------------------------------\n\n // A stored non-image file (any-file mode) renders as a chip, not a thumbnail.\n const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;\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 className='text-sm'>{isSubmittingDraft ? 'Creating row...' : `Uploading ${noun}...`}</p>\n {isUploading && uploadProgress && (\n <div className='mt-3 w-full max-w-xs'>\n <div className='bg-muted h-1.5 overflow-hidden rounded-full'>\n <div\n className='bg-primary h-1.5 rounded-full transition-all duration-300'\n style={{ width: `${uploadProgress.percentage}%` }}\n />\n </div>\n <p className='text-muted-foreground mt-1.5 text-center text-xs'>\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 const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith('image/') ?? false);\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} 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 {imageUrl && (\n <p\n className='text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50'\n title={imageUrl}\n >\n {imageUrl}\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 : isUploading\n ? 'Uploading...'\n : imageUrl\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'>{imageUrl ? `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 || (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 {isDraftRow ? '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 { 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 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/** Optional upload settings. `bucketKey` defaults to \"public\". */\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\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 { 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","/**\n * Field-Specific Upload Hook\n * Provides upload functionality that integrates with the existing dynamic mutation system\n * Works with backend's field-specific upload pattern: <fieldName>Upload fields\n *\n * Ported from apps/admin use-image-upload.ts with context injection.\n */\n\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\n\nimport { cleanTable, type CleanTable, type MetaTable } from '@constructive-io/data';\nimport { useSheetsMeta } from './use-sheets-meta';\nimport {\n\ttoCamelCaseSingular,\n\ttoPatchFieldName,\n\ttoUpdateInputTypeName,\n\ttoUpdateMutationName,\n} from '@constructive-io/data';\n\nimport { useSheetsContext } from '../context/sheets-context';\nimport type { SheetsScopeKey, SheetsConfig } from '../context/sheets-context';\nimport {\n\tcreateSheetsExecute,\n\tcreateSheetsUpload,\n\ttype SheetsExecuteFn,\n\ttype SheetsUploadFn,\n} from '../context/sheets-execute';\nimport { sheetsTableQueryKeys } from './use-sheets-table';\nimport { useSheetsStoreApi } from '../store/sheets-store';\n\n/**\n * Upload progress callback type\n */\nexport interface UploadProgress {\n\tloaded: number;\n\ttotal: number;\n\tpercentage: number;\n}\n\n/**\n * Upload response from backend\n */\nexport interface UploadResponse {\n\turl: string;\n\tfilename: string;\n\tmime: string;\n\tsize: number;\n}\n\n/**\n * Field upload options\n */\nexport interface UseFieldUploadOptions {\n\tonProgress?: (progress: UploadProgress) => void;\n\tonSuccess?: (data: UploadResponse) => void;\n\tonError?: (error: Error) => void;\n\tshowToast?: boolean; // default true\n\tsuccessMessage?: string; // custom success message\n\tsuccessToastDelayMs?: number; // optional delay for success toast\n}\n\ninterface UploadNaming {\n\tmutationName: string;\n\tsingularName: string;\n\tpatchFieldName: string;\n\tupdateInputTypeName: string;\n}\n\ninterface ExecuteFieldUploadOptions {\n\tonAuthError?: () => void;\n\t/**\n\t * Transport seam. When the hooks call this, they thread the context\n\t * `execute`/`executeUpload` here so injected/mock implementations intercept\n\t * both steps. When omitted (e.g. image-editor's direct retry path), the\n\t * functions are built from `endpoint`/`getToken`/`onAuthError` via the same\n\t * factories — never a raw fetch.\n\t */\n\texecute?: SheetsExecuteFn;\n\texecuteUpload?: SheetsUploadFn;\n\tonProgress?: (progress: UploadProgress) => void;\n}\n\nfunction resolveUploadNaming(tableName: string, table?: CleanTable | null): UploadNaming {\n\treturn {\n\t\tmutationName: toUpdateMutationName(tableName, table),\n\t\tsingularName: toCamelCaseSingular(tableName, table),\n\t\tpatchFieldName: toPatchFieldName(tableName, table),\n\t\tupdateInputTypeName: toUpdateInputTypeName(tableName),\n\t};\n}\n\ninterface PatchMutationResult {\n\t[mutationName: string]: { [singular: string]: Record<string, unknown> } | undefined;\n}\n\n/**\n * Build the transport seam for an upload. When the caller injects\n * `execute`/`executeUpload` (the hooks pass the context functions), those are\n * used verbatim so consumer/mock implementations intercept both steps.\n * Otherwise the same factories that back the provider are used, sourced from\n * `endpoint`/`getToken`/`onAuthError` — guaranteeing canonical error normalization\n * and onAuthError without any raw fetch in this module.\n */\nfunction resolveTransport(\n\tendpoint: string,\n\tgetToken: () => string | null,\n\toptions?: ExecuteFieldUploadOptions,\n): { execute: SheetsExecuteFn; executeUpload: SheetsUploadFn } {\n\tif (options?.execute && options?.executeUpload) {\n\t\treturn { execute: options.execute, executeUpload: options.executeUpload };\n\t}\n\tconst config: SheetsConfig = {\n\t\tendpoint,\n\t\tauth: { mode: 'standalone' },\n\t\tonAuthError: options?.onAuthError,\n\t};\n\treturn {\n\t\texecute: createSheetsExecute(config, getToken),\n\t\texecuteUpload: createSheetsUpload(config, getToken),\n\t};\n}\n\n/**\n * Execute field upload using two sequential requests, both routed through the\n * injectable transport seam:\n * 1. File upload via `executeUpload` → returns file metadata\n * 2. GraphQL mutation via `execute` to patch the row with the upload result\n *\n * Exported for direct use when record ID is known at call time (e.g., after draft submission)\n *\n * @param tableName - Table name\n * @param fieldName - Field name for the upload (the actual DB column, e.g. \"photo\")\n * @param recordId - Record ID to update\n * @param file - File to upload\n * @param endpoint - GraphQL endpoint URL (used to build the seam when none injected)\n * @param getToken - Function that returns the current auth token (or null)\n * @param naming - Optional pre-resolved naming overrides\n * @param options - Auth callback + optional injected execute/executeUpload + progress\n */\nexport async function executeFieldUpload(\n\ttableName: string,\n\tfieldName: string,\n\trecordId: string | number,\n\tfile: File,\n\tendpoint: string,\n\tgetToken: () => string | null,\n\tnaming?: UploadNaming,\n\toptions?: ExecuteFieldUploadOptions,\n): Promise<UploadResponse> {\n\t// Validate endpoint (only meaningful for the factory-built seam path)\n\tif (!endpoint && !(options?.execute && options?.executeUpload)) {\n\t\tthrow new Error('No endpoint configured. Select a database API or use Direct Connect.');\n\t}\n\n\tconst { execute, executeUpload } = resolveTransport(endpoint, getToken, options);\n\n\t// ── Step 1: Upload file through the executeUpload seam ──\n\t// Field/row metadata + progress flow as the third arg so injected\n\t// implementations can use them; the default REST transport ignores them.\n\tconst uploadResult = await executeUpload(file, undefined, {\n\t\ttableName,\n\t\tfieldName,\n\t\trecordId,\n\t\tonProgress: options?.onProgress,\n\t});\n\n\t// ── Step 2: Patch the row with the upload result via the execute seam ──\n\tconst resolvedNaming = naming ?? resolveUploadNaming(tableName);\n\n\t// Sanitize upload result — only pass fields the DB schema expects.\n\t// For jsonb columns (image/upload domains): { url, filename, mime, size }\n\t// For text columns (attachment domain): just the URL string.\n\tconst patchValue = {\n\t\t...(uploadResult.url != null && { url: uploadResult.url }),\n\t\t...(uploadResult.filename != null && { filename: uploadResult.filename }),\n\t\t...(uploadResult.mime != null && { mime: uploadResult.mime }),\n\t\t...(uploadResult.size != null && { size: uploadResult.size }),\n\t};\n\n\tconst mutationString = `\n\t\tmutation ${resolvedNaming.mutationName}Mutation($input: ${resolvedNaming.updateInputTypeName}!) {\n\t\t\t${resolvedNaming.mutationName}(input: $input) {\n\t\t\t\t${resolvedNaming.singularName} {\n\t\t\t\t\tid\n\t\t\t\t\t${fieldName}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`.trim();\n\n\t// execute() normalizes auth/forbidden/GraphQL errors to ConstructiveError and fires\n\t// onAuthError on 401/UNAUTHENTICATED — no manual equivalent needed here.\n\tconst result = await execute<PatchMutationResult>(mutationString, {\n\t\tinput: {\n\t\t\tid: recordId,\n\t\t\t[resolvedNaming.patchFieldName]: {\n\t\t\t\t[fieldName]: patchValue,\n\t\t\t},\n\t\t},\n\t});\n\n\t// Extract the updated record from PostGraphile response\n\tconst updatedRecord = result?.[resolvedNaming.mutationName]?.[resolvedNaming.singularName] as\n\t\t| Record<string, unknown>\n\t\t| undefined;\n\n\tif (!updatedRecord) {\n\t\tthrow new Error('Upload succeeded but no data returned from patch');\n\t}\n\n\t// Extract the uploaded file data from the updated record. jsonb columns\n\t// (image/upload domains) return an object; text columns (attachment domain)\n\t// return a plain URL string.\n\tconst uploadedFileData = updatedRecord[fieldName];\n\tif (!uploadedFileData) {\n\t\tthrow new Error(`Upload succeeded but ${fieldName} field not found in response`);\n\t}\n\n\tconst fileObject =\n\t\ttypeof uploadedFileData === 'object' ? (uploadedFileData as Record<string, unknown>) : null;\n\n\t// Return standardized upload response\n\treturn {\n\t\turl: (fileObject?.url as string) || (uploadedFileData as string),\n\t\tfilename: (fileObject?.filename as string) || file.name,\n\t\tmime: (fileObject?.mime as string) || file.type,\n\t\tsize: (fileObject?.size as number) || file.size,\n\t};\n}\n\n/**\n * Hook for uploading files to specific table fields\n * Integrates with the existing dynamic mutation system\n */\nexport function useSheetsFieldUpload(\n\ttableName: string,\n\tfieldName: string,\n\trecordId: string | number,\n\toptions: UseFieldUploadOptions = {},\n) {\n\tconst queryClient = useQueryClient();\n\tconst { scopeKey, config, execute, executeUpload } = useSheetsContext();\n\tconst storeApi = useSheetsStoreApi();\n\tconst { data: meta } = useSheetsMeta();\n\tconst table = useMemo<CleanTable | null>(() => {\n\t\tif (!meta?._meta?.tables) return null;\n\t\tconst candidate = meta._meta.tables.find((item) => item?.name === tableName) as MetaTable | undefined;\n\t\treturn candidate ? cleanTable(candidate) : null;\n\t}, [meta, tableName]);\n\tconst resolvedNaming = useMemo(() => resolveUploadNaming(tableName, table), [tableName, table]);\n\n\t// Build a stable getToken from context\n\tconst getToken = useMemo(() => {\n\t\tif (config.auth.mode === 'embedded') {\n\t\t\treturn config.auth.getToken;\n\t\t}\n\t\treturn () => storeApi.getState().accessToken;\n\t}, [config.auth, storeApi]);\n\n\t// Keep latest params in refs to avoid stale closures\n\tconst tableRef = useRef(tableName);\n\tconst fieldRef = useRef(fieldName);\n\tconst idRef = useRef(recordId);\n\n\tuseEffect(() => {\n\t\ttableRef.current = tableName;\n\t\tfieldRef.current = fieldName;\n\t\tidRef.current = recordId;\n\t}, [tableName, fieldName, recordId]);\n\n\treturn useMutation<UploadResponse, Error, File>({\n\t\tmutationKey: ['sheets', scopeKey, 'field-upload', tableName, fieldName, recordId],\n\t\tmutationFn: async (file: File) => {\n\t\t\t// Route both steps through the context seam so injected/mock\n\t\t\t// execute/executeUpload intercept the upload.\n\t\t\treturn executeFieldUpload(\n\t\t\t\ttableRef.current,\n\t\t\t\tfieldRef.current,\n\t\t\t\tidRef.current,\n\t\t\t\tfile,\n\t\t\t\tconfig.endpoint,\n\t\t\t\tgetToken,\n\t\t\t\tresolvedNaming,\n\t\t\t\t{ onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress },\n\t\t\t);\n\t\t},\n\t\tonSuccess: (data) => {\n\t\t\t// First allow callers to react (e.g., close overlay)\n\t\t\toptions.onSuccess?.(data);\n\t\t\t// Invalidate related queries to refresh data\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });\n\t\t},\n\t\tonError: (error) => {\n\t\t\toptions.onError?.(error);\n\t\t},\n\t});\n}\n\n/**\n * Hook for uploading images with validation\n * Convenience wrapper around useSheetsFieldUpload with image-specific validation\n */\nexport function useSheetsImageUpload(\n\ttableName: string,\n\tfieldName: string,\n\trecordId: string | number,\n\toptions: UseFieldUploadOptions = {},\n) {\n\tconst queryClient = useQueryClient();\n\tconst { scopeKey, config, execute, executeUpload } = useSheetsContext();\n\tconst storeApi = useSheetsStoreApi();\n\tconst { data: meta } = useSheetsMeta();\n\tconst table = useMemo<CleanTable | null>(() => {\n\t\tif (!meta?._meta?.tables) return null;\n\t\tconst candidate = meta._meta.tables.find((item) => item?.name === tableName) as MetaTable | undefined;\n\t\treturn candidate ? cleanTable(candidate) : null;\n\t}, [meta, tableName]);\n\tconst resolvedNaming = useMemo(() => resolveUploadNaming(tableName, table), [tableName, table]);\n\n\t// Build a stable getToken from context\n\tconst getToken = useMemo(() => {\n\t\tif (config.auth.mode === 'embedded') {\n\t\t\treturn config.auth.getToken;\n\t\t}\n\t\treturn () => storeApi.getState().accessToken;\n\t}, [config.auth, storeApi]);\n\n\t// Keep latest params in refs to avoid stale closures\n\tconst tableRef = useRef(tableName);\n\tconst fieldRef = useRef(fieldName);\n\tconst idRef = useRef(recordId);\n\n\tuseEffect(() => {\n\t\ttableRef.current = tableName;\n\t\tfieldRef.current = fieldName;\n\t\tidRef.current = recordId;\n\t}, [tableName, fieldName, recordId]);\n\n\treturn useMutation<UploadResponse, Error, File>({\n\t\tmutationKey: ['sheets', scopeKey, 'image-upload', tableName, fieldName, recordId],\n\t\tmutationFn: async (file: File) => {\n\t\t\t// Validate file type\n\t\t\tif (!file.type.startsWith('image/')) {\n\t\t\t\tthrow new Error('Please select an image file');\n\t\t\t}\n\n\t\t\t// Validate file size (10MB limit)\n\t\t\tconst maxSize = 10 * 1024 * 1024; // 10MB\n\t\t\tif (file.size > maxSize) {\n\t\t\t\tthrow new Error('File size must be less than 10MB');\n\t\t\t}\n\n\t\t\t// Route both steps through the context seam so injected/mock\n\t\t\t// execute/executeUpload intercept the upload.\n\t\t\treturn executeFieldUpload(\n\t\t\t\ttableRef.current,\n\t\t\t\tfieldRef.current,\n\t\t\t\tidRef.current,\n\t\t\t\tfile,\n\t\t\t\tconfig.endpoint,\n\t\t\t\tgetToken,\n\t\t\t\tresolvedNaming,\n\t\t\t\t{ onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress },\n\t\t\t);\n\t\t},\n\t\tonSuccess: (data) => {\n\t\t\t// First allow callers to react (e.g., close overlay)\n\t\t\toptions.onSuccess?.(data);\n\n\t\t\t// Invalidate related queries to refresh data\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });\n\t\t},\n\t\tonError: (error) => {\n\t\t\toptions.onError?.(error);\n\t\t},\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 {\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\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 doc = buildPostGraphileUpdate(table, allTables, {\n\t\t\t\t...options,\n\t\t\t\tfieldSelection: options.fieldSelection || 'display',\n\t\t\t});\n\t\t\tconst patchFieldName = toPatchFieldName(tableName, table);\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 mutationName = toUpdateMutationName(tableName, table);\n\t\t\tconst singularName = toCamelCaseSingular(tableName, table);\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","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\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 type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { ConstructiveError, createError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig } from './sheets-context';\nimport {\n\tcallUploadOp,\n\tdiscoverUploadCapability,\n\tfetchDownloadUrl,\n\tpresignedPut,\n\tsha256HexFromBuffer,\n} from './sheets-upload-presigned';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;\n\nexport type SheetsExecuteFn = <T = unknown>(\n\tdocument: ExecutableDocument,\n\tvariables?: Record<string, unknown>,\n) => Promise<T>;\n\n/**\n * Result of an upload through the seam. `url` is the only guaranteed field;\n * the REST upload endpoint also returns `{ filename, mime, size }` (and may\n * return server-internal extras). Keeping it open-ended lets callers read the\n * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.\n */\nexport type SheetsUploadResult = { url: string } & Record<string, unknown>;\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\ninterface GraphQLResponseError {\n\tmessage: string;\n\textensions?: { code?: string };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: GraphQLResponseError[];\n}\n\nfunction hasAuthMessage(message: string | undefined): boolean {\n\tconst normalized = String(message ?? '').toLowerCase();\n\treturn (\n\t\tnormalized.includes('unauthenticated') ||\n\t\tnormalized.includes('unauthorized') ||\n\t\tnormalized.includes('authentication')\n\t);\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): ConstructiveError | null {\n\tif (!response.errors?.length) return null;\n\n\tconst error = response.errors[0];\n\tconst code = error.extensions?.code;\n\tconst message = error.message || 'GraphQL query failed';\n\n\tif (code === 'UNAUTHENTICATED' || hasAuthMessage(message)) {\n\t\tonAuthError?.();\n\t\treturn createError.unauthorized('Authentication required. Please log in again.');\n\t}\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): 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});\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\tthrow createError.forbidden('You do not have permission to perform this action.');\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();\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tthrow createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);\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\tthrow graphqlError;\n\t\t}\n\n\t\treturn result.data as T;\n\t};\n}\n\n/**\n * Presigned-URL cell-upload seam.\n *\n * Replaces the legacy multipart `<endpoint>/upload` POST entirely. The flow:\n * 1. Read + SHA-256 hash the file bytes (Web Crypto)\n * 2. Discover (cached per endpoint) the upload op + downloadUrl-by-id field\n * via GraphQL introspection — the root `upload<Type>File` mutation, matched\n * by FIELD/TYPE SHAPE (LOCKED: no hardcoded names)\n * 3. Call the upload op with input `{ bucketKey, contentHash, contentType,\n * size, filename }` — NO `ownerId` (app-scoped buckets have no owner_id)\n * 4. If `uploadUrl` is non-null, PUT the raw bytes to it with ONLY the signed\n * `Content-Type` header (NO Authorization). Skipped when `deduplicated`.\n * 5. Resolve the stable public `downloadUrl` for the returned fileId.\n *\n * Returns `{ url, filename, mime, size, key, fileId }` where `url` is the stable\n * download URL — the same cell value shape callers/Step-2 already consume.\n *\n * `path` is ignored (content-addressed buckets key on `contentHash`).\n */\nexport function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\t// Reuse the kept GraphQL executor so canonical error normalization + onAuthError\n\t// (401/UNAUTHENTICATED) apply to introspection, the upload op, and the\n\t// downloadUrl query alike.\n\tconst execute = config.execute ?? createSheetsExecute(config, getToken);\n\n\treturn async (file: File, _path?: string, options?: SheetsUploadOptions): Promise<SheetsUploadResult> => {\n\t\tif (!config.endpoint) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst bucketKey = config.upload?.bucketKey ?? 'public';\n\t\tconst contentType = file.type || 'application/octet-stream';\n\n\t\t// Single read of the bytes — reused for both hashing and the PUT body.\n\t\tconst buffer = await file.arrayBuffer();\n\t\tconst contentHash = await sha256HexFromBuffer(buffer);\n\n\t\tconst cap = await discoverUploadCapability(config.endpoint, execute);\n\n\t\tconst payload = await callUploadOp(execute, cap, {\n\t\t\tbucketKey,\n\t\t\tcontentHash,\n\t\t\tcontentType,\n\t\t\tsize: file.size,\n\t\t\tfilename: file.name,\n\t\t});\n\n\t\t// Dedup (deduplicated ⇒ uploadUrl === null) means the row + S3 object already\n\t\t// exist; skip the PUT. A non-deduplicated payload MUST carry an uploadUrl — a\n\t\t// null there is a server-contract violation, so fail loudly rather than\n\t\t// resolving a downloadUrl for an object that was never uploaded.\n\t\tif (!payload.deduplicated) {\n\t\t\tif (!payload.uploadUrl) {\n\t\t\t\tthrow createError.badRequest('Upload failed: server returned no uploadUrl for a non-deduplicated file.');\n\t\t\t}\n\t\t\tawait presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);\n\t\t} else {\n\t\t\toptions?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });\n\t\t}\n\n\t\tconst url = await fetchDownloadUrl(execute, cap, payload.fileId);\n\n\t\treturn {\n\t\t\turl,\n\t\t\tfilename: file.name,\n\t\t\tmime: file.type,\n\t\t\tsize: file.size,\n\t\t\tkey: payload.key,\n\t\t\tfileId: payload.fileId,\n\t\t};\n\t};\n}\n\nexport { ConstructiveError } from '@constructive-io/data';\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. Resolve the stable public `downloadUrl` for the fileId\n *\n * `confirmUpload` is intentionally skipped: the backend plugin creates the file\n * row inside the upload op, so `downloadUrl` resolves immediately.\n *\n * The upload op is discovered via runtime introspection, matched by FIELD/TYPE\n * SHAPE (never a hardcoded name): a root mutation `upload<Type>File(input: {...})`\n * whose input + payload carry the upload shape.\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 { SheetsExecuteFn } 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\t/** Query field used to resolve the stable 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}\n\ninterface UploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\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\nconst capabilityCache = new Map<string, Promise<UploadCapability>>();\n\n/** Test-only: clear the per-endpoint capability cache between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache.clear();\n}\n\n/**\n * Discover the upload op + downloadUrl-by-id field for an endpoint, by shape.\n * Cached per `endpoint`; concurrent uploads share one in-flight introspection.\n */\nexport function discoverUploadCapability(endpoint: string, execute: SheetsExecuteFn): Promise<UploadCapability> {\n\tconst cached = capabilityCache.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 resolveUploadCapability(schema);\n\t})();\n\n\t// Don't cache a rejected discovery — let the next attempt retry.\n\tpromise.catch(() => capabilityCache.delete(endpoint));\n\tcapabilityCache.set(endpoint, promise);\n\treturn promise;\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, never by a literal name.\n */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\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', '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: Pick<UploadCapability, 'uploadFieldName' | 'inputTypeName'> | 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\tinputHasFields(inputTypeName, INPUT_FIELDS) &&\n\t\t\tobjectHasFields(payloadTypeName, PAYLOAD_FIELDS)\n\t\t) {\n\t\t\tupload = { uploadFieldName: field.name, inputTypeName: inputTypeName as string };\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!upload) {\n\t\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n\t}\n\n\t// --- File object type + by-id field for downloadUrl ---\n\tconst downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);\n\n\treturn {\n\t\t...upload,\n\t\t...downloadById,\n\t};\n}\n\ntype DownloadByIdResult = Omit<UploadCapability, 'uploadFieldName' | 'inputTypeName'>;\n\nfunction resolveDownloadByIdField(\n\tschema: IntrospectionSchema,\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tuploadFieldName: string,\n): DownloadByIdResult {\n\t// The file object type carries a `downloadUrl` field (grounded on\n\t// download-url-field.ts which adds `downloadUrl: String` to @storageFiles).\n\tconst fileTypesWithDownloadUrl = 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\tfileTypesWithDownloadUrl.add(t.name);\n\t\t}\n\t}\n\n\t// 1. Prefer the 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\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\treturn {\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}\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, uploadFieldName);\n\tif (connection) return 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 preferred = uploadFieldName.replace(/^upload/, '');\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\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n}\n\n/**\n * Discover a filtered-connection downloadUrl-by-id path. Returns null if the\n * schema exposes no such connection. 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\tuploadFieldName: string,\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\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 = EQUALITY_OPERATORS.map((op) =>\n\t\t\t\t\tidFieldType.inputFields!.find((f) => f.name === op),\n\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});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// id field is an input object but with no recognized equality op — skip.\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 (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});\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\tconst preferred = uploadFieldName.replace(/^upload/, '');\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}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, UploadPayload | null>>(mutation, {\n\t\tinput: {\n\t\t\tbucketKey: 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\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 */\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 (error) {\n\t\tthrow createError.network(error instanceof Error ? error : undefined);\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(createError.network()));\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 the stable public download URL for a file id via the discovered\n * by-id field. For public files the backend returns a permanent public URL\n * (its exact path shape is the backend's concern) — stored opaquely in the cell.\n */\nexport async function fetchDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\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}, 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/**\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 once per endpoint (cached)\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 cap = await discoverUploadCapability(endpoint, execute);\n\t\treturn await fetchDownloadUrl(execute, cap, fileId);\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// 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: (obj.size as number) || (obj.fileSize as number) || 0,\n\t\tmime: (obj.mime as string) || (obj.type as string) || (obj.contentType as string) || 'unknown',\n\t\turl: getImageUrl(imageValue) || '',\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 [status, setStatus] = useState<ImageStatus>('idle');\n\n\tuseEffect(() => {\n\t\tif (!src) return setStatus('idle');\n\n\t\tsetStatus('loading');\n\t\tconst img = new Image();\n\t\timg.src = src;\n\n\t\tconst onLoad = () => setStatus('loaded');\n\t\tconst onError = () => setStatus('error');\n\n\t\timg.addEventListener('load', onLoad);\n\t\timg.addEventListener('error', onError);\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\treturn status;\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 <img src={currentSrc!} alt={alt} className={cn('object-cover', className)} {...imgProps} />;\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:border-primary/60 focus:ring-2 focus:ring-primary/20'\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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\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-50',\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-primary')}>\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 { 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-primary';\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-primary 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-primary 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\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//\n// Ports v1 `ImageCellFactory` (grid/cell-content-factory.ts). The glide cell put\n// the resolved URL in BOTH `data` and `displayData` as a single-element array\n// (`[url]`); empty/null/'' collapses to `['']`. The neutral SheetsCell keeps the\n// SAME `data: [url]` array (so copyText === JSON.stringify([url]) like glide) and\n// sets `displayData` to the STRING form of that array (JSON.stringify) so the\n// `image` kind — projected via stringifyField, NOT the geometry/custom branch —\n// yields the SAME displayText glide produced from its array `displayData`.\n//\n// URL extraction logic copied verbatim (NOT imported from cell-content-factory,\n// which 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 { MEDIA_TYPES } from '../../cell-types/cell-type-groups';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\n/** Resolve a media URL from a string or an object's url/src/href/path keys (v1 order). */\nfunction resolveMediaUrl(value: unknown): string {\n\tif (typeof value === 'string') return value;\n\tif (typeof value === 'object' && value) {\n\t\tconst obj = value as Record<string, unknown>;\n\t\treturn (obj.url || obj.src || obj.href || obj.path || '') as string;\n\t}\n\treturn '';\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 url = value === null || value === undefined || value === '' ? '' : resolveMediaUrl(value);\n\t\tconst data = [url];\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,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,sBAAsB,mBAAmB,eAAe,sBAAsB,QAAQ,aAAa;AACtG,8BAAsB,QAAQ,MAAM;AAAA,MACrC;AAAA,IACD;AAAA,EACD,GAAG,CAAC,CAAC;AAGL,QAAM,oBAAgB;AAAA,IACrB,CAAC,MAA2B;AAE3B,kBAAY,CAAC;AAEb,UAAI,EAAE,QAAQ,UAAU;AACvB,UAAE,eAAe;AACjB,UAAE,gBAAgB;AAClB,mBAAW;AACX;AAAA,MACD;AAEA,UAAI,EAAE,QAAQ,MAAO;AAErB,YAAM,YAAY,aAAa;AAC/B,UAAI,CAAC,UAAW;AAEhB,YAAM,oBAAoB,oBAAoB,SAAS;AACvD,UAAI,kBA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,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","import_react","useZustandStore","import_react","import_react_query","import_data","import_react_query","import_data","import_react","import_data","import_data","import_data","totalCount","data","import_data","import_graphql","import_data","import_data","query","data","url","idScalar","import_data","document","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_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/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/context/sheets-context.ts","../src/store/sheets-store.ts","../src/hooks/use-sheets-upload.ts","../src/hooks/use-sheets-meta.ts","../src/adapter/postgraphile-adapter.ts","../src/hooks/use-sheets-table.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/context/sheets-execute.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/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']);\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='&copy; <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 source (getImageUrl).\n// • recordId -> EditorProps.rowId.\n// • isDraftRow -> rowId startsWith 'draft:'.\n// • onSaveComplete -> onCommitPatch({ [colKey]: saveData.imageData }) (single field).\n// • onSubmitDraft -> onSubmitDraftRow(draftRowId) (mapped to a DraftSubmitResult).\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 { DraftSubmitResult } from '../../grid/draft-types';\nimport type { EditorProps } from './editor-props';\n\nconst DRAFT_PREFIX = 'draft:';\n\nexport function ImageEditorDom({\n\tvalue,\n\tcell,\n\tcolKey,\n\trowId,\n\ttableName,\n\tonCommitPatch,\n\tonCancel,\n\tonSubmitDraftRow,\n\tonInvalidateData,\n}: EditorProps) {\n\tconst isDraftRow = 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\t// Draft rows: persist first to obtain a real id. The editor expects a\n\t// DraftSubmitResult ({ createdRow }); EditorProps.onSubmitDraftRow resolves to\n\t// the raw server row, so wrap it into that shape.\n\tconst handleSubmitDraft = isDraftRow && onSubmitDraftRow\n\t\t? async (): Promise<DraftSubmitResult> => {\n\t\t\t\tconst createdRow = (await onSubmitDraftRow(rowId)) as DraftSubmitResult['createdRow'];\n\t\t\t\treturn { createdRow };\n\t\t\t}\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={rowId}\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 { useSheetsContext } from '../../context/sheets-context';\nimport { useSheetsStoreApi } from '../../store/sheets-store';\nimport {\n\tuseSheetsFieldUpload,\n\texecuteFieldUpload,\n\ttype UploadProgress,\n\ttype UploadResponse,\n} from '../../hooks/use-sheets-upload';\nimport { formatFileSize, getImageMetadata, getImageUrl } 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';\n\n/** Data passed to onSaveComplete for optimistic updates */\nexport interface ImageSaveData {\n imageData: {\n url: string;\n filename?: string;\n size?: number;\n mime?: string;\n } | null;\n}\n\ntype UploadState = 'idle' | 'submitting-draft' | 'uploading';\n\ninterface NormalizedImageData {\n url: string;\n filename: string;\n size: number;\n mime: string;\n}\n\nfunction normalizeUploadResponse(data: UploadResponse): NormalizedImageData {\n return { url: data.url, filename: data.filename, size: data.size, mime: data.mime };\n}\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 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 {(size || hasMime) && (\n <p className='text-muted-foreground mt-0.5 text-xs'>\n {size ? formatFileSize(size) : null}\n {size && 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?: string | number;\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 { config } = useSheetsContext();\n const storeApi = useSheetsStoreApi();\n const { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);\n\n const getToken = useMemo(() => {\n if (config.auth.mode === 'embedded') return config.auth.getToken;\n return () => storeApi.getState().accessToken;\n }, [config.auth, storeApi]);\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<string | number | 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 isBusy = uploadState !== 'idle';\n\n const imageUrl = useMemo(() => getImageUrl(imageValue), [imageValue]);\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 // 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 const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === 'error';\n const hasImage = imageUrl != null && !imageLoadFailed && storedIsImage;\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 handleUploadSuccess = useCallback((data: UploadResponse) => {\n const normalized = normalizeUploadResponse(data);\n resetFileState();\n setImageValue(normalized);\n onSaveComplete?.({ imageData: normalized });\n onFinishedEditing();\n toast.success({ message: `${Noun} uploaded successfully` });\n }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);\n\n // Existing-row upload failure: keep the editor open with the staged file\n // retained so the user can retry or cancel, surface the real error message\n // (canonical error messages pass through), and log at error level. Mirrors the\n // draft-row catch UX — never closes the editor on failure.\n const handleUploadError = useCallback((error: Error) => {\n setUploadState('idle');\n sheetsLogger().error('[image-editor] upload failed:', error);\n toast.error({ message: error.message || 'Upload failed' });\n }, []);\n\n const uploadMutation = useSheetsFieldUpload(tableName || '', fieldName || '', recordId || '', {\n onProgress: setUploadProgress,\n onSuccess: handleUploadSuccess,\n onError: handleUploadError,\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 (!tableName || !fieldName || !selectedFile) return;\n\n // A draft that was already persisted server-side (its upload failed earlier).\n // Retry against the real id directly — the draft is gone, so re-submitting\n // it via onSubmitDraft() would fail. Keep the selected file on failure so\n // the user can retry again.\n const committedId = committedRecordIdRef.current ?? recordId;\n if (committedRecordIdRef.current != null) {\n try {\n toast.info({ message: `Uploading ${noun}...` });\n setUploadState('uploading');\n\n const uploadResult = await executeFieldUpload(\n tableName, fieldName, committedRecordIdRef.current, selectedFile,\n config.endpoint, getToken, undefined, { onAuthError: config.onAuthError },\n );\n\n const normalized = normalizeUploadResponse(uploadResult);\n resetFileState();\n setImageValue(normalized);\n onDraftUploadComplete?.();\n toast.success({ message: `${Noun} uploaded successfully` });\n onFinishedEditing();\n } catch (error) {\n // Real row already exists — surface it to the host and keep the file\n // selected so the upload can be retried without rebuilding the row.\n onDraftUploadComplete?.();\n setUploadState('idle');\n toast.error({ message: error instanceof Error ? error.message : 'Upload failed' });\n }\n return;\n }\n\n if (isDraftRow) {\n if (!onSubmitDraft) {\n toast.error({ message: 'Cannot upload to draft row - save the row first' });\n return;\n }\n\n try {\n toast.info({ message: 'Creating row...' });\n setUploadState('submitting-draft');\n\n const result = await onSubmitDraft();\n\t\tconst createdId = result.createdRow?.id;\n\t\tif (typeof createdId !== 'string' && typeof createdId !== 'number') {\n\t\t\tthrow new Error('Image uploads require a scalar id primary key.');\n\t\t}\n\n // Row is now persisted and the draft has been removed from the store.\n // From here on, treat it as a real row: any retry must hit this id.\n\t\tcommittedRecordIdRef.current = createdId;\n\n toast.info({ message: `Uploading ${noun}...` });\n setUploadState('uploading');\n\n const uploadResult = await executeFieldUpload(\n\t\t\ttableName, fieldName, createdId, selectedFile,\n config.endpoint, getToken, undefined, { onAuthError: config.onAuthError },\n );\n\n const normalized = normalizeUploadResponse(uploadResult);\n resetFileState();\n setImageValue(normalized);\n onDraftUploadComplete?.();\n toast.success({ message: `Row created and ${noun} uploaded` });\n onFinishedEditing();\n } catch (error) {\n // The row was persisted (draft removed) but the upload failed, leaving\n // a real row with no image. Notify the host so the now-real row appears,\n // and keep the selected file so the user can retry immediately.\n onDraftUploadComplete?.();\n setUploadState('idle');\n toast.error({ message: error instanceof Error ? error.message : 'Upload failed' });\n }\n return;\n }\n\n if (!committedId) {\n toast.error({ message: 'Missing record context for upload' });\n return;\n }\n setUploadState('uploading');\n uploadMutation.mutate(selectedFile);\n }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);\n\n // --- Save / Cancel -----------------------------------------------------\n\n const handleSave = useCallback(() => {\n if (!imageValue) {\n onFinishedEditing(null);\n return;\n }\n\n const url = getImageUrl(imageValue);\n const originalUrl = getImageUrl(value);\n\n // Nothing changed — close without triggering mutation\n if (url && originalUrl === url) {\n onFinishedEditing();\n return;\n }\n\n onFinishedEditing(url ?? value);\n }, [imageValue, value, onFinishedEditing]);\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 handleSave();\n }\n }, [handleSave]);\n\n // --- Dropzone content --------------------------------------------------\n\n // A stored non-image file (any-file mode) renders as a chip, not a thumbnail.\n const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;\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 className='text-sm'>{isSubmittingDraft ? 'Creating row...' : `Uploading ${noun}...`}</p>\n {isUploading && uploadProgress && (\n <div className='mt-3 w-full max-w-xs'>\n <div className='bg-muted h-1.5 overflow-hidden rounded-full'>\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 className='text-muted-foreground mt-1.5 text-center text-xs'>\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 const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith('image/') ?? false);\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} 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 {imageUrl && (\n <p\n className='text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50'\n title={imageUrl}\n >\n {imageUrl}\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 : isUploading\n ? 'Uploading...'\n : imageUrl\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'>{imageUrl ? `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 || (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 {isDraftRow ? '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 { 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 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/** Optional upload settings. `bucketKey` defaults to \"public\". */\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\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 { 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","/**\n * Field-Specific Upload Hook\n * Provides upload functionality that integrates with the existing dynamic mutation system\n * Works with backend's field-specific upload pattern: <fieldName>Upload fields\n *\n * Ported from apps/admin use-image-upload.ts with context injection.\n */\n\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\n\nimport { cleanTable, type CleanTable, type MetaTable } from '@constructive-io/data';\nimport { useSheetsMeta } from './use-sheets-meta';\nimport {\n\ttoCamelCaseSingular,\n\ttoPatchFieldName,\n\ttoUpdateInputTypeName,\n\ttoUpdateMutationName,\n} from '@constructive-io/data';\n\nimport { useSheetsContext } from '../context/sheets-context';\nimport type { SheetsScopeKey, SheetsConfig } from '../context/sheets-context';\nimport {\n\tcreateSheetsExecute,\n\tcreateSheetsUpload,\n\ttype SheetsExecuteFn,\n\ttype SheetsUploadFn,\n} from '../context/sheets-execute';\nimport { sheetsTableQueryKeys } from './use-sheets-table';\nimport { useSheetsStoreApi } from '../store/sheets-store';\n\n/**\n * Upload progress callback type\n */\nexport interface UploadProgress {\n\tloaded: number;\n\ttotal: number;\n\tpercentage: number;\n}\n\n/**\n * Upload response from backend\n */\nexport interface UploadResponse {\n\turl: string;\n\tfilename: string;\n\tmime: string;\n\tsize: number;\n}\n\n/**\n * Field upload options\n */\nexport interface UseFieldUploadOptions {\n\tonProgress?: (progress: UploadProgress) => void;\n\tonSuccess?: (data: UploadResponse) => void;\n\tonError?: (error: Error) => void;\n\tshowToast?: boolean; // default true\n\tsuccessMessage?: string; // custom success message\n\tsuccessToastDelayMs?: number; // optional delay for success toast\n}\n\ninterface UploadNaming {\n\tmutationName: string;\n\tsingularName: string;\n\tpatchFieldName: string;\n\tupdateInputTypeName: string;\n}\n\ninterface ExecuteFieldUploadOptions {\n\tonAuthError?: () => void;\n\t/**\n\t * Transport seam. When the hooks call this, they thread the context\n\t * `execute`/`executeUpload` here so injected/mock implementations intercept\n\t * both steps. When omitted (e.g. image-editor's direct retry path), the\n\t * functions are built from `endpoint`/`getToken`/`onAuthError` via the same\n\t * factories — never a raw fetch.\n\t */\n\texecute?: SheetsExecuteFn;\n\texecuteUpload?: SheetsUploadFn;\n\tonProgress?: (progress: UploadProgress) => void;\n}\n\nfunction resolveUploadNaming(tableName: string, table?: CleanTable | null): UploadNaming {\n\treturn {\n\t\tmutationName: toUpdateMutationName(tableName, table),\n\t\tsingularName: toCamelCaseSingular(tableName, table),\n\t\tpatchFieldName: toPatchFieldName(tableName, table),\n\t\tupdateInputTypeName: toUpdateInputTypeName(tableName),\n\t};\n}\n\ninterface PatchMutationResult {\n\t[mutationName: string]: { [singular: string]: Record<string, unknown> } | undefined;\n}\n\n/**\n * Build the transport seam for an upload. When the caller injects\n * `execute`/`executeUpload` (the hooks pass the context functions), those are\n * used verbatim so consumer/mock implementations intercept both steps.\n * Otherwise the same factories that back the provider are used, sourced from\n * `endpoint`/`getToken`/`onAuthError` — guaranteeing canonical error normalization\n * and onAuthError without any raw fetch in this module.\n */\nfunction resolveTransport(\n\tendpoint: string,\n\tgetToken: () => string | null,\n\toptions?: ExecuteFieldUploadOptions,\n): { execute: SheetsExecuteFn; executeUpload: SheetsUploadFn } {\n\tif (options?.execute && options?.executeUpload) {\n\t\treturn { execute: options.execute, executeUpload: options.executeUpload };\n\t}\n\tconst config: SheetsConfig = {\n\t\tendpoint,\n\t\tauth: { mode: 'standalone' },\n\t\tonAuthError: options?.onAuthError,\n\t};\n\treturn {\n\t\texecute: createSheetsExecute(config, getToken),\n\t\texecuteUpload: createSheetsUpload(config, getToken),\n\t};\n}\n\n/**\n * Execute field upload using two sequential requests, both routed through the\n * injectable transport seam:\n * 1. File upload via `executeUpload` → returns file metadata\n * 2. GraphQL mutation via `execute` to patch the row with the upload result\n *\n * Exported for direct use when record ID is known at call time (e.g., after draft submission)\n *\n * @param tableName - Table name\n * @param fieldName - Field name for the upload (the actual DB column, e.g. \"photo\")\n * @param recordId - Record ID to update\n * @param file - File to upload\n * @param endpoint - GraphQL endpoint URL (used to build the seam when none injected)\n * @param getToken - Function that returns the current auth token (or null)\n * @param naming - Optional pre-resolved naming overrides\n * @param options - Auth callback + optional injected execute/executeUpload + progress\n */\nexport async function executeFieldUpload(\n\ttableName: string,\n\tfieldName: string,\n\trecordId: string | number,\n\tfile: File,\n\tendpoint: string,\n\tgetToken: () => string | null,\n\tnaming?: UploadNaming,\n\toptions?: ExecuteFieldUploadOptions,\n): Promise<UploadResponse> {\n\t// Validate endpoint (only meaningful for the factory-built seam path)\n\tif (!endpoint && !(options?.execute && options?.executeUpload)) {\n\t\tthrow new Error('No endpoint configured. Select a database API or use Direct Connect.');\n\t}\n\n\tconst { execute, executeUpload } = resolveTransport(endpoint, getToken, options);\n\n\t// ── Step 1: Upload file through the executeUpload seam ──\n\t// Field/row metadata + progress flow as the third arg so injected\n\t// implementations can use them; the default REST transport ignores them.\n\tconst uploadResult = await executeUpload(file, undefined, {\n\t\ttableName,\n\t\tfieldName,\n\t\trecordId,\n\t\tonProgress: options?.onProgress,\n\t});\n\n\t// ── Step 2: Patch the row with the upload result via the execute seam ──\n\tconst resolvedNaming = naming ?? resolveUploadNaming(tableName);\n\n\t// Sanitize upload result — only pass fields the DB schema expects.\n\t// For jsonb columns (image/upload domains): { url, filename, mime, size }\n\t// For text columns (attachment domain): just the URL string.\n\tconst patchValue = {\n\t\t...(uploadResult.url != null && { url: uploadResult.url }),\n\t\t...(uploadResult.filename != null && { filename: uploadResult.filename }),\n\t\t...(uploadResult.mime != null && { mime: uploadResult.mime }),\n\t\t...(uploadResult.size != null && { size: uploadResult.size }),\n\t};\n\n\tconst mutationString = `\n\t\tmutation ${resolvedNaming.mutationName}Mutation($input: ${resolvedNaming.updateInputTypeName}!) {\n\t\t\t${resolvedNaming.mutationName}(input: $input) {\n\t\t\t\t${resolvedNaming.singularName} {\n\t\t\t\t\tid\n\t\t\t\t\t${fieldName}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`.trim();\n\n\t// execute() normalizes auth/forbidden/GraphQL errors to ConstructiveError and fires\n\t// onAuthError on 401/UNAUTHENTICATED — no manual equivalent needed here.\n\tconst result = await execute<PatchMutationResult>(mutationString, {\n\t\tinput: {\n\t\t\tid: recordId,\n\t\t\t[resolvedNaming.patchFieldName]: {\n\t\t\t\t[fieldName]: patchValue,\n\t\t\t},\n\t\t},\n\t});\n\n\t// Extract the updated record from PostGraphile response\n\tconst updatedRecord = result?.[resolvedNaming.mutationName]?.[resolvedNaming.singularName] as\n\t\t| Record<string, unknown>\n\t\t| undefined;\n\n\tif (!updatedRecord) {\n\t\tthrow new Error('Upload succeeded but no data returned from patch');\n\t}\n\n\t// Extract the uploaded file data from the updated record. jsonb columns\n\t// (image/upload domains) return an object; text columns (attachment domain)\n\t// return a plain URL string.\n\tconst uploadedFileData = updatedRecord[fieldName];\n\tif (!uploadedFileData) {\n\t\tthrow new Error(`Upload succeeded but ${fieldName} field not found in response`);\n\t}\n\n\tconst fileObject =\n\t\ttypeof uploadedFileData === 'object' ? (uploadedFileData as Record<string, unknown>) : null;\n\n\t// Return standardized upload response\n\treturn {\n\t\turl: (fileObject?.url as string) || (uploadedFileData as string),\n\t\tfilename: (fileObject?.filename as string) || file.name,\n\t\tmime: (fileObject?.mime as string) || file.type,\n\t\tsize: (fileObject?.size as number) || file.size,\n\t};\n}\n\n/**\n * Hook for uploading files to specific table fields\n * Integrates with the existing dynamic mutation system\n */\nexport function useSheetsFieldUpload(\n\ttableName: string,\n\tfieldName: string,\n\trecordId: string | number,\n\toptions: UseFieldUploadOptions = {},\n) {\n\tconst queryClient = useQueryClient();\n\tconst { scopeKey, config, execute, executeUpload } = useSheetsContext();\n\tconst storeApi = useSheetsStoreApi();\n\tconst { data: meta } = useSheetsMeta();\n\tconst table = useMemo<CleanTable | null>(() => {\n\t\tif (!meta?._meta?.tables) return null;\n\t\tconst candidate = meta._meta.tables.find((item) => item?.name === tableName) as MetaTable | undefined;\n\t\treturn candidate ? cleanTable(candidate) : null;\n\t}, [meta, tableName]);\n\tconst resolvedNaming = useMemo(() => resolveUploadNaming(tableName, table), [tableName, table]);\n\n\t// Build a stable getToken from context\n\tconst getToken = useMemo(() => {\n\t\tif (config.auth.mode === 'embedded') {\n\t\t\treturn config.auth.getToken;\n\t\t}\n\t\treturn () => storeApi.getState().accessToken;\n\t}, [config.auth, storeApi]);\n\n\t// Keep latest params in refs to avoid stale closures\n\tconst tableRef = useRef(tableName);\n\tconst fieldRef = useRef(fieldName);\n\tconst idRef = useRef(recordId);\n\n\tuseEffect(() => {\n\t\ttableRef.current = tableName;\n\t\tfieldRef.current = fieldName;\n\t\tidRef.current = recordId;\n\t}, [tableName, fieldName, recordId]);\n\n\treturn useMutation<UploadResponse, Error, File>({\n\t\tmutationKey: ['sheets', scopeKey, 'field-upload', tableName, fieldName, recordId],\n\t\tmutationFn: async (file: File) => {\n\t\t\t// Route both steps through the context seam so injected/mock\n\t\t\t// execute/executeUpload intercept the upload.\n\t\t\treturn executeFieldUpload(\n\t\t\t\ttableRef.current,\n\t\t\t\tfieldRef.current,\n\t\t\t\tidRef.current,\n\t\t\t\tfile,\n\t\t\t\tconfig.endpoint,\n\t\t\t\tgetToken,\n\t\t\t\tresolvedNaming,\n\t\t\t\t{ onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress },\n\t\t\t);\n\t\t},\n\t\tonSuccess: (data) => {\n\t\t\t// First allow callers to react (e.g., close overlay)\n\t\t\toptions.onSuccess?.(data);\n\t\t\t// Invalidate related queries to refresh data\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });\n\t\t},\n\t\tonError: (error) => {\n\t\t\toptions.onError?.(error);\n\t\t},\n\t});\n}\n\n/**\n * Hook for uploading images with validation\n * Convenience wrapper around useSheetsFieldUpload with image-specific validation\n */\nexport function useSheetsImageUpload(\n\ttableName: string,\n\tfieldName: string,\n\trecordId: string | number,\n\toptions: UseFieldUploadOptions = {},\n) {\n\tconst queryClient = useQueryClient();\n\tconst { scopeKey, config, execute, executeUpload } = useSheetsContext();\n\tconst storeApi = useSheetsStoreApi();\n\tconst { data: meta } = useSheetsMeta();\n\tconst table = useMemo<CleanTable | null>(() => {\n\t\tif (!meta?._meta?.tables) return null;\n\t\tconst candidate = meta._meta.tables.find((item) => item?.name === tableName) as MetaTable | undefined;\n\t\treturn candidate ? cleanTable(candidate) : null;\n\t}, [meta, tableName]);\n\tconst resolvedNaming = useMemo(() => resolveUploadNaming(tableName, table), [tableName, table]);\n\n\t// Build a stable getToken from context\n\tconst getToken = useMemo(() => {\n\t\tif (config.auth.mode === 'embedded') {\n\t\t\treturn config.auth.getToken;\n\t\t}\n\t\treturn () => storeApi.getState().accessToken;\n\t}, [config.auth, storeApi]);\n\n\t// Keep latest params in refs to avoid stale closures\n\tconst tableRef = useRef(tableName);\n\tconst fieldRef = useRef(fieldName);\n\tconst idRef = useRef(recordId);\n\n\tuseEffect(() => {\n\t\ttableRef.current = tableName;\n\t\tfieldRef.current = fieldName;\n\t\tidRef.current = recordId;\n\t}, [tableName, fieldName, recordId]);\n\n\treturn useMutation<UploadResponse, Error, File>({\n\t\tmutationKey: ['sheets', scopeKey, 'image-upload', tableName, fieldName, recordId],\n\t\tmutationFn: async (file: File) => {\n\t\t\t// Validate file type\n\t\t\tif (!file.type.startsWith('image/')) {\n\t\t\t\tthrow new Error('Please select an image file');\n\t\t\t}\n\n\t\t\t// Validate file size (10MB limit)\n\t\t\tconst maxSize = 10 * 1024 * 1024; // 10MB\n\t\t\tif (file.size > maxSize) {\n\t\t\t\tthrow new Error('File size must be less than 10MB');\n\t\t\t}\n\n\t\t\t// Route both steps through the context seam so injected/mock\n\t\t\t// execute/executeUpload intercept the upload.\n\t\t\treturn executeFieldUpload(\n\t\t\t\ttableRef.current,\n\t\t\t\tfieldRef.current,\n\t\t\t\tidRef.current,\n\t\t\t\tfile,\n\t\t\t\tconfig.endpoint,\n\t\t\t\tgetToken,\n\t\t\t\tresolvedNaming,\n\t\t\t\t{ onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress },\n\t\t\t);\n\t\t},\n\t\tonSuccess: (data) => {\n\t\t\t// First allow callers to react (e.g., close overlay)\n\t\t\toptions.onSuccess?.(data);\n\n\t\t\t// Invalidate related queries to refresh data\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });\n\t\t},\n\t\tonError: (error) => {\n\t\t\toptions.onError?.(error);\n\t\t},\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 {\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\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 doc = buildPostGraphileUpdate(table, allTables, {\n\t\t\t\t...options,\n\t\t\t\tfieldSelection: options.fieldSelection || 'display',\n\t\t\t});\n\t\t\tconst patchFieldName = toPatchFieldName(tableName, table);\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 mutationName = toUpdateMutationName(tableName, table);\n\t\t\tconst singularName = toCamelCaseSingular(tableName, table);\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","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\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 type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { ConstructiveError, createError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig } from './sheets-context';\nimport {\n\tcallUploadOp,\n\tdiscoverUploadCapability,\n\tfetchDownloadUrl,\n\tpresignedPut,\n\tsha256HexFromBuffer,\n} from './sheets-upload-presigned';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;\n\nexport type SheetsExecuteFn = <T = unknown>(\n\tdocument: ExecutableDocument,\n\tvariables?: Record<string, unknown>,\n) => Promise<T>;\n\n/**\n * Result of an upload through the seam. `url` is the only guaranteed field;\n * the REST upload endpoint also returns `{ filename, mime, size }` (and may\n * return server-internal extras). Keeping it open-ended lets callers read the\n * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.\n */\nexport type SheetsUploadResult = { url: string } & Record<string, unknown>;\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\ninterface GraphQLResponseError {\n\tmessage: string;\n\textensions?: { code?: string };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: GraphQLResponseError[];\n}\n\nfunction hasAuthMessage(message: string | undefined): boolean {\n\tconst normalized = String(message ?? '').toLowerCase();\n\treturn (\n\t\tnormalized.includes('unauthenticated') ||\n\t\tnormalized.includes('unauthorized') ||\n\t\tnormalized.includes('authentication')\n\t);\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): ConstructiveError | null {\n\tif (!response.errors?.length) return null;\n\n\tconst error = response.errors[0];\n\tconst code = error.extensions?.code;\n\tconst message = error.message || 'GraphQL query failed';\n\n\tif (code === 'UNAUTHENTICATED' || hasAuthMessage(message)) {\n\t\tonAuthError?.();\n\t\treturn createError.unauthorized('Authentication required. Please log in again.');\n\t}\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): 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});\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\tthrow createError.forbidden('You do not have permission to perform this action.');\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();\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tthrow createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);\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\tthrow graphqlError;\n\t\t}\n\n\t\treturn result.data as T;\n\t};\n}\n\n/**\n * Presigned-URL cell-upload seam.\n *\n * Replaces the legacy multipart `<endpoint>/upload` POST entirely. The flow:\n * 1. Read + SHA-256 hash the file bytes (Web Crypto)\n * 2. Discover (cached per endpoint) the upload op + downloadUrl-by-id field\n * via GraphQL introspection — the root `upload<Type>File` mutation, matched\n * by FIELD/TYPE SHAPE (LOCKED: no hardcoded names)\n * 3. Call the upload op with input `{ bucketKey, contentHash, contentType,\n * size, filename }` — NO `ownerId` (app-scoped buckets have no owner_id)\n * 4. If `uploadUrl` is non-null, PUT the raw bytes to it with ONLY the signed\n * `Content-Type` header (NO Authorization). Skipped when `deduplicated`.\n * 5. Resolve the stable public `downloadUrl` for the returned fileId.\n *\n * Returns `{ url, filename, mime, size, key, fileId }` where `url` is the stable\n * download URL — the same cell value shape callers/Step-2 already consume.\n *\n * `path` is ignored (content-addressed buckets key on `contentHash`).\n */\nexport function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\t// Reuse the kept GraphQL executor so canonical error normalization + onAuthError\n\t// (401/UNAUTHENTICATED) apply to introspection, the upload op, and the\n\t// downloadUrl query alike.\n\tconst execute = config.execute ?? createSheetsExecute(config, getToken);\n\n\treturn async (file: File, _path?: string, options?: SheetsUploadOptions): Promise<SheetsUploadResult> => {\n\t\tif (!config.endpoint) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst bucketKey = config.upload?.bucketKey ?? 'public';\n\t\tconst contentType = file.type || 'application/octet-stream';\n\n\t\t// Single read of the bytes — reused for both hashing and the PUT body.\n\t\tconst buffer = await file.arrayBuffer();\n\t\tconst contentHash = await sha256HexFromBuffer(buffer);\n\n\t\tconst cap = await discoverUploadCapability(config.endpoint, execute);\n\n\t\tconst payload = await callUploadOp(execute, cap, {\n\t\t\tbucketKey,\n\t\t\tcontentHash,\n\t\t\tcontentType,\n\t\t\tsize: file.size,\n\t\t\tfilename: file.name,\n\t\t});\n\n\t\t// Dedup (deduplicated ⇒ uploadUrl === null) means the row + S3 object already\n\t\t// exist; skip the PUT. A non-deduplicated payload MUST carry an uploadUrl — a\n\t\t// null there is a server-contract violation, so fail loudly rather than\n\t\t// resolving a downloadUrl for an object that was never uploaded.\n\t\tif (!payload.deduplicated) {\n\t\t\tif (!payload.uploadUrl) {\n\t\t\t\tthrow createError.badRequest('Upload failed: server returned no uploadUrl for a non-deduplicated file.');\n\t\t\t}\n\t\t\tawait presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);\n\t\t} else {\n\t\t\toptions?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });\n\t\t}\n\n\t\tconst url = await fetchDownloadUrl(execute, cap, payload.fileId);\n\n\t\treturn {\n\t\t\turl,\n\t\t\tfilename: file.name,\n\t\t\tmime: file.type,\n\t\t\tsize: file.size,\n\t\t\tkey: payload.key,\n\t\t\tfileId: payload.fileId,\n\t\t};\n\t};\n}\n\nexport { ConstructiveError } from '@constructive-io/data';\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. Resolve the stable public `downloadUrl` for the fileId\n *\n * `confirmUpload` is intentionally skipped: the backend plugin creates the file\n * row inside the upload op, so `downloadUrl` resolves immediately.\n *\n * The upload op is discovered via runtime introspection, matched by FIELD/TYPE\n * SHAPE (never a hardcoded name): a root mutation `upload<Type>File(input: {...})`\n * whose input + payload carry the upload shape.\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 { SheetsExecuteFn } 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\t/** Query field used to resolve the stable 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}\n\ninterface UploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\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\nconst capabilityCache = new Map<string, Promise<UploadCapability>>();\n\n/** Test-only: clear the per-endpoint capability cache between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache.clear();\n}\n\n/**\n * Discover the upload op + downloadUrl-by-id field for an endpoint, by shape.\n * Cached per `endpoint`; concurrent uploads share one in-flight introspection.\n */\nexport function discoverUploadCapability(endpoint: string, execute: SheetsExecuteFn): Promise<UploadCapability> {\n\tconst cached = capabilityCache.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 resolveUploadCapability(schema);\n\t})();\n\n\t// Don't cache a rejected discovery — let the next attempt retry.\n\tpromise.catch(() => capabilityCache.delete(endpoint));\n\tcapabilityCache.set(endpoint, promise);\n\treturn promise;\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, never by a literal name.\n */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\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', '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: Pick<UploadCapability, 'uploadFieldName' | 'inputTypeName'> | 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\tinputHasFields(inputTypeName, INPUT_FIELDS) &&\n\t\t\tobjectHasFields(payloadTypeName, PAYLOAD_FIELDS)\n\t\t) {\n\t\t\tupload = { uploadFieldName: field.name, inputTypeName: inputTypeName as string };\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!upload) {\n\t\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n\t}\n\n\t// --- File object type + by-id field for downloadUrl ---\n\tconst downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);\n\n\treturn {\n\t\t...upload,\n\t\t...downloadById,\n\t};\n}\n\ntype DownloadByIdResult = Omit<UploadCapability, 'uploadFieldName' | 'inputTypeName'>;\n\nfunction resolveDownloadByIdField(\n\tschema: IntrospectionSchema,\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tuploadFieldName: string,\n): DownloadByIdResult {\n\t// The file object type carries a `downloadUrl` field (grounded on\n\t// download-url-field.ts which adds `downloadUrl: String` to @storageFiles).\n\tconst fileTypesWithDownloadUrl = 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\tfileTypesWithDownloadUrl.add(t.name);\n\t\t}\n\t}\n\n\t// 1. Prefer the 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\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\treturn {\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}\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, uploadFieldName);\n\tif (connection) return 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 preferred = uploadFieldName.replace(/^upload/, '');\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\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n}\n\n/**\n * Discover a filtered-connection downloadUrl-by-id path. Returns null if the\n * schema exposes no such connection. 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\tuploadFieldName: string,\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\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 = EQUALITY_OPERATORS.map((op) =>\n\t\t\t\t\tidFieldType.inputFields!.find((f) => f.name === op),\n\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});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// id field is an input object but with no recognized equality op — skip.\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 (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});\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\tconst preferred = uploadFieldName.replace(/^upload/, '');\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}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, UploadPayload | null>>(mutation, {\n\t\tinput: {\n\t\t\tbucketKey: 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\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 */\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 (error) {\n\t\tthrow createError.network(error instanceof Error ? error : undefined);\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(createError.network()));\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 the stable public download URL for a file id via the discovered\n * by-id field. For public files the backend returns a permanent public URL\n * (its exact path shape is the backend's concern) — stored opaquely in the cell.\n */\nexport async function fetchDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\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}, 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/**\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 once per endpoint (cached)\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 cap = await discoverUploadCapability(endpoint, execute);\n\t\treturn await fetchDownloadUrl(execute, cap, fileId);\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// 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: (obj.size as number) || (obj.fileSize as number) || 0,\n\t\tmime: (obj.mime as string) || (obj.type as string) || (obj.contentType as string) || 'unknown',\n\t\turl: getImageUrl(imageValue) || '',\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 [status, setStatus] = useState<ImageStatus>('idle');\n\n\tuseEffect(() => {\n\t\tif (!src) return setStatus('idle');\n\n\t\tsetStatus('loading');\n\t\tconst img = new Image();\n\t\timg.src = src;\n\n\t\tconst onLoad = () => setStatus('loaded');\n\t\tconst onError = () => setStatus('error');\n\n\t\timg.addEventListener('load', onLoad);\n\t\timg.addEventListener('error', onError);\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\treturn status;\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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\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 { 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\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//\n// Ports v1 `ImageCellFactory` (grid/cell-content-factory.ts). The glide cell put\n// the resolved URL in BOTH `data` and `displayData` as a single-element array\n// (`[url]`); empty/null/'' collapses to `['']`. The neutral SheetsCell keeps the\n// SAME `data: [url]` array (so copyText === JSON.stringify([url]) like glide) and\n// sets `displayData` to the STRING form of that array (JSON.stringify) so the\n// `image` kind — projected via stringifyField, NOT the geometry/custom branch —\n// yields the SAME displayText glide produced from its array `displayData`.\n//\n// URL extraction logic copied verbatim (NOT imported from cell-content-factory,\n// which 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 { MEDIA_TYPES } from '../../cell-types/cell-type-groups';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\n/** Resolve a media URL from a string or an object's url/src/href/path keys (v1 order). */\nfunction resolveMediaUrl(value: unknown): string {\n\tif (typeof value === 'string') return value;\n\tif (typeof value === 'object' && value) {\n\t\tconst obj = value as Record<string, unknown>;\n\t\treturn (obj.url || obj.src || obj.href || obj.path || '') as string;\n\t}\n\treturn '';\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 url = value === null || value === undefined || value === '' ? '' : resolveMediaUrl(value);\n\t\tconst data = [url];\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,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,sBAAsB,mBAAmB,eAAe,sBAAsB,QAAQ,aAAa;AACtG,8BAAsB,QAAQ,MAAM;AAAA,MACrC;AAAA,IACD;AAAA,EACD,GAAG,CAAC,CAAC;AAGL,QAAM,oBAAgB;AAAA,IACrB,CAAC,MAA2B;AAE3B,kBAAY,CAAC;AAEb,UAAI,EAAE,QAAQ,UAAU;AACvB,UAAE,eAAe;AACjB,UAAE,gBAAgB;AAClB,mB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AAU,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","import_react","useZustandStore","import_react","import_react_query","import_data","import_react_query","import_data","import_react","import_data","import_data","import_data","totalCount","data","import_data","import_graphql","import_data","import_data","query","data","url","idScalar","import_data","document","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_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"]}