@leftoff/cli 0.9.8-beta.2 → 0.9.8-beta.21

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/ui/tour.js ADDED
@@ -0,0 +1,364 @@
1
+ // The product tour (0.9.8): six quick spotlight steps over the real board,
2
+ // separate from the setup wizard (ui/wizard.js). It dims the page, cuts a hole
3
+ // around the part it talks about and puts a small card beside it. A part that
4
+ // isn't on screen (no session yet, tabs on a phone, Live outside a session)
5
+ // gets the card in the middle with a small drawing instead: never a spotlight
6
+ // on nothing, and nothing is written into your sessions for it.
7
+ //
8
+ // It runs by itself once per Mac (the record sits beside the wizard's,
9
+ // GET /v1/tour, POST /v1/tour/seen), after setup has been seen, on a plain
10
+ // board open. Settings → Updates & about → "Take the tour" and the command
11
+ // palette replay it (#/tour). The pure parts below are shared with the unit
12
+ // tests; startTour() is the DOM side.
13
+
14
+ export const TOUR_KEYS = ['needs', 'card', 'live', 'tabs', 'catchup', 'phone']
15
+
16
+ // Does the board start it by itself? state: GET /v1/tour. routeName: the
17
+ // route the board is on. Not over the setup wizard: on this Mac's own board
18
+ // it waits until setup has been seen (another device never gets the wizard).
19
+ export function shouldAutoTour(state, routeName) {
20
+ return !!state && state.auto === true && state.seen === false && (state.setupSeen === true || state.local === false) && (!routeName || routeName === 'board')
21
+ }
22
+
23
+ // The six steps for what's on screen. found: { needs: 'strip' | 'nav' | null,
24
+ // card: bool, live: bool, tabs: 'strip' | 'row' | null, catchup: bool }.
25
+ // ctx: { narrow: phone width, standalone: the Home Screen app, host: the
26
+ // leftoff.dev name or null }. Each step: { key, title, body, target, illus }:
27
+ // target names what to spotlight (null: the card sits in the middle with
28
+ // illus, a small drawing).
29
+ export function tourSteps(found = {}, ctx = {}) {
30
+ const f = found || {}
31
+ const host = ctx.host || 'yourname.leftoff.dev'
32
+ const steps = []
33
+ steps.push(f.needs === 'strip'
34
+ ? { key: 'needs', title: 'Needs you', body: 'Sessions waiting on you come first: a permission prompt or a question from Claude. Answer right here, or Go to the terminal.', target: 'needs-strip', illus: null }
35
+ : { key: 'needs', title: 'Needs you', body: 'When a session stops for a permission prompt or a question, it lands here, longest wait first. Answer from the board, or Go to the terminal.', target: f.needs === 'nav' ? 'needs-nav' : null, illus: f.needs === 'nav' ? null : 'needs' })
36
+ steps.push({ key: 'card', title: 'A session', body: 'One card per Claude Code session: its status and its latest checkpoint (what it was doing, where it stopped, what’s next). Go jumps to its terminal, Resume reopens a closed one, and Checkpoint now is in the ⋯ menu.', target: f.card ? 'card' : null, illus: f.card ? null : 'card' })
37
+ steps.push({ key: 'live', title: 'Live', body: 'Start a session with leftoff live and talk to it from its page: Claude reads your message as its next prompt. Attach photos or files with the paperclip, and answer permission prompts here or on your phone.', target: f.live ? 'live' : null, illus: f.live ? null : 'live' })
38
+ steps.push(ctx.narrow
39
+ ? { key: 'tabs', title: 'Open sessions', body: 'Sessions you open stay in an Open row on the board. On a session, swipe or tap ‹ › to move between them.', target: f.tabs === 'row' ? 'tabs-row' : null, illus: f.tabs === 'row' ? null : 'tabs' }
40
+ : { key: 'tabs', title: 'Tabs', body: 'Sessions open in tabs up here, next to the board. A click opens a preview tab; it stays once you type in it or double-click it.', target: f.tabs === 'strip' ? 'tabs-strip' : null, illus: f.tabs === 'strip' ? null : 'tabs' })
41
+ steps.push({ key: 'catchup', title: 'Catch up', body: 'Back after a while? Catch me up tells you what got done and what’s waiting. The digest sums up each day.', target: f.catchup ? 'catchup' : null, illus: f.catchup ? null : 'catchup' })
42
+ steps.push(ctx.narrow && ctx.standalone
43
+ ? { key: 'phone', title: 'Your phone', body: 'You’re in the Home Screen app. Tap Turn on notifications under More, and your phone buzzes when a session needs you.', target: null, illus: 'phone', host }
44
+ : { key: 'phone', title: 'Your phone', body: 'Open ' + host + ' on your iPhone and add it to your Home Screen. It works like an app, with a notification when a session needs you.', target: null, illus: 'phone', host, link: { href: '#/settings/phone', label: 'Phone settings' } })
45
+ return steps
46
+ }
47
+
48
+ // Next index for a move: dir -1 | 1, clamped to the steps there are.
49
+ export function moveIndex(i, n, dir) {
50
+ const k = Math.max(0, Math.min(Number(n) - 1, (Number(i) || 0) + (dir < 0 ? -1 : 1)))
51
+ return Number.isFinite(k) ? k : 0
52
+ }
53
+
54
+ // Where the card goes. target: { top, left, width, height } (the spotlight)
55
+ // or null (the middle). card: { width, height }. vp: { width, height }.
56
+ // insets: { top, right, bottom, left } kept clear (safe areas, the phone's
57
+ // bottom bar). Below, else above, else beside, else over the bottom of the
58
+ // target; always inside vp minus insets (and a margin) when it fits there.
59
+ export function placeCard(target, card, vp, insets = {}, { gap = 12, margin = 8 } = {}) {
60
+ const ins = { top: 0, right: 0, bottom: 0, left: 0, ...insets }
61
+ const x0 = ins.left + margin, x1 = vp.width - ins.right - margin
62
+ const y0 = ins.top + margin, y1 = vp.height - ins.bottom - margin
63
+ const cw = Math.min(card.width, x1 - x0), ch = card.height
64
+ const clampX = (x) => Math.max(x0, Math.min(x1 - cw, x))
65
+ const clampY = (y) => Math.max(y0, Math.min(y1 - ch, y))
66
+ const out = (left, top, side) => ({ left: Math.round(left), top: Math.round(top), side })
67
+ if (!target) return out(clampX((x0 + x1 - cw) / 2), clampY((y0 + y1 - ch) / 2), 'center')
68
+ const t = { top: target.top, left: target.left, bottom: target.top + target.height, right: target.left + target.width }
69
+ const midX = clampX(t.left + (t.right - t.left) / 2 - cw / 2)
70
+ if (y1 - (t.bottom + gap) >= ch) return out(midX, Math.max(y0, t.bottom + gap), 'below')
71
+ if (t.top - gap - y0 >= ch) return out(midX, Math.min(y1 - ch, t.top - gap - ch), 'above')
72
+ const midY = clampY(t.top)
73
+ if (x1 - (t.right + gap) >= cw) return out(t.right + gap, midY, 'right')
74
+ if (t.left - gap - x0 >= cw) return out(t.left - gap - cw, midY, 'left')
75
+ return out(midX, clampY(y1 - ch), 'over')
76
+ }
77
+
78
+ // The spotlight for an element's rect: a little room around it, kept on screen.
79
+ export function holeFor(rect, vp, pad = 6) {
80
+ const left = Math.max(2, rect.left - pad), top = Math.max(2, rect.top - pad)
81
+ const right = Math.min(vp.width - 2, rect.left + rect.width + pad), bottom = Math.min(vp.height - 2, rect.top + rect.height + pad)
82
+ if (right - left < 4 || bottom - top < 4) return null
83
+ return { left, top, width: right - left, height: bottom - top }
84
+ }
85
+
86
+ // ------------------------------------------------------------- drawings
87
+
88
+ const CLIP = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m21.4 11.1-8.9 8.9a5.5 5.5 0 0 1-7.8-7.8l8.9-8.9a3.7 3.7 0 0 1 5.2 5.2l-8.9 8.9a1.8 1.8 0 0 1-2.6-2.6l8.2-8.2"/></svg>'
89
+ const ESC = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]))
90
+
91
+ // Small static drawings for a step whose part isn't on screen. Demo names only.
92
+ export function illusHtml(name, step = {}) {
93
+ const box = (inner) => '<div class="tour-illus tour-illus-' + name + '" aria-hidden="true">' + inner + '</div>'
94
+ if (name === 'needs') return box('<div class="ti-need"><span class="ti-pill ti-needs">needs you</span><b>api</b><span class="ti-faint">Bash: pnpm test</span><div class="ti-row"><span class="ti-btn ti-primary">Allow</span><span class="ti-btn">Deny</span></div></div>')
95
+ if (name === 'card') return box('<div class="ti-card"><div class="ti-row"><span class="ti-dot"></span><b>Fix the login redirect</b><span class="ti-pill">waiting</span></div><div class="ti-faint">acme/web · studio · 2 min</div>' +
96
+ '<div class="ti-cp"><div><i>Doing</i> moving the redirect into middleware</div><div><i>Stopped at</i> tests for the expired-session case</div><div><i>Next</i> run the e2e suite</div></div>' +
97
+ '<div class="ti-row"><span class="ti-btn ti-primary">Go</span><span class="ti-btn">⋯</span></div></div>')
98
+ if (name === 'live') return box('<div class="ti-live"><div class="ti-msg ti-you">Can you run the tests?</div><div class="ti-msg ti-claude">Running them now.</div>' +
99
+ '<div class="ti-need ti-mini"><span class="ti-faint">Allow Bash: pnpm test?</span><div class="ti-row"><span class="ti-btn ti-primary">Allow</span><span class="ti-btn">Deny</span></div></div>' +
100
+ '<div class="ti-composer"><span class="ti-clip">' + CLIP + '</span><span class="ti-input">Message Claude</span><span class="ti-send">↑</span></div></div>')
101
+ if (name === 'tabs') return box('<div class="ti-tabs"><span class="ti-tab ti-on">Board</span><span class="ti-tab"><i>acme/web</i></span><span class="ti-tab">api ×</span></div>')
102
+ if (name === 'catchup') return box('<div class="ti-row"><span class="ti-btn ti-primary">Catch me up</span><span class="ti-btn">Today’s digest →</span></div>')
103
+ if (name === 'phone') return box('<div class="ti-phone"><div class="ti-url">' + ESC(step.host || 'yourname.leftoff.dev') + '</div><div class="ti-note"><b>Leftoff</b><span>api needs you: Allow Bash?</span></div><div class="ti-lines"><span></span><span></span><span></span></div></div>')
104
+ return ''
105
+ }
106
+
107
+ // The card's inside for step i of n.
108
+ export function cardHtml(step, i, n) {
109
+ const last = i === n - 1
110
+ return (step.illus ? illusHtml(step.illus, step) : '') +
111
+ '<div class="tour-count">' + (i + 1) + ' of ' + n + '</div>' +
112
+ '<h2 class="tour-title" id="tourTitle">' + ESC(step.title) + '</h2>' +
113
+ '<p class="tour-body" id="tourBody">' + ESC(step.body) + '</p>' +
114
+ '<div class="tour-nav">' + (last ? (step.link ? '<a class="btn tour-link" href="' + ESC(step.link.href) + '" data-tour="link">' + ESC(step.link.label) + '</a>' : '') + '<span class="tour-grow"></span>' : '<button type="button" class="btn linkish tour-skip" data-tour="skip">Skip tour</button><span class="tour-grow"></span>') +
115
+ (i > 0 ? '<button type="button" class="btn" data-tour="back">Back</button>' : '') +
116
+ '<button type="button" class="btn primary" data-tour="' + (last ? 'done' : 'next') + '">' + (last ? 'Done' : 'Next') + '</button></div>'
117
+ }
118
+
119
+ // ------------------------------------------------------------- the DOM side
120
+
121
+ const SEL = {
122
+ 'needs-strip': '#app .needs-strip',
123
+ 'needs-nav': '#needsTab',
124
+ card: '#app article.card:not(.agentcard):not(.closed-card)',
125
+ live: '#app #live',
126
+ 'tabs-strip': '#tabStrip',
127
+ 'tabs-row': '#openRow',
128
+ catchup: '#app .pagehead .actions',
129
+ }
130
+ function shown(el) {
131
+ if (!el || el.hidden || el.closest('[hidden]')) return false
132
+ const r = el.getBoundingClientRect()
133
+ if (r.width < 4 || r.height < 4) return false
134
+ const cs = getComputedStyle(el)
135
+ return cs.visibility !== 'hidden' && cs.display !== 'none'
136
+ }
137
+ // The room a target gets on screen: under the top bars, above the phone's bottom bar.
138
+ function room() {
139
+ const ins = insets()
140
+ let top = ins.top
141
+ for (const el of document.querySelectorAll('.top, #tabStrip')) {
142
+ if (!shown(el)) continue
143
+ const r = el.getBoundingClientRect(), pos = getComputedStyle(el).position
144
+ if ((pos === 'fixed' || pos === 'sticky') && r.top < 10 && r.bottom < window.innerHeight / 3) top = Math.max(top, r.bottom)
145
+ }
146
+ return { top, bottom: window.innerHeight - ins.bottom, ins }
147
+ }
148
+ function findEl(target, cardH = 260) {
149
+ if (!target) return null
150
+ const all = [...document.querySelectorAll(SEL[target] || '#none')].filter(shown)
151
+ if (target === 'card') {
152
+ // a session card short enough to sit beside the tour's card, else the shortest of the first few
153
+ const cards = all.filter((el) => !el.closest('.needs-strip')).slice(0, 8)
154
+ const r = room(), fits = (el) => el.getBoundingClientRect().height + cardH + 40 <= r.bottom - r.top
155
+ return cards.find((el) => fits(el) && el.querySelector('.actions-row')) || cards.sort((a, b) => a.offsetHeight - b.offsetHeight)[0] || null
156
+ }
157
+ return all[0] || null
158
+ }
159
+ // What gets the spotlight: the element, or for the Needs you strip its head and first ask.
160
+ function rectOf(target, el) {
161
+ if (target === 'needs-strip') {
162
+ const parts = [el.querySelector('.needs-head'), el.querySelector('.needs-list > *')].filter(Boolean).map((x) => x.getBoundingClientRect())
163
+ if (parts.length) {
164
+ const l = Math.min(...parts.map((r) => r.left)), t = Math.min(...parts.map((r) => r.top)), rr = Math.max(...parts.map((r) => r.right)), b = Math.max(...parts.map((r) => r.bottom))
165
+ return { left: l, top: t, width: rr - l, height: b - t }
166
+ }
167
+ }
168
+ return el.getBoundingClientRect()
169
+ }
170
+ // What's on screen right now, for tourSteps().
171
+ export function probe() {
172
+ const has = (t) => !!findEl(t)
173
+ return {
174
+ needs: has('needs-strip') ? 'strip' : has('needs-nav') ? 'nav' : null,
175
+ card: has('card'), live: has('live'),
176
+ tabs: has('tabs-strip') ? 'strip' : has('tabs-row') ? 'row' : null,
177
+ catchup: has('catchup'),
178
+ }
179
+ }
180
+
181
+ let current = null // one tour at a time
182
+ export function tourOpen() { return !!current }
183
+
184
+ function loadCss() {
185
+ if (document.querySelector('link[data-tour-css]')) return Promise.resolve()
186
+ return new Promise((resolve) => {
187
+ const l = document.createElement('link')
188
+ l.rel = 'stylesheet'; l.href = 'tour.css'; l.dataset.tourCss = '1'
189
+ const t = setTimeout(resolve, 2000)
190
+ l.onload = l.onerror = () => { clearTimeout(t); resolve() }
191
+ document.head.appendChild(l)
192
+ })
193
+ }
194
+ const waitFor = (pred, ms = 4000) => new Promise((resolve) => {
195
+ const t0 = Date.now()
196
+ const tick = () => { if (pred()) return resolve(true); if (Date.now() - t0 > ms) return resolve(false); setTimeout(tick, 60) }
197
+ tick()
198
+ })
199
+ const narrowQ = () => window.matchMedia('(max-width: 699.98px)').matches
200
+ const reduced = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches
201
+ const isStandalone = () => !!(window.navigator.standalone || (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches))
202
+
203
+ // Safe areas, read from a probe the stylesheet pads with env(), plus the
204
+ // phone's bottom bar while it shows.
205
+ function insets() {
206
+ const p = document.createElement('div')
207
+ p.className = 'tour-safe'
208
+ document.body.appendChild(p)
209
+ const cs = getComputedStyle(p)
210
+ const ins = { top: parseFloat(cs.paddingTop) || 0, right: parseFloat(cs.paddingRight) || 0, bottom: parseFloat(cs.paddingBottom) || 0, left: parseFloat(cs.paddingLeft) || 0 }
211
+ p.remove()
212
+ const bar = document.querySelector('.top .tabs')
213
+ if (bar && narrowQ() && !document.body.classList.contains('nav-hidden')) {
214
+ const r = bar.getBoundingClientRect()
215
+ if (r.height && r.top > window.innerHeight / 2) ins.bottom = Math.max(ins.bottom, window.innerHeight - r.top)
216
+ }
217
+ return ins
218
+ }
219
+
220
+ // Start it. deps: { api, auto: started by itself, onEnd(how) }. Goes to the
221
+ // board first when it's somewhere else.
222
+ export async function startTour({ api, auto = false, onEnd = () => {} } = {}) {
223
+ if (current) return current
224
+ const me = (current = { closed: false })
225
+ const back = document.activeElement && document.activeElement !== document.body ? document.activeElement : null
226
+ if (!/^#\/?(\?|$)/.test(location.hash || '#/')) location.hash = '#/'
227
+ // the board, drawn (its head links to the digest; no other page's does)
228
+ await Promise.all([loadCss(), waitFor(() => /^#\/?(\?|$)/.test(location.hash || '#/') && !!document.querySelector('#app .pagehead .actions a[href="#/digest"]'))])
229
+ if (me.closed) return
230
+ if (document.querySelector('.wz')) { current = null; return } // the setup wizard is up: not over it
231
+ let host = /\.leftoff\.dev$/.test(location.hostname) ? location.hostname : null
232
+ if (!host && api) { try { const r = await api('GET', '/v1/relay', undefined, { timeoutMs: 1500 }); if (r && r.host) host = r.host } catch {} }
233
+
234
+ const root = document.createElement('div')
235
+ root.className = 'tour' + (reduced() ? ' tour-still' : '')
236
+ root.innerHTML = '<div class="tour-dim"></div><div class="tour-hole" hidden></div>' +
237
+ '<div class="tour-card" role="dialog" aria-modal="true" aria-labelledby="tourTitle" aria-describedby="tourBody" tabindex="-1"></div>'
238
+ document.body.appendChild(root)
239
+ document.body.classList.add('tour-on')
240
+ const dim = root.querySelector('.tour-dim'), hole = root.querySelector('.tour-hole'), card = root.querySelector('.tour-card')
241
+ let i = 0, steps = [], raf = 0, timer = 0, pinned = null, marked = null
242
+
243
+ const ctx = () => ({ narrow: narrowQ(), standalone: isStandalone(), host })
244
+ const place = () => {
245
+ raf = 0
246
+ if (me.closed) return
247
+ const step = steps[i]
248
+ const el = step && (pinned && pinned.isConnected ? pinned : findEl(step.target, card.offsetHeight))
249
+ const vp = { width: window.innerWidth, height: window.innerHeight }
250
+ let h = el ? holeFor(rectOf(step.target, el), vp) : null
251
+ // A target too tall to sit beside the card: the spotlight keeps its top part.
252
+ if (h && step.target !== 'needs-nav' && step.target !== 'tabs-strip') {
253
+ const rm = room(), spare = rm.bottom - 12 - card.offsetHeight - 12 - h.top
254
+ if (h.top + h.height > rm.bottom - card.offsetHeight - 24 && h.top - rm.top < card.offsetHeight + 24 && spare >= 80) h = { ...h, height: Math.min(h.height, spare) }
255
+ }
256
+ // the spotlit element carries data-tour-on (the browser check reads it)
257
+ const lit = h ? el : null
258
+ if (marked !== lit) { if (marked) marked.removeAttribute('data-tour-on'); if (lit) lit.setAttribute('data-tour-on', step.target); marked = lit }
259
+ root.dataset.step = step ? step.key : ''
260
+ root.dataset.mode = h ? 'spot' : 'center'
261
+ if (h) {
262
+ hole.hidden = false; dim.hidden = true
263
+ Object.assign(hole.style, { left: h.left + 'px', top: h.top + 'px', width: h.width + 'px', height: h.height + 'px' })
264
+ } else { hole.hidden = true; dim.hidden = false }
265
+ const at = placeCard(h, { width: card.offsetWidth, height: card.offsetHeight }, vp, insets())
266
+ Object.assign(card.style, { left: at.left + 'px', top: at.top + 'px' })
267
+ card.dataset.side = at.side
268
+ }
269
+ const soon = () => { if (!raf) raf = requestAnimationFrame(place) }
270
+
271
+ const show = (k, focus = true) => {
272
+ i = k
273
+ steps = tourSteps(probe(), ctx())
274
+ let step = steps[i]
275
+ // The target a step names: brought on screen under the top bars (the bars
276
+ // held, so the phone's bottom bar doesn't slide away under it).
277
+ if (window.leftoffNav) window.leftoffNav.show()
278
+ card.innerHTML = cardHtml(step, i, steps.length) // measured below
279
+ const el = findEl(step.target, card.offsetHeight)
280
+ pinned = el
281
+ if (el && step.target !== 'needs-nav' && step.target !== 'tabs-strip') {
282
+ const r = rectOf(step.target, el), rm = room()
283
+ const fitsWithCard = r.height + card.offsetHeight + 24 <= rm.bottom - rm.top
284
+ if (fitsWithCard ? (r.top < rm.top + 8 || r.top + r.height + card.offsetHeight + 24 > rm.bottom) : (r.top < rm.top + 8 || r.top > rm.top + 24)) window.scrollBy(0, r.top - rm.top - 12)
285
+ }
286
+ if (!el && step.target) { steps[i] = step = { ...step, target: null, illus: step.illus || step.key } }
287
+ card.innerHTML = cardHtml(step, i, steps.length)
288
+ card.dataset.key = step.key
289
+ place()
290
+ clearTimeout(timer); timer = setTimeout(place, 260) // after the bars and the scroll settle
291
+ if (focus) { const b = card.querySelector('[data-tour="next"], [data-tour="done"]'); if (b) b.focus({ preventScroll: true }) }
292
+ }
293
+
294
+ const end = (how) => {
295
+ if (me.closed) return
296
+ me.closed = true; current = null
297
+ cancelAnimationFrame(raf); clearTimeout(timer)
298
+ mo.disconnect()
299
+ window.removeEventListener('resize', soon); window.removeEventListener('scroll', soon, true)
300
+ document.removeEventListener('keydown', onKey, true)
301
+ root.remove(); document.body.classList.remove('tour-on')
302
+ if (api) api('POST', '/v1/tour/seen', { how }).catch(() => {})
303
+ document.removeEventListener('focusin', onFocus)
304
+ window.removeEventListener('hashchange', onHash)
305
+ if (marked) marked.removeAttribute('data-tour-on')
306
+ // focus goes back where it was; if that's gone (Settings → Take the tour), to the page's heading
307
+ const to = back && back.isConnected ? back : document.querySelector('#app .pagehead h1')
308
+ if (to && to !== back) to.tabIndex = -1
309
+ if (to && to.focus) { try { to.focus({ preventScroll: true }) } catch {} }
310
+ onEnd(how)
311
+ }
312
+ me.end = end
313
+
314
+ const go = (dir) => { const k = moveIndex(i, steps.length, dir); if (k !== i) show(k) }
315
+ root.addEventListener('click', (e) => {
316
+ const b = e.target.closest('[data-tour]')
317
+ if (!b) return
318
+ const a = b.dataset.tour
319
+ if (a === 'next') go(1)
320
+ else if (a === 'back') go(-1)
321
+ else if (a === 'done') end('done')
322
+ else if (a === 'skip') end('skipped')
323
+ else if (a === 'link') { e.preventDefault(); const to = b.getAttribute('href'); end('done'); location.hash = to }
324
+ })
325
+ // Nothing under the dim scrolls or takes a tap while it's up.
326
+ const still = (e) => { if (!card.contains(e.target)) e.preventDefault() }
327
+ root.addEventListener('wheel', still, { passive: false })
328
+ root.addEventListener('touchmove', still, { passive: false })
329
+ function onKey(e) {
330
+ if (me.closed) return
331
+ const k = e.key
332
+ if (k === 'Escape') { e.preventDefault(); end('skipped') }
333
+ else if (k === 'ArrowRight' || k === 'PageDown') { e.preventDefault(); go(1) }
334
+ else if (k === 'ArrowLeft' || k === 'PageUp') { e.preventDefault(); go(-1) }
335
+ else if (k === 'Enter' && !(e.target.closest && e.target.closest('button, a') && card.contains(e.target))) { e.preventDefault(); if (i === steps.length - 1) end('done'); else go(1) }
336
+ else if (k === 'Tab') {
337
+ // focus stays in the card
338
+ const f = [...card.querySelectorAll('button, a[href]')].filter((x) => !x.disabled)
339
+ if (!f.length) return
340
+ const at = f.indexOf(document.activeElement)
341
+ e.preventDefault()
342
+ const n = e.shiftKey ? (at <= 0 ? f.length - 1 : at - 1) : (at < 0 || at === f.length - 1 ? 0 : at + 1)
343
+ f[n].focus()
344
+ } else if (!card.contains(e.target)) e.preventDefault()
345
+ e.stopPropagation() // the board's own shortcuts wait
346
+ }
347
+ document.addEventListener('keydown', onKey, true)
348
+ function onFocus(e) { if (!me.closed && !root.contains(e.target)) { const b = card.querySelector('[data-tour="next"], [data-tour="done"]'); if (b) b.focus({ preventScroll: true }) } }
349
+ document.addEventListener('focusin', onFocus)
350
+ // The board redraws under it (live updates): the spotlight follows.
351
+ const mo = new MutationObserver(() => { if (pinned && !pinned.isConnected) pinned = null; soon() })
352
+ const app = document.getElementById('app')
353
+ if (app) mo.observe(app, { childList: true, subtree: true })
354
+ window.addEventListener('resize', soon)
355
+ window.addEventListener('scroll', soon, true)
356
+ // Leaving the board (a link, the back button) ends it.
357
+ function onHash() { if (!me.closed && !/^#\/?(\?|$)/.test(location.hash || '#/')) end('skipped') }
358
+ window.addEventListener('hashchange', onHash)
359
+ show(0)
360
+ return me
361
+ }
362
+
363
+ // Close a running tour (the board calls this before it opens something else).
364
+ export function endTour(how = 'skipped') { if (current && current.end) current.end(how) }
@@ -0,0 +1,158 @@
1
+ // 0.9.8: "Leftoff updated · Refresh". An open board (a desktop tab, the
2
+ // iPhone Home Screen app) keeps running the code it loaded with until it's
3
+ // reloaded. The page knows the build it came with (index.html's
4
+ // <meta name="leftoff-ui">, stamped by the Mac that served it, src/ui-build.js)
5
+ // and every health check says what that Mac serves now (`ui`); when they differ
6
+ // a bar offers a one-tap reload. Never on first load, never on its own, and a
7
+ // failed health check changes nothing. The pure parts are unit-tested.
8
+
9
+ export const POLL_MS = 60 * 1000 // a health check at least this often while the page is visible
10
+ export const CARRY_KEY = 'leftoff.reload.carry' // drafts handed to the reloaded page
11
+ export const CARRY_MAX_AGE_MS = 2 * 60 * 1000
12
+
13
+ // The build this page loaded with: { build, machine } from the meta tag, or null.
14
+ export function pageBuild(doc = typeof document !== 'undefined' ? document : null) {
15
+ const m = doc && doc.querySelector && doc.querySelector('meta[name="leftoff-ui"]')
16
+ const build = m && m.getAttribute('content')
17
+ return build ? { build, machine: m.getAttribute('data-machine') || '' } : null
18
+ }
19
+
20
+ // Should the bar show? loaded: { build, machine } (what this page runs);
21
+ // current: a health answer ({ ui, machine }), or null when the check failed;
22
+ // state: { showing, dismissed } (dismissed: the build whose bar was closed).
23
+ export function shouldShow(loaded, current, state = {}) {
24
+ const showing = !!state.showing
25
+ if (!current || typeof current.ui !== 'string' || !current.ui) return showing // no answer (or an older Mac): keep what's there
26
+ if (!loaded || !loaded.build) return false
27
+ // The board moved to another Mac (yours went to sleep): its files aren't an update of this page's.
28
+ if (loaded.machine && current.machine && loaded.machine !== current.machine) return showing
29
+ if (current.ui === loaded.build) return false
30
+ if (state.dismissed && state.dismissed === current.ui) return false
31
+ return true
32
+ }
33
+
34
+ // What a reload would lose, in words; empty when nothing. Drafts (the Live
35
+ // composer, replies) are carried over, so they aren't here.
36
+ export function reloadRisks({ attachments = 0, uploading = 0, unsavedSettings = false, typing = false } = {}) {
37
+ const out = []
38
+ if (uploading > 0) out.push(uploading === 1 ? 'A file is still uploading' : uploading + ' files are still uploading')
39
+ else if (attachments > 0) out.push(attachments === 1 ? 'The attached file won’t carry over' : 'The ' + attachments + ' attached files won’t carry over')
40
+ if (unsavedSettings) out.push('Unsaved settings will be lost')
41
+ if (typing) out.push('What you’re typing will be lost')
42
+ return out
43
+ }
44
+
45
+ // Drafts handed over a reload: written right before it, read once right after.
46
+ export function packCarry({ drafts = {}, focus = null, now = Date.now() } = {}) {
47
+ const d = {}
48
+ for (const [k, v] of Object.entries(drafts || {})) if (typeof v === 'string' && v.trim()) d[k] = v
49
+ return JSON.stringify({ at: now, drafts: d, focus: focus && d[focus.key] != null ? focus : null })
50
+ }
51
+ export function unpackCarry(raw, { now = Date.now(), maxAgeMs = CARRY_MAX_AGE_MS } = {}) {
52
+ try {
53
+ const j = JSON.parse(raw || '')
54
+ if (!j || typeof j.at !== 'number' || now - j.at > maxAgeMs || now < j.at - 5000) return null
55
+ const drafts = {}
56
+ for (const [k, v] of Object.entries(j.drafts || {})) if (typeof v === 'string') drafts[k] = v
57
+ const f = j.focus && typeof j.focus.key === 'string' ? { key: j.focus.key, a: Number(j.focus.a) || 0, b: Number(j.focus.b) || 0 } : null
58
+ return { drafts, focus: f }
59
+ } catch { return null }
60
+ }
61
+
62
+ // ------------------------------------------------------------ the bar (DOM)
63
+
64
+ // mountUpdateBar({ health, risks, carry, icon }) -> { check(h), shown() }
65
+ // health(): a fresh health answer (the board's refreshHealth); risks(): the
66
+ // reloadRisks input; carry(): { drafts, focus } to hand over.
67
+ export function mountUpdateBar({ health, risks = () => ({}), carry = () => ({}), icon = () => '', pollMs } = {}) {
68
+ const every = Number(pollMs || (typeof window !== 'undefined' && window.LEFTOFF_UPDATE_POLL_MS)) || POLL_MS
69
+ let loaded = pageBuild()
70
+ const st = { showing: false, dismissed: null, confirming: false, reloading: false }
71
+ let lastCheckAt = Date.now()
72
+ let el = null
73
+
74
+ function build() {
75
+ el = document.createElement('div')
76
+ el.className = 'updatebar'
77
+ el.id = 'updateBar'
78
+ el.setAttribute('role', 'status')
79
+ el.setAttribute('aria-live', 'polite')
80
+ el.hidden = true
81
+ el.innerHTML = '<span class="ub-icon" aria-hidden="true">' + icon('refresh-cw') + '</span><span class="ub-text">Leftoff updated</span>' +
82
+ '<button type="button" class="ub-go">Refresh</button><button type="button" class="ub-x" aria-label="Dismiss" title="Not now">' + icon('x') + '</button>'
83
+ document.body.appendChild(el)
84
+ // a click doesn't pull focus out of the box you're typing in
85
+ for (const b of el.querySelectorAll('button')) b.addEventListener('mousedown', (ev) => ev.preventDefault())
86
+ el.querySelector('.ub-go').addEventListener('click', onGo)
87
+ el.querySelector('.ub-x').addEventListener('click', onDismiss)
88
+ }
89
+ function paint() {
90
+ if (!el) build()
91
+ const was = !el.hidden
92
+ el.hidden = !st.showing
93
+ el.classList.toggle('confirm', st.confirming)
94
+ const text = el.querySelector('.ub-text'), go = el.querySelector('.ub-go')
95
+ if (st.confirming) { text.textContent = st.confirming; go.textContent = 'Refresh anyway' } else { text.textContent = 'Leftoff updated'; go.textContent = st.reloading ? 'Refreshing…' : 'Refresh' }
96
+ go.disabled = !!st.reloading
97
+ if (st.showing && !was) requestAnimationFrame(() => el && el.classList.add('in'))
98
+ if (!st.showing) el.classList.remove('in')
99
+ document.documentElement.classList.toggle('has-updatebar', st.showing)
100
+ }
101
+
102
+ // Every health answer the board gets comes through here (its own poll, the
103
+ // event stream reopening after a restart, the page coming back).
104
+ function check(h) {
105
+ lastCheckAt = Date.now()
106
+ if (h && !loaded && typeof h.ui === 'string' && h.ui) loaded = { build: h.ui, machine: h.machine || '' } // a page with no stamp: its first answer is its build
107
+ const next = shouldShow(loaded, h || null, st)
108
+ if (next !== st.showing) { st.showing = next; st.confirming = false; paint() }
109
+ }
110
+
111
+ function onDismiss() {
112
+ const h = lastHealth
113
+ st.dismissed = (h && h.ui) || st.dismissed || 'any'
114
+ st.showing = false; st.confirming = false
115
+ paint()
116
+ }
117
+ let lastHealth = null
118
+ function onHealth(h) { lastHealth = h; check(h) }
119
+
120
+ async function onGo() {
121
+ if (st.reloading) return
122
+ const words = reloadRisks(risks() || {})
123
+ if (words.length && !st.confirming) { st.confirming = words.join(' · '); paint(); return }
124
+ st.reloading = true; st.confirming = false; paint()
125
+ try { sessionStorage.setItem(CARRY_KEY, packCarry(carry() || {})) } catch {}
126
+ // A new service worker, if its file changed, before the page comes back.
127
+ try {
128
+ const reg = 'serviceWorker' in navigator && await navigator.serviceWorker.getRegistration()
129
+ if (reg) await Promise.race([reg.update(), new Promise((r) => setTimeout(r, 3000))])
130
+ } catch {}
131
+ location.reload()
132
+ }
133
+
134
+ // A health check at least every `every` ms while visible, and at once when
135
+ // the page comes back (the Home Screen app resumes, a bfcache restore).
136
+ const due = () => document.visibilityState !== 'hidden' && Date.now() - lastCheckAt >= every - 250
137
+ const tick = () => { if (due()) { lastCheckAt = Date.now(); Promise.resolve(health()).catch(() => {}) } }
138
+ setInterval(tick, Math.min(every, 15000))
139
+ const wake = (ev) => {
140
+ if (document.visibilityState === 'hidden') return
141
+ if (ev && ev.type === 'pageshow' && !ev.persisted) return
142
+ if (Date.now() - lastCheckAt < 3000) return
143
+ lastCheckAt = Date.now(); Promise.resolve(health()).catch(() => {})
144
+ }
145
+ document.addEventListener('visibilitychange', wake)
146
+ window.addEventListener('pageshow', wake)
147
+ window.addEventListener('online', wake)
148
+
149
+ return { check: onHealth, shown: () => st.showing, loaded: () => loaded }
150
+ }
151
+
152
+ // Right after a reload from the bar: the drafts it carried (once).
153
+ export function takeCarry(storage = typeof sessionStorage !== 'undefined' ? sessionStorage : null) {
154
+ if (!storage) return null
155
+ let raw = null
156
+ try { raw = storage.getItem(CARRY_KEY); if (raw != null) storage.removeItem(CARRY_KEY) } catch { return null }
157
+ return raw ? unpackCarry(raw) : null
158
+ }