-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Extract tree expand/collapse logic as hook
- Loading branch information
Showing
2 changed files
with
77 additions
and
42 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import { ref } from 'vue' | ||
import type { TreeNode } from 'primevue/treenode' | ||
|
||
export function useTreeExpansion() { | ||
const expandedKeys = ref<Record<string, boolean>>({}) | ||
|
||
const toggleNode = (node: TreeNode) => { | ||
if (node.key && typeof node.key === 'string') { | ||
if (node.key in expandedKeys.value) { | ||
delete expandedKeys.value[node.key] | ||
} else { | ||
expandedKeys.value[node.key] = true | ||
} | ||
} | ||
} | ||
|
||
const toggleNodeRecursive = (node: TreeNode) => { | ||
if (node.key && typeof node.key === 'string') { | ||
if (node.key in expandedKeys.value) { | ||
collapseNode(node) | ||
} else { | ||
expandNode(node) | ||
} | ||
} | ||
} | ||
|
||
const expandNode = (node: TreeNode) => { | ||
if ( | ||
node.key && | ||
typeof node.key === 'string' && | ||
node.children && | ||
node.children.length | ||
) { | ||
expandedKeys.value[node.key] = true | ||
|
||
for (const child of node.children) { | ||
expandNode(child) | ||
} | ||
} | ||
} | ||
|
||
const collapseNode = (node: TreeNode) => { | ||
if ( | ||
node.key && | ||
typeof node.key === 'string' && | ||
node.children && | ||
node.children.length | ||
) { | ||
delete expandedKeys.value[node.key] | ||
|
||
for (const child of node.children) { | ||
collapseNode(child) | ||
} | ||
} | ||
} | ||
|
||
const onNonLeafClick = (e: MouseEvent, node: TreeNode) => { | ||
if (e.ctrlKey) { | ||
toggleNodeRecursive(node) | ||
} else { | ||
toggleNode(node) | ||
} | ||
} | ||
|
||
return { | ||
expandedKeys, | ||
toggleNode, | ||
toggleNodeRecursive, | ||
expandNode, | ||
collapseNode, | ||
onNonLeafClick | ||
} | ||
} |