diff --git a/src/kit/code-block.tsx b/src/kit/code-block.tsx new file mode 100644 index 0000000..a1f2e2e --- /dev/null +++ b/src/kit/code-block.tsx @@ -0,0 +1,23 @@ +import { CopyIcon } from "lucide-react" + +import { cn } from "@/lib/utils" +import { copyToClipboard } from "@/lib/clipboard" + +/** Фрагмент кода с кнопкой копирования. */ +export function CodeBlock({ code, className }: { code: string; className?: string }) { + return ( +
+
+        {code}
+      
+ +
+ ) +} diff --git a/src/kit/content-tabs.tsx b/src/kit/content-tabs.tsx new file mode 100644 index 0000000..fc40189 --- /dev/null +++ b/src/kit/content-tabs.tsx @@ -0,0 +1,80 @@ +import { type LucideIcon } from "lucide-react" + +import { cn } from "@/lib/utils" + +export interface ContentTabItem { + readonly id: T + readonly label: string + readonly icon?: LucideIcon + /** Счётчик справа от подписи. */ + readonly count?: number + readonly disabled?: boolean +} + +/** + * Контентные вкладки внутри страницы/карточки. + * `line` — подчёркивание (разделы карточки), `pill` — заливка (переключатели в блоках). + */ +export function ContentTabs({ + tabs, + value, + onValueChange, + variant = "line", + className, +}: { + tabs: readonly ContentTabItem[] + value: T + onValueChange: (value: T) => void + variant?: "line" | "pill" + className?: string +}) { + return ( +
+ {tabs.map((tab) => { + const active = tab.id === value + return ( + + ) + })} +
+ ) +} diff --git a/src/kit/data-table.tsx b/src/kit/data-table.tsx new file mode 100644 index 0000000..3eb5b8b --- /dev/null +++ b/src/kit/data-table.tsx @@ -0,0 +1,141 @@ +import * as React from "react" +import { ArrowDownIcon, ArrowUpIcon, ChevronsUpDownIcon } from "lucide-react" + +import { cn } from "@/lib/utils" + +export type SortDirection = "asc" | "desc" + +export interface SortState { + readonly id: string + readonly direction: SortDirection +} + +export interface DataColumn { + readonly id: string + readonly header: React.ReactNode + readonly cell: (row: T, index: number) => React.ReactNode + /** Компаратор — колонка становится сортируемой. */ + readonly sort?: (a: T, b: T) => number + readonly className?: string + readonly headerClassName?: string +} + +/** Отсортировать строки по словарю компараторов {columnId: compare}. */ +export function sortBy( + rows: readonly T[], + comparators: Readonly number) | undefined>>, + sort: SortState | null, +) { + const compare = sort && comparators[sort.id] + if (!sort || !compare) return [...rows] + const dir = sort.direction === "asc" ? 1 : -1 + return [...rows].sort((a, b) => dir * compare(a, b)) +} + +/** Отсортировать строки по колонкам таблицы (для пагинации снаружи). */ +export function sortRows(rows: readonly T[], columns: readonly DataColumn[], sort: SortState | null) { + return sortBy(rows, Object.fromEntries(columns.map((c) => [c.id, c.sort])), sort) +} + +/** Клик по заголовку: по возрастанию → по убыванию → без сортировки. */ +export function nextSort(current: SortState | null, id: string): SortState | null { + if (current?.id !== id) return { id, direction: "asc" } + if (current.direction === "asc") return { id, direction: "desc" } + return null +} + +/** + * Таблица кита: липкая шапка, сортировка по клику на заголовок, + * кликабельные строки. Строки передаются уже отсортированными/порезанными + * (см. sortRows) — так таблица одинаково работает с пагинацией и без неё. + */ +export function DataTable({ + columns, + rows, + getRowId, + sort, + onSortChange, + onRowClick, + rowProps, + rowClassName, + empty, + className, +}: { + columns: readonly DataColumn[] + rows: readonly T[] + getRowId: (row: T) => React.Key + sort?: SortState | null + onSortChange?: (sort: SortState | null) => void + onRowClick?: (row: T, event: React.MouseEvent) => void + rowProps?: (row: T, index: number) => React.HTMLAttributes + rowClassName?: (row: T, index: number) => string | false | undefined + empty?: React.ReactNode + className?: string +}) { + return ( + + + + {columns.map((col) => { + const active = sort?.id === col.id + const Icon = !active ? ChevronsUpDownIcon : sort.direction === "asc" ? ArrowUpIcon : ArrowDownIcon + return ( + + ) + })} + + + + {rows.map((row, i) => { + const extra = rowProps?.(row, i) + return ( + onRowClick(row, e) : extra?.onClick} + className={cn( + "border-b border-border/60 transition-colors last:border-b-0", + onRowClick && "cursor-pointer hover:bg-muted/50", + rowClassName?.(row, i), + extra?.className, + )} + > + {columns.map((col) => ( + + ))} + + ) + })} + {!rows.length && empty && ( + + + + )} + +
+ {col.sort && onSortChange ? ( + + ) : ( + col.header + )} +
+ {col.cell(row, i)} +
+ {empty} +
+ ) +} diff --git a/src/kit/date-leaf.tsx b/src/kit/date-leaf.tsx new file mode 100644 index 0000000..b4b732f --- /dev/null +++ b/src/kit/date-leaf.tsx @@ -0,0 +1,32 @@ +import { cn } from "@/lib/utils" + +const WEEKDAYS = ["вс", "пн", "вт", "ср", "чт", "пт", "сб"] +const MONTHS = ["янв", "фев", "мар", "апр", "мая", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"] + +/** Дата приёма «листком календаря». */ +export function DateLeaf({ date, upcoming }: { date: string; upcoming?: boolean }) { + const [d, m, y] = date.split(".").map(Number) + const weekday = WEEKDAYS[new Date(y, m - 1, d).getDay()] + + return ( +
+
+ {weekday} +
+
{d}
+
+ {MONTHS[m - 1]} {String(y).slice(2)} +
+
+ ) +} diff --git a/src/kit/file-gallery.tsx b/src/kit/file-gallery.tsx new file mode 100644 index 0000000..f2a9b3a --- /dev/null +++ b/src/kit/file-gallery.tsx @@ -0,0 +1,295 @@ +import * as React from "react" +import { + ChevronLeftIcon, + ChevronRightIcon, + DownloadIcon, + FileArchiveIcon, + FileIcon, + FileTextIcon, + ImageIcon, + XIcon, +} from "lucide-react" + +import { cn } from "@/lib/utils" +import { formatBytes } from "@/lib/format" +import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog" + +export interface FileItem { + readonly name: string + /** Размер в байтах. */ + readonly size: number + readonly type?: string + /** Ссылка на файл; без неё — только карточка без просмотра. */ + readonly src?: string + readonly description?: string +} + +export type FileGallerySize = "sm" | "md" | "lg" + +export function isImageFile(file: FileItem) { + return Boolean(file.type?.startsWith("image/")) || /\.(jpe?g|png|gif|webp|bmp)$/i.test(file.name) +} + +export function isPdfFile(file: FileItem) { + return Boolean(file.type?.includes("pdf")) || /\.pdf$/i.test(file.name) +} + +function fileIcon(file: FileItem) { + if (isImageFile(file)) return ImageIcon + if (isPdfFile(file)) return FileTextIcon + if (/\.(zip|rar|7z)$/i.test(file.name)) return FileArchiveIcon + return FileIcon +} + +function extension(file: FileItem) { + return file.name.split(".").pop()?.toUpperCase() ?? "" +} + +const tileSize: Record = { + sm: "w-24", + md: "w-32", + lg: "w-44", +} + +/** + * Список файлов плитками. Клик по изображению — лайтбокс со стрелками, + * по PDF — встроенный просмотрщик, остальное — скачивание. + */ +export function FileGallery({ + files, + size = "md", + className, +}: { + files: readonly FileItem[] + size?: FileGallerySize + className?: string +}) { + const [openIndex, setOpenIndex] = React.useState(null) + const images = files.filter((f) => isImageFile(f) && f.src) + const opened = openIndex === null ? null : files[openIndex] + + const open = (file: FileItem, index: number) => { + if (!file.src) return + if (isImageFile(file) || isPdfFile(file)) setOpenIndex(index) + else window.open(file.src, "_blank", "noopener") + } + + return ( + <> +
    + {files.map((file, index) => ( +
  • + open(file, index)} /> +
  • + ))} +
