SPB Git

Repository Public

DatabaseEditors.swift 23.7 KB 482 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Work/Database/DatabaseEditors.swift3// Description: Cells and editors of the database screen: the read rendering of a cell (AI values under the AI mark,4//              server-computed values read-only), the per-type editor used inline (regular) and in the row sheet5//              (compact), the row editor, and the filter / sort / group builders with the structure section.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesAPI10import SPNotesDesign11import SPNotesDocument12import SPNotesSync13import SwiftUI1415/// Read rendering of one cell.16struct DatabaseCellView: View {17    let display: DatabaseCellDisplay18    var lineLimit: Int? = 119    var openURL: ((String) -> Void)?2021    var body: some View {22        HStack(spacing: NVSpace.xs) {23            if display.isAI { NVAIBadge(style: .compact) }24            content25        }26        .accessibilityElement(children: .combine)27        .accessibilityLabel(display.isAI ? LF("%@, généré par IA", display.text) : display.text)28    }2930    @ViewBuilder31    private var content: some View {32        switch display.kind {33        case .empty:34            Text("—").nvFont(.ui).foregroundStyle(NVColor.fgFaint).accessibilityLabel(L("vide"))35        case .checkbox(let on):36            Image(systemName: on ? "checkmark.square.fill" : "square").foregroundStyle(on ? NVColor.accent : NVColor.fgMuted)37        case .options(let options):38            HStack(spacing: NVSpace.xs) {39                ForEach(Array(options.enumerated()), id: \.offset) { _, option in NVChip(option.name, tone: WorkTone.tone(option.color)) }40            }41        case .url(let text):42            if let openURL {43                Button { openURL(text) } label: { Text(text).nvFont(.ui).foregroundStyle(NVColor.accent).underline().lineLimit(lineLimit) }.buttonStyle(.plain)44            } else {45                Text(text).nvFont(.ui).foregroundStyle(NVColor.accent).lineLimit(lineLimit)46            }47        case .relations(let titles):48            HStack(spacing: NVSpace.xs) {49                ForEach(Array(titles.enumerated()), id: \.offset) { _, title in50                    Label(title, systemImage: "arrow.up.right").nvFont(.ui).foregroundStyle(NVColor.fg).lineLimit(1)51                }52            }53        case .error:54            Label(display.text, systemImage: "exclamationmark.triangle").nvFont(.micro).foregroundStyle(NVColor.dangerText).lineLimit(lineLimit)55        case .pending:56            Label(display.text, systemImage: "hourglass").nvFont(.micro).foregroundStyle(NVColor.fgMuted)57        case .number:58            Text(display.text).nvFont(.ui).monospacedDigit().foregroundStyle(NVColor.fg).lineLimit(lineLimit)59        case .text:60            Text(display.text).nvFont(.ui).foregroundStyle(NVColor.fg).lineLimit(lineLimit).multilineTextAlignment(.leading)61        }62    }63}6465/// The editor of one cell for the stored types. Text-like types commit on Return; choices and checkboxes commit at once.66struct DatabaseCellEditor: View {67    let model: DatabaseModel68    let row: DatabaseRowValues69    let property: DatabaseProperty70    @State private var text: String71    @State private var date: Date72    @FocusState private var focused: Bool7374    init(model: DatabaseModel, row: DatabaseRowValues, property: DatabaseProperty) {75        self.model = model76        self.row = row77        self.property = property78        let value = DatabaseCellFormat.value(property, row)79        switch value {80        case .string(let string)?: _text = State(initialValue: string)81        case .int(let number)?: _text = State(initialValue: String(number))82        case .double(let number)?: _text = State(initialValue: String(number))83        default: _text = State(initialValue: "")84        }85        let day = DatabaseCellFormat.day(value) ?? WorkDay.string(Date(), timeZone: .current)86        _date = State(initialValue: WorkDay.date(day, hour: 12, timeZone: .current) ?? Date())87    }8889    var body: some View {90        switch property.type {91        case DatabasePropertyType.checkbox:92            let on = DatabaseCellFormat.value(property, row).map(DatabaseCellFormat.truthy) ?? false93            Toggle(property.name, isOn: Binding(get: { on }, set: { value in Task { await model.setValue(.bool(value), rowId: row.id, propertyId: property.id) } }))94                .labelsHidden()95        case DatabasePropertyType.select, DatabasePropertyType.status:96            WorkFlow(spacing: NVSpace.sm) {97                let current = row.values[property.id]?.stringValue98                ForEach(property.options) { option in99                    NVChip(option.name, tone: WorkTone.tone(option.color), isSelected: current == option.id) {100                        Task { await model.setValue(current == option.id ? nil : .string(option.id), rowId: row.id, propertyId: property.id) }101                    }102                    .accessibilityAddTraits(current == option.id ? .isSelected : [])103                }104            }105        case DatabasePropertyType.multiSelect:106            WorkFlow(spacing: NVSpace.sm) {107                let current = Set((row.values[property.id]?.arrayValue ?? []).compactMap(\.stringValue))108                ForEach(property.options) { option in109                    NVChip(option.name, systemImage: current.contains(option.id) ? "checkmark" : nil, tone: WorkTone.tone(option.color), isSelected: current.contains(option.id)) {110                        Task { await model.toggleOption(option.id, rowId: row.id, property: property) }111                    }112                    .accessibilityAddTraits(current.contains(option.id) ? .isSelected : [])113                }114            }115        case DatabasePropertyType.date:116            HStack(spacing: NVSpace.sm) {117                DatePicker(property.name, selection: $date, displayedComponents: .date)118                    .labelsHidden()119                    .onChange(of: date) { _, value in120                        Task { await model.setValue(.string(WorkDay.string(value, timeZone: .current)), rowId: row.id, propertyId: property.id) }121                    }122                if row.values[property.id]?.stringValue?.isEmpty == false {123                    FeatureIconButton("xmark.circle", label: LF("Effacer %@", property.name)) { Task { await model.setValue(nil, rowId: row.id, propertyId: property.id) } }124                }125            }126        default:127            HStack(spacing: NVSpace.sm) {128                TextField(property.name, text: $text)129                    .workField()130                    .focused($focused)131                    .onSubmit { Task { await model.setText(text, rowId: row.id, property: property) } }132                FeatureIconButton("checkmark", label: LF("Enregistrer %@", property.name), tone: .accent) { Task { await model.setText(text, rowId: row.id, property: property) } }133            }134            .onAppear { focused = model.editingCell == DatabaseModel.CellRef(rowId: row.id, propertyId: property.id) }135        }136    }137}138139/// Every property of one row: editable ones with their editor, the others read-only with the reason.140public struct DatabaseRowEditor: View {141    private let model: DatabaseModel142    private let row: DatabaseRowValues143144    public init(model: DatabaseModel, row: DatabaseRowValues) {145        self.model = model146        self.row = row147    }148149    public var body: some View {150        WorkDetailContainer(title: row.title.isEmpty ? L("Sans titre") : row.title, close: { model.inspector = .none }) {151            VStack(alignment: .leading, spacing: NVSpace.lg) {152                if !model.canWrite {153                    Label(L("Hors ligne : les valeurs sont en lecture seule."), systemImage: "wifi.slash").nvFont(.ui).foregroundStyle(NVColor.fgMuted)154                }155                if let failure = model.actionFailure { WorkActionFailure(failure: failure) { model.actionFailure = nil } }156                ForEach(model.properties) { property in157                    WorkFormRow(label: property.name) {158                        if model.isEditable(property) {159                            DatabaseCellEditor(model: model, row: row, property: property).id(property.id + row.id)160                        } else {161                            DatabaseCellView(display: DatabaseCellFormat.display(property, row), lineLimit: nil, openURL: { model.openURL($0) })162                            if let reason = readOnlyReason(property) {163                                Label(reason, systemImage: "lock").nvFont(.micro).foregroundStyle(NVColor.fgMuted)164                            }165                        }166                    }167                }168                Divider().overlay(NVColor.line)169                HStack(spacing: NVSpace.sm) {170                    FeatureButton(L("Ouvrir la page"), systemImage: "arrow.up.right.square") { model.openRow(row) }171                    FeatureButton(L("Supprimer"), systemImage: "trash", kind: .destructive) { Task { await model.deleteRows([row.id]) } }172                        .disabled(!model.canWrite)173                }174            }175        }176    }177178    private func readOnlyReason(_ property: DatabaseProperty) -> String? {179        switch property.type {180        case DatabasePropertyType.formula, DatabasePropertyType.rollup: return L("Calculé par le serveur")181        case DatabasePropertyType.relation: return L("Relation : modifiable sur le Web")182        case DatabasePropertyType.ai: return L("Rempli par un modèle ; généré depuis le Web")183        case DatabasePropertyType.createdTime, DatabasePropertyType.lastEditedTime: return L("Automatique")184        case DatabasePropertyType.file: return L("Fichiers : modifiables dans la page")185        default: return model.canWrite ? nil : nil186        }187    }188}189190// MARK: - Builders191192/// Filter, sort and group builders of the current view, plus the structure (add a property).193public struct DatabaseBuilderView: View {194    @Bindable private var model: DatabaseModel195    @State private var newPropertyName = ""196    @State private var newPropertyType = DatabasePropertyType.text197198    public init(model: DatabaseModel) { self.model = model }199200    public var body: some View {201        WorkDetailContainer(title: L("Filtrer, trier, grouper"), close: { model.inspector = .none }) {202            VStack(alignment: .leading, spacing: NVSpace.xl) {203                if let failure = model.actionFailure { WorkActionFailure(failure: failure) { model.actionFailure = nil } }204                section(L("Filtres"), "line.3.horizontal.decrease.circle") {205                    DatabaseFilterGroupEditor(model: model, group: model.draft.filter.root, depth: 0)206                }207                section(L("Tris"), "arrow.up.arrow.down") { sorts }208                section(L("Groupement"), "rectangle.3.group") { grouping }209                saveBar210                Divider().overlay(NVColor.line)211                section(L("Structure"), "square.stack.3d.up") { structure }212            }213        }214    }215216    private func section<Content: View>(_ title: String, _ symbol: String, @ViewBuilder content: () -> Content) -> some View {217        VStack(alignment: .leading, spacing: NVSpace.sm) {218            Label(title, systemImage: symbol).nvFont(.uiStrong).foregroundStyle(NVColor.fg).accessibilityAddTraits(.isHeader)219            content()220        }221    }222223    private var sorts: some View {224        VStack(alignment: .leading, spacing: NVSpace.sm) {225            ForEach(Array(model.draft.sorts.enumerated()), id: \.offset) { index, sort in226                HStack(spacing: NVSpace.sm) {227                    propertyMenu(selected: sort.property) { id in228                        model.draft.sorts[index].property = id229                        Task { await model.applyDraft() }230                    }231                    NVChip(sort.descending ? L("Décroissant") : L("Croissant"), systemImage: sort.descending ? "arrow.down" : "arrow.up", tone: .accent) {232                        model.draft.sorts[index].descending.toggle()233                        Task { await model.applyDraft() }234                    }235                    Spacer(minLength: 0)236                    FeatureIconButton("minus.circle", label: L("Retirer ce tri")) {237                        model.draft.sorts.remove(at: index)238                        Task { await model.applyDraft() }239                    }240                }241            }242            Menu {243                ForEach(model.properties) { property in244                    Button(property.name) {245                        model.draft.sorts.append(DatabaseViewSort(property: property.id))246                        Task { await model.applyDraft() }247                    }248                }249            } label: { Label(L("Ajouter un tri"), systemImage: "plus") }250            .menuStyle(.borderlessButton).fixedSize()251        }252    }253254    private var grouping: some View {255        Menu {256            Button(L("Aucun groupement")) {257                model.draft.groupBy = nil258                Task { await model.applyDraft() }259            }260            ForEach(model.properties.filter { !$0.isComputed && $0.type != DatabasePropertyType.relation && $0.type != DatabasePropertyType.title }) { property in261                Button(property.name) {262                    model.draft.groupBy = property.id263                    Task { await model.applyDraft() }264                }265            }266        } label: {267            Label(model.property(model.draft.groupBy)?.name ?? L("Aucun groupement"), systemImage: "chevron.up.chevron.down")268        }269        .menuStyle(.borderlessButton).fixedSize()270    }271272    @ViewBuilder273    private var saveBar: some View {274        if model.isDraftDirty {275            VStack(alignment: .leading, spacing: NVSpace.sm) {276                Label(L("Aperçu : ces réglages ne sont pas encore enregistrés dans la vue."), systemImage: "eye").nvFont(.ui).foregroundStyle(NVColor.fgMuted)277                    .fixedSize(horizontal: false, vertical: true)278                HStack(spacing: NVSpace.sm) {279                    FeatureButton(L("Enregistrer dans la vue"), systemImage: "checkmark", kind: .primary) { Task { await model.saveView() } }280                        .disabled(!model.canWrite || model.isWorking)281                        .opacity(model.canWrite ? 1 : 0.5)282                    FeatureButton(L("Réinitialiser")) { Task { await model.resetDraft() } }283                }284                if !model.canWrite {285                    Text(L("Hors ligne : l'aperçu est calculé sur l'appareil ; l'enregistrement attendra le serveur.")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)286                        .fixedSize(horizontal: false, vertical: true)287                }288            }289        }290    }291292    private var structure: some View {293        VStack(alignment: .leading, spacing: NVSpace.sm) {294            ForEach(model.properties) { property in295                HStack(spacing: NVSpace.sm) {296                    Image(systemName: DatabaseCellFormat.typeSymbol(property.type)).foregroundStyle(NVColor.fgMuted).frame(width: 20).accessibilityHidden(true)297                    Text(property.name).nvFont(.ui).foregroundStyle(NVColor.fg)298                    Spacer(minLength: NVSpace.sm)299                    Text(DatabaseCellFormat.typeLabel(property.type)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)300                }301                .accessibilityElement(children: .combine)302            }303            HStack(spacing: NVSpace.sm) {304                TextField(L("Nouvelle propriété"), text: $newPropertyName).workField()305                Menu {306                    ForEach([DatabasePropertyType.text, DatabasePropertyType.number, DatabasePropertyType.date, DatabasePropertyType.checkbox, DatabasePropertyType.select,307                             DatabasePropertyType.multiSelect, DatabasePropertyType.status, DatabasePropertyType.url], id: \.self) { type in308                        Button(DatabaseCellFormat.typeLabel(type)) { newPropertyType = type }309                    }310                } label: { Label(DatabaseCellFormat.typeLabel(newPropertyType), systemImage: DatabaseCellFormat.typeSymbol(newPropertyType)) }311                .menuStyle(.borderlessButton).fixedSize()312            }313            FeatureButton(L("Ajouter la propriété"), systemImage: "plus") {314                Task { if await model.createProperty(name: newPropertyName, type: newPropertyType) { newPropertyName = "" } }315            }316            .disabled(!model.canWrite || model.isWorking)317            .opacity(model.canWrite ? 1 : 0.5)318        }319    }320321    private func propertyMenu(selected: String, choose: @escaping (String) -> Void) -> some View {322        Menu {323            ForEach(model.properties) { property in Button(property.name) { choose(property.id) } }324        } label: {325            Text(model.property(selected)?.name ?? L("Propriété inconnue")).nvFont(.ui)326        }327        .menuStyle(.borderlessButton).fixedSize()328    }329}330331/// One group of the filter tree (recursive).332struct DatabaseFilterGroupEditor: View {333    @Bindable var model: DatabaseModel334    let group: DatabaseFilterDraft.Group335    let depth: Int336337    var body: some View {338        VStack(alignment: .leading, spacing: NVSpace.sm) {339            if group.nodes.count > 1 || depth > 0 {340                HStack(spacing: NVSpace.sm) {341                    NVChip(L("Toutes les règles"), tone: .accent, isSelected: group.conjunction == .all) { setConjunction(.all) }342                    NVChip(L("Au moins une"), tone: .accent, isSelected: group.conjunction == .any) { setConjunction(.any) }343                    Spacer(minLength: 0)344                    if depth > 0 {345                        FeatureIconButton("minus.circle", label: L("Retirer ce groupe")) { model.draft.filter.remove(group.id); apply() }346                    }347                }348            }349            if group.nodes.isEmpty, depth == 0 {350                Text(L("Aucun filtre : toutes les lignes sont affichées.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)351            }352            ForEach(group.nodes) { node in353                switch node {354                case .rule(let rule): DatabaseFilterRuleEditor(model: model, rule: rule)355                case .group(let inner):356                    DatabaseFilterGroupEditor(model: model, group: inner, depth: depth + 1)357                        .padding(NVSpace.sm)358                        .background(NVColor.bgSunken, in: NVRadius.shape(NVRadius.sm))359                }360            }361            HStack(spacing: NVSpace.md) {362                Menu {363                    ForEach(model.properties) { property in364                        Button(property.name) { model.draft.filter.addRule(DatabaseFilterOps.defaultRule(for: property), to: group.id); apply() }365                    }366                } label: { Label(L("Ajouter une règle"), systemImage: "plus") }367                .menuStyle(.borderlessButton).fixedSize()368                if depth == 0 {369                    Button { model.draft.filter.addGroup(to: group.id) } label: { Label(L("Ajouter un groupe"), systemImage: "plus.rectangle.on.rectangle").nvFont(.ui) }370                        .buttonStyle(.plain).foregroundStyle(NVColor.accent)371                }372            }373        }374    }375376    private func setConjunction(_ conjunction: DatabaseFilterDraft.Conjunction) {377        model.draft.filter.setConjunction(conjunction, of: group.id)378        apply()379    }380381    private func apply() { Task { await model.applyDraft() } }382}383384/// One rule: property, operator, value (typed by the property).385struct DatabaseFilterRuleEditor: View {386    @Bindable var model: DatabaseModel387    let rule: DatabaseFilterDraft.Rule388    @State private var text: String389390    init(model: DatabaseModel, rule: DatabaseFilterDraft.Rule) {391        self.model = model392        self.rule = rule393        switch rule.value {394        case .string(let string)?: _text = State(initialValue: string)395        case .int(let number)?: _text = State(initialValue: String(number))396        case .double(let number)?: _text = State(initialValue: String(number))397        default: _text = State(initialValue: "")398        }399    }400401    var body: some View {402        let property = model.property(rule.property)403        VStack(alignment: .leading, spacing: NVSpace.xs) {404            HStack(spacing: NVSpace.sm) {405                Menu {406                    ForEach(model.properties) { candidate in407                        Button(candidate.name) {408                            let fresh = DatabaseFilterOps.defaultRule(for: candidate)409                            model.draft.filter.update(rule.id) { $0.property = fresh.property; $0.op = fresh.op; $0.value = fresh.value }410                            text = ""411                            apply()412                        }413                    }414                } label: { Text(property?.name ?? L("Propriété inconnue")).nvFont(.uiStrong) }415                .menuStyle(.borderlessButton).fixedSize()416                Menu {417                    ForEach(DatabaseFilterOps.ops(for: property?.type ?? DatabasePropertyType.text), id: \.self) { op in418                        Button(DatabaseFilterOps.label(op)) { model.draft.filter.update(rule.id) { $0.op = op }; apply() }419                    }420                } label: { Text(DatabaseFilterOps.label(rule.op)).nvFont(.ui) }421                .menuStyle(.borderlessButton).fixedSize()422                Spacer(minLength: 0)423                FeatureIconButton("minus.circle", label: L("Retirer cette règle")) { model.draft.filter.remove(rule.id); apply() }424            }425            if DatabaseFilterOps.needsValue(rule.op), let property { value(property) }426            if let property, property.isComputed || property.type == DatabasePropertyType.relation {427                Label(L("Évaluée par le serveur seulement"), systemImage: "server.rack").nvFont(.micro).foregroundStyle(NVColor.fgMuted)428            }429        }430        .padding(NVSpace.sm)431        .background(NVColor.bg, in: NVRadius.shape(NVRadius.sm))432        .overlay(NVRadius.shape(NVRadius.sm).strokeBorder(NVColor.line, lineWidth: 1))433    }434435    @ViewBuilder436    private func value(_ property: DatabaseProperty) -> some View {437        switch property.type {438        case DatabasePropertyType.checkbox:439            HStack(spacing: NVSpace.sm) {440                NVChip(L("Cochée"), tone: .accent, isSelected: rule.value == .bool(true)) { set(.bool(true)) }441                NVChip(L("Non cochée"), tone: .accent, isSelected: rule.value == .bool(false)) { set(.bool(false)) }442            }443        case DatabasePropertyType.select, DatabasePropertyType.status, DatabasePropertyType.multiSelect:444            WorkFlow(spacing: NVSpace.sm) {445                ForEach(property.options) { option in446                    NVChip(option.name, tone: WorkTone.tone(option.color), isSelected: rule.value == .string(option.id)) { set(.string(option.id)) }447                }448            }449        default:450            TextField(placeholder(property), text: $text)451                .workField()452                .onSubmit { commitText(property) }453                .onChange(of: text) { _, _ in commitText(property) }454        }455    }456457    private func placeholder(_ property: DatabaseProperty) -> String {458        switch property.type {459        case DatabasePropertyType.number: return L("Nombre")460        case DatabasePropertyType.date, DatabasePropertyType.createdTime, DatabasePropertyType.lastEditedTime: return L("AAAA-MM-JJ ou today")461        default: return L("Valeur")462        }463    }464465    private func commitText(_ property: DatabaseProperty) {466        let trimmed = text.trimmingCharacters(in: .whitespaces)467        if property.type == DatabasePropertyType.number, let number = Double(trimmed.replacingOccurrences(of: ",", with: ".")) {468            set(number == number.rounded() && abs(number) < 1e15 ? .int(Int64(number)) : .double(number))469        } else {470            set(trimmed.isEmpty ? nil : .string(trimmed))471        }472    }473474    private func set(_ value: JSONValue?) {475        guard model.draft.filter.rule(rule.id)?.value != value else { return }476        model.draft.filter.update(rule.id) { $0.value = value }477        apply()478    }479480    private func apply() { Task { await model.applyDraft() } }481}482
Files main
Menu

Theme