feat: implement modal service and components for enhanced user interaction, including modal showcase in demo page
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
@if (activeModal(); as modal) {
|
||||
<app-modal-shell
|
||||
[title]="modal.config.title"
|
||||
[size]="modal.config.size"
|
||||
[showCloseButton]="modal.config.showCloseButton"
|
||||
(backdropClick)="onBackdropClick()"
|
||||
(closeRequested)="onCloseRequested()"
|
||||
>
|
||||
<ng-container *ngComponentOutlet="modal.component; injector: contentInjector()" />
|
||||
</app-modal-shell>
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import '@angular/compiler';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { DOCUMENT } from '@angular/common';
|
||||
import { TestBed, getTestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import {
|
||||
BrowserTestingModule,
|
||||
platformBrowserTesting
|
||||
} from '@angular/platform-browser/testing';
|
||||
import {
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi
|
||||
} from 'vitest';
|
||||
|
||||
import {
|
||||
MODAL_DATA,
|
||||
ModalRef,
|
||||
ModalService
|
||||
} from '../../../core/services/modal.service';
|
||||
import { ModalHostComponent } from './modal-host.component';
|
||||
|
||||
@Component({
|
||||
standalone: true,
|
||||
template: `
|
||||
<div class="modal-test-content">
|
||||
<span class="modal-test-title">{{ data?.title }}</span>
|
||||
<button type="button" class="modal-test-close" (click)="close()">Cerrar</button>
|
||||
</div>
|
||||
`
|
||||
})
|
||||
class ModalContentTestComponent {
|
||||
readonly data = inject<{ title: string } | null>(MODAL_DATA);
|
||||
readonly modalRef = inject<ModalRef<string>>(ModalRef);
|
||||
|
||||
close(): void {
|
||||
this.modalRef.close('accepted');
|
||||
}
|
||||
}
|
||||
|
||||
describe('ModalHostComponent', () => {
|
||||
let service: ModalService;
|
||||
let doc: Document;
|
||||
|
||||
beforeAll(() => {
|
||||
try {
|
||||
getTestBed().initTestEnvironment(
|
||||
BrowserTestingModule,
|
||||
platformBrowserTesting()
|
||||
);
|
||||
} catch {
|
||||
// Test environment may already be initialized by another setup entrypoint.
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ModalHostComponent]
|
||||
}).compileComponents();
|
||||
|
||||
service = TestBed.inject(ModalService);
|
||||
doc = TestBed.inject(DOCUMENT);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
doc.body.style.overflow = '';
|
||||
TestBed.resetTestingModule();
|
||||
});
|
||||
|
||||
it('renders nothing when no modal is active', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.nativeElement.textContent?.trim()).toBe('');
|
||||
expect(doc.body.style.overflow).toBe('');
|
||||
});
|
||||
|
||||
it('opens and renders the requested component with its title and data', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
|
||||
service.open(ModalContentTestComponent, {
|
||||
title: 'Editar producto',
|
||||
data: { title: 'Contenido del modal' }
|
||||
});
|
||||
fixture.detectChanges();
|
||||
|
||||
const title = fixture.nativeElement.querySelector('.modal-shell__title');
|
||||
const content = fixture.nativeElement.querySelector('.modal-test-title');
|
||||
|
||||
expect(title?.textContent).toContain('Editar producto');
|
||||
expect(content?.textContent).toContain('Contenido del modal');
|
||||
expect(doc.body.style.overflow).toBe('hidden');
|
||||
});
|
||||
|
||||
it('closes with a result from the child component', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'Cerrar' }
|
||||
});
|
||||
const closedSpy = vi.fn();
|
||||
|
||||
ref.afterClosed$.subscribe(closedSpy);
|
||||
fixture.detectChanges();
|
||||
|
||||
const closeButton = fixture.nativeElement.querySelector('.modal-test-close') as HTMLButtonElement;
|
||||
closeButton.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(closedSpy).toHaveBeenCalledWith('accepted');
|
||||
expect(service.activeModal()).toBeNull();
|
||||
expect(doc.body.style.overflow).toBe('');
|
||||
});
|
||||
|
||||
it('closes on backdrop click when enabled', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'Backdrop' },
|
||||
closeOnBackdrop: true
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
|
||||
const backdrop = fixture.nativeElement.querySelector('.modal-shell') as HTMLDivElement;
|
||||
backdrop.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(service.activeModal()).toBeNull();
|
||||
expect(ref.dismissReason()).toBe('backdrop');
|
||||
});
|
||||
|
||||
it('does not close on backdrop click when disabled', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'Persistente' },
|
||||
closeOnBackdrop: false
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
|
||||
const backdrop = fixture.nativeElement.querySelector('.modal-shell') as HTMLDivElement;
|
||||
backdrop.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(service.activeModal()?.ref).toBe(ref);
|
||||
});
|
||||
|
||||
it('closes on Escape when enabled', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'Escape' },
|
||||
closeOnEscape: true
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
doc.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(service.activeModal()).toBeNull();
|
||||
expect(ref.dismissReason()).toBe('escape');
|
||||
});
|
||||
|
||||
it('keeps the modal open on Escape when disabled', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
data: { title: 'No Escape' },
|
||||
closeOnEscape: false
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
doc.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(service.activeModal()?.ref).toBe(ref);
|
||||
});
|
||||
|
||||
it('closes from the shell close button with a programmatic dismiss reason', () => {
|
||||
const fixture = TestBed.createComponent(ModalHostComponent);
|
||||
const ref = service.open(ModalContentTestComponent, {
|
||||
title: 'Con cierre',
|
||||
data: { title: 'Boton' }
|
||||
});
|
||||
|
||||
fixture.detectChanges();
|
||||
|
||||
const closeButton = fixture.debugElement.query(By.css('.btn-close')).nativeElement as HTMLButtonElement;
|
||||
closeButton.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(service.activeModal()).toBeNull();
|
||||
expect(ref.dismissReason()).toBe('programmatic');
|
||||
});
|
||||
});
|
||||
93
src/app/shared/components/modal-host/modal-host.component.ts
Normal file
93
src/app/shared/components/modal-host/modal-host.component.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { DOCUMENT, NgComponentOutlet, isPlatformBrowser } from '@angular/common';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
Injector,
|
||||
PLATFORM_ID,
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
viewChild
|
||||
} from '@angular/core';
|
||||
|
||||
import {
|
||||
MODAL_DATA,
|
||||
ModalRef,
|
||||
ModalService
|
||||
} from '../../../core/services/modal.service';
|
||||
import { ModalShellComponent } from '../modal-shell/modal-shell.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-modal-host',
|
||||
imports: [NgComponentOutlet, ModalShellComponent],
|
||||
templateUrl: './modal-host.component.html',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class ModalHostComponent {
|
||||
private readonly modalService = inject(ModalService);
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly document = inject(DOCUMENT);
|
||||
private readonly platformId = inject(PLATFORM_ID);
|
||||
private readonly modalShell = viewChild(ModalShellComponent);
|
||||
private readonly isBrowser = isPlatformBrowser(this.platformId);
|
||||
|
||||
readonly activeModal = this.modalService.activeModal;
|
||||
protected readonly contentInjector = computed<Injector | undefined>(() => {
|
||||
const modal = this.activeModal();
|
||||
|
||||
if (!modal) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return Injector.create({
|
||||
providers: [
|
||||
{ provide: ModalRef, useValue: modal.ref },
|
||||
{ provide: MODAL_DATA, useValue: modal.config.data ?? null }
|
||||
],
|
||||
parent: this.injector
|
||||
});
|
||||
});
|
||||
|
||||
constructor() {
|
||||
effect((onCleanup) => {
|
||||
const modal = this.activeModal();
|
||||
|
||||
if (!this.isBrowser || !modal) {
|
||||
return;
|
||||
}
|
||||
|
||||
const body = this.document.body;
|
||||
const previousOverflow = body.style.overflow;
|
||||
body.style.overflow = 'hidden';
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape' || !this.activeModal()?.config.closeOnEscape) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
this.activeModal()?.ref.dismiss('escape');
|
||||
};
|
||||
|
||||
this.document.addEventListener('keydown', onKeyDown);
|
||||
queueMicrotask(() => this.modalShell()?.focusInitialElement());
|
||||
|
||||
onCleanup(() => {
|
||||
this.document.removeEventListener('keydown', onKeyDown);
|
||||
body.style.overflow = previousOverflow;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected onBackdropClick(): void {
|
||||
const modal = this.activeModal();
|
||||
|
||||
if (modal?.config.closeOnBackdrop) {
|
||||
modal.ref.dismiss('backdrop');
|
||||
}
|
||||
}
|
||||
|
||||
protected onCloseRequested(): void {
|
||||
this.activeModal()?.ref.dismiss('programmatic');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<div class="modal-shell" (click)="backdropClick.emit()">
|
||||
<div
|
||||
class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-shell__dialog"
|
||||
[ngClass]="dialogClass()"
|
||||
(click)="$event.stopPropagation()"
|
||||
>
|
||||
<div
|
||||
#panel
|
||||
class="modal-content border-0 shadow-lg modal-shell__content"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
[attr.aria-labelledby]="ariaLabelledBy"
|
||||
tabindex="-1"
|
||||
>
|
||||
@if (title() || showCloseButton()) {
|
||||
<header class="modal-header border-0 modal-shell__header">
|
||||
@if (title()) {
|
||||
<h2 class="modal-title modal-shell__title" [id]="titleId">{{ title() }}</h2>
|
||||
} @else {
|
||||
<span></span>
|
||||
}
|
||||
|
||||
@if (showCloseButton()) {
|
||||
<button
|
||||
type="button"
|
||||
class="btn-close"
|
||||
aria-label="Cerrar modal"
|
||||
(click)="closeRequested.emit()"
|
||||
></button>
|
||||
}
|
||||
</header>
|
||||
}
|
||||
|
||||
<div class="modal-body modal-shell__body">
|
||||
<ng-content />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,87 @@
|
||||
:host {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
.modal-shell {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
background: rgba(16, 18, 22, 0.48);
|
||||
backdrop-filter: blur(2px);
|
||||
}
|
||||
|
||||
.modal-shell__dialog {
|
||||
width: min(100%, 40rem);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.modal-shell__dialog.modal-sm {
|
||||
width: min(100%, 24rem);
|
||||
}
|
||||
|
||||
.modal-shell__dialog.modal-lg {
|
||||
width: min(100%, 52rem);
|
||||
}
|
||||
|
||||
.modal-shell__dialog.modal-xl {
|
||||
width: min(100%, 68rem);
|
||||
}
|
||||
|
||||
.modal-shell__dialog--full {
|
||||
width: min(100%, 92rem);
|
||||
height: min(100%, calc(100dvh - 2rem));
|
||||
}
|
||||
|
||||
.modal-shell__content {
|
||||
max-height: calc(100dvh - 2rem);
|
||||
border-radius: 1.25rem;
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(248, 248, 248, 0.98));
|
||||
}
|
||||
|
||||
.modal-shell__dialog--full .modal-shell__content {
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.modal-shell__header {
|
||||
align-items: flex-start;
|
||||
padding: 1.25rem 1.25rem 0.75rem;
|
||||
}
|
||||
|
||||
.modal-shell__title {
|
||||
margin: 0;
|
||||
font-size: clamp(1.15rem, 1rem + 0.4vw, 1.5rem);
|
||||
font-weight: 700;
|
||||
line-height: 1.15;
|
||||
color: #202020;
|
||||
}
|
||||
|
||||
.modal-shell__body {
|
||||
padding: 0 1.25rem 1.25rem;
|
||||
color: #303030;
|
||||
}
|
||||
|
||||
@media (max-width: 576px) {
|
||||
.modal-shell {
|
||||
padding: 0.75rem;
|
||||
align-items: flex-end;
|
||||
}
|
||||
|
||||
.modal-shell__dialog,
|
||||
.modal-shell__dialog.modal-sm,
|
||||
.modal-shell__dialog.modal-lg,
|
||||
.modal-shell__dialog.modal-xl,
|
||||
.modal-shell__dialog--full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.modal-shell__content {
|
||||
max-height: min(100dvh - 1.5rem, 48rem);
|
||||
border-radius: 1.25rem 1.25rem 0.75rem 0.75rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { NgClass } from '@angular/common';
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
ElementRef,
|
||||
computed,
|
||||
input,
|
||||
output,
|
||||
viewChild
|
||||
} from '@angular/core';
|
||||
|
||||
import { ModalSize } from '../../../core/services/modal.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-modal-shell',
|
||||
imports: [NgClass],
|
||||
templateUrl: './modal-shell.component.html',
|
||||
styleUrl: './modal-shell.component.scss',
|
||||
changeDetection: ChangeDetectionStrategy.OnPush
|
||||
})
|
||||
export class ModalShellComponent {
|
||||
private readonly panel = viewChild.required<ElementRef<HTMLElement>>('panel');
|
||||
|
||||
readonly title = input<string | undefined>();
|
||||
readonly size = input<ModalSize>('md');
|
||||
readonly showCloseButton = input(true);
|
||||
|
||||
readonly backdropClick = output<void>();
|
||||
readonly closeRequested = output<void>();
|
||||
|
||||
protected readonly dialogClass = computed(() => {
|
||||
const size = this.size();
|
||||
|
||||
return {
|
||||
'modal-sm': size === 'sm',
|
||||
'modal-lg': size === 'lg',
|
||||
'modal-xl': size === 'xl',
|
||||
'modal-shell__dialog--full': size === 'full'
|
||||
};
|
||||
});
|
||||
|
||||
protected readonly titleId = `modal-title-${Math.random().toString(36).slice(2, 9)}`;
|
||||
|
||||
protected get ariaLabelledBy(): string | null {
|
||||
return this.title() ? this.titleId : null;
|
||||
}
|
||||
|
||||
focusInitialElement(): void {
|
||||
const panel = this.panel().nativeElement;
|
||||
const focusTarget = panel.querySelector<HTMLElement>(
|
||||
[
|
||||
'[autofocus]',
|
||||
'button:not([disabled])',
|
||||
'[href]',
|
||||
'input:not([disabled])',
|
||||
'select:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])'
|
||||
].join(', ')
|
||||
);
|
||||
|
||||
(focusTarget ?? panel).focus();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user