+ + {opened && isImageFile(opened) && ( + setOpenIndex(files.indexOf(images[i]))} + onClose={() => setOpenIndex(null)} + /> + )} + {opened && isPdfFile(opened) && setOpenIndex(null)} />} + + ) +} + +function FileTile({ file, size, onOpen }: { file: FileItem; size: FileGallerySize; onOpen: () => void }) { + const [broken, setBroken] = React.useState(false) + const Icon = fileIcon(file) + const image = isImageFile(file) && file.src && !broken + const previewable = Boolean(file.src) && (isImageFile(file) || isPdfFile(file)) + + return ( +
+ +
+ {file.description && size !== "sm" && ( +
+ {file.description} +
+ )} +
+ {file.name} +
+
+ {formatBytes(file.size)} + {file.src && ( + + + + )} +
+
+
+ ) +} + +function ImageLightbox({ + images, + index, + onIndexChange, + onClose, +}: { + images: readonly FileItem[] + index: number + onIndexChange: (index: number) => void + onClose: () => void +}) { + const file = images[index] + const go = React.useCallback( + (delta: number) => onIndexChange((index + delta + images.length) % images.length), + [index, images.length, onIndexChange], + ) + + React.useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "ArrowRight") go(1) + if (e.key === "ArrowLeft") go(-1) + } + window.addEventListener("keydown", onKey) + return () => window.removeEventListener("keydown", onKey) + }, [go]) + + return ( + !v && onClose()}> + + {file.description ?? file.name} + Просмотр изображения +
+ {file.description + {images.length > 1 && ( + <> + go(-1)}> + + + go(1)}> + + + + )} +
+
+
+
{file.description ?? file.name}
+
+ {file.name} · {formatBytes(file.size)} + {images.length > 1 && ` · ${index + 1} из ${images.length}`} +
+
+ + + + +
+
+
+ ) +} + +function LightboxButton({ + side, + label, + onClick, + children, +}: { + side: "left" | "right" + label: string + onClick: () => void + children: React.ReactNode +}) { + return ( + + ) +} + +function PdfPreview({ file, onClose }: { file: FileItem; onClose: () => void }) { + return ( + !v && onClose()}> + +
+ +
+ {file.description ?? file.name} + + {file.name} · {formatBytes(file.size)} + +
+ + Скачать + +
+