@@ -164,22 +164,28 @@ class ModelImporter(private val root: INode, val stats: ImportStats? = null) {
164
164
165
165
val targetIndices = HashMap <String ?, Int >(nodeData.children.size)
166
166
for (child in toBeSortedSpec) {
167
- val baseIndex = toBeSortedSpec.filter { it.role == node.roleInParent }.indexOf(child)
167
+
168
+ val childrenInRole = existingChildren.filter { it.roleInParent == child.role }
169
+ val baseIndex = child.getIndexWithinRole(nodeData, childrenInRole.lastIndex)
168
170
var offset = 0
169
- offset + = existingChildren.filter { it.roleInParent == child.role } .slice(0 .. baseIndex).count {
171
+ offset + = childrenInRole .slice(0 .. baseIndex).count {
170
172
! originalIdToSpec.containsKey(it.originalId()) // node will be deleted
171
173
}
172
- offset - = specifiedChildren.filter { it.role == child.role } .slice(0 .. baseIndex).count {
174
+ offset - = childrenInRole .slice(0 .. baseIndex).count {
173
175
! existingIds.contains(it.originalId()) // node will be moved here
174
176
}
175
- val index = baseIndex + offset
176
- targetIndices[child.originalId()] = minOf(index, existingChildren.size - 1 )
177
+ val index = if (childrenInRole.isEmpty()) 0 else baseIndex + offset
178
+ val upperBound = if (existingChildren.isEmpty()) 0 else existingChildren.lastIndex
179
+ targetIndices[child.originalId()] = minOf(index, upperBound)
177
180
}
178
181
179
- for ((index, child) in existingChildren.withIndex()) {
182
+ existingChildren.forEach { child ->
183
+
184
+ val currentIndex = child.index()
185
+ val targetRole = originalIdToSpec[child.originalId()]?.role
180
186
val targetIndex = targetIndices[child.originalId()]
181
- if (targetIndex != null && targetIndex != index ) {
182
- node.moveChildWithStats(child.roleInParent , targetIndex, child)
187
+ if (targetIndex != null && ( targetIndex != currentIndex || child.roleInParent != targetRole) ) {
188
+ node.moveChildWithStats(targetRole , targetIndex, child)
183
189
}
184
190
}
185
191
}
0 commit comments