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

34 lines
996 B
TypeScript
Raw Normal View History

2024-03-07 12:06:00 +01:00
import { ApplicationController } from './application_controller';
import { attach } from '@frsource/autoresize-textarea';
import { isTextAreaElement } from '@coldwired/utils';
export class AutoresizeController extends ApplicationController {
declare observer: IntersectionObserver;
2024-03-07 12:06:00 +01:00
#detach?: () => void;
connect(): void {
if (isTextAreaElement(this.element)) {
this.element.classList.add('resize-none');
this.observer = new IntersectionObserver(this.onIntersect.bind(this), {
threshold: [0]
});
this.observer.observe(this.element);
}
}
onIntersect(entries: IntersectionObserverEntry[]): void {
const visible = entries[0].isIntersecting == true;
if (visible) {
this.#detach = attach(this.element as HTMLTextAreaElement)?.detach;
this.observer.unobserve(this.element);
2024-03-07 12:06:00 +01:00
}
}
disconnect(): void {
this.#detach?.();
this.observer.unobserve(this.element);
2024-03-07 12:06:00 +01:00
this.element.classList.remove('resize-none');
}
}