'use strict'; /* 홈페이지 게시판. 주소의 # 뒤로 화면을 나눈다. * #/b/게시판 글 목록(?p=쪽&q=검색) #/p/번호 글 보기와 댓글 * #/w/게시판 새 글 쓰기 #/e/번호 글 고치기 * 로그인은 홈페이지 첫 화면과 같은 쿠키를 쓴다. 글과 댓글은 모두 textContent로 넣어 HTML로 해석되지 않는다. */ (function () { const $ = id => document.getElementById(id); const KST = new Intl.DateTimeFormat('ko-KR', { timeZone: 'Asia/Seoul', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }); const KST_DAY = new Intl.DateTimeFormat('ko-KR', { timeZone: 'Asia/Seoul', month: '2-digit', day: '2-digit' }); let info = null; function el(tag, text, className) { const node = document.createElement(tag); if (text !== undefined && text !== null) node.textContent = String(text); if (className) node.className = className; return node; } function link(text, href, className) { const node = el('a', text, className); node.href = href; return node; } function button(text, action, className) { const node = el('button', text, className); node.type = 'button'; node.onclick = action; return node; } function when(seconds) { return KST.format(new Date(seconds * 1000)); } function short(seconds) { const diff = Date.now() / 1000 - seconds; if (diff < 3600) return Math.max(1, Math.floor(diff / 60)) + '분 전'; if (diff < 86400) return Math.floor(diff / 3600) + '시간 전'; return KST_DAY.format(new Date(seconds * 1000)); } async function api(path, body) { const options = { headers: { 'X-Duty-Request': '1' }, cache: 'no-store' }; if (body !== undefined) { options.method = 'POST'; options.headers['Content-Type'] = 'application/json'; options.body = JSON.stringify(body); } const response = await fetch('api/' + path, options); let result = {}; try { result = await response.json(); } catch {} if (!response.ok) { const error = new Error(typeof result.detail === 'string' ? result.detail : '요청을 처리하지 못했습니다.'); error.status = response.status; throw error; } return result; } function notify(message) { $('toast').textContent = message; $('toast').hidden = false; clearTimeout(notify.timer); notify.timer = setTimeout(() => { $('toast').hidden = true; }, 4000); } function confirmAction(message, label) { return new Promise(resolve => { const dialog = $('confirm-dialog'); $('confirm-message').textContent = message; $('confirm-accept').textContent = label; const finish = value => { dialog.close(); resolve(value); }; $('confirm-cancel').onclick = () => finish(false); $('confirm-accept').onclick = () => finish(true); dialog.oncancel = () => resolve(false); dialog.showModal(); }); } // 본문의 https 주소만 링크로 바꾼다. 줄바꿈은 CSS(pre-wrap)로 그대로 보인다. function bodyText(parent, text) { for (const part of String(text).split(/(https:\/\/[^\s<>"']+)/g)) { if (!part) continue; if (/^https:\/\//.test(part)) { const a = link(part, part); a.target = '_blank'; a.rel = 'noopener noreferrer nofollow'; parent.append(a); } else parent.append(part); } return parent; } function author(row) { const span = el('span', row.authorName, 'author'); if (row.authorAdmin) span.append(el('em', '운영진', 'tag')); return span; } function show(...nodes) { $('board-view').replaceChildren(...nodes); window.scrollTo(0, 0); } function problem(error) { if (error.status === 401) { show(el('p', error.message, 'notice-box'), link('홈페이지에서 로그인하기', './', 'button-link')); } else show(el('p', error.message, 'notice-box'), link('게시판 처음으로', '#/', 'button-link secondary')); } async function loadInfo() { info = await api('boards'); $('board-me').textContent = info.me ? info.me.name + ' 님' : ''; $('board-login').hidden = Boolean(info.me); const tabs = $('board-tabs'); tabs.replaceChildren(); for (const board of info.boards) tabs.append(link(board.name, '#/b/' + board.id)); } function markTab(boardId) { for (const tab of $('board-tabs').children) tab.setAttribute('aria-current', tab.getAttribute('href') === '#/b/' + boardId ? 'page' : 'false'); } // ------------------------------------------------------------ 글 목록 async function listView(boardId, params) { const page = Math.max(1, Number(params.get('p')) || 1), q = params.get('q') || ''; markTab(boardId); const data = await api('boards/' + encodeURIComponent(boardId) + '/posts?page=' + page + '&q=' + encodeURIComponent(q)); const head = el('div', null, 'board-head'); const title = el('div'); title.append(el('h2', data.board.name), el('p', data.board.description, 'small')); head.append(title); if (data.board.canWrite) head.append(link('글쓰기', '#/w/' + boardId, 'button-link')); else if (!info.me && data.board.writeLevel === 'member') head.append(link('로그인하고 글쓰기', './', 'button-link secondary')); const search = el('form', null, 'board-search'); const input = el('input'); input.type = 'search'; input.maxLength = 40; input.value = q; input.placeholder = '제목이나 내용 찾기'; input.setAttribute('aria-label', '글 찾기'); const go = el('button', '찾기', 'secondary'); go.type = 'submit'; search.append(input, go); search.onsubmit = event => { event.preventDefault(); location.hash = '#/b/' + boardId + (input.value.trim() ? '?q=' + encodeURIComponent(input.value.trim()) : ''); }; const list = el('ul', null, 'post-list'); if (!data.posts.length) list.append(el('li', q ? '찾는 글이 없습니다.' : '아직 글이 없습니다. 첫 글을 남겨 주세요.', 'empty')); for (const post of data.posts) { const item = el('li', null, post.pinned ? 'pinned' : ''); const a = link('', '#/p/' + post.id, 'post-link'); const line = el('span', null, 'post-title'); if (post.pinned) line.append(el('em', '고정', 'tag accent')); line.append(post.title); if (post.comments) line.append(el('span', '[' + post.comments + ']', 'comment-count')); const meta = el('span', null, 'post-meta'); meta.append(author(post), el('span', short(post.created))); a.append(line, meta); item.append(a); list.append(item); } const pages = Math.max(1, Math.ceil(data.total / data.pageSize)); const pager = el('div', null, 'board-pager'); const base = '#/b/' + boardId + '?' + (q ? 'q=' + encodeURIComponent(q) + '&' : '') + 'p='; if (page > 1) pager.append(link('이전', base + (page - 1), 'button-link secondary')); pager.append(el('span', page + ' / ' + pages + '쪽 · 글 ' + data.total + '개', 'small')); if (page < pages) pager.append(link('다음', base + (page + 1), 'button-link secondary')); show(head, search, list, pager); } // ------------------------------------------------------------ 글 보기 async function postView(postId) { const data = await api('posts/' + postId); const post = data.post, board = data.board; markTab(board.id); const article = el('article', null, 'post-view' + (post.state !== 'open' ? ' muted-post' : '')); const top = el('p', null, 'post-board'); top.append(link(board.name, '#/b/' + board.id)); const title = el('h2'); if (post.pinned) title.append(el('em', '고정', 'tag accent')); title.append(post.title); const meta = el('p', null, 'post-meta'); meta.append(author(post), el('span', when(post.created))); if (post.updated > post.created + 60) meta.append(el('span', '고친 때 ' + when(post.updated))); if (post.state !== 'open') meta.append(el('em', post.state === 'hidden' ? '운영진이 숨긴 글' : '지운 글', 'tag warn')); const body = bodyText(el('div', null, 'post-body'), post.body); const actions = el('div', null, 'post-actions'); actions.append(link('목록', '#/b/' + board.id, 'button-link secondary')); if (post.canEdit && post.state !== 'deleted') { actions.append(link('고치기', '#/e/' + post.id, 'button-link secondary')); actions.append(button('지우기', async () => { if (!await confirmAction('이 글을 지울까요? 댓글도 함께 보이지 않게 됩니다.', '지우기')) return; try { await api('posts/' + post.id, { action: 'delete' }); notify('글을 지웠습니다.'); location.hash = '#/b/' + board.id; } catch (error) { notify(error.message); } }, 'secondary danger')); } if (info.me && info.me.admin) { const admin = (label, action) => button(label, async () => { try { await api('admin/board-post/' + post.id, { action }); notify({ pin: '맨 위에 고정했습니다.', unpin: '고정을 풀었습니다.', hide: '숨겼습니다.', show: '다시 보이게 했습니다.', restore: '되살렸습니다.' }[action]); route(); } catch (error) { notify(error.message); } }, 'secondary'); actions.append(admin(post.pinned ? '고정 해제' : '맨 위 고정', post.pinned ? 'unpin' : 'pin')); if (post.state === 'open') actions.append(admin('숨기기', 'hide')); else actions.append(admin('다시 보이기', post.state === 'hidden' ? 'show' : 'restore')); } article.append(top, title, meta, body, actions); show(article, commentsView(data)); } function commentsView(data) { const box = el('section', null, 'comments'); box.append(el('h3', '댓글 ' + data.comments.filter(row => row.state === 'open').length + '개')); const list = el('ul', null, 'comment-list'); for (const row of data.comments) { const item = el('li', null, row.state !== 'open' ? 'muted-post' : ''); const meta = el('p', null, 'post-meta'); meta.append(author(row), el('span', when(row.created))); if (row.state !== 'open') meta.append(el('em', row.state === 'hidden' ? '숨김' : '지움', 'tag warn')); const body = bodyText(el('div', null, 'comment-body'), row.body); item.append(meta, body); const tools = el('div', null, 'comment-tools'); if (row.canEdit && row.state === 'open') { tools.append(button('고치기', () => editComment(item, row), 'text-button')); tools.append(button('지우기', async () => { if (!await confirmAction('이 댓글을 지울까요?', '지우기')) return; try { await api('comments/' + row.id, { action: 'delete' }); notify('댓글을 지웠습니다.'); route(); } catch (error) { notify(error.message); } }, 'text-button')); } if (info.me && info.me.admin) { const action = row.state === 'open' ? 'hide' : row.state === 'hidden' ? 'show' : 'restore'; tools.append(button(row.state === 'open' ? '숨기기' : '다시 보이기', async () => { try { await api('admin/board-comment/' + row.id, { action }); route(); } catch (error) { notify(error.message); } }, 'text-button')); } if (tools.children.length) item.append(tools); list.append(item); } if (!data.comments.length) list.append(el('li', '아직 댓글이 없습니다.', 'empty')); box.append(list); if (data.board.canComment && data.post.state === 'open') box.append(commentForm(data.post.id)); else if (!info.me && data.board.commentLevel === 'member') box.append(el('p', '로그인하면 댓글을 쓸 수 있습니다.', 'small')); return box; } function counter(input, limit) { const count = el('span', '0 / ' + limit.toLocaleString('ko-KR'), 'small counter'); input.addEventListener('input', () => { count.textContent = input.value.length.toLocaleString('ko-KR') + ' / ' + limit.toLocaleString('ko-KR'); }); return count; } function commentForm(postId) { const form = el('form', null, 'comment-form'); const text = el('textarea'); text.rows = 3; text.maxLength = info.limits.comment; text.placeholder = '댓글을 남겨 주세요'; text.setAttribute('aria-label', '댓글'); text.required = true; const send = el('button', '댓글 쓰기'); send.type = 'submit'; const row = el('div', null, 'form-row'); row.append(counter(text, info.limits.comment), send); form.append(text, row); form.onsubmit = async event => { event.preventDefault(); send.disabled = true; try { await api('posts/' + postId + '/comments', { body: text.value }); notify('댓글을 남겼습니다.'); route(); } catch (error) { notify(error.message); send.disabled = false; } }; return form; } function editComment(item, row) { const form = el('form', null, 'comment-form'); const text = el('textarea'); text.rows = 3; text.maxLength = info.limits.comment; text.value = row.body; text.setAttribute('aria-label', '댓글 고치기'); const save = el('button', '저장'); save.type = 'submit'; const cancel = button('취소', () => route(), 'secondary'); const actions = el('div', null, 'form-row'); actions.append(cancel, save); form.append(text, actions); form.onsubmit = async event => { event.preventDefault(); try { await api('comments/' + row.id, { action: 'edit', body: text.value }); notify('댓글을 고쳤습니다.'); route(); } catch (error) { notify(error.message); } }; item.replaceChildren(form); text.focus(); } // ------------------------------------------------------------ 글쓰기와 고치기 async function writeView(boardId, postId) { if (!info.me) { problem(Object.assign(new Error('회원 로그인 후 글을 쓸 수 있습니다.'), { status: 401 })); return; } let post = null, board = info.boards.find(item => item.id === boardId); if (postId) { const data = await api('posts/' + postId); post = data.post; board = data.board; } if (!board) { problem(new Error('게시판을 찾을 수 없습니다.')); return; } markTab(board.id); const form = el('form', null, 'write-form'); form.append(el('h2', (post ? '글 고치기 · ' : '새 글 · ') + board.name)); const titleLabel = el('label', '제목'); const title = el('input'); title.maxLength = info.limits.title; title.required = true; title.value = post ? post.title : ''; titleLabel.append(title); const bodyLabel = el('label', '내용'); const body = el('textarea'); body.rows = 14; body.maxLength = info.limits.post; body.required = true; body.value = post ? post.body : ''; bodyLabel.append(body); const note = el('p', '글자만 올릴 수 있습니다. 개인 연락처나 다른 사람의 근무표를 올리지 마세요. https:// 주소는 누르면 열리는 링크가 됩니다.', 'small'); const save = el('button', post ? '고친 내용 저장' : '올리기'); save.type = 'submit'; const cancel = link('취소', post ? '#/p/' + post.id : '#/b/' + board.id, 'button-link secondary'); const row = el('div', null, 'form-row'); row.append(counter(body, info.limits.post), cancel, save); form.append(titleLabel, bodyLabel, note, row); form.onsubmit = async event => { event.preventDefault(); save.disabled = true; try { if (post) { await api('posts/' + post.id, { action: 'edit', title: title.value, body: body.value }); notify('글을 고쳤습니다.'); location.hash = '#/p/' + post.id; } else { const result = await api('boards/' + encodeURIComponent(board.id) + '/posts', { title: title.value, body: body.value }); notify('글을 올렸습니다.'); location.hash = '#/p/' + result.id; } } catch (error) { notify(error.message); save.disabled = false; } }; show(form); body.dispatchEvent(new Event('input')); title.focus(); } async function route() { const hash = location.hash.replace(/^#/, '') || '/'; const [path, query] = hash.split('?'); const parts = path.split('/').filter(Boolean); try { if (!info) await loadInfo(); if (parts[0] === 'p' && /^\d+$/.test(parts[1] || '')) await postView(parts[1]); else if (parts[0] === 'w' && parts[1]) await writeView(decodeURIComponent(parts[1])); else if (parts[0] === 'e' && /^\d+$/.test(parts[1] || '')) await writeView(null, parts[1]); else if (parts[0] === 'b' && parts[1]) await listView(decodeURIComponent(parts[1]), new URLSearchParams(query || '')); else if (info.boards.length) await listView(info.boards[0].id, new URLSearchParams()); else show(el('p', '아직 열린 게시판이 없습니다.', 'notice-box')); } catch (error) { problem(error); } } window.addEventListener('hashchange', route); route(); })();