import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import type { CSSProperties } from "react"; import { CatalogApplicationView } from "../customer-grid/CatalogView"; import { GalleryView, TimelineView } from "../customer-grid/GalleryTimelineViews"; import { MapView } from "../customer-grid/MapView"; import { SwipeView } from "../customer-grid/SwipeView"; import { CalendarView, KanbanView, ListView } from "../customer-grid/viewModes"; import type { Field, Row } from "../customer-grid/types"; import { splitAddress, chartPaneProjections, lockstepScrollX } from "./sheetState"; import { fetchViewRows, showingLine, viewBlockGeometry } from "./viewPlacement"; import type { SheetTab, ViewBinding, ViewRowsAnswer } from "./types"; import { viewBlockSize } from "./types"; // CustomerGrid normally supplies the bounded scroller used by Gallery and Timeline. import "../styles/wave50/grid.css"; import "../styles/wave55/apps.css"; interface SheetViewLayerProps { workbookId: string; tab: SheetTab; busy: boolean; visCols: number[]; visRows: number[]; columns: readonly { width: number }[]; columnX: (index: number) => number; rowHeightAt: (index: number) => number; frozenCols: number; bandRows: number; headerHeight: number; viewport: { x: number; y: number; tx: number; ty: number }; onResize: (origin: string, block: { cols: number; rows: number }) => void; onNotice: (message: string) => void; onUndo: () => void; onRedo: () => void; } const boundary = (visible: number[], real: number) => { const index = visible.findIndex(value => value >= real); return index < 0 ? visible.length : index; }; const ignore = () => undefined; /** These are row renderers only. The resolver, never an embedded grid, owns their data scope. */ function ViewContent({ answer, binding, onNotice }: { answer: ViewRowsAnswer; binding: ViewBinding; onNotice: (message: string) => void; }) { const fields = useMemo(() => answer.fields.map(field => ({ key: field.key, label: field.label, type: (field.kind === "number" ? "int" : field.kind) as Field["type"], source: "odoo", ...(field.kind === "select" ? { options: [...new Set(answer.rows .map(row => String(row[field.key] ?? "")).filter(Boolean))] } : {}), })), [answer]); const rows = useMemo(() => answer.rows.filter(row => typeof row.pid === "number") .map(row => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, value == null || typeof value === "string" || typeof value === "number" ? value : typeof value === "object" ? JSON.stringify(value) : String(value)])) as Row), [answer]); const fieldByKey = useMemo(() => new Map(fields.map(field => [field.key, field])), [fields]); const visibleKeys = fields.map(field => field.key); const title = fields[0]; const date = fields.find(field => field.type === "date" || field.type === "created_time"); const stack = fields.find(field => field.type === "select" || field.type === "status"); const [selectedPids, setSelectedPids] = useState>(new Set()); const onOpen = () => onNotice("Open it in Table for details."); if (!title) return
Choose fields for this view.
; const common = { rows, fields, fieldByKey, titleKey: title.key, onOpen }; switch (binding.viewType) { case "gallery": return ; case "timeline": return date ? :
Choose a date field for this view.
; case "calendar": return date ? :
Choose a date field for this view.
; case "list": return ({ kind: "data", record }))} onToggleGroup={ignore} />; case "kanban": return stack ? key !== title.key && key !== stack.key)} canMove={false} readOnlyReason={null} onMove={ignore} onAddOption={null} /> :
Choose a status or single-select field for this view.
; case "map": return setSelectedPids(before => new Set(mode === "add" ? [...before, ...pids] : pids))} onOpen={onOpen} routePanelOpen={false} activeView={null} tableKey={binding.database} />; case "catalog": return field.type === "image")?.key }, }} />; case "swipe": return ; default: return null; } } type Projection = ReturnType[number]; function ViewBlock({ origin, binding, workbookId, busy, projections, width, height, resized, onResize, onNotice, onUndo, onRedo }: { origin: string; binding: ViewBinding; workbookId: string; busy: boolean; projections: Projection[]; width: number; height: number; resized: (dx: number, dy: number) => { cols: number; rows: number; width: number; height: number }; onResize: SheetViewLayerProps["onResize"]; onNotice: SheetViewLayerProps["onNotice"]; onUndo: () => void; onRedo: () => void; }) { const query = JSON.stringify({ ...binding, block: undefined }); const [resolved, setResolved] = useState<{ key: string; answer?: ViewRowsAnswer; error?: string }>(); const [preview, setPreview] = useState | null>(null); const drag = useRef<{ x: number; y: number; binding: ViewBinding } | null>(null); const root = useRef(null); // The stored document contains only the binding and cell dimensions, never a second row store. useEffect(() => { if (busy) return; let current = true; setResolved(undefined); void fetchViewRows(workbookId, JSON.parse(query) as ViewBinding).then(result => { if (current) setResolved(result.ok ? { key: query, answer: result.answer } : { key: query, error: result.message }); }).catch(() => { if (current) setResolved({ key: query, error: "The view rows could not be read." }); }); return () => { current = false; }; }, [workbookId, query, busy]); useEffect(() => { setPreview(null); drag.current = null; }, [binding]); const boxWidth = preview?.width ?? width, boxHeight = preview?.height ?? height; const answer = !busy && resolved?.key === query ? resolved.answer : undefined; const error = !busy && resolved?.key === query ? resolved.error : undefined; const block = viewBlockSize(binding); const geometry = viewBlockGeometry(splitAddress(origin)!, binding); const buttonStyle: CSSProperties = { position: "absolute", right: 0, bottom: 0, width: 20, height: 20, padding: 2, border: 0, background: "var(--lp-surface)", font: "inherit", color: "var(--lp-muted)", cursor: "nwse-resize", touchAction: "none" }; return
{projections.map(p => { const ownsHandle = p.chartLeft + boxWidth > 0 && p.chartLeft + boxWidth <= p.width && p.chartTop + boxHeight > 0 && p.chartTop + boxHeight <= p.height; return
event.stopPropagation()} onWheel={event => event.stopPropagation()} onKeyDown={event => { event.stopPropagation(); if (event.target instanceof Element && event.target.closest("input, textarea, select, [contenteditable=true]")) return; if (!(event.ctrlKey || event.metaKey) || event.altKey) return; if (event.key.toLowerCase() === "z") { event.preventDefault(); (event.shiftKey ? onRedo : onUndo)(); } if (event.key.toLowerCase() === "y") { event.preventDefault(); onRedo(); } }} style={{ position: "absolute", left: p.chartLeft, top: p.chartTop, width: boxWidth, height: boxHeight, pointerEvents: "auto", overflow: "hidden", background: "var(--lp-surface)", border: "1px solid var(--lp-line)", boxSizing: "border-box" }}>
{ // Frozen-pane copies show the same part of each renderer's internal scrollbox. const source = event.target as HTMLElement; const container = event.currentTarget; const index = Array.from(container.querySelectorAll("*")).indexOf(source); root.current?.querySelectorAll(".sheet-view-content").forEach(copy => { if (copy === container) return; const target = index < 0 ? copy : copy.querySelectorAll("*")[index]; if (target && (target.scrollTop !== source.scrollTop || target.scrollLeft !== source.scrollLeft)) { target.scrollTop = source.scrollTop; target.scrollLeft = source.scrollLeft; } }); }}> {answer ? :
{error ?? "Loading view…"}
}
{answer ? showingLine(answer.rows.length, answer.total) : ""}
; })}
; } export default function SheetViewLayer({ workbookId, tab, busy, visCols, visRows, columns, columnX, rowHeightAt, frozenCols, bandRows, headerHeight, viewport, onResize, onNotice, onUndo, onRedo }: SheetViewLayerProps) { const root = useRef(null); const [size, setSize] = useState({ width: 0, height: 0 }); useLayoutEffect(() => { const node = root.current; if (!node) return; const measure = () => setSize({ width: node.clientWidth, height: node.clientHeight }); measure(); const observer = new ResizeObserver(measure); observer.observe(node); return () => observer.disconnect(); }, []); const rowOffsets = useMemo(() => { const offsets = [0]; for (let i = 0; i < visRows.length; i++) offsets.push(offsets[i] + rowHeightAt(i)); return offsets; }, [rowHeightAt, visRows.length]); const rowY = (index: number) => rowOffsets[Math.max(0, Math.min(index, visRows.length))] ?? 0; const frozenHeight = rowY(bandRows); const scrollX = lockstepScrollX(columns.map(column => column.width), frozenCols, viewport.x, viewport.tx); const scrollY = rowY(bandRows + viewport.y) - frozenHeight - viewport.ty; return
{/* ⛔ `tab.cells` IS LEGITIMATELY UNDEFINED ON A FIRST RENDER. `GET /sheets/{id}?tabs=meta` answers tabs with NO cells, so a tab the page has not fetched yet renders here with none, and `Object.entries(undefined)` throws inside a render. That is what "[Sheet] render failed TypeError: Cannot convert undefined or null to object" was, found by this lane's own Kanban screenshot. `SheetGrid.tsx` already guards its own read one line above the twin of this one. */} {Object.entries(tab.cells ?? {}).map(([origin, cell]) => { if (cell?.kind !== "bound" || cell.binding?.mode !== "view" || cell.binding.viewType === "grid" || !cell.binding.block) return null; const at = splitAddress(origin); if (!at) return null; const binding = cell.binding as ViewBinding, geometry = viewBlockGeometry(at, binding); const col = boundary(visCols, geometry.col0), row = boundary(visRows, geometry.row0); const endCol = boundary(visCols, geometry.col1 + 1), endRow = boundary(visRows, geometry.row1 + 1); const width = columnX(endCol) - columnX(col), height = rowY(endRow) - rowY(row); if (width <= 0 || height <= 0) return null; const projections = chartPaneProjections({ left: columnX(col), top: headerHeight + rowY(row) }, { ...size, markerWidth: columnX(0), headerHeight, frozenWidth: columnX(frozenCols) - columnX(0), frozenHeight, scrollX, scrollY, }); const nearest = (visible: number[], offset: (index: number) => number, start: number, target: number) => { let best = start + 1; for (let i = start + 2; i <= visible.length; i++) { if (Math.abs(offset(i) - target) < Math.abs(offset(best) - target)) best = i; } return best; }; return { const c = dx ? nearest(visCols, columnX, col, columnX(endCol) + dx) : endCol; const r = dy ? nearest(visRows, rowY, row, rowY(endRow) + dy) : endRow; return { cols: dx ? (visCols[c - 1] + 1) - geometry.col0 : viewBlockSize(binding).cols, rows: dy ? (visRows[r - 1] + 1) - geometry.row0 : viewBlockSize(binding).rows, width: columnX(c) - columnX(col), height: rowY(r) - rowY(row) }; }} />; })}
; }