Commit c5901cef authored by Kourser's avatar Kourser
Browse files

feat: surlignages, marque-pages et notes

« Surligner » rejoint « Traduire » dans le menu de sélection, en cinq
couleurs, avec une note libre par surlignage. Le ruban en haut bascule
le marque-page de la page courante — reposer le ruban sur la même page
le retire, parce que c'est ce que le geste veut dire.

Les deux sont le même enregistrement avec un genre différent : une
position et un peu de métadonnée. Les séparer aurait donné deux
magasins, deux écrans et deux chemins de synchronisation pour rien.

La liste est rangée dans l'ordre du livre et non du plus récent :
quelqu'un qui l'ouvre cherche un passage, pas ce qu'il a fait hier soir.
À position égale, la date de création tranche. Export en Markdown, parce
que c'est là qu'une note de lecture finit.

Un surlignage sans texte est refusé : il serait invisible dans le livre
et introuvable dans la liste.

Le stockage est local, délibérément. Calibre a une API d'annotations,
mais ses enregistrements sont indexés par CFI EPUB, que son propre
lecteur produit et qu'un locator Readium n'est pas. Prétendre
synchroniser demanderait d'inventer un dialecte de CFI — même conclusion
que pour les positions de lecture.

Readium reçoit l'ensemble courant des décorations à chaque changement
plutôt qu'un diff : il est documenté pour fonctionner ainsi et décide
lui-même de ce qu'il redessine.

220 tests au vert.

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

### Ajouté
- Surlignages en cinq couleurs depuis le menu de sélection, note libre par
  surlignage, et marque-page bascule sur la page courante.
- Liste des annotations rangée dans l'ordre du livre, filtrable, avec export
  Markdown. Stockage local : les annotations de Calibre sont indexées par CFI,
  que Readium ne produit pas.
- Mode voiture : écran à trois cibles plein écran, file qui s'enchaîne seule,
  et récapitulatif de ce qui est disponible hors-ligne avant de partir.
- Un autoradio reconnu comme tel lance le mode voiture seul ; un Bluetooth
+160 −0
Changes for Packages/Core/Sources/PodbookUI/Annotations/AnnotationStore.swift: 160 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import Observation

/// Highlights and bookmarks, on disk.
///
/// Append-only, one JSON object per line, like the vocabulary notebook: it
/// survives a crash mid-write, and it stays readable with `tail`. Ordered by
/// position in the book rather than by when it was made — that is how someone
/// looks for a passage again.
///
/// Local only, deliberately. Calibre has an annotations API, but its records
/// are keyed by EPUB CFI, which its own viewer produces and a Readium locator
/// is not. Pretending to sync would mean inventing a CFI dialect; see the same
/// decision for reading positions in docs/API-CALIBRE.md.
@MainActor
@Observable
public final class AnnotationStore {
    public private(set) var annotations: [BookAnnotation] = []
    public private(set) var bookID: Int?

    private let root: URL

    public init(root: URL? = nil) {
        if let root {
            self.root = root
        } else {
            let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
                ?? FileManager.default.temporaryDirectory
            self.root = base.appendingPathComponent("Podbook/Annotations", isDirectory: true)
        }
        try? FileManager.default.createDirectory(at: self.root, withIntermediateDirectories: true)
    }

    // MARK: - Reading

    public func load(bookID: Int) {
        self.bookID = bookID
        guard let text = try? String(contentsOf: file(bookID), encoding: .utf8) else {
            annotations = []
            return
        }
        let decoder = JSONDecoder()
        annotations = text
            .split(separator: "\n", omittingEmptySubsequences: true)
            .compactMap { line in
                guard let data = line.data(using: .utf8) else { return nil }
                return try? decoder.decode(BookAnnotation.self, from: data)
            }
            .sorted(by: Self.inReadingOrder)
    }

    /// Position first, then creation time for two marks on the same paragraph.
    static func inReadingOrder(_ lhs: BookAnnotation, _ rhs: BookAnnotation) -> Bool {
        switch (lhs.progression, rhs.progression) {
        case let (left?, right?) where left != right: left < right
        default: lhs.createdAt < rhs.createdAt
        }
    }

    public var highlights: [BookAnnotation] { annotations.filter { $0.kind == .highlight } }
    public var bookmarks: [BookAnnotation] { annotations.filter { $0.kind == .bookmark } }

    public func bookmark(at locator: String) -> BookAnnotation? {
        annotations.first { $0.kind == .bookmark && $0.locator == locator }
    }

    public func isBookmarked(_ locator: String) -> Bool {
        bookmark(at: locator) != nil
    }

    // MARK: - Writing

    @discardableResult
    public func add(_ annotation: BookAnnotation) -> BookAnnotation? {
        // A highlight with nothing selected would be invisible and
        // undeletable from the list.
        if annotation.kind == .highlight,
           annotation.text?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty != false {
            return nil
        }
        annotations.append(annotation)
        annotations.sort(by: Self.inReadingOrder)
        persist()
        return annotation
    }

