|
| 1 | +import { |
| 2 | + Directive, |
| 3 | + HostListener, |
| 4 | + Input, |
| 5 | + booleanAttribute, |
| 6 | + Output, |
| 7 | + EventEmitter, |
| 8 | + AfterViewInit, |
| 9 | + inject, |
| 10 | + Renderer2, |
| 11 | +} from '@angular/core'; |
| 12 | + |
| 13 | +@Directive({ |
| 14 | + selector: '[collapse]', |
| 15 | + standalone: true, |
| 16 | +}) |
| 17 | +export class CollapseDirective implements AfterViewInit { |
| 18 | + @Input({ required: true }) collapse!: HTMLElement; |
| 19 | + @Input({ transform: booleanAttribute }) collapsed = false; |
| 20 | + @Input() animationSpeed = 300; |
| 21 | + @Output() collapsedChange = new EventEmitter<boolean>(); |
| 22 | + |
| 23 | + private collapseAnimation: Animation | null = null; |
| 24 | + private clientHeight = 0; |
| 25 | + private readonly renderer: Renderer2 = inject(Renderer2); |
| 26 | + |
| 27 | + ngAfterViewInit(): void { |
| 28 | + this.setInitialState(); |
| 29 | + } |
| 30 | + |
| 31 | + @HostListener('click') |
| 32 | + onClick(): void { |
| 33 | + this.collapsed = !this.collapsed; |
| 34 | + this.collapsedChange.emit(this.collapsed); |
| 35 | + this.updateState(); |
| 36 | + } |
| 37 | + |
| 38 | + updateState(): void { |
| 39 | + if (this.collapseAnimation) { |
| 40 | + this.collapseAnimation.cancel(); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + if (this.collapsed) { |
| 45 | + this.clientHeight = this.collapse.clientHeight; |
| 46 | + this.collapseElement(); |
| 47 | + } else { |
| 48 | + this.expandElement(); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private setInitialState(): void { |
| 53 | + if (this.collapsed) { |
| 54 | + this.clientHeight = this.collapse.clientHeight; |
| 55 | + this.renderer.addClass(this.collapse, 'collapsed') |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + private collapseElement(): void { |
| 60 | + this.collapse.classList.add('transforming'); |
| 61 | + this.collapseAnimation = this.collapse.animate( |
| 62 | + { height: [`${this.clientHeight}px`, '0px'] }, |
| 63 | + { duration: this.animationSpeed, easing: 'ease-in-out' }, |
| 64 | + ); |
| 65 | + this.collapseAnimation.finished |
| 66 | + .then(() => { |
| 67 | + this.renderer.addClass(this.collapse, 'collapsed') |
| 68 | + }) |
| 69 | + .finally(() => { |
| 70 | + this.renderer.removeClass(this.collapse, 'transforming'); |
| 71 | + this.collapseAnimation = null; |
| 72 | + }); |
| 73 | + } |
| 74 | + |
| 75 | + private expandElement(): void { |
| 76 | + this.collapseAnimation = this.collapse.animate( |
| 77 | + { height: ['0px', `${this.clientHeight}px`] }, |
| 78 | + { duration: this.animationSpeed, easing: 'ease-in-out' }, |
| 79 | + ); |
| 80 | + this.collapseAnimation.finished |
| 81 | + .then(() => { |
| 82 | + this.renderer.removeClass(this.collapse, 'collapsed'); |
| 83 | + }) |
| 84 | + .finally(() => { |
| 85 | + this.collapseAnimation = null; |
| 86 | + }); |
| 87 | + } |
| 88 | +} |
0 commit comments