@constructive-io/sheets 0.9.1 → 0.9.2

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 +0,0 @@
1
- {"version":3,"sources":["../src/row-identity.ts","../src/hooks/use-sheets-table.ts","../src/hooks/use-sheets-meta.ts","../src/adapter/postgraphile-adapter.ts","../src/adapter/use-sheets-adapter.ts","../src/hooks/relation-field-resolution.ts","../src/hooks/orderby-enum-resolution.ts","../src/cell-model/factories/badges.ts","../src/cell-model/factories/boolean.ts","../src/cell-model/factories/datetime.ts","../src/grid/sheets.formatters.ts","../src/cell-model/factories/geometry.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","../src/grid/editors/overlay-viewport-guard.tsx","../src/hooks/use-sheets-upload.ts","../src/hooks/use-sheets-table-cursor.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-dom/editors/image-editor.tsx","../src/grid/editors/image-editor.tsx","../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/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"],"sourcesContent":["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","/**\n * Unified hooks system for table operations\n * Consolidates all table operations into a single, powerful hook\n *\n * Ported from apps/admin use-table.ts with context injection.\n */\nimport { useMemo } from 'react';\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';\n\nimport { useSheetsMeta } from './use-sheets-meta';\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsContext } from '../context/sheets-context';\nimport type { SheetsScopeKey } from '../context/sheets-context';\n\nimport { cleanTable, type CleanTable, type MetaTable, type MutationOptions, type QueryOptions } from '@constructive-io/data';\nimport { createError } from '@constructive-io/data';\nimport type { FieldSelection } from '@constructive-io/data';\nimport {\n\tbuildSelect,\n\ttoCamelCasePlural,\n\ttoCamelCaseSingular,\n\ttoOrderByEnumValue,\n} from '@constructive-io/data';\nimport { reuseSheetsPlaceholderData, sheetsQueryKeys } from './query-keys';\nimport { resolveRelationFieldMap } from './relation-field-resolution';\nimport { validateOrderByVariables } from './orderby-enum-resolution';\nimport {\n\tassertSheetsMutationAllowed,\n\tresolveSheetsIdentifier,\n\tresolveSheetsRowIdentity,\n\tsheetsIdentifierCacheKey,\n\tsheetsIdentifierToWhere,\n\ttype SheetsRowIdentifier,\n} from '../row-identity';\n\ntype RowRecord = Record<string, unknown>;\ntype DeleteIdentifier = SheetsRowIdentifier;\n\n/**\n * Transform relation data by extracting nodes from hasMany/manyToMany connections\n */\nexport function transformRelationData<TData extends RowRecord>(data: unknown, table: CleanTable): TData[] {\n\tif (!data) return [] as TData[];\n\tif (!Array.isArray(data)) return data as TData[];\n\n\tconst transformed = data.map((row) => {\n\t\tif (!row || typeof row !== 'object') return row as TData;\n\n\t\tconst transformedRow: RowRecord = { ...(row as RowRecord) };\n\n\t\tconst hasManyRelations = table.relations.hasMany || [];\n\t\tconst manyToManyRelations = table.relations.manyToMany || [];\n\t\tconst connectionRelations = [...hasManyRelations, ...manyToManyRelations];\n\n\t\tconnectionRelations.forEach((relation) => {\n\t\t\tconst fieldName = relation.fieldName;\n\t\t\tif (!fieldName || !(fieldName in transformedRow)) return;\n\n\t\t\tconst relationValue = transformedRow[fieldName];\n\t\t\tif (relationValue && typeof relationValue === 'object' && 'nodes' in (relationValue as RowRecord)) {\n\t\t\t\tconst connectionData = relationValue as { nodes?: unknown[] };\n\t\t\t\ttransformedRow[fieldName] = connectionData.nodes || [];\n\t\t\t}\n\t\t});\n\n\t\treturn transformedRow as TData;\n\t});\n\n\treturn transformed as TData[];\n}\n\n/**\n * Unified table hook options\n */\nexport interface UseTableOptions extends QueryOptions {\n\t/** Enable/disable automatic data fetching */\n\tenabled?: boolean;\n\t/** Field selection for queries */\n\tselect?: FieldSelection;\n\t/** Mutation options */\n\tmutationOptions?: MutationOptions;\n}\n\n/**\n * Unified table hook result\n */\nexport interface UseTableResult<TData extends RowRecord = RowRecord> {\n\t// Data\n\tdata: TData[];\n\ttotalCount: number;\n\tisLoading: boolean;\n\terror: Error | null;\n\n\t// Single row operations\n\tfindOne: (id: SheetsRowIdentifier) => Promise<TData | null>;\n\n\t// Mutations\n\tcreate: (data: RowRecord) => Promise<{ createdRow: TData | null }>;\n\tupdate: (id: SheetsRowIdentifier, patch: RowRecord) => Promise<{ updatedRow: TData | null }>;\n\tdelete: (id: DeleteIdentifier) => Promise<{ deletedId: DeleteIdentifier }>;\n\n\t// Mutation states\n\tisCreating: boolean;\n\tisUpdating: boolean;\n\tisDeleting: boolean;\n\n\t// Mutation errors\n\tcreateError: Error | null;\n\tupdateError: Error | null;\n\tdeleteError: Error | null;\n\n\t// Utilities\n\trefetch: () => Promise<unknown>;\n\tinvalidate: () => void;\n}\n\n/**\n * Generate query keys for consistent cache management\n */\nexport const sheetsTableQueryKeys = {\n\tscope: (scope: SheetsScopeKey) => sheetsQueryKeys.scope(scope),\n\ttable: (scope: SheetsScopeKey, tableName: string) => sheetsQueryKeys.table(scope, tableName),\n\ttableRows: (scope: SheetsScopeKey, tableName: string, options?: QueryOptions) =>\n\t\tsheetsQueryKeys.tableRows(scope, tableName, options),\n\ttableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) =>\n\t\tsheetsQueryKeys.tableRow(scope, tableName, id),\n\ttableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) =>\n\t\tsheetsQueryKeys.tableCount(scope, tableName, where),\n};\n\nconst sheetsTableMutationKeys = {\n\tcreate: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsTableQueryKeys.table(scope, tableName), 'mutation', 'create'] as const,\n\tupdate: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsTableQueryKeys.table(scope, tableName), 'mutation', 'update'] as const,\n\tdelete: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsTableQueryKeys.table(scope, tableName), 'mutation', 'delete'] as const,\n};\n\n/**\n * Transform QueryOptions to PostGraphile pagination variables\n */\nexport function transformToPostGraphileVariables(table: CleanTable, options: QueryOptions = {}): Record<string, unknown> {\n\tconst variables: Record<string, unknown> = {};\n\n\t// Transform limit to first (PostGraphile uses first for forward pagination)\n\tconst limitValue = options.limit ?? options.first;\n\tif (limitValue !== undefined) {\n\t\tvariables.first = limitValue;\n\t}\n\n\t// Keep offset as is (PostGraphile supports offset-based pagination)\n\tif (options.offset !== undefined) {\n\t\tvariables.offset = options.offset;\n\t}\n\n\t// Add cursor-based pagination variables (for infinite scroll)\n\tif (options.after !== undefined) {\n\t\tvariables.after = options.after;\n\t}\n\tif (options.before !== undefined) {\n\t\tvariables.before = options.before;\n\t}\n\n\t// Transform orderBy to PostGraphile format\n\t// PostGraphile expects format like: [\"ID_ASC\", \"NAME_DESC\"]\n\tif (options.orderBy && options.orderBy.length > 0) {\n\t\tconst availableFields = new Set(table.fields.map((field) => field.name));\n\t\tvariables.orderBy = options.orderBy\n\t\t\t.filter(({ field }) => availableFields.has(field))\n\t\t\t.map(({ field, direction }) => toOrderByEnumValue(field, direction));\n\t}\n\n\t// Add where/filter conditions if present\n\tif (options.where) {\n\t\t// constructive APIs expose the connection filter as `where` (buildSelect emits `$where`).\n\t\t// Naming this variable `filter` left `$where` unbound → server-side filtering was\n\t\t// silently dropped (every `where` returned all rows). Must match buildSelect's `$where`.\n\t\tvariables.where = options.where;\n\t}\n\n\treturn variables;\n}\n\n/**\n * Main unified table hook\n * Returns all table operations in a single hook\n */\nexport function useSheetsTable<TData extends RowRecord = RowRecord>(\n\ttableName: string,\n\toptions: UseTableOptions = {},\n): UseTableResult<TData> {\n\tconst queryClient = useQueryClient();\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst { data: meta } = useSheetsMeta();\n\tconst adapter = useSheetsAdapter();\n\n\tconst metaTables = useMemo<MetaTable[]>(() => {\n\t\tif (!meta?._meta?.tables) return [];\n\n\t\treturn meta._meta.tables.filter((candidate): candidate is MetaTable => candidate != null);\n\t}, [meta]);\n\n\tconst tables = useMemo<CleanTable[]>(() => metaTables.map(cleanTable), [metaTables]);\n\n\tconst table = useMemo<CleanTable | null>(\n\t\t() => tables.find((candidate) => candidate.name === tableName) ?? null,\n\t\t[tables, tableName],\n\t);\n\tconst tableMeta = useMemo<MetaTable | null>(\n\t\t() => metaTables.find((candidate) => candidate.name === tableName) ?? null,\n\t\t[metaTables, tableName],\n\t);\n\n\tconst resolveIdentifier = (identifier: SheetsRowIdentifier): SheetsRowIdentifier => {\n\t\tif (!tableMeta) throw createError.notFound(`Table '${tableName}' not found`);\n\t\tconst resolution = resolveSheetsIdentifier(tableMeta, identifier);\n\t\tif (resolution.status !== 'identified') {\n\t\t\tthrow createError.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);\n\t\t}\n\t\treturn resolution.identifier;\n\t};\n\n\tconst rowCacheKey = (row: RowRecord | null | undefined): string | number | null => {\n\t\tif (!tableMeta || !row) return null;\n\t\tconst resolution = resolveSheetsRowIdentity(tableMeta, row);\n\t\tif (resolution.status !== 'identified') return null;\n\t\treturn typeof resolution.identifier === 'object' ? resolution.key : resolution.identifier;\n\t};\n\n\t// Extract options\n\tconst { enabled = true, select: fieldSelection, mutationOptions = {}, ...queryOptions } = options;\n\n\t// Update query options with field selection\n\tconst finalQueryOptions: QueryOptions = {\n\t\t...queryOptions,\n\t\tfieldSelection,\n\t};\n\n\t// Data fetching with error handling\n\tconst {\n\t\tdata,\n\t\tisLoading,\n\t\terror,\n\t\trefetch,\n\t\t} = useQuery<{ rows: TData[]; totalCount: number }>({\n\t\t\tqueryKey: sheetsTableQueryKeys.tableRows(scopeKey, tableName, finalQueryOptions),\n\t\t\tqueryFn: async () => {\n\t\t\t\tif (!table) {\n\t\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t\t}\n\n\t\t\t\t// Cache-bound resolution stays in the hook. The orderBy validation mutates\n\t\t\t\t// `variables.orderBy` (PostGraphile enum strings) in place; we fold that\n\t\t\t\t// result back into the `{ field, direction }[]` orderBy we hand the adapter,\n\t\t\t\t// so the adapter rebuilds an identical (validated) variables payload.\n\t\t\t\tconst variables = transformToPostGraphileVariables(table, finalQueryOptions);\n\n\t\t\t\tconst [relationFieldMap] = await Promise.all([\n\t\t\t\t\tresolveRelationFieldMap({\n\t\t\t\t\t\ttable,\n\t\t\t\t\t\tfieldSelection: finalQueryOptions.fieldSelection,\n\t\t\t\t\t\tscopeKey,\n\t\t\t\t\t\tqueryClient,\n\t\t\t\t\t\texecute,\n\t\t\t\t\t}),\n\t\t\t\t\tvalidateOrderByVariables(variables, table, scopeKey, queryClient, execute),\n\t\t\t\t]);\n\n\t\t\t\tconst validatedOrderByEnum = new Set((variables.orderBy as string[] | undefined) ?? []);\n\t\t\t\tconst availableOrderByFields = new Set(table.fields.map((field) => field.name));\n\t\t\t\tconst validatedOrderBy = finalQueryOptions.orderBy?.filter(\n\t\t\t\t\t({ field, direction }) =>\n\t\t\t\t\t\tavailableOrderByFields.has(field) && validatedOrderByEnum.has(toOrderByEnumValue(field, direction)),\n\t\t\t\t);\n\n\t\t\t\tconst { rows, totalCount } = await adapter.listRows<TData>(\n\t\t\t\t\t{ table, allTables: tables, tableName },\n\t\t\t\t\t{\n\t\t\t\t\t\t...finalQueryOptions,\n\t\t\t\t\t\torderBy: validatedOrderBy,\n\t\t\t\t\t\t// resolveRelationFieldMap yields `string | null` (null = omit field). The\n\t\t\t\t\t\t// contract narrows to `string`, but the null values are passed through to\n\t\t\t\t\t\t// buildSelect unchanged at runtime — behavior is identical to before.\n\t\t\t\t\t\trelationFieldMap: relationFieldMap as Record<string, string>,\n\t\t\t\t\t},\n\t\t\t\t\texecute,\n\t\t\t\t);\n\t\t\t\treturn { rows, totalCount };\n\t\t},\n\t\tenabled: enabled && !!table,\n\t\tplaceholderData: (previousData, previousQuery) =>\n\t\t\treuseSheetsPlaceholderData(previousData, previousQuery?.queryKey, scopeKey),\n\t\tstaleTime: 5 * 60 * 1000, // 5 minutes\n\t});\n\n\tconst rowsData = data?.rows ?? [];\n\tconst totalCount = data?.totalCount ?? 0;\n\n\t// Create mutation with error handling\n\tconst createMutation = useMutation<\n\t\t{ createdRow: TData | null; __rawResult: Record<string, unknown> },\n\t\tError,\n\t\tRowRecord\n\t>({\n\t\tmutationKey: sheetsTableMutationKeys.create(scopeKey, tableName),\n\t\tmutationFn: async (data: RowRecord) => {\n\t\t\tif (!table || !tableMeta) {\n\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t}\n\t\t\tassertSheetsMutationAllowed(tableMeta, 'create');\n\n\t\t\t// Get all tables for AST generation\n\t\t\tconst allTables = meta?._meta?.tables\n\t\t\t\t? meta._meta.tables.filter((t): t is NonNullable<typeof t> => t != null).map(cleanTable)\n\t\t\t\t: [];\n\n\t\t\tconst createdRow = await adapter.createRow<TData>({ table, allTables, tableName }, data, execute, {\n\t\t\t\t...mutationOptions,\n\t\t\t\tfieldSelection: mutationOptions.fieldSelection || fieldSelection || 'display',\n\t\t\t});\n\n\t\t\treturn { createdRow, __rawResult: {} };\n\t\t},\n\t\tonSuccess: ({ createdRow }: { createdRow: TData | null; __rawResult: Record<string, unknown> }) => {\n\t\t\t// Invalidate all related queries for paginated mode\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });\n\n\t\t\t// Cross-invalidate infinite scroll queries to ensure both modes stay in sync\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });\n\n\t\t\t// Update individual row cache\n\t\t\tconst createdRowKey = rowCacheKey(createdRow as RowRecord | null);\n\t\t\tif (createdRowKey !== null) {\n\t\t\t\tqueryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, createdRowKey), createdRow);\n\t\t\t}\n\t\t},\n\t});\n\n\t// Update mutation with error handling\n\tconst updateMutation = useMutation<\n\t\t{ updatedRow: TData | null; __rawResult: Record<string, unknown> },\n\t\tError,\n\t\t{ id: SheetsRowIdentifier; patch: RowRecord },\n\t\t{ previousRows: Array<[readonly unknown[], { rows: TData[]; totalCount: number } | undefined]> }\n\t>({\n\t\tmutationKey: sheetsTableMutationKeys.update(scopeKey, tableName),\n\t\tmutationFn: async ({ id, patch }) => {\n\t\t\tif (!table || !tableMeta) {\n\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t}\n\t\t\tassertSheetsMutationAllowed(tableMeta, 'update');\n\t\t\tconst mutationIdentifier = resolveIdentifier(id);\n\n\t\t\t// Get all tables for AST generation\n\t\t\tconst allTables = meta?._meta?.tables\n\t\t\t\t? meta._meta.tables.filter((t): t is NonNullable<typeof t> => t != null).map(cleanTable)\n\t\t\t\t: [];\n\n\t\t\tconst updatedRow = await adapter.updateRow<TData>({ table, allTables, tableName }, mutationIdentifier, patch, execute, {\n\t\t\t\t...mutationOptions,\n\t\t\t\tfieldSelection: mutationOptions.fieldSelection || fieldSelection || 'display',\n\t\t\t});\n\n\t\t\treturn { updatedRow, __rawResult: {} };\n\t\t},\n\t\t// Optimistic patch: an inline cell edit must show the new value instantly,\n\t\t// not after the server round-trip + the onSuccess refetch round-trip. The\n\t\t// active rows cache is `{ rows, totalCount }` keyed by `tableRows(...options)`;\n\t\t// patch every cached `tableRows` variant that holds the row (the active query\n\t\t// key embeds `finalQueryOptions`, but other option permutations may be cached\n\t\t// too), matching the row by its scalar `id`.\n\t\tonMutate: async ({ id, patch }) => {\n\t\t\tconst tablePrefix = sheetsTableQueryKeys.table(scopeKey, tableName);\n\t\t\tawait queryClient.cancelQueries({ queryKey: tablePrefix });\n\t\t\tconst targetKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, id) : null;\n\n\t\t\tconst isRowsKey = (key: readonly unknown[]) => key[key.length - 2] === 'rows';\n\t\t\tconst previousRows = queryClient\n\t\t\t\t.getQueriesData<{ rows: TData[]; totalCount: number }>({ queryKey: tablePrefix })\n\t\t\t\t.filter(([key]) => isRowsKey(key)) as Array<\n\t\t\t\t[readonly unknown[], { rows: TData[]; totalCount: number } | undefined]\n\t\t\t>;\n\n\t\t\tfor (const [key] of previousRows) {\n\t\t\t\tqueryClient.setQueryData<{ rows: TData[]; totalCount: number }>(key, (old) => {\n\t\t\t\t\tif (!old) return old;\n\t\t\t\t\tlet changed = false;\n\t\t\t\t\tconst rows = old.rows.map((row) => {\n\t\t\t\t\t\tif (targetKey !== null && rowCacheKey(row as RowRecord) === targetKey) {\n\t\t\t\t\t\t\tchanged = true;\n\t\t\t\t\t\t\treturn { ...(row as RowRecord), ...patch } as TData;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn row;\n\t\t\t\t\t});\n\t\t\t\t\treturn changed ? { ...old, rows } : old;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn { previousRows };\n\t\t},\n\t\tonError: (_err, _vars, ctx) => {\n\t\t\t// Roll the optimistic patch back to the snapshot on failure.\n\t\t\tctx?.previousRows.forEach(([key, data]) => queryClient.setQueryData(key, data));\n\t\t},\n\t\tonSuccess: ({ updatedRow }: { updatedRow: TData | null; __rawResult: Record<string, unknown> }) => {\n\t\t\t// Invalidate all related queries for paginated mode\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });\n\n\t\t\t// NOTE: deliberately NOT invalidating the infinite-scroll cache here.\n\t\t\t// An inline field update never changes row membership/ordering/count, so:\n\t\t\t// - infinite mode reconciles via the caller's optimistic `updateRowAtIndex`\n\t\t\t// (+ self-heal refetch on a cache miss) in use-sheets.ts;\n\t\t\t// - paginated mode is covered by the `table` invalidation above.\n\t\t\t// A blanket `infiniteTable` invalidation would refetch EVERY loaded page\n\t\t\t// (the live-observed 2x refetch on each edit) and clobber the optimistic\n\t\t\t// patch on the active page. The create/delete mutations still\n\t\t\t// cross-invalidate the infinite cache since no per-cell optimistic patch\n\t\t\t// covers a membership change.\n\n\t\t\t// Update individual row cache\n\t\t\tconst updatedRowKey = rowCacheKey(updatedRow as RowRecord | null);\n\t\t\tif (updatedRowKey !== null) {\n\t\t\t\tqueryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, updatedRowKey), updatedRow);\n\t\t\t}\n\t\t},\n\t});\n\n\t// Delete mutation with error handling\n\tconst deleteMutation = useMutation<\n\t\t{ deletedId: DeleteIdentifier; __rawResult: Record<string, unknown> },\n\t\tError,\n\t\tDeleteIdentifier\n\t>({\n\t\tmutationKey: sheetsTableMutationKeys.delete(scopeKey, tableName),\n\t\tmutationFn: async (idOrPk) => {\n\t\t\tif (!table || !tableMeta) {\n\t\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t\t}\n\t\t\tassertSheetsMutationAllowed(tableMeta, 'delete');\n\t\t\tconst mutationIdentifier = resolveIdentifier(idOrPk);\n\n\t\t\t// Get all tables for AST generation\n\t\t\tconst allTables = meta?._meta?.tables\n\t\t\t\t? meta._meta.tables.filter((t): t is NonNullable<typeof t> => t != null).map(cleanTable)\n\t\t\t\t: [];\n\n\t\t\tawait adapter.deleteRow({ table, allTables, tableName }, mutationIdentifier, execute, mutationOptions);\n\n\t\t\treturn { deletedId: idOrPk, __rawResult: {} };\n\t\t},\n\t\tonSuccess: ({ deletedId }: { deletedId: DeleteIdentifier; __rawResult: Record<string, unknown> }) => {\n\t\t\t// Invalidate all related queries for paginated mode\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });\n\n\t\t\t// Cross-invalidate infinite scroll queries to ensure both modes stay in sync\n\t\t\tqueryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });\n\n\t\t\tconst deletedRowKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, deletedId) : null;\n\t\t\tif (deletedRowKey !== null) {\n\t\t\t\tqueryClient.removeQueries({\n\t\t\t\t\tqueryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableName, deletedRowKey),\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t});\n\n\t// Find one function with error handling\n\tconst findOne = async (id: SheetsRowIdentifier) => {\n\t\tif (!table || !tableMeta) {\n\t\t\tthrow createError.notFound(`Table '${tableName}' not found`);\n\t\t}\n\t\tconst where = sheetsIdentifierToWhere(tableMeta, id);\n\t\tif (!where) {\n\t\t\tthrow createError.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);\n\t\t}\n\n\t\tconst doc = buildSelect(table, tables, {\n\t\t\twhere,\n\t\t\tlimit: 1,\n\t\t});\n\t\tconst variables = transformToPostGraphileVariables(table, {\n\t\t\twhere,\n\t\t\tlimit: 1,\n\t\t});\n\t\tconst result = (await execute(doc, variables)) as Record<string, unknown>;\n\n\t\t// Some schemas expose a singular root field; keep this as a compatibility fallback.\n\t\tconst singularName = toCamelCaseSingular(tableName, table);\n\t\tconst singularData = result[singularName];\n\t\tif (singularData && typeof singularData === 'object') {\n\t\t\treturn singularData as TData;\n\t\t}\n\n\t\t// Handle Relay-style response structure (connection fallback)\n\t\tconst queryTableName = toCamelCasePlural(tableName, table);\n\t\tconst data = result[queryTableName];\n\n\t\tif (data && typeof data === 'object' && 'nodes' in data) {\n\t\t\tconst nodes = (data as { nodes: unknown[] }).nodes || [];\n\t\t\tconst transformedNodes = transformRelationData<TData>(nodes, table);\n\t\t\treturn transformedNodes[0] || null;\n\t\t}\n\n\t\t// Fallback for direct array response\n\t\tconst rows = (result[tableName] as unknown[]) || [];\n\t\tconst transformedRows = transformRelationData<TData>(rows, table);\n\t\treturn transformedRows[0] || null;\n\t};\n\n\t// Invalidate function\n\tconst invalidate = () => {\n\t\tqueryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });\n\t};\n\n\treturn {\n\t\t// Data\n\t\tdata: rowsData,\n\t\ttotalCount,\n\t\tisLoading,\n\t\terror,\n\n\t\t// Single row operations\n\t\tfindOne,\n\n\t\t// Mutations\n\t\tcreate: (data: RowRecord) => createMutation.mutateAsync(data),\n\t\tupdate: (id: SheetsRowIdentifier, patch: RowRecord) => updateMutation.mutateAsync({ id, patch }),\n\t\tdelete: (id: DeleteIdentifier) => deleteMutation.mutateAsync(id),\n\n\t\t// Mutation states\n\t\tisCreating: createMutation.isPending,\n\t\tisUpdating: updateMutation.isPending,\n\t\tisDeleting: deleteMutation.isPending,\n\n\t\t// Mutation errors\n\t\tcreateError: createMutation.error,\n\t\tupdateError: updateMutation.error,\n\t\tdeleteError: deleteMutation.error,\n\n\t\t// Utilities\n\t\trefetch,\n\t\tinvalidate,\n\t};\n}\n","// src/hooks/use-sheets-meta.ts\nimport { useQuery, type UseQueryResult } from '@tanstack/react-query';\n\nimport type { MetaQuery } from '@constructive-io/data';\n\nimport { useSheetsAdapter } from '../adapter/use-sheets-adapter';\nimport { useSheetsContext, type SheetsScopeKey } from '../context/sheets-context';\nimport { sheetsQueryKeys } from './query-keys';\n\nexport const metaKey = (scope: SheetsScopeKey) => sheetsQueryKeys.meta(scope);\n\nexport interface UseMetaOptions {\n\tenabled?: boolean;\n}\n\nexport function useSheetsMeta(options: UseMetaOptions = {}): UseQueryResult<MetaQuery, Error> {\n\tconst { enabled = true } = options;\n\tconst { execute, scopeKey } = useSheetsContext();\n\tconst adapter = useSheetsAdapter();\n\treturn useQuery<MetaQuery, Error>({\n\t\tqueryKey: metaKey(scopeKey),\n\t\tqueryFn: () => adapter.fetchMeta(execute),\n\t\tstaleTime: 5 * 60 * 1000, // 5 min - finite so invalidation + remount triggers refetch\n\t\tgcTime: 30 * 60 * 1000, // 30 min - survive long schema-editing sessions\n\t\trefetchOnMount: true, // Respect staleTime and refetch stale metadata on mount\n\t\tenabled,\n\t});\n}\n","import {\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","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 { 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","// 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// Parity contract (projectSheetsCell ≡ projectGlideCell):\n// The glide BooleanCell carries `data: boolValue` and NO `displayData`, so\n// projectGlideCell yields { displayText: '', copyText: String(boolValue) }.\n// We mirror that: `data` holds EXACTLY the boolean glide put in `.data`, and\n// `displayData` is '' (glide Boolean had none). Since kind 'boolean' is not\n// geometry/custom, projectSheetsCell reads displayData -> '' and data ->\n// String(boolValue), matching glide branch-for-branch. The glide BooleanCell\n// sets no `readonly`, so readonly = false.\n\nimport type { CellCreationMetadata } from '../../grid/grid-cell-types';\nimport { BOOLEAN_TYPES } from '../../cell-types/cell-type-groups';\nimport type { SheetsCell } from '../sheets-cell';\nimport type { SheetsCellFactory } from './types';\n\nfunction canHandle(cellType: string, _value: unknown): boolean {\n\treturn BOOLEAN_TYPES.has(cellType);\n}\n\nfunction create(value: unknown, _metadata: CellCreationMetadata): SheetsCell {\n\tconst boolValue = value === null || value === undefined ? 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// mirrors that exactly so projectSheetsCell deep-equals projectGlideCell.\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","/**\n * Formatter utilities for grid cell previews\n * - Keep these pure so they are easy to test\n */\n\nexport function compactJsonPreview(value: unknown, maxLen = 80): string {\n\ttry {\n\t\tconst s = typeof value === 'string' ? value : JSON.stringify(value);\n\t\tif (s.length <= maxLen) return s;\n\t\treturn s.slice(0, maxLen - 1) + '\\u2026';\n\t} catch {\n\t\tconst s = String(value);\n\t\treturn s.length > maxLen ? s.slice(0, maxLen - 1) + '\\u2026' : s;\n\t}\n}\n\nexport function formatArrayPreview(arr: unknown[], max = 3): string {\n\tconst items = arr\n\t\t.slice(0, max)\n\t\t.map((v) => (typeof v === 'object' && v !== null ? compactJsonPreview(v, 20) : String(v)));\n\tconst more = arr.length > max ? ` +${arr.length - max}` : '';\n\treturn items.join(', ') + more;\n}\n\nexport function formatImagePreview(val: unknown): string {\n\tif (!val) return '';\n\tif (typeof val === 'string') return val.split('/').pop() || val;\n\tif (typeof val === 'object' && val !== null) {\n\t\tconst rec = val as Record<string, unknown>;\n\t\tconst url = (rec.url as string) || '';\n\t\tconst filename = (rec.filename as string) || url.split('/').pop() || 'image';\n\t\treturn filename;\n\t}\n\treturn String(val);\n}\n\n","// Geometry SheetsCell factory — native analogue of v1 `GeometryCellFactory`.\n//\n// Owns GEOMETRY_TYPES (geometry, geometry-point, geometry-collection). Geometry\n// stays out-of-band: when the caller supplies a `deriveGeometry` builder (the\n// native mirror of v1's `createGeometryCell`), this factory delegates to it so\n// this module never imports the leaflet-backed geometry view. Without a builder,\n// it falls back to a compact JSON preview as both the copy value and the display\n// string — identical to v1's Text fallback.\n//\n// Parity: `projectSheetsCell` special-cases kind `geometry` so copyText ===\n// displayText === displayData. The fallback therefore sets `data` and\n// `displayData` to the SAME `compactJsonPreview(value, 80)` string v1 emits.\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","// 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// Parity contract (projectSheetsCell ≡ projectGlideCell):\n// - null/undefined OR NaN coercion -> data: undefined, displayData: ''\n// (projects copyText '' + displayText '')\n// - otherwise -> data: numValue (number), displayData: String(numValue)\n// Mirrors the glide NumberCell branch-for-branch; `data` holds EXACTLY what the\n// glide factory put in `.data`, and `displayData` is the string form of glide's\n// `.displayData`. The glide NumberCell sets no `readonly`, so readonly = false.\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// PARITY: projectSheetsCell(create(...)) deep-equals projectGlideCell(v1 create).\n// single — glide Text: data = label, displayData = label.\n// list — glide Bubble: data = finalData (chips + \"+N\"), displayData = '' (Bubble\n// carries no displayData, so it projects to '' on the display side).\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. This factory mirrors that exactly so projectSheetsCell deep-equals\n// projectGlideCell. `compactJsonPreview` is shared (sheets.formatters), so it is\n// imported 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// PARITY: projectSheetsCell(create(...)) deep-equals projectGlideCell of v1's\n// UriCell — `data`/`displayData` are the SAME strings v1 emits. v1 drops only\n// the `onClickUri` side-effect (the DOM view owns clicks).\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. Parity-safe: `projectSheetsCell`\n * ignores `meta` entirely, so display/copy text is unchanged.\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","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","/**\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","/**\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 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","'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","// 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","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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIM;AAyBP,SAAS,iBACR,YACkD;AAClD,QAAM,UAAU,OAAO,QAAQ,UAAU;AACzC,SACC,QAAQ,WAAW,KACnB,QAAQ,CAAC,EAAE,CAAC,MAAM,SACjB,OAAO,QAAQ,CAAC,EAAE,CAAC,MAAM,YAAY,OAAO,QAAQ,CAAC,EAAE,CAAC,MAAM;AAEjE;AAMO,SAAS,yBACf,OACA,KAC8B;AAC9B,QAAM,aAAa,mBAAmB,OAAO,GAAG;AAChD,MAAI,WAAW,WAAW,aAAa;AACtC,WAAO,EAAE,QAAQ,eAAe,QAAQ,iBAAiB;AAAA,EAC1D;AACA,MAAI,WAAW,WAAW,eAAe;AACxC,WAAO,EAAE,QAAQ,eAAe,QAAQ,cAAc;AAAA,EACvD;AAEA,QAAM,aAAa,wBAAwB,WAAW,QAAQ;AAC9D,SAAO;AAAA,IACN,QAAQ;AAAA,IACR,YAAY,iBAAiB,UAAU,IAAI,WAAW,KAAK;AAAA,IAC3D;AAAA,IACA,KAAK,qBAAqB,WAAW,QAAQ;AAAA,EAC9C;AACD;AAGO,SAAS,wBACf,OACA,YAC8B;AAC9B,QAAM,MACL,OAAO,eAAe,YAAY,eAAe,OAC9C,aACA,EAAE,IAAI,WAAW;AACrB,SAAO,yBAAyB,OAAO,GAAG;AAC3C;AAGO,SAAS,wBACf,OACA,YACuD;AACvD,QAAM,aAAa,wBAAwB,OAAO,UAAU;AAC5D,MAAI,WAAW,WAAW,aAAc,QAAO;AAC/C,SAAO,OAAO;AAAA,IACb,OAAO,QAAQ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U,SAAS,SAAY,SAAS,IAAI,SAAS,IAAI;AAAA;AAAA,EAC9E,GACD;AAEF;;;ACgCO,SAAS,iBAAiB,QAAoC,aAAoC;AACxG,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,UAAU;AAIhB,UAAQ,qBAAqB;AAC7B,SAAO;AACR;AAcO,IAAM,sBAAoD;AAAA;AAAA,EAEhE,MAAM;AAAA,EACN,SAAS;AAAA;AAAA,EAET,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS;AAAA,EACT,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,QAAQ;AAAA;AAAA,EAER,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,QAAQ;AAAA;AAAA,EAER,MAAM;AAAA,EACN,UAAU;AAAA,EACV,aAAa;AAAA,EACb,MAAM;AAAA;AAAA,EAEN,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,uBAAuB;AAAA;AAAA,EAEvB,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,MAAM;AAAA,EACN,KAAK;AAAA;AAAA,EAEL,OAAO;AAAA,EACP,cAAc;AAAA,EACd,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,cAAc;AAAA,EACd,MAAM;AAAA;AAAA,EAEN,MAAM;AAAA,EACN,OAAO;AACR;AASO,SAAS,oBACf,SACA,UAC2B;AAC3B,SAAO,WAAW,OAAO,KAAK,oBAAoB,OAAO;AAC1D;","names":["useQuery","createError","buildSelect","toCamelCasePlural","toCamelCaseSingular","TypedDocumentString","TypedDocumentString","createError","useQuery","totalCount","data","buildSelect","toCamelCaseSingular","toCamelCasePlural","canHandle","create","canHandle","create","canHandle","create","canHandle","create","canHandle","create","label","canHandle","create","canHandle","create","useMemo","useMemo","useMemo","useRef","useMutation","useQueryClient","cleanTable","toCamelCaseSingular","toPatchFieldName","toUpdateMutationName","toUpdateMutationName","toCamelCaseSingular","toPatchFieldName","useQueryClient","useMemo","cleanTable","useRef","useMutation","useMemo","useQueryClient","cleanTable","createError","toOrderByEnumValue","useQueryClient","useMemo","cleanTable","createError","toOrderByEnumValue","useEffect","useMemo","useRef","jsx","useMemo","useRef","useEffect","add","handleSave","remove","handleCancel","input","jsx","jsx","Suspense","lazy","Suspense","useCallback","useLayoutEffect","useMemo","useRef","useState","Map","Button","jsx","jsxs","lazy","useMemo","useState","useCallback","useRef","useLayoutEffect","Map","Button","Suspense","jsx","Suspense","Suspense","useCallback","useContext","useEffect","useMemo","useRef","useState","Loader2","XIcon","useEffect","useState","Button","useMemo","useState","jsx","useMemo","useState","Fragment","jsx","jsxs","XIcon","useState","useContext","useMemo","useRef","useCallback","useEffect","Loader2","Button","jsx","Suspense","useCallback","useEffect","useRef","useState","Button","jsx","jsxs","MAC_UA_RE","useState","useRef","useCallback","useEffect","handleSave","handleCancel","Button","jsx","useCallback","useState","Button","jsx","jsxs","useState","useCallback","Button","jsx","useCallback","useEffect","useMemo","useRef","useState","Button","jsx","jsxs","MAC_UA_RE","useState","useRef","useMemo","useCallback","useEffect","handleSave","handleCancel","Button","jsx","useRef","useState","Button","jsx","jsxs","useState","useRef","Button","useCallback","useContext","useEffect","useLayoutEffect","useMemo","useRef","useState","Check","Loader2","X","useQueryClient","Badge","Button","Label","toast","useRef","useState","jsx","jsxs","useState","useRef","jsx","jsxs","useQueryClient","useEffect","useMemo","useContext","useRef","useState","useLayoutEffect","useCallback","toast","Badge","Label","Button","X","Check","Loader2","jsx","DRAFT_PREFIX","useRef","useState","Button","jsx","jsxs","useState","useRef","Button","useCallback","useMemo","Search","X","Button","Label","jsx","jsxs","useMemo","useCallback","Search","Label","Button","X","jsx","useCallback","useState","Check","Link","X","Button","Input","Label","jsx","jsxs","useState","useCallback","Link","Label","Input","Button","X","Check","jsx"]}