    /// Bookmarks toggle: pressing the ribbon again on the same page removes it,
    /// which is what the gesture means.
    @discardableResult
    public func toggleBookmark(
        bookID: Int,
        locator: String,
        chapter: String? = nil,
        progression: Double? = nil
    ) -> Bool {
        if let existing = bookmark(at: locator) {
            remove(existing)
            return false
        }
        add(BookAnnotation(
            bookID: bookID,
            kind: .bookmark,
            locator: locator,
            chapter: chapter,
            progression: progression
        ))
        return true
    }

    public func remove(_ annotation: BookAnnotation) {
        annotations.removeAll { $0.id == annotation.id }
        persist()
    }

    public func update(_ annotation: BookAnnotation, note: String?) {
        guard let index = annotations.firstIndex(where: { $0.id == annotation.id }) else { return }
        let trimmed = note?.trimmingCharacters(in: .whitespacesAndNewlines)
        annotations[index].note = (trimmed?.isEmpty ?? true) ? nil : trimmed
        persist()
    }

    public func update(_ annotation: BookAnnotation, tint: BookAnnotation.Tint) {
        guard let index = annotations.firstIndex(where: { $0.id == annotation.id }) else { return }
        annotations[index].tint = tint
        persist()
    }

    /// One line per annotation, rewritten whole. A reading session makes a
    /// handful of marks, not thousands, so simplicity wins over appending.
    private func persist() {
        guard let bookID else { return }
        let encoder = JSONEncoder()
        let text = annotations
            .filter { $0.bookID == bookID }
            .compactMap { try? encoder.encode($0) }
            .compactMap { String(data: $0, encoding: .utf8) }
            .joined(separator: "\n")
        try? (text + "\n").write(to: file(bookID), atomically: true, encoding: .utf8)
    }

    private func file(_ bookID: Int) -> URL {
        root.appendingPathComponent("\(bookID).jsonl")
    }

    /// Markdown, because that is what a reading note is pasted into.
    public func markdownExport(bookTitle: String) -> String {
        var lines = ["# \(bookTitle)", ""]
        for annotation in annotations {
            switch annotation.kind {
            case .highlight:
                if let text = annotation.text { lines.append("> \(text)") }
                if let note = annotation.note { lines.append(contentsOf: ["", note]) }
            case .bookmark:
                lines.append("— Marque-page : \(annotation.chapter ?? "sans titre")")
            }
            lines.append("")
        }
        return lines.joined(separator: "\n")
    }
}
+194 −0
Changes for Packages/Core/Sources/PodbookUI/Annotations/AnnotationsView.swift: 194 added lines, 0 removed lines.
Original line number Diff line number Diff line
import SwiftUI

#if canImport(UIKit)
import UIKit

extension BookAnnotation.Tint {
    /// Readium draws its highlights with a `UIColor`.
    var uiColor: UIColor { UIColor(color) }
}
#endif

extension BookAnnotation.Tint {
    var color: Color {
        switch self {
        case .yellow: Color(red: 1.0, green: 0.85, blue: 0.30)
        case .green: Color(red: 0.55, green: 0.85, blue: 0.50)
        case .blue: Color(red: 0.45, green: 0.72, blue: 0.98)
        case .pink: Color(red: 1.0, green: 0.62, blue: 0.72)
        case .purple: Color(red: 0.74, green: 0.60, blue: 0.95)
        }
    }
}

/// Highlights and bookmarks, in reading order.
///
/// Reading order rather than most-recent-first: someone opening this list is
/// looking for a passage in the book, not reviewing what they did last night.
struct AnnotationsView: View {
    let store: AnnotationStore
    let bookTitle: String
    let onSelect: (BookAnnotation) -> Void

    @Environment(\.dismiss) private var dismiss
    @State private var filter: Filter = .all
    @State private var editingNote: BookAnnotation?
    @State private var noteDraft = ""

    enum Filter: String, CaseIterable {
        case all, highlights, bookmarks

        var label: String {
            switch self {
            case .all: "Tout"
            case .highlights: "Surlignages"
            case .bookmarks: "Marque-pages"
            }
        }
    }

    private var shown: [BookAnnotation] {
        switch filter {
        case .all: store.annotations
        case .highlights: store.highlights
        case .bookmarks: store.bookmarks
        }
    }

