@glassly/miniapp 0.4.3-beta.1240 → 0.4.3-beta.1278

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 (139) hide show
  1. package/README.md +41 -3
  2. package/dist/display/profiles/types.d.ts.map +1 -1
  3. package/dist/display/scene/types.d.ts.map +1 -1
  4. package/dist/display/scene/types.js.map +1 -1
  5. package/dist/host/index.d.ts +1 -0
  6. package/dist/host/index.d.ts.map +1 -1
  7. package/dist/host/index.js +1 -0
  8. package/dist/host/index.js.map +1 -1
  9. package/dist/host/settingsBridge.d.ts +31 -8
  10. package/dist/host/settingsBridge.d.ts.map +1 -1
  11. package/dist/host/settingsBridge.js +63 -11
  12. package/dist/host/settingsBridge.js.map +1 -1
  13. package/dist/host/ttsSanitizer.d.ts +5 -0
  14. package/dist/host/ttsSanitizer.d.ts.map +1 -0
  15. package/dist/host/ttsSanitizer.js +61 -0
  16. package/dist/host/ttsSanitizer.js.map +1 -0
  17. package/dist/modules/cloud.d.ts +2 -0
  18. package/dist/modules/cloud.d.ts.map +1 -1
  19. package/dist/modules/cloud.js +17 -7
  20. package/dist/modules/cloud.js.map +1 -1
  21. package/dist/modules/settings.d.ts +4 -1
  22. package/dist/modules/settings.d.ts.map +1 -1
  23. package/dist/modules/settings.js +4 -1
  24. package/dist/modules/settings.js.map +1 -1
  25. package/dist/reader/Reader.d.ts +147 -0
  26. package/dist/reader/Reader.d.ts.map +1 -0
  27. package/dist/reader/Reader.js +525 -0
  28. package/dist/reader/Reader.js.map +1 -0
  29. package/dist/reader/document.d.ts +54 -0
  30. package/dist/reader/document.d.ts.map +1 -0
  31. package/dist/reader/document.js +114 -0
  32. package/dist/reader/document.js.map +1 -0
  33. package/dist/reader/index.d.ts +12 -0
  34. package/dist/reader/index.d.ts.map +1 -0
  35. package/dist/reader/index.js +9 -0
  36. package/dist/reader/index.js.map +1 -0
  37. package/dist/reader/lens.d.ts +55 -0
  38. package/dist/reader/lens.d.ts.map +1 -0
  39. package/dist/reader/lens.js +210 -0
  40. package/dist/reader/lens.js.map +1 -0
  41. package/dist/sub-path-types.test-d.d.ts +3 -1
  42. package/dist/sub-path-types.test-d.d.ts.map +1 -1
  43. package/dist/sub-path-types.test-d.js +1 -7
  44. package/dist/sub-path-types.test-d.js.map +1 -1
  45. package/dist/theme.css +856 -0
  46. package/dist/ui/index.d.ts +1 -0
  47. package/dist/ui/index.d.ts.map +1 -1
  48. package/dist/ui/index.js +1 -0
  49. package/dist/ui/index.js.map +1 -1
  50. package/dist/ui/kit/Badge.d.ts +8 -0
  51. package/dist/ui/kit/Badge.d.ts.map +1 -0
  52. package/dist/ui/kit/Badge.js +6 -0
  53. package/dist/ui/kit/Badge.js.map +1 -0
  54. package/dist/ui/kit/Button.d.ts +9 -0
  55. package/dist/ui/kit/Button.d.ts.map +1 -0
  56. package/dist/ui/kit/Button.js +7 -0
  57. package/dist/ui/kit/Button.js.map +1 -0
  58. package/dist/ui/kit/Card.d.ts +10 -0
  59. package/dist/ui/kit/Card.d.ts.map +1 -0
  60. package/dist/ui/kit/Card.js +21 -0
  61. package/dist/ui/kit/Card.js.map +1 -0
  62. package/dist/ui/kit/Dock.d.ts +29 -0
  63. package/dist/ui/kit/Dock.d.ts.map +1 -0
  64. package/dist/ui/kit/Dock.js +34 -0
  65. package/dist/ui/kit/Dock.js.map +1 -0
  66. package/dist/ui/kit/Feedback.d.ts +37 -0
  67. package/dist/ui/kit/Feedback.d.ts.map +1 -0
  68. package/dist/ui/kit/Feedback.js +21 -0
  69. package/dist/ui/kit/Feedback.js.map +1 -0
  70. package/dist/ui/kit/Field.d.ts +8 -0
  71. package/dist/ui/kit/Field.d.ts.map +1 -0
  72. package/dist/ui/kit/Field.js +16 -0
  73. package/dist/ui/kit/Field.js.map +1 -0
  74. package/dist/ui/kit/Page.d.ts +33 -0
  75. package/dist/ui/kit/Page.d.ts.map +1 -0
  76. package/dist/ui/kit/Page.js +77 -0
  77. package/dist/ui/kit/Page.js.map +1 -0
  78. package/dist/ui/kit/Section.d.ts +17 -0
  79. package/dist/ui/kit/Section.d.ts.map +1 -0
  80. package/dist/ui/kit/Section.js +22 -0
  81. package/dist/ui/kit/Section.js.map +1 -0
  82. package/dist/ui/kit/SetupGuide.d.ts +45 -0
  83. package/dist/ui/kit/SetupGuide.d.ts.map +1 -0
  84. package/dist/ui/kit/SetupGuide.js +40 -0
  85. package/dist/ui/kit/SetupGuide.js.map +1 -0
  86. package/dist/ui/kit/Switch.d.ts +7 -0
  87. package/dist/ui/kit/Switch.d.ts.map +1 -0
  88. package/dist/ui/kit/Switch.js +11 -0
  89. package/dist/ui/kit/Switch.js.map +1 -0
  90. package/dist/ui/kit/Tabs.d.ts +20 -0
  91. package/dist/ui/kit/Tabs.d.ts.map +1 -0
  92. package/dist/ui/kit/Tabs.js +53 -0
  93. package/dist/ui/kit/Tabs.js.map +1 -0
  94. package/dist/ui/kit/cx.d.ts +2 -0
  95. package/dist/ui/kit/cx.d.ts.map +1 -0
  96. package/dist/ui/kit/cx.js +4 -0
  97. package/dist/ui/kit/cx.js.map +1 -0
  98. package/dist/ui/kit/hooks.d.ts +17 -0
  99. package/dist/ui/kit/hooks.d.ts.map +1 -0
  100. package/dist/ui/kit/hooks.js +34 -0
  101. package/dist/ui/kit/hooks.js.map +1 -0
  102. package/dist/ui/kit/index.d.ts +14 -0
  103. package/dist/ui/kit/index.d.ts.map +1 -0
  104. package/dist/ui/kit/index.js +14 -0
  105. package/dist/ui/kit/index.js.map +1 -0
  106. package/dist/ui/kit/useWide.d.ts +4 -0
  107. package/dist/ui/kit/useWide.d.ts.map +1 -0
  108. package/dist/ui/kit/useWide.js +18 -0
  109. package/dist/ui/kit/useWide.js.map +1 -0
  110. package/package.json +16 -5
  111. package/src/display/profiles/types.ts +9 -1
  112. package/src/display/scene/types.ts +6 -1
  113. package/src/host/index.ts +1 -0
  114. package/src/host/settingsBridge.ts +72 -12
  115. package/src/host/ttsSanitizer.ts +66 -0
  116. package/src/modules/cloud.ts +21 -7
  117. package/src/modules/settings.ts +4 -1
  118. package/src/reader/Reader.ts +580 -0
  119. package/src/reader/document.ts +154 -0
  120. package/src/reader/index.ts +12 -0
  121. package/src/reader/lens.ts +250 -0
  122. package/src/sub-path-types.test-d.ts +5 -0
  123. package/src/ui/index.ts +2 -0
  124. package/src/ui/kit/Badge.tsx +19 -0
  125. package/src/ui/kit/Button.tsx +27 -0
  126. package/src/ui/kit/Card.tsx +29 -0
  127. package/src/ui/kit/Dock.tsx +77 -0
  128. package/src/ui/kit/Feedback.tsx +101 -0
  129. package/src/ui/kit/Field.tsx +38 -0
  130. package/src/ui/kit/Page.tsx +154 -0
  131. package/src/ui/kit/Section.tsx +80 -0
  132. package/src/ui/kit/SetupGuide.tsx +153 -0
  133. package/src/ui/kit/Switch.tsx +28 -0
  134. package/src/ui/kit/Tabs.tsx +108 -0
  135. package/src/ui/kit/cx.ts +3 -0
  136. package/src/ui/kit/hooks.ts +53 -0
  137. package/src/ui/kit/index.ts +51 -0
  138. package/src/ui/kit/useWide.ts +19 -0
  139. package/src/ui/theme.css +856 -0
