oficina / docs Public

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

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