    var body: some View {
        NavigationStack {
            List {
                ForEach(shown) { annotation in
                    row(annotation)
                }
            }
            .overlay {
                if shown.isEmpty { emptyState }
            }
            .safeAreaInset(edge: .top) {
                Picker("Filtre", selection: $filter) {
                    ForEach(Filter.allCases, id: \.self) { Text($0.label).tag($0) }
                }
                .pickerStyle(.segmented)
                .padding(.horizontal)
                .padding(.bottom, 6)
                .background(.bar)
            }
            .navigationTitle("Annotations")
            #if canImport(UIKit)
            .navigationBarTitleDisplayMode(.inline)
            #endif
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Fermer") { dismiss() }
                }
                if !store.annotations.isEmpty {
                    ToolbarItem {
                        ShareLink(
                            item: store.markdownExport(bookTitle: bookTitle),
                            preview: SharePreview("Annotations — \(bookTitle)")
                        ) {
                            Label("Exporter", systemImage: "square.and.arrow.up")
                        }
                    }
                }
            }
            .sheet(item: $editingNote) { annotation in
                noteEditor(for: annotation)
            }
        }
    }

    private func row(_ annotation: BookAnnotation) -> some View {
        Button {
            onSelect(annotation)
            dismiss()
        } label: {
            HStack(alignment: .top, spacing: 10) {
                Rectangle()
                    .fill(annotation.kind == .highlight ? annotation.tint.color : Color.accentColor)
                    .frame(width: 4)
                    .clipShape(Capsule())

                VStack(alignment: .leading, spacing: 4) {
                    if let text = annotation.text {
                        Text(text).font(.callout).lineLimit(4)
                    } else {
                        Label(annotation.chapter ?? "Marque-page",
                              systemImage: annotation.kind.systemImage)
                            .font(.callout)
                    }
                    if let note = annotation.note {
                        Text(note)
                            .font(.footnote)
                            .foregroundStyle(.secondary)
                            .italic()
                    }
                    if let chapter = annotation.chapter, annotation.text != nil {
                        Text(chapter).font(.caption2).foregroundStyle(.tertiary)
                    }
                }
            }
        }
        .buttonStyle(.plain)
        .swipeActions(edge: .trailing) {
            Button("Supprimer", role: .destructive) { store.remove(annotation) }
        }
        .swipeActions(edge: .leading) {
            Button("Note") {
                noteDraft = annotation.note ?? ""
                editingNote = annotation
            }
            .tint(.indigo)
        }
        .contextMenu {
            if annotation.kind == .highlight {
                ForEach(BookAnnotation.Tint.allCases, id: \.self) { tint in
                    Button {
                        store.update(annotation, tint: tint)
                    } label: {
                        Label(tint.label, systemImage: annotation.tint == tint
                              ? "checkmark.circle.fill" : "circle.fill")
                    }
                }
            }
        }
    }

    private var emptyState: some View {
        ContentUnavailableView {
            Label("Rien d'annoté", systemImage: "highlighter")
        } description: {
            Text("Sélectionne un passage en lisant pour le surligner, ou pose un marque-page avec le ruban.")
        }
    }

    private func noteEditor(for annotation: BookAnnotation) -> some View {
        NavigationStack {
            Form {
                if let text = annotation.text {
                    Section("Passage") {
                        Text(text).font(.callout).foregroundStyle(.secondary)
                    }
                }
                Section("Note") {
                    TextField("Ce que tu en retiens", text: $noteDraft, axis: .vertical)
                        .lineLimit(3...10)
                }
            }
            .formStyle(.grouped)
            .navigationTitle("Note")
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Annuler") { editingNote = nil }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button("Enregistrer") {
                        store.update(annotation, note: noteDraft)
                        editingNote = nil
                    }
                }
            }
        }
    }
}
+84 −0
Changes for Packages/Core/Sources/PodbookUI/Annotations/BookAnnotation.swift: 84 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation

/// Something the reader marked in a book.
///
/// Highlights and bookmarks are the same record with a different kind: both are
/// a position plus a little metadata, both appear in the same list, and keeping
/// them apart would mean two stores, two sheets and two sync paths for no gain.
public struct BookAnnotation: Codable, Sendable, Hashable, Identifiable {
    public enum Kind: String, Codable, CaseIterable, Sendable {
        case highlight
        case bookmark

        public var label: String {
            switch self {
            case .highlight: "Surlignage"
            case .bookmark: "Marque-page"
            }
        }

        public var systemImage: String {
            switch self {
            case .highlight: "highlighter"
            case .bookmark: "bookmark.fill"
            }
        }
    }

    public enum Tint: String, Codable, CaseIterable, Sendable {
        case yellow, green, blue, pink, purple

        public var label: String {
            switch self {
            case .yellow: "Jaune"
            case .green: "Vert"
            case .blue: "Bleu"
            case .pink: "Rose"
            case .purple: "Violet"
            }
        }
    }

    public var id: UUID
    public var bookID: Int
    public var kind: Kind
    public var tint: Tint
    /// Opaque reading position, the same shape ``ReadingLocation`` stores.
    public var locator: String
    /// The selected passage, for a highlight. A bookmark has none.
    public var text: String?
    public var note: String?
    public var chapter: String?
    /// 0…1 through the book, which is how the list is ordered.
    public var progression: Double?
    public var createdAt: Date

    public init(
        id: UUID = UUID(),
        bookID: Int,
        kind: Kind,
        tint: Tint = .yellow,
        locator: String,
        text: String? = nil,
        note: String? = nil,
        chapter: String? = nil,
        progression: Double? = nil,
        createdAt: Date = .now
    ) {
        self.id = id
        self.bookID = bookID
        self.kind = kind
        self.tint = tint
        self.locator = locator
        self.text = text
        self.note = note
        self.chapter = chapter
        self.progression = progression
        self.createdAt = createdAt
    }

    public var hasNote: Bool {
        guard let note else { return false }
        return !note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }
}
+126 −5

File changed.

Preview size limit exceeded, changes collapsed.

Loading