#if os(macOS) import AppKit import Foundation import RastrilloApple import RastrilloNative import SwiftUI import XCTest @testable import DocsKit /// The Share popover in a real document window (spec 2026-11-22 §11, /// hosted-window tests; plan S2b acceptance): Share… opens it under the /// button with focus in the email field; Share… while it is open does /// nothing; the once-only URL shows once and survives a click outside, /// which closes it otherwise; Esc closes it and gives the keyboard back to /// Share…. @MainActor final class SharePopoverTests: XCTestCase { private struct Hosted { let window: NSWindow let server: ShareWindowServer } private func host() async throws -> Hosted { let server = ShareWindowServer() try await server.chrome.seed() let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc", team: "Tito", accountLabel: "alice@example.com") let controller = NSHostingController(rootView: workspace) controller.sceneBridgingOptions = [.toolbars, .title] controller.sizingOptions = [] let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1280, height: 800), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) window.isReleasedWhenClosed = false window.contentViewController = controller window.setContentSize(NSSize(width: 1280, height: 800)) window.makeKeyAndOrderFront(nil) let hosted = Hosted(window: window, server: server) try await until("the document opened") { Self.find(DocsPagedTextView.self, in: window.contentView).map { !$0.string.isEmpty } == true } try await until("Share… is in the toolbar") { anchor(hosted) != nil } await pump(0.3) return hosted } private func close(_ hosted: Hosted) async { anchor(hosted)?.popover?.dismiss() hosted.window.orderOut(nil) hosted.window.contentViewController = nil await pump(0.1) } /// Runs the run loop, delivering posted events as the app would. private func pump(_ seconds: Double) async { let end = Date().addingTimeInterval(seconds) while Date() < end { while let event = NSApp.nextEvent(matching: .any, until: Date(), inMode: .default, dequeue: true) { NSApp.sendEvent(event) } NSApp?.windows.forEach { $0.contentView?.layoutSubtreeIfNeeded() } try? await Task.sleep(for: .milliseconds(10)) } } /// Waits for what the test asserts: a timeout is a failure, never a skip. private func until(_ what: String, _ condition: () -> Bool) async throws { let deadline = Date().addingTimeInterval(10) while !condition() { guard Date() < deadline else { throw Timeout(what: what) } await pump(0.02) } } private struct Timeout: Error, CustomStringConvertible { let what: String var description: String { "timed out waiting for \(what)" } } private static func find(_ type: T.Type, in view: NSView?) -> T? { guard let view else { return nil } if let found = view as? T { return found } return view.subviews.lazy.compactMap { find(type, in: $0) }.first } /// Share…'s anchor, in the toolbar's own views. private func anchor(_ hosted: Hosted) -> DocsShareAnchorView? { let frame = hosted.window.contentView?.superview return Self.find(DocsShareAnchorView.self, in: frame) } /// A real click, posted to the app's queue and delivered by `pump`. private func click(_ window: NSWindow, at point: NSPoint) async { for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { let event = NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)! NSApp.postEvent(event, atStart: false) await pump(0.05) } await pump(0.2) } private func center(of view: NSView) -> NSPoint { let rect = view.convert(view.bounds, to: nil) return NSPoint(x: rect.midX, y: rect.midY) } /// Opens the popover with a click on Share…. private func openShare(_ hosted: Hosted) async throws -> DocsSharePopover { let anchor = try XCTUnwrap(anchor(hosted)) let popover = try XCTUnwrap(anchor.popover) await click(hosted.window, at: center(of: anchor)) try await until("the popover opened") { popover.popover?.isShown == true } try await until("the panel loaded") { popover.panel?.information != nil } return popover } func testShareOpensThePanelUnderTheButtonWithFocusInTheEmailField() async throws { let hosted = try await host() defer { Task { await close(hosted) } } let share = try await openShare(hosted) let popover = try XCTUnwrap(share.popover) XCTAssertEqual(popover.behavior, .transient, "a click outside closes it while no URL shows") let panelWindow = try XCTUnwrap(popover.contentViewController?.view.window) try await until("the email field has the keyboard") { panelWindow.firstResponder is NSTextView } XCTAssertEqual(popover.contentViewController?.view.frame.width ?? 0, 420, accuracy: 1, "420pt wide") let anchorFrame = try XCTUnwrap(anchor(hosted)).convert(try XCTUnwrap(anchor(hosted)).bounds, to: nil) let panelFrame = hosted.window.convertFromScreen(panelWindow.frame) XCTAssertLessThan(panelFrame.maxY, anchorFrame.minY + 1, "under Share…, arrow at the top") } func testShareWhileOpenIsANoOp() async throws { let hosted = try await host() defer { Task { await close(hosted) } } let share = try await openShare(hosted) let first = try XCTUnwrap(share.popover) let loads = await hosted.server.shareLoads XCTAssertEqual(loads, 1) // A click on Share… is not a click outside: the popover stays, and // nothing opens or loads again. await click(hosted.window, at: center(of: try XCTUnwrap(anchor(hosted)))) XCTAssertTrue(share.popover === first && first.isShown, "the same popover, still open") let after = await hosted.server.shareLoads XCTAssertEqual(after, 1, "Share… while open did nothing") } func testTheOnceOnlyURLShowsOnceAndSurvivesAClickOutside() async throws { let hosted = try await host() defer { Task { await close(hosted) } } // Without a URL, a click outside closes it. var share = try await openShare(hosted) await click(hosted.window, at: NSPoint(x: 300, y: 200)) try await until("a click outside closed it") { share.popover == nil } share = try await openShare(hosted) let panel = try XCTUnwrap(share.panel) let published = await panel.setLink(true) XCTAssertTrue(published) XCTAssertNotNil(panel.onceURL) let popover = try XCTUnwrap(share.popover) XCTAssertEqual(popover.behavior, .applicationDefined, "not transient while the URL shows") await click(hosted.window, at: NSPoint(x: 300, y: 200)) XCTAssertTrue(popover.isShown, "a click outside does not close it while the URL shows") XCTAssertNotNil(panel.onceURL, "and the URL is still there") // Close: the URL goes with the panel, and a new panel never shows it. share.dismiss() XCTAssertNil(panel.onceURL) share = try await openShare(hosted) XCTAssertNil(share.panel?.onceURL, "shown once") XCTAssertEqual(share.popover?.behavior, .transient) } /// Fable on #178, finding 3: an earlier popover's close, arriving after /// a new one has opened, leaves the new one alone. func testAnOldPopoversLateCloseLeavesTheNewOneAlone() async throws { let hosted = try await host() defer { Task { await close(hosted) } } let share = try await openShare(hosted) let old = try XCTUnwrap(share.popover) share.dismiss() try await until("closed") { share.popover == nil } _ = try await openShare(hosted) let current = try XCTUnwrap(share.popover) XCTAssertFalse(current === old) share.popoverDidClose(Notification(name: NSPopover.didCloseNotification, object: old)) XCTAssertTrue(share.popover === current && current.isShown, "the new popover is still the one showing") XCTAssertNotNil(share.panel, "and its panel is still there") } /// Fable on #178, finding 4: Esc while an input method is composing in /// the email field (ja, zh-Hans, yue) belongs to the composition; the /// panel stays. Without marked text, Esc closes it. func testEscDuringAnIMECompositionLeavesThePanelOpen() async throws { let hosted = try await host() defer { Task { await close(hosted) } } let share = try await openShare(hosted) let panelWindow = try XCTUnwrap(share.popover?.contentViewController?.view.window) try await until("the email field has the keyboard") { panelWindow.firstResponder is NSTextView } let editor = try XCTUnwrap(panelWindow.firstResponder as? NSTextView) editor.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0)) XCTAssertTrue(editor.hasMarkedText()) NSApp.postEvent(esc(panelWindow), atStart: false) await pump(0.4) XCTAssertNotNil(share.popover, "Esc went to the composition, not the panel") editor.unmarkText() XCTAssertFalse(editor.hasMarkedText()) NSApp.postEvent(esc(panelWindow), atStart: false) try await until("Esc closed it once nothing was composing") { share.popover == nil } } private func esc(_ window: NSWindow) -> NSEvent { NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53)! } func testEscClosesItAndReturnsTheKeyboardToShare() async throws { let hosted = try await host() defer { Task { await close(hosted) } } let share = try await openShare(hosted) let panelWindow = try XCTUnwrap(share.popover?.contentViewController?.view.window) try await until("the email field has the keyboard") { panelWindow.firstResponder is NSTextView } let esc = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: panelWindow.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53)! NSApp.postEvent(esc, atStart: false) try await until("Esc closed it") { share.popover == nil } await pump(0.2) let anchor = try XCTUnwrap(anchor(hosted)) XCTAssertTrue(hosted.window.firstResponder === anchor, "the keyboard is back on Share…, not \(String(describing: hosted.window.firstResponder))") // Return there presses Share… again. let enter = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: hosted.window.windowNumber, context: nil, characters: "\r", charactersIgnoringModifiers: "\r", isARepeat: false, keyCode: 36)! NSApp.postEvent(enter, atStart: false) try await until("Return on Share… opened it again") { share.popover?.isShown == true } try await until("the panel loaded") { share.panel?.information != nil } // While the once-only URL shows, Esc still closes it (only Close and Esc do). let published = await share.panel?.setLink(true) XCTAssertEqual(published, true) XCTAssertEqual(share.popover?.behavior, .applicationDefined) let again = try XCTUnwrap(share.popover?.contentViewController?.view.window) // The email field has the keyboard (this test process is never the // active app, so no window here is key; the panel's own window is // still where the field editor is). try await until("the email field has the keyboard again") { again.firstResponder is NSTextView } let esc2 = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: again.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53)! NSApp.postEvent(esc2, atStart: false) try await until("Esc closed it with the URL showing") { share.popover == nil } await pump(0.2) XCTAssertTrue(hosted.window.firstResponder === anchor, "and the keyboard is back on Share…") } } /// ChromeServer's document, plus the share routes as share.go answers them. actor ShareWindowServer: NativeTransport { nonisolated let origin = URL(string: "https://docs.share.invalid")! let chrome = ChromeServer(canWrite: true) private(set) var shareLoads = 0 private var published = false func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { let json = ["Content-Type": "application/json"] switch (method, path) { case ("GET", "/d/doc/share"): shareLoads += 1 let state: [String: Any] = ["sqid": "doc", "title": "Chrome test", "grants": [["address": "bob@example.com", "role": "writer"]], "published": published, "public_url": "", "visibility": "team", "error": ""] return NativeResponse(data: try JSONSerialization.data(withJSONObject: state), status: 200, headers: json) case ("POST", "/d/doc/share/link"): published = String(decoding: body ?? Data(), as: UTF8.self).contains("on=1") let answer: [String: Any] = ["published": published, "public_url": published ? "https://docs.share.invalid/p/once" : ""] return NativeResponse(data: try JSONSerialization.data(withJSONObject: answer), status: 200, headers: json) default: return try await chrome.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes) } } func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { try await chrome.stream(path, onOpen: onOpen, onLine: onLine) } func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } } #endif