@unana_dev/doxen 0.2.6 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -566,3 +566,25 @@ npm pack
566
566
  **구조 한 줄 요약:** `bin/docs.js` → 설정 로더 → Markdown·섹션·첨부 처리 → 정적 빌드 또는 로컬 서버. 화면과 브라우저 검색 코드는 `client/`에 있습니다.
567
567
 
568
568
  궁금한 점이나 버그는 저장소 이슈로 남겨 주세요. 즐거운 문서 작성 되세요! 📚
569
+
570
+ ### 문서 댓글 설정
571
+
572
+ 댓글은 Cloudflare Access로 보호된 배포에서 선택적으로 사용할 수 있습니다. Cloudflare D1 데이터베이스를 만들고 패키지의 `src/comments.sql`을 해당 데이터베이스에 적용하세요. 예를 들어 프로젝트에 설치된 패키지를 기준으로 다음 명령을 실행합니다.
573
+
574
+ ```bash
575
+ npx wrangler d1 execute 데이터베이스이름 --remote --file=node_modules/@unana_dev/doxen/src/comments.sql
576
+ ```
577
+
578
+ 직접 `docs.config.ts`에 배포 설정을 작성했다면 `deploy.comments: { databaseName: "데이터베이스이름", databaseId: "D1 데이터베이스 UUID" }`를 추가합니다. 자동 배포 설정을 사용한다면 `.doxen-deploy.json`의 최상위에 동일한 `comments` 객체를 추가한 뒤 다시 배포합니다. 배포 시 `COMMENTS_DB` D1 바인딩이 설정됩니다. 데이터베이스 생성과 SQL 적용은 별도로 필요하며, 로컬 미리보기와 정적 빌드에는 댓글 저장 기능이 없습니다.
579
+
580
+ 본문의 문구를 선택한 후 해당 문단 오른쪽의 버튼을 누르거나, 문구 선택 없이 버튼을 눌러 댓글을 작성합니다. 작성자는 Access의 이메일로 표시됩니다. 문단 내용이나 같은 내용의 문단 순서가 바뀌면 기존 댓글은 본문 아래의 위치를 찾을 수 없는 댓글 목록에서 확인할 수 있습니다.
581
+
582
+ #### 매일 GitHub 이슈로 댓글 모으기
583
+
584
+ 설치된 패키지의 `src/templates/comment-report.yml`을 문서 저장소의 `.github/workflows/comment-report.yml`로 복사합니다. 저장소 Actions secrets에 `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_D1_DATABASE_ID`, D1 읽기 권한의 `CLOUDFLARE_D1_READ_TOKEN`을 등록하고, 기본 브랜치에 워크플로를 반영하세요. `npm ci`를 사용하는 예제이므로 프로젝트에 npm 잠금 파일이 필요합니다.
585
+
586
+ 저장소의 Actions variables에 배포된 문서 사이트 주소를 `DOXEN_SITE_URL`로 등록하세요. 설정 파일이 저장소 루트의 기본 이름이 아니라면 `DOXEN_CONFIG`에 저장소 기준 경로도 등록합니다. 보고서의 각 댓글에는 보고서 실행 시점 커밋의 GitHub 원본 파일 링크와 배포 사이트의 해당 댓글 링크가 표시됩니다. 현재 설정에서 문서를 찾지 못하면 링크 대신 안내 문구가 표시됩니다.
587
+
588
+ 매일 한국 시간 오전 8시에 전날 00:00~24:00의 댓글을 하나의 이슈로 작성합니다. 댓글은 문서별로 묶이며, 같은 문서 안에서는 작성 순서대로 표시됩니다. 댓글이 없으면 이슈를 만들지 않으며, 같은 날짜의 보고서 이슈가 이미 있으면 중복 생성하지 않습니다. Actions 화면의 수동 실행에서 날짜를 입력해 누락된 날을 다시 집계할 수 있습니다. 이슈 본문 양식은 패키지의 `src/comment-report.js`에서 확인할 수 있으며 필요에 맞게 복사해 수정하세요. 댓글 내용과 작성자 이메일이 이슈 저장소의 열람자에게 공개되므로 접근 권한을 확인하세요. GitHub 예약 실행은 지연되거나 누락될 수 있습니다.
589
+
590
+ 문서별 최종 수정자와 수정일을 표시하려면 빌드 환경에 전체 Git 이력이 필요합니다. GitHub Actions에서는 `actions/checkout`에 `fetch-depth: 0`을 설정하세요. 얕은 복제의 경계 커밋은 파일의 실제 마지막 수정인지 확인할 수 없어 해당 정보가 표시되지 않습니다.
package/client/app.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { searchDocuments, matchRanges, matchesRow } from "./search.js";
2
+ import { attachComments } from "./comments.js";
2
3
 
3
4
  const $ = (selector) => document.querySelector(selector);
