2016-08-24 13:25:14 +03:00
|
|
|
|
|
|
|
import UIKit
|
|
|
|
|
|
|
|
let nodesMap = NodesMap()
|
2016-08-25 12:10:27 +03:00
|
|
|
var parentsMap = [Node: Set<Node>]()
|
|
|
|
|
2016-08-24 13:25:14 +03:00
|
|
|
class NodesMap {
|
|
|
|
var map = [Node: MacawView]()
|
|
|
|
|
2016-08-25 12:10:27 +03:00
|
|
|
// MARK: - Macaw View
|
2016-09-27 16:45:31 +03:00
|
|
|
func add(_ node: Node, view: MacawView) {
|
2016-08-24 13:25:14 +03:00
|
|
|
map[node] = view
|
|
|
|
|
|
|
|
if let group = node as? Group {
|
|
|
|
group.contents.forEach { child in
|
|
|
|
self.add(child, view: view)
|
2016-08-25 12:11:46 +03:00
|
|
|
self.add(child, parent: node)
|
2016-08-24 13:25:14 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-27 16:45:31 +03:00
|
|
|
func getView(_ node: Node) -> MacawView? {
|
2016-08-24 13:25:14 +03:00
|
|
|
return map[node]
|
|
|
|
}
|
|
|
|
|
2016-09-27 16:45:31 +03:00
|
|
|
func remove(_ node: Node) {
|
|
|
|
map.removeValue(forKey: node)
|
|
|
|
parentsMap.removeValue(forKey: node)
|
2016-08-25 12:10:27 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// MARK: - Parents
|
2016-09-27 16:45:31 +03:00
|
|
|
func add(_ node: Node, parent: Node) {
|
2016-08-25 12:10:27 +03:00
|
|
|
if var nodesSet = parentsMap[node] {
|
|
|
|
nodesSet.insert(parent)
|
|
|
|
} else {
|
|
|
|
parentsMap[node] = Set([parent])
|
|
|
|
}
|
2017-02-13 14:55:21 +03:00
|
|
|
|
|
|
|
if let group = node as? Group {
|
|
|
|
group.contents.forEach { child in
|
|
|
|
self.add(child, parent: node)
|
|
|
|
}
|
|
|
|
}
|
2016-08-25 12:10:27 +03:00
|
|
|
}
|
|
|
|
|
2016-09-27 16:45:31 +03:00
|
|
|
func parents(_ node: Node) -> [Node] {
|
2016-08-25 12:10:27 +03:00
|
|
|
guard let nodesSet = parentsMap[node] else {
|
|
|
|
return []
|
|
|
|
}
|
|
|
|
|
|
|
|
return Array(nodesSet)
|
2016-08-24 13:25:14 +03:00
|
|
|
}
|
2017-03-01 13:13:30 +03:00
|
|
|
|
|
|
|
func replace(node: Node, to: Node) {
|
|
|
|
let parents = parentsMap[node]
|
|
|
|
let hostingView = map[node]
|
|
|
|
|
|
|
|
remove(node)
|
2017-03-02 12:02:01 +03:00
|
|
|
|
2017-03-01 13:13:30 +03:00
|
|
|
parents?.forEach { parent in
|
|
|
|
guard let group = parent as? Group else {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var contents = group.contents
|
2017-03-02 12:02:01 +03:00
|
|
|
var indexToInsert = 0
|
2017-03-01 13:13:30 +03:00
|
|
|
if let index = contents.index(of: node) {
|
|
|
|
contents.remove(at: index)
|
2017-03-02 12:02:01 +03:00
|
|
|
indexToInsert = index
|
2017-03-01 13:13:30 +03:00
|
|
|
}
|
|
|
|
|
2017-03-02 12:02:01 +03:00
|
|
|
contents.insert(to, at: indexToInsert)
|
2017-03-01 13:13:30 +03:00
|
|
|
group.contents = contents
|
|
|
|
|
|
|
|
add(to, parent: parent)
|
|
|
|
}
|
|
|
|
|
|
|
|
if let view = hostingView {
|
|
|
|
add(to, view: view)
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2016-08-24 13:25:14 +03:00
|
|
|
}
|