Sources/OrgApp/FlashcardReview.swift

4752dd3a1e83428b7d3360dbd60184ea42644ead
orgstar/Sources/OrgApp/FlashcardReview.swift

172 lines · 7576 bytes

  1import Foundation
  2import Observation
  3import OrgCore
  4import OrgIndex
  5
  6/// A review of the flashcards due across the workspace, as `org-fc-review` runs one over
  7/// `org-fc-directories`: each due position shown, flipped and rated, its review data written
  8/// back through the document session (an edit the buffer can undo when the file is open) and
  9/// a line added to the review history. A position rated Again comes back at the end.
 10@MainActor
 11@Observable
 12public final class FlashcardReview {
 13    /// Positions left, the one shown first.
 14    public private(set) var queue: [Flashcards.Item] = []
 15    /// What the first position shows, read from its file's current text.
 16    public private(set) var face: Flashcards.Face?
 17    public var flipped = false
 18    /// A text-input card's typed answer.
 19    public var typed = ""
 20    public private(set) var reviewed = 0
 21    public private(set) var isLoading = false
 22    /// Set once the first load finished.
 23    public private(set) var loaded = false
 24    /// Why the last action didn't happen, for the screen to show.
 25    public var message: String?
 26
 27    private let workspace: WorkspaceModel
 28    private let session: DocumentSession
 29    @ObservationIgnored private var shownAt = Date()
 30    /// Where ratings are logged: `org-fc-review-history-file`.
 31    @ObservationIgnored public var history = OrgPreferences.fcReviewHistoryFile()
 32
 33    public init(workspace: WorkspaceModel, session: DocumentSession) {
 34        self.workspace = workspace
 35        self.session = session
 36    }
 37
 38    public var current: Flashcards.Item? { queue.first }
 39
 40    /// The cards in the workspace's files, open files as their buffers have them. Only files
 41    /// whose index rows have a heading tagged `fc` are read.
 42    public static func cards(workspace: WorkspaceModel, session: DocumentSession) async -> [(path: String, card: Flashcards.Card)] {
 43        let open = session.openDocuments
 44        let overlay = workspace.overlay(open)
 45        let paths = (try? workspace.index.files(withLocalTag: Flashcards.tag, overlay: overlay)) ?? []
 46        let texts = session.openTexts
 47        let defaults = session.defaults
 48        return await read(paths: paths, texts: texts, defaults: defaults)
 49    }
 50
 51    @concurrent
 52    private static func read(paths: [String], texts: [String: String], defaults: OrgSettings) async -> [(path: String, card: Flashcards.Card)] {
 53        paths.flatMap { path -> [(path: String, card: Flashcards.Card)] in
 54            guard path.hasSuffix(".org"), let text = texts[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return [] }
 55            return Flashcards.cards(in: text, defaults: defaults).map { (path, $0) }
 56        }
 57    }
 58
 59    /// Finds the positions due now and shows the first.
 60    public func start(now: Date = Date()) async {
 61        isLoading = true
 62        let cards = await Self.cards(workspace: workspace, session: session)
 63        queue = Flashcards.due(cards, at: now)
 64        reviewed = 0
 65        isLoading = false
 66        loaded = true
 67        show()
 68    }
 69
 70    /// The first position's face, from its file as it is now.
 71    private func show() {
 72        flipped = false
 73        typed = ""
 74        face = nil
 75        while let item = queue.first {
 76            if let card = fresh(item), let face = Flashcards.face(card, position: item.position) {
 77                queue[0].card = card
 78                self.face = face
 79                shownAt = Date()
 80                return
 81            }
 82            queue.removeFirst()
 83        }
 84    }
 85
 86    /// The item's card as its file has it now.
 87    private func fresh(_ item: Flashcards.Item) -> Flashcards.Card? {
 88        guard let text = session.exportText(of: item.path) else { return nil }
 89        return Flashcards.cards(in: text, defaults: session.defaults).first { $0.id == item.card.id }
 90    }
 91
 92    public func flip() {
 93        guard face != nil else { return }
 94        flipped = true
 95    }
 96
 97    /// Rates the shown position, writes its review data and the history line, and shows the next.
 98    public func rate(_ rating: Flashcards.Rating, now: Date = Date()) {
 99        guard let item = current else { return }
100        switch Self.rate(path: item.path, card: item.card.id, position: item.position, rating: rating, seconds: now.timeIntervalSince(shownAt), session: session, history: history, now: now) {
101        case .rated(let problem):
102            message = problem
103        case .gone:
104            message = String(localized: "The card changed; it was skipped.", comment: "Flashcard review")
105            queue.removeFirst()
106            return show()
107        case .failed(let reason):
108            message = reason
109            return
110        }
111        reviewed += 1
112        queue.removeFirst()
113        if rating == .again { queue.append(item) }
114        show()
115    }
116
117    public enum Outcome: Equatable {
118        /// Rated; with why the history line couldn't be added, if it couldn't.
119        case rated(String?)
120        /// The card or its position is no longer in the file.
121        case gone
122        case failed(String)
123    }
124
125    /// Rates a position of the card with ID `card` in `path`, through the session, and adds the
126    /// line to the review history: for the review screen and for the watch.
127    public static func rate(path: String, card id: String, position name: String, rating: Flashcards.Rating, seconds: Double, session: DocumentSession,
128                            history: URL = OrgPreferences.fcReviewHistoryFile(), now: Date = Date()) -> Outcome {
129        guard let text = session.exportText(of: path), let card = Flashcards.cards(in: text, defaults: session.defaults).first(where: { $0.id == id }),
130              let position = card.positions.first(where: { $0.name == name }) else { return .gone }
131        if case .failed(let reason) = session.perform(RateFlashcard(card: id, position: name, rating: rating), path: path, at: 0, expect: nil, now: now) {
132            return .failed(reason)
133        }
134        let line = Flashcards.historyLine(at: now, path: path, id: id, position: position, rating: rating, seconds: seconds)
135        do {
136            try appendHistory(line, to: history)
137            return .rated(nil)
138        } catch {
139            return .rated(String(localized: "Can't add to the review history: \(error.localizedDescription)", comment: "Flashcard review"))
140        }
141    }
142
143    /// Tags the shown card `suspended` and leaves its positions out of the rest of the review.
144    public func suspend() {
145        guard let item = current, let card = fresh(item) else { return }
146        let step = session.perform(SuspendFlashcard(), path: item.path, at: card.headingOffset, expect: (card.headingOffset, card.headingLine))
147        if case .failed(let reason) = step {
148            message = reason
149            return
150        }
151        queue.removeAll { $0.path == item.path && $0.card.id == item.card.id }
152        show()
153    }
154
155    static func appendHistory(_ line: String, to file: URL) throws {
156        let manager = FileManager.default
157        if !manager.fileExists(atPath: file.path) {
158            try manager.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
159            try Data(line.utf8).write(to: file)
160            return
161        }
162        let handle = try FileHandle(forWritingTo: file)
163        defer { try? handle.close() }
164        try handle.seekToEnd()
165        try handle.write(contentsOf: Data(line.utf8))
166    }
167
168    /// Whether the typed answer is the expected one.
169    public var typedIsRight: Bool {
170        face?.expected.map { $0 == typed } ?? false
171    }
172}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form