4
5
  const el = (tag, text, className) => {
@@ -558,10 +559,19 @@ function spreadsheetViewer(doc, rawSheets) {
558
559
  return viewer;
559
560
  }
560
561
 
562
+ function renderModified(doc) {
563
+ if (!doc.modified?.date) return;
564
+ const date = new Date(doc.modified.date);
565
+ if (Number.isNaN(date.getTime())) return;
566
+ const label = `최종 수정 ${date.toLocaleDateString("ko-KR")}${doc.modified.author ? ` · ${doc.modified.author}` : ""}`;
567
+ $("#article h1").after(el("p", label, "document-modified"));
568
+ }
569
+
561
570
  async function renderSpreadsheet(doc) {
562
571
  const article = $("#article");
563
572
  const content = el("p", "엑셀 파일을 불러오는 중입니다.", "sheet-message");
564
573
  article.replaceChildren(el("h1", doc.title), content);
574
+ renderModified(doc);
565
575
  try {
566
576
  const response = await fetch(doc.spreadsheet.data);
567
577
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
@@ -581,9 +591,17 @@ async function renderSpreadsheet(doc) {
581
591
  }
582
592
 
583
593
  function render() {
584
- let id, anchor;
594
+ document.body.classList.remove('has-comments', 'comment-card-open');
595
+ $('#article').commentLaneObserver?.disconnect();
596
+ $('#article').commentDismissController?.abort();
597
+ $('.compact-toc').hidden = true;
598
+ $('#compact-toc-links').hidden = true;
599
+ $('#compact-toc-toggle').setAttribute('aria-expanded', 'false');
600
+ let id, anchor, commentId;
585
601
  try {
586
- [id, anchor] = location.hash.slice(2).split("/").map(decodeURIComponent);
602
+ [id, anchor, commentId] = location.hash.slice(2).split("/").map(decodeURIComponent);
603
+ if (anchor !== 'comment') commentId = undefined;
604
+ if (commentId) anchor = undefined;
587
605
  } catch {
588
606
  id = "invalid";
589
607
  }
@@ -600,6 +618,7 @@ function render() {
600
618
  const isFolder = folderPath && site.documents.some(
601
619
  (doc) => doc.tab === activeTab && doc.path.startsWith(folderPath),
602
620
  );
621
+ $("#article").dataset.commentDocument = "";
603
622
  document.body.classList.toggle("is-spreadsheet", Boolean(current?.spreadsheet));
604
623
  document.body.classList.remove("sheet-fullscreen");
605
624
  renderNavigation(isFolder ? folderPath : null);
@@ -639,8 +658,23 @@ function render() {
639
658
  window.scrollTo(0, 0);
640
659
  return;
641
660
  }
661
+ $("#article").dataset.commentDocument = current.id;
642
662
  $("#article").innerHTML = current.html;
643
663
  if (!$("#article h1")) $("#article").prepend(el("h1", current.title));
664
+ renderModified(current);
665
+ if (current.markdown) {
666
+ const heading = $("#article h1");
667
+ const title = el("div", undefined, "document-title");
668
+ heading.before(title);
669
+ title.append(heading);
670
+ const download = el("a", undefined, "document-download");
671
+ download.href = current.markdown;
672
+ download.download = current.path.split("/").at(-1);
673
+ download.setAttribute("aria-label", "Markdown 파일 다운로드");
674
+ download.title = "Markdown 파일 다운로드";
675
+ download.innerHTML = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12m-4-4 4 4 4-4M4 17v3h16v-3"/></svg>';
676
+ title.append(download);
677
+ }
644
678
  for (const heading of $("#article").querySelectorAll("h2, h3, h4, h5, h6")) {
645
679
  if (/^version\s*:\s*\S+/i.test(heading.textContent.trim()))
646
680
  heading.classList.add("document-version");
@@ -657,6 +691,9 @@ function render() {
657
691
  link.style.paddingLeft = `${Math.max(0, heading.level - 2) * 12}px`;
658
692
  $("#toc").append(link);
659
693
  }
694
+ $('#compact-toc-links').replaceChildren(...[...$('#toc').children].map((link) => link.cloneNode(true)));
695
+ requestAnimationFrame(updateTocFades);
696
+ $('.compact-toc').hidden = !$('#toc').children.length;
660
697
  const siblings = site.documents.filter((doc) => doc.tab === activeTab);
661
698
  const index = siblings.indexOf(current);
662
699
  for (const [label, doc] of [
@@ -673,6 +710,7 @@ function render() {
673
710
  $("#pagination").append(link);
674
711
  }
675
712
  attachTableSearches();
713
+ attachComments($("#article"), current.id, commentId);
676
714
  const diagrams = [...$("#article").querySelectorAll("pre > code")].filter(
677
715
  (code) => code.classList.contains("language-mermaid") ||
678
716
  (!code.className && /^\s*sequenceDiagram\b/.test(code.textContent)),
@@ -694,16 +732,50 @@ function render() {
694
732
  } else window.scrollTo(0, 0);
695
733
  }
696
734
 
735
+ let searchTab = null;
736
+
697
737
  function renderResults() {
698
738
  const query = $("#global-search").value;
699
- const results = searchDocuments(site.documents, query);
739
+ const results = searchDocuments(searchTab ? site.documents.filter((doc) => doc.tab === searchTab.slug) : site.documents, query);
740
+ $("#clear-search").hidden = !query;
741
+ const suggestions = $("#search-suggestions");
742
+ suggestions.replaceChildren();
743
+ suggestions.hidden = true;
744
+ if (!searchTab && /^#[^ ]*$/.test(query)) {
745
+ const tabs = site.tabs.filter((tab) => tab.title.toLocaleLowerCase().includes(query.slice(1).toLocaleLowerCase()));
746
+ if (tabs.length) {
747
+ suggestions.hidden = false;
748
+ suggestions.append(el("p", "탭으로 범위 지정"));
749
+ for (const tab of tabs) {
750
+ const button = el("button", undefined, "search-suggestion");
751
+ button.type = "button";
752
+ button.append(el("span", `# ${tab.title}`), el("small", `문서 ${site.documents.filter((doc) => doc.tab === tab.slug).length}개`));
753
+ button.onclick = () => selectSearchTab(tab);
754
+ suggestions.append(button);
755
+ }
756
+ }
757
+ }
758
+ $("#search-count").hidden = !suggestions.hidden;
700
759
  $("#search-count").textContent = query.trim()
701
760
  ? results.length
702
- ? `${results.length}개 결과${results.length === 80 ? " (최대 80개 표시)" : ""}`
761
+ ? `${searchTab ? `${searchTab.title} 탭에서 ` : ""}${results.length}개 결과${results.length === 80 ? " (최대 80개 표시)" : ""}`
703
762
  : "일치하는 내용이 없습니다."
704
- : "한국어와 영문으로 모든 탭의 내용을 검색합니다.";
763
+ : searchTab ? `${searchTab.title} 탭에서 검색합니다.` : "한국어와 영문으로 모든 탭의 내용을 검색합니다.";
705
764
  $("#results").replaceChildren();
706
- for (const { doc, section } of results) {
765
+ if (query.trim() && !results.length && suggestions.hidden) {
766
+ const empty = el("div", undefined, "search-empty");
767
+ empty.append(el("strong", searchTab ? `‘${searchTab.title}’에 ‘${query}’ 결과가 없어요` : `‘${query}’ 검색 결과가 없어요`));
768
+ if (searchTab) {
769
+ const otherCount = searchDocuments(site.documents, query).length;
770
+ empty.append(el("p", `전체 탭에서 ${otherCount}개를 찾았습니다.`));
771
+ const button = el("button", "모든 탭에서 검색");
772
+ button.type = "button";
773
+ button.onclick = clearSearchTab;
774
+ empty.append(button);
775
+ }
776
+ $("#results").append(empty);
777
+ }
778
+ for (const { doc, section } of suggestions.hidden ? results : []) {
707
779
  const link = el("a", undefined, "result");
708
780
  link.href = route(doc.id, section.anchor);
709
781
  const title = el("strong", section.title);
@@ -732,20 +804,78 @@ function renderResults() {
732
804
  }
733
805
  }
734
806
 
807
+ function selectSearchTab(tab) {
808
+ searchTab = tab;
809
+ $("#global-search").value = "";
810
+ $("#search-tag-label").textContent = `# ${tab.title}`;
811
+ $("#search-tag").hidden = false;
812
+ renderResults();
813
+ $("#global-search").focus();
814
+ }
815
+ function clearSearchTab() {
816
+ searchTab = null;
817
+ $("#search-tag").hidden = true;
818
+ renderResults();
819
+ $("#global-search").focus();
820
+ }
821
+ function positionSearch() {
822
+ const rect = $("#content").getBoundingClientRect();
823
+ dialog.style.left = `${rect.left}px`;
824
+ dialog.style.width = `${rect.width}px`;
825
+ }
735
826
  const openSearch = () => {
736
827
  if (!site) return;
828
+ positionSearch();
737
829
  dialog.showModal();
738
830
  $("#global-search").focus();
739
831
  renderResults();
740
832
  };
833
+ const closeCompactToc = () => {
834
+ $('#compact-toc-links').hidden = true;
835
+ $('#compact-toc-toggle').setAttribute('aria-expanded', 'false');
836
+ };
837
+ $('#compact-toc-toggle').onclick = () => {
838
+ const links = $('#compact-toc-links');
839
+ links.hidden = !links.hidden;
840
+ $('#compact-toc-toggle').setAttribute('aria-expanded', String(!links.hidden));
841
+ };
842
+ $('#compact-toc-links').onclick = (event) => {
843
+ if (event.target.closest('a')) closeCompactToc();
844
+ };
845
+ document.addEventListener('click', (event) => {
846
+ if (!event.target.closest('.compact-toc')) closeCompactToc();
847
+ });
848
+ document.addEventListener('keydown', (event) => {
849
+ if (event.key === 'Escape' && !$('#compact-toc-links').hidden) {
850
+ closeCompactToc();
851
+ $('#compact-toc-toggle').focus();
852
+ }
853
+ });
741
854
  $("#open-search").onclick = openSearch;
742
855
  $("#close-search").onclick = () => dialog.close();
743
- $("#global-search").oninput = renderResults;
856
+ $("#clear-search-tag").onclick = clearSearchTab;
857
+ $("#clear-search").onclick = () => { $("#global-search").value = ""; renderResults(); $("#global-search").focus(); };
858
+ window.addEventListener("resize", () => { if (dialog.open) positionSearch(); });
859
+ $("#global-search").oninput = (event) => {
860
+ const input = event.target;
861
+ if (!searchTab && !event.isComposing) {
862
+ const tab = site.tabs.find((item) => input.value.startsWith(`#${item.title} `));
863
+ if (tab) {
864
+ searchTab = tab;
865
+ input.value = input.value.slice(tab.title.length + 2);
866
+ $("#search-tag-label").textContent = `# ${tab.title}`;
867
+ $("#search-tag").hidden = false;
868
+ }
869
+ }
870
+ renderResults();
871
+ };
744
872
  $("#global-search").onkeydown = (event) => {
745
- if (event.key === "ArrowDown") {
873
+ if (event.key === "Backspace" && !event.isComposing && searchTab && !event.target.value && event.target.selectionStart === 0) {
874
+ clearSearchTab();
875
+ } else if (event.key === "ArrowDown") {
746
876
  event.preventDefault();
747
- $("#results a")?.focus();
748
- } else if (event.key === "Enter") $("#results a")?.click();
877
+ $("#search-suggestions:not([hidden]) button, #results a")?.focus();
878
+ } else if (event.key === "Enter") $("#search-suggestions:not([hidden]) button, #results a")?.click();
749
879
  };
750
880
  $("#results").onkeydown = (event) => {
751
881
  if (!["ArrowDown", "ArrowUp"].includes(event.key)) return;
@@ -776,6 +906,14 @@ dialog.addEventListener("click", (event) => {
776
906
  dialog.close();
777
907
  }
778
908
  });
909
+ const updateTocFades = () => {
910
+ const toc = $('#toc');
911
+ const frame = $('.toc-frame');
912
+ frame.classList.toggle('has-above', toc.scrollTop > 1);
913
+ frame.classList.toggle('has-below', toc.scrollTop + toc.clientHeight < toc.scrollHeight - 1);
914
+ };
915
+ $('#toc').addEventListener('scroll', updateTocFades);
916
+ new ResizeObserver(updateTocFades).observe($('.toc-frame'));
779
917
  window.addEventListener("hashchange", () => {
780
918
  if (site) render();
781
919
  });
@@ -0,0 +1,361 @@
1
+ const api = "/__doxen/comments";
2
+ const avatarColors = ['#2F6B4F', '#3E5BA9', '#9A4D16', '#6D4AA8', '#0E7490', '#9F1239'];
3
+ function avatarColor(author) {
4
+ let hash = 0;
5
+ for (const char of author) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) >>> 0;
6
+ return avatarColors[hash % avatarColors.length];
7
+ }
8
+
9
+
10
+ export async function attachComments(article, documentId, commentId) {
11
+ let response;
12
+ try { response = await fetch(`${api}?document=${encodeURIComponent(documentId)}`); }
13
+ catch { return; }
14
+ if (!response.ok || !article.isConnected || article.dataset.commentDocument !== documentId) return;
15
+ let comments = await response.json();
16
+ if (article.dataset.commentDocument !== documentId) return;
17
+ document.body.classList.add('has-comments');
18
+ const blocks = [...article.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, pre, blockquote, td, th')]
19
+ .filter((node) => {
20
+ if (node.tagName === 'LI') return [...node.childNodes].some((child) => !(child.nodeType === 1 && child.matches('ul, ol, p, pre, blockquote')) && child.textContent.trim());
21
+ return !node.querySelector('p, li, pre, blockquote, td, th') && node.textContent.trim();
22
+ });
23
+ const occurrences = new Map();
24
+ const matched = new Set();
25
+ const anchors = new Map();
26
+ const popover = document.createElement('button');
27
+ popover.type = 'button';
28
+ popover.className = 'comment-selection-trigger';
29
+ popover.setAttribute('aria-label', '댓글 추가');
30
+ popover.innerHTML = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 4.5h14a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-6l-4.5 3v-3H5a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2Z"/><path d="M7.5 9h9m-9 4h6"/></svg><span>댓글</span>';
31
+ popover.hidden = true;
32
+ article.append(popover);
33
+ let selectionTarget;
34
+ function clearDraftHighlight() {
35
+ for (const mark of article.querySelectorAll('.comment-draft-highlight')) {
36
+ const parent = mark.parentNode;
37
+ mark.replaceWith(...mark.childNodes);
38
+ parent.normalize();
39
+ }
40
+ }
41
+ const dismissController = new AbortController();
42
+ article.commentDismissController = dismissController;
43
+ const dismissComment = () => {
44
+ clearDraftHighlight();
45
+ popover.hidden = true;
46
+ for (const panel of article.querySelectorAll('.comment-anchor > .comment-panel')) panel.hidden = true;
47
+ for (const trigger of article.querySelectorAll('.comment-trigger.is-open')) trigger.classList.remove('is-open');
48
+ document.body.classList.remove('comment-card-open');
49
+ };
50
+ document.addEventListener('pointerdown', (event) => {
51
+ if (!event.target.closest('.comment-panel, .comment-trigger, .comment-selection-trigger')) dismissComment();
52
+ }, { signal: dismissController.signal });
53
+ document.addEventListener('keydown', (event) => {
54
+ if (event.key === 'Escape' && article.querySelector('.comment-trigger.is-open')) dismissComment();
55
+ }, { signal: dismissController.signal });
56
+ function showDraftHighlight(block, range) {
57
+ if (!range) return;
58
+ const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT);
59
+ const nodes = [];
60
+ while (walker.nextNode()) {
61
+ const node = walker.currentNode;
62
+ if (range.intersectsNode(node) && !node.parentElement.closest('.comment-panel, .comment-trigger')) nodes.push(node);
63
+ }
64
+ for (const node of nodes.reverse()) {
65
+ const start = node === range.startContainer ? range.startOffset : 0;
66
+ const end = node === range.endContainer ? range.endOffset : node.length;
67
+ if (start >= end) continue;
68
+ const selected = node.splitText(start);
69
+ selected.splitText(end - start);
70
+ const mark = document.createElement('mark');
71
+ mark.className = 'comment-draft-highlight';
72
+ selected.replaceWith(mark);
73
+ mark.append(selected);
74
+ }
75
+ }
76
+ article.onmousedown = (event) => {
77
+ if (!popover.contains(event.target)) popover.hidden = true;
78
+ };
79
+ article.onmouseup = () => {
80
+ const selection = window.getSelection();
81
+ if (!selection || selection.isCollapsed || !selection.toString().trim()) return;
82
+ const start = selection.anchorNode?.parentElement?.closest('.comment-anchor');
83
+ const end = selection.focusNode?.parentElement?.closest('.comment-anchor');
84
+ if (!start || start !== end || !anchors.has(start)) return;
85
+ const range = selection.getRangeAt(0);
86
+ const rect = range.cloneRange();
87
+ rect.collapse(selection.focusNode === range.startContainer && selection.focusOffset === range.startOffset);
88
+ const position = rect.getBoundingClientRect();
89
+ selectionTarget = { wrapper: start, quote: selection.toString().trim().slice(0, 2000), range: range.cloneRange() };
90
+ popover.style.left = `${Math.max(8, Math.min(window.innerWidth - 120, position.left))}px`;
91
+ popover.style.top = `${Math.max(8, Math.min(window.innerHeight - 48, position.bottom + 8))}px`;
92
+ popover.hidden = false;
93
+ };
94
+ popover.addEventListener('mousedown', (event) => event.preventDefault());
95
+ popover.addEventListener('click', () => {
96
+ if (selectionTarget) anchors.get(selectionTarget.wrapper)?.(selectionTarget.quote, selectionTarget.range);
97
+ popover.hidden = true;
98
+ });
99
+ for (const block of blocks) {
100
+ const ownNodes = block.tagName === 'LI' ? [...block.childNodes].filter((child) => !(child.nodeType === 1 && child.matches('ul, ol, p, pre, blockquote'))) : null;
101
+ const text = ownNodes ? ownNodes.map((node) => node.textContent).join('').trim() : block.textContent.trim();
102
+ const occurrence = occurrences.get(text) || 0;
103
+ occurrences.set(text, occurrence + 1);
104
+ const key = JSON.stringify([text, occurrence]);
105
+ if (key.length > 10000) continue;
106
+ matched.add(key);
107
+ const wrapper = document.createElement('div');
108
+ wrapper.className = 'comment-anchor';
109
+ if (['LI', 'TD', 'TH'].includes(block.tagName)) {
110
+ if (ownNodes) {
111
+ block.insertBefore(wrapper, ownNodes[0]);
112
+ wrapper.append(...ownNodes);
113
+ } else {
114
+ wrapper.append(...block.childNodes);
115
+ block.append(wrapper);
116
+ }
117
+ } else {
118
+ block.before(wrapper);
119
+ wrapper.append(block);
120
+ }
121
+ const button = document.createElement('button');
122
+ button.type = 'button';
123
+ button.className = 'comment-trigger';
124
+ button.setAttribute('aria-label', '이 부분에 댓글 달기');
125
+ wrapper.append(button);
126
+ const panel = document.createElement('div');
127
+ panel.className = 'comment-panel';
128
+ panel.hidden = true;
129
+ wrapper.append(panel);
130
+ let draftQuote = '';
131
+ anchors.set(wrapper, (quote, range) => openPanel(quote, range));
132
+ function draw(newItem) {
133
+ const oldList = panel.querySelector('.comment-list');
134
+ if (oldList) article.commentLaneObserver?.unobserve(oldList);
135
+ const items = comments.filter((item) => item.block === key);
136
+ for (const quote of new Set(items.map((item) => item.quote).filter(Boolean))) {
137
+ const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT);
138
+ const matches = [];
139
+ while (walker.nextNode()) {
140
+ const node = walker.currentNode;
141
+ if (node.parentElement.closest('.comment-panel, .comment-trigger, mark')) continue;
142
+ const index = node.data.indexOf(quote);
143
+ if (index >= 0) {
144
+ matches.push([node, index]);
145
+ if (node.data.indexOf(quote, index + 1) >= 0) matches.push([node, index]);
146
+ }
147
+ }
148
+ if (matches.length === 1) {
149
+ const [node, index] = matches[0];
150
+ const range = document.createRange();
151
+ range.setStart(node, index);
152
+ range.setEnd(node, index + quote.length);
153
+ const mark = document.createElement('mark');
154
+ mark.className = 'comment-highlight';
155
+ range.surroundContents(mark);
156
+ }
157
+ }
158
+ button.replaceChildren();
159
+ if (items.length) {
160
+ for (const author of [...new Set(items.map((item) => item.author))].slice(0, 3)) {
161
+ const avatar = document.createElement('span');
162
+ avatar.className = 'comment-avatar';
163
+ avatar.textContent = author[0].toUpperCase();
164
+ avatar.title = author;
165
+ avatar.style.backgroundColor = avatarColor(author);
166
+ button.append(avatar);
167
+ }
168
+ const count = document.createElement('span');
169
+ count.className = 'comment-count';
170
+ count.textContent = `${items.length}`;
171
+ const tooltip = document.createElement('span');
172
+ tooltip.className = 'comment-tooltip';
173
+ tooltip.textContent = '댓글 더보기';
174
+ button.setAttribute('aria-label', `댓글 ${items.length}개 더보기`);
175
+ button.append(count, tooltip);
176
+ } else {
177
+ button.setAttribute('aria-label', '이 부분에 댓글 달기');
178
+ button.innerHTML = '<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 4.5h14a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-6l-4.5 3v-3H5a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2Z"/><path d="M12 8v6m-3-3h6"/></svg>';
179
+ }
180
+ panel.replaceChildren();
181
+ const list = document.createElement('div');
182
+ list.className = 'comment-list';
183
+ const listFrame = document.createElement('div');
184
+ listFrame.className = 'comment-list-frame';
185
+ const updateFades = () => {
186
+ listFrame.classList.toggle('has-above', list.scrollTop > 1);
187
+ listFrame.classList.toggle('has-below', list.scrollTop + list.clientHeight < list.scrollHeight - 1);
188
+ };
189
+ list.updateFades = updateFades;
190
+ list.addEventListener('scroll', updateFades);
191
+ for (const item of items) {
192
+ const entry = document.createElement('div');
193
+ entry.dataset.commentId = item.id;
194
+ const summary = document.createElement('div');
195
+ summary.className = 'comment-card-head';
196
+ const avatar = document.createElement('span');
197
+ avatar.className = 'comment-avatar';
198
+ avatar.textContent = item.author[0].toUpperCase();
199
+ avatar.style.backgroundColor = avatarColor(item.author);
200
+ const name = document.createElement('strong');
201
+ name.textContent = item.author;
202
+ const time = document.createElement('time');
203
+ const created = new Date(item.created_at);
204
+ const minutes = Math.floor((Date.now() - created.getTime()) / 60000);
205
+ time.textContent = minutes < 1 ? '지금' : minutes < 60 ? `${minutes}분` : minutes < 1440 ? `${Math.floor(minutes / 60)}시간` : created.toLocaleDateString('ko-KR');
206
+ time.dateTime = item.created_at;
207
+ time.title = created.toLocaleString('ko-KR');
208
+ summary.append(avatar, name, time);
209
+ entry.append(summary);
210
+ if (item.quote) {
211
+ const quote = document.createElement('p');
212
+ quote.className = 'comment-quote';
213
+ const mark = document.createElement('mark');
214
+ mark.textContent = item.quote;
215
+ quote.append(mark);
216
+ entry.append(quote);
217
+ }
218
+ const body = document.createElement('p');
219
+ body.className = 'comment-body';
220
+ body.textContent = item.body;
221
+ entry.append(body);
222
+ list.append(entry);
223
+ }
224
+ if (items.length) {
225
+ listFrame.append(list);
226
+ panel.append(listFrame);
227
+ article.commentLaneObserver?.observe(list);
228
+ requestAnimationFrame(updateFades);
229
+ }
230
+ if (newItem) list.scrollTop = list.scrollHeight;
231
+ const form = document.createElement('form');
232
+ const input = document.createElement('textarea');
233
+ input.required = true;
234
+ input.rows = 1;
235
+ input.maxLength = 5000;
236
+ input.placeholder = '댓글 추가';
237
+ input.setAttribute('aria-label', '댓글 내용');
238
+ const submit = document.createElement('button');
239
+ submit.textContent = '댓글 등록';
240
+ const error = document.createElement('div');
241
+ error.setAttribute('role', 'alert');
242
+ form.className = 'comment-form';
243
+ submit.className = 'comment-submit';
244
+ submit.setAttribute('aria-label', '댓글 등록');
245
+ submit.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>';
246
+ submit.disabled = true;
247
+ const avatar = document.createElement('span');
248
+ avatar.className = 'comment-avatar';
249
+ avatar.textContent = '나';
250
+ const row = document.createElement('div');
251
+ row.className = 'comment-input-row';
252
+ const field = document.createElement('div');
253
+ field.className = 'comment-field';
254
+ field.append(input, submit);
255
+ row.append(avatar, field);
256
+ const foot = document.createElement('div');
257
+ foot.className = 'comment-foot';
258
+ const hint = document.createElement('span');
259
+ hint.textContent = '';
260
+ const counter = document.createElement('span');
261
+ foot.append(hint, counter);
262
+ foot.hidden = true;
263
+ input.addEventListener('input', () => {
264
+ submit.disabled = !input.value.trim();
265
+ foot.hidden = input.value.length < 4500;
266
+ counter.textContent = input.value.length >= 4500 ? `${input.value.length.toLocaleString('ko-KR')} / 5,000` : '';
267
+ error.textContent = '';
268
+ input.style.height = 'auto';
269
+ input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
270
+ input.style.overflowY = input.scrollHeight > 160 ? 'auto' : 'hidden';
271
+ });
272
+ input.addEventListener('keydown', (event) => {
273
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
274
+ event.preventDefault();
275
+ if (!submit.disabled) form.requestSubmit();
276
+ }
277
+ });
278
+ form.append(row, foot, error);
279
+ form.onsubmit = async (event) => {
280
+ event.preventDefault();
281
+ submit.disabled = true;
282
+ hint.textContent = '등록 중…';
283
+ foot.hidden = false;
284
+ try {
285
+ const result = await fetch(api, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document: documentId, block: key, quote: draftQuote, body: input.value }) });
286
+ if (!result.ok) throw new Error();
287
+ const newItem = await result.json();
288
+ comments.push(newItem);
289
+ clearDraftHighlight();
290
+ draftQuote = '';
291
+ draw(newItem);
292
+ } catch { error.textContent = '댓글을 저장하지 못했습니다. 다시 시도해 주세요.'; foot.hidden = true; submit.disabled = !input.value.trim(); }
293
+ };
294
+ panel.append(form);
295
+ }
296
+ function openPanel(quote = '', range, focus = true) {
297
+ clearDraftHighlight();
298
+ for (const other of article.querySelectorAll('.comment-anchor > .comment-panel')) other.hidden = true;
299
+ for (const other of article.querySelectorAll('.comment-trigger.is-open')) other.classList.remove('is-open');
300
+ draftQuote = quote;
301
+ showDraftHighlight(block, range);
302
+ panel.hidden = false;
303
+ button.classList.add('is-open');
304
+ document.body.classList.add('comment-card-open');
305
+ panel.querySelector('.comment-list')?.updateFades();
306
+ if (focus) panel.querySelector('textarea').focus();
307
+ }
308
+ button.addEventListener('mousedown', (event) => event.preventDefault());
309
+ button.addEventListener('click', () => {
310
+ const selection = window.getSelection();
311
+ const quote = selection && !selection.isCollapsed && block.contains(selection.anchorNode) && block.contains(selection.focusNode) ? selection.toString().trim().slice(0, 2000) : '';
312
+ if (!panel.hidden) { clearDraftHighlight(); draftQuote = ''; panel.hidden = true; button.classList.remove('is-open'); document.body.classList.remove('comment-card-open'); }
313
+ else openPanel(quote, quote && selection.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined);
314
+ popover.hidden = true;
315
+ });
316
+ draw();
317
+ if (commentId && comments.some((item) => item.id === commentId && item.block === key)) {
318
+ openPanel('', undefined, false);
319
+ const entry = [...panel.querySelectorAll('[data-comment-id]')].find((item) => item.dataset.commentId === commentId);
320
+ requestAnimationFrame(() => entry?.scrollIntoView({ block: 'center' }));
321
+ }
322
+ }
323
+ const alignButtons = () => {
324
+ const right = article.getBoundingClientRect().right;
325
+ for (const wrapper of anchors.keys()) {
326
+ wrapper.style.setProperty('--comment-offset', `${Math.max(0, right - wrapper.getBoundingClientRect().right)}px`);
327
+ wrapper.style.setProperty('--comment-panel-right', `${wrapper.getBoundingClientRect().right - window.innerWidth + 16}px`);
328
+ }
329
+ for (const list of article.querySelectorAll('.comment-list')) list.updateFades();
330
+ };
331
+ article.commentLaneObserver = new ResizeObserver(alignButtons);
332
+ window.addEventListener('resize', alignButtons, { signal: dismissController.signal });
333
+ article.commentLaneObserver.observe(article);
334
+ for (const wrapper of anchors.keys()) article.commentLaneObserver.observe(wrapper);
335
+ for (const list of article.querySelectorAll('.comment-list')) article.commentLaneObserver.observe(list);
336
+ alignButtons();
337
+ const orphaned = comments.filter((item) => !matched.has(item.block));
338
+ if (orphaned.length) {
339
+ const details = document.createElement('details');
340
+ details.className = 'comment-orphans';
341
+ const summary = document.createElement('summary');
342
+ summary.textContent = `위치를 찾을 수 없는 댓글 ${orphaned.length}개`;
343
+ details.append(summary);
344
+ for (const item of orphaned) {
345
+ const entry = document.createElement('div');
346
+ entry.dataset.commentId = item.id;
347
+ const label = document.createElement('strong');
348
+ label.textContent = item.author;
349
+ const body = document.createElement('p');
350
+ body.textContent = `${item.quote ? item.quote + '\n' : ''}${item.body}`;
351
+ entry.append(label, body);
352
+ details.append(entry);
353
+ }
354
+ article.append(details);
355
+ if (commentId && orphaned.some((item) => item.id === commentId)) {
356
+ details.open = true;
357
+ const entry = [...details.querySelectorAll('[data-comment-id]')].find((item) => item.dataset.commentId === commentId);
358
+ requestAnimationFrame(() => entry?.scrollIntoView({ block: 'center' }));
359
+ }
360
+ }
361
+ }
package/client/index.html CHANGED
@@ -16,7 +16,7 @@
16
16
  ><span class="brand-icon">D</span
17
17
  ><span id="site-title">Doxen</span></a
18
18
  ><button id="open-search" class="search-trigger">
19
- <span class="search-label">검색...</span><kbd>⌘ / Ctrl K</kbd></button
19
+ <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></svg><span class="search-label">검색...</span><kbd>⌘ / Ctrl K</kbd></button
20
20
  ><span class="header-label"></span>
21
21
  </header>
22
22
  <nav id="tabs" aria-label="문서 탭"></nav>
@@ -28,28 +28,33 @@
28
28
  </aside>
29
29
  <main id="content" tabindex="-1">
30
30
  <nav id="breadcrumb" aria-label="문서 경로"></nav>
31
+ <div class="compact-toc" hidden>
32
+ <button type="button" id="compact-toc-toggle" aria-expanded="false" aria-controls="compact-toc-links">☰ 목차</button>
33
+ <nav id="compact-toc-links" aria-label="이 페이지에서" hidden></nav>
34
+ </div>
31
35
  <article id="article"></article>
32
36
  <nav id="pagination" aria-label="이전 다음 문서"></nav>
33
37
  </main>
34
38
  <aside class="toc">
35
39
  <div class="eyebrow">이 페이지에서</div>
36
- <nav id="toc" aria-label="목차"></nav>
40
+ <div class="toc-frame"><nav id="toc" aria-label="목차"></nav></div>
37
41
  </aside>
38
42
  </div>
39
43
  <dialog id="search-dialog" aria-labelledby="search-title">
40
44
  <div class="dialog-head">
41
- <label id="search-title" for="global-search">전체 문서 검색</label
42
- ><button id="close-search" aria-label="검색 닫기">
43
- 닫기 <kbd>Esc</kbd>
44
- </button>
45
+ <label id="search-title" for="global-search">전체 문서 검색</label>
46
+ <button id="close-search" type="button" aria-label="검색 닫기">×</button>
45
47
  </div>
46
- <input
47
- id="global-search"
48
- type="search"
49
- placeholder="제목, 내용 또는 용어를 검색하세요"
50
- autocomplete="off"
51
- />
52
- <p id="search-count" aria-live="polite"></p>
48
+ <div class="search-body">
49
+ <div class="global-search-field">
50
+ <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/></svg>
51
+ <span id="search-tag" hidden><span id="search-tag-label"></span><button id="clear-search-tag" type="button" aria-label="탭 범위 지우기">×</button></span>
52
+ <input id="global-search" type="search" placeholder="제목, 내용 또는 용어를 검색하세요" autocomplete="off" />
53
+ <button id="clear-search" type="button" aria-label="검색어 지우기" hidden>×</button>
54
+ </div>
55
+ <p id="search-count" aria-live="polite"></p>
56
+ </div>
57
+ <div id="search-suggestions" hidden></div>
53
58
  <div id="results"></div>
54
59
  </dialog>
55
60
  <script type="module" src="./app.js"></script>
package/client/style.css CHANGED
@@ -939,13 +939,21 @@ article img {
939
939
  .toc {
940
940
  position: sticky;
941
941
  top: 0;
942
+ display: flex;
943
+ flex-direction: column;
942
944
  height: 100vh;
943
945
  padding: 30px 0;
944
- overflow: auto;
945
946
  }
946
947
  .toc .eyebrow {
947
948
  font-size: 12px;
948
949
  }
950
+ .toc-frame { position: relative; min-height: 0; }
951
+ .toc-frame::before, .toc-frame::after { content: ''; position: absolute; z-index: 1; left: 0; right: 0; height: 24px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
952
+ .toc-frame::before { top: 0; background: linear-gradient(to bottom, #fff, #fff0); }
953
+ .toc-frame::after { bottom: 0; background: linear-gradient(to top, #fff, #fff0); }
954
+ .toc-frame.has-above::before, .toc-frame.has-below::after { opacity: 1; }
955
+ #toc { max-height: 100%; overflow-y: auto; scrollbar-width: none; }
956
+ #toc::-webkit-scrollbar { display: none; }
949
957
  #toc a {
950
958
  display: block;
951
959
  color: #7d8289;
@@ -1058,7 +1066,7 @@ dialog::backdrop {
1058
1066
  .result mark {
1059
1067
  background: var(--accent-highlight, #dcf0ff);
1060
1068
  }
1061
- @media (max-width: 1200px) {
1069
+ @media (max-width: 1199px) {
1062
1070
  header,
1063
1071
  .layout {
1064
1072
  grid-template-columns: 230px minmax(0, 1fr);
@@ -1142,3 +1150,149 @@ dialog::backdrop {
1142
1150
  scroll-behavior: auto !important;
1143
1151
  }
1144
1152
  }
1153
+
1154
+ .comment-anchor { position: relative; }
1155
+ .comment-trigger { position: absolute; left: calc(100% + 20px); top: calc((1lh - 28px) / 2); z-index: 2; display: flex; align-items: center; gap: 6px; height: 28px; padding: 0 8px 0 3px; border: 0; border-radius: 14px; background: transparent; color: #374151; font-size: 13px; font-weight: 600; cursor: pointer; opacity: 0; white-space: nowrap; }
1156
+ .comment-trigger:not(:has(.comment-avatar)) { width: 32px; height: 32px; top: calc((1lh - 32px) / 2); padding: 0; justify-content: center; color: #9ca3af; }
1157
+ .comment-anchor:hover > .comment-trigger, .comment-trigger:focus-visible, .comment-trigger:has(.comment-avatar) { opacity: 1; }
1158
+ .comment-trigger:hover:has(.comment-avatar), .comment-trigger:focus-visible:has(.comment-avatar) { background: #f3f4f6; }
1159
+ .comment-trigger.is-open:has(.comment-avatar) { background: #fef3c7; }
1160
+ .comment-trigger:not(:has(.comment-avatar)):hover { color: #4b5563; }
1161
+ .comment-trigger .comment-avatar { width: 22px; height: 22px; box-shadow: 0 0 0 2px white; }
1162
+ .comment-trigger .comment-avatar + .comment-avatar { margin-left: -12px; }
1163
+ .comment-tooltip { position: absolute; top: calc(100% + 6px); left: 0; z-index: 3; display: none; border-radius: 6px; padding: 4px 8px; background: #191919; color: white; font-size: 12px; font-weight: 400; }
1164
+ .comment-trigger:hover .comment-tooltip, .comment-trigger:focus-visible .comment-tooltip { display: block; }
1165
+ .comment-avatar { display: inline-grid; flex: none; place-items: center; width: 24px; height: 24px; border-radius: 50%; background: #2f6b4f; color: white; font-size: 11px; font-weight: 600; }
1166
+ .comment-panel { position: absolute; z-index: 10; left: 0; top: calc(100% + 8px); display: flex; flex-direction: column; box-sizing: border-box; width: min(320px, calc(100vw - 32px)); max-height: calc(100dvh - 24px); border: 1px solid #e5e7eb; border-radius: 12px; background: #fff; box-shadow: 0 12px 32px #1118271a, 0 2px 6px #1118270d; color: #191919; font-size: 13px; overflow: hidden; text-align: left; }
1167
+ .comment-panel[hidden], .comment-selection-trigger[hidden], .comment-foot[hidden] { display: none; }
1168
+ .comment-list-frame { position: relative; display: flex; flex: 0 1 auto; min-height: 0; max-height: 50dvh; }
1169
+ .comment-list-frame::before, .comment-list-frame::after { content: ''; position: absolute; z-index: 1; left: 0; right: 0; height: 24px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
1170
+ .comment-list-frame::before { top: 0; background: linear-gradient(to bottom, #fff, #fff0); }
1171
+ .comment-list-frame::after { bottom: 0; background: linear-gradient(to top, #fff, #fff0); }
1172
+ .comment-list-frame.has-above::before, .comment-list-frame.has-below::after { opacity: 1; }
1173
+ .comment-list { flex: 1; min-height: 0; padding: 4px 0; overflow-y: auto; scrollbar-width: none; }
1174
+ .comment-list::-webkit-scrollbar { display: none; }
1175
+ .comment-card-head { display: flex; align-items: center; gap: 10px; padding: 10px 16px 6px; }
1176
+ .comment-card-head strong { flex: 1; min-width: 0; overflow: hidden; font-size: 13px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; }
1177
+ .comment-card-head time { flex: none; color: #6b7280; font-size: 12px; }
1178
+ .comment-panel p.comment-body { margin: 0; padding: 0 16px 12px 50px; color: #1f2937; font-size: 14px; line-height: 1.6; white-space: pre-wrap; overflow-wrap: anywhere; }
1179
+ .comment-panel p.comment-quote { margin: 2px 16px 6px 50px; color: #57534e; font-size: 12px; line-height: 1.5; overflow-wrap: anywhere; }
1180
+ .comment-quote mark { border-bottom: 1.5px solid #eab308; border-radius: 2px; padding: 1px 2px; background: #fef3c7; color: inherit; }
1181
+ .comment-form { padding: 10px 16px 12px; background: #fff; }
1182
+ .comment-input-row { display: flex; align-items: flex-start; gap: 10px; }
1183
+ .comment-input-row > .comment-avatar { margin-top: 8px; }
1184
+ .comment-field { display: flex; flex: 1; align-items: flex-end; gap: 6px; min-width: 0; padding: 3px 10px; border: 1px solid #d1d5db; border-radius: 10px; background: white; }
1185
+ .comment-panel textarea { flex: 1; min-width: 0; height: 32px; max-height: 160px; margin: 0; padding: 6px 4px 6px 0; border: 0; background: transparent; color: #191919; resize: none; outline: 0; font: inherit; font-size: 14px; line-height: 20px; overflow-y: hidden; }
1186
+ .comment-panel textarea::placeholder { color: #9ca3af; }
1187
+ .comment-submit { display: grid; flex: none; place-items: center; width: 22px; height: 22px; margin-bottom: 5px; padding: 0; border: 0; border-radius: 50%; background: #191919; color: white; cursor: pointer; }
1188
+ .comment-submit:disabled { background: #f3f4f6; color: #9ca3af; cursor: not-allowed; }
1189
+ .comment-foot { display: flex; justify-content: space-between; gap: 8px; margin: 6px 0 0 34px; color: #6b7280; font-size: 11px; }
1190
+ .comment-form [role="alert"] { margin: 6px 0 0 34px; color: #b91c1c; font-size: 12px; }
1191
+ .comment-form [role="alert"]:empty { display: none; }
1192
+ .comment-selection-trigger { position: fixed; z-index: 100; display: inline-flex; align-items: center; gap: 6px; height: 32px; padding: 0 12px 0 10px; border: 1px solid #e5e7eb; border-radius: 8px; background: white; box-shadow: 0 6px 16px #1118271a, 0 1px 2px #1118270f; color: #191919; font: inherit; font-size: 13px; font-weight: 500; line-height: 1; cursor: pointer; }
1193
+ .comment-orphans { position: static; width: min(320px, 100%); margin-top: 24px; padding: 12px 16px; border: 1px solid #e5e7eb; border-radius: 12px; background: white; font-size: 13px; }
1194
+ .comment-orphans summary { cursor: pointer; font-weight: 600; }
1195
+ .comment-orphans > div { margin-top: 10px; }
1196
+ .comment-orphans p { white-space: pre-wrap; overflow-wrap: anywhere; }
1197
+ .comment-draft-highlight { background: #cfe3ff; color: inherit; }
1198
+ .comment-highlight { border-bottom: 2px solid #eab308; background: #fef3c7; color: inherit; }
1199
+ .comment-anchor:has(.comment-trigger.is-open) .comment-highlight { background: #fde68a; }
1200
+ @media (min-width: 1600px) { .comment-panel { left: calc(100% + 88px); top: -8px; } }
1201
+ @media (hover: none) { .comment-trigger { left: auto; right: 0; min-width: 44px; min-height: 44px; opacity: 1; } }
1202
+
1203
+ /* Reserve a lane beside the document for comment controls. */
1204
+ body.has-comments #content { --comment-lane: 56px; padding-right: var(--comment-lane); }
1205
+ body.has-comments .comment-trigger { left: calc(100% + var(--comment-offset, 0px) + 8px); right: auto; }
1206
+ body.has-comments .comment-panel { left: auto; right: var(--comment-panel-right); width: min(320px, calc(100vw - 32px)); }
1207
+ .comment-tooltip { top: auto; bottom: calc(100% + 6px); }
1208
+ .compact-toc { display: none; }
1209
+ .compact-toc[hidden], #compact-toc-links[hidden] { display: none !important; }
1210
+ @media (min-width: 1600px) {
1211
+ body.has-comments #content { --comment-lane: 88px; }
1212
+ body.has-comments .comment-panel { left: calc(100% + var(--comment-offset, 0px) + 88px); right: auto; top: -8px; width: 320px; }
1213
+ body.comment-card-open .toc { opacity: .3; }
1214
+ }
1215
+ @media (max-width: 1599px) {
1216
+ body.has-comments .comment-trigger:has(.comment-avatar) { width: 44px; height: 44px; padding: 0; justify-content: center; background: transparent; }
1217
+ body.has-comments .comment-trigger .comment-avatar { width: 24px; height: 24px; }
1218
+ body.has-comments .comment-trigger .comment-avatar + .comment-avatar { display: none; }
1219
+ body.has-comments .comment-count { position: absolute; top: 20px; right: 0; min-width: 16px; height: 16px; padding: 0 3px; border-radius: 8px; background: #191919; color: white; font-size: 10px; line-height: 16px; text-align: center; }
1220
+ body.has-comments .comment-trigger.is-open .comment-avatar { box-shadow: 0 0 0 3px #fef3c7; }
1221
+ }
1222
+ @media (max-width: 1199px) {
1223
+ body.has-comments #content { --comment-lane: 48px; }
1224
+ body.has-comments .compact-toc:not([hidden]) { position: absolute; z-index: 20; display: flex; flex-direction: column; align-items: flex-end; top: 18px; right: 0; }
1225
+ #compact-toc-toggle { height: 32px; padding: 0 12px; border: 1px solid #e5e7eb; border-radius: 8px; background: white; color: #374151; font: inherit; font-size: 13px; cursor: pointer; }
1226
+ #compact-toc-links { width: 220px; max-width: calc(100vw - 40px); margin-top: 8px; padding: 12px 14px; border: 1px solid #e5e7eb; border-radius: 10px; background: white; box-shadow: 0 10px 24px #1118271a; }
1227
+ #compact-toc-links a { display: block; margin: 8px 0; color: #4b5563; font-size: 13px; }
1228
+ body.has-comments #breadcrumb { padding-right: 58px; }
1229
+ }
1230
+
1231
+ .document-modified {
1232
+ margin: -12px 0 24px;
1233
+ color: #929ba5;
1234
+ font-size: 12px;
1235
+ }
1236
+ .global-search-field {
1237
+ display: flex;
1238
+ align-items: center;
1239
+ gap: 6px;
1240
+ }
1241
+ #search-tag {
1242
+ flex: none;
1243
+ padding: 5px 8px;
1244
+ border-radius: 6px;
1245
+ background: var(--accent-soft, #f5f9fc);
1246
+ font-size: 12px;
1247
+ }
1248
+ #global-search { min-width: 0; }
1249
+
1250
+ /* 전체 문서 검색 */
1251
+ .search-trigger { width: 100%; height: 40px; gap: 10px; padding: 0 8px 0 14px; border: 1px solid #e5e7eb; border-radius: 10px; background: #f9fafb; box-shadow: none; color: #6b7280; cursor: text; }
1252
+ .search-trigger:hover { background: #fff; border-color: #d1d5db; }
1253
+ .search-trigger:focus-visible { outline: none; border-color: var(--accent, #eab308); box-shadow: 0 0 0 3px var(--accent-soft, #fef3c7); }
1254
+ .search-icon { width: 18px; height: 18px; flex: none; color: #6b7280; }
1255
+ .search-trigger .search-icon { width: 16px; height: 16px; }
1256
+ .search-trigger .search-label { flex: 1; }
1257
+ .search-label::before { content: none; }
1258
+ .search-trigger kbd { background: #fff; padding: 1px 6px; }
1259
+ #search-dialog { position: fixed; top: 120px; right: auto; bottom: auto; max-width: calc(100% - 40px); max-height: calc(100vh - 140px); margin: 0; padding: 0; border: 0; border-radius: 14px; box-shadow: 0 24px 60px #1118274d, 0 2px 8px #11182714; color: #191919; }
1260
+ #search-dialog::backdrop { background: #1118276b; backdrop-filter: blur(3px); }
1261
+ .dialog-head { margin: 0; padding: 18px 20px 12px; font-size: 15px; font-weight: 600; }
1262
+ .dialog-head button, #clear-search, #clear-search-tag { display: grid; place-items: center; padding: 0; border: 0; background: transparent; color: #6b7280; font-size: 24px; line-height: 1; }
1263
+ .dialog-head button, #clear-search { width: 32px; height: 32px; }
1264
+ .search-body { padding: 0 20px 12px; }
1265
+ .global-search-field { height: 48px; gap: 8px; padding: 0 8px 0 14px; border: 1px solid #e5e7eb; border-radius: 10px; }
1266
+ .global-search-field:focus-within { border-color: var(--accent, #eab308); box-shadow: 0 0 0 3px var(--accent-soft, #fef3c7); }
1267
+ #global-search { flex: 1; width: 100%; min-width: 40px; height: 24px; padding: 0; border: 0; border-radius: 0; outline: 0; background: transparent; font-size: 15px; }
1268
+ #global-search::-webkit-search-cancel-button { display: none; }
1269
+ #search-tag:not([hidden]) { display: flex; align-items: center; flex: 0 1 auto; min-width: 0; max-width: 180px; height: 28px; padding: 0 4px 0 8px; border-radius: 6px; background: var(--accent-soft, #fef3c7); color: var(--accent, #92400e); font-size: 13px; font-weight: 600; }
1270
+ #search-tag-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1271
+ #clear-search-tag { display: flex; align-items: center; justify-content: flex-end; flex: none; width: 20px; height: 20px; color: color-mix(in srgb, var(--accent, #92400e) 80%, black); font-size: 13px; font-weight: 600; }
1272
+ #clear-search[hidden] { display: none; }
1273
+ #search-count { margin: 10px 2px 0; color: #6b7280; font-size: 12px; }
1274
+ #search-suggestions:not([hidden]) { margin: 0 20px 16px; padding: 6px; border: 1px solid #ecedef; border-radius: 10px; }
1275
+ #search-suggestions p { margin: 4px 8px 6px; color: #6b7280; font-size: 11px; }
1276
+ .search-suggestion { display: flex; align-items: center; gap: 10px; width: 100%; height: 40px; padding: 0 10px; border: 0; text-align: left; }
1277
+ .search-suggestion:hover, .search-suggestion:focus-visible { background: var(--accent-soft, #fef9e7); }
1278
+ .search-suggestion span { padding: 2px 8px; border-radius: 6px; background: var(--accent-soft, #fef3c7); color: var(--accent, #92400e); font-size: 13px; font-weight: 600; }
1279
+ .search-suggestion small { color: #6b7280; font-size: 12px; }
1280
+ #results:not(:empty) { padding: 4px 12px 12px; border-top: 1px solid #f0f1f3; }
1281
+ .result { padding: 12px; border: 0; border-radius: 10px; }
1282
+ .result:hover, .result:focus-visible { background: #f9fafb; }
1283
+ .result small { color: #6b7280; font-size: 12px; }
1284
+ .result strong { display: block; margin: 2px 0 4px; color: var(--accent, #b45309); font-size: 15px; }
1285
+ .result p { display: -webkit-box; overflow: hidden; -webkit-box-orient: vertical; -webkit-line-clamp: 2; margin: 0; color: #4b5563; font-size: 13px; line-height: 1.6; }
1286
+ .search-empty { padding: 28px 8px 20px; text-align: center; font-size: 14px; }
1287
+ .search-empty p { margin: 6px 0 14px; color: #6b7280; font-size: 13px; }
1288
+ .search-empty button { color: #191919; font-size: 13px; }
1289
+ @media (max-width: 700px) {
1290
+ .search-trigger { width: 150px; }
1291
+ #search-dialog { top: 80px; max-height: calc(100vh - 100px); }
1292
+ }
1293
+
1294
+ .document-title { display: flex; align-items: flex-start; gap: 12px; }
1295
+ .document-title h1 { flex: 1; min-width: 0; }
1296
+ .document-download { display: grid; flex: none; place-items: center; width: 36px; height: 36px; border-radius: 6px; color: #6b7280; }
1297
+ .document-download:hover { background: #f3f4f6; color: #191919; }
1298
+ .document-title > .comment-anchor { flex: 1; min-width: 0; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unana_dev/doxen",
3
- "version": "0.2.6",
3
+ "version": "0.3.1",
4
4
  "description": "Config-first Markdown documentation sites with Korean and section search",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,6 +12,7 @@ export function accessWorker(access, keys = createRemoteJWKSet(
12
12
  });
13
13
  const token = request.headers.get("cf-access-jwt-assertion");
14
14
  if (!token) return denied();
15
+ let email;
15
16
  try {
16
17
  const { payload } = await jwtVerify(token, keys, {
17
18
  issuer: access.teamDomain,
@@ -21,9 +22,36 @@ export function accessWorker(access, keys = createRemoteJWKSet(
21
22
  });
22
23
  if (typeof payload.email !== "string" || !emails.has(payload.email.toLowerCase()))
23
24
  return denied();
25
+ email = payload.email.toLowerCase();
24
26
  } catch {
25
27
  return denied();
26
28
  }
29
+ const url = new URL(request.url);
30
+ if (url.pathname === "/__doxen/comments") {
31
+ const headers = { "Cache-Control": "private, no-store" };
32
+ if (!env.COMMENTS_DB) return new Response("댓글 저장소가 설정되지 않았습니다.", { status: 503, headers });
33
+ if (request.method === "GET") {
34
+ const document = url.searchParams.get("document");
35
+ if (!document || document.length > 500) return new Response("잘못된 문서", { status: 400, headers });
36
+ const rows = await env.COMMENTS_DB.prepare("SELECT id, block, quote, body, author, created_at FROM comments WHERE document = ? ORDER BY created_at, id").bind(document).all();
37
+ return Response.json(rows.results, { headers });
38
+ }
39
+ if (request.method === "POST") {
40
+ if (request.headers.get("origin") !== url.origin || !request.headers.get("content-type")?.startsWith("application/json"))
41
+ return new Response("잘못된 요청", { status: 403, headers });
42
+ let data;
43
+ try { data = await request.json(); } catch { return new Response("잘못된 요청", { status: 400, headers }); }
44
+ if (![data?.document, data?.block, data?.quote, data?.body].every((value) => typeof value === "string") ||
45
+ !data.document || data.document.length > 500 || !data.block || data.block.length > 10000 ||
46
+ data.quote.length > 2000 || !data.body.trim() || data.body.length > 5000)
47
+ return new Response("잘못된 댓글", { status: 400, headers });
48
+ const row = { id: crypto.randomUUID(), block: data.block, quote: data.quote, body: data.body.trim(), author: email, created_at: new Date().toISOString() };
49
+ await env.COMMENTS_DB.prepare("INSERT INTO comments (id, document, block, quote, body, author, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
50
+ .bind(row.id, data.document, row.block, row.quote, row.body, row.author, row.created_at).run();
51
+ return Response.json(row, { status: 201, headers });
52
+ }
53
+ return new Response("허용되지 않는 요청", { status: 405, headers });
54
+ }
27
55
  const asset = await env.ASSETS.fetch(request);
28
56
  const response = new Response(asset.body, asset);
29
57
  response.headers.set("Cache-Control", "private, no-store");
package/src/build.js CHANGED
@@ -53,7 +53,7 @@ export async function siteFiles(config, dev = false) {
53
53
  `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="${config.icon.background}"/><text x="16" y="16" dominant-baseline="middle" text-anchor="middle" font-family="Arial, sans-serif" font-size="22" font-weight="700" fill="${config.icon.color}">${initial.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)}</text></svg>`,
54
54
  ),
55
55
  );
56
- for (const name of ["index.html", "app.js", "style.css", "search.js"])
56
+ for (const name of ["index.html", "app.js", "style.css", "search.js", "comments.js"])
57
57
  files.set(`/${name}`, await readFile(path.join(client, name)));
58
58
  for (const output of (await getPresentationAssets()).outputFiles) {
59
59
  const name = path.relative(path.join(client, "generated"), output.path).split(path.sep).join("/");
@@ -0,0 +1,82 @@
1
+ // Copy src/templates/comment-report.yml into the consuming repository to run this report.
2
+ import path from 'node:path';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { loadConfig, inside } from './config.js';
5
+ import { collectSite } from './content.js';
6
+
7
+ const { CLOUDFLARE_ACCOUNT_ID: account, CLOUDFLARE_D1_DATABASE_ID: database,
8
+ CLOUDFLARE_API_TOKEN: cloudflareToken, GITHUB_TOKEN: githubToken,
9
+ GITHUB_REPOSITORY: repository, GITHUB_SHA: commit, DOXEN_SITE_URL: siteUrl, REPORT_DATE } = process.env;
10
+ if (!account || !database || !cloudflareToken || !githubToken || !repository || !commit || !siteUrl)
11
+ throw new Error('댓글 보고서에 필요한 Cloudflare 및 GitHub 환경 변수가 없습니다.');
12
+ if (!/^[a-f0-9]{40}$/i.test(commit)) throw new Error('GITHUB_SHA가 올바르지 않습니다.');
13
+ let site;
14
+ try { site = new URL(siteUrl); } catch { throw new Error('DOXEN_SITE_URL은 사이트의 HTTP(S) 주소여야 합니다.'); }
15
+ if (!['http:', 'https:'].includes(site.protocol) || site.username || site.password || site.search || site.hash)
16
+ throw new Error('DOXEN_SITE_URL은 쿼리나 인증 정보가 없는 사이트 주소여야 합니다.');
17
+ const date = REPORT_DATE || new Date(Date.now() + 9 * 3600000 - 86400000).toISOString().slice(0, 10);
18
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || new Date(`${date}T00:00:00Z`).toISOString().slice(0, 10) !== date)
19
+ throw new Error('REPORT_DATE는 YYYY-MM-DD 형식의 유효한 날짜여야 합니다.');
20
+ const start = new Date(`${date}T00:00:00+09:00`);
21
+ const end = new Date(start.getTime() + 86400000);
22
+ const cloudflare = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(account)}/d1/database/${encodeURIComponent(database)}/query`, {
23
+ method: 'POST', headers: { Authorization: `Bearer ${cloudflareToken}`, 'Content-Type': 'application/json' },
24
+ body: JSON.stringify({ sql: 'SELECT id, document, quote, body, author, created_at FROM comments WHERE created_at >= ? AND created_at < ? ORDER BY created_at, id', params: [start.toISOString(), end.toISOString()] }),
25
+ });
26
+ if (!cloudflare.ok) throw new Error(`D1 조회 실패: HTTP ${cloudflare.status}`);
27
+ const result = await cloudflare.json();
28
+ if (!result.success || !result.result?.[0]?.success) throw new Error('D1 조회에 실패했습니다.');
29
+ const comments = result.result[0].results;
30
+ if (!comments.length) { console.log(`${date}: 등록할 댓글이 없습니다.`); process.exit(0); }
31
+ const github = `https://api.github.com/repos/${repository}/issues`;
32
+ const headers = { Authorization: `Bearer ${githubToken}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' };
33
+ const marker = `<!-- doxen-comment-report:${date} -->`;
34
+ for (let page = 1; ; page++) {
35
+ const response = await fetch(`${github}?state=all&per_page=100&page=${page}`, { headers });
36
+ if (!response.ok) throw new Error(`GitHub 이슈 조회 실패: HTTP ${response.status}`);
37
+ const issues = await response.json();
38
+ if (issues.some((issue) => !issue.pull_request && issue.body?.includes(marker))) {
39
+ console.log(`${date}: 이미 보고서 이슈가 있습니다.`); process.exit(0);
40
+ }
41
+ if (issues.length < 100) break;
42
+ }
43
+ const workspace = await realpath(process.env.GITHUB_WORKSPACE || process.cwd());
44
+ const config = await loadConfig(workspace, process.env.DOXEN_CONFIG || undefined);
45
+ const { data } = await collectSite(config);
46
+ const paths = new Map(data.documents.filter((doc) => !doc.spreadsheet).map((doc) => {
47
+ const tab = config.tabs.find((item) => item.slug === doc.tab);
48
+ const file = path.resolve(tab.dir, doc.path);
49
+ return [doc.id, inside(workspace, file) ? path.relative(workspace, file).split(path.sep).join('/') : null];
50
+ }));
51
+ const encodedPath = (value) => value.split('/').map(encodeURIComponent).join('/');
52
+ const safeLink = (value) => value.replace(/[()<>\s]/g, (char) => encodeURIComponent(char));
53
+ const fileLink = (document) => {
54
+ const file = paths.get(document);
55
+ if (!file) return ['- 문서 링크: 현재 문서 경로를 찾을 수 없습니다.'];
56
+ return [
57
+ `- 원본 파일: [${safe(file).replace(/[\\\[\]]/g, '\\$&')}](<https://github.com/${repository}/blob/${commit}/${encodedPath(file)}>)`,
58
+ ];
59
+ };
60
+ const commentLink = (item) => {
61
+ if (!paths.get(item.document)) return [];
62
+ const documentUrl = new URL(site);
63
+ documentUrl.hash = `/${encodeURIComponent(item.document)}/comment/${encodeURIComponent(item.id)}`;
64
+ return [`- 배포 사이트: [댓글 위치 보기](<${safeLink(documentUrl.href)}>)`];
65
+ };
66
+ const safe = (value) => String(value).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]).replace(/@/g, '&#64;');
67
+ const grouped = new Map();
68
+ for (const item of comments) {
69
+ if (!grouped.has(item.document)) grouped.set(item.document, []);
70
+ grouped.get(item.document).push(item);
71
+ }
72
+ const body = [marker, `## ${date} 문서 댓글`, '', `총 ${comments.length}개 · 한국 시간 기준`, '', ...[...grouped].flatMap(([document, items]) => [
73
+ `### ${safe(document)} · 댓글 ${items.length}개`, ...fileLink(document), '',
74
+ ...items.flatMap((item, index) => [
75
+ `#### 댓글 ${index + 1}`, ...commentLink(item), `- 작성자: ${safe(item.author)}`, `- 작성 시각: ${safe(item.created_at)}`,
76
+ ...(item.quote ? ['', '**선택한 문구**', `<pre>${safe(item.quote)}</pre>`] : []),
77
+ '', '**댓글**', `<pre>${safe(item.body)}</pre>`, '',
78
+ ]), '---', '',
79
+ ]), '## 후속 작업', '- [ ] 댓글 검토 및 처리'].join('\n');
80
+ const created = await fetch(github, { method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify({ title: `[문서 댓글] ${date} 일일 보고`, body }) });
81
+ if (!created.ok) throw new Error(`GitHub 이슈 생성 실패: HTTP ${created.status}`);
82
+ console.log(`${date}: 댓글 ${comments.length}개를 이슈로 등록했습니다.`);
@@ -0,0 +1,10 @@
1
+ CREATE TABLE IF NOT EXISTS comments (
2
+ id TEXT PRIMARY KEY,
3
+ document TEXT NOT NULL,
4
+ block TEXT NOT NULL,
5
+ quote TEXT NOT NULL,
6
+ body TEXT NOT NULL,
7
+ author TEXT NOT NULL,
8
+ created_at TEXT NOT NULL
9
+ );
10
+ CREATE INDEX IF NOT EXISTS comments_document ON comments(document, created_at);
package/src/content.js CHANGED
@@ -1,5 +1,7 @@
1
- import { readFile, readdir, realpath } from "node:fs/promises";
1
+ import { readFile, readdir, realpath, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
3
5
  import { createHash } from "node:crypto";
4
6
  import MarkdownIt from "markdown-it";
5
7
  import container from "markdown-it-container";
@@ -8,6 +10,24 @@ import sanitizeHtml from "sanitize-html";
8
10
  import readXlsxFile from "read-excel-file/node";
9
11
  import { inside } from "./config.js";
10
12
 
13
+ const execFileAsync = promisify(execFile);
14
+
15
+ async function modificationInfo(file, root) {
16
+ try {
17
+ const { stdout } = await execFileAsync("git", ["log", "-1", "--format=%H%n%aI%n%an", "--follow", "--", file], { cwd: root });
18
+ const [commit, date, author] = stdout.trim().split("\n");
19
+ if (date) {
20
+ const { stdout: shallowPath } = await execFileAsync("git", ["rev-parse", "--git-path", "shallow"], { cwd: root });
21
+ const boundaries = await readFile(path.resolve(root, shallowPath.trim()), "utf8").catch(() => "");
22
+ if (!boundaries.split(/\s+/).includes(commit)) return { date, author };
23
+ return {};
24
+ }
25
+ } catch {
26
+ // Files outside Git or environments without Git use the filesystem timestamp.
27
+ }
28
+ return { date: (await stat(file)).mtime.toISOString() };
29
+ }
30
+
11
31
  const assetExtensions = new Set([
12
32
  ".png",
13
33
  ".jpg",
@@ -64,6 +84,7 @@ export async function collectSite(config) {
64
84
  tab: tab.slug,
65
85
  path: relative,
66
86
  file,
87
+ modified: await modificationInfo(file, config.root),
67
88
  source: await readFile(file, /\.xlsx$/i.test(file) ? undefined : "utf8"),
68
89
  });
69
90
  }
@@ -84,6 +105,9 @@ export async function collectSite(config) {
84
105
  delete doc.file;
85
106
  continue;
86
107
  }
108
+ const hash = createHash("sha256").update(doc.source).digest("hex").slice(0, 20);
109
+ assets.set(`${hash}.md`, Buffer.from(doc.source));
110
+ doc.markdown = `./assets/${hash}.md`;
87
111
  const slugger = new GithubSlugger();
88
112
  const md = new MarkdownIt({
89
113
  html: false,
@@ -69,6 +69,7 @@ export function deploymentFromState(state) {
69
69
  if (!state?.ready) return undefined;
70
70
  return {
71
71
  project: state.project,
72
+ ...(state.comments ? { comments: state.comments } : {}),
72
73
  access: { teamDomain: state.teamDomain, audiences: Object.values(state.apps).map((app) => app.aud), emails: state.emails },
73
74
  };
74
75
  }
package/src/deploy.js CHANGED
@@ -22,9 +22,13 @@ export function validateDeployment(deploy) {
22
22
  if (!Array.isArray(access.emails) || !access.emails.length ||
23
23
  access.emails.some((value) => typeof value !== "string" || !/^[^\s@*]+@[^\s@*]+\.[^\s@*]+$/.test(value)))
24
24
  throw new Error("deploy.access.emails에 허용할 이메일 주소를 하나 이상 설정하세요.");
25
+ if (deploy.comments && (typeof deploy.comments.databaseName !== "string" || !/^[a-zA-Z0-9_-]+$/.test(deploy.comments.databaseName) ||
26
+ typeof deploy.comments.databaseId !== "string" || !/^[a-f0-9-]{36}$/i.test(deploy.comments.databaseId)))
27
+ throw new Error("deploy.comments에 올바른 databaseName과 databaseId를 설정하세요.");
25
28
  return {
26
29
  project: deploy.project,
27
30
  access: { teamDomain: access.teamDomain, audiences: access.audiences, emails: access.emails },
31
+ ...(deploy.comments ? { comments: deploy.comments } : {}),
28
32
  };
29
33
  }
30
34
 
@@ -94,6 +98,7 @@ export async function deploy(config, options) {
94
98
  name: settings.project,
95
99
  pages_build_output_dir: out,
96
100
  compatibility_date: "2026-10-08",
101
+ ...(settings.comments ? { d1_databases: [{ binding: "COMMENTS_DB", database_name: settings.comments.databaseName, database_id: settings.comments.databaseId }] } : {}),
97
102
  }));
98
103
  await new Promise((resolve, reject) => {
99
104
  const child = spawn(process.execPath, [wrangler, "pages", "deploy", out,
package/src/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export interface DocsConfig {
5
5
  icon?: string | { background?: string; color?: string; border?: string };
6
6
  deploy?: {
7
7
  project: string;
8
+ comments?: { databaseName: string; databaseId: string };
8
9
  access: {
9
10
  teamDomain: string;
10
11
  audiences: string[];
@@ -0,0 +1,34 @@
1
+ name: Daily Doxen comments
2
+ on:
3
+ schedule:
4
+ - cron: '0 23 * * *' # 매일 오전 8시 (Asia/Seoul)
5
+ workflow_dispatch:
6
+ inputs:
7
+ report_date:
8
+ description: '집계할 날짜 (YYYY-MM-DD, 한국 시간; 비우면 전날)'
9
+ required: false
10
+ permissions:
11
+ contents: read
12
+ issues: write
13
+ concurrency:
14
+ group: doxen-comment-report
15
+ cancel-in-progress: false
16
+ jobs:
17
+ report:
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - uses: actions/setup-node@v4
22
+ with:
23
+ node-version: '22'
24
+ - run: npm ci
25
+ - name: Create daily comment issue
26
+ run: node node_modules/@unana_dev/doxen/src/comment-report.js
27
+ env:
28
+ CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
29
+ CLOUDFLARE_D1_DATABASE_ID: ${{ secrets.CLOUDFLARE_D1_DATABASE_ID }}
30
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_D1_READ_TOKEN }}
31
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
32
+ DOXEN_SITE_URL: ${{ vars.DOXEN_SITE_URL }}
33
+ DOXEN_CONFIG: ${{ vars.DOXEN_CONFIG }}
34
+ REPORT_DATE: ${{ inputs.report_date }}