@glassly/miniapp 0.4.1-dev.1158 → 0.4.1-dev.1164

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 (63) hide show
  1. package/dist/display/index.d.ts +13 -3
  2. package/dist/display/index.d.ts.map +1 -1
  3. package/dist/display/index.js +10 -3
  4. package/dist/display/index.js.map +1 -1
  5. package/dist/display/scene/anchor.d.ts +16 -0
  6. package/dist/display/scene/anchor.d.ts.map +1 -0
  7. package/dist/display/scene/anchor.js +32 -0
  8. package/dist/display/scene/anchor.js.map +1 -0
  9. package/dist/display/scene/degrade.d.ts +25 -0
  10. package/dist/display/scene/degrade.d.ts.map +1 -0
  11. package/dist/display/scene/degrade.js +67 -0
  12. package/dist/display/scene/degrade.js.map +1 -0
  13. package/dist/display/scene/differ.d.ts +50 -0
  14. package/dist/display/scene/differ.d.ts.map +1 -0
  15. package/dist/display/scene/differ.js +129 -0
  16. package/dist/display/scene/differ.js.map +1 -0
  17. package/dist/display/scene/process.d.ts +41 -0
  18. package/dist/display/scene/process.d.ts.map +1 -0
  19. package/dist/display/scene/process.js +408 -0
  20. package/dist/display/scene/process.js.map +1 -0
  21. package/dist/display/scene/store.d.ts +48 -0
  22. package/dist/display/scene/store.d.ts.map +1 -0
  23. package/dist/display/scene/store.js +0 -0
  24. package/dist/display/scene/store.js.map +1 -0
  25. package/dist/display/scene/svgPath.d.ts +9 -0
  26. package/dist/display/scene/svgPath.d.ts.map +1 -0
  27. package/dist/display/scene/svgPath.js +167 -0
  28. package/dist/display/scene/svgPath.js.map +1 -0
  29. package/dist/host/index.d.ts +7 -0
  30. package/dist/host/index.d.ts.map +1 -0
  31. package/dist/host/index.js +7 -0
  32. package/dist/host/index.js.map +1 -0
  33. package/dist/host/uiShim.d.ts +38 -0
  34. package/dist/host/uiShim.d.ts.map +1 -0
  35. package/dist/host/uiShim.js +383 -0
  36. package/dist/host/uiShim.js.map +1 -0
  37. package/dist/host/webviewGlobals.d.ts +60 -0
  38. package/dist/host/webviewGlobals.d.ts.map +1 -0
  39. package/dist/host/webviewGlobals.js +211 -0
  40. package/dist/host/webviewGlobals.js.map +1 -0
  41. package/dist/mirror/canvas.d.ts +13 -2
  42. package/dist/mirror/canvas.d.ts.map +1 -1
  43. package/dist/mirror/canvas.js +42 -21
  44. package/dist/mirror/canvas.js.map +1 -1
  45. package/dist/mirror/index.d.ts +1 -1
  46. package/dist/mirror/index.d.ts.map +1 -1
  47. package/dist/mirror/index.js.map +1 -1
  48. package/dist/ui/index.d.ts +1 -1
  49. package/dist/ui/index.js +1 -1
  50. package/package.json +6 -2
  51. package/src/display/index.ts +14 -3
  52. package/src/display/scene/anchor.ts +38 -0
  53. package/src/display/scene/degrade.ts +83 -0
  54. package/src/display/scene/differ.ts +152 -0
  55. package/src/display/scene/process.ts +443 -0
  56. package/src/display/scene/store.ts +0 -0
  57. package/src/display/scene/svgPath.ts +163 -0
  58. package/src/host/index.ts +14 -0
  59. package/src/host/uiShim.ts +389 -0
  60. package/src/host/webviewGlobals.ts +251 -0
  61. package/src/mirror/canvas.ts +86 -43
  62. package/src/mirror/index.ts +1 -1
  63. package/src/ui/index.ts +1 -1
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Scene processing — validate → clamp → budget → wrap. Everything here is
3
+ * generic; device variation enters only through the capabilities block and the
4
+ * display profile (data, not code). Spec §5.
5
+ *
6
+ * Never rejects a frame: offending elements are dropped per-element and
7
+ * reported via `dropped` / `degraded` (design doc §3.4.6; spec §4 refines the
8
+ * design doc's image "reject" to per-element drop).
9
+ */
10
+
11
+ import {compileSvgPath} from "./svgPath"
12
+ import {isUnsupportedScript} from "../measurer/script-detection"
13
+ import {TextMeasurer} from "../measurer/TextMeasurer"
14
+ import {TextWrapper} from "../wrapper/TextWrapper"
15
+ import type {DisplayProfile} from "../profiles/types"
16
+ import type {DiffableElement} from "./differ"
17
+ import type {
18
+ SceneBox,
19
+ SceneBoxInput,
20
+ SceneDisplayCapabilities,
21
+ SceneElementInput,
22
+ ScenePoint,
23
+ SceneTextStyle,
24
+ SceneTransition,
25
+ SceneTransitionEdge,
26
+ } from "./types"
27
+ import {MAX_SCENE_DEPTH, POINT_SHAPE_ARITY, POINT_SHAPE_TYPES, elementContentHash} from "./types"
28
+
29
+ export interface ProcessedScene {
30
+ elements: DiffableElement[]
31
+ degraded: boolean
32
+ dropped: string[]
33
+ }
34
+
35
+ /** Reporting id for an element the app may not have named. */
36
+ function reportId(el: SceneElementInput, index: number): string {
37
+ return el.id ?? `${el.type}[${index}]`
38
+ }
39
+
40
+ function clampBox(box: SceneBox, width: number, height: number): SceneBox | null {
41
+ const x1 = Math.max(0, Math.floor(box.x))
42
+ const y1 = Math.max(0, Math.floor(box.y))
43
+ const x2 = Math.min(width, Math.floor(box.x) + Math.max(0, Math.floor(box.w)))
44
+ const y2 = Math.min(height, Math.floor(box.y) + Math.max(0, Math.floor(box.h)))
45
+ if (x2 <= x1 || y2 <= y1) return null
46
+ return {x: x1, y: y1, w: x2 - x1, h: y2 - y1}
47
+ }
48
+
49
+ const isFinite = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n)
50
+
51
+ /**
52
+ * Text the host cannot wrap: a script the measurer has no widths or break
53
+ * rules for (Thai has no spaces between words, for one). It is passed through
54
+ * unwrapped and the device's text engine lays it out in the box.
55
+ */
56
+ export function wrapsOnDevice(text: string): boolean {
57
+ for (const char of text) {
58
+ if (isUnsupportedScript(char)) return true
59
+ }
60
+ return false
61
+ }
62
+
63
+ /** Integer points, or null when the count/values are invalid for the type. */
64
+ function validPoints(el: SceneElementInput): ScenePoint[] | null {
65
+ const raw = (el as {points?: unknown}).points
66
+ if (!Array.isArray(raw) || !(POINT_SHAPE_ARITY[el.type] ?? []).includes(raw.length)) return null
67
+ const points: ScenePoint[] = []
68
+ for (const p of raw) {
69
+ if (!p || typeof p !== "object" || !isFinite((p as ScenePoint).x) || !isFinite((p as ScenePoint).y)) return null
70
+ points.push({x: Math.floor((p as ScenePoint).x), y: Math.floor((p as ScenePoint).y)})
71
+ }
72
+ return points
73
+ }
74
+
75
+ function pointsBox(points: ScenePoint[]): SceneBox {
76
+ const xs = points.map((p) => p.x)
77
+ const ys = points.map((p) => p.y)
78
+ const x = Math.min(...xs)
79
+ const y = Math.min(...ys)
80
+ return {x, y, w: Math.max(...xs) - x + 1, h: Math.max(...ys) - y + 1}
81
+ }
82
+
83
+ function validEdge(e: unknown): SceneTransitionEdge | undefined {
84
+ if (!e || typeof e !== "object") return undefined
85
+ const dx = Math.round(Number((e as SceneTransitionEdge).dx ?? 0))
86
+ const dy = Math.round(Number((e as SceneTransitionEdge).dy ?? 0))
87
+ if (!isFinite(dx) || !isFinite(dy) || Math.abs(dx) > 1024 || Math.abs(dy) > 1024) return undefined
88
+ return {dx, dy}
89
+ }
90
+
91
+ function validTransition(t: unknown): SceneTransition | undefined {
92
+ if (!t || typeof t !== "object") return undefined
93
+ const {durationMs, easing} = t as SceneTransition
94
+ if (!isFinite(durationMs) || durationMs <= 0) return undefined
95
+ const out: SceneTransition = easing ? {durationMs, easing} : {durationMs}
96
+ const enter = validEdge((t as SceneTransition).enter)
97
+ const exit = validEdge((t as SceneTransition).exit)
98
+ if (enter) out.enter = enter
99
+ if (exit) out.exit = exit
100
+ return out
101
+ }
102
+
103
+ function boxShrunk(orig: SceneBox, clamped: SceneBox): boolean {
104
+ return (
105
+ clamped.x !== Math.floor(orig.x) ||
106
+ clamped.y !== Math.floor(orig.y) ||
107
+ clamped.w !== Math.floor(orig.w) ||
108
+ clamped.h !== Math.floor(orig.h)
109
+ )
110
+ }
111
+
112
+ /**
113
+ * Line height for box-height→line-count math — ONLY when the profile declares
114
+ * a calibrated `lineHeightPx`. Deriving one from full-canvas numbers proved
115
+ * wrong on hardware (288/8=36px clipped the G2 nav instruction to one line;
116
+ * the real container line height is smaller). Without calibration we return
117
+ * null and the wrap step skips host-side height clipping entirely — text wraps
118
+ * to the box WIDTH and the firmware clips vertically in-box, which is exactly
119
+ * the legacy behavior.
120
+ */
121
+ export function profileLineHeightPx(profile: DisplayProfile, _canvasHeight: number): number | null {
122
+ return profile.lineHeightPx ?? null
123
+ }
124
+
125
+ /**
126
+ * Process a raw scene against a device's capabilities + profile. Output is
127
+ * diff-ready (text pre-wrapped, boxes clamped, content hashed) and reflects
128
+ * exactly what will be sent — the diff baseline is post-processed by design
129
+ * (spec §4).
130
+ */
131
+ export function processScene(
132
+ input: readonly SceneElementInput[],
133
+ caps: SceneDisplayCapabilities,
134
+ profile: DisplayProfile,
135
+ ): ProcessedScene {
136
+ const dropped: string[] = []
137
+ let degraded = false
138
+
139
+ const measurer = new TextMeasurer(profile)
140
+ const wrapper = new TextWrapper(measurer)
141
+ const lineHeight = profileLineHeightPx(profile, caps.height)
142
+
143
+ // Validate + dedupe explicit ids (first occurrence wins; dupes are dev error).
144
+ const seenIds = new Set<string>()
145
+ const valid: {el: SceneElementInput; index: number; box: SceneBoxInput; points?: ScenePoint[]}[] = []
146
+ input.forEach((raw, index) => {
147
+ if (!raw || typeof raw !== "object") {
148
+ dropped.push(reportId(raw ?? ({type: "text"} as SceneElementInput), index))
149
+ degraded = true
150
+ return
151
+ }
152
+ let points: ScenePoint[] | undefined
153
+ if (POINT_SHAPE_TYPES.includes(raw.type)) {
154
+ const valid = validPoints(raw)
155
+ if (!valid) {
156
+ dropped.push(reportId(raw, index))
157
+ degraded = true
158
+ return
159
+ }
160
+ points = valid
161
+ raw = {...raw, box: pointsBox(valid)} as SceneElementInput
162
+ }
163
+ if (!raw.box) {
164
+ dropped.push(reportId(raw, index))
165
+ degraded = true
166
+ return
167
+ }
168
+ // Non-finite box numbers (NaN/±Infinity/non-number) would survive the
169
+ // Math.* clamp below and poison the frame all the way to native ints.
170
+ const b = raw.box
171
+ if (![b.x, b.y, b.w, b.h].every(isFinite)) {
172
+ dropped.push(reportId(raw, index))
173
+ degraded = true
174
+ return
175
+ }
176
+ if ((raw.type === "arc" || raw.type === "pie") && !(isFinite(raw.startDeg) && isFinite(raw.endDeg))) {
177
+ dropped.push(reportId(raw, index))
178
+ degraded = true
179
+ return
180
+ }
181
+ // Leading "~" is the differ's synthetic-id namespace — an app id there
182
+ // would never match across frames (re-created every push). Normalize by
183
+ // stripping; the rewrite is deterministic, so diffing stays stable.
184
+ const el = raw.id?.startsWith("~") ? {...raw, id: raw.id.replace(/^~+/, "") || undefined} : raw
185
+ if (el.id) {
186
+ const key = `${el.type}:${el.id}`
187
+ if (seenIds.has(key)) {
188
+ dropped.push(reportId(el, index))
189
+ degraded = true
190
+ return
191
+ }
192
+ seenIds.add(key)
193
+ }
194
+ valid.push({el, index, box: el.box as SceneBoxInput, points})
195
+ })
196
+
197
+ // Clamp + per-type limits, then budget in array order.
198
+ let textBudget = caps.maxTextElements
199
+ let imageBudget = caps.maxImageElements
200
+ const out: DiffableElement[] = []
201
+ let pathEdges = 0
202
+
203
+ for (const {el, index, box, points} of valid) {
204
+ const transition = validTransition((el as {transition?: unknown}).transition)
205
+ // Leaving elements only exist to tween away; a device that jumps never shows them.
206
+ if (transition?.exit && !caps.animation) continue
207
+ const transform: {rotation?: number; pivot?: ScenePoint} = {}
208
+ if (el.rotation !== undefined || el.pivot !== undefined) {
209
+ const angle = el.rotation ?? 0
210
+ const pivot = el.pivot ?? {x: box.x + box.w / 2, y: box.y + box.h / 2}
211
+ if (
212
+ !isFinite(angle) ||
213
+ Math.abs(angle) > 36000 ||
214
+ !isFinite(pivot.x) ||
215
+ !isFinite(pivot.y) ||
216
+ Math.abs(pivot.x) > 32767 ||
217
+ Math.abs(pivot.y) > 32767 ||
218
+ !caps.rotation ||
219
+ el.type === "image" ||
220
+ el.type === "text"
221
+ ) {
222
+ dropped.push(reportId(el, index))
223
+ degraded = true
224
+ continue
225
+ }
226
+ transform.rotation = Math.round(angle * 256) / 256
227
+ transform.pivot = {x: Math.round(pivot.x), y: Math.round(pivot.y)}
228
+ if (transition) transition.durationMs = Math.min(65535, transition.durationMs)
229
+ }
230
+ const transformHash =
231
+ transform.rotation === undefined ? undefined : `${transform.rotation}:${transform.pivot?.x}:${transform.pivot?.y}`
232
+ // Depth is a lens disparity, not content: devices without it draw the
233
+ // element flat instead of dropping it. A non-number is still a dev error.
234
+ let depth: number | undefined
235
+ if (el.depth !== undefined) {
236
+ if (!isFinite(el.depth)) {
237
+ dropped.push(reportId(el, index))
238
+ degraded = true
239
+ continue
240
+ }
241
+ const d = Math.max(-MAX_SCENE_DEPTH, Math.min(MAX_SCENE_DEPTH, Math.round(el.depth)))
242
+ if (caps.depth && d !== 0) depth = d
243
+ }
244
+ const plane = depth === undefined ? {} : {depth}
245
+ const clamped = clampBox(box, caps.width, caps.height)
246
+ if (!clamped) {
247
+ dropped.push(reportId(el, index))
248
+ degraded = true
249
+ continue
250
+ }
251
+ const shrunk = boxShrunk(box, clamped)
252
+ if (shrunk) degraded = true
253
+
254
+ if (el.type === "svg") {
255
+ try {
256
+ if (!caps.shapes.includes("svg") || textBudget <= 0 || shrunk)
257
+ throw new Error("SVG unavailable or out of bounds")
258
+ const scale = el.scale ?? 1
259
+ if (
260
+ !isFinite(scale) ||
261
+ scale < 0 ||
262
+ scale > 8 ||
263
+ (el.fillRule !== undefined && el.fillRule !== "evenodd" && el.fillRule !== "nonzero")
264
+ )
265
+ throw new Error("Invalid SVG scale or fill rule")
266
+ const compiled = compileSvgPath(el.d)
267
+ if (pathEdges + compiled.edges > 4096) throw new Error("SVG scene exceeds the edge budget")
268
+ pathEdges += compiled.edges
269
+ textBudget--
270
+ out.push({
271
+ id: el.id,
272
+ type: "svg",
273
+ box: clamped,
274
+ d: el.d,
275
+ path: compiled.commands,
276
+ pathScale: Math.round(scale * 256),
277
+ fillRule: el.fillRule ?? "nonzero",
278
+ style: el.style,
279
+ ...transform,
280
+ ...plane,
281
+ ...(transition ? {transition} : {}),
282
+ contentHash: elementContentHash({
283
+ type: "svg",
284
+ data: `${el.d}:${scale}:${el.fillRule}:${transformHash}`,
285
+ style: el.style,
286
+ depth,
287
+ }),
288
+ })
289
+ } catch {
290
+ dropped.push(reportId(el, index))
291
+ degraded = true
292
+ }
293
+ continue
294
+ }
295
+
296
+ if (el.type !== "text" && el.type !== "image" && el.type !== "rect") {
297
+ // Vector shapes: only devices that draw them get them; the device clips
298
+ // point shapes itself, so an off-canvas point is not a drop.
299
+ if (!caps.shapes.includes(el.type) || textBudget <= 0) {
300
+ dropped.push(reportId(el, index))
301
+ degraded = true
302
+ continue
303
+ }
304
+ textBudget--
305
+ const angles = el.type === "arc" || el.type === "pie" ? {startDeg: el.startDeg, endDeg: el.endDeg} : {}
306
+ out.push({
307
+ id: el.id,
308
+ type: el.type,
309
+ box: clamped,
310
+ style: el.style,
311
+ ...(points ? {points} : {}),
312
+ ...angles,
313
+ ...(transition ? {transition} : {}),
314
+ ...transform,
315
+ ...plane,
316
+ contentHash: elementContentHash({
317
+ type: el.type,
318
+ style: el.style,
319
+ points,
320
+ ...angles,
321
+ data: transformHash,
322
+ depth,
323
+ }),
324
+ })
325
+ continue
326
+ }
327
+
328
+ if (el.type === "image") {
329
+ // Images: a shrunk box can't be honored (we don't crop pixels host-side)
330
+ // and per-image device limits are box-level (the firmware allocates the
331
+ // component from the box). SGCs scale pixels to the box (phone-side
332
+ // scaling — never on glasses).
333
+ if (shrunk) {
334
+ dropped.push(reportId(el, index))
335
+ continue
336
+ }
337
+ if (caps.maxImagePx && (clamped.w > caps.maxImagePx.width || clamped.h > caps.maxImagePx.height)) {
338
+ dropped.push(reportId(el, index))
339
+ degraded = true
340
+ continue
341
+ }
342
+ if (imageBudget <= 0) {
343
+ dropped.push(reportId(el, index))
344
+ degraded = true
345
+ continue
346
+ }
347
+ imageBudget--
348
+ out.push({
349
+ id: el.id,
350
+ type: "image",
351
+ box: clamped,
352
+ data: el.data,
353
+ ...(el.style ? {style: el.style} : {}),
354
+ ...(transition ? {transition} : {}),
355
+ ...plane,
356
+ contentHash: elementContentHash({type: "image", data: el.data, style: el.style, depth}),
357
+ })
358
+ continue
359
+ }
360
+
361
+ // text + rect share the text-container budget (design doc §3.4.6).
362
+ if (textBudget <= 0) {
363
+ dropped.push(reportId(el, index))
364
+ degraded = true
365
+ continue
366
+ }
367
+ textBudget--
368
+
369
+ if (el.type === "rect") {
370
+ out.push({
371
+ id: el.id,
372
+ type: "rect",
373
+ box: clamped,
374
+ style: el.style,
375
+ ...(transition ? {transition} : {}),
376
+ ...transform,
377
+ ...plane,
378
+ contentHash: elementContentHash({type: "rect", style: el.style, data: transformHash, depth}),
379
+ })
380
+ continue
381
+ }
382
+
383
+ // Text: wrap on the phone into the (clamped) box. The box then carries
384
+ // pre-wrapped text; firmware in-box wrap is a fallback, not the mechanism.
385
+ // Height clipping only applies with a CALIBRATED line height — otherwise
386
+ // the firmware clips vertically in-box (legacy behavior).
387
+ const style: SceneTextStyle = el.style ?? {}
388
+ if (style.font === "mono" || style.font === "builtin" || wrapsOnDevice(el.text ?? "")) {
389
+ // Grid text is laid out by the app (cols × rows), builtin text by the
390
+ // glasses' own font engine and unsupported scripts by the device's text
391
+ // engine; the host's proportional wrap metrics don't apply to any of
392
+ // them. Pass lines through and let the device wrap and clip.
393
+ const monoText = el.text ?? ""
394
+ out.push({
395
+ id: el.id,
396
+ type: "text",
397
+ box: clamped,
398
+ text: monoText,
399
+ style: el.style,
400
+ ...(transition ? {transition} : {}),
401
+ ...plane,
402
+ contentHash: elementContentHash({type: "text", text: monoText, style: el.style, depth}),
403
+ })
404
+ continue
405
+ }
406
+ const maxLines = lineHeight ? Math.max(1, Math.floor(clamped.h / lineHeight)) : profile.maxLines
407
+ const maxWidthPx = Math.max(1, clamped.w - 2 * (profile.textInsetPx ?? 0))
408
+ const result = wrapper.wrap(el.text ?? "", {
409
+ maxWidthPx,
410
+ maxLines,
411
+ ...(style.breakMode ? {breakMode: style.breakMode} : {}),
412
+ })
413
+ let lines = result.lines
414
+ if (result.truncated) {
415
+ degraded = true
416
+ if (style.overflow === "ellipsis" && lines.length > 0) {
417
+ // Trim the last line until it fits WITH the ellipsis appended —
418
+ // otherwise the extra glyph can overflow the clamped box width.
419
+ let last = lines[lines.length - 1]
420
+ while (last.length > 0 && !measurer.fitsInWidth(`${last}…`, maxWidthPx)) {
421
+ last = last.slice(0, -1)
422
+ }
423
+ // A box narrower than the ellipsis glyph itself gets an empty line —
424
+ // never emit a line wider than the clamped box.
425
+ const ellipsized = last.length > 0 || measurer.fitsInWidth("…", maxWidthPx) ? `${last}…` : ""
426
+ lines = [...lines.slice(0, -1), ellipsized]
427
+ }
428
+ }
429
+ const wrappedText = lines.join("\n")
430
+ out.push({
431
+ id: el.id,
432
+ type: "text",
433
+ box: clamped,
434
+ text: wrappedText,
435
+ style: el.style,
436
+ ...(transition ? {transition} : {}),
437
+ ...plane,
438
+ contentHash: elementContentHash({type: "text", text: wrappedText, style: el.style, depth}),
439
+ })
440
+ }
441
+
442
+ return {elements: out, degraded, dropped}
443
+ }
Binary file
@@ -0,0 +1,163 @@
1
+ /** SVG path compiler shared by scene validation and native wire encoding.
2
+ * Ported from g2flash revision 21; no DOM, Node or mobile-platform dependencies. */
3
+ const u16 = (v: number) => [v & 255, (v >>> 8) & 255]
4
+ function integer(v: number, min: number, max: number, name: string): number {
5
+ if (!Number.isInteger(v) || v < min || v > max) throw new Error(`${name} outside ${min}..${max}: ${v}`)
6
+ return v
7
+ }
8
+ /** SVG d subset: absolute/relative M L H V Q C S T Z; implicit repetitions.
9
+ * Unsupported syntax is rejected. Each filled contour must explicitly close. */
10
+ export function svgPath(d: string): number[] {
11
+ const tokens = d.match(/[a-zA-Z]|[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?/g) ?? []
12
+ const residue = d.replace(/[a-zA-Z]|[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][-+]?\d+)?/g, "")
13
+ if (/[^\s,]/.test(residue)) throw new Error("Invalid SVG path syntax")
14
+ let i = 0,
15
+ cmd = "",
16
+ x = 0,
17
+ y = 0,
18
+ sx = 0,
19
+ sy = 0,
20
+ open = false,
21
+ previous = ""
22
+ let cx = 0,
23
+ cy = 0
24
+ const out: number[] = []
25
+ const emit = (op: number, ...coords: number[]) => {
26
+ out.push(op, ...coords.flatMap((v) => u16(integer(Math.round(v * 16), -32768, 32767, "Q4 coordinate"))))
27
+ }
28
+ const number = () => {
29
+ if (i >= tokens.length || /^[a-z]$/i.test(tokens[i])) throw new Error("Missing SVG coordinate")
30
+ const v = Number(tokens[i++])
31
+ if (!Number.isFinite(v)) throw new Error("Invalid number")
32
+ return v
33
+ }
34
+ while (i < tokens.length) {
35
+ if (/^[a-z]$/i.test(tokens[i])) cmd = tokens[i++]
36
+ if (!cmd || !/^[MLHVQCSTZ]$/i.test(cmd)) throw new Error(`Unsupported SVG command: ${cmd}`)
37
+ const op = cmd.toUpperCase(),
38
+ rel = cmd !== op
39
+ const pair = (): [number, number] => [number() + (rel ? x : 0), number() + (rel ? y : 0)]
40
+ if (op === "Z") {
41
+ if (!open) throw new Error("Z without an open contour")
42
+ emit(4)
43
+ x = sx
44
+ y = sy
45
+ open = false
46
+ previous = "Z"
47
+ cmd = ""
48
+ continue
49
+ }
50
+ if (op !== "M" && !open) throw new Error("Path must start with M")
51
+ if (op === "M") {
52
+ if (open) throw new Error("Filled contours must close with Z before another M")
53
+ ;[x, y] = pair()
54
+ sx = x
55
+ sy = y
56
+ open = true
57
+ emit(0, x, y)
58
+ cmd = rel ? "l" : "L"
59
+ } else if (op === "L" || op === "H" || op === "V") {
60
+ if (op === "L") [x, y] = pair()
61
+ else if (op === "H") x = number() + (rel ? x : 0)
62
+ else y = number() + (rel ? y : 0)
63
+ emit(1, x, y)
64
+ } else if (op === "Q" || op === "T") {
65
+ const c = op === "Q" ? pair() : previous === "Q" || previous === "T" ? [2 * x - cx, 2 * y - cy] : [x, y]
66
+ const end = pair()
67
+ emit(2, ...c, ...end)
68
+ ;[cx, cy] = c
69
+ ;[x, y] = end
70
+ } else {
71
+ const a = op === "C" ? pair() : previous === "C" || previous === "S" ? [2 * x - cx, 2 * y - cy] : [x, y]
72
+ const b = pair(),
73
+ end = pair()
74
+ emit(3, ...a, ...b, ...end)
75
+ ;[cx, cy] = b
76
+ ;[x, y] = end
77
+ }
78
+ previous = op
79
+ }
80
+ if (open || !out.length) throw new Error("Expected explicitly closed filled path")
81
+ return out
82
+ }
83
+
84
+ /** Check the same fixed-point subdivision and budgets as revision 21 firmware. */
85
+ export function compileSvgPath(d: string): {commands: number[]; edges: number} {
86
+ if (typeof d !== "string" || d.length > 65536) throw new Error("Invalid SVG path data")
87
+ const commands = svgPath(d)
88
+ if (commands.length > 8192) throw new Error("SVG path exceeds 8192 command bytes")
89
+ let edges = 0,
90
+ count = 0,
91
+ x = 0,
92
+ y = 0,
93
+ sx = 0,
94
+ sy = 0
95
+ const edge = (ax: number, ay: number, bx: number, by: number) => {
96
+ if ((ax !== bx || ay !== by) && ++edges > 512) throw new Error("SVG path exceeds 512 compiled edges")
97
+ }
98
+ const curve = (p: number[], depth: number): void => {
99
+ const u = [
100
+ 3 * p[2] - 2 * p[0] - p[6],
101
+ 3 * p[3] - 2 * p[1] - p[7],
102
+ 3 * p[4] - 2 * p[6] - p[0],
103
+ 3 * p[5] - 2 * p[7] - p[1],
104
+ ]
105
+ if (u.every((v) => Math.abs(v) <= 16)) {
106
+ edge(p[0], p[1], p[6], p[7])
107
+ return
108
+ }
109
+ if (depth === 8) throw new Error("SVG curve exceeds subdivision limit")
110
+ const a = new Array<number>(8),
111
+ b = new Array<number>(8)
112
+ for (let k = 0; k < 2; k++) {
113
+ const ab = Math.trunc((p[k] + p[k + 2]) / 2),
114
+ bc = Math.trunc((p[k + 2] + p[k + 4]) / 2),
115
+ cd = Math.trunc((p[k + 4] + p[k + 6]) / 2)
116
+ const abc = Math.trunc((ab + bc) / 2),
117
+ bcd = Math.trunc((bc + cd) / 2),
118
+ mid = Math.trunc((abc + bcd) / 2)
119
+ a[k] = p[k]
120
+ a[k + 2] = ab
121
+ a[k + 4] = abc
122
+ a[k + 6] = mid
123
+ b[k] = mid
124
+ b[k + 2] = bcd
125
+ b[k + 4] = cd
126
+ b[k + 6] = p[k + 6]
127
+ }
128
+ curve(a, depth + 1)
129
+ curve(b, depth + 1)
130
+ }
131
+ for (let i = 0; i < commands.length;) {
132
+ const op = commands[i++],
133
+ pairs = op === 4 ? 0 : op === 3 ? 3 : op === 2 ? 2 : 1
134
+ if (++count > 1024) throw new Error("SVG path exceeds 1024 commands")
135
+ const p = [x, y]
136
+ for (let k = 0; k < pairs * 2; k++, i += 2) p.push(((commands[i] | (commands[i + 1] << 8)) << 16) >> 16)
137
+ if (op === 0) {
138
+ x = sx = p[2]
139
+ y = sy = p[3]
140
+ } else if (op === 4) {
141
+ edge(x, y, sx, sy)
142
+ x = sx
143
+ y = sy
144
+ } else if (op === 1) {
145
+ edge(x, y, p[2], p[3])
146
+ x = p[2]
147
+ y = p[3]
148
+ } else {
149
+ if (op === 2) {
150
+ p[6] = p[4]
151
+ p[7] = p[5]
152
+ for (let k = 0; k < 2; k++) {
153
+ p[k + 4] = Math.trunc((p[k + 6] + 2 * p[k + 2]) / 3)
154
+ p[k + 2] = Math.trunc((p[k] + 2 * p[k + 2]) / 3)
155
+ }
156
+ }
157
+ curve(p, 0)
158
+ x = p[6]
159
+ y = p[7]
160
+ }
161
+ }
162
+ return {commands, edges}
163
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * What a host injects into a miniapp's UI WebView. Used by the Glassly App's
3
+ * engine and the desktop simulator; miniapps never import this.
4
+ */
5
+
6
+ export {buildUiShim, type UiShimOptions} from "./uiShim"
7
+ export {
8
+ buildWebviewGlobalsScript,
9
+ buildSafeAreaUpdateScript,
10
+ type BuildWebviewGlobalsOptions,
11
+ type CapsuleMenuRect,
12
+ type MiniappColorScheme,
13
+ type MiniappSafeArea,
14
+ } from "./webviewGlobals"