SPB Git

Repository Public

SplitMainView.swift 14.1 KB 294 lines swift

1// Main window on macOS and iPad: sidebar, item list, detail. A two-column NavigationSplitView whose detail holds2// the list and the item side by side (HStack + Divider — HSplitView and a three-column split mis-size the window on3// macOS 27 when anything of unbounded height sits above the detail page; banners here are fixed-height). Tool pages4// (Security Center, Devices, …) take the whole detail area.5import SharedVaultKit6import SwiftUI78struct SplitMainView: View {9    @Environment(AppModel.self) private var model10    @FocusState private var searchFocused: Bool11    @State private var confirm: ConfirmRequest?1213    var body: some View {14        @Bindable var model = model15        NavigationSplitView {16            Sidebar()17                .navigationSplitViewColumnWidth(min: 210, ideal: 232, max: 300)18        } detail: {19            VStack(spacing: 0) {20                StatusBanner()21                if model.section.isItemList {22                    HStack(spacing: 0) {23                        ItemListColumn().frame(width: listWidth)24                        Divider().overlay(Palette.line)25                        Group {26                            if let v = model.selectedItem { ItemDetailView(view: v).id(v.id) }27                            else { EmptyState(symbol: "lock.square.stack", title: "Select an item", text: "Secrets stay masked until you reveal or copy them.").vaultBackground() }28                        }29                        .frame(maxWidth: .infinity, maxHeight: .infinity)30                    }31                } else {32                    toolPage.frame(maxWidth: .infinity, maxHeight: .infinity)33                }34            }35            .vaultBackground()36            #if os(macOS)37            .navigationTitle(model.section.title)38            #else39            .navigationTitle("")40            .navigationBarTitleDisplayMode(.inline)41            #endif42        }43        .searchable(text: $model.query, placement: .toolbar, prompt: "Search")44        .searchFocused($searchFocused)45        .onChange(of: model.searchFocusTick) { _, _ in46            if !model.section.isItemList { model.section = .allItems }47            searchFocused = true48        }49        .onChange(of: model.query) { _, q in if !q.isEmpty, !model.section.isItemList { model.section = .allItems } }50        #if os(macOS)51        .toolbar {52            ToolbarItem(placement: .primaryAction) {53                Menu {54                    ForEach(ItemType.allCases, id: \.self) { t in55                        Button { model.newItem(t) } label: { Label(t.template.label, systemImage: ItemMeta.symbol(t)) }56                    }57                } label: { Label("New item", systemImage: "plus") } primaryAction: { model.newItem() }58                .help("New item (⌘N)").accessibilityIdentifier("new-item")59            }60            ToolbarItem(placement: .primaryAction) { SyncPill() }61            ToolbarItem(placement: .primaryAction) {62                Button { model.lock() } label: { Label("Lock", systemImage: "lock") }.help("Lock (⌘L)").accessibilityIdentifier("lock")63            }64        }65        #endif66        .sheet(item: $model.editor) { ItemEditorView(request: $0) }67        #if os(macOS)68        .frame(minWidth: 980, minHeight: 620)69        #endif70        .containerID("main")71    }7273    private var listWidth: CGFloat {74        #if os(macOS)75        31076        #else77        34078        #endif79    }8081    @ViewBuilder private var toolPage: some View {82        switch model.section {83        case .vaults: VaultsPage()84        case .shared: RelayPage()85        case .security: SecurityCenterPage()86        case .generator: GeneratorPage()87        case .devices: DevicesPage()88        case .activity: ActivityPage()89        case .connect: ConnectPage()90        case .settings: SettingsPage()91        default: EmptyView()92        }93    }94}9596/// Fixed-height banner for states the user must know about (session expired, offline, security warnings).97struct StatusBanner: View {98    @Environment(AppModel.self) private var model99    var body: some View {100        if let h = model.health {101            if h.warnings.contains(where: { $0.localizedCaseInsensitiveContains("rollback") || $0.localizedCaseInsensitiveContains("forged") }) {102                banner("exclamationmark.octagon.fill", Palette.danger, Palette.dangerSoft, "Security warning: the server presented inconsistent data. Open the Security Center for details.", "Open") { model.section = .security }103            } else if h.needsSignIn {104                banner("person.badge.key", Palette.brass, Palette.brassSoft, "The server session expired. Your vault is open from this device's copy; sign in again to sync.", "Sign in") {105                    Task { await model.act("Signed in — syncing") { _ = try await model.engine.signIn(); try await model.engine.sync() } }106                }107                .accessibilityIdentifier("banner-signin")108            } else if !h.online {109                banner("wifi.slash", Palette.muted, Palette.s2, "Offline — changes are saved on this device and sent when the server is reachable.", "Retry") { Task { await model.syncNow() } }110                    .accessibilityIdentifier("banner-offline")111            }112        }113    }114115    private func banner(_ symbol: String, _ tint: Color, _ fill: Color, _ text: String, _ action: String, _ run: @escaping () -> Void) -> some View {116        HStack(spacing: 10) {117            Image(systemName: symbol).foregroundStyle(tint).accessibilityHidden(true)118            Text(text).font(.callout).foregroundStyle(Palette.text).lineLimit(1).truncationMode(.tail)119            Spacer(minLength: 8)120            Button(action, action: run).buttonStyle(.vaultCompact)121        }122        .padding(.horizontal, 16).frame(height: 40)123        .background(fill)124        .overlay(alignment: .bottom) { Rectangle().fill(Palette.line).frame(height: 1) }125    }126}127128struct SyncPill: View {129    @Environment(AppModel.self) private var model130    var body: some View {131        let h = model.health132        let (symbol, text): (String, String) = {133            guard let h else { return ("circle.dotted", "Not synced yet") }134            if !h.online { return ("wifi.slash", h.pending > 0 ? "Offline · \(h.pending) pending" : "Offline") }135            if h.pending > 0 { return ("arrow.triangle.2.circlepath", "\(h.pending) pending") }136            return ("checkmark", "Synced · \(ItemMeta.relative(h.lastSyncAt))")137        }()138        Button { Task { await model.syncNow() } } label: {139            Label(text, systemImage: symbol).labelStyle(.titleAndIcon).font(.callout)140        }141        .help("Sync now (⌘R)")142        .accessibilityIdentifier("sync-pill")143    }144}145146// ── sidebar ──147148private struct Sidebar: View {149    @Environment(AppModel.self) private var model150151    var body: some View {152        @Bindable var model = model153        List(selection: Binding(get: { Optional(model.section) }, set: { if let s = $0 { model.section = s; if !s.isItemList { model.selectedItemID = nil } } })) {154            Section {155                row(.allItems)156                row(.favorites)157            }158            Section {159                ForEach(model.vaults) { v in160                    Label { HStack { Text(v.meta.name.isEmpty ? "Vault" : v.meta.name).lineLimit(1); Spacer(); count(.vault(v.vaultId)) } } icon: { Image(systemName: v.members.count > 1 ? "person.2.square.stack" : "lock.square") }161                        .tag(SidebarSection.vault(v.vaultId)).accessibilityIdentifier(SidebarSection.vault(v.vaultId).testID)162                }163                Label("Manage vaults…", systemImage: "slider.horizontal.3").foregroundStyle(Palette.muted).tag(SidebarSection.vaults).accessibilityIdentifier("section-vaults")164            } header: { Text("Vaults") }165            Section("Categories") { ForEach(SidebarSection.categories, id: \.self) { row($0) } }166            Section("Vault tools") { ForEach(SidebarSection.tools, id: \.self) { row($0) } }167        }168        .listStyle(.sidebar)169        .safeAreaInset(edge: .top, spacing: 0) {170            HStack { BrandMark(size: 22); Spacer() }.padding(.horizontal, 16).padding(.top, 6).padding(.bottom, 8)171        }172        .safeAreaInset(edge: .bottom, spacing: 0) {173            HStack(spacing: 9) {174                Text(String(model.handle.prefix(1)).uppercased()).font(.system(size: 12, weight: .semibold, design: .serif)).foregroundStyle(Palette.accent)175                    .frame(width: 24, height: 24).overlay(Circle().strokeBorder(Palette.accentLine, lineWidth: 1)).accessibilityHidden(true)176                Text(model.handle).font(.callout.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1).accessibilityIdentifier("account-handle")177                Spacer()178                IconButton(systemName: "lock", label: "Lock the vault") { model.lock() }179            }180            .padding(.horizontal, 14).frame(height: 44)181            .background(.bar)182            .overlay(alignment: .top) { Rectangle().fill(Palette.line).frame(height: 1) }183        }184    }185186    private func row(_ s: SidebarSection) -> some View {187        Label { HStack { Text(s.title); Spacer(); if s.isItemList { count(s) } else if s == .devices, model.pairingHint { Circle().fill(Palette.brass).frame(width: 7, height: 7).accessibilityLabel("A device is waiting") } } } icon: { Image(systemName: s.symbol) }188            .tag(s).accessibilityIdentifier(s.testID)189    }190191    private func count(_ s: SidebarSection) -> some View {192        Text("\(model.count(in: s))").font(.caption.monospacedDigit()).foregroundStyle(Palette.muted)193    }194}195196// ── item list ──197198struct ItemListColumn: View {199    @Environment(AppModel.self) private var model200201    var body: some View {202        @Bindable var model = model203        let list = model.items(in: model.section)204        VStack(alignment: .leading, spacing: 0) {205            HStack(alignment: .firstTextBaseline, spacing: 8) {206                Text(title).font(.vaultHeadline).foregroundStyle(Palette.text).lineLimit(1)207                Text("\(list.count) item\(list.count == 1 ? "" : "s")").font(.caption).foregroundStyle(Palette.muted).accessibilityIdentifier("list-count")208                Spacer()209                #if os(iOS)210                Button { Task { await model.syncNow() } } label: { Image(systemName: model.health?.online == false ? "wifi.slash" : "arrow.triangle.2.circlepath").foregroundStyle(Palette.muted) }211                    .accessibilityLabel("Sync now").accessibilityIdentifier("sync-pill")212                Menu {213                    ForEach(ItemType.allCases, id: \.self) { t in Button { model.newItem(t) } label: { Label(t.template.label, systemImage: ItemMeta.symbol(t)) } }214                } label: {215                    Image(systemName: "plus").font(.body.weight(.semibold)).foregroundStyle(Palette.accentInk).frame(width: 34, height: 34).background(Palette.accent, in: Circle())216                } primaryAction: { model.newItem() }217                .accessibilityLabel("New item").accessibilityIdentifier("new-item")218                #endif219            }220            .padding(.horizontal, 16).frame(height: listHeader)221            if list.isEmpty {222                if model.query.isEmpty { EmptyState(symbol: model.section.symbol, title: emptyTitle, text: emptyText) }223                else { EmptyState(symbol: "magnifyingglass", title: "No match", text: "Search runs on this device, over titles, usernames, addresses, tags and notes.") }224            } else {225                #if os(macOS)226                List(list, selection: $model.selectedItemID) { v in227                    ItemRowView(view: v).tag(v.id)228                        .listRowSeparator(.hidden)229                        .contextMenu { ItemContextMenu(view: v) }230                }231                .listStyle(.inset)232                .scrollContentBackground(.hidden)233                .accessibilityIdentifier("item-list")234                #else235                List(list) { v in236                    Button { model.selectedItemID = v.id } label: { ItemRowView(view: v) }237                        .buttonStyle(.plain)238                        .listRowSeparator(.hidden)239                        .listRowBackground(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(v.id == model.selectedItemID ? Palette.s3 : Color.clear).padding(.horizontal, 8))240                        .contextMenu { ItemContextMenu(view: v) }241                }242                .listStyle(.plain)243                .scrollContentBackground(.hidden)244                .accessibilityIdentifier("item-list")245                #endif246            }247        }248        .background(Palette.s1.opacity(0.5))249    }250251    private var title: String {252        if case .vault(let id) = model.section { return model.vault(id)?.meta.name ?? "Vault" }253        return model.section.title254    }255    private var listHeader: CGFloat {256        #if os(macOS)257        44258        #else259        56260        #endif261    }262    private var emptyTitle: String { model.section == .trash ? "Trash is empty" : "Nothing here yet" }263    private var emptyText: String { model.section == .trash ? "Items you move to the trash stay here until you delete them permanently." : SplitMainView.addHint }264}265266extension SplitMainView {267    static var addHint: String {268        #if os(macOS)269        "Press ⌘N to add an item."270        #else271        "Tap + to add an item."272        #endif273    }274}275276struct ItemContextMenu: View {277    @Environment(AppModel.self) private var model278    let view: ItemView279    var body: some View {280        if (view.item.trashedAt ?? "").isEmpty {281            if view.item.fields["username"]?.isEmpty == false { Button("Copy Username") { model.copyUsername(view) } }282            if SPV1.primarySecret(view.item) != nil { Button("Copy Password") { model.copyPassword(view) } }283            if view.item.fields["totp"]?.isEmpty == false { Button("Copy One-Time Code") { model.copyOneTimeCode(view) } }284            Divider()285            Button("Edit…") { model.edit(view) }286            Button(view.item.favorite ? "Remove from Favorites" : "Add to Favorites") { Task { await model.toggleFavorite(view) } }287            Divider()288            Button("Move to Trash", role: .destructive) { Task { await model.trash(view) } }289        } else {290            Button("Restore") { Task { await model.restore(view) } }291        }292    }293}294
Files main
Menu

Theme