Page MenuHomeSealhub

exportable-textarea.stimulus.ts
No OneTemporary

exportable-textarea.stimulus.ts

/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { Controller } from "stimulus";
function download(data: string, filename: string, type: string) {
const file = new Blob([data], { type: type });
const a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
export default class ExportableTextarea extends Controller<HTMLDetailsElement> {
connect() {
console.log("exportable", this.element);
this.element.removeAttribute("open");
this.element.addEventListener(
"turbo:before-morph-attribute",
(event: CustomEvent<{ attributeName: string }>) => {
if (
event.target == this.element &&
event.detail.attributeName == "open"
) {
event.preventDefault();
}
}
);
}
async copy(e: MouseEvent) {
e.preventDefault();
const textarea = this.element.querySelector("textarea");
if (!textarea) {
throw new Error("Couldn't find the textarea");
}
await navigator.clipboard.writeText(textarea.value);
(e.target as HTMLButtonElement).textContent = "Copied";
await sleep(1000);
(e.target as HTMLButtonElement).textContent = "Copy";
}
async download(e: MouseEvent) {
e.preventDefault();
const textarea = this.element.querySelector("textarea");
if (!textarea) {
throw new Error("Couldn't find the textarea");
}
download(
textarea.value,
String(Date.now()) + ".json",
"application/json"
);
}
async import(e: MouseEvent) {
e.preventDefault();
const file_input = this.element.querySelector(
"input[type='file']"
) as HTMLInputElement;
const file = file_input.files?.[0];
if (file) {
const text = await file.text();
const textarea = this.element.querySelector("textarea");
textarea!.innerHTML = text.replaceAll("<", "&lt;");
textarea!.dispatchEvent(new Event("change"));
}
}
}
function sleep(n: number) {
return new Promise((resolve) => setTimeout(resolve, n));
}

File Metadata

Mime Type
text/x-java
Expires
Tue, Jul 8, 07:46 (14 h, 55 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
800008
Default Alt Text
exportable-textarea.stimulus.ts (2 KB)

Event Timeline