forked from angular/components
/
dialog.ts
420 lines (362 loc) · 15.3 KB
/
dialog.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directionality} from '@angular/cdk/bidi';
import {
Overlay,
OverlayConfig,
OverlayContainer,
OverlayRef,
ScrollStrategy,
} from '@angular/cdk/overlay';
import {ComponentPortal, ComponentType, TemplatePortal} from '@angular/cdk/portal';
import {Location} from '@angular/common';
import {
Directive,
Inject,
Injectable,
InjectFlags,
InjectionToken,
Injector,
OnDestroy,
Optional,
SkipSelf,
StaticProvider,
TemplateRef,
Type,
} from '@angular/core';
import {defer, Observable, of as observableOf, Subject} from 'rxjs';
import {startWith} from 'rxjs/operators';
import {MatDialogConfig} from './dialog-config';
import {MatDialogContainer, _MatDialogContainerBase} from './dialog-container';
import {MatDialogRef} from './dialog-ref';
/** Injection token that can be used to access the data that was passed in to a dialog. */
export const MAT_DIALOG_DATA = new InjectionToken<any>('MatDialogData');
/** Injection token that can be used to specify default dialog options. */
export const MAT_DIALOG_DEFAULT_OPTIONS =
new InjectionToken<MatDialogConfig>('mat-dialog-default-options');
/** Injection token that determines the scroll handling while the dialog is open. */
export const MAT_DIALOG_SCROLL_STRATEGY =
new InjectionToken<() => ScrollStrategy>('mat-dialog-scroll-strategy');
/** @docs-private */
export function MAT_DIALOG_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.block();
}
/** @docs-private */
export function MAT_DIALOG_SCROLL_STRATEGY_PROVIDER_FACTORY(overlay: Overlay):
() => ScrollStrategy {
return () => overlay.scrollStrategies.block();
}
/** @docs-private */
export const MAT_DIALOG_SCROLL_STRATEGY_PROVIDER = {
provide: MAT_DIALOG_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_DIALOG_SCROLL_STRATEGY_PROVIDER_FACTORY,
};
/**
* Base class for dialog services. The base dialog service allows
* for arbitrary dialog refs and dialog container components.
*/
@Directive()
export abstract class _MatDialogBase<C extends _MatDialogContainerBase> implements OnDestroy {
private _openDialogsAtThisLevel: MatDialogRef<any>[] = [];
private readonly _afterAllClosedAtThisLevel = new Subject<void>();
private readonly _afterOpenedAtThisLevel = new Subject<MatDialogRef<any>>();
private _ariaHiddenElements = new Map<Element, string|null>();
private _scrollStrategy: () => ScrollStrategy;
/** Keeps track of the currently-open dialogs. */
get openDialogs(): MatDialogRef<any>[] {
return this._parentDialog ? this._parentDialog.openDialogs : this._openDialogsAtThisLevel;
}
/** Stream that emits when a dialog has been opened. */
get afterOpened(): Subject<MatDialogRef<any>> {
return this._parentDialog ? this._parentDialog.afterOpened : this._afterOpenedAtThisLevel;
}
_getAfterAllClosed(): Subject<void> {
const parent = this._parentDialog;
return parent ? parent._getAfterAllClosed() : this._afterAllClosedAtThisLevel;
}
// TODO (jelbourn): tighten the typing right-hand side of this expression.
/**
* Stream that emits when all open dialog have finished closing.
* Will emit on subscribe if there are no open dialogs to begin with.
*/
readonly afterAllClosed: Observable<void> = defer(() => this.openDialogs.length ?
this._getAfterAllClosed() :
this._getAfterAllClosed().pipe(startWith(undefined))) as Observable<any>;
constructor(
private _overlay: Overlay,
private _injector: Injector,
private _defaultOptions: MatDialogConfig|undefined,
private _parentDialog: _MatDialogBase<C>|undefined,
private _overlayContainer: OverlayContainer,
scrollStrategy: any,
private _dialogRefConstructor: Type<MatDialogRef<any>>,
private _dialogContainerType: Type<C>,
private _dialogDataToken: InjectionToken<any>) {
this._scrollStrategy = scrollStrategy;
}
/**
* Opens a modal dialog containing the given component.
* @param component Type of the component to load into the dialog.
* @param config Extra configuration options.
* @returns Reference to the newly-opened dialog.
*/
open<T, D = any, R = any>(component: ComponentType<T>,
config?: MatDialogConfig<D>): MatDialogRef<T, R>;
/**
* Opens a modal dialog containing the given template.
* @param template TemplateRef to instantiate as the dialog content.
* @param config Extra configuration options.
* @returns Reference to the newly-opened dialog.
*/
open<T, D = any, R = any>(template: TemplateRef<T>,
config?: MatDialogConfig<D>): MatDialogRef<T, R>;
open<T, D = any, R = any>(template: ComponentType<T> | TemplateRef<T>,
config?: MatDialogConfig<D>): MatDialogRef<T, R>;
open<T, D = any, R = any>(componentOrTemplateRef: ComponentType<T> | TemplateRef<T>,
config?: MatDialogConfig<D>): MatDialogRef<T, R> {
config = _applyConfigDefaults(config, this._defaultOptions || new MatDialogConfig());
if (config.id && this.getDialogById(config.id) &&
(typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error(`Dialog with id "${config.id}" exists already. The dialog id must be unique.`);
}
const overlayRef = this._createOverlay(config);
const dialogContainer = this._attachDialogContainer(overlayRef, config);
const dialogRef = this._attachDialogContent<T, R>(componentOrTemplateRef,
dialogContainer,
overlayRef,
config);
// If this is the first dialog that we're opening, hide all the non-overlay content.
if (!this.openDialogs.length) {
this._hideNonDialogContentFromAssistiveTechnology();
}
this.openDialogs.push(dialogRef);
dialogRef.afterClosed().subscribe(() => this._removeOpenDialog(dialogRef));
this.afterOpened.next(dialogRef);
// Notify the dialog container that the content has been attached.
dialogContainer._initializeWithAttachedContent();
return dialogRef;
}
/**
* Closes all of the currently-open dialogs.
*/
closeAll(): void {
this._closeDialogs(this.openDialogs);
}
/**
* Finds an open dialog by its id.
* @param id ID to use when looking up the dialog.
*/
getDialogById(id: string): MatDialogRef<any> | undefined {
return this.openDialogs.find(dialog => dialog.id === id);
}
ngOnDestroy() {
// Only close the dialogs at this level on destroy
// since the parent service may still be active.
this._closeDialogs(this._openDialogsAtThisLevel);
this._afterAllClosedAtThisLevel.complete();
this._afterOpenedAtThisLevel.complete();
}
/**
* Creates the overlay into which the dialog will be loaded.
* @param config The dialog configuration.
* @returns A promise resolving to the OverlayRef for the created overlay.
*/
private _createOverlay(config: MatDialogConfig): OverlayRef {
const overlayConfig = this._getOverlayConfig(config);
return this._overlay.create(overlayConfig);
}
/**
* Creates an overlay config from a dialog config.
* @param dialogConfig The dialog configuration.
* @returns The overlay configuration.
*/
private _getOverlayConfig(dialogConfig: MatDialogConfig): OverlayConfig {
const state = new OverlayConfig({
positionStrategy: this._overlay.position().global(),
scrollStrategy: dialogConfig.scrollStrategy || this._scrollStrategy(),
panelClass: dialogConfig.panelClass,
hasBackdrop: dialogConfig.hasBackdrop,
direction: dialogConfig.direction,
minWidth: dialogConfig.minWidth,
minHeight: dialogConfig.minHeight,
maxWidth: dialogConfig.maxWidth,
maxHeight: dialogConfig.maxHeight,
disposeOnNavigation: dialogConfig.closeOnNavigation
});
if (dialogConfig.backdropClass) {
state.backdropClass = dialogConfig.backdropClass;
}
return state;
}
/**
* Attaches a dialog container to a dialog's already-created overlay.
* @param overlay Reference to the dialog's underlying overlay.
* @param config The dialog configuration.
* @returns A promise resolving to a ComponentRef for the attached container.
*/
private _attachDialogContainer(overlay: OverlayRef, config: MatDialogConfig): C {
const userInjector = config && config.viewContainerRef && config.viewContainerRef.injector;
const injector = Injector.create({
parent: userInjector || this._injector,
providers: [{provide: MatDialogConfig, useValue: config}]
});
const containerPortal = new ComponentPortal(this._dialogContainerType,
config.viewContainerRef, injector, config.componentFactoryResolver);
const containerRef = overlay.attach<C>(containerPortal);
return containerRef.instance;
}
/**
* Attaches the user-provided component to the already-created dialog container.
* @param componentOrTemplateRef The type of component being loaded into the dialog,
* or a TemplateRef to instantiate as the content.
* @param dialogContainer Reference to the wrapping dialog container.
* @param overlayRef Reference to the overlay in which the dialog resides.
* @param config The dialog configuration.
* @returns A promise resolving to the MatDialogRef that should be returned to the user.
*/
private _attachDialogContent<T, R>(
componentOrTemplateRef: ComponentType<T> | TemplateRef<T>,
dialogContainer: C,
overlayRef: OverlayRef,
config: MatDialogConfig): MatDialogRef<T, R> {
// Create a reference to the dialog we're creating in order to give the user a handle
// to modify and close it.
const dialogRef = new this._dialogRefConstructor(overlayRef, dialogContainer, config.id);
if (componentOrTemplateRef instanceof TemplateRef) {
dialogContainer.attachTemplatePortal(
new TemplatePortal<T>(componentOrTemplateRef, null!,
<any>{$implicit: config.data, dialogRef}));
} else {
const injector = this._createInjector<T>(config, dialogRef, dialogContainer);
const contentRef = dialogContainer.attachComponentPortal<T>(
new ComponentPortal(componentOrTemplateRef, config.viewContainerRef, injector));
dialogRef.componentInstance = contentRef.instance;
}
dialogRef
.updateSize(config.width, config.height)
.updatePosition(config.position);
return dialogRef;
}
/**
* Creates a custom injector to be used inside the dialog. This allows a component loaded inside
* of a dialog to close itself and, optionally, to return a value.
* @param config Config object that is used to construct the dialog.
* @param dialogRef Reference to the dialog.
* @param dialogContainer Dialog container element that wraps all of the contents.
* @returns The custom injector that can be used inside the dialog.
*/
private _createInjector<T>(
config: MatDialogConfig,
dialogRef: MatDialogRef<T>,
dialogContainer: C): Injector {
const userInjector = config && config.viewContainerRef && config.viewContainerRef.injector;
// The dialog container should be provided as the dialog container and the dialog's
// content are created out of the same `ViewContainerRef` and as such, are siblings
// for injector purposes. To allow the hierarchy that is expected, the dialog
// container is explicitly provided in the injector.
const providers: StaticProvider[] = [
{provide: this._dialogContainerType, useValue: dialogContainer},
{provide: this._dialogDataToken, useValue: config.data},
{provide: this._dialogRefConstructor, useValue: dialogRef}
];
if (config.direction && (!userInjector ||
!userInjector.get<Directionality | null>(Directionality, null, InjectFlags.Optional))) {
providers.push({
provide: Directionality,
useValue: {value: config.direction, change: observableOf()}
});
}
return Injector.create({parent: userInjector || this._injector, providers});
}
/**
* Removes a dialog from the array of open dialogs.
* @param dialogRef Dialog to be removed.
*/
private _removeOpenDialog(dialogRef: MatDialogRef<any>) {
const index = this.openDialogs.indexOf(dialogRef);
if (index > -1) {
this.openDialogs.splice(index, 1);
// If all the dialogs were closed, remove/restore the `aria-hidden`
// to a the siblings and emit to the `afterAllClosed` stream.
if (!this.openDialogs.length) {
this._ariaHiddenElements.forEach((previousValue, element) => {
if (previousValue) {
element.setAttribute('aria-hidden', previousValue);
} else {
element.removeAttribute('aria-hidden');
}
});
this._ariaHiddenElements.clear();
this._getAfterAllClosed().next();
}
}
}
/**
* Hides all of the content that isn't an overlay from assistive technology.
*/
private _hideNonDialogContentFromAssistiveTechnology() {
const overlayContainer = this._overlayContainer.getContainerElement();
// Ensure that the overlay container is attached to the DOM.
if (overlayContainer.parentElement) {
const siblings = overlayContainer.parentElement.children;
for (let i = siblings.length - 1; i > -1; i--) {
let sibling = siblings[i];
if (sibling !== overlayContainer &&
sibling.nodeName !== 'SCRIPT' &&
sibling.nodeName !== 'STYLE' &&
!sibling.hasAttribute('aria-live')) {
this._ariaHiddenElements.set(sibling, sibling.getAttribute('aria-hidden'));
sibling.setAttribute('aria-hidden', 'true');
}
}
}
}
/** Closes all of the dialogs in an array. */
private _closeDialogs(dialogs: MatDialogRef<any>[]) {
let i = dialogs.length;
while (i--) {
// The `_openDialogs` property isn't updated after close until the rxjs subscription
// runs on the next microtask, in addition to modifying the array as we're going
// through it. We loop through all of them and call close without assuming that
// they'll be removed from the list instantaneously.
dialogs[i].close();
}
}
}
/**
* Service to open Material Design modal dialogs.
*/
@Injectable()
export class MatDialog extends _MatDialogBase<MatDialogContainer> {
constructor(
overlay: Overlay,
injector: Injector,
/**
* @deprecated `_location` parameter to be removed.
* @breaking-change 10.0.0
*/
@Optional() location: Location,
@Optional() @Inject(MAT_DIALOG_DEFAULT_OPTIONS) defaultOptions: MatDialogConfig,
@Inject(MAT_DIALOG_SCROLL_STRATEGY) scrollStrategy: any,
@Optional() @SkipSelf() parentDialog: MatDialog,
overlayContainer: OverlayContainer) {
super(overlay, injector, defaultOptions, parentDialog, overlayContainer, scrollStrategy,
MatDialogRef, MatDialogContainer, MAT_DIALOG_DATA);
}
}
/**
* Applies default options to the dialog config.
* @param config Config to be modified.
* @param defaultOptions Default options provided.
* @returns The new configuration object.
*/
function _applyConfigDefaults(
config?: MatDialogConfig, defaultOptions?: MatDialogConfig): MatDialogConfig {
return {...defaultOptions, ...config};
}