// The system share sheet: where a finished file goes, on either system. A // share sheet on the phone and the Finder on the Mac — a capability the two // systems answer differently, so it branches here, at its own site, and the // screens that hand a file over (a document, its rendition, a release asset) // call it without branching themselves. import Foundation import SwiftUI #if canImport(UIKit) import UIKit #endif /// The system share sheet, reached from a screen rather than a `ShareLink`. /// /// `ShareLink` wants its item at BUILD time; an export is produced on a tap and /// is not there until the call comes back. So the sheet is presented on the key /// window, which is also the only presenter that survives being called from a /// popover menu's action. enum ShareSheet { @MainActor static func present(_ file: URL) { #if os(macOS) NSWorkspace.shared.activateFileViewerSelecting([file]) #else present(items: [file]) #endif } /// Words handed to the share sheet (a slip's Share); the Mac, which has /// no sheet to raise from here, puts them on the pasteboard. @MainActor static func present(words: String) { #if os(macOS) SystemClipboard().put(words) #else present(items: [words]) #endif } /// A small text file and its words together (Settings' Share a report): /// apps that take files get the file, apps that take words the words. @MainActor static func present(file: URL, words: String) { #if os(macOS) NSWorkspace.shared.activateFileViewerSelecting([file]) #else present(items: [file, words]) #endif } #if !os(macOS) @MainActor private static func present(items: [Any]) { let scenes = UIApplication.shared.connectedScenes guard let window = scenes.compactMap({ $0 as? UIWindowScene }) .flatMap(\.windows) .first(where: \.isKeyWindow), var top = window.rootViewController else { return } // Over whatever is already presented (a page opened full screen), or // the sheet would not show at all. while let presented = top.presentedViewController, !presented.isBeingDismissed { top = presented } let sheet = UIActivityViewController(activityItems: items, applicationActivities: nil) // An iPad has no "over the whole screen" presentation for this, and a // popover with no anchor crashes rather than degrading. sheet.popoverPresentationController?.sourceView = window sheet.popoverPresentationController?.sourceRect = CGRect( x: window.bounds.midX, y: window.bounds.maxY, width: 0, height: 0 ) top.present(sheet, animated: true) } #endif }