oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/scene-data.mjs — a scene's data, edited by hand (scenes and
2// clips spec §5, "Data"): a table when the data is a list of objects
3// whose fields are scalars, or holds one as a top-level value, a row
4// per object and a column per key;
5// otherwise, and on asking, the JSON itself. Every edit writes the
6// whole value with one set_scene{data} (data is replaced whole, plan
7// call 9), and the block's frame is made afresh with it, a new init
8// (scene-layer.mjs: a frame's signature holds its data).
9//
10// A cell keeps its column's kind: a number stays a number when what is
11// typed is one, true and false stay booleans, anything else is text. A
12// new row takes each column's empty value: 0, false or "".
13//
14// Data is at most 960 KiB of canonical JSON (MAX_SCENE_DATA), and its
15// set_scene must also fit one live update (ops.mjs measures the update
16// before anything is written, and refuses it as tooBig): number-heavy
17// data encodes larger than its JSON. An edit past either is not
18// written: it stays in its field, marked invalid, and the panel says
19// why ([slides-scene-data-big]) until an edit fits.
20//
21// mountSceneData({el, commit}) → {fill(id, scene), destroy()}; el is
22// the card's [slides-scene-data]. Every word on it is the page's.
23
24import { canonicalJSON, utf8 } from './scene-version.mjs'
25import { MAX_SCENE_DATA } from './scenes.mjs'
26
27/** Whether value is past the most a scene's data may be, in UTF-8 bytes of its canonical JSON. */
28export const dataTooBig = value => utf8(canonicalJSON(value)).length > MAX_SCENE_DATA
29
30const isObject = v => v !== null && typeof v === 'object' && !Array.isArray(v)
31const scalar = v => v === null || ['string', 'number', 'boolean'].includes(typeof v)
32const isRow = v => isObject(v) && Object.values(v).every(scalar)
33
34function rowsTable (rows) {
35 if (!Array.isArray(rows) || rows.length === 0 || !rows.every(isRow)) return null
36 // In code point order: the order a scene's keys are stored in is not
37 // the order they were written in.
38 const cols = [...new Set(rows.flatMap(r => Object.keys(r)))].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
39 return cols.length ? { rows, cols } : null
40}
41
42/** The table data is: {key, rows, cols}, key null for a list at the top, or null when it is not one. */
43export function tableOf (data) {
44 const top = rowsTable(data)
45 if (top) return { key: null, ...top }
46 if (!isObject(data)) return null
47 for (const [key, v] of Object.entries(data)) {
48 const t = rowsTable(v)
49 if (t) return { key, ...t }
50 }
51 return null
52}
53
54/** The first value a column has, which says its kind. */
55const sample = (t, col) => t.rows.map(r => r[col]).find(v => v !== undefined && v !== null)
56
57function valueFor (before, text) {
58 if (typeof before === 'number') return text.trim() !== '' && Number.isFinite(Number(text)) ? Number(text) : text
59 if (typeof before === 'boolean') return text === 'true' ? true : text === 'false' ? false : text
60 return text
61}
62
63const withRows = (data, t, rows) => (t.key === null ? rows : { ...data, [t.key]: rows })
64
65/** data with row i's col set from text, kept the kind its column has. */
66export function withCell (data, t, i, col, text) {
67 const rows = t.rows.map((r, j) => (j === i ? { ...r, [col]: valueFor(r[col] ?? sample(t, col), text) } : r))
68 return withRows(data, t, rows)
69}
70
71/** data with a row added, each column empty for its kind. */
72export function withRow (data, t) {
73 const row = {}
74 for (const col of t.cols) {
75 const s = sample(t, col)
76 row[col] = typeof s === 'number' ? 0 : typeof s === 'boolean' ? false : ''
77 }
78 return withRows(data, t, [...t.rows, row])
79}
80
81/** data with row i taken out. */
82export function withoutRow (data, t, i) {
83 return withRows(data, t, t.rows.filter((_, j) => j !== i))
84}
85
86/** text as JSON: {ok: true, value}, or {ok: false}. */
87export function parseData (text) {
88 try {
89 return { ok: true, value: JSON.parse(text) }
90 } catch {
91 return { ok: false }
92 }
93}
94
95const shown = v => (v === undefined || v === null ? '' : String(v))
96
97export function mountSceneData ({ el, commit }) {
98 if (!el) return { fill () {}, destroy () {} }
99 const views = el.querySelector('[slides-scene-data-views]')
100 const tableEl = el.querySelector('[slides-scene-table]')
101 const table = tableEl.querySelector('table')
102 const removeTemplate = tableEl.querySelector('template[slides-scene-remove-template]')
103 const jsonEl = el.querySelector('[slides-scene-json]')
104 const json = jsonEl.querySelector('textarea')
105 const invalid = jsonEl.querySelector('[slides-scene-invalid]')
106 const big = el.querySelector('[slides-scene-data-big]')
107 let current = { id: '', data: null, table: null, drawn: '', tableKey: '', jsonKey: '' }
108 const abort = new AbortController()
109 const on = (node, type, fn) => node.addEventListener(type, fn, { signal: abort.signal })
110
111 // The edit, from field: written, or kept in its field past the limit.
112 function refuse (over, field) {
113 big.hidden = !over
114 for (const f of el.querySelectorAll('[aria-invalid="true"]')) f.removeAttribute('aria-invalid')
115 if (over && field) field.setAttribute('aria-invalid', 'true')
116 }
117 function write (data, field) {
118 const over = dataTooBig(data)
119 refuse(over, field)
120 if (over) return
121 commit([{ op: 'set_scene', id: current.id, data }], {
122 onError: err => (err && err.tooBig ? refuse(true, field) : console.error('ops:', err))
123 })
124 }
125 const view = () => (views.querySelector('input:checked') || {}).value || 'table'
126
127 function drawTable (t) {
128 const head = document.createElement('tr')
129 for (const col of [...t.cols, '']) {
130 const th = document.createElement('th')
131 th.scope = 'col'
132 th.textContent = col
133 head.append(th)
134 }
135 table.tHead.replaceChildren(head)
136 table.tBodies[0].replaceChildren(...t.rows.map((r, i) => {
137 const tr = document.createElement('tr')
138 for (const col of t.cols) {
139 const td = document.createElement('td')
140 const input = document.createElement('input')
141 input.type = 'text'
142 input.setAttribute('rst-input', 'short')
143 input.dataset.row = String(i)
144 input.dataset.col = col
145 input.value = shown(r[col])
146 input.setAttribute('aria-label', `${col} ${i + 1}`)
147 td.append(input)
148 tr.append(td)
149 }
150 const td = document.createElement('td')
151 const remove = removeTemplate.content.firstElementChild.cloneNode(true)
152 remove.dataset.row = String(i)
153 td.append(remove)
154 tr.append(td)
155 return tr
156 }))
157 }
158
159 function showView () {
160 const asTable = !!current.table && view() === 'table'
161 views.hidden = !current.table
162 tableEl.hidden = !asTable
163 jsonEl.hidden = asTable
164 }
165
166 function fill (id, scene) {
167 const data = scene && scene.data !== undefined ? scene.data : null
168 const drawn = JSON.stringify(data)
169 if (id !== current.id) {
170 invalid.hidden = true
171 big.hidden = true
172 json.removeAttribute('aria-invalid')
173 current = { ...current, tableKey: '', jsonKey: '' }
174 }
175 current = { ...current, id, data, drawn, table: tableOf(data) }
176 // Never under the person: a cell they are typing in, or the JSON,
177 // keeps what they typed, and a JSON they were told is not JSON
178 // stays; each is drawn again once they have left it.
179 const typing = table.contains(document.activeElement) && document.activeElement.matches('input')
180 if (current.table && !typing && current.tableKey !== drawn) {
181 drawTable(current.table)
182 current.tableKey = drawn
183 }
184 if (document.activeElement !== json && invalid.hidden && big.hidden && current.jsonKey !== drawn) {
185 json.value = JSON.stringify(data, null, 2)
186 current.jsonKey = drawn
187 }
188 showView()
189 }
190
191 on(views, 'change', showView)
192 on(tableEl, 'change', e => {
193 const input = e.target.closest('input[data-col]')
194 if (!input || !current.table) return
195 write(withCell(current.data, current.table, Number(input.dataset.row), input.dataset.col, input.value), input)
196 })
197 on(tableEl, 'click', e => {
198 const t = current.table
199 if (!t) return
200 if (e.target.closest('[slides-scene-add]')) write(withRow(current.data, t), null)
201 const remove = e.target.closest('[slides-scene-remove]')
202 if (remove) write(withoutRow(current.data, t, Number(remove.dataset.row)), null)
203 })
204 on(json, 'change', () => {
205 const got = parseData(json.value)
206 invalid.hidden = got.ok
207 json.setAttribute('aria-invalid', String(!got.ok))
208 if (!got.ok) big.hidden = true
209 else if (JSON.stringify(got.value) !== current.drawn) write(got.value, json)
210 else big.hidden = true
211 })
212
213 return { fill, destroy () { abort.abort() } }
214}
215