1import UIKit
2
3/// A page's place in its section's order, as `sb_section_arrange` takes it.
4struct Placed: Codable, Equatable {
5 let id: String
6 var level: Int
7}
8
9/// Where `Arranging.move(page:)` took a page, from `sb_library_move_page`.
10private struct MovedPage: Decodable {
11 let page: String
12 let added: String?
13 let before: String?
14 let level: Int
15 /// Why the page also stayed where it was: the move only copied it.
16 let copied: String?
17}
18
19/// The catalog path of the folder holding the section or group at `path`; "" for the
20/// notebook's top.
21func parentFolder(of path: String) -> String {
22 path.range(of: "/", options: .backwards).map { String(path[..<$0.lowerBound]) } ?? ""
23}
24
25private func json(_ value: some Encodable) -> String {
26 (try? JSONEncoder().encode(value)).flatMap { String(data: $0, encoding: .utf8) } ?? ""
27}
28
29/// Moves of pages, sections, section groups and notebooks, each made as the desktop makes it,
30/// as one edit through the notebook, and kept for Undo: shake, three-finger swipe or ⌘Z in
31/// either list.
32enum Arranging {
33 static let history = UndoManager()
34 private(set) static var busy = false
35 private static let owner = NSObject()
36
37 /// ⌘Z and ⇧⌘Z in a list, which, unlike a text view, has none of its own.
38 static let keyCommands = [
39 UIKeyCommand(title: "Undo", action: #selector(UIResponder.undoArranging), input: "z", modifierFlags: .command),
40 UIKeyCommand(title: "Redo", action: #selector(UIResponder.redoArranging), input: "z", modifierFlags: [.command, .shift]),
41 ]
42
43 /// Keeps `undo` as Undo for `name`. Called as the change starts, so that a change Undo
44 /// makes keeps its own undo as Redo.
45 private static func done(_ name: String, undo: @escaping () -> Void) {
46 history.registerUndo(withTarget: owner) { _ in undo() }
47 history.setActionName(name)
48 UIImpactFeedbackGenerator(style: .light).impactOccurred()
49 }
50
51 /// Runs `work` off the main thread after the changes before it, then `then` with its result
52 /// on the main thread.
53 private static func later<T>(_ work: @escaping () -> T, then: @escaping (T) -> Void) {
54 queue.async {
55 let result = work()
56 DispatchQueue.main.async { then(result) }
57 }
58 }
59 private static let queue = DispatchQueue(label: "Arranging")
60
61 private static func failed(_ title: String, _ message: String = "Check that the notebook can be reached, then try again.") {
62 let window = UIApplication.shared.connectedScenes.lazy.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first
63 var top = window?.rootViewController
64 while let presented = top?.presentedViewController { top = presented }
65 top?.alert(title, message)
66 }
67
68 private static func available() -> Bool {
69 guard !busy else {
70 failed("Notebook Is Busy", "Wait for the current notebook change to finish, then try again.")
71 return false
72 }
73 return true
74 }
75
76 /// Excludes queued moves and filesystem mutations through their asynchronous outcomes.
77 static func reserve() -> (() -> Void)? {
78 guard available() else { return nil }
79 busy = true
80 return { busy = false }
81 }
82
83 /// The pages `rows` lists with page `id` moved to `index` of them, at its level or under
84 /// the page now above it, as the desktop drops a dragged page.
85 static func order(_ rows: [Row], moving id: String, to index: Int) -> [Placed] {
86 var order = rows.map { Placed(id: $0.id, level: $0.level) }
87 guard let from = order.firstIndex(where: { $0.id == id }) else { return order }
88 var page = order.remove(at: from)
89 let at = min(max(index, 0), order.count)
90 page.level = min(page.level, at == 0 ? 1 : order[at - 1].level + 1)
91 order.insert(page, at: at)
92 return order
93 }
94
95 /// Puts the pages of `section` in `order`, page `id` the one moved, as one edit.
96 @discardableResult
97 static func arrange(_ section: Section, _ order: [Placed], moving id: String) -> Bool {
98 guard available() else { return false }
99 let before = section.rows.map { Placed(id: $0.id, level: $0.level) }
100 guard order != before, section.arrange(order, moving: id) else { return false }
101 let (notebook, path) = (section.notebook, section.tab.path)
102 done("Move Page") {
103 opening(path, of: notebook) { arrange($0, before, moving: id) }
104 }
105 return true
106 }
107
108 /// Gives page `id` of `section` `level` where it stands, as Make Subpage and Promote
109 /// Subpage do.
110 static func indent(_ section: Section, _ id: String, to level: Int) {
111 guard available() else { return }
112 var order = section.rows.map { Placed(id: $0.id, level: $0.level) }
113 guard let at = order.firstIndex(where: { $0.id == id }), order[at].level != level else { return }
114 let was = order[at].level
115 order[at].level = level
116 guard section.arrange(order, moving: id) else { return }
117 let (notebook, path) = (section.notebook, section.tab.path)
118 done(level > was ? "Make Subpage" : "Promote Subpage") {
119 opening(path, of: notebook) { indent($0, id, to: was) }
120 }
121 }
122
123 /// Hands `then` the section at `path` of `notebook`, opening it where it isn't open.
124 private static func opening(_ path: String, of notebook: Notebook, then: @escaping (Section) -> Void) {
125 guard let tab = notebook.tabs.first(where: { $0.path == path }) else { return }
126 Section.open(tab, of: notebook) { section, _ in section.map(then) }
127 }
128
129 /// Moves page `id` of the section at `from` into the section at `to`, before `before` at
130 /// `level` (last without), as OneNote moves a page dropped on a section's tab.
131 static func move(
132 page id: String, of notebook: Notebook, from: String, to: String, before: String? = nil, level: Int = 1,
133 discard: String? = nil
134 ) {
135 guard let library = notebook.handle, let release = reserve() else { return }
136 let pointer = Int(bitPattern: library)
137 let author = Author.name ?? ""
138 let (date, time) = titleDate()
139 // Undo takes back what the move reports, once it has.
140 var reported: MovedPage?
141 done("Move Page") {
142 guard let moved = reported else { return }
143 move(
144 page: moved.page, of: notebook, from: to, to: from, before: moved.before, level: moved.level,
145 discard: moved.added)
146 }
147 later({
148 decode(
149 MovedPage.self,
150 sb_library_move_page(
151 OpaquePointer(bitPattern: pointer), from, id, to, before, UInt32(level), discard, author, date,
152 time))
153 }) { moved in
154 reported = moved
155 release()
156 for section in Section.all where section.notebook === notebook && [from, to].contains(section.tab.path) {
157 section.reloadRows()
158 }
159 if moved == nil { failed("Can’t Move Page") }
160 if let copied = moved?.copied { failed("Page Kept in Both Sections", copied) }
161 }
162 }
163
164 /// Moves only the selected pages, retaining their ancestry among the selection.
165 static func move(pages ids: [String], from source: Section, to tab: Tab) {
166 guard let release = reserve() else { return }
167 Section.open(tab, of: source.notebook) { target, _ in
168 guard let target else {
169 release()
170 return failed("Can’t Move Pages")
171 }
172 var ancestors: [Int] = []
173 var selected: [Placed] = []
174 for row in source.rows {
175 ancestors.removeAll { $0 >= row.level }
176 guard ids.contains(row.id) else { continue }
177 selected.append(Placed(id: row.id, level: ancestors.count + 1))
178 ancestors.append(row.level)
179 }
180 let order = target.rows.map { Placed(id: $0.id, level: $0.level) } + selected
181 // Hand off the reservation without yielding the main thread.
182 release()
183 transfer(selected.map { (page: $0.id, discard: nil) },
184 from: source, to: target, order: order)
185 }
186 }
187
188 private static func transfer(
189 _ pages: [(page: String, discard: String?)], from source: Section, to target: Section, order: [Placed],
190 repairs: [(id: String, expected: Int, restore: Int)] = []
191 ) {
192 guard !pages.isEmpty, let library = source.notebook.handle,
193 let sourceHandle = source.handle, let targetHandle = target.handle,
194 let release = reserve()
195 else { return }
196 let before = source.rows.map { Placed(id: $0.id, level: $0.level) }
197 let pointer = Int(bitPattern: library)
198 let sourcePointer = Int(bitPattern: sourceHandle)
199 let targetPointer = Int(bitPattern: targetHandle)
200 let author = Author.name ?? ""
201 let (date, time) = titleDate()
202 var undo: () -> Void = {}
203 let undoing = history.isUndoing
204 let reciprocal = undoing || history.isRedoing
205 if reciprocal { done("Move Pages") { undo() } }
206 later({ () -> ([MovedPage], [Placed], [(id: String, expected: Int, restore: Int)], Bool) in
207 var reported: [MovedPage] = []
208 var arrived: [String: String] = [:]
209 var promotions: [(id: String, expected: Int, restore: Int)] = []
210 // Removing a parent can promote its first remaining child.
211 for page in pages.reversed() {
212 guard let listed = decode([Row].self, sb_section_pages(OpaquePointer(bitPattern: sourcePointer))) else { break }
213 let next = listed.first?.id == page.page ? listed.dropFirst().first : nil
214 guard let moved = decode(MovedPage.self, sb_library_move_page(
215 OpaquePointer(bitPattern: pointer), source.tab.path, page.page, target.tab.path,
216 nil, 1, page.discard, author, date, time)) else { break }
217 reported.append(moved)
218 arrived[page.page] = moved.page
219 if let next, next.level > 1, moved.before == next.id {
220 promotions.removeAll { $0.id == next.id }
221 promotions.append((id: next.id, expected: 1, restore: next.level))
222 }
223 }
224 promotions.removeAll { arrived[$0.id] != nil }
225 let restore = before.map { Placed(id: arrived[$0.id] ?? $0.id, level: $0.level) }
226 guard !reported.isEmpty else { return (reported, restore, promotions, false) }
227 let placed = order.map { Placed(id: arrived[$0.id] ?? $0.id, level: $0.level) }
228 guard sb_section_arrange(OpaquePointer(bitPattern: targetPointer), json(placed), json(Array(arrived.values))) else {
229 return (reported, restore, promotions, false)
230 }
231 if !repairs.isEmpty {
232 guard let present = decode([Row].self, sb_section_pages(OpaquePointer(bitPattern: targetPointer))) else {
233 return (reported, restore, promotions, false)
234 }
235 let applicable = repairs.filter { repair in present.contains { $0.id == repair.id && $0.level == repair.expected } }
236 let order = present.map { row in Placed(id: row.id, level: applicable.first { $0.id == row.id }?.restore ?? row.level) }
237 if !applicable.isEmpty && !sb_section_arrange(OpaquePointer(bitPattern: targetPointer), json(order), json(applicable.map(\.id))) {
238 return (reported, restore, promotions, false)
239 }
240 }
241 return (reported, restore, promotions, reported.count == pages.count)
242 }) { reported, restore, promotions, succeeded in
243 undo = { transfer(reported.map { (page: $0.page, discard: $0.added) }, from: target, to: source, order: restore, repairs: promotions) }
244 if reciprocal && reported.isEmpty {
245 // A rejected Undo or Redo must leave its original action retryable.
246 undo = { done("Move Pages") { transfer(pages, from: source, to: target, order: order, repairs: repairs) } }
247 if undoing { history.redo() } else { history.undo() }
248 }
249 if !reciprocal && !reported.isEmpty { done("Move Pages") { undo() } }
250 release()
251 source.reloadRows()
252 target.reloadRows()
253 if let copied = reported.lazy.compactMap(\.copied).first {
254 failed("Page Kept in Both Sections", copied)
255 } else if !succeeded {
256 failed("Can’t Move All Pages", reported.isEmpty
257 ? "Check both sections, then try moving the remaining pages again."
258 : "Check both sections. Use \(undoing ? "Redo" : "Undo") to reverse completed moves, or try moving the remaining pages again.")
259 }
260 }
261 }
262
263 /// Puts the section or group at `path` of `notebook` into `folder`, ordered as `order`
264 /// names its entries once moved; a section shown opens again where it went.
265 static func place(_ path: String, of notebook: Notebook, in folder: String, order: [String] = [], then: @escaping () -> Void = {}) {
266 guard let library = notebook.handle, let release = reserve() else { return }
267 let home = parentFolder(of: path)
268 let name = path.split(separator: "/").last.map(String.init) ?? path
269 let placed = home == folder ? path : folder.isEmpty ? name : folder + "/" + name
270 let undo = notebook.entries(in: home)
271 done("Move Section") { place(placed, of: notebook, in: home, order: undo) }
272 let scenes = UIApplication.shared.connectedScenes.compactMap { $0.delegate as? SceneDelegate }
273 let released = home == folder ? [] : scenes.compactMap { scene in scene.release(path, of: notebook).map { (scene, $0) } }
274 let pointer = Int(bitPattern: library)
275 let paths = json(order)
276 later({ take(sb_library_place(OpaquePointer(bitPattern: pointer), path, folder, paths)) != nil }) { moved in
277 notebook.reload {
278 release()
279 NotificationCenter.default.post(name: Notebook.listed, object: notebook)
280 for (scene, shown) in released {
281 let section = moved ? follow(shown.section, from: path, to: placed) : shown.section
282 if let tab = notebook.tabs.first(where: { $0.path == section }) {
283 scene.open(tab, of: notebook, page: shown.page)
284 }
285 }
286 if moved { then() } else { failed("Can’t Move Section") }
287 }
288 }
289 }
290
291 /// `current`, a section's path, after the section or group at `from` went to `to`.
292 private static func follow(_ current: String, from: String, to: String) -> String {
293 current == from ? to : current.hasPrefix(from + "/") ? to + current.dropFirst(from.count) : current
294 }
295
296 /// Puts `notebook` at `index` among the notebooks of its place in the list.
297 static func move(_ notebook: Notebook, to index: Int) {
298 guard available() else { return }
299 guard let from = Notebooks.siblings(of: notebook).firstIndex(where: { $0 === notebook }), from != index else {
300 return
301 }
302 Notebooks.move(notebook, to: index)
303 NotificationCenter.default.post(name: Notebook.listed, object: notebook)
304 done("Move Notebook") { move(notebook, to: from) }
305 }
306}
307
308extension UIResponder {
309 @objc func undoArranging() { if !Arranging.busy { Arranging.history.undo() } }
310 @objc func redoArranging() { if !Arranging.busy { Arranging.history.redo() } }
311}
312
313extension Section {
314 /// Puts page `id` where `order` places it, as one edit; false where it isn't listed.
315 func arrange(_ order: [Placed], moving id: String) -> Bool {
316 guard let handle, sb_section_arrange(handle, json(order), json([id])) else { return false }
317 reloadRows()
318 return true
319 }
320}
321
322extension Notebook {
323 /// The section groups, by catalog path, in the order the list shows them.
324 var groups: [String] {
325 var groups: [String] = []
326 for tab in tabs {
327 var path = ""
328 for part in tab.group.split(separator: "/") {
329 path += (path.isEmpty ? "" : "/") + part
330 if !groups.contains(path) { groups.append(path) }
331 }
332 }
333 return groups
334 }
335
336 /// The sections and groups directly in `folder`, by catalog path, as the list shows them.
337 func entries(in folder: String) -> [String] {
338 tabs.filter { $0.group == folder }.map(\.path) + groups.filter { parentFolder(of: $0) == folder }
339 }
340
341 /// Where the section or group at `path` can move: the notebook's top and its groups, by
342 /// catalog path, leaving out its own folder, itself and its groups.
343 func destinations(of path: String) -> [String] {
344 ([""] + groups).filter { $0 != parentFolder(of: path) && $0 != path && !$0.hasPrefix(path + "/") }
345 }
346
347 /// The sections a page of the section at `path` can move to.
348 func sections(besides path: String) -> [Tab] {
349 tabs.filter { $0.path != path && $0.readable && !$0.locked }
350 }
351}
352
353/// A page dragged out of the page list.
354final class PageDrag {
355 let section: Section
356 let id: String
357
358 init(section: Section, id: String) {
359 self.section = section
360 self.id = id
361 }
362}
363
364/// A sheet offering `actions`, for VoiceOver’s Move actions, from `view`.
365private func sheet(_ title: String, _ actions: [UIAction], from view: UIView, in controller: UIViewController) {
366 let sheet = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
367 for action in actions {
368 let item = UIAlertAction(title: action.title, style: .default) { _ in action.performWithSender(nil, target: nil) }
369 item.isEnabled = !action.attributes.contains(.disabled)
370 sheet.addAction(item)
371 }
372 sheet.addAction(UIAlertAction(title: "Cancel", style: .cancel))
373 sheet.popoverPresentationController?.sourceView = view
374 sheet.popoverPresentationController?.sourceRect = view.bounds
375 controller.present(sheet, animated: true)
376}
377
378// MARK: Pages
379
380extension PagesViewController: UITableViewDragDelegate, UITableViewDropDelegate {
381 func setUpArranging() {
382 tableView.dragDelegate = self
383 tableView.dropDelegate = self
384 tableView.dragInteractionEnabled = true
385 tableView.allowsMultipleSelectionDuringEditing = true
386 navigationItem.rightBarButtonItem = editButtonItem
387 }
388
389 override var canBecomeFirstResponder: Bool { true }
390 override var undoManager: UndoManager? { !Arranging.busy ? Arranging.history : nil }
391 override var keyCommands: [UIKeyCommand]? { Arranging.keyCommands }
392
393 /// Undo in the list takes back its moves.
394 override func viewDidAppear(_ animated: Bool) {
395 super.viewDidAppear(animated)
396 becomeFirstResponder()
397 }
398
399 /// Page `id` moved to `index` of the section's pages.
400 @discardableResult
401 private func move(_ id: String, to index: Int) -> Bool {
402 guard let section else { return false }
403 let order = Arranging.order(section.rows, moving: id, to: index)
404 guard order.first?.level == 1, Arranging.arrange(section, order, moving: id) else { return false }
405 becomeFirstResponder()
406 return true
407 }
408
409 /// Page `id` a level deeper or shallower, where it stays.
410 private func indent(_ id: String, by change: Int) {
411 guard let section, let row = section.rows.first(where: { $0.id == id }) else { return }
412 Arranging.indent(section, id, to: row.level + change)
413 becomeFirstResponder()
414 }
415
416 /// Whether page `at` of `rows` can become a subpage, as the desktop allows: under a page
417 /// at its level or deeper, at most three deep.
418 private func indentable(_ rows: [Row], _ at: Int) -> Bool {
419 at > 0 && rows[at].level < 3 && rows[at - 1].level >= rows[at].level
420 }
421
422 private func moveActions(_ item: Item) -> [UIAction] {
423 guard let section else { return [] }
424 return section.notebook.sections(besides: section.tab.path).map { tab in
425 UIAction(
426 title: tab.name, subtitle: tab.group.isEmpty ? nil : tab.group,
427 image: UIImage(systemName: "rectangle.portrait.fill")?.withTintColor(tab.uiColor, renderingMode: .alwaysOriginal),
428 attributes: !Arranging.busy ? [] : .disabled
429 ) { [weak self] _ in
430 Arranging.move(page: item.row.id, of: section.notebook, from: section.tab.path, to: tab.path)
431 self?.becomeFirstResponder()
432 }
433 }
434 }
435
436 /// Make Subpage, Promote Subpage and Move to Section, for a page's menu.
437 func arrangeMenu(_ item: Item) -> [UIMenuElement] {
438 guard let rows = section?.rows, let at = rows.firstIndex(where: { $0.id == item.row.id }) else { return [] }
439 let id = item.row.id
440 var actions: [UIMenuElement] = [
441 UIAction(
442 title: "Make Subpage", image: UIImage(systemName: "increase.indent"),
443 attributes: !Arranging.busy && indentable(rows, at) ? [] : .disabled
444 ) { [weak self] _ in self?.indent(id, by: 1) },
445 UIAction(
446 title: "Promote Subpage", image: UIImage(systemName: "decrease.indent"),
447 attributes: !Arranging.busy && rows[at].level > 1 ? [] : .disabled
448 ) { [weak self] _ in self?.indent(id, by: -1) },
449 ]
450 let moves = moveActions(item)
451 if !moves.isEmpty {
452 actions.append(UIMenu(title: "Move to Section", image: UIImage(systemName: "arrow.right.doc.on.clipboard"), children: moves))
453 }
454 return [UIMenu(options: .displayInline, children: actions)]
455 }
456
457 /// VoiceOver's ways to move a page without dragging it.
458 func arrangeActions(_ item: Item) -> [UIAccessibilityCustomAction]? {
459 guard !Arranging.busy, item.version == nil, let section,
460 let at = section.rows.firstIndex(where: { $0.id == item.row.id })
461 else { return nil }
462 let rows = section.rows
463 let id = item.row.id
464 var actions: [UIAccessibilityCustomAction] = []
465 for (name, direction) in [("Move Up", -1), ("Move Down", 1)] {
466 guard rows.indices.contains(at + direction),
467 at > 0 || direction < 0 || rows[1].level == 1
468 else { continue }
469 actions.append(UIAccessibilityCustomAction(name: name) { [weak self] _ in
470 guard let self, self.section === section,
471 let at = section.rows.firstIndex(where: { $0.id == id }), section.rows.indices.contains(at + direction)
472 else { return false }
473 return move(id, to: at + direction)
474 })
475 }
476 let add = { (name: String, act: @escaping () -> Void) in
477 actions.append(UIAccessibilityCustomAction(name: name) { _ in act(); return true })
478 }
479 if indentable(rows, at) { add("Make Subpage") { [weak self] in self?.indent(id, by: 1) } }
480 if rows[at].level > 1 { add("Promote Subpage") { [weak self] in self?.indent(id, by: -1) } }
481 if !moveActions(item).isEmpty {
482 add("Move to Section") { [weak self] in
483 guard let self, let row = items.firstIndex(where: { $0.id == id }),
484 let cell = tableView.cellForRow(at: IndexPath(row: row, section: 0))
485 else { return }
486 sheet("Move to Section", moveActions(item), from: cell, in: self)
487 }
488 }
489 return actions
490 }
491
492 override func tableView(
493 _ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath
494 ) -> UISwipeActionsConfiguration? {
495 // A swipe across the list changes section instead.
496 guard !Arranging.busy, !Prototype.sectionStrip, let rows = section?.rows, items[indexPath.row].version == nil,
497 let at = rows.firstIndex(where: { $0.id == items[indexPath.row].row.id })
498 else { return nil }
499 let id = rows[at].id
500 var actions: [UIContextualAction] = []
501 if indentable(rows, at) {
502 let indent = UIContextualAction(style: .normal, title: "Make Subpage") { [weak self] _, _, done in
503 self?.indent(id, by: 1)
504 done(true)
505 }
506 indent.image = UIImage(systemName: "increase.indent")
507 indent.backgroundColor = .systemIndigo
508 actions.append(indent)
509 }
510 if rows[at].level > 1 {
511 let promote = UIContextualAction(style: .normal, title: "Promote Subpage") { [weak self] _, _, done in
512 self?.indent(id, by: -1)
513 done(true)
514 }
515 promote.image = UIImage(systemName: "decrease.indent")
516 promote.backgroundColor = .systemTeal
517 actions.append(promote)
518 }
519 return UISwipeActionsConfiguration(actions: actions)
520 }
521
522 override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
523 !Arranging.busy && items[indexPath.row].version == nil
524 }
525
526 override func tableView(_ tableView: UITableView, moveRowAt from: IndexPath, to: IndexPath) {
527 var moved = items
528 let item = moved.remove(at: from.row)
529 moved.insert(item, at: to.row)
530 guard let index = moved.filter({ $0.version == nil }).firstIndex(where: { $0.id == item.id }) else { return }
531 // The table finishes its move before the list reloads.
532 DispatchQueue.main.async { [weak self] in self?.move(item.id, to: index) }
533 }
534
535 override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
536 false
537 }
538
539 func tableView(
540 _ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath
541 ) -> [UIDragItem] {
542 let item = items[indexPath.row]
543 guard !Arranging.busy, let section, item.version == nil else { return [] }
544 let drag = UIDragItem(itemProvider: NSItemProvider())
545 drag.localObject = PageDrag(section: section, id: item.row.id)
546 return [drag]
547 }
548
549 func tableView(_ tableView: UITableView, dragSessionIsRestrictedToDraggingApplication session: UIDragSession) -> Bool {
550 true
551 }
552
553 /// A wide window shows the notebooks beside the pages while a page is dragged, so it can
554 /// be dropped on a section there.
555 func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) {
556 guard let split = splitViewController, !split.isCollapsed, split.displayMode != .twoBesideSecondary else { return }
557 session.localContext = split.preferredDisplayMode
558 split.preferredDisplayMode = .twoBesideSecondary
559 }
560
561 func tableView(_ tableView: UITableView, dragSessionDidEnd session: UIDragSession) {
562 guard let mode = session.localContext as? UISplitViewController.DisplayMode else { return }
563 splitViewController?.preferredDisplayMode = mode
564 }
565
566 func tableView(
567 _ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath: IndexPath?
568 ) -> UITableViewDropProposal {
569 let page = session.localDragSession?.items.first?.localObject as? PageDrag
570 guard !Arranging.busy, let page, page.section === section else {
571 return UITableViewDropProposal(operation: .forbidden)
572 }
573 return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
574 }
575
576 /// Drops within the list reorder through `moveRowAt`.
577 func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {}
578}
579
580// MARK: Notebooks, sections and groups
581
582extension NotebooksViewController: UICollectionViewDragDelegate, UICollectionViewDropDelegate {
583 func setUpArranging() {
584 collectionView.dragDelegate = self
585 collectionView.dropDelegate = self
586 collectionView.dragInteractionEnabled = true
587 collectionView.allowsMultipleSelectionDuringEditing = true
588 // A sidebar's trailing edge has no room left for it.
589 if UIDevice.current.userInterfaceIdiom == .pad {
590 navigationItem.leftBarButtonItem = editButtonItem
591 } else {
592 navigationItem.rightBarButtonItems?.append(editButtonItem)
593 }
594 // Rows dragged between rows, and by Edit's reorder handles, move through the data source.
595 dataSource.reorderingHandlers.canReorderItem = { [weak self] item in
596 !Arranging.busy && self?.movable(item) == true && (self?.collectionView.indexPathsForSelectedItems?.count ?? 0) < 2
597 }
598 // The data source is still applying the move when this runs.
599 dataSource.reorderingHandlers.didReorder = { [weak self] transaction in
600 DispatchQueue.main.async { self?.reordered(transaction) }
601 }
602 }
603
604 override var canBecomeFirstResponder: Bool { true }
605 override var undoManager: UndoManager? { !Arranging.busy ? Arranging.history : nil }
606 override var keyCommands: [UIKeyCommand]? { Arranging.keyCommands }
607
608 /// Undo in the list takes back its moves.
609 override func viewDidAppear(_ animated: Bool) {
610 super.viewDidAppear(animated)
611 becomeFirstResponder()
612 }
613
614 private func movable(_ item: Item) -> Bool {
615 switch item {
616 case .notebook, .group, .section: true
617 default: false
618 }
619 }
620
621 /// The notebook and catalog path of a section or group row.
622 private func entry(_ item: Item) -> (notebook: Notebook, path: String)? {
623 switch item {
624 case .group(let id, let path), .section(let id, let path): notebook(id).map { ($0, path) }
625 default: nil
626 }
627 }
628
629 /// The group or notebook top a row stands for, as a folder an entry of `notebook` can go into.
630 private func folder(_ item: Item, in notebook: Notebook) -> String? {
631 switch item {
632 case .notebook(let id) where id == notebook.id: ""
633 case .group(let id, let path) where id == notebook.id: path
634 default: nil
635 }
636 }
637
638 /// Moves the section or group at `path` within its folder by `offset`.
639 private func shift(_ path: String, of notebook: Notebook, by offset: Int) {
640 var order = notebook.entries(in: parentFolder(of: path))
641 guard let at = order.firstIndex(of: path), order.indices.contains(at + offset) else { return }
642 order.swapAt(at, at + offset)
643 Arranging.place(path, of: notebook, in: parentFolder(of: path), order: order)
644 becomeFirstResponder()
645 }
646
647 private func moveActions(_ path: String, of notebook: Notebook) -> [UIAction] {
648 notebook.destinations(of: path).map { folder in
649 UIAction(
650 title: folder.isEmpty ? notebook.name : folder.split(separator: "/").joined(separator: " › "),
651 image: UIImage(systemName: folder.isEmpty ? "book.closed" : "folder"),
652 attributes: !Arranging.busy ? [] : .disabled
653 ) { [weak self] _ in
654 Arranging.place(path, of: notebook, in: folder)
655 self?.becomeFirstResponder()
656 }
657 }
658 }
659
660 /// Move, into the notebook's top or a group, for a section's or group's menu; Move Up and
661 /// Move Down for a notebook's, as the desktop's.
662 func arrangeMenu(_ item: Item) -> [UIMenuElement] {
663 if case .notebook(let id) = item, let notebook = notebook(id) {
664 let siblings = Notebooks.siblings(of: notebook)
665 guard let at = siblings.firstIndex(where: { $0 === notebook }), siblings.count > 1 else { return [] }
666 return [
667 UIMenu(options: .displayInline, children: [
668 UIAction(title: "Move Up", image: UIImage(systemName: "arrow.up"), attributes: !Arranging.busy && at > 0 ? [] : .disabled) {
669 _ in Arranging.move(notebook, to: at - 1)
670 },
671 UIAction(
672 title: "Move Down", image: UIImage(systemName: "arrow.down"),
673 attributes: !Arranging.busy && at < siblings.count - 1 ? [] : .disabled
674 ) { _ in Arranging.move(notebook, to: at + 1) },
675 ])
676 ]
677 }
678 guard let (notebook, path) = entry(item) else { return [] }
679 let moves = moveActions(path, of: notebook)
680 return moves.isEmpty ? [] : [UIMenu(title: "Move", image: UIImage(systemName: "folder"), children: moves)]
681 }
682
683 /// Adds Edit's reorder handle and VoiceOver's ways to move to a row.
684 func arranging(_ cell: UICollectionViewListCell, _ item: Item) {
685 if movable(item) {
686 cell.accessories += [.multiselect(), .reorder(displayed: .whenEditing)]
687 }
688 var actions: [UIAccessibilityCustomAction] = []
689 let add = { (name: String, act: @escaping () -> Void) in
690 actions.append(UIAccessibilityCustomAction(name: name) { _ in act(); return true })
691 }
692 if case .notebook(let id) = item, let notebook = notebook(id) {
693 let siblings = Notebooks.siblings(of: notebook)
694 if let at = siblings.firstIndex(where: { $0 === notebook }) {
695 if at > 0 { add("Move Up") { Arranging.move(notebook, to: at - 1) } }
696 if at < siblings.count - 1 { add("Move Down") { Arranging.move(notebook, to: at + 1) } }
697 }
698 } else if let (notebook, path) = entry(item) {
699 let order = notebook.entries(in: parentFolder(of: path))
700 if let at = order.firstIndex(of: path) {
701 if at > 0 { add("Move Up") { [weak self] in self?.shift(path, of: notebook, by: -1) } }
702 if at < order.count - 1 { add("Move Down") { [weak self] in self?.shift(path, of: notebook, by: 1) } }
703 }
704 if !notebook.destinations(of: path).isEmpty {
705 add("Move") { [weak self, weak cell] in
706 guard let self, let cell else { return }
707 sheet("Move", moveActions(path, of: notebook), from: cell, in: self)
708 }
709 }
710 }
711 cell.accessibilityCustomActions = actions
712 }
713
714 /// Carries out a move the data source made: a notebook among its place's, or a
715 /// section or group into the folder it landed in; anywhere else it goes back.
716 private func reordered(_ transaction: NSDiffableDataSourceTransaction<Location, Item>) {
717 becomeFirstResponder()
718 let moved = transaction.difference.insertions.lazy.compactMap { change -> Item? in
719 if case .insert(_, let item, _) = change { return item }
720 return nil
721 }.first
722 guard let moved, let list = transaction.sectionTransactions.first?.finalSnapshot,
723 let parent = list.parent(of: moved)
724 else { return reload() }
725 let siblings = list.snapshot(of: parent).rootItems
726 if case .notebook(let id) = moved, let notebook = notebook(id), case .location = parent {
727 let notebooks = siblings.filter { if case .notebook = $0 { true } else { false } }
728 return Arranging.move(notebook, to: notebooks.firstIndex(of: moved) ?? 0)
729 }
730 guard let (notebook, path) = entry(moved), let folder = folder(parent, in: notebook),
731 folder != path, !folder.hasPrefix(path + "/")
732 else { return reload() }
733 let name = path.split(separator: "/").last.map(String.init) ?? path
734 let order = siblings.compactMap { sibling in
735 sibling == moved ? (folder.isEmpty ? name : folder + "/" + name) : entry(sibling)?.path
736 }
737 Arranging.place(path, of: notebook, in: folder, order: order)
738 }
739
740 func collectionView(
741 _ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath
742 ) -> [UIDragItem] {
743 guard !Arranging.busy, let item = dataSource.itemIdentifier(for: indexPath), movable(item) else { return [] }
744 let drag = UIDragItem(itemProvider: NSItemProvider())
745 drag.localObject = item
746 return [drag]
747 }
748
749 func collectionView(
750 _ collectionView: UICollectionView, dragSessionIsRestrictedToDraggingApplication session: UIDragSession
751 ) -> Bool {
752 true
753 }
754
755 func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
756 session.localDragSession != nil
757 }
758
759 /// The row under `session`'s touch.
760 private func row(under session: UIDropSession) -> (IndexPath, Item, UICollectionViewCell)? {
761 let point = session.location(in: collectionView)
762 guard let indexPath = collectionView.indexPathForItem(at: point),
763 let item = dataSource.itemIdentifier(for: indexPath), let cell = collectionView.cellForItem(at: indexPath)
764 else { return nil }
765 return (indexPath, item, cell)
766 }
767
768 /// The section a dragged page would move to, under the touch.
769 private func section(for page: PageDrag, under session: UIDropSession) -> Tab? {
770 guard let (_, item, _) = row(under: session), case .section(let id, let path) = item,
771 id == page.section.notebook.id
772 else { return nil }
773 return page.section.notebook.sections(besides: page.section.tab.path).first { $0.path == path }
774 }
775
776 func collectionView(
777 _ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession,
778 withDestinationIndexPath destinationIndexPath: IndexPath?
779 ) -> UICollectionViewDropProposal {
780 guard !Arranging.busy else { return UICollectionViewDropProposal(operation: .forbidden) }
781 let dragged = session.localDragSession?.items.first?.localObject
782 if let page = dragged as? PageDrag {
783 guard section(for: page, under: session) != nil else { return UICollectionViewDropProposal(operation: .forbidden) }
784 return UICollectionViewDropProposal(operation: .move, intent: .insertIntoDestinationIndexPath)
785 }
786 guard dragged is Item else { return UICollectionViewDropProposal(operation: .forbidden) }
787 // A row dropped between rows moves through the data source's reordering handlers.
788 return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
789 }
790
791 func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
792 guard let drop = coordinator.items.first else { return }
793 let session = coordinator.session
794 guard let page = drop.dragItem.localObject as? PageDrag, let tab = section(for: page, under: session),
795 let (indexPath, _, cell) = row(under: session)
796 else { return }
797 coordinator.drop(drop.dragItem, intoItemAt: indexPath, rect: cell.bounds)
798 Arranging.move(page: page.id, of: page.section.notebook, from: page.section.tab.path, to: tab.path)
799 becomeFirstResponder()
800 }
801}