SPB Git

Repository Public License

Prompts.swift 13.8 KB 289 lines swift

1import DownloadEngine2import LunarDesign3import NavigatorCore4import PrivacyEngine5import SwiftUI6import WebRuntime78/// Dims the page and shows the prompt of the selected tab. The prompt belongs to the tab, not to the window:9/// other tabs stay usable.10struct PromptOverlay: View {11    @Environment(\.lunarTheme) private var theme12    let window: WindowModel13    let prompt: PagePrompt1415    var body: some View {16        ZStack {17            Rectangle().fill(LunarRGBA.black.withAlpha(theme.isDark ? 0.45 : 0.25))18                .accessibilityHidden(true)19            LunarCard(padding: LunarSpacing.lg, shape: .lg, elevation: .floating) {20                content.frame(maxWidth: .infinity, alignment: .leading)21            }22            .frame(maxWidth: 420)23            .padding(LunarSpacing.lg)24            .accessibilityAddTraits(.isModal)25        }26        .id(prompt.id)27        .transition(.opacity)28        .accessibilityElement(children: .contain)29        .accessibilityIdentifier("prompt")30    }3132    @ViewBuilder private var content: some View {33        switch prompt.kind {34        case .dialog(let dialog): DialogPrompt(dialog: dialog) { window.prompts.answer(prompt, with: .dialog($0)) }35        case .authentication(let request):36            AuthenticationPrompt(request: request) { window.prompts.answer(prompt, with: .authentication($0)) }37        case .permission(let request):38            PermissionPrompt(request: request) { allow, duration in39                window.answerPermission(prompt, allow: allow, duration: duration)40            }41        case .externalApp(let request, let name):42            ExternalAppPrompt(request: request, applicationName: name) { window.prompts.answer(prompt, with: .externalApp($0)) }43        case .download(let question):44            DownloadPrompt(question: question) { window.prompts.answer(prompt, with: .download($0)) }45        }46    }47}4849private struct PromptHeader: View {50    @Environment(\.lunarTheme) private var theme51    let icon: String52    let title: String53    let origin: String?5455    var body: some View {56        HStack(alignment: .top, spacing: LunarSpacing.sm) {57            LunarIconView(.symbol(icon), size: 22).foregroundStyle(theme.accent)58                .frame(width: 40, height: 40)59                .background { Circle().fill(theme.selection) }60            VStack(alignment: .leading, spacing: 2) {61                Text(title).lunarFont(.headline).foregroundStyle(theme.textPrimary)62                    .fixedSize(horizontal: false, vertical: true)63                    .accessibilityAddTraits(.isHeader)64                if let origin {65                    Text(origin).lunarFont(.mono).foregroundStyle(theme.textSecondary).lineLimit(1).truncationMode(.middle)66                        .accessibilityIdentifier("prompt.origin")67                }68            }69        }70    }71}7273struct DialogPrompt: View {74    @Environment(\.lunarTheme) private var theme75    let dialog: JavaScriptDialog76    let respond: (JavaScriptDialogResponse) -> Void77    @State private var text = ""78    @State private var suppress = false7980    private var isPrompt: Bool { if case .prompt = dialog.kind { true } else { false } }81    private var isAlert: Bool { if case .alert = dialog.kind { true } else { false } }8283    var body: some View {84        VStack(alignment: .leading, spacing: LunarSpacing.md) {85            PromptHeader(icon: "text.bubble", title: L("This page says"),86                         origin: dialog.origin.map(\.host) ?? L("Unknown page"))87            ScrollView {88                Text(dialog.message).lunarFont(.body).foregroundStyle(theme.textPrimary)89                    .frame(maxWidth: .infinity, alignment: .leading)90                    .textSelection(.enabled)91            }92            .frame(maxHeight: 180)93            .fixedSize(horizontal: false, vertical: dialog.message.count < 400)94            if isPrompt {95                LunarTextField(L("Answer"), text: $text)96                    .onSubmit { respond(JavaScriptDialogResponse(accepted: true, text: text, suppressFurtherDialogs: suppress)) }97                    .accessibilityIdentifier("prompt.text")98            }99            if dialog.sequenceOnPage >= 2 {100                Toggle(L("Prevent this page from creating more dialogs"), isOn: $suppress)101                    .toggleStyle(.lunar)102                    .lunarFont(.footnote)103                    .foregroundStyle(theme.textSecondary)104                    .accessibilityIdentifier("prompt.suppress")105            }106            HStack(spacing: LunarSpacing.xs) {107                Spacer(minLength: 0)108                if !isAlert {109                    Button(L("Cancel")) { respond(JavaScriptDialogResponse(accepted: false, suppressFurtherDialogs: suppress)) }110                        .buttonStyle(.lunar(.secondary))111                        .keyboardShortcut(.cancelAction)112                        .accessibilityIdentifier("prompt.cancel")113                }114                Button(L("OK")) {115                    respond(JavaScriptDialogResponse(accepted: true, text: isPrompt ? text : nil, suppressFurtherDialogs: suppress))116                }117                .buttonStyle(.lunar(.primary))118                .keyboardShortcut(.defaultAction)119                .accessibilityIdentifier("prompt.ok")120            }121        }122        .onAppear { if case .prompt(let defaultText) = dialog.kind { text = defaultText ?? "" } }123    }124}125126struct AuthenticationPrompt: View {127    @Environment(\.lunarTheme) private var theme128    let request: AuthenticationRequest129    let respond: (AuthenticationResponse) -> Void130    @State private var user = ""131    @State private var password = ""132    @State private var remember = true133    @FocusState private var passwordFocused: Bool134135    var body: some View {136        VStack(alignment: .leading, spacing: LunarSpacing.md) {137            PromptHeader(icon: "person.badge.key", title: request.isProxy ? L("The proxy asks you to sign in") : L("This site asks you to sign in"),138                         origin: request.port == 443 || request.port == 80 ? request.host : "\(request.host):\(request.port)")139            if let realm = request.realm, !realm.isEmpty {140                Text(L("The site says: “%@”", realm)).lunarFont(.callout).foregroundStyle(theme.textSecondary)141                    .fixedSize(horizontal: false, vertical: true)142            }143            if !request.isSecureTransport {144                LunarBadge(L("Your password will be sent without encryption"), status: .warning)145            }146            if request.previousFailureCount > 0 {147                Text(L("The name or password was not accepted.")).lunarFont(.footnote).foregroundStyle(theme.danger)148            }149            LunarTextField(L("User name"), text: $user, icon: .symbol("person"))150                #if os(iOS)151                .textInputAutocapitalization(.never)152                .autocorrectionDisabled()153                .textContentType(.username)154                #endif155                .accessibilityIdentifier("auth.user")156            SecureField("", text: $password, prompt: Text(L("Password")).foregroundStyle(theme.textTertiary))157                .lunarField(isFocused: passwordFocused)158                .focused($passwordFocused)159                .onSubmit(submit)160                .accessibilityLabel(L("Password"))161                .accessibilityIdentifier("auth.password")162            Toggle(L("Stay signed in until I quit"), isOn: $remember)163                .toggleStyle(.lunar).lunarFont(.footnote).foregroundStyle(theme.textSecondary)164            HStack(spacing: LunarSpacing.xs) {165                Spacer(minLength: 0)166                Button(L("Cancel")) { respond(.cancel) }.buttonStyle(.lunar(.secondary)).keyboardShortcut(.cancelAction)167                Button(L("Sign In"), action: submit).buttonStyle(.lunar(.primary)).keyboardShortcut(.defaultAction)168                    .disabled(user.isEmpty)169                    .accessibilityIdentifier("auth.submit")170            }171        }172        .onAppear { user = request.proposedUser ?? "" }173    }174175    private func submit() {176        guard !user.isEmpty else { return }177        respond(.credential(user: user, password: password, rememberForSession: remember))178    }179}180181struct PermissionPrompt: View {182    @Environment(\.lunarTheme) private var theme183    let request: PermissionRequest184    /// Whether the site may use the feature, and for how long the answer holds.185    let respond: (Bool, PermissionDuration) -> Void186187    var body: some View {188        VStack(alignment: .leading, spacing: LunarSpacing.md) {189            PromptHeader(icon: icon, title: title, origin: request.origin.description)190            if let frame = request.requestingOrigin, frame != request.origin {191                Text(L("Requested by embedded content from %@.", frame.host)).lunarFont(.footnote)192                    .foregroundStyle(theme.textSecondary).fixedSize(horizontal: false, vertical: true)193            }194            VStack(spacing: LunarSpacing.xs) {195                Button(L("Allow Once")) { respond(true, .once) }196                    .buttonStyle(.lunar(.primary, fullWidth: true))197                    .accessibilityIdentifier("permission.allowOnce")198                Button(L("Allow for This Session")) { respond(true, .session) }199                    .buttonStyle(.lunar(.secondary, size: .compact, fullWidth: true))200                    .accessibilityHint(L("Until you quit ORIX Navigator"))201                    .accessibilityIdentifier("permission.allowSession")202                Button(L("Allow for 24 Hours")) { respond(true, .day) }203                    .buttonStyle(.lunar(.secondary, size: .compact, fullWidth: true))204                    .accessibilityIdentifier("permission.allowDay")205                Button(L("Always Allow for This Site")) { respond(true, .always) }206                    .buttonStyle(.lunar(.secondary, size: .compact, fullWidth: true))207                    .accessibilityIdentifier("permission.allow")208                Button(L("Don’t Allow")) { respond(false, .once) }209                    .buttonStyle(.lunar(.secondary, fullWidth: true))210                    .keyboardShortcut(.cancelAction)211                    .accessibilityIdentifier("permission.deny")212            }213        }214    }215216    private var icon: String {217        if request.kinds.contains(.camera) { return "video" }218        if request.kinds.contains(.microphone) { return "mic" }219        if request.kinds.contains(.location) { return "location" }220        return "hand.raised"221    }222223    private var title: String {224        let kinds = Set(request.kinds)225        if kinds.contains(.camera) && kinds.contains(.microphone) { return L("Allow this site to use your camera and microphone?") }226        if kinds.contains(.camera) { return L("Allow this site to use your camera?") }227        if kinds.contains(.microphone) { return L("Allow this site to use your microphone?") }228        if kinds.contains(.location) { return L("Allow this site to know your location?") }229        if kinds.contains(.deviceMotion) { return L("Allow this site to read motion and orientation?") }230        return L("Allow this site to use a protected feature?")231    }232}233234struct ExternalAppPrompt: View {235    @Environment(\.lunarTheme) private var theme236    let request: ExternalAppRequest237    let applicationName: String?238    let respond: (Bool) -> Void239240    var body: some View {241        VStack(alignment: .leading, spacing: LunarSpacing.md) {242            PromptHeader(icon: "arrow.up.forward.app",243                         title: applicationName.map { L("Open in %@?", $0) } ?? L("Open in another app?"),244                         origin: request.sourceURL.map(URLDisplay.host))245            Text(L("This page wants to open a “%@:” link outside ORIX Navigator.", request.scheme))246                .lunarFont(.callout).foregroundStyle(theme.textSecondary).fixedSize(horizontal: false, vertical: true)247            HStack(spacing: LunarSpacing.xs) {248                Spacer(minLength: 0)249                Button(L("Cancel")) { respond(false) }.buttonStyle(.lunar(.secondary)).keyboardShortcut(.cancelAction)250                    .accessibilityIdentifier("external.cancel")251                Button(L("Open")) { respond(true) }.buttonStyle(.lunar(.primary)).keyboardShortcut(.defaultAction)252                    .accessibilityIdentifier("external.open")253            }254        }255    }256}257258struct DownloadPrompt: View {259    @Environment(\.lunarTheme) private var theme260    let question: DownloadQuestion261    let respond: (Bool) -> Void262263    var body: some View {264        VStack(alignment: .leading, spacing: LunarSpacing.md) {265            PromptHeader(icon: "arrow.down.circle", title: L("Allow this page to download a file?"),266                         origin: question.candidate.originURL.map(URLDisplay.host) ?? URLDisplay.host(question.candidate.sourceURL))267            VStack(alignment: .leading, spacing: 2) {268                Text(question.filename).lunarFont(.bodyEmphasized).foregroundStyle(theme.textPrimary).lineLimit(2)269                    .truncationMode(.middle)270                if let bytes = question.expectedBytes {271                    Text(bytes.formatted(.byteCount(style: .file))).lunarFont(.caption).foregroundStyle(theme.textSecondary)272                }273            }274            if question.risk.requiresOpenConfirmation {275                LunarBadge(L("This type of file can harm your device"), status: .warning)276            }277            Text(L("The page started this download by itself."))278                .lunarFont(.callout).foregroundStyle(theme.textSecondary).fixedSize(horizontal: false, vertical: true)279            HStack(spacing: LunarSpacing.xs) {280                Spacer(minLength: 0)281                Button(L("Don’t Allow")) { respond(false) }.buttonStyle(.lunar(.secondary)).keyboardShortcut(.cancelAction)282                    .accessibilityIdentifier("download.deny")283                Button(L("Download")) { respond(true) }.buttonStyle(.lunar(.primary))284                    .accessibilityIdentifier("download.allow")285            }286        }287    }288}289
Files main
Menu

Theme