SpreadsheetPreview.tsx 1.38 KB
"use client";

import { useEffect, useRef } from "react";
import type { SheetData } from "x-data-spreadsheet";

// 只读电子表格预览:动态加载 x-data-spreadsheet 并渲染。从 app/page.tsx 抽出。
export const SpreadsheetPreview = ({ sheets }: { sheets: SheetData[] }) => {
  const containerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return undefined;
    container.innerHTML = "";
    let cancelled = false;
    import("x-data-spreadsheet/dist/xspreadsheet.js")
      .then(() => {
        if (cancelled || !window.x_spreadsheet) return;
        const instance = window.x_spreadsheet(container, {
          mode: "read",
          showToolbar: false,
          showContextmenu: false,
          showBottomBar: true,
          view: {
            height: () => container.clientHeight,
            width: () => container.clientWidth,
          },
        });
        instance.loadData(sheets);
      })
      .catch((e) => {
        console.error("加载 x-data-spreadsheet 失败", e);
      });
    return () => {
      cancelled = true;
      container.innerHTML = "";
    };
  }, [sheets]);

  return (
    <div
      ref={containerRef}
      className="wiki-spreadsheet-readonly w-full h-full overflow-hidden"
      onWheel={(e) => e.stopPropagation()}
    />
  );
};

export default SpreadsheetPreview;