pisha-server 0.0.0-stage → 0.0.11

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.
Files changed (125) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/accounts/accounts.js +754 -0
  4. package/accounts/index.js +1 -0
  5. package/accounts/passwords.js +41 -0
  6. package/accounts/totp.js +54 -0
  7. package/boards/boards.js +1079 -0
  8. package/boards/github.js +212 -0
  9. package/boards/index.js +1 -0
  10. package/boards/sync.js +980 -0
  11. package/companies.js +294 -0
  12. package/company-export.js +101 -0
  13. package/company.js +79 -0
  14. package/dashboard/dashboard.js +407 -0
  15. package/dashboard/index.js +1 -0
  16. package/data-upgrade.js +69 -0
  17. package/install/linux.sh +181 -0
  18. package/install/macos.sh +121 -0
  19. package/install/windows.bat +54 -0
  20. package/machines/index.js +3 -0
  21. package/machines/machines.js +910 -0
  22. package/messaging/inbox.js +252 -0
  23. package/messaging/index.js +3 -0
  24. package/messaging/messaging.js +551 -0
  25. package/messaging/plans.js +67 -0
  26. package/observation/index.js +1 -0
  27. package/observation/observation.js +224 -0
  28. package/organization/index.js +1 -0
  29. package/organization/organization.js +218 -0
  30. package/package.json +54 -4
  31. package/permissions/index.js +1 -0
  32. package/permissions/permissions.js +211 -0
  33. package/pisha-host.mjs +3297 -0
  34. package/pisha-host.mjs.sig +1 -0
  35. package/platform/acme.js +207 -0
  36. package/platform/basics.js +14 -0
  37. package/platform/config.js +154 -0
  38. package/platform/control.js +93 -0
  39. package/platform/credentials.js +151 -0
  40. package/platform/database.js +251 -0
  41. package/platform/errors.js +13 -0
  42. package/platform/files.js +50 -0
  43. package/platform/http.js +207 -0
  44. package/platform/index.js +58 -0
  45. package/platform/limits.js +122 -0
  46. package/platform/listen.js +183 -0
  47. package/platform/roles.js +6 -0
  48. package/platform/stream.js +19 -0
  49. package/platform/text.js +83 -0
  50. package/platform/ws.js +186 -0
  51. package/routes.js +405 -0
  52. package/server.js +65 -0
  53. package/sessions/index.js +1 -0
  54. package/sessions/sessions.js +533 -0
  55. package/ui/LICENSE-affectui.txt +26 -0
  56. package/ui/addmachine.js +151 -0
  57. package/ui/api.js +20 -0
  58. package/ui/app.js +143 -0
  59. package/ui/attention.js +78 -0
  60. package/ui/back.js +166 -0
  61. package/ui/boards.js +958 -0
  62. package/ui/chat.js +388 -0
  63. package/ui/content.js +157 -0
  64. package/ui/dialogs.js +135 -0
  65. package/ui/doing.js +112 -0
  66. package/ui/dom.js +6 -0
  67. package/ui/ds-base.css +146 -0
  68. package/ui/ds-components.css +229 -0
  69. package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
  70. package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
  71. package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
  72. package/ui/format.js +25 -0
  73. package/ui/i18n.js +2093 -0
  74. package/ui/icons/apple-touch-icon.png +0 -0
  75. package/ui/icons/icon-192.png +0 -0
  76. package/ui/icons/icon-512.png +0 -0
  77. package/ui/icons/maskable-512.png +0 -0
  78. package/ui/icons.js +40 -0
  79. package/ui/inbox.js +535 -0
  80. package/ui/index.html +103 -0
  81. package/ui/machines.js +261 -0
  82. package/ui/manifest.webmanifest +16 -0
  83. package/ui/mosaic.js +189 -0
  84. package/ui/nav.js +141 -0
  85. package/ui/newteam.js +223 -0
  86. package/ui/org.js +653 -0
  87. package/ui/overlays.css +126 -0
  88. package/ui/palette.js +179 -0
  89. package/ui/people.js +370 -0
  90. package/ui/permissions.js +202 -0
  91. package/ui/qr.js +158 -0
  92. package/ui/router.js +171 -0
  93. package/ui/routes.js +46 -0
  94. package/ui/screen-boards.css +241 -0
  95. package/ui/screen-inbox.css +201 -0
  96. package/ui/screen-machines.css +76 -0
  97. package/ui/screen-mosaic.css +26 -0
  98. package/ui/screen-newteam.css +90 -0
  99. package/ui/screen-org.css +113 -0
  100. package/ui/screen-session.css +99 -0
  101. package/ui/screen-signin.css +28 -0
  102. package/ui/screen-team.css +80 -0
  103. package/ui/screen-teams.css +41 -0
  104. package/ui/session.js +42 -0
  105. package/ui/shell.css +122 -0
  106. package/ui/signin.js +120 -0
  107. package/ui/squads.js +370 -0
  108. package/ui/state.js +59 -0
  109. package/ui/stream.js +268 -0
  110. package/ui/styles.css +343 -0
  111. package/ui/team.js +115 -0
  112. package/ui/teams.js +58 -0
  113. package/ui/terminal.js +261 -0
  114. package/ui/theme.js +32 -0
  115. package/ui/timeline.js +163 -0
  116. package/ui/topbar.js +205 -0
  117. package/ui/voice-parse.js +98 -0
  118. package/ui/voice.js +320 -0
  119. package/vendor/InterVariable.woff2 +0 -0
  120. package/vendor/LICENSE-inter +92 -0
  121. package/vendor/LICENSE-xterm +21 -0
  122. package/vendor/README.md +8 -0
  123. package/vendor/addon-fit.js +2 -0
  124. package/vendor/xterm.css +218 -0
  125. package/vendor/xterm.js +2 -0
