Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter a tree #1456

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 22 additions & 45 deletions packages/radix-vue/src/Tree/TreeRoot.vue
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,6 @@ interface TreeRootContext<T = Record<string, any>> {
handleMultipleReplace: ReturnType<typeof useSelectionBehavior>['handleMultipleReplace']
}

export type FlattenedItem<T> = {
_id: string
index: number
value: T
level: number
hasChildren: boolean
parentItem?: T
bind: {
value: T
level: number
[key: string]: any
}
}

export const [injectTreeRootContext, provideTreeRootContext] = createContext<TreeRootContext<any>>('TreeRoot')
</script>

Expand All @@ -78,6 +64,7 @@ import { type EventHook, createEventHook, useVModel } from '@vueuse/core'
import { RovingFocusGroup } from '@/RovingFocus'
import { type Ref, computed, nextTick, ref, toRefs } from 'vue'
import { MAP_KEY_TO_FOCUS_INTENT } from '@/RovingFocus/utils'
import { flattenedItems, flattenItems, flattenFilter } from './utils'

const props = withDefaults(defineProps<TreeRootProps<T, U>>(), {
as: 'ul',
Expand Down Expand Up @@ -126,39 +113,29 @@ const selectedKeys = computed(() => {
return [props.getKey(modelValue.value as any ?? {})]
})

function flattenItems(items: T[], level: number = 1, parentItem?: T): FlattenedItem<T>[] {
return items.reduce((acc: FlattenedItem<T>[], item: T, index: number) => {
const key = props.getKey(item)
const children = props.getChildren(item)
const isExpanded = expanded.value.includes(key)

const flattenedItem: FlattenedItem<T> = {
_id: key,
value: item,
index,
level,
parentItem,
hasChildren: !!children,
bind: {
'value': item,
level,
'aria-setsize': items.length,
'aria-posinset': index + 1,
},
}
acc.push(flattenedItem)

if (children && isExpanded)
acc.push(...flattenItems(children, level + 1, item))

return acc
}, [])
}
const stext = ref<string>('')
const searchFunc : (T)=>bool = (i) ->props.getKey(item).toLowerCase().includes(stext.value)
const searchForceVisible = ref<string[]>([])

const expandedItems = computed(() => {
const items = props.items
const expandedKeys = expanded.value.map(i => i)
return flattenItems(items ?? [])
const items = props.items ?? []
const expandedKeys = expanded.value.map((i) => i)
// when no search
if (search.value === '') {
return flattenItems(items, {
expanded: expandedKeys,
getKey: props.getKey,
getChildren: props.getChildren,
})
} else {
const st = search.value.toLowerCase()
return flattenFilter(items, {
predicate: searchFunc.value,
forceVisible: searchForceVisible.value,
getKey: props.getKey,
getChildren: props.getChildren,
})
}
})

function handleKeydown(event: KeyboardEvent) {
Expand Down
45 changes: 45 additions & 0 deletions packages/radix-vue/src/Tree/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { describe, expect, it } from 'vitest'

import { flattenFilter } from './utils'

describe('Tree', () => {
describe('flattenFilter', () => {
it('should return the filtered items and expanded keys', () => {
const items = [
{
name: 'a',
children: [
{
name: 'b',
children: [{ name: 'c' }],
},
{
name: 'd',
children: [],
},
],
},
{
name: 'e',
children: [{ name: 'f' }],
},
]

const predicate = (item: any) => ['c', 'e'].includes(item.name)
const getKey = (item: any) => item.name

const result = flattenFilter(items, {
predicate,
getKey,
getChildren: (item: any) => item.children,
forceVisible: [],
})

const names = result.result.map((item) => item._id)
expect(names).toEqual(['a', 'b', 'c', 'e'])

expect(result.expanded.sort()).toEqual(['a', 'b'])

})
})
})
127 changes: 125 additions & 2 deletions packages/radix-vue/src/Tree/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export function flatten<U, T extends { children: any[] } >(items: T[]): U[] {
export function flatten<U, T extends { children: any[] }>(items: T[]): U[] {
return items.reduce((acc: any[], item: T) => {
acc.push(item)

Expand All @@ -9,4 +9,127 @@ export function flatten<U, T extends { children: any[] } >(items: T[]): U[] {
}, [])
}

// TODO: expose more utility function to handle flattened item
export type FlattenedItem<T> = {
_id: string
index: number
value: T
level: number
hasChildren: boolean
parentItem?: T
bind: {
value: T
level: number
[key: string]: any
}
}

export function flattenItems<T>(
items: T[],
ctx: {
getKey: (item: T) => string
getChildren: (item: T) => T[] | undefined
expanded: string[]
},
): FlattenedItem<T>[] {
const expandedSet = new Set(ctx.expanded)
const flatNoFilter = (items: T[], level: number, parentItem?: T) =>
items.reduce((acc: FlattenedItem<T>[], item: T, index: number) => {
const key = ctx.getKey(item)
const children = ctx.getChildren(item)

const flattenedItem: FlattenedItem<T> = {
_id: key,
value: item,
index,
level,
parentItem,
hasChildren: !!children,
bind: {
value: item,
level,
'aria-setsize': items.length,
'aria-posinset': index + 1,
},
}
acc.push(flattenedItem)

if (children && expandedSet.has(key))
acc.push(...flatNoFilter(children, level + 1, item))

return acc
}, [])

return flatNoFilter(items, 1)
}

export function flattenFilter<T>(
items: T[],
ctx: {
getKey: (item: T) => string
getChildren: (item: T) => T[] | undefined
predicate: (item: T) => boolean
forceVisible: string[]
},
): {
result: FlattenedItem<T>[]
expanded: string[]
} {
const expanded: string[] = []
const forceVisibleSet = new Set(ctx.forceVisible)

const flatFilter = (
itms: T[] | undefined,
force: boolean,
level: number,
parentItem?: T,
) =>
itms
? itms.reduce((acc: FlattenedItem<T>[], item: T, index: number) => {
const iMatch = force || ctx.predicate(item)
const key = ctx.getKey(item)
const children = ctx.getChildren(item)
//console.log('iMatch', iMatch, iKey, force)

const cCnt = children ? children.length : 0

const flattenedItem: FlattenedItem<T> = {
_id: key,
value: item,
index,
level,
parentItem,
hasChildren: cCnt > 0,
bind: {
value: item,
level,
'aria-setsize': items.length,
'aria-posinset': index + 1,
},
}

if (cCnt === 0) {
if (iMatch) acc.push(flattenedItem)
return acc
}
// check if children match, then add parent and add to expanded
const cres = flatFilter(
children,
forceVisibleSet.has(key),
level + 1,
item,
)
if (cres.length > 0) {
acc.push(flattenedItem)
expanded.push(key)
acc.push(...cres)
} else if (iMatch) {
acc.push(flattenedItem)
}

//console.log('return from flatFilter', acc)
return acc
}, [])
: []
const result = flatFilter(items, true, 1, undefined)
return { result, expanded }
}