Commit 92019274 authored by Kourser's avatar Kourser
Browse files

feat: expérience de lecture à la manière de Books

Le lecteur EPUB affichait le texte et rien d'autre. Il a maintenant ce
qu'on attend d'une app de lecture : pages tournées plutôt que
défilement, trois thèmes — clair, sépia, nuit —, taille de police par
paliers, six polices présentes sur iOS plus OpenDyslexic que Readium
embarque, et sous un interrupteur les réglages fins : interligne,
alignement, espace entre paragraphes, césures, marges.

L'interrupteur « respecter la mise en forme de l'éditeur » est exposé
parce que Readium fonctionne ainsi : tant qu'il est actif, l'interligne
et l'alignement sont ignorés. Le masquer donnerait un curseur qui a
l'air cassé.

S'y ajoutent le sommaire déclaré par le livre, le titre de chapitre et
le pourcentage en pied de page, et un chrome qui s'escamote au tap pour
ne laisser que le texte. Le tap passe par l'observateur d'entrée du
navigateur et non par un geste SwiftUI, qui empêcherait les pages de
tourner.

Les réglages valent pour toute la bibliothèque, pas par livre :
quelqu'un qui a trouvé sa taille de police la veut partout.

Deux pièges du compilateur, notés sur place : `Link` est ambigu parce
que SwiftUI en déclare un, et un sommaire dessiné récursivement dans une
fonction `some View` définit son type opaque en fonction de lui-même —
il est donc aplati, la profondeur devenant une indentation.

198 tests au vert.

Co-Authored-By: default avatarClaude Opus 5 <noreply@anthropic.com>
parent 6397ef12
Loading
Loading
Loading
Loading
+13 −0
Changes for CHANGELOG.md: 13 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,19 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).

## [Non publié]

### Ajouté
- Expérience de lecture à la manière de Books : pages tournées, thèmes clair,
  sépia et nuit, taille de police par paliers, choix de police dont
  OpenDyslexic, et sous un interrupteur l'interligne, l'alignement, l'espace
  entre paragraphes, les césures et les marges.
- Sommaire du livre, titre de chapitre et progression en pied de page, chrome
  escamotable au tap.
- Les réglages de lecture valent pour toute la bibliothèque et survivent au
  relancement.
- File d'attente du mode voiture : résumés déjà produits du plus court au plus
  long, puis le livre repris en cours, avec enchaînement automatique et un
  récapitulatif de ce qui est disponible hors-ligne.

### Corrigé
- La connexion à un calibre-server échouait avec des identifiants corrects :
  son `--auth-mode` vaut `auto` par défaut, ce qui signifie **Digest**, et le
+168 −2
Changes for Packages/Core/Sources/PodbookUI/Reader/EPUBReader.swift: 168 added lines, 2 removed lines.
Original line number Diff line number Diff line
#if canImport(ReadiumNavigator)

