| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import Foundation |
| 4 | import RastrilloApple |
| 5 | import RastrilloNative |
| 6 | import SwiftUI |
| 7 | import XCTest |
| 8 | @testable import DocsKit |
| 9 | |
| 10 | /// The Share popover in a real document window (spec 2026-11-22 §11, |
| 11 | /// hosted-window tests; plan S2b acceptance): Share… opens it under the |
| 12 | /// button with focus in the email field; Share… while it is open does |
| 13 | /// nothing; the once-only URL shows once and survives a click outside, |
| 14 | /// which closes it otherwise; Esc closes it and gives the keyboard back to |
| 15 | /// Share…. |
| 16 | @MainActor final class SharePopoverTests: XCTestCase { |
| 17 | private struct Hosted { |
| 18 | let window: NSWindow |
| 19 | let server: ShareWindowServer |
| 20 | } |
| 21 | |
| 22 | private func host() async throws -> Hosted { |
| 23 | let server = ShareWindowServer() |
| 24 | try await server.chrome.seed() |
| 25 | let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", |
| 26 | team: "Tito", accountLabel: "alice@example.com") |
| 27 | let controller = NSHostingController(rootView: workspace) |
| 28 | controller.sceneBridgingOptions = [.toolbars, .title] |
| 29 | controller.sizingOptions = [] |
| 30 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1280, height: 800), |
| 31 | styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) |
| 32 | window.isReleasedWhenClosed = false |
| 33 | window.contentViewController = controller |
| 34 | window.setContentSize(NSSize(width: 1280, height: 800)) |
| 35 | window.makeKeyAndOrderFront(nil) |
| 36 | let hosted = Hosted(window: window, server: server) |
| 37 | try await until("the document opened") { Self.find(DocsPagedTextView.self, in: window.contentView).map { !$0.string.isEmpty } == true } |
| 38 | try await until("Share… is in the toolbar") { anchor(hosted) != nil } |
| 39 | await pump(0.3) |
| 40 | return hosted |
| 41 | } |
| 42 | |
| 43 | private func close(_ hosted: Hosted) async { |
| 44 | anchor(hosted)?.popover?.dismiss() |
| 45 | hosted.window.orderOut(nil) |
| 46 | hosted.window.contentViewController = nil |
| 47 | await pump(0.1) |
| 48 | } |
| 49 | |
| 50 | /// Runs the run loop, delivering posted events as the app would. |
| 51 | private func pump(_ seconds: Double) async { |
| 52 | let end = Date().addingTimeInterval(seconds) |
| 53 | while Date() < end { |
| 54 | while let event = NSApp.nextEvent(matching: .any, until: Date(), inMode: .default, dequeue: true) { NSApp.sendEvent(event) } |
| 55 | NSApp?.windows.forEach { $0.contentView?.layoutSubtreeIfNeeded() } |
| 56 | try? await Task.sleep(for: .milliseconds(10)) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// Waits for what the test asserts: a timeout is a failure, never a skip. |
| 61 | private func until(_ what: String, _ condition: () -> Bool) async throws { |
| 62 | let deadline = Date().addingTimeInterval(10) |
| 63 | while !condition() { |
| 64 | guard Date() < deadline else { throw Timeout(what: what) } |
| 65 | await pump(0.02) |
| 66 | } |
| 67 | } |
| 68 | private struct Timeout: Error, CustomStringConvertible { |
| 69 | let what: String |
| 70 | var description: String { "timed out waiting for \(what)" } |
| 71 | } |
| 72 | |
| 73 | private static func find<T: NSView>(_ type: T.Type, in view: NSView?) -> T? { |
| 74 | guard let view else { return nil } |
| 75 | if let found = view as? T { return found } |
| 76 | return view.subviews.lazy.compactMap { find(type, in: $0) }.first |
| 77 | } |
| 78 | |
| 79 | /// Share…'s anchor, in the toolbar's own views. |
| 80 | private func anchor(_ hosted: Hosted) -> DocsShareAnchorView? { |
| 81 | let frame = hosted.window.contentView?.superview |
| 82 | return Self.find(DocsShareAnchorView.self, in: frame) |
| 83 | } |
| 84 | |
| 85 | /// A real click, posted to the app's queue and delivered by `pump`. |
| 86 | private func click(_ window: NSWindow, at point: NSPoint) async { |
| 87 | for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { |
| 88 | let event = NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, |
| 89 | windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)! |
| 90 | NSApp.postEvent(event, atStart: false) |
| 91 | await pump(0.05) |
| 92 | } |
| 93 | await pump(0.2) |
| 94 | } |
| 95 | |
| 96 | private func center(of view: NSView) -> NSPoint { |
| 97 | let rect = view.convert(view.bounds, to: nil) |
| 98 | return NSPoint(x: rect.midX, y: rect.midY) |
| 99 | } |
| 100 | |
| 101 | /// Opens the popover with a click on Share…. |
| 102 | private func openShare(_ hosted: Hosted) async throws -> DocsSharePopover { |
| 103 | let anchor = try XCTUnwrap(anchor(hosted)) |
| 104 | let popover = try XCTUnwrap(anchor.popover) |
| 105 | await click(hosted.window, at: center(of: anchor)) |
| 106 | try await until("the popover opened") { popover.popover?.isShown == true } |
| 107 | try await until("the panel loaded") { popover.panel?.information != nil } |
| 108 | return popover |
| 109 | } |
| 110 | |
| 111 | func testShareOpensThePanelUnderTheButtonWithFocusInTheEmailField() async throws { |
| 112 | let hosted = try await host() |
| 113 | defer { Task { await close(hosted) } } |
| 114 | let share = try await openShare(hosted) |
| 115 | let popover = try XCTUnwrap(share.popover) |
| 116 | XCTAssertEqual(popover.behavior, .transient, "a click outside closes it while no URL shows") |
| 117 | let panelWindow = try XCTUnwrap(popover.contentViewController?.view.window) |
| 118 | try await until("the email field has the keyboard") { panelWindow.firstResponder is NSTextView } |
| 119 | XCTAssertEqual(popover.contentViewController?.view.frame.width ?? 0, 420, accuracy: 1, "420pt wide") |
| 120 | let anchorFrame = try XCTUnwrap(anchor(hosted)).convert(try XCTUnwrap(anchor(hosted)).bounds, to: nil) |
| 121 | let panelFrame = hosted.window.convertFromScreen(panelWindow.frame) |
| 122 | XCTAssertLessThan(panelFrame.maxY, anchorFrame.minY + 1, "under Share…, arrow at the top") |
| 123 | } |
| 124 | |
| 125 | func testShareWhileOpenIsANoOp() async throws { |
| 126 | let hosted = try await host() |
| 127 | defer { Task { await close(hosted) } } |
| 128 | let share = try await openShare(hosted) |
| 129 | let first = try XCTUnwrap(share.popover) |
| 130 | let loads = await hosted.server.shareLoads |
| 131 | XCTAssertEqual(loads, 1) |
| 132 | // A click on Share… is not a click outside: the popover stays, and |
| 133 | // nothing opens or loads again. |
| 134 | await click(hosted.window, at: center(of: try XCTUnwrap(anchor(hosted)))) |
| 135 | XCTAssertTrue(share.popover === first && first.isShown, "the same popover, still open") |
| 136 | let after = await hosted.server.shareLoads |
| 137 | XCTAssertEqual(after, 1, "Share… while open did nothing") |
| 138 | } |
| 139 | |
| 140 | func testTheOnceOnlyURLShowsOnceAndSurvivesAClickOutside() async throws { |
| 141 | let hosted = try await host() |
| 142 | defer { Task { await close(hosted) } } |
| 143 | // Without a URL, a click outside closes it. |
| 144 | var share = try await openShare(hosted) |
| 145 | await click(hosted.window, at: NSPoint(x: 300, y: 200)) |
| 146 | try await until("a click outside closed it") { share.popover == nil } |
| 147 | |
| 148 | share = try await openShare(hosted) |
| 149 | let panel = try XCTUnwrap(share.panel) |
| 150 | let published = await panel.setLink(true) |
| 151 | XCTAssertTrue(published) |
| 152 | XCTAssertNotNil(panel.onceURL) |
| 153 | let popover = try XCTUnwrap(share.popover) |
| 154 | XCTAssertEqual(popover.behavior, .applicationDefined, "not transient while the URL shows") |
| 155 | await click(hosted.window, at: NSPoint(x: 300, y: 200)) |
| 156 | XCTAssertTrue(popover.isShown, "a click outside does not close it while the URL shows") |
| 157 | XCTAssertNotNil(panel.onceURL, "and the URL is still there") |
| 158 | |
| 159 | // Close: the URL goes with the panel, and a new panel never shows it. |
| 160 | share.dismiss() |
| 161 | XCTAssertNil(panel.onceURL) |
| 162 | share = try await openShare(hosted) |
| 163 | XCTAssertNil(share.panel?.onceURL, "shown once") |
| 164 | XCTAssertEqual(share.popover?.behavior, .transient) |
| 165 | } |
| 166 | |
| 167 | /// Fable on #178, finding 3: an earlier popover's close, arriving after |
| 168 | /// a new one has opened, leaves the new one alone. |
| 169 | func testAnOldPopoversLateCloseLeavesTheNewOneAlone() async throws { |
| 170 | let hosted = try await host() |
| 171 | defer { Task { await close(hosted) } } |
| 172 | let share = try await openShare(hosted) |
| 173 | let old = try XCTUnwrap(share.popover) |
| 174 | share.dismiss() |
| 175 | try await until("closed") { share.popover == nil } |
| 176 | _ = try await openShare(hosted) |
| 177 | let current = try XCTUnwrap(share.popover) |
| 178 | XCTAssertFalse(current === old) |
| 179 | share.popoverDidClose(Notification(name: NSPopover.didCloseNotification, object: old)) |
| 180 | XCTAssertTrue(share.popover === current && current.isShown, "the new popover is still the one showing") |
| 181 | XCTAssertNotNil(share.panel, "and its panel is still there") |
| 182 | } |
| 183 | |
| 184 | /// Fable on #178, finding 4: Esc while an input method is composing in |
| 185 | /// the email field (ja, zh-Hans, yue) belongs to the composition; the |
| 186 | /// panel stays. Without marked text, Esc closes it. |
| 187 | func testEscDuringAnIMECompositionLeavesThePanelOpen() async throws { |
| 188 | let hosted = try await host() |
| 189 | defer { Task { await close(hosted) } } |
| 190 | let share = try await openShare(hosted) |
| 191 | let panelWindow = try XCTUnwrap(share.popover?.contentViewController?.view.window) |
| 192 | try await until("the email field has the keyboard") { panelWindow.firstResponder is NSTextView } |
| 193 | let editor = try XCTUnwrap(panelWindow.firstResponder as? NSTextView) |
| 194 | editor.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0)) |
| 195 | XCTAssertTrue(editor.hasMarkedText()) |
| 196 | NSApp.postEvent(esc(panelWindow), atStart: false) |
| 197 | await pump(0.4) |
| 198 | XCTAssertNotNil(share.popover, "Esc went to the composition, not the panel") |
| 199 | editor.unmarkText() |
| 200 | XCTAssertFalse(editor.hasMarkedText()) |
| 201 | NSApp.postEvent(esc(panelWindow), atStart: false) |
| 202 | try await until("Esc closed it once nothing was composing") { share.popover == nil } |
| 203 | } |
| 204 | |
| 205 | private func esc(_ window: NSWindow) -> NSEvent { |
| 206 | NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, |
| 207 | windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", |
| 208 | isARepeat: false, keyCode: 53)! |
| 209 | } |
| 210 | |
| 211 | func testEscClosesItAndReturnsTheKeyboardToShare() async throws { |
| 212 | let hosted = try await host() |
| 213 | defer { Task { await close(hosted) } } |
| 214 | let share = try await openShare(hosted) |
| 215 | let panelWindow = try XCTUnwrap(share.popover?.contentViewController?.view.window) |
| 216 | try await until("the email field has the keyboard") { panelWindow.firstResponder is NSTextView } |
| 217 | let esc = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, |
| 218 | windowNumber: panelWindow.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", |
| 219 | isARepeat: false, keyCode: 53)! |
| 220 | NSApp.postEvent(esc, atStart: false) |
| 221 | try await until("Esc closed it") { share.popover == nil } |
| 222 | await pump(0.2) |
| 223 | let anchor = try XCTUnwrap(anchor(hosted)) |
| 224 | XCTAssertTrue(hosted.window.firstResponder === anchor, "the keyboard is back on Share…, not \(String(describing: hosted.window.firstResponder))") |
| 225 | // Return there presses Share… again. |
| 226 | let enter = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, |
| 227 | windowNumber: hosted.window.windowNumber, context: nil, characters: "\r", charactersIgnoringModifiers: "\r", |
| 228 | isARepeat: false, keyCode: 36)! |
| 229 | NSApp.postEvent(enter, atStart: false) |
| 230 | try await until("Return on Share… opened it again") { share.popover?.isShown == true } |
| 231 | try await until("the panel loaded") { share.panel?.information != nil } |
| 232 | |
| 233 | // While the once-only URL shows, Esc still closes it (only Close and Esc do). |
| 234 | let published = await share.panel?.setLink(true) |
| 235 | XCTAssertEqual(published, true) |
| 236 | XCTAssertEqual(share.popover?.behavior, .applicationDefined) |
| 237 | let again = try XCTUnwrap(share.popover?.contentViewController?.view.window) |
| 238 | // The email field has the keyboard (this test process is never the |
| 239 | // active app, so no window here is key; the panel's own window is |
| 240 | // still where the field editor is). |
| 241 | try await until("the email field has the keyboard again") { again.firstResponder is NSTextView } |
| 242 | let esc2 = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, |
| 243 | windowNumber: again.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", |
| 244 | isARepeat: false, keyCode: 53)! |
| 245 | NSApp.postEvent(esc2, atStart: false) |
| 246 | try await until("Esc closed it with the URL showing") { share.popover == nil } |
| 247 | await pump(0.2) |
| 248 | XCTAssertTrue(hosted.window.firstResponder === anchor, "and the keyboard is back on Share…") |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | /// ChromeServer's document, plus the share routes as share.go answers them. |
| 253 | actor ShareWindowServer: NativeTransport { |
| 254 | nonisolated let origin = URL(string: "https://docs.share.invalid")! |
| 255 | let chrome = ChromeServer(canWrite: true) |
| 256 | private(set) var shareLoads = 0 |
| 257 | private var published = false |
| 258 | |
| 259 | func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| 260 | let json = ["Content-Type": "application/json"] |
| 261 | switch (method, path) { |
| 262 | case ("GET", "/d/doc/share"): |
| 263 | shareLoads += 1 |
| 264 | let state: [String: Any] = ["sqid": "doc", "title": "Chrome test", "grants": [["address": "bob@example.com", "role": "writer"]], |
| 265 | "published": published, "public_url": "", "visibility": "team", "error": ""] |
| 266 | return NativeResponse(data: try JSONSerialization.data(withJSONObject: state), status: 200, headers: json) |
| 267 | case ("POST", "/d/doc/share/link"): |
| 268 | published = String(decoding: body ?? Data(), as: UTF8.self).contains("on=1") |
| 269 | let answer: [String: Any] = ["published": published, "public_url": published ? "https://docs.share.invalid/p/once" : ""] |
| 270 | return NativeResponse(data: try JSONSerialization.data(withJSONObject: answer), status: 200, headers: json) |
| 271 | default: |
| 272 | return try await chrome.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) |
| 273 | } |
| 274 | } |
| 275 | func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| 276 | try await chrome.stream(path, onOpen: onOpen, onLine: onLine) |
| 277 | } |
| 278 | func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| 279 | } |
| 280 | #endif |
| 281 | |