SPB Git

Repository Public License

WebEngineDelegates.swift 8.9 KB 181 lines swift

1import Foundation2import NavigatorCore3import WebKit45#if canImport(AppKit)6import AppKit7#elseif canImport(UIKit)8import UIKit9#endif1011/// Tab-level decisions the web layer cannot take alone. Implemented by the window/tab controller.12@MainActor13public protocol WebEngineNavigationDelegate: AnyObject {14    /// The page opened a window (`window.open`, `target=_blank`) and the popup policy let it through.15    /// `child` already owns the web view WebKit requires for the opener relationship: adopt it as a new tab and16    /// return `true`, or return `false` to refuse (the child is discarded and the page gets `null`).17    func webEngine(_ engine: WebEngine, didCreateChild child: WebEngine, for request: NewTabRequest) -> Bool1819    /// The engine wants `request.url` opened in a new, unrelated tab (⌘-click, context-menu action, a blocked20    /// popup the user chose to open).21    func webEngine(_ engine: WebEngine, requestsNewTab request: NewTabRequest)2223    /// The page wants to leave the browser (`mailto:`, `tel:`, `itms-apps:`, any app scheme). The navigation was24    /// cancelled. Ask the user, naming the scheme/application, then open the URL yourself (`NSWorkspace` /25    /// `UIApplication`). Return whether it was opened. When `request.isUserGesture` is false the page did this26    /// on its own: prefer a non-modal notice.27    func webEngine(_ engine: WebEngine, requestsExternalApp request: ExternalAppRequest) async -> Bool2829    /// The page called `window.close()` on a window it opened.30    func webEngineDidRequestClose(_ engine: WebEngine)31}3233public extension WebEngineNavigationDelegate {34    func webEngineDidRequestClose(_ engine: WebEngine) {}35}3637/// Prompts shown to the user on behalf of a page. Implemented by the tab's UI.38/// With no UI delegate every prompt resolves to the safe answer: dialogs are dismissed, permissions denied,39/// authentication left to fail, file choosers cancelled.40@MainActor41public protocol WebEngineUIDelegate: AnyObject {42    /// `alert`, `confirm`, `prompt`. From `dialog.sequenceOnPage == 2` the UI must offer the suppression choice43    /// and report it in the response.44    func webEngine(_ engine: WebEngine, present dialog: JavaScriptDialog) async -> JavaScriptDialogResponse4546    /// HTTP Basic / Digest / NTLM. Nothing is stored unless the response says so, and then only for the session.47    func webEngine(_ engine: WebEngine, credentialsFor request: AuthenticationRequest) async -> AuthenticationResponse4849    /// A permission whose stored verdict is "ask" (camera, microphone, location, device motion).50    func webEngine(_ engine: WebEngine, decide request: PermissionRequest) async -> PermissionPromptResponse5152    /// `<input type=file>` on macOS (iOS presents its own picker). Return `nil` to cancel.53    func webEngine(_ engine: WebEngine, chooseFilesFor request: FileChooserRequest) async -> [URL]?54}5556public extension WebEngineUIDelegate {57    func webEngine(_ engine: WebEngine, chooseFilesFor request: FileChooserRequest) async -> [URL]? { nil }58}5960/// Context menus. The UI decides which actions exist; `WebEngine.perform(_:on:)` executes the standard ones.61@MainActor62public protocol WebEngineContextMenuDelegate: AnyObject {63    #if os(macOS)64    /// Called from `NSView.willOpenMenu` with WebKit's proposed menu. Mutate `menu` in place: remove WebKit's65    /// window-oriented items (see `WebKitMenuItemIdentifier`) and insert tab-oriented ones.66    func webEngine(_ engine: WebEngine, willOpen menu: NSMenu, for element: ContextMenuElement)67    #elseif os(iOS)68    /// Return the menu (and optional preview) for a long-pressed link, or `nil` for no menu.69    /// `WebContextMenu.configuration(for:engine:actions:)` builds a standard one.70    func webEngine(_ engine: WebEngine, contextMenuConfigurationFor element: ContextMenuElement) -> UIContextMenuConfiguration?71    /// The user tapped the preview: usually open the link in this tab.72    func webEngine(_ engine: WebEngine, commitPreviewFor element: ContextMenuElement)73    #endif74}7576#if os(iOS)77public extension WebEngineContextMenuDelegate {78    func webEngine(_ engine: WebEngine, commitPreviewFor element: ContextMenuElement) {79        if let url = element.linkURL { engine.load(url, transition: .link) }80    }81}82#endif8384/// Identifiers WebKit puts on the items of its macOS context menu (`NSMenuItem.identifier`).85/// They are read through public AppKit API but are not documented by Apple: treat a missing item as normal.86public enum WebKitMenuItemIdentifier {87    public static let openLink = "WKMenuItemIdentifierOpenLink"88    public static let openLinkInNewWindow = "WKMenuItemIdentifierOpenLinkInNewWindow"89    public static let downloadLinkedFile = "WKMenuItemIdentifierDownloadLinkedFile"90    public static let copyLink = "WKMenuItemIdentifierCopyLink"91    public static let openImageInNewWindow = "WKMenuItemIdentifierOpenImageInNewWindow"92    public static let downloadImage = "WKMenuItemIdentifierDownloadImage"93    public static let copyImage = "WKMenuItemIdentifierCopyImage"94    public static let openMediaInNewWindow = "WKMenuItemIdentifierOpenMediaInNewWindow"95    public static let downloadMedia = "WKMenuItemIdentifierDownloadMedia"96    public static let openFrameInNewWindow = "WKMenuItemIdentifierOpenFrameInNewWindow"97    public static let searchWeb = "WKMenuItemIdentifierSearchWeb"98    public static let inspectElement = "WKMenuItemIdentifierInspectElement"99    public static let reload = "WKMenuItemIdentifierReload"100    public static let goBack = "WKMenuItemIdentifierGoBack"101    public static let goForward = "WKMenuItemIdentifierGoForward"102103    /// Items that create a window by themselves; a tabbed browser replaces them.104    public static let windowOpening: Set<String> = [105        openLinkInNewWindow, openImageInNewWindow, openMediaInNewWindow, openFrameInNewWindow,106    ]107}108109/// `WKWebView` subclass used by every engine. The subclass exists for one reason: on macOS the only public hook110/// on WebKit's context menu is `NSView.willOpenMenu(_:with:)`.111public final class NavigatorWebView: WKWebView {112    weak var engine: WebEngine?113114    #if os(macOS)115    public override func willOpenMenu(_ menu: NSMenu, with event: NSEvent) {116        super.willOpenMenu(menu, with: event)117        engine?.willOpenContextMenu(menu)118    }119    #endif120}121122#if os(iOS)123/// Builds standard iOS context menus from `ContextMenuAction`s.124@MainActor125public enum WebContextMenu {126    public static let defaultLinkActions: [ContextMenuAction] = [127        .openLink, .openLinkInNewTab, .openLinkInSplit, .copyLink, .shareLink, .downloadLink,128    ]129130    /// A configuration whose actions call `handler` (default: `engine.perform`). `preview` supplies the link131    /// preview controller; `nil` lets UIKit show the default (no) preview.132    public static func configuration(for element: ContextMenuElement, engine: WebEngine,133                                     actions: [ContextMenuAction] = defaultLinkActions,134                                     preview: (@MainActor () -> UIViewController?)? = nil,135                                     handler: (@MainActor (ContextMenuAction, ContextMenuElement) -> Void)? = nil)136        -> UIContextMenuConfiguration? {137        guard element.linkURL != nil else { return nil }138        let run: @MainActor (ContextMenuAction) -> Void = { [weak engine] action in139            if let handler { handler(action, element) } else { _ = engine?.perform(action, on: element) }140        }141        return UIContextMenuConfiguration(identifier: nil, previewProvider: preview.map { provider in { provider() } }) { _ in142            UIMenu(children: actions.map { action in143                UIAction(title: title(for: action), image: UIImage(systemName: symbol(for: action))) { _ in run(action) }144            })145        }146    }147148    /// English titles; the UI layer localises by building its own actions when needed.149    public static func title(for action: ContextMenuAction) -> String {150        switch action {151        case .openLink: "Open"152        case .openLinkInNewTab: "Open in New Tab"153        case .openLinkInBackgroundTab: "Open in Background"154        case .openLinkInSplit: "Open in Split View"155        case .copyLink: "Copy Link"156        case .shareLink: "Share…"157        case .downloadLink: "Download Linked File"158        case .openImageInNewTab: "Open Image in New Tab"159        case .copyImageAddress: "Copy Image Address"160        case .downloadImage: "Save Image"161        case .copySelection: "Copy"162        case .searchSelection: "Search"163        }164    }165166    public static func symbol(for action: ContextMenuAction) -> String {167        switch action {168        case .openLink: "safari"169        case .openLinkInNewTab: "plus.square.on.square"170        case .openLinkInBackgroundTab: "square.stack"171        case .openLinkInSplit: "rectangle.split.2x1"172        case .copyLink, .copyImageAddress, .copySelection: "doc.on.doc"173        case .shareLink: "square.and.arrow.up"174        case .downloadLink, .downloadImage: "arrow.down.circle"175        case .openImageInNewTab: "photo"176        case .searchSelection: "magnifyingglass"177        }178    }179}180#endif181
Files main
Menu

Theme