Open History to see the last commit
1import AppKit
2import SwiftUI
3import CoreText
4
5@MainActor
6final class ExpeditionJournal: ObservableObject {
7 enum Kind: String, Codable, Sendable { case request, response, activity }
8 struct Entry: Identifiable, Codable, Sendable {
9 let id: UUID
10 let date: Date
11 let kind: Kind
12 var text: String
13 var details: String
14 var photo: String? = nil
15 }
16 struct Expedition: Identifiable {
17 let id: UUID
18 let date: Date
19 var title: String
20 var entries: [Entry] = []
21 var status = "Ready for your next direction"
22 var isRunning = false
23 var isFinished = false
24 }
25 @Published private(set) var expeditions: [Expedition] = []
26 @Published private(set) var selectedID: UUID?
27 @Published private(set) var activeID: UUID?
28 @Published private(set) var storageIssue: String?
29 @Published private(set) var saveFailed = false
30 private var store: ExpeditionJournalStore?
31 var committedStore: ExpeditionJournalStore? { store }
32 private var restoreWarning: String?
33 static var defaultDirectory: URL {
34 let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
35 ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support")
36 return support.appendingPathComponent("Jerry/Expeditions", isDirectory: true)
37 }
38 init(storageDirectory: URL? = ExpeditionJournal.defaultDirectory) {
39 guard let storageDirectory else { return }
40 let store = ExpeditionJournalStore(directory: storageDirectory) { [weak self] issue in
41 Task { @MainActor [weak self] in self?.storageIssue = issue ?? self?.restoreWarning; self?.saveFailed = issue != nil }
42 }
43 self.store = store
44 let restored = store.restore(); restoreWarning = restored.warning; storageIssue = restored.warning
45 expeditions = restored.expeditions.map {
46 Expedition(id: $0.header.id, date: $0.header.date, title: $0.header.title, entries: $0.entries,
47 status: $0.wasRunning ? "Paused after restarting — add a direction to continue" : $0.status,
48 isRunning: false, isFinished: $0.isFinished)
49 }
50 activeID = expeditions.last(where: { !$0.isFinished })?.id
51 selectedID = activeID ?? expeditions.last?.id
52 for saved in restored.expeditions where saved.wasRunning {
53 if let expedition = expeditions.first(where: { $0.id == saved.header.id }) { recordState(expedition) }
54 }
55 }
56 func flush() { store?.flush() }
57 func retrySaving() { store?.retry() }
58 private func recordState(_ expedition: Expedition) {
59 store?.append(.init(event: .state, status: expedition.status, isRunning: expedition.isRunning, isFinished: expedition.isFinished), to: expedition.id)
60 }
61 @Published private(set) var revision = 0
62 @Published var followsLatest = true
63 @Published var sidebarVisible = true
64 @Published var toolbarHeight: CGFloat = 52
65 @Published var composerFocusRevision = 0
66 var selected: Expedition? { expeditions.first { $0.id == selectedID } }
67 var entries: [Entry] { selected?.entries ?? [] }
68 var taskTitle: String { selected?.title ?? "Ready for an expedition" }
69 var status: String {
70 get { selected?.status ?? "Ask Jerry to start a new expedition." }
71 set { changeActive { $0.status = newValue } }
72 }
73 var isRunning: Bool {
74 get { expeditions.first { $0.id == activeID }?.isRunning ?? false }
75 set { changeActive { $0.isRunning = newValue } }
76 }
77 private func changeActive(_ change: (inout Expedition) -> Void) {
78 guard let index = expeditions.firstIndex(where: { $0.id == activeID }) else { return }
79 let previous = expeditions[index]
80 change(&expeditions[index]); revision += 1
81 let current = expeditions[index]
82 if previous.status != current.status || previous.isRunning != current.isRunning || previous.isFinished != current.isFinished { recordState(current) }
83 }
84 func select(_ id: UUID) { selectedID = id; followsLatest = true; revision += 1 }
85 func finishActive() {
86 changeActive { $0.isRunning = false; $0.isFinished = true; $0.status = "Expedition finished" }
87 activeID = nil; revision += 1; flush()
88 }
89 func prepareNew() { finishActive(); selectedID = nil; revision += 1 }
90 @discardableResult func continueExpedition(prompt: String, id: UUID? = nil) -> UUID {
91 if let target = id ?? activeID, let index = expeditions.firstIndex(where: { $0.id == target }) {
92 if activeID != target { finishActive() }
93 activeID = target; selectedID = target; expeditions[index].isFinished = false
94 followsLatest = true; revision += 1; recordState(expeditions[index]); return target
95 }
96 finishActive()
97 let expedition = Expedition(id: UUID(), date: Date(), title: "An untitled adventure")
98 expeditions.append(expedition); activeID = expedition.id; selectedID = expedition.id
99 store?.append(.init(event: .created, expedition: .init(id: expedition.id, date: expedition.date, title: expedition.title)), to: expedition.id)
100 followsLatest = true; revision += 1; flush(); return expedition.id
101 }
102 var needsTitle: Bool {
103 guard let expedition = expeditions.first(where: { $0.id == activeID }) else { return false }
104 return expedition.title == "An untitled adventure" || expedition.entries.first(where: { $0.kind == .request }).map { expedition.title == String($0.text.prefix(100)) } == true
105 }
106 func nameExpedition(_ text: String) -> Bool {
107 let title = text.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ").trimmingCharacters(in: .init(charactersIn: "\"“”"))
108 guard needsTitle, !title.isEmpty, title.count <= 70, let id = activeID else { return false }
109 let prompt = expeditions.first(where: { $0.id == id })?.entries.first(where: { $0.kind == .request })?.text
110 if let prompt, prompt.split(whereSeparator: { $0.isWhitespace }).joined(separator: " ").caseInsensitiveCompare(title) == .orderedSame { return false }
111 changeActive { $0.title = title }
112 store?.append(.init(event: .titleChanged, text: title), to: id)
113 return true
114 }
115 @discardableResult func append(_ kind: Kind, _ text: String, details: String = "") -> UUID {
116 if activeID == nil { continueExpedition(prompt: text) }
117 let entry = Entry(id: UUID(), date: Date(), kind: kind, text: text, details: details)
118 changeActive { $0.entries.append(entry) }
119 if let activeID { store?.append(.init(event: .entry, entry: entry), to: activeID) }
120 return entry.id
121 }
122 func savePhoto(_ data: Data, caption: String) async throws {
123 guard let expedition = activeID, let store else { throw AgentConnectionError(message: "A saved expedition is needed for photos.") }
124 let filename = try await store.savePhoto(data, to: expedition)
125 // Capture may finish after an interruption. Keep the photo in its original expedition.
126 guard let index = expeditions.firstIndex(where: { $0.id == expedition }) else { return }
127 let entry = Entry(id: UUID(), date: Date(), kind: .activity, text: String(caption.prefix(300)), details: "Local photograph of Jerry and the task window. Not attached to the AI conversation.", photo: filename)
128 expeditions[index].entries.append(entry); revision += 1
129 store.append(.init(event: .entry, entry: entry), to: expedition)
130 }
131 func photoURL(for entry: Entry) -> URL? {
132 guard let store, let filename = entry.photo, filename.hasSuffix(".jpg"), UUID(uuidString: String(filename.dropLast(4))) != nil,
133 let expedition = expeditions.first(where: { $0.entries.contains(where: { $0.id == entry.id }) }) else { return nil }
134 let folder = store.directory.appendingPathComponent(expedition.id.uuidString)
135 let url = folder.appendingPathComponent(filename)
136 guard (try? folder.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == false,
137 let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isRegularFileKey]), values.isSymbolicLink == false, values.isRegularFile == true else { return nil }
138 return url
139 }
140 func update(_ id: UUID, text: String) {
141 for expedition in expeditions.indices {
142 guard let row = expeditions[expedition].entries.firstIndex(where: { $0.id == id }) else { continue }
143 let previous = expeditions[expedition].entries[row].text
144 if previous != text {
145 expeditions[expedition].entries[row].text = text; revision += 1
146 let appending = text.hasPrefix(previous)
147 store?.append(.init(event: appending ? .textAppended : .textReplaced, entryID: id, text: appending ? String(text.dropFirst(previous.count)) : text), to: expeditions[expedition].id)
148 }
149 return
150 }
151 }
152 func addDetails(_ id: UUID, _ text: String) {
153 for expedition in expeditions.indices {
154 guard let row = expeditions[expedition].entries.firstIndex(where: { $0.id == id }) else { continue }
155 let addition = (expeditions[expedition].entries[row].details.isEmpty ? "" : "\n\n") + text
156 expeditions[expedition].entries[row].details += addition
157 store?.append(.init(event: .detailsAppended, entryID: id, text: addition), to: expeditions[expedition].id)
158 revision += 1; return
159 }
160 }
161 func exportText() -> String {
162 let clock = ISO8601DateFormatter()
163 return expeditions.map { expedition in
164 let entries = expedition.entries.map { entry in
165 let role = entry.kind == .request ? "YOUR INSTRUCTION" : (entry.kind == .response ? "JERRY" : "JOURNAL")
166 return "\(clock.string(from: entry.date)) \(role)\n\(entry.text)" + (entry.photo.map { "\n[Photograph: \(expedition.id.uuidString)/\($0)]" } ?? "") + (entry.details.isEmpty ? "" : "\n\nDETAILS\n\(entry.details)")
167 }.joined(separator: "\n\n────────────────────\n\n")
168 return "EXPEDITION: \(expedition.title)\n\(clock.string(from: expedition.date))\n\n" + entries
169 }.joined(separator: "\n\n════════════════════\n\n")
170 }
171}
172
173/// Shared by the SwiftUI journal and the AppKit welcome/settings notebooks.
174@MainActor
175enum NotebookTheme {
176 static let marginX: CGFloat = 25
177 static let cornerRadius: CGFloat = 12
178 static let paper = NSColor(calibratedRed: 0.98, green: 0.95, blue: 0.86, alpha: 1)
179 static let ink = NSColor(calibratedRed: 0.24, green: 0.29, blue: 0.25, alpha: 1)
180 static let faded = NSColor(calibratedRed: 0.45, green: 0.45, blue: 0.36, alpha: 1)
181 static let leather = NSColor(calibratedRed: 0.38, green: 0.26, blue: 0.17, alpha: 1)
182 static let rust = NSColor(calibratedRed: 0.64, green: 0.32, blue: 0.22, alpha: 1)
183 static func font(_ size: CGFloat, weight: NSFont.Weight = .regular, italic: Bool = false) -> NSFont {
184 let base = NSFont.systemFont(ofSize: size, weight: weight)
185 guard var descriptor = base.fontDescriptor.withDesign(.serif) else { return base }
186 if italic { descriptor = descriptor.withSymbolicTraits(.italic) }
187 return NSFont(descriptor: descriptor, size: size) ?? base
188 }
189 private static let journalFontRegistered: Bool = {
190 guard let url = Bundle.main.url(forResource: "Caveat", withExtension: "ttf") else { return false }
191 return CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)
192 }()
193 static func journalFont(_ size: CGFloat) -> NSFont {
194 _ = journalFontRegistered
195 return NSFont(name: "Caveat-Regular", size: size) ?? font(size)
196 }
197 static func style(_ button: NSButton, primary: Bool = false) {
198 button.bezelStyle = .rounded; button.bezelColor = primary ? ink : leather.withAlphaComponent(0.09)
199 button.contentTintColor = primary ? paper : ink
200 button.font = .systemFont(ofSize: 12, weight: primary ? .medium : .regular)
201 let title = NSAttributedString(string: button.title, attributes: [.foregroundColor: primary ? paper : ink, .font: button.font!])
202 button.attributedTitle = title; button.attributedAlternateTitle = title
203 }
204 /// Keep the native controls clear of the binding and level with the field-note title.
205 static func alignWindowButtons(in content: NSView) {
206 guard let window = content.window else { return }
207 for (index, kind) in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton].enumerated() {
208 guard let button = window.standardWindowButton(kind), let parent = button.superview else { continue }
209 let size = button.frame.size
210 let origin = NSPoint(x: marginX + 12 + CGFloat(index) * 20, y: content.bounds.height - 16 - size.height / 2)
211 let converted = content.convert(origin, to: parent)
212 button.setFrameOrigin(.init(x: converted.x, y: window.toolbar == nil ? converted.y : button.frame.minY))
213 }
214 }
215 static func install(on window: NSWindow, title: String, showsCaption: Bool = true, toolbar: NSToolbar? = nil) -> NSView {
216 window.titleVisibility = .hidden; window.titlebarAppearsTransparent = true
217 window.isOpaque = false; window.backgroundColor = .clear; window.hasShadow = true
218 window.isMovableByWindowBackground = true; window.appearance = NSAppearance(named: .aqua)
219 let root = NotebookPaperView(); root.wantsLayer = true; root.layer?.cornerRadius = cornerRadius; root.layer?.masksToBounds = true
220 window.contentView = root
221 if let toolbar {
222 window.toolbarStyle = .unified; window.toolbar = toolbar
223 let body = NSView(); body.translatesAutoresizingMaskIntoConstraints = false; root.addSubview(body)
224 NSLayoutConstraint.activate([
225 body.topAnchor.constraint(equalTo: (window.contentLayoutGuide as! NSLayoutGuide).topAnchor),
226 body.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 14),
227 body.trailingAnchor.constraint(equalTo: root.trailingAnchor), body.bottomAnchor.constraint(equalTo: root.bottomAnchor)
228 ])
229 return body
230 }
231 let header = NotebookHeaderView(); header.translatesAutoresizingMaskIntoConstraints = false; root.addSubview(header)
232 let caption = NSTextField(labelWithString: "◉ JERRY / " + title.uppercased())
233 caption.isHidden = !showsCaption
234 caption.font = .monospacedSystemFont(ofSize: 10, weight: .medium); caption.textColor = faded
235 caption.translatesAutoresizingMaskIntoConstraints = false; header.addSubview(caption)
236 let body = NSView(); body.translatesAutoresizingMaskIntoConstraints = false; root.addSubview(body)
237 NSLayoutConstraint.activate([
238 header.topAnchor.constraint(equalTo: root.topAnchor), header.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 14), header.trailingAnchor.constraint(equalTo: root.trailingAnchor), header.heightAnchor.constraint(equalToConstant: 44),
239 caption.leadingAnchor.constraint(equalTo: header.leadingAnchor, constant: 94), caption.centerYAnchor.constraint(equalTo: header.topAnchor, constant: 16),
240 body.topAnchor.constraint(equalTo: header.bottomAnchor), body.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 14), body.trailingAnchor.constraint(equalTo: root.trailingAnchor), body.bottomAnchor.constraint(equalTo: root.bottomAnchor)
241 ])
242 return body
243 }
244}
245
246@MainActor
247final class NotebookWindow: NSWindow {
248 override var canBecomeKey: Bool { true }
249 override var canBecomeMain: Bool { true }
250 override func update() {
251 super.update()
252 // AppKit lays out the toolbar after the content view. Apply the paper
253 // inset last, so its native titlebar layout cannot reset the controls.
254 if let contentView { NotebookTheme.alignWindowButtons(in: contentView) }
255 }
256}
257
258private final class NotebookHeaderView: NSView {
259 override var mouseDownCanMoveWindow: Bool { true }
260 override func mouseDown(with event: NSEvent) { window?.performDrag(with: event) }
261}
262
263class NotebookContentView: NSView {
264 var onTitlebarLayout: ((CGFloat) -> Void)?
265 private var previousTitlebarHeight: CGFloat = -1
266 override func layout() {
267 super.layout(); NotebookTheme.alignWindowButtons(in: self)
268 DispatchQueue.main.async { [weak self] in
269 if let self { NotebookTheme.alignWindowButtons(in: self) }
270 }
271 if let window, window.toolbar != nil {
272 let height = max(0, bounds.maxY - convert(window.contentLayoutRect, from: nil).maxY)
273 if abs(height - previousTitlebarHeight) > 0.5 {
274 previousTitlebarHeight = height
275 DispatchQueue.main.async { [weak self] in self?.onTitlebarLayout?(height) }
276 }
277 }
278 }
279}
280
281private final class NotebookPaperView: NotebookContentView {
282 override var mouseDownCanMoveWindow: Bool { true }
283 override func draw(_ dirtyRect: NSRect) {
284 NotebookTheme.paper.setFill(); bounds.fill()
285 NotebookTheme.leather.withAlphaComponent(0.025).setStroke()
286 let fibres = NSBezierPath(); fibres.lineWidth = 0.5
287 for y in stride(from: CGFloat(2), to: bounds.height, by: 4) { fibres.move(to: .init(x: 10, y: y)); fibres.line(to: .init(x: bounds.width, y: y)) }; fibres.stroke()
288 NotebookTheme.rust.withAlphaComponent(0.22).setStroke()
289 let margin = NSBezierPath(); margin.lineWidth = 0.7; margin.move(to: .init(x: NotebookTheme.marginX, y: 0)); margin.line(to: .init(x: NotebookTheme.marginX, y: bounds.height)); margin.stroke()
290 NotebookTheme.leather.setFill(); NSRect(x: 0, y: 0, width: 10, height: bounds.height).fill()
291 NotebookTheme.paper.withAlphaComponent(0.5).setStroke()
292 let stitches = NSBezierPath(); stitches.lineWidth = 1
293 for y in stride(from: CGFloat(12), to: bounds.height, by: 10) { stitches.move(to: .init(x: 5, y: y)); stitches.line(to: .init(x: 5, y: y + 4)) }; stitches.stroke()
294 NotebookTheme.leather.withAlphaComponent(0.25).setStroke()
295 NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: NotebookTheme.cornerRadius, yRadius: NotebookTheme.cornerRadius).stroke()
296 }
297}
298
299@MainActor
300private enum JournalPalette {
301 static let paper = Color(nsColor: NotebookTheme.paper)
302 static let ink = Color(nsColor: NotebookTheme.ink)
303 static let faded = Color(nsColor: NotebookTheme.faded)
304 static let leather = Color(nsColor: NotebookTheme.leather)
305 static let rust = Color(nsColor: NotebookTheme.rust)
306}
307
308struct ExpeditionJournalView: View {
309 @ObservedObject var journal: ExpeditionJournal
310 let stop: () -> Void
311 let send: (String, UUID?) -> Void
312 @State private var instruction = ""
313 @FocusState private var composing: Bool
314 private var leadingInset: CGFloat { journal.sidebarVisible ? 20 : 36 }
315
316 var body: some View {
317 VStack(spacing: 0) {
318 Color.clear.frame(height: journal.toolbarHeight)
319 HStack(spacing: 0) {
320 if journal.sidebarVisible {
321 sidebar
322 .overlay(alignment: .trailing) {
323 Rectangle().fill(JournalPalette.leather.opacity(0.15)).frame(width: 1)
324 .padding(.top, -journal.toolbarHeight).allowsHitTesting(false)
325 }
326 .transition(.move(edge: .leading))
327 }
328 VStack(spacing: 0) { pages; composer }
329 .frame(maxWidth: .infinity, maxHeight: .infinity)
330 }
331 .animation(.easeInOut(duration: 0.2), value: journal.sidebarVisible)
332 }
333 .font(Font(NotebookTheme.journalFont(17)))
334 .foregroundStyle(JournalPalette.ink)
335 .background(notebookPaper)
336 .clipShape(RoundedRectangle(cornerRadius: NotebookTheme.cornerRadius))
337 .overlay { RoundedRectangle(cornerRadius: NotebookTheme.cornerRadius).strokeBorder(JournalPalette.leather.opacity(0.22), lineWidth: 1).allowsHitTesting(false) }
338 .ignoresSafeArea(.container, edges: .top)
339 .frame(minWidth: journal.sidebarVisible ? 560 : 360, minHeight: 380)
340 .environment(\.colorScheme, .light)
341 .tint(JournalPalette.ink)
342 }
343 private var sidebar: some View {
344 VStack(alignment: .leading, spacing: 10) {
345 Text("Expeditions").font(Font(NotebookTheme.journalFont(14))).tracking(0.4)
346 .foregroundStyle(JournalPalette.faded).padding(.horizontal, 9)
347 ScrollView {
348 LazyVStack(alignment: .leading, spacing: 4) {
349 if journal.expeditions.isEmpty {
350 Text("No expeditions yet").font(Font(NotebookTheme.journalFont(17))).italic()
351 .foregroundStyle(JournalPalette.faded).padding(9)
352 }
353 ForEach(journal.expeditions.reversed()) { expedition in
354 Button { journal.select(expedition.id); instruction = "" } label: {
355 VStack(alignment: .leading, spacing: 5) {
356 Text(expedition.title).font(Font(NotebookTheme.journalFont(17)))
357 .lineLimit(2).multilineTextAlignment(.leading)
358 HStack(spacing: 5) {
359 if expedition.id == journal.activeID {
360 Circle().fill(expedition.isRunning ? JournalPalette.rust : JournalPalette.ink).frame(width: 4, height: 4)
361 }
362 Text(expedition.date, format: .dateTime.day().month(.abbreviated).hour().minute())
363 .font(Font(NotebookTheme.journalFont(13)))
364 }.foregroundStyle(JournalPalette.faded)
365 }.frame(maxWidth: .infinity, alignment: .leading).padding(8)
366 .background(journal.selectedID == expedition.id ? JournalPalette.leather.opacity(0.09) : .clear, in: RoundedRectangle(cornerRadius: 7))
367 }.buttonStyle(.plain).help(expedition.title)
368 }
369 }
370 }.scrollIndicators(.hidden)
371 }.padding(.leading, 28).padding(.trailing, 10).padding(.vertical, 14).frame(width: 176)
372 .frame(maxHeight: .infinity).background(JournalPalette.leather.opacity(0.025))
373 }
374 private var pages: some View {
375 GeometryReader { viewport in
376 ScrollViewReader { proxy in
377 ScrollView {
378 LazyVStack(alignment: .leading, spacing: 20) {
379 if let expedition = journal.selected {
380 Text(expedition.date, format: .dateTime.weekday(.wide).day().month(.wide))
381 .font(Font(NotebookTheme.journalFont(14))).foregroundStyle(JournalPalette.faded)
382 ForEach(expedition.entries) { entry in
383 JournalEntryView(entry: entry, photoURL: journal.photoURL(for: entry), pauseFollowing: { journal.followsLatest = false }).id(entry.id)
384 }
385 if expedition.isRunning {
386 HStack(spacing: 8) {
387 ProgressView().controlSize(.small)
388 Text("Jerry is working…").font(Font(NotebookTheme.journalFont(17))).italic()
389 }.foregroundStyle(JournalPalette.faded)
390 } else if expedition.isFinished || expedition.status != "Ready for your next direction" {
391 Text(expedition.status).font(Font(NotebookTheme.journalFont(17))).italic().foregroundStyle(JournalPalette.faded)
392 }
393 } else {
394 VStack(alignment: .leading, spacing: 9) {
395 Text("A new expedition").font(Font(NotebookTheme.journalFont(29))).italic()
396 Text("Where shall we go?").font(Font(NotebookTheme.journalFont(18))).foregroundStyle(JournalPalette.faded)
397 }.padding(.top, 14)
398 }
399 if let issue = journal.storageIssue {
400 HStack(alignment: .top, spacing: 10) {
401 Text(issue).font(Font(NotebookTheme.journalFont(17)))
402 if journal.saveFailed { Button("Retry saving") { journal.retrySaving() }.buttonStyle(.link) }
403 }.foregroundStyle(JournalPalette.rust)
404 }
405 Color.clear.frame(height: 1).id("journal-bottom")
406 }
407 .frame(maxWidth: 640, alignment: .leading)
408 .frame(maxWidth: .infinity)
409 .padding(.leading, leadingInset).padding(.trailing, 20).padding(.vertical, 18)
410 .background {
411 GeometryReader { geometry in
412 Color.clear.preference(key: JournalLegacyScrollKey.self, value: .init(bottom: geometry.frame(in: .named("journal-scroll")).maxY, height: geometry.size.height))
413 }
414 }
415 }
416 .coordinateSpace(name: "journal-scroll")
417 .accessibilityValue(journal.followsLatest ? "Following latest" : "Reading earlier entries")
418 .modifier(JournalScrollTracking(followsLatest: $journal.followsLatest, viewportHeight: viewport.size.height, pin: { proxy.scrollTo("journal-bottom", anchor: .bottom) }))
419 .onChange(of: journal.revision) { _, _ in
420 if journal.followsLatest && journal.selectedID == journal.activeID { proxy.scrollTo("journal-bottom", anchor: .bottom) }
421 }
422 .onChange(of: journal.selectedID) { _, _ in proxy.scrollTo("journal-bottom", anchor: .bottom) }
423 }
424 }.clipped()
425 }
426 private var composer: some View {
427 HStack(spacing: 9) {
428 TextField(journal.selected == nil ? "Give Jerry a mission…" : (journal.selectedID == journal.activeID ? "Add a direction…" : "Resume this expedition…"), text: $instruction)
429 .textFieldStyle(.plain).font(.custom("Courier", size: 12))
430 .focused($composing).onSubmit(submitInstruction)
431 .onChange(of: journal.composerFocusRevision) { _, _ in instruction = ""; composing = true }
432 .onChange(of: instruction) { _, text in if !text.isEmpty && journal.isRunning { stop() } }
433 .accessibilityLabel("Expedition instruction")
434 Button(action: submitInstruction) { Image(systemName: "arrow.up.circle.fill").font(.system(size: 24)) }
435 .buttonStyle(.plain).disabled(instruction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty).accessibilityLabel("Send expedition instruction")
436 }
437 .padding(.horizontal, 11).padding(.vertical, 10)
438 .background(JournalPalette.ink.opacity(0.04), in: RoundedRectangle(cornerRadius: 8))
439 .overlay { RoundedRectangle(cornerRadius: 8).strokeBorder(JournalPalette.ink.opacity(composing ? 0.32 : 0.13), lineWidth: 1) }
440 .frame(maxWidth: 640).frame(maxWidth: .infinity)
441 .padding(.leading, leadingInset).padding(.trailing, 20).padding(.top, 10).padding(.bottom, 14)
442 }
443 private var notebookPaper: some View {
444 ZStack(alignment: .leading) {
445 JournalPalette.paper
446 Canvas { context, size in
447 for y in stride(from: 2.0, to: size.height, by: 4) {
448 var fibre = Path(); fibre.move(to: .init(x: 12, y: y)); fibre.addLine(to: .init(x: size.width, y: y))
449 context.stroke(fibre, with: .color(JournalPalette.leather.opacity(0.025)), lineWidth: 0.5)
450 }
451 var margin = Path(); margin.move(to: .init(x: NotebookTheme.marginX, y: 0)); margin.addLine(to: .init(x: NotebookTheme.marginX, y: size.height))
452 context.stroke(margin, with: .color(JournalPalette.rust.opacity(0.22)), lineWidth: 0.7)
453 }.allowsHitTesting(false)
454 Rectangle().fill(JournalPalette.leather.gradient).frame(width: 10)
455 Canvas { context, size in
456 for y in stride(from: 12.0, to: size.height, by: 10) {
457 var stitch = Path(); stitch.move(to: .init(x: 5, y: y)); stitch.addLine(to: .init(x: 5, y: y + 4))
458 context.stroke(stitch, with: .color(JournalPalette.paper.opacity(0.5)), lineWidth: 1)
459 }
460 }.frame(width: 10).allowsHitTesting(false)
461 }
462 }
463 private func submitInstruction() {
464 let value = instruction.trimmingCharacters(in: .whitespacesAndNewlines)
465 guard !value.isEmpty else { return }
466 composing = false; send(value, journal.selectedID); instruction = ""
467 }
468}
469
470private struct JournalLegacyScrollPosition: Equatable {
471 var bottom: CGFloat = 0
472 var height: CGFloat = 0
473}
474private struct JournalLegacyScrollKey: PreferenceKey {
475 static let defaultValue = JournalLegacyScrollPosition()
476 static func reduce(value: inout JournalLegacyScrollPosition, nextValue: () -> JournalLegacyScrollPosition) { value = nextValue() }
477}
478private struct JournalScrollMetrics: Equatable {
479 var nearBottom: Bool
480 var contentHeight: CGFloat
481 var viewportHeight: CGFloat
482 var viewportWidth: CGFloat
483 var offset: CGFloat
484}
485private struct JournalScrollTracking: ViewModifier {
486 @Binding var followsLatest: Bool
487 let viewportHeight: CGFloat
488 let pin: () -> Void
489 @State private var userScrolling = false
490 @State private var previousLegacyHeight: CGFloat = 0
491 func body(content: Content) -> some View {
492 if #available(macOS 15.0, *) {
493 content
494 .onScrollPhaseChange { _, phase in userScrolling = phase == .tracking || phase == .interacting || phase == .decelerating }
495 .onScrollGeometryChange(for: JournalScrollMetrics.self) { geometry in
496 .init(nearBottom: geometry.contentSize.height - geometry.contentOffset.y - geometry.containerSize.height < 80, contentHeight: geometry.contentSize.height, viewportHeight: geometry.containerSize.height, viewportWidth: geometry.containerSize.width, offset: geometry.contentOffset.y)
497 } action: { old, new in
498 let movedUp = new.offset < old.offset - 0.5 && abs(new.contentHeight - old.contentHeight) < 0.5
499 && new.viewportHeight == old.viewportHeight && new.viewportWidth == old.viewportWidth
500 if new.nearBottom { followsLatest = true }
501 else if userScrolling || movedUp { followsLatest = false }
502 if followsLatest && (old.contentHeight != new.contentHeight || old.viewportHeight != new.viewportHeight) { pin() }
503 }
504 } else {
505 content.onPreferenceChange(JournalLegacyScrollKey.self) { position in
506 let nearBottom = position.bottom < viewportHeight + 80
507 let contentChanged = abs(position.height - previousLegacyHeight) > 0.5
508 if nearBottom || !contentChanged { followsLatest = nearBottom }
509 previousLegacyHeight = position.height
510 if followsLatest && contentChanged { pin() }
511 }
512 }
513 }
514}
515
516private struct JournalEntryView: View {
517 let entry: ExpeditionJournal.Entry
518 let photoURL: URL?
519 let pauseFollowing: () -> Void
520 @State private var expanded = false
521 var body: some View {
522 VStack(alignment: .leading, spacing: 8) {
523 entryPaper
524 if !entry.details.isEmpty {
525 DisclosureGroup(isExpanded: $expanded) {
526 ScrollView {
527 Text(entry.details).font(.custom("Courier", size: 11)).textSelection(.enabled)
528 .frame(maxWidth: .infinity, alignment: .leading).padding(10)
529 }.frame(maxHeight: 180)
530 .background { JournalPaperCutout().fill(.white).shadow(color: .black.opacity(0.12), radius: 2, x: 1, y: 2) }
531 .overlay(alignment: .topTrailing) {
532 JournalTape().frame(width: 43, height: 15).rotationEffect(.degrees(11)).offset(x: -14, y: -6)
533 }
534 .padding(.vertical, 10)
535 } label: { Text("Details").font(.custom("Courier", size: 11)).foregroundStyle(JournalPalette.faded) }
536 .onChange(of: expanded) { _, opened in if opened { pauseFollowing() } }
537 }
538 }
539 }
540 private var entryPaper: some View {
541 VStack(alignment: .leading, spacing: 8) {
542 HStack {
543 Text(entry.photo != nil ? "A memento" : (entry.kind == .request ? "Your direction" : (entry.kind == .response ? "Jerry’s notes" : "On the trail")))
544 .font(Font(NotebookTheme.journalFont(14))).tracking(0.3)
545 Spacer()
546 Text(entry.date, format: .dateTime.hour().minute()).font(Font(NotebookTheme.journalFont(13)))
547 }.foregroundStyle(JournalPalette.faded)
548 if entry.photo != nil {
549 VStack(spacing: 0) {
550 JournalPhotograph(url: photoURL, caption: entry.text)
551 .overlay(Rectangle().stroke(.black.opacity(0.12), lineWidth: 0.5))
552 Text(entry.text).font(Font(NotebookTheme.journalFont(19))).foregroundStyle(JournalPalette.ink)
553 .frame(maxWidth: .infinity, minHeight: 62, alignment: .topLeading)
554 .padding(.horizontal, 4).padding(.top, 8).padding(.bottom, 10).textSelection(.enabled)
555 }
556 .padding([.top, .horizontal], 12).frame(maxWidth: 320)
557 .background(Color(red: 1, green: 0.995, blue: 0.975))
558 .overlay(Rectangle().stroke(JournalPalette.leather.opacity(0.16), lineWidth: 0.5))
559 // Flatten the opaque print before shadowing: otherwise SwiftUI
560 // can shadow the photo and handwriting as separate descendants.
561 .compositingGroup()
562 .shadow(color: .black.opacity(0.15), radius: 4, x: 1, y: 3)
563 .overlay(alignment: .top) {
564 JournalTape().frame(width: 54, height: 18).rotationEffect(.degrees(-5)).offset(y: -8)
565 }
566 .rotationEffect(.degrees(-1.7))
567 .padding(.horizontal, 10).padding(.vertical, 14)
568 } else { Group {
569 if entry.kind == .response { Text(.init(entry.text)) }
570 else { Text(entry.text) }
571 }
572 .font(entry.kind == .request ? .custom("Courier", size: 12) : Font(NotebookTheme.journalFont(18))).lineSpacing(4).textSelection(.enabled)
573 .foregroundStyle(entry.kind == .activity ? JournalPalette.faded : JournalPalette.ink)
574 .frame(maxWidth: .infinity, alignment: .leading)
575 if entry.kind == .response {
576 Text("— Jerry").font(Font(NotebookTheme.journalFont(20))).foregroundStyle(JournalPalette.faded)
577 }
578 }
579
580 }
581 .padding(entry.kind == .request ? 14 : 0)
582 .background {
583 if entry.kind == .request {
584 JournalPaperCutout().fill(Color(red: 1, green: 0.998, blue: 0.985))
585 .shadow(color: .black.opacity(0.12), radius: 2, x: 0.5, y: 2)
586 }
587 }
588 .overlay(alignment: .topLeading) {
589 if entry.kind == .request {
590 JournalTape().frame(width: 46, height: 16).rotationEffect(.degrees(-13)).offset(x: 15, y: -7)
591 }
592 }
593 .overlay(alignment: .bottomTrailing) {
594 if entry.kind == .request {
595 JournalTape().frame(width: 42, height: 16).rotationEffect(.degrees(-9)).offset(x: -13, y: 6)
596 }
597 }
598 .padding(.vertical, entry.kind == .request ? 9 : 0)
599 }
600}
601
602/// Read photo bytes off the main thread, once per asset rather than on every streamed token.
603private struct JournalPhotograph: View {
604 let url: URL?
605 let caption: String
606 @State private var image: NSImage?
607 @State private var loaded = false
608 var body: some View {
609 GeometryReader { geometry in
610 Group {
611 if let image {
612 Image(nsImage: image).resizable().aspectRatio(contentMode: .fill)
613 .accessibilityLabel("Expedition photograph: " + caption)
614 } else {
615 Label(loaded ? "Photograph unavailable" : "Developing photograph…", systemImage: "photo")
616 .font(Font(NotebookTheme.journalFont(17))).foregroundStyle(JournalPalette.faded)
617 }
618 }
619 .frame(width: geometry.size.width, height: geometry.size.height)
620 .clipped()
621 }.aspectRatio(1, contentMode: .fit)
622 .background(JournalPalette.ink.opacity(0.025))
623 .task(id: url) {
624 let data = await Task.detached(priority: .utility) { url.flatMap { try? Data(contentsOf: $0) } }.value
625 guard !Task.isCancelled else { return }
626 image = data.flatMap { NSImage(data: $0) }; loaded = true
627 }
628 }
629}
630
631/// Translucent tape with uneven cut ends and a small reflected crease.
632private struct JournalTape: View {
633 var body: some View {
634 GeometryReader { geometry in
635 let size = geometry.size
636 Path { path in
637 path.move(to: .init(x: 1, y: 0)); path.addLine(to: .init(x: size.width - 1, y: 0.7))
638 path.addLine(to: .init(x: size.width - 2, y: size.height * 0.3))
639 path.addLine(to: .init(x: size.width, y: size.height * 0.55))
640 path.addLine(to: .init(x: size.width - 1, y: size.height))
641 path.addLine(to: .init(x: 0, y: size.height - 0.5))
642 path.addLine(to: .init(x: 1.5, y: size.height * 0.6))
643 path.addLine(to: .init(x: 0, y: size.height * 0.3)); path.closeSubpath()
644 }.fill(LinearGradient(colors: [Color(red: 0.88, green: 0.83, blue: 0.62).opacity(0.48), Color.white.opacity(0.35), Color(red: 0.82, green: 0.76, blue: 0.55).opacity(0.45)], startPoint: .topLeading, endPoint: .bottomTrailing))
645 Rectangle().fill(.white.opacity(0.3)).frame(height: 0.5).offset(y: 2)
646 }.allowsHitTesting(false).accessibilityHidden(true)
647 }
648}
649
650private struct JournalPaperCutout: Shape {
651 func path(in rect: CGRect) -> Path {
652 Path { path in
653 path.move(to: .init(x: 0.5, y: 0.5))
654 path.addLine(to: .init(x: rect.width * 0.4, y: 0)); path.addLine(to: .init(x: rect.maxX, y: 0.8))
655 path.addLine(to: .init(x: rect.maxX - 0.5, y: rect.maxY)); path.addLine(to: .init(x: rect.width * 0.6, y: rect.maxY - 0.7))
656 path.addLine(to: .init(x: 0, y: rect.maxY)); path.closeSubpath()
657 }
658 }
659}