@@ -15,6 +15,7 @@ export type CloudClientConnectionStatus = "connected" | "connecting" | "reconnec
15
15
  export type CloudClientAudioTransport = "udp" | "ws" | "offline" | "none"
16
16
  /** Metered cloud features the account's plan can run out of. */
17
17
  export type CloudQuotaFeature = "transcription"
18
+ export type CloudSpeechFeature = "transcription" | "translation"
18
19
 
19
20
  export interface CloudClientStatus {
20
21
  status: CloudClientConnectionStatus
@@ -25,6 +26,7 @@ export interface CloudClientStatus {
25
26
  * declined. Empty on hosts that predate the field.
26
27
  */
27
28
  quotaBlocked: CloudQuotaFeature[]
29
+ speechFailed: CloudSpeechFeature[]
28
30
  }
29
31
 
30
32
  type CloudEmitterEvents = {
@@ -37,9 +39,19 @@ const DEFAULT_STATUS: CloudClientStatus = {
37
39
  status: "disconnected",
38
40
  audioTransport: "none",
39
41
  quotaBlocked: [],
42
+ speechFailed: [],
40
43
  }
41
44
 
42
45
  const QUOTA_FEATURES: readonly CloudQuotaFeature[] = ["transcription"]
46
+ const SPEECH_FEATURES: readonly CloudSpeechFeature[] = ["transcription", "translation"]
47
+
48
+ function knownFeatures<T extends string>(raw: unknown, known: readonly T[]): T[] {
49
+ return Array.isArray(raw) ? raw.filter((f): f is T => known.includes(f as T)) : []
50
+ }
51
+
52
+ function sameList(a: readonly string[], b: readonly string[]): boolean {
53
+ return a.length === b.length && a.every((f, i) => f === b[i])
54
+ }
43
55
 
44
56
  function normalizeCloudStatus(data: unknown): CloudClientStatus | null {
45
57
  if (!data || typeof data !== "object") return null
@@ -59,18 +71,20 @@ function normalizeCloudStatus(data: unknown): CloudClientStatus | null {
59
71
  return null
60
72
  }
61
73
 
62
- const quotaBlocked = Array.isArray(raw.quotaBlocked)
63
- ? raw.quotaBlocked.filter((f): f is CloudQuotaFeature => QUOTA_FEATURES.includes(f as CloudQuotaFeature))
64
- : []
65
- return {status, audioTransport, quotaBlocked}
74
+ return {
75
+ status,
76
+ audioTransport,
77
+ quotaBlocked: knownFeatures(raw.quotaBlocked, QUOTA_FEATURES),
78
+ speechFailed: knownFeatures(raw.speechFailed, SPEECH_FEATURES),
79
+ }
66
80
  }
67
81
 
68
82
  function sameStatus(a: CloudClientStatus, b: CloudClientStatus): boolean {
69
83
  return (
70
84
  a.status === b.status &&
71
85
  a.audioTransport === b.audioTransport &&
72
- a.quotaBlocked.length === b.quotaBlocked.length &&
73
- a.quotaBlocked.every((f, i) => f === b.quotaBlocked[i])
86
+ sameList(a.quotaBlocked, b.quotaBlocked) &&
87
+ sameList(a.speechFailed, b.speechFailed)
74
88
  )
75
89
  }
76
90
 
@@ -90,7 +104,7 @@ export class CloudModule {
90
104
 
91
105
  /** Latest status snapshot pushed by the phone runtime. */
92
106
  get status(): CloudClientStatus {
93
- return {...this.current, quotaBlocked: [...this.current.quotaBlocked]}
107
+ return {...this.current, quotaBlocked: [...this.current.quotaBlocked], speechFailed: [...this.current.speechFailed]}
94
108
  }
95
109
 
96
110
  /** Whether the plan quota is refusing `feature` right now. */
@@ -1,7 +1,10 @@
1
1
  /**
2
2
  * @fileoverview SettingsModule — `session.settings`, the engine's settings
3
3
  * store behind an allowlist. Needs the PLATFORM_SETTINGS manifest
4
- * permission: without it every call rejects with PERMISSION_NOT_DECLARED.
4
+ * permission, except for the wearer's reading settings (`reading_wpm` and
5
+ * the other `reading_*` keys), which every miniapp may read and follow, and
6
+ * whose speed it may set. Without it, other keys reject with
7
+ * PERMISSION_NOT_DECLARED.
5
8
  * A dashboard miniapp is the usual consumer: it reads and edits the
6
9
  * notification and glasses-menu keys the phone's settings screens used to,
7
10
  * so firmware sync and the host's notification policy keep one source of
@@ -0,0 +1,580 @@
1
+ /**
2
+ * The Reader: a miniapp hands it a title, sections of text and its end-screen
3
+ * actions, and the glasses read the text to the wearer line by line at their
4
+ * reading speed. Built only on session.display, session.input and
5
+ * session.settings, so it runs on any Glassly App; one that predates the
6
+ * reading settings reads at 220 wpm and keeps a glasses speed change for the
7
+ * rest of the session.
8
+ *
9
+ * Gestures (map A, as Teleprompter): tap pauses and resumes, and at an end
10
+ * screen runs its tap action; swipe down / up step a line while reading and
11
+ * change the speed by 20 wpm while paused (dial and scroll steps count as
12
+ * swipes); hold runs the app's hold action; double tap, or a Neural Band's
13
+ * swipe left, leaves the Reader.
14
+ */
15
+
16
+ import {TextMeasurer} from "../display/measurer"
17
+ import {textProfileFor, type DisplayProfile} from "../display/profiles"
18
+ import {TextWrapper} from "../display/wrapper"
19
+ import type {RenderElement} from "../modules/display"
20
+ import {ReaderDocument, type ReaderSection} from "./document"
21
+ import {lensElements, lensLayout, textWrapWidth, type LensFrame, type LensHighlight, type LensLayout} from "./lens"
22
+
23
+ export interface ReaderOptions {
24
+ title: string
25
+ details?: string
26
+ sections: ReaderSection[]
27
+ hold?: {action: string; label: string}
28
+ leaveLabel?: string
29
+ start?: {part?: number; percent?: number}
30
+ }
31
+
32
+ export type ReaderEvent =
33
+ | {type: "action"; action: string}
34
+ | {type: "progress"; part: number; section: number; percent: number}
35
+ | {type: "closed"; reason: "double_tap" | "swipe_left" | "app"}
36
+
37
+ export interface ReaderDeps {
38
+ later: (fn: () => void, ms: number) => () => void
39
+ now: () => number
40
+ }
41
+
42
+ export interface ReaderSession {
43
+ packageName: string
44
+ capabilities: {modelName?: unknown; display?: object | null} | null
45
+ display: {render: (elements: RenderElement[]) => Promise<unknown>}
46
+ input: {
47
+ onTouch: (handler: (data: {kind: string}) => void) => () => void
48
+ setClaimedGestures: (gestures: string[], options?: {scope?: string}) => Promise<void>
49
+ }
50
+ settings: {
51
+ getAll: (keys?: string[]) => Promise<Record<string, unknown>>
52
+ set: (key: string, value: unknown) => Promise<void>
53
+ onChange: (handler: (change: {key: string; value: unknown}) => void) => () => void
54
+ }
55
+ onCapabilitiesChange?: (handler: (capabilities: unknown) => void) => () => void
56
+ onPause?: (handler: (reason: unknown) => void) => () => void
57
+ paused?: boolean
58
+ ready?: boolean
59
+ on?: (event: "ready", handler: () => void) => () => void
60
+ }
61
+
62
+ export const READER_WPM = {min: 100, max: 400, step: 20, default: 220} as const
63
+ const TITLE_CARD_MS = 2000
64
+ const TOAST_MS = 2000
65
+ const SCOPE = "reader"
66
+ const READING_KEYS = [
67
+ "reading_wpm",
68
+ "reading_auto_start",
69
+ "reading_pause_paragraphs",
70
+ "reading_glasses_speed",
71
+ "reading_highlight",
72
+ "reading_app_speed",
73
+ ]
74
+
75
+ type Phase = "title" | "reading" | "paused" | "stop"
76
+
77
+ interface Preferences {
78
+ wpm: number
79
+ autoStart: boolean
80
+ beats: boolean
81
+ keep: boolean
82
+ highlight: LensHighlight
83
+ appSpeed: number | "off" | null
84
+ }
85
+
86
+ const DEFAULTS: Preferences = {
87
+ wpm: READER_WPM.default,
88
+ autoStart: true,
89
+ beats: true,
90
+ keep: true,
91
+ highlight: "filled",
92
+ appSpeed: null,
93
+ }
94
+
95
+ const sessionWpm = new WeakMap<object, number>()
96
+
97
+ const defaultDeps = (): ReaderDeps => ({
98
+ later: (fn, ms) => {
99
+ const timer = setTimeout(fn, ms)
100
+ return () => clearTimeout(timer)
101
+ },
102
+ now: Date.now,
103
+ })
104
+
105
+ const clampWpm = (wpm: number) => Math.max(READER_WPM.min, Math.min(READER_WPM.max, wpm))
106
+ const isWpm = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value) && value > 0
107
+
108
+ function clock(ms: number): string {
109
+ const seconds = Math.max(0, Math.round(ms / 1000))
110
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`
111
+ }
112
+
113
+ export function openReader(session: ReaderSession, options: ReaderOptions, deps: Partial<ReaderDeps> = {}): Reader {
114
+ const reader = new Reader(session, options, {...defaultDeps(), ...deps})
115
+ reader.open()
116
+ return reader
117
+ }
118
+
119
+ export class Reader {
120
+ private options: ReaderOptions
121
+ private prefs: Preferences = {...DEFAULTS}
122
+ private bridged = false
123
+ private readWpm: number | null = null
124
+ private profile: DisplayProfile = textProfileFor(null)
125
+ private measurer = new TextMeasurer(this.profile)
126
+ private wrapper = new TextWrapper(this.measurer)
127
+ private layout!: LensLayout
128
+ private doc!: ReaderDocument
129
+ private wrapWidth = 0
130
+ private docProfile: DisplayProfile | null = null
131
+ private phase: Phase = "title"
132
+ private line = 0
133
+ private part = 0
134
+ private toastText: string | null = null
135
+ private readOnWhenReady = false
136
+ private readMs = 0
137
+ private readingSince: number | null = null
138
+ private lastFrame = ""
139
+ private isOpenNow = false
140
+ private handlers = new Set<(event: ReaderEvent) => void>()
141
+ private cancelClock: (() => void) | null = null
142
+ private cancelToast: (() => void) | null = null
143
+ private unsubs: (() => void)[] = []
144
+
145
+ constructor(
146
+ private readonly session: ReaderSession,
147
+ options: ReaderOptions,
148
+ private readonly deps: ReaderDeps,
149
+ ) {
150
+ this.options = options
151
+ }
152
+
153
+ get isOpen(): boolean {
154
+ return this.isOpenNow
155
+ }
156
+
157
+ get wpm(): number {
158
+ return this.speed()
159
+ }
160
+
161
+ onEvent(handler: (event: ReaderEvent) => void): () => void {
162
+ this.handlers.add(handler)
163
+ return () => this.handlers.delete(handler)
164
+ }
165
+
166
+ open(): void {
167
+ if (this.isOpenNow) return
168
+ this.isOpenNow = true
169
+ const legacy = sessionWpm.get(this.session)
170
+ if (legacy) this.prefs.wpm = legacy
171
+ this.relayout()
172
+ const start = this.options.start
173
+ if (start) {
174
+ this.part = Math.max(0, Math.min(this.doc.parts.length - 1, start.part ?? 0))
175
+ this.line = this.doc.lineAt(this.part, start.percent ?? 0)
176
+ this.phase = "paused"
177
+ } else {
178
+ this.line = this.firstLine(0)
179
+ }
180
+ this.unsubs.push(this.session.input.onTouch((data) => this.gesture(data.kind)))
181
+ if (this.session.onPause) {
182
+ this.unsubs.push(this.session.onPause(() => this.pauseForAway()))
183
+ }
184
+ if (this.session.onCapabilitiesChange) {
185
+ this.unsubs.push(this.session.onCapabilitiesChange(() => this.relayout(true)))
186
+ }
187
+ if (this.session.ready === false && this.session.on) {
188
+ const off = this.session.on("ready", () => {
189
+ off()
190
+ this.relayout(true)
191
+ void this.loadPreferences()
192
+ if (this.session.paused) this.pauseForAway()
193
+ })
194
+ this.unsubs.push(off)
195
+ }
196
+ void this.session.input.setClaimedGestures(["double_tap"], {scope: SCOPE}).catch(() => {})
197
+ this.render()
198
+ if (this.session.ready !== false || !this.session.on) void this.loadPreferences()
199
+ if (this.phase === "title") this.cancelClock = this.deps.later(() => this.autoStart(), TITLE_CARD_MS)
200
+ if (this.session.paused) this.pauseForAway()
201
+ }
202
+
203
+ close(): void {
204
+ this.finish("app")
205
+ }
206
+
207
+ /** Change the text or the hold action while open, keeping the place: e.g. comments arriving after the post. */
208
+ update(next: Partial<Omit<ReaderOptions, "start">>): void {
209
+ this.options = {...this.options, ...next}
210
+ if (!this.isOpenNow) return
211
+ this.relayout(true)
212
+ if (this.readOnWhenReady && this.phase === "stop" && this.continueReading()) this.readOnWhenReady = false
213
+ }
214
+
215
+ /** Show a brief message for 2 s, e.g. "★ Saved\nopens in Reddit on your phone". */
216
+ toast(text: string, ms = TOAST_MS): void {
217
+ if (!this.isOpenNow) return
218
+ this.cancelToast?.()
219
+ this.toastText = text
220
+ this.render()
221
+ this.cancelToast = this.deps.later(() => {
222
+ this.cancelToast = null
223
+ this.toastText = null
224
+ this.render()
225
+ }, ms)
226
+ }
227
+
228
+ // ---------------------------------------------------------------------------
229
+
230
+ private emit(event: ReaderEvent): void {
231
+ for (const handler of [...this.handlers]) handler(event)
232
+ }
233
+
234
+ private manual(): boolean {
235
+ return this.prefs.appSpeed === "off"
236
+ }
237
+
238
+ private speed(): number {
239
+ if (this.readWpm) return this.readWpm
240
+ if (isWpm(this.prefs.appSpeed)) return clampWpm(this.prefs.appSpeed)
241
+ return clampWpm(this.prefs.wpm)
242
+ }
243
+
244
+ private async loadPreferences(): Promise<void> {
245
+ let values: Record<string, unknown>
246
+ try {
247
+ values = await this.session.settings.getAll(READING_KEYS)
248
+ } catch {
249
+ return
250
+ }
251
+ if (!this.isOpenNow) return
252
+ this.bridged = true
253
+ this.apply(values)
254
+ this.unsubs.push(this.session.settings.onChange(({key, value}) => this.apply({[key]: value})))
255
+ }
256
+
257
+ private apply(values: Record<string, unknown>): void {
258
+ const prefs = {...this.prefs}
259
+ if ("reading_wpm" in values && isWpm(values.reading_wpm)) prefs.wpm = values.reading_wpm
260
+ if (typeof values.reading_auto_start === "boolean") prefs.autoStart = values.reading_auto_start
261
+ if (typeof values.reading_pause_paragraphs === "boolean") prefs.beats = values.reading_pause_paragraphs
262
+ if (values.reading_glasses_speed === "keep" || values.reading_glasses_speed === "this_read") {
263
+ prefs.keep = values.reading_glasses_speed === "keep"
264
+ }
265
+ const highlight = values.reading_highlight
266
+ if (highlight === "filled" || highlight === "brackets" || highlight === "dim") prefs.highlight = highlight
267
+ if ("reading_app_speed" in values) {
268
+ const own = values.reading_app_speed
269
+ prefs.appSpeed = own === "off" ? "off" : isWpm(own) ? own : null
270
+ }
271
+ const rewrap = prefs.highlight !== this.prefs.highlight
272
+ const wasManual = this.manual()
273
+ this.prefs = prefs
274
+ if (rewrap) this.relayout(true)
275
+ if (this.phase === "title" && !prefs.autoStart) {
276
+ this.cancelClock?.()
277
+ this.cancelClock = null
278
+ }
279
+ if (wasManual !== this.manual() && this.phase === "reading") this.schedule()
280
+ this.render()
281
+ }
282
+
283
+ private relayout(keepPlace = false): void {
284
+ const capabilities = this.session.capabilities
285
+ const profile = textProfileFor(capabilities as Parameters<typeof textProfileFor>[0])
286
+ if (profile.id !== this.profile.id) {
287
+ this.profile = profile
288
+ this.measurer = new TextMeasurer(profile)
289
+ this.wrapper = new TextWrapper(this.measurer)
290
+ }
291
+ this.layout = lensLayout(profile, (capabilities?.display ?? null) as Parameters<typeof lensLayout>[1])
292
+ const wrapWidth = textWrapWidth(this.layout, this.prefs.highlight, this.measurer)
293
+ const sameText = !!this.doc && this.doc.sections === this.options.sections
294
+ if (keepPlace && sameText && wrapWidth === this.wrapWidth && profile === this.docProfile) return this.render()
295
+ const before =
296
+ keepPlace && this.doc ? {part: this.part, words: this.doc.wordsBefore(this.line), line: this.line} : null
297
+ this.doc = new ReaderDocument(this.options.sections, this.wrapper, wrapWidth)
298
+ this.wrapWidth = wrapWidth
299
+ this.docProfile = profile
300
+ if (before) {
301
+ this.part = Math.min(before.part, this.doc.parts.length - 1)
302
+ this.line = sameText
303
+ ? this.doc.lineAtWord(this.part, before.words)
304
+ : Math.min(before.line, this.doc.lines.length - 1)
305
+ this.render()
306
+ }
307
+ }
308
+
309
+ private firstLine(part: number): number {
310
+ const p = this.doc.parts[part]
311
+ return this.doc.nextReadable(p.first - 1, p.last) ?? p.first
312
+ }
313
+
314
+ // ---------------------------------------------------------------------------
315
+ // Reading
316
+
317
+ private autoStart(): void {
318
+ this.cancelClock = null
319
+ if (this.phase === "title" && this.prefs.autoStart && !this.manual()) this.startReading()
320
+ }
321
+
322
+ private startReading(): void {
323
+ this.phase = "reading"
324
+ this.markReading(true)
325
+ this.render()
326
+ this.progress()
327
+ this.schedule()
328
+ }
329
+
330
+ private markReading(on: boolean): void {
331
+ const now = this.deps.now()
332
+ if (this.readingSince !== null) this.readMs += now - this.readingSince
333
+ this.readingSince = on ? now : null
334
+ }
335
+
336
+ private schedule(): void {
337
+ this.cancelClock?.()
338
+ this.cancelClock = null
339
+ if (this.phase !== "reading" || this.manual()) return
340
+ this.cancelClock = this.deps.later(() => this.advance(), this.doc.lineMs(this.line, this.speed(), this.prefs.beats))
341
+ }
342
+
343
+ private advance(): void {
344
+ this.cancelClock = null
345
+ const last = this.doc.parts[this.part].last
346
+ const next = this.doc.nextReadable(this.line, last)
347
+ if (next === null) return this.enterStop()
348
+ this.line = next
349
+ this.render()
350
+ this.progress()
351
+ this.schedule()
352
+ }
353
+
354
+ private step(delta: 1 | -1): void {
355
+ const part = this.doc.parts[this.part]
356
+ const rows = this.manual() ? Math.max(1, this.layout.rows - 1) : 1
357
+ let line = this.line
358
+ for (let i = 0; i < rows; i++) {
359
+ const next = delta > 0 ? this.doc.nextReadable(line, part.last) : this.doc.previousReadable(line, part.first)
360
+ if (next === null) {
361
+ if (delta > 0 && i === 0) return this.enterStop()
362
+ break
363
+ }
364
+ line = next
365
+ }
366
+ if (line === this.line) return
367
+ this.line = line
368
+ this.render()
369
+ this.progress()
370
+ this.schedule()
371
+ }
372
+
373
+ private enterStop(): void {
374
+ this.cancelClock?.()
375
+ this.cancelClock = null
376
+ this.markReading(false)
377
+ this.phase = "stop"
378
+ this.render()
379
+ this.emit({
380
+ type: "progress",
381
+ part: this.part,
382
+ section: this.doc.parts[this.part].stopSection,
383
+ percent: 100,
384
+ })
385
+ }
386
+
387
+ /** Read on into the next part, from its first line. */
388
+ private continueReading(): boolean {
389
+ if (this.part >= this.doc.parts.length - 1) return false
390
+ this.part += 1
391
+ this.line = this.firstLine(this.part)
392
+ this.startReading()
393
+ return true
394
+ }
395
+
396
+ private progress(): void {
397
+ this.emit({
398
+ type: "progress",
399
+ part: this.part,
400
+ section: this.doc.lines[this.line]?.section ?? 0,
401
+ percent: this.doc.percent(this.line),
402
+ })
403
+ }
404
+
405
+ private pauseForAway(): void {
406
+ if (this.phase === "title") {
407
+ this.cancelClock?.()
408
+ this.cancelClock = null
409
+ }
410
+ if (this.phase !== "reading" || this.manual()) return
411
+ this.phase = "paused"
412
+ this.markReading(false)
413
+ this.schedule()
414
+ this.render()
415
+ }
416
+
417
+ private changeSpeed(delta: 1 | -1): void {
418
+ const next = clampWpm(this.speed() + delta * READER_WPM.step)
419
+ if (next === this.speed()) return
420
+ const ownSpeed = isWpm(this.prefs.appSpeed)
421
+ if (ownSpeed || !this.prefs.keep) {
422
+ this.readWpm = next
423
+ this.toast(`${next} wpm\nfor this read`)
424
+ return
425
+ }
426
+ this.prefs.wpm = next
427
+ if (!this.bridged) {
428
+ sessionWpm.set(this.session, next)
429
+ this.toast(`${next} wpm`)
430
+ return
431
+ }
432
+ this.toast(`${next} wpm\nsaved for every app`)
433
+ void this.session.settings.set("reading_wpm", next).catch(() => sessionWpm.set(this.session, next))
434
+ }
435
+
436
+ // ---------------------------------------------------------------------------
437
+ // Gestures
438
+
439
+ private gesture(kind: string): void {
440
+ if (!this.isOpenNow) return
441
+ const down = kind === "swipe_down" || kind === "dial_down" || kind === "scroll_down"
442
+ const up = kind === "swipe_up" || kind === "dial_up" || kind === "scroll_up"
443
+ if (kind === "double_tap") return this.finish("double_tap")
444
+ if (kind === "swipe_left") return this.finish("swipe_left")
445
+ if (kind === "long_press" || kind === "tap_then_hold") {
446
+ if (this.options.hold) this.emit({type: "action", action: this.options.hold.action})
447
+ return
448
+ }
449
+ if (kind !== "single_tap" && !down && !up) return
450
+ switch (this.phase) {
451
+ case "title":
452
+ this.cancelClock?.()
453
+ this.cancelClock = null
454
+ this.startReading()
455
+ if (down) this.step(1)
456
+ return
457
+ case "reading":
458
+ if (kind === "single_tap") {
459
+ if (this.manual()) return
460
+ this.phase = "paused"
461
+ this.markReading(false)
462
+ this.schedule()
463
+ this.render()
464
+ return
465
+ }
466
+ this.step(down ? 1 : -1)
467
+ return
468
+ case "paused":
469
+ if (kind === "single_tap") return this.startReading()
470
+ this.changeSpeed(down ? 1 : -1)
471
+ return
472
+ case "stop": {
473
+ if (up) {
474
+ this.readOnWhenReady = false
475
+ this.phase = this.manual() ? "reading" : "paused"
476
+ this.render()
477
+ return
478
+ }
479
+ const tap = this.options.sections[this.doc.parts[this.part].stopSection]?.stop?.tap
480
+ if (kind === "single_tap" && tap?.action) return this.emit({type: "action", action: tap.action})
481
+ if (!this.continueReading() && kind === "single_tap") this.readOnWhenReady = true
482
+ }
483
+ }
484
+ }
485
+
486
+ private finish(reason: "double_tap" | "swipe_left" | "app"): void {
487
+ if (!this.isOpenNow) return
488
+ this.isOpenNow = false
489
+ this.cancelClock?.()
490
+ this.cancelToast?.()
491
+ this.cancelClock = this.cancelToast = null
492
+ for (const unsub of this.unsubs) unsub()
493
+ this.unsubs = []
494
+ void this.session.input.setClaimedGestures([], {scope: SCOPE}).catch(() => {})
495
+ this.emit({type: "closed", reason})
496
+ }
497
+
498
+ // ---------------------------------------------------------------------------
499
+ // Drawing
500
+
501
+ private statusTitle(): string {
502
+ const section = this.options.sections[this.doc.lines[this.line]?.section ?? 0]
503
+ return section?.status ?? this.options.title
504
+ }
505
+
506
+ private frame(): LensFrame {
507
+ const {rows, marked} = this.layout
508
+ const base = {highlight: this.prefs.highlight, toast: this.toastText}
509
+ const wpm = this.speed()
510
+ switch (this.phase) {
511
+ case "title": {
512
+ const wrap = (text: string, max: number) =>
513
+ this.wrapper.wrap(text, {
514
+ maxWidthPx: this.layout.wrapWidthPx,
515
+ maxLines: max,
516
+ maxBytes: Infinity,
517
+ breakMode: "word",
518
+ }).lines
519
+ const head = [
520
+ ...wrap(this.options.title, rows >= 7 ? 3 : 2),
521
+ ...(this.options.details ? wrap(this.options.details, 2) : []),
522
+ ]
523
+ const auto = this.prefs.autoStart && !this.manual()
524
+ const hint = [
525
+ auto ? "Reader starts in 2 s" : this.manual() ? "Swipe to read by hand" : "Tap to start reading",
526
+ auto ? "tap to start now · swipe to read by hand" : "",
527
+ ].filter(Boolean)
528
+ const lines = [...head.slice(0, Math.max(1, rows - hint.length - 1)), "", ...hint].slice(0, rows)
529
+ const minutes = Math.max(1, Math.round(this.doc.wordsLeft(this.firstLine(this.part)) / wpm))
530
+ const detail = this.manual() ? "swipe to read" : `about ${minutes} min at ${wpm} wpm`
531
+ return {...base, rows: lines, marked: null, status: this.options.title, detail}
532
+ }
533
+ case "stop": {
534
+ const part = this.doc.parts[this.part]
535
+ const stop = this.options.sections[part.stopSection]?.stop
536
+ const last = this.part === this.doc.parts.length - 1
537
+ const actions = [
538
+ stop?.title ?? (last ? "End" : "Paused here"),
539
+ ...(stop?.tap ? [`tap ${stop.tap.label}`] : !last ? ["tap read on"] : []),
540
+ ...(this.options.hold ? [`hold ${this.options.hold.label}`] : []),
541
+ `double tap ${this.options.leaveLabel ?? "back"}`,
542
+ ].slice(0, rows)
543
+ const room = Math.max(0, rows - actions.length - 1)
544
+ const tail: string[] = []
545
+ for (let i = part.last; i >= part.first && tail.length < room; i--) {
546
+ if (this.doc.lines[i].kind !== "blank") tail.unshift(this.doc.lines[i].text)
547
+ }
548
+ const lines = tail.length ? [...tail, "", ...actions] : actions
549
+ const status = last ? `Done · ${clock(this.readMs)} read` : this.statusTitle()
550
+ return {
551
+ ...base,
552
+ rows: lines,
553
+ marked: null,
554
+ dimBefore: tail.length + (tail.length ? 1 : 0),
555
+ status,
556
+ detail: "100%",
557
+ }
558
+ }
559
+ default: {
560
+ const percent = this.doc.percent(this.line)
561
+ const lines = this.doc.rowsAround(this.line, marked, rows)
562
+ if (this.phase === "paused") {
563
+ return {...base, rows: lines, marked, status: "Paused · tap to resume", detail: `${wpm} wpm · ${percent}%`}
564
+ }
565
+ const left = clock((this.doc.wordsLeft(this.line) * 60_000) / wpm)
566
+ const detail = this.manual() ? "swipe to scroll" : `${wpm} wpm · ${left} left`
567
+ return {...base, rows: lines, marked, status: `${this.statusTitle()} · ${percent}%`, detail}
568
+ }
569
+ }
570
+ }
571
+
572
+ private render(): void {
573
+ if (!this.isOpenNow || !this.doc) return
574
+ const elements = lensElements(this.layout, this.frame(), this.measurer)
575
+ const encoded = JSON.stringify(elements)
576
+ if (encoded === this.lastFrame) return
577
+ this.lastFrame = encoded
578
+ void this.session.display.render(elements).catch(() => {})
579
+ }
580
+ }