| 1 | // fixtures/scene-code.mjs — a scene's code, edited by hand (scenes and |
| 2 | // clips spec §5, "Code"; §8 call 6): the bundle's text in a plain text |
| 3 | // field, with who last changed it; Preview, which runs the unsaved text |
| 4 | // in the block's own frame; and Save code, which stores it as a new |
| 5 | // bundle and names that as the scene's code. |
| 6 | // |
| 7 | // Preview posts the text as a form's one field, html, to the preview |
| 8 | // route (scenes.go's previewScene), its target the block's frame by |
| 9 | // name: the route answers it under the sealed policy, so a draft runs |
| 10 | // exactly as the saved bundle will, and nothing is stored. The frame is |
| 11 | // made for it afresh (scene-layer.mjs's preview), and goes back to the |
| 12 | // saved code once the block is chosen again or the scene changes. |
| 13 | // |
| 14 | // Save is a picture's upload with text/html as its type (uploads.mjs's |
| 15 | // flow, editor-entry.js's requests): sign, PUT, register, which reads the |
| 16 | // bytes back and refuses anything but one HTML document of at most |
| 17 | // 2 MiB; then one set_scene{code}, its author the server's to stamp |
| 18 | // (this person, which the author line then says). A refusal is said in |
| 19 | // the page's words, the scene's name in them. Code that did not load |
| 20 | // says so, with Try again, and cannot be saved over until it has. An |
| 21 | // author the page did not name is asked for (GET /d/{sqid}/scene-authors). |
| 22 | // |
| 23 | // mountSceneCode({el, base, labels, texts, commit, save, preview}) → |
| 24 | // {fill(id, scene, shown), destroy()}. el is [slides-scene-code]; |
| 25 | // save({text}) the request seams' saveSceneCode; preview(id, submit) |
| 26 | // remakes the scene's frame and calls submit(frameName). |
| 27 | import { UploadError } from './uploads.mjs' |
| 28 | |
| 29 | /** The most a bundle may be (scenes.go's maxSceneBytes). */ |
| 30 | export const MAX_CODE = 2 * 1024 * 1024 |
| 31 | const NAME = 'scene.html' |
| 32 | |
| 33 | /** text stored as a scene bundle through the seams: its ref. Throws an UploadError. */ |
| 34 | export async function saveSceneCode ({ text, sign, put, register, hash }) { |
| 35 | const blob = new Blob([text], { type: 'text/html' }) |
| 36 | if (blob.size === 0) throw new UploadError('not_html') |
| 37 | if (blob.size > MAX_CODE) throw new UploadError('too_large') |
| 38 | const signed = await sign({ name: NAME, size: blob.size, type: 'text/html', hash: await hash(blob) }) |
| 39 | if (!signed || !signed.url || !signed.ref) throw new UploadError('failed') |
| 40 | await put(signed.url, blob, signed.headers || {}) |
| 41 | const record = await register({ ref: signed.ref, name: NAME }) |
| 42 | if (!record || record.kind !== 'scene' || !record.ref) throw new UploadError('failed') |
| 43 | return record.ref |
| 44 | } |
| 45 | |
| 46 | /** A refused save in the page's words: texts {refused, refusedBig, failed}, name the scene's. */ |
| 47 | export function refusalText (code, name, texts) { |
| 48 | if (code === 'not_html') return (texts.refused || '').replace('{name}', name) |
| 49 | if (code === 'too_large') return (texts.refusedBig || '').replace('{name}', name) |
| 50 | return texts.failed || '' |
| 51 | } |
| 52 | |
| 53 | /** "Last changed by {name}" for actor, or '' when nobody is known by that actor. */ |
| 54 | export function authorLine (actor, labels, text) { |
| 55 | const name = actor && labels && Object.hasOwn(labels, actor) ? labels[actor] : '' |
| 56 | return name ? text.replace('{name}', name) : '' |
| 57 | } |
| 58 | |
| 59 | /** Posts html to action in a form whose target is the frame named target (the sealed preview route). */ |
| 60 | export function postPreview ({ doc = document, action, target, html }) { |
| 61 | const form = doc.createElement('form') |
| 62 | form.method = 'post' |
| 63 | form.action = action |
| 64 | form.enctype = 'multipart/form-data' |
| 65 | form.target = target |
| 66 | form.hidden = true |
| 67 | const field = doc.createElement('textarea') |
| 68 | field.name = 'html' |
| 69 | field.value = html |
| 70 | form.append(field) |
| 71 | doc.body.append(form) |
| 72 | form.submit() |
| 73 | form.remove() |
| 74 | } |
| 75 | |
| 76 | export function mountSceneCode ({ el, base, labels = {}, texts = {}, commit, save, preview }) { |
| 77 | if (!el) return { fill () {}, destroy () {} } |
| 78 | const area = el.querySelector('textarea') |
| 79 | const status = el.querySelector('[slides-scene-status]') |
| 80 | const author = el.querySelector('[slides-scene-author]') |
| 81 | const saveBtn = el.querySelector('[slides-scene-save]') |
| 82 | const retry = el.querySelector('[slides-scene-retry]') |
| 83 | // The scene shown; the code its text was read from (ready once it |
| 84 | // has been), or that could not be read; whether the person has |
| 85 | // changed the text since. |
| 86 | let current = { id: '', scene: null, loaded: '', ready: false, failed: '', dirty: false } |
| 87 | let busy = false |
| 88 | const names = { ...labels } |
| 89 | const asked = new Set() |
| 90 | const abort = new AbortController() |
| 91 | const on = (node, type, fn) => node.addEventListener(type, fn, { signal: abort.signal }) |
| 92 | const sync = () => { saveBtn.disabled = busy || !current.ready } |
| 93 | |
| 94 | // Code that did not come is not empty code: the line says so with Try |
| 95 | // again, and Save stays off until this code's text has been read, so |
| 96 | // an older text is never saved over newer code. |
| 97 | async function load (id, ref) { |
| 98 | current.loaded = ref |
| 99 | current.failed = '' |
| 100 | current.ready = false |
| 101 | retry.hidden = true |
| 102 | sync() |
| 103 | try { |
| 104 | const res = await fetch(`${base}/scenes/${encodeURIComponent(id)}/${encodeURIComponent(ref)}`, { credentials: 'same-origin' }) |
| 105 | if (!res.ok) throw new Error(`scene code: ${res.status}`) |
| 106 | const text = await res.text() |
| 107 | if (current.id !== id || current.loaded !== ref) return |
| 108 | if (!current.dirty) area.value = text |
| 109 | current.ready = true |
| 110 | if (status.textContent === texts.loadFailed) status.textContent = '' |
| 111 | } catch (err) { |
| 112 | console.error('scene code:', err) |
| 113 | if (current.id !== id || current.loaded !== ref) return |
| 114 | current.loaded = '' |
| 115 | current.failed = ref |
| 116 | current.ready = false |
| 117 | status.textContent = texts.loadFailed || '' |
| 118 | retry.hidden = false |
| 119 | } |
| 120 | sync() |
| 121 | } |
| 122 | |
| 123 | function showAuthor () { |
| 124 | const scene = current.scene |
| 125 | const line = scene ? authorLine(scene.author, names, texts.author || '') : '' |
| 126 | author.textContent = line |
| 127 | author.hidden = !line |
| 128 | } |
| 129 | |
| 130 | // An author the page was not told of (who changed the code while it |
| 131 | // was open) is asked for once. |
| 132 | async function learn (actor) { |
| 133 | asked.add(actor) |
| 134 | try { |
| 135 | const res = await fetch(`${base}/scene-authors`, { credentials: 'same-origin' }) |
| 136 | if (res.ok) Object.assign(names, await res.json()) |
| 137 | } catch (err) { |
| 138 | console.error('scene authors:', err) |
| 139 | } |
| 140 | showAuthor() |
| 141 | } |
| 142 | |
| 143 | function fill (id, scene, shown) { |
| 144 | if (id !== current.id) { |
| 145 | current = { id, scene, loaded: '', ready: false, failed: '', dirty: false } |
| 146 | area.value = '' |
| 147 | status.textContent = '' |
| 148 | retry.hidden = true |
| 149 | } |
| 150 | current.scene = scene |
| 151 | showAuthor() |
| 152 | if (scene && scene.author && !Object.hasOwn(names, scene.author) && !asked.has(scene.author)) learn(scene.author) |
| 153 | // Read only once the panel is open, and again when the code moves |
| 154 | // on under a text nobody has changed. |
| 155 | if (shown && scene && scene.code && scene.code !== current.loaded && scene.code !== current.failed && !current.dirty) load(id, scene.code) |
| 156 | sync() |
| 157 | } |
| 158 | |
| 159 | on(area, 'input', () => { current.dirty = true }) |
| 160 | on(el, 'click', async e => { |
| 161 | const { id, scene } = current |
| 162 | if (!id || !scene) return |
| 163 | if (e.target.closest('[slides-scene-retry]')) return load(id, scene.code) |
| 164 | if (e.target.closest('[slides-scene-preview]')) { |
| 165 | preview(id, name => postPreview({ action: `${base}/scenes/preview`, target: name, html: area.value })) |
| 166 | return |
| 167 | } |
| 168 | if (!e.target.closest('[slides-scene-save]') || busy || !current.ready) return |
| 169 | busy = true |
| 170 | sync() |
| 171 | status.textContent = '' |
| 172 | const text = area.value |
| 173 | try { |
| 174 | const ref = await save({ text }) |
| 175 | if (current.id !== id) return |
| 176 | await commit([{ op: 'set_scene', id, code: ref }]) |
| 177 | if (area.value === text) { |
| 178 | current.dirty = false |
| 179 | current.loaded = ref |
| 180 | } |
| 181 | } catch (err) { |
| 182 | const code = err instanceof UploadError ? err.code : 'failed' |
| 183 | if (!(err instanceof UploadError)) console.error('scene code:', err) |
| 184 | if (current.id === id) status.textContent = refusalText(code, scene.name, texts) |
| 185 | } finally { |
| 186 | busy = false |
| 187 | sync() |
| 188 | } |
| 189 | }) |
| 190 | |
| 191 | return { fill, destroy () { abort.abort() } } |
| 192 | } |
| 193 | |