ngx-modialog
Version:
Modal / Dialog for Angular
1,658 lines (1,635 loc) • 54.4 kB
JavaScript
import { ComponentFactoryResolver, Directive, Input, ElementRef, ViewContainerRef, Component, ViewEncapsulation, Renderer2, ViewChild, TemplateRef, Injectable, Injector, ApplicationRef, ANALYZE_FOR_ENTRY_COMPONENTS, NgModule } from '@angular/core';
import { Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { CommonModule } from '@angular/common';
import { EVENT_MANAGER_PLUGINS } from '@angular/platform-browser';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
const /** @type {?} */ PRIVATE_PREFIX = '$$';
const /** @type {?} */ RESERVED_REGEX = /^(\$\$).*/;
/**
* @param {?} name
* @return {?}
*/
function validateMethodName(name) {
if (!name) {
throw new Error(`Illegal method name. Empty method name is not allowed`);
}
else if (name in this) {
throw new Error(`A member name '${name}' already defined.`);
}
}
/**
* Returns a list of assigned property names (non private)
* @param {?} subject
* @return {?}
*/
function getAssignedPropertyNames(subject) {
return Object.getOwnPropertyNames(subject)
.filter(name => RESERVED_REGEX.test(name))
.map(name => name.substr(2));
}
/**
* @param {?} name
* @return {?}
*/
function privateKey(name) {
return PRIVATE_PREFIX + name;
}
/**
* @param {?} obj
* @param {?} propertyName
* @param {?} value
* @return {?}
*/
function objectDefinePropertyValue(obj, propertyName, value) {
Object.defineProperty(obj, propertyName, /** @type {?} */ ({
configurable: false,
enumerable: false,
writable: false,
value
}));
}
/**
* Given a FluentAssign instance, apply all of the supplied default values so calling
* instance.toJSON will return those values (does not create a setter function)
* @param {?} instance
* @param {?} defaultValues
* @return {?}
*/
function applyDefaultValues(instance, defaultValues) {
Object.getOwnPropertyNames(defaultValues)
.forEach(name => (/** @type {?} */ (instance))[privateKey(name)] = (/** @type {?} */ (defaultValues))[name]);
}
/**
* Create a function for setting a value for a property on a given object.
* @template T
* @param {?} obj The object to apply the key & setter on.
* @param {?} propertyName The name of the property on the object
* @param {?=} writeOnce If true will allow writing once (default: false)
*
* Example:
* let obj = new FluentAssign<any>;
* setAssignMethod(obj, 'myProp');
* obj.myProp('someValue');
* const result = obj.toJSON();
* console.log(result); //{ myProp: 'someValue' }
*
*
* let obj = new FluentAssign<any>;
* setAssignMethod(obj, 'myProp', true); // applying writeOnce
* obj.myProp('someValue');
* obj.myProp('someValue'); // ERROR: Overriding config property 'myProp' is not allowed.
* @return {?}
*/
function setAssignMethod(obj, propertyName, writeOnce = false) {
validateMethodName.call(obj, propertyName);
const /** @type {?} */ key = privateKey(propertyName);
objectDefinePropertyValue(obj, propertyName, (value) => {
if (writeOnce && this.hasOwnProperty(key)) {
throw new Error(`Overriding config property '${propertyName}' is not allowed.`);
}
obj[key] = value;
return obj;
});
}
/**
* Create a function for setting a value that is an alias to an other setter function.
* @template T
* @param {?} obj The object to apply the key & setter on.
* @param {?} propertyName The name of the property on the object
* @param {?} srcPropertyName The name of the property on the object this alias points to
* @param {?=} hard If true, will set a readonly property on the object that returns
* the value of the source property. Default: false
*
* Example:
* let obj = new FluentAssign<any> ;
* setAssignMethod(obj, 'myProp');
* setAssignAlias(obj, 'myPropAlias', 'myProp');
* obj.myPropAlias('someValue');
* const result = obj.toJSON();
* console.log(result); //{ myProp: 'someValue' }
* result.myPropAlias // undefined
*
*
* let obj = new FluentAssign<any> ;
* setAssignMethod(obj, 'myProp');
* setAssignAlias(obj, 'myPropAlias', 'myProp', true); // setting a hard alias.
* obj.myPropAlias('someValue');
* const result = obj.toJSON();
* console.log(result); //{ myProp: 'someValue' }
* result.myPropAlias // someValue
* @return {?}
*/
function setAssignAlias(obj, propertyName, srcPropertyName, hard = false) {
validateMethodName.call(obj, propertyName);
objectDefinePropertyValue(obj, propertyName, (value) => {
obj[srcPropertyName](value);
return obj;
});
if (hard === true) {
const /** @type {?} */ key = privateKey(propertyName), /** @type {?} */
srcKey = privateKey(srcPropertyName);
Object.defineProperty(obj, key, /** @type {?} */ ({
configurable: false,
enumerable: false,
get: () => obj[srcKey]
}));
}
}
/**
* Represent a fluent API factory wrapper for defining FluentAssign instances.
* @template T
*/
class FluentAssignFactory {
/**
* @param {?=} fluentAssign
*/
constructor(fluentAssign) {
this._fluentAssign =
fluentAssign instanceof FluentAssign ? fluentAssign : /** @type {?} */ (new FluentAssign());
}
/**
* Create a setter method on the FluentAssign instance.
* @param {?} name The name of the setter function.
* @param {?=} defaultValue If set (not undefined) set's the value on the instance immediately.
* @return {?}
*/
setMethod(name, defaultValue = undefined) {
setAssignMethod(this._fluentAssign, name);
if (defaultValue !== undefined) {
(/** @type {?} */ (this._fluentAssign))[name](defaultValue);
}
return this;
}
/**
* The FluentAssign instance.
* @return {?}
*/
get fluentAssign() {
return this._fluentAssign;
}
}
/**
* Represent an object where every property is a function representing an assignment function.
* Calling each function with a value will assign the value to the object and return the object.
* Calling 'toJSON' returns an object with the same properties but this time representing the
* assigned values.
*
* This allows setting an object in a fluent API manner.
* Example:
* let fluent = new FluentAssign<any>(undefined, ['some', 'went']);
* fluent.some('thing').went('wrong').toJSON();
* // { some: 'thing', went: 'wrong' }
* @template T
*/
class FluentAssign {
/**
*
* @param {?=} defaultValues An object representing default values for the underlying object.
* @param {?=} initialSetters A list of initial setters for this FluentAssign.
* @param {?=} baseType the class/type to create a new base. optional, {} is used if not supplied.
*/
constructor(defaultValues = undefined, initialSetters = undefined, baseType = undefined) {
if (Array.isArray(defaultValues)) {
(/** @type {?} */ (defaultValues)).forEach(d => applyDefaultValues(this, d));
}
else if (defaultValues) {
applyDefaultValues(this, defaultValues);
}
if (Array.isArray(initialSetters)) {
initialSetters.forEach(name => setAssignMethod(this, name));
}
if (baseType) {
this.__fluent$base__ = baseType;
}
}
/**
* Returns a FluentAssignFactory<FluentAssign<T>> ready to define a FluentAssign type.
* @template T
* @param {?=} defaultValues An object representing default values for the instance.
* @param {?=} initialSetters A list of initial setters for the instance.
* @return {?}
*/
static compose(defaultValues = undefined, initialSetters = undefined) {
return /** @type {?} */ (FluentAssign.composeWith(new FluentAssign(defaultValues, initialSetters)));
}
/**
* Returns a FluentAssignFactory<Z> where Z is an instance of FluentAssign<?> or a derived
* class of it.
* @template Z
* @param {?} fluentAssign An instance of FluentAssign<?> or a derived class of FluentAssign<?>.
* @return {?}
*/
static composeWith(fluentAssign) {
return /** @type {?} */ (new FluentAssignFactory(/** @type {?} */ (fluentAssign)));
}
/**
* @return {?}
*/
toJSON() {
return getAssignedPropertyNames(this)
.reduce((obj, name) => {
const /** @type {?} */ key = privateKey(name);
// re-define property descriptors (we dont want their value)
let /** @type {?} */ propDesc = Object.getOwnPropertyDescriptor(this, key);
if (propDesc) {
Object.defineProperty(obj, name, propDesc);
}
else {
(/** @type {?} */ (obj))[name] = (/** @type {?} */ (this))[key];
}
return obj;
}, this.__fluent$base__ ? new this.__fluent$base__() : /** @type {?} */ ({}));
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Simple object extend
* @template T
* @param {?} m1
* @param {?} m2
* @return {?}
*/
function extend(m1, m2) {
var /** @type {?} */ m = /** @type {?} */ ({});
for (var /** @type {?} */ attr in m1) {
if (m1.hasOwnProperty(attr)) {
(/** @type {?} */ (m))[attr] = (/** @type {?} */ (m1))[attr];
}
}
for (var /** @type {?} */ attr in m2) {
if (m2.hasOwnProperty(attr)) {
(/** @type {?} */ (m))[attr] = (/** @type {?} */ (m2))[attr];
}
}
return m;
}
/**
* Simple, not optimized, array union of unique values.
* @template T
* @param {?} arr1
* @param {?} arr2
* @return {?}
*/
function arrayUnion(arr1, arr2) {
return arr1
.concat(arr2.filter(v => arr1.indexOf(v) === -1));
}
/**
* Returns true if the config supports a given key.
* @param {?} keyCode
* @param {?} config
* @return {?}
*/
function supportsKey(keyCode, config) {
if (!Array.isArray(config))
return config === null ? false : true;
return config.indexOf(keyCode) > -1;
}
/**
* @template R
*/
class PromiseCompleter {
constructor() {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
}
/**
* @return {?}
*/
function noop() { }
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @param {?} instructions
* @return {?}
*/
function createComponent(instructions) {
const /** @type {?} */ injector = instructions.injector || instructions.vcRef.parentInjector;
const /** @type {?} */ cmpFactory = injector.get(ComponentFactoryResolver).resolveComponentFactory(instructions.component);
if (instructions.vcRef) {
return instructions.vcRef.createComponent(cmpFactory, instructions.vcRef.length, injector, instructions.projectableNodes);
}
else {
return cmpFactory.create(injector);
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
class DialogBailOutError extends Error {
/**
* @param {?=} value
*/
constructor(value) {
super();
if (!value) {
value = 'Dialog was forced to close by an unknown source.';
}
this.message = value;
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* API to an open modal window.
* @template T
*/
class DialogRef {
/**
* @param {?} overlay
* @param {?=} context
*/
constructor(overlay, context) {
this.overlay = overlay;
this.context = context;
this._resultDeferred = new PromiseCompleter();
this._onDestroy = new Subject();
this.onDestroy = this._onDestroy.asObservable();
}
/**
* A Promise that is resolved on a close event and rejected on a dismiss event.
* @return {?}
*/
get result() {
return this._resultDeferred.promise;
}
/**
* Set a close/dismiss guard
* @param {?} guard
* @return {?}
*/
setCloseGuard(guard) {
this.closeGuard = guard;
}
/**
* Close the modal with a return value, i.e: result.
* @param {?=} result
* @return {?}
*/
close(result = null) {
const /** @type {?} */ _close = () => {
this.destroy();
this._resultDeferred.resolve(result);
};
this._fireHook('beforeClose')
.then(value => value !== true && _close())
.catch(_close);
}
/**
* Close the modal without a return value, i.e: cancelled.
* This call is automatically invoked when a user either:
* - Presses an exit keyboard key (if configured).
* - Clicks outside of the modal window (if configured).
* Usually, dismiss represent a Cancel button or a X button.
* @return {?}
*/
dismiss() {
const /** @type {?} */ _dismiss = () => {
this.destroy();
this._resultDeferred.promise.catch(() => { });
this._resultDeferred.reject();
};
this._fireHook('beforeDismiss')
.then(value => value !== true && _dismiss())
.catch(_dismiss);
}
/**
* Gracefully close the overlay/dialog with a rejected result.
* Does not trigger canDestroy on the overlay.
* @return {?}
*/
bailOut() {
if (this.destroyed !== true) {
this.destroyed = true;
this._onDestroy.next(null);
this._onDestroy.complete();
this._resultDeferred.reject(new DialogBailOutError());
}
}
/**
* @return {?}
*/
destroy() {
if (this.destroyed !== true) {
this.destroyed = true;
if (typeof this.overlayRef.instance.canDestroy === 'function') {
this.overlayRef.instance.canDestroy()
.catch(() => { })
.then(() => this._destroy());
}
else {
this._destroy();
}
}
}
/**
* @return {?}
*/
_destroy() {
this._onDestroy.next(null);
this._onDestroy.complete();
this.overlayRef.destroy();
}
/**
* @template T
* @param {?} name
* @return {?}
*/
_fireHook(name) {
const /** @type {?} */ gurad = this.closeGuard, /** @type {?} */
fn = gurad && typeof gurad[name] === 'function' && gurad[name];
return Promise.resolve(fn ? fn.call(gurad) : false);
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/** @enum {number} */
const DROP_IN_TYPE = {
alert: 0,
prompt: 1,
confirm: 2,
};
DROP_IN_TYPE[DROP_IN_TYPE.alert] = "alert";
DROP_IN_TYPE[DROP_IN_TYPE.prompt] = "prompt";
DROP_IN_TYPE[DROP_IN_TYPE.confirm] = "confirm";
/**
* @abstract
*/
class OverlayRenderer {
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
const /** @type {?} */ vcRefCollection = {};
/**
* @param {?} key
* @return {?}
*/
function getVCRef(key) {
return vcRefCollection[key] ? vcRefCollection[key].slice() : [];
}
/**
* @param {?} key
* @param {?} vcRef
* @return {?}
*/
function setVCRef(key, vcRef) {
if (!vcRefCollection.hasOwnProperty(key)) {
vcRefCollection[key] = [];
}
vcRefCollection[key].push(vcRef);
}
/**
* @param {?} key
* @param {?=} vcRef
* @return {?}
*/
function delVCRef(key, vcRef) {
if (!vcRef) {
vcRefCollection[key] = [];
}
else {
const /** @type {?} */ coll = vcRefCollection[key] || [], /** @type {?} */
idx = coll.indexOf(vcRef);
if (idx > -1) {
coll.splice(idx, 1);
}
}
}
/**
* A Simple store that holds a reference to ViewContainerRef instances by a user defined key.
* This, with the OverlayTarget directive makes it easy to block the overlay inside an element
* without having to use the angular query boilerplate.
*/
const /** @type {?} */ vcRefStore = { getVCRef, setVCRef, delVCRef };
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A directive use to signal the overlay that the host of this directive
* is a dialog boundary, i.e: over click outside of the element should close the modal
* (if non blocking)
*/
class OverlayDialogBoundary {
/**
* @param {?} el
* @param {?} dialogRef
*/
constructor(el, dialogRef) {
if (dialogRef && el.nativeElement) {
dialogRef.overlayRef.instance.setClickBoundary(el.nativeElement);
}
}
}
OverlayDialogBoundary.decorators = [
{ type: Directive, args: [{
selector: '[overlayDialogBoundary]'
},] },
];
/** @nocollapse */
OverlayDialogBoundary.ctorParameters = () => [
{ type: ElementRef, },
{ type: DialogRef, },
];
class OverlayTarget {
/**
* @param {?} vcRef
*/
constructor(vcRef) {
this.vcRef = vcRef;
}
/**
* @param {?} value
* @return {?}
*/
set targetKey(value) {
this._targetKey = value;
if (value) {
vcRefStore.setVCRef(value, this.vcRef);
}
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._targetKey) {
vcRefStore.delVCRef(this._targetKey, this.vcRef);
}
}
}
OverlayTarget.decorators = [
{ type: Directive, args: [{
selector: '[overlayTarget]'
},] },
];
/** @nocollapse */
OverlayTarget.ctorParameters = () => [
{ type: ViewContainerRef, },
];
OverlayTarget.propDecorators = {
"targetKey": [{ type: Input, args: ['overlayTarget',] },],
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
const /** @type {?} */ BROWSER_PREFIX = ['webkit', 'moz', 'MS', 'o', ''];
/**
* @param {?} eventName
* @param {?} element
* @param {?} cb
* @return {?}
*/
function register(eventName, element, cb) {
BROWSER_PREFIX.forEach(p => {
element.addEventListener(p ? p + eventName : eventName.toLowerCase(), cb, false);
});
}
/**
* A base class for supporting dynamic components.
* There are 3 main support areas:
* 1 - Easy wrapper for dynamic styling via CSS classes and inline styles.
* 2 - Easy wrapper for interception of transition/animation end events.
* 3 - Easy wrapper for component creation and injection.
*
* Dynamic css is done via direct element manipulation (via renderer), it does not use change detection
* or binding. This is to allow better control over animation.
*
* Animation support is limited, only transition/keyframes END even are notified.
* The animation support is needed since currently the angular animation module is limited as well and
* does not support CSS animation that are not pre-parsed and are not in the styles metadata of a component.
*
* Capabilities: Add/Remove styls, Add/Remove classes, listen to animation/transition end event,
* add components
*/
class BaseDynamicComponent {
/**
* @param {?} el
* @param {?} renderer
*/
constructor(el, renderer) {
this.el = el;
this.renderer = renderer;
}
/**
* @return {?}
*/
activateAnimationListener() {
if (this.animationEnd)
return;
this.animationEnd = new Subject();
this.animationEnd$ = this.animationEnd.asObservable();
register('TransitionEnd', this.el.nativeElement, (e) => this.onEnd(e));
register('AnimationEnd', this.el.nativeElement, (e) => this.onEnd(e));
}
/**
* Set a specific inline style on the overlay host element.
* @param {?} prop The style key
* @param {?} value The value, undefined to remove
* @return {?}
*/
setStyle(prop, value) {
this.renderer.setStyle(this.el.nativeElement, prop, value);
return this;
}
/**
* @return {?}
*/
forceReflow() {
this.el.nativeElement.offsetWidth;
}
/**
* @param {?} css
* @param {?=} forceReflow
* @return {?}
*/
addClass(css, forceReflow = false) {
css.split(' ')
.forEach(c => this.renderer.addClass(this.el.nativeElement, c));
if (forceReflow)
this.forceReflow();
}
/**
* @param {?} css
* @param {?=} forceReflow
* @return {?}
*/
removeClass(css, forceReflow = false) {
css.split(' ')
.forEach(c => this.renderer.removeClass(this.el.nativeElement, c));
if (forceReflow) {
this.forceReflow();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this.animationEnd && !this.animationEnd.closed) {
this.animationEnd.complete();
}
}
/**
* @return {?}
*/
myAnimationEnd$() {
return this.animationEnd$.pipe(filter(e => e.target === this.el.nativeElement));
}
/**
* Add a component, supply a view container ref.
* Note: The components vcRef will result in a sibling.
* @template T
* @param {?} instructions
* @return {?}
*/
_addComponent(instructions) {
const /** @type {?} */ cmpRef = createComponent(instructions);
cmpRef.changeDetectorRef.detectChanges();
return cmpRef;
}
/**
* @param {?} event
* @return {?}
*/
onEnd(event) {
if (!this.animationEnd.closed) {
this.animationEnd.next(event);
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Represents the modal backdrop shaped by CSS.
*/
class CSSBackdrop extends BaseDynamicComponent {
/**
* @param {?} el
* @param {?} renderer
*/
constructor(el, renderer) {
super(el, renderer);
this.activateAnimationListener();
const /** @type {?} */ style = {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
};
Object.keys(style).forEach(k => this.setStyle(k, style[k]));
}
}
CSSBackdrop.decorators = [
{ type: Component, args: [{
selector: 'css-backdrop',
host: {
'[attr.class]': 'cssClass',
'[attr.style]': 'styleStr'
},
encapsulation: ViewEncapsulation.None,
template: ``
},] },
];
/** @nocollapse */
CSSBackdrop.ctorParameters = () => [
{ type: ElementRef, },
{ type: Renderer2, },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A component that acts as a top level container for an open modal window.
*/
class CSSDialogContainer extends BaseDynamicComponent {
/**
* @param {?} dialog
* @param {?} el
* @param {?} renderer
*/
constructor(dialog, el, renderer) {
super(el, renderer);
this.dialog = dialog;
this.activateAnimationListener();
}
}
CSSDialogContainer.decorators = [
{ type: Component, args: [{
selector: 'css-dialog-container',
host: {
'tabindex': '-1',
'role': 'dialog'
},
encapsulation: ViewEncapsulation.None,
template: `<ng-content></ng-content>`
},] },
];
/** @nocollapse */
CSSDialogContainer.ctorParameters = () => [
{ type: DialogRef, },
{ type: ElementRef, },
{ type: Renderer2, },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
// export { FadeInBackdrop } from './fade-in-backdrop';
// export { SplitScreenBackdrop } from './split-screen-backdrop';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
// TODO: use DI factory for this.
// TODO: consolidate dup code
const /** @type {?} */ isDoc = !(typeof document === 'undefined' || !document);
/**
* Represents the modal overlay.
*/
class ModalOverlay extends BaseDynamicComponent {
/**
* @param {?} dialogRef
* @param {?} vcr
* @param {?} el
* @param {?} renderer
*/
constructor(dialogRef, vcr, el, renderer) {
super(el, renderer);
this.dialogRef = dialogRef;
this.vcr = vcr;
this.activateAnimationListener();
}
/**
* \@internal
* @template T
* @param {?} content
* @return {?}
*/
getProjectables(content) {
let /** @type {?} */ nodes;
if (typeof content === 'string') {
nodes = [[this.renderer.createText(`${content}`)]];
}
else if (content instanceof TemplateRef) {
nodes = [this.vcr.createEmbeddedView(content, { $implicit: this.dialogRef.context, dialogRef: this.dialogRef }).rootNodes];
}
else {
nodes = [this.embedComponent({ component: content }).rootNodes];
}
return nodes;
}
/**
* @param {?} config
* @return {?}
*/
embedComponent(config) {
const /** @type {?} */ ctx = /** @type {?} */ (config);
return this.vcr.createEmbeddedView(this.template, /** @type {?} */ ({
$implicit: ctx
}));
}
/**
* @template T
* @param {?} type
* @param {?=} projectableNodes
* @return {?}
*/
addComponent(type, projectableNodes = []) {
return super._addComponent({
component: type,
vcRef: this.innerVcr,
projectableNodes
});
}
/**
* @return {?}
*/
fullscreen() {
const /** @type {?} */ style = {
position: 'fixed',
top: 0,
left: 0,
bottom: 0,
right: 0,
'z-index': 1500
};
Object.keys(style).forEach(k => this.setStyle(k, style[k]));
}
/**
* @return {?}
*/
insideElement() {
const /** @type {?} */ style = {
position: 'absolute',
overflow: 'hidden',
width: '100%',
height: '100%',
top: 0,
left: 0,
bottom: 0,
right: 0
};
Object.keys(style).forEach(k => this.setStyle(k, style[k]));
}
/**
* Set a specific inline style for the container of the whole dialog component
* The dialog component root element is the host of this component, it contains only 1 direct
* child which is the container.
*
* Structure:
*
* ```html
* <modal-overlay>
* <div>
* <!-- BACKDROP ELEMENT -->
* <!-- DIALOG CONTAINER ELEMENT -->
* </div>
* </modal-overlay>
* ```
*
* @param {?} prop The style key
* @param {?} value The value, undefined to remove
* @return {?}
*/
setContainerStyle(prop, value) {
this.renderer.setStyle(this.container.nativeElement, prop, value);
return this;
}
/**
* Define an element that click inside it will not trigger modal close.
* Since events bubble, clicking on a dialog will bubble up to the overlay, a plugin
* must define an element that represent the dialog, the overlay will make sure no to close when
* it was clicked.
* @param {?} element
* @return {?}
*/
setClickBoundary(element) {
let /** @type {?} */ target;
const /** @type {?} */ elListener = event => target = /** @type {?} */ (event.target);
const /** @type {?} */ docListener = event => {
if (this.dialogRef.context.isBlocking || !this.dialogRef.overlay.isTopMost(this.dialogRef)) {
return;
}
let /** @type {?} */ current = event.target;
// on click, this will hit.
if (current === target)
return;
// on mouse down -> drag -> release the current might not be 'target', it might be
// a sibling or a child (i.e: not part of the tree-up direction). It might also be a release
// outside the dialog... so we compare to the boundary element
do {
if (current === element) {
return;
}
} while (current.parentNode && (current = current.parentNode));
this.dialogRef.dismiss();
};
if (isDoc) {
this.dialogRef.onDestroy.subscribe(() => {
element.removeEventListener('click', elListener, false);
element.removeEventListener('touchstart', elListener, false);
document.removeEventListener('click', docListener, false);
document.removeEventListener('touchend', docListener, false);
});
setTimeout(() => {
element.addEventListener('mousedown', elListener, false);
element.addEventListener('touchstart', docListener, false);
document.addEventListener('click', docListener, false);
document.addEventListener('touchend', docListener, false);
});
}
}
/**
* Temp workaround for animation where destruction of the top level component does not
* trigger child animations. Solution should be found either in animation module or in design
* of the modal component tree.
* @return {?}
*/
canDestroy() {
const /** @type {?} */ completer = new PromiseCompleter();
if (!Array.isArray(this.beforeDestroyHandlers)) {
completer.resolve();
}
else {
// run destroy notification but protect against halt.
let /** @type {?} */ id = setTimeout(() => {
id = null;
completer.reject();
}, 1000);
const /** @type {?} */ resolve = () => {
if (id === null)
return;
clearTimeout(id);
completer.resolve();
};
Promise.all(this.beforeDestroyHandlers.map(fn => fn()))
.then(resolve)
.catch(resolve);
}
return completer.promise;
}
/**
* A handler running before destruction of the overlay
* use to delay destruction due to animation.
* This is part of the workaround for animation, see canDestroy.
*
* NOTE: There is no guarantee that the listeners will fire, use dialog.onDestory for that.
* @param {?} fn
* @return {?}
*/
beforeDestroy(fn) {
if (!this.beforeDestroyHandlers) {
this.beforeDestroyHandlers = [];
}
this.beforeDestroyHandlers.push(fn);
}
/**
* @param {?} event
* @return {?}
*/
documentKeypress(event) {
// check that this modal is the last in the stack.
if (!this.dialogRef.overlay.isTopMost(this.dialogRef))
return;
if (supportsKey(event.keyCode, /** @type {?} */ (this.dialogRef.context.keyboard))) {
this.dialogRef.dismiss();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
super.ngOnDestroy();
if (this.dialogRef.destroyed !== true) {
// if we're here the overlay is destroyed by an external event that is not user invoked.
// i.e: The user did no call dismiss or close and dialogRef.destroy() did not invoke.
// this will happen when routing or killing an element containing a blocked overlay (ngIf)
// we bail out, i.e gracefully shutting down.
this.dialogRef.bailOut();
}
}
}
ModalOverlay.decorators = [
{ type: Component, args: [{
selector: 'modal-overlay',
host: {
'(body:keydown)': 'documentKeypress($event)'
},
encapsulation: ViewEncapsulation.None,
template: `<div #container>
<ng-template #innerView></ng-template>
</div>
<ng-template #template let-ctx>
<ng-container *ngComponentOutlet="ctx.component; injector: ctx.injector; content: ctx.projectableNodes"></ng-container>
</ng-template>`
},] },
];
/** @nocollapse */
ModalOverlay.ctorParameters = () => [
{ type: DialogRef, },
{ type: ViewContainerRef, },
{ type: ElementRef, },
{ type: Renderer2, },
];
ModalOverlay.propDecorators = {
"container": [{ type: ViewChild, args: ['container', { read: ElementRef },] },],
"innerVcr": [{ type: ViewChild, args: ['innerView', { read: ViewContainerRef },] },],
"template": [{ type: ViewChild, args: ['template',] },],
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
const /** @type {?} */ BASKET_GROUP = {};
/**
* A dumb stack implementation over an array.
* @template T
*/
class DialogRefStack {
constructor() {
this._stack = [];
this._stackMap = new Map();
}
/**
* @return {?}
*/
get length() {
return this._stack.length;
}
/**
* @param {?=} result
* @return {?}
*/
closeAll(result = null) {
for (let /** @type {?} */ i = 0, /** @type {?} */ len = this._stack.length; i < len; i++) {
this._stack.pop().close(result);
}
}
/**
* @param {?} dialogRef
* @param {?=} group
* @return {?}
*/
push(dialogRef, group) {
if (this._stack.indexOf(dialogRef) === -1) {
this._stack.push(dialogRef);
this._stackMap.set(dialogRef, group || BASKET_GROUP);
}
}
/**
* Push a DialogRef into the stack and manage it so when it's done
* it will automatically kick itself out of the stack.
* @param {?} dialogRef
* @param {?=} group
* @return {?}
*/
pushManaged(dialogRef, group) {
this.push(dialogRef, group);
dialogRef.onDestroy.subscribe(() => this.remove(dialogRef));
}
/**
* @return {?}
*/
pop() {
const /** @type {?} */ dialogRef = this._stack.pop();
this._stackMap.delete(dialogRef);
return dialogRef;
}
/**
* Remove a DialogRef from the stack.
* @param {?} dialogRef
* @return {?}
*/
remove(dialogRef) {
let /** @type {?} */ idx = this.indexOf(dialogRef);
if (idx > -1) {
this._stack.splice(idx, 1);
this._stackMap.delete(dialogRef);
}
}
/**
* @param {?} index
* @return {?}
*/
index(index) {
return this._stack[index];
}
/**
* @param {?} dialogRef
* @return {?}
*/
indexOf(dialogRef) {
return this._stack.indexOf(dialogRef);
}
/**
* @param {?} dialogRef
* @return {?}
*/
groupOf(dialogRef) {
return this._stackMap.get(dialogRef);
}
/**
* @param {?} group
* @return {?}
*/
groupBy(group) {
let /** @type {?} */ arr = [];
if (group) {
this._stackMap.forEach((value, key) => {
if (value === group) {
arr.push(key);
}
});
}
return arr;
}
/**
* @param {?} group
* @return {?}
*/
groupLength(group) {
let /** @type {?} */ count = 0;
if (group) {
this._stackMap.forEach((value) => {
if (value === group) {
count++;
}
});
}
return count;
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
const /** @type {?} */ _stack = new DialogRefStack();
class Overlay {
/**
* @param {?} _modalRenderer
* @param {?} injector
*/
constructor(_modalRenderer, injector) {
this._modalRenderer = _modalRenderer;
this.injector = injector;
}
/**
* @return {?}
*/
get stackLength() {
return _stack.length;
}
/**
* Check if a given DialogRef is the top most ref in the stack.
* TODO: distinguish between body modal vs in element modal.
* @param {?} dialogRef
* @return {?}
*/
isTopMost(dialogRef) {
return _stack.indexOf(dialogRef) === _stack.length - 1;
}
/**
* @param {?} dialogRef
* @return {?}
*/
stackPosition(dialogRef) {
return _stack.indexOf(dialogRef);
}
/**
* @param {?} dialogRef
* @return {?}
*/
groupStackLength(dialogRef) {
return _stack.groupLength(_stack.groupOf(dialogRef));
}
/**
* @param {?=} result
* @return {?}
*/
closeAll(result = null) {
_stack.closeAll(result);
}
/**
* Creates an overlay and returns a dialog ref.
* @template T
* @param {?} config instructions how to create the overlay
* @param {?=} group A token to associate the new overlay with, used for reference (stacks usually)
* @return {?}
*/
open(config, group) {
let /** @type {?} */ viewContainer = config.viewContainer, /** @type {?} */
containers = [];
if (typeof viewContainer === 'string') {
containers = vcRefStore.getVCRef(/** @type {?} */ (viewContainer));
}
else if (Array.isArray(viewContainer)) {
containers = /** @type {?} */ (viewContainer);
}
else if (viewContainer) {
containers = /** @type {?} */ ([viewContainer]);
}
else {
containers = [null];
}
return containers
.map(vc => this.createOverlay(config.renderer || this._modalRenderer, vc, config, group));
}
/**
* @param {?} renderer
* @param {?} vcRef
* @param {?} config
* @param {?} group
* @return {?}
*/
createOverlay(renderer, vcRef, config, group) {
if (config.context) {
config.context.normalize();
}
if (!config.injector) {
config.injector = this.injector;
}
let /** @type {?} */ dialog = new DialogRef(this, config.context || {});
dialog.inElement = config.context && !!config.context.inElement;
let /** @type {?} */ cmpRef = renderer.render(dialog, vcRef, config.injector);
Object.defineProperty(dialog, 'overlayRef', { value: cmpRef });
_stack.pushManaged(dialog, group);
return dialog;
}
}
Overlay.decorators = [
{ type: Injectable },
];
/** @nocollapse */
Overlay.ctorParameters = () => [
{ type: OverlayRenderer, },
{ type: Injector, },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
class DOMOverlayRenderer {
/**
* @param {?} appRef
* @param {?} injector
*/
constructor(appRef, injector) {
this.appRef = appRef;
this.injector = injector;
this.isDoc = !(typeof document === 'undefined' || !document);
}
/**
* @param {?} dialog
* @param {?} vcRef
* @param {?=} injector
* @return {?}
*/
render(dialog, vcRef, injector) {
if (!injector) {
injector = this.injector;
}
const /** @type {?} */ cmpRef = createComponent({
component: ModalOverlay,
vcRef,
injector: Injector.create([
{ provide: DialogRef, useValue: dialog }
], injector)
});
if (!vcRef) {
this.appRef.attachView(cmpRef.hostView);
// TODO: doesn't look like this is needed, explore. leaving now to be on the safe side.
dialog.onDestroy.subscribe(() => this.appRef.detachView(cmpRef.hostView));
}
if (vcRef && dialog.inElement) {
vcRef.element.nativeElement.appendChild(cmpRef.location.nativeElement);
}
else if (this.isDoc) {
document.body.appendChild(cmpRef.location.nativeElement);
}
return cmpRef;
}
}
DOMOverlayRenderer.decorators = [
{ type: Injectable },
];
/** @nocollapse */
DOMOverlayRenderer.ctorParameters = () => [
{ type: ApplicationRef, },
{ type: Injector, },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @param {?} dropInName
* @return {?}
*/
function unsupportedDropInError(dropInName) {
return new Error(`Unsupported Drop-In ${dropInName}`);
}
/**
* @abstract
*/
class Modal {
/**
* @param {?} overlay
*/
constructor(overlay) {
this.overlay = overlay;
}
/**
* @return {?}
*/
alert() {
throw unsupportedDropInError('alert');
}
/**
* @return {?}
*/
prompt() {
throw unsupportedDropInError('prompt');
}
/**
* @return {?}
*/
confirm() {
throw unsupportedDropInError('confirm');
}
/**
* Opens a modal window inside an existing component.
* @param {?} content The content to display, either string, template ref or a component.
* @param {?=} config Additional settings.
* @return {?}
*/
open(content, config) {
config = config || /** @type {?} */ ({});
let /** @type {?} */ dialogs = this.overlay.open(config, this.constructor);
if (dialogs.length > 1) {
console.warn(`Attempt to open more then 1 overlay detected.
Multiple modal copies are not supported at the moment,
only the first viewContainer will display.`);
}
// TODO: Currently supporting 1 view container, hence working on dialogs[0].
// upgrade to multiple containers.
return this.create(dialogs[0], content);
}
/**
* @template T
* @param {?} dialogRef
* @param {?} BackdropComponent
* @return {?}
*/
createBackdrop(dialogRef, BackdropComponent) {
return dialogRef.overlayRef.instance.addComponent(BackdropComponent);
}
/**
* @template T
* @param {?} dialogRef
* @param {?} ContainerComponent
* @param {?} content
* @return {?}
*/
createContainer(dialogRef, ContainerComponent, content) {
let /** @type {?} */ nodes = dialogRef.overlayRef.instance.getProjectables(content);
return dialogRef.overlayRef.instance.addComponent(ContainerComponent, nodes);
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
// TODO: use DI factory for this.
// TODO: consolidate dup code
const /** @type {?} */ isDoc$1 = !(typeof document === 'undefined' || !document);
const /** @type {?} */ eventMap = {
clickOutside: 'click',
mousedownOutside: 'mousedown',
mouseupOutside: 'mouseup',
mousemoveOutside: 'mousemove'
};
/**
* An event handler factory for event handlers that bubble the event to a given handler
* if the event target is not an ancestor of the given element.
* @param {?} element
* @param {?} handler
* @return {?}
*/
function bubbleNonAncestorHandlerFactory(element, handler) {
return (event) => {
let /** @type {?} */ current = event.target;
do {
if (current === element) {
return;
}
} while (current.parentNode && (current = current.parentNode));
handler(event);
};
}
class DOMOutsideEventPlugin {
constructor() {
if (!isDoc$1 || typeof document.addEventListener !== 'function') {
this.addEventListener = /** @type {?} */ (noop);
}
}
/**
* @param {?} eventName
* @return {?}
*/
supports(eventName) {
return eventMap.hasOwnProperty(eventName);
}
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
addEventListener(element, eventName, handler) {
const /** @type {?} */ zone = this.manager.getZone();
// A Factory that registers the event on the document, instead of the element.
// the handler is created at runtime, and it acts as a propagation/bubble predicate, it will
// bubble up the event (i.e: execute our original event handler) only if the event targer
// is an ancestor of our element.
// The event is fired inside the angular zone so change detection can kick into action.
const /** @type {?} */ onceOnOutside = () => {
const /** @type {?} */ listener = bubbleNonAncestorHandlerFactory(element, evt => zone.runGuarded(() => handler(evt)));
// mimic BrowserDomAdapter.onAndCancel
document.addEventListener(eventMap[eventName], listener, false);
return () => document.removeEventListener(eventMap[eventName], listener, false);
};
// we run the event registration for the document in a different zone, this will make sure
// change detection is off.
// It turns out that if a component that use DOMOutsideEventPlugin is built from a click
// event, we might get here before the event reached the document, causing a quick false
// positive handling (when stopPropagation() was'nt invoked). To workaround this we wait
// for the next vm turn and register.
// Event registration returns a dispose function for that event, angular use it to clean
// up after component get's destroyed. Since we need to return a dispose function
// synchronously we have to put a wrapper for it since we will get it asynchronously,
// i.e: after we need to return it.
//
return zone.runOutsideAngular(() => {
let /** @type {?} */ fn;
setTimeout(() => fn = onceOnOutside(), 0);
return () => {
if (fn)
fn();
};
});
}
}
DOMOutsideEventPlugin.decorators = [
{ type: Injectable },
];
/** @nocollapse */
DOMOutsideEventPlugin.ctorParameters = () => [];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
const /** @type {?} */ DEFAULT_VALUES = {
inElement: false,
isBlocking: true,
keyboard: [27],
supportsKey: function supportsKey$$1(keyCode) {
return (/** @type {?} */ (this.keyboard)).indexOf(keyCode) > -1;
}
};
const /** @type {?} */ DEFAULT_SETTERS = [
'inElement',
'isBlocking',
'keyboard'
];
class OverlayContext {
/**
* @return {?}
*/
normalize() {
if (this.isBlocking !== false)
this.isBlocking = true;
if (this.keyboard === null) {
this.keyboard = [];
}
else if (typeof this.keyboard === 'number') {
this.keyboard = [/** @type {?} */ (this.keyboard)];
}
else if (!Array.isArray(/** @type {?} */ (this.keyboard))) {
this.keyboard = DEFAULT_VALUES.keyboard;
}
}
}
// unsupported: template constraints.
/**
* A core context builder for a modal window instance, used to define the context upon
* a modal choose it's behaviour.
* @template T
*/
class OverlayContextBuilder extends FluentAssign {
/**
* @param {?=} defaultValues
* @param {?=} initialSetters
* @param {?=} baseType
*/
constructor(defaultValues = undefined, initialSetters = undefined, baseType = undefined) {
super(extend(DEFAULT_VALUES, defaultValues || {}), arrayUnion(DEFAULT_SETTERS, initialSetters || []), baseType || /** @type {?} */ (OverlayContext // https://github.com/Microsoft/TypeScript/issues/7234
) // https://github.com/Microsoft/TypeScript/issues/7234
);
}
/**
* Returns an new OverlayConfig with a context property representing the data in this builder.
* @param {?=} base A base configuration that the result will extend
* @return {?}
*/
toOverlayConfig(base) {
return extend(base || {}, {
context: this.toJSON()
});
}
}
/**
* A helper to create an `OverlayConfig` on the fly.
* Since `OverlayConfig` requires context it means a builder is needed, this process had some boilerplate.
* When a quick, on the fly overlay config is needed use this helper to avoid that boilerplate.
*
* A builder is used as an API to allow setting the context and providing some operations around the modal.
* When a developers knows the context before hand we can skip this step, this is what this factory is for.
*
* @template T
* @param {?} context The context for the modal
* @param {?=} baseContextType Optional. The type/class of the context. This is the class used to init a new instance of the context
* @param {?=} baseConfig A base configuration that the result will extend
* @return {?}
*/
function overlayConfigFactory(context, baseContextType, baseConfig) {
return new OverlayContextBuilder(/** @type {?} */ (context), undefined, baseContextType).toOverlayConfig(baseConfig);
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
const /** @type {?} */ DEFAULT_VALUES$1 = {};
const /** @type {?} */ DEFAULT_SETTERS$1 = [
'message'
];
class ModalContext extends OverlayContext {
}
// unsupported: template constraints.
/**
* A core context builder for a modal window instance, used to define the context upon
* a modal choose it's behaviour.
* @template T
*/
class ModalContextBuilder extends OverlayContextBuilder {
/**
* @param {?=} defaultValues
* @param {?=} initialSetters
* @param {?=} baseType
*/
constructor(defaultValues = undefined, initialSetters = undefined, baseType = undefined) {
super(extend(DEFAULT_VALUES$1, defaultValues || {}), arrayUnion(DEFAULT_SETTERS$1, initialSetters || []), baseType);
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
const /** @type {?} */ DEFAULT_SETTERS$2 = [
'component'
];
class ModalOpenContext extends ModalContext {
}
// unsupported: template constraints.
/**
* A Moda