From 96239dd064a4d64366999b5b99ca33eaea1c21cd Mon Sep 17 00:00:00 2001 From: Ilya Mukhortov Date: Sun, 25 Oct 2026 12:07:20 +1000 Subject: [PATCH] Window shell, section tabs, CopyValue, SearchField, release 0.5.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- README.md | 20 +- package.json | 2 +- src/index.ts | 1 + src/kit/app-shell.tsx | 58 ++++++ src/kit/app-sidebar.tsx | 383 +++++++++++++++++++++++++++++++++++++ src/kit/copy-value.tsx | 53 +++++ src/kit/index.ts | 7 + src/kit/search-field.tsx | 62 ++++++ src/kit/search-input.tsx | 4 +- src/kit/section-frame.tsx | 78 ++++++++ src/kit/section-tabs.tsx | 350 +++++++++++++++++++++++++++++++++ src/kit/shell-provider.tsx | 76 ++++++++ src/lib/store.ts | 29 +++ 13 files changed, 1119 insertions(+), 4 deletions(-) create mode 100644 src/kit/app-shell.tsx create mode 100644 src/kit/app-sidebar.tsx create mode 100644 src/kit/copy-value.tsx create mode 100644 src/kit/search-field.tsx create mode 100644 src/kit/section-frame.tsx create mode 100644 src/kit/section-tabs.tsx create mode 100644 src/kit/shell-provider.tsx create mode 100644 src/lib/store.ts diff --git a/README.md b/README.md index 8c47125..9885cef 100644 --- a/README.md +++ b/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 ( + + + }>… + + + ) +} +``` + +`storageKey` — префикс ключей localStorage (вкладки, свёрнутое меню): у приложений на одном домене память не смешивается. + Peer-зависимости: `react`, `react-dom` 19, `tailwindcss` 4. В Vite-проекте ничего настраивать не нужно. ## Правила для кода пакета diff --git a/package.json b/package.json index 80b5bcd..16a7fea 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/src/index.ts b/src/index.ts index f67c19b..f4bdbe0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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" diff --git a/src/kit/app-shell.tsx b/src/kit/app-shell.tsx new file mode 100644 index 0000000..962c464 --- /dev/null +++ b/src/kit/app-shell.tsx @@ -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`, обычно ``). + * Окно целиком не прокручивается — только тело раздела. Свёрнутость меню помнится + * (`.sidebar-collapsed`), на узком экране меню всегда свёрнуто. При печати меню скрыто. + * Нужен ShellProvider выше. + */ +export function AppShell({ + sidebar, + className, + children, +}: { + sidebar: Omit + 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 ( +
+ +
+ {children} +
+
+ ) +} diff --git a/src/kit/app-sidebar.tsx b/src/kit/app-sidebar.tsx new file mode 100644 index 0000000..b93c022 --- /dev/null +++ b/src/kit/app-sidebar.tsx @@ -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 ( + + ) +} + +function SidebarTooltip({ label, enabled, children }: { label: string; enabled: boolean; children: React.ReactElement }) { + if (!enabled) return children + return ( + + {children} + {label} + + ) +} + +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 ( + + + + {!collapsed && item.label} + + + ) + } + + return ( + <> + + + {active && } + + {!collapsed && {item.label}} + {count > 0 ? ( + + {count > 999 ? "999+" : count} + + ) : tabs.length > 0 ? ( + collapsed ? ( + + ) : ( + + {tabs.length} + + ) + ) : null} + + + + {/* Открытые карточки раздела — «зеркало» вкладок прямо в меню */} + {!collapsed && tabs.length > 0 && ( +
    + {visible.map((tab) => { + const here = isHere(tab) + return ( +
  • + + + {tab.alert && ( + + )} + + +
  • + ) + })} + {hidden.length > 0 && ( +
  • + + + + + + Ещё открыто + {hidden.map((tab) => ( + navigate(tab.href)} className="group/item gap-2 pr-1"> + + {tab.label} + {tab.alert && } + + + ))} + + +
  • + )} +
+ )} + + ) +} + +function UserMenu({ user, collapsed, menu }: { user: SidebarUser; collapsed: boolean; menu?: React.ReactNode }) { + const trigger = ( + + ) + if (!menu) return trigger + + return ( + + {trigger} + + {menu} + + + ) +} + +function SidebarIconButton({ label, onClick, children }: { label: string; onClick: () => void; children: React.ReactNode }) { + return ( + + + + + {label} + + ) +} diff --git a/src/kit/copy-value.tsx b/src/kit/copy-value.tsx new file mode 100644 index 0000000..6c79d04 --- /dev/null +++ b/src/kit/copy-value.tsx @@ -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 ( + + + { + // в строке таблицы клик по значению не открывает строку + 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} + + + {state === "failed" ? "Не удалось скопировать" : "Скопировано"} + + ) +} diff --git a/src/kit/index.ts b/src/kit/index.ts index c33f56f..e92afb4 100644 --- a/src/kit/index.ts +++ b/src/kit/index.ts @@ -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" diff --git a/src/kit/search-field.tsx b/src/kit/search-field.tsx new file mode 100644 index 0000000..b30e2a8 --- /dev/null +++ b/src/kit/search-field.tsx @@ -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, "value" | "onValueChange" | "onChange"> & { + value: string + onChange: (value: string) => void + delay?: number + selectOnEnter?: boolean +}) { + const [input, setInput] = React.useState(value) + const inputRef = React.useRef(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 ( + { + 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() + }} + /> + ) +} diff --git a/src/kit/search-input.tsx b/src/kit/search-input.tsx index a9cd876..02dd9de 100644 --- a/src/kit/search-input.tsx +++ b/src/kit/search-input.tsx @@ -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(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", diff --git a/src/kit/section-frame.tsx b/src/kit/section-frame.tsx new file mode 100644 index 0000000..0553d83 --- /dev/null +++ b/src/kit/section-frame.tsx @@ -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 ( +
+
+ {bar} +
{children}
+
+
+ ) +} + +/** Кнопка «Развернуть / Свернуть» для полосы вкладок раздела. */ +export function FrameMaximizeButton() { + const maximized = maximizedStore.use() + const label = maximized ? "Свернуть" : "Развернуть на весь экран" + return ( + + + + + + {label} Alt F + + + ) +} diff --git a/src/kit/section-tabs.tsx b/src/kit/section-tabs.tsx new file mode 100644 index 0000000..6d6bbf8 --- /dev/null +++ b/src/kit/section-tabs.tsx @@ -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, ключ `.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 & { 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(null) + +const storageName = (storageKey: string, section: string) => `${storageKey}.section-tabs.${section}` +const changeEvent = (storageKey: string) => `${storageKey}:section-tabs` + +/** Разделы, чей провайдер сейчас смонтирован, — им закрытие передаётся напрямую. Ключ — storageName. */ +const mountedClosers = new Map 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 + children: React.ReactNode +}) { + const { pathname, search, navigate, storageKey } = useShell() + + const [tabs, setTabs] = React.useState(() => { + 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( + (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( + () => ({ + 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 {children} +} + +export function useSectionTabs() { + const ctx = React.useContext(SectionTabsContext) + if (!ctx) throw new Error("useSectionTabs — только внутри ") + return ctx +} + +/** Страница-карточка регистрирует свою вкладку, если её ещё нет (прямой заход по ссылке). */ +export function useRegisterSectionTab(tab: (Omit & { 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).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 ( + + {actions} + + + } + renderMenu={(item) => { + const tab = tabs.find((t) => t.id === item.id)! + return ( + <> + activate(tab.id)}>Открыть + { + copyText(window.location.origin + toHref(tab.href)).then( + () => toast.success("Ссылка скопирована", { description: tab.label }), + () => toast.error("Не удалось скопировать ссылку"), + ) + }} + > + Скопировать ссылку + + + close(tab.id)}> + Закрыть + Alt W + + closeOthers(tab.id)}>Закрыть остальные + closeToRight(tab.id)}>Закрыть справа + + Закрыть все карточки + + + ) + }} + /> + ) +} diff --git a/src/kit/shell-provider.tsx b/src/kit/shell-provider.tsx new file mode 100644 index 0000000..3708fea --- /dev/null +++ b/src/kit/shell-provider.tsx @@ -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() + * + * ``` + */ +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(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(() => { + const base = basename.replace(/\/+$/, "") + return { pathname, search, navigate: stableNavigate, storageKey, toHref: (path) => base + path } + }, [pathname, search, stableNavigate, storageKey, basename]) + return {children} +} + +export function useShell(): ShellValue { + const ctx = React.useContext(ShellContext) + if (!ctx) throw new Error("Каркас окна (AppShell, вкладки разделов) должен быть внутри ") + return ctx +} + +/** Ссылка для каркаса: обычный клик — переход роутером, Ctrl/⌘/средняя кнопка — новая вкладка браузера. */ +export function ShellLink({ href, onClick, ...props }: React.ComponentProps<"a"> & { href: string }) { + const { navigate, toHref } = useShell() + return ( + { + onClick?.(e) + if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return + e.preventDefault() + navigate(href) + }} + {...props} + /> + ) +} diff --git a/src/lib/store.ts b/src/lib/store.ts new file mode 100644 index 0000000..258ba21 --- /dev/null +++ b/src/lib/store.ts @@ -0,0 +1,29 @@ +import * as React from "react" + +/** + * Крошечное хранилище в памяти: значение, + * set по функции и React-хук с подпиской. Общее для всех страниц (моки, общие флаги окна). + */ +export function createStore(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(selector?: (state: T) => R): R { + return React.useSyncExternalStore(subscribe, () => (selector ? selector(state) : (state as unknown as R))) + }, + } +}