Release 0.15.0: file type icon and upload progress.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b57b3e1ad0
commit
08ef767b63
|
|
@ -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
|
||||
|
||||
### Изменено
|
||||
|
|
|
|||
|
|
@ -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) — правки видны сразу.
|
||||
|
|
|
|||
|
|
@ -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": {
|
||||
|
|
|
|||
|
|
@ -26,11 +26,11 @@ export interface FileItem {
|
|||
|
||||
export type FileGallerySize = "sm" | "md" | "lg"
|
||||
|
||||
export function isImageFile(file: FileItem) {
|
||||
export function isImageFile(file: Pick<FileItem, "name" | "type">) {
|
||||
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<FileItem, "name" | "type">) {
|
||||
return Boolean(file.type?.includes("pdf")) || /\.pdf$/i.test(file.name)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
})
|
||||
})
|
||||
|
|
@ -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<Record<string, FileKind>> = {
|
||||
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<FileItem, "name" | "type">): FileKind {
|
||||
if (isPdfFile(file)) return "pdf"
|
||||
if (isImageFile(file)) return "image"
|
||||
return EXTENSION_KIND[file.name.split(".").pop()?.toLowerCase() ?? ""] ?? "other"
|
||||
}
|
||||
|
||||
/** Цвет различает группы файлов, а не украшает. */
|
||||
const KIND_STYLE: Readonly<Record<FileKind, { icon: LucideIcon; tone: string }>> = {
|
||||
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<FileItem, "name" | "type">; className?: string }) {
|
||||
const { icon: Icon, tone } = KIND_STYLE[fileKind(file)]
|
||||
return (
|
||||
<span aria-hidden className={cn("grid size-8 shrink-0 place-items-center rounded-lg", tone, className)}>
|
||||
<Icon className="size-4" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<div className={cn("flex items-center gap-2.5 rounded-lg bg-muted/50 px-3 py-2", className)}>
|
||||
<FileTypeIcon file={file} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium" title={file.name}>
|
||||
{file.name}
|
||||
</div>
|
||||
{error ? (
|
||||
<div role="alert" className="text-xs text-coral">
|
||||
{error}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-xs text-muted-foreground tabular">
|
||||
{formatBytes(file.size)} · {percent === null ? "Загрузка…" : `Загрузка ${percent}%`}
|
||||
</div>
|
||||
<Progress value={percent} aria-label={`Загрузка файла ${file.name}`} className="mt-1 h-1" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{onCancel && (
|
||||
<Button variant="ghost" size="icon-sm" title={cancelLabel} aria-label={cancelLabel} onClick={onCancel}>
|
||||
<XIcon />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -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 МБ")
|
||||
})
|
||||
})
|
||||
|
|
@ -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 ₽» */
|
||||
|
|
|
|||
Loading…
Reference in New Issue