oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1// The second pass of applyOps — core/src/ops.rs's apply_one, and the
2// constructors it uses from schema.rs. Runs inside one transaction after
3// the model has passed every op, so by construction every lookup here
4// succeeds; the throws that remain surface a bug as a message rather
5// than a half-applied batch going unnoticed.
6//
7// What a slide and a block look like in the document is decided here
8// and in the core together (schema.rs's module comment): a block map
9// holds id, type, props (Y.Map of plain values), phone (Y.Map), then
10// region (flow) or box + z (canvas); text-bearing types carry text (an
11// XmlFragment), a table carries cells (a Y.Array of XmlFragments).
12import * as Y from 'yjs'
13import { getString, getNumber, getMap, getArray, getFragment, findById, mapsOf, mapToJSON, cloneMap, orderedMaps, hasExplicitOrder, renumber } from './ydoc.mjs'
14import { writeText, textFragment } from './schema.mjs'
15import { parse, parseLines } from './markdown.mjs'
16import { defaultRegion, regionRect, boxJSON, blocksOf, toCanvas, toFlow } from './layout.mjs'
17import { isTextType, tableSide } from './ops-model.mjs'
18import { fontFilesValue } from './font-files.mjs'
19import { applySceneOp } from './scenes.mjs'
20
21export const DEFAULT_TEMPLATE = 'blank'
22export const DEFAULT_TABLE_ROWS = 2
23export const DEFAULT_TABLE_COLS = 2
24
25const fail = msg => { throw new Error(msg) }
26
27function slideMap (r, id) {
28 return findById(r.slides, id) ?? fail(`no slide ${JSON.stringify(id)}`)
29}
30function blockMap (blocks, id) {
31 return findById(blocks, id) ?? fail(`no block ${JSON.stringify(id)}`)
32}
33
34/** Where an after puts a new entry: absent appends, null goes first, an id goes right after it. */
35function insertIndex (array, after) {
36 if (after === undefined) return array.length
37 if (after === null) return 0
38 return (findById(array, after) ?? fail(`no entry ${JSON.stringify(after)}`))[0] + 1
39}
40
41/**
42 * Puts the entry id of an ordered array — a slide of the deck, a block
43 * of a slide — at the reading position after asks for: undefined means
44 * first, an id means right after it. It does that by renumbering order
45 * on every entry (ydoc.mjs, "reading order"). The array is not
46 * touched, so a peer's edit in flight against any entry still lands
47 * (codex 4).
48 */
49function placeEntry (array, what, id, after) {
50 const ordered = orderedMaps(array).map(([, m]) => [getString(m, 'id') ?? '', m])
51 const i = ordered.findIndex(([bid]) => bid === id)
52 if (i === -1) fail(`no ${what} ${JSON.stringify(id)}`)
53 const [moved] = ordered.splice(i, 1)
54 let at = 0
55 if (after !== undefined) {
56 const j = ordered.findIndex(([bid]) => bid === after)
57 if (j === -1) fail(`no entry ${JSON.stringify(after)}`)
58 at = j + 1
59 }
60 ordered.splice(at, 0, moved)
61 renumber(ordered.map(([, m]) => m))
62}
63
64/**
65 * placeEntry for an entry just inserted, whose after is the
66 * three-valued kind (undefined appends, null first, an id after it).
67 * Only called when the array already carries explicit order keys.
68 */
69function placeNew (array, what, id, after) {
70 let afterId
71 if (after === undefined) {
72 const others = orderedMaps(array).map(([, m]) => getString(m, 'id') ?? '').filter(other => other !== id)
73 afterId = others.length ? others[others.length - 1] : undefined
74 } else if (after === null) {
75 afterId = undefined
76 } else {
77 afterId = after
78 }
79 placeEntry(array, what, id, afterId)
80}
81
82function fragmentOf (map, key) {
83 let f = getFragment(map, key)
84 if (f === null) { f = new Y.XmlFragment(); map.set(key, f) }
85 return f
86}
87function mapOf (map, key) {
88 let m = getMap(map, key)
89 if (m === null) { m = new Y.Map(); map.set(key, m) }
90 return m
91}
92
93/** Text for a block of kind from its Markdown: code is plain lines, everything else the subset. */
94const textFor = (kind, markdown) => (kind === 'code' ? parseLines(markdown) : parse(markdown))
95
96function plainMap (entries) {
97 const m = new Y.Map()
98 for (const k of Object.keys(entries)) m.set(k, entries[k])
99 return m
100}
101
102function backgroundMap (kind, value) {
103 return plainMap({ kind, value })
104}
105
106/** A block map with a fresh text fragment / cells array where the type wants one (schema.rs block_prelim). */
107function blockPrelim ({ id, kind, props, region, box, z, text, cells }) {
108 const m = new Y.Map()
109 m.set('id', id)
110 m.set('type', kind)
111 m.set('props', plainMap(props))
112 m.set('phone', new Y.Map())
113 if (region !== undefined) m.set('region', region)
114 if (box !== undefined) m.set('box', box)
115 if (z !== undefined) m.set('z', z)
116 if (text !== undefined) m.set('text', textFragment(text))
117 if (cells !== undefined) {
118 const a = new Y.Array()
119 m.set('cells', a)
120 a.insert(0, Array.from({ length: cells }, () => new Y.XmlFragment()))
121 }
122 return m
123}
124
125function slidePrelim (id, layout, template) {
126 const m = new Y.Map()
127 m.set('id', id)
128 m.set('layout', layout)
129 m.set('template', template)
130 m.set('phone', 'inherit')
131 m.set('transition', 'none')
132 m.set('background', backgroundMap('theme', ''))
133 m.set('notes', new Y.XmlFragment())
134 m.set('blocks', new Y.Array())
135 return m
136}
137
138/** Drops removedId from every columns block's props.children in blocks. */
139function removeFromColumnsChildren (blocks, removedId) {
140 for (const [, m] of mapsOf(blocks)) {
141 if (getString(m, 'type') !== 'columns') continue
142 const pm = getMap(m, 'props')
143 if (pm === null) continue
144 const children = mapToJSON(pm).children
145 if (!Array.isArray(children) || !children.includes(removedId)) continue
146 pm.set('children', children.filter(c => c !== removedId))
147 }
148}
149
150/**
151 * Gives a copied slide its new ids: the slide's own, each block's, and
152 * any columns.children naming the old ones. The k-th new id goes to the
153 * k-th block in READING order — the order the model paired them in —
154 * whatever the array position; the copied order keys come along, so
155 * the copy reads as the original did.
156 */
157function rewriteIds (copy, newId, newBlockIds) {
158 copy.set('id', newId)
159 const blocks = getArray(copy, 'blocks')
160 if (blocks === null) return
161 const mapping = new Map()
162 const maps = orderedMaps(blocks)
163 maps.forEach(([, bm], k) => {
164 if (k >= newBlockIds.length) return
165 const old = getString(bm, 'id')
166 if (old !== null) mapping.set(old, newBlockIds[k])
167 bm.set('id', newBlockIds[k])
168 })
169 for (const [, bm] of maps) {
170 const props = getMap(bm, 'props')
171 if (props === null) continue
172 const children = props.get('children')
173 if (!Array.isArray(children)) continue
174 props.set('children', children.map(c => (typeof c === 'string' && mapping.has(c) ? mapping.get(c) : c)))
175 }
176}
177
178function setMeta (r, op) {
179 if (op.title !== undefined) r.meta.set('title', op.title)
180 if (op.theme !== undefined) r.meta.set('theme', op.theme)
181 if (op.accent === null) r.meta.delete('accent')
182 else if (op.accent !== undefined) r.meta.set('accent', op.accent)
183 if (op.fonts === null) r.meta.delete('fonts')
184 else if (op.fonts !== undefined) r.meta.set('fonts', { heading: op.fonts.heading, body: op.fonts.body })
185 if (op.fontFiles === null) r.meta.delete('fontFiles')
186 else if (op.fontFiles !== undefined) r.meta.set('fontFiles', fontFilesValue(op.fontFiles))
187 setOrClear(r.meta, 'arrive', op.arrive)
188}
189
190/** A nullable key's write: undefined leaves key alone, null removes it, a value sets it. */
191function setOrClear (map, key, value) {
192 if (value === null) map.delete(key)
193 else if (value !== undefined) map.set(key, value)
194}
195
196function addBlock (r, op) {
197 const [, s] = slideMap(r, op.slide)
198 const blocks = blocksOf(s)
199 const at = insertIndex(blocks, op.after)
200 const canvas = getString(s, 'layout') === 'canvas'
201 const props = { ...op.props }
202 let cells
203 if (op.type === 'table') {
204 const rows = tableSide(props, 'rows') ?? DEFAULT_TABLE_ROWS
205 const cols = tableSide(props, 'cols') ?? DEFAULT_TABLE_COLS
206 props.rows = rows
207 props.cols = cols
208 cells = rows * cols
209 }
210 const text = isTextType(op.type) ? (op.markdown === undefined ? [] : textFor(op.type, op.markdown)) : undefined
211 const region = op.region ?? defaultRegion(op.type)
212 const spec = { id: op.id, kind: op.type, props, text, cells }
213 if (canvas) {
214 spec.box = op.box !== undefined ? boxJSON(op.box.x, op.box.y, op.box.w, op.box.h) : boxJSON(...regionRect(region, false))
215 spec.z = op.z ?? at
216 } else {
217 spec.region = region
218 }
219 const explicit = hasExplicitOrder(blocks)
220 blocks.insert(at, [blockPrelim(spec)])
221 // On a slide nobody has reordered the array IS the reading order and
222 // the insert put the block where after asked. Once the slide carries
223 // order keys the array position means nothing, so the new block is
224 // placed by renumbering instead (ydoc.mjs, "reading order").
225 if (explicit) placeNew(blocks, 'block', op.id, op.after)
226}
227
228function setBlock (r, op) {
229 const [, s] = slideMap(r, op.slide)
230 const blocks = blocksOf(s)
231 const [, m] = blockMap(blocks, op.id)
232 if (op.props !== undefined) {
233 const pm = mapOf(m, 'props')
234 for (const k of Object.keys(op.props)) {
235 if (op.props[k] === null) pm.delete(k)
236 else pm.set(k, op.props[k])
237 }
238 const isTable = getString(m, 'type') === 'table'
239 // cells is row-major and flat, so a size change only appends to or
240 // truncates the end of it (spec §2.4's v1 limitation).
241 if (isTable && ('rows' in op.props || 'cols' in op.props)) {
242 const rows = Math.trunc(getNumber(pm, 'rows') ?? DEFAULT_TABLE_ROWS)
243 const cols = Math.trunc(getNumber(pm, 'cols') ?? DEFAULT_TABLE_COLS)
244 const want = Math.max(rows, 1) * Math.max(cols, 1)
245 let cells = getArray(m, 'cells')
246 if (cells === null) { cells = new Y.Array(); m.set('cells', cells) }
247 const have = cells.length
248 if (have > want) cells.delete(want, have - want)
249 if (have < want) cells.insert(have, Array.from({ length: want - have }, () => new Y.XmlFragment()))
250 }
251 }
252 if (op.region === null) m.delete('region')
253 else if (op.region !== undefined) m.set('region', op.region)
254 if (op.box === null) m.delete('box')
255 else if (op.box !== undefined) m.set('box', boxJSON(op.box.x, op.box.y, op.box.w, op.box.h))
256 if (op.z !== undefined) m.set('z', op.z)
257 setOrClear(m, 'step', op.step)
258 setOrClear(m, 'items', op.items)
259}
260
261function setPhone (r, op) {
262 const [, s] = slideMap(r, op.slide)
263 const [, m] = blockMap(blocksOf(s), op.id)
264 const pm = mapOf(m, 'phone')
265 pm.clear()
266 const p = op.phone
267 if (p.hidden !== undefined) pm.set('hidden', p.hidden)
268 if (p.order !== undefined) pm.set('order', p.order)
269 if (p.size !== undefined) pm.set('size', p.size)
270 if (p.box !== undefined) pm.set('box', boxJSON(p.box.x, p.box.y, p.box.w, p.box.h))
271}
272
273export function applyOne (r, op) {
274 switch (op.op) {
275 case 'set_meta': return setMeta(r, op)
276 case 'add_slide': {
277 const at = insertIndex(r.slides, op.after)
278 const explicit = hasExplicitOrder(r.slides)
279 r.slides.insert(at, [slidePrelim(op.id, op.layout, op.template ?? DEFAULT_TEMPLATE)])
280 // On a deck nobody has reordered the array IS the reading order;
281 // once it carries order keys the array position means nothing
282 // and the slide is placed by renumbering (ydoc.mjs, "reading
283 // order").
284 if (explicit) placeNew(r.slides, 'slide', op.id, op.after)
285 return
286 }
287 case 'remove_slide':
288 return r.slides.delete(slideMap(r, op.id)[0], 1)
289 case 'move_slide':
290 slideMap(r, op.id)
291 return placeEntry(r.slides, 'slide', op.id, op.after)
292 case 'duplicate_slide': {
293 const [i, m] = slideMap(r, op.id)
294 const copy = cloneMap(m)
295 const explicit = hasExplicitOrder(r.slides)
296 r.slides.insert(i + 1, [copy])
297 rewriteIds(copy, op.new_id, op.new_block_ids)
298 // The copy carries the original's order too, so on a reordered
299 // deck it would tie with it; renumber so the duplicate is
300 // unambiguously the next slide.
301 if (explicit) placeEntry(r.slides, 'slide', op.new_id, op.id)
302 return
303 }
304 case 'set_slide': {
305 const [, m] = slideMap(r, op.id)
306 if (op.layout !== undefined) {
307 const current = getString(m, 'layout') ?? 'flow'
308 if (op.layout !== current) {
309 if (op.layout === 'canvas') toCanvas(m)
310 else toFlow(m)
311 m.set('layout', op.layout)
312 }
313 }
314 if (op.template !== undefined) m.set('template', op.template)
315 if (op.background !== undefined) m.set('background', backgroundMap(op.background.kind, op.background.value))
316 if (op.phone !== undefined) m.set('phone', op.phone)
317 if (op.transition !== undefined) m.set('transition', op.transition)
318 setOrClear(m, 'talk', op.talk)
319 return
320 }
321 case 'set_notes': {
322 const [, m] = slideMap(r, op.id)
323 return writeText(fragmentOf(m, 'notes'), parse(op.markdown))
324 }
325 case 'add_block': return addBlock(r, op)
326 case 'remove_block': {
327 const [, s] = slideMap(r, op.slide)
328 const blocks = blocksOf(s)
329 blocks.delete(blockMap(blocks, op.id)[0], 1)
330 return removeFromColumnsChildren(blocks, op.id)
331 }
332 case 'move_block': {
333 const [, s] = slideMap(r, op.slide)
334 const blocks = blocksOf(s)
335 blockMap(blocks, op.id)
336 return placeEntry(blocks, 'block', op.id, op.after)
337 }
338 case 'set_block': return setBlock(r, op)
339 case 'set_text': {
340 const [, s] = slideMap(r, op.slide)
341 const [, m] = blockMap(blocksOf(s), op.id)
342 const kind = getString(m, 'type') ?? ''
343 return writeText(fragmentOf(m, 'text'), textFor(kind, op.markdown))
344 }
345 case 'set_phone': return setPhone(r, op)
346 case 'register_asset': // a clip's video carries its poster and length; a picture neither
347 return r.assets.set(op.id, { ref: op.ref, name: op.name, width: op.width, height: op.height, alt: op.alt, ...(op.poster ? { poster: op.poster } : {}), ...(op.duration > 0 ? { duration: op.duration } : {}) })
348 case 'remove_asset':
349 return r.assets.delete(op.id)
350 case 'add_scene': case 'set_scene': case 'remove_scene':
351 return applySceneOp(r, op)
352 }
353}
354