package/ui/boards.js ADDED
@@ -0,0 +1,958 @@
1
+ import { $, store } from './dom.js'
2
+ import { T, LOCALE, COLLATOR } from './i18n.js'
3
+ import { state, sessions, can, companyPref } from './state.js'
4
+ import { esc, ago } from './format.js'
5
+ import { api } from './api.js'
6
+ import { postJson } from './machines.js'
7
+ import { setHtml, soon, renderNav } from './nav.js'
8
+ import { currentRoute } from './router.js'
9
+ import { dialog, confirmDialog } from './dialogs.js'
10
+ import { alertBox } from './mosaic.js'
11
+ import { icon } from './icons.js'
12
+ import { renderTop } from './topbar.js'
13
+
14
+ // Task boards: the company's, each seen by the teams it is given. People and
15
+ // agents work on the same tasks. Giving a task to an agent tells nobody by
16
+ // itself: the person says when ("Notify" now, or "Notify the teams" once they
17
+ // are done handing out), and a mistake never sets anyone to work.
18
+ // A column can be a step of the board's flow: who handles it, what to do
19
+ // there, where a task goes once done. A task moved there is that one's (asked
20
+ // before telling, as any other, when a person moved it).
21
+ // A task can have subtasks (as GitHub's sub-issues): tasks of their own, each
22
+ // with its card; the parent shows them and how many are finished.
23
+
24
+ const CATEGORIES = ['backlog', 'unstarted', 'started', 'review', 'done', 'closed']
25
+ const COLORS = ['gray', 'blue', 'green', 'yellow', 'orange', 'red', 'purple', 'pink']
26
+ const ACTIVE = new Set(['unstarted', 'started', 'review'])
27
+
28
+ const tasksOf = new Map() // board id -> Map(seq -> task), loaded when the board is opened
29
+ const loading = new Map() // board id -> its request
30
+ let people = { members: [], sessions: {} } // who a board's tasks can be given to
31
+ let peopleAt = 0
32
+ const filters = new Map() // board id -> { text, who, label, type, pending }
33
+ let detail = null // the open task, whole: { seq, task, dirty }
34
+ let shownKey = null // what the board's frame was drawn for
35
+ let startAt = false // (to scroll to where work waits, once it is drawn)
36
+
37
+ const mode = () => (store.get(companyPref('pishaBoardMode')) === 'list' ? 'list' : 'cols')
38
+ const boardOf = id => state.boards.find(b => b.id === Number(id)) ?? null
39
+ const statusOf = (b, id) => b?.statuses.find(s => s.id === id) ?? null
40
+ const categoryOf = (b, t) => statusOf(b, t.status)?.category ?? 'unstarted'
41
+ const prefixed = seq => `${state.boardPrefix}-${seq}`
42
+ // The coordinator of a session's team: who hears of a task given to it.
43
+ const teamOf = (boardId, name) => people.sessions[boardId]?.find(s => s.name === name)?.team ?? (sessions.get(name)?.role === 'coordinator' ? name : sessions.get(name)?.coordinator ?? null)
44
+
45
+ async function loadPeople(force = false) {
46
+ if (!force && Date.now() - peopleAt < 30_000) return
47
+ peopleAt = Date.now()
48
+ try {
49
+ const r = await api('/api/boards')
50
+ people = { members: r.members ?? [], sessions: r.sessions ?? {} }
51
+ state.boardPrefix = r.prefix ?? state.boardPrefix
52
+ state.boards = r.boards ?? state.boards
53
+ } catch {}
54
+ }
55
+
56
+ async function loadTasks(id) {
57
+ if (loading.has(id)) return loading.get(id)
58
+ const p = api(`/api/boards/tasks?board=${id}`).then(list => {
59
+ tasksOf.set(id, new Map(list.map(t => [t.seq, compact(t)])))
60
+ }).finally(() => loading.delete(id))
61
+ loading.set(id, p)
62
+ return p
63
+ }
64
+
65
+ // --- GitHub, while the board is in use ----------------------------------------
66
+ // The server asks GitHub only while someone looks: when a board connected to
67
+ // it is opened (or a task of it), and every few minutes while it stays open
68
+ // and the browser tab is in sight. What changes comes back by the stream.
69
+ const WATCH_EVERY = 180_000
70
+ let watching = null // { board, task, timer }
71
+ function stopWatching() { if (watching) clearInterval(watching.timer); watching = null }
72
+ function stillShown() {
73
+ const r = currentRoute()
74
+ return !!watching && r.view === 'board' && Number(r.board) === watching.board && !$('boards').hidden && !!boardOf(watching.board)?.github
75
+ }
76
+ function watchPing(extra = {}) {
77
+ if (!stillShown()) { stopWatching(); return }
78
+ if (document.visibilityState !== 'visible') return
79
+ void postJson('/api/boards/github-watch', { board: watching.board, ...(watching.task ? { task: watching.task } : {}), ...extra }).catch(() => {})
80
+ }
81
+ function watchGithub(b, task) {
82
+ if (!b?.github) { stopWatching(); return }
83
+ if (watching?.board === b.id && watching.task === task) return
84
+ const opened = watching?.board !== b.id
85
+ const taskOpened = !!task && (opened || watching.task !== task)
86
+ stopWatching()
87
+ watching = { board: b.id, task, timer: setInterval(() => watchPing(), WATCH_EVERY) }
88
+ watchPing({ ...(opened ? { opened: true } : {}), ...(taskOpened ? { taskOpened: true } : {}) })
89
+ }
90
+ document.addEventListener('visibilitychange', () => { if (watching && document.visibilityState === 'visible') watchPing() })
91
+
92
+ // --- from the stream ------------------------------------------------------------
93
+ export function boardsArrived(list) {
94
+ state.boards = Array.isArray(list) ? list : []
95
+ const r = currentRoute()
96
+ if (r.view === 'boards' || r.view === 'board') { soon(renderBoards); soon(renderTop) }
97
+ soon(renderNav)
98
+ }
99
+ export function taskArrived(t) {
100
+ const map = tasksOf.get(t.board)
101
+ if (map) { if (t.deleted) map.delete(t.seq); else map.set(t.seq, compact(t)) }
102
+ const r = currentRoute()
103
+ if (r.view === 'board' && Number(r.board) === t.board) {
104
+ soon(renderBoard)
105
+ if (detail?.seq === t.seq) {
106
+ if (t.deleted) { detail = null; soon(renderBoard) } else void openTask(t.seq, { quiet: true })
107
+ }
108
+ }
109
+ }
110
+ export function boardDeleted({ id }) {
111
+ tasksOf.delete(id)
112
+ if (currentRoute().view === 'board' && Number(currentRoute().board) === id) location.hash = '#/boards'
113
+ }
114
+
115
+ // --- what a task looks like ---------------------------------------------------
116
+ const colorVar = c => (COLORS.includes(c) ? c : 'gray')
117
+ const chip = (name, color, cls = 'lbl') => `<span class="${cls}" data-color="${colorVar(color)}">${esc(name)}</span>`
118
+ function labelChips(b, t) {
119
+ return t.labels.map(id => b.labels.find(l => l.id === id)).filter(Boolean).map(l => chip(l.name, l.color)).join('')
120
+ }
121
+ function typeChip(b, t) {
122
+ const ty = t.type && b.types.find(x => x.id === t.type)
123
+ return ty ? chip(ty.name, ty.color, 'lbl type') : ''
124
+ }
125
+ const prioTag = p => (p > 0 ? `<span class="bd-prio" data-p="${p}" title="${esc(T.taskPriority)}: ${esc(T.priorities[p])}">${esc(T.priorities[p])}</span>` : '')
126
+ const DUE_FMT = new Intl.DateTimeFormat(LOCALE, { day: 'numeric', month: 'short', timeZone: 'UTC' })
127
+ function dueTag(b, t) {
128
+ if (!t.due) return ''
129
+ const late = new Date(`${t.due}T23:59:59Z`).getTime() < Date.now() && !['done', 'closed'].includes(categoryOf(b, t))
130
+ return `<span class="bd-due${late ? ' late' : ''}" title="${esc(T.taskDue)}">${esc(DUE_FMT.format(new Date(`${t.due}T00:00:00Z`)))}</span>`
131
+ }
132
+ function whoTag(a) {
133
+ if (!a) return ''
134
+ if (a.kind === 'user') return `<span class="bd-who">${icon('teams')}${esc(a.name)}</span>`
135
+ const role = sessions.get(a.id)?.role === 'coordinator' ? 'coord' : 'worker'
136
+ return `<span class="bd-who bd-agent"><span class="role ${role}" aria-hidden="true"></span>${esc(a.id)}</span>`
137
+ }
138
+ // The people of a task: their initials (three at most, then how many more), their names on hover.
139
+ function peopleTag(list) {
140
+ if (!list?.length) return ''
141
+ const initials = n => n.trim().split(/\s+/).slice(0, 2).map(w => w.charAt(0).toUpperCase()).join('')
142
+ return `<span class="bd-ppl-tag" title="${esc(list.map(p => p.name).join(', '))}">${list.slice(0, 3).map(p => `<span class="bd-av">${esc(initials(p.name))}</span>`).join('')}${list.length > 3 ? `<span class="bd-av more">+${list.length - 3}</span>` : ''}</span>`
143
+ }
144
+ // (Backlog never tells anyone: there it isn't waiting to be told.)
145
+ const untold = (b, t) => t.notify === 'pending' && t.assignee?.kind === 'session' && ACTIVE.has(statusOf(b, t.status)?.category)
146
+ const pendingTag = (b, t) => (untold(b, t) ? `<span class="bd-pending" title="${esc(T.pendingTitle)}">${esc(T.pendingTag)}</span>` : '')
147
+
148
+ // Subtasks: the one it belongs to, and how many of its own are finished.
149
+ function parentTag(b, t) {
150
+ if (!t.parent) return ''
151
+ const p = tasksOf.get(b.id)?.get(t.parent)
152
+ return `<span class="bd-parent" title="${esc(T.bSubOf(prefixed(t.parent), p?.title ?? ''))}">↑ ${esc(prefixed(t.parent))}</span>`
153
+ }
154
+ // Its pull requests: on the card, how many and how the latest stands; open, the list.
155
+ const prLine = p => `#${p.number} «${p.title}»: ${T.prState[p.state] ?? p.state}${p.review ? `, ${T.prReview[p.review] ?? p.review}` : ''}`
156
+ const prTag = t => (t.prs?.length ? `<span class="bd-pr-tag" data-pr="${esc(t.prs[0].state)}" title="${esc(`${T.bPrsTag(t.prs.length)}\n${t.prs.map(prLine).join('\n')}`)}">${icon('pr')}${t.prs.length}</span>` : '')
157
+ function prList(t) {
158
+ if (!t.prs?.length) return ''
159
+ return `<section class="bd-prsec"><h3>${esc(T.bPrs)}</h3><ul class="bd-prs">${t.prs.map(p => `<li data-pr="${esc(p.state)}"><span class="bd-pr-ic" aria-hidden="true">${icon('pr')}</span>
160
+ <a href="${esc(p.url)}" target="_blank" rel="noopener noreferrer"><span class="bd-id">#${p.number}</span> ${esc(p.title)}</a><span class="grow"></span>
161
+ ${p.review ? `<span class="bd-pr-rv" data-rv="${esc(p.review)}">${esc(T.prReview[p.review] ?? p.review)}</span>` : ''}<span class="bd-pr-st">${esc(T.prState[p.state] ?? p.state)}</span></li>`).join('')}</ul></section>`
162
+ }
163
+ const progressTag = t => (t.subtasks ? `<span class="bd-subs-n${t.subtasks.done === t.subtasks.total ? ' all' : ''}" title="${esc(T.bSubProgress(t.subtasks.done, t.subtasks.total))}">☑ ${t.subtasks.done}/${t.subtasks.total}</span>` : '')
164
+
165
+ function card(b, t) {
166
+ return `<article class="bd-card${detail?.seq === t.seq ? ' on' : ''}" data-task="${t.seq}"${can('operator') ? ' draggable="true"' : ''}>
167
+ <div class="bd-card-top"><span class="bd-id">${esc(prefixed(t.seq))}</span>${parentTag(b, t)}${typeChip(b, t)}${prioTag(t.priority)}${pendingTag(b, t)}</div>
168
+ <a class="bd-title" href="#/b/${b.id}/${esc(prefixed(t.seq))}">${esc(t.title)}</a>
169
+ ${t.labels.length || t.due || t.assignee || t.people?.length || t.comments || t.subtasks || t.prs?.length ? `<div class="bd-card-foot">${labelChips(b, t)}${dueTag(b, t)}${progressTag(t)}${prTag(t)}${t.comments ? `<span class="bd-ncom" title="${esc(T.bComments)}">💬 ${t.comments}</span>` : ''}${whoTag(t.assignee)}${peopleTag(t.people)}</div>` : ''}
170
+ </article>`
171
+ }
172
+
173
+ // How the board stands with GitHub, in a few words.
174
+ // The board's state with GitHub, in its header: when it was last synced (the
175
+ // exact time on hover), what is on its way, whether it failed (and why, on a
176
+ // click), and a button to sync now. It follows the server as it changes.
177
+ const TIME_FMT_GH = new Intl.DateTimeFormat(LOCALE, { hour: '2-digit', minute: '2-digit', hour12: false })
178
+ function lastSync(t) {
179
+ const d = new Date(t)
180
+ return d.toDateString() === new Date().toDateString() ? T.ghStLastToday(TIME_FMT_GH.format(d)) : T.ghStLastOn(WHEN_FMT.format(d))
181
+ }
182
+ function ghStatus(b) {
183
+ const g = b.github
184
+ if (!g) return ''
185
+ const busy = g.syncing
186
+ let text
187
+ if (g.error) text = `<button type="button" class="bd-gherr" data-gherr>${esc(T.ghStFailed)}</button>${g.pending ? ` · ${esc(T.ghStUnsent(g.pending))}` : ''}`
188
+ else if (busy) text = esc(T.ghStSyncing)
189
+ else if (g.pending) text = esc(T.ghStSending(g.pending))
190
+ else text = esc(g.synced_at ? T.ghStSynced(ago(g.synced_at)) : T.ghStNever)
191
+ const title = g.synced_at ? lastSync(g.synced_at) : ''
192
+ const now = can('operator') ? `<button type="button" class="icon-btn bd-ghnow" data-ghnow title="${esc(T.ghStNow)}" aria-label="${esc(T.ghStNow)}"${busy ? ' disabled' : ''}>${icon('refresh')}</button>` : ''
193
+ return `<span class="bd-ghstat${g.error ? ' err' : ''}${busy ? ' busy' : ''}" data-ghstat title="${esc(title)}"><span class="long">GitHub · </span><span class="bd-ghtext" aria-live="polite">${text}</span>${now}</span>`
194
+ }
195
+ // («5 minutes ago» stays true while the board is shown.)
196
+ setInterval(() => { const r = currentRoute(); if (r.view === 'board' && boardOf(r.board)?.github) renderTop() }, 30_000)
197
+
198
+ // --- the list of boards -------------------------------------------------------
199
+ function boardCard(b) {
200
+ const open = b.statuses.filter(s => !['done', 'closed'].includes(s.category)).reduce((n, s) => n + s.tasks, 0)
201
+ const all = b.statuses.reduce((n, s) => n + s.tasks, 0)
202
+ const teams = b.teams.map(c => state.squadMeta.get(c)?.title || c)
203
+ return `<a class="card bl-card${b.archived_at ? ' archived' : ''}" href="#/b/${b.id}" aria-label="${esc(T.bOpenBoard(b.name))}">
204
+ <div class="bl-h"><b>${esc(b.name)}</b>${b.archived_at ? `<span class="tag">${esc(T.archivedTag)}</span>` : ''}${b.pending ? `<span class="bd-pending">${esc(T.pendingTag)} · ${b.pending}</span>` : ''}</div>
205
+ ${b.description ? `<p class="bl-desc">${esc(b.description)}</p>` : ''}
206
+ <div class="bl-meta"><span>${esc(T.ofTotal(open, all))} · ${esc(T.bTasks(all))}</span><span>${esc(teams.join(', ') || '—')}</span></div>
207
+ <div class="bl-bar" aria-hidden="true">${b.statuses.filter(s => s.tasks).map(s => `<span data-cat="${s.category}" style="flex:${s.tasks}"></span>`).join('')}</div>
208
+ </a>`
209
+ }
210
+
211
+ function renderList() {
212
+ shownKey = null
213
+ const live = state.boards.filter(b => !b.archived_at)
214
+ const archived = state.boards.filter(b => b.archived_at)
215
+ setHtml($('boards'), `<div class="bl">${state.boards.length
216
+ ? `<div class="bl-grid">${live.map(boardCard).join('')}</div>${archived.length ? `<h2 class="bl-sec">${esc(T.archivedTag)}</h2><div class="bl-grid">${archived.map(boardCard).join('')}</div>` : ''}`
217
+ : `<div class="empty">${icon('board', 'empty-ic')}<b>${esc(T.noBoards)}</b><span>${esc(T.noBoardsHint)}</span>${can('manager') ? `<button type="button" class="btn primary" data-newboard>${esc(T.newBoard)}</button>` : ''}</div>`}</div>`)
218
+ $('topSub').textContent = state.boards.length ? T.boardsCount(live.length) : ''
219
+ }
220
+
221
+ // --- one board ----------------------------------------------------------------
222
+ const filterOf = id => filters.get(id) ?? (filters.set(id, { text: '', who: '', label: '', type: '', pending: false }), filters.get(id))
223
+ function matches(b, t, f) {
224
+ if (f.text && !`${prefixed(t.seq)} ${t.title}`.toLowerCase().includes(f.text.toLowerCase())) return false
225
+ if (f.who === '-' && (t.assignee || t.people?.length)) return false
226
+ if (f.who && f.who !== '-' && assigneeValue(t.assignee) !== f.who && !(t.people ?? []).some(p => `u:${p.id}` === f.who)) return false
227
+ if (f.label && !t.labels.includes(Number(f.label))) return false
228
+ if (f.type && t.type !== Number(f.type)) return false
229
+ if (f.pending && !untold(b, t)) return false
230
+ return true
231
+ }
232
+ const byRank = (a, b) => a.rank - b.rank || a.seq - b.seq
233
+ // A task as the board keeps it: its comments counted, not listed.
234
+ const compact = t => ({ ...t, comments: Array.isArray(t.comments) ? t.comments.length : t.comments ?? 0 })
235
+
236
+ // Who a task can be given to: people, then each team, its coordinator first.
237
+ function assigneeOptions(b, value) {
238
+ const opt = (v, label) => `<option value="${esc(v)}"${v === value ? ' selected' : ''}>${esc(label)}</option>`
239
+ const teams = new Map()
240
+ for (const s of people.sessions[b.id] ?? []) { if (!teams.has(s.team)) teams.set(s.team, []); teams.get(s.team).push(s.name) }
241
+ const groups = [...teams].map(([team, names]) => `<optgroup label="${esc(T.bTeamOf(state.squadMeta.get(team)?.title || team))}">${names.sort((x, y) => (x === team ? -1 : y === team ? 1 : COLLATOR.compare(x, y))).map(n => opt(`s:${n}`, n === team ? `${n} (${T.roleCoordinator})` : n)).join('')}</optgroup>`)
242
+ return `${opt('', T.nobody)}${groups.join('')}`
243
+ }
244
+ // What a task can be a subtask of: any other task of the board but its own subtasks.
245
+ function parentOptions(b, t) {
246
+ const map = tasksOf.get(b.id) ?? new Map()
247
+ const under = seq => { for (let x = map.get(seq), n = 0; x?.parent && n < 20; x = map.get(x.parent), n++) if (x.parent === t.seq) return true; return false }
248
+ const list = [...map.values()].filter(x => x.seq !== t.seq && !(t.seq && under(x.seq))).sort((x, y) => x.seq - y.seq)
249
+ const opt = (v, label) => `<option value="${v}"${String(v) === String(t.parent ?? '') ? ' selected' : ''}>${esc(label)}</option>`
250
+ return opt('', T.noParent) + list.map(x => opt(x.seq, `${prefixed(x.seq)} · ${x.title}`)).join('')
251
+ }
252
+ const assigneeValue = a => (a ? `${a.kind === 'user' ? 'u' : 's'}:${a.id}` : '')
253
+ const assigneeFrom = v => (!v ? null : { kind: v.startsWith('u:') ? 'user' : 'session', id: v.slice(2) })
254
+
255
+ function filterBar(b) {
256
+ const f = filterOf(b.id)
257
+ const who = new Map()
258
+ for (const t of tasksOf.get(b.id)?.values() ?? []) {
259
+ if (t.assignee) who.set(assigneeValue(t.assignee), t.assignee.kind === 'user' ? t.assignee.name : t.assignee.id)
260
+ for (const p of t.people ?? []) who.set(`u:${p.id}`, p.name)
261
+ }
262
+ const opt = (v, label, cur) => `<option value="${esc(v)}"${v === cur ? ' selected' : ''}>${esc(label)}</option>`
263
+ return `<div class="bd-filters" role="search">
264
+ <input type="search" class="input" data-bf="text" placeholder="${esc(T.bFilter)}" aria-label="${esc(T.bFilter)}" value="${esc(f.text)}">
265
+ <select class="input" data-bf="who" aria-label="${esc(T.taskAssignee)}">${opt('', T.bAnyone, f.who)}${opt('-', T.nobody, f.who)}${[...who].sort((x, y) => COLLATOR.compare(x[1], y[1])).map(([v, n]) => opt(v, n, f.who)).join('')}</select>
266
+ ${b.labels.length ? `<select class="input" data-bf="label" aria-label="${esc(T.taskLabels)}">${opt('', T.bAnyLabel, f.label)}${b.labels.map(l => opt(String(l.id), l.name, f.label)).join('')}</select>` : ''}
267
+ ${b.types.length ? `<select class="input" data-bf="type" aria-label="${esc(T.taskType)}">${opt('', T.bAnyType, f.type)}${b.types.map(x => opt(String(x.id), x.name, f.type)).join('')}</select>` : ''}
268
+ <label class="check bd-onlypending"><input type="checkbox" data-bf="pending"${f.pending ? ' checked' : ''}> <span>${esc(T.bOnlyPending)}</span></label>
269
+ </div>`
270
+ }
271
+
272
+ // A column's step, in a line: who handles it and where a task goes next.
273
+ const handlerName = h => (h.kind === 'user' ? h.name : h.id)
274
+ function stepLine(b, s) {
275
+ const parts = [s.handler ? T.stepBy(handlerName(s.handler)) : '', s.next ? T.stepThen(statusOf(b, s.next)?.name ?? '?') : ''].filter(Boolean)
276
+ if (!parts.length && !s.instructions) return ''
277
+ return `<div class="bd-step"${s.instructions ? ` title="${esc(s.instructions)}"` : ''}>${esc(parts.join(' · ') || T.stepInstructionsOnly)}</div>`
278
+ }
279
+ function columns(b, list) {
280
+ return `<div class="bd-cols">${b.statuses.map(s => {
281
+ const here = list.filter(t => t.status === s.id).sort(byRank)
282
+ return `<section class="bd-col" data-status="${s.id}" data-cat="${s.category}" aria-label="${esc(s.name)}">
283
+ <header class="bd-col-h"><span class="bd-dot" data-cat="${s.category}" aria-hidden="true"></span><h2>${esc(s.name)}</h2><span class="bd-count">${here.length}</span>
284
+ ${can('manager') && !b.archived_at ? `<button type="button" class="icon-btn" data-colflow="${s.id}" title="${esc(T.stepTitle(s.name))}" aria-label="${esc(T.stepTitle(s.name))}">${icon('more')}</button>` : ''}
285
+ ${can('operator') && !b.archived_at ? `<button type="button" class="icon-btn" data-newtask="${s.id}" title="${esc(T.bAddTo(s.name))}" aria-label="${esc(T.bAddTo(s.name))}">${icon('plus')}</button>` : ''}</header>
286
+ ${stepLine(b, s)}
287
+ <div class="bd-col-body">${here.map(t => card(b, t)).join('')}</div>
288
+ </section>`
289
+ }).join('')}</div>`
290
+ }
291
+
292
+ function table(b, list) {
293
+ const order = new Map(b.statuses.map((s, i) => [s.id, i]))
294
+ const rows = [...list].sort((x, y) => (order.get(x.status) - order.get(y.status)) || byRank(x, y))
295
+ return `<div class="bd-tablewrap"><table class="bd-table">
296
+ <thead><tr><th>${esc('ID')}</th><th>${esc(T.taskTitle)}</th><th>${esc(T.taskStatus)}</th><th>${esc(T.taskType)}</th><th>${esc(T.taskLabels)}</th><th>${esc(T.taskAssignee)}</th><th>${esc(T.taskPriority)}</th><th>${esc(T.taskDue)}</th></tr></thead>
297
+ <tbody>${rows.map(t => `<tr data-task="${t.seq}"${detail?.seq === t.seq ? ' class="on"' : ''}>
298
+ <td class="bd-id">${esc(prefixed(t.seq))}</td>
299
+ <td>${parentTag(b, t)} <a class="bd-title" href="#/b/${b.id}/${esc(prefixed(t.seq))}">${esc(t.title)}</a> ${progressTag(t)} ${pendingTag(b, t)}</td>
300
+ <td><span class="bd-dot" data-cat="${categoryOf(b, t)}" aria-hidden="true"></span>${esc(statusOf(b, t.status)?.name ?? '')}</td>
301
+ <td>${typeChip(b, t)}</td><td>${labelChips(b, t)}</td><td>${whoTag(t.assignee)}</td><td>${prioTag(t.priority)}</td><td>${dueTag(b, t)}</td>
302
+ </tr>`).join('')}</tbody></table></div>`
303
+ }
304
+
305
+ export function renderBoard() {
306
+ const r = currentRoute()
307
+ const b = boardOf(r.board)
308
+ if (!b) { shownKey = null; stopWatching(); setHtml($('boards'), `<div class="empty"><b>${esc(T.boardGone)}</b></div>`); return }
309
+ if (!tasksOf.has(b.id)) {
310
+ void loadTasks(b.id).then(() => soon(renderBoard), err => alertBox(err.message))
311
+ void loadPeople().then(() => soon(renderBoard))
312
+ }
313
+ const key = String(b.id) // (the view switch redraws the tasks, not the task open beside them)
314
+ if (shownKey !== key) {
315
+ shownKey = key
316
+ $('boards')._html = undefined // (not what setHtml drew last any more)
317
+ $('boards').innerHTML = '<div class="bd"><div class="bd-main"><div class="bd-fbar"></div><div class="bd-view"></div></div><aside class="bd-panel" hidden></aside></div>'
318
+ startAt = true
319
+ }
320
+ const all = [...(tasksOf.get(b.id)?.values() ?? [])]
321
+ const f = filterOf(b.id)
322
+ const list = all.filter(t => matches(b, t, f))
323
+ setHtml($('boards').querySelector('.bd-fbar'), filterBar(b))
324
+ const empty = tasksOf.has(b.id) && !list.length ? `<div class="bd-empty">${esc(all.length ? T.bNoMatch : T.bNoTasks)}</div>` : ''
325
+ setHtml($('boards').querySelector('.bd-view'), (mode() === 'list' ? table(b, list) : columns(b, list)) + empty)
326
+ // (On a phone, one column shows: the first where work waits, not the backlog.)
327
+ if (startAt && tasksOf.has(b.id)) {
328
+ startAt = false
329
+ const first = $('boards').querySelector('.bd-col[data-cat=unstarted], .bd-col[data-cat=started]')
330
+ if (first && matchMedia('(max-width: 900px)').matches) $('boards').querySelector('.bd-view').scrollLeft = first.offsetLeft - 12
331
+ }
332
+ $('topSub').textContent = tasksOf.has(b.id) ? T.bTasks(all.length) : ''
333
+ // The task open beside it.
334
+ const want = r.task ?? null
335
+ const wantSeq = want && want !== 'new' ? Number(/(\d+)$/.exec(want)?.[1]) || null : null
336
+ watchGithub(b, wantSeq)
337
+ const panel = $('boards').querySelector('.bd-panel')
338
+ if (!want) { if (detail) { detail = null } panel.hidden = true; $('boards').querySelector('.bd').classList.remove('with-panel'); return }
339
+ $('boards').querySelector('.bd').classList.add('with-panel')
340
+ panel.hidden = false
341
+ if (want === 'new') { if (detail?.seq !== 'new') drawNew(b) } else {
342
+ const seq = Number(/(\d+)$/.exec(want)?.[1])
343
+ if (detail?.seq !== seq) void openTask(seq)
344
+ }
345
+ }
346
+
347
+ export function renderBoards() {
348
+ const r = currentRoute()
349
+ if (r.view === 'boards') { detail = null; stopWatching(); renderList(); void loadPeople() } else renderBoard()
350
+ }
351
+ export const refreshBoards = () => { const r = currentRoute(); if ((r.view === 'boards' || r.view === 'board') && !$('boards').hidden) renderBoards() }
352
+
353
+ // What the header shows for the boards: title, view switch and actions.
354
+ export function boardsHead(r) {
355
+ if (r.view === 'boards') {
356
+ return { title: esc(T.boards), tabs: '', right: can('manager') ? `<button class="btn primary" data-newboard>${esc(T.newBoard)}</button>` : '' }
357
+ }
358
+ const b = boardOf(r.board)
359
+ if (!b) return { title: esc(T.boards), tabs: '', right: '' }
360
+ const m = mode()
361
+ const tabs = `<nav class="seg" aria-label="${esc(b.name)}"><button type="button" data-bmode="cols"${m === 'cols' ? ' aria-pressed="true"' : ''}>${esc(T.bColumns)}</button><button type="button" data-bmode="list"${m === 'list' ? ' aria-pressed="true"' : ''}>${esc(T.bList)}</button></nav>`
362
+ const right = [
363
+ ghStatus(b),
364
+ can('operator') && b.pending ? `<button class="btn ok" data-bnotify>${esc(T.notifyTeams(b.pending))}</button>` : '',
365
+ can('operator') && !b.archived_at ? `<a class="btn primary" href="#/b/${b.id}/new" data-newtaskhead>${esc(T.newTask)}</a>` : '',
366
+ can('manager') && b.trash ? `<button class="icon-btn" data-btrash title="${esc(T.bTrash(b.trash))}" aria-label="${esc(T.bTrash(b.trash))}">${icon('trash')}</button>` : '',
367
+ can('manager') ? `<button class="icon-btn" data-bsettings title="${esc(T.boardSettings)}" aria-label="${esc(T.boardSettings)}">${icon('settings')}</button>` : '',
368
+ ].join('')
369
+ return { title: `${esc(b.name)}${b.archived_at ? ` <span class="tag">${esc(T.archivedTag)}</span>` : ''}`, tabs, right }
370
+ }
371
+
372
+ // --- the task beside the board ------------------------------------------------
373
+ function form(b, t) {
374
+ const ro = !can('operator') || !!b.archived_at
375
+ const dis = ro ? ' disabled' : ''
376
+ const opt = (v, label, cur) => `<option value="${esc(v)}"${String(v) === String(cur ?? '') ? ' selected' : ''}>${esc(label)}</option>`
377
+ const coordinator = t.assignee?.kind === 'session' ? teamOf(b.id, t.assignee.id) : null
378
+ return `<form class="bd-form" data-bform novalidate>
379
+ <label class="field"><span>${esc(T.taskTitle)}</span><input type="text" name="title" maxlength="200" required value="${esc(t.title ?? '')}"${dis}></label>
380
+ <div class="bd-grid2">
381
+ <label class="field"><span>${esc(T.taskStatus)}</span><select name="status"${dis}>${b.statuses.map(s => opt(s.id, s.name, t.status)).join('')}</select>${stepLine(b, statusOf(b, t.status) ?? {})}</label>
382
+ <label class="field"><span>${esc(T.taskType)}</span><select name="type"${dis}>${opt('', T.noType, t.type ?? '')}${b.types.map(x => opt(x.id, x.name, t.type)).join('')}</select></label>
383
+ <label class="field"><span>${esc(T.taskPriority)}</span><select name="priority"${dis}>${T.priorities.map((p, i) => opt(i, p, t.priority ?? 0)).join('')}</select></label>
384
+ <label class="field"><span>${esc(T.taskDue)}</span><input type="date" name="due" value="${esc(t.due ?? '')}"${dis}></label>
385
+ </div>
386
+ <label class="field"><span>${esc(T.taskAgent)}</span><select name="assignee"${dis}>${assigneeOptions(b, assigneeValue(t.assignee))}</select>
387
+ ${!(people.sessions[b.id] ?? []).length ? `<span class="hint">${esc(T.noAssignable)}</span>` : ''}
388
+ ${untold(b, t) && coordinator ? `<span class="hint bd-pending-hint">${esc(T.pendingTitle)}</span>` : ''}</label>
389
+ ${people.members.length ? `<fieldset class="bd-labels bd-ppl"><legend>${esc(T.taskPeople)}</legend>${people.members.map(m => `<label class="bd-lpick"${b.github && !m.github ? ` title="${esc(T.bNoGithubUser)}"` : ''}><input type="checkbox" name="person" value="${esc(m.id)}"${(t.people ?? []).some(x => x.id === m.id) ? ' checked' : ''}${dis}><span>${esc(m.name)}${b.github && !m.github ? ' <span class="dim-note">*</span>' : ''}</span></label>`).join('')}</fieldset>` : ''}
390
+ <label class="field"><span>${esc(T.taskParent)}</span><select name="parent"${dis}>${parentOptions(b, t)}</select></label>
391
+ ${b.labels.length ? `<fieldset class="bd-labels"><legend>${esc(T.taskLabels)}</legend>${b.labels.map(l => `<label class="bd-lpick"><input type="checkbox" name="label" value="${l.id}"${(t.labels ?? []).includes(l.id) ? ' checked' : ''}${dis}>${chip(l.name, l.color)}</label>`).join('')}</fieldset>` : ''}
392
+ <label class="field"><span>${esc(T.taskDescription)}</span><textarea name="description" rows="7" maxlength="20000"${dis}>${esc(t.description ?? '')}</textarea></label>
393
+ <div class="err" role="alert"></div>
394
+ ${ro ? '' : `<div class="actions">${t.seq && can('manager') ? `<button type="button" class="btn danger" data-bdelete>${esc(T.deleteTask)}</button>` : ''}<button type="submit" class="btn primary">${esc(t.seq ? T.save : T.createTask)}</button></div>`}
395
+ </form>`
396
+ }
397
+
398
+ const WHEN_FMT = new Intl.DateTimeFormat(LOCALE, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', hour12: false })
399
+ const whoName = w => (w ? (w.kind === 'session' ? w.id : w.name) : '?')
400
+ function comments(b, t) {
401
+ const coordinator = t.assignee?.kind === 'session' ? teamOf(b.id, t.assignee.id) : null
402
+ const list = t.comments.map(c => `<li class="bd-com"><div class="bd-com-h"><b>${esc(whoName(c.author))}</b><span>${esc(WHEN_FMT.format(new Date(c.created_at)))}</span>${c.edited_at ? `<span class="bd-edited" title="${esc(WHEN_FMT.format(new Date(c.edited_at)))}">${esc(T.bEdited)}</span>` : ''}${c.notified ? `<span class="tag">${esc(T.bToldTo(c.notified))}</span>` : ''}</div><p>${esc(c.text)}</p></li>`).join('')
403
+ return `<h3>${esc(T.bComments)}${t.comments.length ? ` <span class="badge soft">${t.comments.length}</span>` : ''}</h3>
404
+ <ul class="bd-coms">${list}</ul>
405
+ ${can('operator') ? `<form class="bd-cform" data-bcomment>
406
+ <textarea class="input" name="text" rows="3" maxlength="8000" placeholder="${esc(T.bCommentPh)}" aria-label="${esc(T.bComment)}"></textarea>
407
+ ${coordinator ? `<label class="check"><input type="checkbox" name="notify"> <span>${esc(T.bNotifyCoord(coordinator))}</span></label>` : ''}
408
+ <div class="err" role="alert"></div>
409
+ <div class="actions"><button type="submit" class="btn">${esc(T.bComment)}</button></div></form>` : ''}`
410
+ }
411
+ function subtasks(b, t) {
412
+ const rows = t.children.map(c => `<li data-task="${c.seq}"><span class="bd-dot" data-cat="${statusOf(b, c.status)?.category ?? 'unstarted'}" title="${esc(statusOf(b, c.status)?.name ?? '')}" aria-hidden="true"></span><span class="bd-id">${esc(prefixed(c.seq))}</span>
413
+ <a class="bd-title" href="#/b/${b.id}/${esc(prefixed(c.seq))}">${esc(c.title)}</a>${progressTag(c)}<span class="grow"></span>${whoTag(c.assignee)}${peopleTag(c.people)}</li>`).join('')
414
+ return `<h3>${esc(T.bSubtasks)}${t.subtasks ? ` <span class="badge soft">${t.subtasks.done}/${t.subtasks.total}</span>` : ''}</h3>
415
+ ${rows ? `<ul class="bd-subs">${rows}</ul>` : ''}
416
+ ${can('operator') && !b.archived_at ? `<button type="button" class="btn quiet" data-addsub>${icon('plus')} ${esc(T.bAddSubtask)}</button>` : ''}`
417
+ }
418
+ function history(t) {
419
+ const what = e => (e.what === 'created' ? T.bCreatedIt : e.what === 'notified' ? T.bToldIt(e.data?.to ?? '?') : e.what === 'deleted' ? T.bDeletedIt : e.what === 'restored' ? T.bRestoredIt : e.what === 'pr' ? T.bPrIt(e.data ?? {}) : T.bChangedIt)
420
+ return `<details class="bd-hist"><summary>${esc(T.bHistory)}</summary><ul>${t.events.map(e => `<li><b>${esc(whoName(e.who))}</b> ${esc(what(e))} <span>${esc(WHEN_FMT.format(new Date(e.at)))}</span></li>`).join('')}</ul></details>`
421
+ }
422
+
423
+ function panelHtml(b, t) {
424
+ const gh = t.github?.url ? `<a class="bd-gh" href="${esc(t.github.url)}" target="_blank" rel="noopener noreferrer">${esc(T.ghIssue(t.github.number))}</a>` : t.github?.draft ? `<span class="bd-gh">${esc(T.ghDraft)}</span>` : ''
425
+ return `<header class="bd-panel-h"><span class="bd-id">${esc(t.seq ? prefixed(t.seq) : T.newTask)}</span>${t.seq ? pendingTag(b, t) : ''}${gh}<span class="grow"></span>
426
+ <a class="icon-btn" href="#/b/${b.id}" title="${esc(T.bClosePanel)}" aria-label="${esc(T.bClosePanel)}">${icon('close')}</a></header>
427
+ <div class="bd-panel-body">${t.parent ? `<a class="bd-up" href="#/b/${b.id}/${esc(prefixed(t.parent))}">↑ ${esc(T.bSubOf(prefixed(t.parent), t.parent_title ?? ''))}</a>` : ''}${t.seq ? prList(t) : ''}${form(b, t)}${t.seq ? `<section class="bd-subsec">${subtasks(b, t)}</section><section class="bd-comsec">${comments(b, t)}</section>${history(t)}` : ''}</div>`
428
+ }
429
+
430
+ let newStatus = null
431
+ let newParent = null // (a subtask being added: the task it is of)
432
+ // A new task's panel, drawn at once (not when the address has changed): what is
433
+ // typed goes into it, never into the task that was open before.
434
+ function openNew(boardId) {
435
+ drawNew(boardOf(boardId))
436
+ if (currentRoute().task !== 'new') location.hash = `#/b/${boardId}/new`
437
+ }
438
+ function drawNew(b) {
439
+ const panel = $('boards').querySelector('.bd-panel')
440
+ if (!b || !panel) return
441
+ panel.hidden = false
442
+ $('boards').querySelector('.bd')?.classList.add('with-panel')
443
+ const status = newStatus ?? (b.statuses.find(s => s.category === 'unstarted') ?? b.statuses[0])?.id
444
+ // (In a column someone handles: theirs, as the server will make it.)
445
+ detail = { seq: 'new', task: { title: '', status, labels: [], priority: 0, assignee: statusOf(b, status)?.handler ?? null, parent: newParent }, dirty: false }
446
+ panel.innerHTML = panelHtml(b, detail.task)
447
+ panel.querySelector('[name=title]')?.focus()
448
+ void loadPeople().then(() => { if (detail?.seq === 'new' && !detail.dirty) { panel.innerHTML = panelHtml(b, detail.task); panel.querySelector('[name=title]')?.focus() } })
449
+ }
450
+
451
+ async function openTask(seq, { quiet = false } = {}) {
452
+ const b = boardOf(currentRoute().board)
453
+ const panel = $('boards').querySelector('.bd-panel')
454
+ if (!b || !panel) return
455
+ if (!quiet) { detail = { seq, task: null, dirty: false }; panel.innerHTML = `<div class="bd-panel-body"><div class="dim-note">…</div></div>` }
456
+ let t
457
+ try { t = await api(`/api/boards/task?id=${seq}`) } catch {
458
+ if (detail?.seq === seq) panel.innerHTML = `<header class="bd-panel-h"><span></span><a class="icon-btn" href="#/b/${b.id}" aria-label="${esc(T.bClosePanel)}">${icon('close')}</a></header><div class="empty"><b>${esc(T.bTaskGone)}</b></div>`
459
+ return
460
+ }
461
+ if (detail?.seq !== seq) return
462
+ // What is being typed stays: only the comments and the history follow.
463
+ if (quiet && detail.dirty) {
464
+ detail.task = { ...detail.task, comments: t.comments, events: t.events }
465
+ const sec = panel.querySelector('.bd-comsec h3')
466
+ if (sec) { const s = panel.querySelector('.bd-comsec'); const typed = s.querySelector('textarea')?.value ?? ''; s.innerHTML = comments(b, t); s.querySelector('textarea').value = typed }
467
+ return
468
+ }
469
+ const typed = panel.querySelector('[data-bcomment] textarea')?.value ?? ''
470
+ detail = { seq, task: t, dirty: false }
471
+ panel.innerHTML = panelHtml(b, t)
472
+ const ta = panel.querySelector('[data-bcomment] textarea')
473
+ if (ta) ta.value = typed
474
+ }
475
+
476
+ // What the form says, as the server takes it.
477
+ function fromForm(f) {
478
+ const v = n => f.elements[n]?.value
479
+ return {
480
+ title: v('title').trim(), status: Number(v('status')), type: v('type') ? Number(v('type')) : null, priority: Number(v('priority')),
481
+ due: v('due') || null, assignee: assigneeFrom(v('assignee')), description: v('description'),
482
+ people: [...f.querySelectorAll('[name=person]:checked')].map(x => x.value),
483
+ labels: [...f.querySelectorAll('[name=label]:checked')].map(x => Number(x.value)),
484
+ parent: v('parent') ? Number(v('parent')) : null,
485
+ }
486
+ }
487
+
488
+ // Given to an agent where work waits: tell its coordinator now, or not yet.
489
+ function askNotify(b, coordinator, id) {
490
+ return new Promise(resolve => {
491
+ const d = dialog(`<h3>${esc(T.askNotifyTitle(coordinator))}</h3><p>${esc(T.askNotifyText(coordinator, id))}</p>
492
+ <div class="actions"><button type="button" class="btn primary" data-cancel data-notyet>${esc(T.notYet)}</button><button type="button" class="btn ok" data-notifynow>${esc(T.notifyNow)}</button></div>`)
493
+ let answered = false
494
+ d.el.onclose = () => { if (!answered) resolve(false) }
495
+ d.el.querySelector('[data-notifynow]').addEventListener('click', () => { answered = true; resolve(true); d.close() })
496
+ d.el.querySelector('[data-notyet]').focus() // (a slip of Enter never sets anyone to work)
497
+ })
498
+ }
499
+ // Whether this change gives a task to an agent where work waits, untold.
500
+ function wouldNotify(b, before, after) {
501
+ const a = after.assignee
502
+ if (a?.kind !== 'session' || !ACTIVE.has(statusOf(b, after.status)?.category)) return null
503
+ const newAssignee = assigneeValue(a) !== assigneeValue(before?.assignee)
504
+ const leftBacklog = before && statusOf(b, before.status)?.category === 'backlog'
505
+ const notTold = !before || newAssignee || before.notify === 'pending'
506
+ return (newAssignee || leftBacklog || (!before && notTold)) && notTold ? teamOf(b.id, a.id) : null
507
+ }
508
+
509
+ async function save(f) {
510
+ const b = boardOf(currentRoute().board)
511
+ if (!b || !detail) return
512
+ const err = f.querySelector('.err')
513
+ err.textContent = ''
514
+ const body = fromForm(f)
515
+ if (!body.title) { err.textContent = `${T.taskTitle}?`; f.elements.title.focus(); return }
516
+ const before = detail.seq === 'new' ? null : detail.task
517
+ const button = f.querySelector('[type=submit]')
518
+ button.disabled = true
519
+ const shown = t => {
520
+ tasksOf.get(b.id)?.set(t.seq, compact(t))
521
+ detail = { seq: t.seq, task: t, dirty: false }
522
+ $('boards').querySelector('.bd-panel').innerHTML = panelHtml(b, t)
523
+ soon(renderBoard)
524
+ }
525
+ try {
526
+ const t = before
527
+ ? await postJson('/api/tasks/update', { id: before.seq, version: before.version, ...body })
528
+ : await postJson('/api/tasks/create', { board: b.id, ...body })
529
+ if (!before) { newStatus = null; newParent = null; location.hash = `#/b/${b.id}/${prefixed(t.seq)}` }
530
+ shown(t)
531
+ // (Asked once the server says who has it: a column's step may have given it on.)
532
+ const coordinator = wouldNotify(b, before, t)
533
+ if (coordinator && await askNotify(b, coordinator, `${prefixed(t.seq)} «${t.title}»`)) shown(await postJson('/api/tasks/update', { id: t.seq, notify: true }))
534
+ } catch (e) {
535
+ button.disabled = false
536
+ if (e.reason === 'changed') {
537
+ detail.dirty = false
538
+ await openTask(before.seq)
539
+ const again = $('boards').querySelector('.bd-form .err')
540
+ if (again) again.textContent = T.changedMeanwhile
541
+ return
542
+ }
543
+ err.textContent = e.message
544
+ }
545
+ }
546
+
547
+ // --- moving a card --------------------------------------------------------------
548
+ async function move(b, seq, statusId, rank) {
549
+ const t = tasksOf.get(b.id)?.get(seq)
550
+ if (!t) return
551
+ // (Shown moved at once; the server's answer puts it right.)
552
+ tasksOf.get(b.id).set(seq, { ...t, status: statusId, rank })
553
+ soon(renderBoard)
554
+ try {
555
+ const moved = await postJson('/api/tasks/update', { id: seq, version: t.version, status: statusId, rank })
556
+ tasksOf.get(b.id).set(seq, compact(moved))
557
+ soon(renderBoard)
558
+ const coordinator = statusId !== t.status ? wouldNotify(b, t, moved) : null
559
+ if (coordinator && await askNotify(b, coordinator, `${prefixed(seq)} «${t.title}»`)) tasksOf.get(b.id).set(seq, compact(await postJson('/api/tasks/update', { id: seq, notify: true })))
560
+ } catch (e) {
561
+ tasksOf.get(b.id).set(seq, t)
562
+ soon(renderBoard)
563
+ alertBox(e.reason === 'changed' ? T.changedMeanwhile : e.message)
564
+ if (e.reason === 'changed') void loadTasks(b.id).then(() => soon(renderBoard))
565
+ }
566
+ }
567
+
568
+ // Where in a column a card dropped at that height goes: between its neighbours.
569
+ function rankAt(b, col, y, seq) {
570
+ const cards = [...col.querySelectorAll('.bd-card')].filter(c => Number(c.dataset.task) !== seq)
571
+ const map = tasksOf.get(b.id)
572
+ const next = cards.findIndex(c => { const r = c.getBoundingClientRect(); return y < r.top + r.height / 2 })
573
+ const rankOf = c => map.get(Number(c.dataset.task))?.rank ?? 0
574
+ if (!cards.length) return 1
575
+ if (next === 0) return rankOf(cards[0]) - 1
576
+ if (next === -1) return rankOf(cards.at(-1)) + 1
577
+ return (rankOf(cards[next - 1]) + rankOf(cards[next])) / 2
578
+ }
579
+
580
+ let dragging = null
581
+ $('boards').addEventListener('dragstart', e => {
582
+ const c = e.target.closest?.('.bd-card[draggable]')
583
+ if (!c) return
584
+ dragging = Number(c.dataset.task)
585
+ e.dataTransfer.effectAllowed = 'move'
586
+ e.dataTransfer.setData('text/plain', c.querySelector('.bd-id')?.textContent ?? '')
587
+ c.classList.add('dragging')
588
+ })
589
+ $('boards').addEventListener('dragend', e => { e.target.closest?.('.bd-card')?.classList.remove('dragging'); dragging = null; for (const c of $('boards').querySelectorAll('.bd-col.over')) c.classList.remove('over') })
590
+ $('boards').addEventListener('dragover', e => {
591
+ const col = dragging != null && e.target.closest('.bd-col')
592
+ if (!col) return
593
+ e.preventDefault()
594
+ for (const c of $('boards').querySelectorAll('.bd-col.over')) if (c !== col) c.classList.remove('over')
595
+ col.classList.add('over')
596
+ })
597
+ $('boards').addEventListener('drop', e => {
598
+ const col = dragging != null && e.target.closest('.bd-col')
599
+ if (!col) return
600
+ e.preventDefault()
601
+ col.classList.remove('over')
602
+ const b = boardOf(currentRoute().board)
603
+ if (b) void move(b, dragging, Number(col.dataset.status), rankAt(b, col, e.clientY, dragging))
604
+ })
605
+
606
+ // --- the board's settings, a new board, notifying -------------------------------
607
+ function coordinators(extra = []) {
608
+ const names = new Set([...[...sessions.values()].filter(s => s.role === 'coordinator' && !s.archived_at).map(s => s.name), ...extra])
609
+ return [...names].sort((a, b) => COLLATOR.compare(state.squadMeta.get(a)?.title || a, state.squadMeta.get(b)?.title || b))
610
+ }
611
+ const teamChecks = chosen => {
612
+ const list = coordinators(chosen)
613
+ return list.length
614
+ ? `<fieldset class="bd-teams"><legend>${esc(T.boardTeams)}</legend>${list.map(c => `<label class="check"><input type="checkbox" name="team" value="${esc(c)}"${chosen.includes(c) ? ' checked' : ''}> <span>${esc(state.squadMeta.get(c)?.title || c)}${state.squadMeta.get(c)?.title ? ` <span class="dim-note">${esc(c)}</span>` : ''}</span></label>`).join('')}<span class="hint">${esc(T.boardTeamsHint)}</span></fieldset>`
615
+ : `<p class="dim-note">${esc(T.noTeamsForBoard)}</p>`
616
+ }
617
+
618
+ function newBoardDialog() {
619
+ const d = dialog(`<h3>${esc(T.newBoard)}</h3><form data-bnew>
620
+ <label class="field"><span>${esc(T.boardName)}</span><input type="text" name="name" maxlength="60" required></label>
621
+ <label class="field"><span>${esc(T.boardDescription)}</span><textarea name="description" rows="2" maxlength="1000"></textarea></label>
622
+ ${teamChecks([])}
623
+ <div class="err" role="alert"></div>
624
+ <div class="actions"><button type="button" class="btn plain" data-cancel>${esc(T.cancel)}</button><button type="submit" class="btn primary">${esc(T.createBoard)}</button></div></form>`)
625
+ const f = d.el.querySelector('form')
626
+ f.elements.name.focus()
627
+ f.addEventListener('submit', async e => {
628
+ e.preventDefault()
629
+ try {
630
+ const b = await postJson('/api/boards/create', {
631
+ name: f.elements.name.value, description: f.elements.description.value,
632
+ teams: [...f.querySelectorAll('[name=team]:checked')].map(x => x.value),
633
+ statuses: T.defaultStatuses.map(([name, category]) => ({ name, category })),
634
+ types: T.defaultTypes.map(([name, color]) => ({ name, color })),
635
+ })
636
+ state.boards = [...state.boards.filter(x => x.id !== b.id), b]
637
+ peopleAt = 0
638
+ d.close()
639
+ location.hash = `#/b/${b.id}`
640
+ } catch (err) { f.querySelector('.err').textContent = err.message }
641
+ })
642
+ }
643
+
644
+ // Statuses, labels and types, edited as lists: ids kept, order as shown.
645
+ function listEditor(key, items, withCategory) {
646
+ const rows = items.map((x, i) => `<div class="bd-row" data-i="${i}">
647
+ <input type="text" class="input" data-k="name" value="${esc(x.name)}" maxlength="60" aria-label="${esc(T.boardName)}">
648
+ ${withCategory
649
+ ? `<select class="input" data-k="category" aria-label="${esc(T.bCategory)}">${CATEGORIES.map(c => `<option value="${c}"${c === x.category ? ' selected' : ''}>${esc(T.categories[c])}</option>`).join('')}</select>`
650
+ : `<select class="input" data-k="color" aria-label="${esc(T.bColor)}">${COLORS.map(c => `<option value="${c}"${c === x.color ? ' selected' : ''}>${esc(T.colors[c])}</option>`).join('')}</select>`}
651
+ <button type="button" class="icon-btn" data-up title="${esc(T.bMoveUp)}" aria-label="${esc(T.bMoveUp)}"${i === 0 ? ' disabled' : ''}>${icon('chevron', 'up')}</button>
652
+ <button type="button" class="icon-btn" data-rm title="${esc(T.bRemove)}" aria-label="${esc(T.bRemove)}">${icon('close')}</button>
653
+ </div>`).join('')
654
+ return `<div class="bd-rows">${rows}</div><button type="button" class="btn quiet" data-add>${icon('plus')} ${esc(T.bAdd)}</button>`
655
+ }
656
+
657
+ function settingsDialog(b) {
658
+ const lists = {
659
+ statuses: b.statuses.map(({ id, name, category }) => ({ id, name, category })),
660
+ labels: b.labels.map(({ id, name, color }) => ({ id, name, color })),
661
+ types: b.types.map(({ id, name, color }) => ({ id, name, color })),
662
+ }
663
+ const d = dialog(`<h3>${esc(T.boardSettings)}</h3><form data-bset>
664
+ <label class="field"><span>${esc(T.boardName)}</span><input type="text" name="name" maxlength="60" required value="${esc(b.name)}"></label>
665
+ <label class="field"><span>${esc(T.boardDescription)}</span><textarea name="description" rows="2" maxlength="1000">${esc(b.description)}</textarea></label>
666
+ ${teamChecks(b.teams)}
667
+ <section class="bd-edit" data-list="statuses"><h4>${esc(T.bStatuses)}</h4><p class="dim-note">${esc(T.bStatusesHint)}</p><div></div></section>
668
+ <section class="bd-edit" data-list="labels"><h4>${esc(T.bLabels)}</h4><div></div></section>
669
+ <section class="bd-edit" data-list="types"><h4>${esc(T.bTypes)}</h4><div></div></section>
670
+ <section class="bd-edit bd-ghsec"><h4>${esc(T.ghSection)}</h4>${ghSummary(b)}</section>
671
+ <label class="field bd-prefix"><span>${esc(T.taskPrefix)}</span><input type="text" name="prefix" maxlength="6" value="${esc(state.boardPrefix)}" autocapitalize="characters"></label>
672
+ <div class="err" role="alert"></div>
673
+ <div class="actions bd-set-actions">
674
+ <button type="button" class="btn" data-barchive>${esc(b.archived_at ? T.unarchiveBoard : T.archiveBoard)}</button>
675
+ ${b.archived_at ? `<button type="button" class="btn danger" data-bdel>${esc(T.deleteBoard)}</button>` : ''}
676
+ <span class="grow"></span>
677
+ <button type="button" class="btn plain" data-cancel>${esc(T.cancel)}</button><button type="submit" class="btn primary">${esc(T.save)}</button></div></form>`, { wide: true })
678
+ const f = d.el.querySelector('form')
679
+ const draw = key => { d.el.querySelector(`[data-list=${key}] > div`).innerHTML = listEditor(key, lists[key], key === 'statuses') }
680
+ // (What is typed in a row is kept before the list is drawn again.)
681
+ const read = key => {
682
+ for (const row of d.el.querySelectorAll(`[data-list=${key}] .bd-row`)) {
683
+ const x = lists[key][Number(row.dataset.i)]
684
+ for (const el of row.querySelectorAll('[data-k]')) x[el.dataset.k] = el.value
685
+ }
686
+ }
687
+ for (const key of Object.keys(lists)) draw(key)
688
+ d.el.addEventListener('click', e => {
689
+ const sec = e.target.closest('[data-list]')
690
+ if (!sec) return
691
+ const key = sec.dataset.list
692
+ const i = Number(e.target.closest('.bd-row')?.dataset.i)
693
+ if (e.target.closest('[data-add]')) { read(key); lists[key].push(key === 'statuses' ? { id: null, name: '', category: 'unstarted' } : { id: null, name: '', color: 'gray' }); draw(key); sec.querySelector('.bd-row:last-child input')?.focus(); return }
694
+ if (e.target.closest('[data-up]') && i > 0) { read(key); [lists[key][i - 1], lists[key][i]] = [lists[key][i], lists[key][i - 1]]; draw(key); return }
695
+ if (e.target.closest('[data-rm]')) { read(key); lists[key].splice(i, 1); draw(key) }
696
+ })
697
+ f.addEventListener('submit', async e => {
698
+ e.preventDefault()
699
+ for (const key of Object.keys(lists)) read(key)
700
+ const clean = list => list.filter(x => x.name.trim()).map(x => ({ ...x, name: x.name.trim() }))
701
+ try {
702
+ if (f.elements.prefix.value.trim().toUpperCase() !== state.boardPrefix) {
703
+ state.boardPrefix = (await postJson('/api/boards/prefix', { prefix: f.elements.prefix.value })).prefix
704
+ }
705
+ await postJson('/api/boards/update', {
706
+ id: b.id, name: f.elements.name.value, description: f.elements.description.value,
707
+ teams: [...f.querySelectorAll('[name=team]:checked')].map(x => x.value),
708
+ statuses: clean(lists.statuses), labels: clean(lists.labels), types: clean(lists.types),
709
+ })
710
+ peopleAt = 0
711
+ void loadPeople(true).then(() => soon(renderBoard))
712
+ d.close()
713
+ } catch (err) { f.querySelector('.err').textContent = err.message }
714
+ })
715
+ d.el.querySelector('[data-ghconnect]')?.addEventListener('click', () => { d.close(); githubDialog(b) })
716
+ d.el.querySelector('.bd-ghsec').addEventListener('change', async e => {
717
+ const box = e.target.closest('[data-ghmerge]')
718
+ if (!box) return
719
+ box.disabled = true
720
+ try { const nb = await postJson('/api/boards/github-merge', { board: b.id, on: box.checked }); state.boards = state.boards.map(x => (x.id === nb.id ? nb : x)) } catch (err) { box.checked = !box.checked; f.querySelector('.err').textContent = err.message }
721
+ box.disabled = false
722
+ })
723
+ d.el.querySelector('[data-ghsync]')?.addEventListener('click', async e => {
724
+ e.target.disabled = true
725
+ try { const nb = await postJson('/api/boards/github-sync', { board: b.id }); state.boards = state.boards.map(x => (x.id === nb.id ? nb : x)); d.el.querySelector('.bd-ghsec').innerHTML = `<h4>${esc(T.ghSection)}</h4>${ghSummary(nb)}`; void loadTasks(b.id).then(() => soon(renderBoard)) } catch (err) { f.querySelector('.err').textContent = err.message; e.target.disabled = false }
726
+ })
727
+ d.el.querySelector('[data-ghoff]')?.addEventListener('click', () => {
728
+ d.close()
729
+ confirmDialog({ title: T.ghDisconnectTitle, text: T.ghDisconnectText(esc(b.github.title ?? '')), confirm: T.ghDisconnect, danger: true, run: async () => { const nb = await postJson('/api/boards/github-off', { board: b.id }); state.boards = state.boards.map(x => (x.id === nb.id ? nb : x)); soon(renderBoard); soon(renderTop) } })
730
+ })
731
+ d.el.querySelector('[data-barchive]').addEventListener('click', async () => {
732
+ try { await postJson('/api/boards/update', { id: b.id, archived: !b.archived_at }); d.close() } catch (err) { f.querySelector('.err').textContent = err.message }
733
+ })
734
+ d.el.querySelector('[data-bdel]')?.addEventListener('click', () => {
735
+ d.close()
736
+ confirmDialog({ title: T.deleteBoardTitle(b.name), text: esc(T.deleteBoardText(b.name)), confirm: T.deleteBoard, danger: true, run: async () => { await postJson('/api/boards/delete', { id: b.id }); location.hash = '#/boards' } })
737
+ })
738
+ }
739
+
740
+ // The board's GitHub connection, in the settings: what it follows and how it went.
741
+ function ghSummary(b) {
742
+ const g = b.github
743
+ if (!g) return `<p class="dim-note">${esc(T.ghNone)}</p><button type="button" class="btn" data-ghconnect>${esc(T.ghConnect)}</button>`
744
+ return `<p class="bd-ghstate"><a href="${esc(g.url ?? '#')}" target="_blank" rel="noopener noreferrer">${esc(T.ghStatus(g.title ?? '', g.repo))}</a></p>
745
+ <p class="dim-note">${esc([g.synced_at ? T.ghSynced(ago(g.synced_at)) : T.ghSyncing, T.ghLinked(g.linked)].join(' · '))}</p>
746
+ ${g.error ? `<p class="err" role="alert">${esc(g.error)}</p>` : ''}
747
+ <label class="check"><input type="checkbox" data-ghmerge${g.merge_moves ? ' checked' : ''}> ${esc(T.ghMergeMoves)}</label>
748
+ <p class="dim-note">${esc(T.ghPrsHint)}</p>
749
+ <div class="bd-ghacts"><button type="button" class="btn" data-ghsync>${esc(T.ghSyncNow)}</button><button type="button" class="btn" data-ghconnect>${esc(T.ghChange)}</button><button type="button" class="btn danger" data-ghoff>${esc(T.ghDisconnect)}</button></div>`
750
+ }
751
+
752
+ function githubDialog(b) {
753
+ const g = b.github
754
+ const d = dialog(`<h3>${esc(T.ghTitle)}</h3><form data-bgh autocomplete="off">
755
+ <label class="field"><span>${esc(T.ghUrl)}</span><input type="url" name="url" required placeholder="${esc(T.ghUrlPh)}" value="${esc(g ? `https://github.com/${g.owner_kind === 'org' ? 'orgs' : 'users'}/${g.owner}/projects/${g.number}` : '')}"></label>
756
+ <label class="field"><span>${esc(T.ghRepo)}</span><input type="text" name="repo" required placeholder="${esc(T.ghRepoPh)}" value="${esc(g?.repo ?? '')}" autocapitalize="off" spellcheck="false"><span class="hint">${esc(T.ghRepoHint)}</span></label>
757
+ <label class="field"><span>${esc(T.ghToken)}</span><input type="password" name="token" ${g ? `placeholder="${esc(T.ghTokenKeep)}"` : 'required'} autocomplete="new-password" spellcheck="false"><span class="hint">${esc(T.ghTokenHint)}</span></label>
758
+ <p class="dim-note">${esc(T.ghColumnsNote)}</p>
759
+ <div class="err" role="alert"></div>
760
+ <div class="actions"><button type="button" class="btn plain" data-cancel>${esc(T.cancel)}</button><button type="submit" class="btn primary">${esc(T.ghConnectBtn)}</button></div></form>`, { wide: true })
761
+ const f = d.el.querySelector('form')
762
+ f.elements.url.focus()
763
+ f.addEventListener('submit', async e => {
764
+ e.preventDefault()
765
+ const button = f.querySelector('[type=submit]')
766
+ button.disabled = true
767
+ try {
768
+ await postJson('/api/boards/github', { board: b.id, url: f.elements.url.value, repo: f.elements.repo.value, token: f.elements.token.value })
769
+ f.elements.token.value = ''
770
+ d.close()
771
+ void loadPeople(true).then(() => { soon(renderBoard); soon(renderTop) })
772
+ } catch (err) { f.querySelector('.err').textContent = err.message; button.disabled = false }
773
+ })
774
+ }
775
+
776
+ // One column as a step of the flow: who handles it, what to do, where next.
777
+ function flowDialog(b, s) {
778
+ const opt = (v, label, cur) => `<option value="${esc(v)}"${String(v) === String(cur ?? '') ? ' selected' : ''}>${esc(label)}</option>`
779
+ const others = b.statuses.filter(x => x.id !== s.id)
780
+ const d = dialog(`<h3>${esc(T.stepTitle(s.name))}</h3><form data-bflow>
781
+ <p class="dim-note">${esc(T.stepHint)}</p>
782
+ <label class="field"><span>${esc(T.stepHandler)}</span><select name="handler">${assigneeOptions(b, s.handler ? assigneeValue(s.handler) : '')}</select><span class="hint">${esc(T.stepHandlerHint)}</span></label>
783
+ <label class="field"><span>${esc(T.stepInstructions)}</span><textarea name="instructions" rows="4" maxlength="4000" placeholder="${esc(T.stepInstructionsPh)}">${esc(s.instructions ?? '')}</textarea></label>
784
+ <div class="row2">
785
+ <label class="field"><span>${esc(T.stepNext)}</span><select name="next">${opt('', T.stepNoNext, s.next ?? '')}${others.map(x => opt(x.id, x.name, s.next)).join('')}</select></label>
786
+ <label class="field"><span>${esc(T.stepBack)}</span><select name="back">${opt('', T.stepNoBack, s.back ?? '')}${others.map(x => opt(x.id, x.name, s.back)).join('')}</select></label>
787
+ </div>
788
+ <div class="err" role="alert"></div>
789
+ <div class="actions"><button type="button" class="btn plain" data-cancel>${esc(T.cancel)}</button><button type="submit" class="btn primary">${esc(T.save)}</button></div></form>`, { wide: true })
790
+ const f = d.el.querySelector('form')
791
+ f.elements.handler.focus()
792
+ f.addEventListener('submit', async e => {
793
+ e.preventDefault()
794
+ const num = v => (v ? Number(v) : null)
795
+ try {
796
+ const nb = await postJson('/api/boards/flow', { board: b.id, status: s.id, handler: assigneeFrom(f.elements.handler.value), instructions: f.elements.instructions.value, next: num(f.elements.next.value), back: num(f.elements.back.value) })
797
+ state.boards = state.boards.map(x => (x.id === nb.id ? nb : x))
798
+ soon(renderBoard)
799
+ d.close()
800
+ } catch (err) { f.querySelector('.err').textContent = err.message }
801
+ })
802
+ }
803
+
804
+ function notifyDialog(b) {
805
+ const byTeam = new Map()
806
+ for (const t of [...(tasksOf.get(b.id)?.values() ?? [])].sort(byRank)) {
807
+ if (t.notify !== 'pending' || t.assignee?.kind !== 'session' || !ACTIVE.has(categoryOf(b, t))) continue
808
+ const team = teamOf(b.id, t.assignee.id) ?? '?'
809
+ if (!byTeam.has(team)) byTeam.set(team, [])
810
+ byTeam.get(team).push(t)
811
+ }
812
+ const list = [...byTeam].map(([team, ts]) => `<li><b>${esc(state.squadMeta.get(team)?.title || team)}</b><ul>${ts.map(t => `<li><span class="bd-id">${esc(prefixed(t.seq))}</span> ${esc(t.title)} → ${esc(t.assignee.id)}</li>`).join('')}</ul></li>`).join('')
813
+ confirmDialog({
814
+ title: T.notifyTitle, text: `${esc(T.notifyText)}</p><ul class="bd-notify-list">${list}</ul><p>`, confirm: T.notifyConfirm, settles: true,
815
+ run: async () => {
816
+ const r = await postJson('/api/tasks/notify', { board: b.id })
817
+ if (r.failed?.length) alertBox(T.notifyFailed(r.failed.map(x => x.team).join(', ')))
818
+ },
819
+ })
820
+ }
821
+
822
+ // --- clicks and typing ------------------------------------------------------------
823
+ $('boards').addEventListener('click', e => {
824
+ if (e.target.closest('[data-newboard]')) return newBoardDialog()
825
+ const step = e.target.closest('[data-colflow]')
826
+ if (step) { const b = boardOf(currentRoute().board); const s = statusOf(b, Number(step.dataset.colflow)); if (s) void loadPeople().then(() => flowDialog(b, s)); return }
827
+ const add = e.target.closest('[data-newtask]')
828
+ if (add) { newStatus = Number(add.dataset.newtask); newParent = null; openNew(currentRoute().board); return }
829
+ if (e.target.closest('[data-bdelete]') && detail?.task?.seq) {
830
+ const t = detail.task
831
+ const b = boardOf(currentRoute().board)
832
+ const subs = t.children?.length ?? 0
833
+ return confirmDialog({
834
+ title: T.deleteTaskTitle(prefixed(t.seq)), text: esc(T.deleteTaskText(prefixed(t.seq))), confirm: T.deleteTask, danger: true,
835
+ option: subs ? T.deleteWithSubtasks(subs) : null, optionChecked: false,
836
+ run: async withSubs => { await postJson('/api/tasks/delete', { id: t.seq, subtasks: !!withSubs }); tasksOf.get(b.id)?.delete(t.seq); detail = null; location.hash = `#/b/${b.id}` },
837
+ })
838
+ }
839
+ if (e.target.closest('[data-addsub]') && detail?.task?.seq) {
840
+ const parent = detail.task
841
+ newStatus = null; newParent = parent.seq
842
+ openNew(currentRoute().board)
843
+ return
844
+ }
845
+ // A card, a row or a subtask: open it (its title is the link; the rest of it too).
846
+ const row = e.target.closest('.bd-card, .bd-table tr[data-task], .bd-subs li[data-task]')
847
+ if (row && !e.target.closest('a, button, input, select, textarea')) {
848
+ location.hash = `#/b/${currentRoute().board}/${prefixed(Number(row.dataset.task))}`
849
+ }
850
+ })
851
+ $('boards').addEventListener('input', e => {
852
+ const f = e.target.closest('[data-bf]')
853
+ if (f) {
854
+ const b = currentRoute().board
855
+ const flt = filterOf(Number(b))
856
+ flt[f.dataset.bf] = f.type === 'checkbox' ? f.checked : f.value
857
+ return soon(renderBoard)
858
+ }
859
+ if (e.target.closest('[data-bform]') && detail) detail.dirty = true
860
+ })
861
+ $('boards').addEventListener('change', e => {
862
+ // (A column someone handles, chosen in the form: shown as who will have it.)
863
+ if (e.target.matches('[data-bform] [name=status]') && detail) {
864
+ const b = boardOf(currentRoute().board)
865
+ const s = statusOf(b, Number(e.target.value))
866
+ const who = e.target.form.elements.assignee
867
+ const label = e.target.closest('label')
868
+ label.querySelector('.bd-step')?.remove()
869
+ label.insertAdjacentHTML('beforeend', stepLine(b, s ?? {}))
870
+ if (s?.handler && who && who.value === assigneeValue(detail.task?.assignee)) who.value = assigneeValue(s.handler)
871
+ }
872
+ const f = e.target.closest('[data-bf]')
873
+ if (f) { filterOf(Number(currentRoute().board))[f.dataset.bf] = f.type === 'checkbox' ? f.checked : f.value; soon(renderBoard) }
874
+ })
875
+ $('boards').addEventListener('submit', async e => {
876
+ const f = e.target
877
+ if (f.matches('[data-bform]')) { e.preventDefault(); return save(f) }
878
+ if (f.matches('[data-bcomment]')) {
879
+ e.preventDefault()
880
+ const text = f.elements.text.value.trim()
881
+ if (!text || !detail?.task?.seq) return
882
+ const button = f.querySelector('[type=submit]')
883
+ button.disabled = true
884
+ try {
885
+ await postJson('/api/tasks/comment', { id: detail.task.seq, text, notify: !!f.elements.notify?.checked })
886
+ f.elements.text.value = ''
887
+ if (f.elements.notify) f.elements.notify.checked = false
888
+ await openTask(detail.task.seq, { quiet: true })
889
+ } catch (err) { f.querySelector('.err').textContent = err.message } finally { button.disabled = false }
890
+ }
891
+ })
892
+ // Ctrl+Enter sends a comment or saves the task.
893
+ $('boards').addEventListener('keydown', e => {
894
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
895
+ const f = e.target.closest('[data-bform], [data-bcomment]')
896
+ if (f) { e.preventDefault(); f.requestSubmit() }
897
+ }
898
+ })
899
+
900
+ // The header's buttons (see topbar.js).
901
+ export function boardsTopClick(e) {
902
+ if (e.target.closest('[data-newboard]')) { newBoardDialog(); return true }
903
+ if (e.target.closest('[data-newtaskhead]') && currentRoute().board) { e.preventDefault(); newStatus = null; newParent = null; openNew(currentRoute().board); return true }
904
+ const b = boardOf(currentRoute().board)
905
+ const m = e.target.closest('[data-bmode]')
906
+ if (m) { store.set(companyPref('pishaBoardMode'), m.dataset.bmode); soon(renderBoard); soon(renderTop); return true }
907
+ if (!b) return false
908
+ if (e.target.closest('[data-bnotify]')) { void loadTasks(b.id).then(() => notifyDialog(b)); return true }
909
+ if (e.target.closest('[data-bsettings]')) { void loadPeople().then(() => settingsDialog(b)); return true }
910
+ if (e.target.closest('[data-btrash]')) { void trashDialog(b); return true }
911
+ if (e.target.closest('[data-gherr]') && b.github?.error) { alertBox(T.ghStFailedText(b.github.error, b.github.pending), T.ghStFailedTitle); return true }
912
+ const now = e.target.closest('[data-ghnow]')
913
+ if (now) {
914
+ now.disabled = true
915
+ // (The board, and the task open beside it with its comments.)
916
+ const seq = typeof detail?.seq === 'number' ? detail.seq : null
917
+ const work = [postJson('/api/boards/github-sync', { board: b.id })]
918
+ if (seq) work.push(postJson('/api/boards/github-watch', { board: b.id, task: seq, force: true }))
919
+ Promise.all(work).catch(err => alertBox(err.message)).finally(() => { now.disabled = false; soon(renderTop) })
920
+ return true
921
+ }
922
+ return false
923
+ }
924
+
925
+ // --- the trash: deleted tasks, to be restored ----------------------------------------
926
+ function trashRows(list) {
927
+ if (!list.length) return `<p class="dim-note">${esc(T.bTrashEmpty)}</p>`
928
+ return `<ul class="bd-trash">${list.map(t => `<li>
929
+ <div class="grow"><div class="bd-trash-t"><span class="bd-id">${esc(t.id)}</span> ${esc(t.title)}</div>
930
+ <div class="dim-note">${esc([T.bTrashBy(whoName(t.deleted_by), ago(t.deleted_at)), t.parent ? T.bTrashSubOf(t.parent.id, t.parent.trashed) : '', t.subtasks ? T.bTrashWith(t.subtasks) : ''].filter(Boolean).join(' · '))}</div></div>
931
+ <button type="button" class="btn ok" data-restore="${t.seq}">${esc(T.restoreTask)}</button></li>`).join('')}</ul>`
932
+ }
933
+ async function trashDialog(b) {
934
+ let list
935
+ try { list = await api(`/api/boards/trash?board=${b.id}`) } catch (err) { alertBox(err.message); return }
936
+ const d = dialog(`<h3>${esc(T.bTrashTitle(b.name))}</h3><div class="bd-trash-body">${trashRows(list)}</div><div class="err"></div><div class="actions"><button type="button" class="btn plain" data-cancel>${esc(T.close)}</button></div>`, { wide: true })
937
+ const redraw = async () => { list = await api(`/api/boards/trash?board=${b.id}`); d.el.querySelector('.bd-trash-body').innerHTML = trashRows(list) }
938
+ const restore = async (t, withSubs) => {
939
+ const r = await postJson('/api/tasks/restore', { id: t.seq, subtasks: !!withSubs })
940
+ if (r.without_parent && !t.parent?.trashed) alertBox(T.restoredNoParent(t.id, r.without_parent))
941
+ await redraw()
942
+ }
943
+ d.el.addEventListener('click', e => {
944
+ const btn = e.target.closest('[data-restore]')
945
+ if (!btn) return
946
+ const t = list.find(x => x.seq === Number(btn.dataset.restore))
947
+ if (!t) return
948
+ const orphan = t.parent?.trashed
949
+ // (Nothing to ask: back at once.)
950
+ if (!orphan && !t.subtasks) { btn.disabled = true; restore(t, false).catch(err => { d.el.querySelector('.err').textContent = err.message; btn.disabled = false }); return }
951
+ confirmDialog({
952
+ title: T.restoreTitle(t.id), text: esc(orphan ? T.restoreNoParent(t.id, t.parent.id) : T.restoreText(t.id)), confirm: T.restoreTask, settles: true,
953
+ option: t.subtasks ? T.restoreWithSubtasks(t.subtasks) : null, run: withSubs => restore(t, withSubs),
954
+ })
955
+ })
956
+ }
957
+ // (The view switch sits in the header's tabs.)
958
+ $('topTabs').addEventListener('click', e => { if (e.target.closest('[data-bmode]')) boardsTopClick(e) })