// fixtures/scene-data.mjs — a scene's data, edited by hand (scenes and // clips spec §5, "Data"): a table when the data is a list of objects // whose fields are scalars, or holds one as a top-level value, a row // per object and a column per key; // otherwise, and on asking, the JSON itself. Every edit writes the // whole value with one set_scene{data} (data is replaced whole, plan // call 9), and the block's frame is made afresh with it, a new init // (scene-layer.mjs: a frame's signature holds its data). // // A cell keeps its column's kind: a number stays a number when what is // typed is one, true and false stay booleans, anything else is text. A // new row takes each column's empty value: 0, false or "". // // Data is at most 960 KiB of canonical JSON (MAX_SCENE_DATA), and its // set_scene must also fit one live update (ops.mjs measures the update // before anything is written, and refuses it as tooBig): number-heavy // data encodes larger than its JSON. An edit past either is not // written: it stays in its field, marked invalid, and the panel says // why ([slides-scene-data-big]) until an edit fits. // // mountSceneData({el, commit}) → {fill(id, scene), destroy()}; el is // the card's [slides-scene-data]. Every word on it is the page's. import { canonicalJSON, utf8 } from './scene-version.mjs' import { MAX_SCENE_DATA } from './scenes.mjs' /** Whether value is past the most a scene's data may be, in UTF-8 bytes of its canonical JSON. */ export const dataTooBig = value => utf8(canonicalJSON(value)).length > MAX_SCENE_DATA const isObject = v => v !== null && typeof v === 'object' && !Array.isArray(v) const scalar = v => v === null || ['string', 'number', 'boolean'].includes(typeof v) const isRow = v => isObject(v) && Object.values(v).every(scalar) function rowsTable (rows) { if (!Array.isArray(rows) || rows.length === 0 || !rows.every(isRow)) return null // In code point order: the order a scene's keys are stored in is not // the order they were written in. const cols = [...new Set(rows.flatMap(r => Object.keys(r)))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) return cols.length ? { rows, cols } : null } /** The table data is: {key, rows, cols}, key null for a list at the top, or null when it is not one. */ export function tableOf (data) { const top = rowsTable(data) if (top) return { key: null, ...top } if (!isObject(data)) return null for (const [key, v] of Object.entries(data)) { const t = rowsTable(v) if (t) return { key, ...t } } return null } /** The first value a column has, which says its kind. */ const sample = (t, col) => t.rows.map(r => r[col]).find(v => v !== undefined && v !== null) function valueFor (before, text) { if (typeof before === 'number') return text.trim() !== '' && Number.isFinite(Number(text)) ? Number(text) : text if (typeof before === 'boolean') return text === 'true' ? true : text === 'false' ? false : text return text } const withRows = (data, t, rows) => (t.key === null ? rows : { ...data, [t.key]: rows }) /** data with row i's col set from text, kept the kind its column has. */ export function withCell (data, t, i, col, text) { const rows = t.rows.map((r, j) => (j === i ? { ...r, [col]: valueFor(r[col] ?? sample(t, col), text) } : r)) return withRows(data, t, rows) } /** data with a row added, each column empty for its kind. */ export function withRow (data, t) { const row = {} for (const col of t.cols) { const s = sample(t, col) row[col] = typeof s === 'number' ? 0 : typeof s === 'boolean' ? false : '' } return withRows(data, t, [...t.rows, row]) } /** data with row i taken out. */ export function withoutRow (data, t, i) { return withRows(data, t, t.rows.filter((_, j) => j !== i)) } /** text as JSON: {ok: true, value}, or {ok: false}. */ export function parseData (text) { try { return { ok: true, value: JSON.parse(text) } } catch { return { ok: false } } } const shown = v => (v === undefined || v === null ? '' : String(v)) export function mountSceneData ({ el, commit }) { if (!el) return { fill () {}, destroy () {} } const views = el.querySelector('[slides-scene-data-views]') const tableEl = el.querySelector('[slides-scene-table]') const table = tableEl.querySelector('table') const removeTemplate = tableEl.querySelector('template[slides-scene-remove-template]') const jsonEl = el.querySelector('[slides-scene-json]') const json = jsonEl.querySelector('textarea') const invalid = jsonEl.querySelector('[slides-scene-invalid]') const big = el.querySelector('[slides-scene-data-big]') let current = { id: '', data: null, table: null, drawn: '', tableKey: '', jsonKey: '' } const abort = new AbortController() const on = (node, type, fn) => node.addEventListener(type, fn, { signal: abort.signal }) // The edit, from field: written, or kept in its field past the limit. function refuse (over, field) { big.hidden = !over for (const f of el.querySelectorAll('[aria-invalid="true"]')) f.removeAttribute('aria-invalid') if (over && field) field.setAttribute('aria-invalid', 'true') } function write (data, field) { const over = dataTooBig(data) refuse(over, field) if (over) return commit([{ op: 'set_scene', id: current.id, data }], { onError: err => (err && err.tooBig ? refuse(true, field) : console.error('ops:', err)) }) } const view = () => (views.querySelector('input:checked') || {}).value || 'table' function drawTable (t) { const head = document.createElement('tr') for (const col of [...t.cols, '']) { const th = document.createElement('th') th.scope = 'col' th.textContent = col head.append(th) } table.tHead.replaceChildren(head) table.tBodies[0].replaceChildren(...t.rows.map((r, i) => { const tr = document.createElement('tr') for (const col of t.cols) { const td = document.createElement('td') const input = document.createElement('input') input.type = 'text' input.setAttribute('rst-input', 'short') input.dataset.row = String(i) input.dataset.col = col input.value = shown(r[col]) input.setAttribute('aria-label', `${col} ${i + 1}`) td.append(input) tr.append(td) } const td = document.createElement('td') const remove = removeTemplate.content.firstElementChild.cloneNode(true) remove.dataset.row = String(i) td.append(remove) tr.append(td) return tr })) } function showView () { const asTable = !!current.table && view() === 'table' views.hidden = !current.table tableEl.hidden = !asTable jsonEl.hidden = asTable } function fill (id, scene) { const data = scene && scene.data !== undefined ? scene.data : null const drawn = JSON.stringify(data) if (id !== current.id) { invalid.hidden = true big.hidden = true json.removeAttribute('aria-invalid') current = { ...current, tableKey: '', jsonKey: '' } } current = { ...current, id, data, drawn, table: tableOf(data) } // Never under the person: a cell they are typing in, or the JSON, // keeps what they typed, and a JSON they were told is not JSON // stays; each is drawn again once they have left it. const typing = table.contains(document.activeElement) && document.activeElement.matches('input') if (current.table && !typing && current.tableKey !== drawn) { drawTable(current.table) current.tableKey = drawn } if (document.activeElement !== json && invalid.hidden && big.hidden && current.jsonKey !== drawn) { json.value = JSON.stringify(data, null, 2) current.jsonKey = drawn } showView() } on(views, 'change', showView) on(tableEl, 'change', e => { const input = e.target.closest('input[data-col]') if (!input || !current.table) return write(withCell(current.data, current.table, Number(input.dataset.row), input.dataset.col, input.value), input) }) on(tableEl, 'click', e => { const t = current.table if (!t) return if (e.target.closest('[slides-scene-add]')) write(withRow(current.data, t), null) const remove = e.target.closest('[slides-scene-remove]') if (remove) write(withoutRow(current.data, t, Number(remove.dataset.row)), null) }) on(json, 'change', () => { const got = parseData(json.value) invalid.hidden = got.ok json.setAttribute('aria-invalid', String(!got.ok)) if (!got.ok) big.hidden = true else if (JSON.stringify(got.value) !== current.drawn) write(got.value, json) else big.hidden = true }) return { fill, destroy () { abort.abort() } } }