forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

e2e.rs528 lines, 23.1 KiBHistoryRawDownload
1//! `cargo xtask e2e`: drives the editor in headless Firefox through geckodriver.
2//! Starts the server on a scratch database; nothing is shown on screen
3//! (`-headless`, and DISPLAY/WAYLAND_DISPLAY are removed for the browser).
4
5use std::io::Read;
6use std::path::Path;
7use std::process::{Child, Command, Stdio};
8use std::thread::sleep;
9use std::time::{Duration, Instant};
10
11use anyhow::{Context, Result, bail};
12use serde_json::{Value, json};
13
14const SERVER: &str = "http://127.0.0.1:3917";
15const ELEMENT: &str = "element-6066-11e4-a52e-4f735466cecf";
16const ENTER: &str = "\u{E007}";
17const BACKSPACE: &str = "\u{E003}";
18const CONTROL: &str = "\u{E009}";
19
20pub(crate) struct Kill(pub(crate) Child);
21
22impl Drop for Kill {
23 fn drop(&mut self) {
24 let _ = self.0.kill();
25 let _ = self.0.wait();
26 }
27}
28
29pub(crate) fn agent() -> ureq::Agent {
30 ureq::Agent::config_builder().http_status_as_error(false).build().into()
31}
32
33pub(crate) struct Session {
34 agent: ureq::Agent,
35 driver: String,
36 id: String,
37}
38
39impl Session {
40 pub(crate) fn new(agent: &ureq::Agent, driver: &str, profile_dir: &Path) -> Result<Session> {
41 let caps = json!({"capabilities": {"alwaysMatch": {
42 "browserName": "firefox",
43 "moz:firefoxOptions": {
44 "args": ["-headless", "-profile", profile_dir.to_str().unwrap()],
45 // Page console output goes to geckodriver's log (see `run`).
46 "prefs": {
47 "devtools.console.stdout.content": true,
48 "media.navigator.streams.fake": true,
49 "media.navigator.permission.disabled": true
50 }
51 }
52 }}});
53 let v = call(agent, "POST", &format!("{driver}/session"), Some(caps))?;
54 let id = v["sessionId"].as_str().context("no session id")?.to_owned();
55 Ok(Session { agent: agent.clone(), driver: driver.to_owned(), id })
56 }
57
58 pub(crate) fn cmd(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value> {
59 call(&self.agent, method, &format!("{}/session/{}{path}", self.driver, self.id), body)
60 }
61
62 pub(crate) fn go(&self, url: &str) -> Result<()> {
63 self.cmd("POST", "/url", Some(json!({"url": url})))?;
64 Ok(())
65 }
66
67 pub(crate) fn js(&self, script: &str) -> Result<Value> {
68 self.cmd("POST", "/execute/sync", Some(json!({"script": script, "args": []})))
69 }
70
71 fn wait(&self, script: &str, what: &str) -> Result<()> {
72 self.wait_for(script, what, 15)
73 }
74
75 pub(crate) fn wait_for(&self, script: &str, what: &str, secs: u64) -> Result<()> {
76 let t = Instant::now();
77 while t.elapsed() < Duration::from_secs(secs) {
78 if self.js(script)? == Value::Bool(true) {
79 return Ok(());
80 }
81 sleep(Duration::from_millis(100));
82 }
83 bail!("timed out waiting for {what}")
84 }
85
86 pub(crate) fn keys(&self, css: &str, text: &str) -> Result<()> {
87 let el = self.cmd("POST", "/element", Some(json!({"using": "css selector", "value": css})))?;
88 let id = el[ELEMENT].as_str().context("element not found")?;
89 self.cmd("POST", &format!("/element/{id}/value"), Some(json!({"text": text})))?;
90 Ok(())
91 }
92
93 pub(crate) fn screenshot(&self, path: &Path) -> Result<()> {
94 let v = self.cmd("GET", "/screenshot", None)?;
95 let b64 = v.as_str().context("no screenshot")?;
96 std::fs::write(path, decode_b64(b64))?;
97 Ok(())
98 }
99
100 pub(crate) fn close(&self) {
101 let _ = self.cmd("DELETE", "", None);
102 }
103}
104
105fn call(agent: &ureq::Agent, method: &str, url: &str, body: Option<Value>) -> Result<Value> {
106 let mut resp = match method {
107 "POST" => agent.post(url).send_json(body.unwrap_or(json!({})))?,
108 "DELETE" => agent.delete(url).call()?,
109 _ => agent.get(url).call()?,
110 };
111 let v: Value = resp.body_mut().read_json()?;
112 if let Some(err) = v["value"].get("error") {
113 bail!("webdriver {method} {url}: {err} {}", v["value"]["message"]);
114 }
115 Ok(v["value"].clone())
116}
117
118fn decode_b64(s: &str) -> Vec<u8> {
119 let val = |c: u8| match c {
120 b'A'..=b'Z' => c - b'A',
121 b'a'..=b'z' => c - b'a' + 26,
122 b'0'..=b'9' => c - b'0' + 52,
123 b'+' => 62,
124 _ => 63,
125 };
126 let bytes: Vec<u8> = s.bytes().filter(|&c| c != b'=' && !c.is_ascii_whitespace()).map(val).collect();
127 let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
128 for ch in bytes.chunks(4) {
129 let n = ch.iter().enumerate().fold(0u32, |n, (i, &b)| n | (b as u32) << (18 - 6 * i));
130 for i in 0..ch.len().saturating_sub(1) {
131 out.push((n >> (16 - 8 * i)) as u8);
132 }
133 }
134 out
135}
136
137pub(crate) fn wait_http(agent: &ureq::Agent, url: &str) -> Result<()> {
138 let t = Instant::now();
139 while t.elapsed() < Duration::from_secs(30) {
140 if agent.get(url).call().is_ok() {
141 return Ok(());
142 }
143 sleep(Duration::from_millis(200));
144 }
145 bail!("{url} did not come up")
146}
147
148pub(crate) const CAPTURE: &str = "window.__log = []; for (const k of ['error', 'warn', 'log']) { const o = console[k]; \
149 console[k] = (...a) => { __log.push(k + ': ' + a.join(' ')); o(...a) } } \
150 addEventListener('error', e => __log.push('uncaught: ' + e.message)); \
151 for (const t of ['keydown', 'beforeinput', 'input']) document.addEventListener(t, e => \
152 __log.push(t + ':' + (e.inputType || e.key) + (e.defaultPrevented ? '!' : '')), true); return true";
153pub(crate) const EDITABLE: &str = "return document.querySelector('#editor .ProseMirror')?.contentEditable === 'true'";
154const CARET_END: &str = "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \
155 const s = getSelection(); s.selectAllChildren(r); s.collapseToEnd(); return true";
156
157/// The server on the scratch database. `run` and the restart in `media` both start it this way.
158fn spawn_server(root: &Path, target: &Path, dir: &Path) -> Result<Kill> {
159 Ok(Kill(
160 Command::new(target.join("debug/project_note"))
161 .current_dir(root)
162 .env("NOTE_DB", dir.join("notes.db"))
163 .env("NOTE_MEDIA", dir.join("media"))
164 .env("PORT", "3917")
165 .stdout(Stdio::null())
166 .spawn()
167 .context("starting the server")?,
168 ))
169}
170
171pub fn run(root: &Path, target: &Path) -> Result<()> {
172 // Builds the server and bundles its assets next to the executable.
173 let status = Command::new("topcoat")
174 .args(["asset", "bundle", "-p", "project_note"])
175 .current_dir(root)
176 .status()?;
177 if !status.success() {
178 bail!("server build failed");
179 }
180 let dir = target.join("e2e");
181 let _ = std::fs::remove_file(dir.join("notes.db"));
182 let _ = std::fs::remove_dir_all(dir.join("media/rec"));
183 std::fs::create_dir_all(dir.join("profile-a"))?;
184 std::fs::create_dir_all(dir.join("profile-b"))?;
185 let start = || spawn_server(root, target, &dir);
186 let mut server = start()?;
187 // geckodriver runs one session per process: one per client.
188 let gecko = |port: &str| -> Result<Kill> {
189 let log = std::fs::File::create(dir.join(format!("gecko-{port}.log")))?;
190 Ok(Kill(
191 Command::new("geckodriver")
192 .args(["--port", port])
193 .env("MOZ_HEADLESS", "1")
194 .env_remove("DISPLAY")
195 .env_remove("WAYLAND_DISPLAY")
196 .stdout(log.try_clone()?)
197 .stderr(log)
198 .spawn()
199 .context("starting geckodriver (cargo install geckodriver)")?,
200 ))
201 };
202 let drivers = [gecko("4917")?, gecko("4918")?];
203 let agent = agent();
204 wait_http(&agent, &format!("{SERVER}/"))?;
205 for port in ["4917", "4918"] {
206 wait_http(&agent, &format!("http://127.0.0.1:{port}/status"))?;
207 }
208
209 let id = agent
210 .post(&format!("{SERVER}/notes/quick"))
211 .send_form([("title", "E2E")])?
212 .body_mut()
213 .read_to_string()?
214 .trim()
215 .to_owned();
216 let note = format!("{SERVER}/notes/{id}");
217 println!("note {id}");
218
219 let a = Session::new(&agent, "http://127.0.0.1:4917", &dir.join("profile-a"))?;
220 let result = scenario(&agent, &a, &note, &dir)
221 .and_then(|_| media(&agent, &a, &dir, &mut server, &start))
222 .and_then(|_| code(&agent, &a, &dir))
223 .and_then(|_| perf(&agent, &a));
224 let _ = a.screenshot(&dir.join("a.png"));
225 if let Ok(log) = a.js("return window.__log") {
226 println!("console: {log}");
227 }
228 if let Ok(html) = a.js("return document.querySelector('#editor .ProseMirror').innerHTML") {
229 println!("dom: {}", html.as_str().unwrap_or_default());
230 }
231 a.close();
232 drop(drivers);
233 drop(server);
234 if result.is_err() {
235 // The page's console (panics land there), from the first client's browser.
236 let log = std::fs::read_to_string(dir.join("gecko-4917.log")).unwrap_or_default();
237 for l in log.lines().filter(|l| l.starts_with("console.") || l.contains("JavaScript") || l.contains("panicked")).take(40) {
238 println!("browser: {l}");
239 }
240 }
241 result?;
242 println!("e2e ok (screenshot in {})", dir.join("a.png").display());
243 Ok(())
244}
245
246fn markdown(agent: &ureq::Agent, note: &str) -> Result<String> {
247 Ok(agent.get(&format!("{note}/export.md")).call()?.body_mut().read_to_string()?)
248}
249
250fn expect_md(agent: &ureq::Agent, note: &str, want: &str) -> Result<()> {
251 let t = Instant::now();
252 let mut got = String::new();
253 while t.elapsed() < Duration::from_secs(5) {
254 got = markdown(agent, note)?;
255 if got.trim() == want.trim() {
256 return Ok(());
257 }
258 sleep(Duration::from_millis(200));
259 }
260 bail!("markdown mismatch\n--- want\n{want}\n--- got\n{got}")
261}
262
263fn scenario(agent: &ureq::Agent, a: &Session, note: &str, dir: &Path) -> Result<()> {
264 let ed = "#editor .ProseMirror";
265 a.go(note)?;
266 a.wait(EDITABLE, "the editor to become editable")?;
267 a.js(CAPTURE)?;
268 a.js(CARET_END)?;
269 a.keys(ed, &format!("{ENTER}hello world{ENTER}- item one{ENTER}item two{ENTER}{ENTER}**bold** done"))?;
270 expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold** done")?;
271
272 // Deleting is its own undo step once typing has paused past the merge interval.
273 sleep(Duration::from_millis(1200));
274 a.js(CARET_END)?;
275 a.keys(ed, &BACKSPACE.repeat(5))?;
276 expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold**")?;
277 a.keys(ed, &format!("{CONTROL}z{CONTROL}"))?;
278 expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold** done")?;
279
280 // A second client sees the same content.
281 let b = Session::new(agent, "http://127.0.0.1:4918", &dir.join("profile-b"))?;
282 let seen = (|| -> Result<()> {
283 b.go(note)?;
284 b.wait(EDITABLE, "the second editor")?;
285 b.wait(
286 "return document.querySelector('#editor .ProseMirror').textContent.includes('bold done')",
287 "the second client to show the text",
288 )?;
289 b.js(CARET_END)?;
290 b.keys(ed, " from b")?;
291 a.wait(
292 "return document.querySelector('#editor .ProseMirror').textContent.includes('done from b')",
293 "the first client to see the second's edit",
294 )
295 })();
296 b.close();
297 seen
298}
299
300const MEASURE: &str = "const root = document.querySelector('#editor .ProseMirror'); \
301 const mo = new MutationObserver(() => {}); \
302 mo.observe(root, {subtree: true, childList: true, characterData: true, attributes: true}); \
303 const run = (n, f) => { const t = []; let m = 0; for (let i = 0; i < n; i++) { \
304 const s = performance.now(); f(); t.push(performance.now() - s); m += mo.takeRecords().length; } \
305 t.sort((a, b) => a - b); \
306 return {avg: t.reduce((a, b) => a + b, 0) / n, p95: t[Math.floor(n * 0.95)], mutations_per_op: m / n}; }; \
307 const type = run(50, () => root.dispatchEvent(new InputEvent('beforeinput', \
308 {inputType: 'insertText', data: ' ', cancelable: true, bubbles: true}))); \
309 const enter = run(20, () => root.dispatchEvent(new KeyboardEvent('keydown', \
310 {key: 'Enter', code: 'Enter', cancelable: true, bubbles: true}))); \
311 mo.disconnect(); \
312 return {type, enter, blocks: root.querySelectorAll(':scope > .pm-page > *').length}";
313
314const AUDIOS: &str = "document.querySelectorAll('#editor audio.note-media').length";
315const RECORD: &str = "document.querySelector('[data-command=record]').click(); return true";
316const TAKES: &str = "document.querySelectorAll('#editor .note-take').length";
317const RECS: &str = "document.querySelectorAll('#editor audio[src^=\"/media/rec/\"]').length";
318/// The state of the note's last take.
319const TAKE_STATE: &str = "[...document.querySelectorAll('#editor .note-take')].pop()?.dataset.takeState";
320
321/// Waits until the `n`th (from 1) recording audio of the note has loaded with a duration in `want`
322/// seconds, and returns its src and duration.
323fn loaded_take(a: &Session, n: usize, want: (f64, f64), wait: u64) -> Result<(String, f64)> {
324 let t = Instant::now();
325 let mut last = Value::Null;
326 while t.elapsed() < Duration::from_secs(wait) {
327 last = a.js(&format!(
328 "const x = [...document.querySelectorAll('#editor audio[src^=\"/media/rec/\"]')][{}]; \
329 return x ? {{src: x.getAttribute('src'), ready: x.readyState, duration: x.duration}} : null",
330 n - 1
331 ))?;
332 if let (Some(d), Some(r)) = (last["duration"].as_f64(), last["ready"].as_u64()) {
333 if r >= 1 && d >= want.0 && d <= want.1 {
334 return Ok((last["src"].as_str().unwrap_or_default().to_owned(), d));
335 }
336 }
337 sleep(Duration::from_millis(100));
338 }
339 bail!("recording {n} did not load as {want:?} s: {last}")
340}
341
342/// Uploads, Range, import rewriting, recording, and a recording cut off by leaving the note.
343fn media(agent: &ureq::Agent, a: &Session, dir: &Path, server: &mut Kill, start: &dyn Fn() -> Result<Kill>) -> Result<()> {
344 let upload = |name: &str, bytes: &[u8]| -> Result<String> {
345 let url = format!("{SERVER}/media?name={name}");
346 Ok(agent.post(&url).send(bytes)?.body_mut().read_to_string()?.trim().to_owned())
347 };
348 let cat = upload("cat.PNG", b"not really a png")?;
349 if !cat.starts_with("/media/") || !cat.ends_with(".png") || upload("again.png", b"not really a png")? != cat {
350 bail!("upload answered {cat}");
351 }
352 let resp = agent.get(&format!("{SERVER}{cat}")).header("range", "bytes=4-9").call()?;
353 if resp.status() != 206 || resp.headers()["content-range"] != "bytes 4-9/16" {
354 bail!("range: {:?}", resp.headers());
355 }
356 let svg = upload("evil.svg", b"<svg onload=alert(1)>")?;
357 let resp = agent.get(&format!("{SERVER}{svg}")).call()?;
358 if resp.headers()["content-disposition"] != "attachment" || resp.headers()["content-type"] != "application/octet-stream" {
359 bail!("svg served as {:?}", resp.headers());
360 }
361
362 let song = upload("song.mp3", b"not really an mp3")?;
363 let text = "# Media\n\n![a cat](../att/cat.png)\n\n![[song.mp3|tune]]\n\n`![[song.mp3]]`\n";
364 let map = json!({"att/cat.png": cat, "vault/song.mp3": song}).to_string();
365 let id = agent
366 .post(&format!("{SERVER}/import/file"))
367 .send_form([("path", "vault/note.md"), ("text", text), ("media", map.as_str())])?
368 .body_mut()
369 .read_to_string()?
370 .trim()
371 .to_owned();
372 let note = format!("{SERVER}/notes/{id}");
373 expect_md(agent, &note, &format!("# Media\n\n![a cat]({cat})\n\n![tune]({song})\n\n`![[song.mp3]]`"))?;
374 a.go(&note)?;
375 a.wait(EDITABLE, "the media note")?;
376 a.wait(&format!("return {AUDIOS} === 1 && !!document.querySelector('#editor img')"), "the embeds to show")?;
377
378 // Dropped file.
379 a.js(CARET_END)?;
380 a.js("const dt = new DataTransfer(); dt.items.add(new File(['pasted'], 'p.png', {type: 'image/png'})); \
381 document.querySelector('#editor .ProseMirror').dispatchEvent(new DragEvent('drop', \
382 {dataTransfer: dt, bubbles: true, cancelable: true})); return true")?;
383 a.wait("return document.querySelectorAll('#editor img').length === 2", "the dropped image")?;
384
385 // Recording from the fake microphone. The take's embed appears at its first ack and stays.
386 a.js(CARET_END)?;
387 a.js(RECORD)?;
388 a.wait("return !!document.querySelector('[data-recording=true]')", "recording to start")?;
389 sleep(Duration::from_millis(2500));
390 a.wait(&format!("return {TAKE_STATE} === 'live'"), "the take to show as live while recording")?;
391 a.js(RECORD)?;
392 a.wait(&format!("return {RECS} === 1 && {TAKES} === 1"), "the recording to appear")?;
393 let (src, d) = loaded_take(a, 1, (2.0, 3.2), 40)?;
394 println!("recorded {src} {d:.2} s");
395 let src1 = src;
396
397 // Continue the take: same embed, one more part.
398 a.js("document.querySelector('#editor .note-take-continue').click(); return true")?;
399 a.wait("return !!document.querySelector('[data-recording=true]')", "the continued recording")?;
400 sleep(Duration::from_millis(2000));
401 a.js(RECORD)?;
402 a.wait(&format!("return {TAKES} === 1 && {RECS} === 1 && {TAKE_STATE} === 'absent'"), "the continued take to end")?;
403 a.go(&note)?;
404 a.wait(EDITABLE, "the note after continuing")?;
405 let (_, d) = loaded_take(a, 1, (4.0, 5.2), 40)?;
406 println!("continued take {d:.2} s");
407 a.js("const x = document.querySelector('#editor audio[src^=\"/media/rec/\"]'); window.__seeked = false; \
408 x.addEventListener('seeked', () => window.__seeked = true, {once: true}); x.currentTime = 3.5; return true")?;
409 a.wait("return window.__seeked === true", "the continued take to seek")?;
410
411 // The server restarts mid-take: the client reconnects to the same part and the gap arrives.
412 a.js(CARET_END)?;
413 a.js(RECORD)?;
414 a.wait("return !!document.querySelector('[data-recording=true]')", "the restart recording")?;
415 sleep(Duration::from_millis(2000));
416 server.0.kill()?;
417 server.0.wait()?;
418 sleep(Duration::from_millis(3000));
419 *server = start()?;
420 wait_http(agent, &format!("{SERVER}/"))?;
421 sleep(Duration::from_millis(3000));
422 a.js(RECORD)?;
423 a.wait(&format!("return {TAKES} === 2 && {TAKE_STATE} === 'absent'"), "the restart take to end")?;
424 let n = a.js(&format!("return {RECS}"))?.as_u64().unwrap_or(0) as usize;
425 let (_, d) = loaded_take(a, n, (7.0, 9.5), 40)?;
426 println!("restart take {d:.2} s");
427
428 // A browser killed outright mid-recording: the embed in the other client shows the take as lost,
429 // and the audio is whatever reached the server.
430 let b = Session::new(agent, "http://127.0.0.1:4918", &dir.join("profile-b"))?;
431 b.go(&note)?;
432 b.wait(EDITABLE, "the recording client")?;
433 b.js(CARET_END)?;
434 b.js(RECORD)?;
435 b.wait("return !!document.querySelector('[data-recording=true]')", "the crash recording")?;
436 sleep(Duration::from_millis(4000));
437 a.wait(&format!("return {TAKES} === 3"), "the crash take to reach the other client")?;
438 let killed = Command::new("pkill").args(["-9", "-f", dir.join("profile-b").to_str().unwrap()]).status()?;
439 if !killed.success() {
440 bail!("no browser to kill");
441 }
442 a.wait(
443 "const t = [...document.querySelectorAll('#editor .note-take')].pop(); return !!t && t.dataset.takeState !== 'live'",
444 "the crash take to stop being live",
445 )?;
446 let n = a.js(&format!("return {RECS}"))?.as_u64().unwrap_or(0) as usize;
447 let (_, d) = loaded_take(a, n, (3.0, 4.2), 45)?;
448 println!("crash take {d:.2} s");
449 let _ = a.screenshot(&dir.join("media.png"));
450
451 // The import page: a note and the image it references, then a lone media file.
452 let vault = dir.join("vault");
453 std::fs::create_dir_all(&vault)?;
454 let (picked, pic, tone) = (vault.join("Picked.md"), vault.join("my pic.png"), vault.join("tone.mp3"));
455 std::fs::write(&picked, "# Picked\n\n![pic](my%20pic.png)\n")?;
456 std::fs::write(&pic, "picked image")?;
457 std::fs::write(&tone, "picked audio")?;
458 let import = format!("{SERVER}/import");
459 let done = "return !document.querySelector('#import-link').classList.contains('hidden')";
460 a.go(&import)?;
461 a.keys("#import-files", &format!("{}\n{}", picked.display(), pic.display()))?;
462 a.wait(done, "the import to finish")?;
463 a.go(&format!("{SERVER}/notes/by-title/Picked"))?;
464 a.wait(EDITABLE, "the imported note")?;
465 a.wait("return !!document.querySelector('#editor img[src^=\"/media/\"]')", "the imported image")?;
466 a.go(&import)?;
467 a.keys("#import-files", &tone.display().to_string())?;
468 a.wait(done, "the media import to finish")?;
469 a.go(&format!("{SERVER}/notes/by-title/tone"))?;
470 a.wait(EDITABLE, "the note of the lone file")?;
471 a.wait(&format!("return {AUDIOS} === 1"), "the imported audio")?;
472
473 let mut zip = Vec::new();
474 agent.get(&format!("{SERVER}/export.zip")).call()?.into_body().into_reader().read_to_end(&mut zip)?;
475 std::fs::write(dir.join("export.zip"), &zip)?;
476 let entry = format!("media/rec/{}", src1.trim_start_matches("/media/rec/"));
477 if !zip.windows(entry.len()).any(|w| w == entry.as_bytes()) {
478 bail!("the export has no {entry}");
479 }
480 Ok(())
481}
482
483/// Code blocks: the language is detected and Format rewrites the code through the server.
484fn code(agent: &ureq::Agent, a: &Session, dir: &Path) -> Result<()> {
485 let text = "Code\n\n```\nlet x=foo( a,b );\nlet y = x.map(|s|s.len());\n```\n";
486 let id = agent
487 .post(&format!("{SERVER}/import/file"))
488 .send_form([("path", "code.md"), ("text", text)])?
489 .body_mut()
490 .read_to_string()?
491 .trim()
492 .to_owned();
493 let note = format!("{SERVER}/notes/{id}");
494 a.go(&note)?;
495 a.wait(EDITABLE, "the code note")?;
496 a.wait(
497 "const s = document.querySelector('.code-head .code-lang'); return !!s && s.options[0].text.includes('Rust')",
498 "the header to show the detected language",
499 )?;
500 let _ = a.screenshot(&dir.join("code.png"));
501 a.js("document.querySelector('.code-head .code-format').click(); return true")?;
502 expect_md(agent, &note, "# code\n\nCode\n\n```rust\nlet x = foo(a, b);\nlet y = x.map(|s| s.len());\n```")
503}
504
505/// Typing latency on a 5000-paragraph note.
506fn perf(agent: &ureq::Agent, a: &Session) -> Result<()> {
507 let text: String = (0..5000).map(|i| format!("Paragraph {i} with some ordinary words in it.\n\n")).collect();
508 let id = agent
509 .post(&format!("{SERVER}/import/file"))
510 .send_form([("path", "big.md"), ("text", text.as_str())])?
511 .body_mut()
512 .read_to_string()?
513 .trim()
514 .to_owned();
515 a.go(&format!("{SERVER}/notes/{id}"))?;
516 a.wait(EDITABLE, "the big note to become editable")?;
517 let ready = a.js("return performance.now()")?;
518 // Top-level blocks live in pages that are built near the viewport: scroll there first.
519 a.js("const r = document.querySelector('#editor .ProseMirror'); r.focus(); \
520 const pages = r.querySelectorAll(':scope > .pm-page'); pages[pages.length >> 1].scrollIntoView({block: 'center'}); return true")?;
521 sleep(Duration::from_millis(300));
522 a.js("const pages = document.querySelectorAll('#editor .ProseMirror > .pm-page'); \
523 const p = pages[pages.length >> 1].firstElementChild; getSelection().collapse(p.firstChild, 9); return true")?;
524 sleep(Duration::from_millis(100));
525 let m = a.js(MEASURE)?;
526 println!("perf: editable after {ready} ms; {m}");
527 Ok(())
528}