DEV Community

Darkø Tasevski
Darkø Tasevski

Posted on Originally published at darkotasevski.dev

Keeping a Readium navigator on screen while a SwiftUI reader closes

I'm building an ebook reader with SwiftUI, TCA (The Composable Architecture) and Readium, and I want to write down a bug from its EPUB close, because the fix was one line in a view's switch but finding why that line mattered took me through how SwiftUI decides what stays mounted.

The close and what it has to do

When we close an EPUB, a few things happen in order. The reader's TCA store gets .onDisappear, which stops its observers, releases keep-awake and resets the reader's per-book state. Then a dismiss step reads the page that is currently visible and keeps a short excerpt of it, the Readium navigator is closed, and the excerpt is saved for the Home screen, which shows it as "where you left off".

The Mac (Catalyst) reader window already did it in that order, but on iOS nothing sent the store .onDisappear at all, so that teardown never ran there. The change that fixed it ended the store first in the iOS close too, roughly like this (simplified, the real code returns a tuple):

private static func endStore(
    _ store: StoreOf<ReaderFeature>?
) async -> CaptureReads? {
    guard let store else { return nil }
    let reads = CaptureReads(state: store.state)
    await store.send(.onDisappear).finish()
    return reads
}
Enter fullscreen mode Exit fullscreen mode

The surface's teardown calls this first, then runs the excerpt capture against the navigator, then closes it. Ending the store before the capture is deliberate, because the store's reset shouldn't have to wait on a page read and a flush. When I tried it on an iPhone, the close looked fine and Home showed an excerpt.

Why the excerpt was empty

On iOS the reader is a full-screen cover, and the cover is still on screen while this teardown runs (it is only removed after the close settles), so the reader view keeps rendering the whole time. That matters because of what .onDisappear does to the reducer's phase:

switch readerPhase {
case .ready:
    if let publication {
        navigatorView(publication: publication)
    } else {
        loadingView(bookTitle: bookTitle)
    }

case .idle, .loadingInitialData, .openingPublication:
    loadingView(bookTitle: bookTitle)

case .closing:
    // Show loading during close (brief transition)
    loadingView(bookTitle: bookTitle)

// ...
}
Enter fullscreen mode Exit fullscreen mode

.onDisappear sets readerPhase = .closing, and .closing was drawn as the loading view, so the very next render after ending the store swapped the navigator's representable out for the loading view, under a cover that was still presented. The Readium fork the app uses drops its loaded pages when the pagination view leaves the window (stock Readium only cancels the page loads that are still in flight, so on upstream the details would differ, but a view that was taken out of the window is still not something a later step should read). By the time the excerpt capture asked the navigator for the visible text there was no current page, the read returned nil and nothing was saved. Every guard on the way passed, because the holder (the object that keeps the navigator alive across renders) still had the navigator, it just had nothing loaded in it anymore.

A review of the change pointed this out, and my device check had missed it because the excerpt on Home was the one an earlier close had left there (the capture only logs at debug level, so the console at the default level showed nothing either way). A check that the old value can't fake is to jump to a different chapter, close the book with the Close button, and look at whether Home moved, and doing that showed the old text.

Before moving a state change earlier in a teardown, look at what the view draws for that state while it's still on screen, and at every later step that reads something the view hosts.

Drawing the closing phase through the live branch

The obvious alternative is to send .onDisappear after the capture again, but that brings back the reset waiting on the page read, so the fix goes in the view instead, which keeps drawing the navigator while the reader closes. How we write that matters, because SwiftUI treats each branch of a switch in a view builder as a different view, so two cases that both draw navigatorView still tear the representable down and build a new one when the phase moves from one to the other, and the pages are dropped anyway. Both phases have to land in the same branch, and here that's one case with two patterns:

switch readerPhase {
case .ready, .closing:
    // A reader closed mid-open never drew a navigator, so don't build one now.
    if let publication, readerPhase == .ready || isNavigatorReady {
        navigatorView(publication: publication)
    } else {
        loadingView(bookTitle: bookTitle)
    }

case .idle, .loadingInitialData, .openingPublication:
    loadingView(bookTitle: bookTitle)

// ...
}
Enter fullscreen mode Exit fullscreen mode

Now the navigator keeps its identity across .ready → .closing and stays in the window until the holder releases the publication, so it still has its pages when the capture reads them. The Mac window ends its store in the same order, so the fix covers it there too, although I never checked whether the Mac was losing excerpts before. The tests that existed read the source text and stayed green with the bug in place, so the shared case is now pinned by a test that fails if .closing gets a case of its own again.

The isNavigatorReady check came from a second look at the first version of the fix, which was only if let publication. That version also drew a navigator for a reader closed while its publication was still opening, because the cancelled open could still hand the holder its publication, and .closing would then build a fresh navigator for a holder that was already closed for good (a Cmd-W on the Mac or a quick dismiss during a slow open). isNavigatorReady is view @State that is set once the navigator is first ready, and the reducer's reset can't touch it, so in .closing the condition means "a navigator was already on screen", and otherwise the view stays on the loading view.

Summary

A phase that the reducer sets during a teardown is something the view renders, as long as the view is still on screen, so if a later step reads a view, a web view or a UIKit object that the view hosts, the terminal phase should keep drawing what the live phase drew, through the same switch branch so SwiftUI sees one view. And when we verify something like a saved excerpt, we should change the input first (another chapter, another page), so that a value left over from a previous run can't pass for a new one.

Top comments (0)