feat: add filter node by text

This commit is contained in:
Methapon Metanipat 2024-10-16 13:19:31 +07:00
parent f01e3d4ca9
commit 35c8a0ffb3
2 changed files with 197 additions and 170 deletions

View file

@ -39,6 +39,7 @@ type Props = {
const props = defineProps<Props>(); const props = defineProps<Props>();
const nodes = defineModel<Node[]>('nodes', { required: true }); const nodes = defineModel<Node[]>('nodes', { required: true });
const filterText = defineModel<string>('filterText', { required: false });
const emits = defineEmits<{ const emits = defineEmits<{
(e: 'checked'): void; (e: 'checked'): void;
@ -91,6 +92,25 @@ function toggleExpand(node: Node, ancestor?: []) {
node.opened = !node.opened; node.opened = !node.opened;
emits('open', node, ancestor); emits('open', node, ancestor);
} }
function filterNode(text: string, node: Node, ancestor?: Node[]) {
if (!text) return;
const getTitle = (n: Node): string => n[props.keyTitle || 'title'];
const getSubtitle = (n: Node): string => n[props.keySubtitle || 'subtitle'];
const recursiveFilter = (n: Node): boolean => {
if (!n.children) {
return getTitle(n).includes(text) || getSubtitle(n).includes(text);
}
return n.children.some((v) => recursiveFilter(v));
};
return (
ancestor?.some(
(v) => getTitle(v).includes(text) || getSubtitle(v).includes(text),
) || recursiveFilter(node)
);
}
</script> </script>
<template> <template>
@ -101,7 +121,11 @@ function toggleExpand(node: Node, ancestor?: []) {
'last-children': level && level === maxLevel, 'last-children': level && level === maxLevel,
}" }"
> >
<div v-for="(node, i) in nodes" class="tree-item" :key="i"> <template v-for="(node, i) in nodes" :key="i">
<div
class="tree-item"
v-if="filterText ? filterNode(filterText, node, ancestorNode) : true"
>
<slot <slot
v-if="$slots['item']" v-if="$slots['item']"
name="item" name="item"
@ -232,6 +256,7 @@ function toggleExpand(node: Node, ancestor?: []) {
:hideCheckBox :hideCheckBox
:selectable :selectable
:selectedNode :selectedNode
:filterText
:deleteable="deleteableDeep" :deleteable="deleteableDeep"
class="item__children" class="item__children"
v-if="node.children" v-if="node.children"
@ -284,6 +309,7 @@ function toggleExpand(node: Node, ancestor?: []) {
</transition> </transition>
<q-separator v-if="!level && i !== nodes.length - 1" class="q-mt-sm" /> <q-separator v-if="!level && i !== nodes.length - 1" class="q-mt-sm" />
</div> </div>
</template>
</div> </div>
</template> </template>

View file

@ -540,6 +540,7 @@ watch(
movable movable
deleteable deleteable
selectable selectable
:filter-text="inputSearch"
:selected-node="selectedNode" :selected-node="selectedNode"
@move-up="(node) => toggleMove(node, 'up')" @move-up="(node) => toggleMove(node, 'up')"
@move-down="(node) => toggleMove(node, 'down')" @move-down="(node) => toggleMove(node, 'down')"