//go:build browser package slidestest // The final review's round on scenes (scenes and clips spec §5, §8): // a scene edit is one undo step, data that would encode past what one // live update may carry is refused before it is written, and two // blocks of one scene on a slide each run. import ( "context" "encoding/json" "net/http" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/blobs" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/kb" "amadan.net/oficina/slides/internal/slides/deck" ) // TestASceneWordEditIsUndone: a word written from the scene card is // taken back by one click on Undo, in the deck and in its field. func TestASceneWordEditIsUndone(t *testing.T) { se := openSceneEditor(t, sceneEditorOpts{}) se.selectScene(t) title := `[slides-scene-words] input[data-word="title"]` se.typeInto(title, "Wien") se.leave() se.untilScene(t, se.world, "titled Wien", func(s deck.Scene) bool { return s.Words["title"] == "Wien" }) se.rig.Run(chromedp.Click(chromedp.CSS(`[slides-press][data-command="undo"]`))) se.untilScene(t, se.world, "titled Vienna again", func(s deck.Scene) bool { return s.Words["title"] == "Vienna" && s.Words["sign"] == "Open" }) se.rig.Run(waitFor(`document.querySelector('` + title + `').value === 'Vienna'`)) } // tenths is a JSON list of n copies of 0.1: four bytes each in JSON, // nine in a Yjs update. func tenths(n int) string { return "[" + strings.TrimSuffix(strings.Repeat("0.1,", n), ",") + "]" } // TestSceneDataPastOneUpdateIsRefused (final review call 3): 150,000 // tenths are 600,001 bytes of JSON, within the data limit, but their // set_scene would be a 1.35 MB update, past the 1 MiB the server takes. // The editor refuses it before writing anything, in the data limit's // words, and keeps it in its field; 116,000 of them, just under one // update, are written. func TestSceneDataPastOneUpdateIsRefused(t *testing.T) { se := openSceneEditor(t, sceneEditorOpts{}) se.selectScene(t) json := `textarea[name="slides-scene-json"]` se.rig.Run(clickLabelOf(`input[name="slides-scene-data-view"][value="json"]`), waitFor(`document.querySelector('`+json+`')?.checkVisibility()`)) put := func(text string) { se.rig.Run(chromedp.Evaluate[chromedp.Void](`(a => { a.focus(); a.value = ` + jsString(text) + `; a.dispatchEvent(new Event('input', { bubbles: true })); a.dispatchEvent(new Event('change', { bubbles: true })) })(document.querySelector('` + json + `'))`)) } over := tenths(150000) put(over) se.rig.Run(waitFor(`document.querySelector('[slides-scene-data-big]')?.checkVisibility()`)) var state struct { Length int Invalid string Words string } se.rig.Run(evalInto(&state, `({ Length: document.querySelector('`+json+`').value.length, Invalid: document.querySelector('`+json+`').getAttribute('aria-invalid') || '', Words: document.querySelector('[slides-scene-data-big]').textContent.trim() })`)) if state.Length != len(over) || state.Invalid != "true" || state.Words != "This data is over 960 KB, so it wasn't saved." { t.Errorf("past one update: the field holds %d characters, aria-invalid %q, saying %q; want the edit kept, invalid, and words", state.Length, state.Invalid, state.Words) } if p := pieces(se.scene(t, se.world).Data); len(p) != 2 { t.Errorf("data past one update was written: %v", se.scene(t, se.world).Data) } put(tenths(116000)) se.untilScene(t, se.world, "116,000 tenths", func(s deck.Scene) bool { l, _ := s.Data.([]any) return len(l) == 116000 }) se.rig.Run(waitFor(`!document.querySelector('[slides-scene-data-big]').checkVisibility() && document.querySelector('` + json + `').getAttribute('aria-invalid') !== 'true'`)) } // placementsJS: every frame in the scene layer, by the block it is over, // with what its document was last told. const placementsJS = `[...document.querySelectorAll('[slides-scene-layer] iframe')].map((f) => { const log = (window.__scenes || {})[f.__doc] || []; const last = log[log.length - 1] || {}; return {For: f.getAttribute('data-for') || '', Doc: f.__doc || '', Mark: !!f.__mark, Visible: getComputedStyle(f).opacity === '1', Inits: log.filter((m) => m.type === 'init').length, Type: last.type || '', State: last.state || ''}; })` type placement struct { For, Doc, Type, State string Mark, Visible bool Inits int } // TestTwoBlocksOfOneSceneEachRun (final review call 5): a slide with two // blocks of one scene runs a frame over each, live. On the next slide // the first block of that scene carries on from the first one (the same // box: the same frame, told its new state), and the second, in another // box, starts fresh. func TestTwoBlocksOfOneSceneEachRun(t *testing.T) { const scene = "twinsceneaaa" block := func(slide, id, box, state string) string { return `{"op":"add_block","slide":"` + slide + `","id":"` + id + `","type":"scene","box":` + box + `,"props":{"scene":"` + scene + `","from":"` + state + `","to":"` + state + `"}}` } fr, sqid := twinDeck(t, scene, `{"op":"add_slide","id":"twinslide01","layout":"canvas"}`, block("twinslide01", "twinleft0001", boxL, "one"), block("twinslide01", "twinright001", boxR, "one"), `{"op":"add_slide","id":"twinslide02","layout":"canvas"}`, block("twinslide02", "twinleft0002", boxL, "two"), block("twinslide02", "twinlow00002", boxLow, "two")) deckPath := "/d/" + sqid ctx := fr.rig.Context() run(t, ctx, chromedp.Navigate(fr.rig.Origin+deckPath+"?slide=1"), waitFor(`document.documentElement.getAttribute('data-slides-fonts') !== 'pending' && !!document.querySelector('[slides-slide]')`)) run(t, ctx, evalValue(nil, sceneWatch)) until := func(what string, ok func(map[string]placement) bool) map[string]placement { t.Helper() return untilPlacements(t, ctx, what, ok) } first := until("a live frame over each block", func(m map[string]placement) bool { return len(m) == 2 && live(m["twinleft0001"], "one") && live(m["twinright001"], "one") }) if first["twinleft0001"].Doc == first["twinright001"].Doc { t.Errorf("the two blocks share one frame's document: %+v", first) } run(t, ctx, evalValue(nil, `document.querySelectorAll('[slides-scene-layer] iframe').forEach((f) => { f.__mark = true; })`)) run(t, ctx, chromedp.Click(chromedp.CSS(`[slides-pager] a[rel="next"]`)), waitFor(`location.search.includes('slide=2')`)) next := until("the first carried on and the second made afresh", func(m map[string]placement) bool { return len(m) == 2 && live(m["twinleft0002"], "two") && live(m["twinlow00002"], "two") }) if l := next["twinleft0002"]; !l.Mark || l.Doc != first["twinleft0001"].Doc || l.Type != "state" || l.Inits != 1 { t.Errorf("the first block of the scene did not carry on from the first: %+v (was %+v)", l, first["twinleft0001"]) } if r := next["twinlow00002"]; r.Mark || r.Doc == first["twinright001"].Doc || r.Inits != 1 || r.Type != "init" { t.Errorf("the second block, in another box, should start fresh: %+v", r) } } var ( boxL = `{"x":0.05,"y":0.1,"w":0.4,"h":0.4}` boxR = `{"x":0.55,"y":0.1,"w":0.4,"h":0.4}` boxLow = `{"x":0.55,"y":0.55,"w":0.4,"h":0.4}` ) // twinDeck is a deck holding only the scene id, recorderScene with // states one and two, and the slides ops make. func twinDeck(t *testing.T, scene string, ops ...string) (*fontRig, string) { t.Helper() store, err := blobs.Dir(t.TempDir()) if err != nil { t.Fatalf("blobs.Dir: %v", err) } fr := newFontRigWith(t, store) sqid := apiDeck(t, fr.app, fr.token, "Twins") code := uploadScene(t, fr.app, "/d/"+sqid, fr.cookies, []byte(recorderScene)) view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK) var batch []string for _, s := range view["slides"].([]any) { batch = append(batch, `{"op":"remove_slide","id":`+quote(s.(map[string]any)["id"].(string))+`}`) } batch = append(batch, `{"op":"add_scene","id":"`+scene+`","name":"Twins","code":"`+code+`","states":[{"id":"one"},{"id":"two"}],"words":{"two":"Second"}}`) batch = append(batch, ops...) apiJSON(t, fr.app, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", fr.token, `{"ops":[`+strings.Join(batch, ",")+`]}`, http.StatusOK) return fr, sqid } // untilPlacements waits for the frames, by the block each is over, to // satisfy ok. func untilPlacements(t *testing.T, ctx context.Context, what string, ok func(map[string]placement) bool) map[string]placement { t.Helper() deadline := time.Now().Add(10 * time.Second) for { var list []placement run(t, ctx, evalInto(&list, placementsJS)) got := map[string]placement{} for _, p := range list { got[p.For] = p } if len(got) == len(list) && ok(got) { return got } if time.Now().After(deadline) { raw, _ := json.MarshalIndent(list, "", " ") t.Fatalf("waiting for %s; the frames are:\n%s", what, raw) } time.Sleep(60 * time.Millisecond) } } func live(p placement, state string) bool { return p.Visible && p.Doc != "" && p.State == state } // TestAnEarlierBlockArrivingLeavesALaterOneRunning (re-review): of two // blocks of one scene, the first is in a box that arrives on press 1 // (a scene block itself is there when its slide arrives, so the box // holding it is what waits) and the second is there from the start. // The press brings the first in with a frame of its own and leaves the // second's frame as it was: the same element, the same document, never // told init again. func TestAnEarlierBlockArrivingLeavesALaterOneRunning(t *testing.T) { const scene = "twinsceneaaa" block := func(id, region string) string { return `{"op":"add_block","slide":"waitslide001","id":"` + id + `","type":"scene","region":"` + region + `","props":{"scene":"` + scene + `","from":"one","to":"one"}}` } fr, sqid := twinDeck(t, scene, `{"op":"add_slide","id":"waitslide001","layout":"flow","template":"two-column"}`, block("waitfirst001", "body"), `{"op":"add_block","slide":"waitslide001","id":"waitlater001","type":"columns","region":"body","props":{"count":2,"children":["waitfirst001"]}}`, `{"op":"set_block","slide":"waitslide001","id":"waitlater001","step":1}`, block("waitsecond01", "aside")) session, _ := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies) ctx := fr.rig.Context() open(t, ctx, fr.rig.Origin, "/p/"+session) run(t, ctx, evalValue(nil, sceneWatch)) before := untilPlacements(t, ctx, "the second block running alone", func(m map[string]placement) bool { return len(m) == 1 && live(m["waitsecond01"], "one") }) run(t, ctx, evalValue(nil, `document.querySelectorAll('[slides-scene-layer] iframe').forEach((f) => { f.__mark = true; })`)) run(t, ctx, key(kb.ArrowRight), waitFor(rootJS+`.dataset.step === '1'`)) after := untilPlacements(t, ctx, "both blocks running", func(m map[string]placement) bool { return len(m) == 2 && live(m["waitfirst001"], "one") && live(m["waitsecond01"], "one") }) if s := after["waitsecond01"]; !s.Mark || s.Doc != before["waitsecond01"].Doc || s.Inits != 1 { t.Errorf("the first block's arrival restarted the second's frame: %+v (was %+v)", s, before["waitsecond01"]) } if f := after["waitfirst001"]; f.Mark || f.Inits != 1 { t.Errorf("the first block, arriving, should have a frame of its own: %+v", f) } }