-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathupdateEntityChildArray.js
47 lines (42 loc) · 1.33 KB
/
updateEntityChildArray.js
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
import { without } from 'substance'
export default function updateEntityChildArray (tx, nodeId, tagName, attribute, oldEntityIds, newEntityIds) {
let node = tx.get(nodeId)
let addedEntityIds = without(newEntityIds, ...oldEntityIds)
let removedEntityIds = without(oldEntityIds, ...newEntityIds)
// Remove old entities
removedEntityIds.forEach(entityId => {
let entityRefNode = node.find(`${tagName}[${attribute}=${entityId}]`)
node.removeChild(entityRefNode)
// Remove it completely
tx.delete(entityRefNode.id)
})
// Create new entities
addedEntityIds.forEach(entityId => {
let entityRefNode = node.find(`${tagName}[${attribute}=${entityId}]`)
if (!entityRefNode) {
let opts = {}
if (attribute === 'id') {
opts = { id: entityId }
}
entityRefNode = tx.createElement(tagName, opts)
if (attribute !== 'id') {
entityRefNode.setAttribute(attribute, entityId)
}
}
node.appendChild(entityRefNode)
})
// Sort entities in order of newEntityIds array
let map = {}
let refs = tx.findAll(`${tagName}`)
refs.forEach(ref => {
const rid = ref.getAttribute('rid')
map[rid] = ref
})
node.children.forEach(child => {
node.removeChild(child)
})
newEntityIds.forEach(entityId => {
node.appendChild(map[entityId])
})
tx.setSelection(null)
}