Files
mnote/wolai-frontend/src/components/online-table/FullScreenTableEditor.tsx
T

354 lines
12 KiB
TypeScript
Raw Normal View History

"use client";
2025-11-23 20:04:29 +08:00
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Loader2, Table, X, Zap } from "lucide-react";
import type { DocumentTable, TableRowData } from "@/types/online-table";
import {
DEFAULT_TABLE_COLUMNS,
DEFAULT_TABLE_ROWS,
DEFAULT_TABLE_SCHEMA,
createDefaultTableSnapshot,
saveOnlineTable,
} from "@/lib/online-table";
import { useDebouncedCallback } from "@/hooks/use-debounced-callback";
interface FullScreenTableEditorProps {
tableId: string;
onClose: () => void;
}
// Luckysheet 容器的 ID
const LUCKY_SHEET_CONTAINER_ID = "luckysheet-editor-container";
// Luckysheet 资源路径 (相对于 public 目录)
const LUCKY_SHEET_RESOURCES = {
css: [
"/luckysheet/css/luckysheet.css",
"/luckysheet/plugins/plugins.css",
"/luckysheet/plugins/css/pluginsCss.css",
"/luckysheet/assets/iconfont/iconfont.css",
],
js: [
"/luckysheet/plugins/js/plugin.js",
"/luckysheet/luckysheet.umd.js",
],
};
2025-11-23 20:04:29 +08:00
const extractRowsForPreview = (luckysheetData: any, columns: Array<{ id: string }>): TableRowData[] => {
const sheet = Array.isArray(luckysheetData) ? luckysheetData[0] : null;
if (!sheet) return [];
const columnIds = columns.length > 0 ? columns.map((item) => item.id) : Array.from({ length: DEFAULT_TABLE_COLUMNS }, (_, idx) => `col${idx + 1}`);
const rows: TableRowData[] = [];
const grid = Array.isArray(sheet.data) ? sheet.data : [];
const pickValue = (cell: any) => {
if (!cell) return undefined;
if (cell.m !== undefined && cell.m !== null) return cell.m;
if (cell.v?.m !== undefined && cell.v?.m !== null) return cell.v.m;
if (cell.v?.v !== undefined && cell.v?.v !== null) return cell.v.v;
if (cell.v !== undefined && cell.v !== null && typeof cell.v !== "object") return cell.v;
if (cell.w !== undefined && cell.w !== null) return cell.w;
return undefined;
};
grid.forEach((row: any[], rowIndex: number) => {
if (!Array.isArray(row)) return;
const rowObj: TableRowData = {};
let hasValue = false;
columnIds.forEach((colId, colIndex) => {
const value = pickValue(row[colIndex]);
if (value !== undefined && value !== null && value !== "") {
rowObj[colId] = value;
hasValue = true;
}
});
if (hasValue) {
rows.push(rowObj);
}
});
if (rows.length === 0 && Array.isArray(sheet.celldata)) {
const map = new Map<number, TableRowData>();
sheet.celldata.forEach((cell: { r: number; c: number; v: unknown }) => {
const value = pickValue(cell?.v ?? cell);
if (value === undefined || value === null || value === "") return;
const existing = map.get(cell.r) ?? {};
existing[columnIds[cell.c] ?? `col${cell.c + 1}`] = value;
map.set(cell.r, existing);
});
Array.from(map.entries())
.sort(([a], [b]) => a - b)
.forEach(([, row]) => rows.push(row));
}
return rows;
};
const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId, onClose }) => {
const containerRef = useRef<HTMLDivElement>(null);
2025-11-23 20:04:29 +08:00
const isApplyingSnapshotRef = useRef(false);
const hasInitializedRef = useRef(false);
const lastTableIdRef = useRef<string | null>(null);
const [isLoaded, setIsLoaded] = useState(false);
const [tableData, setTableData] = useState<DocumentTable | null>(null);
const [isTableLoading, setIsTableLoading] = useState(true);
const [tableError, setTableError] = useState<string | null>(null);
2025-11-23 20:04:29 +08:00
const [isSaving, setIsSaving] = useState(false);
const [hasPendingChanges, setHasPendingChanges] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);
const persistSnapshotRef = useRef<((reason: "auto" | "close") => Promise<void>) | null>(null);
2025-11-23 20:04:29 +08:00
const fetchTable = useCallback((id: string) => {
setIsTableLoading(true);
setTableError(null);
setTableData(null);
fetch(`/api/tables/${id}`)
.then((response) => {
if (!response.ok) {
throw new Error(`Failed to load table ${id}`);
}
return response.json() as Promise<DocumentTable>;
})
.then((data) => {
setTableData(data);
})
.catch((error) => {
console.error(error);
setTableError("无法加载表格数据,请稍后重试。");
setTableData(null);
})
.finally(() => setIsTableLoading(false));
2025-11-23 20:04:29 +08:00
}, []);
useEffect(() => {
fetchTable(tableId);
2025-11-23 20:04:29 +08:00
hasInitializedRef.current = false;
lastTableIdRef.current = tableId;
}, [fetchTable, tableId]);
// 动态加载 Luckysheet 资源
useEffect(() => {
if (window.luckysheet) {
setIsLoaded(true);
return;
}
const loadResource = (tag: "link" | "script", url: string) => {
if (document.querySelector(`${tag}[href="${url}"]`) || document.querySelector(`${tag}[src="${url}"]`)) {
return true;
}
2025-11-23 20:04:29 +08:00
if (tag === "link") {
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
document.head.appendChild(link);
return true;
} else if (tag === "script") {
return new Promise<void>((resolve) => {
const script = document.createElement("script");
script.src = url;
script.onload = () => resolve();
document.body.appendChild(script);
});
}
return false;
};
2025-11-23 20:04:29 +08:00
LUCKY_SHEET_RESOURCES.css.forEach((url) => loadResource("link", url));
const loadJsSequentially = async () => {
for (const url of LUCKY_SHEET_RESOURCES.js) {
await loadResource("script", url);
}
setIsLoaded(true);
};
loadJsSequentially();
}, []);
2025-11-23 20:04:29 +08:00
const luckysheetSheets = useMemo(() => {
if (tableData?.snapshot?.luckysheet && Array.isArray(tableData.snapshot.luckysheet) && tableData.snapshot.luckysheet.length > 0) {
return tableData.snapshot.luckysheet;
}
const snapshot = createDefaultTableSnapshot(tableData?.schema ?? DEFAULT_TABLE_SCHEMA);
return snapshot.luckysheet ?? [];
2025-11-23 20:04:29 +08:00
}, [tableData]);
const persistSnapshot = useCallback(async (reason: "auto" | "close") => {
if (!tableData || !window.luckysheet || typeof window.luckysheet.getluckysheetfile !== "function") {
return;
}
setIsSaving(true);
setSaveError(null);
try {
const luckysheetData = window.luckysheet.getluckysheetfile?.() ?? luckysheetSheets;
const rows = extractRowsForPreview(
luckysheetData,
(tableData.schema?.columns ?? []).map((item) => ({ id: item.id })),
).filter((row) => row && typeof row === "object" && Object.keys(row).length > 0);
const snapshot = {
...(tableData.snapshot ?? {}),
rows,
luckysheet: Array.isArray(luckysheetData) ? luckysheetData : luckysheetSheets,
};
const updated = await saveOnlineTable(tableId, {
snapshot,
rows,
schema: tableData.schema,
});
setTableData(updated);
setHasPendingChanges(false);
setLastSyncedAt(Date.now());
window.dispatchEvent(new CustomEvent("online-table-saved", { detail: { tableId } }));
} catch (error) {
console.error("保存 Luckysheet 数据失败", error);
setSaveError(reason === "close" ? "关闭前保存失败,请重试" : "自动保存失败");
} finally {
setIsSaving(false);
}
}, [tableData, tableId]);
const debouncedPersist = useDebouncedCallback(() => {
void persistSnapshot("auto");
}, 1200);
useEffect(() => {
persistSnapshotRef.current = persistSnapshot;
}, [persistSnapshot]);
useEffect(() => {
return () => {
debouncedPersist.cancel();
void persistSnapshotRef.current?.("close");
};
}, [debouncedPersist]);
// Luckysheet 初始化和清理
useEffect(() => {
if (!isLoaded || !tableData || !containerRef.current || !window.luckysheet) {
return;
}
2025-11-23 20:04:29 +08:00
if (hasInitializedRef.current && lastTableIdRef.current === tableId) {
return;
}
hasInitializedRef.current = true;
isApplyingSnapshotRef.current = true;
if (containerRef.current.children.length > 0) {
window.luckysheet.destroy(LUCKY_SHEET_CONTAINER_ID);
containerRef.current.innerHTML = "";
}
const options = {
container: LUCKY_SHEET_CONTAINER_ID,
title: tableData.title ?? tableId,
lang: "zh",
showinfobar: false,
showtoolbar: true,
showsheetbar: true,
showstatisticBar: true,
allowEdit: true,
row: DEFAULT_TABLE_ROWS,
column: DEFAULT_TABLE_COLUMNS,
2025-11-23 20:04:29 +08:00
data: luckysheetSheets,
hook: {
updated: () => {
if (isApplyingSnapshotRef.current) return;
setHasPendingChanges(true);
debouncedPersist();
},
},
};
window.luckysheet.create(options);
2025-11-23 20:04:29 +08:00
// 等待首帧渲染完成再开放 updated 事件
setTimeout(() => {
isApplyingSnapshotRef.current = false;
}, 0);
return () => {
if (window.luckysheet) {
window.luckysheet.destroy(LUCKY_SHEET_CONTAINER_ID);
}
};
2025-11-23 20:04:29 +08:00
}, [debouncedPersist, luckysheetSheets, isLoaded, tableData, tableId]);
const handleClose = async () => {
await persistSnapshot("close");
onClose();
};
const showLoadingOverlay = !isLoaded || isTableLoading;
const loadingMessage = !isLoaded ? "正在加载 Luckysheet 资源..." : "正在加载表格数据...";
2025-11-23 20:04:29 +08:00
const statusText = saveError
? saveError
: isSaving
? "同步中..."
: hasPendingChanges
? "有未保存变更"
: lastSyncedAt
? `已同步 ${new Date(lastSyncedAt).toLocaleTimeString()}`
: "准备就绪";
return (
<div className="fixed inset-0 z-50 bg-white dark:bg-gray-900 flex flex-col">
{/* 顶部工具栏 */}
<header className="flex justify-between items-center p-3 border-b border-gray-200 shadow-sm">
<div className="flex items-center space-x-3">
<Table className="h-5 w-5 text-blue-500" />
<h1 className="text-lg font-bold">
2025-11-23 20:04:29 +08:00
在线表格编辑 - {(tableData?.title ?? tableId).slice(0, 24)}
</h1>
<Zap className="h-4 w-4 text-yellow-500" />
<span className="text-xs text-yellow-600 font-medium" title="协同模式">协同模式 (单用户模式)</span>
</div>
2025-11-23 20:04:29 +08:00
<div className="flex items-center space-x-3">
<span className="text-xs text-gray-500">{statusText}</span>
<button
onClick={handleClose}
className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
title="退出并保存"
>
{isSaving ? <Loader2 className="h-5 w-5 animate-spin" /> : <X className="h-5 w-5" />}
</button>
</div>
</header>
{/* Luckysheet 容器 */}
<div
id={LUCKY_SHEET_CONTAINER_ID}
ref={containerRef}
className="flex-grow w-full h-full"
2025-11-23 20:04:29 +08:00
style={{ display: isLoaded && !isTableLoading && !tableError ? "block" : "none" }}
/>
{showLoadingOverlay && (
<div className="flex justify-center items-center h-full text-gray-500 border border-dashed">
2025-11-23 20:04:29 +08:00
<p>{loadingMessage}</p>
</div>
)}
{tableError && !showLoadingOverlay && (
<div className="flex flex-col justify-center items-center h-full text-red-500 border border-dashed space-y-2">
<p>{tableError}</p>
<button
type="button"
className="px-3 py-1 rounded-md border border-red-300 text-sm"
onClick={() => fetchTable(tableId)}
>
重试
</button>
</div>
)}
</div>
);
};
export default FullScreenTableEditor;