//go:build browser package slidestest // Editing a scene by hand in the editor (scenes and clips spec §5; // fixtures/scene-card.mjs, scene-data.mjs, scene-code.mjs): the scene // block's card (its scene, From and To, its words, the out-of-date note // and the missing pictures), the data as a table or as JSON, the code // with a live preview and Save, and a scene block's states counted in // the editor's press numbers. Every write is read back over the API. import ( "encoding/json" "net/http" "reflect" "strings" "testing" "time" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/kb" "amadan.net/oficina/slides/internal/slides/deck" ) // worldData is the World scene's data: a list of objects under a key, // which the data panel shows as a table. const worldData = `{"pieces":[{"name":"Tower","floors":3,"lit":true},{"name":"Garden","floors":0,"lit":false}]}` // sceneEditor is an editor (with an object store) on a deck holding the // scene World (editorScene; states a, b, c named A, B, C; words title // and sign; worldData) and, with two, the scene Other (one state, x), // and one canvas slide, scenecanvas1: a heading, World's block // sceneblock01 from a to c (presses 1 and 2), a text on step 1 // (scenetext001, press 3) and a text with the slide (scenetext002). type sceneEditor struct { *tidyEditor token, world, other string } type sceneEditorOpts struct { two bool // the scene Other too stills bool // a still for each of World's states, made from its version now // staleOther: Other's one still, made from its version before its // words changed (with two). staleOther bool } func openSceneEditor(t *testing.T, o sceneEditorOpts) *sceneEditor { t.Helper() se := &sceneEditor{} te := newTidyEditorWith(t, dirStore(t), 1280, 800, func(a *testApp, cookies []*http.Cookie) string { se.token = mintAgent(t, a, cookies, "scene-editor") sqid := apiDeck(t, a, se.token, "Scenes by hand") code := uploadScene(t, a, "/d/"+sqid, cookies, []byte(editorScene)) ops := []string{`{"op":"add_scene","name":"World","code":"` + code + `","states":[` + `{"id":"a","name":"A","description":"The field"},{"id":"b","name":"B","description":"The town"},` + `{"id":"c","name":"C","description":"The city"}],"words":{"title":"Vienna","sign":"Open"},"data":` + worldData + `}`} if o.two { ops = append(ops, `{"op":"add_scene","name":"Other","code":"`+code+`","states":[{"id":"x","name":"X","description":"Only"}]}`) } out := apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", se.token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) ids, _ := out["ids"].(map[string]any) se.world, _ = ids["0"].(string) if o.two { se.other, _ = ids["1"].(string) } view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, se.token, "", http.StatusOK) ops = nil for _, s := range view["slides"].([]any) { ops = append(ops, `{"op":"remove_slide","id":`+quote(s.(map[string]any)["id"].(string))+`}`) } ops = append(ops, `{"op":"add_slide","id":"scenecanvas1","layout":"canvas"}`, `{"op":"add_block","slide":"scenecanvas1","id":"sceneshead01","type":"heading","box":{"x":0.05,"y":0.03,"w":0.9,"h":0.15},"props":{"level":1},"markdown":"By hand"}`, `{"op":"add_block","slide":"scenecanvas1","id":"sceneblock01","type":"scene","box":{"x":0.05,"y":0.25,"w":0.5,"h":0.6},"props":{"scene":"`+se.world+`","from":"a","to":"c"}}`, `{"op":"add_block","slide":"scenecanvas1","id":"scenetext001","type":"text","box":{"x":0.6,"y":0.25,"w":0.35,"h":0.2},"markdown":"Later"}`, `{"op":"set_block","slide":"scenecanvas1","id":"scenetext001","step":1}`, `{"op":"add_block","slide":"scenecanvas1","id":"scenetext002","type":"text","box":{"x":0.6,"y":0.6,"w":0.35,"h":0.2},"markdown":"Last"}`) apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", se.token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) if o.stills { made := deck.SceneVersion(sceneOf(t, a, se.token, sqid, se.world)) for _, state := range []string{"a", "b", "c"} { if rec := agentCall(t, a, http.MethodPut, stillURL(sqid, se.world, state, made), se.token, onePixelPNG); rec.Code != http.StatusOK { t.Fatalf("PUT still %s: status %d\n%s", state, rec.Code, rec.Body) } } } if o.two && o.staleOther { made := deck.SceneVersion(sceneOf(t, a, se.token, sqid, se.other)) if rec := agentCall(t, a, http.MethodPut, stillURL(sqid, se.other, "x", made), se.token, onePixelPNG); rec.Code != http.StatusOK { t.Fatalf("PUT Other's still: status %d\n%s", rec.Code, rec.Body) } apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", se.token, `{"ops":[{"op":"set_scene","id":"`+se.other+`","words":{"note":"Changed"}}]}`, http.StatusOK) } return "/d/" + sqid + "/edit" }) te.rig.Run( chromedp.Navigate(te.rig.Origin+te.path), chromedp.WaitVisible(chromedp.CSS(`[slides-editor]`)), waitFor(editorBound), evalInto(new(bool), sceneWatch), ) se.tidyEditor = te return se } // scene is World (or another scene) as the API reads it. func (se *sceneEditor) scene(t *testing.T, id string) deck.Scene { t.Helper() return sceneOf(t, se.app, se.token, se.sqid(), id) } // untilScene polls the API until scene id satisfies ok, for up to 20 s. func (se *sceneEditor) untilScene(t *testing.T, id, what string, ok func(deck.Scene) bool) deck.Scene { t.Helper() deadline := time.Now().Add(20 * time.Second) for { s := se.scene(t, id) if ok(s) { return s } if time.Now().After(deadline) { raw, _ := json.Marshal(s) t.Fatalf("the scene never became %s: %s", what, raw) } time.Sleep(100 * time.Millisecond) } } // selectScene selects sceneblock01 and waits for its card. func (se *sceneEditor) selectScene(t *testing.T) { t.Helper() se.selectBoxByID(t, "sceneblock01") se.rig.Run(waitFor(`document.querySelector('[slides-scene-body]')?.checkVisibility()`)) } // sceneCardJS reads the scene block's card as a person sees it. const sceneCardJS = `(() => { const body = document.querySelector('[slides-scene-body]') const vis = el => !!el && el.checkVisibility() const text = el => vis(el) ? el.textContent.replace(/\s+/g, ' ').trim() : '' const q = s => body ? body.querySelector(s) : null const pick = q('select[name="rst-block-scene"]'), from = q('select[name="rst-block-scene-from"]'), to = q('select[name="rst-block-scene-to"]') return { Shown: vis(body), Picks: vis(pick) ? [...pick.options].map(o => o.textContent) : [], Pick: vis(pick) ? pick.value : '', Name: text(q('[slides-scene-name]')), States: vis(from) ? [...from.options].map(o => o.textContent) : [], From: vis(from) ? from.value : '', To: vis(to) ? to.value : '', Words: body ? [...body.querySelectorAll('[slides-scene-words] input')].filter(vis).map(i => i.labels[0].textContent + '=' + i.value) : [], Stale: text(q('[slides-scene-stale]')), Ask: vis(q('[slides-scene-ask]')) ? (q('[slides-scene-ask]').getAttribute('href') + ' ' + q('[slides-scene-ask]').getAttribute('target')) : '', Missing: text(q('[slides-scene-missing]')) } })()` type sceneCard struct { Shown bool Picks, States, Words []string Pick, Name, From, To string Stale, Ask, Missing string } func (se *sceneEditor) card(t *testing.T) sceneCard { t.Helper() var c sceneCard se.rig.Run(evalInto(&c, sceneCardJS)) return c } // choose picks value in the card's select named name, as a person does. func (se *sceneEditor) choose(name, value string) { se.rig.Run(chromedp.Evaluate[chromedp.Void](`(s => { s.focus(); s.value = ` + jsString(value) + `; s.dispatchEvent(new Event('change', { bubbles: true })) })(document.querySelector('[slides-scene-body] select[name="` + name + `"]'))`)) } // typeInto replaces the text of the field sel with text, typed, and // leaves it with Tab: one change. func (se *sceneEditor) typeInto(sel, text string) { se.rig.Run( chromedp.Focus(chromedp.CSS(sel)), chromedp.Evaluate[chromedp.Void](`document.activeElement.select()`), chromedp.KeyEvent(text), ) } func (se *sceneEditor) leave() { se.rig.Run(chromedp.KeyEvent(kb.Tab)) } // propsOf is block id's props on slide s as the API reads them. func propsOf(s map[string]any, id string) map[string]any { b, _ := blockOf(s, id) p, _ := b["props"].(map[string]any) return p } // TestTheSceneCardEditsWordsAndStates: a scene block's card names its // scene (a choice when the deck has several), its From and To by state // name, its words as fields, and the states with no picture. From and // To are each one set_block, kept in order; a word is written when its // field is left, not as it is typed; another scene starts at its first // state; and Insert → Scene places a block of one. func TestTheSceneCardEditsWordsAndStates(t *testing.T) { se := openSceneEditor(t, sceneEditorOpts{two: true}) se.selectScene(t) c := se.card(t) if !reflect.DeepEqual(c.Picks, []string{"Other", "World"}) || c.Pick != se.world || c.Name != "" { t.Errorf("two scenes: the card picks %v (%q) named %q, want Other and World with World chosen", c.Picks, c.Pick, c.Name) } if !reflect.DeepEqual(c.States, []string{"A", "B", "C"}) || c.From != "a" || c.To != "c" { t.Errorf("From and To: %v from %q to %q, want A B C from a to c", c.States, c.From, c.To) } if !reflect.DeepEqual(c.Words, []string{"sign=Open", "title=Vienna"}) { t.Errorf("the words are %v, want sign=Open title=Vienna", c.Words) } if c.Missing != "3 states have no picture yet." || c.Stale != "" { t.Errorf("no stills: missing %q and stale %q, want 3 states have no picture yet. and no note", c.Missing, c.Stale) } se.rig.Screen(`[slides-inspector]`, "a scene block's card") se.choose("rst-block-scene-to", "b") se.untilSlide(t, se.token, "scenecanvas1", "to b", func(s map[string]any) bool { p := propsOf(s, "sceneblock01") return p["from"] == "a" && p["to"] == "b" }) // From past To takes To with it: the two stay in order. se.choose("rst-block-scene-from", "c") se.untilSlide(t, se.token, "scenecanvas1", "from c to c", func(s map[string]any) bool { p := propsOf(s, "sceneblock01") return p["from"] == "c" && p["to"] == "c" }) se.rig.Run(waitFor(`document.querySelector('[slides-scene-body] select[name="rst-block-scene-to"]').value === 'c'`)) // A word: nothing while it is typed, written once it is left. title := `[slides-scene-words] input[data-word="title"]` se.typeInto(title, "Wien") time.Sleep(800 * time.Millisecond) if w := se.scene(t, se.world).Words; w["title"] != "Vienna" { t.Errorf("a word was written while it was typed: %v", w) } se.leave() se.untilScene(t, se.world, "titled Wien", func(s deck.Scene) bool { return s.Words["title"] == "Wien" && s.Words["sign"] == "Open" }) // Another scene: its first state to its last. se.choose("rst-block-scene", se.other) se.untilSlide(t, se.token, "scenecanvas1", "showing Other", func(s map[string]any) bool { p := propsOf(s, "sceneblock01") return p["scene"] == se.other && p["from"] == "x" && p["to"] == "x" }) se.rig.Run(waitFor(`document.querySelector('[slides-scene-body] select[name="rst-block-scene-from"]').options.length === 1`)) // Insert → Scene: a block of the first scene by name, first state to last. sel := `[slides-stage] [slides-block][data-block="scene"]` se.rig.Run( chromedp.Click(chromedp.CSS(`[slides-menu="insert"] > summary`)), chromedp.Click(chromedp.CSS(`[slides-menu="insert"] [data-insert-scene]`)), waitFor(`document.querySelectorAll('`+sel+`').length === 2`), ) s := se.untilSlide(t, se.token, "scenecanvas1", "with a second scene block", func(s map[string]any) bool { n := 0 for _, b := range s["blocks"].([]any) { if b.(map[string]any)["type"] == "scene" { n++ } } return n == 2 }) for _, b := range s["blocks"].([]any) { m := b.(map[string]any) if m["type"] != "scene" || m["id"] == "sceneblock01" { continue } if p, _ := m["props"].(map[string]any); p["scene"] != se.other || p["from"] != "x" || p["to"] != "x" { t.Errorf("Insert → Scene made props %v, want Other from x to x", p) } } } // sceneFramesJS: every scene frame on the stage, with what its document // was told at its last init. const sceneFramesJS = `[...document.querySelectorAll('[slides-scene-layer] iframe, [slides-scene-frame]')].map(f => { const log = (window.__scenes || {})[f.__doc] || [] const init = log.filter(m => m.type === 'init').pop() return { Doc: f.__doc || '', Live: getComputedStyle(f).opacity === '1', Mark: init ? init.mark : '', Title: init ? init.title : '', Data: init ? init.data : '' } })` type editorFrame struct { Doc, Mark, Title, Data string Live bool } // untilFrame waits for a live frame on the stage that ok accepts. func (se *sceneEditor) untilFrame(t *testing.T, what string, ok func(editorFrame) bool) editorFrame { t.Helper() deadline := time.Now().Add(15 * time.Second) for { var fs []editorFrame se.rig.Run(evalInto(&fs, sceneFramesJS)) for _, f := range fs { if f.Live && f.Doc != "" && ok(f) { return f } } if time.Now().After(deadline) { t.Fatalf("no live frame %s; the frames: %+v", what, fs) } time.Sleep(80 * time.Millisecond) } } // dataOf is the scene's data decoded from JSON f told it. func dataOf(t *testing.T, raw string) map[string]any { t.Helper() var v map[string]any if err := json.Unmarshal([]byte(raw), &v); err != nil { t.Fatalf("data %q: %v", raw, err) } return v } func pieces(v any) []any { m, _ := v.(map[string]any) p, _ := m["pieces"].([]any) return p } // tableJS: the data table's columns and rows as shown. const tableJS = `(() => { const t = document.querySelector('[slides-scene-table] table') if (!t || !t.checkVisibility()) return { Cols: [], Rows: [] } return { Cols: [...t.querySelectorAll('thead th')].map(th => th.textContent.trim()).filter(Boolean), Rows: [...t.querySelectorAll('tbody tr')].map(tr => [...tr.querySelectorAll('input')].map(i => i.value)) } })()` type dataTable struct { Cols []string Rows [][]string } // TestTheDataTableRedrawsTheScene: a scene whose data holds a list of // objects shows it as a table, a column per key (in code point order: // stored keys keep no other); a cell, Add a row and // Remove row each write the whole data once, keeping a number a number, // and the scene running on the stage is told the new data. The JSON // view takes anything, and says so when what it is given is not JSON. func TestTheDataTableRedrawsTheScene(t *testing.T) { se := openSceneEditor(t, sceneEditorOpts{}) se.selectScene(t) if c := se.card(t); c.Name != "World" || len(c.Picks) != 0 { t.Errorf("one scene: the card names %q and picks %v, want World and no choice", c.Name, c.Picks) } var tbl dataTable se.rig.Run(waitFor(`document.querySelector('[slides-scene-table] table')?.checkVisibility()`), evalInto(&tbl, tableJS)) if !reflect.DeepEqual(tbl.Cols, []string{"floors", "lit", "name"}) || !reflect.DeepEqual(tbl.Rows, [][]string{{"3", "true", "Tower"}, {"0", "false", "Garden"}}) { t.Errorf("the table is %+v, want floors lit name over 3 true Tower and 0 false Garden", tbl) } se.rig.Screen(`[slides-inspector]`, "a scene's data as a table") first := se.untilFrame(t, "told World's data", func(f editorFrame) bool { return len(pieces(dataOf(t, f.Data))) == 2 }) se.typeInto(`[slides-scene-table] input[data-row="0"][data-col="floors"]`, "5") se.leave() got := se.untilScene(t, se.world, "with five floors", func(s deck.Scene) bool { p := pieces(s.Data) return len(p) == 2 && p[0].(map[string]any)["floors"] == float64(5) }) if p := pieces(got.Data)[0].(map[string]any); p["name"] != "Tower" || p["lit"] != true { t.Errorf("a cell's write changed the rest of its row: %v", p) } se.untilFrame(t, "told five floors", func(f editorFrame) bool { p := pieces(dataOf(t, f.Data)) return f.Doc != first.Doc && len(p) == 2 && p[0].(map[string]any)["floors"] == float64(5) }) se.rig.Run(chromedp.Click(chromedp.CSS(`[slides-scene-add]`))) se.untilScene(t, se.world, "with a third row", func(s deck.Scene) bool { p := pieces(s.Data) return len(p) == 3 && reflect.DeepEqual(p[2], map[string]any{"name": "", "floors": float64(0), "lit": false}) }) se.rig.Run(chromedp.Click(chromedp.CSS(`[slides-scene-remove][data-row="2"]`))) se.untilScene(t, se.world, "two rows again", func(s deck.Scene) bool { return len(pieces(s.Data)) == 2 }) // The JSON view. se.rig.Run(clickLabelOf(`input[name="slides-scene-data-view"][value="json"]`), waitFor(`document.querySelector('textarea[name="slides-scene-json"]')?.checkVisibility()`)) var shown string se.rig.Run(evalInto(&shown, `document.querySelector('textarea[name="slides-scene-json"]').value`)) if v := dataOf(t, shown); len(pieces(v)) != 2 { t.Errorf("the JSON view shows %q", shown) } se.typeInto(`textarea[name="slides-scene-json"]`, `{"pieces": [`) se.leave() se.rig.Run(waitFor(`document.querySelector('[slides-scene-invalid]')?.checkVisibility()`)) var invalid string se.rig.Run(evalInto(&invalid, `document.querySelector('[slides-scene-invalid]').textContent.trim()`)) if invalid != "That isn't valid JSON." { t.Errorf("not JSON: the panel says %q", invalid) } time.Sleep(500 * time.Millisecond) if len(pieces(se.scene(t, se.world).Data)) != 2 { t.Error("text that is not JSON was written") } se.typeInto(`textarea[name="slides-scene-json"]`, `{"pieces":[{"name":"Tower","floors":7,"lit":true}]}`) se.leave() se.untilScene(t, se.world, "one row of seven floors", func(s deck.Scene) bool { p := pieces(s.Data) return len(p) == 1 && p[0].(map[string]any)["floors"] == float64(7) }) se.rig.Run(waitFor(`!document.querySelector('[slides-scene-invalid]').checkVisibility()`)) } // TestTheCodePanelPreviewsAndSaves: the code panel holds the bundle's // text and who last changed it; Preview runs the unsaved text in the // block's frame through the sealed preview route and writes nothing; // Save code stores a new bundle and names it as the scene's code, Paul // its author; a text that is not one HTML page is refused in words. func TestTheCodePanelPreviewsAndSaves(t *testing.T) { se := openSceneEditor(t, sceneEditorOpts{}) se.selectScene(t) code := `textarea[name="slides-scene-code"]` se.rig.Run(clickLabelOf(`input[name="slides-scene-panel"][value="code"]`), waitFor(`document.querySelector('`+code+`')?.checkVisibility() && document.querySelector('`+code+`').value === `+jsString(editorScene))) var author string se.rig.Run(evalInto(&author, `document.querySelector('[slides-scene-author]').textContent.trim()`)) if !strings.HasPrefix(author, "Last changed by ") || !strings.Contains(author, "scene-editor") { t.Errorf("the author line says %q, want Last changed by the agent scene-editor", author) } before := se.scene(t, se.world).Code saved := se.untilFrame(t, "running the saved code", func(f editorFrame) bool { return f.Mark == "saved" }) draft := strings.Replace(editorScene, "const MARK = 'saved';", "const MARK = 'draft';", 1) set := func(text string) { se.rig.Run(chromedp.Evaluate[chromedp.Void](`(a => { a.value = ` + jsString(text) + `; a.dispatchEvent(new Event('input', { bubbles: true })) })(document.querySelector('` + code + `'))`)) } set(draft) se.rig.Run(chromedp.Click(chromedp.CSS(`[slides-scene-preview]`))) se.untilFrame(t, "running the draft", func(f editorFrame) bool { return f.Mark == "draft" && f.Doc != saved.Doc }) if got := se.scene(t, se.world).Code; got != before { t.Errorf("Preview changed the scene's code to %s", got) } se.rig.Screen(`[slides-stage-pane]`, "the draft previewing on the stage") se.rig.Run(chromedp.Click(chromedp.CSS(`[slides-scene-save]`))) s := se.untilScene(t, se.world, "with the draft as its code", func(s deck.Scene) bool { return s.Code == hashOf([]byte(draft)) }) if !strings.HasPrefix(s.Author, "person:") { t.Errorf("a hand edit's author is %q, want the person", s.Author) } se.rig.Run(waitFor(`document.querySelector('[slides-scene-author]').textContent.trim() === 'Last changed by ` + allowedAddress + `'`)) se.untilFrame(t, "running the saved draft", func(f editorFrame) bool { return f.Mark == "draft" }) set("not a page") se.rig.Run(chromedp.Click(chromedp.CSS(`[slides-scene-save]`)), waitFor(`document.querySelector('[slides-scene-status]').textContent.trim() === "World isn't a single HTML page."`)) if got := se.scene(t, se.world).Code; got != hashOf([]byte(draft)) { t.Errorf("a refused save changed the code to %s", got) } } // TestAHandEditMarksStillsOutOfDate: with a still for every state made // from the scene as it is, the card says nothing about pictures; a word // changed by hand leaves them older than the scene, which the card says, // with the way to an agent who can redraw them: the Agents page, in a // tab of its own. func TestAHandEditMarksStillsOutOfDate(t *testing.T) { se := openSceneEditor(t, sceneEditorOpts{stills: true}) se.selectScene(t) if c := se.card(t); c.Stale != "" || c.Missing != "" { t.Errorf("current stills: the card says %q / %q, want nothing", c.Stale, c.Missing) } se.typeInto(`[slides-scene-words] input[data-word="sign"]`, "Closed") se.leave() se.untilScene(t, se.world, "signed Closed", func(s deck.Scene) bool { return s.Words["sign"] == "Closed" }) se.rig.Run(waitFor(`document.querySelector('[slides-scene-stale]')?.checkVisibility()`)) c := se.card(t) if c.Stale != "These pictures are older than the scene. Ask an agent to redraw them" || c.Ask != "/agents _blank" { t.Errorf("after a hand edit the note is %q asking at %q, want the out-of-date note and the Agents page", c.Stale, c.Ask) } if stillsCurrent(se.scene(t, se.world)) { t.Error("the API still reads the stills as current") } se.rig.Screen(`[slides-inspector]`, "stills older than the scene") } // TestAfterNeverOffersPressZero: a scene block's states are the slide's // first presses in the editor too; After… on another box lists the // presses after them by their numbers and never the scene's value 0, // and the press numbers mark the scene's range. func TestAfterNeverOffersPressZero(t *testing.T) { se := openSceneEditor(t, sceneEditorOpts{}) se.selectBoxByID(t, "scenetext002") if m := se.stepMarks(); !reflect.DeepEqual(m.Numbers, []string{"1–2", "3"}) { t.Errorf("the press numbers are %v, want 1–2 on the scene and 3 on the later text", m.Numbers) } after := `[slides-inspector-form][data-section="block"] [popovertarget="slides-pop-after"]` se.rig.Run( waitFor(`document.querySelector('`+after+`')?.checkVisibility()`), chromedp.Click(chromedp.CSS(after)), waitFor(`document.querySelector('#slides-pop-after').matches(':popover-open')`), ) var rows []string se.rig.Run(evalInto(&rows, `[...document.querySelectorAll('#slides-pop-after [data-after]')].map(r => r.textContent.trim() + ' @' + r.dataset.after)`)) if !reflect.DeepEqual(rows, []string{"After press 3 @1"}) { t.Errorf("After… lists %v, want After press 3 alone (no value 0)", rows) } se.rig.Run(chromedp.Click(chromedp.CSS(`#slides-pop-after [data-after]`))) se.untilSlide(t, se.token, "scenecanvas1", "the last text after press 3", stepsAre(map[string]float64{"scenetext002": 2, "scenetext001": 1})) }