-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(plugins/mpa): use custom hook resolve tabs
- Loading branch information
Showing
2 changed files
with
53 additions
and
13 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,50 @@ | ||
import { atom } from 'jotai' | ||
import { useCallback } from 'react' | ||
import { atom, useAtom, useStore } from 'jotai' | ||
|
||
export const tabsAtom = atom<{ | ||
interface Tab { | ||
id: string | ||
icon?: string | ||
title: string | ||
closeable?: boolean | ||
active?: boolean | ||
}[]>([]) | ||
} | ||
|
||
export const tabsAtom = atom<Tab[]>([]) | ||
|
||
export const useTabs = () => { | ||
const [tabs, setTabs] = useAtom(tabsAtom, { store: useStore() }) | ||
return { | ||
tabs, | ||
setActiveTab: useCallback((id: string) => { | ||
setTabs(tabs => tabs.map(tab => ({ ...tab, active: tab.id === id }))) | ||
}, [setTabs]), | ||
addTab: useCallback((tab: Tab, options?: { | ||
} & ( | ||
| { | ||
beforeActive?: boolean | ||
} | ||
| { | ||
afterActive?: boolean | ||
} | ||
)) => { | ||
const { | ||
// @ts-ignore | ||
beforeActive, afterActive | ||
} = options ?? { | ||
beforeActive: true, | ||
afterActive: false | ||
} | ||
setTabs(tabs => { | ||
const activeIndex = tabs.findIndex(tab => tab.active) | ||
const index = activeIndex !== -1 ? ( | ||
activeIndex + (beforeActive ? 0 : 1) + (afterActive ? 1 : 0) | ||
) : 0 | ||
return [ | ||
...tabs.slice(0, index), | ||
tab, | ||
...tabs.slice(index) | ||
] | ||
}) | ||
}, [setTabs]) | ||
} | ||
} |
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