SPB Git

Repository Public

TagEditorSheet.swift 9.6 KB 205 lines swift

1// SP Notes iOS2// File: Features/Organize/TagEditorSheet.swift3// Description: Sheet to edit the tags of one note (or of several at once): current tags as removable chips, a text field with4//              suggestions from the existing tags, and the same normalisation as the store and the server.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SwiftUI1011/// Pure rules of the tag editor (tested).12enum TagEditing {13    /// Adds what was typed (several tags may be separated by commas), normalised exactly like `NotesStore.normalizeTags`.14    static func adding(_ input: String, to tags: [String]) -> [String] {15        NotesStore.normalizeTags(tags + input.split(separator: ",").map(String.init))16    }1718    /// Whether typing `input` would add at least one tag.19    static func canAdd(_ input: String, to tags: [String]) -> Bool { adding(input, to: tags) != NotesStore.normalizeTags(tags) }2021    /// Existing tags matching what is being typed, most used first, without those already on the note.22    static func suggestions(for input: String, existing: [TagInfo], current: [String], limit: Int = 12) -> [String] {23        let needle = NotesStore.normalizeTags([input]).first ?? ""24        let taken = Set(current)25        return existing26            .filter { !taken.contains($0.name) && (needle.isEmpty || $0.name.contains(needle)) }27            .sorted { a, b in28                let ap = a.name.hasPrefix(needle), bp = b.name.hasPrefix(needle)29                if ap != bp { return ap }30                if a.count != b.count { return a.count > b.count }31                return a.name < b.name32            }33            .prefix(limit).map(\.name)34    }3536    /// Tags carried by every note of a selection, in the order of the first note.37    static func common(_ lists: [[String]]) -> [String] {38        guard let first = lists.first else { return [] }39        return first.filter { tag in lists.allSatisfy { $0.contains(tag) } }40    }4142    /// The new tags of one note of a selection: what the editor removed from the common tags goes away, what it shows is43    /// added, and the note's other tags are kept.44    static func merged(original: [String], initialCommon: [String], edited: [String]) -> [String] {45        let removed = Set(initialCommon).subtracting(edited)46        return NotesStore.normalizeTags(original.filter { !removed.contains($0) } + edited)47    }48}4950struct TagEditorSheet: View {51    let noteIds: [String]5253    init(noteId: String) { noteIds = [noteId] }54    init(noteIds: [String]) { self.noteIds = noteIds }5556    @Environment(AppModel.self) private var app57    @Environment(\.dismiss) private var dismiss58    @State private var tags: [String] = []59    @State private var initialCommon: [String] = []60    @State private var originals: [String: [String]] = [:]61    @State private var existing: [TagInfo] = []62    @State private var input = ""63    @State private var loaded = false64    @FocusState private var focused: Bool6566    private var suggestions: [String] { TagEditing.suggestions(for: input, existing: existing, current: tags) }6768    var body: some View {69        NavigationStack {70            Form {71                Section {72                    if tags.isEmpty {73                        Text(noteIds.count > 1 ? "Aucun tag commun à ces notes" : "Aucun tag").foregroundStyle(Color.spTextSecondary)74                    } else {75                        FlowLayout(spacing: 8) {76                            ForEach(tags, id: \.self) { tag in77                                Button { tags.removeAll { $0 == tag } } label: {78                                    HStack(spacing: 6) {79                                        Text("#\(tag)").lineLimit(1)80                                        Image(systemName: "xmark.circle.fill").foregroundStyle(Color.spMuted)81                                    }82                                    .font(.subheadline)83                                    .padding(.horizontal, 12)84                                    .frame(minHeight: 36)85                                    .background(Color.accentColor.opacity(0.16), in: Capsule())86                                    .foregroundStyle(Color.spText)87                                    .contentShape(Capsule())88                                }89                                .buttonStyle(.plain)90                                .accessibilityLabel("Retirer le tag \(tag)")91                                .accessibilityIdentifier("tag-chip")92                            }93                        }94                        .padding(.vertical, 4)95                    }96                } header: {97                    Text(noteIds.count > 1 ? "Tags communs aux \(noteIds.count) notes" : "Tags de la note")98                }99                Section {100                    HStack {101                        TextField("Ajouter un tag", text: $input)102                            .textInputAutocapitalization(.never)103                            .autocorrectionDisabled()104                            .focused($focused)105                            .submitLabel(.done)106                            .onSubmit(add)107                            .accessibilityIdentifier("tag-input")108                        if TagEditing.canAdd(input, to: tags) {109                            Button("Ajouter", action: add).accessibilityIdentifier("tag-add")110                        }111                    }112                } footer: {113                    Text("Les tags sont en minuscules, sans #, 40 caractères au plus et 20 par note. Sépare plusieurs tags par des virgules.")114                }115                if !suggestions.isEmpty {116                    Section("Suggestions") {117                        FlowLayout(spacing: 8) {118                            ForEach(suggestions, id: \.self) { tag in119                                Button { tags = TagEditing.adding(tag, to: tags); input = "" } label: {120                                    Text("#\(tag)").font(.subheadline).lineLimit(1)121                                        .padding(.horizontal, 12).frame(minHeight: 36)122                                        .background(Color.spSurface2, in: Capsule())123                                        .foregroundStyle(Color.spText)124                                        .contentShape(Capsule())125                                }126                                .buttonStyle(.plain)127                                .accessibilityLabel("Ajouter le tag \(tag)")128                            }129                        }130                        .padding(.vertical, 4)131                    }132                }133            }134            .navigationTitle("Tags")135            .navigationBarTitleDisplayMode(.inline)136            .toolbar {137                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }138                ToolbarItem(placement: .confirmationAction) { Button("OK", action: save).disabled(!loaded).accessibilityIdentifier("tags-done") }139            }140            .task { await load() }141        }142        .presentationDetents([.medium, .large])143    }144145    private func add() {146        tags = TagEditing.adding(input, to: tags)147        input = ""148        focused = true149    }150151    private func load() async {152        guard !loaded else { return }153        for id in noteIds { if let summary = try? await app.store.summary(id: id) { originals[id] = summary.tags } }154        initialCommon = TagEditing.common(noteIds.compactMap { originals[$0] })155        tags = initialCommon156        existing = (try? await app.store.tags()) ?? []157        loaded = true158    }159160    private func save() {161        // What is still in the field counts: nobody expects typed text to be dropped by "OK".162        let edited = TagEditing.adding(input, to: tags)163        Task {164            let done = await app.attempt {165                for id in noteIds {166                    guard let original = originals[id] else { continue }167                    try await app.setTags(id, TagEditing.merged(original: original, initialCommon: initialCommon, edited: edited))168                }169            }170            if done { dismiss() }171        }172    }173}174175/// Lays chips out in rows, wrapping to the width available.176struct FlowLayout: Layout {177    var spacing: CGFloat = 8178179    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {180        arrange(width: proposal.width ?? .infinity, subviews: subviews).size181    }182183    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {184        let arrangement = arrange(width: bounds.width, subviews: subviews)185        for (index, origin) in arrangement.origins.enumerated() {186            subviews[index].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: ProposedViewSize(width: min(arrangement.sizes[index].width, bounds.width), height: nil))187        }188    }189190    private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, origins: [CGPoint], sizes: [CGSize]) {191        var origins: [CGPoint] = [], sizes: [CGSize] = []192        var x: CGFloat = 0, y: CGFloat = 0, rowHeight: CGFloat = 0, maxX: CGFloat = 0193        for subview in subviews {194            var size = subview.sizeThatFits(.unspecified)195            if width.isFinite, size.width > width { size = subview.sizeThatFits(ProposedViewSize(width: width, height: nil)) }196            if x > 0, x + size.width > width { x = 0; y += rowHeight + spacing; rowHeight = 0 }197            origins.append(CGPoint(x: x, y: y)); sizes.append(size)198            x += size.width + spacing199            rowHeight = max(rowHeight, size.height)200            maxX = max(maxX, x - spacing)201        }202        return (CGSize(width: width.isFinite ? width : maxX, height: y + rowHeight), origins, sizes)203    }204}205
Files main
Menu

Theme