Jotley / app · jotley.ai / Shared / Views / SummaryTemplatesView.swift
| 1 | import SwiftUI |
| 2 | import CoreData |
| 3 | |
| 4 | enum SummaryTemplatePresentation: String, Identifiable { |
| 5 | case create, manage |
| 6 | var id: String { rawValue } |
| 7 | } |
| 8 | |
| 9 | struct SummaryTemplatesView: View { |
| 10 | @ObservedObject private var catalog = SummaryTemplateStore.shared |
| 11 | @State private var selectedKey: String? |
| 12 | @State private var draft: TemplateDraft? |
| 13 | var onUse: ((SummaryTemplateDefinition) -> Void)? |
| 14 | |
| 15 | var body: some View { |
| 16 | #if os(macOS) |
| 17 | ViewThatFits(in: .horizontal) { |
| 18 | HSplitView { |
| 19 | library.frame(minWidth: 240, idealWidth: 260, maxWidth: 300) |
| 20 | selectedEditor.frame(minWidth: 440, maxWidth: .infinity, maxHeight: .infinity) |
| 21 | }.frame(minWidth: 700) |
| 22 | VStack(spacing: 0) { |
| 23 | HStack(spacing: 12) { |
| 24 | Picker("Template", selection: $selectedKey) { |
| 25 | Text("Choose a template").tag(String?.none) |
| 26 | ForEach(catalog.definitions) { definition in |
| 27 | Text(definition.title).tag(Optional(definition.key)) |
| 28 | } |
| 29 | }.frame(maxWidth: .infinity) |
| 30 | Button { draft = TemplateDraft() } label: { Label("New Template", systemImage: "plus") } |
| 31 | .accessibilityIdentifier("templatesNewButton") |
| 32 | } |
| 33 | .padding(.horizontal, 20).padding(.vertical, 16) |
| 34 | Divider() |
| 35 | selectedEditor |
| 36 | } |
| 37 | } |
| 38 | .sheet(item: $draft) { value in draftEditor(value) } |
| 39 | .onAppear { |
| 40 | if selectedKey == nil { selectedKey = catalog.templates.first?.key ?? LocalSummaryTemplate.auto.key } |
| 41 | } |
| 42 | #else |
| 43 | library |
| 44 | .navigationTitle("Summary Templates") |
| 45 | .sheet(item: $draft) { value in NavigationStack { draftEditor(value) } } |
| 46 | #endif |
| 47 | } |
| 48 | @ViewBuilder private var selectedEditor: some View { |
| 49 | if let selectedKey, let definition = try? catalog.resolve(selectedKey) { |
| 50 | editor(definition).id(selectedKey) |
| 51 | } else { |
| 52 | ContentUnavailableView("Summary Templates", systemImage: "doc.text", |
| 53 | description: Text("Create a template or duplicate a built-in template to make it your own.")) |
| 54 | } |
| 55 | } |
| 56 | private var library: some View { |
| 57 | List { |
| 58 | Section { |
| 59 | Button { draft = TemplateDraft() } label: { Label("New Template", systemImage: "plus") } |
| 60 | .accessibilityIdentifier("templatesNewButton") |
| 61 | } |
| 62 | if let error = catalog.storageError { Section { Text(error).foregroundStyle(.secondary) } } |
| 63 | Section("My Templates") { |
| 64 | if catalog.templates.isEmpty { Text("No custom templates yet").foregroundStyle(.secondary) } |
| 65 | ForEach(catalog.templates) { template in row(template.definition) } |
| 66 | } |
| 67 | Section("Built-in Templates") { |
| 68 | ForEach(LocalSummaryTemplate.allCases) { row(.init($0)) } |
| 69 | } |
| 70 | Section { |
| 71 | Text(catalog.syncEnabled ? "Custom templates sync with your iCloud account. Existing summaries change only when you regenerate them." : "Custom templates are saved on this device. Existing summaries change only when you regenerate them.") |
| 72 | .font(.footnote).foregroundStyle(.secondary) |
| 73 | } |
| 74 | } |
| 75 | .tint(Color.themePrimaryAccent) |
| 76 | .accessibilityIdentifier("summaryTemplatesLibrary") |
| 77 | } |
| 78 | @ViewBuilder private func row(_ definition: SummaryTemplateDefinition) -> some View { |
| 79 | #if os(macOS) |
| 80 | Button { selectedKey = definition.key } label: { |
| 81 | HStack { Text(definition.title); Spacer(); if selectedKey == definition.key { Image(systemName: "checkmark").foregroundStyle(Color.themePrimaryAccent) } } |
| 82 | .contentShape(Rectangle()) |
| 83 | }.buttonStyle(.plain).padding(.vertical, 4).accessibilityIdentifier("templateRow-\(definition.key)") |
| 84 | #else |
| 85 | NavigationLink { editor(definition) } label: { Text(definition.title) } |
| 86 | .accessibilityIdentifier("templateRow-\(definition.key)") |
| 87 | #endif |
| 88 | } |
| 89 | private func editor(_ definition: SummaryTemplateDefinition) -> some View { |
| 90 | SummaryTemplateEditor(draft: TemplateDraft(definition: definition, catalog: catalog), onSaved: { selectedKey = $0.key }, |
| 91 | onDuplicate: { draft = TemplateDraft(name: definition.title + " copy", instructions: definition.prompt) }, |
| 92 | onDeleted: { selectedKey = nil }, onUse: onUse) |
| 93 | } |
| 94 | private func draftEditor(_ value: TemplateDraft) -> some View { |
| 95 | SummaryTemplateEditor(draft: value, onSaved: { record in selectedKey = record.key; draft = nil }, |
| 96 | onDuplicate: {}, onDeleted: {}, onUse: onUse, onCancel: { draft = nil }) |
| 97 | #if os(macOS) |
| 98 | .frame(width: 580, height: 690) |
| 99 | #endif |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// Present creation directly from a note. A second sheet during the first |
| 104 | /// sheet's presentation can be dropped by SwiftUI on iPhone/iPad. |
| 105 | struct NewSummaryTemplateView: View { |
| 106 | @Environment(\.dismiss) private var dismiss |
| 107 | var onSaved: () -> Void = {} |
| 108 | var onUse: ((SummaryTemplateDefinition) -> Void)? |
| 109 | var body: some View { |
| 110 | SummaryTemplateEditor(draft: TemplateDraft(), onSaved: { _ in onSaved(); dismiss() }, |
| 111 | onDuplicate: {}, onDeleted: {}, onUse: onUse, onCancel: { dismiss() }) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | private struct TemplateDraft: Identifiable { |
| 116 | let id = UUID() |
| 117 | var recordID: UUID? |
| 118 | var revision: String? |
| 119 | var name = "" |
| 120 | var instructions = "" |
| 121 | var builtIn = false |
| 122 | var key = "custom/preview" |
| 123 | init(name: String = "", instructions: String = "") { self.name = name; self.instructions = instructions } |
| 124 | @MainActor init(definition: SummaryTemplateDefinition, catalog: SummaryTemplateStore) { |
| 125 | name = definition.title; instructions = definition.prompt; builtIn = !definition.isCustom |
| 126 | key = definition.key |
| 127 | if let record = catalog.templates.first(where: { $0.key == definition.key }) { recordID = record.id; revision = record.revision } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | private struct SummaryTemplateEditor: View { |
| 132 | @ObservedObject private var catalog = SummaryTemplateStore.shared |
| 133 | @Environment(\.dismiss) private var dismiss |
| 134 | @AppStorage("transcriptionLanguage") private var language = "en-US" |
| 135 | @FetchRequest(sortDescriptors: [NSSortDescriptor(key: "timestamp", ascending: false)], |
| 136 | predicate: SharedPersistenceController.activeNotesPredicate) private var notes: FetchedResults<Note> |
| 137 | let draft: TemplateDraft |
| 138 | let onSaved: (CustomSummaryTemplate) -> Void |
| 139 | let onDuplicate: () -> Void |
| 140 | let onDeleted: () -> Void |
| 141 | var onUse: ((SummaryTemplateDefinition) -> Void)? |
| 142 | var onCancel: (() -> Void)? |
| 143 | @State private var name: String |
| 144 | @State private var instructions: String |
| 145 | @State private var revision: String? |
| 146 | @State private var recordID: UUID? |
| 147 | @State private var error: String? |
| 148 | @State private var savedMessage: String? |
| 149 | @State private var showDelete = false |
| 150 | @State private var previewNote: UUID? |
| 151 | @State private var preview = "" |
| 152 | @State private var isPreviewing = false |
| 153 | @State private var previewTask: Task<Void, Never>? |
| 154 | @State private var previewID: UUID? |
| 155 | |
| 156 | init(draft: TemplateDraft, onSaved: @escaping (CustomSummaryTemplate) -> Void, |
| 157 | onDuplicate: @escaping () -> Void, onDeleted: @escaping () -> Void, |
| 158 | onUse: ((SummaryTemplateDefinition) -> Void)? = nil, onCancel: (() -> Void)? = nil) { |
| 159 | self.draft = draft; self.onSaved = onSaved; self.onDuplicate = onDuplicate; self.onDeleted = onDeleted |
| 160 | self.onUse = onUse; self.onCancel = onCancel |
| 161 | _name = State(initialValue: draft.name); _instructions = State(initialValue: draft.instructions) |
| 162 | _revision = State(initialValue: draft.revision); _recordID = State(initialValue: draft.recordID) |
| 163 | } |
| 164 | private var eligibleNotes: [Note] { Array(notes.filter { !($0.transcription ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }.prefix(30)) } |
| 165 | private var valid: Bool { !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && name.count <= SummaryTemplateStore.nameLimit && !instructions.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && instructions.utf8.count <= SummaryTemplateStore.instructionByteLimit } |
| 166 | var body: some View { |
| 167 | Form { |
| 168 | Section { |
| 169 | TextField("Name", text: $name).disabled(draft.builtIn).accessibilityIdentifier("templateNameField") |
| 170 | VStack(alignment: .leading, spacing: 8) { |
| 171 | Text("Instructions").font(.headline) |
| 172 | TextEditor(text: $instructions).frame(minHeight: 150).disabled(draft.builtIn) |
| 173 | .accessibilityLabel("Template instructions").accessibilityIdentifier("templateInstructionsField") |
| 174 | Text("\(instructions.utf8.count) / \(SummaryTemplateStore.instructionByteLimit) bytes").font(.caption).foregroundStyle(.secondary) |
| 175 | Text("Describe the sections, focus, length and tone you want. Jotley uses only facts in the note and runs the summary on-device.").font(.footnote).foregroundStyle(.secondary) |
| 176 | } |
| 177 | if draft.builtIn { |
| 178 | Button("Duplicate Template", action: onDuplicate).accessibilityIdentifier("templateDuplicateButton") |
| 179 | } else { |
| 180 | HStack { |
| 181 | Button("Save Template") { save(use: false) }.disabled(!valid || isPreviewing).accessibilityIdentifier("templateSaveButton") |
| 182 | if onUse != nil { Button("Save & Use") { save(use: true) }.disabled(!valid || isPreviewing) } |
| 183 | }.buttonStyle(.borderless) |
| 184 | if recordID != nil { |
| 185 | HStack { |
| 186 | Button("Duplicate") { onDuplicate() }.disabled(onCancel != nil) |
| 187 | Button("Delete Template", role: .destructive) { showDelete = true }.accessibilityIdentifier("templateDeleteButton") |
| 188 | }.buttonStyle(.borderless) |
| 189 | } |
| 190 | } |
| 191 | if let savedMessage { Text(savedMessage).foregroundStyle(.secondary).accessibilityIdentifier("templateSavedStatus") } |
| 192 | if let error { Text(error).foregroundStyle(.red).accessibilityIdentifier("templateError") } |
| 193 | } |
| 194 | Section("Try on a Note") { |
| 195 | if eligibleNotes.isEmpty { |
| 196 | Text("Add a transcript to a note to preview this template.").foregroundStyle(.secondary) |
| 197 | } else { |
| 198 | Picker("Note", selection: $previewNote) { |
| 199 | Text("Choose a note").tag(UUID?.none) |
| 200 | ForEach(eligibleNotes) { note in Text(note.title ?? "Untitled").tag(note.id) } |
| 201 | }.disabled(isPreviewing).accessibilityIdentifier("templatePreviewNotePicker") |
| 202 | if isPreviewing { |
| 203 | ProgressView("Generating preview…") |
| 204 | Button("Cancel Preview") { cancelPreview() } |
| 205 | .jotleyDismissButtonStyle() |
| 206 | } else { |
| 207 | Button("Preview Summary") { generatePreview() }.disabled(!valid || previewNote == nil).accessibilityIdentifier("templatePreviewButton") |
| 208 | } |
| 209 | Text("Previewing does not change the note’s saved summary.").font(.footnote).foregroundStyle(.secondary) |
| 210 | if !preview.isEmpty { StructuredSummaryView(content: preview).accessibilityIdentifier("templatePreviewResult") } |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | .formStyle(.grouped) |
| 215 | .navigationTitle(draft.builtIn ? name : (recordID == nil ? "New Template" : "Edit Template")) |
| 216 | .tint(Color.themePrimaryAccent) |
| 217 | .toolbar { |
| 218 | if let onCancel { |
| 219 | ToolbarItem(placement: .cancellationAction) { |
| 220 | Button("Cancel", action: onCancel).jotleyDismissButtonStyle(inToolbar: true) |
| 221 | } |
| 222 | .sharedBackgroundVisibility(.hidden) |
| 223 | } |
| 224 | } |
| 225 | .alert("Delete this template?", isPresented: $showDelete) { |
| 226 | Button("Delete Template", role: .destructive) { |
| 227 | guard let recordID, let revision else { return } |
| 228 | do { |
| 229 | try catalog.delete(id: recordID, expectedRevision: revision); onDeleted() |
| 230 | #if os(iOS) |
| 231 | dismiss() |
| 232 | #endif |
| 233 | } |
| 234 | catch { self.error = error.localizedDescription } |
| 235 | }.accessibilityIdentifier("templateConfirmDeleteButton") |
| 236 | Button("Cancel", role: .cancel) {} |
| 237 | } message: { Text("Saved notes and summaries will be kept. Choose another template to regenerate notes that used this one.") } |
| 238 | .onAppear { previewNote = eligibleNotes.first?.id } |
| 239 | .onChange(of: name) { _, _ in savedMessage = nil; cancelPreview() } |
| 240 | .onChange(of: instructions) { _, _ in savedMessage = nil; cancelPreview() } |
| 241 | .onChange(of: previewNote) { _, _ in cancelPreview() } |
| 242 | .onDisappear { cancelPreview() } |
| 243 | } |
| 244 | private func save(use: Bool) { |
| 245 | do { |
| 246 | let record = try catalog.save(id: recordID, name: name, instructions: instructions, expectedRevision: revision) |
| 247 | recordID = record.id; revision = record.revision; savedMessage = "Template saved. Existing summaries are unchanged."; error = nil |
| 248 | onSaved(record) |
| 249 | if use { onUse?(record.definition) } |
| 250 | } catch { self.error = error.localizedDescription } |
| 251 | } |
| 252 | private func cancelPreview() { previewID = nil; previewTask?.cancel(); previewTask = nil; isPreviewing = false; preview = "" } |
| 253 | private func generatePreview() { |
| 254 | guard let note = eligibleNotes.first(where: { $0.id == previewNote }) else { return } |
| 255 | let source = note.transcription ?? "" |
| 256 | let definition = SummaryTemplateDefinition(key: draft.builtIn ? draft.key : "custom/preview", title: name, prompt: instructions) |
| 257 | let locale = Locale(identifier: language) |
| 258 | let identifier = UUID(); previewID = identifier |
| 259 | isPreviewing = true; preview = ""; error = nil |
| 260 | previewTask = Task { |
| 261 | defer { if !Task.isCancelled { isPreviewing = false; previewTask = nil } } |
| 262 | do { |
| 263 | let result = try await LocalSummary.generate(source, template: definition, locale: locale) { value in |
| 264 | guard !Task.isCancelled else { return } |
| 265 | await MainActor.run { if previewID == identifier { preview = value } } |
| 266 | } |
| 267 | try Task.checkCancellation(); preview = result |
| 268 | } catch is CancellationError {} catch { if !Task.isCancelled { self.error = error.localizedDescription } } |
| 269 | } |
| 270 | } |
| 271 | } |