#if os(macOS) import AppKit import Observation import SwiftUI /// Shows the Share panel in a popover under Share… (spec 2026-11-22 §1, /// "Share popover"): arrow at the top, 420pt wide. An `NSPopover` of its /// own rather than SwiftUI's `.popover`, which cannot be made non-transient: /// - transient, so a click outside closes it, except while the once-only /// URL shows (`.applicationDefined`; only Close and Esc close it then); /// - Share… while it is open does nothing (a click on Share… is not taken /// as a click outside, which would close it and open it again); /// - Close and Esc return the keyboard to Share…. @MainActor final class DocsSharePopover: NSObject, NSPopoverDelegate { /// The Share… button's own view (`DocsShareAnchor`). weak var anchor: NSView? /// The editor's view, for when Share… is in the toolbar's » menu. weak var fallback: NSView? private(set) var popover: NSPopover? private(set) var panel: DocsSharePanelModel? private var returnFocus = false /// Esc while the panel's window has it: Close, whatever the behaviour /// (a non-transient popover does not close itself on Esc). private var escMonitor: Any? var isShown: Bool { popover != nil } /// Shows `model`'s panel; nothing when one is already showing. func present(_ model: DocsSharePanelModel, me: String?) { guard popover == nil, let (view, rect) = positioning() else { return } let popover = NSPopover() popover.contentViewController = NSHostingController(rootView: DocsSharePanel(model: model, me: me, close: { [weak self] in self?.dismiss() })) popover.delegate = self popover.animates = !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion self.popover = popover panel = model returnFocus = false track() popover.show(relativeTo: rect, of: view, preferredEdge: .minY) // Opened from the keyboard (Return on Share…, File ▸ Share…) a // popover is not made key, and the email field could not take focus. popover.contentViewController?.view.window?.makeKey() escMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in guard event.keyCode == 53, event.modifierFlags.intersection(.deviceIndependentFlagsMask).isEmpty, let self, let panelWindow = self.popover?.contentViewController?.view.window, event.window === panelWindow, !self.composing else { return event } self.dismiss() return nil } Task { await model.load() } } /// Close and Esc: always close, and give the keyboard back to Share…. func dismiss() { guard let popover else { return } returnFocus = true popover.close() // close() does not always post didClose when the popover never // finished appearing; finish here, once. finish() } /// The email field holds marked text: an input method is composing. private var composing: Bool { (popover?.contentViewController?.view.window?.firstResponder as? NSTextView)?.hasMarkedText() == true } /// A popover released while it shows must not leave its monitor behind. isolated deinit { if let escMonitor { NSEvent.removeMonitor(escMonitor) } } func popoverShouldClose(_ popover: NSPopover) -> Bool { // Esc, which a transient popover handles itself before the panel's // Close shortcut sees it: Close's rules, always, URL or not. if let event = NSApp.currentEvent, event.type == .keyDown, event.keyCode == 53 { // Esc during an IME composition (ja, zh-Hans, yue) is the input // method's: it cancels the composition, not the panel. if composing { return false } returnFocus = true return true } if panel?.blocksOutsideDismissal == true { return false } // The click that would close it is on Share… itself: Share… while // open is a no-op, not close-then-open (which would load again). // (SharePopoverTests runs in a process that is never the active // app, where such a click does not reach here; this is for the app.) if let anchor, let event = NSApp.currentEvent, [.leftMouseDown, .rightMouseDown].contains(event.type), event.window === anchor.window, anchor.bounds.contains(anchor.convert(event.locationInWindow, from: nil)) { return false } return true } /// Only this popover's own close: an earlier one's, arriving late, must /// not tear down the one showing now (Fable on #178, finding 3). func popoverDidClose(_ notification: Notification) { guard let closed = notification.object as? NSPopover, closed === popover else { return } finish() } private func finish() { guard popover != nil else { return } if let escMonitor { NSEvent.removeMonitor(escMonitor) } escMonitor = nil popover = nil panel?.closed() panel = nil // After the popover's window has gone: until then the parent is not // key again, and its first responder is put back as it was. if returnFocus, let target = focusTarget() { DispatchQueue.main.async { [weak target] in guard let target, let window = target.window else { return } window.makeFirstResponder(target) } } returnFocus = false } /// The panel's behaviour follows the once-only URL: not transient while /// it shows. private func track() { guard let panel, let popover else { return } let blocks = withObservationTracking { panel.blocksOutsideDismissal } onChange: { [weak self] in Task { @MainActor in self?.track() } } popover.behavior = blocks ? .applicationDefined : .transient } /// Under Share…, or, when it is in the » menu, under the toolbar at the /// window's trailing edge. private func positioning() -> (NSView, NSRect)? { if let anchor, anchor.window != nil, !anchor.isHiddenOrHasHiddenAncestor, !anchor.visibleRect.isEmpty { return (anchor, anchor.bounds) } guard let fallback, fallback.window != nil else { return nil } let bounds = fallback.bounds let trailing = fallback.userInterfaceLayoutDirection == .rightToLeft ? bounds.minX + 48 : bounds.maxX - 48 let top = fallback.isFlipped ? bounds.minY : bounds.maxY - 1 return (fallback, NSRect(x: trailing, y: top, width: 1, height: 1)) } /// Where Close and Esc put the keyboard: Share…'s anchor, which takes it /// on the button's behalf (a focus ring round the pill; Space or Return /// opens the panel again). SwiftUI's toolbar button cannot be given the /// keyboard from here, and with Full Keyboard Access off it takes none. func focusTarget() -> NSView? { anchor } } /// The view Share… is drawn over: where the popover hangs from. struct DocsShareAnchor: NSViewRepresentable { let popover: DocsSharePopover /// Share…'s own action, for Space and Return while the anchor has the keyboard. let activate: () -> Void func makeNSView(context: Context) -> DocsShareAnchorView { let view = DocsShareAnchorView() view.popover = popover view.activate = activate popover.anchor = view return view } func updateNSView(_ view: DocsShareAnchorView, context: Context) { view.popover = popover view.activate = activate if popover.anchor !== view { popover.anchor = view } } } /// Share…'s anchor; it knows its popover, so a window test can find both. /// Clicks go through it to the button. It takes the keyboard only when the /// popover gives it back (never by Tab: the button keeps its own place). final class DocsShareAnchorView: NSView { weak var popover: DocsSharePopover? var activate: (() -> Void)? override func hitTest(_ point: NSPoint) -> NSView? { nil } override var acceptsFirstResponder: Bool { true } override var canBecomeKeyView: Bool { false } override var focusRingMaskBounds: NSRect { bounds } override func drawFocusRingMask() { NSBezierPath(roundedRect: bounds, xRadius: bounds.height / 2, yRadius: bounds.height / 2).fill() } override func becomeFirstResponder() -> Bool { focusRingType = .exterior; noteFocusRingMaskChanged(); return true } override func keyDown(with event: NSEvent) { // Space, Return and Enter press Share…, as on the button itself. if [49, 36, 76].contains(event.keyCode), event.modifierFlags.intersection(.deviceIndependentFlagsMask).isEmpty, let activate { activate() } else { super.keyDown(with: event) } } override func isAccessibilityElement() -> Bool { false } } /// The editor's view, for the popover when Share… is in the » menu. struct DocsShareFallback: NSViewRepresentable { let popover: DocsSharePopover func makeNSView(context: Context) -> NSView { let view = NSView() popover.fallback = view return view } func updateNSView(_ view: NSView, context: Context) { if popover.fallback !== view { popover.fallback = view } } } #endif