Jotley / app / Shared / Views / StructuredSummaryView.swift
| 1 | // |
| 2 | // StructuredSummaryView.swift |
| 3 | // Jotley |
| 4 | // |
| 5 | // Renders a Markdown summary as an overview card and visual sections on |
| 6 | // iPhone, iPad and Mac. The stored summary stays plain Markdown. |
| 7 | // |
| 8 | |
| 9 | import SwiftUI |
| 10 | |
| 11 | enum MarkdownTaskState: Equatable { |
| 12 | case unchecked, checked |
| 13 | |
| 14 | var systemImage: String { self == .checked ? "checkmark.square.fill" : "square" } |
| 15 | var accessibilityLabel: String { self == .checked ? "Completed task" : "Incomplete task" } |
| 16 | } |
| 17 | |
| 18 | private struct SummaryListMarker: View { |
| 19 | let marker: String |
| 20 | let taskState: MarkdownTaskState? |
| 21 | |
| 22 | var body: some View { |
| 23 | Group { |
| 24 | if let taskState { Image(systemName: taskState.systemImage) } |
| 25 | else { Text(marker) } |
| 26 | }.accessibilityHidden(true) |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | /// Cache syntax only: appearance and fonts stay reactive in the SwiftUI view. |
| 31 | /// Template changes must not parse the whole unchanged summary on the main thread. |
| 32 | @MainActor |
| 33 | final class ParsedNoteMarkdown: NSObject { |
| 34 | struct Line: Identifiable { |
| 35 | let id: Int |
| 36 | let heading: Bool |
| 37 | let marker: String? |
| 38 | let taskState: MarkdownTaskState? |
| 39 | let indentation: Int |
| 40 | let text: AttributedString |
| 41 | } |
| 42 | let lines: [Line] |
| 43 | private static let cache: NSCache<NSString, ParsedNoteMarkdown> = { |
| 44 | let cache = NSCache<NSString, ParsedNoteMarkdown>() |
| 45 | cache.countLimit = 16 |
| 46 | cache.totalCostLimit = 8 * 1024 * 1024 |
| 47 | return cache |
| 48 | }() |
| 49 | private static let listPattern = try! NSRegularExpression(pattern: #"^([ \t]*)([-+*]|[0-9]{1,9}[.)])[ \t]+(.*)$"#) |
| 50 | private static let taskPattern = try! NSRegularExpression(pattern: #"^\[([ xX])\](?:[ \t]+(.*)|$)"#) |
| 51 | private init(content: String, isStreaming: Bool) { |
| 52 | var sourceLines = LocalSummary.markdownForDisplay(content).components(separatedBy: "\n") |
| 53 | // The model streams prefixes, not complete Markdown nodes. Don't turn a |
| 54 | // trailing "-", "## Act" or "**Owner" into a temporary paragraph/card. |
| 55 | // Ordinary prose and list bodies still update as each snapshot arrives. |
| 56 | if isStreaming, let tail = sourceLines.last, Self.awaitingStructure(tail) { |
| 57 | sourceLines[sourceLines.count - 1] = "" |
| 58 | } |
| 59 | lines = sourceLines.enumerated().map { index, line in |
| 60 | let heading = line.hasPrefix("#") |
| 61 | var text = heading ? String(line.drop(while: { $0 == "#" || $0 == " " })) : line |
| 62 | var marker: String? |
| 63 | var taskState: MarkdownTaskState? |
| 64 | var indentation = 0 |
| 65 | if let match = Self.listPattern.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)), |
| 66 | let whitespace = Range(match.range(at: 1), in: line), |
| 67 | let prefix = Range(match.range(at: 2), in: line), |
| 68 | let body = Range(match.range(at: 3), in: line) { |
| 69 | let token = String(line[prefix]) |
| 70 | marker = ["-", "+", "*"].contains(token) ? "•" : String(token.dropLast()) + "." |
| 71 | indentation = line[whitespace].reduce(0) { $0 + ($1 == "\t" ? 4 : 1) } |
| 72 | text = String(line[body]) |
| 73 | if let task = Self.taskPattern.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)), |
| 74 | let state = Range(task.range(at: 1), in: text) { |
| 75 | taskState = text[state] == " " ? .unchecked : .checked |
| 76 | text = Range(task.range(at: 2), in: text).map { String(text[$0]) } ?? "" |
| 77 | } |
| 78 | } |
| 79 | return Line(id: index, heading: heading, marker: marker, taskState: taskState, indentation: indentation, |
| 80 | text: (try? AttributedString(markdown: text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(text)) |
| 81 | } |
| 82 | } |
| 83 | static func awaitingStructure(_ line: String) -> Bool { |
| 84 | let text = line.trimmingCharacters(in: .whitespaces) |
| 85 | if let match = listPattern.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)), |
| 86 | let range = Range(match.range(at: 3), in: line) { |
| 87 | let body = line[range].trimmingCharacters(in: .whitespaces).lowercased() |
| 88 | if ["[", "[x", "[ ]", "[x]"].contains(body) { return true } |
| 89 | // Filler such as "No decisions are mentioned" is removed by the |
| 90 | // finished parser. Hold its prefixes too, rather than building a |
| 91 | // card for "No decisions are" and then collapsing it on "mentioned". |
| 92 | if ["none", "nothing", "n/a", "na"].contains(where: { $0.hasPrefix(body) }) |
| 93 | || body == "no" || body.hasPrefix("no ") || body.hasPrefix("none") || body.hasPrefix("nothing") { return true } |
| 94 | } |
| 95 | return text.hasPrefix("#") || text.hasPrefix("**") || text.hasPrefix("__") |
| 96 | || text.hasPrefix("```") || ["-", "+", "*"].contains(text) |
| 97 | || text.range(of: #"^[0-9]{1,9}[.)]?$"#, options: .regularExpression) != nil |
| 98 | } |
| 99 | |
| 100 | static func rendering(_ content: String, isStreaming: Bool = false) -> ParsedNoteMarkdown { |
| 101 | let key = ((isStreaming ? "stream:" : "saved:") + content) as NSString |
| 102 | if let saved = cache.object(forKey: key) { return saved } |
| 103 | let result = ParsedNoteMarkdown(content: content, isStreaming: isStreaming) |
| 104 | // Account for both the source key and the attributed-text/line storage. |
| 105 | cache.setObject(result, forKey: key, cost: content.utf8.count * 8 + result.lines.count * 128) |
| 106 | return result |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | |
| 111 | // MARK: - Structured Summary |
| 112 | |
| 113 | /// Groups a Markdown summary into an overview and titled sections. It reads the |
| 114 | /// same cached lines as `MarkdownContentView`, so the stored summary, editing and |
| 115 | /// exports stay plain Markdown. |
| 116 | struct StructuredSummary { |
| 117 | enum Style { case numbered, checklist, questions, risks, plain } |
| 118 | struct Item: Identifiable { |
| 119 | let id: Int |
| 120 | let marker: String |
| 121 | let taskState: MarkdownTaskState? |
| 122 | let indentation: Int |
| 123 | let label: AttributedString? |
| 124 | let body: AttributedString |
| 125 | let fullText: String |
| 126 | var accessibilityText: String { |
| 127 | taskState.map { "\($0.accessibilityLabel): \(fullText)" } ?? "\(marker) \(fullText)" |
| 128 | } |
| 129 | } |
| 130 | struct Section: Identifiable { |
| 131 | let id: Int |
| 132 | let title: String? |
| 133 | var paragraphs: [ParsedNoteMarkdown.Line] = [] |
| 134 | var items: [Item] = [] |
| 135 | var isEmpty: Bool { paragraphs.isEmpty && items.isEmpty } |
| 136 | var style: Style { StructuredSummary.style(for: title) } |
| 137 | var systemImage: String { StructuredSummary.systemImage(for: title, style: style) } |
| 138 | } |
| 139 | let overview: Section? |
| 140 | let sections: [Section] |
| 141 | |
| 142 | private static let overviewTitles: Set<String> = ["summary", "overview", "tl;dr", "tldr", "in short", "at a glance", "executive summary", |
| 143 | "résumé", "resume", "resumen", "resumo", "riassunto", "zusammenfassung", "samenvatting", "概要", "要約", "摘要", "요약"] |
| 144 | |
| 145 | init(_ parsed: ParsedNoteMarkdown) { |
| 146 | var sections: [Section] = [] |
| 147 | var current = Section(id: -1, title: nil) |
| 148 | for line in parsed.lines { |
| 149 | let plain = String(line.text.characters).trimmingCharacters(in: .whitespaces) |
| 150 | if line.heading || Self.isBoldHeading(line, plain: plain) { |
| 151 | if !current.isEmpty || current.title != nil { sections.append(current) } |
| 152 | current = Section(id: line.id, title: Self.headingTitle(plain)) |
| 153 | } else if let marker = line.marker { |
| 154 | // A bare "-" or a "No formulas provided." filler has nothing to show. |
| 155 | guard !plain.isEmpty, !Self.isPlaceholder(plain) else { continue } |
| 156 | let (label, splitBody) = Self.split(line.text) |
| 157 | let body = label == nil ? Self.sentenceCased(splitBody) : splitBody |
| 158 | current.items.append(Item(id: line.id, marker: marker, taskState: line.taskState, indentation: line.indentation, |
| 159 | label: label, body: body, fullText: plain)) |
| 160 | } else if !plain.isEmpty { |
| 161 | current.paragraphs.append(line) |
| 162 | } |
| 163 | } |
| 164 | if !current.isEmpty || current.title != nil { sections.append(current) } |
| 165 | sections.removeAll { $0.isEmpty } |
| 166 | // The opening section is the overview when it is untitled, uses a known |
| 167 | // overview title, or is a short prose lead-in before other sections. |
| 168 | if let first = sections.first, first.title == nil || Self.overviewTitles.contains(first.title!.lowercased()) |
| 169 | || (first.items.isEmpty && sections.count > 1) { |
| 170 | overview = first; self.sections = Array(sections.dropFirst()) |
| 171 | } else { |
| 172 | overview = nil; self.sections = sections |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// Earlier summaries mark sections with a standalone bold line such as |
| 177 | /// "**Key Points:**" rather than a Markdown heading. |
| 178 | static func isBoldHeading(_ line: ParsedNoteMarkdown.Line, plain: String) -> Bool { |
| 179 | guard line.marker == nil, !plain.isEmpty, plain.count <= 60 else { return false } |
| 180 | return line.text.runs.allSatisfy { run in |
| 181 | run.inlinePresentationIntent?.contains(.stronglyEmphasized) == true |
| 182 | || String(line.text[run.range].characters).allSatisfy { $0.isWhitespace || $0 == ":" || $0 == ":" } |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | private static let placeholderPattern = try! NSRegularExpression( |
| 187 | pattern: #"^(none|n/?a|nothing|no\b.{0,40}\b(provided|mentioned|discussed|given|stated|identified|noted|specified))\.?$"#, |
| 188 | options: [.caseInsensitive]) |
| 189 | |
| 190 | static func isPlaceholder(_ plain: String) -> Bool { |
| 191 | let text = plain.trimmingCharacters(in: .whitespaces) |
| 192 | return placeholderPattern.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) != nil |
| 193 | } |
| 194 | |
| 195 | static func headingTitle(_ plain: String) -> String { |
| 196 | var title = plain |
| 197 | while title.last == ":" || title.last == ":" { title.removeLast() } |
| 198 | return title.trimmingCharacters(in: .whitespaces) |
| 199 | } |
| 200 | |
| 201 | /// "**Owner**: task" or "Topic: detail" becomes a short label and a body. |
| 202 | /// Long prefixes are ordinary sentences, so they stay intact. |
| 203 | static func split(_ text: AttributedString) -> (AttributedString?, AttributedString) { |
| 204 | guard let colon = text.characters.firstIndex(where: { $0 == ":" || $0 == ":" }) else { return (nil, text) } |
| 205 | let prefix = String(text.characters[..<colon]).trimmingCharacters(in: .whitespaces) |
| 206 | let afterColon = text.characters.index(after: colon) |
| 207 | let rest = String(text.characters[afterColon...]).trimmingCharacters(in: .whitespaces) |
| 208 | // Times ("10:30") and bare URLs ("https://") are not labels. |
| 209 | let isTime = prefix.last?.isNumber == true && rest.first?.isNumber == true |
| 210 | guard !prefix.isEmpty, prefix.count <= 40, prefix.split(separator: " ").count <= 5, !isTime, |
| 211 | !prefix.allSatisfy(\.isNumber), !rest.isEmpty, !rest.hasPrefix("//") else { return (nil, text) } |
| 212 | var body = AttributedString(text[afterColon...]) |
| 213 | while body.characters.first?.isWhitespace == true { body.removeSubrange(body.startIndex..<body.characters.index(after: body.startIndex)) } |
| 214 | return (AttributedString(prefix), sentenceCased(body)) |
| 215 | } |
| 216 | |
| 217 | /// "sends the list" or "renew the registration" reads as a sentence once it |
| 218 | /// stands alone; words such as "iPad" keep their own capitalization. |
| 219 | static func sentenceCased(_ text: AttributedString) -> AttributedString { |
| 220 | let firstWord = String(text.characters.prefix { !$0.isWhitespace }) |
| 221 | guard let first = text.characters.first, first.isLowercase, |
| 222 | firstWord.allSatisfy({ !$0.isUppercase }) else { return text } |
| 223 | var result = text |
| 224 | let end = result.characters.index(after: result.startIndex) |
| 225 | let attributes = result[result.startIndex..<end].runs.first?.attributes ?? AttributeContainer() |
| 226 | result.replaceSubrange(result.startIndex..<end, with: AttributedString(String(first).uppercased(), attributes: attributes)) |
| 227 | return result |
| 228 | } |
| 229 | |
| 230 | static func style(for title: String?) -> Style { |
| 231 | let title = (title ?? "").lowercased() |
| 232 | func has(_ words: [String]) -> Bool { words.contains { title.contains($0) } } |
| 233 | if has(["action", "next step", "to-do", "todo", "task", "follow-up", "follow up", "owner", "assignment", "remind", |
| 234 | "handlingspunkt", "actiepunt", "à mener", "à faire", "aufgabe", "azion", "da fare", "oppgave", "ação", "ações", |
| 235 | "tarea", "att göra", "uppgift", "yapılacak", "görev", "việc cần làm", "待办", "待辦", "アクション", "やること", |
| 236 | "실행 항목", "할 일"]) { return .checklist } |
| 237 | if has(["question", "unresolved", "open item", "unknown"]) { return .questions } |
| 238 | if has(["risk", "blocker", "concern", "issue", "challenge"]) { return .risks } |
| 239 | if title.isEmpty { return .plain } |
| 240 | return .numbered |
| 241 | } |
| 242 | |
| 243 | static func systemImage(for title: String?, style: Style) -> String { |
| 244 | let title = (title ?? "").lowercased() |
| 245 | func has(_ words: [String]) -> Bool { words.contains { title.contains($0) } } |
| 246 | switch style { |
| 247 | case .checklist: return "checklist" |
| 248 | case .questions: return "questionmark.bubble" |
| 249 | case .risks: return "exclamationmark.triangle" |
| 250 | case .plain: return "text.alignleft" |
| 251 | case .numbered: |
| 252 | if has(["decision", "agreed", "outcome"]) { return "checkmark.seal" } |
| 253 | if has(["date", "deadline", "schedule", "timeline", "milestone", "check-in", "meeting"]) { return "calendar" } |
| 254 | if has(["idea", "brainstorm", "theme"]) { return "lightbulb" } |
| 255 | if has(["people", "participant", "attendee", "who"]) { return "person.2" } |
| 256 | if has(["metric", "number", "fact", "data", "progress"]) { return "chart.bar" } |
| 257 | if has(["concept", "definition", "lecture", "learn", "study", "review"]) { return "book" } |
| 258 | if has(["feedback", "quote"]) { return "quote.bubble" } |
| 259 | return "list.number" |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// Colors for one rendering. The app follows the current theme; a shared PDF |
| 265 | /// always prints on white. |
| 266 | struct SummaryPalette { |
| 267 | var headingIcon: Color |
| 268 | var badge: Color |
| 269 | var marker: Color |
| 270 | var text: Color |
| 271 | var secondary: Color |
| 272 | var card: Color |
| 273 | |
| 274 | static var current: SummaryPalette { |
| 275 | let marker = Color(white: Color.shouldUseDarkTheme() ? 0.72 : 0.36) |
| 276 | let accent = Color.themePrimaryAccent |
| 277 | let badge = accent.mix(with: marker, by: 0.28) |
| 278 | return SummaryPalette(headingIcon: accent, badge: badge, marker: marker, text: .themeTextPrimary, |
| 279 | secondary: Color.themeTextPrimary.opacity(0.78), card: .themeContentBackground) |
| 280 | } |
| 281 | static var print: SummaryPalette { |
| 282 | let accent = ThemeManager.shared.currentThemeColor.color(in: .light) |
| 283 | return SummaryPalette(headingIcon: accent, badge: accent, marker: Color(white: 0.36), text: .themeLightTextPrimary, |
| 284 | secondary: Color.themeLightTextPrimary.opacity(0.78), card: .themeLightContentBackground) |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | extension StructuredSummary { |
| 289 | enum Block: Identifiable { |
| 290 | case overview(Section), section(Section) |
| 291 | var id: Int { switch self { case .overview(let section), .section(let section): return section.id } } |
| 292 | } |
| 293 | var blocks: [Block] { (overview.map { [.overview($0)] } ?? []) + sections.map { .section($0) } } |
| 294 | } |
| 295 | |
| 296 | /// One device-wide preference shared by every note and the Settings screen. |
| 297 | enum SummaryDisplayStyle: String, CaseIterable, Identifiable { |
| 298 | case cards, standard |
| 299 | static let preferenceKey = "jotley.summaryDisplayStyle" |
| 300 | var id: String { rawValue } |
| 301 | var title: String { self == .cards ? "Cards" : "Standard Text" } |
| 302 | } |
| 303 | |
| 304 | struct SummaryDisplayStylePicker: View { |
| 305 | @AppStorage(SummaryDisplayStyle.preferenceKey) private var style: SummaryDisplayStyle = .cards |
| 306 | |
| 307 | var body: some View { |
| 308 | Picker("Summary Style", selection: $style) { |
| 309 | ForEach(SummaryDisplayStyle.allCases) { style in |
| 310 | Text(style.title).tag(style) |
| 311 | .accessibilityIdentifier("summaryDisplayStyle-\(style.rawValue)") |
| 312 | } |
| 313 | } |
| 314 | .accessibilityIdentifier("summaryDisplayStylePicker") |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | /// Readable Markdown with neutral text, headings and bullets, without cards. |
| 319 | /// This changes presentation only; editing, AI and exports keep the same source. |
| 320 | struct StandardSummaryTextView: View { |
| 321 | let markdown: ParsedNoteMarkdown |
| 322 | var bodyFont: Font = .body |
| 323 | |
| 324 | var body: some View { |
| 325 | VStack(alignment: .leading, spacing: 8) { |
| 326 | ForEach(markdown.lines) { line in |
| 327 | if !line.text.characters.isEmpty { |
| 328 | HStack(alignment: .firstTextBaseline, spacing: 8) { |
| 329 | if let marker = line.marker { |
| 330 | SummaryListMarker(marker: marker, taskState: line.taskState) |
| 331 | } |
| 332 | Text(line.text) |
| 333 | .font(line.heading ? .title3.weight(.semibold) : bodyFont) |
| 334 | .accessibilityAddTraits(line.heading ? .isHeader : []) |
| 335 | .textSelection(.enabled) |
| 336 | .frame(maxWidth: .infinity, alignment: .leading) |
| 337 | } |
| 338 | .font(bodyFont) |
| 339 | .foregroundStyle(Color.themeTextPrimary) |
| 340 | .lineSpacing(4) |
| 341 | .padding(.leading, CGFloat(line.indentation) * 8) |
| 342 | .padding(.top, line.heading && line.id > 0 ? 12 : 0) |
| 343 | .accessibilityElement(children: .combine) |
| 344 | .accessibilityLabel(line.taskState.map { "\($0.accessibilityLabel): \(String(line.text.characters))" } ?? String(line.text.characters)) |
| 345 | .accessibilityIdentifier(line.marker == nil ? "summaryTextLine-\(line.id)" : "markdownListItem-\(line.id)") |
| 346 | } else { |
| 347 | Color.clear.frame(height: 4).accessibilityHidden(true) |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | .frame(maxWidth: .infinity, alignment: .leading) |
| 352 | .accessibilityElement(children: .contain) |
| 353 | .accessibilityIdentifier("standardSummaryText") |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | /// Keep the marker outside the text column so wrapped chat answers hang |
| 358 | /// beneath the first word, including answers containing literal bullet glyphs. |
| 359 | struct JotleyChatAnswerText: View { |
| 360 | let content: String |
| 361 | var font: Font = .body |
| 362 | var body: some View { |
| 363 | let markdown = content.replacingOccurrences(of: #"(?m)^(\h*)•\h+"#, with: "$1- ", options: .regularExpression) |
| 364 | StandardSummaryTextView(markdown: ParsedNoteMarkdown.rendering(markdown), bodyFont: font) |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | struct StructuredSummaryView: View { |
| 369 | @ObservedObject private var themeManager = ThemeManager.shared |
| 370 | @AppStorage(SummaryDisplayStyle.preferenceKey) private var style: SummaryDisplayStyle = .cards |
| 371 | let content: String |
| 372 | var isStreaming = false |
| 373 | |
| 374 | var body: some View { |
| 375 | let markdown = ParsedNoteMarkdown.rendering(content, isStreaming: isStreaming) |
| 376 | let summary = StructuredSummary(markdown) |
| 377 | let palette = SummaryPalette.current |
| 378 | // Use actual card heights as the streaming text grows. |
| 379 | return Group { |
| 380 | if style == .standard { |
| 381 | StandardSummaryTextView(markdown: markdown) |
| 382 | } else { |
| 383 | VStack(alignment: .leading, spacing: 22) { |
| 384 | ForEach(summary.blocks) { block in StructuredSummaryBlockView(block: block, palette: palette) } |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | .accessibilityElement(children: .contain) |
| 389 | .transaction { if isStreaming { $0.animation = nil } } |
| 390 | } |
| 391 | |
| 392 | /// A top-level item and the nested items under it share one card or row. |
| 393 | static func groups(_ items: [StructuredSummary.Item]) -> [[StructuredSummary.Item]] { |
| 394 | var result: [[StructuredSummary.Item]] = [] |
| 395 | let base = items.map(\.indentation).min() ?? 0 |
| 396 | for item in items { |
| 397 | if item.indentation > base, !result.isEmpty { result[result.count - 1].append(item) } |
| 398 | else { result.append([item]) } |
| 399 | } |
| 400 | return result |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | /// One overview card or section. Text uses Dynamic Type styles, so it follows |
| 405 | /// the person's text size setting. |
| 406 | struct StructuredSummaryBlockView: View { |
| 407 | let block: StructuredSummary.Block |
| 408 | let palette: SummaryPalette |
| 409 | @ScaledMetric(relativeTo: .headline) private var iconBox: CGFloat = 34 |
| 410 | @ScaledMetric(relativeTo: .body) private var numberSize: CGFloat = 30 |
| 411 | @ScaledMetric(relativeTo: .body) private var preferredTextColumnWidth: CGFloat = 230 |
| 412 | |
| 413 | var body: some View { |
| 414 | switch block { |
| 415 | case .overview(let overview): |
| 416 | VStack(alignment: .leading, spacing: 10) { |
| 417 | Label { |
| 418 | Text("Summary").foregroundStyle(palette.text) |
| 419 | } icon: { |
| 420 | Image(systemName: "sparkles").foregroundStyle(palette.headingIcon) |
| 421 | } |
| 422 | .font(.headline) |
| 423 | overviewBody(overview) |
| 424 | } |
| 425 | .padding(18).frame(maxWidth: .infinity, alignment: .leading) |
| 426 | .background(palette.card, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) |
| 427 | .overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).strokeBorder(palette.text.opacity(0.15), lineWidth: 1)) |
| 428 | .accessibilityIdentifier("structuredSummaryOverview") |
| 429 | case .section(let section): |
| 430 | VStack(alignment: .leading, spacing: 12) { |
| 431 | if section.title != nil { titleRow(section) } |
| 432 | if !section.paragraphs.isEmpty { paragraphsCard(section) } |
| 433 | if !section.items.isEmpty { itemsView(section) } |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | func titleRow(_ section: StructuredSummary.Section) -> some View { |
| 439 | HStack(spacing: 12) { |
| 440 | Image(systemName: section.systemImage) |
| 441 | .font(.headline).foregroundStyle(palette.headingIcon) |
| 442 | .frame(width: iconBox, height: iconBox) |
| 443 | .background(palette.headingIcon.opacity(0.10), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) |
| 444 | .accessibilityHidden(true) |
| 445 | Text(section.title ?? "").font(.title3.weight(.semibold)).foregroundStyle(palette.text) |
| 446 | .accessibilityAddTraits(.isHeader) |
| 447 | Spacer(minLength: 0) |
| 448 | if section.items.count > 1 { |
| 449 | Text("\(section.items.filter { $0.indentation == 0 }.count)") |
| 450 | .font(.subheadline.weight(.semibold)).foregroundStyle(palette.secondary) |
| 451 | .padding(.horizontal, 9).padding(.vertical, 3) |
| 452 | .background(Capsule().fill(palette.text.opacity(0.08))) |
| 453 | .accessibilityHidden(true) |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | func paragraphsCard(_ section: StructuredSummary.Section) -> some View { |
| 459 | VStack(alignment: .leading, spacing: 8) { |
| 460 | ForEach(section.paragraphs) { line in |
| 461 | Text(line.text).font(.body).foregroundStyle(palette.text).textSelection(.enabled) |
| 462 | .frame(maxWidth: .infinity, alignment: .leading) |
| 463 | } |
| 464 | }.padding(16).background(palette.card, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) |
| 465 | } |
| 466 | |
| 467 | @ViewBuilder |
| 468 | private func overviewBody(_ section: StructuredSummary.Section) -> some View { |
| 469 | ForEach(section.paragraphs) { line in |
| 470 | Text(line.text).font(.body).foregroundStyle(palette.text).textSelection(.enabled) |
| 471 | .frame(maxWidth: .infinity, alignment: .leading) |
| 472 | } |
| 473 | ForEach(section.items) { item in |
| 474 | HStack(alignment: .firstTextBaseline, spacing: 8) { |
| 475 | SummaryListMarker(marker: item.marker, taskState: item.taskState).foregroundStyle(palette.marker) |
| 476 | itemText(item, color: palette.text) |
| 477 | } |
| 478 | .font(.body) |
| 479 | .padding(.leading, CGFloat(item.indentation) * 8) |
| 480 | .accessibilityElement(children: .combine) |
| 481 | .accessibilityLabel(item.accessibilityText) |
| 482 | .accessibilityIdentifier("markdownListItem-\(item.id)") |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | @ViewBuilder |
| 487 | private func itemsView(_ section: StructuredSummary.Section) -> some View { |
| 488 | let groups = StructuredSummaryView.groups(section.items) |
| 489 | switch section.style { |
| 490 | case .numbered: |
| 491 | VStack(spacing: numberedRowSpacing) { |
| 492 | ForEach(Array(groups.enumerated()), id: \.element.first?.id) { index, group in |
| 493 | numberedCard(index: index, group: group) |
| 494 | } |
| 495 | } |
| 496 | default: |
| 497 | VStack(alignment: .leading, spacing: 0) { |
| 498 | ForEach(Array(groups.enumerated()), id: \.element.first?.id) { index, group in |
| 499 | if index > 0 { Divider().padding(.leading, 44) } |
| 500 | row(section, group: group) |
| 501 | } |
| 502 | } |
| 503 | .padding(.horizontal, 14) |
| 504 | .background(palette.card, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | private var numberedRowSpacing: CGFloat { |
| 509 | #if os(macOS) |
| 510 | return 6 |
| 511 | #else |
| 512 | return 10 |
| 513 | #endif |
| 514 | } |
| 515 | |
| 516 | private var numberedRowVerticalPadding: CGFloat { |
| 517 | #if os(macOS) |
| 518 | return 8 |
| 519 | #else |
| 520 | return 14 |
| 521 | #endif |
| 522 | } |
| 523 | |
| 524 | func numberedCard(index: Int, group: [StructuredSummary.Item]) -> some View { |
| 525 | HStack(alignment: .firstTextBaseline, spacing: 12) { |
| 526 | if let taskState = group.first?.taskState { |
| 527 | Image(systemName: taskState.systemImage).font(.callout).foregroundStyle(palette.marker) |
| 528 | .frame(width: numberSize, height: numberSize).accessibilityHidden(true) |
| 529 | } else { |
| 530 | Text("\(index + 1)") |
| 531 | .font(.callout.weight(.semibold).monospacedDigit()).foregroundStyle(palette.marker) |
| 532 | .frame(width: numberSize, height: numberSize) |
| 533 | .overlay(Circle().strokeBorder(palette.marker.opacity(0.65), lineWidth: 1)) |
| 534 | .accessibilityHidden(true) |
| 535 | } |
| 536 | groupText(group, emphasizeLabel: true) |
| 537 | } |
| 538 | .padding(.horizontal, 14).padding(.vertical, numberedRowVerticalPadding) |
| 539 | .frame(maxWidth: .infinity, alignment: .leading) |
| 540 | .background(palette.card, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) |
| 541 | } |
| 542 | |
| 543 | private func row(_ section: StructuredSummary.Section, group: [StructuredSummary.Item]) -> some View { |
| 544 | // Align to the task's first text baseline, including when a padded |
| 545 | // owner chip makes the text group taller or the task wraps. |
| 546 | HStack(alignment: .firstTextBaseline, spacing: 12) { |
| 547 | Image(systemName: group.first?.taskState?.systemImage ?? Self.rowImage(section.style)) |
| 548 | .font(.body).foregroundStyle(palette.marker) |
| 549 | .frame(width: 26).accessibilityHidden(true) |
| 550 | groupText(group, emphasizeLabel: false) |
| 551 | }.padding(.vertical, 12) |
| 552 | } |
| 553 | |
| 554 | /// A list row on its own card, so a PDF can break pages between rows. |
| 555 | func rowCard(_ section: StructuredSummary.Section, group: [StructuredSummary.Item]) -> some View { |
| 556 | row(section, group: group).padding(.horizontal, 14) |
| 557 | .frame(maxWidth: .infinity, alignment: .leading) |
| 558 | .background(palette.card, in: RoundedRectangle(cornerRadius: 16, style: .continuous)) |
| 559 | } |
| 560 | |
| 561 | private func groupText(_ group: [StructuredSummary.Item], emphasizeLabel: Bool) -> some View { |
| 562 | VStack(alignment: .leading, spacing: 6) { |
| 563 | ForEach(group) { item in |
| 564 | Group { |
| 565 | if item.id == group.first?.id { |
| 566 | if let label = item.label, emphasizeLabel { |
| 567 | VStack(alignment: .leading, spacing: 4) { |
| 568 | Text(label).font(.headline).foregroundStyle(palette.text) |
| 569 | Text(item.body).font(.body).foregroundStyle(palette.secondary) |
| 570 | .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) |
| 571 | } |
| 572 | } else if let label = item.label { |
| 573 | ViewThatFits(in: .horizontal) { |
| 574 | HStack(alignment: .firstTextBaseline, spacing: 8) { |
| 575 | rowText(item) |
| 576 | .frame(minWidth: preferredTextColumnWidth, idealWidth: preferredTextColumnWidth, |
| 577 | maxWidth: .infinity, alignment: .leading) |
| 578 | rowBadge(label).fixedSize() |
| 579 | } |
| 580 | VStack(alignment: .leading, spacing: 6) { |
| 581 | rowText(item).frame(maxWidth: .infinity, alignment: .leading) |
| 582 | rowBadge(label).fixedSize(horizontal: false, vertical: true) |
| 583 | } |
| 584 | } |
| 585 | } else { |
| 586 | rowText(item).frame(maxWidth: .infinity, alignment: .leading) |
| 587 | } |
| 588 | } else { |
| 589 | HStack(alignment: .firstTextBaseline, spacing: 6) { |
| 590 | SummaryListMarker(marker: item.marker, taskState: item.taskState).foregroundStyle(palette.marker) |
| 591 | itemText(item, color: palette.secondary) |
| 592 | }.font(.body).padding(.leading, 6 + CGFloat(max(0, item.indentation - 2)) * 6) |
| 593 | } |
| 594 | } |
| 595 | .accessibilityElement(children: .combine) |
| 596 | .accessibilityLabel(item.accessibilityText) |
| 597 | .accessibilityIdentifier("markdownListItem-\(item.id)") |
| 598 | } |
| 599 | }.frame(maxWidth: .infinity, alignment: .leading) |
| 600 | } |
| 601 | |
| 602 | private func rowText(_ item: StructuredSummary.Item) -> some View { |
| 603 | Text(item.body).font(.body).foregroundStyle(palette.text).textSelection(.enabled) |
| 604 | } |
| 605 | |
| 606 | private func rowBadge(_ label: AttributedString) -> some View { |
| 607 | Text(label).font(.subheadline.weight(.semibold)).foregroundStyle(palette.badge) |
| 608 | .padding(.horizontal, 10).padding(.vertical, 4) |
| 609 | .background(Capsule().fill(palette.badge.opacity(0.10))) |
| 610 | } |
| 611 | |
| 612 | private func itemText(_ item: StructuredSummary.Item, color: Color) -> some View { |
| 613 | var text = AttributedString() |
| 614 | if let label = item.label { |
| 615 | var bold = label; bold.inlinePresentationIntent = .stronglyEmphasized |
| 616 | text = bold + AttributedString(": ") + item.body |
| 617 | } else { text = item.body } |
| 618 | return Text(text).foregroundStyle(color).textSelection(.enabled) |
| 619 | .frame(maxWidth: .infinity, alignment: .leading) |
| 620 | } |
| 621 | |
| 622 | private static func rowImage(_ style: StructuredSummary.Style) -> String { |
| 623 | switch style { |
| 624 | case .checklist: return "circle" |
| 625 | case .questions: return "questionmark.circle" |
| 626 | case .risks: return "exclamationmark.triangle.fill" |
| 627 | default: return "smallcircle.filled.circle" |
| 628 | } |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | /// Renders a summary as a paginated PDF that matches the in-app layout. |
| 633 | /// Sections are split into their heading, cards and rows, so pages fill |
| 634 | /// before breaking and a heading always stays with what follows it. |
| 635 | @MainActor enum SummaryPDF { |
| 636 | private struct Piece { let view: AnyView; var keepWithNext = false; var gapAfter: CGFloat = 10 } |
| 637 | |
| 638 | static func write(title: String, date: Date?, markdown: String, to url: URL) throws { |
| 639 | let page = CGSize(width: 612, height: 792), margin: CGFloat = 42, width = page.width - margin * 2 |
| 640 | var box = CGRect(origin: .zero, size: page) |
| 641 | guard let pdf = CGContext(url as CFURL, mediaBox: &box, [kCGPDFContextTitle as String: title, kCGPDFContextCreator as String: "Jotley"] as CFDictionary) else { |
| 642 | throw LocalError.message("The PDF could not be created.") |
| 643 | } |
| 644 | let palette = SummaryPalette.print |
| 645 | let header = VStack(alignment: .leading, spacing: 6) { |
| 646 | Text(title).font(.title.bold()).foregroundStyle(palette.text) |
| 647 | if let date { |
| 648 | Text(date, format: .dateTime.weekday(.wide).month(.wide).day().year().hour().minute()) |
| 649 | .font(.subheadline).foregroundStyle(palette.secondary) |
| 650 | } |
| 651 | }.frame(maxWidth: .infinity, alignment: .leading) |
| 652 | var pieces = [Piece(view: AnyView(header), gapAfter: 18)] |
| 653 | for block in StructuredSummary(ParsedNoteMarkdown.rendering(markdown)).blocks { |
| 654 | let view = StructuredSummaryBlockView(block: block, palette: palette) |
| 655 | guard case .section(let section) = block else { |
| 656 | pieces.append(Piece(view: AnyView(view), gapAfter: 22)); continue |
| 657 | } |
| 658 | if section.title != nil { pieces.append(Piece(view: AnyView(view.titleRow(section)), keepWithNext: true, gapAfter: 12)) } |
| 659 | if !section.paragraphs.isEmpty { pieces.append(Piece(view: AnyView(view.paragraphsCard(section)))) } |
| 660 | for (index, group) in StructuredSummaryView.groups(section.items).enumerated() { |
| 661 | pieces.append(Piece(view: section.style == .numbered |
| 662 | ? AnyView(view.numberedCard(index: index, group: group)) |
| 663 | : AnyView(view.rowCard(section, group: group)), gapAfter: 8)) |
| 664 | } |
| 665 | if let last = pieces.indices.last { pieces[last].gapAfter = 22 } |
| 666 | } |
| 667 | let renderers = pieces.map { piece -> ImageRenderer<AnyView> in |
| 668 | let renderer = ImageRenderer(content: AnyView(piece.view.frame(width: width) |
| 669 | .environment(\.colorScheme, .light).environment(\.dynamicTypeSize, .small))) |
| 670 | renderer.proposedSize = ProposedViewSize(width: width, height: nil) |
| 671 | return renderer |
| 672 | } |
| 673 | var heights: [CGFloat] = [] |
| 674 | for renderer in renderers { renderer.render { size, _ in heights.append(size.height) } } |
| 675 | |
| 676 | var y = margin, pageOpen = false |
| 677 | func newPage() { |
| 678 | if pageOpen { pdf.endPDFPage() } |
| 679 | pdf.beginPDFPage(nil); pageOpen = true; y = margin |
| 680 | } |
| 681 | newPage() |
| 682 | let bottom = page.height - margin |
| 683 | for (index, renderer) in renderers.enumerated() { |
| 684 | let height = heights[index] |
| 685 | // A heading moves with the first card under it. |
| 686 | let needed = pieces[index].keepWithNext && index + 1 < heights.count ? height + pieces[index].gapAfter + heights[index + 1] : height |
| 687 | if y > margin, y + needed > bottom, needed <= bottom - margin { newPage() } |
| 688 | renderer.render { size, draw in |
| 689 | var shown: CGFloat = 0 |
| 690 | while true { |
| 691 | let available = bottom - y |
| 692 | pdf.saveGState() |
| 693 | pdf.clip(to: CGRect(x: margin, y: margin, width: width, height: available)) |
| 694 | pdf.translateBy(x: margin, y: page.height - y - size.height + shown) |
| 695 | draw(pdf) |
| 696 | pdf.restoreGState() |
| 697 | let used = min(available, size.height - shown) |
| 698 | shown += used; y += used |
| 699 | if shown >= size.height { break } |
| 700 | newPage() |
| 701 | } |
| 702 | } |
| 703 | y += pieces[index].gapAfter |
| 704 | } |
| 705 | if pageOpen { pdf.endPDFPage() } |
| 706 | pdf.closePDF() |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | /// A shared capsule track keeps the two note views visually connected. |
| 711 | struct NoteContentSwitch: View { |
| 712 | @Binding var selection: String |
| 713 | var showsSummary: Bool |
| 714 | var showsTranscript: Bool = true |
| 715 | var summaryIsGenerating = false |
| 716 | var animatesSelection = true |
| 717 | @Namespace private var highlight |
| 718 | @ObservedObject private var theme = ThemeManager.shared |
| 719 | @Environment(\.accessibilityReduceMotion) private var reduceMotion |
| 720 | |
| 721 | private var tabs: [String] { |
| 722 | (showsSummary ? ["Summary"] : []) + (showsTranscript ? ["Transcript"] : []) |
| 723 | } |
| 724 | var body: some View { |
| 725 | HStack(spacing: 0) { |
| 726 | ForEach(tabs, id: \.self) { tab in |
| 727 | Button { selection = tab } label: { |
| 728 | HStack(spacing: 5) { |
| 729 | if tab == "Summary" && summaryIsGenerating { ProgressView().controlSize(.mini) } |
| 730 | Text(tab == "Summary" ? LocalizedStringKey("Summary") : LocalizedStringKey("Transcript")) |
| 731 | .font(.subheadline.weight(selection == tab ? .semibold : .medium)).lineLimit(1) |
| 732 | } |
| 733 | .foregroundStyle(Color.themeTextPrimary) |
| 734 | .padding(.horizontal, 16).padding(.vertical, 7) |
| 735 | .frame(minWidth: 92) |
| 736 | .background { |
| 737 | if selection == tab { |
| 738 | if animatesSelection { |
| 739 | selectionHighlight.matchedGeometryEffect(id: "selectedTab", in: highlight) |
| 740 | } else { |
| 741 | selectionHighlight |
| 742 | } |
| 743 | } |
| 744 | } |
| 745 | .contentShape(Capsule()) |
| 746 | } |
| 747 | .buttonStyle(.plain) |
| 748 | .accessibilityIdentifier("noteDetail\(tab)Tab") |
| 749 | .accessibilityAddTraits(selection == tab ? .isSelected : []) |
| 750 | } |
| 751 | } |
| 752 | .padding(3) |
| 753 | .background(Color.themeTextPrimary.opacity(0.08), in: Capsule()) |
| 754 | .modifier(JotleyControlShadow()) |
| 755 | .fixedSize(horizontal: true, vertical: false) |
| 756 | .animation(animatesSelection && !reduceMotion ? .easeInOut(duration: 0.18) : nil, value: selection) |
| 757 | .accessibilityElement(children: .contain) |
| 758 | .accessibilityLabel("Note view") |
| 759 | } |
| 760 | |
| 761 | private var selectionHighlight: some View { |
| 762 | Capsule().fill(Color.themeBackground) |
| 763 | .overlay { Capsule().strokeBorder(Color.themePrimaryAccent) } |
| 764 | } |
| 765 | } |