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.
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/accounts/accounts.js +754 -0
- package/accounts/index.js +1 -0
- package/accounts/passwords.js +41 -0
- package/accounts/totp.js +54 -0
- package/boards/boards.js +1079 -0
- package/boards/github.js +212 -0
- package/boards/index.js +1 -0
- package/boards/sync.js +980 -0
- package/companies.js +294 -0
- package/company-export.js +101 -0
- package/company.js +79 -0
- package/dashboard/dashboard.js +407 -0
- package/dashboard/index.js +1 -0
- package/data-upgrade.js +69 -0
- package/install/linux.sh +181 -0
- package/install/macos.sh +121 -0
- package/install/windows.bat +54 -0
- package/machines/index.js +3 -0
- package/machines/machines.js +910 -0
- package/messaging/inbox.js +252 -0
- package/messaging/index.js +3 -0
- package/messaging/messaging.js +551 -0
- package/messaging/plans.js +67 -0
- package/observation/index.js +1 -0
- package/observation/observation.js +224 -0
- package/organization/index.js +1 -0
- package/organization/organization.js +218 -0
- package/package.json +54 -4
- package/permissions/index.js +1 -0
- package/permissions/permissions.js +211 -0
- package/pisha-host.mjs +3297 -0
- package/pisha-host.mjs.sig +1 -0
- package/platform/acme.js +207 -0
- package/platform/basics.js +14 -0
- package/platform/config.js +154 -0
- package/platform/control.js +93 -0
- package/platform/credentials.js +151 -0
- package/platform/database.js +251 -0
- package/platform/errors.js +13 -0
- package/platform/files.js +50 -0
- package/platform/http.js +207 -0
- package/platform/index.js +58 -0
- package/platform/limits.js +122 -0
- package/platform/listen.js +183 -0
- package/platform/roles.js +6 -0
- package/platform/stream.js +19 -0
- package/platform/text.js +83 -0
- package/platform/ws.js +186 -0
- package/routes.js +405 -0
- package/server.js +65 -0
- package/sessions/index.js +1 -0
- package/sessions/sessions.js +533 -0
- package/ui/LICENSE-affectui.txt +26 -0
- package/ui/addmachine.js +151 -0
- package/ui/api.js +20 -0
- package/ui/app.js +143 -0
- package/ui/attention.js +78 -0
- package/ui/back.js +166 -0
- package/ui/boards.js +958 -0
- package/ui/chat.js +388 -0
- package/ui/content.js +157 -0
- package/ui/dialogs.js +135 -0
- package/ui/doing.js +112 -0
- package/ui/dom.js +6 -0
- package/ui/ds-base.css +146 -0
- package/ui/ds-components.css +229 -0
- package/ui/fonts/LICENSE-space-grotesk.txt +93 -0
- package/ui/fonts/space-grotesk-latin-700-normal.woff2 +0 -0
- package/ui/fonts/space-grotesk-latin-ext-700-normal.woff2 +0 -0
- package/ui/format.js +25 -0
- package/ui/i18n.js +2093 -0
- package/ui/icons/apple-touch-icon.png +0 -0
- package/ui/icons/icon-192.png +0 -0
- package/ui/icons/icon-512.png +0 -0
- package/ui/icons/maskable-512.png +0 -0
- package/ui/icons.js +40 -0
- package/ui/inbox.js +535 -0
- package/ui/index.html +103 -0
- package/ui/machines.js +261 -0
- package/ui/manifest.webmanifest +16 -0
- package/ui/mosaic.js +189 -0
- package/ui/nav.js +141 -0
- package/ui/newteam.js +223 -0
- package/ui/org.js +653 -0
- package/ui/overlays.css +126 -0
- package/ui/palette.js +179 -0
- package/ui/people.js +370 -0
- package/ui/permissions.js +202 -0
- package/ui/qr.js +158 -0
- package/ui/router.js +171 -0
- package/ui/routes.js +46 -0
- package/ui/screen-boards.css +241 -0
- package/ui/screen-inbox.css +201 -0
- package/ui/screen-machines.css +76 -0
- package/ui/screen-mosaic.css +26 -0
- package/ui/screen-newteam.css +90 -0
- package/ui/screen-org.css +113 -0
- package/ui/screen-session.css +99 -0
- package/ui/screen-signin.css +28 -0
- package/ui/screen-team.css +80 -0
- package/ui/screen-teams.css +41 -0
- package/ui/session.js +42 -0
- package/ui/shell.css +122 -0
- package/ui/signin.js +120 -0
- package/ui/squads.js +370 -0
- package/ui/state.js +59 -0
- package/ui/stream.js +268 -0
- package/ui/styles.css +343 -0
- package/ui/team.js +115 -0
- package/ui/teams.js +58 -0
- package/ui/terminal.js +261 -0
- package/ui/theme.js +32 -0
- package/ui/timeline.js +163 -0
- package/ui/topbar.js +205 -0
- package/ui/voice-parse.js +98 -0
- package/ui/voice.js +320 -0
- package/vendor/InterVariable.woff2 +0 -0
- package/vendor/LICENSE-inter +92 -0
- package/vendor/LICENSE-xterm +21 -0
- package/vendor/README.md +8 -0
- package/vendor/addon-fit.js +2 -0
- package/vendor/xterm.css +218 -0
- package/vendor/xterm.js +2 -0
package/ui/topbar.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { $, store } from './dom.js'
|
|
2
|
+
import { T } from './i18n.js'
|
|
3
|
+
import { sessions, state, linksOf, hosts, can } from './state.js'
|
|
4
|
+
import { esc, kfmt } from './format.js'
|
|
5
|
+
import { sortedSessions, status, agentMark } from './content.js'
|
|
6
|
+
import { setHtml } from './nav.js'
|
|
7
|
+
import { currentRoute } from './router.js'
|
|
8
|
+
import { applyCols, buildMosaic } from './mosaic.js'
|
|
9
|
+
import { runAction, openMenu } from './dialogs.js'
|
|
10
|
+
import { terminalOf, hostLine, hostAction } from './machines.js'
|
|
11
|
+
import { reopenable, reopen, addWorkerTo, saveTemplateDialog } from './squads.js'
|
|
12
|
+
import { orgSquads, orgZoom, linksDialog } from './org.js'
|
|
13
|
+
import { renderBack } from './back.js'
|
|
14
|
+
import { voiceButton } from './voice.js'
|
|
15
|
+
import { boardsHead, boardsTopClick } from './boards.js'
|
|
16
|
+
|
|
17
|
+
// The terminal a session view shows (null: its chat).
|
|
18
|
+
// (An observer has no terminals: its chat instead.)
|
|
19
|
+
export const sessionTerm = r => (r.view === 'session' && !r.chat && state.role !== 'observer' ? terminalOf(r.name) : null)
|
|
20
|
+
|
|
21
|
+
// The Pisha session behind a machine's terminal: only one that machine
|
|
22
|
+
// opened (a machine could list any name; it can't make it its own).
|
|
23
|
+
export function sessionOn(hostId, term) {
|
|
24
|
+
const s = sessions.get(term)
|
|
25
|
+
return s && s.host_id === hostId ? s : null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function roleTag(role) {
|
|
29
|
+
return role ? `<span class="role-tag ${role}">${role === 'coordinator' ? T.roleCoordinator : role === 'solo' ? T.roleSolo : T.roleWorker}</span>` : ''
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// A task's final report (done, blocked, failed, question), or information
|
|
33
|
+
// that needs none (fyi), on a message.
|
|
34
|
+
export function msgTag(it) {
|
|
35
|
+
if (['done', 'blocked', 'failed', 'question'].includes(it.report)) return ` <span class="rep ${it.report}">${T.reportTag[it.report]}</span>`
|
|
36
|
+
return it.fyi ? ` <span class="rep fyi">${T.fyiTag}</span>` : ''
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// The persona (skill or agent) a session follows.
|
|
40
|
+
export function personaTag(p) {
|
|
41
|
+
return p?.name ? `<span class="persona-tag" title="${esc(`${p.kind === 'agent' ? T.personaAgent : T.personaSkill} ${p.name}${p.description ? ` — ${p.description}` : ''}`)}">${esc(p.name)}</span>` : ''
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Teams can be seen three ways: every session, the coordinators with their
|
|
45
|
+
// teams, or the org chart.
|
|
46
|
+
const teamsSeg = view => `<nav class="seg" aria-label="${esc(T.teams)}">${[['teams', '#/teams', T.viewList], ['org', '#/org', T.org], ['mosaic', '#/mosaic', T.viewMosaic]]
|
|
47
|
+
.map(([v, href, label]) => `<a href="${href}"${v === view ? ' class="on" aria-current="page"' : ''}>${esc(label)}</a>`).join('')}</nav>`
|
|
48
|
+
|
|
49
|
+
export function renderTop() {
|
|
50
|
+
renderHead()
|
|
51
|
+
renderBack()
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function renderHead() {
|
|
55
|
+
const r = currentRoute()
|
|
56
|
+
// (Only the teams views and the inbox have a selector; a squad's own view is
|
|
57
|
+
// one team. The inbox's, with its counts, is its own: see renderInbox.)
|
|
58
|
+
if (!['org', 'teams', 'inbox'].includes(r.view) && !(r.view === 'mosaic' && !r.squad)) setHtml($('topTabs'), '')
|
|
59
|
+
if (r.view === 'inbox') {
|
|
60
|
+
// (Its subtitle, how many wait on you, is the inbox's own: see renderInbox.)
|
|
61
|
+
setHtml($('topTitle'), esc(T.inbox))
|
|
62
|
+
// (Hands-free: what waits on you, read aloud and answered by voice.)
|
|
63
|
+
setHtml($('topRight'), voiceButton())
|
|
64
|
+
return
|
|
65
|
+
}
|
|
66
|
+
if (r.view === 'boards' || r.view === 'board') {
|
|
67
|
+
// (Its subtitle, how many boards or tasks, is the board's own: see renderBoards.)
|
|
68
|
+
const h = boardsHead(r)
|
|
69
|
+
setHtml($('topTitle'), h.title); setHtml($('topTabs'), h.tabs); setHtml($('topRight'), h.right)
|
|
70
|
+
return
|
|
71
|
+
}
|
|
72
|
+
if (r.view === 'teams') {
|
|
73
|
+
// (Its subtitle, how many teams and sessions, is the list's own: see renderTeams.)
|
|
74
|
+
setHtml($('topTitle'), esc(T.teams)); setHtml($('topTabs'), teamsSeg('teams'))
|
|
75
|
+
setHtml($('topRight'), can('operator') ? `<button class="btn primary" data-newteam>${esc(T.newTeam)}</button>` : '')
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
if (r.view === 'addmachine') {
|
|
79
|
+
setHtml($('topTitle'), esc(T.addTitle))
|
|
80
|
+
$('topSub').textContent = ''
|
|
81
|
+
setHtml($('topRight'), `<a class="btn plain" href="#/hosts" data-amcancel data-back>${esc(T.cancel)}</a>`)
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
if (r.view === 'newteam') {
|
|
85
|
+
setHtml($('topTitle'), esc(T.newTeam))
|
|
86
|
+
$('topSub').textContent = ''
|
|
87
|
+
setHtml($('topRight'), `<a class="btn plain" href="#/teams" data-back>${esc(T.cancel)}</a>`)
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
if (r.view === 'team') {
|
|
91
|
+
const name = r.squad
|
|
92
|
+
const meta = state.squadMeta.get(name)
|
|
93
|
+
// (Its subtitle, who is connected, is the page's own: see renderTeam.)
|
|
94
|
+
setHtml($('topTitle'), esc(meta?.title || name))
|
|
95
|
+
setHtml($('topRight'), `<a class="btn wide-only" href="#/q/${encodeURIComponent(name)}/live">${esc(T.tqLive)}</a>${can('operator') ? `<button class="btn" data-addworker="${esc(name)}">${esc(T.tqAddWorker)}</button>` : ''}<a class="btn primary" href="#/s/${encodeURIComponent(name)}">${esc(T.tqGiveOrder)}</a>`)
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
if (r.view === 'org') {
|
|
99
|
+
const { squads } = orgSquads()
|
|
100
|
+
setHtml($('topTitle'), esc(T.teams)); setHtml($('topTabs'), teamsSeg('org'))
|
|
101
|
+
$('topSub').textContent = T.orgSub(squads.length, squads.reduce((t, q) => t + 1 + q.workers.length, 0), state.links.length)
|
|
102
|
+
setHtml($('topRight'), `<span class="seg"><button data-orgzoom="-" aria-label="${esc(T.orgZoomOut)}">−</button><button data-orgzoom="1" title="${esc(T.orgZoomReset)}">${Math.round(orgZoom * 100)}%</button><button data-orgzoom="+" aria-label="${esc(T.orgZoomIn)}">+</button></span>${can('manager') ? `<button class="btn" data-orgact="arrange" title="${esc(T.orgArrangeTitle)}">${T.orgArrange}</button>` : ''}${can('operator') ? `<button class="btn primary" data-orgact="newsquad">${T.orgNewSquad}</button>` : ''}`)
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
if (r.view === 'leads') {
|
|
106
|
+
const cs = sortedSessions().filter(s => s.role === 'coordinator')
|
|
107
|
+
const ws = sortedSessions().filter(s => s.role !== 'coordinator' && cs.some(c => c.name === s.coordinator))
|
|
108
|
+
setHtml($('topTitle'), esc(T.leads))
|
|
109
|
+
$('topSub').textContent = T.leadsSub(cs.length, ws.length)
|
|
110
|
+
setHtml($('topRight'), `<span class="seg" id="colsSeg" role="group" aria-label="${esc(T.columns)}" title="${esc(T.columns)}">${['auto', '1', '2', '3', '4'].map(n => `<button data-c="${n}" class="${n === state.cols ? 'on' : ''}">${n === 'auto' ? T.auto : n}</button>`).join('')}</span>`)
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
if (r.view === 'mosaic') {
|
|
114
|
+
// (Who has no terminals has nothing to choose.)
|
|
115
|
+
const modeSeg = !can('operator') ? '' : `<span class="seg" id="modeSeg">${['terms', 'chats'].map(m => `<button data-mode="${m}" class="${m === state.mosaicMode ? 'on' : ''}">${m === 'terms' ? T.modeTerms : T.modeChats}</button>`).join('')}</span>`
|
|
116
|
+
const colsSeg = `${modeSeg}<span class="seg" id="colsSeg" role="group" aria-label="${esc(T.columns)}" title="${esc(T.columns)}">${['auto', '2', '3', '4', '5', '6'].map(n => `<button data-c="${n}" class="${n === state.cols ? 'on' : ''}">${n === 'auto' ? T.auto : n}</button>`).join('')}</span>`
|
|
117
|
+
if (r.squad) {
|
|
118
|
+
const c = sessions.get(r.squad)
|
|
119
|
+
const ws = sortedSessions().filter(s => s.role !== 'coordinator' && s.coordinator === r.squad)
|
|
120
|
+
setHtml($('topTitle'), esc(T.tqLiveTitle(state.squadMeta.get(r.squad)?.title || r.squad)))
|
|
121
|
+
const linked = linksOf(r.squad)
|
|
122
|
+
$('topSub').textContent = [T.squadCount(ws.filter(w => w.online).length, ws.length), linked.length ? T.linkedWith(linked.join(', ')) : ''].filter(Boolean).join(' · ')
|
|
123
|
+
setHtml($('topRight'), `${colsSeg}${can('operator') ? `<button class="btn" data-addworker="${esc(r.squad)}">${esc(T.addWorker)}</button>` : ''}`)
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
setHtml($('topTitle'), esc(T.teams)); setHtml($('topTabs'), teamsSeg('mosaic'))
|
|
127
|
+
$('topSub').textContent = ''
|
|
128
|
+
setHtml($('topRight'), colsSeg)
|
|
129
|
+
} else if (r.view === 'hosts') {
|
|
130
|
+
const h = r.host && hosts.get(r.host)
|
|
131
|
+
const all = [...hosts.values()]
|
|
132
|
+
setHtml($('topTitle'), h ? `<span class="dot ${h.online ? 'ok' : 'off'}" aria-hidden="true"></span>${esc(h.name)}` : esc(T.machines))
|
|
133
|
+
$('topSub').textContent = h ? hostLine(h) : all.length ? T.mcOnline(all.filter(x => x.online).length, all.length) : ''
|
|
134
|
+
setHtml($('topRight'), `${can('manager') ? `<button class="btn" data-hact="add">${T.addMachine}</button>` : ''}${can('operator') ? `<button class="btn" data-hact="templates">${T.templates}</button><button class="btn primary" data-hact="new"${h ? ` data-h="${esc(h.id)}"` : ''}>${T.newSession}</button>` : ''}`)
|
|
135
|
+
} else if (r.view === 'terminal') {
|
|
136
|
+
const h = hosts.get(r.host)
|
|
137
|
+
const t = h?.info?.terminals?.find(x => x.id === r.term)
|
|
138
|
+
const s = sessionOn(r.host, r.term)
|
|
139
|
+
setHtml($('topTitle'), `<span class="dot ${s ? status(s).dot : ''}"></span>⌨ ${esc(r.term)} ${roleTag(s?.role ?? t?.role)} ${personaTag(s?.persona ?? t?.persona)}`)
|
|
140
|
+
$('topSub').textContent = [h ? T.onHost(h.name) : '', t?.folder ?? '', h?.info && !t ? T.notListed : ''].filter(Boolean).join(' · ')
|
|
141
|
+
const acts = []
|
|
142
|
+
if (s) acts.push(`<button class="btn" data-go="#/s/${encodeURIComponent(r.term)}/chat">${T.chat}</button>`)
|
|
143
|
+
acts.push(`<button class="btn" data-tact="redraw">${T.redraw}</button>`)
|
|
144
|
+
if (t && h?.online) acts.push(`<button class="btn danger" data-tact="kill">${T.closeSession}</button>`)
|
|
145
|
+
setHtml($('topRight'), acts.join(''))
|
|
146
|
+
} else if (r.view === 'archived') {
|
|
147
|
+
setHtml($('topTitle'), T.archivedTitle)
|
|
148
|
+
$('topSub').textContent = T.archivedSub
|
|
149
|
+
setHtml($('topRight'), '')
|
|
150
|
+
} else {
|
|
151
|
+
const s = sessions.get(r.name)
|
|
152
|
+
const st = status(s)
|
|
153
|
+
const role = s?.role === 'coordinator' ? 'coord' : s?.role === 'solo' ? 'solo' : 'worker'
|
|
154
|
+
const team = s?.role === 'coordinator' ? s.name : s?.coordinator
|
|
155
|
+
const teamName = team ? state.squadMeta.get(team)?.title || team : ''
|
|
156
|
+
setHtml($('topTitle'), `<span class="role ${role}" aria-hidden="true"></span>${agentMark(r.name)}<span class="sv-name">${esc(r.name)}</span>${s?.archived_at ? ` <span class="tag">${esc(T.archivedTag)}</span>` : ''}`)
|
|
157
|
+
$('topSub').textContent = [s ? T.roleName[s.role] ?? T.roleName.worker : '', teamName, st.text].filter(Boolean).join(' · ')
|
|
158
|
+
// Its conversation, or its live terminal when it has one.
|
|
159
|
+
const where = terminalOf(r.name)
|
|
160
|
+
const termOn = !!(where && !r.chat && can('operator'))
|
|
161
|
+
if (where && can('operator')) setHtml($('topTabs'), `<nav class="seg" aria-label="${esc(r.name)}"><a href="#/s/${encodeURIComponent(r.name)}/chat"${termOn ? '' : ' class="on" aria-current="page"'}>${esc(T.svChat)}</a><a href="#/s/${encodeURIComponent(r.name)}"${termOn ? ' class="on" aria-current="page"' : ''}>${esc(T.terminal)}</a></nav>`)
|
|
162
|
+
else setHtml($('topTabs'), '')
|
|
163
|
+
const acts = []
|
|
164
|
+
if (reopenable(s) && can('operator')) acts.push(`<button class="btn primary" data-reopen="${esc(r.name)}">${T.reopen}</button>`)
|
|
165
|
+
if (s?.approval_pending && can('manager')) acts.push(`<button class="btn primary ok" data-act="approve" data-s="${esc(s.name)}">${T.approve}</button>`)
|
|
166
|
+
if (termOn) acts.push(`<button class="btn quiet" data-tact="redraw">${esc(T.redraw)}</button><button class="btn quiet danger" data-tact="kill">${esc(T.closeSession)}</button>`)
|
|
167
|
+
if (s && !termOn && !s.online && can('operator')) acts.push(s.archived_at
|
|
168
|
+
? `<button class="btn" data-act="unarchive" data-s="${esc(s.name)}">${T.unarchive}</button>`
|
|
169
|
+
: `<button class="btn" data-act="archive" data-s="${esc(s.name)}">${T.archive}</button>`)
|
|
170
|
+
if (s) acts.push(`<button class="btn quiet" data-menu="${esc(s.name)}" aria-haspopup="menu" aria-label="${esc(T.svMore(s.name))}">${esc(T.svMoreShort)}</button>`)
|
|
171
|
+
setHtml($('topRight'), acts.join(''))
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
$('topRight').addEventListener('click', e => {
|
|
176
|
+
if (boardsTopClick(e)) return
|
|
177
|
+
const c = e.target.closest('[data-c]')
|
|
178
|
+
if (c) { state.cols = c.dataset.c; store.set('pishaCols', state.cols); applyCols(); renderTop() }
|
|
179
|
+
const ro = e.target.closest('[data-reopen]')
|
|
180
|
+
if (ro) return reopen(ro.dataset.reopen)
|
|
181
|
+
const md = e.target.closest('[data-mode]')
|
|
182
|
+
if (md) { state.mosaicMode = md.dataset.mode === 'chats' ? 'chats' : 'terms'; store.set('pishaMosaicMode', state.mosaicMode); buildMosaic(); renderTop() }
|
|
183
|
+
const go = e.target.closest('[data-go]')
|
|
184
|
+
if (go) location.hash = go.dataset.go
|
|
185
|
+
const act = e.target.closest('[data-act]')
|
|
186
|
+
if (act) runAction(act.dataset.act, act.dataset.s)
|
|
187
|
+
const hact = e.target.closest('[data-hact]')
|
|
188
|
+
if (hact) hostAction(hact.dataset.hact, hact.dataset.h)
|
|
189
|
+
if (e.target.closest('[data-newteam]')) { location.hash = '#/new'; return }
|
|
190
|
+
const aw = e.target.closest('[data-addworker]')
|
|
191
|
+
if (aw) addWorkerTo(aw.dataset.addworker)
|
|
192
|
+
const stp = e.target.closest('[data-savetpl]')
|
|
193
|
+
if (stp) saveTemplateDialog(stp.dataset.savetpl)
|
|
194
|
+
const lk = e.target.closest('[data-links]')
|
|
195
|
+
if (lk) linksDialog(lk.dataset.links)
|
|
196
|
+
const menu = e.target.closest('[data-menu]')
|
|
197
|
+
if (menu) return openMenu(menu, menu.dataset.menu)
|
|
198
|
+
const tact = e.target.closest('[data-tact]')
|
|
199
|
+
if (tact) {
|
|
200
|
+
const r = currentRoute()
|
|
201
|
+
const st = sessionTerm(r)
|
|
202
|
+
if (tact.dataset.tact === 'redraw') state.termView?.refresh()
|
|
203
|
+
if (tact.dataset.tact === 'kill') hostAction('kill', r.host ?? st?.host.id, r.term ?? r.name)
|
|
204
|
+
}
|
|
205
|
+
})
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// What was said, while the inbox is read aloud: a command, an option (with
|
|
2
|
+
// whatever detail follows it), or an answer in the user's own words. In
|
|
3
|
+
// Spanish and in English alike, whatever the dashboard's language: people mix.
|
|
4
|
+
// (No DOM here: the tests load it on its own.)
|
|
5
|
+
|
|
6
|
+
// Lower case, without accents or punctuation around the words.
|
|
7
|
+
export const normalize = text => String(text ?? '')
|
|
8
|
+
.toLowerCase()
|
|
9
|
+
.normalize('NFD').replace(/[̀-ͯ]/g, '')
|
|
10
|
+
.replace(/[¿¡!?.,;:"«»()]/g, ' ')
|
|
11
|
+
.replace(/\s+/g, ' ')
|
|
12
|
+
.trim()
|
|
13
|
+
|
|
14
|
+
// Said on their own, these steer the reading instead of answering.
|
|
15
|
+
const COMMANDS = {
|
|
16
|
+
stop: ['para', 'parar', 'salir', 'sal', 'cuelga', 'colgar', 'termina', 'terminar', 'fin', 'stop', 'exit', 'quit', 'hang up', 'end'],
|
|
17
|
+
next: ['siguiente', 'salta', 'saltar', 'saltala', 'luego', 'despues', 'mas tarde', 'pasa', 'next', 'skip', 'later'],
|
|
18
|
+
repeat: ['repite', 'repitelo', 'repitela', 'otra vez', 'como', 'que', 'repeat', 'again', 'say again', 'what'],
|
|
19
|
+
done: ['hecho', 'leido', 'entendido', 'visto', 'done', 'read', 'got it', 'seen'],
|
|
20
|
+
dismiss: ['descarta', 'descartar', 'descartala', 'dismiss'],
|
|
21
|
+
}
|
|
22
|
+
const YES = ['si', 'vale', 'envia', 'enviala', 'envialo', 'de acuerdo', 'ok', 'okay', 'correcto', 'eso es', 'adelante', 'yes', 'yeah', 'yep', 'send', 'send it', 'sure', 'correct', 'go ahead']
|
|
23
|
+
const NO = ['no', 'cambia', 'cambiar', 'cambialo', 'espera', 'nope', 'change', 'change it', 'wait']
|
|
24
|
+
|
|
25
|
+
// The option's number, said as a word or a digit.
|
|
26
|
+
const NUMBERS = [
|
|
27
|
+
['1', 'uno', 'una', 'primera', 'primero', 'one', 'first'],
|
|
28
|
+
['2', 'dos', 'segunda', 'segundo', 'two', 'second'],
|
|
29
|
+
['3', 'tres', 'tercera', 'tercero', 'three', 'third'],
|
|
30
|
+
['4', 'cuatro', 'cuarta', 'cuarto', 'four', 'fourth'],
|
|
31
|
+
['5', 'cinco', 'quinta', 'quinto', 'five', 'fifth'],
|
|
32
|
+
['6', 'seis', 'sexta', 'sexto', 'six', 'sixth'],
|
|
33
|
+
]
|
|
34
|
+
const NUMBER_OF = new Map(NUMBERS.flatMap((words, n) => words.map(w => [w, n])))
|
|
35
|
+
// Words before the choice ("la dos", "opción 2", "the second one", "number three").
|
|
36
|
+
const LEAD = new Set(['la', 'el', 'lo', 'opcion', 'numero', 'quiero', 'elijo', 'option', 'number', 'the', 'choose', 'pick', 'i'])
|
|
37
|
+
const AFTER = new Set(['one', 'option', 'opcion'])
|
|
38
|
+
const RECOMMENDED = [['recomendada'], ['recomendado'], ['que', 'recomiendas'], ['que', 'recomienda'], ['recommended'], ['what', 'you', 'recommend']]
|
|
39
|
+
// Words that only join the detail to the choice ("la dos, y que sea el lunes").
|
|
40
|
+
const JOINERS = new Set(['y', 'e', 'pero', 'con', 'and', 'but', 'with'])
|
|
41
|
+
const ARTICLES = new Set(['una', 'uno', 'one'])
|
|
42
|
+
|
|
43
|
+
// yes / no / null, for the question "do I send it?"
|
|
44
|
+
export function yesNo(text) {
|
|
45
|
+
const t = normalize(text)
|
|
46
|
+
if (YES.includes(t) || YES.some(w => t.startsWith(`${w} `))) return true
|
|
47
|
+
if (NO.includes(t) || NO.some(w => t.startsWith(`${w} `))) return false
|
|
48
|
+
return null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// { kind: 'command', cmd } | { kind: 'option', n, detail } | { kind: 'free', text } | { kind: 'empty' }
|
|
52
|
+
// The detail and the free text keep what was said as it was said, only trimmed.
|
|
53
|
+
export function parseUtterance(text, { options = 0, recommended = -1 } = {}) {
|
|
54
|
+
const said = String(text ?? '').trim()
|
|
55
|
+
const t = normalize(said)
|
|
56
|
+
if (!t) return { kind: 'empty' }
|
|
57
|
+
for (const [cmd, words] of Object.entries(COMMANDS)) if (words.includes(t)) return { kind: 'command', cmd }
|
|
58
|
+
if (options) {
|
|
59
|
+
// Each word as said, with how it reads (punctuation alone is no word).
|
|
60
|
+
const words = said.split(/\s+/).map(raw => ({ raw, n: normalize(raw) })).filter(w => w.n)
|
|
61
|
+
let i = 0
|
|
62
|
+
while (i < words.length && LEAD.has(words[i].n)) i++
|
|
63
|
+
let n = NUMBER_OF.get(words[i]?.n)
|
|
64
|
+
let next = i + 1
|
|
65
|
+
// ("una cosa más", "one more thing": an article, not a choice, unless it is introduced or alone.)
|
|
66
|
+
if (ARTICLES.has(words[i]?.n) && i === 0 && words.length > 1 && !JOINERS.has(words[1].n) && !AFTER.has(words[1].n) && !/[,.;:]$/.test(words[0].raw)) n = null
|
|
67
|
+
if (n == null && recommended >= 0) {
|
|
68
|
+
const p = RECOMMENDED.find(p => p.every((w, k) => words[i + k]?.n === w))
|
|
69
|
+
if (p) { n = recommended; next = i + p.length }
|
|
70
|
+
}
|
|
71
|
+
if (n != null && n < options) {
|
|
72
|
+
if (AFTER.has(words[next]?.n)) next++
|
|
73
|
+
return { kind: 'option', n, detail: tidy(words.slice(next)) }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return { kind: 'free', text: said }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// What follows the choice, without the words that only join it.
|
|
80
|
+
function tidy(words) {
|
|
81
|
+
let k = 0
|
|
82
|
+
while (k < words.length && JOINERS.has(words[k].n)) k++
|
|
83
|
+
return words.slice(k).map(w => w.raw).join(' ').replace(/^[\s,.;:—–-]+/, '').trim()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Text to be read aloud: no markdown, no links spelled out, no long paths.
|
|
87
|
+
export function speakable(text, { link = 'a link', path = 'a file' } = {}) {
|
|
88
|
+
return String(text ?? '')
|
|
89
|
+
.replace(/```[\s\S]*?```/g, ' ')
|
|
90
|
+
.replace(/`([^`]*)`/g, '$1')
|
|
91
|
+
.replace(/https?:\/\/\S+/g, link)
|
|
92
|
+
.replace(/(?:^|\s)(?:\/[\w.-]+){2,}\/?/g, ` ${path}`)
|
|
93
|
+
.replace(/\*\*|__|[*_]/g, '')
|
|
94
|
+
.replace(/[#>|]/g, ' ')
|
|
95
|
+
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
96
|
+
.replace(/\s+/g, ' ')
|
|
97
|
+
.trim()
|
|
98
|
+
}
|
package/ui/voice.js
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// The inbox read aloud, and answered by voice: hands-free, for a phone.
|
|
2
|
+
// It reads each decision that can be answered from here, with its options,
|
|
3
|
+
// listens for the answer, says back what it understood and sends it only
|
|
4
|
+
// once the user says yes. Then what there is to know, which can be replied
|
|
5
|
+
// to or marked done. Everything runs in the browser: its speech recognition
|
|
6
|
+
// and its voices (Chrome on Android sends the audio to Google to recognise it:
|
|
7
|
+
// the user is told before the first time).
|
|
8
|
+
|
|
9
|
+
import { $ } from './dom.js'
|
|
10
|
+
import { T, LANG, LOCALE } from './i18n.js'
|
|
11
|
+
import { state, can, sessions } from './state.js'
|
|
12
|
+
import { esc } from './format.js'
|
|
13
|
+
import { postJson } from './machines.js'
|
|
14
|
+
import { alertBox } from './mosaic.js'
|
|
15
|
+
import { confirmDialog } from './dialogs.js'
|
|
16
|
+
import { replaceHash } from './back.js'
|
|
17
|
+
import { currentRoute } from './router.js'
|
|
18
|
+
import { cantAnswer } from './inbox.js'
|
|
19
|
+
import { icon } from './icons.js'
|
|
20
|
+
import { parseUtterance, yesNo, speakable } from './voice-parse.js'
|
|
21
|
+
|
|
22
|
+
const Recognition = window.SpeechRecognition ?? window.webkitSpeechRecognition
|
|
23
|
+
const SPEECH_LANG = LANG === 'es' ? 'es-ES' : 'en-GB'
|
|
24
|
+
const CONSENT = 'pisha.voice-ok'
|
|
25
|
+
const HEARD_TRIES = 2 // silences in a row before moving on
|
|
26
|
+
// How fast it reads, as on a voice message: a tap on the chip, the next one.
|
|
27
|
+
// (Small steps: past 1.2 the voices get hard to follow.)
|
|
28
|
+
const RATES = [1, 1.1, 1.2]
|
|
29
|
+
const RATE_KEY = 'pisha.voice-rate'
|
|
30
|
+
let rate = (() => { try { const r = Number(localStorage.getItem(RATE_KEY)); return RATES.includes(r) ? r : 1 } catch { return 1 } })()
|
|
31
|
+
// (Said in words, normal, fast, faster: a number says little about a voice.)
|
|
32
|
+
const rateLabel = r => T.vRates[RATES.indexOf(r)] ?? `${r.toLocaleString(LOCALE)}×`
|
|
33
|
+
|
|
34
|
+
export const voiceSupported = () => !!Recognition && 'speechSynthesis' in window
|
|
35
|
+
export const voiceButton = () => (can('operator') ? `<button type="button" class="btn" data-voice aria-pressed="${!!run}">${icon('mic')}<span>${esc(run ? T.vStop : T.vListen)}</span></button>` : '')
|
|
36
|
+
|
|
37
|
+
let run = null // the reading going on: { stopped, utterance, recognition, lock }
|
|
38
|
+
|
|
39
|
+
// --- speaking and listening -------------------------------------------------
|
|
40
|
+
|
|
41
|
+
function voiceFor() {
|
|
42
|
+
const voices = speechSynthesis.getVoices()
|
|
43
|
+
return voices.find(v => v.lang === SPEECH_LANG) ?? voices.find(v => v.lang?.startsWith(LANG)) ?? null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Said aloud; resolves when it ends, is cut short (a tap) or the reading stops.
|
|
47
|
+
// A new speed takes effect at once: the sentence it was in is said again, faster
|
|
48
|
+
// or slower (where it is going comes from the voice's word boundaries, when it
|
|
49
|
+
// gives them; if not, from the start).
|
|
50
|
+
function say(text) {
|
|
51
|
+
if (!run || run.stopped) return Promise.resolve()
|
|
52
|
+
show(text, 'speaking')
|
|
53
|
+
return new Promise(resolve => {
|
|
54
|
+
const from = start => {
|
|
55
|
+
const u = new SpeechSynthesisUtterance(text.slice(start))
|
|
56
|
+
u.lang = SPEECH_LANG
|
|
57
|
+
u.rate = rate
|
|
58
|
+
const v = voiceFor(); if (v) u.voice = v
|
|
59
|
+
u.onboundary = e => { if (run) run.at = start + (e.charIndex ?? 0) }
|
|
60
|
+
u.onend = u.onerror = () => {
|
|
61
|
+
if (u.replaced) return
|
|
62
|
+
if (run?.utterance === u) { run.utterance = null; run.again = null }
|
|
63
|
+
resolve()
|
|
64
|
+
}
|
|
65
|
+
run.utterance = u
|
|
66
|
+
run.at = start
|
|
67
|
+
run.again = () => {
|
|
68
|
+
u.replaced = true
|
|
69
|
+
speechSynthesis.cancel()
|
|
70
|
+
// (A moment for the voice to stop: some drop what is said right after a cancel.)
|
|
71
|
+
setTimeout(() => { if (run && !run.stopped) from(sentenceStart(text, run.at ?? start)); else resolve() }, 60)
|
|
72
|
+
}
|
|
73
|
+
speechSynthesis.speak(u)
|
|
74
|
+
}
|
|
75
|
+
from(0)
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
// Where the sentence that has position at begins.
|
|
79
|
+
function sentenceStart(text, at) {
|
|
80
|
+
let s = 0
|
|
81
|
+
for (const m of text.slice(0, at).matchAll(/[.?!…:]\s+/g)) s = m.index + m[0].length
|
|
82
|
+
return s
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// What the user says next ('' after a silence, or once the reading stops).
|
|
86
|
+
function listen() {
|
|
87
|
+
if (!run || run.stopped) return Promise.resolve('')
|
|
88
|
+
show('', 'listening')
|
|
89
|
+
return new Promise(resolve => {
|
|
90
|
+
const r = new Recognition()
|
|
91
|
+
r.lang = SPEECH_LANG
|
|
92
|
+
r.interimResults = true
|
|
93
|
+
r.maxAlternatives = 1
|
|
94
|
+
let heard = ''
|
|
95
|
+
r.onresult = e => {
|
|
96
|
+
heard = [...e.results].map(x => x[0].transcript).join(' ').trim()
|
|
97
|
+
show(heard, 'listening')
|
|
98
|
+
}
|
|
99
|
+
r.onerror = e => { if (e.error === 'not-allowed' || e.error === 'service-not-allowed') stop(T.vMicDenied) }
|
|
100
|
+
r.onend = () => { if (run?.recognition === r) run.recognition = null; resolve(heard) }
|
|
101
|
+
run.recognition = r
|
|
102
|
+
try { r.start() } catch { resolve('') }
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// --- the bar at the bottom: what is said, what was heard ---------------------
|
|
107
|
+
|
|
108
|
+
function show(text, mode) {
|
|
109
|
+
let bar = $('voiceBar')
|
|
110
|
+
if (!bar) {
|
|
111
|
+
bar = document.createElement('div')
|
|
112
|
+
bar.id = 'voiceBar'
|
|
113
|
+
bar.className = 'voice-bar'
|
|
114
|
+
bar.setAttribute('role', 'status')
|
|
115
|
+
bar.innerHTML = `<div class="voice-head"><span class="voice-mode"></span><button type="button" class="voice-speed" data-voicespeed></button></div>
|
|
116
|
+
<button type="button" class="voice-say" data-voicecut><span class="voice-text"></span></button>
|
|
117
|
+
<div class="voice-actions"><button type="button" class="btn" data-voicenext>${esc(T.vNext)}</button><button type="button" class="btn danger" data-voicestop>${esc(T.vStop)}</button></div>`
|
|
118
|
+
document.body.appendChild(bar)
|
|
119
|
+
}
|
|
120
|
+
bar.dataset.mode = mode
|
|
121
|
+
const label = mode === 'listening' ? T.vListening : mode === 'sending' ? T.vSending : T.vSpeaking
|
|
122
|
+
bar.querySelector('.voice-mode').textContent = label
|
|
123
|
+
bar.querySelector('.voice-text').textContent = text
|
|
124
|
+
showRate(bar)
|
|
125
|
+
}
|
|
126
|
+
function showRate(bar = $('voiceBar')) {
|
|
127
|
+
const b = bar?.querySelector('[data-voicespeed]')
|
|
128
|
+
if (!b) return
|
|
129
|
+
b.textContent = rateLabel(rate)
|
|
130
|
+
b.setAttribute('aria-label', T.vSpeed(rateLabel(rate)))
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// A tap while it speaks cuts it short; "next" skips what is being read.
|
|
134
|
+
document.addEventListener('click', e => {
|
|
135
|
+
if (e.target.closest('[data-voicespeed]')) {
|
|
136
|
+
rate = RATES[(RATES.indexOf(rate) + 1) % RATES.length]
|
|
137
|
+
try { localStorage.setItem(RATE_KEY, String(rate)) } catch {}
|
|
138
|
+
showRate()
|
|
139
|
+
run?.again?.()
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
if (e.target.closest('[data-voicecut]') && run?.utterance) { speechSynthesis.cancel(); return }
|
|
143
|
+
if (e.target.closest('[data-voicenext]') && run) { run.skip = true; cutShort(); return }
|
|
144
|
+
if (e.target.closest('[data-voicestop]')) { stop(); return }
|
|
145
|
+
if (e.target.closest('[data-voice]')) { run ? stop() : start(); return }
|
|
146
|
+
})
|
|
147
|
+
function cutShort() {
|
|
148
|
+
speechSynthesis.cancel()
|
|
149
|
+
try { run?.recognition?.abort() } catch {}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// --- what is read ----------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
// What can be done here: decisions answered from the dashboard, then notes.
|
|
155
|
+
// (A decision that has to be answered in its session is only mentioned.)
|
|
156
|
+
function queue(skipped) {
|
|
157
|
+
const open = state.inbox.filter(i => !i.resolved_at && !skipped.has(i.id))
|
|
158
|
+
const asks = open.filter(i => i.kind === 'ask').sort((a, b) => a.id - b.id)
|
|
159
|
+
const tells = open.filter(i => i.kind === 'tell').sort((a, b) => a.id - b.id)
|
|
160
|
+
return [...asks, ...tells]
|
|
161
|
+
}
|
|
162
|
+
const team = name => state.squadMeta.get(sessions.get(name)?.role === 'coordinator' ? name : sessions.get(name)?.coordinator)?.title || name
|
|
163
|
+
const clean = text => speakable(text, { link: T.vLink, path: T.vPath })
|
|
164
|
+
// (Each part ends as a sentence, so the voice pauses before the next.)
|
|
165
|
+
const sentence = text => (/[.?!…:]$/.test(text) ? text : `${text}.`)
|
|
166
|
+
const recIndexOf = i => {
|
|
167
|
+
const rec = String(i.recommended ?? '').trim().toLowerCase()
|
|
168
|
+
return rec ? i.options.findIndex(o => { const t = o.trim().toLowerCase(); return rec === t || (rec.startsWith(t) && /^[\s:.,;—–-]/.test(rec.slice(t.length))) }) : -1
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function readAsk(i) {
|
|
172
|
+
const rec = recIndexOf(i)
|
|
173
|
+
const opts = i.options.map((o, n) => T.vOption(n + 1, clean(o))).join(' ')
|
|
174
|
+
return [T.vAskFrom(i.session, team(i.session)), sentence(clean(i.text)), opts, rec >= 0 ? T.vRecommends(rec + 1) : '', i.options.length ? T.vHowAnswerOptions : T.vHowAnswer].filter(Boolean).join(' ')
|
|
175
|
+
}
|
|
176
|
+
const readTell = i => [T.vTellFrom(i.session, team(i.session)), sentence(clean(i.text)), cantAnswer(i) ? T.vHowDoneOnly : T.vHowTell].join(' ')
|
|
177
|
+
|
|
178
|
+
// "Stop" or "next" said where a yes or a no was expected: they still apply.
|
|
179
|
+
// true: it was one of them (and done).
|
|
180
|
+
async function steered(heard) {
|
|
181
|
+
const p = parseUtterance(heard)
|
|
182
|
+
if (p.kind !== 'command') return false
|
|
183
|
+
if (p.cmd === 'stop') { stop(); return true }
|
|
184
|
+
if (p.cmd === 'next') { if (run) run.skip = true; await say(T.vSkipped); return true }
|
|
185
|
+
return false
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// The answer read back, and sent only on a yes. true: sent.
|
|
189
|
+
async function confirmAndSend(i, answer, what) {
|
|
190
|
+
await say(T.vConfirm(what))
|
|
191
|
+
for (let k = 0; k < HEARD_TRIES && !run?.stopped && !run?.skip; k++) {
|
|
192
|
+
const heard = await listen()
|
|
193
|
+
if (await steered(heard)) return false
|
|
194
|
+
const yn = yesNo(heard)
|
|
195
|
+
if (yn === true) {
|
|
196
|
+
show(what, 'sending')
|
|
197
|
+
try {
|
|
198
|
+
await postJson('/api/inbox/answer', { id: i.id, version: i.version, answer })
|
|
199
|
+
await say(T.vSent)
|
|
200
|
+
return true
|
|
201
|
+
} catch (err) {
|
|
202
|
+
await say(err.reason === 'changed' ? T.vChanged : T.vFailed(err.message))
|
|
203
|
+
return false
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (yn === false) { await say(T.vSayAgain); return false }
|
|
207
|
+
await say(T.vYesOrNo)
|
|
208
|
+
}
|
|
209
|
+
return false
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function handle(i) {
|
|
213
|
+
// Fresh from the inbox: it may have changed, or closed, while another was read.
|
|
214
|
+
const now = () => state.inbox.find(x => x.id === i.id)
|
|
215
|
+
replaceHash(`#/inbox/i${i.id}`)
|
|
216
|
+
const ask = i.kind === 'ask'
|
|
217
|
+
if (ask && cantAnswer(i)) { await say(`${T.vAskFrom(i.session, team(i.session))} ${sentence(clean(i.text))} ${T.vAnswerInSession}`); return }
|
|
218
|
+
await say(ask ? readAsk(i) : readTell(i))
|
|
219
|
+
let silences = 0
|
|
220
|
+
while (run && !run.stopped && !run.skip) {
|
|
221
|
+
const cur = now()
|
|
222
|
+
if (!cur || cur.resolved_at) return
|
|
223
|
+
if (cur.version !== i.version) { i = cur; await say(`${T.vChanged} ${ask ? readAsk(i) : readTell(i)}`); continue }
|
|
224
|
+
const heard = await listen()
|
|
225
|
+
if (!run || run.stopped || run.skip) return
|
|
226
|
+
const p = parseUtterance(heard, { options: ask ? i.options.length : 0, recommended: ask ? recIndexOf(i) : -1 })
|
|
227
|
+
if (p.kind === 'empty') {
|
|
228
|
+
if (++silences >= HEARD_TRIES) { await say(T.vMovingOn); return }
|
|
229
|
+
await say(T.vDidntHear); continue
|
|
230
|
+
}
|
|
231
|
+
silences = 0
|
|
232
|
+
if (p.kind === 'command') {
|
|
233
|
+
if (p.cmd === 'stop') return stop()
|
|
234
|
+
if (p.cmd === 'next') return say(T.vSkipped)
|
|
235
|
+
if (p.cmd === 'repeat') { await say(ask ? readAsk(i) : readTell(i)); continue }
|
|
236
|
+
if (p.cmd === 'done' && !ask) {
|
|
237
|
+
try { await postJson('/api/inbox/resolve', { id: i.id }); await say(T.vMarkedDone) } catch (err) { await say(T.vFailed(err.message)) }
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
if (p.cmd === 'dismiss' && ask) {
|
|
241
|
+
await say(T.vConfirmDismiss)
|
|
242
|
+
const heard = await listen()
|
|
243
|
+
if (await steered(heard)) return
|
|
244
|
+
if (yesNo(heard) === true) {
|
|
245
|
+
try { await postJson('/api/inbox/dismiss', { id: i.id }); await say(T.vDismissed) } catch (err) { await say(T.vFailed(err.message)) }
|
|
246
|
+
return
|
|
247
|
+
}
|
|
248
|
+
await say(T.vSayAgain); continue
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (!ask && cantAnswer(i)) { await say(T.vHowDoneOnly); continue }
|
|
252
|
+
if (p.kind === 'option') {
|
|
253
|
+
const choice = i.options[p.n]
|
|
254
|
+
const answer = p.detail ? `${choice}. ${p.detail}` : choice
|
|
255
|
+
if (await confirmAndSend(i, answer, T.vOptionSaid(p.n + 1, choice, p.detail))) return
|
|
256
|
+
continue
|
|
257
|
+
}
|
|
258
|
+
// In their own words (also a command that doesn't apply here, as said).
|
|
259
|
+
const text = p.kind === 'free' ? p.text : heard
|
|
260
|
+
if (await confirmAndSend(i, text, T.vWordsSaid(text))) return
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// --- starting and stopping ---------------------------------------------------
|
|
265
|
+
|
|
266
|
+
async function start() {
|
|
267
|
+
if (!window.isSecureContext) return alertBox(T.vNeedsHttps)
|
|
268
|
+
if (!voiceSupported()) return alertBox(T.vUnsupported)
|
|
269
|
+
let ok = false
|
|
270
|
+
try { ok = localStorage.getItem(CONSENT) === '1' } catch {}
|
|
271
|
+
if (!ok) {
|
|
272
|
+
return confirmDialog({ title: T.vConsentTitle, text: esc(T.vConsent), confirm: T.vConsentOk, settles: true, run: async () => {
|
|
273
|
+
try { localStorage.setItem(CONSENT, '1') } catch {}
|
|
274
|
+
setTimeout(begin) // (after the dialog closes: its button was the gesture that lets it speak)
|
|
275
|
+
} })
|
|
276
|
+
}
|
|
277
|
+
begin()
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function begin() {
|
|
281
|
+
if (run) return
|
|
282
|
+
run = { stopped: false, skip: false, utterance: null, recognition: null, lock: null }
|
|
283
|
+
refreshButton()
|
|
284
|
+
try { run.lock = await navigator.wakeLock?.request('screen') } catch {}
|
|
285
|
+
const skipped = new Set()
|
|
286
|
+
const first = queue(skipped)
|
|
287
|
+
const asks = first.filter(i => i.kind === 'ask').length
|
|
288
|
+
await say(first.length ? T.vStart(asks, first.length - asks) : T.vNothing)
|
|
289
|
+
while (run && !run.stopped) {
|
|
290
|
+
const next = queue(skipped)[0]
|
|
291
|
+
if (!next) break
|
|
292
|
+
skipped.add(next.id) // (read once each time round; what is left open stays open)
|
|
293
|
+
run.skip = false
|
|
294
|
+
await handle(next)
|
|
295
|
+
}
|
|
296
|
+
if (run && !run.stopped && first.length) await say(queue(new Set()).length ? T.vEndSome : T.vEnd)
|
|
297
|
+
stop()
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function stop(why = '') {
|
|
301
|
+
if (!run) return
|
|
302
|
+
run.stopped = true
|
|
303
|
+
cutShort()
|
|
304
|
+
try { run.lock?.release() } catch {}
|
|
305
|
+
run = null
|
|
306
|
+
$('voiceBar')?.remove()
|
|
307
|
+
refreshButton()
|
|
308
|
+
if (why) alertBox(why)
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function refreshButton() {
|
|
312
|
+
for (const b of document.querySelectorAll('[data-voice]')) {
|
|
313
|
+
b.setAttribute('aria-pressed', String(!!run))
|
|
314
|
+
b.querySelector('span').textContent = run ? T.vStop : T.vListen
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Leaving the inbox, or the page, ends it.
|
|
319
|
+
window.addEventListener('hashchange', () => { if (run && currentRoute().view !== 'inbox') stop() })
|
|
320
|
+
window.addEventListener('pagehide', () => stop())
|
|
Binary file
|