oficina / mapa Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package mapatest
4
5import (
6 "bytes"
7 "context"
8 "encoding/base64"
9 "image"
10 "image/color"
11
12 "image/png"
13 "io"
14 "os"
15 "path/filepath"
16 "strings"
17 "sync"
18 "testing"
19
20 "amadan.net/rastrillo/rastrillo/blobs"
21 "amadan.net/rastrillo/rastrillo/harness"
22 "github.com/chromedp/chromedp"
23
24 "amadan.net/oficina/mapa/internal/mapa"
25)
26
27// The images' page gates in a real Chromium (images spec §6): L5 with
28// images, L9 with an upload in flight, L10's walk, and the JPEG that is
29// scaled down upright before it is sent.
30
31// filePicker holds the file inputs the editor opens, so the test can give
32// them files: the system's picker is not part of the page.
33const filePicker = `(function () {
34 var click = HTMLInputElement.prototype.click;
35 HTMLInputElement.prototype.click = function () {
36 if (this.hasAttribute("mapa-image-input")) return;
37 return click.call(this);
38 };
39})()`
40
41// pictureFile writes a PNG of width by height to a file.
42func pictureFile(t *testing.T, width, height int) string {
43 t.Helper()
44 canvas := image.NewRGBA(image.Rect(0, 0, width, height))
45 for column := range width {
46 for line := range height {
47 canvas.Set(column, line, color.RGBA{uint8(column), 90,
48 uint8(line), 255})
49 }
50 }
51 var out bytes.Buffer
52 if err := png.Encode(&out, canvas); err != nil {
53 t.Fatal(err)
54 }
55 path := filepath.Join(t.TempDir(), "picture.png")
56 if err := os.WriteFile(path, out.Bytes(), 0o600); err != nil {
57 t.Fatal(err)
58 }
59 return path
60}
61
62// addImage stores a picture as who's pending image.
63func addImage(t *testing.T, store *mapa.Store, who string, width,
64 height int) mapa.Image {
65 t.Helper()
66 raw, err := os.ReadFile(pictureFile(t, width, height))
67 if err != nil {
68 t.Fatal(err)
69 }
70 ctx := context.Background()
71 viewer, _ := store.Viewer(ctx, who, nil)
72 member := viewer.MemberID
73 if member == 0 {
74 if err := store.SetTimeZone(ctx, who, "Europe/Dublin"); err != nil {
75 t.Fatal(err)
76 }
77 viewer, _ = store.Viewer(ctx, who, nil)
78 member = viewer.MemberID
79 }
80 added, err := store.AddImage(ctx, member, bytes.NewReader(raw))
81 if err != nil {
82 t.Fatal(err)
83 }
84 return added
85}
86
87// choose gives the file input the editor opened a file.
88func choose(path string) chromedp.Action[chromedp.Void] {
89 return chromedp.Steps(chromedp.WaitReady(`input[mapa-image-input]`),
90 chromedp.SetUploadFiles(`input[mapa-image-input]`, []string{path}))
91}
92
93// heldGets holds every image's bytes until let() is called, so L5
94// measures the boxes before a single picture has arrived (Fable M7: on
95// loopback the pictures arrived before the first measurement, and the
96// gate passed with width and height removed).
97type heldGets struct {
98 blobs.Store
99 mutex sync.Mutex
100 gate chan struct{}
101}
102
103func (store *heldGets) hold() {
104 store.mutex.Lock()
105 store.gate = make(chan struct{})
106 store.mutex.Unlock()
107}
108
109func (store *heldGets) let() {
110 store.mutex.Lock()
111 if store.gate != nil {
112 close(store.gate)
113 store.gate = nil
114 }
115 store.mutex.Unlock()
116}
117
118func (store *heldGets) Get(ctx context.Context,
119 key string) (io.ReadCloser, error) {
120 store.mutex.Lock()
121 gate := store.gate
122 store.mutex.Unlock()
123 if gate != nil {
124 select {
125 case <-gate:
126 case <-ctx.Done():
127 return nil, ctx.Err()
128 }
129 }
130 return store.Store.Get(ctx, key)
131}
132
133func TestL5ImagesReserveTheirBoxes(t *testing.T) {
134 held := &heldGets{}
135 rig, store := browserRigWith(t, 0, func(inner blobs.Store) blobs.Store {
136 held.Store = inner
137 return held
138 })
139 t.Cleanup(held.let)
140 ctx := context.Background()
141 top, below := addImage(t, store, Bo, 900, 500), addImage(t, store, Bo,
142 300, 700)
143 body := "# Pictures\n\n" + top.Markdown("Above the fold") + "\n\n" +
144 strings.Repeat("A paragraph that fills the page. ", 120) +
145 "\n\nBetween " + below.Markdown("below") + " words.\n\n" +
146 "![gone](/i/zz9) and the end."
147 page, err := store.CreateTeamPage(ctx, Bo, "Pictures", body)
148 if err != nil {
149 t.Fatal(err)
150 }
151 drafted := addImage(t, store, Ana, 400, 400)
152 viewer, _ := store.Viewer(ctx, Ana, nil)
153 drive(t, rig, onNewDocument(shiftRecorder))
154 for _, draft := range []bool{false, true} {
155 if draft {
156 write := mapa.DraftWrite{Base: page.Revision,
157 Body: body + "\n\n" + drafted.Markdown("in my draft")}
158 if _, err := store.Autosave(ctx, viewer,
159 mapa.DraftKey{PageID: page.ID}, write); err != nil {
160 t.Fatal(err)
161 }
162 }
163 for _, width := range []int64{1440, 390} {
164 for _, live := range []bool{false, true} {
165 beforeTheBytes(t, rig, held, mapa.PagePath(page), width, live)
166 }
167 }
168 }
169}
170
171// beforeTheBytes loads path with every picture held, measures the
172// blocks, lets the pictures come, and finds every block where it was
173// and no layout shift.
174func beforeTheBytes(t *testing.T, rig *harness.Rig, held *heldGets,
175 path string, width int64, live bool) {
176 t.Helper()
177 held.hold()
178 drive(t, rig, scripts(live), chromedp.EmulateViewport(width, 900),
179 chromedp.Evaluate[chromedp.Void](`location.href = `+
180 "`"+rig.Origin+path+"`"),
181 chromedp.WaitVisible("article[mapa-body] p"))
182 if live {
183 drive(t, rig, chromedp.WaitVisible(mounted))
184 }
185 before := read(t, rig, chromedp.Evaluate[string](boxes))
186 held.let()
187 loaded(t, rig, before)
188 if t.Failed() {
189 t.Fatalf("%dpx, scripts on: %v", width, live)
190 }
191}
192
193// loaded scrolls to every image, waits for each to load, and finds no
194// layout shift and every box as before was.
195func loaded(t *testing.T, rig *harness.Rig, before string) {
196 t.Helper()
197 eventually(t, "every image loaded", func() bool {
198 return read(t, rig, chromedp.Evaluate[bool](`Array.prototype.every.call(
199 document.querySelectorAll('article[mapa-body] img[src^="/i/"]'),
200 function (img) {
201 img.scrollIntoView();
202 return img.complete && img.naturalWidth > 0; })`))
203 })
204 drive(t, rig, chromedp.Evaluate[chromedp.Void](`window.scrollTo(0, 0)`))
205 after := read(t, rig, chromedp.Evaluate[string](boxes))
206 if after != before {
207 t.Errorf("blocks moved when the images loaded:\n%s\n%s", before,
208 after)
209 }
210 shifts := read(t, rig, chromedp.Evaluate[string](
211 `JSON.stringify(window.__shifts || [])`))
212 if shifts != "[]" {
213 t.Errorf("layout shifts while the images loaded: %s", shifts)
214 }
215}
216
217// heldStore holds every Put until let() is called.
218type heldStore struct {
219 blobs.Store
220 mutex sync.Mutex
221 gate chan struct{}
222}
223
224func (store *heldStore) hold() {
225 store.mutex.Lock()
226 store.gate = make(chan struct{})
227 store.mutex.Unlock()
228}
229
230func (store *heldStore) let() {
231 store.mutex.Lock()
232 if store.gate != nil {
233 close(store.gate)
234 store.gate = nil
235 }
236 store.mutex.Unlock()
237}
238
239func (store *heldStore) Put(ctx context.Context, data io.Reader,
240 kind string) (blobs.Ref, error) {
241 store.mutex.Lock()
242 gate := store.gate
243 store.mutex.Unlock()
244 if gate != nil {
245 <-gate
246 }
247 return store.Store.Put(ctx, data, kind)
248}
249
250// pasteFile pastes a PNG file the page draws itself, as a screenshot
251// on the clipboard would arrive.
252func pasteFile(path string) chromedp.Action[chromedp.Void] {
253 raw, _ := os.ReadFile(path)
254 encoded := base64.StdEncoding.EncodeToString(raw)
255 return chromedp.Evaluate[chromedp.Void](`(function () {
256 var bytes = Uint8Array.from(atob("` + encoded + `"), function (c) {
257 return c.charCodeAt(0); });
258 var data = new DataTransfer();
259 data.items.add(new File([bytes], "shot.png", { type: "image/png" }));
260 mapaEditor.view.dom.dispatchEvent(new ClipboardEvent("paste",
261 { clipboardData: data, bubbles: true, cancelable: true }));
262})()`)
263}
264