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

47 lines
1.2 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>;
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
}
}