medkit/src/kit/section-tabs.tsx

351 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as React from "react"
import { type LucideIcon } from "lucide-react"
import { toast } from "sonner"
import { copyText } from "../lib/clipboard"
import { ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut } from "../ui/context-menu"
import { PageTabs } from "./page-tabs"
import { FrameMaximizeButton } from "./section-frame"
import { useShell } from "./shell-provider"
/**
* Вкладки внутри раздела.
*
* У каждого раздела (Пациенты, Врачи…) своя полоса вкладок: одна корневая
* (поиск/список, не закрывается) и сколько угодно открытых карточек.
* Вкладка запоминает последний адрес внутри себя (подраздел, ?q=, ?section=),
* поэтому при переключении человек возвращается ровно туда, где был.
* Набор вкладок переживает перезагрузку (localStorage, ключ `<storageKey>.section-tabs.<раздел>`).
* Адрес и переход берутся из ShellProvider.
*/
export type SectionTabTone = "male" | "female" | "neutral"
export interface SectionTab {
readonly id: string
readonly label: string
/** Базовый путь вкладки: всё, что начинается с него, — её территория. */
readonly base: string
/** Последний адрес внутри вкладки (pathname + search). */
readonly href: string
readonly letter?: string
readonly tone?: SectionTabTone
/** Причина красной точки на вкладке; пусто — точки нет. */
readonly alert?: string
readonly pinned?: boolean
/** Владеет только точным путём (корневая вкладка-список). */
readonly exact?: boolean
}
interface SectionTabsValue {
readonly section: string
readonly tabs: readonly SectionTab[]
readonly activeId: string | null
open: (tab: Omit<SectionTab, "href"> & { href?: string }, opts?: { focus?: boolean }) => void
close: (id: string) => void
closeOthers: (id: string) => void
closeToRight: (id: string) => void
closeAll: () => void
move: (fromId: string, toId: string) => void
activate: (id: string) => void
}
const SectionTabsContext = React.createContext<SectionTabsValue | null>(null)
const storageName = (storageKey: string, section: string) => `${storageKey}.section-tabs.${section}`
const changeEvent = (storageKey: string) => `${storageKey}:section-tabs`
/** Разделы, чей провайдер сейчас смонтирован, — им закрытие передаётся напрямую. Ключ — storageName. */
const mountedClosers = new Map<string, (id: string) => void>()
function readStored(storageKey: string, section: string): SectionTab[] | null {
try {
const raw = localStorage.getItem(storageName(storageKey, section))
return raw ? (JSON.parse(raw) as SectionTab[]) : null
} catch {
return null
}
}
function writeStored(storageKey: string, section: string, tabs: readonly SectionTab[]) {
try {
localStorage.setItem(storageName(storageKey, section), JSON.stringify(tabs))
window.dispatchEvent(new CustomEvent(changeEvent(storageKey), { detail: section }))
} catch {
/* приватный режим — живём без памяти */
}
}
function trimSlash(path: string) {
return path.replace(/\/+$/, "") || "/"
}
function findActive(tabs: readonly SectionTab[], pathname: string): SectionTab | null {
const path = trimSlash(pathname)
let best: SectionTab | null = null
for (const tab of tabs) {
const base = trimSlash(tab.base)
if (path === base || (!tab.exact && path.startsWith(base + "/"))) {
if (!best || base.length > trimSlash(best.base).length) best = tab
}
}
return best
}
export function SectionTabsProvider({
section,
root,
children,
}: {
section: string
root: Omit<SectionTab, "href" | "pinned">
children: React.ReactNode
}) {
const { pathname, search, navigate, storageKey } = useShell()
const [tabs, setTabs] = React.useState<SectionTab[]>(() => {
const rootTab: SectionTab = { ...root, href: root.base, pinned: true, exact: true }
const saved = readStored(storageKey, section)
const stored = saved?.filter((t) => t.id !== root.id) ?? []
const storedRoot = saved?.find((t) => t.id === root.id)
return [{ ...rootTab, href: storedRoot?.href ?? rootTab.href }, ...stored]
})
React.useEffect(() => {
writeStored(storageKey, section, tabs)
}, [storageKey, section, tabs])
const active = findActive(tabs, pathname)
const activeId = active?.id ?? null
// Вкладка помнит, где внутри неё находится пользователь.
const here = pathname + search
React.useEffect(() => {
if (!activeId) return
setTabs((list) =>
list.map((t) => (t.id === activeId && t.href !== here ? { ...t, href: here } : t)),
)
}, [activeId, here])
const tabsRef = React.useRef(tabs)
const activeRef = React.useRef(activeId)
React.useLayoutEffect(() => {
tabsRef.current = tabs
activeRef.current = activeId
})
const open = React.useCallback<SectionTabsValue["open"]>(
(tab, opts) => {
const focus = opts?.focus ?? true
const existing = tabsRef.current.find((t) => t.id === tab.id)
setTabs((list) => {
const index = list.findIndex((t) => t.id === tab.id)
if (index >= 0) {
const current = list[index]
// Явный href (быстрая ссылка на подраздел) важнее запомненного.
const next = { ...current, ...tab, href: tab.href ?? current.href }
return list.map((t, i) => (i === index ? next : t))
}
// Новая вкладка встаёт сразу справа от активной — как в браузере.
const activeIndex = list.findIndex((t) => t.id === activeRef.current)
const insertAt = activeIndex >= 0 ? activeIndex + 1 : list.length
const created: SectionTab = { ...tab, href: tab.href ?? tab.base }
return [...list.slice(0, insertAt), created, ...list.slice(insertAt)]
})
if (focus) navigate(tab.href ?? existing?.href ?? tab.base)
},
[navigate],
)
const removeWhere = React.useCallback(
(predicate: (tab: SectionTab, index: number) => boolean) => {
const list = tabsRef.current
const next = list.filter((t, i) => t.pinned || !predicate(t, i))
if (next.length === list.length) return
setTabs(next)
const currentId = activeRef.current
if (currentId && !next.some((t) => t.id === currentId)) {
const oldIndex = list.findIndex((t) => t.id === currentId)
const fallback = next[Math.min(oldIndex, next.length - 1)] ?? next[0]
if (fallback) navigate(fallback.href)
}
},
[navigate],
)
const value = React.useMemo<SectionTabsValue>(
() => ({
section,
tabs,
activeId,
open,
close: (id) => removeWhere((t) => t.id === id),
closeOthers: (id) => removeWhere((t) => t.id !== id),
closeToRight: (id) => {
const from = tabsRef.current.findIndex((t) => t.id === id)
removeWhere((_, i) => i > from)
},
closeAll: () => removeWhere(() => true),
move: (fromId, toId) =>
setTabs((list) => {
const from = list.findIndex((t) => t.id === fromId)
const to = list.findIndex((t) => t.id === toId)
if (from < 0 || to < 0 || from === to || list[from].pinned || list[to].pinned) return list
const next = [...list]
const [moved] = next.splice(from, 1)
next.splice(to, 0, moved)
return next
}),
activate: (id) => {
const tab = tabsRef.current.find((t) => t.id === id)
if (tab) navigate(tab.href)
},
}),
[section, tabs, activeId, open, removeWhere, navigate],
)
React.useEffect(() => {
const key = storageName(storageKey, section)
mountedClosers.set(key, value.close)
return () => {
mountedClosers.delete(key)
}
}, [storageKey, section, value.close])
return <SectionTabsContext.Provider value={value}>{children}</SectionTabsContext.Provider>
}
export function useSectionTabs() {
const ctx = React.useContext(SectionTabsContext)
if (!ctx) throw new Error("useSectionTabs — только внутри <SectionTabsProvider>")
return ctx
}
/** Страница-карточка регистрирует свою вкладку, если её ещё нет (прямой заход по ссылке). */
export function useRegisterSectionTab(tab: (Omit<SectionTab, "href"> & { href?: string }) | null) {
const { open } = useSectionTabs()
const key = tab ? JSON.stringify(tab) : null
React.useEffect(() => {
if (tab) open(tab, { focus: false })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, open])
}
/** Открытые (незакреплённые) вкладки раздела — для навигации, работает и вне провайдера. */
export function useStoredSectionTabs(section: string): readonly SectionTab[] {
const { storageKey } = useShell()
const [tabs, setTabs] = React.useState(() => readStored(storageKey, section) ?? [])
React.useEffect(() => {
// раздел сменился (тот же хук в другом пункте меню) — перечитываем сразу, не дожидаясь события
setTabs(readStored(storageKey, section) ?? [])
const sync = (event: Event) => {
if ((event as CustomEvent<string>).detail === section) setTabs(readStored(storageKey, section) ?? [])
}
const name = changeEvent(storageKey)
window.addEventListener(name, sync)
return () => window.removeEventListener(name, sync)
}, [storageKey, section])
return React.useMemo(() => tabs.filter((t) => !t.pinned), [tabs])
}
/** Закрыть вкладку раздела снаружи (например, из бокового меню); раздел может быть и не смонтирован. */
export function useCloseSectionTab() {
const { storageKey } = useShell()
return React.useCallback(
(section: string, id: string) => {
const close = mountedClosers.get(storageName(storageKey, section))
if (close) {
close(id)
return
}
const stored = readStored(storageKey, section)
if (stored) writeStored(storageKey, section, stored.filter((t) => t.pinned || t.id !== id))
},
[storageKey],
)
}
/** PageTabs, подключённые к вкладкам раздела: роутинг, хоткеи, контекстное меню. */
export function SectionTabsBar({ rootIcon, actions }: { rootIcon: LucideIcon; actions?: React.ReactNode }) {
const { tabs, activeId, activate, close, closeOthers, closeToRight, closeAll, move } = useSectionTabs()
const { toHref } = useShell()
// Alt+1…9 — перейти на вкладку, Alt+W — закрыть текущую.
React.useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if (!event.altKey || event.metaKey || event.ctrlKey) return
const digit = /^Digit([1-9])$/.exec(event.code)?.[1]
if (digit) {
const tab = digit === "9" ? tabs.at(-1) : tabs[Number(digit) - 1]
if (tab) {
event.preventDefault()
activate(tab.id)
}
} else if (event.code === "KeyW" && activeId) {
event.preventDefault()
close(activeId)
}
}
window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [tabs, activeId, activate, close])
const items = React.useMemo(
() => tabs.map((t) => ({ ...t, icon: t.pinned ? rootIcon : undefined })),
[tabs, rootIcon],
)
return (
<PageTabs
tabs={items}
activeId={activeId}
onSelect={activate}
onClose={close}
onMove={move}
hotkeyHints
actions={
<>
{actions}
<FrameMaximizeButton />
</>
}
renderMenu={(item) => {
const tab = tabs.find((t) => t.id === item.id)!
return (
<>
<ContextMenuItem onSelect={() => activate(tab.id)}>Открыть</ContextMenuItem>
<ContextMenuItem
onSelect={() => {
copyText(window.location.origin + toHref(tab.href)).then(
() => toast.success("Ссылка скопирована", { description: tab.label }),
() => toast.error("Не удалось скопировать ссылку"),
)
}}
>
Скопировать ссылку
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem disabled={tab.pinned} onSelect={() => close(tab.id)}>
Закрыть
<ContextMenuShortcut>Alt W</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuItem onSelect={() => closeOthers(tab.id)}>Закрыть остальные</ContextMenuItem>
<ContextMenuItem onSelect={() => closeToRight(tab.id)}>Закрыть справа</ContextMenuItem>
<ContextMenuItem variant="destructive" onSelect={closeAll}>
Закрыть все карточки
</ContextMenuItem>
</>
)
}}
/>
)
}