Window shell, section tabs, CopyValue, SearchField, release 0.5.0
The shell used to be copied into every app; now it lives in the kit: - ShellProvider: the app passes location, navigate, storageKey and basename, so the kit stays router-agnostic and apps on one domain keep separate storage - AppShell and AppSidebar: groups, badges, disabled items, open section tabs, search button, user menu; logo and header extras come from props - SectionFrame with Alt+F maximize, SectionTabsProvider/SectionTabsBar and hooks, useCloseSectionTab instead of closeSectionTab - createStore in lib/store - CopyValue: click to copy with a short "Скопировано" tooltip - SearchField: debounced filter, Enter applies at once, optional select for the next scan - SearchInput: a passed onKeyDown no longer disables Esc-to-clear Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4d04e9af68
commit
96239dd064
20
README.md
20
README.md
|
|
@ -18,7 +18,7 @@ src/styles.css тема (токены, шрифты, тёмный режим)
|
|||
Пакет ставится прямо из git, версии — теги `vX.Y.Z`:
|
||||
|
||||
```bash
|
||||
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.4.0"
|
||||
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.5.0"
|
||||
```
|
||||
|
||||
`package-lock.json` фиксирует коммит; обновиться до свежего тега — `npm update @medkit/ui`. В medicine-ui kit подключён git-submodule в `packages/medkit` (npm workspace) — правки видны сразу.
|
||||
|
|
@ -55,6 +55,24 @@ CSS приложения:
|
|||
|
||||
`NotifyToaster` без `navigate` переходит по `href` через `window.location.assign`.
|
||||
|
||||
Каркас окна (меню, рамка раздела, вкладки разделов) роутера не знает — адрес и переход даёт `ShellProvider`:
|
||||
|
||||
```tsx
|
||||
function App() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
return (
|
||||
<ShellProvider storageKey="lis" basename="/medicine-lis" pathname={location.pathname} search={location.search} navigate={navigate}>
|
||||
<Routes>
|
||||
<Route element={<AppShell sidebar={{ logo, groups, search, user, userMenu }}><Outlet /></AppShell>}>…</Route>
|
||||
</Routes>
|
||||
</ShellProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`storageKey` — префикс ключей localStorage (вкладки, свёрнутое меню): у приложений на одном домене память не смешивается.
|
||||
|
||||
Peer-зависимости: `react`, `react-dom` 19, `tailwindcss` 4. В Vite-проекте ничего настраивать не нужно.
|
||||
|
||||
## Правила для кода пакета
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@medkit/ui",
|
||||
"version": "0.4.0",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)",
|
||||
"repository": {
|
||||
|
|
|
|||
|
|
@ -44,5 +44,6 @@ export * from "./hooks/use-media-query"
|
|||
export * from "./lib/clipboard"
|
||||
export * from "./lib/format"
|
||||
export * from "./lib/masks"
|
||||
export * from "./lib/store"
|
||||
export * from "./lib/utils"
|
||||
export * from "./theme-provider"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,58 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { useMediaQuery } from "../hooks/use-media-query"
|
||||
import { cn } from "../lib/utils"
|
||||
import { AppSidebar, type AppSidebarProps } from "./app-sidebar"
|
||||
import { useShell } from "./shell-provider"
|
||||
|
||||
/**
|
||||
* Каркас окна: тёмное меню слева, справа — лист с текущим разделом (`children`, обычно `<Outlet />`).
|
||||
* Окно целиком не прокручивается — только тело раздела. Свёрнутость меню помнится
|
||||
* (`<storageKey>.sidebar-collapsed`), на узком экране меню всегда свёрнуто. При печати меню скрыто.
|
||||
* Нужен ShellProvider выше.
|
||||
*/
|
||||
export function AppShell({
|
||||
sidebar,
|
||||
className,
|
||||
children,
|
||||
}: {
|
||||
sidebar: Omit<AppSidebarProps, "collapsed" | "onToggle">
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { storageKey } = useShell()
|
||||
const collapsedKey = `${storageKey}.sidebar-collapsed`
|
||||
const [collapsed, setCollapsed] = React.useState(() => {
|
||||
try {
|
||||
return localStorage.getItem(collapsedKey) === "1"
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
// На узких экранах меню — всегда полоса иконок, иначе контенту не остаётся места.
|
||||
const narrow = useMediaQuery("(max-width: 767px)")
|
||||
|
||||
const toggle = () =>
|
||||
setCollapsed((v) => {
|
||||
try {
|
||||
localStorage.setItem(collapsedKey, v ? "0" : "1")
|
||||
} catch {
|
||||
// не запомнили — не страшно
|
||||
}
|
||||
return !v
|
||||
})
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-svh overflow-hidden bg-sidebar print:block print:h-auto print:overflow-visible print:bg-transparent",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<AppSidebar {...sidebar} collapsed={collapsed || narrow} onToggle={toggle} />
|
||||
<main className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-background lg:my-2 lg:mr-2 lg:rounded-2xl print:m-0 print:block print:overflow-visible print:rounded-none print:bg-transparent">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,383 @@
|
|||
import * as React from "react"
|
||||
import { ChevronRightIcon, PanelLeftCloseIcon, PanelLeftOpenIcon, SearchIcon, XIcon, type LucideIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "../lib/utils"
|
||||
import { Avatar, AvatarFallback } from "../ui/avatar"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from "../ui/dropdown-menu"
|
||||
import { Kbd } from "../ui/kbd"
|
||||
import { ScrollArea } from "../ui/scroll-area"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
||||
import { MAX_VISIBLE_TABS, splitTabs } from "./page-tabs"
|
||||
import { useCloseSectionTab, useStoredSectionTabs, type SectionTab } from "./section-tabs"
|
||||
import { ShellLink, useShell } from "./shell-provider"
|
||||
|
||||
export interface SidebarNavItem {
|
||||
readonly to: string
|
||||
readonly label: string
|
||||
readonly icon: LucideIcon
|
||||
/** Счётчик справа от названия (непрочитанное, ждёт действия); 0 — не показывается. */
|
||||
readonly badge?: number
|
||||
/** Цвет счётчика: negative — красный (по умолчанию), warning — жёлтый. */
|
||||
readonly badgeTone?: "negative" | "warning"
|
||||
/** Раздел ещё не готов: серый, без перехода. */
|
||||
readonly disabled?: boolean
|
||||
/** Раздел со вкладками (SectionTabsProvider section=…): под пунктом — открытые карточки. */
|
||||
readonly tabsSection?: string
|
||||
/** Когда пункт активен; по умолчанию — адрес равен `to` или начинается с `to/`. */
|
||||
readonly match?: (pathname: string) => boolean
|
||||
}
|
||||
|
||||
export interface SidebarNavGroup {
|
||||
readonly label: string
|
||||
readonly items: readonly SidebarNavItem[]
|
||||
}
|
||||
|
||||
export interface SidebarSearch {
|
||||
/** Подпись кнопки («Поиск», «Штрихкод»). */
|
||||
readonly label: string
|
||||
/** Подсказка в свёрнутом меню. */
|
||||
readonly tooltip: string
|
||||
readonly shortcut?: string
|
||||
readonly icon?: LucideIcon
|
||||
readonly onClick: () => void
|
||||
}
|
||||
|
||||
export interface SidebarUser {
|
||||
readonly name: string
|
||||
readonly subtitle?: string
|
||||
readonly initials: string
|
||||
}
|
||||
|
||||
export interface AppSidebarProps {
|
||||
collapsed: boolean
|
||||
onToggle: () => void
|
||||
/** Логотип; получает свёрнутость меню. */
|
||||
logo: (collapsed: boolean) => React.ReactNode
|
||||
/** Справа от логотипа в развёрнутом меню (часы, окружение). */
|
||||
headerExtra?: React.ReactNode
|
||||
search?: SidebarSearch
|
||||
groups: readonly SidebarNavGroup[]
|
||||
user?: SidebarUser
|
||||
/** Пункты меню пользователя (DropdownMenuLabel, DropdownMenuItem…). */
|
||||
userMenu?: React.ReactNode
|
||||
className?: string
|
||||
}
|
||||
|
||||
const toneDot = (tone: SectionTab["tone"], fallback: string) =>
|
||||
tone === "female" ? "bg-female" : tone === "male" ? "bg-male" : fallback
|
||||
|
||||
/**
|
||||
* Тёмное боковое меню: логотип, кнопка поиска, разделы группами со счётчиками,
|
||||
* открытые карточки разделов со вкладками, пользователь и сворачивание. Обычно — внутри AppShell.
|
||||
*/
|
||||
export function AppSidebar({
|
||||
collapsed,
|
||||
onToggle,
|
||||
logo,
|
||||
headerExtra,
|
||||
search,
|
||||
groups,
|
||||
user,
|
||||
userMenu,
|
||||
className,
|
||||
}: AppSidebarProps) {
|
||||
const SearchItemIcon = search?.icon ?? SearchIcon
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
"flex h-svh shrink-0 flex-col overflow-hidden bg-sidebar text-sidebar-foreground transition-[width] duration-200 print:hidden",
|
||||
collapsed ? "w-[60px]" : "w-56",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className={cn("flex h-14 shrink-0 items-center", collapsed ? "justify-center" : "gap-2.5 px-5")}>
|
||||
{logo(collapsed)}
|
||||
{!collapsed && headerExtra}
|
||||
</div>
|
||||
|
||||
{search && (
|
||||
<div className="shrink-0 px-3 pb-1">
|
||||
<SidebarTooltip label={search.tooltip} enabled={collapsed}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={search.onClick}
|
||||
aria-label={collapsed ? search.tooltip : undefined}
|
||||
className={cn(
|
||||
"flex h-9 w-full items-center gap-2 rounded-lg border border-sidebar-border bg-white/[0.03] text-sm text-sidebar-muted transition hover:bg-white/[0.06] hover:text-sidebar-foreground",
|
||||
collapsed ? "justify-center" : "px-3",
|
||||
)}
|
||||
>
|
||||
<SearchItemIcon className="size-4 shrink-0" />
|
||||
{!collapsed && (
|
||||
<>
|
||||
<span className="truncate">{search.label}</span>
|
||||
{search.shortcut && (
|
||||
<Kbd className="ml-auto border-0 bg-white/10 text-sidebar-foreground">{search.shortcut}</Kbd>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</SidebarTooltip>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ScrollArea className="min-h-0 flex-1 [&_[data-slot=scroll-area-thumb]]:bg-white/15 [&_[data-slot=scroll-area-thumb]]:group-hover/bar:bg-white/30">
|
||||
<nav className={cn("px-3 py-2", collapsed ? "space-y-1.5" : "space-y-4")}>
|
||||
{groups.map((group) => (
|
||||
<div key={group.label} className="group/nav">
|
||||
{collapsed ? (
|
||||
<div className="mx-auto mb-1.5 h-px w-6 bg-sidebar-border group-first/nav:hidden" />
|
||||
) : (
|
||||
<div className="mb-1 px-3 text-[10px] font-semibold tracking-[0.14em] text-sidebar-muted uppercase">
|
||||
{group.label}
|
||||
</div>
|
||||
)}
|
||||
<ul className="space-y-0.5">
|
||||
{group.items.map((item) => (
|
||||
<li key={item.to}>
|
||||
<SidebarLink item={item} collapsed={collapsed} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
</ScrollArea>
|
||||
|
||||
<div className="shrink-0 border-t border-sidebar-border p-3">
|
||||
<div className={cn("flex items-center gap-1", collapsed && "flex-col")}>
|
||||
{user ? <UserMenu user={user} collapsed={collapsed} menu={userMenu} /> : <div className="flex-1" />}
|
||||
<SidebarIconButton label={collapsed ? "Развернуть меню" : "Свернуть меню"} onClick={onToggle}>
|
||||
{collapsed ? <PanelLeftOpenIcon /> : <PanelLeftCloseIcon />}
|
||||
</SidebarIconButton>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarTooltip({ label, enabled, children }: { label: string; enabled: boolean; children: React.ReactElement }) {
|
||||
if (!enabled) return children
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{children}</TooltipTrigger>
|
||||
<TooltipContent side="right">{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
const isUnder = (pathname: string, base: string) => pathname === base || pathname.startsWith(`${base}/`)
|
||||
|
||||
function SidebarLink({ item, collapsed }: { item: SidebarNavItem; collapsed: boolean }) {
|
||||
const Icon = item.icon
|
||||
const { pathname, navigate } = useShell()
|
||||
const closeTab = useCloseSectionTab()
|
||||
const active = item.match ? item.match(pathname) : isUnder(pathname, item.to)
|
||||
const count = item.badge ?? 0
|
||||
const openTabs = useStoredSectionTabs(item.tabsSection ?? "")
|
||||
const tabs = item.tabsSection ? openTabs : []
|
||||
const isHere = (tab: SectionTab) => isUnder(pathname, tab.base)
|
||||
// Тот же лимит, что у вкладок в шапке раздела; открытая сейчас карточка всегда видна.
|
||||
// Строка «ещё 1» занимает столько же места, сколько сама карточка, — поэтому одну лишнюю просто показываем.
|
||||
const limit = tabs.length <= MAX_VISIBLE_TABS + 1 ? tabs.length : MAX_VISIBLE_TABS
|
||||
const { visible, hidden } = splitTabs(tabs, tabs.find(isHere)?.id, limit)
|
||||
const label = count > 0 ? `${item.label}: ${count}` : item.label
|
||||
|
||||
const base = cn(
|
||||
"relative flex h-9 items-center rounded-lg text-sm font-medium transition-colors",
|
||||
collapsed ? "justify-center" : "gap-3 px-3",
|
||||
)
|
||||
|
||||
if (item.disabled) {
|
||||
return (
|
||||
<SidebarTooltip label={`${item.label} · скоро`} enabled={collapsed}>
|
||||
<span className={cn(base, "cursor-not-allowed opacity-40")}>
|
||||
<Icon className="size-[18px] shrink-0" />
|
||||
{!collapsed && item.label}
|
||||
</span>
|
||||
</SidebarTooltip>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SidebarTooltip label={label} enabled={collapsed}>
|
||||
<ShellLink
|
||||
href={item.to}
|
||||
aria-label={collapsed ? label : undefined}
|
||||
aria-current={active ? "page" : undefined}
|
||||
className={cn(
|
||||
base,
|
||||
active ? "bg-sidebar-accent text-white" : "text-sidebar-foreground/85 hover:bg-white/[0.04] hover:text-white",
|
||||
)}
|
||||
>
|
||||
{active && <span className="absolute top-2 bottom-2 left-0 w-[3px] rounded-r-full bg-sidebar-primary" />}
|
||||
<Icon className={cn("size-[18px] shrink-0", active && "text-sidebar-primary")} />
|
||||
{!collapsed && <span className="truncate">{item.label}</span>}
|
||||
{count > 0 ? (
|
||||
<span
|
||||
className={cn(
|
||||
"grid place-items-center rounded-full font-semibold tabular-nums",
|
||||
item.badgeTone === "warning" ? "bg-warning text-sidebar" : "bg-coral text-white",
|
||||
collapsed
|
||||
? "absolute top-0.5 right-1 min-w-4 px-1 text-[10px] leading-4 ring-2 ring-sidebar"
|
||||
: "ml-auto min-w-5 px-1.5 text-[11px] leading-5",
|
||||
)}
|
||||
>
|
||||
{count > 999 ? "999+" : count}
|
||||
</span>
|
||||
) : tabs.length > 0 ? (
|
||||
collapsed ? (
|
||||
<span className="absolute top-1 right-1.5 size-2 rounded-full bg-sidebar-primary ring-2 ring-sidebar" />
|
||||
) : (
|
||||
<span className="ml-auto rounded-md bg-white/10 px-1.5 text-[11px] leading-5 font-semibold text-sidebar-foreground">
|
||||
{tabs.length}
|
||||
</span>
|
||||
)
|
||||
) : null}
|
||||
</ShellLink>
|
||||
</SidebarTooltip>
|
||||
|
||||
{/* Открытые карточки раздела — «зеркало» вкладок прямо в меню */}
|
||||
{!collapsed && tabs.length > 0 && (
|
||||
<ul className="mt-0.5 ml-[21px] space-y-px border-l border-sidebar-border py-1 pl-2">
|
||||
{visible.map((tab) => {
|
||||
const here = isHere(tab)
|
||||
return (
|
||||
<li
|
||||
key={tab.id}
|
||||
className={cn(
|
||||
"group/item flex h-7 items-center rounded-md text-[13px] transition-colors",
|
||||
here ? "bg-white/[0.06] text-white" : "text-sidebar-muted hover:bg-white/[0.03] hover:text-sidebar-foreground",
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate(tab.href)}
|
||||
title={tab.alert ? `${tab.label} · ${tab.alert}` : tab.label}
|
||||
className="flex h-full min-w-0 flex-1 items-center gap-2 pl-2 text-left"
|
||||
>
|
||||
<span className={cn("size-1.5 shrink-0 rounded-full", toneDot(tab.tone, "bg-sidebar-muted"))} />
|
||||
<span className="truncate">{tab.label}</span>
|
||||
</button>
|
||||
<span className="relative grid size-6 shrink-0 place-items-center">
|
||||
{tab.alert && (
|
||||
<span title={tab.alert} className="size-1.5 rounded-full bg-coral transition-opacity group-hover/item:opacity-0" />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Закрыть ${tab.label}`}
|
||||
onClick={() => closeTab(item.tabsSection!, tab.id)}
|
||||
className="absolute inset-0.5 grid place-items-center rounded text-sidebar-muted opacity-0 transition group-hover/item:opacity-100 hover:bg-white/10 hover:text-white focus-visible:opacity-100"
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</button>
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
{hidden.length > 0 && (
|
||||
<li>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="flex h-6 w-full items-center gap-1.5 rounded-md px-2 text-[11px] text-sidebar-muted transition hover:bg-white/[0.03] hover:text-sidebar-foreground data-[state=open]:text-sidebar-foreground"
|
||||
>
|
||||
ещё {hidden.length}
|
||||
{hidden.some((t) => t.alert) && <span className="size-1.5 rounded-full bg-coral" />}
|
||||
<ChevronRightIcon className="ml-auto size-3" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent side="right" align="start" className="w-60">
|
||||
<DropdownMenuLabel className="text-xs text-muted-foreground">Ещё открыто</DropdownMenuLabel>
|
||||
{hidden.map((tab) => (
|
||||
<DropdownMenuItem key={tab.id} onSelect={() => navigate(tab.href)} className="group/item gap-2 pr-1">
|
||||
<span className={cn("size-1.5 shrink-0 rounded-full", toneDot(tab.tone, "bg-muted-foreground"))} />
|
||||
<span className="min-w-0 flex-1 truncate">{tab.label}</span>
|
||||
{tab.alert && <span title={tab.alert} className="size-1.5 rounded-full bg-coral" />}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Закрыть ${tab.label}`}
|
||||
// Только click: pointerdown должен дойти до пункта меню, иначе Radix на pointerup
|
||||
// «докликивает» пункт сам и открывает карточку вместо закрытия.
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
closeTab(item.tabsSection!, tab.id)
|
||||
}}
|
||||
className="grid size-6 place-items-center rounded-md text-muted-foreground opacity-0 transition group-hover/item:opacity-100 group-data-[highlighted]/item:opacity-100 hover:bg-foreground/10 hover:text-foreground"
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</button>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function UserMenu({ user, collapsed, menu }: { user: SidebarUser; collapsed: boolean; menu?: React.ReactNode }) {
|
||||
const trigger = (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={collapsed ? user.name : undefined}
|
||||
className={cn(
|
||||
"flex min-w-0 items-center gap-2.5 rounded-lg p-1.5 text-left transition hover:bg-white/[0.05]",
|
||||
collapsed ? "justify-center" : "flex-1",
|
||||
)}
|
||||
>
|
||||
<Avatar className="size-8 rounded-lg">
|
||||
<AvatarFallback className="rounded-lg bg-sidebar-primary/20 text-xs font-semibold text-sidebar-primary">
|
||||
{user.initials}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
{!collapsed && (
|
||||
<div className="min-w-0 flex-1 leading-tight">
|
||||
<div className="truncate text-sm font-semibold text-white">{user.name}</div>
|
||||
{user.subtitle && <div className="truncate text-xs text-sidebar-muted">{user.subtitle}</div>}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
if (!menu) return trigger
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger>
|
||||
<DropdownMenuContent side="right" align="end" className="w-64">
|
||||
{menu}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function SidebarIconButton({ label, onClick, children }: { label: string; onClick: () => void; children: React.ReactNode }) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={label}
|
||||
onClick={onClick}
|
||||
className="grid size-8 shrink-0 place-items-center rounded-lg text-sidebar-muted transition hover:bg-white/[0.06] hover:text-white [&_svg]:size-4"
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right">{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { copyText } from "../lib/clipboard"
|
||||
import { cn } from "../lib/utils"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
||||
|
||||
/**
|
||||
* Значение, которое копируется по клику (ФИО, штрихкод, номер заявки). При наведении ничего не меняется,
|
||||
* после клика на полсекунды всплывает «Скопировано». Работает и с клавиатуры (Enter, пробел).
|
||||
*/
|
||||
export function CopyValue({ text, className, children }: { text: string; className?: string; children?: React.ReactNode }) {
|
||||
const [state, setState] = React.useState<"idle" | "copied" | "failed">("idle")
|
||||
|
||||
React.useEffect(() => {
|
||||
if (state === "idle") return
|
||||
const timer = setTimeout(() => setState("idle"), state === "failed" ? 1500 : 500)
|
||||
return () => clearTimeout(timer)
|
||||
}, [state])
|
||||
|
||||
const copy = () =>
|
||||
copyText(text).then(
|
||||
() => setState("copied"),
|
||||
() => setState("failed"),
|
||||
)
|
||||
|
||||
return (
|
||||
<Tooltip open={state !== "idle"}>
|
||||
<TooltipTrigger asChild>
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={`Скопировать ${text}`}
|
||||
onClick={(e) => {
|
||||
// в строке таблицы клик по значению не открывает строку
|
||||
e.stopPropagation()
|
||||
void copy()
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
void copy()
|
||||
}
|
||||
}}
|
||||
className={cn("cursor-copy rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/60", className)}
|
||||
>
|
||||
{children ?? text}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top">{state === "failed" ? "Не удалось скопировать" : "Скопировано"}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
|
@ -1,10 +1,13 @@
|
|||
// Составные компоненты Medkit. Витрина — /ui в medicine-ui (src/pages/ui/ui-page.tsx).
|
||||
export * from "./app-shell"
|
||||
export * from "./app-sidebar"
|
||||
export * from "./autocomplete"
|
||||
export * from "./chip"
|
||||
export * from "./code-block"
|
||||
export * from "./combobox"
|
||||
export * from "./confirm-dialog"
|
||||
export * from "./content-tabs"
|
||||
export * from "./copy-value"
|
||||
export * from "./data-table"
|
||||
export * from "./date-input"
|
||||
export * from "./date-leaf"
|
||||
|
|
@ -27,9 +30,13 @@ export * from "./patient-panel"
|
|||
export * from "./patient-picker"
|
||||
export * from "./person-chip"
|
||||
export * from "./save-bar"
|
||||
export * from "./search-field"
|
||||
export * from "./search-input"
|
||||
export * from "./section-frame"
|
||||
export * from "./section-tabs"
|
||||
export * from "./service-lines"
|
||||
export * from "./service-picker"
|
||||
export * from "./shell-provider"
|
||||
export * from "./snils-input"
|
||||
export * from "./stat-tile"
|
||||
export * from "./status-badge"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,62 @@
|
|||
import * as React from "react"
|
||||
|
||||
import { SearchInput } from "./search-input"
|
||||
|
||||
/**
|
||||
* Поиск, который применяется с задержкой (`delay` мс): фильтр не дёргается на каждую букву.
|
||||
* Enter применяет сразу — так работает сканер штрихкода; крестик и Esc очищают сразу.
|
||||
* `selectOnEnter` — после Enter текст выделен, и следующий скан заменяет его.
|
||||
* `value` — применённый текст (уже без пробелов по краям), `onChange` получает его же.
|
||||
*/
|
||||
export function SearchField({
|
||||
value,
|
||||
onChange,
|
||||
delay = 350,
|
||||
selectOnEnter = false,
|
||||
...props
|
||||
}: Omit<React.ComponentProps<typeof SearchInput>, "value" | "onValueChange" | "onChange"> & {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
delay?: number
|
||||
selectOnEnter?: boolean
|
||||
}) {
|
||||
const [input, setInput] = React.useState(value)
|
||||
const inputRef = React.useRef<HTMLInputElement>(null)
|
||||
|
||||
// значение сменили снаружи (сброс фильтров, переход по ссылке) — показываем его
|
||||
const [shown, setShown] = React.useState(value)
|
||||
if (shown !== value) {
|
||||
setShown(value)
|
||||
if (input.trim() !== value) setInput(value)
|
||||
}
|
||||
|
||||
const onChangeRef = React.useRef(onChange)
|
||||
React.useLayoutEffect(() => {
|
||||
onChangeRef.current = onChange
|
||||
})
|
||||
|
||||
React.useEffect(() => {
|
||||
const next = input.trim()
|
||||
if (next === value) return
|
||||
const timer = setTimeout(() => onChangeRef.current(next), delay)
|
||||
return () => clearTimeout(timer)
|
||||
}, [input, value, delay])
|
||||
|
||||
return (
|
||||
<SearchInput
|
||||
{...props}
|
||||
ref={inputRef}
|
||||
value={input}
|
||||
onValueChange={(next) => {
|
||||
setInput(next)
|
||||
if (!next && value) onChange("")
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
props.onKeyDown?.(e)
|
||||
if (e.key !== "Enter" || e.defaultPrevented) return
|
||||
onChange(input.trim())
|
||||
if (selectOnEnter) inputRef.current?.select()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -13,7 +13,7 @@ export const SearchInput = React.forwardRef<
|
|||
/** Что показать справа, пока поле пустое (подсказка клавиши). */
|
||||
trailing?: React.ReactNode
|
||||
}
|
||||
>(function SearchInput({ value, onValueChange, size = "md", trailing, className, ...props }, ref) {
|
||||
>(function SearchInput({ value, onValueChange, size = "md", trailing, className, onKeyDown, ...props }, ref) {
|
||||
const innerRef = React.useRef<HTMLInputElement>(null)
|
||||
React.useImperativeHandle(ref, () => innerRef.current!)
|
||||
|
||||
|
|
@ -35,7 +35,7 @@ export const SearchInput = React.forwardRef<
|
|||
e.stopPropagation()
|
||||
onValueChange("")
|
||||
}
|
||||
props.onKeyDown?.(e)
|
||||
onKeyDown?.(e)
|
||||
}}
|
||||
className={cn(
|
||||
"w-full rounded-lg border border-transparent bg-muted/70 transition outline-none placeholder:text-muted-foreground/80 [&::-webkit-search-cancel-button]:hidden",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,78 @@
|
|||
import * as React from "react"
|
||||
import { Maximize2Icon, Minimize2Icon } from "lucide-react"
|
||||
|
||||
import { createStore } from "../lib/store"
|
||||
import { cn } from "../lib/utils"
|
||||
import { Button } from "../ui/button"
|
||||
import { Kbd } from "../ui/kbd"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
|
||||
|
||||
// Развёрнутость общая для всех разделов: переход в другой раздел её не сбрасывает.
|
||||
const maximizedStore = createStore(false)
|
||||
const toggleMaximized = () => maximizedStore.set((v) => !v)
|
||||
|
||||
/**
|
||||
* Рамка раздела со вкладками: карточка, сверху полоса (`SectionTabsBar`), под ней контент.
|
||||
* Alt+F или кнопка в полосе — развернуть на весь экран поверх меню, Esc — свернуть.
|
||||
* Разделы без вкладок — `PageFrame`.
|
||||
*/
|
||||
export function SectionFrame({ bar, children }: { bar: React.ReactNode; children: React.ReactNode }) {
|
||||
const maximized = maximizedStore.use()
|
||||
|
||||
// Alt+F — развернуть/свернуть, Esc — свернуть (если не открыт диалог или меню).
|
||||
React.useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.altKey && !event.metaKey && !event.ctrlKey && event.code === "KeyF") {
|
||||
event.preventDefault()
|
||||
toggleMaximized()
|
||||
} else if (
|
||||
event.key === "Escape" &&
|
||||
maximizedStore.get() &&
|
||||
!event.defaultPrevented &&
|
||||
!document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')
|
||||
) {
|
||||
maximizedStore.set(false)
|
||||
}
|
||||
}
|
||||
window.addEventListener("keydown", onKey)
|
||||
return () => window.removeEventListener("keydown", onKey)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col",
|
||||
// Развёрнуто — поверх меню на тёмной подложке, как будто окно на весь экран.
|
||||
maximized ? "fixed inset-0 z-40 bg-sidebar p-2 duration-200 animate-in fade-in" : "p-2 lg:p-3",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border bg-card shadow-[0_1px_2px_rgba(15,40,60,0.04)]",
|
||||
maximized && "duration-200 animate-in zoom-in-[0.98]",
|
||||
)}
|
||||
>
|
||||
{bar}
|
||||
<div className="relative flex min-h-0 flex-1 flex-col">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Кнопка «Развернуть / Свернуть» для полосы вкладок раздела. */
|
||||
export function FrameMaximizeButton() {
|
||||
const maximized = maximizedStore.use()
|
||||
const label = maximized ? "Свернуть" : "Развернуть на весь экран"
|
||||
return (
|
||||
<Tooltip delayDuration={400}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="icon-sm" aria-label={label} aria-pressed={maximized} onClick={toggleMaximized}>
|
||||
{maximized ? <Minimize2Icon /> : <Maximize2Icon />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{label} <Kbd>Alt F</Kbd>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,350 @@
|
|||
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>
|
||||
</>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import * as React from "react"
|
||||
|
||||
/**
|
||||
* Крошечное хранилище в памяти: значение,
|
||||
* set по функции и React-хук с подпиской. Общее для всех страниц (моки, общие флаги окна).
|
||||
*/
|
||||
export function createStore<T>(initial: T) {
|
||||
let state = initial
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
const subscribe = (listener: () => void) => {
|
||||
listeners.add(listener)
|
||||
return () => {
|
||||
listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get: () => state,
|
||||
set(next: T | ((prev: T) => T)) {
|
||||
state = typeof next === "function" ? (next as (prev: T) => T)(state) : next
|
||||
for (const listener of listeners) listener()
|
||||
},
|
||||
/** Подписка на всё значение или его часть (селектор должен возвращать стабильные ссылки). */
|
||||
use<R = T>(selector?: (state: T) => R): R {
|
||||
return React.useSyncExternalStore(subscribe, () => (selector ? selector(state) : (state as unknown as R)))
|
||||
},
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue