import { filter, fromEvent, Observable, takeUntil } from 'rxjs';

export const takeUntilKeydown =
  <T>(key: string) =>
  (source: Observable<T>): Observable<T> => {
    const keydownEvent$ = fromEvent<KeyboardEvent>(document, 'keydown').pipe(
      // Filter for the specific key
      filter((event) => event.key === key),
    );

    return source.pipe(takeUntil(keydownEvent$));
  };

export const takeUntilKeydownEscape = <T>() => takeUntilKeydown<T>('Escape');
