diff --git a/README.md b/README.md index 7316c4b..8c47125 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.3.0" +npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.4.0" ``` `package-lock.json` фиксирует коммит; обновиться до свежего тега — `npm update @medkit/ui`. В medicine-ui kit подключён git-submodule в `packages/medkit` (npm workspace) — правки видны сразу. diff --git a/package.json b/package.json index 3e0d60e..80b5bcd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@medkit/ui", - "version": "0.3.0", + "version": "0.4.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 25d189a..f67c19b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,7 @@ export * from "./ui/button" export * from "./ui/calendar" export * from "./ui/card" export * from "./ui/checkbox" +export * from "./ui/collapsible" export * from "./ui/command" export * from "./ui/context-menu" export * from "./ui/dialog" @@ -20,12 +21,14 @@ export * from "./ui/kbd" export * from "./ui/label" export * from "./ui/popover" export * from "./ui/progress" +export * from "./ui/radio-group" export * from "./ui/scroll-area" export * from "./ui/select" export * from "./ui/separator" export * from "./ui/sheet" export * from "./ui/skeleton" export * from "./ui/sonner" +export * from "./ui/spinner" export * from "./ui/switch" export * from "./ui/table" export * from "./ui/tabs" diff --git a/src/kit/autocomplete.tsx b/src/kit/autocomplete.tsx new file mode 100644 index 0000000..aeac43c --- /dev/null +++ b/src/kit/autocomplete.tsx @@ -0,0 +1,212 @@ +import * as React from "react" +import { Command as CommandPrimitive } from "cmdk" +import { CheckIcon, SearchIcon, XIcon } from "lucide-react" + +import { cn } from "../lib/utils" +import { CommandGroup, CommandItem, CommandList } from "../ui/command" +import { InputGroup, InputGroupAddon } from "../ui/input-group" +import { Popover, PopoverAnchor, PopoverContent } from "../ui/popover" +import { Spinner } from "../ui/spinner" + +const norm = (v: string) => v.toLowerCase().replace(/ё/g, "е") + +/** + * Поиск с подсказками: печатают прямо в поле, варианты — списком под ним (как MUI Autocomplete). + * Значение — сам объект. Без `onSearchChange` фильтрует `options` по `getLabel`; + * с ним — ищет сервер: текст уходит в `onSearchChange` через `searchDelay` мс, `options` и `loading` — от запроса. + */ +export function Autocomplete({ + options, + value, + onChange, + getKey, + getLabel, + renderOption, + onSearchChange, + searchDelay = 300, + minSearchLength = 0, + loading = false, + emptyText = "Ничего не найдено", + hint, + placeholder, + autoFocus, + disabled, + invalid, + id, + className, + "aria-label": ariaLabel, +}: { + options: readonly T[] + value: T | null + onChange: (value: T | null) => void + getKey: (option: T) => string | number + /** Текст в поле после выбора; по нему же фильтруются варианты без `onSearchChange`. */ + getLabel: (option: T) => string + /** Строка списка; по умолчанию — `getLabel`. */ + renderOption?: (option: T) => React.ReactNode + /** Задан — варианты ищет сервер, сами не фильтруем. */ + onSearchChange?: (search: string) => void + searchDelay?: number + /** Пока текст короче — список не ищется, показывается `hint` (только с `onSearchChange`). */ + minSearchLength?: number + loading?: boolean + emptyText?: React.ReactNode + hint?: React.ReactNode + placeholder?: string + autoFocus?: boolean + disabled?: boolean + invalid?: boolean + id?: string + className?: string + "aria-label"?: string +}) { + const anchorRef = React.useRef(null) + const inputRef = React.useRef(null) + const [open, setOpen] = React.useState(false) + const [text, setText] = React.useState(value ? getLabel(value) : "") + // null — пользователь не печатает (после выбора или ухода из поля): показываем все варианты + const [query, setQuery] = React.useState(null) + const [active, setActive] = React.useState("") + + // значение сменили снаружи (сброс формы) — показываем его подпись + const valueKey = value == null ? null : getKey(value) + const [shownKey, setShownKey] = React.useState(valueKey) + if (shownKey !== valueKey) { + setShownKey(valueKey) + setText(value ? getLabel(value) : "") + setQuery(null) + } + + const onSearchRef = React.useRef(onSearchChange) + React.useLayoutEffect(() => { + onSearchRef.current = onSearchChange + }) + const server = !!onSearchChange + React.useEffect(() => { + if (query === null || !onSearchRef.current) return + const timer = setTimeout(() => onSearchRef.current?.(query.trim()), searchDelay) + return () => clearTimeout(timer) + }, [query, searchDelay]) + + const search = (query ?? "").trim() + const items = server || !search ? options : options.filter((o) => norm(getLabel(o)).includes(norm(search))) + const tooShort = server && search.length < minSearchLength + const keys = items.map((o) => String(getKey(o))) + // подсвеченный вариант — всегда из текущего списка: Enter берёт первый + const activeKey = keys.includes(active) ? active : (keys[0] ?? "") + // вариант выбран и пользователь ещё не печатает — подсказка «от N символов» не нужна + const hasContent = tooShort ? !!hint && !(query === null && value) : true + + const pick = (option: T) => { + onChange(option) + setText(getLabel(option)) + setQuery(null) + setOpen(false) + } + + const restore = () => { + setOpen(false) + setQuery(null) + setText(value ? getLabel(value) : "") + } + + const isInside = (target: EventTarget | null) => !!target && !!anchorRef.current?.contains(target as Node) + + return ( + + !next && setOpen(false)}> + + + + + + { + setText(next) + setQuery(next) + setOpen(true) + if (!next && value) onChange(null) + }} + onFocus={() => setOpen(true)} + onClick={() => setOpen(true)} + onBlur={restore} + onKeyDown={(e) => { + if (!open && (e.key === "ArrowDown" || e.key === "ArrowUp")) setOpen(true) + }} + autoFocus={autoFocus} + disabled={disabled} + placeholder={placeholder} + aria-label={ariaLabel ?? placeholder} + aria-invalid={invalid} + autoComplete="off" + className="h-full min-w-0 flex-1 bg-transparent pr-2 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50" + /> + {(loading || (text && !disabled)) && ( + + {loading && } + {text && !disabled && ( + + )} + + )} + + + e.preventDefault()} + onCloseAutoFocus={(e) => e.preventDefault()} + onInteractOutside={(e) => isInside(e.target) && e.preventDefault()} + onFocusOutside={(e) => isInside(e.target) && e.preventDefault()} + // клик по варианту не должен уводить фокус из поля (иначе blur закроет список до выбора) + onMouseDown={(e) => e.preventDefault()} + > + + {tooShort ? ( +
{hint}
+ ) : !items.length ? ( +
{loading ? "Поиск…" : emptyText}
+ ) : ( + + {items.map((o, i) => { + const selected = valueKey !== null && getKey(o) === valueKey + return ( + pick(o)}> + +
{renderOption ? renderOption(o) : getLabel(o)}
+
+ ) + })} +
+ )} +
+
+
+
+ ) +} diff --git a/src/kit/chip.tsx b/src/kit/chip.tsx new file mode 100644 index 0000000..40100eb --- /dev/null +++ b/src/kit/chip.tsx @@ -0,0 +1,148 @@ +import * as React from "react" +import { XIcon } from "lucide-react" + +import { cn } from "../lib/utils" +import type { StatusTone } from "./status-badge" + +export type ChipTone = StatusTone | "primary" +export type ChipVariant = "soft" | "outline" | "solid" + +const toneClass: Record> = { + primary: { + soft: "border-transparent bg-primary/10 text-primary", + outline: "border-primary/30 text-primary", + solid: "border-primary bg-primary text-primary-foreground", + hover: "hover:border-primary/40 hover:bg-primary/5 hover:text-foreground", + }, + positive: { + soft: "border-transparent bg-success-soft text-success", + outline: "border-success/30 text-success", + solid: "border-success bg-success text-white", + hover: "hover:border-success/40 hover:bg-success-soft", + }, + info: { + soft: "border-transparent bg-info-soft text-info", + outline: "border-info/30 text-info", + solid: "border-info bg-info text-white", + hover: "hover:border-info/40 hover:bg-info-soft", + }, + warning: { + soft: "border-transparent bg-warning-soft text-warning", + outline: "border-warning/40 text-warning", + solid: "border-warning bg-warning text-black/85", + hover: "hover:border-warning/50 hover:bg-warning-soft", + }, + negative: { + soft: "border-transparent bg-coral-soft text-coral", + outline: "border-coral/30 text-coral", + solid: "border-coral bg-coral text-white", + hover: "hover:border-coral/40 hover:bg-coral-soft", + }, + neutral: { + soft: "border-transparent bg-muted text-muted-foreground", + outline: "border-border text-muted-foreground", + solid: "border-foreground bg-foreground text-background", + hover: "hover:border-primary/40 hover:bg-primary/5 hover:text-foreground", + }, +} + +const sizeClass = { + sm: { root: "h-5 gap-1 px-1.5 text-[11px]", remove: "pr-0.5", x: "size-4" }, + md: { root: "h-6 gap-1.5 px-2.5 text-xs", remove: "pr-1", x: "size-4.5" }, +} + +/** + * Метка-тег: статичная («cito», «повтор»), выбираемая (фильтр, причина — `onClick` + `selected`), + * со счётчиком (`count`) и с крестиком (`onRemove`). Кликабельная по умолчанию — `outline`, + * выбранная — сплошная в цвет тона (нейтральная — в основной цвет). + */ +export function Chip({ + tone = "neutral", + variant, + size = "md", + selected, + onClick, + count, + onRemove, + icon, + title, + disabled, + className, + children, +}: { + tone?: ChipTone + variant?: ChipVariant + size?: "sm" | "md" + selected?: boolean + onClick?: () => void + count?: number + onRemove?: () => void + icon?: React.ReactNode + title?: string + disabled?: boolean + className?: string + children: React.ReactNode +}) { + const sizes = sizeClass[size] + const colors = selected + ? toneClass[tone === "neutral" ? "primary" : tone].solid + : cn(toneClass[tone][variant ?? (onClick ? "outline" : "soft")], onClick && !disabled && toneClass[tone].hover) + const root = cn( + "inline-flex w-fit shrink-0 items-center rounded-full border font-medium whitespace-nowrap transition outline-none [&_svg]:size-3 [&_svg]:shrink-0", + "focus-visible:ring-[3px] focus-visible:ring-ring/50 has-[button:focus-visible]:ring-[3px] has-[button:focus-visible]:ring-ring/50", + sizes.root, + onRemove && sizes.remove, + colors, + disabled && "opacity-50", + className, + ) + const body = ( + <> + {icon} + {children} + {count != null && {count}} + + ) + + if (onClick && !onRemove) + return ( + + ) + + return ( + + {onClick ? ( + + ) : ( + body + )} + {onRemove && ( + + )} + + ) +} diff --git a/src/kit/index.ts b/src/kit/index.ts index f1eafc1..c33f56f 100644 --- a/src/kit/index.ts +++ b/src/kit/index.ts @@ -1,4 +1,6 @@ // Составные компоненты Medkit. Витрина — /ui в medicine-ui (src/pages/ui/ui-page.tsx). +export * from "./autocomplete" +export * from "./chip" export * from "./code-block" export * from "./combobox" export * from "./confirm-dialog" @@ -12,8 +14,10 @@ export * from "./file-drop" export * from "./file-gallery" export * from "./form-field" export * from "./info-section" +export * from "./loading-bar" export * from "./login-form" export * from "./multi-select" +export * from "./notice" export * from "./notify" export * from "./page-frame" export * from "./page-tabs" diff --git a/src/kit/loading-bar.tsx b/src/kit/loading-bar.tsx new file mode 100644 index 0000000..1f7bc5f --- /dev/null +++ b/src/kit/loading-bar.tsx @@ -0,0 +1,29 @@ +import * as React from "react" + +import { cn } from "../lib/utils" +import { Progress } from "../ui/progress" + +/** + * Бегущая полоса по верхнему краю блока — фоновое обновление списка (у родителя `relative`). + * Появляется через `delay` мс, чтобы не мигать на быстрых запросах. + */ +export function LoadingBar({ active, delay = 150, className }: { active: boolean; delay?: number; className?: string }) { + const [shown, setShown] = React.useState(false) + + React.useEffect(() => { + if (!active) return + const timer = setTimeout(() => setShown(true), delay) + return () => { + clearTimeout(timer) + setShown(false) + } + }, [active, delay]) + + if (!active || !shown) return null + return ( + + ) +} diff --git a/src/kit/multi-select.tsx b/src/kit/multi-select.tsx index 2e8aedb..c8c9e3b 100644 --- a/src/kit/multi-select.tsx +++ b/src/kit/multi-select.tsx @@ -4,6 +4,7 @@ import { CheckIcon, ChevronDownIcon, XIcon } from "lucide-react" import { cn } from "../lib/utils" import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "../ui/command" import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover" +import { Chip } from "./chip" export interface MultiSelectOption { readonly value: T @@ -78,23 +79,13 @@ export function MultiSelect({ ) : ( value.map((v) => ( - toggle(v)} + className="gap-1 rounded-md border-transparent bg-secondary pl-2 text-secondary-foreground" > {labelOf(v)} - - + )) )} diff --git a/src/kit/notice.tsx b/src/kit/notice.tsx new file mode 100644 index 0000000..e5ae24e --- /dev/null +++ b/src/kit/notice.tsx @@ -0,0 +1,60 @@ +import * as React from "react" +import { XIcon } from "lucide-react" + +import { cn } from "../lib/utils" +import { NOTIFY_ICON, type NotifyType } from "./notify" + +const toneClass: Record = { + error: "border-coral/25 bg-coral-soft text-coral", + warning: "border-warning/30 bg-warning-soft text-warning", + info: "border-info/20 bg-info-soft text-info", + success: "border-success/20 bg-success-soft text-success", +} + +/** + * Плашка-сообщение на месте содержимого: ошибка запроса, предупреждение, подсказка. + * `action` — кнопка справа, `onClose` — крестик; `icon={false}` убирает иконку. + */ +export function Notice({ + tone = "error", + title, + icon = true, + action, + onClose, + className, + children, +}: { + tone?: NotifyType + title?: React.ReactNode + icon?: boolean + action?: React.ReactNode + onClose?: () => void + className?: string + children?: React.ReactNode +}) { + const Icon = NOTIFY_ICON[tone] + + return ( +
+ {icon && } +
+ {title &&
{title}
} + {children &&
{children}
} +
+ {action &&
{action}
} + {onClose && ( + + )} +
+ ) +} diff --git a/src/kit/notify.tsx b/src/kit/notify.tsx index 4374f70..9fee0a1 100644 --- a/src/kit/notify.tsx +++ b/src/kit/notify.tsx @@ -19,11 +19,19 @@ const TOASTER_ID = "notify" /** Переход по href из карточки; без роутера — обычная навигация браузера. */ const NavigateContext = React.createContext<(href: string) => void>((href) => window.location.assign(href)) -const typeMeta: Record = { - success: { icon: CircleCheckIcon, tile: "bg-success-soft text-success", bar: "bg-success", duration: 5000 }, - info: { icon: InfoIcon, tile: "bg-info-soft text-info", bar: "bg-info", duration: 6000 }, - warning: { icon: TriangleAlertIcon, tile: "bg-warning-soft text-warning", bar: "bg-warning", duration: 8000 }, - error: { icon: OctagonXIcon, tile: "bg-coral-soft text-coral", bar: "bg-coral", duration: 10000 }, +/** Иконка по типу сообщения — общая для тостов и Notice. */ +export const NOTIFY_ICON: Record = { + success: CircleCheckIcon, + info: InfoIcon, + warning: TriangleAlertIcon, + error: OctagonXIcon, +} + +const typeMeta: Record = { + success: { tile: "bg-success-soft text-success", bar: "bg-success", duration: 5000 }, + info: { tile: "bg-info-soft text-info", bar: "bg-info", duration: 6000 }, + warning: { tile: "bg-warning-soft text-warning", bar: "bg-warning", duration: 8000 }, + error: { tile: "bg-coral-soft text-coral", bar: "bg-coral", duration: 10000 }, } export interface NotifyOptions { @@ -79,7 +87,8 @@ function NotifyCard({ actionLabel = "Перейти", }: Omit & { id: string | number; type: NotifyType }) { const navigate = React.useContext(NavigateContext) - const { icon: Icon, tile, bar } = typeMeta[type] + const { tile, bar } = typeMeta[type] + const Icon = NOTIFY_ICON[type] return (
) { + return +} + +function CollapsibleTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +// Открытие и закрытие анимируются по высоте (tw-animate-css). Блок без Trigger — +// прямо в ячейке второй строки таблицы. +function CollapsibleContent({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { Collapsible, CollapsibleTrigger, CollapsibleContent } diff --git a/src/ui/progress.tsx b/src/ui/progress.tsx index d874392..360e9b6 100644 --- a/src/ui/progress.tsx +++ b/src/ui/progress.tsx @@ -15,13 +15,22 @@ function Progress({ "relative h-2 w-full overflow-hidden rounded-full bg-primary/20", className )} + value={value} {...props} > - + {/* Без value — неизвестно, сколько осталось: бегущий отрезок */} + {value == null ? ( + + ) : ( + + )} ) } diff --git a/src/ui/radio-group.tsx b/src/ui/radio-group.tsx new file mode 100644 index 0000000..72333c7 --- /dev/null +++ b/src/ui/radio-group.tsx @@ -0,0 +1,42 @@ +import * as React from "react" +import { cn } from "../lib/utils" +import { CircleIcon } from "lucide-react" +import { RadioGroup as RadioGroupPrimitive } from "radix-ui" + +function RadioGroup({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function RadioGroupItem({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + + + ) +} + +export { RadioGroup, RadioGroupItem } diff --git a/src/ui/spinner.tsx b/src/ui/spinner.tsx new file mode 100644 index 0000000..28da079 --- /dev/null +++ b/src/ui/spinner.tsx @@ -0,0 +1,16 @@ +import * as React from "react" +import { cn } from "../lib/utils" +import { Loader2Icon } from "lucide-react" + +function Spinner({ className, ...props }: React.ComponentProps<"svg">) { + return ( + + ) +} + +export { Spinner }