Skip to content

Commit

Permalink
fix: Expand parent nodes of selected item. riophae#310
Browse files Browse the repository at this point in the history
Scroll menu to selected item, by center. Pull request by varlamov88.
  • Loading branch information
almas committed Aug 8, 2021
1 parent 43be769 commit 8b6a1f1
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/mixins/treeselectMixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,14 @@ export default {
type: [ Number, String ],
default: 999,
},

/**
* Set selected option to the center of the menu, if possible
*/
scrollPositionOnCenter: {
type: Boolean,
default: false
}
},

data() {
Expand Down Expand Up @@ -961,6 +969,7 @@ export default {
}

this.hasBranchNodes = this.forest.normalizedOptions.some(rootNode => rootNode.isBranch)
this.expandParentNodes()
},

getInstanceId() {
Expand Down Expand Up @@ -1525,6 +1534,9 @@ export default {
this.$nextTick(this.restoreMenuScrollPosition)
if (!this.options && !this.async) this.loadRootOptions()
this.toggleClickOutsideEvent(true)
if (this.scrollPositionOnCenter) {
this.$nextTick(this.scrollMenuOnCenter);
}
this.$emit('open', this.getInstanceId())
},

Expand Down Expand Up @@ -1843,12 +1855,16 @@ export default {
this.buildForestState()

if (nextState) {
this.expandParentNodes();
this.$emit('select', node.raw, this.getInstanceId())
} else {
this.$emit('deselect', node.raw, this.getInstanceId())
}

if (this.localSearch.active && nextState && (this.single || this.clearOnSelect)) {
if (this.scrollPositionOnCenter) {
this.$nextTick(this.scrollMenuOnCenter);
}
this.resetSearchQuery()
}

Expand Down Expand Up @@ -1990,16 +2006,36 @@ export default {
},

saveMenuScrollPosition() {
if (this.scrollPositionOnCenter) return;
const $menu = this.getMenu()
// istanbul ignore else
if ($menu) this.menu.lastScrollPosition = $menu.scrollTop
},

restoreMenuScrollPosition() {
if (this.scrollPositionOnCenter) return;
const $menu = this.getMenu()
// istanbul ignore else
if ($menu) $menu.scrollTop = this.menu.lastScrollPosition
},

scrollMenuOnCenter() {
const $option = document.querySelector(".vue-treeselect__option--selected");
const $menu = this.getMenu();

if ($option && $menu) {
const position = Math.max($option.offsetTop - (($menu.offsetHeight - $option.offsetHeight) / 2), 0);
$menu.scrollTop = position;
}
},

expandParentNodes() {
for (const id of this.forest.selectedNodeIds) {
for (const ancestor of this.forest.nodeMap[id].ancestors) {
ancestor.isExpanded = true;
}
}
}
},

created() {
Expand Down

0 comments on commit 8b6a1f1

Please sign in to comment.