@glassly/miniapp 0.4.1 → 0.4.2-beta.1188

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 (83) hide show
  1. package/README.md +1 -0
  2. package/dist/display/index.d.ts +14 -4
  3. package/dist/display/index.d.ts.map +1 -1
  4. package/dist/display/index.js +11 -4
  5. package/dist/display/index.js.map +1 -1
  6. package/dist/display/measurer/script-detection.d.ts +1 -1
  7. package/dist/display/measurer/script-detection.d.ts.map +1 -1
  8. package/dist/display/measurer/script-detection.js +46 -10
  9. package/dist/display/measurer/script-detection.js.map +1 -1
  10. package/dist/display/profiles/index.d.ts +1 -1
  11. package/dist/display/profiles/index.d.ts.map +1 -1
  12. package/dist/display/profiles/index.js +1 -1
  13. package/dist/display/profiles/index.js.map +1 -1
  14. package/dist/display/profiles/nimo.d.ts +6 -0
  15. package/dist/display/profiles/nimo.d.ts.map +1 -1
  16. package/dist/display/profiles/nimo.js +17 -0
  17. package/dist/display/profiles/nimo.js.map +1 -1
  18. package/dist/display/scene/anchor.d.ts +16 -0
  19. package/dist/display/scene/anchor.d.ts.map +1 -0
  20. package/dist/display/scene/anchor.js +32 -0
  21. package/dist/display/scene/anchor.js.map +1 -0
  22. package/dist/display/scene/degrade.d.ts +25 -0
  23. package/dist/display/scene/degrade.d.ts.map +1 -0
  24. package/dist/display/scene/degrade.js +67 -0
  25. package/dist/display/scene/degrade.js.map +1 -0
  26. package/dist/display/scene/differ.d.ts +50 -0
  27. package/dist/display/scene/differ.d.ts.map +1 -0
  28. package/dist/display/scene/differ.js +129 -0
  29. package/dist/display/scene/differ.js.map +1 -0
  30. package/dist/display/scene/process.d.ts +41 -0
  31. package/dist/display/scene/process.d.ts.map +1 -0
  32. package/dist/display/scene/process.js +408 -0
  33. package/dist/display/scene/process.js.map +1 -0
  34. package/dist/display/scene/store.d.ts +48 -0
  35. package/dist/display/scene/store.d.ts.map +1 -0
  36. package/dist/display/scene/store.js +0 -0
  37. package/dist/display/scene/store.js.map +1 -0
  38. package/dist/display/scene/svgPath.d.ts +9 -0
  39. package/dist/display/scene/svgPath.d.ts.map +1 -0
  40. package/dist/display/scene/svgPath.js +167 -0
  41. package/dist/display/scene/svgPath.js.map +1 -0
  42. package/dist/host/index.d.ts +7 -0
  43. package/dist/host/index.d.ts.map +1 -0
  44. package/dist/host/index.js +7 -0
  45. package/dist/host/index.js.map +1 -0
  46. package/dist/host/uiShim.d.ts +38 -0
  47. package/dist/host/uiShim.d.ts.map +1 -0
  48. package/dist/host/uiShim.js +383 -0
  49. package/dist/host/uiShim.js.map +1 -0
  50. package/dist/host/webviewGlobals.d.ts +60 -0
  51. package/dist/host/webviewGlobals.d.ts.map +1 -0
  52. package/dist/host/webviewGlobals.js +211 -0
  53. package/dist/host/webviewGlobals.js.map +1 -0
  54. package/dist/mirror/canvas.d.ts +13 -2
  55. package/dist/mirror/canvas.d.ts.map +1 -1
  56. package/dist/mirror/canvas.js +42 -21
  57. package/dist/mirror/canvas.js.map +1 -1
  58. package/dist/mirror/index.d.ts +1 -1
  59. package/dist/mirror/index.d.ts.map +1 -1
  60. package/dist/mirror/index.js.map +1 -1
  61. package/dist/modules/display.d.ts +10 -0
  62. package/dist/modules/display.d.ts.map +1 -1
  63. package/dist/modules/display.js.map +1 -1
  64. package/dist/ui/index.d.ts +1 -1
  65. package/dist/ui/index.js +1 -1
  66. package/package.json +6 -2
  67. package/src/display/index.ts +15 -3
  68. package/src/display/measurer/script-detection.ts +47 -10
  69. package/src/display/profiles/index.ts +1 -1
  70. package/src/display/profiles/nimo.ts +18 -0
  71. package/src/display/scene/anchor.ts +38 -0
  72. package/src/display/scene/degrade.ts +83 -0
  73. package/src/display/scene/differ.ts +152 -0
  74. package/src/display/scene/process.ts +443 -0
  75. package/src/display/scene/store.ts +0 -0
  76. package/src/display/scene/svgPath.ts +163 -0
  77. package/src/host/index.ts +14 -0
  78. package/src/host/uiShim.ts +389 -0
  79. package/src/host/webviewGlobals.ts +251 -0
  80. package/src/mirror/canvas.ts +86 -43
  81. package/src/mirror/index.ts +1 -1
  82. package/src/modules/display.ts +4 -0
  83. package/src/ui/index.ts +1 -1
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Degrade — compile a scene for devices that can't position elements
3
+ * (`canPosition: false`: G1, Z100). Output is a LEGACY layout that rides the
4
+ * existing display path — DisplayProcessor wraps it there, exactly as today,
5
+ * which is what keeps sugar byte-identical on old hardware (spec §2/§5:
6
+ * degrade output must be UNWRAPPED; wrapping twice breaks the goldens).
7
+ *
8
+ * Rules (design doc §3.4.8): content-preserving, never-erroring,
9
+ * honestly-reported. Text collapses in reading order (y, then x) joined by
10
+ * blank lines; EXACTLY two text elements sharing a y-range with disjoint
11
+ * x-ranges become a double_text_wall (ColumnComposer path downstream); rects
12
+ * drop silently (decoration); images drop + report.
13
+ */
14
+
15
+ import type {SceneElementInput} from "./types"
16
+
17
+ export interface DegradedScene {
18
+ /** Legacy layout for the existing display path, or null for an empty scene (caller clears). */
19
+ layout: {layoutType: string; [key: string]: unknown} | null
20
+ degraded: boolean
21
+ dropped: string[]
22
+ }
23
+
24
+ type TextEl = Extract<SceneElementInput, {type: "text"}>
25
+
26
+ function yOverlap(a: TextEl, b: TextEl): boolean {
27
+ return a.box.y < b.box.y + b.box.h && b.box.y < a.box.y + a.box.h
28
+ }
29
+
30
+ function xDisjoint(a: TextEl, b: TextEl): boolean {
31
+ return a.box.x + a.box.w <= b.box.x || b.box.x + b.box.w <= a.box.x
32
+ }
33
+
34
+ export function degradeScene(input: readonly SceneElementInput[]): DegradedScene {
35
+ const dropped: string[] = []
36
+ let degraded = false
37
+
38
+ const texts: TextEl[] = []
39
+ input.forEach((el, index) => {
40
+ if (el && typeof el === "object" && Array.isArray((el as {points?: unknown}).points)) {
41
+ return // vector shapes: decoration on a text wall
42
+ }
43
+ if (!el || typeof el !== "object" || !el.box) {
44
+ // Malformed element — report it like the positioning pipeline does
45
+ // instead of silently pretending the render was clean.
46
+ dropped.push((el as {id?: string} | null)?.id ?? `element[${index}]`)
47
+ degraded = true
48
+ return
49
+ }
50
+ if (el.type === "text") {
51
+ texts.push(el)
52
+ } else if (el.type === "image") {
53
+ dropped.push(el.id ?? `image[${index}]`)
54
+ degraded = true
55
+ }
56
+ // rects and other shapes: silent drop — pure decoration on a text wall.
57
+ })
58
+
59
+ if (texts.length === 0) {
60
+ return {layout: null, degraded, dropped}
61
+ }
62
+
63
+ // Row exception: exactly 2 columns with clean separation — the shipped
64
+ // double_text_wall mechanism (scope guard: nothing fancier; this is NOT a
65
+ // layout engine).
66
+ if (texts.length === 2 && yOverlap(texts[0], texts[1]) && xDisjoint(texts[0], texts[1])) {
67
+ const [left, right] = texts[0].box.x <= texts[1].box.x ? [texts[0], texts[1]] : [texts[1], texts[0]]
68
+ return {
69
+ layout: {layoutType: "double_text_wall", topText: left.text ?? "", bottomText: right.text ?? ""},
70
+ degraded,
71
+ dropped,
72
+ }
73
+ }
74
+
75
+ // Reading order: y, then x; join with blank lines. Downstream wrap clips
76
+ // overflow per the device profile.
77
+ const ordered = [...texts].sort((a, b) => a.box.y - b.box.y || a.box.x - b.box.x)
78
+ const text = ordered
79
+ .map((t) => t.text ?? "")
80
+ .filter((t) => t.length > 0)
81
+ .join("\n\n")
82
+ return {layout: {layoutType: "text_wall", text}, degraded, dropped}
83
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Scene differ — matches elements between the last frame sent to the device and
3
+ * the next scene, and classifies each element's change. Pure set arithmetic:
4
+ * nothing in here is device-specific (spec §1).
5
+ *
6
+ * Matching rules (design doc §3.4.1, in order):
7
+ * 1. same explicit `id` + same `type` ⇒ same element
8
+ * 2. no id: same `type` + identical box ⇒ same element
9
+ * 3. no id: same `type`, by order among the still-unmatched
10
+ * 4. anything unmatched in prev ⇒ removed; unmatched in next ⇒ created
11
+ *
12
+ * Matched no-id elements INHERIT the previous element's assigned id so the
13
+ * device-side id⇒firmware-component mapping stays stable; fresh elements get a
14
+ * synthesized id from the caller (SceneStore counter). Synthesized ids are
15
+ * prefixed "~" so they can never collide with app-supplied ids.
16
+ */
17
+
18
+ import type {FrameElement, SceneBox, SceneChange, SceneElementType, ScenePoint, SceneTransition} from "./types"
19
+ import {boxesEqual} from "./types"
20
+
21
+ /** A processed (clamped/wrapped) element, pre-diff: id optional, no annotation yet. */
22
+ export interface DiffableElement {
23
+ /** SVG path and its checked firmware command stream (Q4 coordinates). */
24
+ d?: string
25
+ path?: number[]
26
+ pathScale?: number
27
+ fillRule?: "nonzero" | "evenodd"
28
+ rotation?: number
29
+ pivot?: ScenePoint
30
+ depth?: number
31
+
32
+ id?: string
33
+ type: SceneElementType
34
+ box: SceneBox
35
+ text?: string
36
+ data?: string
37
+ style?: FrameElement["style"]
38
+ points?: ScenePoint[]
39
+ startDeg?: number
40
+ endDeg?: number
41
+ transition?: SceneTransition
42
+ contentHash: string
43
+ }
44
+
45
+ export interface DiffResult {
46
+ elements: FrameElement[]
47
+ removed: string[]
48
+ }
49
+
50
+ function classify(prev: FrameElement, next: DiffableElement): SceneChange {
51
+ if (!boxesEqual(prev.box, next.box)) return "moved"
52
+ if (prev.contentHash !== next.contentHash) return "updated"
53
+ return "unchanged"
54
+ }
55
+
56
+ /**
57
+ * Assemble the annotated FrameElement, OMITTING optional fields that are
58
+ * undefined. A present key with an `undefined` value cannot cross the Expo
59
+ * Android bridge — its `Map<String, Any>` converter rejects it ("Value is
60
+ * undefined, expected an Object"), which surfaces as ERR_UNEXPECTED from
61
+ * displayEvent. (iOS's `[String: Any]` bridge silently drops nils, so the
62
+ * defect was invisible there.) Keeping the keys absent — not undefined —
63
+ * matches the optional-field contract in types.ts.
64
+ */
65
+ function buildFrameElement(el: DiffableElement, id: string, change: SceneChange): FrameElement {
66
+ const out: FrameElement = {id, type: el.type, box: el.box, contentHash: el.contentHash, change}
67
+ if (el.text !== undefined) out.text = el.text
68
+ if (el.data !== undefined) out.data = el.data
69
+ if (el.style !== undefined) out.style = el.style
70
+ if (el.points !== undefined) out.points = el.points
71
+ if (el.startDeg !== undefined) out.startDeg = el.startDeg
72
+ if (el.endDeg !== undefined) out.endDeg = el.endDeg
73
+ if (el.transition !== undefined) out.transition = el.transition
74
+ if (el.d !== undefined) out.d = el.d
75
+ if (el.path !== undefined) out.path = el.path
76
+ if (el.pathScale !== undefined) out.pathScale = el.pathScale
77
+ if (el.fillRule !== undefined) out.fillRule = el.fillRule
78
+ if (el.rotation !== undefined) out.rotation = el.rotation
79
+ if (el.pivot !== undefined) out.pivot = el.pivot
80
+ if (el.depth !== undefined) out.depth = el.depth
81
+ return out
82
+ }
83
+
84
+ /**
85
+ * Diff `next` against `prev` (the last frame sent for this app/view/device;
86
+ * empty array for a fresh scene). `nextSyntheticId` mints ids for elements the
87
+ * app didn't name — must be stable per (app, view) across calls (SceneStore).
88
+ */
89
+ export function diffScene(
90
+ prev: readonly FrameElement[],
91
+ next: readonly DiffableElement[],
92
+ nextSyntheticId: () => string,
93
+ ): DiffResult {
94
+ const prevUnmatched = new Set(prev.map((_, i) => i))
95
+ const prevByExplicitId = new Map<string, number>()
96
+ prev.forEach((el, i) => {
97
+ if (!el.id.startsWith("~")) prevByExplicitId.set(`${el.type}:${el.id}`, i)
98
+ })
99
+
100
+ // matches[nextIndex] = prevIndex | undefined
101
+ const matches: (number | undefined)[] = new Array(next.length).fill(undefined)
102
+
103
+ // Pass 1: explicit id + type.
104
+ next.forEach((el, i) => {
105
+ if (!el.id) return
106
+ const j = prevByExplicitId.get(`${el.type}:${el.id}`)
107
+ if (j !== undefined && prevUnmatched.has(j)) {
108
+ matches[i] = j
109
+ prevUnmatched.delete(j)
110
+ }
111
+ })
112
+
113
+ // Pass 2: no-id elements match a no-id prev element of the same type with an
114
+ // identical box.
115
+ next.forEach((el, i) => {
116
+ if (el.id || matches[i] !== undefined) return
117
+ for (const j of prevUnmatched) {
118
+ const p = prev[j]
119
+ if (p.id.startsWith("~") && p.type === el.type && boxesEqual(p.box, el.box)) {
120
+ matches[i] = j
121
+ prevUnmatched.delete(j)
122
+ break
123
+ }
124
+ }
125
+ })
126
+
127
+ // Pass 3: remaining no-id elements match remaining no-id prev of the same
128
+ // type in order (k-th unmatched text ↔ k-th unmatched text).
129
+ next.forEach((el, i) => {
130
+ if (el.id || matches[i] !== undefined) return
131
+ for (const j of prevUnmatched) {
132
+ const p = prev[j]
133
+ if (p.id.startsWith("~") && p.type === el.type) {
134
+ matches[i] = j
135
+ prevUnmatched.delete(j)
136
+ break
137
+ }
138
+ }
139
+ })
140
+
141
+ const elements: FrameElement[] = next.map((el, i) => {
142
+ const j = matches[i]
143
+ if (j !== undefined) {
144
+ const p = prev[j]
145
+ return buildFrameElement(el, el.id ?? p.id, classify(p, el))
146
+ }
147
+ return buildFrameElement(el, el.id ?? nextSyntheticId(), "created")
148
+ })
149
+
150
+ const removed = [...prevUnmatched].map((j) => prev[j].id)
151
+ return {elements, removed}
152
+ }
@@ -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