SPB Git

Repository Public

FormatBar.swift 12.9 KB 231 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose/FormatBar.swift3// Description: The formatting bar of the composer (a row above the text on macOS and iPad, the keyboard accessory on iPhone), the link4// editor, and the « Format » menu with its keyboard shortcuts. Every control has a VoiceOver label and says whether it is on.5import SPMailCore6import SwiftUI78/// Formatting controls for one rich text controller. With a `model`, the composer's own insertions (picture, snippet, template) are added.9struct FormatBar: View {10    let editor: RichTextController11    var model: ComposeModel?12    /// The keyboard accessory form: one scrolling row with larger targets, undo / redo and « done ».13    var accessory = false14    @Binding var showLink: Bool1516    #if os(iOS)17    private let side: CGFloat = 4018    #else19    private let side: CGFloat = 2820    #endif2122    var body: some View {23        let row = HStack(spacing: accessory ? 2 : 1) {24            styleMenu25            divider26            toggle(.bold, "bold", L("Gras"), "⌘B")27            toggle(.italic, "italic", L("Italique"), "⌘I")28            toggle(.underline, "underline", L("Souligné"), "⌘U")29            toggle(.strike, "strikethrough", L("Barré"), "⇧⌘X")30            divider31            button("list.bullet", L("Liste à puces"), "⇧⌘8", active: editor.block.kind == .bullet) { editor.toggleList(ordered: false) }32            button("list.number", L("Liste numérotée"), "⇧⌘7", active: editor.block.kind == .ordered) { editor.toggleList(ordered: true) }33            if editor.block.isList {34                button("decrease.indent", L("Diminuer le retrait"), "⌘[") { editor.indent(-1) }35                button("increase.indent", L("Augmenter le retrait"), "⌘]") { editor.indent(1) }36            }37            button("text.quote", L("Citation"), "⌘'", active: editor.block.quote > 0) { editor.toggleQuote() }38            divider39            button("link", L("Lien"), "⇧⌘K", active: editor.linkAtSelection != nil) { showLink = true }40            if let model { imageControl(model) }41            toggle(.code, "chevron.left.forwardslash.chevron.right", L("Code"), nil)42            button("eraser", L("Effacer la mise en forme"), nil) { editor.clearFormatting() }43            if let model {44                divider45                button("text.badge.plus", L("Insérer un extrait"), nil) { model.snippetRequest += 1 }46                button("rectangle.on.rectangle.angled", L("Insérer un modèle"), nil) { model.templateRequest += 1 }47                // optional intelligence: nothing here unless the « write » feature is on48                if model.assistantAvailable { divider; WritingAssistantMenu(model: model, side: side, accessory: accessory) }49            }50            if accessory {51                divider52                button("arrow.uturn.backward", L("Annuler la frappe"), "⌘Z") { editor.undoEdit() }.disabled(!editor.canUndo)53                button("arrow.uturn.forward", L("Rétablir"), "⇧⌘Z") { editor.redoEdit() }.disabled(!editor.canRedo)54            }55        }56        .buttonStyle(.borderless)57        .accessibilityElement(children: .contain)58        .accessibilityLabel(Text("Barre de mise en forme"))59        if accessory {60            ScrollView(.horizontal, showsIndicators: false) { row.padding(.horizontal, SPSpacing.l) }61                .frame(height: 46)62        } else {63            ViewThatFits(in: .horizontal) {64                HStack(spacing: 0) { row; Spacer(minLength: 0) }65                ScrollView(.horizontal, showsIndicators: false) { row }66            }67        }68    }6970    private var divider: some View { Rectangle().fill(SPColor.border).frame(width: 1, height: 16).padding(.horizontal, accessory ? 5 : 4).accessibilityHidden(true) }7172    private func toggle(_ mark: RichMark, _ icon: String, _ label: String, _ shortcut: String?) -> some View {73        button(icon, label, shortcut, active: editor.activeMarks.contains(mark)) { editor.toggle(mark) }74    }7576    private func button(_ icon: String, _ label: String, _ shortcut: String?, active: Bool = false, action: @escaping () -> Void) -> some View {77        Button(action: action) {78            Image(systemName: icon)79                .font(.system(size: accessory ? 17 : 13, weight: active ? .semibold : .regular))80                .frame(width: side, height: side)81                .foregroundStyle(active ? SPColor.accent : SPColor.text2)82                .background { if active { RoundedRectangle(cornerRadius: SPRadius.chip, style: .continuous).fill(SPColor.accentSoft) } }83                .contentShape(Rectangle())84        }85        .help(shortcut.map { "\(label) (\($0))" } ?? label)86        .accessibilityLabel(Text(label))87        .accessibilityValue(Text(active ? L("activé") : ""))88        .accessibilityAddTraits(active ? [.isSelected] : [])89    }9091    private var styleName: String {92        switch editor.block.kind { case .heading(1): L("Titre"); case .heading(2): L("Sous-titre"); case .heading: L("Intertitre"); default: L("Corps") }93    }94    private var styleMenu: some View {95        Menu {96            Button { editor.setHeading(0) } label: { Text("Corps") }97            Button { editor.setHeading(1) } label: { Text("Titre").font(.title2.weight(.semibold)) }98            Button { editor.setHeading(2) } label: { Text("Sous-titre").font(.title3.weight(.semibold)) }99            Button { editor.setHeading(3) } label: { Text("Intertitre").font(.headline) }100        } label: {101            HStack(spacing: 3) { Text(styleName).font(SPFont.callout); Image(systemName: "chevron.down").font(.system(size: 8, weight: .semibold)) }102                .foregroundStyle(SPColor.text2).padding(.horizontal, 6).frame(minWidth: accessory ? 76 : 70, minHeight: side, alignment: .leading).contentShape(Rectangle())103        }104        .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()105        .help("Style du paragraphe")106        .accessibilityLabel(Text("Style du paragraphe"))107        .accessibilityValue(Text(styleName))108    }109110    /// Insert a picture; with a picture selected, its size presets.111    @ViewBuilder private func imageControl(_ model: ComposeModel) -> some View {112        if let image = editor.imageAtSelection {113            Menu {114                let current = RichImage.Preset.matching(width: image.width)115                ForEach(RichImage.Preset.allCases, id: \.self) { p in116                    Button { model.resizeSelectedImage(to: p) } label: { if p == current { Label(Self.title(p), systemImage: "checkmark") } else { Text(Self.title(p)) } }117                }118            } label: {119                Image(systemName: "photo.badge.arrow.down").font(.system(size: accessory ? 17 : 13)).frame(width: side, height: side).foregroundStyle(SPColor.accent)120                    .background(SPColor.accentSoft, in: RoundedRectangle(cornerRadius: SPRadius.chip, style: .continuous))121            }122            .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()123            .help("Taille de l’image")124            .accessibilityLabel(Text("Taille de l’image"))125            .accessibilityValue(Text(Self.title(.matching(width: image.width))))126        } else {127            button("photo", L("Insérer une image"), "⌥⌘I") { model.imageRequest += 1 }128        }129    }130    static func title(_ p: RichImage.Preset) -> String {131        switch p { case .small: L("Petite"); case .medium: L("Moyenne"); case .large: L("Grande"); case .original: L("Taille d’origine") }132    }133}134135// MARK: - link editor136137/// Insert, edit or remove a link. A bare address gets `https://`, an e-mail address `mailto:`; nothing else unsafe is accepted.138struct LinkEditor: View {139    let editor: RichTextController140    @Binding var isPresented: Bool141    @State private var text = ""142    @State private var url = ""143    @State private var invalid = false144    @FocusState private var focus: Bool145146    var body: some View {147        let existing = editor.linkAtSelection != nil148        VStack(alignment: .leading, spacing: SPSpacing.l) {149            Text(existing ? "Modifier le lien" : "Insérer un lien").font(SPFont.headline)150            TextField("Texte affiché", text: $text).textFieldStyle(.roundedBorder).accessibilityLabel(Text("Texte affiché"))151            TextField("Adresse (https://… ou courriel)", text: $url)152                .textFieldStyle(.roundedBorder).focused($focus).autocorrectionDisabled()153                #if os(iOS)154                .textInputAutocapitalization(.never).keyboardType(.URL)155                #endif156                .onSubmit(apply)157                .accessibilityLabel(Text("Adresse du lien"))158            if invalid { Text("Cette adresse n’est pas un lien http, https ou courriel.").font(SPFont.caption).foregroundStyle(SPColor.danger) }159            HStack {160                if existing { Button("Retirer le lien", role: .destructive) { editor.setLink(nil); isPresented = false } }161                Spacer()162                Button("Annuler", role: .cancel) { isPresented = false }.keyboardShortcut(.cancelAction)163                Button("OK", action: apply).keyboardShortcut(.defaultAction).disabled(url.trimmingCharacters(in: .whitespaces).isEmpty)164            }165        }166        .padding(SPSpacing.xl)167        .frame(minWidth: 300, idealWidth: 360)168        .onAppear {169            text = editor.linkText()170            url = editor.linkAtSelection?.replacingOccurrences(of: "mailto:", with: "") ?? ""171            focus = true172        }173    }174175    private func apply() {176        guard let link = RichImport.normalizedLink(url) else { invalid = true; return }177        editor.setLink(link, text: text)178        isPresented = false179    }180}181182// MARK: - menu « Format »183184/// The items of the « Format » menu: they act on the composer in front (macOS menu bar; iPad: listed while ⌘ is held).185struct ComposeFormatMenu: View {186    let composer: ComposeModel?187188    var body: some View {189        let editor = composer?.editor190        let off = composer == nil || composer?.isLocked == true191        Group {192            Button("Gras") { editor?.toggle(.bold) }.keyboardShortcut("b")193            Button("Italique") { editor?.toggle(.italic) }.keyboardShortcut("i")194            Button("Souligné") { editor?.toggle(.underline) }.keyboardShortcut("u")195            Button("Barré") { editor?.toggle(.strike) }.keyboardShortcut("x", modifiers: [.command, .shift])196            Button("Code") { editor?.toggle(.code) }197            Divider()198            Menu("Style") {199                // ⌥⌘0 belongs to « Fenêtre principale » while no composer is in front (see MailCommands)200                Button("Corps") { editor?.setHeading(0) }.keyboardShortcut(composer != nil ? KeyboardShortcut("0", modifiers: [.command, .option]) : nil)201                Button("Titre") { editor?.setHeading(1) }.keyboardShortcut("1", modifiers: [.command, .option])202                Button("Sous-titre") { editor?.setHeading(2) }.keyboardShortcut("2", modifiers: [.command, .option])203                Button("Intertitre") { editor?.setHeading(3) }.keyboardShortcut("3", modifiers: [.command, .option])204            }205            Button("Liste numérotée") { editor?.toggleList(ordered: true) }.keyboardShortcut("7", modifiers: [.command, .shift])206            Button("Liste à puces") { editor?.toggleList(ordered: false) }.keyboardShortcut("8", modifiers: [.command, .shift])207            Button("Augmenter le retrait") { editor?.indent(1) }.keyboardShortcut("]")208            Button("Diminuer le retrait") { editor?.indent(-1) }.keyboardShortcut("[")209            Button("Citation") { editor?.toggleQuote() }.keyboardShortcut("'")210            Divider()211            // ⇧⌘K on every platform: ⌘K is the command palette (both live on iPad, the palette under the composer sheet)212            Button("Lien…") { composer?.linkRequest += 1 }.keyboardShortcut("k", modifiers: [.command, .shift])213            Button("Effacer la mise en forme") { editor?.clearFormatting() }.keyboardShortcut("\\")214            Divider()215        }216        .disabled(off)217        Group {218            Button("Insérer une image…") { composer?.imageRequest += 1 }.keyboardShortcut("i", modifiers: [.command, .option])219            Button("Joindre un fichier") { composer?.attachRequest += 1 }.keyboardShortcut("a", modifiers: [.command, .shift])220            Button("Insérer un extrait…") { composer?.snippetRequest += 1 }.keyboardShortcut("e", modifiers: [.command, .option])221            // ⌃⌘T: ⌥⌘T is the system's « Show / Hide Toolbar » (ToolbarCommands)222            Button("Insérer un modèle…") { composer?.templateRequest += 1 }.keyboardShortcut("t", modifiers: [.command, .control])223            Divider()224            // ⌘S saves the draft while a composer is in front, the template otherwise (« Modèles › Enregistrer le modèle »)225            Button("Enregistrer le brouillon") { if let composer { Task { await composer.save() } } }.keyboardShortcut(composer != nil ? KeyboardShortcut("s") : nil)226            Button("Envoyer") { composer?.sendRequest += 1 }.keyboardShortcut("d", modifiers: [.command, .shift]).disabled(composer?.canSend != true)227        }228        .disabled(off)229    }230}231
Files main
Menu

Theme