Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): Dialog/Dropdown use CloseWatcher to close on Android native back button #10300

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
import {NgForOf, NgIf} from '@angular/common';
import type {AfterViewInit, ElementRef, QueryList} from '@angular/core';
import {ChangeDetectionStrategy, Component, inject, ViewChildren} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {EMPTY_QUERY} from '@taiga-ui/cdk/constants';
import {tuiCloseWatcher, tuiZonefull} from '@taiga-ui/cdk/observables';
import type {TuiPopover} from '@taiga-ui/cdk/services';
import {tuiInjectElement} from '@taiga-ui/cdk/utils/dom';
import {tuiSlideInTop} from '@taiga-ui/core/animations';
import {TUI_ANIMATIONS_SPEED} from '@taiga-ui/core/tokens';
import {tuiGetDuration} from '@taiga-ui/core/utils/miscellaneous';
import {shouldCall} from '@taiga-ui/event-plugins';
import {injectContext, PolymorpheusOutlet} from '@taiga-ui/polymorpheus';
import {exhaustMap, filter, isObservable, merge, of, Subject, take} from 'rxjs';

import type {TuiSheetDialogOptions} from './sheet-dialog.options';

// So we re-enter ngZone and trigger change detection
function isCloseable(this: TuiSheetDialogComponent<unknown>): boolean {
return this.context.closeable === true;
}

