File size: 4,730 Bytes
e079a73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**

 * Scene differ — matches elements between the last frame sent to the device and

 * the next scene, and classifies each element's change. Pure set arithmetic:

 * nothing in here is device-specific (spec §1).

 *

 * Matching rules (design doc §3.4.1, in order):

 *   1. same explicit `id` + same `type`  ⇒ same element

 *   2. no id: same `type` + identical box ⇒ same element

 *   3. no id: same `type`, by order among the still-unmatched

 *   4. anything unmatched in prev ⇒ removed; unmatched in next ⇒ created

 *

 * Matched no-id elements INHERIT the previous element's assigned id so the

 * device-side id⇒firmware-component mapping stays stable; fresh elements get a

 * synthesized id from the caller (SceneStore counter). Synthesized ids are

 * prefixed "~" so they can never collide with app-supplied ids.

 */

import type {FrameElement, SceneBox, SceneChange, SceneElementType} from "./types"
import {boxesEqual} from "./types"

/** A processed (clamped/wrapped) element, pre-diff: id optional, no annotation yet. */
export interface DiffableElement {
  id?: string
  type: SceneElementType
  box: SceneBox
  text?: string
  data?: string
  style?: FrameElement["style"]
  contentHash: string
}

export interface DiffResult {
  elements: FrameElement[]
  removed: string[]
}

function classify(prev: FrameElement, next: DiffableElement): SceneChange {
  if (!boxesEqual(prev.box, next.box)) return "moved"
  if (prev.contentHash !== next.contentHash) return "updated"
  return "unchanged"
}

/**

 * Assemble the annotated FrameElement, OMITTING optional fields that are

 * undefined. A present key with an `undefined` value cannot cross the Expo

 * Android bridge — its `Map<String, Any>` converter rejects it ("Value is

 * undefined, expected an Object"), which surfaces as ERR_UNEXPECTED from

 * displayEvent. (iOS's `[String: Any]` bridge silently drops nils, so the

 * defect was invisible there.) Keeping the keys absent — not undefined —

 * matches the optional-field contract in types.ts.

 */
function buildFrameElement(el: DiffableElement, id: string, change: SceneChange): FrameElement {
  const out: FrameElement = {id, type: el.type, box: el.box, contentHash: el.contentHash, change}
  if (el.text !== undefined) out.text = el.text
  if (el.data !== undefined) out.data = el.data
  if (el.style !== undefined) out.style = el.style
  return out
}

/**

 * Diff `next` against `prev` (the last frame sent for this app/view/device;

 * empty array for a fresh scene). `nextSyntheticId` mints ids for elements the

 * app didn't name — must be stable per (app, view) across calls (SceneStore).

 */
export function diffScene(

  prev: readonly FrameElement[],

  next: readonly DiffableElement[],

  nextSyntheticId: () => string,

): DiffResult {
  const prevUnmatched = new Set(prev.map((_, i) => i))
  const prevByExplicitId = new Map<string, number>()
  prev.forEach((el, i) => {
    if (!el.id.startsWith("~")) prevByExplicitId.set(`${el.type}:${el.id}`, i)
  })

  // matches[nextIndex] = prevIndex | undefined
  const matches: (number | undefined)[] = new Array(next.length).fill(undefined)

  // Pass 1: explicit id + type.
  next.forEach((el, i) => {
    if (!el.id) return
    const j = prevByExplicitId.get(`${el.type}:${el.id}`)
    if (j !== undefined && prevUnmatched.has(j)) {
      matches[i] = j
      prevUnmatched.delete(j)
    }
  })

  // Pass 2: no-id elements match a no-id prev element of the same type with an
  // identical box.
  next.forEach((el, i) => {
    if (el.id || matches[i] !== undefined) return
    for (const j of prevUnmatched) {
      const p = prev[j]
      if (p.id.startsWith("~") && p.type === el.type && boxesEqual(p.box, el.box)) {
        matches[i] = j
        prevUnmatched.delete(j)
        break
      }
    }
  })

  // Pass 3: remaining no-id elements match remaining no-id prev of the same
  // type in order (k-th unmatched text ↔ k-th unmatched text).
  next.forEach((el, i) => {
    if (el.id || matches[i] !== undefined) return
    for (const j of prevUnmatched) {
      const p = prev[j]
      if (p.id.startsWith("~") && p.type === el.type) {
        matches[i] = j
        prevUnmatched.delete(j)
        break
      }
    }
  })

  const elements: FrameElement[] = next.map((el, i) => {
    const j = matches[i]
    if (j !== undefined) {
      const p = prev[j]
      return buildFrameElement(el, el.id ?? p.id, classify(p, el))
    }
    return buildFrameElement(el, el.id ?? nextSyntheticId(), "created")
  })

  const removed = [...prevUnmatched].map((j) => prev[j].id)
  return {elements, removed}
}