Skip to content

Commit

Permalink
refactor(plugins/mpa): use custom hook resolve tabs
Browse files Browse the repository at this point in the history
  • Loading branch information
NWYLZW committed Nov 12, 2023
1 parent 6e8fb7e commit f304351
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 13 deletions.
47 changes: 44 additions & 3 deletions core/src/plugins/mpa/atoms.ts
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])
}
}
19 changes: 9 additions & 10 deletions core/src/plugins/mpa/topbar/Files.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
import './Files.scss'

import { useEffect, useMemo } from 'react'
import { useAtom, useStore } from 'jotai'
import { useEffect, useMemo, useRef } from 'react'

import { classnames } from '../../../utils'
import type { BarItemProps } from '../..'
import { tabsAtom } from '../atoms'
import { useTabs } from '../atoms'

const prefix = 'mpa__topbar__files'

export const Files: React.ComponentType<BarItemProps> = () => {
const [
tabs, setTabs
] = useAtom(tabsAtom, { store: useStore() })
const { tabs, addTab } = useTabs()
const addOnlyOnce = useRef(false)
useEffect(() => {
if (addOnlyOnce.current) return

addOnlyOnce.current = true
if (tabs.length === 0) {
// TODO only editor mounted?
setTabs([
{ id: 'index.ts', title: 'index.ts', icon: 'file', active: true }
])
addTab({ id: 'index.ts', title: 'index.ts', icon: 'file', active: true })
}
}, [setTabs, tabs.length])
}, [addTab, tabs.length])
const activeTabId = useMemo(() => tabs.find(tab => tab.active)?.id, [tabs])
return <div className={prefix}>
{tabs.map(tab => <div
Expand Down

0 comments on commit f304351

Please sign in to comment.