Skip to content

Instantly share code, notes, and snippets.

@AnteaterKit
Created January 23, 2021 04:41
Show Gist options
  • Save AnteaterKit/ddd89a627f754e3024f23e82f4714028 to your computer and use it in GitHub Desktop.
Save AnteaterKit/ddd89a627f754e3024f23e82f4714028 to your computer and use it in GitHub Desktop.
import { DOCUMENT } from '@angular/common';
import { Directive, ElementRef, Inject, Output } from '@angular/core';
import { fromEvent } from 'rxjs';
import { distinctUntilChanged, map, switchMap, takeUntil, tap } from 'rxjs/operators';
export interface ResizeData {
width: number;
height: number;
}
@Directive({
selector: '[resizable]'
})
export class ResizableDirective {
@Output()
readonly resizable = fromEvent<MouseEvent>(
this.elementRef.nativeElement,
'mousedown'
).pipe(
tap(e => e.preventDefault()),
switchMap(() => {
const { width, right, height, bottom } = this.elementRef.nativeElement
.closest('span')
.getBoundingClientRect();
return fromEvent<MouseEvent>(this.documentRef, 'mousemove').pipe(
map(
({ clientX, clientY }) => {
return { width: width + clientX - right, height: height + clientY - bottom };
}
),
distinctUntilChanged(),
takeUntil(fromEvent(this.documentRef, 'mouseup'))
);
})
);
constructor(
@Inject(DOCUMENT) private readonly documentRef: Document,
@Inject(ElementRef)
private readonly elementRef: ElementRef<HTMLElement>
) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment