| 1 | package deck |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "math" |
| 7 | "regexp" |
| 8 | "sort" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | ) |
| 12 | |
| 13 | // Scene is one of a deck's scenes (scenes and clips spec §2): code an |
| 14 | // agent wrote, run sealed, drawing named states. Code is the ref of its |
| 15 | // stored bundle; Author is who wrote that code, set by the server from |
| 16 | // whoever changed it; Words are its labels, key to text; Data is its |
| 17 | // model, any JSON value; Stills are a picture per state, by state id. |
| 18 | // core/src/scene.rs decides the shape; the view has already dropped |
| 19 | // anything mistyped. |
| 20 | type Scene struct { |
| 21 | Name string `json:"name"` |
| 22 | Author string `json:"author"` |
| 23 | Code string `json:"code"` |
| 24 | States []SceneState `json:"states"` |
| 25 | Words map[string]string `json:"words"` |
| 26 | Data any `json:"data"` |
| 27 | Stills map[string]Still `json:"stills"` |
| 28 | } |
| 29 | |
| 30 | // SceneState is one named state of a scene. ID is stable; Name shows in |
| 31 | // the editor; Description is what assistive technology reads for it. |
| 32 | type SceneState struct { |
| 33 | ID string `json:"id"` |
| 34 | Name string `json:"name"` |
| 35 | Description string `json:"description"` |
| 36 | } |
| 37 | |
| 38 | // Still is a state's picture: Ref is the stored image, Made the scene's |
| 39 | // SceneVersion when it was drawn, so a still drawn from older code, data |
| 40 | // or words can be told apart. |
| 41 | type Still struct { |
| 42 | Ref string `json:"ref"` |
| 43 | Made string `json:"made"` |
| 44 | } |
| 45 | |
| 46 | // StateIndex is the place of state id in the scene's states, -1 when it |
| 47 | // has none by that id. |
| 48 | func (s Scene) StateIndex(id string) int { |
| 49 | for i, st := range s.States { |
| 50 | if st.ID == id { |
| 51 | return i |
| 52 | } |
| 53 | } |
| 54 | return -1 |
| 55 | } |
| 56 | |
| 57 | // Shown is the states a scene block whose props name from and to |
| 58 | // draws, as indices in s.States: from, then each state a press brings |
| 59 | // (plan call R2), up to and including to. A block whose from comes |
| 60 | // after its to, or names a state the scene no longer has, draws the one |
| 61 | // of the two still there, to first; none when neither is. |
| 62 | func (s Scene) Shown(from, to string) []int { |
| 63 | f, t := s.StateIndex(from), s.StateIndex(to) |
| 64 | switch { |
| 65 | case f >= 0 && t >= f: |
| 66 | out := make([]int, 0, t-f+1) |
| 67 | for i := f; i <= t; i++ { |
| 68 | out = append(out, i) |
| 69 | } |
| 70 | return out |
| 71 | case t >= 0: |
| 72 | return []int{t} |
| 73 | case f >= 0: |
| 74 | return []int{f} |
| 75 | } |
| 76 | return nil |
| 77 | } |
| 78 | |
| 79 | // StillOf is the picture a scene's state is drawn as where its code |
| 80 | // doesn't run: the asset the deck registered its still's ref under (the |
| 81 | // lowest id when several share it) and that asset. A state with no |
| 82 | // still, or a still whose ref the deck never registered, has none, and |
| 83 | // is drawn as the placeholder panel (plan call R4). |
| 84 | func (d *Deck) StillOf(s Scene, state string) (string, Asset, bool) { |
| 85 | still, ok := s.Stills[state] |
| 86 | if !ok || still.Ref == "" || d == nil { |
| 87 | return "", Asset{}, false |
| 88 | } |
| 89 | var id string |
| 90 | for k, a := range d.Assets { |
| 91 | if a.Ref == still.Ref && (id == "" || k < id) { |
| 92 | id = k |
| 93 | } |
| 94 | } |
| 95 | if id == "" { |
| 96 | return "", Asset{}, false |
| 97 | } |
| 98 | return id, d.Assets[id], true |
| 99 | } |
| 100 | |
| 101 | // MaxSceneData is the most data a scene may hold, measured as |
| 102 | // SceneDataSize: 960 KiB. The core's ops refuse more (core/src/scene.rs |
| 103 | // MAX_SCENE_DATA); the server refuses a posted update that leaves more. |
| 104 | // It does not by itself make a set_scene fit one live-sync update (1 MiB, |
| 105 | // live.go maxUpdateBytes): numbers encode larger than their JSON, so the |
| 106 | // core's ops also refuse a batch with a scene op whose update would be |
| 107 | // over 1 MiB (core/src/scene.rs MAX_UPDATE_BYTES), and a posted update |
| 108 | // is under that cap already. |
| 109 | const MaxSceneData = 960 * 1024 |
| 110 | |
| 111 | // sceneID is the document's id pattern (spec §2.2), which scene ids keep |
| 112 | // to as slide and block ids do. |
| 113 | var sceneID = regexp.MustCompile(`^[a-z2-7]{12}$`) |
| 114 | |
| 115 | // SceneID reports whether id is a well-formed scene id: 12 lowercase |
| 116 | // base32 characters. The core's ops refuse any other. |
| 117 | func SceneID(id string) bool { return sceneID.MatchString(id) } |
| 118 | |
| 119 | // Proto is the key no scene may use as an id, a state id, a word key or |
| 120 | // anywhere in its data: JavaScript's decoder for plain values (lib0, |
| 121 | // under Yjs) assigns it through the prototype setter, so a browser |
| 122 | // would lose it. The core's ops refuse it (core/src/scene.rs PROTO). |
| 123 | const Proto = "__proto__" |
| 124 | |
| 125 | // HoldsProto reports whether v, as the view parsed it, has an object key |
| 126 | // Proto at any depth. |
| 127 | func HoldsProto(v any) bool { |
| 128 | switch x := v.(type) { |
| 129 | case []any: |
| 130 | for _, item := range x { |
| 131 | if HoldsProto(item) { |
| 132 | return true |
| 133 | } |
| 134 | } |
| 135 | case map[string]any: |
| 136 | for k, item := range x { |
| 137 | if k == Proto || HoldsProto(item) { |
| 138 | return true |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | return false |
| 143 | } |
| 144 | |
| 145 | // SceneDataSize is the size of a scene's data as its canonical JSON, in |
| 146 | // UTF-8 bytes — what MaxSceneData limits. |
| 147 | func SceneDataSize(s Scene) int { |
| 148 | var b strings.Builder |
| 149 | writeCanonical(&b, s.Data) |
| 150 | return b.Len() |
| 151 | } |
| 152 | |
| 153 | // SceneVersion is a scene's version (plan call R1, as amended in |
| 154 | // review): the SHA-256, in lowercase hex, of SceneCanonical. It changes |
| 155 | // with the code, the data or the words, and with nothing else. It is |
| 156 | // never stored: the core (core/src/scene.rs) and the browser |
| 157 | // (fixtures/scene-version.mjs) compute the same thing, held to one |
| 158 | // answer by fixtures/vectors/scene-version.json. |
| 159 | func SceneVersion(s Scene) string { |
| 160 | sum := sha256.Sum256([]byte(SceneCanonical(s))) |
| 161 | return hex.EncodeToString(sum[:]) |
| 162 | } |
| 163 | |
| 164 | // SceneCanonical is what SceneVersion hashes: the canonical JSON of the |
| 165 | // object {"code", "data", "words"}. Canonical JSON is JSON.stringify's, |
| 166 | // made deterministic: no white space, object keys sorted by code point |
| 167 | // at every level (Go's byte order on UTF-8 is that), numbers as |
| 168 | // JavaScript prints them, strings escaped only where JSON must be |
| 169 | // (encoding/json would also escape <, >, & and U+2028, so it is written |
| 170 | // out here). Data is what the view parsed into: nil, bool, float64, |
| 171 | // string, []any, map[string]any. |
| 172 | func SceneCanonical(s Scene) string { |
| 173 | words := make(map[string]any, len(s.Words)) |
| 174 | for k, v := range s.Words { |
| 175 | words[k] = v |
| 176 | } |
| 177 | var b strings.Builder |
| 178 | writeCanonical(&b, map[string]any{"code": s.Code, "data": s.Data, "words": words}) |
| 179 | return b.String() |
| 180 | } |
| 181 | |
| 182 | func writeCanonical(b *strings.Builder, v any) { |
| 183 | switch x := v.(type) { |
| 184 | case nil: |
| 185 | b.WriteString("null") |
| 186 | case bool: |
| 187 | b.WriteString(strconv.FormatBool(x)) |
| 188 | case float64: |
| 189 | b.WriteString(esNumber(x)) |
| 190 | case int: |
| 191 | b.WriteString(esNumber(float64(x))) |
| 192 | case string: |
| 193 | writeString(b, x) |
| 194 | case []any: |
| 195 | b.WriteByte('[') |
| 196 | for i, item := range x { |
| 197 | if i > 0 { |
| 198 | b.WriteByte(',') |
| 199 | } |
| 200 | writeCanonical(b, item) |
| 201 | } |
| 202 | b.WriteByte(']') |
| 203 | case map[string]any: |
| 204 | keys := make([]string, 0, len(x)) |
| 205 | for k := range x { |
| 206 | keys = append(keys, k) |
| 207 | } |
| 208 | sort.Strings(keys) |
| 209 | b.WriteByte('{') |
| 210 | for i, k := range keys { |
| 211 | if i > 0 { |
| 212 | b.WriteByte(',') |
| 213 | } |
| 214 | writeString(b, k) |
| 215 | b.WriteByte(':') |
| 216 | writeCanonical(b, x[k]) |
| 217 | } |
| 218 | b.WriteByte('}') |
| 219 | default: |
| 220 | b.WriteString("null") |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | func writeString(b *strings.Builder, s string) { |
| 225 | const hexDigits = "0123456789abcdef" |
| 226 | b.WriteByte('"') |
| 227 | for _, r := range s { |
| 228 | switch r { |
| 229 | case '"': |
| 230 | b.WriteString(`\"`) |
| 231 | case '\\': |
| 232 | b.WriteString(`\\`) |
| 233 | case '\b': |
| 234 | b.WriteString(`\b`) |
| 235 | case '\f': |
| 236 | b.WriteString(`\f`) |
| 237 | case '\n': |
| 238 | b.WriteString(`\n`) |
| 239 | case '\r': |
| 240 | b.WriteString(`\r`) |
| 241 | case '\t': |
| 242 | b.WriteString(`\t`) |
| 243 | default: |
| 244 | if r < 0x20 { |
| 245 | b.WriteString(`\u00`) |
| 246 | b.WriteByte(hexDigits[r>>4]) |
| 247 | b.WriteByte(hexDigits[r&0xf]) |
| 248 | } else { |
| 249 | b.WriteRune(r) |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | b.WriteByte('"') |
| 254 | } |
| 255 | |
| 256 | // esNumber is f as JavaScript's Number::toString prints it: encoding/json's |
| 257 | // float rule, which follows ES6 (fixed notation from 1e-6 up to 1e21, |
| 258 | // exponent notation outside it with no leading zero in the exponent), |
| 259 | // except that -0 is 0. |
| 260 | func esNumber(f float64) string { |
| 261 | if f == 0 { |
| 262 | return "0" |
| 263 | } |
| 264 | if math.IsNaN(f) || math.IsInf(f, 0) { |
| 265 | return "null" |
| 266 | } |
| 267 | format := byte('f') |
| 268 | if abs := math.Abs(f); abs < 1e-6 || abs >= 1e21 { |
| 269 | format = 'e' |
| 270 | } |
| 271 | out := strconv.AppendFloat(nil, f, format, -1, 64) |
| 272 | if format == 'e' { |
| 273 | // e-07 is e-7, as JavaScript writes it. |
| 274 | if n := len(out); n >= 4 && out[n-4] == 'e' && out[n-3] == '-' && out[n-2] == '0' { |
| 275 | out[n-2] = out[n-1] |
| 276 | out = out[:n-1] |
| 277 | } |
| 278 | } |
| 279 | return string(out) |
| 280 | } |
| 281 | |