SPB Git

Repository Public

CommandCenterView.swift 9.8 KB 235 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Command/CommandCenterView.swift3// Description: The command centre (⌘K): a search field over the registry, sectioned rows with the matched characters4//              highlighted and the shortcut hint, arrows / return / escape on a keyboard, 44 pt rows for touch. Regular5//              = a floating glass panel; compact = a full-width sheet content. `.commandCenter(isPresented:model:)`6//              presents it; the app owns the ⌘K key equivalent.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SPNotesDesign11import SwiftUI1213public struct CommandCenterView: View {14    @State private var model: CommandCenterModel15    @FocusState private var focused: Bool16    @Environment(\.featureSizeClassOverride) private var override17    @Environment(\.horizontalSizeClass) private var horizontal1819    public init(model: CommandCenterModel) { _model = State(initialValue: model) }2021    public init(registry: CommandRegistry, onDismiss: (() -> Void)? = nil) {22        self.init(model: CommandCenterModel(registry: registry, onDismiss: onDismiss))23    }2425    private var compact: Bool {26        #if os(macOS)27        return override == .compact28        #else29        return (override ?? (horizontal == .compact ? .compact : .regular)) == .compact30        #endif31    }3233    public var body: some View {34        VStack(spacing: 0) {35            field36            Rectangle().fill(NVColor.line).frame(height: 1)37            results38        }39        .background(NVColor.bgElevated)40        .onAppear {41            model.refresh()42            focused = true43        }44    }4546    private var field: some View {47        HStack(spacing: NVSpace.md) {48            Image(systemName: "command").foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)49            TextField(L("Rechercher une commande ou une page…"), text: Binding(get: { model.query }, set: { model.query = $0 }))50                .textFieldStyle(.plain)51                .nvFont(.body)52                .foregroundStyle(NVColor.fg)53                .focused($focused)54                .autocorrectionDisabled()55                #if os(iOS)56                .textInputAutocapitalization(.never)57                .submitLabel(.go)58                #endif59                .onSubmit { Task { await model.runSelected() } }60                .onKeyPress(.downArrow) { model.moveSelection(1); return .handled }61                .onKeyPress(.upArrow) { model.moveSelection(-1); return .handled }62                .onKeyPress(.escape) { model.onDismiss?(); return .handled }63                .accessibilityLabel(L("Rechercher une commande ou une page"))64            if !model.query.isEmpty {65                Button { model.query = "" } label: {66                    Image(systemName: "xmark.circle.fill").foregroundStyle(NVColor.fgMuted).frame(minWidth: 28, minHeight: 28).contentShape(Rectangle())67                }68                .buttonStyle(.plain)69                .accessibilityLabel(L("Effacer la recherche"))70            }71        }72        .padding(.horizontal, NVSpace.lg)73        .frame(minHeight: compact ? 56 : 52)74    }7576    @ViewBuilder77    private var results: some View {78        if model.isEmpty {79            VStack(spacing: NVSpace.sm) {80                Image(systemName: "magnifyingglass").font(.system(size: 22)).foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)81                Text(model.query.isEmpty ? L("Aucune commande disponible.") : L("Aucune commande ni page ne correspond.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)82            }83            .frame(maxWidth: .infinity, minHeight: 160)84        } else {85            ScrollViewReader { proxy in86                ScrollView {87                    VStack(alignment: .leading, spacing: NVSpace.xxs) {88                        ForEach(model.sections) { section in89                            Text(section.title)90                                .nvFont(.micro)91                                .foregroundStyle(NVColor.fgMuted)92                                .padding(.horizontal, NVSpace.md)93                                .padding(.top, NVSpace.md)94                                .padding(.bottom, NVSpace.xxs)95                                .accessibilityAddTraits(.isHeader)96                            ForEach(section.rows) { row in97                                CommandRowView(row: row, selected: row.id == model.selectedId, compact: compact) {98                                    model.select(row)99                                    Task { await model.run(row) }100                                }101                                .id(row.id)102                            }103                        }104                    }105                    .padding(.horizontal, NVSpace.sm)106                    .padding(.bottom, NVSpace.sm)107                }108                .onChange(of: model.selectedId) { _, id in109                    if let id { proxy.scrollTo(id) }110                }111            }112        }113    }114}115116struct CommandRowView: View {117    let row: CommandRow118    let selected: Bool119    let compact: Bool120    let action: () -> Void121122    var body: some View {123        Button(action: action) {124            HStack(spacing: NVSpace.md) {125                Group {126                    if let emoji = row.emoji, !emoji.isEmpty { Text(emoji) } else {127                        Image(systemName: row.systemImage ?? "chevron.right.circle").foregroundStyle(selected ? NVColor.accent : NVColor.fgMuted)128                    }129                }130                .frame(width: 22)131                .accessibilityHidden(true)132                Text(CommandRowView.highlighted(row.title, positions: row.positions))133                    .nvFont(.body)134                    .foregroundStyle(NVColor.fg)135                    .lineLimit(1)136                if let subtitle = row.subtitle, !subtitle.isEmpty {137                    Text(subtitle).nvFont(.ui).foregroundStyle(NVColor.fgMuted).lineLimit(1)138                }139                Spacer(minLength: NVSpace.sm)140                if let shortcut = row.shortcut, !shortcut.isEmpty, !compact {141                    Text(shortcut)142                        .font(NVFont.fixed(.micro))143                        .foregroundStyle(NVColor.fgMuted)144                        .padding(.horizontal, NVSpace.sm)145                        .padding(.vertical, NVSpace.xxs)146                        .background(NVColor.bgSunken, in: NVRadius.shape(NVRadius.xs))147                        .accessibilityLabel(LF("Raccourci %@", shortcut))148                }149            }150            .padding(.horizontal, NVSpace.md)151            .frame(maxWidth: .infinity, minHeight: compact ? 44 : 36, alignment: .leading)152            .background(selected ? NVColor.accentSoft : Color.clear, in: NVRadius.shape(NVRadius.sm))153            .contentShape(Rectangle())154        }155        .buttonStyle(.plain)156        .accessibilityAddTraits(selected ? .isSelected : [])157    }158159    /// The title with the matched characters in the accent colour and semibold.160    static func highlighted(_ title: String, positions: [Int]) -> AttributedString {161        guard !positions.isEmpty else { return AttributedString(title) }162        let marked = Set(positions)163        var out = AttributedString()164        for (index, character) in title.enumerated() {165            var piece = AttributedString(String(character))166            if marked.contains(index) {167                piece.foregroundColor = NVColor.accent168                piece.inlinePresentationIntent = .stronglyEmphasized169            }170            out.append(piece)171        }172        return out173    }174}175176/// Presents the command centre over a view: a floating panel under the top edge on regular widths, a sheet on a phone.177public struct CommandCenterPresenter: ViewModifier {178    @Binding var isPresented: Bool179    let model: CommandCenterModel180    @Environment(\.horizontalSizeClass) private var horizontal181    @Environment(\.featureSizeClassOverride) private var override182    @Environment(\.accessibilityReduceMotion) private var reduceMotion183184    private var compact: Bool {185        #if os(macOS)186        return override == .compact187        #else188        return (override ?? (horizontal == .compact ? .compact : .regular)) == .compact189        #endif190    }191192    public func body(content: Content) -> some View {193        Group {194            if compact {195                content.sheet(isPresented: $isPresented) {196                    CommandCenterView(model: model).featureSizeClass(.compact)197                }198            } else {199                content.overlay(alignment: .top) {200                    if isPresented {201                        ZStack(alignment: .top) {202                            NVColor.bgSunken.opacity(0.45)203                                .ignoresSafeArea()204                                .onTapGesture { dismiss() }205                                .accessibilityHidden(true)206                            CommandCenterView(model: model)207                                .frame(maxWidth: 640, maxHeight: 460)208                                .clipShape(NVRadius.shape(NVRadius.xl))209                                .nvPop(radius: NVRadius.xl)210                                .padding(.top, 72)211                                .padding(.horizontal, NVSpace.xl)212                                .nvPanelTransition(edge: .top)213                        }214                    }215                }216            }217        }218        .onChange(of: isPresented) { _, shown in219            if shown { model.query = ""; model.refresh() }220        }221        .onAppear { model.onDismiss = { dismiss() } }222    }223224    private func dismiss() {225        withNVAnimation(.fast, reduceMotion: reduceMotion) { isPresented = false }226    }227}228229public extension View {230    /// Presents the command centre. The app toggles `isPresented` from its ⌘K command.231    func commandCenter(isPresented: Binding<Bool>, model: CommandCenterModel) -> some View {232        modifier(CommandCenterPresenter(isPresented: isPresented, model: model))233    }234}235
Files main
Menu

Theme