SPB Git

Repository Public

PhoneMainView.swift 12.6 KB 237 lines swift

1// iPhone: tab bar (Items, Generator, Security, Settings, Search), item list with swipe actions, primary actions2// within thumb reach at the bottom.3import SharedVaultKit4import SwiftUI56struct PhoneMainView: View {7    enum TabID: Hashable { case items, generator, security, settings, search }8    @Environment(AppModel.self) private var model9    @State private var tab: TabID = .items10    @State private var settingsPath: [SidebarSection] = []1112    var body: some View {13        @Bindable var model = model14        TabView(selection: $tab) {15            Tab("Items", systemImage: "square.grid.2x2", value: TabID.items) { ItemsTab() }16            Tab("Generator", systemImage: "dice", value: TabID.generator) { NavigationStack { GeneratorPage() } }17            Tab("Security", systemImage: "checkmark.shield", value: TabID.security) { NavigationStack { SecurityCenterPage() } }18            Tab("Settings", systemImage: "gearshape", value: TabID.settings) { MoreTab(path: $settingsPath) }19                .badge(model.pairingHint ? 1 : 0)20            // an ordinary tab: with the search role, iOS 26 bounces back to the previous tab as soon as the field is not focused21            Tab("Search", systemImage: "magnifyingglass", value: TabID.search) { SearchTab() }22        }23        .tint(Palette.accent)24        .safeAreaInset(edge: .top, spacing: 0) { StatusBanner() }25        .sheet(item: $model.editor) { ItemEditorView(request: $0) }26        .onChange(of: model.revealTick) { _, _ in tab = .items }27        .onChange(of: model.section) { _, s in28            // pages asked for by other screens ("open this vault", "open the Security Center")29            if case .vault = s { tab = .items }30            else if s == .security { tab = .security }31            else if s == .generator { tab = .generator }32        }33        .containerID("main")34    }35}3637// ── Items ──3839private struct ItemsTab: View {40    @Environment(AppModel.self) private var model41    @State private var confirm: ConfirmRequest?4243    var body: some View {44        @Bindable var model = model45        let section = model.section.isItemList ? model.section : .allItems46        let list = model.items(in: section)47        NavigationStack {48            Group {49                if list.isEmpty {50                    EmptyState(symbol: section.symbol, title: section == .trash ? "Trash is empty" : "Nothing here yet",51                               text: section == .trash ? "Items you move to the trash stay here until you delete them permanently." : "Tap + to add your first item.")52                } else {53                    List(list) { v in54                        Button { model.selectedItemID = v.id; Haptics.tap() } label: { ItemRowView(view: v) }55                            .buttonStyle(.plain)56                            .listRowBackground(Palette.bg)57                            .listRowSeparatorTint(Palette.line)58                            .swipeActions(edge: .leading, allowsFullSwipe: true) {59                                if SPV1.primarySecret(v.item) != nil, section != .trash {60                                    Button { model.copyPassword(v) } label: { Label("Copy password", systemImage: "key") }.tint(Palette.accent)61                                }62                            }63                            .swipeActions(edge: .trailing, allowsFullSwipe: false) {64                                if section == .trash {65                                    Button { Task { await model.restore(v) } } label: { Label("Restore", systemImage: "arrow.uturn.backward") }.tint(Palette.accent)66                                } else if model.vault(v.vaultId)?.role != .reader {67                                    Button(role: .destructive) { Task { await model.trash(v) } } label: { Label("Trash", systemImage: "trash") }68                                    Button { Task { await model.toggleFavorite(v) } } label: { Label(v.item.favorite ? "Unfavorite" : "Favorite", systemImage: v.item.favorite ? "star.slash" : "star") }.tint(Palette.brass)69                                }70                            }71                            .contextMenu { ItemContextMenu(view: v) }72                    }73                    .listStyle(.plain)74                    .accessibilityIdentifier("item-list")75                }76            }77            .vaultBackground()78            .scrollContentBackground(.hidden)79            .navigationTitle(title(section))80            .navigationBarTitleDisplayMode(.large)81            .toolbar {82                ToolbarItem(placement: .topBarLeading) {83                    Button { model.lock() } label: { Label("Lock", systemImage: "lock") }.accessibilityIdentifier("lock")84                }85                ToolbarItem(placement: .topBarTrailing) { sectionMenu(section) }86            }87            .overlay(alignment: .bottomTrailing) { addButton }88            .navigationDestination(item: $model.selectedItemID) { id in89                if let v = model.item(id) { ItemDetailView(view: v).navigationBarTitleDisplayMode(.inline) }90                else { EmptyState(symbol: "questionmark.square.dashed", title: "This item is no longer here") }91            }92        }93    }9495    private func title(_ s: SidebarSection) -> String {96        if case .vault(let id) = s { return model.vault(id)?.meta.name ?? "Vault" }97        return s.title98    }99100    private func sectionMenu(_ current: SidebarSection) -> some View {101        Menu {102            Picker("Show", selection: Binding(get: { current }, set: { model.section = $0 })) {103                Label("All Items (\(model.count(in: .allItems)))", systemImage: SidebarSection.allItems.symbol).tag(SidebarSection.allItems)104                Label("Favorites (\(model.count(in: .favorites)))", systemImage: SidebarSection.favorites.symbol).tag(SidebarSection.favorites)105                Section("Vaults") {106                    ForEach(model.vaults) { v in Label("\(v.meta.name) (\(model.count(in: .vault(v.vaultId))))", systemImage: "lock.square").tag(SidebarSection.vault(v.vaultId)) }107                }108                Section("Categories") {109                    ForEach(SidebarSection.categories, id: \.self) { s in Label("\(s.title) (\(model.count(in: s)))", systemImage: s.symbol).tag(s) }110                }111                Label("Trash (\(model.count(in: .trash)))", systemImage: "trash").tag(SidebarSection.trash)112            }113        } label: { Label("Show", systemImage: "line.3.horizontal.decrease.circle") }114        .accessibilityIdentifier("section-menu")115    }116117    private var addButton: some View {118        Menu {119            ForEach(ItemType.allCases, id: \.self) { t in Button { model.newItem(t) } label: { Label(t.template.label, systemImage: ItemMeta.symbol(t)) } }120        } label: {121            Image(systemName: "plus").font(.title2.weight(.semibold)).foregroundStyle(Palette.accentInk)122                .frame(width: 58, height: 58).background(Palette.accent, in: Circle()).shadow(color: .black.opacity(0.3), radius: 10, y: 4)123        } primaryAction: { model.newItem(); Haptics.tap() }124        .padding(.trailing, 20).padding(.bottom, 16)125        .accessibilityLabel("New item").accessibilityIdentifier("new-item")126    }127}128129// ── Search ──130131private struct SearchTab: View {132    @Environment(AppModel.self) private var model133    /// Local to this tab: the Items tab is never filtered by a query the user cannot see.134    @State private var query = ""135136    private var results: [ItemView] {137        let q = query.trimmingCharacters(in: .whitespaces)138        guard !q.isEmpty else { return [] }139        return model.items.filter { ($0.item.trashedAt ?? "").isEmpty && SPV1.matchesQuery(haystack: SPV1.searchText($0.item), query: q) }140            .sorted { ItemMeta.displayTitle($0.item).localizedCaseInsensitiveCompare(ItemMeta.displayTitle($1.item)) == .orderedAscending }141    }142143    var body: some View {144        NavigationStack {145            let results = results146            Group {147                if query.trimmingCharacters(in: .whitespaces).isEmpty {148                    EmptyState(symbol: "magnifyingglass", title: "Search your vault", text: "Search runs on this device, over titles, usernames, addresses, tags and notes. Nothing you type is sent to the server.")149                } else if results.isEmpty {150                    EmptyState(symbol: "magnifyingglass", title: "No match")151                } else {152                    List(results) { v in153                        Button { let id = v.id; model.reveal(id) } label: { ItemRowView(view: v) }.buttonStyle(.plain)154                            .listRowBackground(Palette.bg).listRowSeparatorTint(Palette.line)155                            .swipeActions(edge: .leading) { if SPV1.primarySecret(v.item) != nil { Button { model.copyPassword(v) } label: { Label("Copy password", systemImage: "key") }.tint(Palette.accent) } }156                    }157                    .listStyle(.plain).accessibilityIdentifier("search-results")158                }159            }160            .vaultBackground().scrollContentBackground(.hidden)161            .navigationTitle("Search")162            .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "Titles, usernames, addresses, tags")163            .autocorrectionDisabled().textInputAutocapitalization(.never)164            .onChange(of: model.isUnlocked) { _, _ in query = "" }165        }166    }167}168169// ── Settings tab: tools + preferences ──170171private struct MoreTab: View {172    @Environment(AppModel.self) private var model173    @Binding var path: [SidebarSection]174    private static let tools: [SidebarSection] = [.vaults, .shared, .devices, .activity, .connect]175176    var body: some View {177        NavigationStack(path: $path) {178            List {179                Section {180                    HStack(spacing: 12) {181                        Text(String(model.handle.prefix(1)).uppercased()).font(.system(size: 20, weight: .semibold, design: .serif)).foregroundStyle(Palette.accent)182                            .frame(width: 44, height: 44).overlay(Circle().strokeBorder(Palette.accentLine, lineWidth: 1.5)).accessibilityHidden(true)183                        VStack(alignment: .leading, spacing: 2) {184                            Text(model.handle).font(.headline).foregroundStyle(Palette.text).accessibilityIdentifier("account-handle")185                            SyncLine()186                        }187                    }188                    .padding(.vertical, 4).listRowBackground(Palette.s1)189                }190                Section("Vault tools") {191                    ForEach(Self.tools, id: \.self) { s in192                        NavigationLink(value: s) {193                            HStack {194                                Label(s.title, systemImage: s.symbol)195                                if s == .devices, model.pairingHint { Spacer(); Circle().fill(Palette.brass).frame(width: 8, height: 8).accessibilityLabel("A device is waiting") }196                            }197                        }198                        .accessibilityIdentifier(s.testID).listRowBackground(Palette.s1)199                    }200                }201                Section {202                    NavigationLink(value: SidebarSection.settings) { Label("Preferences, backup and account", systemImage: "gearshape") }203                        .accessibilityIdentifier("section-settings").listRowBackground(Palette.s1)204                }205                Section {206                    Button { model.lock() } label: { Label("Lock the vault", systemImage: "lock") }.foregroundStyle(Palette.brass)207                        .accessibilityIdentifier("lock-row").listRowBackground(Palette.s1)208                }209            }210            .scrollContentBackground(.hidden).vaultBackground()211            .navigationTitle("Settings")212            .navigationDestination(for: SidebarSection.self) { s in213                switch s {214                case .vaults: VaultsPage()215                case .shared: RelayPage()216                case .devices: DevicesPage()217                case .activity: ActivityPage()218                case .connect: ConnectPage()219                default: SettingsPage()220                }221            }222        }223    }224}225226private struct SyncLine: View {227    @Environment(AppModel.self) private var model228    var body: some View {229        let h = model.health230        Button { Task { await model.syncNow() } } label: {231            Text(h == nil ? "Not synced yet" : (h!.online ? (h!.pending > 0 ? "\(h!.pending) change\(h!.pending == 1 ? "" : "s") waiting to sync" : "Synced \(ItemMeta.relative(h!.lastSyncAt))") : "Offline — changes are kept on this device"))232                .font(.caption).foregroundStyle(Palette.muted)233        }234        .buttonStyle(.plain).accessibilityHint("Syncs now").accessibilityIdentifier("sync-line")235    }236}237
Files main
Menu

Theme