Fixed Lab 2

This commit is contained in:
c4ch3c4d3
2026-03-26 20:09:49 -06:00
parent 3bafa35460
commit a663cdbd42
8 changed files with 70 additions and 20 deletions
+46 -1
View File
@@ -120,6 +120,51 @@ function ensureCopyButton(pre: HTMLPreElement, label: string) {
pre.appendChild(copyButton);
}
async function copyTextToClipboard(text: string) {
if (window.isSecureContext && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
return;
}
const activeElement = document.activeElement instanceof HTMLElement ? document.activeElement : null;
const selection = document.getSelection();
const previousRanges =
selection && selection.rangeCount > 0
? Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index).cloneRange())
: [];
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("readonly", "");
textarea.setAttribute("aria-hidden", "true");
textarea.style.position = "fixed";
textarea.style.top = "0";
textarea.style.left = "-9999px";
textarea.style.opacity = "0";
textarea.style.pointerEvents = "none";
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
try {
const didCopy = document.execCommand("copy");
if (!didCopy) {
throw new Error("Copy command was rejected");
}
} finally {
document.body.removeChild(textarea);
if (selection) {
selection.removeAllRanges();
for (const range of previousRanges) {
selection.addRange(range);
}
}
activeElement?.focus();
}
}
export function LabContent({ className, html }: LabContentProps) {
const containerRef = useRef<HTMLElement>(null);
const [zoomedImage, setZoomedImage] = useState<ZoomedImageState | null>(null);
@@ -158,7 +203,7 @@ export function LabContent({ className, html }: LabContentProps) {
if (!commandText) return;
const defaultLabel = button.dataset.defaultLabel ?? "Copy";
void navigator.clipboard.writeText(commandText).then(() => {
void copyTextToClipboard(commandText).then(() => {
button.textContent = "Copied";
button.classList.add("is-copied");
window.setTimeout(() => {