1
1
mirror of https://github.com/exyte/Macaw.git synced 2024-09-21 09:59:10 +03:00
Macaw/Source/views/NodesMap.swift

98 lines
2.3 KiB
Swift
Raw Normal View History

2017-08-10 16:01:11 +03:00
import Foundation
2017-08-10 14:26:02 +03:00
#if os(iOS)
import UIKit
2017-08-10 14:26:02 +03:00
#endif
2016-08-24 13:25:14 +03:00
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 {
2017-03-21 14:23:47 +03:00
let map = NSMapTable<Node, MacawView>(keyOptions: NSMapTableWeakMemory, valueOptions: NSMapTableWeakMemory)
2016-08-24 13:25:14 +03:00
// MARK: - Macaw View
func add(_ node: Node, view: MacawView) {
2017-03-21 14:23:47 +03:00
map.setObject(view, forKey: node)
2016-08-24 13:25:14 +03:00
if let group = node as? Group {
group.contents.forEach { child in
self.add(child, view: view)
self.add(child, parent: node)
}
}
}
2016-08-24 13:25:14 +03:00
func getView(_ node: Node) -> MacawView? {
return map.object(forKey: node)
}
2016-08-24 13:25:14 +03:00
func remove(_ node: Node) {
2017-03-21 14:23:47 +03:00
map.removeObject(forKey: node)
parentsMap.removeValue(forKey: node)
}
// MARK: - Parents
func add(_ node: Node, parent: Node) {
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
func parents(_ node: Node) -> [Node] {
guard let nodesSet = parentsMap[node] else {
return []
}
return Array(nodesSet)
}
2016-08-25 12:10:27 +03:00
func replace(node: Node, to: Node) {
let parents = parentsMap[node]
2017-03-21 14:23:47 +03:00
let hostingView = map.object(forKey: node)
remove(node)
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
if let index = contents.index(of: node) {
contents.remove(at: index)
2017-03-02 12:02:01 +03:00
indexToInsert = index
}
2017-03-02 12:02:01 +03:00
contents.insert(to, at: indexToInsert)
group.contents = contents
add(to, parent: parent)
}
if let view = hostingView {
add(to, view: view)
}
// Replacing node in hosting view if needed
guard let hostingNode = hostingView?.node else {
return
}
if hostingNode == node {
hostingView?.node = to
}
// Replacing id
to.id = node.id
}
2016-08-24 13:25:14 +03:00
}