chore: save current changes
This commit is contained in:
@@ -1,9 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { Table, X, Zap } from "lucide-react";
|
||||
import type { DocumentTable } from "@/types/online-table";
|
||||
import { DEFAULT_TABLE_COLUMNS, DEFAULT_TABLE_ROWS, DEFAULT_TABLE_SCHEMA, createDefaultTableSnapshot } from "@/lib/online-table";
|
||||
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;
|
||||
@@ -27,14 +34,72 @@ const LUCKY_SHEET_RESOURCES = {
|
||||
],
|
||||
};
|
||||
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
|
||||
const fetchTable = (id: string) => {
|
||||
const fetchTable = useCallback((id: string) => {
|
||||
setIsTableLoading(true);
|
||||
setTableError(null);
|
||||
setTableData(null);
|
||||
@@ -54,11 +119,13 @@ const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId,
|
||||
setTableData(null);
|
||||
})
|
||||
.finally(() => setIsTableLoading(false));
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchTable(tableId);
|
||||
}, [tableId]);
|
||||
hasInitializedRef.current = false;
|
||||
lastTableIdRef.current = tableId;
|
||||
}, [fetchTable, tableId]);
|
||||
|
||||
// 动态加载 Luckysheet 资源
|
||||
useEffect(() => {
|
||||
@@ -71,7 +138,7 @@ const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId,
|
||||
if (document.querySelector(`${tag}[href="${url}"]`) || document.querySelector(`${tag}[src="${url}"]`)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
if (tag === "link") {
|
||||
const link = document.createElement("link");
|
||||
link.rel = "stylesheet";
|
||||
@@ -89,10 +156,8 @@ const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId,
|
||||
return false;
|
||||
};
|
||||
|
||||
// 加载所有 CSS
|
||||
LUCKY_SHEET_RESOURCES.css.forEach(url => loadResource("link", url));
|
||||
LUCKY_SHEET_RESOURCES.css.forEach((url) => loadResource("link", url));
|
||||
|
||||
// 串行加载 JS,确保顺序
|
||||
const loadJsSequentially = async () => {
|
||||
for (const url of LUCKY_SHEET_RESOURCES.js) {
|
||||
await loadResource("script", url);
|
||||
@@ -101,16 +166,64 @@ const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId,
|
||||
};
|
||||
|
||||
loadJsSequentially();
|
||||
|
||||
}, []);
|
||||
|
||||
const getLuckysheetSheets = () => {
|
||||
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 ?? [];
|
||||
};
|
||||
}, [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(() => {
|
||||
@@ -118,6 +231,13 @@ const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId,
|
||||
return;
|
||||
}
|
||||
|
||||
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 = "";
|
||||
@@ -134,22 +254,48 @@ const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId,
|
||||
allowEdit: true,
|
||||
row: DEFAULT_TABLE_ROWS,
|
||||
column: DEFAULT_TABLE_COLUMNS,
|
||||
data: getLuckysheetSheets(),
|
||||
data: luckysheetSheets,
|
||||
hook: {
|
||||
updated: () => {
|
||||
if (isApplyingSnapshotRef.current) return;
|
||||
setHasPendingChanges(true);
|
||||
debouncedPersist();
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
window.luckysheet.create(options);
|
||||
|
||||
// 等待首帧渲染完成再开放 updated 事件
|
||||
setTimeout(() => {
|
||||
isApplyingSnapshotRef.current = false;
|
||||
}, 0);
|
||||
|
||||
return () => {
|
||||
if (window.luckysheet) {
|
||||
window.luckysheet.destroy(LUCKY_SHEET_CONTAINER_ID);
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tableId, isLoaded, tableData]);
|
||||
}, [debouncedPersist, luckysheetSheets, isLoaded, tableData, tableId]);
|
||||
|
||||
const handleClose = async () => {
|
||||
await persistSnapshot("close");
|
||||
onClose();
|
||||
};
|
||||
|
||||
const showLoadingOverlay = !isLoaded || isTableLoading;
|
||||
const loadingMessage = !isLoaded ? "正在加载 Luckysheet 资源..." : "正在加载表格数据...";
|
||||
|
||||
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">
|
||||
{/* 顶部工具栏 */}
|
||||
@@ -157,34 +303,34 @@ const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId,
|
||||
<div className="flex items-center space-x-3">
|
||||
<Table className="h-5 w-5 text-blue-500" />
|
||||
<h1 className="text-lg font-bold">
|
||||
在线表格编辑 - {(tableData?.title ?? tableId).slice(0, 16)}
|
||||
在线表格编辑 - {(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>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors"
|
||||
title="退出全屏"
|
||||
>
|
||||
<X className="h-5 w-5" />
|
||||
</button>
|
||||
<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 容器 */}
|
||||
{/* 确保容器在加载完成后可见,并使用 ref 绑定 */}
|
||||
<div
|
||||
id={LUCKY_SHEET_CONTAINER_ID}
|
||||
ref={containerRef}
|
||||
className="flex-grow w-full h-full"
|
||||
style={{ display: isLoaded && !isTableLoading && !tableError ? 'block' : 'none' }}
|
||||
>
|
||||
{/* Luckysheet 将在这个容器中初始化 */}
|
||||
</div>
|
||||
style={{ display: isLoaded && !isTableLoading && !tableError ? "block" : "none" }}
|
||||
/>
|
||||
|
||||
{showLoadingOverlay && (
|
||||
<div className="flex justify-center items-center h-full text-gray-500 border border-dashed">
|
||||
<p>{loadingMessage}</p>
|
||||
<p>{loadingMessage}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user