SPB Git

Repository Public

LinkSheet.swift 6.1 KB 126 lines swift

1// SP Notes iOS2// File: Features/Editor/Sheets/LinkSheet.swift3// Description: Sheet to set, change, open or remove the link of the selected text. Links open in the system browser, never in the app.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import UIKit910/// Rules for the addresses typed in the link sheet.11enum LinkAddress {12    /// What is stored as `href`: trimmed; `https://` is added when no scheme was typed (`mailto:` for an e-mail address).13    /// nil when the text cannot be a link.14    static func normalized(_ input: String) -> String? {15        let text = input.trimmingCharacters(in: .whitespacesAndNewlines)16        guard !text.isEmpty, !text.contains(where: \.isWhitespace) else { return nil }17        let lower = text.lowercased()18        if lower.hasPrefix("javascript:") || lower.hasPrefix("data:") || lower.hasPrefix("vbscript:") || lower.hasPrefix("file:") { return nil }19        // In-app targets of the web editor are kept as typed.20        if text.hasPrefix("/") || text.hasPrefix("#") { return text }21        if let colon = text.firstIndex(of: ":"), let first = text.first, first.isLetter {22            let scheme = text[..<colon].lowercased(), rest = text[text.index(after: colon)...]23            let wellFormed = scheme.allSatisfy { $0.isLetter || $0.isNumber || $0 == "+" || $0 == "-" || $0 == "." }24            // "example.org:8080/x" and "localhost:3000" are a host and a port, not a scheme.25            let isScheme = rest.hasPrefix("//") || ["mailto", "tel", "sms", "facetime", "maps"].contains(scheme)26                || (!scheme.contains(".") && !(rest.first?.isNumber ?? true))27            if wellFormed, isScheme { return !rest.isEmpty && URL(string: text) != nil ? text : nil }28        }29        if text.contains("@"), !text.contains("/") { return URL(string: "mailto:\(text)") != nil ? "mailto:\(text)" : nil }30        guard text.contains(".") || text.lowercased().hasPrefix("localhost"), URL(string: "https://\(text)")?.host() != nil else { return nil }31        return "https://\(text)"32    }3334    /// The URL the system can open for a stored `href` (web, mail, phone…); nil for in-app or unusable targets.35    static func openableURL(_ href: String) -> URL? {36        guard let normalized = normalized(href), let url = URL(string: normalized), let scheme = url.scheme?.lowercased() else { return nil }37        return ["http", "https", "mailto", "tel", "sms", "facetime", "maps"].contains(scheme) ? url : nil38    }39}4041/// Sheet for the link of the current selection.42/// - `onApply`: the normalized address to set with `setLink(href:…)`.43/// - `onRemove`: non-nil when the selection already has a link ("Retirer le lien" is shown).44struct LinkSheet: View {45    var onApply: (String) -> Void46    var onRemove: (() -> Void)?47    var onCancel: () -> Void4849    @State private var address: String50    @FocusState private var isFocused: Bool5152    init(href: String = "", onApply: @escaping (String) -> Void, onRemove: (() -> Void)? = nil, onCancel: @escaping () -> Void) {53        _address = State(initialValue: href)54        self.onApply = onApply55        self.onRemove = onRemove56        self.onCancel = onCancel57    }5859    private var normalized: String? { LinkAddress.normalized(address) }60    private var openable: URL? { LinkAddress.openableURL(address) }6162    var body: some View {63        NavigationStack {64            Form {65                Section {66                    TextField(text: $address, prompt: Text(verbatim: "https://exemple.org")) { Text("Adresse") }67                        .keyboardType(.URL)68                        .textContentType(.URL)69                        .textInputAutocapitalization(.never)70                        .autocorrectionDisabled()71                        .submitLabel(.done)72                        .focused($isFocused)73                        .onSubmit(apply)74                        .frame(minHeight: 44)75                        .accessibilityIdentifier("link-address")76                } header: {77                    Text("Adresse du lien")78                } footer: {79                    if !address.trimmingCharacters(in: .whitespaces).isEmpty, normalized == nil {80                        Text("Cette adresse n’est pas valide.").foregroundStyle(Color("Danger"))81                    }82                }83                .listRowBackground(Color("Surface"))84                Section {85                    Button { if let openable { UIApplication.shared.open(openable) } } label: {86                        Label { Text("Ouvrir") } icon: { Image(systemName: "safari") }87                    }88                    .disabled(openable == nil)89                    .frame(minHeight: 44)90                    .accessibilityHint(Text("Ouvre le lien dans le navigateur."))91                    .accessibilityIdentifier("link-open")92                    if let onRemove {93                        Button(role: .destructive) { onRemove() } label: {94                            Label { Text("Retirer le lien") } icon: { Image(systemName: "link.badge.minus") }95                        }96                        .frame(minHeight: 44)97                        .accessibilityIdentifier("link-remove")98                    }99                }100                .listRowBackground(Color("Surface"))101            }102            .scrollContentBackground(.hidden)103            .background(Color("Background"))104            .navigationTitle(onRemove == nil ? Text("Ajouter un lien") : Text("Modifier le lien"))105            .navigationBarTitleDisplayMode(.inline)106            .toolbar {107                ToolbarItem(placement: .cancellationAction) {108                    Button { onCancel() } label: { Text("Annuler") }.accessibilityIdentifier("link-cancel")109                }110                ToolbarItem(placement: .confirmationAction) {111                    Button(action: apply) { Text("Appliquer").bold() }112                        .disabled(normalized == nil)113                        .accessibilityIdentifier("link-apply")114                }115            }116            .onAppear { isFocused = true }117        }118        .presentationDetents([.medium])119    }120121    private func apply() {122        guard let normalized else { return }123        onApply(normalized)124    }125}126
Files main
Menu

Theme