@Component({
standalone: true,
selector: 'tui-sheet-dialog',
Expand All @@ -28,12 +25,12 @@ function isCloseable(this: TuiSheetDialogComponent<unknown>): boolean {
host: {
'[@tuiSlideInTop]': 'slideInTop',
'[style.--tui-offset.px]': 'context.offset',
'[class._closeable]': 'context.closeable === true',
'[class._closeable]': 'context.closeable',
'(document:touchstart.passive.zoneless)': 'onPointerChange(1)',
'(document:touchend.zoneless)': 'onPointerChange(-1)',
'(document:touchcancel.zoneless)': 'onPointerChange(-1)',
'(scroll.zoneless)': 'onPointerChange(0)',
'(click.self)': 'close()',
'(click.self)': 'close$.next()',
},
})
export class TuiSheetDialogComponent<I> implements AfterViewInit {
Expand All @@ -54,24 +51,43 @@ export class TuiSheetDialogComponent<I> implements AfterViewInit {
protected readonly context =
injectContext<TuiPopover<TuiSheetDialogOptions<I>, any>>();

public ngAfterViewInit(): void {
this.el.scrollTop =
[
...this.stops.map((e) => e.nativeElement.offsetTop - this.context.offset),
this.el.clientHeight ?? Infinity,
][this.context.initial] ?? 0;
}
protected readonly close$ = new Subject<void>();
protected readonly $ = merge(this.close$, tuiCloseWatcher())
.pipe(
tuiZonefull(),
exhaustMap(() => {
if (isObservable(this.context.closeable)) {
if (this.el.scrollTop <= 0) {
this.el.scrollTo({top: this.initial, behavior: 'smooth'});
}

return this.context.closeable.pipe(take(1));
}

@shouldCall(isCloseable)
protected close(): void {
this.context.$implicit.complete();
return of(this.context.closeable);
}),
filter(Boolean),
takeUntilDestroyed(),
)
.subscribe(() => this.context.$implicit.complete());

public ngAfterViewInit(): void {
this.el.scrollTop = this.initial;
}

protected onPointerChange(delta: number): void {
this.pointers = Math.max(this.pointers + delta, 0);

if (!this.pointers && this.el.scrollTop <= 0) {
this.close();
this.close$.next();
}
}

private get initial(): number {
return (
this.stops
.map((e) => e.nativeElement.offsetTop - this.context.offset)
.concat(this.el.clientHeight ?? Infinity)[this.context.initial] ?? 0
);
}
}
31 changes: 31 additions & 0 deletions projects/cdk/observables/close-watcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import {Observable} from 'rxjs';

interface CloseWatcher {
destroy: () => void;
onclose?: (event: Event) => void;
oncancel?: (event: Event) => void;
}

export function tuiCloseWatcher(): Observable<void> {
return new Observable((subscriber) => {
let watcher = getWatcher();

const setup = () => {

Check failure on line 13 in projects/cdk/observables/close-watcher.ts

View workflow job for this annotation

GitHub Actions / Lint

Missing return type on function
watcher = getWatcher();
watcher.onclose = () => setup();
watcher.oncancel = (event) => {
event.preventDefault();
subscriber.next();
};
};

setup();

return () => watcher.destroy();
});
}

function getWatcher(): CloseWatcher {
// @ts-ignore
return typeof CloseWatcher === 'undefined' ? {destroy: () => {}} : new CloseWatcher();
}
1 change: 1 addition & 0 deletions projects/cdk/observables/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './close-watcher';
export * from './control-value';
export * from './drag-and-drop-from';
export * from './events';
Expand Down
14 changes: 11 additions & 3 deletions projects/core/components/dialog/dialog-close.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {DOCUMENT} from '@angular/common';
import {inject, Injectable} from '@angular/core';
import {WA_WINDOW} from '@ng-web-apis/common';
import {tuiTypedFromEvent} from '@taiga-ui/cdk/observables';
import {tuiCloseWatcher, tuiTypedFromEvent, tuiZonefull} from '@taiga-ui/cdk/observables';
import {
tuiContainsOrAfter,
tuiGetActualTarget,
Expand All @@ -24,7 +24,9 @@ export class TuiDialogCloseService extends Observable<unknown> {
const target = tuiGetActualTarget(event);

return (
event.key === 'Escape' &&
// @ts-ignore
typeof CloseWatcher === 'undefined' &&
event.key.toLowerCase() === 'escape' &&
!event.defaultPrevented &&
(this.el.contains(target) || this.isOutside(target))
);
Expand All @@ -47,7 +49,13 @@ export class TuiDialogCloseService extends Observable<unknown> {
);

constructor() {
super((subscriber) => merge(this.esc$, this.mousedown$).subscribe(subscriber));
super((subscriber) =>
merge(
this.esc$,
this.mousedown$,
tuiCloseWatcher().pipe(tuiZonefull()),
).subscribe(subscriber),
);
}

private isOutside(target: EventTarget): boolean {
Expand Down
14 changes: 12 additions & 2 deletions projects/core/components/dialog/dialog.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,17 @@ import {tuiGetDuration} from '@taiga-ui/core/utils';
import type {PolymorpheusContent} from '@taiga-ui/polymorpheus';
import {injectContext, PolymorpheusOutlet} from '@taiga-ui/polymorpheus';
import type {Observable} from 'rxjs';
import {filter, isObservable, map, merge, of, Subject, switchMap} from 'rxjs';
import {
exhaustMap,
filter,
isObservable,
map,
merge,
of,
Subject,
switchMap,
take,
} from 'rxjs';

import type {TuiDialogOptions, TuiDialogSize} from './dialog.interfaces';
import {TUI_DIALOGS_CLOSE} from './dialog.tokens';
Expand Down Expand Up @@ -84,7 +94,7 @@ export class TuiDialogComponent<O, I> {
merge(
this.close$.pipe(switchMap(() => toObservable(this.context.closeable))),
inject(TuiDialogCloseService).pipe(
switchMap(() => toObservable(this.context.dismissible)),
exhaustMap(() => toObservable(this.context.dismissible).pipe(take(1))),
),
inject(TUI_DIALOGS_CLOSE).pipe(map(TUI_TRUE_HANDLER)),
)
Expand Down
49 changes: 33 additions & 16 deletions projects/core/directives/dropdown/dropdown-open.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ import {
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {TuiActiveZone} from '@taiga-ui/cdk/directives/active-zone';
import {TuiObscured} from '@taiga-ui/cdk/directives/obscured';
import {tuiWatch} from '@taiga-ui/cdk/observables';
import {
tuiCloseWatcher,
tuiIfMap,
tuiWatch,
tuiZonefull,
} from '@taiga-ui/cdk/observables';
import {
tuiGetActualTarget,
tuiInjectElement,
Expand All @@ -28,14 +33,15 @@ import {
import {tuiAsDriver} from '@taiga-ui/core/classes';
import {tuiIsEditingKey} from '@taiga-ui/core/utils/miscellaneous';
import {shouldCall} from '@taiga-ui/event-plugins';
import {filter, fromEvent, map, merge} from 'rxjs';
import {filter, fromEvent, merge} from 'rxjs';

import {TuiDropdownDirective} from './dropdown.directive';
import {TuiDropdownDriver} from './dropdown.driver';

function shouldClose(this: TuiDropdownOpen, event: Event | KeyboardEvent): boolean {
function shouldClose(this: TuiDropdownOpen, event: KeyboardEvent): boolean {
return (
'key' in event &&
// @ts-ignore
typeof CloseWatcher === 'undefined' &&
event.key.toLowerCase() === 'escape' &&
this.tuiDropdownEnabled &&
!!this.tuiDropdownOpen &&
Expand Down Expand Up @@ -70,22 +76,12 @@ export class TuiDropdownOpen implements OnChanges {
private readonly directive = inject(TuiDropdownDirective);
private readonly el = tuiInjectElement();
private readonly obscured = inject(TuiObscured);
private readonly activeZone = inject(TuiActiveZone);

private readonly dropdown = computed(
() => this.directive.ref()?.location.nativeElement,
);

protected readonly sub = merge(
this.obscured.tuiObscured.pipe(filter(Boolean)),
inject(TuiActiveZone).tuiActiveZoneChange.pipe(filter((a) => !a)),
fromEvent(this.el, 'focusin').pipe(
map(tuiGetActualTarget),
filter((target) => !this.host.contains(target) || !this.directive.ref()),
),
)
.pipe(tuiWatch(), takeUntilDestroyed())
.subscribe(() => this.toggle(false));

@Input()
public tuiDropdownEnabled = true;

Expand All @@ -97,6 +93,27 @@ export class TuiDropdownOpen implements OnChanges {

// TODO: make it private when all legacy controls will be deleted from @taiga-ui/legacy (5.0)
public readonly driver = inject(TuiDropdownDriver);
public readonly sub = this.driver
.pipe(
tuiIfMap(() =>
merge(
tuiCloseWatcher(),
this.obscured.tuiObscured.pipe(filter(Boolean)),
this.activeZone.tuiActiveZoneChange.pipe(filter((a) => !a)),
fromEvent(this.el, 'focusin').pipe(
filter(
(event) =>
!this.host.contains(tuiGetActualTarget(event)) ||
!this.directive.ref(),
),
),
),
),
tuiZonefull(),
tuiWatch(),
takeUntilDestroyed(),
)
.subscribe(() => this.toggle(false));

public ngOnChanges(): void {
this.update(!!this.tuiDropdownOpen);
Expand All @@ -111,7 +128,7 @@ export class TuiDropdownOpen implements OnChanges {
}

@shouldCall(shouldClose)
protected onEsc(event: Event): void {
protected onEsc(event: KeyboardEvent): void {
event.preventDefault();
this.toggle(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {Component, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {changeDetection} from '@demo/emulate/change-detection';
import {encapsulation} from '@demo/emulate/encapsulation';
import {TuiResponsiveDialogService} from '@taiga-ui/addon-mobile';
import {TuiButton, TuiDialogService} from '@taiga-ui/core';
import {TuiConfirmService} from '@taiga-ui/kit';
import {TuiInputModule} from '@taiga-ui/legacy';
Expand All @@ -13,7 +14,13 @@ import type {PolymorpheusContent} from '@taiga-ui/polymorpheus';
templateUrl: './index.html',
encapsulation,
changeDetection,
providers: [TuiConfirmService],
providers: [
TuiConfirmService,
{
provide: TuiDialogService,
useExisting: TuiResponsiveDialogService,
},
],
})
export default class Example {
private readonly confirm = inject(TuiConfirmService);
Expand Down
Loading