-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNSOutlineView+Snapshot.swift
52 lines (46 loc) · 1.62 KB
/
NSOutlineView+Snapshot.swift
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
//
// NSOutlineView+Snapshot.swift
// OutlineViewDiffableDataSource
//
// Created by Steve Sparks on 2/8/20.
// Copyright © 2020 Big Nerd Ranch. All rights reserved.
//
import Cocoa
// Turn a diff into commands
extension NSOutlineView {
func apply(_ snapshot: OutlineViewSnapshotDiff, with animation: NSTableView.AnimationOptions = [.effectFade]) {
beginUpdates()
snapshot.forEach { instr in
switch instr {
case .insert(_, let indexPath):
let parent = lastParent(for: indexPath)
if let childIndex = indexPath.last {
insertItems(at: [childIndex], inParent: parent, withAnimation: animation)
}
case .move(let src, let dst):
let srcParent = lastParent(for: src)
let dstParent = lastParent(for: dst)
if let srcChild = src.last, let dstChild = dst.last {
moveItem(at: srcChild, inParent: srcParent, to: dstChild, inParent: dstParent)
}
case .remove(_, let indexPath):
let parent = lastParent(for: indexPath)
if let childIndex = indexPath.last {
removeItems(at: [childIndex], inParent: parent, withAnimation: animation)
}
}
}
endUpdates()
}
func lastParent(for indexPath: IndexPath) -> Any? {
var parent: Any?
var ip = indexPath
ip.removeLast()
for index in ip {
if let g = child(index, ofItem: parent) {
parent = g
}
}
return parent
}
}