Release 0.19.0: rotating sidebar cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ilya Mukhortov 2026-11-05 15:27:27 +10:00
parent 48ff0d03ed
commit 8556043947
6 changed files with 136 additions and 26 deletions

View File

@ -2,6 +2,11 @@
Установка версии: `npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^X.Y.Z"`. На 0.x `^0.7.0` не подхватывает 0.8.0 — минорную версию поднимаем в зависимости явно.
## [0.19.0] — 2026-11-05
### Новое
- `SidebarCards` и проп `cards` у `AppSidebar`: листающиеся карточки под меню, например непрочитанные уведомления. Пропы: `label`, `items` (`id`, `title`, `description`, `icon`, `to`, `onClick`), `interval` — смена карточки, по умолчанию 6 секунд. На наведении и фокусе с клавиатуры листание останавливается, при «уменьшить движение» в системе видна только первая карточка. Описание — в одну строку с многоточием, полный текст в подсказке. В свёрнутом меню и когда под меню не хватает места карточки не показываются, поэтому на низких окнах их может не быть. Без `cards` меню выглядит как раньше.
## [0.18.0] — 2026-11-05
### Новое

View File

@ -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.18.0"
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.19.0"
```
`package-lock.json` фиксирует коммит; обновиться до свежего тега — `npm update @medkit/ui`. В medicine-ui kit подключён git-submodule в `packages/medkit` (npm workspace) — правки видны сразу.

View File

@ -1,6 +1,6 @@
{
"name": "@medkit/ui",
"version": "0.18.0",
"version": "0.19.0",
"private": true,
"description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)",
"repository": {

View File

@ -16,6 +16,7 @@ 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"
import { SIDEBAR_CARDS_HEIGHT, SidebarCards, type SidebarCardsProps } from "./sidebar-cards"
export interface SidebarNavItem {
readonly to: string
@ -68,6 +69,8 @@ export interface AppSidebarProps {
/** Разделы-кнопки в ряду с логотипом, справа («Уведомления»); в свёрнутом меню — под логотипом, над поиском. */
actions?: readonly SidebarAction[]
groups: readonly SidebarNavGroup[]
/** Листающиеся карточки под меню; в свёрнутом меню и когда под меню нет места — не показываются. */
cards?: SidebarCardsProps
user?: SidebarUser
/** Пункты меню пользователя (DropdownMenuLabel, DropdownMenuItem…). */
userMenu?: React.ReactNode
@ -91,12 +94,30 @@ export function AppSidebar({
search,
actions,
groups,
cards,
user,
userMenu,
footerExtra,
className,
}: AppSidebarProps) {
const SearchItemIcon = search?.icon ?? SearchIcon
const hasCards = (cards?.items.length ?? 0) > 0
const bodyRef = React.useRef<HTMLDivElement>(null)
const navRef = React.useRef<HTMLElement>(null)
const [cardsFit, setCardsFit] = React.useState(false)
// Высота тела не зависит от карточек, поэтому показ карточек не меняет результат проверки.
React.useEffect(() => {
const body = bodyRef.current
const nav = navRef.current
if (!hasCards || !body || !nav) return
const check = () => setCardsFit(nav.offsetHeight + SIDEBAR_CARDS_HEIGHT <= body.clientHeight)
const observer = new ResizeObserver(check)
observer.observe(body)
observer.observe(nav)
return () => observer.disconnect()
}, [hasCards])
const actionLinks = actions?.map((action) => <SidebarActionLink key={action.to} action={action} collapsed={collapsed} />)
return (
@ -146,8 +167,9 @@ export function AppSidebar({
</div>
)}
<div ref={bodyRef} className="flex min-h-0 flex-1 flex-col">
<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-3", collapsed ? "space-y-2" : "space-y-3.5")}>
<nav ref={navRef} className={cn("px-3 py-3", collapsed ? "space-y-2" : "space-y-3.5")}>
{groups.map((group) => (
<div key={group.label} className="group/nav">
{collapsed ? (
@ -170,6 +192,8 @@ export function AppSidebar({
))}
</nav>
</ScrollArea>
{hasCards && cardsFit && !collapsed && <SidebarCards {...cards!} />}
</div>
<div className="shrink-0 border-t border-sidebar-border bg-black/[0.04] px-3 py-2.5 shadow-[0_-8px_20px_rgba(0,0,0,0.06)]">
{footerExtra && <div className="mb-2 border-b border-sidebar-border pb-2">{footerExtra(collapsed)}</div>}

View File

@ -1,6 +1,7 @@
// Составные компоненты Medkit. Витрина — /ui, /ui-form и /ui-table в medicine-ui.
export * from "./app-shell"
export * from "./app-sidebar"
export * from "./sidebar-cards"
export * from "./autocomplete"
export * from "./chip"
export * from "./code-block"

80
src/kit/sidebar-cards.tsx Normal file
View File

@ -0,0 +1,80 @@
import * as React from "react"
import { type LucideIcon } from "lucide-react"
import { useMediaQuery } from "../hooks/use-media-query"
import { ShellLink } from "./shell-provider"
export interface SidebarCard {
readonly id: string
readonly title: string
/** Одна строка, не поместится — многоточие. */
readonly description?: string
readonly icon?: LucideIcon
readonly to: string
/** Перед переходом (например, отметить прочитанным). */
readonly onClick?: () => void
}
export interface SidebarCardsProps {
/** Что за карточки: для скринридера. */
readonly label: string
readonly items: readonly SidebarCard[]
/** Смена карточки, мс. */
readonly interval?: number
}
/** Высота блока с отступом снизу: AppSidebar показывает его, только если под меню есть столько места. */
export const SIDEBAR_CARDS_HEIGHT = 68
/**
* Листающиеся карточки внизу бокового меню. Сами сменяются по `interval`, на наведении и фокусе
* с клавиатуры останавливаются; при «уменьшить движение» в системе видна только первая.
*/
export function SidebarCards({ label, items, interval = 6000 }: SidebarCardsProps) {
const [index, setIndex] = React.useState(0)
const [paused, setPaused] = React.useState(false)
const reducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)")
const count = items.length
React.useEffect(() => {
if (paused || reducedMotion || count < 2) return
const timer = window.setInterval(() => setIndex((i) => i + 1), interval)
return () => window.clearInterval(timer)
}, [paused, reducedMotion, count, interval])
if (count === 0) return null
// Список мог уменьшиться (карточку прочитали) — индекс остаётся в его пределах.
const active = index % count
const card = items[active]
const Icon = card.icon
return (
<div className="shrink-0 px-3 pb-2">
<section
aria-label={label}
onMouseEnter={() => setPaused(true)}
onMouseLeave={() => setPaused(false)}
// Только фокус с клавиатуры: после клика мышью ссылка остаётся в фокусе, и листание бы не возобновилось.
onFocus={(e) => e.target.matches(":focus-visible") && setPaused(true)}
onBlur={() => setPaused(false)}
className="rounded-lg border border-white/[0.08] bg-white/[0.04] p-2.5 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)] transition-colors hover:border-white/[0.12] hover:bg-white/[0.07]"
>
<ShellLink
href={card.to}
onClick={card.onClick}
className="block rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-primary/60"
>
<span key={card.id} className="block motion-safe:duration-300 motion-safe:animate-in motion-safe:fade-in">
<span className="flex h-5 items-center gap-1.5 text-xs font-medium text-white">
{Icon && <Icon className="size-3.5 shrink-0 text-sidebar-primary" />}
<span className="truncate">{card.title}</span>
</span>
<span title={card.description} className="mt-0.5 block h-4 truncate text-2xs leading-4 text-sidebar-muted">
{card.description}
</span>
</span>
</ShellLink>
</section>
</div>
)
}