import ReadiumNavigator
import ReadiumShared
// `@preconcurrency`: `Publication` is not `Sendable` and `tableOfContents()`
// is not main-actor-isolated, so reading it from this main-actor context trips
// region isolation. Same scoped exemption as in EPUBTextSource.
@preconcurrency import ReadiumShared
import ReadiumStreamer
import SwiftUI
import UIKit
@@ -82,10 +85,16 @@ final class EPUBReaderModel {
    /// Where the reader is now, so « listen from here » and « summarise from
    /// here » start at the page on screen.
    var currentLocator: Locator?
    /// 0…1 through the whole book, for the footer.
    var progression: Double?
    var tableOfContents: [ReadiumShared.Link] = []
    /// Chrome hides while reading and comes back on a tap, as Books does.
    var isChromeVisible = true

    let file: ReadableFile
    let bookID: Int
    private let locations: ReadingLocationStore
    private weak var navigator: EPUBNavigatorViewController?

    init(file: ReadableFile, bookID: Int, locations: ReadingLocationStore) {
        self.file = file
@@ -100,18 +109,35 @@ final class EPUBReaderModel {
        let stored = locations.location(bookID: bookID, format: file.format)
        let initial = stored.flatMap { ReadiumLocatorCoding.decode($0.locator) }
        currentLocator = initial
        progression = stored?.progression

        do {
            let publication = try await EPUBOpener.open(fileURL: file.url)
            phase = .ready(publication, initialLocator: initial)
            tableOfContents = (try? await publication.tableOfContents().get()) ?? []
        } catch {
            phase = .failed(error.localizedDescription)
        }
    }

    func attach(_ navigator: EPUBNavigatorViewController, preferences: ReaderPreferences) {
        self.navigator = navigator
        apply(preferences)
    }

    func apply(_ preferences: ReaderPreferences) {
        navigator?.submitPreferences(preferences.epubPreferences)
    }

    func go(to link: ReadiumShared.Link) {
        guard let navigator else { return }
        Task { _ = await navigator.go(to: link, options: NavigatorGoOptions(animated: true)) }
    }

    func record(_ locator: Locator) {
        currentTitle = locator.title
        currentLocator = locator
        progression = locator.locations.totalProgression
        guard let encoded = ReadiumLocatorCoding.encode(locator) else { return }
        locations.save(
            ReadingLocation(
@@ -123,26 +149,41 @@ final class EPUBReaderModel {
        )
    }

    func toggleChrome() {
        isChromeVisible.toggle()
    }

    func close() async {
        await locations.flush()
    }

    var progressLabel: String? {
        guard let progression else { return nil }
        return "\(Int((progression * 100).rounded())) %"
    }
}

// MARK: - View

struct EPUBReaderView: View {
    @State private var model: EPUBReaderModel
    private let preferences: ReaderPreferencesStore
    private let onTranslate: (String) -> Void
    private let onTextSource: (@escaping (DigestScope) async -> [NarrationSegment], String) -> Void

    @State private var showingSettings = false
    @State private var showingContents = false

    init(
        file: ReadableFile,
        bookID: Int,
        locations: ReadingLocationStore,
        preferences: ReaderPreferencesStore,
        onTranslate: @escaping (String) -> Void,
        onTextSource: @escaping (@escaping (DigestScope) async -> [NarrationSegment], String) -> Void
    ) {
        _model = State(initialValue: EPUBReaderModel(file: file, bookID: bookID, locations: locations))
        self.preferences = preferences
        self.onTranslate = onTranslate
        self.onTextSource = onTextSource
    }
@@ -150,10 +191,39 @@ struct EPUBReaderView: View {
    var body: some View {
        content
            .task { await model.load() }
            .onChange(of: preferences.preferences) { _, new in model.apply(new) }
            .onDisappear {
                let model = model
                Task { await model.close() }
            }
            .toolbar {
                if case .ready = model.phase {
                    ToolbarItem {
                        Button { showingContents = true } label: {
                            Label("Sommaire", systemImage: "list.bullet")
                        }
                    }
                    ToolbarItem {
                        Button { showingSettings = true } label: {
                            Text("Aa").font(.body.weight(.semibold))
                        }
                    }
                }
            }
            .toolbarVisibility(model.isChromeVisible ? .automatic : .hidden, for: .navigationBar)
            .sheet(isPresented: $showingSettings) {
                ReaderSettingsPanel(store: preferences)
            }
            .sheet(isPresented: $showingContents) {
                TableOfContentsView(links: model.tableOfContents) { link in
                    model.go(to: link)
                }
            }
            .safeAreaInset(edge: .bottom) {
                if model.isChromeVisible, case .ready = model.phase {
                    footer
                }
            }
    }

    @ViewBuilder
@@ -165,8 +235,11 @@ struct EPUBReaderView: View {
            EPUBNavigatorContainer(
                publication: publication,
                initialLocator: initialLocator,
                preferences: preferences.preferences,
                onLocationChange: { model.record($0) },
                onTranslate: onTranslate
                onTranslate: onTranslate,
                onTap: { model.toggleChrome() },
                onNavigator: { model.attach($0, preferences: preferences.preferences) }
            )
            .ignoresSafeArea(edges: .bottom)
            .task {
@@ -191,6 +264,23 @@ struct EPUBReaderView: View {
            }
        }
    }

    /// Chapter and progress, like the line at the bottom of a Books page.
    private var footer: some View {
        HStack {
            Text(model.currentTitle ?? model.file.title)
                .lineLimit(1)
            Spacer()
            if let progress = model.progressLabel {
                Text(progress).monospacedDigit()
            }
        }
        .font(.caption)
        .foregroundStyle(.secondary)
        .padding(.horizontal, 16)
        .padding(.vertical, 8)
        .background(.bar)
    }
}

/// Hosts Readium's navigator inside SwiftUI, through a parent view controller.
@@ -203,8 +293,11 @@ struct EPUBReaderView: View {
private struct EPUBNavigatorContainer: UIViewControllerRepresentable {
    let publication: Publication
    let initialLocator: Locator?
    let preferences: ReaderPreferences
    let onLocationChange: (Locator) -> Void
    let onTranslate: (String) -> Void
    let onTap: () -> Void
    let onNavigator: (EPUBNavigatorViewController) -> Void

    func makeCoordinator() -> Coordinator {
        Coordinator(onLocationChange: onLocationChange)
@@ -218,6 +311,7 @@ private struct EPUBNavigatorContainer: UIViewControllerRepresentable {
                action: #selector(EPUBHostController.translateSelection)
            ),
        ] + EditingAction.defaultActions
        config.preferences = preferences.epubPreferences

        do {
            let navigator = try EPUBNavigatorViewController(
@@ -227,6 +321,13 @@ private struct EPUBNavigatorContainer: UIViewControllerRepresentable {
            )
            navigator.delegate = context.coordinator
            context.coordinator.navigator = navigator
            // The navigator's own input observer, not a SwiftUI gesture: a tap
            // handler on top of the web view would stop pages turning.
            navigator.addObserver(.tap { _ in
                onTap()
                return true
            })
            onNavigator(navigator)
            return EPUBHostController(navigator: navigator, onTranslate: onTranslate)
        } catch {
            return UIHostingController(rootView: ContentUnavailableView {
@@ -303,4 +404,69 @@ private final class EPUBHostController: UIViewController {
    }
}

/// The book's own table of contents, nested as the publication declares it.
///
/// Flattened into one list rather than drawn recursively: a `some View`
/// function that calls itself defines its opaque type in terms of itself, which
/// the compiler rejects. The depth is carried as a value and turned into an
/// indent.
struct TableOfContentsView: View {
    let links: [ReadiumShared.Link]
    let onSelect: (ReadiumShared.Link) -> Void

    @Environment(\.dismiss) private var dismiss

    struct Entry: Identifiable {
        let id: Int
        let link: ReadiumShared.Link
        let depth: Int
    }

    static func flatten(_ links: [ReadiumShared.Link]) -> [Entry] {
        var entries: [Entry] = []
        func walk(_ links: [ReadiumShared.Link], depth: Int) {
            for link in links {
                entries.append(Entry(id: entries.count, link: link, depth: depth))
                if !link.children.isEmpty { walk(link.children, depth: depth + 1) }
            }
        }
        walk(links, depth: 0)
        return entries
    }

    var body: some View {
        NavigationStack {
            List(Self.flatten(links)) { entry in
                Button {
                    onSelect(entry.link)
                    dismiss()
                } label: {
                    Text(entry.link.title ?? entry.link.href)
                        .padding(.leading, CGFloat(entry.depth) * 14)
                        .frame(maxWidth: .infinity, alignment: .leading)
                }
                .buttonStyle(.plain)
            }
            .overlay {
                if links.isEmpty {
                    ContentUnavailableView {
                        Label("Pas de sommaire", systemImage: "list.bullet")
                    } description: {
                        Text("Ce livre n'en déclare pas.")
                    }
                }
            }
            .navigationTitle("Sommaire")
            #if canImport(UIKit)
            .navigationBarTitleDisplayMode(.inline)
            #endif
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Fermer") { dismiss() }
                }
            }
        }
    }
}

#endif
+217 −0
Changes for Packages/Core/Sources/PodbookUI/Reader/ReaderPreferences.swift: 217 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import Observation

#if canImport(ReadiumNavigator)
import ReadiumNavigator
#endif

/// How the book should look, in terms someone reading would recognise.
///
/// Deliberately its own value type rather than Readium's `EPUBPreferences`:
/// these settings are persisted, shown in an interface and tested, and none of
/// that should depend on a framework that only ships for iOS.
public struct ReaderPreferences: Codable, Sendable, Hashable {
    public enum Theme: String, Codable, CaseIterable, Sendable {
        case light, sepia, dark

        public var label: String {
            switch self {
            case .light: "Clair"
            case .sepia: "Sépia"
            case .dark: "Nuit"
            }
        }
    }

    public enum Layout: String, Codable, CaseIterable, Sendable {
        /// Page turns, like Books. The default, because it is what a book does.
        case paginated
        case scrolled

        public var label: String {
            switch self {
            case .paginated: "Pages"
            case .scrolled: "Défilement"
            }
        }
    }

    /// Typefaces that exist on iOS, plus the accessibility face Readium embeds.
    public enum Typeface: String, Codable, CaseIterable, Sendable {
        case publisher
        case iowanOldStyle
        case georgia
        case palatino
        case seravek
        case helveticaNeue
        case openDyslexic

        public var label: String {
            switch self {
            case .publisher: "De l'éditeur"
            case .iowanOldStyle: "Iowan Old Style"
            case .georgia: "Georgia"
            case .palatino: "Palatino"
            case .seravek: "Seravek"
            case .helveticaNeue: "Helvetica Neue"
            case .openDyslexic: "OpenDyslexic"
            }
        }

        public var isAccessibility: Bool { self == .openDyslexic }
    }

    public enum Alignment: String, Codable, CaseIterable, Sendable {
        case publisher, justify, start

        public var label: String {
            switch self {
            case .publisher: "De l'éditeur"
            case .justify: "Justifié"
            case .start: "À gauche"
            }
        }
    }

    public var theme: Theme
    public var layout: Layout
    public var typeface: Typeface
    /// Multiplier on the publisher's base size; 1 is untouched.
    public var fontSize: Double
    public var lineHeight: Double
    public var pageMargins: Double
    public var paragraphSpacing: Double
    public var alignment: Alignment
    public var hyphens: Bool
    /// When on, the publisher's own stylesheet wins and the fine controls below
    /// have no effect. Readium works that way, and hiding it would make the
    /// line-height slider look broken.
    public var usesPublisherStyles: Bool

    public init(
        theme: Theme = .light,
        layout: Layout = .paginated,
        typeface: Typeface = .publisher,
        fontSize: Double = 1,
        lineHeight: Double = 1.4,
        pageMargins: Double = 1,
        paragraphSpacing: Double = 0,
        alignment: Alignment = .publisher,
        hyphens: Bool = true,
        usesPublisherStyles: Bool = true
    ) {
        self.theme = theme
        self.layout = layout
        self.typeface = typeface
        self.fontSize = fontSize
        self.lineHeight = lineHeight
        self.pageMargins = pageMargins
        self.paragraphSpacing = paragraphSpacing
        self.alignment = alignment
        self.hyphens = hyphens
        self.usesPublisherStyles = usesPublisherStyles
    }

    public static let fontSizeRange: ClosedRange<Double> = 0.6...2.5
    public static let fontSizeStep = 0.1
    public static let lineHeightRange: ClosedRange<Double> = 1.0...2.2
    public static let pageMarginsRange: ClosedRange<Double> = 0.5...2.0
    public static let paragraphSpacingRange: ClosedRange<Double> = 0...2.0

    public var fontSizePercentage: Int { Int((fontSize * 100).rounded()) }

    public mutating func enlarge() {
        fontSize = min(Self.fontSizeRange.upperBound, fontSize + Self.fontSizeStep)
    }

    public mutating func shrink() {
        fontSize = max(Self.fontSizeRange.lowerBound, fontSize - Self.fontSizeStep)
    }

    public var canEnlarge: Bool { fontSize < Self.fontSizeRange.upperBound - 0.001 }
    public var canShrink: Bool { fontSize > Self.fontSizeRange.lowerBound + 0.001 }

    /// Changing a font or a text colour while the publisher's styles are in
    /// charge does nothing, so the interface says so rather than lying.
    public var fineControlsApply: Bool { !usesPublisherStyles }
}

/// Remembers the reading settings between books and launches.
///
/// One set for the whole library, not one per book: someone who has found their
/// font size wants it everywhere.
@MainActor
@Observable
public final class ReaderPreferencesStore {
    public var preferences: ReaderPreferences {
        didSet { persist() }
    }

    private let defaults: UserDefaults
    private let key = "podbook.reader.preferences"

    public init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
        if let data = defaults.data(forKey: key),
           let decoded = try? JSONDecoder().decode(ReaderPreferences.self, from: data) {
            preferences = decoded
        } else {
            preferences = ReaderPreferences()
        }
    }

    private func persist() {
        guard let data = try? JSONEncoder().encode(preferences) else { return }
        defaults.set(data, forKey: key)
    }
}

#if canImport(ReadiumNavigator)

public extension ReaderPreferences {
    /// Translates into what the navigator understands.
    var epubPreferences: EPUBPreferences {
        EPUBPreferences(
            fontFamily: readiumFontFamily,
            fontSize: fontSize,
            hyphens: fineControlsApply ? hyphens : nil,
            lineHeight: fineControlsApply ? lineHeight : nil,
            pageMargins: pageMargins,
            paragraphSpacing: fineControlsApply ? paragraphSpacing : nil,
            publisherStyles: usesPublisherStyles,
            scroll: layout == .scrolled,
            textAlign: fineControlsApply ? readiumAlignment : nil,
            theme: readiumTheme
        )
    }

    private var readiumTheme: ReadiumNavigator.Theme {
        switch theme {
        case .light: .light
        case .sepia: .sepia
        case .dark: .dark
        }
    }

    private var readiumFontFamily: FontFamily? {
        switch typeface {
        case .publisher: nil
        case .iowanOldStyle: .iowanOldStyle
        case .georgia: .georgia
        case .palatino: .palatino
        case .seravek: .seravek
        case .helveticaNeue: .helveticaNeue
        case .openDyslexic: .openDyslexic
        }
    }

    private var readiumAlignment: ReadiumNavigator.TextAlignment? {
        switch alignment {
        case .publisher: nil
        case .justify: .justify
        case .start: .start
        }
    }
}

#endif
+168 −0
Changes for Packages/Core/Sources/PodbookUI/Reader/ReaderSettingsPanel.swift: 168 added lines, 0 removed lines.
Original line number Diff line number Diff line
import SwiftUI

/// The « Aa » panel: themes, size, typeface, and the finer controls under a
/// disclosure, as Books does it.
struct ReaderSettingsPanel: View {
    @Bindable var store: ReaderPreferencesStore
    @Environment(\.dismiss) private var dismiss

    private var preferences: ReaderPreferences { store.preferences }

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    themeRow
                    sizeRow
                } header: {
                    Text("Apparence")
                }

                Section("Disposition") {
                    Picker("Affichage", selection: $store.preferences.layout) {
                        ForEach(ReaderPreferences.Layout.allCases, id: \.self) {
                            Text($0.label).tag($0)
                        }
                    }
                    .pickerStyle(.segmented)
                }

                Section("Police") {
                    Picker("Police", selection: $store.preferences.typeface) {
                        ForEach(ReaderPreferences.Typeface.allCases, id: \.self) { face in
                            Text(face.label).tag(face)
                        }
                    }
                    if preferences.typeface.isAccessibility {
                        Text("OpenDyslexic est fournie par Readium, elle n'a pas à être installée.")
                            .font(.footnote)
                            .foregroundStyle(.secondary)
                    }
                }

                Section {
                    Toggle("Respecter la mise en forme de l'éditeur",
                           isOn: $store.preferences.usesPublisherStyles)
                    if !preferences.fineControlsApply {
                        fineControls
                    } else {
                        Text("Tant que la mise en forme de l'éditeur est respectée, l'interligne, l'alignement et les espacements ci-dessous n'ont aucun effet.")
                            .font(.footnote)
                            .foregroundStyle(.secondary)
                    }
                } header: {
                    Text("Mise en forme")
                }

                Section {
                    sliderRow("Marges", value: $store.preferences.pageMargins,
                              range: ReaderPreferences.pageMarginsRange)
                }
            }
            .formStyle(.grouped)
            .navigationTitle("Mise en page")
            #if canImport(UIKit)
            .navigationBarTitleDisplayMode(.inline)
            #endif
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("Terminé") { dismiss() }
                }
            }
        }
    }

    private var themeRow: some View {
        HStack(spacing: 12) {
            ForEach(ReaderPreferences.Theme.allCases, id: \.self) { theme in
                Button {
                    store.preferences.theme = theme
                } label: {
                    VStack(spacing: 4) {
                        Text("Aa")
                            .font(.title3.weight(.medium))
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 14)
                            .background(background(for: theme))
                            .foregroundStyle(foreground(for: theme))
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                            .overlay {
                                RoundedRectangle(cornerRadius: 8)
                                    .strokeBorder(
                                        preferences.theme == theme ? Color.accentColor : .clear,
                                        lineWidth: 2
                                    )
                            }
                        Text(theme.label).font(.caption2)
                    }
                }
                .buttonStyle(.plain)
            }
        }
        .padding(.vertical, 4)
    }

    private func background(for theme: ReaderPreferences.Theme) -> Color {
        switch theme {
        case .light: .white
        case .sepia: Color(red: 0.98, green: 0.94, blue: 0.86)
        case .dark: .black
        }
    }

    private func foreground(for theme: ReaderPreferences.Theme) -> Color {
        theme == .dark ? .white : .black
    }

    private var sizeRow: some View {
        HStack {
            Button { store.preferences.shrink() } label: {
                Image(systemName: "textformat.size.smaller")
            }
            .disabled(!preferences.canShrink)

            Spacer()
            Text("\(preferences.fontSizePercentage) %")
                .font(.body.monospacedDigit())
                .foregroundStyle(.secondary)
            Spacer()

            Button { store.preferences.enlarge() } label: {
                Image(systemName: "textformat.size.larger")
            }
            .disabled(!preferences.canEnlarge)
        }
        .buttonStyle(.bordered)
    }

    @ViewBuilder
    private var fineControls: some View {
        Picker("Alignement", selection: $store.preferences.alignment) {
            ForEach(ReaderPreferences.Alignment.allCases, id: \.self) {
                Text($0.label).tag($0)
            }
        }
        sliderRow("Interligne", value: $store.preferences.lineHeight,
                  range: ReaderPreferences.lineHeightRange)
        sliderRow("Espace entre paragraphes", value: $store.preferences.paragraphSpacing,
                  range: ReaderPreferences.paragraphSpacingRange)
        Toggle("Césures", isOn: $store.preferences.hyphens)
    }

    private func sliderRow(
        _ title: String,
        value: Binding<Double>,
        range: ClosedRange<Double>
    ) -> some View {
        VStack(alignment: .leading, spacing: 2) {
            HStack {
                Text(title)
                Spacer()
                Text(String(format: "%.2g", value.wrappedValue))
                    .font(.footnote.monospacedDigit())
                    .foregroundStyle(.secondary)
            }
            Slider(value: value, in: range)
        }
    }
}
+4 −1
Changes for Packages/Core/Sources/PodbookUI/Stores/ReadingServices.swift: 4 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -11,6 +11,7 @@ public struct ReadingServices {
    public let digests: DigestStore
    public let usage: UsageMeter
    public let settings: AppSettings
    public let readerPreferences: ReaderPreferencesStore

    public init(
        locations: ReadingLocationStore,
@@ -18,7 +19,8 @@ public struct ReadingServices {
        vocabulary: VocabularyStore,
        digests: DigestStore,
        usage: UsageMeter,
        settings: AppSettings
        settings: AppSettings,
        readerPreferences: ReaderPreferencesStore
    ) {
        self.locations = locations
        self.translator = translator
@@ -26,5 +28,6 @@ public struct ReadingServices {
        self.digests = digests
        self.usage = usage
        self.settings = settings
        self.readerPreferences = readerPreferences
    }
}
Loading