@unana_dev/doxen 0.2.5 → 0.3.0

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.
@@ -0,0 +1,352 @@
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) => !node.querySelector('p, li, pre, blockquote, td, th') && node.textContent.trim());
20
+ const occurrences = new Map();
21
+ const matched = new Set();
22
+ const anchors = new Map();
23
+ const popover = document.createElement('button');
24
+ popover.type = 'button';
25
+ popover.className = 'comment-selection-trigger';
26
+ popover.setAttribute('aria-label', '댓글 추가');
27
+ 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>';
28
+ popover.hidden = true;
29
+ article.append(popover);
30
+ let selectionTarget;
31
+ function clearDraftHighlight() {
32
+ for (const mark of article.querySelectorAll('.comment-draft-highlight')) {
33
+ const parent = mark.parentNode;
34
+ mark.replaceWith(...mark.childNodes);
35
+ parent.normalize();
36
+ }
37
+ }
38
+ const dismissController = new AbortController();
39
+ article.commentDismissController = dismissController;
40
+ const dismissComment = () => {
41
+ clearDraftHighlight();
42
+ popover.hidden = true;
43
+ for (const panel of article.querySelectorAll('.comment-anchor > .comment-panel')) panel.hidden = true;
44
+ for (const trigger of article.querySelectorAll('.comment-trigger.is-open')) trigger.classList.remove('is-open');
45
+ document.body.classList.remove('comment-card-open');
46
+ };
47
+ document.addEventListener('pointerdown', (event) => {
48
+ if (!event.target.closest('.comment-panel, .comment-trigger, .comment-selection-trigger')) dismissComment();
49
+ }, { signal: dismissController.signal });
50
+ document.addEventListener('keydown', (event) => {
51
+ if (event.key === 'Escape' && article.querySelector('.comment-trigger.is-open')) dismissComment();
52
+ }, { signal: dismissController.signal });
53
+ function showDraftHighlight(block, range) {
54
+ if (!range) return;
55
+ const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT);
56
+ const nodes = [];
57
+ while (walker.nextNode()) {
58
+ const node = walker.currentNode;
59
+ if (range.intersectsNode(node) && !node.parentElement.closest('.comment-panel, .comment-trigger')) nodes.push(node);
60
+ }
61
+ for (const node of nodes.reverse()) {
62
+ const start = node === range.startContainer ? range.startOffset : 0;
63
+ const end = node === range.endContainer ? range.endOffset : node.length;
64
+ if (start >= end) continue;
65
+ const selected = node.splitText(start);
66
+ selected.splitText(end - start);
67
+ const mark = document.createElement('mark');
68
+ mark.className = 'comment-draft-highlight';
69
+ selected.replaceWith(mark);
70
+ mark.append(selected);
71
+ }
72
+ }
73
+ article.onmousedown = (event) => {
74
+ if (!popover.contains(event.target)) popover.hidden = true;
75
+ };
76
+ article.onmouseup = () => {
77
+ const selection = window.getSelection();
78
+ if (!selection || selection.isCollapsed || !selection.toString().trim()) return;
79
+ const start = selection.anchorNode?.parentElement?.closest('.comment-anchor');
80
+ const end = selection.focusNode?.parentElement?.closest('.comment-anchor');
81
+ if (!start || start !== end || !anchors.has(start)) return;
82
+ const range = selection.getRangeAt(0);
83
+ const rect = range.cloneRange();
84
+ rect.collapse(selection.focusNode === range.startContainer && selection.focusOffset === range.startOffset);
85
+ const position = rect.getBoundingClientRect();
86
+ selectionTarget = { wrapper: start, quote: selection.toString().trim().slice(0, 2000), range: range.cloneRange() };
87
+ popover.style.left = `${Math.max(8, Math.min(window.innerWidth - 120, position.left))}px`;
88
+ popover.style.top = `${Math.max(8, Math.min(window.innerHeight - 48, position.bottom + 8))}px`;
89
+ popover.hidden = false;
90
+ };
91
+ popover.addEventListener('mousedown', (event) => event.preventDefault());
92
+ popover.addEventListener('click', () => {
93
+ if (selectionTarget) anchors.get(selectionTarget.wrapper)?.(selectionTarget.quote, selectionTarget.range);
94
+ popover.hidden = true;
95
+ });
96
+ for (const block of blocks) {
97
+ const text = block.textContent.trim();
98
+ const occurrence = occurrences.get(text) || 0;
99
+ occurrences.set(text, occurrence + 1);
100
+ const key = JSON.stringify([text, occurrence]);
101
+ if (key.length > 10000) continue;
102
+ matched.add(key);
103
+ const wrapper = document.createElement('div');
104
+ wrapper.className = 'comment-anchor';
105
+ if (['LI', 'TD', 'TH'].includes(block.tagName)) {
106
+ wrapper.append(...block.childNodes);
107
+ block.append(wrapper);
108
+ } else {
109
+ block.before(wrapper);
110
+ wrapper.append(block);
111
+ }
112
+ const button = document.createElement('button');
113
+ button.type = 'button';
114
+ button.className = 'comment-trigger';
115
+ button.setAttribute('aria-label', '이 부분에 댓글 달기');
116
+ wrapper.append(button);
117
+ const panel = document.createElement('div');
118
+ panel.className = 'comment-panel';
119
+ panel.hidden = true;
120
+ wrapper.append(panel);
121
+ let draftQuote = '';
122
+ anchors.set(wrapper, (quote, range) => openPanel(quote, range));
123
+ function draw(newItem) {
124
+ const oldList = panel.querySelector('.comment-list');
125
+ if (oldList) article.commentLaneObserver?.unobserve(oldList);
126
+ const items = comments.filter((item) => item.block === key);
127
+ for (const quote of new Set(items.map((item) => item.quote).filter(Boolean))) {
128
+ const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT);
129
+ const matches = [];
130
+ while (walker.nextNode()) {
131
+ const node = walker.currentNode;
132
+ if (node.parentElement.closest('.comment-panel, .comment-trigger, mark')) continue;
133
+ const index = node.data.indexOf(quote);
134
+ if (index >= 0) {
135
+ matches.push([node, index]);
136
+ if (node.data.indexOf(quote, index + 1) >= 0) matches.push([node, index]);
137
+ }
138
+ }
139
+ if (matches.length === 1) {
140
+ const [node, index] = matches[0];
141
+ const range = document.createRange();
142
+ range.setStart(node, index);
143
+ range.setEnd(node, index + quote.length);
144
+ const mark = document.createElement('mark');
145
+ mark.className = 'comment-highlight';
146
+ range.surroundContents(mark);
147
+ }
148
+ }
149
+ button.replaceChildren();
150
+ if (items.length) {
151
+ for (const author of [...new Set(items.map((item) => item.author))].slice(0, 3)) {
152
+ const avatar = document.createElement('span');
153
+ avatar.className = 'comment-avatar';
154
+ avatar.textContent = author[0].toUpperCase();
155
+ avatar.title = author;
156
+ avatar.style.backgroundColor = avatarColor(author);
157
+ button.append(avatar);
158
+ }
159
+ const count = document.createElement('span');
160
+ count.className = 'comment-count';
161
+ count.textContent = `${items.length}`;
162
+ const tooltip = document.createElement('span');
163
+ tooltip.className = 'comment-tooltip';
164
+ tooltip.textContent = '댓글 더보기';
165
+ button.setAttribute('aria-label', `댓글 ${items.length}개 더보기`);
166
+ button.append(count, tooltip);
167
+ } else {
168
+ button.setAttribute('aria-label', '이 부분에 댓글 달기');
169
+ 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>';
170
+ }
171
+ panel.replaceChildren();
172
+ const list = document.createElement('div');
173
+ list.className = 'comment-list';
174
+ const listFrame = document.createElement('div');
175
+ listFrame.className = 'comment-list-frame';
176
+ const updateFades = () => {
177
+ listFrame.classList.toggle('has-above', list.scrollTop > 1);
178
+ listFrame.classList.toggle('has-below', list.scrollTop + list.clientHeight < list.scrollHeight - 1);
179
+ };
180
+ list.updateFades = updateFades;
181
+ list.addEventListener('scroll', updateFades);
182
+ for (const item of items) {
183
+ const entry = document.createElement('div');
184
+ entry.dataset.commentId = item.id;
185
+ const summary = document.createElement('div');
186
+ summary.className = 'comment-card-head';
187
+ const avatar = document.createElement('span');
188
+ avatar.className = 'comment-avatar';
189
+ avatar.textContent = item.author[0].toUpperCase();
190
+ avatar.style.backgroundColor = avatarColor(item.author);
191
+ const name = document.createElement('strong');
192
+ name.textContent = item.author;
193
+ const time = document.createElement('time');
194
+ const created = new Date(item.created_at);
195
+ const minutes = Math.floor((Date.now() - created.getTime()) / 60000);
196
+ time.textContent = minutes < 1 ? '지금' : minutes < 60 ? `${minutes}분` : minutes < 1440 ? `${Math.floor(minutes / 60)}시간` : created.toLocaleDateString('ko-KR');
197
+ time.dateTime = item.created_at;
198
+ time.title = created.toLocaleString('ko-KR');
199
+ summary.append(avatar, name, time);
200
+ entry.append(summary);
201
+ if (item.quote) {
202
+ const quote = document.createElement('p');
203
+ quote.className = 'comment-quote';
204
+ const mark = document.createElement('mark');
205
+ mark.textContent = item.quote;
206
+ quote.append(mark);
207
+ entry.append(quote);
208
+ }
209
+ const body = document.createElement('p');
210
+ body.className = 'comment-body';
211
+ body.textContent = item.body;
212
+ entry.append(body);
213
+ list.append(entry);
214
+ }
215
+ if (items.length) {
216
+ listFrame.append(list);
217
+ panel.append(listFrame);
218
+ article.commentLaneObserver?.observe(list);
219
+ requestAnimationFrame(updateFades);
220
+ }
221
+ if (newItem) list.scrollTop = list.scrollHeight;
222
+ const form = document.createElement('form');
223
+ const input = document.createElement('textarea');
224
+ input.required = true;
225
+ input.rows = 1;
226
+ input.maxLength = 5000;
227
+ input.placeholder = '댓글 추가';
228
+ input.setAttribute('aria-label', '댓글 내용');
229
+ const submit = document.createElement('button');
230
+ submit.textContent = '댓글 등록';
231
+ const error = document.createElement('div');
232
+ error.setAttribute('role', 'alert');
233
+ form.className = 'comment-form';
234
+ submit.className = 'comment-submit';
235
+ submit.setAttribute('aria-label', '댓글 등록');
236
+ 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>';
237
+ submit.disabled = true;
238
+ const avatar = document.createElement('span');
239
+ avatar.className = 'comment-avatar';
240
+ avatar.textContent = '나';
241
+ const row = document.createElement('div');
242
+ row.className = 'comment-input-row';
243
+ const field = document.createElement('div');
244
+ field.className = 'comment-field';
245
+ field.append(input, submit);
246
+ row.append(avatar, field);
247
+ const foot = document.createElement('div');
248
+ foot.className = 'comment-foot';
249
+ const hint = document.createElement('span');
250
+ hint.textContent = '';
251
+ const counter = document.createElement('span');
252
+ foot.append(hint, counter);
253
+ foot.hidden = true;
254
+ input.addEventListener('input', () => {
255
+ submit.disabled = !input.value.trim();
256
+ foot.hidden = input.value.length < 4500;
257
+ counter.textContent = input.value.length >= 4500 ? `${input.value.length.toLocaleString('ko-KR')} / 5,000` : '';
258
+ error.textContent = '';
259
+ input.style.height = 'auto';
260
+ input.style.height = `${Math.min(input.scrollHeight, 160)}px`;
261
+ input.style.overflowY = input.scrollHeight > 160 ? 'auto' : 'hidden';
262
+ });
263
+ input.addEventListener('keydown', (event) => {
264
+ if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
265
+ event.preventDefault();
266
+ if (!submit.disabled) form.requestSubmit();
267
+ }
268
+ });
269
+ form.append(row, foot, error);
270
+ form.onsubmit = async (event) => {
271
+ event.preventDefault();
272
+ submit.disabled = true;
273
+ hint.textContent = '등록 중…';
274
+ foot.hidden = false;
275
+ try {
276
+ const result = await fetch(api, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document: documentId, block: key, quote: draftQuote, body: input.value }) });
277
+ if (!result.ok) throw new Error();
278
+ const newItem = await result.json();
279
+ comments.push(newItem);
280
+ clearDraftHighlight();
281
+ draftQuote = '';
282
+ draw(newItem);
283
+ } catch { error.textContent = '댓글을 저장하지 못했습니다. 다시 시도해 주세요.'; foot.hidden = true; submit.disabled = !input.value.trim(); }
284
+ };
285
+ panel.append(form);
286
+ }
287
+ function openPanel(quote = '', range, focus = true) {
288
+ clearDraftHighlight();
289
+ for (const other of article.querySelectorAll('.comment-anchor > .comment-panel')) other.hidden = true;
290
+ for (const other of article.querySelectorAll('.comment-trigger.is-open')) other.classList.remove('is-open');
291
+ draftQuote = quote;
292
+ showDraftHighlight(block, range);
293
+ panel.hidden = false;
294
+ button.classList.add('is-open');
295
+ document.body.classList.add('comment-card-open');
296
+ panel.querySelector('.comment-list')?.updateFades();
297
+ if (focus) panel.querySelector('textarea').focus();
298
+ }
299
+ button.addEventListener('mousedown', (event) => event.preventDefault());
300
+ button.addEventListener('click', () => {
301
+ const selection = window.getSelection();
302
+ const quote = selection && !selection.isCollapsed && block.contains(selection.anchorNode) && block.contains(selection.focusNode) ? selection.toString().trim().slice(0, 2000) : '';
303
+ if (!panel.hidden) { clearDraftHighlight(); draftQuote = ''; panel.hidden = true; button.classList.remove('is-open'); document.body.classList.remove('comment-card-open'); }
304
+ else openPanel(quote, quote && selection.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined);
305
+ popover.hidden = true;
306
+ });
307
+ draw();
308
+ if (commentId && comments.some((item) => item.id === commentId && item.block === key)) {
309
+ openPanel('', undefined, false);
310
+ const entry = [...panel.querySelectorAll('[data-comment-id]')].find((item) => item.dataset.commentId === commentId);
311
+ requestAnimationFrame(() => entry?.scrollIntoView({ block: 'center' }));
312
+ }
313
+ }
314
+ const alignButtons = () => {
315
+ const right = article.getBoundingClientRect().right;
316
+ for (const wrapper of anchors.keys()) {
317
+ wrapper.style.setProperty('--comment-offset', `${Math.max(0, right - wrapper.getBoundingClientRect().right)}px`);
318
+ wrapper.style.setProperty('--comment-panel-right', `${wrapper.getBoundingClientRect().right - window.innerWidth + 16}px`);
319
+ }
320
+ for (const list of article.querySelectorAll('.comment-list')) list.updateFades();
321
+ };
322
+ article.commentLaneObserver = new ResizeObserver(alignButtons);
323
+ window.addEventListener('resize', alignButtons, { signal: dismissController.signal });
324
+ article.commentLaneObserver.observe(article);
325
+ for (const wrapper of anchors.keys()) article.commentLaneObserver.observe(wrapper);
326
+ for (const list of article.querySelectorAll('.comment-list')) article.commentLaneObserver.observe(list);
327
+ alignButtons();
328
+ const orphaned = comments.filter((item) => !matched.has(item.block));
329
+ if (orphaned.length) {
330
+ const details = document.createElement('details');
331
+ details.className = 'comment-orphans';
332
+ const summary = document.createElement('summary');
333
+ summary.textContent = `위치를 찾을 수 없는 댓글 ${orphaned.length}개`;
334
+ details.append(summary);
335
+ for (const item of orphaned) {
336
+ const entry = document.createElement('div');
337
+ entry.dataset.commentId = item.id;
338
+ const label = document.createElement('strong');
339
+ label.textContent = item.author;
340
+ const body = document.createElement('p');
341
+ body.textContent = `${item.quote ? item.quote + '\n' : ''}${item.body}`;
342
+ entry.append(label, body);
343
+ details.append(entry);
344
+ }
345
+ article.append(details);
346
+ if (commentId && orphaned.some((item) => item.id === commentId)) {
347
+ details.open = true;
348
+ const entry = [...details.querySelectorAll('[data-comment-id]')].find((item) => item.dataset.commentId === commentId);
349
+ requestAnimationFrame(() => entry?.scrollIntoView({ block: 'center' }));
350
+ }
351
+ }
352
+ }
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>