Browse Source

Fix moving child to first position in tree data (#9761)

Resolves #9760
tags/8.1.2
Adam Wagner 6 years ago
parent
commit
d4fdcb9b46

+ 29
- 20
server/src/main/java/com/vaadin/data/TreeData.java View File

@@ -438,7 +438,8 @@ public class TreeData<T> implements Serializable {
* @param item
* the item to be moved
* @param sibling
* the item after which the moved item will be located
* the item after which the moved item will be located, or {@code
* null} to move item to first position
* @since 8.1
*/
public void moveAfterSibling(T item, T sibling) {
@@ -447,26 +448,34 @@ public class TreeData<T> implements Serializable {
"Item '" + item + "' not in the hierarchy");
}

if (!contains(sibling)) {
throw new IllegalArgumentException(
"Item '" + sibling + "' not in the hierarchy");
if (sibling == null) {
List<T> children = itemToWrapperMap.get(getParent(item))
.getChildren();

// Move item to first position
children.remove(item);
children.add(0, item);
} else {
if (!contains(sibling)) {
throw new IllegalArgumentException(
"Item '" + sibling + "' not in the hierarchy");
}

T parent = itemToWrapperMap.get(item).getParent();

if (!Objects.equals(parent,
itemToWrapperMap.get(sibling).getParent())) {
throw new IllegalArgumentException(
"Items '" + item + "' and '" + sibling
+ "' don't have the same parent");
}

List<T> children = itemToWrapperMap.get(parent).getChildren();

// Move item to the position after the sibling
children.remove(item);
children.add(children.indexOf(sibling) + 1, item);
}

T parent = itemToWrapperMap.get(item).getParent();

if (!Objects
.equals(parent, itemToWrapperMap.get(sibling).getParent())) {
throw new IllegalArgumentException(
"Items '" + item + "' and '" + sibling
+ "' don't have the same parent");
}

List<T> children = itemToWrapperMap.get(parent).getChildren();

// Move item to the position after the sibling
// If sibling is null, item is moved to the first position
children.remove(item);
children.add(children.indexOf(sibling) + 1, item);
}

/**

+ 13
- 0
server/src/test/java/com/vaadin/data/provider/TreeDataProviderTest.java View File

@@ -123,6 +123,19 @@ public class TreeDataProviderTest
data.moveAfterSibling(root0, null);
Assert.assertEquals(root0, data.getRootItems().get(0));
Assert.assertEquals(root9, data.getRootItems().get(9));

StrBean child0 = data.getChildren(root0).get(0);
StrBean child2 = data.getChildren(root0).get(2);

// Move first child to different position
data.moveAfterSibling(child0, child2);
Assert.assertEquals(2, data.getChildren(root0).indexOf(child0));
Assert.assertEquals(1, data.getChildren(root0).indexOf(child2));

// Move child back to first position
data.moveAfterSibling(child0, null);
Assert.assertEquals(0, data.getChildren(root0).indexOf(child0));
Assert.assertEquals(2, data.getChildren(root0).indexOf(child2));
}

@Test(expected = IllegalArgumentException.class)

Loading…
Cancel
Save