Sources/OrgApp/FlashcardReviewView.swift
161 lines · 7118 bytes
9 symbols in this file
1import OrgCore
2import SwiftUI
3
4/// The review screen, on the Mac and on iPhone and iPad: a card's front, Show Answer, then
5/// the back with org-fc's four ratings as large buttons. On the Mac, Space or Return flips
6/// and A, H, G and E rate, as in org-fc.
7public struct FlashcardReviewView: View {
8 @Bindable var review: FlashcardReview
9 /// Opens the shown card's heading in the editor.
10 let open: (String, Int) -> Void
11
12 public init(review: FlashcardReview, open: @escaping (String, Int) -> Void) {
13 self.review = review
14 self.open = open
15 }
16
17 public var body: some View {
18 VStack(spacing: 0) {
19 if review.isLoading && !review.loaded {
20 ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)
21 } else if let face = review.face, let item = review.current {
22 card(face, item)
23 Divider()
24 controls(face)
25 .padding(16)
26 } else {
27 ContentUnavailableView {
28 Label(review.reviewed > 0 ? "Review Done" : "No Cards Due", systemImage: "rectangle.on.rectangle.angled")
29 } description: {
30 Text(review.reviewed > 0
31 ? "\(review.reviewed) reviewed. Nothing else is due."
32 : "Flashcards are headings tagged fc, in org-fc's format. Make one with Make Normal Flashcard or another Make Flashcard command.")
33 } actions: {
34 Button("Check Again") { Task { await review.start() } }
35 }
36 }
37 }
38 .alert("Flashcards", isPresented: Binding(get: { review.message != nil }, set: { if !$0 { review.message = nil } })) {
39 Button("OK") { review.message = nil }
40 } message: {
41 Text(review.message ?? "")
42 }
43 .task { if !review.loaded { await review.start() } }
44 }
45
46 private func card(_ face: Flashcards.Face, _ item: Flashcards.Item) -> some View {
47 let side = review.flipped ? face.back : face.front
48 return ScrollView {
49 VStack(alignment: .leading, spacing: 12) {
50 HStack {
51 Text("\(review.queue.count) left").font(.caption).foregroundStyle(.secondary).monospacedDigit()
52 Spacer()
53 Menu {
54 Button("Open in Editor", systemImage: "square.and.pencil") { open(item.path, item.card.headingOffset) }
55 Button("Suspend Card", systemImage: "pause.circle") { review.suspend() }
56 } label: {
57 Label("Card Actions", systemImage: "ellipsis.circle").labelStyle(.iconOnly)
58 }
59 .fixedSize()
60 }
61 Text(Self.styled(side, title: true)).font(.title2.weight(.semibold))
62 if !side.text.isEmpty {
63 Text(Self.styled(side, title: false)).font(.body)
64 }
65 if let expected = face.expected, review.flipped {
66 answerCheck(expected)
67 }
68 }
69 .textSelection(.enabled)
70 .frame(maxWidth: 700, alignment: .leading)
71 .frame(maxWidth: .infinity)
72 .padding(20)
73 }
74 }
75
76 private func answerCheck(_ expected: String) -> some View {
77 VStack(alignment: .leading, spacing: 4) {
78 Label(review.typedIsRight ? "Correct" : "Not quite", systemImage: review.typedIsRight ? "checkmark.circle.fill" : "xmark.circle.fill")
79 .foregroundStyle(review.typedIsRight ? Color.green : Color.red)
80 Text("Your answer: \(review.typed)")
81 if !review.typedIsRight { Text("Expected: \(expected)") }
82 }
83 .padding(12)
84 .background(.quaternary, in: RoundedRectangle(cornerRadius: 8))
85 }
86
87 @ViewBuilder
88 private func controls(_ face: Flashcards.Face) -> some View {
89 if review.flipped {
90 HStack(spacing: 10) {
91 rating(.again, "Again", .red, key: "a")
92 rating(.hard, "Hard", .orange, key: "h")
93 rating(.good, "Good", .green, key: "g")
94 rating(.easy, "Easy", .blue, key: "e")
95 }
96 } else if face.expected != nil {
97 HStack(spacing: 10) {
98 TextField("Your Answer", text: $review.typed)
99 .textFieldStyle(.roundedBorder)
100 .autocorrectionDisabled()
101 #if os(iOS)
102 .textInputAutocapitalization(.never)
103 #endif
104 .onSubmit { review.flip() }
105 big(Button("Check") { review.flip() }, tint: .accentColor)
106 .frame(maxWidth: 160)
107 }
108 } else {
109 big(Button("Show Answer") { review.flip() }, tint: .accentColor)
110 .keyboardShortcut(.defaultAction)
111 }
112 }
113
114 private func rating(_ rating: Flashcards.Rating, _ title: LocalizedStringKey, _ tint: Color, key: KeyEquivalent) -> some View {
115 big(Button(title) { review.rate(rating) }, tint: tint)
116 .keyboardShortcut(key, modifiers: [])
117 }
118
119 private func big(_ button: Button<Text>, tint: Color) -> some View {
120 button
121 .font(.headline)
122 .buttonStyle(BigButtonStyle(tint: tint))
123 }
124
125 #if os(iOS)
126 static let buttonHeight: CGFloat = 64
127 #else
128 static let buttonHeight: CGFloat = 40
129 #endif
130
131 private struct BigButtonStyle: ButtonStyle {
132 let tint: Color
133 func makeBody(configuration: Configuration) -> some View {
134 configuration.label
135 .foregroundStyle(.white)
136 .frame(maxWidth: .infinity, minHeight: FlashcardReviewView.buttonHeight)
137 .background(tint.opacity(configuration.isPressed ? 0.7 : 1), in: RoundedRectangle(cornerRadius: 12))
138 .contentShape(RoundedRectangle(cornerRadius: 12))
139 }
140 }
141
142 /// The side's title (a placeholder while hidden) or text, with its marks in bold.
143 static func styled(_ side: Flashcards.Face.Side, title: Bool) -> AttributedString {
144 let titleText = side.title ?? "[…]"
145 let whole = (side.title ?? "") + "\n" + side.text
146 let part = title ? titleText : side.text
147 var string = AttributedString(part)
148 if title && side.title == nil { string.foregroundColor = .secondary }
149 let offset = title ? 0 : ((side.title ?? "") as NSString).length + 1
150 let ns = whole as NSString
151 for mark in side.marks {
152 let lower = mark.lowerBound - offset
153 guard lower >= 0, mark.upperBound - offset <= (part as NSString).length, mark.upperBound <= ns.length,
154 let range = Range(NSRange(location: lower, length: mark.count), in: part),
155 let attributed = Range(range, in: string) else { continue }
156 string[attributed].inlinePresentationIntent = .stronglyEmphasized
157 string[attributed].foregroundColor = .accentColor
158 }
159 return string
160 }
161}