// fixtures/scene-code.mjs — a scene's code, edited by hand (scenes and // clips spec §5, "Code"; §8 call 6): the bundle's text in a plain text // field, with who last changed it; Preview, which runs the unsaved text // in the block's own frame; and Save code, which stores it as a new // bundle and names that as the scene's code. // // Preview posts the text as a form's one field, html, to the preview // route (scenes.go's previewScene), its target the block's frame by // name: the route answers it under the sealed policy, so a draft runs // exactly as the saved bundle will, and nothing is stored. The frame is // made for it afresh (scene-layer.mjs's preview), and goes back to the // saved code once the block is chosen again or the scene changes. // // Save is a picture's upload with text/html as its type (uploads.mjs's // flow, editor-entry.js's requests): sign, PUT, register, which reads the // bytes back and refuses anything but one HTML document of at most // 2 MiB; then one set_scene{code}, its author the server's to stamp // (this person, which the author line then says). A refusal is said in // the page's words, the scene's name in them. Code that did not load // says so, with Try again, and cannot be saved over until it has. An // author the page did not name is asked for (GET /d/{sqid}/scene-authors). // // mountSceneCode({el, base, labels, texts, commit, save, preview}) → // {fill(id, scene, shown), destroy()}. el is [slides-scene-code]; // save({text}) the request seams' saveSceneCode; preview(id, submit) // remakes the scene's frame and calls submit(frameName). import { UploadError } from './uploads.mjs' /** The most a bundle may be (scenes.go's maxSceneBytes). */ export const MAX_CODE = 2 * 1024 * 1024 const NAME = 'scene.html' /** text stored as a scene bundle through the seams: its ref. Throws an UploadError. */ export async function saveSceneCode ({ text, sign, put, register, hash }) { const blob = new Blob([text], { type: 'text/html' }) if (blob.size === 0) throw new UploadError('not_html') if (blob.size > MAX_CODE) throw new UploadError('too_large') const signed = await sign({ name: NAME, size: blob.size, type: 'text/html', hash: await hash(blob) }) if (!signed || !signed.url || !signed.ref) throw new UploadError('failed') await put(signed.url, blob, signed.headers || {}) const record = await register({ ref: signed.ref, name: NAME }) if (!record || record.kind !== 'scene' || !record.ref) throw new UploadError('failed') return record.ref } /** A refused save in the page's words: texts {refused, refusedBig, failed}, name the scene's. */ export function refusalText (code, name, texts) { if (code === 'not_html') return (texts.refused || '').replace('{name}', name) if (code === 'too_large') return (texts.refusedBig || '').replace('{name}', name) return texts.failed || '' } /** "Last changed by {name}" for actor, or '' when nobody is known by that actor. */ export function authorLine (actor, labels, text) { const name = actor && labels && Object.hasOwn(labels, actor) ? labels[actor] : '' return name ? text.replace('{name}', name) : '' } /** Posts html to action in a form whose target is the frame named target (the sealed preview route). */ export function postPreview ({ doc = document, action, target, html }) { const form = doc.createElement('form') form.method = 'post' form.action = action form.enctype = 'multipart/form-data' form.target = target form.hidden = true const field = doc.createElement('textarea') field.name = 'html' field.value = html form.append(field) doc.body.append(form) form.submit() form.remove() } export function mountSceneCode ({ el, base, labels = {}, texts = {}, commit, save, preview }) { if (!el) return { fill () {}, destroy () {} } const area = el.querySelector('textarea') const status = el.querySelector('[slides-scene-status]') const author = el.querySelector('[slides-scene-author]') const saveBtn = el.querySelector('[slides-scene-save]') const retry = el.querySelector('[slides-scene-retry]') // The scene shown; the code its text was read from (ready once it // has been), or that could not be read; whether the person has // changed the text since. let current = { id: '', scene: null, loaded: '', ready: false, failed: '', dirty: false } let busy = false const names = { ...labels } const asked = new Set() const abort = new AbortController() const on = (node, type, fn) => node.addEventListener(type, fn, { signal: abort.signal }) const sync = () => { saveBtn.disabled = busy || !current.ready } // Code that did not come is not empty code: the line says so with Try // again, and Save stays off until this code's text has been read, so // an older text is never saved over newer code. async function load (id, ref) { current.loaded = ref current.failed = '' current.ready = false retry.hidden = true sync() try { const res = await fetch(`${base}/scenes/${encodeURIComponent(id)}/${encodeURIComponent(ref)}`, { credentials: 'same-origin' }) if (!res.ok) throw new Error(`scene code: ${res.status}`) const text = await res.text() if (current.id !== id || current.loaded !== ref) return if (!current.dirty) area.value = text current.ready = true if (status.textContent === texts.loadFailed) status.textContent = '' } catch (err) { console.error('scene code:', err) if (current.id !== id || current.loaded !== ref) return current.loaded = '' current.failed = ref current.ready = false status.textContent = texts.loadFailed || '' retry.hidden = false } sync() } function showAuthor () { const scene = current.scene const line = scene ? authorLine(scene.author, names, texts.author || '') : '' author.textContent = line author.hidden = !line } // An author the page was not told of (who changed the code while it // was open) is asked for once. async function learn (actor) { asked.add(actor) try { const res = await fetch(`${base}/scene-authors`, { credentials: 'same-origin' }) if (res.ok) Object.assign(names, await res.json()) } catch (err) { console.error('scene authors:', err) } showAuthor() } function fill (id, scene, shown) { if (id !== current.id) { current = { id, scene, loaded: '', ready: false, failed: '', dirty: false } area.value = '' status.textContent = '' retry.hidden = true } current.scene = scene showAuthor() if (scene && scene.author && !Object.hasOwn(names, scene.author) && !asked.has(scene.author)) learn(scene.author) // Read only once the panel is open, and again when the code moves // on under a text nobody has changed. if (shown && scene && scene.code && scene.code !== current.loaded && scene.code !== current.failed && !current.dirty) load(id, scene.code) sync() } on(area, 'input', () => { current.dirty = true }) on(el, 'click', async e => { const { id, scene } = current if (!id || !scene) return if (e.target.closest('[slides-scene-retry]')) return load(id, scene.code) if (e.target.closest('[slides-scene-preview]')) { preview(id, name => postPreview({ action: `${base}/scenes/preview`, target: name, html: area.value })) return } if (!e.target.closest('[slides-scene-save]') || busy || !current.ready) return busy = true sync() status.textContent = '' const text = area.value try { const ref = await save({ text }) if (current.id !== id) return await commit([{ op: 'set_scene', id, code: ref }]) if (area.value === text) { current.dirty = false current.loaded = ref } } catch (err) { const code = err instanceof UploadError ? err.code : 'failed' if (!(err instanceof UploadError)) console.error('scene code:', err) if (current.id === id) status.textContent = refusalText(code, scene.name, texts) } finally { busy = false sync() } }) return { fill, destroy () { abort.abort() } } }