diff --git a/src/mixins/treeselectMixin.js b/src/mixins/treeselectMixin.js index fa712a0f..cee94130 100644 --- a/src/mixins/treeselectMixin.js +++ b/src/mixins/treeselectMixin.js @@ -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() { @@ -961,6 +969,7 @@ export default { } this.hasBranchNodes = this.forest.normalizedOptions.some(rootNode => rootNode.isBranch) + this.expandParentNodes() }, getInstanceId() { @@ -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()) }, @@ -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() } @@ -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() {