xlsx 파일 주입 완료

This commit is contained in:
sheetEasy AI Team
2025-06-24 16:38:17 +09:00
parent 164db92e06
commit 105265a384
7 changed files with 2991 additions and 196 deletions

View File

@@ -13,6 +13,7 @@ import { UniverSheetsNumfmtPlugin } from "@univerjs/sheets-numfmt";
import { UniverSheetsNumfmtUIPlugin } from "@univerjs/sheets-numfmt-ui";
import { UniverUIPlugin } from "@univerjs/ui";
import { cn } from "../../lib/utils";
import LuckyExcel from "@zwight/luckyexcel";
// 언어팩 import
import DesignEnUS from "@univerjs/design/locale/en-US";
@@ -31,40 +32,101 @@ import "@univerjs/sheets-ui/lib/index.css";
import "@univerjs/sheets-formula-ui/lib/index.css";
import "@univerjs/sheets-numfmt-ui/lib/index.css";
// 전역 고유 키 생성
const GLOBAL_UNIVER_KEY = "__GLOBAL_UNIVER_INSTANCE__";
const GLOBAL_STATE_KEY = "__GLOBAL_UNIVER_STATE__";
// 전역 상태 인터페이스
interface GlobalUniverState {
instance: Univer | null;
isInitializing: boolean;
isDisposing: boolean;
initializationPromise: Promise<Univer> | null;
lastContainerId: string | null;
}
// Window 객체에 전역 상태 확장
declare global {
interface Window {
[GLOBAL_UNIVER_KEY]: Univer | null;
[GLOBAL_STATE_KEY]: GlobalUniverState;
__UNIVER_DEBUG__: {
getGlobalUniver: () => Univer | null;
getGlobalState: () => GlobalUniverState;
clearGlobalState: () => void;
forceReset: () => void;
};
}
}
// 전역 상태 초기화 함수
const initializeGlobalState = (): GlobalUniverState => {
if (!window[GLOBAL_STATE_KEY]) {
window[GLOBAL_STATE_KEY] = {
instance: null,
isInitializing: false,
isDisposing: false,
initializationPromise: null,
lastContainerId: null,
};
}
return window[GLOBAL_STATE_KEY];
};
// 전역 상태 가져오기
const getGlobalState = (): GlobalUniverState => {
return window[GLOBAL_STATE_KEY] || initializeGlobalState();
};
/**
* Univer CE + 파일 업로드 오버레이
* - Univer CE는 항상 렌더링 (기본 레이어)
* - 오버레이로 파일 업로드 UI 표시
* - disposeUnit()으로 메모리 관리
* Window 객체 기반 강화된 전역 Univer 관리자
* 모듈 재로드와 HMR에도 안전하게 작동
*/
const TestSheetViewer: React.FC = () => {
const containerRef = useRef<HTMLDivElement>(null);
const univerRef = useRef<Univer | null>(null);
const initializingRef = useRef<boolean>(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const UniverseManager = {
// 전역 인스턴스 생성 (완전 단일 인스턴스 보장)
async createInstance(container: HTMLElement): Promise<Univer> {
const state = getGlobalState();
const containerId = container.id || `container-${Date.now()}`;
const [isInitialized, setIsInitialized] = useState(false);
const [showUploadOverlay, setShowUploadOverlay] = useState(true); // 초기에는 오버레이 표시
const [isDragOver, setIsDragOver] = useState(false);
const [isProcessing, setIsProcessing] = useState(false);
const [currentFile, setCurrentFile] = useState<File | null>(null);
console.log(`🚀 Univer 인스턴스 생성 요청 - Container: ${containerId}`);
// Univer 초기화 - 공식 문서 패턴 따라서
useEffect(() => {
if (
!containerRef.current ||
isInitialized ||
univerRef.current ||
initializingRef.current
)
return;
// 이미 존재하는 인스턴스가 있고 같은 컨테이너면 재사용
if (state.instance && state.lastContainerId === containerId) {
console.log("✅ 기존 전역 Univer 인스턴스 재사용");
return state.instance;
}
const initializeUniver = async () => {
// 초기화가 진행 중이면 대기
if (state.isInitializing && state.initializationPromise) {
console.log("⏳ 기존 초기화 프로세스 대기 중...");
return state.initializationPromise;
}
// 새로운 초기화 시작
state.isInitializing = true;
console.log("🔄 새로운 Univer 인스턴스 생성 시작");
// 기존 인스턴스 정리
if (state.instance) {
try {
initializingRef.current = true;
console.log("🚀 Univer CE 초기화 시작");
console.log("🗑️ 기존 인스턴스 정리 중...");
await state.instance.dispose();
state.instance = null;
window[GLOBAL_UNIVER_KEY] = null;
} catch (error) {
console.warn("⚠️ 기존 인스턴스 정리 중 오류:", error);
}
}
// 1. Univer 인스턴스 생성
// 초기화 Promise 생성
state.initializationPromise = (async () => {
try {
// 컨테이너 ID 설정
if (!container.id) {
container.id = containerId;
}
console.log("🛠️ Univer 인스턴스 생성 중...");
const univer = new Univer({
theme: defaultTheme,
locale: LocaleType.EN_US,
@@ -81,232 +143,427 @@ const TestSheetViewer: React.FC = () => {
},
});
// 2. 필수 플러그인 등록 (공식 문서 순서)
// 플러그인 등록 순서 (중요: Core → UI → Sheets → Docs → Formula → NumFmt)
console.log("🔌 플러그인 등록 중...");
univer.registerPlugin(UniverRenderEnginePlugin);
univer.registerPlugin(UniverFormulaEnginePlugin);
univer.registerPlugin(UniverUIPlugin, {
container: containerRef.current!,
});
univer.registerPlugin(UniverDocsPlugin);
univer.registerPlugin(UniverDocsUIPlugin);
univer.registerPlugin(UniverUIPlugin, { container });
univer.registerPlugin(UniverSheetsPlugin);
univer.registerPlugin(UniverSheetsUIPlugin);
univer.registerPlugin(UniverDocsPlugin);
univer.registerPlugin(UniverDocsUIPlugin);
univer.registerPlugin(UniverSheetsFormulaPlugin);
univer.registerPlugin(UniverSheetsFormulaUIPlugin);
univer.registerPlugin(UniverSheetsNumfmtPlugin);
univer.registerPlugin(UniverSheetsNumfmtUIPlugin);
// 3. 기본 워크북 생성
univer.createUnit(UniverInstanceType.UNIVER_SHEET, {
id: "default-workbook",
name: "New Workbook",
sheetOrder: ["sheet1"],
sheets: {
sheet1: {
id: "sheet1",
name: "Sheet1",
cellData: {
0: {
0: { v: "Ready for Excel Import" },
1: { v: "파일을 업로드하세요" },
},
},
rowCount: 100,
columnCount: 26,
},
},
});
// 전역 상태 업데이트
state.instance = univer;
state.lastContainerId = containerId;
window[GLOBAL_UNIVER_KEY] = univer;
univerRef.current = univer;
setIsInitialized(true);
console.log("✅ Univer CE 초기화 완료");
console.log("✅ Univer 인스턴스 생성 완료");
return univer;
} catch (error) {
console.error("❌ Univer CE 초기화 실패:", error);
initializingRef.current = false;
console.error("❌ Univer 인스턴스 생성 실패:", error);
throw error;
} finally {
state.isInitializing = false;
state.initializationPromise = null;
}
};
})();
initializeUniver();
}, []);
return state.initializationPromise;
},
// 컴포넌트 언마운트 시 정리
useEffect(() => {
return () => {
try {
if (univerRef.current) {
univerRef.current.dispose();
univerRef.current = null;
}
initializingRef.current = false;
} catch (error) {
console.error("❌ Univer dispose 오류:", error);
}
};
}, []);
// 전역 인스턴스 정리
async disposeInstance(): Promise<void> {
const state = getGlobalState();
// 파일 처리 로직
const handleFileProcessing = useCallback(async (file: File) => {
if (!univerRef.current) return;
if (state.isDisposing) {
console.log("🔄 이미 dispose 진행 중...");
return;
}
setIsProcessing(true);
console.log("📁 파일 처리 시작:", file.name);
if (!state.instance) {
console.log(" 정리할 인스턴스가 없음");
return;
}
state.isDisposing = true;
try {
// 파일을 ArrayBuffer로 읽기
const arrayBuffer = await file.arrayBuffer();
const fileSize = (arrayBuffer.byteLength / 1024).toFixed(2);
console.log("🗑️ 전역 Univer 인스턴스 dispose 시작");
await state.instance.dispose();
state.instance = null;
state.lastContainerId = null;
window[GLOBAL_UNIVER_KEY] = null;
console.log("✅ 전역 Univer 인스턴스 dispose 완료");
} catch (error) {
console.error("❌ dispose 실패:", error);
} finally {
state.isDisposing = false;
}
},
// 기존 워크북 제거 (메모리 관리)
// 현재 인스턴스 반환
getInstance(): Univer | null {
const state = getGlobalState();
return state.instance || window[GLOBAL_UNIVER_KEY] || null;
},
// 상태 확인 메서드들
isInitializing(): boolean {
return getGlobalState().isInitializing || false;
},
isDisposing(): boolean {
return getGlobalState().isDisposing || false;
},
// 강제 리셋 (디버깅용)
forceReset(): void {
const state = getGlobalState();
if (state.instance) {
try {
// TODO: 실제 disposeUnit API 확인 후 구현
// univerRef.current.disposeUnit('default-workbook');
console.log("🗑️ 기존 워크북 정리 완료");
state.instance.dispose();
} catch (error) {
console.warn("⚠️ 기존 워크북 정리 실패:", error);
console.warn("강제 리셋 중 dispose 오류:", error);
}
}
// 새 워크북 생성 (실제 Excel 파싱은 추후 구현)
const newWorkbook = {
state.instance = null;
state.isInitializing = false;
state.isDisposing = false;
state.initializationPromise = null;
state.lastContainerId = null;
window[GLOBAL_UNIVER_KEY] = null;
console.log("🔄 전역 Univer 상태 강제 리셋 완료");
},
};
// 전역 디버그 객체 설정
if (typeof window !== "undefined") {
// 전역 상태 초기화
initializeGlobalState();
// 디버그 객체 설정
window.__UNIVER_DEBUG__ = {
getGlobalUniver: () => UniverseManager.getInstance(),
getGlobalState: () => getGlobalState(),
clearGlobalState: () => {
const state = getGlobalState();
Object.assign(state, {
instance: null,
isInitializing: false,
isDisposing: false,
initializationPromise: null,
lastContainerId: null,
});
window[GLOBAL_UNIVER_KEY] = null;
console.log("🧹 전역 상태 정리 완료");
},
forceReset: () => UniverseManager.forceReset(),
};
console.log("🐛 디버그 객체 설정 완료: window.__UNIVER_DEBUG__");
}
/**
* Univer CE + 파일 업로드 오버레이
* Window 객체 기반 완전한 단일 인스턴스 관리
*/
const TestSheetViewer: React.FC = () => {
const containerRef = useRef<HTMLDivElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const mountedRef = useRef<boolean>(false);
const [isInitialized, setIsInitialized] = useState(false);
const [showUploadOverlay, setShowUploadOverlay] = useState(true);
const [isDragOver, setIsDragOver] = useState(false);
const [isProcessing, setIsProcessing] = useState(false);
const [currentFile, setCurrentFile] = useState<File | null>(null);
// Univer 초기화 함수
const initializeUniver = useCallback(async (workbookData?: any) => {
if (!containerRef.current || !mountedRef.current) {
console.error("❌ 컨테이너가 준비되지 않았습니다!");
return;
}
try {
console.log("🚀 Univer 초기화 시작");
// 전역 인스턴스 생성 또는 재사용
const univer = await UniverseManager.createInstance(containerRef.current);
// 기본 워크북 데이터
const defaultWorkbook = {
id: `workbook-${Date.now()}`,
name: file.name,
sheetOrder: ["imported-sheet"],
locale: LocaleType.EN_US,
name: "Sample Workbook",
sheetOrder: ["sheet-01"],
sheets: {
"imported-sheet": {
id: "imported-sheet",
name: "Imported Data",
cellData: {
0: {
0: { v: "파일명" },
1: { v: file.name },
},
1: {
0: { v: "파일 크기" },
1: { v: `${fileSize} KB` },
},
2: {
0: { v: "업로드 시간" },
1: { v: new Date().toLocaleString() },
},
4: {
0: { v: "상태" },
1: { v: "업로드 완료 - 실제 Excel 파싱은 추후 구현" },
},
},
"sheet-01": {
type: 0,
id: "sheet-01",
name: "Sheet1",
tabColor: "",
hidden: 0,
rowCount: 100,
columnCount: 26,
columnCount: 20,
zoomRatio: 1,
scrollTop: 0,
scrollLeft: 0,
defaultColumnWidth: 93,
defaultRowHeight: 27,
cellData: {},
rowData: {},
columnData: {},
showGridlines: 1,
rowHeader: { width: 46, hidden: 0 },
columnHeader: { height: 20, hidden: 0 },
selections: ["A1"],
rightToLeft: 0,
},
},
};
univerRef.current.createUnit(
const workbookToUse = workbookData || defaultWorkbook;
// 기존 워크북 정리 (API 호환성 고려)
try {
const existingUnits =
(univer as any).getUnitsForType?.(UniverInstanceType.UNIVER_SHEET) ||
[];
for (const unit of existingUnits) {
(univer as any).disposeUnit?.(unit.getUnitId());
}
} catch (error) {
console.log(" 기존 워크북 정리 시 오류 (무시 가능):", error);
}
// 새 워크북 생성
const workbook = univer.createUnit(
UniverInstanceType.UNIVER_SHEET,
newWorkbook,
workbookToUse,
);
setCurrentFile(file);
setShowUploadOverlay(false); // 오버레이 숨기기
console.log("✅ 파일 처리 완료");
console.log("✅ 워크북 생성 완료:", workbook?.getUnitId());
setIsInitialized(true);
} catch (error) {
console.error("❌ 파일 처리 실패:", error);
} finally {
setIsProcessing(false);
console.error("❌ Univer 초기화 실패:", error);
setIsInitialized(false);
}
}, []);
// 파일 선택 처리
const handleFileSelection = useCallback(
async (files: FileList) => {
if (files.length === 0) return;
const file = files[0];
// 파일 타입 검증
if (!file.name.match(/\.(xlsx|xls)$/i)) {
alert("Excel 파일(.xlsx, .xls)만 업로드 가능합니다.");
// 파일 처리 함수
const processFile = useCallback(
async (file: File) => {
// 강화된 상태 확인으로 중복 실행 완전 차단
if (
isProcessing ||
UniverseManager.isInitializing() ||
UniverseManager.isDisposing()
) {
console.log("⏸️ 처리 중이거나 상태 변경 중입니다. 현재 상태:", {
isProcessing,
isInitializing: UniverseManager.isInitializing(),
isDisposing: UniverseManager.isDisposing(),
});
return;
}
// 파일 크기 검증 (50MB)
if (file.size > 50 * 1024 * 1024) {
alert("파일 크기는 50MB를 초과할 수 없습니다.");
return;
if (!file.name.toLowerCase().endsWith(".xlsx")) {
throw new Error("XLSX 파일만 지원됩니다.");
}
await handleFileProcessing(file);
setIsProcessing(true);
console.log("📁 파일 처리 시작:", file.name);
try {
// LuckyExcel을 사용하여 Excel 파일을 Univer 데이터로 변환
await new Promise<void>((resolve, reject) => {
LuckyExcel.transformExcelToUniver(
file,
async (exportJson: any) => {
try {
console.log("📊 LuckyExcel 변환 완료:", exportJson);
// 변환된 데이터로 워크북 업데이트
if (exportJson && typeof exportJson === "object") {
await initializeUniver(exportJson);
} else {
console.warn(
"⚠️ 변환된 데이터가 유효하지 않음, 기본 워크북 사용",
);
await initializeUniver();
}
setCurrentFile(file);
setShowUploadOverlay(false);
resolve();
} catch (error) {
console.error("❌ 워크북 업데이트 오류:", error);
try {
await initializeUniver();
setCurrentFile(file);
setShowUploadOverlay(false);
resolve();
} catch (fallbackError) {
reject(fallbackError);
}
}
},
(error: any) => {
console.error("❌ LuckyExcel 변환 오류:", error);
reject(new Error("파일 변환 중 오류가 발생했습니다."));
},
);
});
} catch (error) {
console.error("❌ 파일 처리 오류:", error);
throw error;
} finally {
setIsProcessing(false);
console.log("✅ 파일 처리 완료");
}
},
[handleFileProcessing],
[isProcessing, initializeUniver],
);
// 파일 입력 변경 처리
const handleFileInputChange = useCallback(
async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
try {
await processFile(file);
} catch (error) {
console.error("❌ 파일 처리 오류:", error);
alert(
error instanceof Error
? error.message
: "파일 처리 중 오류가 발생했습니다.",
);
} finally {
// 파일 입력 초기화로 중복 실행 방지
if (event.target) {
event.target.value = "";
}
}
},
[processFile],
);
// 파일 피커 클릭
const handleFilePickerClick = useCallback(() => {
if (isProcessing || UniverseManager.isInitializing()) return;
fileInputRef.current?.click();
}, [isProcessing]);
// 새 업로드 처리
const handleNewUpload = useCallback(() => {
if (isProcessing || UniverseManager.isInitializing()) return;
setShowUploadOverlay(true);
setCurrentFile(null);
}, [isProcessing]);
// 드래그 앤 드롭 이벤트 핸들러
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
}, []);
const handleDragEnter = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {
setIsDragOver(true);
}
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
}, []);
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
}, []);
const handleDrop = useCallback(
async (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
if (isProcessing) return;
const files = e.dataTransfer.files;
if (files && files.length > 0) {
await handleFileSelection(files);
if (files.length === 0) return;
const file = files[0];
if (!file.name.toLowerCase().endsWith(".xlsx")) {
alert("XLSX 파일만 업로드 가능합니다.");
return;
}
if (file.size > 50 * 1024 * 1024) {
alert("파일 크기는 50MB를 초과할 수 없습니다.");
return;
}
try {
await processFile(file);
} catch (error) {
console.error("❌ 파일 처리 오류:", error);
alert(
error instanceof Error
? error.message
: "파일 처리 중 오류가 발생했습니다.",
);
}
},
[handleFileSelection, isProcessing],
[processFile],
);
// 파일 선택 버튼 클릭
const handleFilePickerClick = useCallback(() => {
if (isProcessing || !fileInputRef.current) return;
fileInputRef.current.click();
}, [isProcessing]);
// 컴포넌트 마운트 시 초기화
useEffect(() => {
mountedRef.current = true;
console.log("🎯 컴포넌트 마운트됨");
// 파일 입력 변경
const handleFileInputChange = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (files && files.length > 0) {
await handleFileSelection(files);
// 기존 전역 인스턴스 확인 및 재사용
const existingUniver = UniverseManager.getInstance();
if (existingUniver && !UniverseManager.isInitializing()) {
console.log("♻️ 기존 전역 Univer 인스턴스 재사용");
setIsInitialized(true);
return;
}
// 컨테이너 준비 후 초기화
const initTimer = setTimeout(() => {
if (containerRef.current && !UniverseManager.isInitializing()) {
console.log("🚀 컴포넌트 마운트 시 Univer 초기화");
initializeUniver();
}
e.target.value = "";
},
[handleFileSelection],
);
}, 100); // 짧은 지연으로 DOM 완전 준비 보장
// 새 파일 업로드 (오버레이 다시 표시)
const handleNewUpload = useCallback(() => {
setShowUploadOverlay(true);
setCurrentFile(null);
return () => {
clearTimeout(initTimer);
mountedRef.current = false;
console.log("👋 컴포넌트 언마운트됨");
};
}, [initializeUniver]);
// 컴포넌트 언마운트 시 정리 (전역 인스턴스는 유지)
useEffect(() => {
return () => {
// 전역 인스턴스는 앱 종료 시에만 정리
// 여기서는 로컬 상태만 초기화
setIsInitialized(false);
console.log("🧹 로컬 상태 정리 완료");
};
}, []);
return (
<div className="w-full h-screen flex flex-col relative">
{/* 헤더 */}
<div className="bg-white border-b p-4 flex-shrink-0 relative z-10">
<h1 className="text-xl font-bold">🧪 Univer CE + </h1>
<h1 className="text-xl font-bold">
🧪 Univer CE + (Window )
</h1>
<div className="mt-2 flex items-center gap-4">
<span
className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
@@ -331,6 +588,12 @@ const TestSheetViewer: React.FC = () => {
</button>
</>
)}
{/* 디버그 정보 */}
<div className="text-xs text-gray-500">
: {UniverseManager.getInstance() ? "✅" : "❌"} |
: {UniverseManager.isInitializing() ? "⏳" : "❌"}
</div>
</div>
</div>
@@ -352,7 +615,7 @@ const TestSheetViewer: React.FC = () => {
<div
style={{
position: "absolute",
top: "00px", // 헤더 높이만큼 아래로 (헤더는 약 80px)
top: "0px", // 헤더 높이만큼 아래로 (헤더는 약 80px)
left: 0,
right: 0,
bottom: 0,
@@ -383,7 +646,13 @@ const TestSheetViewer: React.FC = () => {
className="max-w-2xl w-full"
style={{ transform: "scale(0.8)" }}
>
<div className="bg-white rounded-lg shadow-xl border p-8 md:p-12">
<div
className="bg-white rounded-lg shadow-xl border p-8 md:p-12"
style={{
backgroundColor: "#ffffff",
boxShadow: "0 25px 50px -12px rgba(0, 0, 0, 0.25)",
}}
>
<div className="text-center">
{/* 아이콘 및 제목 */}
<div className="mb-8">
@@ -442,7 +711,7 @@ const TestSheetViewer: React.FC = () => {
) : (
<>
<span className="font-medium text-gray-900">
.xlsx, .xls
.xlsx
</span>{" "}
</>
@@ -490,7 +759,7 @@ const TestSheetViewer: React.FC = () => {
<input
ref={fileInputRef}
type="file"
accept=".xlsx,.xls"
accept=".xlsx"
onChange={handleFileInputChange}
className="hidden"
disabled={isProcessing}
@@ -498,8 +767,12 @@ const TestSheetViewer: React.FC = () => {
{/* 지원 형식 안내 */}
<div className="mt-6 text-xs text-gray-500">
<p> 형식: Excel (.xlsx, .xls)</p>
<p> 형식: Excel (.xlsx)</p>
<p> 크기: 50MB</p>
<p className="mt-2 text-blue-600">
💡 window.__UNIVER_DEBUG__
</p>
</div>
</div>
</div>

1290
src/utils/fileProcessor.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1 +0,0 @@