oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1import { test } from 'node:test'
2import assert from 'node:assert/strict'
3import * as Y from 'yjs'
4
5import { createAssist, buildRequest, readAnswer, errorWord, AssistError, ERROR_WORDS } from './assist.mjs'
6import { mountAssist } from './assist-panel.mjs'
7import { applyOps, view } from './ops.mjs'
8import { el, withDocument } from './dom-stub.mjs'
9
10// --- the request ---
11
12test('a request is the trimmed prompt, the scope, the slide and the model', () => {
13 assert.deepEqual(buildRequest({ prompt: ' punchier please \n', scope: 'slide', slide: 's1', model: 'm' }),
14 { prompt: 'punchier please', scope: 'slide', slide: 's1', model: 'm' })
15 // The whole deck carries no slide, whatever the stage shows.
16 assert.deepEqual(buildRequest({ prompt: 'ten slides on tea', scope: 'deck', slide: 's1', model: 'm' }),
17 { prompt: 'ten slides on tea', scope: 'deck', model: 'm' })
18})
19
20test('an empty, blank or over-long prompt, or "this slide" with none, is never sent', () => {
21 for (const prompt of ['', ' ', 'x'.repeat(2001)]) {
22 assert.throws(() => buildRequest({ prompt, scope: 'deck' }), e => e instanceof AssistError && e.word === 'prompt')
23 }
24 // Counted in characters, not UTF-16 units: 2000 emoji is allowed.
25 assert.doesNotThrow(() => buildRequest({ prompt: '🍵'.repeat(2000), scope: 'deck' }))
26 assert.throws(() => buildRequest({ prompt: 'hi', scope: 'slide', slide: '' }), e => e.word === 'noslide')
27})
28
29test('server words map onto the panel\'s strings, and anything else is generic', () => {
30 assert.equal(errorWord('too_large'), 'too-large')
31 assert.equal(errorWord('rate'), 'rate')
32 assert.equal(errorWord('internal'), 'generic')
33 assert.equal(errorWord(undefined), 'generic')
34 for (const w of ERROR_WORDS) assert.equal(new AssistError(w).word, w)
35})
36
37// --- reading the answer ---
38
39const response = (status, body) => ({
40 ok: status >= 200 && status < 300,
41 status,
42 json: async () => { if (typeof body === 'string') throw new SyntaxError('not json'); return body }
43})
44
45test('an answer must be a list of op objects; anything else is generic', async () => {
46 assert.deepEqual(await readAnswer(response(200, { ops: [{ op: 'set_meta', title: 'T' }], summary: 'S', focus: 'f' })),
47 { ops: [{ op: 'set_meta', title: 'T' }], summary: 'S', focus: 'f' })
48 for (const body of [{ summary: 'no ops' }, { ops: 'nope' }, { ops: [1] }, { ops: [[]] }, '<html>']) {
49 await assert.rejects(readAnswer(response(200, body)), e => e.word === 'generic')
50 }
51 await assert.rejects(readAnswer(response(429, { error: 'rate' })), e => e.word === 'rate')
52 await assert.rejects(readAnswer(response(404, '<html>not found</html>')), e => e.word === 'generic')
53})
54
55// --- the client ---
56
57function rig (over = {}) {
58 const calls = []
59 const assist = createAssist({
60 url: '/d/abc/assist',
61 fetch: async (url, init) => { calls.push(['fetch', url, init]); return response(200, { ops: [{ op: 'add_slide', id: 'n1', layout: 'flow' }], summary: 'Added a slide.', focus: 'n1' }) },
62 commit: async ops => { calls.push(['commit', ops]); return { applied: true, error: null, step: 'step-1' } },
63 flush: async () => { calls.push(['flush']); return true },
64 undoStep: async step => { calls.push(['undo', step]); return true },
65 ...over
66 })
67 return { assist, calls }
68}
69
70test('an answer is posted as JSON, applied through commit, saved, and focused', async () => {
71 const { assist, calls } = rig()
72 const out = await assist.ask({ prompt: 'a slide', scope: 'deck', model: 'm' })
73 assert.deepEqual(out, { state: 'applied', summary: 'Added a slide.', focus: 'n1' })
74 // This tab's unsaved edits go first, so the server's deck is the one
75 // on screen; then the answer is committed and saved.
76 assert.deepEqual(calls.map(c => c[0]), ['flush', 'fetch', 'commit', 'flush'])
77 const [, url, init] = calls[1]
78 assert.equal(url, '/d/abc/assist')
79 assert.equal(init.method, 'POST')
80 assert.equal(init.credentials, 'same-origin')
81 assert.equal(init.headers['Content-Type'], 'application/json')
82 assert.deepEqual(JSON.parse(init.body), { prompt: 'a slide', scope: 'deck', model: 'm' })
83 assert.deepEqual(calls[2][1], [{ op: 'add_slide', id: 'n1', layout: 'flow' }])
84 assert.equal(assist.canUndo, true)
85})
86
87test('a slide is focused only once its save is acknowledged', async () => {
88 const { assist } = rig({ flush: async () => false })
89 const out = await assist.ask({ prompt: 'a slide', scope: 'deck' })
90 assert.equal(out.state, 'applied')
91 assert.equal(out.focus, '')
92})
93
94test('no ops is "nothing", and nothing is committed', async () => {
95 const { assist, calls } = rig({ fetch: async () => response(200, { ops: [], summary: 'There is nothing to split.' }) })
96 assert.deepEqual(await assist.ask({ prompt: 'split', scope: 'slide', slide: 's' }), { state: 'nothing', summary: 'There is nothing to split.', focus: '' })
97 assert.deepEqual(calls.map(c => c[0]), ['flush'], 'only the flush before asking; nothing committed')
98 assert.equal(assist.canUndo, false)
99})
100
101test('every failure is a word, and nothing is applied', async () => {
102 const cases = [
103 [{ fetch: async () => { throw new TypeError('offline') } }, 'unavailable'],
104 [{ fetch: async () => response(502, { error: 'unavailable' }) }, 'unavailable'],
105 [{ fetch: async () => response(504, { error: 'timeout' }) }, 'timeout'],
106 [{ fetch: async () => response(413, { error: 'too_large' }) }, 'too-large'],
107 [{ fetch: async () => response(422, { error: 'refused' }) }, 'refused'],
108 [{ fetch: async () => response(500, '<html>') }, 'generic'],
109 // This tab's deck moved: the ops module refused the batch whole.
110 [{ commit: async () => ({ applied: false, error: new Error('op 0: no slide "x"'), step: null }) }, 'changed'],
111 // A font the batch needs could not be had.
112 [{ commit: async () => ({ applied: false, error: null, step: null }) }, 'fonts'],
113 [{ commit: async () => { throw new Error('boom') } }, 'generic']
114 ]
115 for (const [over, word] of cases) {
116 const errors = console.error
117 console.error = () => {}
118 try {
119 const { assist } = rig(over)
120 assert.deepEqual(await assist.ask({ prompt: 'x', scope: 'deck' }), { state: 'error', word })
121 assert.equal(assist.canUndo, false)
122 } finally {
123 console.error = errors
124 }
125 }
126 const { assist, calls } = rig()
127 assert.deepEqual(await assist.ask({ prompt: '', scope: 'deck' }), { state: 'error', word: 'prompt' })
128 assert.equal(calls.length, 0, 'an empty prompt reaches no network')
129})
130
131test('undo takes back the answer\'s own step, once', async () => {
132 const { assist, calls } = rig()
133 await assist.ask({ prompt: 'x', scope: 'deck' })
134 assert.equal(await assist.undo(), true)
135 assert.deepEqual(calls.at(-1), ['undo', 'step-1'])
136 assert.equal(await assist.undo(), false, 'a second press undoes nothing more')
137 const later = rig({ undoStep: async () => false })
138 await later.assist.ask({ prompt: 'x', scope: 'deck' })
139 assert.equal(await later.assist.undo(), false, 'a step something came after is not undone from here')
140})
141
142// --- the server's batch shape applies in the browser ---
143
144test('a batch shaped as the server answers it applies through ops.mjs', () => {
145 const doc = new Y.Doc()
146 applyOps(doc, [{ op: 'add_slide', id: 'aaaaaaaaaaaa', layout: 'flow', template: 'title' }])
147 // What assist_ops.go sends: minted ids, only each op's own keys,
148 // "after" null or a real id, props as the model wrote them.
149 applyOps(doc, [
150 { op: 'set_meta', title: 'Tea', theme: 'forest', accent: null },
151 { op: 'add_block', slide: 'aaaaaaaaaaaa', id: 'bbbbbbbbbbbb', type: 'heading', region: 'heading', props: { level: 1 }, markdown: 'Tea' },
152 { op: 'add_slide', id: 'cccccccccccc', layout: 'flow', template: 'title-body', after: 'aaaaaaaaaaaa' },
153 { op: 'add_block', slide: 'cccccccccccc', id: 'dddddddddddd', type: 'list', region: 'body', props: { style: 'bullet' }, markdown: '- China\n- **India**' },
154 { op: 'set_notes', id: 'cccccccccccc', markdown: 'Kenya exports the most.' },
155 { op: 'set_slide', id: 'cccccccccccc', transition: 'fade' },
156 { op: 'duplicate_slide', id: 'cccccccccccc', new_id: 'eeeeeeeeeeee', new_block_ids: ['ffffffffffff'] },
157 { op: 'set_text', slide: 'eeeeeeeeeeee', id: 'ffffffffffff', markdown: '- Kenya' },
158 { op: 'move_slide', id: 'eeeeeeeeeeee', after: null }
159 ], 'local')
160 const v = view(doc)
161 assert.equal(v.meta.title, 'Tea')
162 assert.deepEqual(v.slides.map(s => s.id), ['eeeeeeeeeeee', 'aaaaaaaaaaaa', 'cccccccccccc'])
163 assert.equal(v.slides[2].transition, 'fade')
164 assert.equal(v.slides[2].blocks[0].text.length, 2)
165})
166
167// --- the panel ---
168
169function panelRig ({ result = { state: 'applied', summary: 'Made it punchier.', focus: '' }, canUndo = true, slide = 's1' } = {}) {
170 const { document, restore } = withDocument()
171 const prompt = el('textarea', { name: 'slides-assist-prompt' })
172 prompt.value = 'punchier'
173 const scope = el('select'); scope.value = 'slide'
174 const model = el('select'); model.value = 'm'
175 const form = el('form', { 'slides-assist-form': '' }, [prompt])
176 form.elements = { namedItem: n => ({ 'slides-assist-prompt': prompt, 'slides-assist-scope': scope, 'slides-assist-model': model })[n] }
177 const askBtn = el('button', { 'slides-assist-ask': '' })
178 const summary = el('p', { 'slides-assist-summary': '' })
179 const note = el('p', { 'slides-assist-note': '' })
180 const outcome = el('div', { 'slides-assist-outcome': '' }, [summary, note])
181 const undo = el('button', { 'slides-assist-undo': '' }); undo.hidden = true
182 const panel = el('section', {
183 'slides-assist': '', 'data-max-prompt': '2000',
184 'data-text-working': 'Working', 'data-text-applied': 'Applied', 'data-text-nothing': 'Nothing',
185 'data-text-undone': 'Undone', 'data-text-undo-later': 'Later', 'data-text-error-rate': 'Too many', 'data-text-error-generic': 'Oops'
186 }, [form, askBtn, outcome, undo])
187 let hidden = 0
188 panel.hidePopover = () => { hidden++ }
189 const toggle = el('button', { 'slides-assist-toggle': '', 'aria-pressed': 'false' })
190 const root = el('div', {}, [toggle, panel])
191 const asked = []
192 const went = []
193 let undone = 0
194 const assist = {
195 ask: async req => { asked.push(req); assert.equal(askBtn.getAttribute('aria-busy'), 'true'); assert.equal(askBtn.getAttribute('aria-disabled'), 'true'); return result },
196 undo: async () => { undone++; return true },
197 get canUndo () { return canUndo }
198 }
199 const mount = mountAssist({ root, assist, getSlideId: () => slide, go: id => went.push(id), hold: 0 })
200 const fire = async (node, type, ev = {}) => {
201 for (const l of node.listeners.filter(l => l.type === type)) await l.fn({ preventDefault () {}, stopPropagation () {}, ...ev })
202 }
203 return { document, restore, mount, root, panel, toggle, form, askBtn, summary, note, outcome, undo, prompt, scope, asked, went, fire, get hidden () { return hidden }, get undone () { return undone } }
204}
205
206test('the toggle is lit while the panel is open, and opening focuses the prompt', async () => {
207 const r = panelRig()
208 try {
209 await r.fire(r.panel, 'toggle', { newState: 'open' })
210 assert.equal(r.toggle.getAttribute('aria-pressed'), 'true')
211 assert.equal(r.document.activeElement, r.prompt)
212 assert.equal(r.prompt.maxLength, 2000)
213 await r.fire(r.panel, 'toggle', { newState: 'closed' })
214 assert.equal(r.toggle.getAttribute('aria-pressed'), 'false')
215 assert.equal(r.document.activeElement, r.toggle, 'focus leaves the closed panel for its toggle')
216 await r.fire(r.panel, 'keydown', { key: 'Escape' })
217 assert.equal(r.hidden, 1)
218 } finally { r.restore() }
219})
220
221test('a deck with no slide opens on "the whole deck"', async () => {
222 const r = panelRig({ slide: '' })
223 try {
224 await r.fire(r.panel, 'toggle', { newState: 'open' })
225 assert.equal(r.scope.value, 'deck')
226 } finally { r.restore() }
227})
228
229test('asking is busy, then says what was done and offers Undo', async () => {
230 const r = panelRig({ result: { state: 'applied', summary: 'Added two slides.', focus: 'new1' } })
231 try {
232 await r.fire(r.form, 'submit')
233 assert.deepEqual(r.asked, [{ prompt: 'punchier', scope: 'slide', slide: 's1', model: 'm' }])
234 assert.equal(r.askBtn.hasAttribute('aria-busy'), false)
235 assert.equal(r.askBtn.hasAttribute('aria-disabled'), false)
236 assert.equal(r.askBtn.querySelector('[rst-spin]'), null, 'the spinner is gone')
237 assert.equal(r.summary.textContent, 'Added two slides.')
238 assert.equal(r.note.textContent, 'Applied')
239 assert.equal(r.undo.hidden, false)
240 assert.deepEqual(r.went, ['new1'])
241 await r.fire(r.undo, 'click')
242 assert.equal(r.undone, 1)
243 assert.equal(r.note.textContent, 'Undone')
244 assert.equal(r.undo.hidden, true)
245 } finally { r.restore() }
246})
247
248test('an error is said in the catalog\'s words, marked, and offers no Undo', async () => {
249 const r = panelRig({ result: { state: 'error', word: 'rate' } })
250 try {
251 await r.fire(r.form, 'submit')
252 assert.equal(r.note.textContent, 'Too many')
253 assert.equal(r.outcome.getAttribute('data-tone'), 'error')
254 assert.equal(r.undo.hidden, true)
255 } finally { r.restore() }
256 const g = panelRig({ result: { state: 'error', word: 'noslide' } })
257 try {
258 await g.fire(g.form, 'submit')
259 assert.equal(g.note.textContent, 'Oops', 'a word with no string falls back to the generic one')
260 } finally { g.restore() }
261})
262
263test('destroy takes every listener away', () => {
264 const r = panelRig()
265 try {
266 r.mount.destroy()
267 for (const node of [r.panel, r.form, r.undo]) assert.equal(node.listeners.length, 0)
268 } finally { r.restore() }
269})
270