afield 0.0.0-stage → 0.1.0

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 (43) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +165 -2
  3. package/afield +214 -0
  4. package/package.json +42 -4
  5. package/pi-extensions/afield-session.ts +59 -0
  6. package/pi-extensions/elastic-footer.ts +167 -0
  7. package/server/attach.js +264 -0
  8. package/server/auth.js +169 -0
  9. package/server/client.js +64 -0
  10. package/server/control.js +65 -0
  11. package/server/identity.js +45 -0
  12. package/server/index.js +375 -0
  13. package/server/mirror.js +159 -0
  14. package/server/origin.js +51 -0
  15. package/server/picker.js +187 -0
  16. package/server/places.js +348 -0
  17. package/server/protocol.js +51 -0
  18. package/server/quick-tunnel.js +40 -0
  19. package/server/registry.js +190 -0
  20. package/server/serve.js +100 -0
  21. package/server/session-main.js +27 -0
  22. package/server/session.js +112 -0
  23. package/server/supervisor.js +432 -0
  24. package/server/viewer.js +65 -0
  25. package/src/app.js +1683 -0
  26. package/src/apple-touch-icon.png +0 -0
  27. package/src/index.html +96 -0
  28. package/src/keys.js +59 -0
  29. package/src/pi-icon.svg +13 -0
  30. package/src/style.css +559 -0
  31. package/src/transport.js +153 -0
  32. package/src/ttyd.js +51 -0
  33. package/src/viewport.js +168 -0
  34. package/tsconfig.json +14 -0
  35. package/vendor/wterm/LICENSE +191 -0
  36. package/vendor/wterm/README.md +7 -0
  37. package/vendor/wterm/packages/@wterm/dom/src/debug.ts +347 -0
  38. package/vendor/wterm/packages/@wterm/dom/src/hyperlink.ts +8 -0
  39. package/vendor/wterm/packages/@wterm/dom/src/index.ts +13 -0
  40. package/vendor/wterm/packages/@wterm/dom/src/input.ts +662 -0
  41. package/vendor/wterm/packages/@wterm/dom/src/renderer.ts +725 -0
  42. package/vendor/wterm/packages/@wterm/dom/src/terminal.css +195 -0
  43. package/vendor/wterm/packages/@wterm/dom/src/wterm.ts +609 -0
