`;
// 위치 계산
const rect = element.getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
document.body.appendChild(tooltip);
// 말풍선 위치 조정
const tooltipRect = tooltip.getBoundingClientRect();
let top = rect.bottom + scrollTop + 5;
let left = rect.left + scrollLeft;
// 화면 경계 체크
if (left + tooltipRect.width > window.innerWidth) {
left = window.innerWidth - tooltipRect.width - 10;
}
if (top + tooltipRect.height > window.innerHeight + scrollTop) {
top = rect.top + scrollTop - tooltipRect.height - 5;
}
tooltip.style.top = top + 'px';
tooltip.style.left = left + 'px';
// 외부 클릭 시 닫기
setTimeout(() => {
document.addEventListener('click', this.handleTooltipOutsideClick.bind(this));
}, 100);
},
// 말풍선 숨기기
hideTooltip() {
const tooltip = document.getElementById('highlight-tooltip');
if (tooltip) {
tooltip.remove();
}
document.removeEventListener('click', this.handleTooltipOutsideClick.bind(this));
},
// 말풍선 외부 클릭 처리
handleTooltipOutsideClick(e) {
const tooltip = document.getElementById('highlight-tooltip');
if (tooltip && !tooltip.contains(e.target) && !e.target.classList.contains('highlight')) {
this.hideTooltip();
}
},
// 짧은 날짜 형식
formatShortDate(dateString) {
const date = new Date(dateString);
const now = new Date();
const diffTime = Math.abs(now - date);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays === 1) {
return '오늘';
} else if (diffDays === 2) {
return '어제';
} else if (diffDays <= 7) {
return `${diffDays-1}일 전`;
} else {
return date.toLocaleDateString('ko-KR', {
year: '2-digit',
month: '2-digit',
day: '2-digit'
});
}
},
// 메모 추가 폼 표시
showAddNoteForm(highlightId) {
const tooltip = document.getElementById('highlight-tooltip');
if (!tooltip) return;
const notesList = tooltip.querySelector('#notes-list');
notesList.innerHTML = `
`;
// 텍스트 영역에 포커스
setTimeout(() => {
document.getElementById('new-note-content').focus();
}, 100);
},
// 메모 추가 취소
cancelAddNote(highlightId) {
// 말풍선 다시 표시
const highlight = this.highlights.find(h => h.id === highlightId);
if (highlight) {
const element = document.querySelector(`[data-highlight-id="${highlightId}"]`);
if (element) {
this.showHighlightTooltip(highlight, element);
}
}
},
// 새 메모 저장
async saveNewNote(highlightId) {
const content = document.getElementById('new-note-content').value.trim();
if (!content) {
alert('메모 내용을 입력해주세요');
return;
}
try {
const noteData = {
highlight_id: highlightId,
content: content,
is_private: false,
tags: []
};
const newNote = await api.createNote(noteData);
// 로컬 데이터 업데이트
this.notes.push(newNote);
// 말풍선 새로고침
const highlight = this.highlights.find(h => h.id === highlightId);
if (highlight) {
const element = document.querySelector(`[data-highlight-id="${highlightId}"]`);
if (element) {
this.showHighlightTooltip(highlight, element);
}
}
} catch (error) {
console.error('Failed to save note:', error);
alert('메모 저장에 실패했습니다');
}
},
// 하이라이트 삭제
async deleteHighlight(highlightId) {
if (!confirm('이 하이라이트를 삭제하시겠습니까? 연결된 메모도 함께 삭제됩니다.')) {
return;
}
try {
await api.deleteHighlight(highlightId);
// 로컬 데이터에서 제거
this.highlights = this.highlights.filter(h => h.id !== highlightId);
this.notes = this.notes.filter(n => n.highlight_id !== highlightId);
// UI 업데이트
this.hideTooltip();
this.renderHighlights();
} catch (error) {
console.error('Failed to delete highlight:', error);
alert('하이라이트 삭제에 실패했습니다');
}
},
// 언어 전환 함수
toggleLanguage() {
this.isKorean = !this.isKorean;
console.log(`🌐 언어 전환 시작 (isKorean: ${this.isKorean})`);
// 문서 내 언어별 요소 토글 (HTML, HEAD, BODY 태그 제외)
const primaryLangElements = document.querySelectorAll('[lang="ko"]:not(html):not(head):not(body), .korean, .kr, .primary-lang');
const secondaryLangElements = document.querySelectorAll('[lang="en"]:not(html):not(head):not(body), .english, .en, [lang="ja"]:not(html):not(head):not(body), .japanese, .jp, [lang="zh"]:not(html):not(head):not(body), .chinese, .cn, .secondary-lang');
// 디버깅: 찾은 요소 수 출력
console.log(`🔍 Primary 요소 수: ${primaryLangElements.length}`);
console.log(`🔍 Secondary 요소 수: ${secondaryLangElements.length}`);
// 언어별 요소가 있는 경우에만 토글 적용
if (primaryLangElements.length > 0 || secondaryLangElements.length > 0) {
console.log('✅ 언어별 요소 발견, 토글 적용 중...');
primaryLangElements.forEach((el, index) => {
const oldDisplay = el.style.display || getComputedStyle(el).display;
const newDisplay = this.isKorean ? 'block' : 'none';
console.log(`Primary 요소 ${index + 1}: ${el.tagName}#${el.id || 'no-id'}.${el.className || 'no-class'}`);
console.log(` - 이전 display: ${oldDisplay}`);
console.log(` - 새로운 display: ${newDisplay}`);
console.log(` - 요소 내용 미리보기: "${el.textContent?.substring(0, 50) || 'no-text'}..."`);
console.log(` - 요소 위치:`, el.getBoundingClientRect());
el.style.display = newDisplay;
console.log(` - 적용 후 display: ${el.style.display}`);
});
secondaryLangElements.forEach((el, index) => {
const oldDisplay = el.style.display || getComputedStyle(el).display;
const newDisplay = this.isKorean ? 'none' : 'block';
console.log(`Secondary 요소 ${index + 1}: ${el.tagName}#${el.id || 'no-id'}.${el.className || 'no-class'}`);
console.log(` - 이전 display: ${oldDisplay}`);
console.log(` - 새로운 display: ${newDisplay}`);
console.log(` - 요소 내용 미리보기: "${el.textContent?.substring(0, 50) || 'no-text'}..."`);
console.log(` - 요소 위치:`, el.getBoundingClientRect());
el.style.display = newDisplay;
console.log(` - 적용 후 display: ${el.style.display}`);
});
} else {
// 문서 내 콘텐츠에서 언어별 요소를 더 광범위하게 찾기
console.log('⚠️ 기본 언어별 요소를 찾을 수 없습니다. 문서 내 콘텐츠를 분석합니다.');
// 문서 콘텐츠 영역에서 언어별 요소 찾기
const contentArea = document.querySelector('#document-content, .document-content, main, .content, #content');
if (contentArea) {
console.log('📄 문서 콘텐츠 영역 발견:', contentArea.tagName, contentArea.id || contentArea.className);
// 콘텐츠 영역의 구조 분석
console.log('📋 콘텐츠 영역 내 모든 자식 요소들:');
const allChildren = contentArea.querySelectorAll('*');
const childrenInfo = Array.from(allChildren).slice(0, 10).map(el => {
return `${el.tagName}${el.id ? '#' + el.id : ''}${el.className ? '.' + el.className.split(' ').join('.') : ''} [lang="${el.lang || 'none'}"]`;
});
console.log(childrenInfo);
// 콘텐츠 영역 내에서 언어별 요소 재검색
const contentPrimary = contentArea.querySelectorAll('[lang="ko"], .korean, .kr, .primary-lang');
const contentSecondary = contentArea.querySelectorAll('[lang="en"], .english, .en, [lang="ja"], .japanese, .jp, [lang="zh"], .chinese, .cn, .secondary-lang');
console.log(`📄 콘텐츠 내 Primary 요소: ${contentPrimary.length}개`);
console.log(`📄 콘텐츠 내 Secondary 요소: ${contentSecondary.length}개`);
if (contentPrimary.length > 0 || contentSecondary.length > 0) {
// 콘텐츠 영역 내 요소들에 토글 적용
contentPrimary.forEach(el => {
el.style.display = this.isKorean ? 'block' : 'none';
});
contentSecondary.forEach(el => {
el.style.display = this.isKorean ? 'none' : 'block';
});
console.log('✅ 콘텐츠 영역 내 언어 토글 적용됨');
return;
} else {
// 실제 문서 내용에서 언어 패턴 찾기
console.log('🔍 문서 내용에서 언어 패턴을 찾습니다...');
// 문서의 실제 텍스트 내용 확인
const textContent = contentArea.textContent || '';
const hasKorean = /[가-힣]/.test(textContent);
const hasEnglish = /[a-zA-Z]/.test(textContent);
console.log(`📝 문서 언어 분석: 한국어=${hasKorean}, 영어=${hasEnglish}`);
console.log(`📝 문서 내용 미리보기: "${textContent.substring(0, 100)}..."`);
if (!hasKorean && !hasEnglish) {
console.log('❌ 텍스트 콘텐츠를 찾을 수 없습니다.');
}
}
}
// ID 기반 토글 시도
console.log('🔍 ID 기반 토글을 시도합니다.');
const koreanContent = document.getElementById('korean-content');
const englishContent = document.getElementById('english-content');
if (koreanContent && englishContent) {
koreanContent.style.display = this.isKorean ? 'block' : 'none';
englishContent.style.display = this.isKorean ? 'none' : 'block';
console.log('✅ ID 기반 토글 적용됨');
} else {
console.log('❌ 언어 전환 가능한 요소를 찾을 수 없습니다.');
console.log('📋 이 문서는 단일 언어 문서이거나 언어 구분이 없습니다.');
// 단일 언어 문서의 경우 아무것도 하지 않음 (흰색 페이지 방지)
console.log('🔄 언어 전환을 되돌립니다.');
this.isKorean = !this.isKorean; // 상태를 원래대로 되돌림
return;
}
}
console.log(`🌐 언어 전환 완료 (Primary: ${this.isKorean ? '표시' : '숨김'})`);
},
// 매칭된 PDF 다운로드
async downloadMatchedPDF() {
if (!this.document.matched_pdf_id) {
console.warn('매칭된 PDF가 없습니다');
return;
}
try {
console.log('📕 PDF 다운로드 시작:', this.document.matched_pdf_id);
// PDF 문서 정보 가져오기
const pdfDocument = await window.api.getDocument(this.document.matched_pdf_id);
if (!pdfDocument) {
throw new Error('PDF 문서를 찾을 수 없습니다');
}
// PDF 파일 다운로드 URL 생성
const downloadUrl = `/api/documents/${this.document.matched_pdf_id}/download`;
// 인증 헤더 추가를 위해 fetch 사용
const response = await fetch(downloadUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}
});
if (!response.ok) {
throw new Error('PDF 다운로드에 실패했습니다');
}
// Blob으로 변환하여 다운로드
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
// 다운로드 링크 생성 및 클릭
const link = document.createElement('a');
link.href = url;
link.download = pdfDocument.original_filename || `${pdfDocument.title}.pdf`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// URL 정리
window.URL.revokeObjectURL(url);
console.log('✅ PDF 다운로드 완료');
} catch (error) {
console.error('❌ PDF 다운로드 실패:', error);
alert('PDF 다운로드에 실패했습니다: ' + error.message);
}
},
// 원본 파일 다운로드 (연결된 PDF 파일)
async downloadOriginalFile() {
if (!this.document || !this.document.id) {
console.warn('문서 정보가 없습니다');
return;
}
// 연결된 PDF가 있는지 확인
if (!this.document.matched_pdf_id) {
alert('연결된 원본 PDF 파일이 없습니다.\n\n서적 편집 페이지에서 PDF 파일을 연결해주세요.');
return;
}
try {
console.log('📕 연결된 PDF 다운로드 시작:', this.document.matched_pdf_id);
// 연결된 PDF 문서 정보 가져오기
const pdfDocument = await window.api.getDocument(this.document.matched_pdf_id);
if (!pdfDocument) {
throw new Error('연결된 PDF 문서를 찾을 수 없습니다');
}
// PDF 파일 다운로드 URL 생성
const downloadUrl = `/api/documents/${this.document.matched_pdf_id}/download`;
// 인증 헤더 추가를 위해 fetch 사용
const response = await fetch(downloadUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}
});
if (!response.ok) {
throw new Error('연결된 PDF 다운로드에 실패했습니다');
}
// Blob으로 변환하여 다운로드
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
// 다운로드 링크 생성 및 클릭
const link = document.createElement('a');
link.href = url;
link.download = pdfDocument.original_filename || `${pdfDocument.title}.pdf`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// URL 정리
window.URL.revokeObjectURL(url);
console.log('✅ 연결된 PDF 다운로드 완료');
} catch (error) {
console.error('❌ 연결된 PDF 다운로드 실패:', error);
alert('연결된 PDF 다운로드에 실패했습니다: ' + error.message);
}
},
// 네비게이션 정보 로드
async loadNavigation() {
try {
this.navigation = await window.api.getDocumentNavigation(this.documentId);
console.log('📍 네비게이션 정보 로드됨:', this.navigation);
} catch (error) {
console.error('❌ 네비게이션 정보 로드 실패:', error);
// 네비게이션 정보는 필수가 아니므로 에러를 던지지 않음
}
},
// 다른 문서로 네비게이션
navigateToDocument(documentId) {
if (!documentId) return;
const currentUrl = new URL(window.location);
currentUrl.searchParams.set('id', documentId);
window.location.href = currentUrl.toString();
},
// 서적 목차로 이동
goToBookContents() {
if (!this.navigation?.book_info) return;
window.location.href = `/book-documents.html?bookId=${this.navigation.book_info.id}`;
},
// === 문서 링크 관련 함수들 ===
// 문서 링크 생성
async createDocumentLink() {
console.log('🔗 createDocumentLink 함수 실행');
// 이미 설정된 selectedText와 selectedRange 사용
let selectedText = this.selectedText;
let range = this.selectedRange;
// 설정되지 않은 경우 현재 선택 확인
if (!selectedText || !range) {
console.log('📝 기존 선택 없음, 현재 선택 확인');
const selection = window.getSelection();
if (!selection.rangeCount || selection.isCollapsed) {
alert('텍스트를 선택한 후 링크를 생성해주세요.');
return;
}
range = selection.getRangeAt(0);
selectedText = selection.toString().trim();
}
console.log('✅ 선택된 텍스트:', selectedText);
if (selectedText.length === 0) {
alert('텍스트를 선택한 후 링크를 생성해주세요.');
return;
}
// 선택된 텍스트의 위치 계산
const documentContent = document.getElementById('document-content');
const startOffset = this.getTextOffset(documentContent, range.startContainer, range.startOffset);
const endOffset = startOffset + selectedText.length;
console.log('📍 텍스트 위치:', { startOffset, endOffset });
// 폼 데이터 설정
this.linkForm = {
target_document_id: '',
selected_text: selectedText,
start_offset: startOffset,
end_offset: endOffset,
link_text: '',
description: '',
link_type: 'document', // 기본값: 문서 전체 링크
target_text: '',
target_start_offset: null,
target_end_offset: null,
book_scope: 'same', // 기본값: 같은 서적
target_book_id: ''
};
console.log('📋 링크 폼 데이터:', this.linkForm);
// 링크 가능한 문서 목록 로드
await this.loadLinkableDocuments();
// 모달 열기
console.log('🔗 링크 모달 열기');
console.log('🔗 showLinksModal 설정 전:', this.showLinksModal);
this.showLinksModal = true;
this.showLinkModal = true; // 기존 호환성
console.log('🔗 showLinksModal 설정 후:', this.showLinksModal);
this.editingLink = null;
},
// 링크 가능한 문서 목록 로드
async loadLinkableDocuments() {
try {
this.linkableDocuments = await api.getLinkableDocuments(this.documentId);
console.log('🔗 링크 가능한 문서들:', this.linkableDocuments);
// 서적 목록도 함께 로드
await this.loadAvailableBooks();
// 기본적으로 같은 서적 문서들 로드
await this.loadSameBookDocuments();
} catch (error) {
console.error('❌ 링크 가능한 문서 로드 실패:', error);
this.linkableDocuments = [];
}
},
// 문서 링크 저장 (고급 기능 포함)
async saveDocumentLink() {
if (!this.linkForm.target_document_id || !this.linkForm.selected_text) {
alert('필수 정보가 누락되었습니다.');
return;
}
// text_fragment 타입인데 target_text가 없으면 경고
if (this.linkForm.link_type === 'text_fragment' && !this.linkForm.target_text) {
const confirm = window.confirm('특정 부분 링크를 선택했지만 대상 텍스트가 선택되지 않았습니다. 전체 문서 링크로 생성하시겠습니까?');
if (confirm) {
this.linkForm.link_type = 'document';
} else {
return;
}
}
this.linkLoading = true;
try {
const linkData = {
target_document_id: this.linkForm.target_document_id,
selected_text: this.linkForm.selected_text,
start_offset: this.linkForm.start_offset,
end_offset: this.linkForm.end_offset,
link_text: this.linkForm.link_text || null,
description: this.linkForm.description || null,
link_type: this.linkForm.link_type,
target_text: this.linkForm.target_text || null,
target_start_offset: this.linkForm.target_start_offset || null,
target_end_offset: this.linkForm.target_end_offset || null
};
if (this.editingLink) {
await window.api.updateDocumentLink(this.editingLink.id, linkData);
console.log('✅ 링크 수정됨');
} else {
await window.api.createDocumentLink(this.documentId, linkData);
console.log('✅ 링크 생성됨');
}
// 데이터 새로고침
await this.loadDocumentData();
this.renderDocumentLinks();
this.closeLinkModal();
} catch (error) {
console.error('❌ 링크 저장 실패:', error);
alert('링크 저장에 실패했습니다: ' + error.message);
} finally {
this.linkLoading = false;
}
},
// 링크 모달 닫기 (고급 기능 포함)
closeLinkModal() {
this.showLinksModal = false;
this.showLinkModal = false;
this.editingLink = null;
this.linkForm = {
target_document_id: '',
selected_text: '',
start_offset: 0,
end_offset: 0,
link_text: '',
description: '',
link_type: 'document',
target_text: '',
target_start_offset: 0,
target_end_offset: 0,
book_scope: 'same',
target_book_id: ''
};
// 필터링된 문서 목록 초기화
this.filteredDocuments = [];
},
// 문서 링크 렌더링
renderDocumentLinks() {
const documentContent = document.getElementById('document-content');
if (!documentContent) return;
// 기존 링크 스타일 제거
const existingLinks = documentContent.querySelectorAll('.document-link');
existingLinks.forEach(link => {
const parent = link.parentNode;
parent.replaceChild(document.createTextNode(link.textContent), link);
parent.normalize();
});
// 새 링크 적용
this.documentLinks.forEach(link => {
this.highlightTextRange(
documentContent,
link.start_offset,
link.end_offset,
'document-link',
{
'data-link-id': link.id,
'data-target-document': link.target_document_id,
'data-target-title': link.target_document_title,
'title': `링크: ${link.target_document_title}${link.description ? '\n' + link.description : ''}`,
'style': 'color: #7C3AED; text-decoration: underline; cursor: pointer; background-color: rgba(124, 58, 237, 0.1);'
}
);
});
// 링크 클릭 이벤트 추가
const linkElements = documentContent.querySelectorAll('.document-link');
linkElements.forEach(linkEl => {
linkEl.addEventListener('click', (e) => {
e.preventDefault();
const linkId = linkEl.getAttribute('data-link-id');
const targetDocumentId = linkEl.getAttribute('data-target-document');
const targetTitle = linkEl.getAttribute('data-target-title');
// 해당 링크 정보 찾기
const linkInfo = this.documentLinks.find(link => link.id === linkId);
if (confirm(`"${targetTitle}" 문서로 이동하시겠습니까?`)) {
this.navigateToLinkedDocument(targetDocumentId, linkInfo);
}
});
});
},
// 백링크 하이라이트 렌더링 (이 문서를 참조하는 다른 문서의 링크들)
async renderBacklinkHighlights() {
if (!this.documentId) return;
try {
// 백링크 정보 가져오기
const backlinks = await api.getDocumentBacklinks(this.documentId);
console.log('🔗 백링크 정보:', backlinks);
const documentContent = document.getElementById('document-content');
if (!documentContent) return;
// 기존 백링크 하이라이트 제거
const existingBacklinks = documentContent.querySelectorAll('.backlink-highlight');
existingBacklinks.forEach(el => {
const parent = el.parentNode;
parent.replaceChild(document.createTextNode(el.textContent), el);
parent.normalize();
});
// 백링크 하이라이트 적용
backlinks.forEach(backlink => {
// 백링크의 target_text가 있으면 해당 텍스트를 하이라이트
if (backlink.target_text && backlink.target_start_offset !== undefined && backlink.target_end_offset !== undefined) {
this.highlightTextRange(
documentContent,
backlink.target_start_offset,
backlink.target_end_offset,
'backlink-highlight',
{
'data-backlink-id': backlink.id,
'data-source-document': backlink.source_document_id,
'data-source-title': backlink.source_document_title,
'title': `백링크: ${backlink.source_document_title}에서 참조\n"${backlink.selected_text}"`,
'style': 'background-color: rgba(168, 85, 247, 0.15) !important; border-left: 3px solid #A855F7; padding-left: 2px; cursor: pointer;'
}
);
}
});
// 백링크 클릭 이벤트 추가
const backlinkElements = documentContent.querySelectorAll('.backlink-highlight');
backlinkElements.forEach(backlinkEl => {
backlinkEl.addEventListener('click', (e) => {
e.preventDefault();
const sourceDocumentId = backlinkEl.getAttribute('data-source-document');
const sourceTitle = backlinkEl.getAttribute('data-source-title');
if (confirm(`"${sourceTitle}" 문서로 이동하시겠습니까?`)) {
window.location.href = `/viewer.html?id=${sourceDocumentId}`;
}
});
});
} catch (error) {
console.warn('백링크 하이라이트 렌더링 실패:', error);
}
},
// 링크된 문서로 이동 (특정 텍스트 위치 포함)
navigateToLinkedDocument(targetDocumentId, linkInfo) {
let targetUrl = `/viewer.html?id=${targetDocumentId}`;
// 특정 텍스트 위치가 있는 경우 URL에 추가
if (linkInfo && linkInfo.link_type === 'text_fragment' && linkInfo.target_text) {
const params = new URLSearchParams({
highlight_text: linkInfo.target_text,
start_offset: linkInfo.target_start_offset,
end_offset: linkInfo.target_end_offset
});
targetUrl += `&${params.toString()}`;
}
console.log('🔗 링크된 문서로 이동:', targetUrl);
window.location.href = targetUrl;
},
// 기존 navigateToDocument 함수 (백워드 호환성)
navigateToDocument(documentId) {
window.location.href = `/viewer.html?id=${documentId}`;
},
// URL 파라미터에서 특정 텍스트 하이라이트 확인
checkForTextHighlight() {
const urlParams = new URLSearchParams(window.location.search);
const highlightText = urlParams.get('highlight_text');
const startOffset = parseInt(urlParams.get('start_offset'));
const endOffset = parseInt(urlParams.get('end_offset'));
if (highlightText && !isNaN(startOffset) && !isNaN(endOffset)) {
console.log('🎯 링크된 텍스트로 이동:', { highlightText, startOffset, endOffset });
// 약간의 지연 후 하이라이트 및 스크롤 (DOM이 완전히 로드된 후)
setTimeout(() => {
this.highlightAndScrollToText(highlightText, startOffset, endOffset);
}, 500);
}
},
// 특정 텍스트를 하이라이트하고 스크롤
highlightAndScrollToText(targetText, startOffset, endOffset) {
console.log('🎯 highlightAndScrollToText 호출됨:', { targetText, startOffset, endOffset });
const documentContent = document.getElementById('document-content');
if (!documentContent) {
console.error('❌ document-content 요소를 찾을 수 없습니다');
return;
}
console.log('📄 문서 내용 길이:', documentContent.textContent.length);
try {
// 임시 하이라이트 적용
console.log('🎨 하이라이트 적용 시작...');
const highlightElement = this.highlightTextRange(
documentContent,
startOffset,
endOffset,
'linked-text-highlight',
{
'style': 'background-color: #FEF3C7 !important; border: 2px solid #F59E0B; border-radius: 4px; padding: 2px;'
}
);
console.log('🔍 하이라이트 요소 결과:', highlightElement);
if (highlightElement) {
console.log('📐 하이라이트 요소 위치:', highlightElement.getBoundingClientRect());
// 해당 요소로 스크롤
highlightElement.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
console.log('✅ 링크된 텍스트로 스크롤 완료');
// 5초 후 하이라이트 제거
setTimeout(() => {
const tempHighlight = document.querySelector('.linked-text-highlight');
if (tempHighlight) {
const parent = tempHighlight.parentNode;
parent.replaceChild(document.createTextNode(tempHighlight.textContent), tempHighlight);
parent.normalize();
console.log('🗑️ 임시 하이라이트 제거됨');
}
}, 5000);
} else {
console.warn('⚠️ 링크된 텍스트를 찾을 수 없습니다');
console.log('🔍 전체 텍스트 미리보기:', documentContent.textContent.substring(startOffset - 50, endOffset + 50));
}
} catch (error) {
console.error('❌ 텍스트 하이라이트 실패:', error);
}
},
// 텍스트 오프셋 계산 (하이라이트와 동일한 로직)
getTextOffset(container, node, offset) {
let textOffset = 0;
const walker = document.createTreeWalker(
container,
NodeFilter.SHOW_TEXT,
null,
false
);
let currentNode;
while (currentNode = walker.nextNode()) {
if (currentNode === node) {
return textOffset + offset;
}
textOffset += currentNode.textContent.length;
}
return textOffset;
},
// 텍스트 범위 하이라이트 (하이라이트와 동일한 로직, 클래스명만 다름)
highlightTextRange(container, startOffset, endOffset, className, attributes = {}) {
const walker = document.createTreeWalker(
container,
NodeFilter.SHOW_TEXT,
null,
false
);
let currentOffset = 0;
let startNode = null;
let startNodeOffset = 0;
let endNode = null;
let endNodeOffset = 0;
// 시작과 끝 노드 찾기
let node;
while (node = walker.nextNode()) {
const nodeLength = node.textContent.length;
if (!startNode && currentOffset + nodeLength > startOffset) {
startNode = node;
startNodeOffset = startOffset - currentOffset;
}
if (currentOffset + nodeLength >= endOffset) {
endNode = node;
endNodeOffset = endOffset - currentOffset;
break;
}
currentOffset += nodeLength;
}
if (!startNode || !endNode) return;
try {
const range = document.createRange();
range.setStart(startNode, startNodeOffset);
range.setEnd(endNode, endNodeOffset);
const span = document.createElement('span');
span.className = className;
// 속성 추가
Object.entries(attributes).forEach(([key, value]) => {
span.setAttribute(key, value);
});
range.surroundContents(span);
return span; // 생성된 요소 반환
} catch (error) {
console.warn('링크 렌더링 실패:', error);
return null;
}
},
// 백링크 관련 메서드들
async loadBacklinks() {
if (!this.documentId) return;
try {
console.log('🔗 백링크 로드 중...');
this.backlinks = await window.api.getDocumentBacklinks(this.documentId);
console.log(`✅ 백링크 ${this.backlinks.length}개 로드됨`);
} catch (error) {
console.error('백링크 로드 실패:', error);
this.backlinks = [];
}
},
navigateToBacklink(backlink) {
// 백링크의 출발 문서로 이동
const url = `/viewer.html?id=${backlink.source_document_id}&from=backlink&highlight=${backlink.start_offset}-${backlink.end_offset}`;
window.location.href = url;
},
// 고급 링크 기능 메서드들
onTargetDocumentChange() {
// 대상 문서가 변경되면 target_text 초기화
this.linkForm.target_text = '';
this.linkForm.target_start_offset = 0;
this.linkForm.target_end_offset = 0;
},
openTargetDocumentSelector() {
console.log('🎯 openTargetDocumentSelector 함수 호출됨!');
console.log('📋 현재 linkForm.target_document_id:', this.linkForm.target_document_id);
if (!this.linkForm.target_document_id) {
alert('먼저 대상 문서를 선택해주세요.');
return;
}
// 새 창에서 대상 문서 열기 (텍스트 선택 모드 전용 페이지)
const targetUrl = `/text-selector.html?id=${this.linkForm.target_document_id}`;
console.log('🚀 텍스트 선택 창 열기:', targetUrl);
const popup = window.open(targetUrl, 'targetDocumentSelector', 'width=1200,height=800,scrollbars=yes,resizable=yes');
if (!popup) {
console.error('❌ 팝업 창이 차단되었습니다!');
alert('팝업 창이 차단되었습니다. 브라우저 설정에서 팝업을 허용해주세요.');
} else {
console.log('✅ 팝업 창이 성공적으로 열렸습니다');
}
// 팝업에서 텍스트 선택 완료 시 메시지 수신
window.addEventListener('message', (event) => {
if (event.data.type === 'TEXT_SELECTED') {
this.linkForm.target_text = event.data.selectedText;
this.linkForm.target_start_offset = event.data.startOffset;
this.linkForm.target_end_offset = event.data.endOffset;
console.log('🎯 대상 텍스트 선택됨:', event.data);
popup.close();
}
}, { once: true });
},
// 텍스트 선택 모드 초기화
async initTextSelectorMode() {
console.log('🎯 텍스트 선택 모드로 초기화 중...');
// Alpine.js 완전 차단
window.Alpine = {
start: () => console.log('Alpine.js 초기화 차단됨'),
data: () => ({}),
directive: () => {},
magic: () => {},
store: () => ({}),
version: '3.0.0'
};
// 기존 Alpine 인스턴스 제거
if (window.Alpine && window.Alpine.stop) {
window.Alpine.stop();
}
// 인증 확인
if (!api.token) {
window.location.href = '/';
return;
}
try {
// 문서만 로드 (다른 데이터는 불필요)
await this.loadDocument();
// UI 설정
console.log('🔧 텍스트 선택 모드 UI 설정 시작');
this.setupTextSelectorUI();
console.log('✅ 텍스트 선택 모드 UI 설정 완료');
} catch (error) {
console.error('텍스트 선택 모드 초기화 실패:', error);
this.error = '문서를 불러올 수 없습니다: ' + error.message;
} finally {
this.loading = false;
}
},
// 텍스트 선택 모드 UI 설정
setupTextSelectorUI() {
console.log('🔧 setupTextSelectorUI 함수 실행됨');
// 이미 설정되었는지 확인
if (this.textSelectorUISetup) {
console.log('⚠️ 텍스트 선택 모드 UI가 이미 설정됨 - 중복 실행 방지');
return;
}
// 헤더를 텍스트 선택 모드용으로 변경
const header = document.querySelector('header');
console.log('📋 헤더 요소 찾기:', header);
if (header) {
console.log('🎨 헤더 HTML 교체 중...');
// 기존 Alpine 속성 제거
header.removeAttribute('x-data');
header.removeAttribute('x-init');
header.innerHTML = `
텍스트 선택 모드
연결하고 싶은 텍스트를 선택하세요
`;
// 헤더가 다시 변경되지 않도록 보호
header.setAttribute('data-text-selector-mode', 'true');
console.log('🔒 헤더 보호 설정 완료');
// 실제 헤더 내용 확인
console.log('📄 헤더 HTML 확인:', header.innerHTML.substring(0, 200) + '...');
// 언어전환 버튼 확인
const langBtn = header.querySelector('#language-toggle-selector');
console.log('🌐 언어전환 버튼 찾기:', langBtn);
// 취소 버튼 확인
const closeBtn = header.querySelector('button[onclick*="window.close"]');
console.log('❌ 취소 버튼 찾기:', closeBtn);
// 헤더 변경 감지
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'childList' || mutation.type === 'attributes') {
console.log('⚠️ 헤더가 변경되었습니다!', mutation);
console.log('🔍 변경 후 헤더 내용:', header.innerHTML.substring(0, 100) + '...');
}
});
});
observer.observe(header, {
childList: true,
subtree: true,
attributes: true,
attributeOldValue: true
});
}
// 사이드 패널 숨기기
const aside = document.querySelector('aside');
if (aside) {
aside.style.display = 'none';
}
// 메인 컨텐츠 영역 조정
const main = document.querySelector('main');
if (main) {
main.style.marginRight = '0';
main.classList.add('text-selector-mode');
}
// 문서 콘텐츠에 텍스트 선택 이벤트 추가
const documentContent = document.getElementById('document-content');
if (documentContent) {
documentContent.addEventListener('mouseup', this.handleTextSelectionForLinking.bind(this));
// 선택 가능한 영역임을 시각적으로 표시
documentContent.style.cursor = 'crosshair';
documentContent.style.userSelect = 'text';
// 안내 메시지 추가
const guideDiv = document.createElement('div');
guideDiv.className = 'bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6';
guideDiv.innerHTML = `
텍스트 선택 방법
마우스로 연결하고 싶은 텍스트를 드래그하여 선택하세요.
선택이 완료되면 자동으로 부모 창으로 전달됩니다.
`;
documentContent.parentNode.insertBefore(guideDiv, documentContent);
}
// Alpine.js 컴포넌트 비활성화 (텍스트 선택 모드에서는 불필요)
const alpineElements = document.querySelectorAll('[x-data]');
alpineElements.forEach(el => {
el.removeAttribute('x-data');
});
// 설정 완료 플래그
this.textSelectorUISetup = true;
console.log('✅ 텍스트 선택 모드 UI 설정 완료');
},
// 텍스트 선택 모드에서의 텍스트 선택 처리
handleTextSelectionForLinking() {
const selection = window.getSelection();
if (!selection.rangeCount || selection.isCollapsed) return;
const range = selection.getRangeAt(0);
const selectedText = selection.toString().trim();
if (selectedText.length < 3) {
alert('최소 3글자 이상 선택해주세요.');
return;
}
if (selectedText.length > 500) {
alert('선택된 텍스트가 너무 깁니다. 500자 이하로 선택해주세요.');
return;
}
// 텍스트 오프셋 계산
const documentContent = document.getElementById('document-content');
const { startOffset, endOffset } = this.getTextOffset(documentContent, range);
console.log('🎯 텍스트 선택됨:', {
selectedText,
startOffset,
endOffset
});
// 선택 확인 UI 표시
this.showTextSelectionConfirm(selectedText, startOffset, endOffset);
},
// 텍스트 선택 확인 UI
showTextSelectionConfirm(selectedText, startOffset, endOffset) {
// 기존 확인 UI 제거
const existingConfirm = document.querySelector('.text-selection-confirm');
if (existingConfirm) {
existingConfirm.remove();
}
// 확인 UI 생성
const confirmDiv = document.createElement('div');
confirmDiv.className = 'text-selection-confirm fixed bottom-6 left-1/2 transform -translate-x-1/2 bg-white rounded-lg shadow-2xl border p-6 max-w-md z-50';
// 텍스트 미리보기 (안전하게 처리)
const previewText = selectedText.length > 100 ? selectedText.substring(0, 100) + '...' : selectedText;
confirmDiv.innerHTML = `
텍스트가 선택되었습니다
`;
// 텍스트 안전하게 설정
const previewElement = confirmDiv.querySelector('#selected-text-preview');
previewElement.textContent = `"${previewText}"`;
// 이벤트 리스너 추가
const reselectBtn = confirmDiv.querySelector('#reselect-btn');
const confirmBtn = confirmDiv.querySelector('#confirm-selection-btn');
reselectBtn.addEventListener('click', () => {
confirmDiv.remove();
});
confirmBtn.addEventListener('click', () => {
this.confirmTextSelection(selectedText, startOffset, endOffset);
});
document.body.appendChild(confirmDiv);
// 10초 후 자동 제거 (사용자가 선택하지 않은 경우)
setTimeout(() => {
if (document.contains(confirmDiv)) {
confirmDiv.remove();
}
}, 10000);
},
// 텍스트 선택 확정
confirmTextSelection(selectedText, startOffset, endOffset) {
// 부모 창에 선택된 텍스트 정보 전달
if (window.opener) {
window.opener.postMessage({
type: 'TEXT_SELECTED',
selectedText: selectedText,
startOffset: startOffset,
endOffset: endOffset
}, '*');
console.log('✅ 부모 창에 텍스트 선택 정보 전달됨');
// 성공 메시지 표시 후 창 닫기
const confirmDiv = document.querySelector('.text-selection-confirm');
if (confirmDiv) {
confirmDiv.innerHTML = `
선택 완료!
창이 자동으로 닫힙니다...
`;
setTimeout(() => {
window.close();
}, 1500);
}
} else {
alert('부모 창을 찾을 수 없습니다.');
}
},
// 기능 메뉴 토글
toggleFeatureMenu(feature) {
if (this.activeFeatureMenu === feature) {
this.activeFeatureMenu = null;
} else {
this.activeFeatureMenu = feature;
}
},
// 링크 모드 활성화
activateLinkMode() {
console.log('🔗 링크 모드 활성화 - activateLinkMode 함수 실행됨');
// 이미 선택된 텍스트가 있는지 확인
const selection = window.getSelection();
console.log('📝 현재 선택 상태:', {
rangeCount: selection.rangeCount,
isCollapsed: selection.isCollapsed,
selectedText: selection.toString()
});
if (selection.rangeCount > 0 && !selection.isCollapsed) {
const selectedText = selection.toString().trim();
if (selectedText.length > 0) {
console.log('✅ 선택된 텍스트 발견:', selectedText);
this.selectedText = selectedText;
this.selectedRange = selection.getRangeAt(0);
console.log('🔗 createDocumentLink 함수 호출 예정');
this.createDocumentLink();
return;
}
}
// 선택된 텍스트가 없으면 선택 모드 활성화
console.log('📝 텍스트 선택 모드 활성화');
this.activeMode = 'link';
this.showSelectionMessage('텍스트를 선택하세요.');
// 기존 리스너 제거 후 새로 추가
this.removeTextSelectionListener();
this.textSelectionHandler = this.handleTextSelection.bind(this);
document.addEventListener('mouseup', this.textSelectionHandler);
},
// 메모 모드 활성화
activateNoteMode() {
console.log('📝 메모 모드 활성화');
// 이미 선택된 텍스트가 있는지 확인
const selection = window.getSelection();
if (selection.rangeCount > 0 && !selection.isCollapsed) {
const selectedText = selection.toString().trim();
if (selectedText.length > 0) {
console.log('✅ 선택된 텍스트 발견:', selectedText);
this.selectedText = selectedText;
this.selectedRange = selection.getRangeAt(0);
this.createNoteFromSelection();
return;
}
}
// 선택된 텍스트가 없으면 선택 모드 활성화
console.log('📝 텍스트 선택 모드 활성화');
this.activeMode = 'memo';
this.showSelectionMessage('텍스트를 선택하세요.');
// 기존 리스너 제거 후 새로 추가
this.removeTextSelectionListener();
this.textSelectionHandler = this.handleTextSelection.bind(this);
document.addEventListener('mouseup', this.textSelectionHandler);
},
// 책갈피 모드 활성화
activateBookmarkMode() {
console.log('🔖 책갈피 모드 활성화');
// 이미 선택된 텍스트가 있는지 확인
const selection = window.getSelection();
if (selection.rangeCount > 0 && !selection.isCollapsed) {
const selectedText = selection.toString().trim();
if (selectedText.length > 0) {
console.log('✅ 선택된 텍스트 발견:', selectedText);
this.selectedText = selectedText;
this.selectedRange = selection.getRangeAt(0);
this.createBookmarkFromSelection();
return;
}
}
// 선택된 텍스트가 없으면 선택 모드 활성화
console.log('📝 텍스트 선택 모드 활성화');
this.activeMode = 'bookmark';
this.showSelectionMessage('텍스트를 선택하세요.');
// 기존 리스너 제거 후 새로 추가
this.removeTextSelectionListener();
this.textSelectionHandler = this.handleTextSelection.bind(this);
document.addEventListener('mouseup', this.textSelectionHandler);
},
// 텍스트 선택 리스너 제거
removeTextSelectionListener() {
if (this.textSelectionHandler) {
document.removeEventListener('mouseup', this.textSelectionHandler);
this.textSelectionHandler = null;
}
},
// 텍스트 선택 처리
handleTextSelection(event) {
console.log('🎯 텍스트 선택 이벤트 발생');
const selection = window.getSelection();
if (selection.rangeCount > 0 && !selection.isCollapsed) {
const range = selection.getRangeAt(0);
const selectedText = selection.toString().trim();
console.log('📝 선택된 텍스트:', selectedText);
if (selectedText.length > 0) {
this.selectedText = selectedText;
this.selectedRange = range;
// 선택 모드에 따라 다른 동작
console.log('🎯 현재 모드:', this.activeMode);
if (this.activeMode === 'link') {
console.log('🔗 링크 생성 실행');
this.createDocumentLink();
} else if (this.activeMode === 'memo') {
console.log('📝 메모 생성 실행');
this.createNoteFromSelection();
} else if (this.activeMode === 'bookmark') {
console.log('🔖 책갈피 생성 실행');
this.createBookmarkFromSelection();
}
// 모드 해제
this.activeMode = null;
this.hideSelectionMessage();
this.removeTextSelectionListener();
}
}
},
// 선택 메시지 표시
showSelectionMessage(message) {
// 기존 메시지 제거
const existingMessage = document.querySelector('.selection-message');
if (existingMessage) {
existingMessage.remove();
}
// 새 메시지 생성
const messageDiv = document.createElement('div');
messageDiv.className = 'selection-message fixed top-20 left-1/2 transform -translate-x-1/2 bg-blue-500 text-white px-4 py-2 rounded-lg shadow-lg z-50';
messageDiv.textContent = message;
document.body.appendChild(messageDiv);
},
// 선택 메시지 숨기기
hideSelectionMessage() {
const existingMessage = document.querySelector('.selection-message');
if (existingMessage) {
existingMessage.remove();
}
},
// 링크 생성 UI 표시
showLinkCreationUI() {
this.createDocumentLink();
},
// 선택된 텍스트로 메모 생성
async createNoteFromSelection() {
if (!this.selectedText || !this.selectedRange) return;
try {
// 하이라이트 생성
const highlightData = await this.createHighlight(this.selectedText, this.selectedRange, '#FFFF00');
// 메모 내용 입력받기
const content = prompt('메모 내용을 입력하세요:', '');
if (content === null) {
// 취소한 경우 하이라이트 제거
const highlightElement = document.querySelector(`[data-highlight-id="${highlightData.id}"]`);
if (highlightElement) {
const parent = highlightElement.parentNode;
parent.replaceChild(document.createTextNode(highlightElement.textContent), highlightElement);
parent.normalize();
}
return;
}
// 메모 생성
const noteData = {
highlight_id: highlightData.id,
content: content
};
const note = await api.createNote(this.documentId, noteData);
// 데이터 새로고침
await this.loadNotes();
alert('메모가 생성되었습니다.');
} catch (error) {
console.error('메모 생성 실패:', error);
alert('메모 생성에 실패했습니다.');
}
},
// 선택된 텍스트로 책갈피 생성
async createBookmarkFromSelection() {
if (!this.selectedText || !this.selectedRange) return;
try {
// 하이라이트 생성 (책갈피는 주황색)
const highlightData = await this.createHighlight(this.selectedText, this.selectedRange, '#FFA500');
// 책갈피 생성
const bookmarkData = {
highlight_id: highlightData.id,
title: this.selectedText.substring(0, 50) + (this.selectedText.length > 50 ? '...' : '')
};
const bookmark = await api.createBookmark(this.documentId, bookmarkData);
// 데이터 새로고침
await this.loadBookmarks();
alert('책갈피가 생성되었습니다.');
} catch (error) {
console.error('책갈피 생성 실패:', error);
alert('책갈피 생성에 실패했습니다.');
}
},
// 대상 선택 초기화
resetTargetSelection() {
this.linkForm.target_book_id = '';
this.linkForm.target_document_id = '';
this.linkForm.target_text = '';
this.linkForm.target_start_offset = null;
this.linkForm.target_end_offset = null;
this.filteredDocuments = [];
// 같은 서적인 경우 현재 서적의 문서들 로드
if (this.linkForm.book_scope === 'same') {
this.loadSameBookDocuments();
}
},
// 같은 서적의 문서들 로드
async loadSameBookDocuments() {
try {
if (this.navigation?.book_info?.id) {
// 현재 서적의 문서들만 가져오기
const allDocuments = await api.getLinkableDocuments(this.documentId);
this.filteredDocuments = allDocuments.filter(doc =>
doc.book_id === this.navigation.book_info.id && doc.id !== this.documentId
);
console.log('📚 같은 서적 문서들:', this.filteredDocuments);
} else {
// 서적 정보가 없으면 모든 문서
this.filteredDocuments = await api.getLinkableDocuments(this.documentId);
}
} catch (error) {
console.error('같은 서적 문서 로드 실패:', error);
this.filteredDocuments = [];
}
},
// 서적별 문서 로드
async loadDocumentsFromBook() {
try {
if (this.linkForm.target_book_id) {
// 선택된 서적의 문서들만 가져오기
const allDocuments = await api.getLinkableDocuments(this.documentId);
this.filteredDocuments = allDocuments.filter(doc =>
doc.book_id === this.linkForm.target_book_id
);
console.log('📚 선택된 서적 문서들:', this.filteredDocuments);
} else {
this.filteredDocuments = [];
}
// 문서 선택 초기화
this.linkForm.target_document_id = '';
} catch (error) {
console.error('서적별 문서 로드 실패:', error);
this.filteredDocuments = [];
}
},
// 사용 가능한 서적 목록 로드
async loadAvailableBooks() {
try {
console.log('📚 서적 목록 로딩 시작...');
// 문서 목록에서 서적 정보 추출
const allDocuments = await api.getLinkableDocuments(this.documentId);
console.log('📄 모든 문서들:', allDocuments);
// 서적별로 그룹화
const bookMap = new Map();
allDocuments.forEach(doc => {
if (doc.book_id && doc.book_title) {
bookMap.set(doc.book_id, {
id: doc.book_id,
title: doc.book_title
});
}
});
// 현재 서적 제외
const currentBookId = this.navigation?.book_info?.id;
if (currentBookId) {
bookMap.delete(currentBookId);
}
this.availableBooks = Array.from(bookMap.values());
console.log('📚 사용 가능한 서적들:', this.availableBooks);
console.log('🔍 현재 서적 ID:', currentBookId);
} catch (error) {
console.error('서적 목록 로드 실패:', error);
this.availableBooks = [];
}
},
// 선택된 서적 제목 가져오기
getSelectedBookTitle() {
const selectedBook = this.availableBooks.find(book => book.id === this.linkForm.target_book_id);
return selectedBook ? selectedBook.title : '';
}
});