1
1
mirror of https://github.com/exyte/Macaw.git synced 2024-11-11 01:42:35 +03:00
Macaw/Source/views/NodesMap.swift

84 lines
1.8 KiB
Swift
Raw Normal View History

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
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
}
}
}
func getView(_ node: Node) -> MacawView? {
2016-08-24 13:25:14 +03:00
return map[node]
}
func remove(_ node: Node) {
map.removeValue(forKey: node)
parentsMap.removeValue(forKey: node)
2016-08-25 12:10:27 +03:00
}
// MARK: - Parents
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
}
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
}
func replace(node: Node, to: Node) {
let parents = parentsMap[node]
let hostingView = map[node]
remove(node)
2017-03-02 12:02:01 +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
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)
}
}
2016-08-24 13:25:14 +03:00
}