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 f0468527cb
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 — минорную версию поднимаем в зависимости явно. Установка версии: `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 ## [0.18.0] — 2026-11-05
### Новое ### Новое

View File

@ -18,7 +18,7 @@ src/styles.css тема (токены, шрифты, тёмный режим)
Пакет ставится прямо из git, версии — теги `vX.Y.Z`: Пакет ставится прямо из git, версии — теги `vX.Y.Z`:
```bash ```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) — правки видны сразу. `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", "name": "@medkit/ui",
"version": "0.18.0", "version": "0.19.0",
"private": true, "private": true,
"description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)", "description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)",
"repository": { "repository": {

View File

@ -16,6 +16,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
import { MAX_VISIBLE_TABS, splitTabs } from "./page-tabs" import { MAX_VISIBLE_TABS, splitTabs } from "./page-tabs"
import { useCloseSectionTab, useStoredSectionTabs, type SectionTab } from "./section-tabs" import { useCloseSectionTab, useStoredSectionTabs, type SectionTab } from "./section-tabs"
import { ShellLink, useShell } from "./shell-provider" import { ShellLink, useShell } from "./shell-provider"
import { SIDEBAR_CARDS_HEIGHT, SidebarCards, type SidebarCardsProps } from "./sidebar-cards"
export interface SidebarNavItem { export interface SidebarNavItem {
readonly to: string readonly to: string
@ -68,6 +69,8 @@ export interface AppSidebarProps {
/** Разделы-кнопки в ряду с логотипом, справа («Уведомления»); в свёрнутом меню — под логотипом, над поиском. */ /** Разделы-кнопки в ряду с логотипом, справа («Уведомления»); в свёрнутом меню — под логотипом, над поиском. */
actions?: readonly SidebarAction[] actions?: readonly SidebarAction[]
groups: readonly SidebarNavGroup[] groups: readonly SidebarNavGroup[]
/** Листающиеся карточки под меню; в свёрнутом меню и когда под меню нет места — не показываются. */
cards?: SidebarCardsProps
user?: SidebarUser user?: SidebarUser
/** Пункты меню пользователя (DropdownMenuLabel, DropdownMenuItem…). */ /** Пункты меню пользователя (DropdownMenuLabel, DropdownMenuItem…). */
userMenu?: React.ReactNode userMenu?: React.ReactNode
@ -91,12 +94,30 @@ export function AppSidebar({
search, search,
actions, actions,
groups, groups,
cards,
user, user,
userMenu, userMenu,
footerExtra, footerExtra,
className, className,
}: AppSidebarProps) { }: AppSidebarProps) {
const SearchItemIcon = search?.icon ?? SearchIcon 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} />) const actionLinks = actions?.map((action) => <SidebarActionLink key={action.to} action={action} collapsed={collapsed} />)
return ( return (
@ -146,30 +167,33 @@ export function AppSidebar({
</div> </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"> <div ref={bodyRef} className="flex min-h-0 flex-1 flex-col">
<nav className={cn("px-3 py-3", collapsed ? "space-y-2" : "space-y-3.5")}> <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">
{groups.map((group) => ( <nav ref={navRef} className={cn("px-3 py-3", collapsed ? "space-y-2" : "space-y-3.5")}>
<div key={group.label} className="group/nav"> {groups.map((group) => (
{collapsed ? ( <div key={group.label} className="group/nav">
<div className="mx-auto mb-2 h-px w-7 bg-sidebar-border/90 group-first/nav:hidden" /> {collapsed ? (
) : ( <div className="mx-auto mb-2 h-px w-7 bg-sidebar-border/90 group-first/nav:hidden" />
<div className="mb-1.5 flex items-center gap-2 px-3"> ) : (
<span className="text-[10px] leading-4 font-semibold tracking-[0.11em] text-sidebar-muted uppercase"> <div className="mb-1.5 flex items-center gap-2 px-3">
{group.label} <span className="text-[10px] leading-4 font-semibold tracking-[0.11em] text-sidebar-muted uppercase">
</span> {group.label}
</div> </span>
)} </div>
<ul className="space-y-0.5"> )}
{group.items.map((item) => ( <ul className="space-y-0.5">
<li key={item.to}> {group.items.map((item) => (
<SidebarLink item={item} collapsed={collapsed} /> <li key={item.to}>
</li> <SidebarLink item={item} collapsed={collapsed} />
))} </li>
</ul> ))}
</div> </ul>
))} </div>
</nav> ))}
</ScrollArea> </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)]"> <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>} {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. // Составные компоненты Medkit. Витрина — /ui, /ui-form и /ui-table в medicine-ui.
export * from "./app-shell" export * from "./app-shell"
export * from "./app-sidebar" export * from "./app-sidebar"
export * from "./sidebar-cards"
export * from "./autocomplete" export * from "./autocomplete"
export * from "./chip" export * from "./chip"
export * from "./code-block" 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>
)
}