comments.js
JavaScript · 406 рядків
1// Коментарі на порталі: хто увійшов (шапка), виділення → правий клік / кнопка → коментар; підсвітка відкритих,
2// картки «текст змінено» для тих, чию цитату вже не знайдено, згорнутий список «Вирішені (N)» внизу; посилання #C-12.
3// Коміт, до якого прив'язується коментар (один на весь задеплоєний репозиторій), портал кладе в data-атрибут статті — читач його не бачить.
4(function () {
5 var me = null
6 var esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] }) }
7 var api = function (method, url, body) {
8 return fetch(url, { method: method, headers: body ? { 'content-type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined, credentials: 'same-origin' })
9 .then(function (r) { return r.json().then(function (j) { if (!r.ok) throw new Error(j && j.error || r.statusText); return j }) })
10 }
11 var when = function (iso) { try { return new Date(iso).toLocaleString('uk-UA', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }) } catch (e) { return iso } }
12 var here = function () { return location.pathname + location.search }
13
14 // ── шапка: хто я
15 // віджет «хто увійшов» у шапці порталу — розширення додає його саме
16 var userBox = document.getElementById('user')
17 if (!userBox) {
18 var top = document.querySelector('header.top'), menuBtn = top && top.querySelector('.menu')
19 if (top) { userBox = document.createElement('div'); userBox.className = 'user'; userBox.id = 'user'; top.insertBefore(userBox, menuBtn) }
20 }
21 var meReady = api('GET', '/api/me').catch(function () { return null }).then(function (u) {
22 me = u
23 if (userBox) {
24 userBox.innerHTML = u
25 ? '<a class="who" href="/account">' + esc(u.name) + '</a>' + '<span>' + (u.approved ? '' : ' <span class="muted">(чекає підтвердження)</span>') + '</span>'
26 + (u.role === 'admin' ? ' <a href="/users">користувачі' + (u.pending ? ' <b class="pill">' + u.pending + '</b>' : '') + '</a>' : '')
27 + ' <a href="/logout?next=' + encodeURIComponent(here()) + '">вийти</a>'
28 : '<a href="/login?next=' + encodeURIComponent(here()) + '">Увійти</a>'
29 }
30 return u
31 })
32
33 var article = document.querySelector('article.md[data-path]')
34 if (!article) return
35 var path = article.dataset.path
36
37 // ── текст статті як бачить читач (без «#» у заголовках)
38 function textNodes() {
39 var out = [], pos = 0
40 var w = document.createTreeWalker(article, NodeFilter.SHOW_TEXT, {
41 acceptNode: function (n) { return n.parentElement.closest('.anchor, .cbar, .cthreads, .cresolved') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT },
42 })
43 var n
44 while ((n = w.nextNode())) { out.push({ node: n, start: pos }); pos += n.data.length }
45 return { nodes: out, text: out.map(function (x) { return x.node.data }).join('') }
46 }
47 function offsetOf(idx, container, offset) {
48 if (container.nodeType !== 3) {
49 var child = container.childNodes[offset]
50 if (!child) { // кінець елемента — після останнього текстового вузла всередині
51 var last = null
52 idx.nodes.forEach(function (x) { if (container.contains(x.node)) last = x })
53 return last ? last.start + last.node.data.length : -1
54 }
55 for (var i = 0; i < idx.nodes.length; i++) {
56 var p = child.compareDocumentPosition(idx.nodes[i].node)
57 if (idx.nodes[i].node === child || p & Node.DOCUMENT_POSITION_FOLLOWING || p & Node.DOCUMENT_POSITION_CONTAINED_BY) return idx.nodes[i].start
58 }
59 return -1
60 }
61 for (var j = 0; j < idx.nodes.length; j++) if (idx.nodes[j].node === container) return idx.nodes[j].start + offset
62 return -1
63 }
64 var flat = function (s) { return s.replace(/\s+/g, ' ') }
65 /** Де цитата в поточному тексті: збіг з контекстом до/після важить більше; пробіли не важливі. */
66 function locate(idx, c) {
67 var map = [], t = ''
68 for (var i = 0; i < idx.text.length; i++) {
69 var ch = /\s/.test(idx.text[i]) ? ' ' : idx.text[i]
70 if (ch === ' ' && t[t.length - 1] === ' ') continue
71 t += ch; map.push(i)
72 }
73 var q = flat(c.quote).trim(), pre = flat(c.prefix || ''), suf = flat(c.suffix || '')
74 if (!q) return null
75 var best = -1, score = -1, from = 0, at
76 while ((at = t.indexOf(q, from)) >= 0) {
77 var s = 0
78 if (pre && t.slice(Math.max(0, at - pre.length), at).trim() === pre.trim()) s += 2
79 if (suf && t.slice(at + q.length, at + q.length + suf.length).trim() === suf.trim()) s += 1
80 if (s > score) { score = s; best = at }
81 from = at + 1
82 }
83 if (best < 0) return null
84 return { start: map[best], end: map[best + q.length - 1] + 1 }
85 }
86 function wrap(start, end, c) {
87 var idx = textNodes(), first = null
88 idx.nodes.forEach(function (x) {
89 var s = Math.max(start, x.start), e = Math.min(end, x.start + x.node.data.length)
90 if (s >= e || !x.node.data.slice(s - x.start, e - x.start).trim()) return
91 var node = x.node
92 if (e - x.start < node.data.length) node.splitText(e - x.start)
93 if (s - x.start > 0) node = node.splitText(s - x.start)
94 var m = document.createElement('mark')
95 m.className = 'cmark'; m.dataset.ref = c.ref; m.title = c.ref + ' · ' + c.author + ': ' + c.text
96 node.parentNode.insertBefore(m, node); m.appendChild(node)
97 if (c.state === 'closed') m.classList.add('done')
98 if (!first) first = m
99 })
100 return first
101 }
102 function headingFor(node) {
103 var hs = article.querySelectorAll('h1, h2, h3, h4'), found = null
104 hs.forEach(function (h) { if (h.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING) found = h })
105 return found
106 }
107 var headingText = function (h) { return h ? h.textContent.replace(/^#/, '').trim() : '' }
108
109 // ── чат під абзацом: текст досліду — повідомлення «з одного боку», коментар — бульбашка справа під своїм абзацом,
110 // відповідь (Claude чи адмін) — бульбашка зліва під коментарем; вирішені згорнуті в рядок на своєму місці. Клік — підсвітка абзацу чи виділеного.
111 function thread(c, lost) {
112 var t = document.createElement('div')
113 t.className = 'cthread' + (c.state === 'closed' ? ' closed' : '') + (lost ? ' lost' : '')
114 t.id = c.ref; t.dataset.ref = c.ref
115 var reopened = c.log.filter(function (l) { return l.action === 'reopen' && l.text }).pop()
116 t.innerHTML = '<div class="cb mine"><div class="ch"><a href="#' + c.ref + '">' + c.ref + '</a> · <b>' + esc(c.author) + '</b> <span class="muted">' + when(c.created_at) + '</span>'
117 + (lost ? ' <span class="badge draft">текст змінено</span>' : '') + '</div>'
118 + (lost ? '<q class="cq">' + esc(c.quote) + '</q>' : '')
119 + '<div class="ct">' + esc(c.text) + '</div>'
120 + (reopened ? '<div class="muted">↺ знову відкрито (' + esc(reopened.by) + '): ' + esc(reopened.text) + '</div>' : '')
121 + '<div class="cact"></div><div class="cold"></div></div>'
122 + (c.state === 'closed' ? '<div class="cb reply"><div class="ch"><b>' + esc(c.closed_by) + '</b> <span class="muted">' + when(c.closed_at) + '</span> <span class="badge ok">вирішено</span></div>'
123 + '<div class="ct">' + esc(c.answer) + '</div>'
124 + (c.answer_where ? '<div>→ ' + linkIds(c.answer_where) + '</div>' : '') + (c.answer_commit ? '<div class="muted">коміт <code>' + esc(c.answer_commit.slice(0, 8)) + '</code></div>' : '')
125 + '<div class="cact"></div></div>' : '')
126 var act = t.querySelector('.cb.mine .cact')
127 if (lost) button(act, 'Як було', function () { showOld(c, t.querySelector('.cold')) })
128 if (c.state === 'open' && me && me.canResolve) button(act, 'Закрити з відповіддю', function () { closeForm(c, act) })
129 if (c.state === 'closed' && me && me.canComment) button(t.querySelector('.cb.reply .cact'), 'Відкрити знову', function () {
130 var why = prompt('Чому відкрити знову?', '')
131 if (why !== null) api('POST', '/api/comments/' + c.ref + '/reopen', { text: why }).then(load, fail)
132 })
133 t.addEventListener('click', function (e) {
134 if (e.target.closest('a, button, form, textarea, input')) return
135 focus(c.ref, !t.classList.contains('focused'))
136 })
137 return t
138 }
139 function button(parent, label, fn) {
140 var b = document.createElement('button'); b.type = 'button'; b.className = 'btn ghost small'; b.textContent = label; b.onclick = fn; parent.appendChild(b)
141 }
142 /** Підсвітити текст коментаря (і зняти з інших); прокрутити до нього, якщо його не видно. */
143 function unwrap(m) { var p = m.parentNode; while (m.firstChild) p.insertBefore(m.firstChild, m); p.removeChild(m); p.normalize() }
144 function focus(ref, on, noScroll) {
145 article.querySelectorAll('mark.cmark.temp').forEach(unwrap)
146 article.querySelectorAll('mark.cmark.active').forEach(function (m) { m.classList.remove('active') })
147 article.querySelectorAll('.cthread.focused').forEach(function (x) { x.classList.remove('focused') })
148 if (!on) return
149 // вирішений у тексті не підсвічений — знаходимо його текст на час кліку
150 var c = byRef[ref]
151 if (c && c.state === 'closed') {
152 var at = locate(textNodes(), c), first = at && wrap(at.start, at.end, c)
153 article.querySelectorAll('mark.cmark[data-ref="' + ref + '"]').forEach(function (m) { m.classList.add('temp') })
154 if (!first) { var t0 = document.getElementById(ref); if (t0) t0.classList.add('focused', 'gone'); setTimeout(function () { t0 && t0.classList.remove('gone') }, 1500); return }
155 }
156 var marks = article.querySelectorAll('mark.cmark[data-ref="' + ref + '"]'), t = document.getElementById(ref)
157 marks.forEach(function (m) { m.classList.add('active') })
158 if (t) t.classList.add('focused')
159 if (marks.length && !noScroll) {
160 var r = marks[0].getBoundingClientRect()
161 if (r.top < 60 || r.bottom > window.innerHeight) marks[0].scrollIntoView({ block: 'center', behavior: 'smooth' })
162 }
163 }
164 function linkIds(s) {
165 return esc(s).replace(/\b([A-Z]{1,4}-\d{1,4})(\.\d{1,3})?\b/g, function (m, id, sub) {
166 var known = Array.prototype.find.call(document.querySelectorAll('a.xref'), function (x) { return x.textContent.split('.')[0] === id })
167 if (!known) return m
168 var href = known.getAttribute('href').split('#')[0]
169 return '<a href="' + href + (sub ? '#' + id + sub : '') + '">' + m + '</a>'
170 })
171 }
172 function showOld(c, box) {
173 box.textContent = '…'
174 api('GET', '/api/comments/' + c.ref + '/context').then(function (r) {
175 box.innerHTML = r.found ? '<div class="muted">У коміті <code>' + esc(c.commit.slice(0, 8)) + '</code>:</div><p>…' + esc(r.before) + '<mark>' + esc(r.quote) + '</mark>' + esc(r.after) + '…</p>'
176 : '<div class="muted">' + esc(r.note) + '</div>'
177 }, function (e) { box.textContent = e.message })
178 }
179 function closeForm(c, parent) {
180 var f = document.createElement('form'); f.className = 'cform'
181 f.innerHTML = '<textarea name="answer" rows="3" placeholder="Відповідь: що вирішили" required></textarea><input name="where" placeholder="Де записано: R-33.2, розділ…"><input name="commit" placeholder="Коміт (необов\'язково)"><button class="btn small">Закрити</button>'
182 f.onsubmit = function (e) { e.preventDefault(); api('POST', '/api/comments/' + c.ref + '/close', { answer: f.answer.value, where: f.where.value, commit: f.commit.value }).then(load, fail) }
183 parent.appendChild(f)
184 }
185 var fail = function (e) { alert(e.message) }
186 function hidePop() {}
187
188 /** Куди ставити розмову: під абзацом; рядок таблиці — під таблицею; пункт списку — у кінці пункту. */
189 function holderFor(mark) {
190 var b = mark.closest('li, tr, p, h1, h2, h3, h4, h5, pre, blockquote')
191 var after = !b ? null : b.tagName === 'TR' ? (b.closest('.table-wrap') || b.closest('table'))
192 : b.tagName === 'P' && b.parentElement.closest('li, blockquote') ? b.parentElement.closest('li, blockquote') : b
193 if (!after) return null
194 if (after.tagName === 'LI') {
195 var inner = after.querySelector(':scope > .cthreads')
196 if (!inner) { inner = document.createElement('div'); inner.className = 'cthreads'; after.appendChild(inner) }
197 return inner
198 }
199 var next = after.nextElementSibling
200 if (next && next.classList.contains('cthreads')) return next
201 var h = document.createElement('div'); h.className = 'cthreads'
202 after.insertAdjacentElement('afterend', h)
203 return h
204 }
205
206 /** У змісті праворуч — список відкритих коментарів; немає змісту — створюємо колонку. */
207 function tocList(open, lost) {
208 if (!open.length) return
209 var toc = document.querySelector('nav.toc')
210 if (!toc) {
211 var shell = document.querySelector('.shell')
212 if (!shell) return
213 toc = document.createElement('nav'); toc.className = 'toc'; toc.setAttribute('aria-label', 'Зміст')
214 shell.appendChild(toc); shell.classList.add('has-toc')
215 }
216 var order = Array.prototype.map.call(article.querySelectorAll('.cthread'), function (t) { return t.id })
217 var sorted = open.slice().sort(function (a, b) { return order.indexOf(a.ref) - order.indexOf(b.ref) })
218 var box = document.createElement('div'); box.className = 'copen'
219 box.innerHTML = '<div class="toc-h">Відкриті коментарі (' + open.length + ')</div><ul>' + sorted.map(function (c) {
220 return '<li><a href="#' + c.ref + '" title="' + esc(c.text) + '"><b>' + c.ref + '</b> ' + esc(c.author) + (lost.indexOf(c) >= 0 ? ' · <i>текст змінено</i>' : '') + '<span>' + esc(c.text.length > 70 ? c.text.slice(0, 70) + '…' : c.text) + '</span></a></li>'
221 }).join('') + '</ul>'
222 toc.appendChild(box)
223 }
224
225 // ── завантаження й розкладка коментарів
226 var byRef = {}
227 function clear() {
228 article.querySelectorAll('mark.cmark').forEach(unwrap)
229 article.querySelectorAll('.cbar, .cthreads, .cthread, .cresolved').forEach(function (x) { x.remove() })
230 var old = document.querySelector('.toc .copen'); if (old) old.remove()
231 }
232 function load() {
233 return Promise.all([api('GET', '/api/comments?path=' + encodeURIComponent(path)), meReady]).then(function (r) {
234 var list = r[0]
235 clear(); byRef = {}
236 list.forEach(function (c) { byRef[c.ref] = c })
237 var open = list.filter(function (c) { return c.state === 'open' }), closed = list.filter(function (c) { return c.state === 'closed' })
238 // у тексті — лише відкриті
239 var placed = [], lostOpen = []
240 open.forEach(function (c) {
241 var at = locate(textNodes(), c), first = at && wrap(at.start, at.end, c)
242 if (first) placed.push([c, first]); else lostOpen.push(c)
243 })
244 // у порядку тексту, щоб розмови під одним абзацом ішли за порядком цитат
245 placed.sort(function (a, b) { return a[1].compareDocumentPosition(b[1]) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1 })
246 // розмова — після останнього абзацу виділення (виділено 3 абзаци — під третім)
247 placed.forEach(function (p) {
248 var ms = article.querySelectorAll('mark.cmark[data-ref="' + p[0].ref + '"]')
249 var h = holderFor(ms[ms.length - 1] || p[1])
250 if (h) h.appendChild(thread(p[0], false)); else lostOpen.push(p[0])
251 })
252 // відкриті без цитати — на початку свого розділу
253 lostOpen.forEach(function (c) {
254 var h = Array.prototype.find.call(article.querySelectorAll('h1, h2, h3, h4'), function (x) { return headingText(x) === c.heading })
255 var box = document.createElement('div'); box.className = 'cthreads'; box.appendChild(thread(c, true))
256 if (h) h.insertAdjacentElement('afterend', box); else article.insertBefore(box, article.firstChild.nextSibling)
257 })
258 var bar = document.createElement('div'); bar.className = 'cbar'
259 bar.innerHTML = (list.length ? 'Коментарі: <b>відкритих ' + open.length + '</b> · <a href="#cdone">вирішених ' + closed.length + '</a>' + (lostOpen.length ? ' · <span class="muted">текст змінено ' + lostOpen.length + '</span>' : '') : 'Коментарів немає')
260 + ' · <span class="muted">' + (me && me.canComment ? 'виділіть текст або клацніть на абзаці правою кнопкою, щоб коментувати' : me ? 'обліковий запис чекає підтвердження' : '<a href="/login?next=' + encodeURIComponent(here()) + '">увійдіть</a>, щоб коментувати') + '</span>'
261 + ' · <a href="/comments">усі коментарі</a>'
262 var h1 = article.querySelector('h1')
263 if (h1) h1.insertAdjacentElement('afterend', bar); else article.insertBefore(bar, article.firstChild)
264 // вирішені — у самому низу, хронологією, розкриті: питання → відповідь → питання → …
265 if (closed.length) {
266 var done = document.createElement('section'); done.className = 'cresolved'; done.id = 'cdone'
267 done.innerHTML = '<h2>Вирішені коментарі (' + closed.length + ')</h2>'
268 var box = document.createElement('div'); box.className = 'cthreads'
269 closed.slice().sort(function (a, b) { return a.created_at < b.created_at ? -1 : 1 }).forEach(function (c) { box.appendChild(thread(c, false)) })
270 done.appendChild(box)
271 article.appendChild(done)
272 }
273 tocList(open, lostOpen)
274 jump()
275 }).catch(function (e) { console.warn('comments', e) })
276 }
277 function jump() {
278 var id = decodeURIComponent(location.hash.slice(1))
279 if (!/^C-\d+$/.test(id)) return
280 var el = document.getElementById(id)
281 if (!el) return
282 focus(id, true, true)
283 // до початку тексту коментаря (абзац чи виділене — одразу на екрані), а не до самої бульбашки; без тексту — до бульбашки
284 var m = article.querySelector('mark.cmark[data-ref="' + id + '"]')
285 var target = m ? (m.closest('li, tr, p, h1, h2, h3, h4, h5, pre, blockquote') || m) : el
286 var top = target.getBoundingClientRect().top + window.scrollY - 72
287 if (m && m.getBoundingClientRect().top - target.getBoundingClientRect().top > window.innerHeight / 3) top = m.getBoundingClientRect().top + window.scrollY - 120
288 window.scrollTo({ top: Math.max(0, top), behavior: 'auto' })
289 }
290 window.addEventListener('hashchange', jump)
291 // повторний клік на тому ж коментарі в змісті теж прокручує (hashchange тоді не спрацьовує)
292 document.addEventListener('click', function (e) {
293 var a = e.target.closest('.toc .copen a[href^="#C-"]')
294 if (!a) return
295 e.preventDefault()
296 history.replaceState(null, '', a.getAttribute('href'))
297 jump()
298 })
299 // клік на підсвітці — до розмови під абзацом
300 article.addEventListener('click', function (e) {
301 var m = e.target.closest('mark.cmark')
302 if (!m || window.getSelection().toString()) return
303 var t = document.getElementById(m.dataset.ref)
304 if (!t) return
305 e.preventDefault()
306 focus(m.dataset.ref, true)
307 var r = t.getBoundingClientRect()
308 if (r.top < 60 || r.bottom > window.innerHeight) t.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
309 })
310
311 // ── новий коментар: виділення → правий клік (або кнопка біля виділення)
312 var menu = null, fab = null
313 function hideMenu() { if (menu) { menu.remove(); menu = null } article.querySelectorAll('.ctarget').forEach(function (x) { x.classList.remove('ctarget') }) }
314 function hideFab() { if (fab) { fab.remove(); fab = null } }
315 /** Цитата з діапазону тексту статті: точні межі в тексті, контекст до/після, розділ. */
316 function fromRange(range) {
317 if (!article.contains(range.commonAncestorContainer)) return null
318 var idx = textNodes()
319 var s = offsetOf(idx, range.startContainer, range.startOffset), e = offsetOf(idx, range.endContainer, range.endOffset)
320 if (s < 0 || e <= s) return null
321 var quote = idx.text.slice(s, e)
322 if (!quote.trim()) return null
323 var lead = quote.length - quote.replace(/^\s+/, '').length
324 s += lead; quote = quote.trim(); e = s + quote.length
325 return { quote: quote, prefix: idx.text.slice(Math.max(0, s - 40), s), suffix: idx.text.slice(e, e + 40), heading: headingText(headingFor(range.startContainer)), rect: range.getBoundingClientRect() }
326 }
327 function selected() {
328 var sel = window.getSelection()
329 if (!sel.rangeCount || sel.isCollapsed) return null
330 return fromRange(sel.getRangeAt(0))
331 }
332 // без виділення — увесь абзац (пункт списку, рядок таблиці, заголовок, плашка, блок коду) під курсором
333 var BLOCK = 'p, li, tr, h1, h2, h3, h4, h5, pre, blockquote'
334 var BLOCK_NAME = { P: 'абзац', LI: 'пункт', TR: 'рядок таблиці', PRE: 'блок коду', BLOCKQUOTE: 'цитату' }
335 function blockAt(target) {
336 if (target.closest && target.closest('.cthreads, .cbar, .cresolved')) return null
337 var b = target.closest && target.closest(BLOCK)
338 if (!b || !article.contains(b) || b.closest('.cbar, .cthreads, .cresolved')) return null
339 if (b.tagName === 'P' && b.parentElement.closest('li, blockquote') && article.contains(b.parentElement)) b = b.parentElement.closest('li, blockquote')
340 var r = document.createRange(); r.selectNodeContents(b)
341 var s = fromRange(r)
342 if (s) { s.block = b; s.what = BLOCK_NAME[b.tagName] || 'заголовок' }
343 return s
344 }
345 function menuAt(x, y, items) {
346 hideMenu()
347 menu = document.createElement('div'); menu.className = 'cmenu'
348 items.forEach(function (it) { var b = document.createElement('button'); b.type = 'button'; b.textContent = it[0]; b.onclick = function () { hideMenu(); it[1]() }; menu.appendChild(b) })
349 document.body.appendChild(menu)
350 menu.style.left = Math.min(x, window.scrollX + document.documentElement.clientWidth - menu.offsetWidth - 8) + 'px'; menu.style.top = y + 'px'
351 }
352 function actionsFor(s) {
353 if (!me) return [['Увійдіть, щоб коментувати', function () { location.href = '/login?next=' + encodeURIComponent(here()) }]]
354 if (!me.canComment) return [['Обліковий запис чекає підтвердження', function () {}]]
355 return [['💬 Коментувати ' + (s.block ? s.what : 'виділене'), function () { compose(s) }]]
356 }
357 // правий клік: виділений текст, а без виділення — абзац під курсором; Shift + правий клік — звичайне меню браузера
358 article.addEventListener('contextmenu', function (e) {
359 if (e.shiftKey) return
360 var s = selected() || blockAt(e.target)
361 if (!s) return
362 e.preventDefault(); hideFab()
363 var items = actionsFor(s).concat([['Копіювати', function () { navigator.clipboard && navigator.clipboard.writeText(s.quote) }]])
364 var a = e.target.closest('a[href]')
365 if (a) items.push(['Відкрити посилання в новій вкладці', function () { window.open(a.href, '_blank', 'noopener') }])
366 menuAt(e.pageX, e.pageY, items)
367 if (s.block) s.block.classList.add('ctarget')
368 var hint = document.createElement('div'); hint.className = 'muted chint'; hint.textContent = 'Shift + правий клік — меню браузера'; menu.appendChild(hint)
369 })
370 document.addEventListener('mousedown', function (e) { if (menu && !menu.contains(e.target)) hideMenu(); if (fab && !fab.contains(e.target)) hideFab() })
371 document.addEventListener('keydown', function (e) { if (e.key === 'Escape') { hideMenu(); hideFab(); hidePop() } })
372 document.addEventListener('selectionchange', function () {
373 clearTimeout(document._cfab)
374 document._cfab = setTimeout(function () {
375 var s = selected()
376 if (!s || menu || document.querySelector('.cdialog')) { if (!s) hideFab(); return }
377 hideFab()
378 fab = document.createElement('button'); fab.type = 'button'; fab.className = 'cfab'; fab.textContent = '💬'; fab.title = 'Коментувати виділене'
379 fab.onmousedown = function (e) { e.preventDefault() }
380 fab.onclick = function () { var a = actionsFor(s); hideFab(); a.length === 1 ? a[0][1]() : null }
381 document.body.appendChild(fab)
382 fab.style.left = (window.scrollX + s.rect.right + 4) + 'px'; fab.style.top = (window.scrollY + s.rect.top - 34) + 'px'
383 }, 250)
384 })
385 function compose(s) {
386 var dlg = document.createElement('dialog'); dlg.className = 'cdialog'
387 dlg.innerHTML = '<form method="dialog"><h3>Коментар' + (s.block ? ' — ' + s.what : '') + '</h3><q class="cq">' + esc(s.quote.length > 600 ? s.quote.slice(0, 600) + '…' : s.quote) + '</q>'
388 + (s.heading ? '<div class="muted">розділ: ' + esc(s.heading) + '</div>' : '')
389 + '<textarea name="text" rows="5" required placeholder="Питання, сумнів, що уточнити чи доопрацювати"></textarea>'
390 + '<div class="cact"><button class="btn" value="ok">Зберегти</button> <button class="btn ghost" value="cancel" formnovalidate>Скасувати</button></div></form>'
391 document.body.appendChild(dlg)
392 dlg.showModal()
393 dlg.querySelector('textarea').focus()
394 dlg.addEventListener('close', function () {
395 var text = dlg.querySelector('textarea').value.trim()
396 if (dlg.returnValue === 'ok' && text) {
397 api('POST', '/api/comments', { path: path, commit: article.dataset.commit, quote: s.quote, prefix: s.prefix, suffix: s.suffix, heading: s.heading, text: text })
398 .then(function (c) { window.getSelection().removeAllRanges(); history.replaceState(null, '', '#' + c.ref); return load() }, fail)
399 }
400 dlg.remove()
401 })
402 }
403
404 load()
405})()
406