| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import Observation |
| 4 | import SwiftUI |
| 5 | |
| 6 | /// Shows the Share panel in a popover under Share… (spec 2026-11-22 §1, |
| 7 | /// "Share popover"): arrow at the top, 420pt wide. An `NSPopover` of its |
| 8 | /// own rather than SwiftUI's `.popover`, which cannot be made non-transient: |
| 9 | /// - transient, so a click outside closes it, except while the once-only |
| 10 | /// URL shows (`.applicationDefined`; only Close and Esc close it then); |
| 11 | /// - Share… while it is open does nothing (a click on Share… is not taken |
| 12 | /// as a click outside, which would close it and open it again); |
| 13 | /// - Close and Esc return the keyboard to Share…. |
| 14 | @MainActor final class DocsSharePopover: NSObject, NSPopoverDelegate { |
| 15 | /// The Share… button's own view (`DocsShareAnchor`). |
| 16 | weak var anchor: NSView? |
| 17 | /// The editor's view, for when Share… is in the toolbar's » menu. |
| 18 | weak var fallback: NSView? |
| 19 | private(set) var popover: NSPopover? |
| 20 | private(set) var panel: DocsSharePanelModel? |
| 21 | private var returnFocus = false |
| 22 | /// Esc while the panel's window has it: Close, whatever the behaviour |
| 23 | /// (a non-transient popover does not close itself on Esc). |
| 24 | private var escMonitor: Any? |
| 25 | var isShown: Bool { popover != nil } |
| 26 | |
| 27 | /// Shows `model`'s panel; nothing when one is already showing. |
| 28 | func present(_ model: DocsSharePanelModel, me: String?) { |
| 29 | guard popover == nil, let (view, rect) = positioning() else { return } |
| 30 | let popover = NSPopover() |
| 31 | popover.contentViewController = NSHostingController(rootView: DocsSharePanel(model: model, me: me, close: { [weak self] in self?.dismiss() })) |
| 32 | popover.delegate = self |
| 33 | popover.animates = !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion |
| 34 | self.popover = popover |
| 35 | panel = model |
| 36 | returnFocus = false |
| 37 | track() |
| 38 | popover.show(relativeTo: rect, of: view, preferredEdge: .minY) |
| 39 | // Opened from the keyboard (Return on Share…, File ▸ Share…) a |
| 40 | // popover is not made key, and the email field could not take focus. |
| 41 | popover.contentViewController?.view.window?.makeKey() |
| 42 | escMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in |
| 43 | guard event.keyCode == 53, event.modifierFlags.intersection(.deviceIndependentFlagsMask).isEmpty, |
| 44 | let self, let panelWindow = self.popover?.contentViewController?.view.window, event.window === panelWindow, |
| 45 | !self.composing else { return event } |
| 46 | self.dismiss() |
| 47 | return nil |
| 48 | } |
| 49 | Task { await model.load() } |
| 50 | } |
| 51 | |
| 52 | /// Close and Esc: always close, and give the keyboard back to Share…. |
| 53 | func dismiss() { |
| 54 | guard let popover else { return } |
| 55 | returnFocus = true |
| 56 | popover.close() |
| 57 | // close() does not always post didClose when the popover never |
| 58 | // finished appearing; finish here, once. |
| 59 | finish() |
| 60 | } |
| 61 | |
| 62 | /// The email field holds marked text: an input method is composing. |
| 63 | private var composing: Bool { |
| 64 | (popover?.contentViewController?.view.window?.firstResponder as? NSTextView)?.hasMarkedText() == true |
| 65 | } |
| 66 | |
| 67 | /// A popover released while it shows must not leave its monitor behind. |
| 68 | isolated deinit { |
| 69 | if let escMonitor { NSEvent.removeMonitor(escMonitor) } |
| 70 | } |
| 71 | |
| 72 | func popoverShouldClose(_ popover: NSPopover) -> Bool { |
| 73 | // Esc, which a transient popover handles itself before the panel's |
| 74 | // Close shortcut sees it: Close's rules, always, URL or not. |
| 75 | if let event = NSApp.currentEvent, event.type == .keyDown, event.keyCode == 53 { |
| 76 | // Esc during an IME composition (ja, zh-Hans, yue) is the input |
| 77 | // method's: it cancels the composition, not the panel. |
| 78 | if composing { return false } |
| 79 | returnFocus = true |
| 80 | return true |
| 81 | } |
| 82 | if panel?.blocksOutsideDismissal == true { return false } |
| 83 | // The click that would close it is on Share… itself: Share… while |
| 84 | // open is a no-op, not close-then-open (which would load again). |
| 85 | // (SharePopoverTests runs in a process that is never the active |
| 86 | // app, where such a click does not reach here; this is for the app.) |
| 87 | if let anchor, let event = NSApp.currentEvent, [.leftMouseDown, .rightMouseDown].contains(event.type), |
| 88 | event.window === anchor.window, anchor.bounds.contains(anchor.convert(event.locationInWindow, from: nil)) { |
| 89 | return false |
| 90 | } |
| 91 | return true |
| 92 | } |
| 93 | |
| 94 | /// Only this popover's own close: an earlier one's, arriving late, must |
| 95 | /// not tear down the one showing now (Fable on #178, finding 3). |
| 96 | func popoverDidClose(_ notification: Notification) { |
| 97 | guard let closed = notification.object as? NSPopover, closed === popover else { return } |
| 98 | finish() |
| 99 | } |
| 100 | |
| 101 | private func finish() { |
| 102 | guard popover != nil else { return } |
| 103 | if let escMonitor { NSEvent.removeMonitor(escMonitor) } |
| 104 | escMonitor = nil |
| 105 | popover = nil |
| 106 | panel?.closed() |
| 107 | panel = nil |
| 108 | // After the popover's window has gone: until then the parent is not |
| 109 | // key again, and its first responder is put back as it was. |
| 110 | if returnFocus, let target = focusTarget() { |
| 111 | DispatchQueue.main.async { [weak target] in |
| 112 | guard let target, let window = target.window else { return } |
| 113 | window.makeFirstResponder(target) |
| 114 | } |
| 115 | } |
| 116 | returnFocus = false |
| 117 | } |
| 118 | |
| 119 | /// The panel's behaviour follows the once-only URL: not transient while |
| 120 | /// it shows. |
| 121 | private func track() { |
| 122 | guard let panel, let popover else { return } |
| 123 | let blocks = withObservationTracking { panel.blocksOutsideDismissal } onChange: { [weak self] in |
| 124 | Task { @MainActor in self?.track() } |
| 125 | } |
| 126 | popover.behavior = blocks ? .applicationDefined : .transient |
| 127 | } |
| 128 | |
| 129 | /// Under Share…, or, when it is in the » menu, under the toolbar at the |
| 130 | /// window's trailing edge. |
| 131 | private func positioning() -> (NSView, NSRect)? { |
| 132 | if let anchor, anchor.window != nil, !anchor.isHiddenOrHasHiddenAncestor, !anchor.visibleRect.isEmpty { |
| 133 | return (anchor, anchor.bounds) |
| 134 | } |
| 135 | guard let fallback, fallback.window != nil else { return nil } |
| 136 | let bounds = fallback.bounds |
| 137 | let trailing = fallback.userInterfaceLayoutDirection == .rightToLeft ? bounds.minX + 48 : bounds.maxX - 48 |
| 138 | let top = fallback.isFlipped ? bounds.minY : bounds.maxY - 1 |
| 139 | return (fallback, NSRect(x: trailing, y: top, width: 1, height: 1)) |
| 140 | } |
| 141 | |
| 142 | /// Where Close and Esc put the keyboard: Share…'s anchor, which takes it |
| 143 | /// on the button's behalf (a focus ring round the pill; Space or Return |
| 144 | /// opens the panel again). SwiftUI's toolbar button cannot be given the |
| 145 | /// keyboard from here, and with Full Keyboard Access off it takes none. |
| 146 | func focusTarget() -> NSView? { anchor } |
| 147 | } |
| 148 | |
| 149 | /// The view Share… is drawn over: where the popover hangs from. |
| 150 | struct DocsShareAnchor: NSViewRepresentable { |
| 151 | let popover: DocsSharePopover |
| 152 | /// Share…'s own action, for Space and Return while the anchor has the keyboard. |
| 153 | let activate: () -> Void |
| 154 | func makeNSView(context: Context) -> DocsShareAnchorView { |
| 155 | let view = DocsShareAnchorView() |
| 156 | view.popover = popover |
| 157 | view.activate = activate |
| 158 | popover.anchor = view |
| 159 | return view |
| 160 | } |
| 161 | func updateNSView(_ view: DocsShareAnchorView, context: Context) { |
| 162 | view.popover = popover |
| 163 | view.activate = activate |
| 164 | if popover.anchor !== view { popover.anchor = view } |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// Share…'s anchor; it knows its popover, so a window test can find both. |
| 169 | /// Clicks go through it to the button. It takes the keyboard only when the |
| 170 | /// popover gives it back (never by Tab: the button keeps its own place). |
| 171 | final class DocsShareAnchorView: NSView { |
| 172 | weak var popover: DocsSharePopover? |
| 173 | var activate: (() -> Void)? |
| 174 | override func hitTest(_ point: NSPoint) -> NSView? { nil } |
| 175 | override var acceptsFirstResponder: Bool { true } |
| 176 | override var canBecomeKeyView: Bool { false } |
| 177 | override var focusRingMaskBounds: NSRect { bounds } |
| 178 | override func drawFocusRingMask() { |
| 179 | NSBezierPath(roundedRect: bounds, xRadius: bounds.height / 2, yRadius: bounds.height / 2).fill() |
| 180 | } |
| 181 | override func becomeFirstResponder() -> Bool { focusRingType = .exterior; noteFocusRingMaskChanged(); return true } |
| 182 | override func keyDown(with event: NSEvent) { |
| 183 | // Space, Return and Enter press Share…, as on the button itself. |
| 184 | if [49, 36, 76].contains(event.keyCode), event.modifierFlags.intersection(.deviceIndependentFlagsMask).isEmpty, let activate { |
| 185 | activate() |
| 186 | } else { |
| 187 | super.keyDown(with: event) |
| 188 | } |
| 189 | } |
| 190 | override func isAccessibilityElement() -> Bool { false } |
| 191 | } |
| 192 | |
| 193 | /// The editor's view, for the popover when Share… is in the » menu. |
| 194 | struct DocsShareFallback: NSViewRepresentable { |
| 195 | let popover: DocsSharePopover |
| 196 | func makeNSView(context: Context) -> NSView { |
| 197 | let view = NSView() |
| 198 | popover.fallback = view |
| 199 | return view |
| 200 | } |
| 201 | func updateNSView(_ view: NSView, context: Context) { if popover.fallback !== view { popover.fallback = view } } |
| 202 | } |
| 203 | #endif |
| 204 | |