SPB Git

Repository Public

CanvasScreen.swift 15.7 KB 332 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Canvas/CanvasScreen.swift3// Description: The infinite canvas screen. Regular (Mac / iPad): the surface with a tool rail and zoom controls, and an4//              inspector on the right. Compact (iPhone): an outline of the cards in reading order with a detail sheet,5//              and a switch to the pannable canvas. Saves by itself (offline too), follows sync, and offers the review6//              of a conflict.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SPNotesDesign11import SPNotesDocument12import SPNotesSync13import SwiftUI1415public struct CanvasScreen: View {16    @Environment(\.accessibilityReduceMotion) private var reduceMotion17    @State private var model: CanvasModel18    @State private var detailNodeId: String?19    @State private var showsConflict = false2021    /// - Parameters:22    ///   - attachments: how image / pdf / drawing cards read their files (`FeatureAttachmentLoader.standard`).23    ///   - drawingEditor: the iOS app passes its PencilKit editor here; nil = the built-in ink editor.24    public init(repositories: NotesRepositories, pageId: String, router: (any FeatureRouter)? = nil, attachments: FeatureAttachmentLoader = .unavailable,25                drawingEditor: CanvasDrawingEditorProvider? = nil) {26        _model = State(initialValue: CanvasModel(repositories: repositories, pageId: pageId, router: router, attachments: attachments, drawingEditor: drawingEditor))27    }2829    public init(model: CanvasModel) { _model = State(initialValue: model) }3031    public var body: some View {32        FeatureScaffold(title: model.title?.isEmpty == false ? model.title! : L("Canevas"), subtitle: Self.status(model), phase: model.phase,33                        retry: { Task { await model.load() } }, actions: { CanvasHeaderActions(model: model) }) { sizeClass in34            FeaturePhaseView(phase: model.phase, hasData: model.phase == .loaded, retry: { Task { await model.load() } }, empty: { EmptyView() }) {35                VStack(spacing: 0) {36                    notices(compact: sizeClass.isCompact)37                    if sizeClass.isCompact { compact } else { regular }38                }39            }40        }41        .task { if model.phase == .idle { await model.load() } }42        .task { await model.observe() }43        .onDisappear { Task { await model.saveNow() } }44        .sheet(item: $model.inkSession) { session in45            InkEditorView(document: session.document, canSave: model.attachments.canUpload, onCancel: { model.inkSession = nil }) { ink, _ in46                Task { await model.finishInkSession(ink) }47            }48            .frame(minWidth: 360, minHeight: 420)49        }50        .sheet(isPresented: $showsConflict) {51            CanvasConflictReview(model: model) { showsConflict = false }52                .frame(minWidth: 360, minHeight: 420)53        }54        .sheet(isPresented: Binding(get: { detailNodeId != nil }, set: { if !$0 { detailNodeId = nil; model.endEditing() } })) {55            if let id = detailNodeId {56                ScrollView { CanvasNodeDetail(model: model, nodeId: id, compact: true) { detailNodeId = nil }.padding(NVSpace.lg) }57                    .background(NVColor.bg)58                    .presentationDetents([.medium, .large])59            }60        }61    }6263    /// The save / sync line under the title.64    public static func status(_ model: CanvasModel) -> String? {65        guard model.phase == .loaded else { return nil }66        let counts = LF("Cartes : %lld · liens : %lld", model.document.nodes.count, model.document.edges.count)67        switch model.saveState {68        case .saved: return counts + " · " + (model.syncError == nil ? L("Enregistré sur l'appareil") : L("Enregistré, synchronisation en attente"))69        case .dirty: return counts + " · " + L("Modifications en cours")70        case .saving: return counts + " · " + L("Enregistrement…")71        case .failed: return counts + " · " + L("Enregistrement impossible")72        }73    }7475    @ViewBuilder76    private func notices(compact: Bool) -> some View {77        VStack(spacing: 0) {78            if case .failed(let failure) = model.saveState {79                FeatureStatusBanner(failure: failure, freshness: nil, retry: { Task { await model.saveNow() } })80            }81            if let failure = model.actionFailure {82                FeatureStatusBanner(failure: failure, freshness: nil, retry: nil)83                    .onTapGesture { model.actionFailure = nil }84            }85            if let conflict = model.conflict {86                HStack(spacing: NVSpace.sm) {87                    Image(systemName: "arrow.triangle.branch").foregroundStyle(NVColor.warning).accessibilityHidden(true)88                    Text(LF("Ce canevas a aussi été modifié ailleurs. Éléments à départager : %lld.", conflict.merge.conflicts.count))89                        .nvFont(.ui).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)90                    Spacer(minLength: NVSpace.sm)91                    FeatureButton(L("Examiner"), kind: .primary) { showsConflict = true }92                }93                .padding(.horizontal, NVSpace.md).padding(.vertical, NVSpace.sm)94                .background(NVColor.bgElevated, in: NVRadius.shape(NVRadius.md))95                .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.warning.opacity(0.6), lineWidth: 1))96                .padding(.bottom, NVSpace.sm)97            }98        }99        .padding(.horizontal, compact ? NVSpace.lg : NVSpace.xl)100    }101102    // MARK: Regular103104    private var regular: some View {105        HStack(spacing: 0) {106            ZStack {107                CanvasSurfaceView(model: model)108                if model.document.nodes.isEmpty {109                    NVEmptyState(systemImage: "rectangle.3.group", title: L("Canevas vide"), message: L("Ajoutez une première carte, puis reliez vos idées."),110                                 actionTitle: L("Ajouter un texte")) { model.addNode(.text) }111                }112            }113            .overlay(alignment: .topLeading) { CanvasToolRail(model: model, vertical: true).padding(NVSpace.md) }114            .overlay(alignment: .bottomTrailing) { CanvasZoomControls(model: model).padding(NVSpace.md) }115            .onAppear { model.emptyDragPans = false }116            Rectangle().fill(NVColor.line).frame(width: 1)117            ScrollView { CanvasInspector(model: model).padding(NVSpace.lg) }118                .frame(width: 300)119                .background(NVColor.bgSidebar)120        }121        .overlay(alignment: .top) { Rectangle().fill(NVColor.line).frame(height: 1) }122    }123124    // MARK: Compact125126    private var compact: some View {127        VStack(spacing: 0) {128            Picker(L("Affichage"), selection: Binding(get: { model.compactMode }, set: { mode in withNVAnimation(.fast, reduceMotion: reduceMotion) { model.compactMode = mode } })) {129                Text(L("Plan")).tag(CanvasModel.CompactMode.outline)130                Text(L("Canevas")).tag(CanvasModel.CompactMode.canvas)131            }132            .pickerStyle(.segmented)133            .labelsHidden()134            .padding(.horizontal, NVSpace.lg)135            .padding(.bottom, NVSpace.sm)136            if model.compactMode == .outline {137                CanvasOutlineList(model: model) { detailNodeId = $0 }138            } else {139                CanvasSurfaceView(model: model)140                    .overlay(alignment: .bottom) {141                        HStack(spacing: NVSpace.sm) {142                            CanvasToolRail(model: model, vertical: false)143                            CanvasZoomControls(model: model)144                        }145                        .padding(NVSpace.sm)146                    }147                    .overlay(alignment: .topTrailing) {148                        if let id = model.selection.first, model.selection.count == 1 {149                            FeatureButton(L("Détails"), systemImage: "slider.horizontal.3") { detailNodeId = id }.padding(NVSpace.sm)150                        }151                    }152                    .onAppear { model.emptyDragPans = true }153            }154        }155    }156}157158/// Undo / redo / tidy / add, in the header.159struct CanvasHeaderActions: View {160    @Bindable var model: CanvasModel161    @Environment(\.featureSizeClass) private var sizeClass162163    var body: some View {164        if model.phase == .loaded {165            FeatureIconButton("arrow.uturn.backward", label: L("Annuler")) { model.undo() }166                .disabled(!model.canUndo).opacity(model.canUndo ? 1 : 0.4)167                .keyboardShortcut("z", modifiers: .command)168            FeatureIconButton("arrow.uturn.forward", label: L("Rétablir")) { model.redo() }169                .disabled(!model.canRedo).opacity(model.canRedo ? 1 : 0.4)170                .keyboardShortcut("z", modifiers: [.command, .shift])171            Menu {172                Button(L("Ranger automatiquement")) { model.tidy(.auto) }173                Button(L("Ranger en grille")) { model.tidy(.grid) }174                Button(L("Disposition organique")) { model.tidy(.force) }175                Divider()176                Button(L("Tout afficher")) { model.fitToContent() }177                Button(L("Tout sélectionner")) { model.selectAll() }178            } label: {179                CanvasMenuLabel(symbol: "wand.and.stars", label: L("Ranger"))180            }181            .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()182            Menu {183                ForEach(CanvasNodeKind.allKnown, id: \.self) { kind in184                    Button { model.addNode(kind) } label: { Label(CanvasNodeLabel.kindName(kind), systemImage: CanvasNodeLabel.symbol(kind)) }185                }186            } label: {187                CanvasMenuLabel(symbol: "plus", label: L("Ajouter une carte"), prominent: true)188            }189            .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()190        }191    }192}193194struct CanvasMenuLabel: View {195    let symbol: String196    let label: String197    var prominent = false198199    var body: some View {200        Image(systemName: symbol)201            .font(.system(size: 15, weight: .medium))202            .foregroundStyle(prominent ? NVColor.accentFg : NVColor.fgMuted)203            .frame(minWidth: 32, minHeight: 32)204            .background(prominent ? NVColor.accent : NVColor.bgHover.opacity(0.6), in: NVRadius.shape(NVRadius.sm))205            .contentShape(Rectangle())206            .accessibilityLabel(label)207    }208}209210/// Select / pan / connect.211struct CanvasToolRail: View {212    @Bindable var model: CanvasModel213    let vertical: Bool214215    private static func name(_ tool: CanvasModel.Tool) -> String {216        switch tool {217        case .select: return L("Sélectionner et déplacer")218        case .pan: return L("Déplacer la vue")219        case .connect: return L("Relier deux cartes")220        }221    }222223    private static func symbol(_ tool: CanvasModel.Tool) -> String {224        switch tool {225        case .select: return "cursorarrow"226        case .pan: return "hand.draw"227        case .connect: return "arrow.triangle.branch"228        }229    }230231    var body: some View {232        let layout = vertical ? AnyLayout(VStackLayout(spacing: NVSpace.xs)) : AnyLayout(HStackLayout(spacing: NVSpace.xs))233        layout {234            ForEach(CanvasModel.Tool.allCases, id: \.self) { tool in235                Button { model.tool = tool; if tool != .connect { model.clearPendingConnection() } } label: {236                    Image(systemName: Self.symbol(tool))237                        .font(.system(size: 16, weight: .medium))238                        .foregroundStyle(model.tool == tool ? NVColor.accent : NVColor.fgMuted)239                        .frame(minWidth: 40, minHeight: 40)240                        .background(model.tool == tool ? NVColor.accentSoft : .clear, in: NVRadius.shape(NVRadius.sm))241                        .contentShape(Rectangle())242                }243                .buttonStyle(.plain)244                .accessibilityLabel(Self.name(tool))245                .accessibilityAddTraits(model.tool == tool ? .isSelected : [])246            }247        }248        .padding(NVSpace.xs)249        .nvGlass(radius: NVRadius.md)250    }251}252253struct CanvasZoomControls: View {254    @Bindable var model: CanvasModel255256    var body: some View {257        HStack(spacing: NVSpace.xxs) {258            control("minus", L("Zoom arrière")) { model.zoom(by: 1 / 1.25) }259            Button { model.setZoom(1) } label: {260                Text(LF("%lld %%", Int((model.viewport.zoom * 100).rounded())))261                    .nvFont(.micro).monospacedDigit().foregroundStyle(NVColor.fgMuted)262                    .frame(minWidth: 44, minHeight: 40).contentShape(Rectangle())263            }264            .buttonStyle(.plain)265            .accessibilityLabel(L("Revenir à 100 %"))266            control("plus", L("Zoom avant")) { model.zoom(by: 1.25) }267            control("arrow.up.left.and.arrow.down.right", L("Tout afficher")) { model.fitToContent() }268        }269        .padding(NVSpace.xs)270        .nvGlass(radius: NVRadius.md)271    }272273    private func control(_ symbol: String, _ label: String, action: @escaping () -> Void) -> some View {274        Button(action: action) {275            Image(systemName: symbol).font(.system(size: 14, weight: .medium)).foregroundStyle(NVColor.fgMuted)276                .frame(minWidth: 40, minHeight: 40).contentShape(Rectangle())277        }278        .buttonStyle(.plain)279        .accessibilityLabel(label)280    }281}282283/// Compact layout: the cards in reading order.284struct CanvasOutlineList: View {285    @Bindable var model: CanvasModel286    let open: (String) -> Void287288    var body: some View {289        if model.document.nodes.isEmpty {290            NVEmptyState(systemImage: "rectangle.3.group", title: L("Canevas vide"), message: L("Ajoutez une première carte, puis reliez vos idées."),291                         actionTitle: L("Ajouter un texte")) { open(model.addNode(.text)) }292                .frame(maxWidth: .infinity, maxHeight: .infinity)293        } else {294            ScrollView {295                LazyVStack(spacing: NVSpace.sm) {296                    ForEach(Array(model.outline.enumerated()), id: \.element.id) { index, node in297                        Button { model.select(node.id); open(node.id) } label: { row(node) }298                            .buttonStyle(.plain)299                            .nvBlockReveal(index: index)300                    }301                }302                .padding(.horizontal, NVSpace.lg)303                .padding(.bottom, NVSpace.xl)304            }305        }306    }307308    private func row(_ node: CanvasNode) -> some View {309        let links = model.document.edges(of: node.id).count310        let tint = CanvasPaint.color(node.color) ?? NVColor.accent311        return HStack(alignment: .top, spacing: NVSpace.md) {312            Image(systemName: CanvasNodeLabel.symbol(node.kind))313                .font(.system(size: 16, weight: .medium))314                .foregroundStyle(tint)315                .frame(width: 36, height: 36)316                .background(tint.opacity(0.12), in: NVRadius.shape(NVRadius.sm))317                .accessibilityHidden(true)318            VStack(alignment: .leading, spacing: NVSpace.xxs) {319                Text(model.label(node)).nvFont(.body).foregroundStyle(NVColor.fg).lineLimit(2).multilineTextAlignment(.leading)320                Text(links == 0 ? CanvasNodeLabel.kindName(node.kind) : (links == 1 ? LF("%@ · 1 lien", CanvasNodeLabel.kindName(node.kind)) : LF("%@ · %lld liens", CanvasNodeLabel.kindName(node.kind), links)))321                    .nvFont(.micro).foregroundStyle(NVColor.fgMuted)322            }323            Spacer(minLength: NVSpace.sm)324            Image(systemName: "chevron.right").font(.system(size: 12, weight: .semibold)).foregroundStyle(NVColor.fgFaint).padding(.top, NVSpace.sm).accessibilityHidden(true)325        }326        .padding(NVSpace.md)327        .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)328        .nvCard(radius: NVRadius.md)329        .contentShape(Rectangle())330    }331}332
Files main
Menu

Theme