Skip to content

Commit

Permalink
feat(docz): add filter option for useMenus
Browse files Browse the repository at this point in the history
  • Loading branch information
pedronauck committed Mar 12, 2019
1 parent 01004ed commit aeeb311
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
17 changes: 15 additions & 2 deletions core/docz/src/hooks/useMenus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const fromMenu = (menu: string) => (entry: Entry) => entry.menu === menu
const entryAsMenu = (entry: Entry) => ({
name: entry.name,
route: entry.route,
parent: entry.parent,
})

const entriesOfMenu = (menu: string, entries: Entry[]) =>
Expand All @@ -35,10 +36,10 @@ const parseItemStr = (item: MenuItem | string) =>

const normalize = (item: MenuItem | string): MenuItem => {
const selected = parseItemStr(item) as MenuItem

return {
...selected,
id: selected.id || ulid(),
parent: get('parent', selected) || get('parent', item),
menu: Array.isArray(selected.menu)
? selected.menu.map(normalize)
: selected.menu,
Expand Down Expand Up @@ -114,8 +115,19 @@ const search = (val: string, menu: MenuItem[]) => {
return match(flattenedDeduplicated, val, { keys: ['name'] })
}

type FilterFn = (item: MenuItem) => boolean

const filterMenus = (items: MenuItem[], filter?: FilterFn) => {
if (!filter) return items
return items.filter(filter).map(item => {
if (!item.menu) return item
return { ...item, menu: item.menu.filter(filter) }
})
}

export interface UseMenusParams {
query?: string
filter?: FilterFn
}

export const useMenus = (opts?: UseMenusParams) => {
Expand All @@ -127,7 +139,8 @@ export const useMenus = (opts?: UseMenusParams) => {
const entriesMenu = menusFromEntries(arr)
const sorted = useMemo(() => {
const merged = mergeMenus(entriesMenu as MenuItem[], config.menu)
return sortMenus(merged, config.menu)
const result = sortMenus(merged, config.menu)
return filterMenus(result, opts && opts.filter)
}, [entries, config])

return query && query.length > 0
Expand Down
1 change: 1 addition & 0 deletions core/docz/src/state.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export interface MenuItem {
href?: string
menu?: MenuItem[]
order?: number
parent?: string
}

export type ThemeConfig = Record<string, any>
Expand Down

0 comments on commit aeeb311

Please sign in to comment.