-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathNotebookViewController.swift
More file actions
591 lines (526 loc) · 23 KB
/
Copy pathNotebookViewController.swift
File metadata and controls
591 lines (526 loc) · 23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
// Copyright (c) 2018-2026 Brian Dewey. Covered by the Apache 2.0 license.
import BookKit
import LibraryNotesCore
import os
import SnapKit
import UIKit
public extension UIViewController {
/// Walks up parent view controllers to find one that is a NotebookViewController.
var notebookViewController: NotebookViewController? {
findParent(where: { $0 is NotebookViewController }) as? NotebookViewController
}
func findParent(where predicate: (UIViewController) -> Bool) -> UIViewController? {
var currentViewController: UIViewController? = self
while currentViewController != nil {
// See the line above, we know this is non-nil
if predicate(currentViewController!) {
return currentViewController
}
currentViewController = currentViewController?.parent ?? currentViewController?.presentingViewController
}
return nil
}
}
/// Manages the UISplitViewController that shows the contents of a notebook. It's a three-column design:
/// - primary: The overall notebook structure (currently based around hashtags)
/// - supplementary: A list of notes
/// - secondary: An individual note
public final class NotebookViewController: UISplitViewController {
init(database: NoteDatabase) {
self.database = database
self.coverImageCache = CoverImageCache(database: database)
self.documentListViewController = DocumentListViewController(database: database, coverImageCache: coverImageCache)
super.init(style: .tripleColumn)
let supplementaryNavigationController = UINavigationController.notebookNavigationController(rootViewController: documentListViewController, prefersLargeTitles: true)
setViewController(primaryNavigationController, for: .primary)
setViewController(supplementaryNavigationController, for: .supplementary)
setViewController(
UINavigationController.notebookNavigationController(rootViewController: SavingTextEditViewController(database: database, coverImageCache: coverImageCache, containsOnlyDefaultContent: true)),
for: .secondary
)
setViewController(compactNavigationController, for: .compact)
primaryBackgroundStyle = .sidebar
preferredPrimaryColumnWidth = 240
preferredSupplementaryColumnWidth = 340
preferredDisplayMode = .twoBesideSecondary
showsSecondaryOnlyButton = true
delegate = self
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// The notebook we are viewing
private let database: NoteDatabase
/// Global cache
private let coverImageCache: CoverImageCache
public var fileURL: URL { database.fileURL }
/// What are we viewing in the current structure?
// TODO: Get rid of this copy, just read from documentListViewController
private var focusedNotebookStructure: NotebookStructureViewController.StructureIdentifier = .read {
didSet {
documentListViewController.focusedStructure = focusedNotebookStructure
if isCollapsed {
let compactListViewController = DocumentListViewController(database: database, coverImageCache: coverImageCache)
compactListViewController.focusedStructure = focusedNotebookStructure
compactNavigationController.pushViewController(compactListViewController, animated: true)
}
}
}
public func setSecondaryViewController(_ viewController: NotebookSecondaryViewController, pushIfCollapsed: Bool) {
if isCollapsed {
if pushIfCollapsed {
if compactNavigationController.viewControllers.count < 3 {
compactNavigationController.pushViewController(viewController, animated: true)
} else {
compactNavigationController.popToViewController(compactNavigationController.viewControllers[1], animated: true)
compactNavigationController.pushViewController(viewController, animated: true)
}
}
} else {
setViewController(UINavigationController.notebookNavigationController(rootViewController: viewController), for: .secondary)
}
}
public func pushSecondaryViewController(_ viewController: UIViewController) {
if isCollapsed {
compactNavigationController.pushViewController(viewController, animated: true)
} else {
setViewController(viewController, for: .secondary)
}
}
#if targetEnvironment(macCatalyst)
private lazy var primaryNavigationController = UINavigationController.notebookNavigationController(
rootViewController: structureViewController,
barTintColor: nil,
prefersLargeTitles: false
)
#else
private lazy var primaryNavigationController = UINavigationController.notebookNavigationController(
rootViewController: structureViewController,
barTintColor: .grailBackground,
prefersLargeTitles: false
)
#endif
private lazy var structureViewController = makeStructureViewController()
private func makeStructureViewController() -> NotebookStructureViewController {
let structureViewController = NotebookStructureViewController(
database: documentListViewController.database
)
structureViewController.delegate = self
return structureViewController
}
/// A list of notes inside the notebook, displayed in the supplementary column
private let documentListViewController: DocumentListViewController
private lazy var compactNavigationController = UINavigationController.notebookNavigationController(rootViewController: makeStructureViewController(), prefersLargeTitles: true)
override public func viewDidLoad() {
super.viewDidLoad()
configureKeyCommands()
}
override public var canBecomeFirstResponder: Bool { true }
private var isFirstAppearance = true
private var hasAppeared = false
private var pendingNoteNavigation: (noteIdentifier: Note.Identifier, selectedText: String)?
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
hasAppeared = true
if isFirstAppearance {
isFirstAppearance = false
documentListViewController.becomeFirstResponder()
}
if let pendingNoteNavigation {
self.pendingNoteNavigation = nil
navigateToNoteAfterAppearance(
pendingNoteNavigation.noteIdentifier,
selectedText: pendingNoteNavigation.selectedText
)
}
}
func pushNoteWhenVisible(with noteIdentifier: Note.Identifier, selectedText: String) {
if hasAppeared {
navigateToNoteAfterAppearance(noteIdentifier, selectedText: selectedText)
} else {
pendingNoteNavigation = (noteIdentifier, selectedText)
}
}
private func navigateToNoteAfterAppearance(_ noteIdentifier: Note.Identifier, selectedText: String) {
DispatchQueue.main.async { [weak self] in
guard let self else { return }
Logger.shared.info(
"Navigating to widget quote after notebook appearance: isCollapsed=\(self.isCollapsed), horizontalSizeClass=\(String(describing: self.traitCollection.horizontalSizeClass))"
)
pushNote(with: noteIdentifier, selectedText: selectedText)
}
}
private func configureKeyCommands() {
let focusTagsCommand = UIKeyCommand(
title: "View Tags",
action: #selector(tagsBecomeFirstResponder),
input: "1",
modifierFlags: [.command]
)
addKeyCommand(focusTagsCommand)
let focusNotesCommand = UIKeyCommand(
title: "View Notes",
action: #selector(notesBecomeFirstResponder),
input: "2",
modifierFlags: [.command]
)
addKeyCommand(focusNotesCommand)
let searchKeyCommand = UIKeyCommand(
title: "Find",
action: #selector(searchBecomeFirstResponder),
input: "f",
modifierFlags: [.command]
)
addKeyCommand(searchKeyCommand)
let toggleEditModeCommand = UIKeyCommand(
title: "Toggle Edit Mode",
action: #selector(toggleEditMode),
input: "\r",
modifierFlags: [.command]
)
addKeyCommand(toggleEditModeCommand)
}
@objc func searchBecomeFirstResponder() {
show(.supplementary)
documentListViewController.searchBecomeFirstResponder()
}
@objc func tagsBecomeFirstResponder() {
show(.primary)
structureViewController.becomeFirstResponder()
}
@objc func notesBecomeFirstResponder() {
show(.supplementary)
documentListViewController.becomeFirstResponder()
}
@objc func toggleEditMode() {
assertionFailure("Not implemented")
// if currentNoteEditor?.isEditing ?? false {
// currentNoteEditor?.isEditing = false
// } else {
// UIView.animate(withDuration: 0.2) { [notebookSplitViewController] in
// notebookSplitViewController.preferredDisplayMode = .secondaryOnly
// } completion: { [currentNoteEditor] success in
// if success { _ = currentNoteEditor?.editEndOfDocument() }
// }
// }
}
@objc func makeNewNoteFromBarButtonItem(sender: UIBarButtonItem) {
makeNewNote(sender: sender)
}
@objc func makeNewNote(sender: Any? = nil) {
if let apiKey = ApiKey.googleBooks, !apiKey.isEmpty {
let bookSearchViewController = BookEditDetailsViewController(apiKey: apiKey, showSkipButton: true)
bookSearchViewController.delegate = self
bookSearchViewController.title = "Add Book"
let navigationController = UINavigationController(rootViewController: bookSearchViewController)
navigationController.navigationBar.tintColor = .grailTint
navigationController.modalPresentationStyle = .formSheet
if #available(iOS 26.0, *), let sender = sender as? UIBarButtonItem {
navigationController.preferredTransition = .zoom { _ in sender }
}
present(navigationController, animated: true)
} else {
createAndNavigateToNewNote()
}
}
func createAndNavigateToNewNote() {
let hashtag = focusedNotebookStructure.hashtag
let folder = focusedNotebookStructure.predefinedFolder
let (text, offset) = Note.makeBlankNoteText(hashtag: hashtag)
var note = Note(markdown: text)
note.metadata.folder = folder?.rawValue
let viewController = SavingTextEditViewController(
note: note,
database: database,
coverImageCache: coverImageCache,
containsOnlyDefaultContent: true,
initialSelectedRange: NSRange(location: offset, length: 0),
autoFirstResponder: true
)
setSecondaryViewController(viewController, pushIfCollapsed: true)
Logger.shared.info("Created a new view controller for a blank document")
}
override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(editOrInsertBookDetails) {
return secondaryViewController is SavingTextEditViewController
} else {
return super.canPerformAction(action, withSender: sender)
}
}
/// Forward the `editOrInsertBookDetails` selector to the active `SavingTextEditViewController`, if it is visible in the window.
///
/// This is to enable the "info" toolbar button to work even when the editor window doesn't have focus, but something else in the notebook does.
@objc private func editOrInsertBookDetails(sender: UIBarButtonItem) {
guard let editor = secondaryViewController as? SavingTextEditViewController else {
return
}
editor.editOrInsertBookDetails(sender: sender)
}
public static func makeNewNoteButtonItem() -> UIBarButtonItem {
UIBarButtonItem(
title: "New book",
image: UIImage(systemName: "plus"),
target: nil,
action: #selector(makeNewNoteFromBarButtonItem)
)
}
func showNoteEditor(noteIdentifier: Note.Identifier?, note: Note, shiftFocus: Bool) {
let actualNoteIdentifier = noteIdentifier ?? UUID().uuidString
let noteViewController = SavingTextEditViewController(
noteIdentifier: actualNoteIdentifier,
note: note,
database: database,
coverImageCache: coverImageCache,
containsOnlyDefaultContent: false
)
setSecondaryViewController(noteViewController, pushIfCollapsed: shiftFocus)
}
// MARK: - State restoration
private enum ActivityKey {
static let notebookStructure = "org.brians-brain.GrailDiary.NotebookStructure"
static let displayMode = "org.brians-brain.GrailDiary.notebookSplitViewController.displayMode"
static let secondaryViewControllerType = "org.brians-brain.GrailDiary.notebookSplitViewController.secondaryType"
static let secondaryViewControllerData = "org.brians-brain.GrailDiary.notebookSplitViewController.secondaryData"
}
func updateUserActivity(_ userActivity: NSUserActivity) {
userActivity.addUserInfoEntries(from: [
ActivityKey.notebookStructure: focusedNotebookStructure.rawValue,
ActivityKey.displayMode: displayMode.rawValue,
])
structureViewController.updateUserActivity(userActivity)
if let secondaryViewController {
do {
let controllerType = type(of: secondaryViewController).notebookDetailType
try userActivity.addUserInfoEntries(
from: [
ActivityKey.secondaryViewControllerType: controllerType,
ActivityKey.secondaryViewControllerData: secondaryViewController.userActivityData(),
]
)
} catch {
Logger.shared.error("Unexpected error saving secondary VC: \(error)")
}
}
}
var secondaryViewController: NotebookSecondaryViewController? {
secondaryViewController(forCollaped: isCollapsed)
}
func secondaryViewController(forCollaped collapsed: Bool) -> NotebookSecondaryViewController? {
if collapsed {
if compactNavigationController.viewControllers.count >= 3 {
return compactNavigationController.topViewController as? NotebookSecondaryViewController
} else {
return nil
}
} else if let navigationController = viewController(for: .secondary) as? UINavigationController {
return navigationController.viewControllers.first as? NotebookSecondaryViewController
}
return nil
}
func configure(with userActivity: NSUserActivity) {
if
let structureString = userActivity.userInfo?[ActivityKey.notebookStructure] as? String,
let focusedNotebookStructure = NotebookStructureViewController.StructureIdentifier(rawValue: structureString)
{
self.focusedNotebookStructure = focusedNotebookStructure
}
if let rawDisplayMode = userActivity.userInfo?[ActivityKey.displayMode] as? Int,
let displayMode = UISplitViewController.DisplayMode(rawValue: rawDisplayMode)
{
preferredDisplayMode = displayMode
}
structureViewController.configure(with: userActivity)
if let secondaryViewControllerType = userActivity.userInfo?[ActivityKey.secondaryViewControllerType] as? String,
let secondaryViewControllerData = userActivity.userInfo?[ActivityKey.secondaryViewControllerData] as? Data
{
do {
let secondaryViewController = try NotebookSecondaryViewControllerRegistry.shared.reconstruct(
type: secondaryViewControllerType,
data: secondaryViewControllerData,
database: database,
coverImageCache: coverImageCache
)
setSecondaryViewController(secondaryViewController, pushIfCollapsed: true)
} catch {
Logger.shared.error("Error recovering secondary view controller: \(error)")
}
}
}
}
public extension NotebookViewController {
func pushNote(with noteIdentifier: Note.Identifier, selectedText: String? = nil, autoFirstResponder: Bool = false) {
Logger.shared.info("Handling openNoteCommand. Note id = \(noteIdentifier)")
do {
let note = try database.note(noteIdentifier: noteIdentifier)
let rawText = note.text ?? ""
let initialRange: NSRange?
if let selectedText {
let matchingRange = (rawText as NSString).range(of: selectedText)
if matchingRange.location == NSNotFound {
Logger.shared.warning("Could not find requested text in note \(noteIdentifier)")
initialRange = nil
} else {
Logger.shared.info(
"Found requested text in note \(noteIdentifier): rawTextLength=\((rawText as NSString).length), selectedTextLength=\((selectedText as NSString).length), range=\(matchingRange.location)..<\(matchingRange.upperBound)"
)
initialRange = matchingRange
}
} else {
initialRange = nil
}
let noteViewController = SavingTextEditViewController(
noteIdentifier: noteIdentifier,
note: note,
database: database,
coverImageCache: coverImageCache,
containsOnlyDefaultContent: false,
initialSelectedRange: initialRange,
autoFirstResponder: autoFirstResponder
)
setSecondaryViewController(noteViewController, pushIfCollapsed: true)
// TODO: Figure out how to make a "push" make sense in a split view controller
// pushSecondaryViewController(noteViewController)
documentListViewController.selectPage(with: noteIdentifier)
} catch {
Logger.shared.error("Unexpected error getting note \(noteIdentifier): \(error)")
}
}
}
// MARK: - WebScrapingViewControllerDelegate
extension NotebookViewController: WebScrapingViewControllerDelegate {
public func webScrapingViewController(_ viewController: WebScrapingViewController, didScrapeMarkdown markdown: String) {
dismiss(animated: true, completion: nil)
Logger.shared.info("Creating a new page with markdown: \(markdown)")
let (text, offset) = Note.makeBlankNoteText(title: markdown, hashtag: focusedNotebookStructure.hashtag)
var note = Note(markdown: text)
note.metadata.folder = focusedNotebookStructure.predefinedFolder?.rawValue
// TODO: I'm abusing the "title" parameter here
let viewController = SavingTextEditViewController(
note: note,
database: database,
coverImageCache: coverImageCache,
containsOnlyDefaultContent: false,
initialSelectedRange: NSRange(location: offset, length: 0),
autoFirstResponder: true
)
setSecondaryViewController(viewController, pushIfCollapsed: true)
Logger.shared.info("Created a new view controller for a book!")
}
public func webScrapingViewControllerDidCancel(_ viewController: WebScrapingViewController) {
dismiss(animated: true, completion: nil)
}
}
// MARK: - BookSearchViewControllerDelegate
extension NotebookViewController: BookEditDetailsViewControllerDelegate {
public func bookSearchViewController(_ viewController: BookEditDetailsViewController, didSelect book: AugmentedBook, coverImage: UIImage?) {
dismiss(animated: true, completion: nil)
var note = Note(markdown: "")
note.metadata.book = book
do {
let identifier = try database.createNote(note)
if let image = coverImage, let imageData = image.jpegData(compressionQuality: 0.8) {
try NoteScopedImageStorage(identifier: identifier, database: database).storeCoverImage(imageData, type: .jpeg)
}
let viewController = SavingTextEditViewController(
noteIdentifier: identifier,
note: note,
database: database,
coverImageCache: coverImageCache,
containsOnlyDefaultContent: false,
autoFirstResponder: true
)
setSecondaryViewController(viewController, pushIfCollapsed: true)
Logger.shared.info("Created a new view controller for a book!")
} catch {
Logger.shared.error("Unexpected error creating note for book \(String(describing: book)): \(String(describing: error))")
}
}
public func bookSearchViewControllerDidSkip(_ viewController: BookEditDetailsViewController) {
dismiss(animated: true, completion: nil)
createAndNavigateToNewNote()
}
public func bookSearchViewControllerDidCancel(_ viewController: BookEditDetailsViewController) {
dismiss(animated: true, completion: nil)
}
}
// MARK: - NotebookStructureViewControllerDelegate
extension NotebookViewController: NotebookStructureViewControllerDelegate {
func notebookStructureViewController(_ viewController: NotebookStructureViewController, didSelect structure: NotebookStructureViewController.StructureIdentifier) {
focusedNotebookStructure = structure
}
func notebookStructureViewControllerDidRequestChangeFocus(_ viewController: NotebookStructureViewController) {
show(.supplementary)
documentListViewController.becomeFirstResponder()
}
}
// MARK: - DocumentListViewControllerDelegate
extension NotebookViewController {
func documentListViewControllerDidRequestChangeFocus(_ viewController: DocumentListViewController) {
tagsBecomeFirstResponder()
}
}
private extension UINavigationController {
/// Creates a UINavigationController with the expected configuration for being a notebook navigation controller.
static func notebookNavigationController(
rootViewController: UIViewController,
barTintColor: UIColor? = .grailBackground,
prefersLargeTitles: Bool = false
) -> UINavigationController {
let navigationController = UINavigationController(
rootViewController: rootViewController
)
// navigationController.navigationBar.prefersLargeTitles = prefersLargeTitles
// navigationController.navigationBar.barTintColor = barTintColor
return navigationController
}
}
// MARK: - UISplitViewControllerDelegate
extension NotebookViewController: UISplitViewControllerDelegate {
public func splitViewController(
_ svc: UISplitViewController,
displayModeForExpandingToProposedDisplayMode proposedDisplayMode: UISplitViewController.DisplayMode
) -> UISplitViewController.DisplayMode {
if let secondaryViewController = secondaryViewController(forCollaped: true) {
do {
let activityData = try secondaryViewController.userActivityData()
let viewController = try NotebookSecondaryViewControllerRegistry.shared.reconstruct(
type: type(of: secondaryViewController).notebookDetailType,
data: activityData,
database: database,
coverImageCache: coverImageCache
)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [self] in
setSecondaryViewController(viewController, pushIfCollapsed: false)
}
} catch {
Logger.shared.error("Unexpected error rebuilding view hierarchy")
}
}
return proposedDisplayMode
}
public func splitViewController(
_ svc: UISplitViewController,
topColumnForCollapsingToProposedTopColumn proposedTopColumn: UISplitViewController.Column
) -> UISplitViewController.Column {
let compactDocumentList = DocumentListViewController(database: database, coverImageCache: coverImageCache)
compactDocumentList.focusedStructure = focusedNotebookStructure
compactNavigationController.popToRootViewController(animated: false)
compactNavigationController.pushViewController(compactDocumentList, animated: false)
if let secondaryViewController = secondaryViewController(forCollaped: false), secondaryViewController.shouldShowWhenCollapsed {
do {
let activityData = try secondaryViewController.userActivityData()
let viewController = try NotebookSecondaryViewControllerRegistry.shared.reconstruct(
type: type(of: secondaryViewController).notebookDetailType,
data: activityData,
database: database,
coverImageCache: coverImageCache
)
compactNavigationController.pushViewController(viewController, animated: false)
} catch {
Logger.shared.error("Unexpected error rebuilding view hierarchy")
}
}
return .compact
}
}