SPB Git

Repository Public

CanvasInspector.swift 15.1 KB 293 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Canvas/CanvasInspector.swift3// Description: Editing panels of the canvas: the inspector of the regular layout (nothing / one card / several cards / a4//              link selected) and the card detail reused as a sheet on compact — text, URL, LaTeX source, table cells,5//              shape, colour, order, links, open, delete.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesDesign10import SPNotesDocument11import SwiftUI1213struct CanvasInspector: View {14    @Bindable var model: CanvasModel1516    var body: some View {17        VStack(alignment: .leading, spacing: NVSpace.lg) {18            if let edge = model.selectedEdge {19                CanvasEdgeDetail(model: model, edge: edge)20            } else if model.selection.count == 1, let id = model.selection.first {21                CanvasNodeDetail(model: model, nodeId: id, compact: false, close: nil)22            } else if model.selection.count > 1 {23                NVSectionHeader(LF("%lld cartes sélectionnées", model.selection.count))24                FeatureButton(L("Ranger la sélection en grille"), systemImage: "square.grid.2x2") { model.tidy(.grid) }25                FeatureButton(L("Premier plan"), systemImage: "square.3.layers.3d.top.filled") { model.bringSelectionToFront() }26                FeatureButton(L("Arrière-plan"), systemImage: "square.3.layers.3d.bottom.filled") { model.sendSelectionToBack() }27                FeatureButton(L("Supprimer"), systemImage: "trash", kind: .destructive) { model.deleteSelection() }28            } else {29                NVSectionHeader(L("Canevas"), subtitle: L("Sélectionnez une carte ou un lien pour le modifier."))30                hint("cursorarrow", L("Glissez une carte pour la déplacer ; glissez le fond pour sélectionner plusieurs cartes."))31                hint("arrow.triangle.branch", L("Outil Relier : glissez d'une carte à une autre, ou touchez-les l'une après l'autre."))32                hint("hand.draw", L("Défilez pour déplacer la vue, pincez ou ⌘-défilez pour zoomer."))33                hint("icloud.and.arrow.up", L("Le canevas s'enregistre seul, même hors ligne, et se synchronise ensuite."))34            }35        }36        .frame(maxWidth: .infinity, alignment: .leading)37    }3839    private func hint(_ symbol: String, _ text: String) -> some View {40        HStack(alignment: .top, spacing: NVSpace.sm) {41            Image(systemName: symbol).foregroundStyle(NVColor.fgMuted).frame(width: 20).accessibilityHidden(true)42            Text(text).nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)43        }44    }45}4647/// Everything about one card. Used in the inspector (regular) and as the sheet of the outline (compact).48struct CanvasNodeDetail: View {49    @Bindable var model: CanvasModel50    let nodeId: String51    let compact: Bool52    let close: (() -> Void)?5354    var body: some View {55        if let node = model.document.node(id: nodeId) {56            VStack(alignment: .leading, spacing: NVSpace.lg) {57                HStack(spacing: NVSpace.sm) {58                    Image(systemName: CanvasNodeLabel.symbol(node.kind)).foregroundStyle(NVColor.accent).accessibilityHidden(true)59                    Text(CanvasNodeLabel.kindName(node.kind)).nvFont(.h3).foregroundStyle(NVColor.fg)60                    Spacer(minLength: 0)61                    if let close { FeatureButton(L("Terminé"), kind: .primary, action: close) }62                }63                if node.kind.isKnown { fields(node) } else {64                    Text(L("Type inconnu de cette version : conservé tel quel, en lecture seule.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)65                }66                if node.kind.isKnown { colors(node) }67                links(node)68                actions(node)69            }70            .frame(maxWidth: .infinity, alignment: .leading)71        } else {72            NVEmptyState(systemImage: "rectangle.dashed", title: L("Carte supprimée"))73        }74    }7576    private func text(_ key: WritableKeyPath<CanvasNode, String?>) -> Binding<String> {77        Binding(get: { model.document.node(id: nodeId)?[keyPath: key] ?? "" },78                set: { value in model.updateNode(id: nodeId, coalescing: true) { $0[keyPath: key] = value.isEmpty ? nil : value } })79    }8081    private func label(_ title: String) -> some View { Text(title).nvFont(.micro).foregroundStyle(NVColor.fgMuted) }8283    private func editor(_ binding: Binding<String>, monospaced: Bool = false, label: String) -> some View {84        TextEditor(text: binding)85            .font(monospaced ? NVFont.fixed(.code) : NVFont.fixed(.body))86            .foregroundStyle(NVColor.fg)87            .scrollContentBackground(.hidden)88            .padding(NVSpace.xs)89            .frame(minHeight: 96)90            .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.sm))91            .overlay(NVRadius.shape(NVRadius.sm).strokeBorder(NVColor.lineStrong, lineWidth: 1))92            .accessibilityLabel(label)93    }9495    @ViewBuilder96    private func fields(_ node: CanvasNode) -> some View {97        switch node.kind {98        case .math:99            label(L("Source LaTeX"))100            editor(text(\.latex), monospaced: true, label: L("Source LaTeX"))101            Text(L("La formule est affichée sous sa forme source ; son rendu se fait sur le Web.")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)102        case .table:103            label(L("Cellules"))104            CanvasTableEditor(model: model, nodeId: nodeId)105        case .link:106            label(L("Adresse"))107            TextField(L("https://…"), text: text(\.url))108                .textFieldStyle(.roundedBorder)109                #if os(iOS)110                .keyboardType(.URL).textInputAutocapitalization(.never)111                #endif112                .autocorrectionDisabled()113            label(L("Titre"))114            editor(text(\.text), label: L("Titre"))115        case .page, .reference:116            label(node.kind == .page ? L("Page liée") : L("Référence liée"))117            Text(model.label(node)).nvFont(.body).foregroundStyle(NVColor.fg)118            label(L("Note"))119            editor(text(\.text), label: L("Note"))120        case .shape:121            label(L("Forme"))122            Picker(L("Forme"), selection: Binding(get: { model.document.node(id: nodeId)?.shape ?? .rect }, set: { shape in model.updateNode(id: nodeId) { $0.shape = shape } })) {123                Text(L("Rectangle")).tag(CanvasShape.rect)124                Text(L("Ellipse")).tag(CanvasShape.ellipse)125                Text(L("Losange")).tag(CanvasShape.diamond)126            }127            .pickerStyle(.segmented).labelsHidden()128            label(L("Texte"))129            editor(text(\.text), label: L("Texte"))130        case .image, .pdf, .drawing:131            label(L("Légende"))132            editor(text(\.text), label: L("Légende"))133        default:134            label(L("Texte"))135            editor(text(\.text), label: L("Texte"))136        }137    }138139    private func colors(_ node: CanvasNode) -> some View {140        VStack(alignment: .leading, spacing: NVSpace.xs) {141            label(L("Couleur"))142            HStack(spacing: NVSpace.sm) {143                swatch(nil, selected: node.color == nil, name: L("Aucune couleur"))144                ForEach(CanvasDefaults.colors, id: \.self) { hex in swatch(hex, selected: node.color?.lowercased() == hex, name: LF("Couleur %@", hex)) }145            }146        }147    }148149    private func swatch(_ hex: String?, selected: Bool, name: String) -> some View {150        Button { model.updateNode(id: nodeId) { $0.color = hex } } label: {151            ZStack {152                Circle().fill(CanvasPaint.color(hex) ?? NVColor.bgElevated).frame(width: 22, height: 22)153                if hex == nil { Image(systemName: "circle.slash").font(.system(size: 14)).foregroundStyle(NVColor.fgMuted) }154                Circle().strokeBorder(selected ? NVColor.accent : NVColor.lineStrong, lineWidth: selected ? 2 : 1).frame(width: 28, height: 28)155            }156            .frame(minWidth: compact ? 44 : 30, minHeight: compact ? 44 : 30)157            .contentShape(Rectangle())158        }159        .buttonStyle(.plain)160        .accessibilityLabel(name)161        .accessibilityAddTraits(selected ? .isSelected : [])162    }163164    @ViewBuilder165    private func links(_ node: CanvasNode) -> some View {166        let edges = model.document.edges(of: node.id)167        if !edges.isEmpty {168            VStack(alignment: .leading, spacing: NVSpace.xs) {169                label(L("Liens"))170                ForEach(edges) { edge in171                    let outgoing = edge.from == node.id172                    let other = model.document.node(id: outgoing ? edge.to : edge.from)173                    HStack(spacing: NVSpace.sm) {174                        Image(systemName: outgoing ? "arrow.right" : "arrow.left").foregroundStyle(NVColor.fgMuted).accessibilityLabel(outgoing ? L("vers") : L("depuis"))175                        VStack(alignment: .leading, spacing: 0) {176                            Text(other.map(model.label) ?? L("Carte manquante")).nvFont(.ui).foregroundStyle(NVColor.fg).lineLimit(1)177                            if let text = edge.label, !text.isEmpty { Text(text).nvFont(.micro).foregroundStyle(NVColor.fgMuted).lineLimit(1) }178                        }179                        Spacer(minLength: 0)180                        FeatureIconButton("slider.horizontal.3", label: L("Modifier le lien")) { model.selection = []; model.selectedEdgeId = edge.id; close?() }181                    }182                }183            }184        }185    }186187    private func actions(_ node: CanvasNode) -> some View {188        VStack(alignment: .leading, spacing: NVSpace.sm) {189            if model.canOpen(node) {190                FeatureButton(node.kind == .drawing ? L("Modifier le dessin") : L("Ouvrir"), systemImage: node.kind == .drawing ? "pencil.tip" : "arrow.up.forward.square", kind: .primary) {191                    close?()192                    model.open(node.id)193                }194            }195            FeatureButton(L("Relier à une autre carte"), systemImage: "arrow.triangle.branch") {196                model.beginConnection(from: node.id)197                if compact { model.compactMode = .canvas; model.center(on: node.id) }198                close?()199            }200            HStack(spacing: NVSpace.sm) {201                FeatureButton(L("Premier plan"), systemImage: "square.3.layers.3d.top.filled") { model.select(node.id); model.bringSelectionToFront() }202                FeatureButton(L("Arrière-plan"), systemImage: "square.3.layers.3d.bottom.filled") { model.select(node.id); model.sendSelectionToBack() }203            }204            FeatureButton(L("Supprimer la carte"), systemImage: "trash", kind: .destructive) {205                model.select(node.id)206                model.deleteSelection()207                close?()208            }209        }210    }211}212213/// The cells of a `table` card (Markdown table in `text`, the convention shared with the web).214struct CanvasTableEditor: View {215    @Bindable var model: CanvasModel216    let nodeId: String217218    private var cells: [[String]] { CanvasTable.parse(model.document.node(id: nodeId)?.text) }219220    private func write(_ cells: [[String]], coalescing: Bool) {221        model.updateNode(id: nodeId, coalescing: coalescing) { $0.text = CanvasTable.serialize(cells) }222    }223224    var body: some View {225        let cells = cells226        VStack(alignment: .leading, spacing: NVSpace.xs) {227            Grid(horizontalSpacing: NVSpace.xs, verticalSpacing: NVSpace.xs) {228                ForEach(cells.indices, id: \.self) { row in229                    GridRow {230                        ForEach(cells[row].indices, id: \.self) { column in231                            TextField(row == 0 ? L("En-tête") : "", text: Binding(get: { self.cells[safe: row]?[safe: column] ?? "" }, set: { value in232                                var next = self.cells233                                guard row < next.count, column < next[row].count else { return }234                                next[row][column] = value235                                write(next, coalescing: true)236                            }))237                            .textFieldStyle(.roundedBorder)238                            .font(NVFont.fixed(row == 0 ? .uiStrong : .ui))239                            .accessibilityLabel(LF("Ligne %lld, colonne %lld", row + 1, column + 1))240                        }241                    }242                }243            }244            HStack(spacing: NVSpace.sm) {245                FeatureButton(L("Ligne"), systemImage: "plus") { write(cells + [Array(repeating: "", count: max(1, cells.first?.count ?? 1))], coalescing: false) }246                FeatureButton(L("Colonne"), systemImage: "plus") { write(cells.isEmpty ? [[""]] : cells.map { $0 + [""] }, coalescing: false) }247                if cells.count > 1 { FeatureIconButton("minus", label: L("Retirer la dernière ligne")) { write(Array(cells.dropLast()), coalescing: false) } }248            }249        }250    }251}252253extension Array {254    subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }255}256257struct CanvasEdgeDetail: View {258    @Bindable var model: CanvasModel259    let edge: CanvasEdge260261    var body: some View {262        VStack(alignment: .leading, spacing: NVSpace.md) {263            HStack(spacing: NVSpace.sm) {264                Image(systemName: "arrow.triangle.branch").foregroundStyle(NVColor.accent).accessibilityHidden(true)265                Text(L("Lien")).nvFont(.h3).foregroundStyle(NVColor.fg)266            }267            let from = model.document.node(id: edge.from).map(model.label) ?? L("Carte manquante")268            let to = model.document.node(id: edge.to).map(model.label) ?? L("Carte manquante")269            Text(from + " → " + to).nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)270            Text(L("Étiquette")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)271            TextField(L("cause, exemple, précède…"), text: Binding(get: { model.selectedEdge?.label ?? "" }, set: { value in272                model.updateEdge(id: edge.id, coalescing: true) { $0.label = value.isEmpty ? nil : value }273            }))274            .textFieldStyle(.roundedBorder)275            Text(L("Tracé")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)276            Picker(L("Tracé"), selection: Binding(get: { CanvasRouting.hasArrow(model.selectedEdge ?? edge) }, set: { arrow in model.updateEdge(id: edge.id) { $0.kind = arrow ? .arrow : .line } })) {277                Text(L("Flèche")).tag(true)278                Text(L("Trait")).tag(false)279            }280            .pickerStyle(.segmented).labelsHidden()281            Picker(L("Forme du tracé"), selection: Binding(get: { CanvasRouting.style(of: model.selectedEdge ?? edge) }, set: { style in282                model.updateEdge(id: edge.id) { $0["route"] = style == .straight ? nil : .string(style.rawValue) }283            })) {284                Text(L("Droit")).tag(CanvasRouting.Style.straight)285                Text(L("Coudé")).tag(CanvasRouting.Style.orthogonal)286                Text(L("Courbe")).tag(CanvasRouting.Style.curved)287            }288            .pickerStyle(.segmented).labelsHidden()289            FeatureButton(L("Supprimer le lien"), systemImage: "trash", kind: .destructive) { model.deleteSelection() }290        }291    }292}293
Files main
Menu

Theme