Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ struct SettingsView: View {
@EnvironmentObject var appState: AppState
@State private var isPickingVaultFolder = false
@State private var loggingEnabled: Bool
/// Drives the remove-vault confirmation alert below — set by the per-row trash
/// button, matching Android's `vaultToRemove` (SettingsScreen.kt) rather than
/// deleting on tap/swipe with no confirmation.
@State private var vaultPendingRemoval: Vault?
private let logStore = LibraVaultLogStore()

private let skipDurationPresets: [Double] = [10, 15, 30, 45, 60]
Expand Down Expand Up @@ -41,11 +45,18 @@ struct SettingsView: View {
Text(vault.displayName)
.foregroundStyle(LibraVaultColor.onSurface)
Spacer()
}
}
.onDelete { offsets in
for index in offsets {
appState.removeVault(appState.vaults[index])
// Trash icon + confirm alert (below), not swipe/long-press —
// matches Android's VaultRow (SettingsScreen.kt) for parity and
// discoverability. Deliberately not `.onDelete`: a bare swipe
// would delete the vault with no confirmation at all.
Button {
vaultPendingRemoval = vault
} label: {
Image(systemName: "trash")
.foregroundStyle(.red)
}
.buttonStyle(.borderless)
.accessibilityLabel("Remove vault")
}
}

Expand All @@ -61,6 +72,26 @@ struct SettingsView: View {
appState.addVault(pickedURL: pickedURL)
}
}
// Copy mirrors Android's remove-vault AlertDialog (SettingsScreen.kt) word
// for word, down to the quoted display name.
.alert(
"Remove vault?",
isPresented: Binding(
get: { vaultPendingRemoval != nil },
set: { isPresented in if !isPresented { vaultPendingRemoval = nil } }
),
presenting: vaultPendingRemoval
) { vault in
Button("Remove", role: .destructive) {
vaultPendingRemoval = nil
Task { await appState.removeVault(vault) }
}
Button("Cancel", role: .cancel) {
vaultPendingRemoval = nil
}
} message: { vault in
Text("This will remove \"\(vault.displayName)\" and all its items from the library.")
}
}

// MARK: - Reading
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,38 @@ class LibravaultDomainBridge: ObservableObject {
logger?.d(tag: "Bookmarks", message: "Deleted bookmark \(bookmarkId)")
}

// MARK: - Vault Operations

/// Swift-native counterpart to core:domain's `RemoveVaultFolderUseCase`
/// (`libraryRepository.deleteByVault(vaultId)` half only — the second half,
/// `vaultRepository.removeVault(vaultId)`, is `VaultPersistence`'s job on iOS,
/// same as `addVault`'s counterpart `AddVaultFolderUseCase` already is). Called
/// by `AppState.removeVault(_:)` with the ids of every book that belonged to the
/// vault being removed, resolved *before* the vault entry itself is dropped.
///
/// No KMP framework is actually linked into this app (see this file's header
/// comment) — Android's use case relies on Room's `ON DELETE CASCADE` foreign
/// keys to drop a deleted library item's highlights/bookmarks/progress rows for
/// free; there's no on-device database here to do that automatically, so this
/// walks the three dictionaries explicitly instead. Without it, a removed
/// vault's reading data would silently linger forever in UserDefaults, keyed by
/// book ids nothing can ever resolve back to a real book again.
func removeVault(bookIds: [String]) async throws {
guard isInitialized else { throw DomainError.notInitialized }
guard !bookIds.isEmpty else { return }

for bookId in bookIds {
bookmarks.removeValue(forKey: bookId)
highlights.removeValue(forKey: bookId)
progress.removeValue(forKey: bookId)
}
persistence.save(bookmarks: bookmarks)
persistence.save(highlights: highlights)
persistence.save(progress: progress)

logger?.d(tag: "Vaults", message: "Removed reading data for \(bookIds.count) book(s) from a deleted vault")
}

