77 lines
3.1 KiB
TypeScript
77 lines
3.1 KiB
TypeScript
import * as React from "react"
|
||
|
||
/**
|
||
* Роутер и пространство имён приложения для каркаса окна (AppShell, AppSidebar, вкладки разделов).
|
||
* Кит не знает про react-router: приложение передаёт текущий адрес и переход.
|
||
* `storageKey` — префикс ключей localStorage («ml», «lis»): у приложений на одном домене память не смешивается.
|
||
* `basename` — префикс адресов приложения (как у роутера): нужен только для href ссылок и «Скопировать ссылку».
|
||
*
|
||
* С react-router:
|
||
* ```tsx
|
||
* const location = useLocation()
|
||
* <ShellProvider storageKey="ml" pathname={location.pathname} search={location.search} navigate={useNavigate()}>
|
||
* ```
|
||
*/
|
||
export interface ShellValue {
|
||
readonly pathname: string
|
||
readonly search: string
|
||
readonly navigate: (href: string) => void
|
||
readonly storageKey: string
|
||
/** Полный href для адреса внутри приложения: basename + путь. */
|
||
readonly toHref: (path: string) => string
|
||
}
|
||
|
||
const ShellContext = React.createContext<ShellValue | null>(null)
|
||
|
||
export function ShellProvider({
|
||
pathname,
|
||
search = "",
|
||
navigate,
|
||
storageKey,
|
||
basename = "",
|
||
children,
|
||
}: {
|
||
pathname: string
|
||
search?: string
|
||
navigate: (href: string) => void
|
||
storageKey: string
|
||
basename?: string
|
||
children: React.ReactNode
|
||
}) {
|
||
// navigate из react-router меняется на каждый переход — держим последний в ref, наружу отдаём стабильную функцию
|
||
const navigateRef = React.useRef(navigate)
|
||
React.useLayoutEffect(() => {
|
||
navigateRef.current = navigate
|
||
})
|
||
const stableNavigate = React.useCallback((href: string) => navigateRef.current(href), [])
|
||
|
||
const value = React.useMemo<ShellValue>(() => {
|
||
const base = basename.replace(/\/+$/, "")
|
||
return { pathname, search, navigate: stableNavigate, storageKey, toHref: (path) => base + path }
|
||
}, [pathname, search, stableNavigate, storageKey, basename])
|
||
return <ShellContext.Provider value={value}>{children}</ShellContext.Provider>
|
||
}
|
||
|
||
export function useShell(): ShellValue {
|
||
const ctx = React.useContext(ShellContext)
|
||
if (!ctx) throw new Error("Каркас окна (AppShell, вкладки разделов) должен быть внутри <ShellProvider>")
|
||
return ctx
|
||
}
|
||
|
||
/** Ссылка для каркаса: обычный клик — переход роутером, Ctrl/⌘/средняя кнопка — новая вкладка браузера. */
|
||
export function ShellLink({ href, onClick, ...props }: React.ComponentProps<"a"> & { href: string }) {
|
||
const { navigate, toHref } = useShell()
|
||
return (
|
||
<a
|
||
href={toHref(href)}
|
||
onClick={(e) => {
|
||
onClick?.(e)
|
||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return
|
||
e.preventDefault()
|
||
navigate(href)
|
||
}}
|
||
{...props}
|
||
/>
|
||
)
|
||
}
|