feat: integrate luckysheet inline and fullscreen
This commit is contained in:
@@ -26,6 +26,7 @@ import { DocumentToc, type TocEntry } from "@/components/editor/document-toc";
|
||||
import { useSearchPaletteStore } from "@/store/search-palette";
|
||||
import { useEditorBridgeStore } from "@/store/editor-bridge";
|
||||
import type { ReferenceTarget } from "@/types/search";
|
||||
import FullScreenTableEditor from "@/components/online-table/FullScreenTableEditor";
|
||||
|
||||
interface BlockNoteEditorProps {
|
||||
documentId: string;
|
||||
@@ -168,6 +169,8 @@ export function BlockNoteEditor({
|
||||
}: BlockNoteEditorProps) {
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [tocEntries, setTocEntries] = useState<TocEntry[]>([]);
|
||||
const [fullScreenTableId, setFullScreenTableId] = useState<string | null>(null);
|
||||
|
||||
const openReferencePalette = useSearchPaletteStore((state) => state.openReference);
|
||||
const registerEditorBridge = useEditorBridgeStore((state) => state.registerBridge);
|
||||
|
||||
@@ -423,6 +426,9 @@ const computeDocumentStats = (blocks: Block<CustomBlockSchema>[]): DocumentStats
|
||||
return;
|
||||
}
|
||||
const bridge = {
|
||||
openTableFullScreen: (tableId: string) => {
|
||||
setFullScreenTableId(tableId);
|
||||
},
|
||||
insertInlineReference: (target: ReferenceTarget, aliasText?: string) => {
|
||||
editor.focus();
|
||||
const cursor = editor.getTextCursorPosition();
|
||||
@@ -559,27 +565,37 @@ const computeDocumentStats = (blocks: Block<CustomBlockSchema>[]): DocumentStats
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={layoutClass}>
|
||||
<div className={editorWrapperClass}>
|
||||
<BlockNoteView
|
||||
editor={editor}
|
||||
theme="light"
|
||||
data-heading-numbering={pageOptions.showHeadingNumbers ? "true" : "false"}
|
||||
editable={!pageOptions.protectEditing}
|
||||
className={blocknoteClass}
|
||||
>
|
||||
<SideMenuController
|
||||
sideMenu={(props: SideMenuProps<CustomBlockSchema>) => (
|
||||
<CustomSideMenu {...props} currentDocumentId={documentId} />
|
||||
)}
|
||||
/>
|
||||
<CustomSlashMenu editor={editor} currentDocumentId={documentId} />
|
||||
</BlockNoteView>
|
||||
<div className="pointer-events-none absolute right-4 top-3 text-xs text-gray-400">
|
||||
{isSaving ? "保存中..." : "已保存"}
|
||||
<>
|
||||
<div className={layoutClass}>
|
||||
<div className={editorWrapperClass}>
|
||||
<BlockNoteView
|
||||
editor={editor}
|
||||
theme="light"
|
||||
data-heading-numbering={pageOptions.showHeadingNumbers ? "true" : "false"}
|
||||
editable={!pageOptions.protectEditing}
|
||||
className={blocknoteClass}
|
||||
>
|
||||
<SideMenuController
|
||||
sideMenu={(props: SideMenuProps<CustomBlockSchema>) => (
|
||||
<CustomSideMenu {...props} currentDocumentId={documentId} />
|
||||
)}
|
||||
/>
|
||||
<CustomSlashMenu editor={editor} currentDocumentId={documentId} />
|
||||
</BlockNoteView>
|
||||
<div className="pointer-events-none absolute right-4 top-3 text-xs text-gray-400">
|
||||
{isSaving ? "保存中..." : "已保存"}
|
||||
</div>
|
||||
</div>
|
||||
<DocumentToc entries={tocEntries} visible={pageOptions.showToc} onJump={jumpToHeading} />
|
||||
</div>
|
||||
<DocumentToc entries={tocEntries} visible={pageOptions.showToc} onJump={jumpToHeading} />
|
||||
</div>
|
||||
|
||||
{/* 全屏表格编辑器 Modal */}
|
||||
{fullScreenTableId && (
|
||||
<FullScreenTableEditor
|
||||
tableId={fullScreenTableId}
|
||||
onClose={() => setFullScreenTableId(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { BlockNoteEditor, Block } from "@blocknote/core";
|
||||
import { createReactBlockSpec } from "@blocknote/react";
|
||||
import { OnlineTableBlockProps } from "@/types/online-table";
|
||||
import { Table } from "lucide-react";
|
||||
import React from "react";
|
||||
import type { CustomBlockSchema } from "../schema";
|
||||
import CompactTablePreview from "@/components/online-table/CompactTablePreview";
|
||||
import { useEditorBridgeStore } from "@/store/editor-bridge";
|
||||
|
||||
// 占位符组件:在紧凑模式下渲染表格块
|
||||
const OnlineTableBlockComponent = ({
|
||||
block,
|
||||
editor,
|
||||
}: {
|
||||
block: Block<CustomBlockSchema, "onlineTable">;
|
||||
editor: BlockNoteEditor<CustomBlockSchema>;
|
||||
}) => {
|
||||
const { tableId } = block.props;
|
||||
const openTableFullScreen = useEditorBridgeStore((state) => state.bridge?.openTableFullScreen);
|
||||
|
||||
// 阶段三:实现双击/按钮进入全屏编辑
|
||||
const handleFullScreen = () => {
|
||||
if (openTableFullScreen) {
|
||||
openTableFullScreen(tableId);
|
||||
} else {
|
||||
console.error("Editor bridge not ready or openTableFullScreen missing.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<CompactTablePreview tableId={tableId} onFullScreen={handleFullScreen} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Block Spec 定义
|
||||
export const onlineTableBlock = createReactBlockSpec(
|
||||
{
|
||||
type: "onlineTable",
|
||||
propSchema: {
|
||||
tableId: { default: "new-table-id" }, // 应该在创建时被覆盖
|
||||
title: { default: "未命名表格" },
|
||||
},
|
||||
content: "inline", // 允许内联内容,但通常表格块不会有太多内联内容
|
||||
},
|
||||
{
|
||||
render: (props) => <OnlineTableBlockComponent {...props} />,
|
||||
}
|
||||
);
|
||||
@@ -20,10 +20,12 @@ import {
|
||||
Play,
|
||||
Sparkles,
|
||||
SquareCheckBig,
|
||||
Table,
|
||||
} from "lucide-react";
|
||||
import type { CustomBlockSchema } from "../schema";
|
||||
import { useImagePicker } from "@/components/media/image-picker-context";
|
||||
import type { MediaKind, MediaSelection } from "@/types/media";
|
||||
import { createOnlineTable } from "@/lib/online-table";
|
||||
|
||||
type Props = {
|
||||
editor: BlockNoteEditor<CustomBlockSchema>;
|
||||
@@ -134,6 +136,33 @@ export const CustomSlashMenu = ({ editor, currentDocumentId }: Props) => {
|
||||
const cursor = editor.getTextCursorPosition();
|
||||
const referenceBlock = cursor?.block ?? editor.topLevelBlocks[0];
|
||||
|
||||
const createTableItem: DefaultReactSuggestionItem = {
|
||||
title: "在线表格",
|
||||
group: "高级",
|
||||
aliases: ["online table", "bg", "表格"],
|
||||
icon: <Table className="h-4 w-4 text-[#0f172a]" />,
|
||||
onItemClick: async () => {
|
||||
const documentId = currentDocumentId;
|
||||
|
||||
try {
|
||||
const newTable = await createOnlineTable(documentId);
|
||||
editor.insertBlocks(
|
||||
[
|
||||
{
|
||||
type: "onlineTable",
|
||||
props: { tableId: newTable.id, title: newTable.title },
|
||||
},
|
||||
],
|
||||
referenceBlock,
|
||||
"after",
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to create table:", error);
|
||||
// TODO: 插入错误提示块
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const createPageItem: DefaultReactSuggestionItem = {
|
||||
title: "嵌入页面",
|
||||
group: "嵌入",
|
||||
@@ -268,6 +297,7 @@ export const CustomSlashMenu = ({ editor, currentDocumentId }: Props) => {
|
||||
...headingItems,
|
||||
foldHeading,
|
||||
createPageItem,
|
||||
createTableItem,
|
||||
advancedTodo,
|
||||
foldAdvancedTodo,
|
||||
progressMeter,
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pageReferenceBlock } from "./blocks/PageReferenceBlock";
|
||||
import { advancedTodoBlock } from "./blocks/AdvancedTodoBlock";
|
||||
import { progressBlock } from "./blocks/ProgressBlock";
|
||||
import { mediaBlock } from "./blocks/MediaBlock";
|
||||
import { onlineTableBlock } from "./blocks/OnlineTableBlock";
|
||||
|
||||
const headingSpec =
|
||||
typeof window === "undefined"
|
||||
@@ -28,6 +29,7 @@ export const customBlockSchema = BlockNoteSchema.create({
|
||||
advancedTodo: advancedTodoBlock,
|
||||
progressMeter: progressBlock,
|
||||
media: mediaBlock,
|
||||
onlineTable: onlineTableBlock(),
|
||||
},
|
||||
inlineContentSpecs: defaultInlineContentSpecs,
|
||||
styleSpecs: defaultStyleSpecs,
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState, useMemo, useCallback } from "react";
|
||||
import { DocumentTable, TableColumn } from "@/types/online-table";
|
||||
import { DEFAULT_TABLE_COLUMNS, DEFAULT_TABLE_ROWS, getDocumentTable } from "@/lib/online-table";
|
||||
import { Loader2, Table, Maximize2, Plus, Minus } from "lucide-react";
|
||||
|
||||
interface CompactTablePreviewProps {
|
||||
tableId: string;
|
||||
onFullScreen: () => void;
|
||||
}
|
||||
|
||||
// 模拟获取表格行数据(阶段二只关注元数据和预览结构)
|
||||
// 实际应用中,这里会调用 getDocumentTable 并可能获取前N行数据
|
||||
const useTableData = (tableId: string) => {
|
||||
const [table, setTable] = useState<DocumentTable | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
setIsLoading(true);
|
||||
getDocumentTable(tableId)
|
||||
.then((data) => {
|
||||
setTable({ ...data, title: data.title || "未命名表格" });
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("Failed to load table:", err);
|
||||
setTable(null);
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
}, [tableId]);
|
||||
|
||||
return { table, isLoading };
|
||||
};
|
||||
|
||||
// 渲染单个单元格内容的辅助函数
|
||||
const renderCellContent = (column: TableColumn, value: any) => {
|
||||
if (value === undefined || value === null || value === "") {
|
||||
return "";
|
||||
}
|
||||
if (column.type === 'select') {
|
||||
const option = column.options?.find(opt => opt.value === value);
|
||||
if (option) {
|
||||
return (
|
||||
<span className="px-2 py-0.5 text-xs font-medium rounded-full" style={{ backgroundColor: option.color, color: 'white' }}>
|
||||
{value}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
const CompactTablePreview: React.FC<CompactTablePreviewProps> = ({ tableId, onFullScreen }) => {
|
||||
const { table, isLoading } = useTableData(tableId);
|
||||
const [hoveredRowIndex, setHoveredRowIndex] = useState<number | null>(null);
|
||||
const [editingCell, setEditingCell] = useState<{ rowIndex: number, colId: string } | null>(null);
|
||||
const [visibleRows, setVisibleRows] = useState(5);
|
||||
const [visibleCols, setVisibleCols] = useState(5);
|
||||
|
||||
const snapshotRows = table?.snapshot?.rows ?? [];
|
||||
const schemaColumns = table?.schema.columns ?? [];
|
||||
const hasData = snapshotRows.length > 0 && schemaColumns.length > 0;
|
||||
|
||||
const totalRowsAvailable = hasData ? snapshotRows.length : DEFAULT_TABLE_ROWS;
|
||||
const totalColsAvailable = hasData ? schemaColumns.length : DEFAULT_TABLE_COLUMNS;
|
||||
|
||||
useEffect(() => {
|
||||
const maxRows = Math.max(5, totalRowsAvailable);
|
||||
const maxCols = Math.max(5, totalColsAvailable);
|
||||
if (visibleRows > maxRows) {
|
||||
setVisibleRows(maxRows);
|
||||
} else if (visibleRows < 5) {
|
||||
setVisibleRows(5);
|
||||
}
|
||||
if (visibleCols > maxCols) {
|
||||
setVisibleCols(maxCols);
|
||||
} else if (visibleCols < 5) {
|
||||
setVisibleCols(5);
|
||||
}
|
||||
}, [totalRowsAvailable, totalColsAvailable, visibleRows, visibleCols]);
|
||||
|
||||
const columns = useMemo(() => {
|
||||
if (hasData) {
|
||||
return schemaColumns.slice(0, visibleCols);
|
||||
}
|
||||
const placeholderCount = Math.max(visibleCols, 5);
|
||||
return Array.from({ length: placeholderCount }, (_, index) => ({
|
||||
id: `placeholder_col_${index}`,
|
||||
name: "",
|
||||
type: "text" as const,
|
||||
width: 100,
|
||||
}));
|
||||
}, [hasData, schemaColumns, visibleCols]);
|
||||
|
||||
const rowsToDisplay = useMemo(() => {
|
||||
if (hasData) {
|
||||
return snapshotRows.slice(0, visibleRows);
|
||||
}
|
||||
const placeholderCount = Math.max(visibleRows, 5);
|
||||
return Array.from({ length: placeholderCount }, (_, index) => ({ id: `placeholder_row_${index}` }));
|
||||
}, [hasData, snapshotRows, visibleRows]);
|
||||
|
||||
const headerCells = useMemo(() => {
|
||||
const cells = [
|
||||
<th key="row-actions" className="w-8" aria-label="行操作列" />,
|
||||
];
|
||||
columns.forEach((col) => {
|
||||
cells.push(
|
||||
<th
|
||||
key={col.id}
|
||||
style={{ width: col.width ?? 100 }}
|
||||
className="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider whitespace-nowrap relative group"
|
||||
>
|
||||
{col.name}
|
||||
</th>,
|
||||
);
|
||||
});
|
||||
return cells;
|
||||
}, [columns]);
|
||||
|
||||
const suppressEditorEvents = useCallback((event: React.MouseEvent) => {
|
||||
event.stopPropagation();
|
||||
}, []);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-20 bg-gray-50 border border-dashed rounded-md">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-gray-400" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!table) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-20 bg-red-50 border border-red-300 rounded-md text-red-700">
|
||||
<Table className="h-5 w-5 mr-2" />
|
||||
表格加载失败或不存在。
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 模拟行操作:插入/删除
|
||||
// 实际应用中,这里需要调用后端或协同服务
|
||||
const handleRowOperation = (rowIndex: number, type: 'insert' | 'delete') => {
|
||||
console.log(`${type} row at index ${rowIndex} in table ${tableId}`);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative w-full p-1 border border-gray-200 rounded-md transition-shadow hover:shadow-md"
|
||||
onDoubleClick={onFullScreen}
|
||||
contentEditable={false}
|
||||
onMouseDown={suppressEditorEvents}
|
||||
onMouseUp={suppressEditorEvents}
|
||||
onMouseMove={suppressEditorEvents}
|
||||
>
|
||||
{/* 表格标题 */}
|
||||
<div className="flex justify-between items-center px-2 py-1">
|
||||
<h3 className="text-sm font-semibold text-gray-700">{table.title}</h3>
|
||||
{/* 全屏按钮 (hover toolbar的一部分) */}
|
||||
<button
|
||||
onClick={onFullScreen}
|
||||
className="p-1 text-gray-400 hover:text-blue-500 transition-colors"
|
||||
title="进入全屏编辑"
|
||||
>
|
||||
<Maximize2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 紧凑表格视图 */}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
{/* 表头 */}
|
||||
<thead className="bg-gray-100">
|
||||
<tr>{headerCells}</tr>
|
||||
</thead>
|
||||
{/* 表体 */}
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
|
||||
{rowsToDisplay.map((row: any, index: number) => {
|
||||
const rowId = row.id || index;
|
||||
return (
|
||||
<tr
|
||||
key={rowId}
|
||||
className="hover:bg-gray-50 relative group"
|
||||
onMouseEnter={() => setHoveredRowIndex(index)}
|
||||
onMouseLeave={() => setHoveredRowIndex(null)}
|
||||
>
|
||||
{/* 行操作按钮 */}
|
||||
<td className="w-8 p-0 text-center">
|
||||
{hoveredRowIndex === index && (
|
||||
<div className="flex items-center justify-center space-x-0.5 opacity-100 transition-opacity">
|
||||
<button
|
||||
onClick={() => handleRowOperation(index, 'insert')}
|
||||
className="p-0.5 text-gray-400 hover:text-green-500"
|
||||
title="在上方插入一行"
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleRowOperation(index, 'delete')}
|
||||
className="p-0.5 text-gray-400 hover:text-red-500"
|
||||
title="删除此行"
|
||||
>
|
||||
<Minus className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
{columns.map((col) => {
|
||||
const isEditing = editingCell?.rowIndex === index && editingCell?.colId === col.id;
|
||||
const cellValue = row[col.id];
|
||||
|
||||
const handleCellClick = () => {
|
||||
// 仅允许轻编辑文本和数字类型
|
||||
if (col.type === 'text' || col.type === 'number') {
|
||||
setEditingCell({ rowIndex: index, colId: col.id });
|
||||
} else {
|
||||
// TODO: 复杂类型(Select, Date等)引导进入全屏
|
||||
onFullScreen();
|
||||
}
|
||||
}
|
||||
|
||||
const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
|
||||
// TODO: 实际更新 Supabase 数据
|
||||
console.log(`Cell ${col.id} at row ${index} updated to: ${e.target.value}`);
|
||||
setEditingCell(null);
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter' || e.key === 'Escape') {
|
||||
// 提交或取消编辑
|
||||
e.currentTarget.blur();
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<td
|
||||
key={col.id}
|
||||
className="px-3 py-2 whitespace-nowrap text-sm text-gray-900 border-l border-gray-100 cursor-text text-center align-middle min-w-[80px]"
|
||||
onClick={handleCellClick}
|
||||
>
|
||||
{isEditing ? (
|
||||
<input
|
||||
type={col.type === 'number' ? 'number' : 'text'}
|
||||
defaultValue={cellValue}
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
autoFocus
|
||||
className="w-full p-0 border-none focus:ring-0 focus:outline-none bg-transparent"
|
||||
/>
|
||||
) : (
|
||||
renderCellContent(col, cellValue)
|
||||
)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
{/* 提示更多行 */}
|
||||
{table.snapshot?.rows && rowsToDisplay.length < table.snapshot.rows.length && (
|
||||
<tr>
|
||||
<td colSpan={columns.length + 1} className="px-4 py-2 text-center text-xs text-gray-500 italic">
|
||||
... 更多 { table.snapshot.rows.length - rowsToDisplay.length } 行数据,双击进入全屏查看
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="flex items-center justify-end space-x-4 mt-2 text-xs text-gray-500">
|
||||
<label className="flex items-center space-x-2">
|
||||
<span>行数</span>
|
||||
<input
|
||||
type="range"
|
||||
min={5}
|
||||
max={Math.max(5, totalRowsAvailable)}
|
||||
value={visibleRows}
|
||||
onChange={(event) => setVisibleRows(Number(event.target.value))}
|
||||
className="h-1.5 w-28 accent-blue-500"
|
||||
/>
|
||||
<span>{visibleRows}</span>
|
||||
</label>
|
||||
<label className="flex items-center space-x-2">
|
||||
<span>列数</span>
|
||||
<input
|
||||
type="range"
|
||||
min={5}
|
||||
max={Math.max(5, totalColsAvailable)}
|
||||
value={visibleCols}
|
||||
onChange={(event) => setVisibleCols(Number(event.target.value))}
|
||||
className="h-1.5 w-28 accent-blue-500"
|
||||
/>
|
||||
<span>{visibleCols}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CompactTablePreview;
|
||||
@@ -0,0 +1,207 @@
|
||||
"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";
|
||||
|
||||
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",
|
||||
],
|
||||
};
|
||||
|
||||
const FullScreenTableEditor: React.FC<FullScreenTableEditorProps> = ({ tableId, onClose }) => {
|
||||
const containerRef = useRef<HTMLDivElement>(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 fetchTable = (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));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchTable(tableId);
|
||||
}, [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;
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
// 加载所有 CSS
|
||||
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);
|
||||
}
|
||||
setIsLoaded(true);
|
||||
};
|
||||
|
||||
loadJsSequentially();
|
||||
|
||||
}, []);
|
||||
|
||||
const getLuckysheetSheets = () => {
|
||||
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 ?? [];
|
||||
};
|
||||
|
||||
// Luckysheet 初始化和清理
|
||||
useEffect(() => {
|
||||
if (!isLoaded || !tableData || !containerRef.current || !window.luckysheet) {
|
||||
return;
|
||||
}
|
||||
|
||||
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,
|
||||
data: getLuckysheetSheets(),
|
||||
};
|
||||
|
||||
window.luckysheet.create(options);
|
||||
|
||||
return () => {
|
||||
if (window.luckysheet) {
|
||||
window.luckysheet.destroy(LUCKY_SHEET_CONTAINER_ID);
|
||||
}
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tableId, isLoaded, tableData]);
|
||||
|
||||
const showLoadingOverlay = !isLoaded || isTableLoading;
|
||||
const loadingMessage = !isLoaded ? "正在加载 Luckysheet 资源..." : "正在加载表格数据...";
|
||||
|
||||
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">
|
||||
在线表格编辑 - {(tableData?.title ?? tableId).slice(0, 16)}
|
||||
</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>
|
||||
</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>
|
||||
|
||||
{showLoadingOverlay && (
|
||||
<div className="flex justify-center items-center h-full text-gray-500 border border-dashed">
|
||||
<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;
|
||||
Reference in New Issue
Block a user