// scenes.mjs — scenes in the document (scenes and clips spec §2): the // deck-level scenes map, the checks its ops make, its tolerant view, // the scene and clip block props, and a scene's version (plan call R1). // core/src/scene.rs is the twin, message for message. // // In the document, scenes is a root Y.Map of scene id to one Y.Map per // scene: name, author and code (strings), states (a plain list of {id, // name, description}), words (a Y.Map of key to text, so edits to two // words merge), data (one plain JSON value, replaced whole) and stills // (a Y.Map of state id to a plain {ref, made}). // // A scene's version is not stored: scene-version.mjs works it out. import * as Y from 'yjs' import { outToJSON, anyToJSON, put } from './ydoc.mjs' import { canonicalJSON, utf8 } from './scene-version.mjs' export { canonicalJSON, sceneCanonical, sceneVersion, stillsCurrent } from './scene-version.mjs' // 960 KiB of JSON; ops.mjs also holds a scene batch to one update (live.go maxUpdateBytes). export const MAX_SCENE_DATA = 960 * 1024 export const MAX_UPDATE_BYTES = 1 << 20 export const CLIP_PLAYS = ['press', 'loop', 'once'] const fail = msg => { throw new Error(msg) } const q = JSON.stringify const isObject = v => v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Y.AbstractType) export const hex64 = s => typeof s === 'string' && /^[0-9a-f]{64}$/.test(s) // A scene id: the document's id pattern (ids.mjs), 12 lowercase base32. export const sceneId = s => typeof s === 'string' && /^[a-z2-7]{12}$/.test(s) // The key no scene may use as an id, a state id, a word key or anywhere // in its data: lib0, Yjs's decoder for plain values, assigns it through // the prototype setter, so a browser would lose it. export const PROTO = '__proto__' const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k) /** Whether v has an object key __proto__ at any depth. */ const holdsProto = v => v !== null && typeof v === 'object' && (Array.isArray(v) ? v.some(holdsProto) : own(v, PROTO) || Object.values(v).some(holdsProto)) // --- what the ops take --- function textField (o, key, at) { const v = o[key] if (v === undefined || v === null) return '' if (typeof v !== 'string') fail(`${at}.${key} must be a string`) return v } /** A scene's states checked and rebuilt from their known fields, and the ids in order. */ export function sceneStates (v) { if (!Array.isArray(v)) fail('states must be a list') if (v.length === 0) fail('states must have at least one state') const ids = [] const out = v.map((s, i) => { const at = `states[${i}]` if (!isObject(s)) fail(`${at} must be a map`) if (typeof s.id !== 'string') fail(`${at}.id must be a string`) if (s.id === '') fail(`${at}.id is empty`) if (s.id === PROTO) fail(`${at}.id may not be "${PROTO}"`) if (ids.includes(s.id)) fail(`state ${q(s.id)} is used twice`) ids.push(s.id) return { id: s.id, name: textField(s, 'name', at), description: textField(s, 'description', at) } }) return { out, ids } } /** words as an op sends them: key to text, or on set_scene to text or null. */ export function sceneWords (v, patch) { if (!isObject(v)) fail('words must be a map') if (own(v, PROTO)) fail(`words may not have the key "${PROTO}"`) for (const [k, w] of Object.entries(v)) { if (typeof w === 'string' || (patch && w === null)) continue fail(patch ? `words.${k} must be a string or null` : `words.${k} must be a string`) } } /** data within MAX_SCENE_DATA, measured in UTF-8 bytes of its canonical JSON. */ export function sceneData (v) { if (holdsProto(v)) fail(`data may not hold the key "${PROTO}"`) if (utf8(canonicalJSON(v)).length > MAX_SCENE_DATA) fail('data is larger than 960 KiB') } /** stills as set_scene sends them: state id to {ref, made} or null, each naming one of ids. */ export function sceneStills (v, scene, ids) { if (!isObject(v)) fail('stills must be a map') for (const [state, still] of Object.entries(v)) { // null removes, and may name a state the scene no longer has if (still === null) continue if (!ids.includes(state)) fail(`scene ${q(scene)} has no state ${q(state)}`) if (!isObject(still)) fail(`stills.${state} must be a map or null`) for (const key of ['ref', 'made']) { if (!hex64(still[key])) fail(`stills.${state}.${key} is not 64 lowercase hex digits`) } } } const still = v => ({ ref: v.ref, made: v.made }) function checkCode (code) { if (!hex64(code)) fail('code is not 64 lowercase hex digits') } /** add_scene, set_scene and remove_scene against the ops' model (ops-model.mjs). */ export function checkSceneOp (model, op) { switch (op.op) { case 'add_scene': { if (!sceneId(op.id)) fail(`scene id ${q(op.id)} is not 12 lowercase base32 characters`) if (model.scenes.has(op.id)) fail(`scene ${q(op.id)} already exists`) checkCode(op.code) const { ids } = sceneStates(op.states) if (op.words !== undefined) sceneWords(op.words, false) if (op.data !== undefined) sceneData(op.data) model.scenes.set(op.id, ids) return } case 'set_scene': if (!model.scenes.has(op.id)) fail(`no scene ${q(op.id)}`) if (op.code !== undefined) checkCode(op.code) if (op.states !== undefined) model.scenes.set(op.id, sceneStates(op.states).ids) if (op.words !== undefined) sceneWords(op.words, true) if (op.data !== undefined && op.data !== null) sceneData(op.data) if (op.stills !== undefined) sceneStills(op.stills, op.id, model.scenes.get(op.id)) return case 'remove_scene': // The blocks that show it stay as they are (Review Focus 3). if (!model.scenes.delete(op.id)) fail(`no scene ${q(op.id)}`) } } // --- scene and clip blocks --- const SCENE_KEYS = ['scene', 'from', 'to'] /** What a scene block's props point at: the strings among scene, from and to. */ export function sceneRefOf (props) { const out = {} for (const k of SCENE_KEYS) out[k] = typeof props[k] === 'string' ? props[k] : null return out } /** Applies an op's props to ref, checking each key it sets; whether it touched any. */ function patchRef (ref, props) { let touched = false for (const key of SCENE_KEYS) { const v = props[key] if (v === undefined) continue if (v !== null && typeof v !== 'string') fail(`scene block props.${key} must be a string`) ref[key] = v touched = true } return touched } /** Whether ref names a scene the deck has, and two of its states in order. */ function checkRef (model, ref) { const { scene, from, to } = ref if (scene === null) { if (from !== null || to !== null) fail('scene block props.from and props.to need props.scene') return } const ids = model.scenes.get(scene) ?? fail(`no scene ${q(scene)}`) const at = s => { if (s === null) return null const i = ids.indexOf(s) if (i === -1) fail(`scene ${q(scene)} has no state ${q(s)}`) return i } const f = at(from) const t = at(to) if (f !== null && t !== null && f > t) fail(`from ${q(from)} comes after to ${q(to)} in scene ${q(scene)}`) } /** A clip block's props as an op sets them: play one of CLIP_PLAYS, asset a string; null removes either. */ function clipProps (props) { const play = props.play if (play !== undefined && play !== null && !CLIP_PLAYS.includes(play)) fail(`play ${q(play)} is not one of ${CLIP_PLAYS.join(', ')}`) const asset = props.asset if (asset !== undefined && asset !== null && typeof asset !== 'string') fail('clip block props.asset must be a string') } /** add_block's props on a block of kind: checked; the model's scene ref (null unless a scene block). */ export function newBlockScene (model, kind, props) { if (kind === 'clip') clipProps(props) if (kind !== 'scene') return null const ref = sceneRefOf({}) if (patchRef(ref, props)) checkRef(model, ref) return ref } /** set_block's props on the model's block b, checked and kept in step. */ export function setBlockScene (model, b, props) { if (b.kind === 'clip') clipProps(props) if (b.scene) { const ref = { ...b.scene } if (patchRef(ref, props)) checkRef(model, ref) b.scene = ref } } // --- the view, and the model's reading --- /** A scene's states as the view shows them: maps with a non-empty string id, the first of each. */ function viewStates (v) { if (!Array.isArray(v)) return [] const seen = new Set() const out = [] for (const s of v) { if (!isObject(s) || typeof s.id !== 'string' || s.id === '' || seen.has(s.id)) continue seen.add(s.id) const field = k => (typeof s[k] === 'string' ? s[k] : '') out.push({ id: s.id, name: field('name'), description: field('description') }) } return out } /** One scene as the view shows it, from its entry read as JSON; null for an entry that is not a map. */ export function sceneView (entry) { if (!isObject(entry)) return null const text = k => (typeof entry[k] === 'string' ? entry[k] : '') const words = {} if (isObject(entry.words)) for (const [k, w] of Object.entries(entry.words)) if (typeof w === 'string') put(words, k, w) const stills = {} if (isObject(entry.stills)) { for (const [k, s] of Object.entries(entry.stills)) { if (isObject(s) && typeof s.ref === 'string' && typeof s.made === 'string') put(stills, k, still(s)) } } return { name: text('name'), author: text('author'), code: text('code'), states: viewStates(entry.states), words, data: entry.data === undefined ? null : entry.data, stills } } /** Each scene's state ids, as the view shows them: reading only states, never the data. */ export function sceneStatesOf (scenes) { const out = new Map() scenes.forEach((v, k) => { if (v instanceof Y.Map) out.set(k, viewStates(outToJSON(v.get('states'))).map(s => s.id)) else if (isObject(v)) out.set(k, viewStates(anyToJSON(v.states)).map(s => s.id)) }) return out } // --- apply --- function patchMap (m, key, patch, value) { let target = m.get(key) if (!(target instanceof Y.Map)) { const old = isObject(target) ? target : {} target = new Y.Map() m.set(key, target) for (const k of Object.keys(old)) target.set(k, old[k]) } for (const [k, v] of Object.entries(patch)) { if (v === null) target.delete(k) else target.set(k, value(v)) } } /** add_scene, set_scene and remove_scene on the roots (ydoc.mjs), after the model passed them. */ export function applySceneOp (r, op) { switch (op.op) { case 'add_scene': { const m = new Y.Map() r.scenes.set(op.id, m) m.set('name', op.name) m.set('code', op.code) m.set('states', sceneStates(op.states).out) const words = new Y.Map() m.set('words', words) for (const [k, w] of Object.entries(op.words ?? {})) words.set(k, w) m.set('data', op.data ?? null) m.set('stills', new Y.Map()) if (op.author !== undefined) m.set('author', op.author) return } case 'set_scene': { let m = r.scenes.get(op.id) if (!(m instanceof Y.Map)) { // a scene a peer wrote as one plain map: a Y.Map of its fields const fields = isObject(m) ? m : fail(`no scene ${q(op.id)}`) m = new Y.Map() r.scenes.set(op.id, m) for (const k of Object.keys(fields)) m.set(k, fields[k]) } for (const key of ['name', 'code', 'author']) if (op[key] !== undefined) m.set(key, op[key]) if (op.states !== undefined) m.set('states', sceneStates(op.states).out) if (isObject(op.words)) patchMap(m, 'words', op.words, w => w) if (op.data !== undefined) m.set('data', op.data) if (isObject(op.stills)) patchMap(m, 'stills', op.stills, still) return } case 'remove_scene': r.scenes.delete(op.id) } }