diff --git a/CHANGELOG.md b/CHANGELOG.md index 222e45a..f8c71a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ Установка версии: `npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^X.Y.Z"`. На 0.x `^0.7.0` не подхватывает 0.8.0 — минорную версию поднимаем в зависимости явно. +## [0.15.0] — 2026-11-02 + +### Новое +- `FileTypeIcon`: цветная плитка типа файла для строк списка — PDF, изображение, документ, таблица, презентация, архив, прочее. Проп `file` — `{ name, type }`; группу можно узнать и без значка, хелпером `fileKind`. +- `UploadProgress`: строка загружаемого файла с именем, размером, прогрессом и отменой. `progress` — проценты, `null` — бегущий отрезок; с `error` вместо полосы показывается текст ошибки, а крестик (`onCancel`) скрывает строку. + +### Изменено +- `formatBytes`: единицы теперь по-русски, дробная часть — через запятую, у чисел от десяти её нет: «512 Б», «1,5 КБ», «12 МБ» вместо «512 B», «1.5 KB», «12.0 MB». Это видно и в `FileGallery`, и в просмотрщике файлов. Если где-то разбираете эту строку или проверяете её в тестах — обновите. + ## [0.14.2] — 2026-11-01 ### Изменено diff --git a/README.md b/README.md index b47d4d5..3a925bd 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.14.2" +npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.15.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 13b761b..ab990a6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@medkit/ui", - "version": "0.14.2", + "version": "0.15.0", "private": true, "description": "Medkit — UI kit МИС «Медицина»: React 19 + Tailwind 4 + Radix (shadcn/ui)", "repository": { diff --git a/src/kit/file-gallery.tsx b/src/kit/file-gallery.tsx index d437a3f..1b019a3 100644 --- a/src/kit/file-gallery.tsx +++ b/src/kit/file-gallery.tsx @@ -26,11 +26,11 @@ export interface FileItem { export type FileGallerySize = "sm" | "md" | "lg" -export function isImageFile(file: FileItem) { +export function isImageFile(file: Pick) { return Boolean(file.type?.startsWith("image/")) || /\.(jpe?g|png|gif|webp|bmp)$/i.test(file.name) } -export function isPdfFile(file: FileItem) { +export function isPdfFile(file: Pick) { return Boolean(file.type?.includes("pdf")) || /\.pdf$/i.test(file.name) } diff --git a/src/kit/file-type-icon.test.ts b/src/kit/file-type-icon.test.ts new file mode 100644 index 0000000..eda933d --- /dev/null +++ b/src/kit/file-type-icon.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest" + +import { fileKind } from "./file-type-icon" + +describe("fileKind", () => { + it.each([ + ["analizy.PDF", "pdf"], + ["snimok.jpeg", "image"], + ["napravlenie.docx", "document"], + ["zametka.txt", "document"], + ["prays.xlsx", "sheet"], + ["vygruzka.csv", "sheet"], + ["doklad.pptx", "slides"], + ["seriya.7z", "archive"], + ["dannye.bin", "other"], + ["bez-rasshireniya", "other"], + ])("%s → %s", (name, kind) => { + expect(fileKind({ name })).toBe(kind) + }) + + it("без расширения смотрит на тип из браузера", () => { + expect(fileKind({ name: "snimok", type: "image/png" })).toBe("image") + expect(fileKind({ name: "otchet", type: "application/pdf" })).toBe("pdf") + }) +}) diff --git a/src/kit/file-type-icon.tsx b/src/kit/file-type-icon.tsx new file mode 100644 index 0000000..ac8951c --- /dev/null +++ b/src/kit/file-type-icon.tsx @@ -0,0 +1,60 @@ +import { + FileArchiveIcon, + FileIcon, + FileSpreadsheetIcon, + FileTextIcon, + ImageIcon, + PresentationIcon, + type LucideIcon, +} from "lucide-react" + +import { cn } from "../lib/utils" +import { isImageFile, isPdfFile, type FileItem } from "./file-gallery" + +export type FileKind = "pdf" | "image" | "document" | "sheet" | "slides" | "archive" | "other" + +const EXTENSION_KIND: Readonly> = { + doc: "document", + docx: "document", + odt: "document", + rtf: "document", + txt: "document", + xls: "sheet", + xlsx: "sheet", + ods: "sheet", + csv: "sheet", + ppt: "slides", + pptx: "slides", + odp: "slides", + zip: "archive", + rar: "archive", + "7z": "archive", +} + +/** Группа файла по типу из браузера и расширению. */ +export function fileKind(file: Pick): FileKind { + if (isPdfFile(file)) return "pdf" + if (isImageFile(file)) return "image" + return EXTENSION_KIND[file.name.split(".").pop()?.toLowerCase() ?? ""] ?? "other" +} + +/** Цвет различает группы файлов, а не украшает. */ +const KIND_STYLE: Readonly> = { + pdf: { icon: FileTextIcon, tone: "bg-coral-soft text-coral" }, + image: { icon: ImageIcon, tone: "bg-accent text-primary" }, + document: { icon: FileTextIcon, tone: "bg-info-soft text-info" }, + sheet: { icon: FileSpreadsheetIcon, tone: "bg-success-soft text-success" }, + slides: { icon: PresentationIcon, tone: "bg-warning-soft text-warning" }, + archive: { icon: FileArchiveIcon, tone: "bg-muted text-muted-foreground" }, + other: { icon: FileIcon, tone: "bg-muted text-muted-foreground" }, +} + +/** Значок типа файла: цветная плитка для строк списка. */ +export function FileTypeIcon({ file, className }: { file: Pick; className?: string }) { + const { icon: Icon, tone } = KIND_STYLE[fileKind(file)] + return ( + + + + ) +} diff --git a/src/kit/index.ts b/src/kit/index.ts index aa29dda..4afa568 100644 --- a/src/kit/index.ts +++ b/src/kit/index.ts @@ -16,6 +16,7 @@ export * from "./edit-dialog" export * from "./empty-state" export * from "./file-drop" export * from "./file-gallery" +export * from "./file-type-icon" export * from "./filter-bar" export * from "./filter-tabs" export * from "./filter-toggle" @@ -50,3 +51,4 @@ export * from "./status-badge" export * from "./stepper" export * from "./time-input" export * from "./time-range-input" +export * from "./upload-progress" diff --git a/src/kit/upload-progress.tsx b/src/kit/upload-progress.tsx new file mode 100644 index 0000000..189ccb1 --- /dev/null +++ b/src/kit/upload-progress.tsx @@ -0,0 +1,57 @@ +import { XIcon } from "lucide-react" + +import { formatBytes } from "../lib/format" +import { cn } from "../lib/utils" +import { Button } from "../ui/button" +import { Progress } from "../ui/progress" +import { FileTypeIcon } from "./file-type-icon" + +/** + * Строка загружаемого файла: имя, размер, полоса прогресса и отмена. + * `progress` — проценты, `null` — неизвестно, сколько осталось (бегущий отрезок). + * С `error` вместо полосы — текст ошибки, а крестик скрывает строку. + */ +export function UploadProgress({ + file, + progress = null, + error, + onCancel, + className, +}: { + file: { readonly name: string; readonly size: number; readonly type?: string } + progress?: number | null + error?: string + onCancel?: () => void + className?: string +}) { + const percent = progress === null ? null : Math.round(progress) + const cancelLabel = error ? "Скрыть" : "Отменить загрузку" + + return ( +
+ +
+
+ {file.name} +
+ {error ? ( +
+ {error} +
+ ) : ( + <> +
+ {formatBytes(file.size)} · {percent === null ? "Загрузка…" : `Загрузка ${percent}%`} +
+ + + )} +
+ {onCancel && ( + + )} +
+ ) +} diff --git a/src/lib/format.test.ts b/src/lib/format.test.ts new file mode 100644 index 0000000..72f8083 --- /dev/null +++ b/src/lib/format.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest" + +import { formatBytes } from "./format" + +describe("formatBytes", () => { + it("пишет единицы по-русски", () => { + expect(formatBytes(512)).toBe("512 Б") + expect(formatBytes(2048)).toBe("2 КБ") + expect(formatBytes(5 * 1024 * 1024)).toBe("5 МБ") + expect(formatBytes(3 * 1024 ** 3)).toBe("3 ГБ") + }) + + it("дробную часть отделяет запятой, у больших чисел её нет", () => { + expect(formatBytes(1536)).toBe("1,5 КБ") + expect(formatBytes(12_582_912)).toBe("12 МБ") + }) +}) diff --git a/src/lib/format.ts b/src/lib/format.ts index f6e26be..86bd7c0 100644 --- a/src/lib/format.ts +++ b/src/lib/format.ts @@ -12,16 +12,18 @@ export function pluralYears(age: number) { return `${age} ${plural(age, "год", "года", "лет")}` } +/** «512 Б», «1,5 КБ», «12 МБ»: у чисел от десяти дробная часть не нужна. */ export function formatBytes(bytes: number) { - if (bytes < 1024) return `${bytes} B` - const units = ["KB", "MB", "GB"] + if (bytes < 1024) return `${bytes} Б` + const units = ["КБ", "МБ", "ГБ"] let value = bytes / 1024 let unit = 0 while (value >= 1024 && unit < units.length - 1) { value /= 1024 unit++ } - return `${value.toFixed(1)} ${units[unit]}` + const text = value >= 10 ? String(Math.round(value)) : String(Number(value.toFixed(1))).replace(".", ",") + return `${text} ${units[unit]}` } /** «1 300,00 ₽» */