// MARK: - Logger Integration
func log(_ message: String, tag: String = "LibraVault") {
logger?.d(tag: tag, message: message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,10 +276,42 @@ final class AppState: ObservableObject {
Task { await loadLibrary() }
}

func removeVault(_ vault: Vault) {
/// Mirrors Android's `RemoveVaultFolderUseCase` (core:domain UseCases.kt): that
/// use case's two steps are `libraryRepository.deleteByVault(vaultId)` — which,
/// via Room's `ON DELETE CASCADE` foreign keys, also drops any highlights/
/// bookmarks/progress rows tied to that vault's library items — then
/// `vaultRepository.removeVault(vaultId)`. iOS has no on-device database with FK
/// cascades to lean on (see DomainBridge.swift's header comment — no KMP
/// framework is actually linked in), so the same two steps are done explicitly
/// here instead: `bridge.removeVault(bookIds:)` is the Swift-native counterpart
/// to the cascading delete (without it, a removed vault's bookmarks/highlights/
/// reading progress would silently linger forever in UserDefaults, keyed by book
/// ids that no longer resolve to anything), then the vault entry itself is
/// dropped from `vaultPersistence`, same as before.
///
/// `async`, unlike `addVault` (which fires its rescan off as an internal,
/// un-awaited `Task`) — the bridge cleanup here has no other synchronization
/// point a caller (or a test) can hook into to know it's finished, so callers
/// await this directly (see `SettingsView`'s confirm-alert action) instead of
/// racing a detached `Task`.
func removeVault(_ vault: Vault) async {
let orphanedBookIds = books.filter { $0.vaultId == vault.id }.map(\.id)
do {
// Cascade-clean bookmarks/highlights/progress FIRST, matching Android's
// RemoveVaultFolderUseCase (deleteByVault before removeVault). If this
// throws, the vault stays in persistence and its books' data survives —
// orphaned-but-recoverable is the safe failure mode. Doing this after
// dropping the vault would risk the opposite: a vault silently gone while
// its books' bookmarks/highlights/progress live on forever with no owner.
try await bridge.removeVault(bookIds: orphanedBookIds)
} catch {
bridge.logError("Couldn't remove vault \"\(vault.displayName)\"", tag: "Vault", error: error)
self.error = AppError.vaultRemovalFailed
return
}
vaults.removeAll { $0.id == vault.id }
vaultPersistence.save(vaults)
Task { await loadLibrary() }
await loadLibrary()
}

/// Entry point for a file the OS hands LibraVault via "Open In"/"Copy to
Expand Down Expand Up @@ -654,6 +686,7 @@ enum AppError: LocalizedError {
case unsupportedFileType
case fileImportFailed
case invalidVaultSelection
case vaultRemovalFailed

var errorDescription: String? {
switch self {
Expand All @@ -669,6 +702,8 @@ enum AppError: LocalizedError {
return "Please select a folder, not a file — pick the folder that contains your books."
case .fileImportFailed:
return "Couldn't import that file"
case .vaultRemovalFailed:
return "Couldn't remove that vault. Please try again."
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,14 @@ final class AppStateVaultTests: XCTestCase {
XCTAssertEqual(state.error?.errorDescription, AppError.invalidVaultSelection.errorDescription)
}

func testRemoveVaultRemovesItFromTheList() throws {
func testRemoveVaultRemovesItFromTheList() async throws {
let state = AppState(vaultPersistence: makeIsolatedPersistence())
let folder = try makeTempVaultFolder()
defer { try? FileManager.default.removeItem(at: folder) }
state.addVault(pickedURL: folder)
let vault = try XCTUnwrap(state.vaults.first)

state.removeVault(vault)
await state.removeVault(vault)

XCTAssertTrue(state.vaults.isEmpty)
}
Expand Down Expand Up @@ -165,9 +165,34 @@ final class AppStateVaultTests: XCTestCase {
await state.loadLibrary()
let vault = try XCTUnwrap(state.vaults.first)

state.removeVault(vault)
await state.loadLibrary()
await state.removeVault(vault)

XCTAssertFalse(state.books.contains { $0.title == "MyAudiobook" })
}

/// Regression guard for issue #223: removing a vault must also drop the
/// bookmarks/highlights/progress recorded against its books — mirrors Android's
/// `RemoveVaultFolderUseCase`, whose `libraryRepository.deleteByVault(vaultId)`
/// cascades to those rows via Room foreign keys. iOS has no such cascade to lean
/// on, so `AppState.removeVault` must explicitly route through
/// `DomainBridge.removeVault(bookIds:)` for this to actually happen — see that
/// method's own tests in DomainBridgeTests for the cleanup logic itself.
func testRemovingAVaultClearsBookmarksForItsBooks() async throws {
try await LibravaultDomainBridge.shared.initialize()
let persistence = makeIsolatedPersistence()
let folder = try makeTempVaultFolder()
defer { try? FileManager.default.removeItem(at: folder) }
try Data().write(to: folder.appendingPathComponent("MyAudiobook.mp3"))

let state = AppState(vaultPersistence: persistence)
state.addVault(pickedURL: folder)
await state.loadLibrary()
let vault = try XCTUnwrap(state.vaults.first)
let book = try XCTUnwrap(state.books.first { $0.vaultId == vault.id })
try await LibravaultDomainBridge.shared.addBookmark(bookId: book.id, position: "0:00")

await state.removeVault(vault)

XCTAssertNil(LibravaultDomainBridge.shared.bookmarks[book.id])
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,65 @@ final class DomainBridgeTests: XCTestCase {
try await bridge.updateProgress(bookId: "3", progress: 0.75)
XCTAssertEqual(bridge.progress["3"], 0.75)
}

// MARK: - removeVault

/// Swift-native counterpart to core:domain's `RemoveVaultFolderUseCase` — see the
/// method's own doc comment. This is the "delete library items for this vault"
/// half; a removed book's bookmarks, highlights, and reading progress must all go.
func testRemoveVaultClearsBookmarksHighlightsAndProgressForGivenBookIds() async throws {
try await bridge.addBookmark(bookId: "removed-1", position: "chapter-1")
try await bridge.addHighlight(bookId: "removed-1", position: "para-1", text: "quote")
try await bridge.updateProgress(bookId: "removed-1", progress: 0.5)

try await bridge.removeVault(bookIds: ["removed-1"])

XCTAssertNil(bridge.bookmarks["removed-1"])
XCTAssertNil(bridge.highlights["removed-1"])
XCTAssertNil(bridge.progress["removed-1"])
}

/// Regression guard: only the books that actually belonged to the removed vault
/// should be affected — a naive "clear everything" implementation would silently
/// wipe an unrelated, still-present book's reading data too. Asserts a delta
/// (like the `addBookmark`/`deleteBookmark` tests above), not an absolute count —
/// `bridge` is the shared singleton, so an earlier test in the same run may have
/// already left bookmarks behind under the same id.
func testRemoveVaultLeavesOtherBooksReadingDataUntouched() async throws {
let before = bridge.bookmarks["kept-untouched"]?.count ?? 0
try await bridge.addBookmark(bookId: "kept-untouched", position: "chapter-2")
try await bridge.updateProgress(bookId: "kept-untouched", progress: 0.3)
try await bridge.addBookmark(bookId: "removed-1", position: "chapter-1")

try await bridge.removeVault(bookIds: ["removed-1"])

XCTAssertEqual(bridge.bookmarks["kept-untouched"]?.count, before + 1)
XCTAssertEqual(bridge.progress["kept-untouched"], 0.3)
}

func testRemoveVaultWithNoBookIdsIsANoOp() async throws {
let before = bridge.bookmarks["kept-noop"]?.count ?? 0
try await bridge.addBookmark(bookId: "kept-noop", position: "chapter-2")

try await bridge.removeVault(bookIds: [])

XCTAssertEqual(bridge.bookmarks["kept-noop"]?.count, before + 1)
}

func testRemoveVaultThrowsWhenBridgeNotInitialized() async {
let uninitialized = LibravaultDomainBridge(
persistence: ReadingDataPersistence(defaults: UserDefaults(suiteName: "DomainBridgeTests.\(UUID().uuidString)")!)
)

do {
try await uninitialized.removeVault(bookIds: ["1"])
XCTFail("Expected DomainError.notInitialized to be thrown")
} catch DomainError.notInitialized {
// expected
} catch {
XCTFail("Expected DomainError.notInitialized, got \(error)")
}
}
}

/// Regression coverage for the actual bug being fixed: bookmarks/highlights/progress
Expand Down Expand Up @@ -134,4 +193,22 @@ final class DomainBridgePersistenceTests: XCTestCase {

XCTAssertEqual(reloaded.progress["3"], 0.75)
}

/// Regression guard: `removeVault`'s cleanup must actually persist, not just
/// mutate the in-memory dictionaries — a relaunch (a fresh bridge instance
/// reading the same UserDefaults) must not see the removed book's data reappear.
func testRemoveVaultCleanupPersistsAcrossBridgeInstances() async throws {
let persistence = makeIsolatedPersistence()
let first = LibravaultDomainBridge(persistence: persistence)
try await first.initialize()
try await first.addBookmark(bookId: "removed-1", position: "chapter-1")
try await first.updateProgress(bookId: "removed-1", progress: 0.5)

try await first.removeVault(bookIds: ["removed-1"])

let reloaded = LibravaultDomainBridge(persistence: persistence)
try await reloaded.initialize()
XCTAssertNil(reloaded.bookmarks["removed-1"])
XCTAssertNil(reloaded.progress["removed-1"])
}
}
Loading