ข้ามไปยังเนื้อหา

ปุ่มคัดลอก

CopyButton

Copies a value, such as a document number, a link or code, to the clipboard. After a press its icon turns into a green check and says Copied for two seconds, and screen readers hear it. When the browser blocks the clipboard, it turns red and says to select the text and copy it by hand. Every copy action uses it.

ใช้คัดลอกค่าไปยังคลิปบอร์ด เช่น เลขที่เอกสาร ลิงก์ หรือโค้ด เมื่อกดแล้วไอคอนเปลี่ยนเป็นเครื่องหมายถูกสีเขียวพร้อมคำว่า คัดลอกแล้ว 2 วินาที และโปรแกรมอ่านหน้าจอได้ยิน ถ้าเบราว์เซอร์ไม่ให้คัดลอก ปุ่มเป็นสีแดงและบอกให้เลือกข้อความแล้วคัดลอกเอง ทุกปุ่มคัดลอกใช้คอมโพเนนต์นี้

import { CopyButton } from "@bsru/ui";

ตัวอย่าง

ข้างเลขที่เอกสาร

value คือข้อความที่คัดลอก label บอกว่าคัดลอกอะไร และเป็นชื่อที่โปรแกรมอ่านหน้าจออ่าน ลองกดปุ่ม

PR-2570-0001

<span className="font-display text-2xl">{no}</span>
<CopyButton value={no} label={`คัดลอกเลขที่ ${no}`} size="sm" />

ปุ่มพร้อมข้อความ

variant button แสดง label เป็นข้อความ และเปลี่ยนเป็น คัดลอกแล้ว เมื่อคัดลอกสำเร็จ ใช้เมื่อมีที่ว่างพอ เช่น ข้างช่องลิงก์

<TextInput label="ลิงก์ของคำขอ" value={link} readOnly />
<CopyButton value={link} label="คัดลอกลิงก์" variant="button" />

ข้อความเมื่อคัดลอกแล้วของตัวเอง

copiedLabel เปลี่ยนคำที่แสดงหลังคัดลอก outline เพิ่มเส้นขอบ onCopy ได้รับค่าที่คัดลอกสำเร็จ

<CopyButton
  value={"<Icon icon={Wallet} />"}
  label="คัดลอกโค้ด"
  copiedLabel="คัดลอกโค้ดแล้ว"
  outline
/>

ตัวควบคุมที่ไม่ใช่ปุ่มคัดลอก ด้วย useCopy

ถ้าการคัดลอกเกิดจากตัวควบคุมอื่น เช่น ไทล์ในแกลเลอรีไอคอน ใช้ useCopy และแสดงสถานะเดียวกัน: data-copy เป็น copied หรือ failed ให้สีจากแนวทางการออกแบบ

const { state, key, copy } = useCopy();

<button data-copy={key === code ? state : "idle"} onClick={() => copy(code)}>
  {key !== code ? code : state === "copied" ? "คัดลอกแล้ว" : state === "failed" ? "คัดลอกไม่ได้" : code}
</button>

props ทั้งหมด

ตัวอย่างด้านบนใช้ props เพียงบางตัว ตารางนี้แสดงทุกตัวที่คอมโพเนนต์รับ พร้อมค่าเริ่มต้นและค่าที่ใช้ได้

CopyButton props
ชื่อชนิดข้อมูลค่าเริ่มต้นคำอธิบาย
value* จำเป็นstring—The text that goes to the clipboard.
label* จำเป็นstring—What it copies, already in the screen language, such as คัดลอกเลขที่ PR-2570-0001. The icon button's name.
copiedLabelstring—Shown after it works. Defaults to คัดลอกแล้ว in the screen language.
variant"icon" | "button""icon"icon for an icon-only button beside the value, button for a button with its label as text.
size"md" | "sm""md"sm is 36 pixels, for a dense row. md is 44 pixels, the touch size.
outlinebooleanfalseAdds a border to the icon button, such as beside an input.
classNamestring—Placement only, such as absolute top-2 right-2 over a code block.
onCopy(value: string) => void—Hears each copy that worked, such as to record it.

ข้อควรปฏิบัติ

  • ชื่อของปุ่มบอกค่าที่คัดลอก เช่น คัดลอกเลขที่ PR-2570-0001 ไม่ใช่แค่ คัดลอก
  • ไม่ต้องแสดง toast ซ้ำ ปุ่มบอกเองแล้วว่าคัดลอกแล้ว
  • ค่าที่มีข้อมูลส่วนบุคคลห้ามคัดลอกโดยไม่ได้แสดงให้เห็นก่อน

ซอร์สโค้ด: ui/src/copy.tsx