package/src/app.js ADDED
@@ -0,0 +1,1683 @@
1
+ // The client: wires the terminal to the socket, and owns the layout, the key
2
+ // bar, the menu and the on-screen diagnostics.
3
+ import { WTerm } from '../vendor/wterm/packages/@wterm/dom/src/index.ts'
4
+ import { TtydConnection } from './transport.js'
5
+ import { readViewport, rememberKeyboardDown, deriveLayout, horizontalLayout, validVisualHeight, gridFor, measureCell, KEY_BAR_H } from './viewport.js'
6
+ import { keySequence } from './keys.js'
7
+
8
+ const $ = id => document.getElementById(id)
9
+ const el = (tag, className, ...children) => {
10
+ const node = document.createElement(tag)
11
+ if (className) node.className = className
12
+ node.append(...children)
13
+ return node
14
+ }
15
+ const app = $('app')
16
+ const viewport = $('viewport')
17
+ const stage = $('stage')
18
+ const screen = $('screen')
19
+ const bar = $('bar')
20
+ const keys = $('keys')
21
+ const pad = $('pad')
22
+ const toBottom = $('to-bottom')
23
+ const menu = $('menu')
24
+ const tabs = $('tabs')
25
+ const tabsLeft = $('tabs-left')
26
+ const tabsRight = $('tabs-right')
27
+ const places = $('places')
28
+ const placeNow = $('place-now')
29
+ const menuNotice = $('menu-notice')
30
+ const loading = $('loading')
31
+
32
+ // iOS keeps its own copy of a home-screen app's launch document despite the
33
+ // server's `cache-control: no-cache`. So the page checks for a newer build
34
+ // itself. A meta tag survives minification and reads the same from the live DOM
35
+ // and from a re-fetched copy.
36
+ const buildIdOf = doc => doc.querySelector('meta[name=build]')?.content ?? ''
37
+ const BUILD_ID = buildIdOf(document)
38
+
39
+ // Sequences written to our own terminal, never sent to pi. ED 3 is specified as
40
+ // erasing only the saved lines, but this VT core erases the visible grid with
41
+ // it — so it is only ever useful alongside ED 2, never on its own.
42
+ const CURSOR_HOME = '\x1b[H' // CUP: cursor to row 1, column 1
43
+ const ERASE_SCREEN = '\x1b[2J' // ED 2: erase the visible grid
44
+ const ERASE_SAVED = '\x1b[3J' // ED 3: erase saved lines, and here the grid too
45
+
46
+ const BASE_FONT_SIZE = 13
47
+ const MIN_SCALE = 0.4
48
+ const MAX_SCALE = 3
49
+ const ZOOM_STEP = 1.25
50
+ const SETTLE_MS = 200 // viewport values are wrong mid-rotation and mid-keyboard
51
+ const REPEAT_AFTER_MS = 400 // hold an arrow this long before it repeats
52
+ const REPEAT_EVERY_MS = 60
53
+ const PRESETS = [[50, 30], [80, 40], [120, 40], [160, 50]]
54
+
55
+ const state = {
56
+ fontSize: BASE_FONT_SIZE,
57
+ scale: 1,
58
+ cols: 80,
59
+ rows: 24,
60
+ // What we asked the server for. It differs from cols/rows whenever another
61
+ // viewer is narrower, which is what being letterboxed looks like from here.
62
+ wanted: { cols: 80, rows: 24 },
63
+ cell: { width: 8, height: 16 },
64
+ mods: { ctrl: false, alt: false, shift: false },
65
+ }
66
+
67
+ // ---------------------------------------------------------------- terminal
68
+
69
+ // A live PTY has a stable process ID even when pi switches conversations.
70
+ // Keep the requested row separate from the one that actually admitted us.
71
+ let currentPlace = null
72
+ let pendingPlace = null
73
+ let selectionVersion = 0
74
+ let starting = null
75
+ let armedEndId = null
76
+ let endArmTimer = null
77
+ const endingIds = new Set()
78
+ let placesRequest = 0
79
+ // The full-pool picker being loaded or shown. Cleared once taken, or when the menu is left by hand.
80
+ let retryPicker = null
81
+ let tabsRequest = 0
82
+ let tabsEnabled = false
83
+ // The close code the supervisor sends when the session itself is over — pi
84
+ // exited, or someone ended it — as opposed to an ordinary dropped socket.
85
+ const SESSION_ENDED = 1001
86
+ // The close code range the supervisor reserves for a refused join, as opposed
87
+ // to a dropped socket. A refusal is final; anything else is a phone that lost
88
+ // its network and gets the ordinary backoff.
89
+ const REFUSED = code => code >= 4000 && code < 5000
90
+ // A refusal for a full pool is the one that can be taken back: end something,
91
+ // ask again, and it goes through. Every other refusal is final.
92
+ const POOL_FULL = 4006
93
+ // What the menu is showing. The picker is the one case where a tap on a row
94
+ // ends a session instead of joining it, so it is drawn apart from the list.
95
+ let menuView = 'normal'
96
+ const samePlace = (a, b) => Boolean(a && b && a.id === b.id && a.cwd === b.cwd)
97
+ // What the last visit was looking at, whole: a process ID that is gone means
98
+ // nothing on its own, while the conversation it was showing is still there to
99
+ // reopen.
100
+ const readPlace = key => {
101
+ try { return JSON.parse(localStorage.getItem(key)) } catch { return null }
102
+ }
103
+ const writePlace = (key, place) => localStorage.setItem(key, JSON.stringify(place))
104
+ const wsBase = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`
105
+ // A process ID carries its conversation along: a server restarted since has
106
+ // never heard of the process, and reopens the conversation instead.
107
+ const sessionUrl = place => {
108
+ const conversation = `session=${encodeURIComponent(place.id)}&cwd=${encodeURIComponent(place.cwd)}`
109
+ return place.processId
110
+ ? `${wsBase}?process=${encodeURIComponent(place.processId)}&${conversation}`
111
+ : `${wsBase}?${conversation}`
112
+ }
113
+
114
+ // How many rows the menu asks for at a time. Each one returned costs the
115
+ // server a read of its transcript for the label.
116
+ const MENU_PAGE = 200
117
+
118
+ const fetchPlaces = (window = {}) => {
119
+ const query = new URLSearchParams()
120
+ if (window.offset) query.set('offset', window.offset)
121
+ if (window.limit) query.set('limit', window.limit)
122
+ if (window.running) query.set('running', '1')
123
+ return fetch(`/places${query.size ? `?${query}` : ''}`).then(r => r.json())
124
+ }
125
+ const tabOrder = (a, b) => a.startedAt - b.startedAt || a.processId.localeCompare(b.processId)
126
+
127
+ async function refreshTabs() {
128
+ const request = ++tabsRequest
129
+ const response = await fetchPlaces({ running: true }).then(r => r, err => {
130
+ console.error('could not refresh tabs', err)
131
+ return null
132
+ })
133
+ if (response === null) return
134
+ const { sessions } = response
135
+ if (!sessions) throw new Error('places response has no sessions')
136
+ if (request !== tabsRequest) return
137
+ const ordered = [...sessions].sort(tabOrder)
138
+ const totals = new Map()
139
+ for (const sess of ordered) totals.set(sess.label, (totals.get(sess.label) ?? 0) + 1)
140
+ const seen = new Map()
141
+ tabs.replaceChildren()
142
+ for (const sess of ordered) {
143
+ const number = (seen.get(sess.label) ?? 0) + 1
144
+ seen.set(sess.label, number)
145
+ const mark = markOf(sess)
146
+ const name = el('span', 'tab-name',
147
+ ...(mark ? [srOnly(`${mark} `)] : []),
148
+ `${sess.label}${totals.get(sess.label) > 1 ? ` ${number}` : ''}`,
149
+ )
150
+ const button = el('button', `tab${mark ? ` ${mark}` : ''}`, name)
151
+ button.dataset.processId = sess.processId
152
+ if (sess.processId === currentPlace?.processId) button.setAttribute('aria-current', 'true')
153
+ button.addEventListener('click', () => {
154
+ if (!conn.started || sess.processId !== currentPlace?.processId) joinSession(sess)
155
+ })
156
+ tabs.append(button)
157
+ }
158
+ tabs.hidden = !tabsEnabled || ordered.length < 2
159
+ updateTabArrows()
160
+ }
161
+ function updateTabArrows() {
162
+ tabsLeft.hidden = tabs.hidden || tabs.scrollLeft <= 0
163
+ tabsRight.hidden = tabs.hidden || tabs.scrollLeft + tabs.clientWidth >= tabs.scrollWidth - 1
164
+ }
165
+ function refreshPlaces({ preserveNotice = false } = {}) {
166
+ if (!preserveNotice) clearMenuNotice()
167
+ const request = ++placesRequest
168
+ return fetchPlaces({ limit: MENU_PAGE }).then(data => {
169
+ if (request === placesRequest && menuView === 'normal') showPlaces(data)
170
+ })
171
+ }
172
+
173
+ /** The last path segment, for chooser rows and titles. */
174
+ const basename = path => path.slice(path.lastIndexOf('/') + 1)
175
+
176
+ /** The place to land on when the page first loads: last time's, if it is
177
+ * still among the recent sessions the menu shows. A browser with nothing
178
+ * remembered gets the menu instead: the newest conversation is often one
179
+ * already open in a terminal, and joining it would start a second pi on it. */
180
+ async function resolveInitialPlace() {
181
+ const remembered = readPlace('afield-place')
182
+ if (!remembered) return null
183
+ const { sessions } = await fetchPlaces({ limit: MENU_PAGE })
184
+ // A remembered process that has since ended has no row; the conversation it
185
+ // was showing does, which is why the whole place was kept rather than a key.
186
+ return sessions.find(s => remembered.processId && s.processId === remembered.processId)
187
+ ?? sessions.find(s => samePlace(s, remembered))
188
+ ?? null
189
+ }
190
+
191
+ /**
192
+ * The place this viewer is really looking at: whichever one a PROCESS frame
193
+ * named. Nothing else promotes a requested place, so the header cannot end up
194
+ * naming a session the screen is not showing.
195
+ */
196
+ function commitPlace(next) {
197
+ currentPlace = next
198
+ menu.classList.remove('first-visit')
199
+ pendingPlace = null
200
+ writePlace('afield-place', currentPlace)
201
+ // Reconnects redial this, so it follows /new, /resume and a rejoin.
202
+ conn.url = sessionUrl(currentPlace)
203
+ placeNow.textContent = currentPlace.path
204
+ document.title = `${currentPlace.name} — ${currentPlace.path}`
205
+ if (tabsEnabled) refreshTabs()
206
+ if (!menu.hidden) refreshPlaces().catch(() => {})
207
+ }
208
+
209
+ const term = new WTerm(screen, {
210
+ cols: state.cols,
211
+ rows: state.rows,
212
+ autoResize: false,
213
+ cursorBlink: true,
214
+ onData: data => conn.send(withMods(data)),
215
+ // After the paint, before wterm's own scroll pinning: the pin reads the
216
+ // geometry the trim decides.
217
+ onAfterPaint: () => { trimBlankTail(); checkLoaded() },
218
+ })
219
+
220
+ /** Say which session is on its way, until its screen has something on it. */
221
+ let loadingTimer = null
222
+ function hideLoading() {
223
+ clearTimeout(loadingTimer)
224
+ loadingTimer = null
225
+ loading.hidden = true
226
+ }
227
+ function showLoading(sess) {
228
+ loading.textContent = `Opening ${basename(sess.cwd)}…`
229
+ loading.hidden = false
230
+ // A live screen with no text on it would otherwise keep this up for good.
231
+ clearTimeout(loadingTimer)
232
+ loadingTimer = setTimeout(hideLoading, 5_000)
233
+ }
234
+
235
+ // The old session's screen stays up until the new one's snapshot replaces
236
+ // it, but nothing paints it in between: its socket's frames are dropped.
237
+ function checkLoaded() {
238
+ if (loading.hidden) return
239
+ if ([...screen.querySelectorAll('.term-row')].some(row => row.textContent.trim())) hideLoading()
240
+ }
241
+
242
+ function stopDisconnected() {
243
+ pendingPlace = null
244
+ conn.stop()
245
+ conn.discardInput()
246
+ hideLoading()
247
+ showConnection('disconnected')
248
+ }
249
+
250
+ const conn = new TtydConnection({
251
+ // A placeholder until resolveInitialPlace() picks the real one in main() —
252
+ // never actually dialed, since connect() is not called until it has.
253
+ url: wsBase,
254
+ socketFactory: (url, protocols) => new WebSocket(url, protocols),
255
+ schedule: (fn, ms) => setTimeout(fn, ms),
256
+ onOutput: bytes => { lastOutput = Date.now(); deliver(bytes) },
257
+ onProcess: process => {
258
+ // Only the live socket's frames get here (transport.js drops the rest), so
259
+ // each names what the screen shows: a requested place arriving, /new or
260
+ // /resume, or a rejoin after a server restart under a new process ID.
261
+ commitPlace({ ...(pendingPlace ?? currentPlace), ...process })
262
+ },
263
+ onTitle: title => {
264
+ document.title = currentPlace ? `${currentPlace.name} — ${currentPlace.path}` : title
265
+ },
266
+ onSize: ({ cols, rows }) => { snapshotPending = true; applyServerSize(cols, rows) },
267
+ onState: (status, code, reason) => {
268
+ // 'connecting' covers reconnectNow (which closes the old socket so its
269
+ // onclose never fires) as well as every ordinary open.
270
+ if (status !== 'connected') dropHeld()
271
+ // A refused join is the server saying no: clear what was asked for, drop
272
+ // the keys typed at a session that never took them, and let the menu say
273
+ // why. A dropped socket instead keeps its backoff and reconnects silently.
274
+ // A rejoin after a server restart has nothing pending, but a full pool
275
+ // refuses it the same way and it can be asked again the same way.
276
+ const refused = pendingPlace ?? (code === POOL_FULL ? currentPlace : null)
277
+ if (status === 'disconnected' && REFUSED(code) && refused) {
278
+ stopDisconnected()
279
+ // A full pool is the one refusal this viewer can take back: end a
280
+ // session, ask for this one again.
281
+ if (code === POOL_FULL) return showPoolFull(`${refused.label} opens`, () => joinSession(refused))
282
+ showMenuNotice(reason || 'could not join that conversation')
283
+ openMenu({ preserveNotice: true })
284
+ return
285
+ }
286
+ // 1001 is the server saying the session itself ended, not a dropped
287
+ // phone. Retrying would spawn a fresh process from the transcript, so the
288
+ // loop stops and we look for another running tab instead. A refusal with
289
+ // nothing pending is the same news arriving late — the terminal this
290
+ // viewer was on went away while its socket was down — and gets the same
291
+ // bookkeeping, or the header would keep naming somewhere nothing is.
292
+ if (status === 'disconnected' && (code === SESSION_ENDED || REFUSED(code))) {
293
+ return finishEnded(endingIds.has(currentPlace?.processId) ? '' : reason || 'terminal ended')
294
+ }
295
+ showConnection(status)
296
+ },
297
+ })
298
+
299
+ function finishEnded(notice) {
300
+ const ended = currentPlace
301
+ if (ended) writePlace('afield-place', { id: ended.id, cwd: ended.cwd })
302
+ if (notice) showMenuNotice(notice)
303
+ else clearMenuNotice()
304
+ stopDisconnected()
305
+ currentPlace = null
306
+ placeNow.textContent = ''
307
+ document.title = 'afield'
308
+ stopReading()
309
+ term.write(CURSOR_HOME + ERASE_SCREEN + ERASE_SAVED)
310
+ menu.classList.add('first-visit')
311
+ // Leave a full-pool picker and its retry intact; an explicit Start also
312
+ // owns the next selection, even if it ends up failing.
313
+ if (!retryPicker) {
314
+ openMenu({ preserveNotice: Boolean(notice) })
315
+ if (ended && starting !== selectionVersion) switchAfterEnd(ended)
316
+ }
317
+ if (tabsEnabled) refreshTabs()
318
+ }
319
+
320
+ /** The menu is hidden by default, so connection state has to live outside it. */
321
+ function showConnection(status) {
322
+ $('menu-state').textContent = `${status} · ${BUILD_ID}`
323
+ const bolt = $('conn')
324
+ bolt.textContent = '⚡'
325
+ bolt.setAttribute('aria-label', status)
326
+ bolt.title = status
327
+ bolt.hidden = status === 'connected'
328
+ }
329
+
330
+ function clearMenuNotice() {
331
+ menuNotice.textContent = ''
332
+ menuNotice.hidden = true
333
+ }
334
+
335
+ function showMenuNotice(text) {
336
+ menuNotice.textContent = text
337
+ menuNotice.hidden = false
338
+ }
339
+
340
+ // Diagnostic seam: the e2e suite and the on-device probe read the same shape.
341
+ // Published before startup finishes so nothing has to guess when it appears.
342
+ window.afield = { conn, term, state, checkForNewBuild }
343
+
344
+ // ---------------------------------------------------------------- layout
345
+
346
+ /** Size the app to the visual viewport — the space above the keyboard. */
347
+ function applyLayout() {
348
+ // A visual viewport as tall as the document has nowhere to move, so an offset
349
+ // there is the document itself left scrolled (iOS does this rotating out of a
350
+ // landscape launch). The fixed #app already ignores that scroll; following
351
+ // the offset would push it down a second time. The page never scrolls by
352
+ // design, so put it back before measuring. Not innerHeight: iOS shrinks that
353
+ // by the distance scrolled when it pans the page to show a focused field.
354
+ const { height } = visualViewport
355
+ if (!validVisualHeight(height)) return null
356
+ if (height >= document.documentElement.clientHeight) {
357
+ // Once per burst, like the events (see onViewportChange).
358
+ if (window.scrollY !== 0 && settle === null) record('scrollTo')
359
+ window.scrollTo(0, 0)
360
+ }
361
+ const snap = readViewport()
362
+ const l = deriveLayout(snap)
363
+ if (!l) return null
364
+ if (l.keyboardUp) awaitingKeyboard = false
365
+ app.style.height = `${l.appHeight}px`
366
+ app.style.transform = `translateY(${snap.offsetTop}px)`
367
+ app.style.setProperty('--inset-left', `${l.insetLeft}px`)
368
+ app.style.setProperty('--inset-right', `${l.insetRight}px`)
369
+
370
+ // The bar covers the home-indicator inset rather than leaving a gap under it.
371
+ // flex-basis alone sizes a column flex item; `height` would be a third layer
372
+ // saying the same thing, after the CSS var that covers the first paint.
373
+ bar.style.flexBasis = `${l.keyBarHeight}px`
374
+ bar.style.paddingBottom = `${l.keyBarPadBottom}px`
375
+
376
+ toBottom.style.bottom = `${l.keyBarHeight + 10}px`
377
+
378
+ sizeScreen()
379
+ return l
380
+ }
381
+
382
+ // Breathing room so the grid is not flush against the screen edges; reserved
383
+ // in the fit and added to the scroller width, like the gutter.
384
+ const SIDE_PAD = 2
385
+
386
+ // The classic-scrollbar gutter; 0 for overlay scrollbars. Fractional rects:
387
+ // the integer offsetWidth/clientWidth pair rounds the gutter and clips a
388
+ // sliver of the last column at fractional page zoom.
389
+ const scrollbarGutter = () => {
390
+ const probe = document.getElementById('scroll-probe')
391
+ return probe.getBoundingClientRect().width - probe.firstElementChild.getBoundingClientRect().width
392
+ }
393
+
394
+ /**
395
+ * The wterm element is the one scroller: scrollback above, live grid below, and
396
+ * any part of a grid taller than the box reachable by the same gesture.
397
+ */
398
+ function sizeScreen() {
399
+ // The gutter and side padding ride inside the scroller's width; the grid
400
+ // gets the rest.
401
+ const naturalW = state.cols * state.cell.width + scrollbarGutter() + 2 * SIDE_PAD
402
+ // Widths before the height read: a preset that just overflowed can give
403
+ // #viewport a classic horizontal scrollbar, and the rows must see it.
404
+ screen.style.paddingInline = `${SIDE_PAD}px`
405
+ screen.style.width = `${naturalW}px`
406
+ stage.style.width = `${naturalW}px`
407
+ const boxH = viewport.clientHeight
408
+ if (boxH === 0) return
409
+
410
+ // Pin the bottom, not the top. When the keyboard opens the window gets
411
+ // shorter, and holding scrollTop would leave the top of the grid on screen
412
+ // with pi's input box pushed out of sight underneath.
413
+ const fromBottom = screen.scrollHeight - screen.scrollTop - screen.clientHeight
414
+
415
+ // A whole number of rows. wterm scrolls to the bottom by flooring to a row
416
+ // boundary, so a box that is not a multiple of the row height leaves it parked
417
+ // short of the end — and once that remainder exceeds its own 5px tolerance it
418
+ // stops following output at all. The leftover is under a row of background.
419
+ const rows = Math.floor(boxH / state.cell.height)
420
+ screen.style.height = `${rows * state.cell.height}px`
421
+ stage.style.height = `${boxH}px`
422
+
423
+ screen.scrollTop = screen.scrollHeight - screen.clientHeight - Math.max(0, fromBottom)
424
+ }
425
+
426
+ // A resize reaches pi as SIGWINCH and makes it repaint, so it waits for the
427
+ // output to stop rather than landing in the middle of one. Our own core is not
428
+ // the reason: it holds a partial sequence across a resize and finishes parsing
429
+ // it afterwards.
430
+ const QUIET_MS = 120
431
+ let lastOutput = 0
432
+ let pendingGrid = null
433
+ let gridTimer = null
434
+
435
+ function setGrid(cols, rows) {
436
+ pendingGrid = { cols, rows }
437
+ applyPendingGrid()
438
+ }
439
+
440
+ function applyPendingGrid() {
441
+ if (!pendingGrid) return
442
+ clearTimeout(gridTimer)
443
+ const since = Date.now() - lastOutput
444
+ if (since < QUIET_MS) {
445
+ gridTimer = setTimeout(applyPendingGrid, QUIET_MS - since)
446
+ return
447
+ }
448
+ const { cols, rows } = pendingGrid
449
+ pendingGrid = null
450
+ state.wanted = { cols, rows }
451
+ conn.resize(cols, rows)
452
+ }
453
+
454
+ /**
455
+ * Render at the grid the PTY actually has.
456
+ *
457
+ * The server owns the PTY and gives it to the narrowest viewer, so what we ask
458
+ * for and what we get are not always the same. Rendering anything other than
459
+ * the real grid would mean parsing a relative stream drawn for a different
460
+ * width, which is wrong in a way that looks like a layout bug.
461
+ */
462
+ // A grid change is followed by a snapshot that replaces the whole buffer, and
463
+ // the rendered rows are dropped before it arrives. Reading position therefore
464
+ // has to be taken before the resize and put back once wterm has rendered the
465
+ // repaint, which it does on a later frame — but a live stream can keep
466
+ // growing the buffer forever, so this cannot just wait for it to settle. It
467
+ // gives up after a fixed window, and anything that moves the scroll on its
468
+ // own terms — a drag, Top/Bottom, the back-to-live button — cancels it.
469
+ let stopReading = () => {}
470
+ // The share the re-pin in flight is holding the reader at, null when none is.
471
+ let readingShare = null
472
+
473
+ // How far up the history the eye is, as a share of the whole -- the only
474
+ // measure that survives a reflow, since pixels and rows both change. A re-pin
475
+ // already in flight is the honest answer while one does: a resize landing
476
+ // inside another one's reflow reads the emptied DOM as at-bottom and would
477
+ // abandon the reader on the strength of it. Null means the reader is at the
478
+ // live edge, with nowhere to hold.
479
+ const readingShareNow = () => readingShare ?? (atBottom() || screen.scrollHeight === 0
480
+ ? null
481
+ : (screen.scrollHeight - screen.scrollTop - screen.clientHeight) / screen.scrollHeight)
482
+
483
+ function applyServerSize(cols, rows) {
484
+ if (cols === state.cols && rows === state.rows) return
485
+ const share = readingShareNow()
486
+ state.cols = cols
487
+ state.rows = rows
488
+ term.resize(cols, rows)
489
+ sizeScreen()
490
+ if (share !== null) keepReading(share)
491
+ }
492
+
493
+ // Long enough for wterm's own repaint to land after a resize; not a promise to
494
+ // hold position against output that is still streaming in.
495
+ const READING_MS = 600
496
+
497
+ /** Re-apply the position on every frame until the repaint settles or gives up. */
498
+ function keepReading(share) {
499
+ stopReading() // a newer resize, or the user, cancels whatever was running
500
+ // After that cancel, never before it: the outgoing re-pin clears both of
501
+ // these on its way out, and the incoming one needs them set.
502
+ resettling = true
503
+ readingShare = share
504
+ const deadline = performance.now() + READING_MS
505
+ let last = -1
506
+ let frames = 0
507
+ const cancel = () => {
508
+ // A stale cancel firing after a newer resize has already taken over must
509
+ // not clear that newer one's ownership — checked, not assumed, because a
510
+ // resize landing before the next frame calls this twice: once directly,
511
+ // once from its own step's guard.
512
+ if (stopReading === cancel) {
513
+ stopReading = () => {}
514
+ resettling = false
515
+ readingShare = null
516
+ }
517
+ screen.removeEventListener('pointerdown', cancel)
518
+ screen.removeEventListener('wheel', cancel)
519
+ }
520
+ stopReading = cancel
521
+ screen.addEventListener('pointerdown', cancel, { passive: true })
522
+ screen.addEventListener('wheel', cancel, { passive: true })
523
+ const step = () => {
524
+ if (stopReading !== cancel || performance.now() > deadline) { cancel(); return }
525
+ const h = screen.scrollHeight
526
+ screen.scrollTop = h - screen.clientHeight - share * h
527
+ toBottom.hidden = atBottom()
528
+ if (h === last) { if (++frames > 3) { cancel(); return } } else { last = h; frames = 0 }
529
+ requestAnimationFrame(step)
530
+ }
531
+ requestAnimationFrame(step)
532
+ }
533
+
534
+ function setScale(scale) {
535
+ const next = Math.min(MAX_SCALE, Math.max(MIN_SCALE, scale))
536
+ if (next === state.scale) return
537
+ const share = readingShareNow()
538
+ state.scale = next
539
+ state.fontSize = BASE_FONT_SIZE * next
540
+ state.cell = measureCell(state.fontSize)
541
+ screen.style.setProperty('--term-font-size', `${state.fontSize}px`)
542
+ screen.style.setProperty('--term-row-height', `${state.cell.height}px`)
543
+ term.refreshCellSize()
544
+ $('scale-val').textContent = `${Math.round(next * 100)}%`
545
+ const layout = applyLayout()
546
+ // Even without a new app height, the scroller has to match the new cell size.
547
+ if (!layout) sizeScreen()
548
+ if (share === null) screen.scrollTop = screen.scrollHeight - screen.clientHeight
549
+ else keepReading(share)
550
+ fitGrid(layout)
551
+ }
552
+
553
+ /**
554
+ * Size the grid to the device, not to the moment. Rows come from the layout
555
+ * viewport so the keyboard opening never reflows pi; only what is visible
556
+ * changes.
557
+ */
558
+ function fitGrid(l = deriveLayout(readViewport())) {
559
+ // A fit requested without valid geometry waits for a valid, unpanned settle.
560
+ if (!l) { fitted = null; return }
561
+ fitted = { width: l.terminal.width, height: l.stableHeight }
562
+ const { cols, rows } = gridFor(l.terminal.width - scrollbarGutter() - 2 * SIDE_PAD, l.stableHeight, state.cell)
563
+ record(`fit ${cols}x${rows}`)
564
+ setGrid(cols, rows)
565
+ }
566
+
567
+ // visualViewport fires a burst during rotation and keyboard animation, and the
568
+ // intermediate values are wrong. Act at once, then again once it settles.
569
+ let settle = null
570
+ // The width and keyboard-down height the grid was last fitted to. A preset
571
+ // leaves the height null: a pick by hand stands until the width changes.
572
+ let fitted = null
573
+ // How many viewport events the burst now settling has had.
574
+ let burst = 0
575
+ // Whether the last viewport event saw a valid visual height.
576
+ let validHeight = true
577
+
578
+ function onViewportChange(e) {
579
+ // A burst is logged as the event that began it and where it settled, plus
580
+ // any rotation inside it and any change in whether the height is valid.
581
+ const valid = validVisualHeight(visualViewport.height)
582
+ if (e && (settle === null || e.type === 'orientationchange')) record(e.type.replace('orientationchange', 'rotate'))
583
+ else if (valid !== validHeight) record(valid ? 'valid' : 'invalid')
584
+ validHeight = valid
585
+ if (e) burst++
586
+ applyLayout()
587
+ clearTimeout(settle)
588
+ settle = setTimeout(() => {
589
+ settle = null
590
+ const down = rememberKeyboardDown()
591
+ if (down) record(`kb-down ${down.innerHeight}`)
592
+ const l = applyLayout()
593
+ // Rotating is a deliberate act and landscape is worth ~2x the columns, so
594
+ // it refits. The keyboard is not deliberate and never touches the grid:
595
+ // the grid is sized from the keyboard-down layout, which the keyboard does
596
+ // not change. That layout can still change on its own: Chrome on Android
597
+ // can come to rest short after a reload and reach full height later. Not
598
+ // on a panned page, which reads short by the pan (see rememberKeyboardDown).
599
+ if (l) {
600
+ const widthChanged = fitted && l.terminal.width !== fitted.width
601
+ const heightChanged = !fitted || (fitted.height !== null && l.stableHeight !== fitted.height)
602
+ if (widthChanged || (heightChanged && visualViewport.offsetTop === 0)) fitGrid(l)
603
+ }
604
+ record(`settled ${burst}`)
605
+ burst = 0
606
+ }, SETTLE_MS)
607
+ }
608
+
609
+ /**
610
+ * Coming back from hidden. iOS can change the viewport while the page is
611
+ * hidden and fire nothing, so the layout is read again. An iOS home-screen app
612
+ * can also come back panned up for a keyboard that went away while the screen
613
+ * was off, a WebKit fault that outlasts a blur and a reload. The page never
614
+ * scrolls by design, so there the pan is put back.
615
+ */
616
+ function onVisibilityChange() {
617
+ record(document.hidden ? 'hidden' : 'visible')
618
+ if (document.hidden) return
619
+ if (tabsEnabled) refreshTabs()
620
+ if (readViewport().standalone && (window.scrollY > 0 || visualViewport.offsetTop > 0)) {
621
+ window.scrollTo(0, 0)
622
+ record('unpan')
623
+ }
624
+ onViewportChange()
625
+ }
626
+
627
+ // ---------------------------------------------------------------- scrolling
628
+
629
+ /**
630
+ * A row with nothing on it. Blank cells coalesce into one bare `<span>` of
631
+ * spaces, so anything carrying a class or a style — the cursor, a block glyph
632
+ * drawn as a background, a coloured run — is content even where its text is
633
+ * empty.
634
+ */
635
+ const rowIsBlank = row => !row.textContent.trim() && !row.querySelector('span[class],span[style]')
636
+
637
+ /**
638
+ * Hide the empty rows at the foot of the grid, so the scroller ends where the
639
+ * program stopped writing.
640
+ *
641
+ * Everything that means "the bottom" measures the scroller — sizeScreen's pin,
642
+ * atBottom, and wterm's own follow-output and scroll-on-keystroke, which this
643
+ * client does not own. Ending its content at the last written row corrects all
644
+ * of them at once, where a content-aware scroll target here would be undone by
645
+ * the next keystroke.
646
+ */
647
+ function trimBlankTail() {
648
+ const rows = term.renderer.rowEls
649
+ let cut = rows.length
650
+ while (cut > 0 && rowIsBlank(rows[cut - 1])) cut--
651
+ for (let i = 0; i < rows.length; i++) {
652
+ const blank = i >= cut
653
+ if (rows[i].hidden !== blank) rows[i].hidden = blank
654
+ }
655
+ }
656
+
657
+ // wterm owns sticking to the bottom: it checks the position before each write,
658
+ // re-pins after rendering, and jumps back on a keystroke. onScroll's
659
+ // at-bottom branch decides live-vs-held (and drives the way-back button), and
660
+ // uses wterm's own tolerance so the two cannot disagree about whether you are
661
+ // on the live screen.
662
+ const AT_BOTTOM_PX = 5
663
+ const atBottom = () => screen.scrollHeight - screen.scrollTop - screen.clientHeight < AT_BOTTOM_PX
664
+
665
+ // Reading beats liveness. Output that arrives while the reader is up in
666
+ // history is held back rather than rendered under them: a new line shifts
667
+ // every visible row up one, including rows under the reader's eye, so a
668
+ // flowing stream moves the page the reader is on. Holding pauses the terminal
669
+ // rather than corrupting it: bytes replay in order the moment the reader
670
+ // returns to the bottom; the way-back button offers the return.
671
+ const HELD_MAX = 4 * 1024 * 1024
672
+ const held = []
673
+ // Read-only count for the scroll specs; the queue stays private so heldBytes can't desync.
674
+ Object.defineProperty(window.afield, 'heldCount', { get: () => held.length })
675
+ let heldBytes = 0
676
+ // True across a resize's reflow: term.resize empties the rendered rows, so
677
+ // for one turn the scroller is "at the bottom" by geometry alone, and output
678
+ // or a flush acting on that would change content under a parked reader. Set
679
+ // by keepReading, cleared when its re-pin settles or gives up.
680
+ let resettling = false
681
+ // The client sends size with its handshake and the server answers with a
682
+ // snapshot — and it sends the pair again on resize and folder switch, with
683
+ // no connection-state transition to watch for. So a size report is the one
684
+ // reliable "snapshot next" signal for this client, and the first output
685
+ // after one bypasses the hold: queued behind a parked reader it would leave
686
+ // them looking at a stale screen, and at the ring cap it would wipe their
687
+ // history on return.
688
+ let snapshotPending = false
689
+
690
+ // The snapshot is not the whole re-send. On a resize, pi's own redraw of the
691
+ // transcript trails it: the server serializes the mirror the moment the PTY
692
+ // changes, and the repaint arrives afterwards as ordinary output,
693
+ // indistinguishable frame-for-frame from new lines. For a reader at the
694
+ // bottom that lands live and heals; for one parked in history the hold would
695
+ // keep it off for good, leaving them on a layout the grid has already left.
696
+ // So for a short window after a snapshot, output writes through and the
697
+ // reader is held by the share pin instead of by the hold: the redraw is the
698
+ // same history re-wrapped, and the pin keeps their line under the eye while
699
+ // it lands.
700
+ const SNAPSHOT_TAIL_MS = 2000
701
+ let snapshotTail = 0
702
+
703
+ const pinReader = () => {
704
+ const share = readingShareNow()
705
+ if (share !== null) keepReading(share)
706
+ }
707
+
708
+ function flushHeld() {
709
+ if (!held.length) return
710
+ // Shift-per-write, not splice-then-write: a write that throws mid-replay
711
+ // costs the rest of the queue, not the whole of it — and the finally puts
712
+ // the pending grid back whatever happened.
713
+ try {
714
+ while (held.length) {
715
+ const bytes = held.shift()
716
+ heldBytes -= bytes.length
717
+ term.write(bytes)
718
+ }
719
+ } finally {
720
+ applyPendingGrid()
721
+ }
722
+ }
723
+
724
+ /** The hold is dropped, not flushed, on a disconnect: the reconnect snapshot supersedes it. */
725
+ function dropHeld() {
726
+ held.length = 0
727
+ heldBytes = 0
728
+ // A dropped hold rides a PTY reset or a view wipe: the field mirror's line
729
+ // no longer exists, so the next diff must start from an empty field.
730
+ term.input?.resetMirror()
731
+ }
732
+
733
+ function deliver(bytes) {
734
+ if (snapshotPending) {
735
+ snapshotPending = false
736
+ const share = readingShareNow()
737
+ // Everything being held is already inside the snapshot: the server writes
738
+ // its mirror the same bytes it sends us, and serializes it at a boundary
739
+ // behind them. Replaying the hold on top would apply it twice -- history
740
+ // gaining lines that were only ever produced once. What is not inside it
741
+ // -- pi's redraw on a resize -- follows as ordinary output, and the tail
742
+ // window below writes it through.
743
+ dropHeld()
744
+ snapshotTail = share === null ? 0 : performance.now() + SNAPSHOT_TAIL_MS
745
+ term.write(bytes)
746
+ applyPendingGrid()
747
+ if (share !== null) pinReader()
748
+ // The snapshot reset the core, so the rendered window's keys no longer
749
+ // match the fresh core's counts and the next render redraws it wholesale.
750
+ return
751
+ }
752
+ if (performance.now() < snapshotTail) {
753
+ // Inside the tail window the reader is pinned, not protected. The share
754
+ // is read fresh on each write, so one who scrolled mid-window is held
755
+ // where they moved to, and keepReading's cancel-on-touch still applies.
756
+ // A reader at the live edge has no share, and this is just the live path.
757
+ term.write(bytes)
758
+ applyPendingGrid()
759
+ pinReader()
760
+ return
761
+ }
762
+ // The scroll event normally flushes on return to the bottom, but its
763
+ // dispatch can trail the next chunk, and replay order must not depend on
764
+ // that race: whatever is held goes first, always. A resize in flight
765
+ // suspends the at-bottom verdict entirely (see `resettling`).
766
+ const live = atBottom() && !resettling
767
+ if (held.length && live) flushHeld()
768
+ if (live) { term.write(bytes); applyPendingGrid(); return }
769
+ held.push(bytes)
770
+ heldBytes += bytes.length
771
+ // Past the cap this is a memory valve, nothing more: the replay lands under
772
+ // wterm's own follow/compensation logic, which keeps the reader's line put,
773
+ // and the hold resumes with the next chunk. A reader this far ahead of the
774
+ // stream is not reading.
775
+ if (heldBytes > HELD_MAX) flushHeld()
776
+ }
777
+
778
+ function onScroll() {
779
+ const bottom = atBottom() && !resettling
780
+ toBottom.hidden = bottom
781
+ if (bottom) {
782
+ // Landing on the bottom is the reader asking for live again. wterm's own
783
+ // scroll handler clears its follow-output latch on every scroll it does
784
+ // not recognize as its own -- a programmatic jump lands there, since the
785
+ // direct scrollTop write cannot match wterm's programmatic-pin sentinel --
786
+ // and once the latch is down, rotation compensation at a saturated ring
787
+ // walks the box off the bottom a row at a time, silently holding live
788
+ // output. Re-assert the latch so follow-output wins over compensation.
789
+ term.followOutput(true)
790
+ flushHeld()
791
+ }
792
+ }
793
+
794
+ // ---------------------------------------------------------------- key bar
795
+
796
+ // For a letter key, meta is just an ESC prefix, so `esc` then `b` is
797
+ // byte-identical to alt+b and there would be nothing this button adds. Arrows
798
+ // are the exception: alt+Up is one CSI sequence with a modifier parameter
799
+ // (\e[1;3A), not reproducible by sending esc and Up separately — those stay
800
+ // two unrelated sequences, and esc alone is a real keystroke on its own (it
801
+ // aborts the current task), not a modifier waiting to be paired.
802
+ const BAR = [
803
+ { label: '⌃', mod: 'ctrl' },
804
+ { label: '⇧', mod: 'shift' },
805
+ { label: '⌥', mod: 'alt' },
806
+ { label: 'esc', key: 'Escape' },
807
+ { label: '⇥', key: 'Tab' },
808
+ // The bar's ⌫ carries its own repeat timer: iOS repeats deletions natively
809
+ // only through input events on the field, which the field-mirror diff
810
+ // already services -- the bar is for when the field is empty or the
811
+ // keyboard's repeat has run out of line.
812
+ { label: '⌫', key: 'Backspace', repeat: true },
813
+ { label: '⏎', key: 'Enter' },
814
+ { label: '↑↓', name: 'arrow pad', cls: 'wide', act: togglePad },
815
+ { label: '⌨', name: 'keyboard', cls: 'wide', release: toggleKeyboard },
816
+ { label: '≡', name: 'menu', act: openMenu },
817
+ ]
818
+
819
+ // The arrows live in a pad that pops over the terminal rather than on the bar:
820
+ // four more keys squeeze every button under a thumb's width, and Enter needs
821
+ // the room more. The pad stays open across presses -- walking a pi menu is an
822
+ // arrow per step -- and an armed ⌃/⇧/⌥ on the bar reaches its keys like any
823
+ // other.
824
+ const PAD = [
825
+ // Page up/down lead the pad: the terminal is a few screens tall at most on
826
+ // a phone, so the page step is the everyday move and the arrows finish it.
827
+ // Paired arrows for a page of distance, single arrows for a row.
828
+ { label: '⇈', key: 'PageUp', repeat: true },
829
+ { label: '⇊', key: 'PageDown', repeat: true },
830
+ { label: '←', key: 'Left', repeat: true },
831
+ { label: '↓', key: 'Down', repeat: true },
832
+ { label: '↑', key: 'Up', repeat: true },
833
+ { label: '→', key: 'Right', repeat: true },
834
+ ]
835
+
836
+ const terminalInput = () => term.input.textarea
837
+
838
+ // A bar key must not dismiss the keyboard. iOS ends editing when DOM focus
839
+ // leaves the textarea, and a tap's default activation would move focus to the
840
+ // button. Bar buttons are non-focusable and their press is prevented, so focus
841
+ // never leaves the input and the keyboard stays up.
842
+
843
+ /** The app's own close-the-keyboard buttons blur the input, deliberately. */
844
+ function dismissKeyboard() {
845
+ const input = terminalInput()
846
+ if (document.activeElement === input) input.blur()
847
+ }
848
+
849
+ // Set when the keyboard key asks for the keyboard, cleared once the viewport
850
+ // shows it or the input loses focus. Still set means a keyboard the viewport
851
+ // cannot see -- an iPad's floating one, a hardware keyboard's bar -- or one
852
+ // still on its way up, and either way the next press puts it away.
853
+ let awaitingKeyboard = false
854
+
855
+ /**
856
+ * Summon or dismiss the software keyboard without having to find something to
857
+ * tap. Runs on the key's release: a focus only opens the keyboard inside a
858
+ * user gesture, and Chrome on Android counts a touch as one from its pointerup,
859
+ * so on a freshly loaded page, before any pointerup, a focus on pointerdown
860
+ * shows nothing.
861
+ */
862
+ function toggleKeyboard() {
863
+ const input = terminalInput()
864
+ if (document.activeElement === input && (deriveLayout(readViewport())?.keyboardUp || awaitingKeyboard)) {
865
+ record('key down')
866
+ return dismissKeyboard()
867
+ }
868
+ record('key up')
869
+ // Focus alone does not mean a keyboard: the input is focused with none
870
+ // after a fresh load, and after Android's Back hides it without a blur.
871
+ // Focusing it again then does nothing; blurring first makes it a fresh
872
+ // focus, which brings the keyboard up.
873
+ input.blur()
874
+ term.focus()
875
+ awaitingKeyboard = true
876
+ }
877
+
878
+ /** Pop the arrow pad over the terminal, or away again. */
879
+ function showPad(open) {
880
+ pad.hidden = !open
881
+ const toggle = keys.querySelector('button[name="arrow pad"]')
882
+ toggle.classList.toggle('sticky', open)
883
+ toggle.setAttribute('aria-expanded', String(open))
884
+ }
885
+
886
+ function togglePad() { showPad(pad.hidden) }
887
+
888
+ // A tap outside the pad and the bar dismisses it. A bar press does not: an
889
+ // armed ⌃/⇧/⌥ on the bar is how a modified arrow gets sent, so the pad stays
890
+ // up while the modifier is armed.
891
+ document.addEventListener('pointerdown', e => {
892
+ if (!pad.hidden && !e.target.closest('#pad, #keys')) showPad(false)
893
+ })
894
+
895
+ /** The keyboard would cover most of the menu, so it goes away first. */
896
+ /** Show the readout instead of the menu, or the menu instead of the readout. */
897
+ function foldDiag(open) {
898
+ $('diag').hidden = !open
899
+ $('menu-main').hidden = open
900
+ $('diag-caret').textContent = open ? '▾' : '▸'
901
+ }
902
+
903
+ function hideMenu() {
904
+ retryPicker = null
905
+ menu.hidden = true
906
+ }
907
+
908
+ function openMenu({ preserveNotice = false } = {}) {
909
+ retryPicker = null
910
+ menuView = 'normal'
911
+ dismissKeyboard()
912
+ // The pad would cover the sheet the same way the keyboard does.
913
+ showPad(false)
914
+ // Always on the ordinary view: the menu is mostly the session list now, and
915
+ // opening into last time's diagnostics would be a puzzle.
916
+ foldDiag(false)
917
+ $('advanced').open = false
918
+ // Asked for on the way in rather than held from last time: pi is used from
919
+ // other terminals too, so the list goes stale between openings.
920
+ refreshPlaces({ preserveNotice }).catch(() => {})
921
+ menu.hidden = false
922
+ }
923
+
924
+ // ---------------------------------------------------------------- sessions
925
+
926
+ /**
927
+ * Every session pi has a transcript for, as the server found them: running
928
+ * ones first and then newest first, since which folder they
929
+ * are in matters less on a phone than how recently you touched them.
930
+ *
931
+ * Joining one never ends another: sessions keep running once left, so a row
932
+ * acts the moment it is tapped rather than asking for a second confirming tap
933
+ * the way ending a program used to need.
934
+ */
935
+ function placePath(sess) {
936
+ return el('span', 'place-path',
937
+ el('span', 'place-path-text', `${sess.path} · ${ago(sess.at)}`),
938
+ ...(sess.viewers >= 1 ? [el('span', 'place-watchers', `${sess.viewers} watching`)] : []),
939
+ )
940
+ }
941
+
942
+ function showPlaces({ sessions, more, offset, here, kinds }) {
943
+ const active = currentPlace?.processId && sessions.find(s => s.processId === currentPlace.processId)
944
+ if (active) {
945
+ currentPlace = active
946
+ placeNow.textContent = active.path
947
+ }
948
+ places.textContent = ''
949
+
950
+ // The ways to be somewhere with no transcript yet: a fresh pi, or a plain
951
+ // terminal, whichever this server offers.
952
+ const starts = [['pi', '+ New pi session'], ['shell', '+ New terminal']]
953
+ .filter(([kind]) => kinds.includes(kind))
954
+ if (starts.length) {
955
+ const row = el('div', 'place-starts')
956
+ for (const [kind, label] of starts) {
957
+ const start = el('button', 'place start', el('span', 'place-name', label))
958
+ start.addEventListener('click', () => showDirs({ sessions, here, kind }))
959
+ row.append(start)
960
+ }
961
+ places.append(row)
962
+ }
963
+
964
+ for (const sess of sessions) places.append(sessionRow(sess))
965
+ showMore({ more, offset }, sessions)
966
+ }
967
+
968
+ /** What a running session's marker says: it is working, or stopped while nobody watched. */
969
+ const markOf = sess => sess.working ? 'working' : sess.unread ? 'unread' : null
970
+
971
+ /** Every running row has a marker; one that is neither working nor unread is
972
+ * just running. The spoken word sits outside the name, which stays the label,
973
+ * so this goes on the row before the name does. */
974
+ function markRunning(row, sess) {
975
+ const mark = markOf(sess) ?? 'running'
976
+ row.classList.add('running', mark)
977
+ row.append(srOnly(`${mark} `))
978
+ }
979
+
980
+ const srOnly = text => el('span', 'sr-only', text)
981
+
982
+ function confirmEnd(sess, onConfirmed = () => endSession(sess)) {
983
+ if (armedEndId !== sess.processId) return void armEnd(sess.processId)
984
+ clearEndArm()
985
+ void onConfirmed()
986
+ }
987
+
988
+ /** One session row, for the list, appended pages, and the full-pool picker. */
989
+ function sessionRow(sess, { onTap = () => joinSession(sess), onEnd = () => confirmEnd(sess), at = sess.at, markHere = true } = {}) {
990
+ const wrap = el('div', `place-row${sess.running ? ' has-end' : ''}`)
991
+ wrap.dataset.sessionId = sess.id
992
+
993
+ const row = el('button', markHere && samePlace(sess, currentPlace) ? 'place here' : 'place')
994
+ if (sess.running) markRunning(row, sess)
995
+ // pi names a session once it has read the first exchange; before that,
996
+ // the label is whatever was first asked, so the row is never bare.
997
+ row.append(el('span', 'place-name', sess.label), placePath(at === sess.at ? sess : { ...sess, at }))
998
+ row.addEventListener('click', onTap)
999
+ wrap.append(row)
1000
+
1001
+ // Keep the destructive action separate from the join button so it remains
1002
+ // keyboard-accessible without nesting interactive controls.
1003
+ if (sess.running) {
1004
+ const end = el('button', 'place-end')
1005
+ end.dataset.processId = sess.processId
1006
+ end.dataset.label = sess.label
1007
+ end.addEventListener('click', onEnd)
1008
+ updateEndControl(sess.processId, end)
1009
+ wrap.append(end)
1010
+ }
1011
+ return wrap
1012
+ }
1013
+
1014
+ /**
1015
+ * Each tap extends the prefix of the ranking fetched so far. Sessions can
1016
+ * move upward as transcripts are written; rereading the prefix includes those
1017
+ * rows instead of skipping them between offset windows. Already shown rows
1018
+ * are not drawn twice.
1019
+ */
1020
+ function showMore({ more: hasMore, offset }, shown) {
1021
+ if (!hasMore) return
1022
+ const more = document.createElement('button')
1023
+ more.className = 'place-more'
1024
+ more.textContent = 'show older'
1025
+ more.addEventListener('click', async () => {
1026
+ more.disabled = true
1027
+ more.textContent = 'loading…'
1028
+ const request = placesRequest
1029
+ let data
1030
+ try {
1031
+ data = await fetchPlaces({ limit: offset + MENU_PAGE })
1032
+ } catch {
1033
+ if (request !== placesRequest || !more.isConnected) return
1034
+ showMenuNotice('could not load older sessions')
1035
+ more.disabled = false
1036
+ more.textContent = 'show older'
1037
+ return
1038
+ }
1039
+ if (request !== placesRequest || !more.isConnected) return
1040
+ more.remove()
1041
+ const fresh = data.sessions.filter(sess => !shown.some(old => samePlace(sess, old)))
1042
+ for (const sess of fresh) places.append(sessionRow(sess))
1043
+ showMore(data, [...shown, ...fresh])
1044
+ })
1045
+ places.append(more)
1046
+ }
1047
+
1048
+ function updateEndControl(id, existing) {
1049
+ const control = existing ?? [...places.querySelectorAll('.place-end')]
1050
+ .find(button => button.dataset.processId === id)
1051
+ if (!control) return
1052
+ const ending = endingIds.has(id)
1053
+ const armed = armedEndId === id
1054
+ control.disabled = ending
1055
+ control.textContent = ending ? 'Ending…' : armed ? 'End it?' : 'End'
1056
+ control.classList.toggle('confirm', armed && !ending)
1057
+ control.setAttribute('aria-label', `${ending ? 'ending' : armed ? 'confirm ending' : 'end'} ${control.dataset.label}`)
1058
+ }
1059
+
1060
+ function clearEndArm() {
1061
+ if (endArmTimer !== null) clearTimeout(endArmTimer)
1062
+ endArmTimer = null
1063
+ armedEndId = null
1064
+ }
1065
+
1066
+ function armEnd(id) {
1067
+ const previous = armedEndId
1068
+ clearEndArm()
1069
+ if (previous !== null && previous !== id) updateEndControl(previous)
1070
+ armedEndId = id
1071
+ updateEndControl(id)
1072
+ endArmTimer = setTimeout(() => {
1073
+ if (armedEndId !== id) return
1074
+ armedEndId = null
1075
+ endArmTimer = null
1076
+ updateEndControl(id)
1077
+ }, 4_000)
1078
+ }
1079
+
1080
+ /** End a running PTY, then refresh the place list and the tabs. Answers whether the
1081
+ * terminal is gone, which is all the full-pool picker can go on. */
1082
+ async function endSession(sess) {
1083
+ let gone = false
1084
+ endingIds.add(sess.processId)
1085
+ updateEndControl(sess.processId)
1086
+ try {
1087
+ const res = await fetch(`/terminal?process=${encodeURIComponent(sess.processId)}`, { method: 'DELETE' })
1088
+ gone = res.ok || res.status === 404
1089
+ if (!res.ok && res.status !== 404) showMenuNotice(`End failed (${res.status})`)
1090
+ } catch {
1091
+ showMenuNotice('End failed')
1092
+ } finally {
1093
+ // Settled either way: a failed end must not read as "this viewer ended
1094
+ // it" if someone else gets the session killed for real a moment later.
1095
+ endingIds.delete(sess.processId)
1096
+ updateEndControl(sess.processId)
1097
+ // A refused join has already dropped the socket that could report this End.
1098
+ if (gone && !conn.started && currentPlace?.processId === sess.processId) finishEnded('')
1099
+ else {
1100
+ refreshPlaces({ preserveNotice: !gone }).catch(() => {})
1101
+ if (tabsEnabled) refreshTabs()
1102
+ }
1103
+ }
1104
+ return gone
1105
+ }
1106
+
1107
+ /**
1108
+ * The pool is full: say what the server said, offer one row per running
1109
+ * session to end, in the order the server picked, and do the refused action
1110
+ * again once one of them is gone. Two taps to end, the same as the End
1111
+ * control on a list row. Cancel goes back to the ordinary menu.
1112
+ */
1113
+ async function showPoolFull(attempt, retry) {
1114
+ const picker = {}
1115
+ retryPicker = picker
1116
+ let running
1117
+ try {
1118
+ running = (await fetchPlaces({ running: true })).sessions
1119
+ } catch (error) {
1120
+ if (retryPicker !== picker) return
1121
+ openMenu({ preserveNotice: true })
1122
+ showMenuNotice(error.message)
1123
+ return
1124
+ }
1125
+ if (retryPicker !== picker) return
1126
+ clearEndArm()
1127
+ openMenu({ preserveNotice: true })
1128
+ // The ordinary list must not draw over the picker while the menu is open.
1129
+ menuView = 'pick'
1130
+ places.textContent = ''
1131
+ retryPicker = picker
1132
+ places.append(
1133
+ backButton('‹ Cancel', () => openMenu()),
1134
+ el('div', 'place-heading pool', running.length
1135
+ ? `Limit reached (${running.length} running). End one and ${attempt}.`
1136
+ : 'Limit reached. Nothing is running to end.'),
1137
+ )
1138
+
1139
+ for (const sess of running) {
1140
+ const tap = () => {
1141
+ if (retryPicker !== picker) return
1142
+ confirmEnd(sess, async () => {
1143
+ if (await endSession(sess) && retryPicker === picker) {
1144
+ places.replaceChildren()
1145
+ openMenu()
1146
+ await retry()
1147
+ }
1148
+ })
1149
+ }
1150
+ // A row's `at` is when the transcript was touched; the picker is ordered
1151
+ // by when the program last printed anything.
1152
+ places.append(sessionRow(sess, { onTap: tap, onEnd: tap, at: sess.active, markHere: false }))
1153
+ }
1154
+
1155
+ if (!running.length) {
1156
+ retryPicker = null
1157
+ menuView = 'normal'
1158
+ }
1159
+ }
1160
+
1161
+ /** `3m`, `2h`, `5d` since a session was last active. */
1162
+ const ago = at => {
1163
+ if (!at) return ''
1164
+ const s = Math.max(0, (Date.now() - at) / 1000)
1165
+ if (s < 60) return 'now'
1166
+ if (s < 3600) return `${s / 60 | 0}m`
1167
+ if (s < 86400) return `${s / 3600 | 0}h`
1168
+ return `${s / 86400 | 0}d`
1169
+ }
1170
+
1171
+ function backButton(label, onClick) {
1172
+ const button = el('button', 'place dir', label)
1173
+ button.addEventListener('click', onClick)
1174
+ return button
1175
+ }
1176
+
1177
+ function dirRow(title, pathText, onClick) {
1178
+ const button = el('button', 'place dir',
1179
+ el('span', 'place-name', title),
1180
+ ...(pathText !== undefined ? [el('span', 'place-path', pathText)] : []),
1181
+ )
1182
+ button.addEventListener('click', onClick)
1183
+ return button
1184
+ }
1185
+
1186
+ /**
1187
+ * Where a brand-new session can go. The server's own folder comes first and
1188
+ * is the one chosen by just tapping through; the rest are the folders pi
1189
+ * already runs in. Anything else is a walk through the folders on disk.
1190
+ * `kind` is what the session runs, `pi` or `shell`.
1191
+ */
1192
+ function showDirs({ sessions, here, kind }) {
1193
+ places.textContent = ''
1194
+ places.append(
1195
+ backButton('‹ Back', () => refreshPlaces().catch(() => {})),
1196
+ el('div', 'place-heading', `New ${kind === 'pi' ? 'pi session' : 'terminal'} in:`),
1197
+ )
1198
+
1199
+ const dirs = [...new Set([here, ...sessions.map(s => s.cwd)])]
1200
+ const appendDir = dir =>
1201
+ places.append(dirRow(basename(dir), dir === here ? 'this folder' : '', () => startSession(dir, kind)))
1202
+ appendDir(dirs[0])
1203
+ places.append(dirRow('Navigate to folder…', undefined, () => walkSession(here, kind)))
1204
+ for (const dir of dirs.slice(1)) appendDir(dir)
1205
+ }
1206
+
1207
+ /**
1208
+ * Where a fresh session can go when none of the folders above is it: the
1209
+ * folders inside this one, a row at a time. Tapping a name walks in, the
1210
+ * parent row walks out, and the first row starts a session where the walk is.
1211
+ */
1212
+ async function walkSession(cwd, kind) {
1213
+ places.textContent = ''
1214
+ places.append(backButton('‹ Back', () => refreshPlaces().catch(() => {})))
1215
+
1216
+ const res = await fetch(`/subfolders?cwd=${encodeURIComponent(cwd)}`)
1217
+ if (!res.ok) {
1218
+ clearMenuNotice()
1219
+ showMenuNotice((await res.text()) || 'could not read that folder')
1220
+ return
1221
+ }
1222
+ const listing = await res.json()
1223
+
1224
+ places.append(dirRow(`Start ${kind === 'pi' ? 'pi' : 'terminal'} here`, listing.cwd, () => startSession(listing.cwd, kind)))
1225
+ if (listing.parent) places.append(dirRow(`↰ ${basename(listing.parent)}`, listing.parent, () => walkSession(listing.parent, kind)))
1226
+ for (const dir of listing.dirs) places.append(dirRow(basename(dir), '', () => walkSession(dir, kind)))
1227
+ }
1228
+
1229
+ /** Ask the server to begin a fresh session of `kind` in `dir`, then join it. */
1230
+ async function startSession(dir, kind) {
1231
+ // A choice from the tap, not from the answer: automatic selection must
1232
+ // not dial over a Start that is still waiting for the server.
1233
+ const version = ++selectionVersion
1234
+ retryPicker = null
1235
+ starting = version
1236
+ try {
1237
+ const res = await fetch('/start', {
1238
+ method: 'POST',
1239
+ headers: { 'content-type': 'application/json' },
1240
+ body: JSON.stringify({ cwd: dir, kind }),
1241
+ })
1242
+ if (version !== selectionVersion) return
1243
+ if (res.status === 409) return showPoolFull(`your new ${kind === 'pi' ? 'pi session' : 'terminal'} in ${basename(dir)} starts`, () => startSession(dir, kind))
1244
+ if (!res.ok) throw new Error(await res.text())
1245
+ const { id, cwd, processId } = await res.json()
1246
+ if (version !== selectionVersion) return
1247
+ // Name and path come from the PROCESS frame that follows.
1248
+ joinSession({ id, cwd, processId })
1249
+ refreshPlaces().catch(() => {})
1250
+ } catch (error) {
1251
+ if (version === selectionVersion) showMenuNotice(error.message || 'could not start a session')
1252
+ } finally {
1253
+ if (starting === version) starting = null
1254
+ }
1255
+ }
1256
+
1257
+ function dialPlace(sess) {
1258
+ pendingPlace = sess
1259
+ showLoading(sess)
1260
+ const url = sessionUrl(sess)
1261
+ if (conn.started) conn.join(url)
1262
+ else {
1263
+ conn.url = url
1264
+ conn.connect({ cols: state.wanted.cols, rows: state.wanted.rows })
1265
+ }
1266
+ }
1267
+
1268
+ async function switchAfterEnd(ended) {
1269
+ const version = selectionVersion
1270
+ const data = await fetchPlaces({ running: true }).catch(() => null)
1271
+ if (!data?.sessions || version !== selectionVersion || retryPicker) return
1272
+ const remaining = data.sessions.filter(sess => sess.processId !== ended.processId)
1273
+ .sort(tabOrder)
1274
+ const next = remaining.find(sess => tabOrder(sess, ended) > 0) ?? remaining[0]
1275
+ if (next) joinSession(next)
1276
+ }
1277
+
1278
+ /** Point the connection at another session's socket and reconnect to it. */
1279
+ function joinSession(sess) {
1280
+ selectionVersion++
1281
+ clearEndArm()
1282
+ clearMenuNotice()
1283
+ // Reaching a session is the end of the picker that asked for it.
1284
+ menuView = 'normal'
1285
+ dialPlace(sess)
1286
+ hideMenu()
1287
+ }
1288
+
1289
+ /**
1290
+ * Apply a sticky modifier to a key from the software keyboard. Those arrive
1291
+ * through wterm rather than the key bar, so without this `⌃` then `c` sends a
1292
+ * bare `c` and Ctrl-C is unreachable. Only single characters qualify — a paste
1293
+ * or a dictated phrase is not a chord.
1294
+ */
1295
+ function withMods(data) {
1296
+ // Diff-transmitted bytes are the field's own content, not a user chord:
1297
+ // consuming an armed modifier here would rewrite them (⌥+DEL becomes a
1298
+ // kill-word) and desynchronize the mirror. Keydown-sent keystrokes --
1299
+ // where a sticky modifier is the whole point -- still pass through.
1300
+ if (term.input?.inFlush) return data
1301
+ return modChord(data) ?? data
1302
+ }
1303
+
1304
+ /**
1305
+ * The chord the armed modifiers make of one typed key, or null when no Ctrl or
1306
+ * Alt is armed. Also wterm's keyChord hook: Gboard's keydowns are keyCode 229,
1307
+ * so its letters reach wterm only as one-character changes to the field, which
1308
+ * wterm offers here before transmitting them.
1309
+ */
1310
+ function modChord(key) {
1311
+ if (key.length !== 1) return null
1312
+ const { ctrl, alt, shift } = state.mods
1313
+ // Any single key consumes the modifiers, including a lone shift the OS
1314
+ // keyboard already applied — otherwise it stays lit and silently lands on
1315
+ // whatever bar key comes next.
1316
+ clearMods()
1317
+ if (!(ctrl || alt)) return null
1318
+ return keySequence(key, { ctrl, alt, shift })
1319
+ }
1320
+
1321
+ function sendKey(name) {
1322
+ const { ctrl, alt, shift } = state.mods
1323
+ // The bar exists before the WASM core finishes loading, and DECCKM is reset
1324
+ // by definition until an app sets it — so normal-mode CSI is the answer, not
1325
+ // a crash on an early tap.
1326
+ const cursorKeysApp = term.bridge?.cursorKeysApp() ?? false
1327
+ conn.send(keySequence(name, { ctrl, alt, shift, cursorKeysApp }))
1328
+ // Everything a bar key sends either changes or consumes the PTY's line, so
1329
+ // the field mirror goes.
1330
+ term.input?.resetMirror()
1331
+ clearMods()
1332
+ }
1333
+
1334
+ function clearMods() {
1335
+ for (const m of Object.keys(state.mods)) state.mods[m] = false
1336
+ // Only the modifier keys carry the highlight. `toggle(cls, undefined)` flips
1337
+ // rather than removes, so touching the others lit up half the bar.
1338
+ for (const b of keys.children) if (b.dataset.mod) b.classList.remove('sticky')
1339
+ }
1340
+
1341
+ /** One bar or pad key, with the press plumbing that keeps the keyboard up. */
1342
+ function keyButton(item) {
1343
+ const b = document.createElement('button')
1344
+ b.textContent = item.label
1345
+ b.setAttribute('aria-label', item.name ?? item.key ?? item.mod)
1346
+ if (item.name) b.name = item.name
1347
+ if (item.act === togglePad) {
1348
+ // The pad's toggle also reports its state to screen readers.
1349
+ b.setAttribute('aria-controls', 'pad')
1350
+ b.setAttribute('aria-expanded', 'false')
1351
+ }
1352
+ if (item.label.length > 1) b.classList.add('word')
1353
+ if (item.cls) b.classList.add(item.cls)
1354
+ // Keeps the terminal's textarea focused. A tap's default activation would
1355
+ // move DOM focus to this (focusable) button, and iOS ends editing whenever
1356
+ // focus leaves the editable input — that blur is what dismisses the
1357
+ // keyboard. So the button drops out of tab order (tabindex=-1) and its
1358
+ // default press/click is cancelled, which leaves the textarea focused
1359
+ // through the whole gesture.
1360
+ b.tabIndex = -1
1361
+ b.addEventListener('pointerdown', e => e.preventDefault())
1362
+ b.addEventListener('touchstart', e => e.preventDefault(), { passive: false })
1363
+ if (item.mod) {
1364
+ b.dataset.mod = item.mod
1365
+ b.addEventListener('pointerdown', () => {
1366
+ state.mods[item.mod] = !state.mods[item.mod]
1367
+ b.classList.toggle('sticky', state.mods[item.mod])
1368
+ })
1369
+ } else if (item.release) {
1370
+ // Only the release of a press that began on this key counts, not one that
1371
+ // slid in from the terminal or another finger's. A press that leaves the
1372
+ // key is dropped, as bindRepeat's are; a touch never does (the key holds
1373
+ // it until it lifts), so a touch fires wherever it lifts.
1374
+ let pressing = null
1375
+ b.addEventListener('pointerdown', e => { pressing = e.pointerId })
1376
+ for (const ev of ['pointerup', 'pointercancel', 'pointerleave']) {
1377
+ b.addEventListener(ev, e => {
1378
+ if (e.pointerId !== pressing) return
1379
+ pressing = null
1380
+ if (ev === 'pointerup') item.release()
1381
+ })
1382
+ }
1383
+ } else {
1384
+ bindRepeat(b, item.act ?? (() => sendKey(item.key)), item.repeat)
1385
+ }
1386
+ return b
1387
+ }
1388
+
1389
+ function buildKeys() {
1390
+ for (const item of BAR) keys.appendChild(keyButton(item))
1391
+ for (const item of PAD) pad.appendChild(keyButton(item))
1392
+ }
1393
+
1394
+ /** Fire on press, and for navigation keys keep firing while held. */
1395
+ function bindRepeat(btn, fire, repeat) {
1396
+ let delay, timer
1397
+ const stop = () => { clearTimeout(delay); clearInterval(timer) }
1398
+ btn.addEventListener('pointerdown', e => {
1399
+ e.preventDefault()
1400
+ fire()
1401
+ if (repeat) delay = setTimeout(() => { timer = setInterval(fire, REPEAT_EVERY_MS) }, REPEAT_AFTER_MS)
1402
+ })
1403
+ for (const ev of ['pointerup', 'pointercancel', 'pointerleave']) btn.addEventListener(ev, stop)
1404
+ }
1405
+
1406
+ // ---------------------------------------------------------------- diagnostics
1407
+
1408
+ /**
1409
+ * A phone shows no stack trace, so a client that dies during startup looks like
1410
+ * missing chrome or scrolling that will not scroll — symptoms with no visible
1411
+ * cause. Put the error on the screen instead.
1412
+ */
1413
+ function reportFatal(what) {
1414
+ const overlay = $('diag-overlay')
1415
+ if (!overlay) return
1416
+ let detail
1417
+ try { detail = diagnosticText() } catch (e) { detail = `diagnostics failed: ${e}` }
1418
+ overlay.textContent = `ERROR — ${what}\n\n${detail}`
1419
+ overlay.hidden = false
1420
+ }
1421
+
1422
+ window.addEventListener('error', e => reportFatal(`${e.message} @ ${e.lineno}:${e.colno}`))
1423
+ window.addEventListener('unhandledrejection', e => reportFatal(`unhandled: ${e.reason?.message ?? e.reason}`))
1424
+
1425
+ /** On-device readout. The emulator cannot report insets or a real keyboard. */
1426
+ function diagnosticText() {
1427
+ const s = readViewport()
1428
+ const l = deriveLayout(s)
1429
+ const b = term.bridge
1430
+ const sb = b ? `${b.getScrollbackCount()} rows` : 'no core'
1431
+ return [
1432
+ `build ${BUILD_ID} standalone ${s.standalone}`,
1433
+ `ua ${navigator.userAgent}`,
1434
+ `inner ${s.innerWidth}x${s.innerHeight} visual ${Math.round(s.visualWidth)}x${Math.round(s.visualHeight)} @${s.offsetTop} scale ${visualViewport.scale}`,
1435
+ `insets t${s.insetTop} r${s.insetRight} b${s.insetBottom} l${s.insetLeft}`,
1436
+ l ? `keyboard ${l.keyboardHeight} (up ${l.keyboardUp}) ${l.orientation}` : 'keyboard unknown (invalid visual height)',
1437
+ `bar ${l ? `${l.keyBarHeight} (pad ${l.keyBarPadBottom}) ` : ''}rect ${JSON.stringify(bar.getBoundingClientRect().toJSON().top)}..${Math.round(bar.getBoundingClientRect().bottom)}`,
1438
+ `app ${Math.round(app.getBoundingClientRect().top)}..${Math.round(app.getBoundingClientRect().bottom)} screen ${window.screen.width}x${window.screen.height}`,
1439
+ `grid ${state.cols}x${state.rows} cell ${state.cell.width.toFixed(2)}x${state.cell.height} wtermRow ${term._rowHeight} scale ${state.scale}`,
1440
+ l && `term ${Math.round(l.terminal.width)}x${Math.round(l.terminal.height)} stable ${Math.round(l.stableHeight)}`,
1441
+ `scroll top ${screen.scrollTop} of ${screen.scrollHeight} in ${screen.clientHeight}`,
1442
+ `sb ${sb} domRows ${screen.querySelectorAll('.term-row:not([hidden])').length} held ${heldBytes}B`,
1443
+ `overflow ${getComputedStyle(screen).overflowY} class ${screen.className}`,
1444
+ ].filter(Boolean).join('\n')
1445
+ }
1446
+
1447
+ // What the viewport reported around recent events. A layout glitch only shows
1448
+ // after the moment that caused it, and opening the menu to read the numbers
1449
+ // puts the keyboard away, so the lead-up has to be on record already. Kept
1450
+ // across reloads, since a reload is often the first thing tried after a fault.
1451
+ const LOG_MAX = 50
1452
+ const LAYOUT_LOG = 'afield-layout-log'
1453
+ const layoutLog = JSON.parse(sessionStorage.getItem(LAYOUT_LOG) ?? '[]')
1454
+ let lastReading = ''
1455
+
1456
+ const viewportReading = () =>
1457
+ `in${window.innerHeight} vv${Math.round(visualViewport.width)}x${Math.round(visualViewport.height)}@${Math.round(visualViewport.offsetTop)}` +
1458
+ ` y${Math.round(window.scrollY)} ch${document.documentElement.clientHeight} r${window.screen.orientation?.angle} s${visualViewport.scale}`
1459
+
1460
+ function record(what) {
1461
+ lastReading = viewportReading()
1462
+ const flags = (document.activeElement === terminalInput() ? 'F' : '-') +
1463
+ (document.hasFocus() ? 'W' : '-') + (document.hidden ? 'H' : 'V')
1464
+ const now = new Date()
1465
+ const time = `${now.toTimeString().slice(0, 8)}.${String(now.getMilliseconds()).padStart(3, '0')}`
1466
+ layoutLog.unshift(`${time} ${what.padEnd(10)} ${lastReading} app${parseInt(app.style.height)} ${flags}`)
1467
+ layoutLog.length = Math.min(layoutLog.length, LOG_MAX)
1468
+ sessionStorage.setItem(LAYOUT_LOG, JSON.stringify(layoutLog))
1469
+ }
1470
+
1471
+ function showDiagnostics() {
1472
+ $('diag').textContent = [
1473
+ diagnosticText(),
1474
+ '',
1475
+ 'newest first. settled N: after N viewport events',
1476
+ 'poll: the readings changed with no event',
1477
+ 'F field focused, W window focused, V visible',
1478
+ 'ch root clientHeight, r screen angle, s scale',
1479
+ ...layoutLog,
1480
+ ].join('\n')
1481
+ }
1482
+
1483
+ // ---------------------------------------------------------------- menu
1484
+
1485
+ function buildMenu() {
1486
+ const presets = $('presets')
1487
+ tabsEnabled = localStorage.getItem('afield-tabs') === 'on'
1488
+ const tabsToggle = $('tabs-toggle')
1489
+ const updateTabsToggle = () => {
1490
+ tabsToggle.textContent = `Tabs: ${tabsEnabled ? 'on' : 'off'}`
1491
+ tabsToggle.setAttribute('aria-pressed', String(tabsEnabled))
1492
+ }
1493
+ updateTabsToggle()
1494
+ for (const [c, r] of PRESETS) {
1495
+ const b = document.createElement('button')
1496
+ b.textContent = `${c}×${r}`
1497
+ // Recorded so a settle still pending, the startup's if the pick comes that
1498
+ // early, sees no turn and leaves the pick alone.
1499
+ b.addEventListener('click', () => {
1500
+ fitted = { width: horizontalLayout(readViewport()).width, height: null }
1501
+ setGrid(c, r)
1502
+ })
1503
+ presets.appendChild(b)
1504
+ }
1505
+ const fit = document.createElement('button')
1506
+ fit.textContent = 'Fit'
1507
+ // Wrapped, not passed directly: a listener is handed the click event, which
1508
+ // would arrive as the layout argument and throw on l.terminal.
1509
+ fit.addEventListener('click', () => fitGrid())
1510
+ presets.appendChild(fit)
1511
+
1512
+ // The theme lives with the grid controls: it is a look choice, and sharing
1513
+ // the row keeps the sheet short enough to stay on screen over a terminal.
1514
+ const THEMES = {
1515
+ dark: { className: 'theme-dark', color: '#0b0b0d' },
1516
+ light: { className: 'theme-light', color: '#fafafa' },
1517
+ }
1518
+ for (const name of Object.keys(THEMES)) {
1519
+ const b = document.createElement('button')
1520
+ b.textContent = name[0].toUpperCase() + name.slice(1)
1521
+ b.dataset.theme = name
1522
+ presets.appendChild(b)
1523
+ }
1524
+ const named = () => document.documentElement.classList.contains(THEMES.light.className) ? 'light' : 'dark'
1525
+ const applyTheme = name => {
1526
+ const t = THEMES[name] ?? THEMES.dark
1527
+ document.documentElement.classList.toggle(THEMES.dark.className, name === 'dark')
1528
+ document.documentElement.classList.toggle(THEMES.light.className, name === 'light')
1529
+ document.querySelector('meta[name=theme-color]').setAttribute('content', t.color)
1530
+ for (const b of document.querySelectorAll('[data-theme]')) b.classList.toggle('sticky', b.dataset.theme === name)
1531
+ }
1532
+ // A saved preference wins only when it names a theme this server will serve
1533
+ // on reload; otherwise the page default (from --theme) stands. An unknown
1534
+ // stored value must not strip both classes (an html with no theme is a
1535
+ // transparent page), so it resolves to dark and is not re-saved.
1536
+ let saved = null
1537
+ try { saved = localStorage.getItem('afield-theme') } catch {}
1538
+ applyTheme(saved && THEMES[saved] ? saved : named())
1539
+
1540
+ const acts = {
1541
+ close: hideMenu,
1542
+ tabs: () => {
1543
+ tabsEnabled = !tabsEnabled
1544
+ localStorage.setItem('afield-tabs', tabsEnabled ? 'on' : 'off')
1545
+ updateTabsToggle()
1546
+ if (tabsEnabled) refreshTabs()
1547
+ else { tabs.hidden = true; updateTabArrows() }
1548
+ },
1549
+ 'zoom-in': () => setScale(state.scale * ZOOM_STEP),
1550
+ 'zoom-out': () => setScale(state.scale / ZOOM_STEP),
1551
+ 'zoom-reset': () => setScale(1),
1552
+ top: () => { stopReading(); screen.scrollTop = 0; hideMenu() },
1553
+ bottom: () => { stopReading(); screen.scrollTop = screen.scrollHeight; hideMenu() },
1554
+ // iOS offers its paste callout on a real, visible field; the terminal's own
1555
+ // input is hidden, so there is nothing there to long-press.
1556
+ 'send-paste': () => {
1557
+ const field = $('paste')
1558
+ if (!field.value) return
1559
+ conn.send(field.value)
1560
+ field.value = ''
1561
+ term.input?.resetMirror()
1562
+ hideMenu()
1563
+ },
1564
+ // A view rather than another section. The readout is dozens of lines, and
1565
+ // stacked under everything else it fills the screen — while nobody reading
1566
+ // it wants the folder list and the grid presets in the way.
1567
+ diag: () => {
1568
+ foldDiag($('diag').hidden)
1569
+ if (!$('diag').hidden) showDiagnostics()
1570
+ },
1571
+ reconnect: () => conn.reconnectNow(),
1572
+ // Local only: pi's own screen is untouched and its next repaint restores
1573
+ // it. The hold goes with the old screen — those bytes were drawn against
1574
+ // a view that no longer exists.
1575
+ 'clear-view': () => { dropHeld(); term.write(CURSOR_HOME + ERASE_SCREEN + ERASE_SAVED) },
1576
+ // Standalone has no browser chrome, so this is the only way to pick up a
1577
+ // new build by hand. Re-fetch past the cache first, or the reload just
1578
+ // reinstates the copy iOS is already holding.
1579
+ reload: () => location.replace(`${location.pathname}?b=${Date.now().toString(36)}`),
1580
+ }
1581
+ menu.addEventListener('click', e => {
1582
+ const theme = e.target.closest('[data-theme]')
1583
+ if (theme) {
1584
+ // Sticky next visit without a restart (which would kill pi). The choice
1585
+ // is per-device and per-browser; it is not the server's flag -- theme is
1586
+ // a suggestion, and this is the last word.
1587
+ applyTheme(theme.dataset.theme)
1588
+ try { localStorage.setItem('afield-theme', theme.dataset.theme) } catch {}
1589
+ return
1590
+ }
1591
+ const target = e.target.closest('[data-act]')
1592
+ if (target) acts[target.dataset.act]()
1593
+ else if (e.target === menu && !menu.classList.contains('first-visit')) hideMenu()
1594
+ })
1595
+ }
1596
+
1597
+ // ---------------------------------------------------------------- start
1598
+
1599
+ async function checkForNewBuild() {
1600
+ // Best effort: a dropped tunnel is not a client fault, and an unhandled
1601
+ // rejection here would paint the error panel over a working terminal.
1602
+ const html = await fetch(location.pathname, { cache: 'reload' }).then(r => r.text()).catch(() => '')
1603
+ const served = buildIdOf(new DOMParser().parseFromString(html, 'text/html'))
1604
+ if (!served || served === BUILD_ID) return
1605
+ // Go to a URL iOS has no cached copy of. `location.reload()` is routinely
1606
+ // served the same stale document, and the id in the query means the page that
1607
+ // arrives already matches — so this cannot loop and needs no guard.
1608
+ location.replace(`${location.pathname}?b=${served}`)
1609
+ }
1610
+
1611
+ async function main() {
1612
+ const initialVersion = selectionVersion
1613
+ state.cell = measureCell(state.fontSize)
1614
+ // Set on the element, not :root — `.wterm` declares its own defaults, which
1615
+ // would win over anything merely inherited.
1616
+ screen.style.setProperty('--term-font-size', `${state.fontSize}px`)
1617
+ screen.style.setProperty('--term-row-height', `${state.cell.height}px`)
1618
+
1619
+ document.documentElement.style.setProperty('--bar-h', `${KEY_BAR_H}px`)
1620
+ buildKeys()
1621
+ buildMenu()
1622
+ if (tabsEnabled) refreshTabs()
1623
+ setInterval(() => {
1624
+ if (!tabsEnabled || document.hidden) return
1625
+ refreshTabs()
1626
+ }, 15_000)
1627
+ $('scale-val').textContent = '100%'
1628
+ $('diag-overlay').addEventListener('click', () => { $('diag-overlay').hidden = true })
1629
+
1630
+ await term.init()
1631
+ term.input.keyChord = modChord
1632
+ terminalInput().addEventListener('blur', () => { awaitingKeyboard = false })
1633
+ // The server's snapshot carries this many lines of history; a core keeping
1634
+ // fewer would drop the oldest of them on arrival.
1635
+ term.bridge.setScrollbackLines(Number(document.querySelector('meta[name=scrollback]').content))
1636
+
1637
+ screen.addEventListener('scroll', onScroll)
1638
+ toBottom.addEventListener('click', () => { stopReading(); screen.scrollTop = screen.scrollHeight })
1639
+ tabsLeft.addEventListener('click', () => tabs.scrollBy({ left: -tabs.clientWidth * 0.8, behavior: 'smooth' }))
1640
+ tabsRight.addEventListener('click', () => tabs.scrollBy({ left: tabs.clientWidth * 0.8, behavior: 'smooth' }))
1641
+ tabs.addEventListener('scroll', updateTabArrows)
1642
+ new ResizeObserver(updateTabArrows).observe(tabs)
1643
+
1644
+ record('load')
1645
+ fitGrid(applyLayout())
1646
+ // env() insets are not resolved on the first pass, so the first fit is short
1647
+ // by the bottom inset and leaves rows permanently below the fold. Refit once
1648
+ // the real values are in.
1649
+ requestAnimationFrame(() => fitGrid(applyLayout()))
1650
+ // A launch in landscape starts the page in portrait and turns it during the
1651
+ // await below. Listening from here on is what refits the grid for that.
1652
+ visualViewport.addEventListener('resize', onViewportChange)
1653
+ visualViewport.addEventListener('scroll', onViewportChange)
1654
+ window.addEventListener('orientationchange', onViewportChange)
1655
+ // Chrome on Android is still moving the viewport after a reload, past both
1656
+ // fits above: for a few frames it stops the page short of the gesture bar
1657
+ // while already reporting the bar's inset. So a settle follows here too, and
1658
+ // refits if the viewport comes to rest anywhere else.
1659
+ onViewportChange()
1660
+ document.addEventListener('visibilitychange', onVisibilityChange)
1661
+ for (const type of ['focus', 'blur', 'pageshow', 'pagehide']) window.addEventListener(type, () => record(`w.${type}`))
1662
+ for (const type of ['focus', 'blur']) terminalInput().addEventListener(type, () => record(type))
1663
+ // iOS moves the viewport with no event while the page is hidden.
1664
+ setInterval(() => {
1665
+ if (settle === null && viewportReading() !== lastReading) record('poll')
1666
+ }, 1000)
1667
+
1668
+ const place = await resolveInitialPlace()
1669
+ // Unless the viewer already chose something while this was loading.
1670
+ if (selectionVersion === initialVersion) {
1671
+ if (place) {
1672
+ dialPlace(place)
1673
+ } else {
1674
+ // Also when the viewer opened the menu while this was loading.
1675
+ menu.classList.add('first-visit')
1676
+ if (menu.hidden) openMenu()
1677
+ }
1678
+ }
1679
+
1680
+ checkForNewBuild()
1681
+ }
1682
+
1683
+ main().catch(e => reportFatal(`startup: ${e?.message ?? e}`))