feat: 소설 분기 시스템 및 트리 메모장 구현

🌟 주요 기능:
- 트리 구조 메모장 시스템
- 소설 분기 관리 (정사 경로 설정)
- 중앙 배치 트리 다이어그램
- 정사 경로 목차 뷰
- 인라인 편집 기능

📚 백엔드:
- MemoTree, MemoNode 모델 추가
- 정사 경로 자동 순서 관리
- 분기점에서 하나만 선택 가능한 로직
- RESTful API 엔드포인트

🎨 프론트엔드:
- memo-tree.html: 트리 다이어그램 에디터
- story-view.html: 정사 경로 목차 뷰
- SVG 연결선으로 시각적 트리 표현
- Alpine.js 기반 반응형 UI
- Monaco Editor 통합

 특별 기능:
- 정사 경로 황금색 배지 표시
- 확대/축소 및 패닝 지원
- 드래그 앤 드롭 준비
- 내보내기 및 인쇄 기능
- 인라인 편집 모달
This commit is contained in:
Hyungi Ahn
2025-08-25 10:25:10 +09:00
parent 5bfa3822ca
commit f95f67364a
16 changed files with 3992 additions and 6 deletions

View File

@@ -109,8 +109,9 @@
<div class="flex items-center space-x-4">
<h1 class="text-2xl font-bold text-gray-900">📚 문서 관리 시스템</h1>
<div class="flex space-x-2">
<a href="index.html" class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-full hover:bg-gray-200">그리드 뷰</a>
<span class="px-3 py-1 text-sm bg-blue-100 text-blue-800 rounded-full">계층구조 뷰</span>
<a href="index.html" class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-full hover:bg-gray-200">📖 그리드 뷰</a>
<span class="px-3 py-1 text-sm bg-blue-100 text-blue-800 rounded-full">📚 계층구조 뷰</span>
<a href="memo-tree.html" class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-full hover:bg-gray-200">🌳 트리 메모장</a>
</div>
</div>

View File

@@ -59,8 +59,9 @@
Document Server
</h1>
<div class="flex space-x-2">
<span class="px-3 py-1 text-sm bg-blue-100 text-blue-800 rounded-full">그리드 뷰</span>
<a href="hierarchy.html" class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-full hover:bg-gray-200">계층구조 뷰</a>
<span class="px-3 py-1 text-sm bg-blue-100 text-blue-800 rounded-full">📖 그리드 뷰</span>
<a href="hierarchy.html" class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-full hover:bg-gray-200">📚 계층구조 뷰</a>
<a href="memo-tree.html" class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-full hover:bg-gray-200">🌳 트리 메모장</a>
</div>
</div>

651
frontend/memo-tree.html Normal file
View File

