|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | +import { describe, expect, it } from 'vitest' |
| 5 | +import { sortNodesParentsFirst } from './node-order' |
| 6 | + |
| 7 | +const node = (id: string, parentId?: string) => (parentId ? { id, parentId } : { id }) |
| 8 | +const ids = (nodes: Array<{ id: string }>) => nodes.map((n) => n.id) |
| 9 | + |
| 10 | +describe('sortNodesParentsFirst', () => { |
| 11 | + it('moves a child that precedes its container behind it', () => { |
| 12 | + /* The reported bug: a card created before the loop it was later dragged |
| 13 | + into sits ahead of the loop in row order, so React Flow v12 placed it at |
| 14 | + its loop-relative offset on every click. */ |
| 15 | + const nodes = [node('start'), node('earlier'), node('sink', 'loop'), node('loop')] |
| 16 | + |
| 17 | + expect(ids(sortNodesParentsFirst(nodes))).toEqual(['start', 'earlier', 'loop', 'sink']) |
| 18 | + }) |
| 19 | + |
| 20 | + it('returns the same array when every parent already precedes its children', () => { |
| 21 | + const nodes = [node('start'), node('loop'), node('sink', 'loop'), node('later')] |
| 22 | + |
| 23 | + expect(sortNodesParentsFirst(nodes)).toBe(nodes) |
| 24 | + }) |
| 25 | + |
| 26 | + it('leaves a parents-first array alone even when depth drops between siblings', () => { |
| 27 | + const nodes = [node('loopA'), node('a1', 'loopA'), node('loopB'), node('b1', 'loopB')] |
| 28 | + |
| 29 | + expect(sortNodesParentsFirst(nodes)).toBe(nodes) |
| 30 | + }) |
| 31 | + |
| 32 | + it('orders every level of a nested chain and keeps siblings in their original order', () => { |
| 33 | + const nodes = [ |
| 34 | + node('grandchild', 'inner'), |
| 35 | + node('inner', 'outer'), |
| 36 | + node('second', 'outer'), |
| 37 | + node('first', 'outer'), |
| 38 | + node('outer'), |
| 39 | + node('top'), |
| 40 | + ] |
| 41 | + |
| 42 | + expect(ids(sortNodesParentsFirst(nodes))).toEqual([ |
| 43 | + 'outer', |
| 44 | + 'top', |
| 45 | + 'inner', |
| 46 | + 'second', |
| 47 | + 'first', |
| 48 | + 'grandchild', |
| 49 | + ]) |
| 50 | + }) |
| 51 | + |
| 52 | + it('does not move a child whose parent is not in the array', () => { |
| 53 | + const nodes = [node('orphan', 'missing'), node('top')] |
| 54 | + |
| 55 | + expect(sortNodesParentsFirst(nodes)).toBe(nodes) |
| 56 | + }) |
| 57 | + |
| 58 | + it('terminates on a parent cycle', () => { |
| 59 | + const nodes = [node('b', 'a'), node('a', 'b'), node('c', 'a')] |
| 60 | + |
| 61 | + expect(ids(sortNodesParentsFirst(nodes))).toHaveLength(3) |
| 62 | + }) |
| 63 | + |
| 64 | + it('does not mutate its input when it has to reorder', () => { |
| 65 | + const nodes = [node('sink', 'loop'), node('loop')] |
| 66 | + const before = [...nodes] |
| 67 | + |
| 68 | + sortNodesParentsFirst(nodes) |
| 69 | + |
| 70 | + expect(nodes).toEqual(before) |
| 71 | + }) |
| 72 | +}) |
0 commit comments