oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/engines/leaving-webkit.swift — leaving.mjs in WebKit itself: a
2// WKWebView, which keeps pages in its back/forward cache as Safari does
3// (Playwright's WebKit does not). Its window is never shown, so the page
4// is hidden and runs no frames, as an occluded Safari tab does. Same
5// protocol as leaving.mjs, driven by internal/slidestest's
6// leaving_browser_test.go. Docs' harness (dadf9c1), with the surface's
7// path and its caught-up check taken from the config.
8//
9// Built by the test with swiftc; macOS only.
10
11import Cocoa
12import WebKit
13
14struct Config: Decodable {
15 struct Cookie: Decodable {
16 let Name: String
17 let Value: String
18 }
19 let origin: String
20 let path: String
21 let caughtUp: String
22 let cookies: [Cookie]
23}
24
25@MainActor final class Harness: NSObject, NSApplicationDelegate {
26 var window: NSWindow!
27 var web: WKWebView!
28 let config: Config
29
30 init(config: Config) { self.config = config }
31
32 func applicationDidFinishLaunching(_ notification: Notification) {
33 Task {
34 do {
35 try await run()
36 exit(0)
37 } catch {
38 print("LEAVING FAILED \(error)")
39 exit(1)
40 }
41 }
42 }
43
44 func js(_ script: String) async throws -> Any? { try await web.evaluateJavaScript(script) }
45
46 func until(_ script: String, seconds: Double) async -> Bool {
47 let end = Date().addingTimeInterval(seconds)
48 while Date() < end {
49 if (try? await js(script)) as? Bool == true { return true }
50 try? await Task.sleep(for: .milliseconds(100))
51 }
52 return false
53 }
54
55 func line() async -> String? {
56 await withCheckedContinuation { c in
57 DispatchQueue.global().async { c.resume(returning: Swift.readLine()) }
58 }
59 }
60
61 func run() async throws {
62 setbuf(stdout, nil)
63 let cfg = WKWebViewConfiguration()
64 cfg.websiteDataStore = .nonPersistent()
65 let host = URL(string: config.origin)!.host!
66 for c in config.cookies {
67 let cookie = HTTPCookie(properties: [.name: c.Name, .value: c.Value, .domain: host, .path: "/"])!
68 await cfg.websiteDataStore.httpCookieStore.setCookie(cookie)
69 }
70 let source = """
71 window.requestAnimationFrame = () => 0;
72 window.__shown = [];
73 addEventListener('pageshow', (e) => {
74 window.__shown.push(e.persisted);
75 if (e.persisted) sessionStorage.setItem('persisted', '1');
76 });
77 const ES = window.EventSource;
78 window.EventSource = class extends ES {
79 constructor(...args) {
80 super(...args);
81 sessionStorage.setItem('opened', '1');
82 }
83 };
84 """
85 cfg.userContentController.addUserScript(WKUserScript(source: source, injectionTime: .atDocumentStart, forMainFrameOnly: true))
86 web = WKWebView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800), configuration: cfg)
87 window = NSWindow(contentRect: web.frame, styleMask: [.titled], backing: .buffered, defer: false)
88 window.contentView = web
89 web.load(URLRequest(url: URL(string: config.origin + "/")!))
90 guard await until("location.pathname === '/' && document.readyState === 'complete'", seconds: 30) else { throw NSError(domain: "the documents list never loaded", code: 1) }
91 // Leave the moment the editor has opened its stream. From here,
92 // not from the page: WebKit turns a script's navigation before the
93 // load event into a replacement, and there would be no going back.
94 web.load(URLRequest(url: URL(string: config.origin + config.path)!))
95 guard await until("sessionStorage.getItem('opened') === '1'", seconds: 30) else {
96 throw NSError(domain: "the page never opened its stream", code: 1)
97 }
98 web.load(URLRequest(url: URL(string: config.origin + "/")!))
99 guard await until("location.pathname === '/' && document.readyState === 'complete'", seconds: 30) else {
100 throw NSError(domain: "the page was never left", code: 1)
101 }
102 print("LEAVING LEFT")
103 guard await line() == "BACK" else { throw NSError(domain: "expected BACK", code: 1) }
104 web.goBack()
105 let caughtUp = await until(config.caughtUp, seconds: 15)
106 let persisted = ((try? await js("window.__shown.includes(true) || sessionStorage.getItem('persisted') === '1'")) as? Bool) ?? false
107 print("LEAVING SHOWN {\"persisted\":\(persisted),\"caughtUp\":\(caughtUp)}")
108 _ = await line()
109 }
110}
111
112let config = try! JSONDecoder().decode(Config.self, from: ProcessInfo.processInfo.environment["SLIDES_LEAVING_CONFIG"]!.data(using: .utf8)!)
113MainActor.assumeIsolated {
114 let app = NSApplication.shared
115 let delegate = Harness(config: config)
116 app.delegate = delegate
117 app.setActivationPolicy(.accessory)
118 app.run()
119}
120