medkit/src/kit/copy-value.tsx

54 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import * as React from "react"
import { copyText } from "../lib/clipboard"
import { cn } from "../lib/utils"
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"
/**
* Значение, которое копируется по клику (ФИО, штрихкод, номер заявки). При наведении ничего не меняется,
* после клика на полсекунды всплывает «Скопировано». Работает и с клавиатуры (Enter, пробел).
*/
export function CopyValue({ text, className, children }: { text: string; className?: string; children?: React.ReactNode }) {
const [state, setState] = React.useState<"idle" | "copied" | "failed">("idle")
React.useEffect(() => {
if (state === "idle") return
const timer = setTimeout(() => setState("idle"), state === "failed" ? 1500 : 500)
return () => clearTimeout(timer)
}, [state])
const copy = () =>
copyText(text).then(
() => setState("copied"),
() => setState("failed"),
)
return (
<Tooltip open={state !== "idle"}>
<TooltipTrigger asChild>
<span
role="button"
tabIndex={0}
aria-label={`Скопировать ${text}`}
onClick={(e) => {
// в строке таблицы клик по значению не открывает строку
e.stopPropagation()
void copy()
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault()
e.stopPropagation()
void copy()
}
}}
className={cn("cursor-copy rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/60", className)}
>
{children ?? text}
</span>
</TooltipTrigger>
<TooltipContent side="top">{state === "failed" ? "Не удалось скопировать" : "Скопировано"}</TooltipContent>
</Tooltip>
)
}