Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 16,428 Bytes
c1fc133 8cbc29f c1fc133 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | 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<Field[]>(() => 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<Row[]>(() => 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<Set<number>>(new Set());
const onOpen = () => onNotice("Open it in Table for details.");
if (!title) return <div className="cg-mode-empty">Choose fields for this view.</div>;
const common = { rows, fields, fieldByKey, titleKey: title.key, onOpen };
switch (binding.viewType) {
case "gallery": return <GalleryView {...common} visibleKeys={visibleKeys} />;
case "timeline": return date ? <TimelineView {...common} visibleKeys={visibleKeys} field={date} />
: <div className="cg-mode-empty">Choose a date field for this view.</div>;
case "calendar": return date ? <CalendarView {...common} field={date} />
: <div className="cg-mode-empty">Choose a date field for this view.</div>;
case "list": return <ListView {...common} visibleKeys={visibleKeys}
rows={rows.map(record => ({ kind: "data", record }))} onToggleGroup={ignore} />;
case "kanban": return stack ? <KanbanView {...common} field={stack}
cardKeys={visibleKeys.filter(key => key !== title.key && key !== stack.key)}
canMove={false} readOnlyReason={null} onMove={ignore} onAddOption={null} />
: <div className="cg-mode-empty">Choose a status or single-select field for this view.</div>;
case "map": return <MapView rows={rows} field={title} selectedPids={selectedPids}
onSelectPids={(pids, mode) => setSelectedPids(before => new Set(mode === "add"
? [...before, ...pids] : pids))} onOpen={onOpen} routePanelOpen={false}
activeView={null} tableKey={binding.database} />;
case "catalog": return <CatalogApplicationView rows={rows} onOpen={onOpen} definition={{
id: "sheet", name: "Catalog", templateKind: "catalog", sourceDatabase: binding.database,
fieldMap: { key: "pid", title: title.key, image: fields.find(field => field.type === "image")?.key },
}} />;
case "swipe": return <SwipeView {...common} spec={undefined}
cardKeys={visibleKeys} canWrite={false} canBind={false} readOnlyReason={null}
onSpec={ignore} onSwipe={ignore} />;
default: return null;
}
}
type Projection = ReturnType<typeof chartPaneProjections>[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<ReturnType<typeof resized> | null>(null);
const drag = useRef<{ x: number; y: number; binding: ViewBinding } | null>(null);
const root = useRef<HTMLDivElement>(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 <div ref={root}>
{projections.map(p => {
const ownsHandle = p.chartLeft + boxWidth > 0 && p.chartLeft + boxWidth <= p.width
&& p.chartTop + boxHeight > 0 && p.chartTop + boxHeight <= p.height;
return <div key={p.pane} data-pane={p.pane} style={{ position: "absolute", overflow: "hidden",
pointerEvents: "none", left: p.left, top: p.top, width: p.width, height: p.height }}>
<section className="sheet-view-block" data-view-origin={origin} data-view-type={binding.viewType}
data-col0={geometry.col0} data-row0={geometry.row0} data-col1={geometry.col1} data-row1={geometry.row1}
aria-label={`${binding.viewType} view at ${origin}`}
onPointerDown={event => 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" }}>
<div className="sheet-view-content" style={{ width: Math.max(0, boxWidth - 2),
height: Math.max(0, boxHeight - 26), overflow: "auto", overscrollBehavior: "contain" }}
onScrollCapture={event => {
// 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<HTMLElement>(".sheet-view-content").forEach(copy => {
if (copy === container) return;
const target = index < 0 ? copy : copy.querySelectorAll<HTMLElement>("*")[index];
if (target && (target.scrollTop !== source.scrollTop || target.scrollLeft !== source.scrollLeft)) {
target.scrollTop = source.scrollTop; target.scrollLeft = source.scrollLeft;
}
});
}}>
{answer ? <ViewContent answer={answer} binding={binding} onNotice={onNotice} />
: <div className="cg-mode-empty" role={error ? "alert" : "status"}>{error ?? "Loading view…"}</div>}
</div>
<div style={{ height: 24, padding: "4px 24px 4px 8px", boxSizing: "border-box",
color: "var(--lp-muted)", fontSize: "var(--lp-fs-3xs)", whiteSpace: "nowrap", overflow: "hidden" }}>
{answer ? showingLine(answer.rows.length, answer.total) : ""}
</div>
<button type="button" aria-label={`Resize ${binding.viewType} view at ${origin}`}
title={`${block.cols} columns × ${block.rows} rows. Drag or use the arrow keys to resize.`}
tabIndex={ownsHandle ? 0 : -1} style={buttonStyle} disabled={busy}
onPointerDown={event => {
if (event.button !== 0) return;
event.preventDefault(); event.stopPropagation(); event.currentTarget.focus();
event.currentTarget.setPointerCapture(event.pointerId);
drag.current = { x: event.clientX, y: event.clientY, binding };
}}
onPointerMove={event => { if (drag.current) setPreview(resized(
event.clientX - drag.current.x, event.clientY - drag.current.y)); }}
onPointerUp={event => {
const start = drag.current;
drag.current = null; setPreview(null);
if (!start || start.binding !== binding) return;
const next = resized(event.clientX - start.x, event.clientY - start.y);
if (next.cols !== block.cols || next.rows !== block.rows) onResize(origin, next);
}}
onPointerCancel={() => { drag.current = null; setPreview(null); }}
onLostPointerCapture={() => { drag.current = null; setPreview(null); }}
onKeyDown={event => {
if (event.key === "Escape") { drag.current = null; setPreview(null); return; }
if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
event.preventDefault(); event.stopPropagation();
onResize(origin, { cols: Math.max(1, block.cols + (event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0)),
rows: Math.max(1, block.rows + (event.key === "ArrowDown" ? 1 : event.key === "ArrowUp" ? -1 : 0)) });
}}>
<svg viewBox="0 0 16 16" aria-hidden="true" width="16" height="16" fill="none" stroke="currentColor">
<path d="M5 13 13 5M9 13l4-4" />
</svg>
</button>
</section>
</div>;
})}
</div>;
}
export default function SheetViewLayer({ workbookId, tab, busy, visCols, visRows, columns, columnX,
rowHeightAt, frozenCols, bandRows, headerHeight, viewport, onResize, onNotice, onUndo, onRedo }: SheetViewLayerProps) {
const root = useRef<HTMLDivElement>(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 <div className="sheet-view-layer" ref={root} style={{ position: "absolute", inset: 0,
pointerEvents: "none", overflow: "hidden", zIndex: "var(--cg-z-editor)" }}>
{/* ⛔ `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 <ViewBlock key={`${workbookId}/${tab.id}/${origin}`} {...{ origin, binding, workbookId, busy,
projections, width, height, onResize, onNotice, onUndo, onRedo }} resized={(dx, dy) => {
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) };
}} />;
})}
</div>;
}
|