demarches-normaliennes/app/javascript/controllers/clipboard_controller.ts

54 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-11-29 09:37:58 +01:00
import { Controller } from '@hotwired/stimulus';
const SUCCESS_MESSAGE_TIMEOUT = 1000;
export class ClipboardController extends Controller {
static values = { text: String };
static targets = ['success', 'toHide'];
2022-11-29 09:37:58 +01:00
declare readonly textValue: string;
declare readonly successTarget: HTMLElement;
declare readonly toHideTarget: HTMLElement;
2022-11-29 09:37:58 +01:00
declare readonly hasSuccessTarget: boolean;
declare readonly hasToHideTarget: boolean;
2022-11-29 09:37:58 +01:00
#timer?: ReturnType<typeof setTimeout>;
connect(): void {
// some extensions or browsers block clipboard
if (!navigator.clipboard) {
this.element.classList.add('hidden');
}
}
2022-11-29 09:37:58 +01:00
disconnect(): void {
clearTimeout(this.#timer);
}
copy() {
navigator.clipboard
.writeText(this.textValue)
.then(() => this.displayCopyConfirmation());
}
private displayCopyConfirmation() {
if (this.hasToHideTarget) {
this.toHideTarget.classList.add('hidden');
}
2022-11-29 09:37:58 +01:00
if (this.hasSuccessTarget) {
this.successTarget.classList.remove('hidden');
}
clearTimeout(this.#timer);
this.#timer = setTimeout(() => {
if (this.hasSuccessTarget) {
this.successTarget.classList.add('hidden');
}
if (this.hasToHideTarget) {
this.toHideTarget.classList.remove('hidden');
}
}, SUCCESS_MESSAGE_TIMEOUT);
2022-11-29 09:37:58 +01:00
}
}