@@ -0,0 +1,651 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>트리 메모장 - Document Server</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Alpine.js 자동 시작 방지 -->
<script>
// Alpine.js 자동 시작 방지
document.addEventListener('alpine:init', () => {
console.log('Alpine.js 초기화됨');
});
</script>
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Monaco Editor (VS Code 에디터) -->
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.44.0/min/vs/loader.js"></script>
<style>
[x-cloak] { display: none !important; }
/* 트리 스타일 */
.tree-node {
transition: all 0.2s ease;
position: relative;
}
.tree-node:hover {
background-color: #f3f4f6;
}
.tree-node.selected {
background-color: #dbeafe;
border-left: 3px solid #3b82f6;
}
.tree-node.dragging {
opacity: 0.5;
transform: rotate(5deg);
}
/* 트리 연결선 */
.tree-node-item {
position: relative;
}
.tree-node-item::before {
content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0;
border-left: 1px solid #d1d5db;
}
.tree-node-item::after {
content: '';
position: absolute;
left: 0;
top: 50%;
width: 16px;
border-top: 1px solid #d1d5db;
}
/* 루트 노드는 연결선 없음 */
.tree-node-item.root::before,
.tree-node-item.root::after {
display: none;
}
/* 마지막 자식 노드는 세로선을 중간까지만 */
.tree-node-item.last-child::before {
height: 50%;
}
/* 트리 들여쓰기 */
.tree-indent {
width: 20px;
position: relative;
}
/* 트리 라인 스타일 */
.tree-line {
display: inline-block;
width: 20px;
height: 20px;
position: relative;
}
.tree-line.vertical::before {
content: '';
position: absolute;
left: 50%;
top: 0;
bottom: 0;
border-left: 1px solid #d1d5db;
}
.tree-line.branch::before {
content: '';
position: absolute;
left: 50%;
top: 0;
bottom: 0;
border-left: 1px solid #d1d5db;
}
.tree-line.branch::after {
content: '';
position: absolute;
left: 50%;
top: 50%;
width: 10px;
border-top: 1px solid #d1d5db;
}
.tree-line.corner::before {
content: '';
position: absolute;
left: 50%;
top: 0;
height: 50%;
border-left: 1px solid #d1d5db;
}
.tree-line.corner::after {
content: '';
position: absolute;
left: 50%;
top: 50%;
width: 10px;
border-top: 1px solid #d1d5db;
}
.tree-line.empty {
/* 빈 공간 */
}
/* 에디터 컨테이너 */
.editor-container {
height: calc(100vh - 200px);
min-height: 400px;
}
/* 스플리터 */
.splitter {
width: 4px;
background: #e5e7eb;
cursor: col-resize;
transition: background-color 0.2s;
}
.splitter:hover {
background: #3b82f6;
}
/* 노드 타입별 아이콘 색상 */
.node-folder { color: #f59e0b; }
.node-memo { color: #6b7280; }
.node-chapter { color: #8b5cf6; }
.node-character { color: #10b981; }
.node-plot { color: #ef4444; }
/* 상태별 색상 */
.status-draft { border-left-color: #9ca3af; }
.status-writing { border-left-color: #f59e0b; }
.status-review { border-left-color: #3b82f6; }
.status-complete { border-left-color: #10b981; }
</style>
</head>
<body class="bg-gray-50" x-data="memoTreeApp()" x-init="init()" x-cloak>
<!-- 헤더 -->
<header class="bg-white shadow-sm border-b">
<div class="max-w-full mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center h-16">
<!-- 로고 및 네비게이션 -->
<div class="flex items-center space-x-4">
<div class="flex items-center space-x-2">
<i class="fas fa-sitemap text-blue-600 text-xl"></i>
<h1 class="text-xl font-bold text-gray-900">트리 메모장</h1>
</div>
<!-- 네비게이션 링크 -->
<div class="hidden md:flex space-x-4">
<a href="index.html" class="text-gray-600 hover:text-gray-900">📖 문서 관리</a>
<a href="hierarchy.html" class="text-gray-600 hover:text-gray-900">📚 계층구조</a>
<span class="text-blue-600 font-medium">🌳 트리 메모장</span>
<a href="story-view.html" class="text-gray-600 hover:text-gray-900">📖 스토리 뷰</a>
</div>
</div>
<!-- 사용자 메뉴 -->
<div class="flex items-center space-x-4">
<!-- 트리 관리 버튼들 -->
<div x-show="currentUser" class="flex space-x-2">
<button
@click="showNewTreeModal = true"
class="px-3 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
title="새 트리 생성"
>
<i class="fas fa-plus mr-1"></i> 새 트리
</button>
<button
@click="showTreeSettings = !showTreeSettings"
x-show="selectedTree"
class="px-3 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
title="트리 설정"
>
<i class="fas fa-cog"></i>
</button>
</div>
<!-- 사용자 정보 -->
<div x-show="currentUser" class="flex items-center space-x-3">
<span class="text-sm text-gray-600" x-text="currentUser?.full_name || currentUser?.email"></span>
<button @click="logout()" class="text-sm text-red-600 hover:text-red-800">로그아웃</button>
</div>
<!-- 로그인 버튼 -->
<button x-show="!currentUser" @click="openLoginModal()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
로그인
</button>
</div>
</div>
</div>
</header>
<!-- 메인 컨테이너 -->
<div class="h-screen pt-16" x-show="currentUser">
<!-- 상단 툴바 -->
<div class="bg-white border-b shadow-sm p-3">
<div class="flex items-center justify-between">
<!-- 트리 선택 -->
<div class="flex items-center space-x-3">
<select
x-model="selectedTreeId"
@change="loadTree(selectedTreeId)"
class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
>
<option value="">📂 트리 선택</option>
<template x-for="tree in userTrees" :key="tree.id">
<option :value="tree.id" x-text="`${getTreeIcon(tree.tree_type)} ${tree.title}`"></option>
</template>
</select>
<button
@click="showNewTreeModal = true"
class="px-3 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm"
title="새 트리"
>
<i class="fas fa-plus mr-1"></i> 새 트리
</button>
</div>
<!-- 트리 액션 버튼들 -->
<div x-show="selectedTree" class="flex items-center space-x-2">
<button
@click="createRootNode()"
class="px-3 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 text-sm"
>
<i class="fas fa-plus mr-1"></i> 노드 추가
</button>
<button
@click="centerTree()"
class="px-3 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 text-sm"
title="트리 중앙 정렬"
>
<i class="fas fa-crosshairs"></i>
</button>
<button
@click="zoomIn()"
class="px-2 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 text-sm"
title="확대"
>
<i class="fas fa-search-plus"></i>
</button>
<button
@click="zoomOut()"
class="px-2 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 text-sm"
title="축소"
>
<i class="fas fa-search-minus"></i>
</button>
</div>
</div>
</div>
<!-- 메인 트리 다이어그램 영역 -->
<div class="flex h-full">
<!-- 트리 다이어그램 (중앙) -->
<div class="flex-1 relative overflow-hidden bg-gray-50">
<!-- 트리 없음 상태 -->
<div x-show="!selectedTree" class="flex items-center justify-center h-full">
<div class="text-center text-gray-500">
<i class="fas fa-sitemap text-6xl text-gray-300 mb-4"></i>
<h3 class="text-lg font-medium mb-2">트리를 선택하세요</h3>
<p class="text-sm">왼쪽에서 트리를 선택하거나 새로 만들어보세요</p>
</div>
</div>
<!-- 노드 없음 상태 -->
<div x-show="selectedTree && treeNodes.length === 0" class="flex items-center justify-center h-full">
<div class="text-center text-gray-500">
<i class="fas fa-plus-circle text-6xl text-gray-300 mb-4"></i>
<h3 class="text-lg font-medium mb-2">첫 번째 노드를 만들어보세요</h3>
<button
@click="createRootNode()"
class="mt-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
>
<i class="fas fa-plus mr-2"></i> 루트 노드 생성
</button>
</div>
</div>
<!-- 트리 다이어그램 캔버스 -->
<div x-show="selectedTree && treeNodes.length > 0" class="relative w-full h-full" id="tree-canvas">
<!-- 전체 트리 컨테이너 (SVG + 노드 함께 스케일링) -->
<div
class="absolute inset-0 w-full h-full"
id="tree-container"
:style="`transform: scale(${treeZoom}) translate(${treePanX}px, ${treePanY}px); transform-origin: center center;`"
@mousedown="startPan($event)"
@wheel="handleWheel($event)"
>
<!-- SVG 연결선 레이어 -->
<svg class="absolute inset-0 w-full h-full pointer-events-none z-10" id="tree-connections">
<!-- 연결선들이 여기에 그려짐 -->
</svg>
<!-- 노드 레이어 -->
<div class="absolute inset-0 w-full h-full z-20" id="tree-nodes">
<!-- 노드들이 여기에 배치됨 -->
<template x-for="node in treeNodes" :key="node.id">
<div
class="absolute tree-diagram-node"
:style="getNodePosition(node)"
@mousedown="startDragNode($event, node)"
>
<div
class="bg-white rounded-lg shadow-md border-2 p-3 cursor-pointer min-w-32 max-w-48 relative"
:class="{
'border-blue-500 shadow-lg': selectedNode && selectedNode.id === node.id,
'border-gray-200': !selectedNode || selectedNode.id !== node.id,
'border-gray-400': node.status === 'draft',
'border-yellow-400': node.status === 'writing',
'border-blue-400': node.status === 'review',
'border-green-400': node.status === 'complete',
'bg-gradient-to-br from-yellow-50 to-amber-50 border-amber-400': node.is_canonical,
'shadow-amber-200': node.is_canonical
}"
@click="selectNode(node)"
@dblclick="editNodeInline(node)"
>
<!-- 정사 경로 배지 -->
<div x-show="node.is_canonical" class="absolute -top-2 -right-2 bg-amber-500 text-white text-xs px-2 py-1 rounded-full font-bold shadow-md">
<i class="fas fa-star mr-1"></i><span x-text="node.canonical_order || '?'"></span>
</div>
<!-- 노드 헤더 -->
<div class="flex items-center justify-between mb-2">
<div class="flex items-center">
<span class="text-lg mr-1" x-text="getNodeIcon(node.node_type)"></span>
<span x-show="node.is_canonical" class="text-amber-600 text-sm" title="정사 경로"></span>
</div>
<div class="flex space-x-1">
<button
@click.stop="toggleCanonical(node)"
class="w-5 h-5 flex items-center justify-center rounded"
:class="node.is_canonical ? 'text-amber-600 hover:text-amber-700 hover:bg-amber-50' : 'text-gray-400 hover:text-amber-600 hover:bg-amber-50'"
:title="node.is_canonical ? '정사에서 제외' : '정사로 설정'"
>
<i class="fas fa-star text-xs"></i>
</button>
<button
@click.stop="addChildNode(node)"
class="w-5 h-5 flex items-center justify-center text-gray-400 hover:text-green-600 hover:bg-green-50 rounded"
title="자식 노드 추가"
>
<i class="fas fa-plus text-xs"></i>
</button>
<button
@click.stop="showNodeMenu($event, node)"
class="w-5 h-5 flex items-center justify-center text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded"
title="더보기"
>
<i class="fas fa-ellipsis-h text-xs"></i>
</button>
</div>
</div>
<!-- 노드 제목 -->
<div class="text-sm font-medium text-gray-800 truncate" x-text="node.title"></div>
<!-- 노드 정보 -->
<div class="flex items-center justify-between mt-2 text-xs text-gray-500">
<span x-text="node.node_type"></span>
<span x-show="node.word_count > 0" x-text="`${node.word_count}w`"></span>
</div>
</div>
</div>
</template>
</div>
</div>
</div>
</div>
<!-- 오른쪽: 속성 패널 -->
<div class="w-80 bg-white border-l shadow-lg flex flex-col">
<!-- 에디터 헤더 -->
<template x-if="selectedNode">
<div class="p-4 border-b bg-white">
<div class="flex items-center justify-between">
<div class="flex-1">
<input
type="text"
x-model="selectedNode.title"
@blur="saveNodeTitle()"
class="text-lg font-semibold bg-transparent border-none focus:outline-none focus:ring-2 focus:ring-blue-500 rounded px-2 py-1 w-full"
placeholder="노드 제목을 입력하세요"
>
<div class="flex items-center space-x-4 mt-2 text-sm text-gray-600">
<div class="flex items-center space-x-2">
<span>타입:</span>
<select
x-model="selectedNode.node_type"
@change="saveNodeType()"
class="border border-gray-300 rounded px-2 py-1 text-xs"
>
<option value="memo">📝 메모</option>
<option value="folder">📁 폴더</option>
<option value="chapter">📖 챕터</option>
<option value="character">👤 캐릭터</option>
<option value="plot">📋 플롯</option>
</select>
</div>
<div class="flex items-center space-x-2">
<span>상태:</span>
<select
x-model="selectedNode.status"
@change="saveNodeStatus()"
class="border border-gray-300 rounded px-2 py-1 text-xs"
>
<option value="draft">📝 초안</option>
<option value="writing">✍️ 작성중</option>
<option value="review">👀 검토중</option>
<option value="complete">✅ 완료</option>
</select>
</div>
<div x-show="selectedNode?.word_count > 0" class="text-xs">
<span x-text="`${selectedNode?.word_count || 0} 단어`"></span>
</div>
</div>
</div>
<div class="flex space-x-2">
<button
@click="saveNode()"
class="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700"
>
<i class="fas fa-save mr-1"></i> 저장
</button>
<button
@click="deleteNode(selectedNode.id)"
class="px-3 py-1 bg-red-600 text-white rounded text-sm hover:bg-red-700"
>
<i class="fas fa-trash mr-1"></i> 삭제
</button>
</div>
</div>
</template>
<!-- 에디터 -->
<div x-show="selectedNode" class="flex-1 editor-container">
<div id="monaco-editor" class="h-full"></div>
</div>
<!-- 노드 미선택 상태 -->
<div x-show="!selectedNode" class="flex-1 flex items-center justify-center">
<div class="text-center text-gray-500">
<i class="fas fa-edit text-6xl text-gray-300 mb-4"></i>
<h3 class="text-lg font-medium mb-2">노드를 선택하세요</h3>
<p class="text-sm">왼쪽 트리에서 노드를 클릭하여 편집을 시작하세요</p>
</div>
</div>
</div>
</div>
<!-- 로그인이 필요한 상태 -->
<div x-show="!currentUser" class="flex items-center justify-center h-screen">
<div class="text-center">
<i class="fas fa-lock text-6xl text-gray-300 mb-4"></i>
<h2 class="text-2xl font-bold text-gray-900 mb-2">로그인이 필요합니다</h2>
<p class="text-gray-600 mb-4">트리 메모장을 사용하려면 로그인해주세요</p>
<button @click="openLoginModal()" class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
로그인하기
</button>
</div>
</div>
<!-- 새 트리 생성 모달 -->
<div x-show="showNewTreeModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div class="bg-white rounded-lg p-6 w-96 max-w-md mx-4">
<h2 class="text-xl font-bold mb-4">새 트리 생성</h2>
<form @submit.prevent="createTree()">
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">제목</label>
<input
type="text"
x-model="newTree.title"
required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="트리 제목을 입력하세요"
>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">설명</label>
<textarea
x-model="newTree.description"
rows="3"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="트리에 대한 설명을 입력하세요"
></textarea>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">타입</label>
<select
x-model="newTree.tree_type"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="general">📝 일반</option>
<option value="novel">📚 소설</option>
<option value="research">🔬 연구</option>
<option value="project">💼 프로젝트</option>
</select>
</div>
</div>
<div class="flex justify-end space-x-3 mt-6">
<button
type="button"
@click="showNewTreeModal = false"
class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50"
>
취소
</button>
<button
type="submit"
class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
>
생성
</button>
</div>
</form>
</div>
</div>
<!-- 로그인 모달 -->
<div x-show="showLoginModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div class="bg-white rounded-lg p-6 w-96 max-w-md mx-4">
<h2 class="text-xl font-bold mb-4">로그인</h2>
<form @submit.prevent="handleLogin()">
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-2">이메일</label>
<input
type="email"
x-model="loginForm.email"
required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
</div>
<div class="mb-6">
<label class="block text-sm font-medium text-gray-700 mb-2">비밀번호</label>
<input
type="password"
x-model="loginForm.password"
required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
</div>
<div x-show="loginError" class="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
<span x-text="loginError"></span>
</div>
<div class="flex justify-end space-x-3">
<button
type="button"
@click="showLoginModal = false"
class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50"
>
취소
</button>
<button
type="submit"
:disabled="loginLoading"
class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
<span x-show="!loginLoading">로그인</span>
<span x-show="loginLoading">로그인 중...</span>
</button>
</div>
</form>
</div>
</div>
<!-- JavaScript -->
<script>
// 스크립트 순차 로딩을 위한 함수
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// 스크립트들을 순차적으로 로드
async function loadScripts() {
try {
await loadScript('static/js/api.js?v=2025012290');
console.log('✅ API 스크립트 로드 완료');
await loadScript('static/js/auth.js?v=2025012240');
console.log('✅ Auth 스크립트 로드 완료');
await loadScript('static/js/memo-tree.js?v=2025012280');
console.log('✅ Memo Tree 스크립트 로드 완료');
// 모든 스크립트 로드 완료 후 Alpine.js 로드
console.log('🚀 Alpine.js 로딩...');
await loadScript('https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js');
console.log('✅ Alpine.js 로드 완료');
} catch (error) {
console.error('❌ 스크립트 로딩 실패:', error);
}
}
// DOM 로드 후 스크립트 로딩 시작
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', loadScripts);
} else {
loadScripts();
}
</script>
</body>
</html>

View File

@@ -119,7 +119,32 @@ class DocumentServerAPI {
// 인증 관련 API
async login(email, password) {
return await this.post('/auth/login', { email, password });
const response = await this.post('/auth/login', { email, password });
// 토큰 저장
if (response.access_token) {
this.setToken(response.access_token);
// 사용자 정보 가져오기
try {
const user = await this.getCurrentUser();
return {
success: true,
user: user,
token: response.access_token
};
} catch (error) {
return {
success: false,
message: '사용자 정보를 가져올 수 없습니다.'
};
}
} else {
return {
success: false,
message: '로그인에 실패했습니다.'
};
}
}
async logout() {
@@ -414,6 +439,73 @@ class DocumentServerAPI {
async deleteNote(noteId) {
return await this.delete(`/notes/${noteId}`);
}
// ============================================================================
// 트리 메모장 API
// ============================================================================
// 메모 트리 관리
async getUserMemoTrees(includeArchived = false) {
const params = includeArchived ? '?include_archived=true' : '';
return await this.get(`/memo-trees/${params}`);
}
async createMemoTree(treeData) {
return await this.post('/memo-trees/', treeData);
}
async getMemoTree(treeId) {
return await this.get(`/memo-trees/${treeId}`);
}
async updateMemoTree(treeId, treeData) {
return await this.put(`/memo-trees/${treeId}`, treeData);
}
async deleteMemoTree(treeId) {
return await this.delete(`/memo-trees/${treeId}`);
}
// 메모 노드 관리
async getMemoTreeNodes(treeId) {
return await this.get(`/memo-trees/${treeId}/nodes`);
}
async createMemoNode(nodeData) {
return await this.post(`/memo-trees/${nodeData.tree_id}/nodes`, nodeData);
}
async getMemoNode(nodeId) {
return await this.get(`/memo-trees/nodes/${nodeId}`);
}
async updateMemoNode(nodeId, nodeData) {
return await this.put(`/memo-trees/nodes/${nodeId}`, nodeData);
}
async deleteMemoNode(nodeId) {
return await this.delete(`/memo-trees/nodes/${nodeId}`);
}
// 노드 이동
async moveMemoNode(nodeId, moveData) {
return await this.put(`/memo-trees/nodes/${nodeId}/move`, moveData);
}
// 트리 통계
async getMemoTreeStats(treeId) {
return await this.get(`/memo-trees/${treeId}/stats`);
}
// 검색
async searchMemoNodes(searchData) {
return await this.post('/memo-trees/search', searchData);
}
// 내보내기
async exportMemoTree(exportData) {
return await this.post('/memo-trees/export', exportData);
}
}
// 전역 API 인스턴스

View File

@@ -0,0 +1,984 @@
/**
* 트리 구조 메모장 JavaScript
*/
// Monaco Editor 인스턴스
let monacoEditor = null;
// 트리 메모장 Alpine.js 컴포넌트
window.memoTreeApp = function() {
return {
// 상태 관리
currentUser: null,
userTrees: [],
selectedTreeId: '',
selectedTree: null,
treeNodes: [],
selectedNode: null,
// UI 상태
showNewTreeModal: false,
showNewNodeModal: false,
showTreeSettings: false,
showLoginModal: false,
// 로그인 폼 상태
loginForm: {
email: '',
password: ''
},
loginError: '',
loginLoading: false,
// 폼 데이터
newTree: {
title: '',
description: '',
tree_type: 'general'
},
newNode: {
title: '',
node_type: 'memo',
parent_id: null
},
// 에디터 상태
editorContent: '',
isEditorDirty: false,
// 트리 상태
expandedNodes: new Set(),
// 트리 다이어그램 상태
treeZoom: 1,
treePanX: 0,
treePanY: 0,
nodePositions: new Map(), // 노드 ID -> {x, y} 위치 매핑
isDragging: false,
dragNode: null,
dragOffset: { x: 0, y: 0 },
// 초기화
async init() {
console.log('🌳 트리 메모장 초기화 중...');
// API 객체가 로드될 때까지 대기 (더 긴 시간)
let retries = 0;
while ((!window.api || typeof window.api.getUserMemoTrees !== 'function') && retries < 50) {
console.log(`⏳ API 객체 로딩 대기 중... (${retries + 1}/50)`);
await new Promise(resolve => setTimeout(resolve, 100));
retries++;
}
if (!window.api || typeof window.api.getUserMemoTrees !== 'function') {
console.error('❌ API 객체 또는 getUserMemoTrees 함수를 로드할 수 없습니다.');
console.log('현재 window.api:', window.api);
if (window.api) {
console.log('API 객체의 메서드들:', Object.getOwnPropertyNames(window.api));
}
return;
}
try {
await this.checkAuthStatus();
if (this.currentUser) {
await this.loadUserTrees();
await this.initMonacoEditor();
}
} catch (error) {
console.error('❌ 초기화 실패:', error);
}
},
// 인증 상태 확인
async checkAuthStatus() {
try {
const user = await window.api.getCurrentUser();
this.currentUser = user;
console.log('✅ 사용자 인증됨:', user.email);
} catch (error) {
console.log('❌ 인증되지 않음:', error.message);
this.currentUser = null;
// 토큰이 있지만 만료된 경우 제거
if (localStorage.getItem('access_token')) {
console.log('🗑️ 만료된 토큰 제거');
localStorage.removeItem('access_token');
localStorage.removeItem('refresh_token');
window.api.clearToken();
}
}
},
// 사용자 트리 목록 로드
async loadUserTrees() {
try {
console.log('📊 사용자 트리 목록 로딩...');
const trees = await window.api.getUserMemoTrees();
this.userTrees = trees || [];
console.log(`${this.userTrees.length}개 트리 로드 완료`);
} catch (error) {
console.error('❌ 트리 목록 로드 실패:', error);
this.userTrees = [];
}
},
// 트리 로드
async loadTree(treeId) {
if (!treeId) {
this.selectedTree = null;
this.treeNodes = [];
this.selectedNode = null;
return;
}
try {
console.log('🌳 트리 로딩:', treeId);
// 트리 정보 로드
const tree = this.userTrees.find(t => t.id === treeId);
this.selectedTree = tree;
// 트리 노드들 로드
const nodes = await window.api.getMemoTreeNodes(treeId);
this.treeNodes = nodes || [];
// 첫 번째 노드 선택 (있다면)
if (this.treeNodes.length > 0) {
this.selectNode(this.treeNodes[0]);
}
// 트리 다이어그램 위치 계산
this.$nextTick(() => {
setTimeout(() => {
this.calculateNodePositions();
}, 100);
});
console.log(`✅ 트리 로드 완료: ${this.treeNodes.length}개 노드`);
} catch (error) {
console.error('❌ 트리 로드 실패:', error);
alert('트리를 불러오는 중 오류가 발생했습니다.');
}
},
// 트리 생성
async createTree() {
try {
console.log('🌳 새 트리 생성:', this.newTree);
const tree = await window.api.createMemoTree(this.newTree);
// 트리 목록에 추가
this.userTrees.push(tree);
// 새 트리 선택
this.selectedTreeId = tree.id;
await this.loadTree(tree.id);
// 모달 닫기 및 폼 리셋
this.showNewTreeModal = false;
this.newTree = { title: '', description: '', tree_type: 'general' };
console.log('✅ 트리 생성 완료');
} catch (error) {
console.error('❌ 트리 생성 실패:', error);
alert('트리 생성 중 오류가 발생했습니다.');
}
},
// 루트 노드 생성
async createRootNode() {
if (!this.selectedTree) return;
try {
const nodeData = {
tree_id: this.selectedTree.id,
title: '새 노드',
node_type: 'memo',
parent_id: null
};
const node = await window.api.createMemoNode(nodeData);
this.treeNodes.push(node);
this.selectNode(node);
console.log('✅ 루트 노드 생성 완료');
} catch (error) {
console.error('❌ 루트 노드 생성 실패:', error);
alert('노드 생성 중 오류가 발생했습니다.');
}
},
// 노드 선택
selectNode(node) {
// 이전 노드 저장
if (this.selectedNode && this.isEditorDirty) {
this.saveNode();
}
this.selectedNode = node;
// 에디터에 내용 로드
if (monacoEditor && node.content) {
monacoEditor.setValue(node.content || '');
this.isEditorDirty = false;
}
console.log('📝 노드 선택:', node.title);
},
// 노드 저장
async saveNode() {
if (!this.selectedNode) return;
try {
// 에디터 내용 가져오기
if (monacoEditor) {
this.selectedNode.content = monacoEditor.getValue();
// 단어 수 계산 (간단한 방식)
const wordCount = this.selectedNode.content
.replace(/\s+/g, ' ')
.trim()
.split(' ')
.filter(word => word.length > 0).length;
this.selectedNode.word_count = wordCount;
}
await window.api.updateMemoNode(this.selectedNode.id, this.selectedNode);
this.isEditorDirty = false;
console.log('✅ 노드 저장 완료');
} catch (error) {
console.error('❌ 노드 저장 실패:', error);
alert('노드 저장 중 오류가 발생했습니다.');
}
},
// 노드 제목 저장
async saveNodeTitle() {
if (!this.selectedNode) return;
await this.saveNode();
},
// 노드 타입 저장
async saveNodeType() {
if (!this.selectedNode) return;
await this.saveNode();
},
// 노드 상태 저장
async saveNodeStatus() {
if (!this.selectedNode) return;
await this.saveNode();
},
// 노드 삭제
async deleteNode(nodeId) {
if (!confirm('정말로 이 노드를 삭제하시겠습니까?')) return;
try {
await window.api.deleteMemoNode(nodeId);
// 트리에서 제거
this.treeNodes = this.treeNodes.filter(node => node.id !== nodeId);
// 선택된 노드였다면 선택 해제
if (this.selectedNode && this.selectedNode.id === nodeId) {
this.selectedNode = null;
if (monacoEditor) {
monacoEditor.setValue('');
}
}
console.log('✅ 노드 삭제 완료');
} catch (error) {
console.error('❌ 노드 삭제 실패:', error);
alert('노드 삭제 중 오류가 발생했습니다.');
}
},
// 자식 노드 가져오기
getChildNodes(parentId) {
return this.treeNodes
.filter(node => node.parent_id === parentId)
.sort((a, b) => a.sort_order - b.sort_order);
},
// 루트 노드들 가져오기
get rootNodes() {
return this.treeNodes
.filter(node => !node.parent_id)
.sort((a, b) => a.sort_order - b.sort_order);
},
// 노드 타입별 아이콘 가져오기
getNodeIcon(nodeType) {
const icons = {
folder: '📁',
memo: '📝',
chapter: '📖',
character: '👤',
plot: '📋'
};
return icons[nodeType] || '📝';
},
// 상태별 색상 클래스 가져오기
getStatusColor(status) {
const colors = {
draft: 'text-gray-500',
writing: 'text-yellow-600',
review: 'text-blue-600',
complete: 'text-green-600'
};
return colors[status] || 'text-gray-700';
},
// 트리 타입별 아이콘 가져오기
getTreeIcon(treeType) {
const icons = {
novel: '📚',
research: '🔬',
project: '💼',
general: '📂'
};
return icons[treeType] || '📂';
},
// 빠른 자식 노드 추가
async addChildNode(parentNode) {
if (!this.selectedTree) return;
try {
const nodeData = {
tree_id: this.selectedTree.id,
title: '새 노드',
node_type: 'memo',
parent_id: parentNode.id
};
const node = await window.api.createMemoNode(nodeData);
this.treeNodes.push(node);
// 부모 노드 펼치기
this.expandedNodes.add(parentNode.id);
// 새 노드 선택
this.selectNode(node);
console.log('✅ 자식 노드 생성 완료');
} catch (error) {
console.error('❌ 자식 노드 생성 실패:', error);
alert('노드 생성 중 오류가 발생했습니다.');
}
},
// 컨텍스트 메뉴 표시
showContextMenu(event, node) {
// TODO: 우클릭 컨텍스트 메뉴 구현
console.log('컨텍스트 메뉴:', node.title);
},
// 노드 메뉴 표시
showNodeMenu(event, node) {
// TODO: 노드 옵션 메뉴 구현
console.log('노드 메뉴:', node.title);
},
// 정사 경로 토글
async toggleCanonical(node) {
try {
const newCanonicalState = !node.is_canonical;
console.log(`🌟 정사 경로 토글: ${node.title} (${newCanonicalState ? '설정' : '해제'})`);
const updatedData = {
is_canonical: newCanonicalState
};
const updatedNode = await window.api.updateMemoNode(node.id, updatedData);
// 로컬 상태 업데이트 (Alpine.js 반응성 보장)
const nodeIndex = this.treeNodes.findIndex(n => n.id === node.id);
if (nodeIndex !== -1) {
// 배열 전체를 새로 생성하여 Alpine.js 반응성 트리거
this.treeNodes = this.treeNodes.map(n =>
n.id === node.id ? { ...n, ...updatedNode } : n
);
}
// 선택된 노드도 업데이트
if (this.selectedNode && this.selectedNode.id === node.id) {
this.selectedNode = { ...this.selectedNode, ...updatedNode };
}
// 강제 리렌더링을 위한 더미 업데이트
this.treeNodes = [...this.treeNodes];
// 트리 다시 그리기 (연결선 업데이트)
this.$nextTick(() => {
this.calculateNodePositions();
});
console.log(`✅ 정사 경로 ${newCanonicalState ? '설정' : '해제'} 완료`);
console.log('📊 업데이트된 노드:', updatedNode);
console.log('🔍 is_canonical 값:', updatedNode.is_canonical);
console.log('🔍 canonical_order 값:', updatedNode.canonical_order);
console.log('🔄 현재 treeNodes 개수:', this.treeNodes.length);
// 업데이트된 노드 찾기
const updatedNodeInArray = this.treeNodes.find(n => n.id === node.id);
console.log('🔍 배열 내 업데이트된 노드:', updatedNodeInArray?.is_canonical);
} catch (error) {
console.error('❌ 정사 경로 토글 실패:', error);
alert('정사 경로 설정 중 오류가 발생했습니다.');
}
},
// 노드 드래그 시작
startDragNode(event, node) {
// 현재는 드래그 기능 비활성화 (패닝과 충돌 방지)
event.stopPropagation();
console.log('드래그 시작:', node.title);
// TODO: 노드 드래그 앤 드롭 구현
},
// 노드 인라인 편집
editNodeInline(node) {
// 더블클릭 시 노드 선택하고 에디터로 포커스
this.selectNode(node);
// 에디터가 있다면 포커스
this.$nextTick(() => {
const editorContainer = document.getElementById('editor-container');
if (editorContainer && this.monacoEditor) {
this.monacoEditor.focus();
}
});
console.log('인라인 편집:', node.title);
},
// 노드 위치 계산 및 반환
getNodePosition(node) {
if (!this.nodePositions.has(node.id)) {
this.calculateNodePositions();
}
const pos = this.nodePositions.get(node.id) || { x: 0, y: 0 };
return `left: ${pos.x}px; top: ${pos.y}px;`;
},
// 트리 노드 위치 자동 계산
calculateNodePositions() {
const canvas = document.getElementById('tree-canvas');
if (!canvas) return;
const canvasWidth = canvas.clientWidth;
const canvasHeight = canvas.clientHeight;
// 노드 크기 설정
const nodeWidth = 200;
const nodeHeight = 80;
const levelHeight = 150; // 레벨 간 간격
const nodeSpacing = 50; // 노드 간 간격
// 레벨별 노드 그룹화
const levels = new Map();
// 루트 노드들 찾기
const rootNodes = this.treeNodes.filter(node => !node.parent_id);
// BFS로 레벨별 노드 배치
const queue = [];
rootNodes.forEach(node => {
queue.push({ node, level: 0 });
});
while (queue.length > 0) {
const { node, level } = queue.shift();
if (!levels.has(level)) {
levels.set(level, []);
}
levels.get(level).push(node);
// 자식 노드들을 다음 레벨에 추가
const children = this.getChildNodes(node.id);
children.forEach(child => {
queue.push({ node: child, level: level + 1 });
});
}
// 각 레벨의 노드들 위치 계산
levels.forEach((nodes, level) => {
const y = 100 + level * levelHeight; // 상단 여백 + 레벨 * 높이
const totalWidth = nodes.length * nodeWidth + (nodes.length - 1) * nodeSpacing;
const startX = (canvasWidth - totalWidth) / 2;
nodes.forEach((node, index) => {
const x = startX + index * (nodeWidth + nodeSpacing);
this.nodePositions.set(node.id, { x, y });
});
});
// 연결선 다시 그리기
this.drawConnections();
},
// SVG 연결선 그리기
drawConnections() {
const svg = document.getElementById('tree-connections');
if (!svg) return;
// 기존 연결선 제거
svg.innerHTML = '';
// 각 노드의 자식들과 연결선 그리기
this.treeNodes.forEach(node => {
const children = this.getChildNodes(node.id);
if (children.length === 0) return;
const parentPos = this.nodePositions.get(node.id);
if (!parentPos) return;
children.forEach(child => {
const childPos = this.nodePositions.get(child.id);
if (!childPos) return;
// 연결선 생성
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
// 부모 노드 하단 중앙에서 시작
const startX = parentPos.x + 100; // 노드 중앙
const startY = parentPos.y + 80; // 노드 하단
// 자식 노드 상단 중앙으로 연결
const endX = childPos.x + 100; // 노드 중앙
const endY = childPos.y; // 노드 상단
// 곡선 경로 생성 (베지어 곡선)
const midY = startY + (endY - startY) / 2;
const path = `M ${startX} ${startY} C ${startX} ${midY} ${endX} ${midY} ${endX} ${endY}`;
line.setAttribute('d', path);
line.setAttribute('stroke', '#9CA3AF');
line.setAttribute('stroke-width', '2');
line.setAttribute('fill', 'none');
line.setAttribute('marker-end', 'url(#arrowhead)');
svg.appendChild(line);
});
});
// 화살표 마커 추가 (한 번만)
if (!svg.querySelector('#arrowhead')) {
const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
marker.setAttribute('id', 'arrowhead');
marker.setAttribute('markerWidth', '10');
marker.setAttribute('markerHeight', '7');
marker.setAttribute('refX', '9');
marker.setAttribute('refY', '3.5');
marker.setAttribute('orient', 'auto');
const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
polygon.setAttribute('points', '0 0, 10 3.5, 0 7');
polygon.setAttribute('fill', '#9CA3AF');
marker.appendChild(polygon);
defs.appendChild(marker);
svg.appendChild(defs);
}
},
// 트리 중앙 정렬
centerTree() {
this.treePanX = 0;
this.treePanY = 0;
this.treeZoom = 1;
},
// 확대
zoomIn() {
this.treeZoom = Math.min(this.treeZoom * 1.2, 3);
},
// 축소
zoomOut() {
this.treeZoom = Math.max(this.treeZoom / 1.2, 0.3);
},
// 휠 이벤트 처리 (확대/축소)
handleWheel(event) {
event.preventDefault();
if (event.deltaY < 0) {
this.zoomIn();
} else {
this.zoomOut();
}
},
// 패닝 시작
startPan(event) {
if (event.target.closest('.tree-diagram-node')) return; // 노드 클릭 시 패닝 방지
this.isPanning = true;
this.panStartX = event.clientX - this.treePanX;
this.panStartY = event.clientY - this.treePanY;
document.addEventListener('mousemove', this.handlePan.bind(this));
document.addEventListener('mouseup', this.stopPan.bind(this));
},
// 패닝 처리
handlePan(event) {
if (!this.isPanning) return;
this.treePanX = event.clientX - this.panStartX;
this.treePanY = event.clientY - this.panStartY;
},
// 패닝 종료
stopPan() {
this.isPanning = false;
document.removeEventListener('mousemove', this.handlePan);
document.removeEventListener('mouseup', this.stopPan);
},
// 재귀적 트리 노드 렌더링
renderTreeNodeRecursive(node, depth, isLast = false, parentPath = []) {
const hasChildren = this.getChildNodes(node.id).length > 0;
const isExpanded = this.expandedNodes.has(node.id);
const isSelected = this.selectedNode && this.selectedNode.id === node.id;
const isRoot = depth === 0;
// 상태별 색상
let statusClass = 'text-gray-700';
switch(node.status) {
case 'draft': statusClass = 'text-gray-500'; break;
case 'writing': statusClass = 'text-yellow-600'; break;
case 'review': statusClass = 'text-blue-600'; break;
case 'complete': statusClass = 'text-green-600'; break;
}
// 트리 라인 생성
let treeLines = '';
for (let i = 0; i < depth; i++) {
if (i < parentPath.length && parentPath[i]) {
// 부모가 마지막이 아니면 세로선 표시
treeLines += '<span class="tree-line vertical"></span>';
} else {
// 빈 공간
treeLines += '<span class="tree-line empty"></span>';
}
}
// 현재 노드의 연결선
let nodeConnector = '';
if (!isRoot) {
if (isLast) {
nodeConnector = '<span class="tree-line corner"></span>'; // └─
} else {
nodeConnector = '<span class="tree-line branch"></span>'; // ├─
}
}
let html = `
<div class="tree-node-item ${isRoot ? 'root' : ''} ${isLast ? 'last-child' : ''}">
<div
class="tree-node py-1 cursor-pointer flex items-center hover:bg-gray-50 group ${isSelected ? 'bg-blue-50 border-r-2 border-blue-500' : ''} ${statusClass}"
onclick="window.memoTreeInstance.selectNode(${JSON.stringify(node).replace(/"/g, '&quot;')})"
oncontextmenu="event.preventDefault(); window.memoTreeInstance.showContextMenu(event, ${JSON.stringify(node).replace(/"/g, '&quot;')})"
>
<!-- 트리 라인들 -->
<div class="flex items-center">
${treeLines}
${nodeConnector}
<!-- 펼치기/접기 버튼 -->
${hasChildren ?
`<button
onclick="event.stopPropagation(); window.memoTreeInstance.toggleNode('${node.id}')"
class="w-4 h-4 flex items-center justify-center text-gray-400 hover:text-gray-600 mr-1 ml-1"
>
<i class="fas fa-${isExpanded ? 'minus' : 'plus'}-square text-xs"></i>
</button>` :
'<span class="w-4 mr-1 ml-1"></span>'
}
<!-- 아이콘 -->
<span class="mr-2 text-sm">${this.getNodeIcon(node.node_type)}</span>
<!-- 제목 -->
<span class="flex-1 truncate font-medium">${node.title}</span>
</div>
<!-- 액션 버튼들 (호버 시 표시) -->
<div class="opacity-0 group-hover:opacity-100 flex space-x-1 ml-2">
<button
onclick="event.stopPropagation(); window.memoTreeInstance.addChildNode(${JSON.stringify(node).replace(/"/g, '&quot;')})"
class="w-6 h-6 flex items-center justify-center text-gray-400 hover:text-green-600 hover:bg-green-50 rounded"
title="자식 노드 추가"
>
<i class="fas fa-plus text-xs"></i>
</button>
<button
onclick="event.stopPropagation(); window.memoTreeInstance.showNodeMenu(event, ${JSON.stringify(node).replace(/"/g, '&quot;')})"
class="w-6 h-6 flex items-center justify-center text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded"
title="더보기"
>
<i class="fas fa-ellipsis-h text-xs"></i>
</button>
</div>
<!-- 단어 수 -->
${node.word_count > 0 ?
`<span class="text-xs text-gray-400 ml-2">${node.word_count}w</span>` :
''
}
</div>
`;
// 자식 노드들 재귀적으로 렌더링
if (hasChildren && isExpanded) {
const children = this.getChildNodes(node.id);
const newParentPath = [...parentPath, !isLast];
children.forEach((child, index) => {
const isChildLast = index === children.length - 1;
html += this.renderTreeNodeRecursive(child, depth + 1, isChildLast, newParentPath);
});
}
html += '</div>';
return html;
},
// 노드 토글
toggleNode(nodeId) {
if (this.expandedNodes.has(nodeId)) {
this.expandedNodes.delete(nodeId);
} else {
this.expandedNodes.add(nodeId);
}
// 트리 다시 렌더링을 위해 상태 업데이트
this.$nextTick(() => {
this.rerenderTree();
});
},
// 트리 다시 렌더링
rerenderTree() {
// Alpine.js의 반응성을 트리거하기 위해 배열을 새로 할당
this.treeNodes = [...this.treeNodes];
// 강제로 DOM 업데이트
this.$nextTick(() => {
// 트리 컨테이너 찾아서 다시 렌더링
const treeContainer = document.querySelector('.tree-container');
if (treeContainer) {
// Alpine.js가 자동으로 다시 렌더링함
}
});
},
// 모두 펼치기
expandAll() {
this.treeNodes.forEach(node => {
if (this.getChildNodes(node.id).length > 0) {
this.expandedNodes.add(node.id);
}
});
this.rerenderTree();
},
// 모두 접기
collapseAll() {
this.expandedNodes.clear();
this.rerenderTree();
},
// Monaco Editor 초기화
async initMonacoEditor() {
console.log('🎨 Monaco Editor 초기화 시작...');
// Monaco Editor 로더가 로드될 때까지 대기
let retries = 0;
while (typeof require === 'undefined' && retries < 30) {
console.log(`⏳ Monaco Editor 로더 대기 중... (${retries + 1}/30)`);
await new Promise(resolve => setTimeout(resolve, 200));
retries++;
}
if (typeof require === 'undefined') {
console.warn('❌ Monaco Editor 로더를 찾을 수 없습니다. 기본 textarea를 사용합니다.');
this.setupFallbackEditor();
return;
}
try {
require.config({
paths: {
vs: 'https://cdn.jsdelivr.net/npm/monaco-editor@0.44.0/min/vs'
}
});
require(['vs/editor/editor.main'], () => {
// 에디터 컨테이너가 생성될 때까지 대기
const waitForEditor = () => {
const editorElement = document.getElementById('monaco-editor');
if (!editorElement) {
console.log('⏳ Monaco Editor 컨테이너 대기 중...');
setTimeout(waitForEditor, 100);
return;
}
// 이미 Monaco Editor가 생성되어 있다면 제거
if (monacoEditor) {
monacoEditor.dispose();
monacoEditor = null;
}
monacoEditor = monaco.editor.create(editorElement, {
value: '',
language: 'markdown',
theme: 'vs-light',
automaticLayout: true,
wordWrap: 'on',
minimap: { enabled: false },
scrollBeyondLastLine: false,
fontSize: 14,
lineNumbers: 'on',
folding: true,
renderWhitespace: 'boundary'
});
// 내용 변경 감지
monacoEditor.onDidChangeModelContent(() => {
this.isEditorDirty = true;
});
console.log('✅ Monaco Editor 초기화 완료');
};
// 에디터 컨테이너 대기 시작
waitForEditor();
});
} catch (error) {
console.error('❌ Monaco Editor 초기화 실패:', error);
this.setupFallbackEditor();
}
},
// 폴백 에디터 설정 (Monaco가 실패했을 때)
setupFallbackEditor() {
console.log('📝 폴백 textarea 에디터 설정 중...');
const editorElement = document.getElementById('monaco-editor');
if (editorElement) {
editorElement.innerHTML = `
<textarea
id="fallback-editor"
class="w-full h-full p-4 border-none resize-none focus:outline-none"
placeholder="여기에 내용을 입력하세요..."
></textarea>
`;
const textarea = document.getElementById('fallback-editor');
if (textarea) {
textarea.addEventListener('input', () => {
this.isEditorDirty = true;
});
console.log('✅ 폴백 에디터 설정 완료');
}
}
},
// 로그인 모달 열기
openLoginModal() {
this.showLoginModal = true;
this.loginForm = { email: '', password: '' };
this.loginError = '';
},
// 로그인 처리
async handleLogin() {
this.loginLoading = true;
this.loginError = '';
try {
const response = await window.api.login(this.loginForm.email, this.loginForm.password);
if (response.success) {
this.currentUser = response.user;
this.showLoginModal = false;
// 트리 목록 다시 로드
await this.loadUserTrees();
} else {
this.loginError = response.message || '로그인에 실패했습니다.';
}
} catch (error) {
console.error('로그인 오류:', error);
this.loginError = '로그인 중 오류가 발생했습니다.';
} finally {
this.loginLoading = false;
}
},
// 로그아웃
async logout() {
try {
await window.api.logout();
this.currentUser = null;
this.userTrees = [];
this.selectedTree = null;
this.treeNodes = [];
this.selectedNode = null;
console.log('✅ 로그아웃 완료');
} catch (error) {
console.error('❌ 로그아웃 실패:', error);
}
}
};
};
// 전역 인스턴스 등록 (HTML에서 접근하기 위해)
window.memoTreeInstance = null;
// Alpine.js 초기화 후 전역 인스턴스 설정
document.addEventListener('alpine:init', () => {
// 페이지 로드 후 인스턴스 등록
setTimeout(() => {
const appElement = document.querySelector('[x-data="memoTreeApp()"]');
if (appElement && appElement._x_dataStack) {
window.memoTreeInstance = appElement._x_dataStack[0];
}
}, 100);
});
// 트리 노드 컴포넌트
window.treeNodeComponent = function(node) {
return {
node: node,
expanded: true,
get hasChildren() {
return window.memoTreeInstance?.getChildNodes(this.node.id).length > 0;
},
toggleExpanded() {
this.expanded = !this.expanded;
if (this.expanded) {
window.memoTreeInstance?.expandedNodes.add(this.node.id);
} else {
window.memoTreeInstance?.expandedNodes.delete(this.node.id);
}
}
};
};
console.log('🌳 트리 메모장 JavaScript 로드 완료');

View File

@@ -0,0 +1,345 @@
// story-view.js - 정사 경로 스토리 뷰 컴포넌트
console.log('📖 스토리 뷰 JavaScript 로드 완료');
// Alpine.js 컴포넌트
window.storyViewApp = function() {
return {
// 사용자 상태
currentUser: null,
// 트리 데이터
userTrees: [],
selectedTreeId: '',
selectedTree: null,
canonicalNodes: [], // 정사 경로 노드들만
// UI 상태
viewMode: 'toc', // 'toc' | 'full'
showLoginModal: false,
showEditModal: false,
editingNode: null,
// 로그인 폼 상태
loginForm: {
email: '',
password: ''
},
loginError: '',
loginLoading: false,
// 계산된 속성들
get totalWords() {
return this.canonicalNodes.reduce((sum, node) => sum + (node.word_count || 0), 0);
},
// 초기화
async init() {
console.log('📖 스토리 뷰 초기화 중...');
// API 로드 대기
let retryCount = 0;
while (!window.api && retryCount < 50) {
await new Promise(resolve => setTimeout(resolve, 100));
retryCount++;
}
if (!window.api) {
console.error('❌ API가 로드되지 않았습니다.');
return;
}
// 사용자 인증 상태 확인
await this.checkAuthStatus();
// 인증된 경우 트리 목록 로드
if (this.currentUser) {
await this.loadUserTrees();
}
},
// 인증 상태 확인
async checkAuthStatus() {
try {
const user = await window.api.getCurrentUser();
this.currentUser = user;
console.log('✅ 사용자 인증됨:', user.email);
} catch (error) {
console.log('❌ 인증되지 않음:', error.message);
this.currentUser = null;
// 만료된 토큰 정리
localStorage.removeItem('token');
}
},
// 사용자 트리 목록 로드
async loadUserTrees() {
try {
console.log('📊 사용자 트리 목록 로딩...');
const trees = await window.api.getUserMemoTrees();
this.userTrees = trees || [];
console.log(`${this.userTrees.length}개 트리 로드 완료`);
} catch (error) {
console.error('❌ 트리 목록 로드 실패:', error);
this.userTrees = [];
}
},
// 스토리 로드 (정사 경로만)
async loadStory(treeId) {
if (!treeId) {
this.selectedTree = null;
this.canonicalNodes = [];
return;
}
try {
console.log('📖 스토리 로딩:', treeId);
// 트리 정보 로드
this.selectedTree = await window.api.getMemoTree(treeId);
// 모든 노드 로드
const allNodes = await window.api.getMemoTreeNodes(treeId);
// 정사 경로 노드들만 필터링하고 순서대로 정렬
this.canonicalNodes = allNodes
.filter(node => node.is_canonical)
.sort((a, b) => (a.canonical_order || 0) - (b.canonical_order || 0));
console.log(`✅ 스토리 로드 완료: ${this.canonicalNodes.length}개 정사 노드`);
} catch (error) {
console.error('❌ 스토리 로드 실패:', error);
alert('스토리를 불러오는 중 오류가 발생했습니다.');
}
},
// 뷰 모드 토글
toggleView() {
this.viewMode = this.viewMode === 'toc' ? 'full' : 'toc';
},
// 챕터로 스크롤
scrollToChapter(nodeId) {
if (this.viewMode === 'toc') {
this.viewMode = 'full';
// DOM 업데이트 대기 후 스크롤
this.$nextTick(() => {
const element = document.getElementById(`chapter-${nodeId}`);
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
});
} else {
const element = document.getElementById(`chapter-${nodeId}`);
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
},
// 챕터 편집 (인라인 모달)
editChapter(node) {
this.editingNode = { ...node }; // 복사본 생성
this.showEditModal = true;
},
// 편집 취소
cancelEdit() {
this.showEditModal = false;
this.editingNode = null;
},
// 편집 저장
async saveEdit() {
if (!this.editingNode) return;
try {
console.log('💾 챕터 저장 중:', this.editingNode.title);
const updatedNode = await window.api.updateMemoNode(this.editingNode.id, {
title: this.editingNode.title,
content: this.editingNode.content
});
// 로컬 상태 업데이트
const nodeIndex = this.canonicalNodes.findIndex(n => n.id === this.editingNode.id);
if (nodeIndex !== -1) {
this.canonicalNodes = this.canonicalNodes.map(n =>
n.id === this.editingNode.id ? { ...n, ...updatedNode } : n
);
}
this.showEditModal = false;
this.editingNode = null;
console.log('✅ 챕터 저장 완료');
} catch (error) {
console.error('❌ 챕터 저장 실패:', error);
alert('챕터 저장 중 오류가 발생했습니다.');
}
},
// 스토리 내보내기
async exportStory() {
if (!this.selectedTree || this.canonicalNodes.length === 0) {
alert('내보낼 스토리가 없습니다.');
return;
}
try {
// 텍스트 형태로 스토리 생성
let storyText = `${this.selectedTree.title}\n`;
storyText += `${'='.repeat(this.selectedTree.title.length)}\n\n`;
if (this.selectedTree.description) {
storyText += `${this.selectedTree.description}\n\n`;
}
storyText += `작성일: ${this.formatDate(this.selectedTree.created_at)}\n`;
storyText += `수정일: ${this.formatDate(this.selectedTree.updated_at)}\n`;
storyText += `${this.canonicalNodes.length}개 챕터, ${this.totalWords}단어\n\n`;
storyText += `${'='.repeat(50)}\n\n`;
this.canonicalNodes.forEach((node, index) => {
storyText += `${index + 1}. ${node.title}\n`;
storyText += `${'-'.repeat(node.title.length + 3)}\n\n`;
if (node.content) {
// HTML 태그 제거
const plainText = node.content.replace(/<[^>]*>/g, '');
storyText += `${plainText}\n\n`;
} else {
storyText += `[이 챕터는 아직 내용이 없습니다]\n\n`;
}
storyText += `${'─'.repeat(30)}\n\n`;
});
// 파일 다운로드
const blob = new Blob([storyText], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${this.selectedTree.title}_정사스토리.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
console.log('✅ 스토리 내보내기 완료');
} catch (error) {
console.error('❌ 스토리 내보내기 실패:', error);
alert('스토리 내보내기 중 오류가 발생했습니다.');
}
},
// 스토리 인쇄
printStory() {
if (!this.selectedTree || this.canonicalNodes.length === 0) {
alert('인쇄할 스토리가 없습니다.');
return;
}
// 전체 뷰로 변경 후 인쇄
if (this.viewMode === 'toc') {
this.viewMode = 'full';
this.$nextTick(() => {
window.print();
});
} else {
window.print();
}
},
// 유틸리티 함수들
formatDate(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
return date.toLocaleDateString('ko-KR', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
},
formatContent(content) {
if (!content) return '';
// 간단한 마크다운 스타일 변환
return content
.replace(/\n\n/g, '</p><p>')
.replace(/\n/g, '<br>')
.replace(/^/, '<p>')
.replace(/$/, '</p>');
},
getNodeTypeLabel(nodeType) {
const labels = {
'folder': '📁 폴더',
'memo': '📝 메모',
'chapter': '📖 챕터',
'character': '👤 인물',
'plot': '📋 플롯'
};
return labels[nodeType] || '📝 메모';
},
getStatusLabel(status) {
const labels = {
'draft': '📝 초안',
'writing': '✍️ 작성중',
'review': '👀 검토중',
'complete': '✅ 완료'
};
return labels[status] || '📝 초안';
},
// 로그인 관련 함수들
openLoginModal() {
this.showLoginModal = true;
this.loginForm = { email: '', password: '' };
this.loginError = '';
},
async handleLogin() {
this.loginLoading = true;
this.loginError = '';
try {
const response = await window.api.login(this.loginForm.email, this.loginForm.password);
if (response.success) {
this.currentUser = response.user;
this.showLoginModal = false;
// 트리 목록 다시 로드
await this.loadUserTrees();
} else {
this.loginError = response.message || '로그인에 실패했습니다.';
}
} catch (error) {
console.error('로그인 오류:', error);
this.loginError = '로그인 중 오류가 발생했습니다.';
} finally {
this.loginLoading = false;
}
},
async logout() {
try {
await window.api.logout();
this.currentUser = null;
this.userTrees = [];
this.selectedTree = null;
this.canonicalNodes = [];
console.log('✅ 로그아웃 완료');
} catch (error) {
console.error('❌ 로그아웃 실패:', error);
}
}
};
};
console.log('📖 스토리 뷰 컴포넌트 등록 완료');

389
frontend/story-view.html Normal file
View File

@@ -0,0 +1,389 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>스토리 뷰 - 정사 경로</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/* 목차 스타일 */
.toc-item {
transition: all 0.2s ease;
}
.toc-item:hover {
background-color: #f8fafc;
border-left: 4px solid #3b82f6;
padding-left: 16px;
}
.toc-number {
min-width: 2rem;
}
.story-content {
line-height: 1.8;
}
.chapter-divider {
background: linear-gradient(90deg, #e5e7eb 0%, #9ca3af 50%, #e5e7eb 100%);
height: 1px;
margin: 2rem 0;
}
/* 프린트 스타일 */
@media print {
.no-print { display: none !important; }
.story-content { font-size: 12pt; line-height: 1.6; }
.toc-item { break-inside: avoid; }
}
</style>
</head>
<body class="bg-gray-50" x-data="storyViewApp()" x-init="init()">
<!-- 헤더 -->
<header class="bg-white shadow-sm border-b no-print">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center h-16">
<!-- 왼쪽: 로고 및 네비게이션 -->
<div class="flex items-center space-x-4">
<a href="index.html" class="flex items-center space-x-2">
<i class="fas fa-book text-blue-600 text-xl"></i>
<span class="text-xl font-bold text-gray-900">Document Server</span>
</a>
<span class="text-gray-400">|</span>
<nav class="flex space-x-4">
<a href="memo-tree.html" class="text-gray-600 hover:text-blue-600 px-3 py-2 rounded-md text-sm font-medium">
<i class="fas fa-sitemap mr-1"></i> 트리 에디터
</a>
<a href="story-view.html" class="bg-blue-100 text-blue-700 px-3 py-2 rounded-md text-sm font-medium">
<i class="fas fa-book-open mr-1"></i> 스토리 뷰
</a>
</nav>
</div>
<!-- 오른쪽: 사용자 정보 및 액션 -->
<div class="flex items-center space-x-4">
<div x-show="currentUser" class="flex items-center space-x-3">
<span class="text-sm text-gray-600" x-text="currentUser?.full_name || currentUser?.email"></span>
<button @click="logout()" class="text-sm text-gray-500 hover:text-gray-700">로그아웃</button>
</div>
<button x-show="!currentUser" @click="openLoginModal()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
로그인
</button>
</div>
</div>
</div>
</header>
<!-- 메인 컨테이너 -->
<div class="min-h-screen pt-4" x-show="currentUser">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<!-- 상단 툴바 -->
<div class="bg-white rounded-lg shadow-sm p-4 mb-6 no-print">
<div class="flex items-center justify-between">
<!-- 트리 선택 -->
<div class="flex items-center space-x-4">
<select
x-model="selectedTreeId"
@change="loadStory(selectedTreeId)"
class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">📚 스토리 선택</option>
<template x-for="tree in userTrees" :key="tree.id">
<option :value="tree.id" x-text="`📖 ${tree.title}`"></option>
</template>
</select>
<div x-show="selectedTree" class="text-sm text-gray-600">
<span x-text="`총 ${canonicalNodes.length}개 챕터`"></span>
<span class="mx-2"></span>
<span x-text="`${totalWords}단어`"></span>
</div>
</div>
<!-- 액션 버튼들 -->
<div class="flex items-center space-x-2">
<button
@click="toggleView()"
class="px-3 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700 text-sm"
>
<i class="fas fa-eye mr-1"></i>
<span x-text="viewMode === 'toc' ? '전체보기' : '목차보기'"></span>
</button>
<button
@click="exportStory()"
class="px-3 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 text-sm"
>
<i class="fas fa-download mr-1"></i> 내보내기
</button>
<button
@click="printStory()"
class="px-3 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 text-sm"
>
<i class="fas fa-print mr-1"></i> 인쇄
</button>
</div>
</div>
</div>
<!-- 스토리 없음 상태 -->
<div x-show="!selectedTree" class="bg-white rounded-lg shadow-sm p-12 text-center">
<i class="fas fa-book-open text-6xl text-gray-300 mb-4"></i>
<h3 class="text-lg font-medium text-gray-900 mb-2">스토리를 선택하세요</h3>
<p class="text-gray-500">위에서 트리를 선택하면 정사 경로가 목차 형태로 표시됩니다</p>
</div>
<!-- 정사 노드 없음 상태 -->
<div x-show="selectedTree && canonicalNodes.length === 0" class="bg-white rounded-lg shadow-sm p-12 text-center">
<i class="fas fa-route text-6xl text-gray-300 mb-4"></i>
<h3 class="text-lg font-medium text-gray-900 mb-2">정사 경로가 없습니다</h3>
<p class="text-gray-500 mb-4">트리 에디터에서 노드들을 정사로 설정해주세요</p>
<a href="memo-tree.html" class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
<i class="fas fa-sitemap mr-2"></i> 트리 에디터로 가기
</a>
</div>
<!-- 스토리 컨텐츠 -->
<div x-show="selectedTree && canonicalNodes.length > 0" class="space-y-6">
<!-- 스토리 헤더 -->
<div class="bg-white rounded-lg shadow-sm p-6">
<h1 class="text-3xl font-bold text-gray-900 mb-2" x-text="selectedTree?.title"></h1>
<p class="text-gray-600 mb-4" x-text="selectedTree?.description || '소설 설명이 없습니다'"></p>
<div class="flex items-center space-x-4 text-sm text-gray-500">
<span><i class="fas fa-calendar mr-1"></i> <span x-text="formatDate(selectedTree?.created_at)"></span></span>
<span><i class="fas fa-edit mr-1"></i> <span x-text="formatDate(selectedTree?.updated_at)"></span></span>
<span><i class="fas fa-list-ol mr-1"></i> <span x-text="`${canonicalNodes.length}개 챕터`"></span></span>
<span><i class="fas fa-font mr-1"></i> <span x-text="`${totalWords}단어`"></span></span>
</div>
</div>
<!-- 목차 뷰 -->
<div x-show="viewMode === 'toc'" class="bg-white rounded-lg shadow-sm">
<div class="p-6 border-b">
<h2 class="text-xl font-semibold text-gray-900 flex items-center">
<i class="fas fa-list mr-2"></i> 목차 (정사 경로)
</h2>
</div>
<div class="p-6">
<div class="space-y-2">
<template x-for="(node, index) in canonicalNodes" :key="node.id">
<div
class="toc-item flex items-center p-3 rounded-lg cursor-pointer"
@click="scrollToChapter(node.id)"
>
<span class="toc-number text-sm font-medium text-gray-500 mr-3" x-text="`${index + 1}.`"></span>
<div class="flex-1">
<h3 class="font-medium text-gray-900" x-text="node.title"></h3>
<div class="flex items-center space-x-3 text-xs text-gray-500 mt-1">
<span x-text="getNodeTypeLabel(node.node_type)"></span>
<span x-show="node.word_count > 0" x-text="`${node.word_count}단어`"></span>
<span x-text="getStatusLabel(node.status)"></span>
</div>
</div>
<i class="fas fa-chevron-right text-gray-400"></i>
</div>
</template>
</div>
</div>
</div>
<!-- 전체 스토리 뷰 -->
<div x-show="viewMode === 'full'" class="bg-white rounded-lg shadow-sm">
<div class="p-6 border-b">
<h2 class="text-xl font-semibold text-gray-900 flex items-center">
<i class="fas fa-book-open mr-2"></i> 전체 스토리
</h2>
</div>
<div class="story-content">
<template x-for="(node, index) in canonicalNodes" :key="node.id">
<div :id="`chapter-${node.id}`" class="chapter-section">
<!-- 챕터 헤더 -->
<div class="p-6 bg-gray-50 border-b">
<div class="flex items-center justify-between">
<div>
<h3 class="text-lg font-semibold text-gray-900 flex items-center">
<span class="text-blue-600 mr-2" x-text="`${index + 1}.`"></span>
<span x-text="node.title"></span>
</h3>
<div class="flex items-center space-x-3 text-sm text-gray-500 mt-1">
<span x-text="getNodeTypeLabel(node.node_type)"></span>
<span x-show="node.word_count > 0" x-text="`${node.word_count}단어`"></span>
<span x-text="getStatusLabel(node.status)"></span>
</div>
</div>
<button
@click="editChapter(node)"
class="no-print px-3 py-1 text-sm text-blue-600 hover:bg-blue-50 rounded"
>
<i class="fas fa-edit mr-1"></i> 편집
</button>
</div>
</div>
<!-- 챕터 내용 -->
<div class="p-6">
<div x-show="node.content" class="prose max-w-none" x-html="formatContent(node.content)"></div>
<div x-show="!node.content" class="text-gray-400 italic text-center py-8">
이 챕터는 아직 내용이 없습니다
</div>
</div>
<!-- 챕터 구분선 -->
<div x-show="index < canonicalNodes.length - 1" class="chapter-divider"></div>
</div>
</template>
</div>
</div>
</div>
</div>
</div>
<!-- 로그인이 필요한 경우 -->
<div x-show="!currentUser" class="flex items-center justify-center min-h-screen">
<div class="text-center">
<i class="fas fa-lock text-6xl text-gray-300 mb-4"></i>
<h2 class="text-2xl font-bold text-gray-900 mb-2">로그인이 필요합니다</h2>
<p class="text-gray-600 mb-6">스토리를 보려면 먼저 로그인해주세요</p>
<button @click="openLoginModal()" class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
로그인하기
</button>
</div>
</div>
<!-- 편집 모달 -->
<div x-show="showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div class="bg-white rounded-lg w-full max-w-4xl mx-4 h-5/6 flex flex-col">
<div class="p-6 border-b">
<div class="flex items-center justify-between">
<h2 class="text-xl font-bold">챕터 편집</h2>
<button @click="cancelEdit()" class="text-gray-500 hover:text-gray-700">
<i class="fas fa-times text-xl"></i>
</button>
</div>
</div>
<div class="flex-1 p-6 overflow-hidden">
<div class="h-full flex flex-col space-y-4">
<!-- 제목 편집 -->
<div>
<label class="block text-sm font-medium text-gray-700 mb-2">제목</label>
<input
type="text"
x-model="editingNode.title"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder="챕터 제목을 입력하세요"
>
</div>
<!-- 내용 편집 -->
<div class="flex-1 flex flex-col">
<label class="block text-sm font-medium text-gray-700 mb-2">내용</label>
<textarea
x-model="editingNode.content"
class="flex-1 w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
placeholder="챕터 내용을 입력하세요..."
></textarea>
</div>
</div>
</div>
<div class="p-6 border-t bg-gray-50 flex justify-end space-x-3">
<button
@click="cancelEdit()"
class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50"
>
취소
</button>
<button
@click="saveEdit()"
class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
>
<i class="fas fa-save mr-2"></i> 저장
</button>
</div>
</div>
</div>
<!-- 로그인 모달 -->
<div x-show="showLoginModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div class="bg-white rounded-lg p-6 w-96 max-w-md mx-4">
<h2 class="text-xl font-bold mb-4">로그인</h2>
<form @submit.prevent="handleLogin()">
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-2">이메일</label>
<input
type="email"
x-model="loginForm.email"
required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
</div>
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-2">비밀번호</label>
<input
type="password"
x-model="loginForm.password"
required
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
</div>
<div x-show="loginError" class="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
<span x-text="loginError"></span>
</div>
<div class="flex justify-end space-x-3">
<button
type="button"
@click="showLoginModal = false"
class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50"
>
취소
</button>
<button
type="submit"
:disabled="loginLoading"
class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
<span x-show="!loginLoading">로그인</span>
<span x-show="loginLoading">로그인 중...</span>
</button>
</div>
</form>
</div>
</div>
<!-- 스크립트 로딩 -->
<script>
// 순차적 스크립트 로딩
async function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// Alpine.js 초기화 이벤트 리스너
document.addEventListener('alpine:init', () => {
console.log('Alpine.js 초기화됨');
});
// 스크립트 순차 로딩
(async () => {
try {
await loadScript('static/js/api.js?v=2025012290');
console.log('✅ API 스크립트 로드 완료');
await loadScript('static/js/story-view.js?v=2025012295');
console.log('✅ Story View 스크립트 로드 완료');
// 모든 스크립트 로드 완료 후 Alpine.js 로드
console.log('🚀 Alpine.js 로딩...');
await loadScript('https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js');
console.log('✅ Alpine.js 로드 완료');
} catch (error) {
console.error('❌ 스크립트 로드 실패:', error);
}
})();
</script>
</body>
</html>