Status dots, page-controlled ConfirmDialog, system theme, release 0.3.0
- ContentTabs: tone dot before the label for status filter tabs; tabs with a zero count are dimmed - StatusBadge: pulse for in-progress states (connecting, waiting for the device); StatusDot exported on its own - ConfirmDialog: trigger is optional, open/onOpenChange let the page drive it; pending, error, disabled, content fields, footer, extraActions, onClosed. A Promise from onConfirm shows the spinner and error by itself and closes on success; the dialog can't be closed while pending; focus goes to the first field - ThemeProvider: "system" mode that follows the OS, defaultTheme and storageKey props; Toaster works without the provider - copyText with an execCommand fallback for plain http; copyToClipboard uses it and reports failures - Dialog and Sheet: close button labelled "Закрыть" for screen readers Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7446adc55c
commit
e96b8fdf5c
|
|
@ -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.2.0"
|
npm i "git+https://git.med-logic.ru/medlogic/medkit.git#semver:^0.3.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) — правки видны сразу.
|
||||||
|
|
@ -51,6 +51,8 @@ CSS приложения:
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`ThemeProvider` — светлая, тёмная или `system` (как в ОС): `<ThemeProvider defaultTheme="system" storageKey="lis.theme">`. По умолчанию `light` и ключ `ml.theme`. `Toaster` работает и без провайдера — тогда берёт системную тему.
|
||||||
|
|
||||||
`NotifyToaster` без `navigate` переходит по `href` через `window.location.assign`.
|
`NotifyToaster` без `navigate` переходит по `href` через `window.location.assign`.
|
||||||
|
|
||||||
Peer-зависимости: `react`, `react-dom` 19, `tailwindcss` 4. В Vite-проекте ничего настраивать не нужно.
|
Peer-зависимости: `react`, `react-dom` 19, `tailwindcss` 4. В Vite-проекте ничего настраивать не нужно.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@medkit/ui",
|
"name": "@medkit/ui",
|
||||||
"version": "0.2.0",
|
"version": "0.3.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": {
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
|
import { Loader2Icon } from "lucide-react"
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
AlertDialogAction,
|
|
||||||
AlertDialogCancel,
|
AlertDialogCancel,
|
||||||
AlertDialogContent,
|
AlertDialogContent,
|
||||||
AlertDialogDescription,
|
AlertDialogDescription,
|
||||||
|
|
@ -11,41 +11,151 @@ import {
|
||||||
AlertDialogTitle,
|
AlertDialogTitle,
|
||||||
AlertDialogTrigger,
|
AlertDialogTrigger,
|
||||||
} from "../ui/alert-dialog"
|
} from "../ui/alert-dialog"
|
||||||
import { buttonVariants } from "../ui/button"
|
import { Button } from "../ui/button"
|
||||||
|
import { cn } from "../lib/utils"
|
||||||
|
|
||||||
/** Подтверждение необратимого действия: «Удалить профиль?» → Удалить / Отмена. */
|
export interface ConfirmDialogProps {
|
||||||
|
title: React.ReactNode
|
||||||
|
description?: React.ReactNode
|
||||||
|
confirmLabel?: string
|
||||||
|
cancelLabel?: string
|
||||||
|
destructive?: boolean
|
||||||
|
/**
|
||||||
|
* Вернул Promise — окно ждёт: кнопка со спиннером, закрыть нельзя; успех закрывает окно,
|
||||||
|
* `throw new Error(текст)` показывает ошибку. Синхронный вызов закрывает окно, если им не управляет страница.
|
||||||
|
*/
|
||||||
|
onConfirm: () => unknown
|
||||||
|
/** Кнопка-триггер. Без неё окном управляет страница через `open` / `onOpenChange`. */
|
||||||
|
children?: React.ReactElement
|
||||||
|
open?: boolean
|
||||||
|
onOpenChange?: (open: boolean) => void
|
||||||
|
/** Ожидание запроса, которым управляет страница (мутация). */
|
||||||
|
pending?: boolean
|
||||||
|
/** Ошибка запроса — над кнопками. */
|
||||||
|
error?: React.ReactNode
|
||||||
|
/** Нельзя подтвердить: не заполнено обязательное поле. */
|
||||||
|
disabled?: boolean
|
||||||
|
/** Поля между описанием и кнопками: причина отмены, комментарий. */
|
||||||
|
content?: React.ReactNode
|
||||||
|
/** Слева от кнопок: «заполнено 3 из 5». */
|
||||||
|
footer?: React.ReactNode
|
||||||
|
/** Кнопки между «Отмена» и основной. */
|
||||||
|
extraActions?: React.ReactNode
|
||||||
|
/** После закрытия — вернуть фокус, куда нужно (иначе — на триггер). */
|
||||||
|
onClosed?: () => void
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Подтверждение действия: «Удалить профиль?» → Удалить / Отмена.
|
||||||
|
* С триггером — открывается по кнопке; с `open` — окном управляет страница (ожидание и ошибка запроса).
|
||||||
|
*/
|
||||||
export function ConfirmDialog({
|
export function ConfirmDialog({
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
confirmLabel = "Удалить",
|
confirmLabel = "Удалить",
|
||||||
|
cancelLabel = "Отмена",
|
||||||
destructive = true,
|
destructive = true,
|
||||||
onConfirm,
|
onConfirm,
|
||||||
children,
|
children,
|
||||||
}: {
|
open: openProp,
|
||||||
title: string
|
onOpenChange,
|
||||||
description?: React.ReactNode
|
pending: pendingProp,
|
||||||
confirmLabel?: string
|
error: errorProp,
|
||||||
destructive?: boolean
|
disabled,
|
||||||
onConfirm: () => void
|
content,
|
||||||
/** Кнопка-триггер. */
|
footer,
|
||||||
children: React.ReactElement
|
extraActions,
|
||||||
}) {
|
onClosed,
|
||||||
|
className,
|
||||||
|
}: ConfirmDialogProps) {
|
||||||
|
const controlled = openProp !== undefined
|
||||||
|
const [openState, setOpenState] = React.useState(false)
|
||||||
|
const [running, setRunning] = React.useState(false)
|
||||||
|
const [runError, setRunError] = React.useState<string>()
|
||||||
|
const contentRef = React.useRef<HTMLDivElement>(null)
|
||||||
|
const open = controlled ? openProp : openState
|
||||||
|
const pending = pendingProp || running
|
||||||
|
const error = errorProp ?? runError
|
||||||
|
|
||||||
|
const setOpen = (next: boolean) => {
|
||||||
|
if (!next && pending) return
|
||||||
|
if (!controlled) setOpenState(next)
|
||||||
|
onOpenChange?.(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Открыли снаружи — прошлая ошибка не нужна.
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (open) setRunError(undefined)
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
async function confirm() {
|
||||||
|
const result = onConfirm()
|
||||||
|
if (!(result instanceof Promise)) {
|
||||||
|
if (!controlled) setOpenState(false)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
setRunning(true)
|
||||||
|
setRunError(undefined)
|
||||||
|
try {
|
||||||
|
await result
|
||||||
|
setRunning(false)
|
||||||
|
if (!controlled) setOpenState(false)
|
||||||
|
onOpenChange?.(false)
|
||||||
|
} catch (e) {
|
||||||
|
setRunning(false)
|
||||||
|
setRunError(e instanceof Error && e.message ? e.message : "Не удалось выполнить действие")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AlertDialog>
|
<AlertDialog open={open} onOpenChange={setOpen}>
|
||||||
<AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
|
{children && <AlertDialogTrigger asChild>{children}</AlertDialogTrigger>}
|
||||||
<AlertDialogContent>
|
<AlertDialogContent
|
||||||
|
className={className}
|
||||||
|
onEscapeKeyDown={(e) => pending && e.preventDefault()}
|
||||||
|
onOpenAutoFocus={(e) => {
|
||||||
|
// Есть поля — фокус в первое, а не на «Отмена».
|
||||||
|
const field = contentRef.current?.querySelector<HTMLElement>("input, textarea, select, [tabindex]")
|
||||||
|
if (!field) return
|
||||||
|
e.preventDefault()
|
||||||
|
field.focus()
|
||||||
|
}}
|
||||||
|
onCloseAutoFocus={
|
||||||
|
onClosed
|
||||||
|
? (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
onClosed()
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>{title}</AlertDialogTitle>
|
<AlertDialogTitle>{title}</AlertDialogTitle>
|
||||||
{description && <AlertDialogDescription>{description}</AlertDialogDescription>}
|
{/* Описание нужно Radix для диктора — без текста прячем от глаз */}
|
||||||
|
<AlertDialogDescription className={description ? undefined : "sr-only"}>
|
||||||
|
{description ?? title}
|
||||||
|
</AlertDialogDescription>
|
||||||
</AlertDialogHeader>
|
</AlertDialogHeader>
|
||||||
<AlertDialogFooter>
|
{content && <div ref={contentRef}>{content}</div>}
|
||||||
<AlertDialogCancel>Отмена</AlertDialogCancel>
|
{error && (
|
||||||
<AlertDialogAction
|
<p role="alert" className="rounded-lg bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
||||||
onClick={onConfirm}
|
{error}
|
||||||
className={destructive ? buttonVariants({ variant: "destructive" }) : undefined}
|
</p>
|
||||||
|
)}
|
||||||
|
<AlertDialogFooter className="sm:items-center">
|
||||||
|
{footer && <div className="text-xs text-muted-foreground tabular sm:mr-auto">{footer}</div>}
|
||||||
|
<AlertDialogCancel disabled={pending}>{cancelLabel}</AlertDialogCancel>
|
||||||
|
{extraActions}
|
||||||
|
<Button
|
||||||
|
variant={destructive ? "destructive" : "default"}
|
||||||
|
onClick={() => void confirm()}
|
||||||
|
disabled={disabled || pending}
|
||||||
|
className={cn(pending && "disabled:opacity-80")}
|
||||||
>
|
>
|
||||||
|
{pending && <Loader2Icon className="animate-spin" />}
|
||||||
{confirmLabel}
|
{confirmLabel}
|
||||||
</AlertDialogAction>
|
</Button>
|
||||||
</AlertDialogFooter>
|
</AlertDialogFooter>
|
||||||
</AlertDialogContent>
|
</AlertDialogContent>
|
||||||
</AlertDialog>
|
</AlertDialog>
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,23 @@
|
||||||
import { type LucideIcon } from "lucide-react"
|
import { type LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
import { cn } from "../lib/utils"
|
import { cn } from "../lib/utils"
|
||||||
|
import { StatusDot, type StatusTone } from "./status-badge"
|
||||||
|
|
||||||
export interface ContentTabItem<T extends string = string> {
|
export interface ContentTabItem<T extends string = string> {
|
||||||
readonly id: T
|
readonly id: T
|
||||||
readonly label: string
|
readonly label: string
|
||||||
readonly icon?: LucideIcon
|
readonly icon?: LucideIcon
|
||||||
/** Счётчик справа от подписи. */
|
/** Счётчик справа от подписи; вкладка с нулём приглушена. */
|
||||||
readonly count?: number
|
readonly count?: number
|
||||||
|
/** Цветная точка статуса перед подписью — вкладки-фильтры по статусам. */
|
||||||
|
readonly tone?: StatusTone
|
||||||
readonly disabled?: boolean
|
readonly disabled?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Контентные вкладки внутри страницы/карточки.
|
* Контентные вкладки внутри страницы/карточки.
|
||||||
* `line` — подчёркивание (разделы карточки), `pill` — заливка (переключатели в блоках).
|
* `line` — подчёркивание (разделы карточки), `pill` — заливка (переключатели в блоках).
|
||||||
|
* Вкладки-фильтры по статусам: `{ id, label, count, tone }`, первая — «Все» без тона.
|
||||||
*/
|
*/
|
||||||
export function ContentTabs<T extends string>({
|
export function ContentTabs<T extends string>({
|
||||||
tabs,
|
tabs,
|
||||||
|
|
@ -55,9 +59,11 @@ export function ContentTabs<T extends string>({
|
||||||
variant === "pill" && "h-8 rounded-lg px-3",
|
variant === "pill" && "h-8 rounded-lg px-3",
|
||||||
variant === "pill" &&
|
variant === "pill" &&
|
||||||
(active ? "bg-card text-foreground shadow-xs" : "text-muted-foreground hover:text-foreground"),
|
(active ? "bg-card text-foreground shadow-xs" : "text-muted-foreground hover:text-foreground"),
|
||||||
|
tab.count === 0 && !active && "opacity-60",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{tab.icon && <tab.icon className={cn("size-4", active && "text-primary")} />}
|
{tab.icon && <tab.icon className={cn("size-4", active && "text-primary")} />}
|
||||||
|
{tab.tone && <StatusDot tone={tab.tone} />}
|
||||||
{tab.label}
|
{tab.label}
|
||||||
{tab.count !== undefined && (
|
{tab.count !== undefined && (
|
||||||
<span
|
<span
|
||||||
|
|
|
||||||
|
|
@ -10,15 +10,52 @@ const toneClass: Record<StatusTone, string> = {
|
||||||
neutral: "bg-muted text-muted-foreground border-border",
|
neutral: "bg-muted text-muted-foreground border-border",
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Статус с цветной точкой: «Работает», «Записан», «Неявка»… */
|
const dotClass: Record<StatusTone, string> = {
|
||||||
|
positive: "bg-success",
|
||||||
|
info: "bg-info",
|
||||||
|
warning: "bg-warning",
|
||||||
|
negative: "bg-coral",
|
||||||
|
neutral: "bg-muted-foreground/60",
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Цветная точка статуса — во вкладках, списках, рядом с подписью.
|
||||||
|
* `pulse` — мигает: идёт процесс («подключение», «ожидание связи»).
|
||||||
|
*/
|
||||||
|
export function StatusDot({
|
||||||
|
tone,
|
||||||
|
pulse,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
/** Без тона точка берёт цвет текста. */
|
||||||
|
tone?: StatusTone
|
||||||
|
pulse?: boolean
|
||||||
|
className?: string
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
aria-hidden
|
||||||
|
className={cn(
|
||||||
|
"size-1.5 shrink-0 rounded-full",
|
||||||
|
tone ? dotClass[tone] : "bg-current",
|
||||||
|
pulse && "animate-status-pulse motion-reduce:animate-none",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Статус с цветной точкой: «Работает», «Записан», «Неявка»… `pulse` — точка мигает («Подключение…»). */
|
||||||
export function StatusBadge({
|
export function StatusBadge({
|
||||||
tone,
|
tone,
|
||||||
dot = true,
|
dot = true,
|
||||||
|
pulse,
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
tone: StatusTone
|
tone: StatusTone
|
||||||
dot?: boolean
|
dot?: boolean
|
||||||
|
pulse?: boolean
|
||||||
className?: string
|
className?: string
|
||||||
children: React.ReactNode
|
children: React.ReactNode
|
||||||
}) {
|
}) {
|
||||||
|
|
@ -30,7 +67,7 @@ export function StatusBadge({
|
||||||
className,
|
className,
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{dot && <span className="size-1.5 rounded-full bg-current" />}
|
{dot && <StatusDot pulse={pulse} />}
|
||||||
{children}
|
{children}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,39 @@
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
|
|
||||||
/** Скопировать значение и показать подтверждение. */
|
/**
|
||||||
export function copyToClipboard(value: string, title = "Скопировано") {
|
* Скопировать текст в буфер. navigator.clipboard есть только в защищённом контексте (https, localhost);
|
||||||
void navigator.clipboard?.writeText(value)
|
* открыто по http в локальной сети или нет разрешения — запасной путь через скрытое поле и execCommand.
|
||||||
toast.success(title, { description: value })
|
*/
|
||||||
|
export async function copyText(text: string): Promise<void> {
|
||||||
|
if (navigator.clipboard && window.isSecureContext) {
|
||||||
|
try {
|
||||||
|
return await navigator.clipboard.writeText(text)
|
||||||
|
} catch {
|
||||||
|
// нет разрешения на буфер — пробуем по-старому
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const active = document.activeElement as HTMLElement | null
|
||||||
|
const area = Object.assign(document.createElement("textarea"), { value: text, readOnly: true })
|
||||||
|
Object.assign(area.style, { position: "fixed", top: "0", left: "0", opacity: "0", pointerEvents: "none" })
|
||||||
|
// Внутри модального окна поле кладём в него: фокус-ловушка Radix не отдаёт фокус наружу.
|
||||||
|
const host = active?.closest<HTMLElement>("[role=dialog], [role=alertdialog]") ?? document.body
|
||||||
|
host.appendChild(area)
|
||||||
|
area.focus({ preventScroll: true })
|
||||||
|
area.select()
|
||||||
|
try {
|
||||||
|
if (!document.execCommand("copy")) throw new Error("Браузер не дал скопировать")
|
||||||
|
} finally {
|
||||||
|
area.remove()
|
||||||
|
active?.focus({ preventScroll: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Скопировать значение и показать подтверждение (или ошибку). */
|
||||||
|
export async function copyToClipboard(value: string, title = "Скопировано") {
|
||||||
|
try {
|
||||||
|
await copyText(value)
|
||||||
|
toast.success(title, { description: value })
|
||||||
|
} catch {
|
||||||
|
toast.error("Не удалось скопировать", { description: value })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -168,6 +168,13 @@
|
||||||
0%, 70%, 100% { opacity: 1; }
|
0%, 70%, 100% { opacity: 1; }
|
||||||
20%, 50% { opacity: 0; }
|
20%, 50% { opacity: 0; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Мигающая точка статуса: «подключение», «ожидание связи» */
|
||||||
|
--animate-status-pulse: status-pulse 1.4s ease-in-out infinite;
|
||||||
|
@keyframes status-pulse {
|
||||||
|
0%, 100% { opacity: 1; }
|
||||||
|
50% { opacity: 0.3; }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer base {
|
@layer base {
|
||||||
|
|
|
||||||
|
|
@ -1,40 +1,85 @@
|
||||||
import * as React from "react"
|
import * as React from "react"
|
||||||
|
|
||||||
type Theme = "light" | "dark"
|
/** Выбор пользователя; `system` — как в настройках ОС. */
|
||||||
|
export type Theme = "light" | "dark" | "system"
|
||||||
|
/** Тема, которая сейчас на экране. */
|
||||||
|
export type ResolvedTheme = "light" | "dark"
|
||||||
|
|
||||||
const STORAGE_KEY = "ml.theme"
|
const DARK_QUERY = "(prefers-color-scheme: dark)"
|
||||||
|
|
||||||
const ThemeContext = React.createContext<{ theme: Theme; resolvedTheme: Theme; setTheme: (t: Theme) => void } | null>(
|
interface ThemeContextValue {
|
||||||
null,
|
theme: Theme
|
||||||
)
|
resolvedTheme: ResolvedTheme
|
||||||
|
setTheme: (theme: Theme) => void
|
||||||
|
}
|
||||||
|
|
||||||
function readTheme(): Theme {
|
const ThemeContext = React.createContext<ThemeContextValue | null>(null)
|
||||||
|
|
||||||
|
function isTheme(value: unknown): value is Theme {
|
||||||
|
return value === "light" || value === "dark" || value === "system"
|
||||||
|
}
|
||||||
|
|
||||||
|
function readTheme(storageKey: string, fallback: Theme): Theme {
|
||||||
try {
|
try {
|
||||||
return localStorage.getItem(STORAGE_KEY) === "dark" ? "dark" : "light"
|
const stored = localStorage.getItem(storageKey)
|
||||||
|
return isTheme(stored) ? stored : fallback
|
||||||
} catch {
|
} catch {
|
||||||
return "light"
|
return fallback
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Светлая/тёмная тема: класс `dark` на <html>, выбор помнится в localStorage. */
|
function systemTheme(): ResolvedTheme {
|
||||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
return typeof window !== "undefined" && window.matchMedia?.(DARK_QUERY).matches ? "dark" : "light"
|
||||||
const [theme, setThemeState] = React.useState<Theme>(readTheme)
|
}
|
||||||
|
|
||||||
|
/** Тема ОС; следит за переключением. */
|
||||||
|
function useSystemTheme() {
|
||||||
|
return React.useSyncExternalStore(
|
||||||
|
(onChange) => {
|
||||||
|
const query = window.matchMedia?.(DARK_QUERY)
|
||||||
|
query?.addEventListener("change", onChange)
|
||||||
|
return () => query?.removeEventListener("change", onChange)
|
||||||
|
},
|
||||||
|
systemTheme,
|
||||||
|
() => "light" as const,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Светлая, тёмная или «как в системе»: класс `dark` на <html>, выбор помнится в localStorage.
|
||||||
|
* `defaultTheme` — пока пользователь ничего не выбрал.
|
||||||
|
*/
|
||||||
|
export function ThemeProvider({
|
||||||
|
defaultTheme = "light",
|
||||||
|
storageKey = "ml.theme",
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
defaultTheme?: Theme
|
||||||
|
storageKey?: string
|
||||||
|
children: React.ReactNode
|
||||||
|
}) {
|
||||||
|
const [theme, setThemeState] = React.useState<Theme>(() => readTheme(storageKey, defaultTheme))
|
||||||
|
const system = useSystemTheme()
|
||||||
|
const resolvedTheme = theme === "system" ? system : theme
|
||||||
|
|
||||||
React.useLayoutEffect(() => {
|
React.useLayoutEffect(() => {
|
||||||
document.documentElement.classList.toggle("dark", theme === "dark")
|
document.documentElement.classList.toggle("dark", resolvedTheme === "dark")
|
||||||
document.documentElement.style.colorScheme = theme
|
document.documentElement.style.colorScheme = resolvedTheme
|
||||||
}, [theme])
|
}, [resolvedTheme])
|
||||||
|
|
||||||
const setTheme = React.useCallback((next: Theme) => {
|
const setTheme = React.useCallback(
|
||||||
|
(next: Theme) => {
|
||||||
setThemeState(next)
|
setThemeState(next)
|
||||||
try {
|
try {
|
||||||
localStorage.setItem(STORAGE_KEY, next)
|
localStorage.setItem(storageKey, next)
|
||||||
} catch {
|
} catch {
|
||||||
/* noop */
|
/* noop */
|
||||||
}
|
}
|
||||||
}, [])
|
},
|
||||||
|
[storageKey],
|
||||||
|
)
|
||||||
|
|
||||||
const value = React.useMemo(() => ({ theme, resolvedTheme: theme, setTheme }), [theme, setTheme])
|
const value = React.useMemo(() => ({ theme, resolvedTheme, setTheme }), [theme, resolvedTheme, setTheme])
|
||||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -43,3 +88,8 @@ export function useTheme() {
|
||||||
if (!ctx) throw new Error("useTheme must be used inside <ThemeProvider>")
|
if (!ctx) throw new Error("useTheme must be used inside <ThemeProvider>")
|
||||||
return ctx
|
return ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Тема, если приложение обёрнуто в ThemeProvider; иначе null (тостер и т. п. работают и без него). */
|
||||||
|
export function useOptionalTheme() {
|
||||||
|
return React.useContext(ThemeContext)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -72,7 +72,7 @@ function DialogContent({
|
||||||
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||||
>
|
>
|
||||||
<XIcon />
|
<XIcon />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Закрыть</span>
|
||||||
</DialogPrimitive.Close>
|
</DialogPrimitive.Close>
|
||||||
)}
|
)}
|
||||||
</DialogPrimitive.Content>
|
</DialogPrimitive.Content>
|
||||||
|
|
@ -110,7 +110,7 @@ function DialogFooter({
|
||||||
{children}
|
{children}
|
||||||
{showCloseButton && (
|
{showCloseButton && (
|
||||||
<DialogPrimitive.Close asChild>
|
<DialogPrimitive.Close asChild>
|
||||||
<Button variant="outline">Close</Button>
|
<Button variant="outline">Закрыть</Button>
|
||||||
</DialogPrimitive.Close>
|
</DialogPrimitive.Close>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -75,7 +75,7 @@ function SheetContent({
|
||||||
{showCloseButton && (
|
{showCloseButton && (
|
||||||
<SheetPrimitive.Close className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary">
|
<SheetPrimitive.Close className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary">
|
||||||
<XIcon className="size-4" />
|
<XIcon className="size-4" />
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Закрыть</span>
|
||||||
</SheetPrimitive.Close>
|
</SheetPrimitive.Close>
|
||||||
)}
|
)}
|
||||||
</SheetPrimitive.Content>
|
</SheetPrimitive.Content>
|
||||||
|
|
|
||||||
|
|
@ -6,15 +6,16 @@ import {
|
||||||
OctagonXIcon,
|
OctagonXIcon,
|
||||||
TriangleAlertIcon,
|
TriangleAlertIcon,
|
||||||
} from "lucide-react"
|
} from "lucide-react"
|
||||||
import { useTheme } from "../theme-provider"
|
import { useOptionalTheme } from "../theme-provider"
|
||||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||||
|
|
||||||
|
/** Тема — из ThemeProvider кита, без него — как в системе; `theme` в пропсах важнее. */
|
||||||
const Toaster = ({ ...props }: ToasterProps) => {
|
const Toaster = ({ ...props }: ToasterProps) => {
|
||||||
const { theme } = useTheme()
|
const theme = useOptionalTheme()?.resolvedTheme ?? "system"
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Sonner
|
<Sonner
|
||||||
theme={theme as ToasterProps["theme"]}
|
theme={theme}
|
||||||
className="toaster group"
|
className="toaster group"
|
||||||
icons={{
|
icons={{
|
||||||
success: <CircleCheckIcon className="size-4" />,
|
success: <CircleCheckIcon className="size-4" />,
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue