ngx-modialog
Version:
Modal / Dialog for Angular
1,553 lines (1,534 loc) • 61.9 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 { __extends } from 'tslib';
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
*/
var /** @type {?} */ PRIVATE_PREFIX = '$$';
var /** @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(function (name) { return RESERVED_REGEX.test(name); })
.map(function (name) { return 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: 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(function (name) { return ((instance))[privateKey(name)] = ((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) {
var _this = this;
if (writeOnce === void 0) { writeOnce = false; }
validateMethodName.call(obj, propertyName);
var /** @type {?} */ key = privateKey(propertyName);
objectDefinePropertyValue(obj, propertyName, function (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) {
if (hard === void 0) { hard = false; }
validateMethodName.call(obj, propertyName);
objectDefinePropertyValue(obj, propertyName, function (value) {
obj[srcPropertyName](value);
return obj;
});
if (hard === true) {
var /** @type {?} */ key = privateKey(propertyName), /** @type {?} */ srcKey_1 = privateKey(srcPropertyName);
Object.defineProperty(obj, key, /** @type {?} */ ({
configurable: false,
enumerable: false,
get: function () { return obj[srcKey_1]; }
}));
}
}
/**
* Represent a fluent API factory wrapper for defining FluentAssign instances.
* @template T
*/
var FluentAssignFactory = /** @class */ (function () {
/**
* @param {?=} fluentAssign
*/
function FluentAssignFactory(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 {?}
*/
FluentAssignFactory.prototype.setMethod = function (name, defaultValue) {
if (defaultValue === void 0) { defaultValue = undefined; }
setAssignMethod(this._fluentAssign, name);
if (defaultValue !== undefined) {
((this._fluentAssign))[name](defaultValue);
}
return this;
};
Object.defineProperty(FluentAssignFactory.prototype, "fluentAssign", {
/**
* The FluentAssign instance.
* @return {?}
*/
get: function () {
return this._fluentAssign;
},
enumerable: true,
configurable: true
});
return FluentAssignFactory;
}());
/**
* 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
*/
var FluentAssign = /** @class */ (function () {
/**
*
* @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.
*/
function FluentAssign(defaultValues, initialSetters, baseType) {
if (defaultValues === void 0) { defaultValues = undefined; }
if (initialSetters === void 0) { initialSetters = undefined; }
if (baseType === void 0) { baseType = undefined; }
var _this = this;
if (Array.isArray(defaultValues)) {
((defaultValues)).forEach(function (d) { return applyDefaultValues(_this, d); });
}
else if (defaultValues) {
applyDefaultValues(this, defaultValues);
}
if (Array.isArray(initialSetters)) {
initialSetters.forEach(function (name) { return 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 {?}
*/
FluentAssign.compose = function (defaultValues, initialSetters) {
if (defaultValues === void 0) { defaultValues = undefined; }
if (initialSetters === void 0) { 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 {?}
*/
FluentAssign.composeWith = function (fluentAssign) {
return /** @type {?} */ (new FluentAssignFactory(/** @type {?} */ (fluentAssign)));
};
/**
* @return {?}
*/
FluentAssign.prototype.toJSON = function () {
var _this = this;
return getAssignedPropertyNames(this)
.reduce(function (obj, name) {
var /** @type {?} */ key = privateKey(name);
// re-define property descriptors (we dont want their value)
var /** @type {?} */ propDesc = Object.getOwnPropertyDescriptor(_this, key);
if (propDesc) {
Object.defineProperty(obj, name, propDesc);
}
else {
((obj))[name] = ((_this))[key];
}
return obj;
}, this.__fluent$base__ ? new this.__fluent$base__() : /** @type {?} */ ({}));
};
return FluentAssign;
}());
/**
* @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 = ({});
for (var /** @type {?} */ attr in m1) {
if (m1.hasOwnProperty(attr)) {
((m))[attr] = ((m1))[attr];
}
}
for (var /** @type {?} */ attr in m2) {
if (m2.hasOwnProperty(attr)) {
((m))[attr] = ((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(function (v) { return 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
*/
var PromiseCompleter = /** @class */ (function () {
function PromiseCompleter() {
var _this = this;
this.promise = new Promise(function (res, rej) {
_this.resolve = res;
_this.reject = rej;
});
}
return PromiseCompleter;
}());
/**
* @return {?}
*/
function noop() { }
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @param {?} instructions
* @return {?}
*/
function createComponent(instructions) {
var /** @type {?} */ injector = instructions.injector || instructions.vcRef.parentInjector;
var /** @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
*/
var DialogBailOutError = /** @class */ (function (_super) {
__extends(DialogBailOutError, _super);
/**
* @param {?=} value
*/
function DialogBailOutError(value) {
var _this = _super.call(this) || this;
if (!value) {
value = 'Dialog was forced to close by an unknown source.';
}
_this.message = value;
return _this;
}
return DialogBailOutError;
}(Error));
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* API to an open modal window.
* @template T
*/
var DialogRef = /** @class */ (function () {
/**
* @param {?} overlay
* @param {?=} context
*/
function DialogRef(overlay, context) {
this.overlay = overlay;
this.context = context;
this._resultDeferred = new PromiseCompleter();
this._onDestroy = new Subject();
this.onDestroy = this._onDestroy.asObservable();
}
Object.defineProperty(DialogRef.prototype, "result", {
/**
* A Promise that is resolved on a close event and rejected on a dismiss event.
* @return {?}
*/
get: function () {
return this._resultDeferred.promise;
},
enumerable: true,
configurable: true
});
/**
* Set a close/dismiss guard
* @param {?} guard
* @return {?}
*/
DialogRef.prototype.setCloseGuard = function (guard) {
this.closeGuard = guard;
};
/**
* Close the modal with a return value, i.e: result.
* @param {?=} result
* @return {?}
*/
DialogRef.prototype.close = function (result) {
var _this = this;
if (result === void 0) { result = null; }
var /** @type {?} */ _close = function () {
_this.destroy();
_this._resultDeferred.resolve(result);
};
this._fireHook('beforeClose')
.then(function (value) { return 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 {?}
*/
DialogRef.prototype.dismiss = function () {
var _this = this;
var /** @type {?} */ _dismiss = function () {
_this.destroy();
_this._resultDeferred.promise.catch(function () { });
_this._resultDeferred.reject();
};
this._fireHook('beforeDismiss')
.then(function (value) { return value !== true && _dismiss(); })
.catch(_dismiss);
};
/**
* Gracefully close the overlay/dialog with a rejected result.
* Does not trigger canDestroy on the overlay.
* @return {?}
*/
DialogRef.prototype.bailOut = function () {
if (this.destroyed !== true) {
this.destroyed = true;
this._onDestroy.next(null);
this._onDestroy.complete();
this._resultDeferred.reject(new DialogBailOutError());
}
};
/**
* @return {?}
*/
DialogRef.prototype.destroy = function () {
var _this = this;
if (this.destroyed !== true) {
this.destroyed = true;
if (typeof this.overlayRef.instance.canDestroy === 'function') {
this.overlayRef.instance.canDestroy()
.catch(function () { })
.then(function () { return _this._destroy(); });
}
else {
this._destroy();
}
}
};
/**
* @return {?}
*/
DialogRef.prototype._destroy = function () {
this._onDestroy.next(null);
this._onDestroy.complete();
this.overlayRef.destroy();
};
/**
* @template T
* @param {?} name
* @return {?}
*/
DialogRef.prototype._fireHook = function (name) {
var /** @type {?} */ gurad = this.closeGuard, /** @type {?} */ fn = gurad && typeof gurad[name] === 'function' && gurad[name];
return Promise.resolve(fn ? fn.call(gurad) : false);
};
return DialogRef;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/** @enum {number} */
var 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
*/
var OverlayRenderer = /** @class */ (function () {
function OverlayRenderer() {
}
return OverlayRenderer;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
var /** @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 {
var /** @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.
*/
var /** @type {?} */ vcRefStore = { getVCRef: getVCRef, setVCRef: setVCRef, delVCRef: 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)
*/
var OverlayDialogBoundary = /** @class */ (function () {
/**
* @param {?} el
* @param {?} dialogRef
*/
function OverlayDialogBoundary(el, dialogRef) {
if (dialogRef && el.nativeElement) {
dialogRef.overlayRef.instance.setClickBoundary(el.nativeElement);
}
}
return OverlayDialogBoundary;
}());
OverlayDialogBoundary.decorators = [
{ type: Directive, args: [{
selector: '[overlayDialogBoundary]'
},] },
];
/** @nocollapse */
OverlayDialogBoundary.ctorParameters = function () { return [
{ type: ElementRef, },
{ type: DialogRef, },
]; };
var OverlayTarget = /** @class */ (function () {
/**
* @param {?} vcRef
*/
function OverlayTarget(vcRef) {
this.vcRef = vcRef;
}
Object.defineProperty(OverlayTarget.prototype, "targetKey", {
/**
* @param {?} value
* @return {?}
*/
set: function (value) {
this._targetKey = value;
if (value) {
vcRefStore.setVCRef(value, this.vcRef);
}
},
enumerable: true,
configurable: true
});
/**
* @return {?}
*/
OverlayTarget.prototype.ngOnDestroy = function () {
if (this._targetKey) {
vcRefStore.delVCRef(this._targetKey, this.vcRef);
}
};
return OverlayTarget;
}());
OverlayTarget.decorators = [
{ type: Directive, args: [{
selector: '[overlayTarget]'
},] },
];
/** @nocollapse */
OverlayTarget.ctorParameters = function () { return [
{ type: ViewContainerRef, },
]; };
OverlayTarget.propDecorators = {
"targetKey": [{ type: Input, args: ['overlayTarget',] },],
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
var /** @type {?} */ BROWSER_PREFIX = ['webkit', 'moz', 'MS', 'o', ''];
/**
* @param {?} eventName
* @param {?} element
* @param {?} cb
* @return {?}
*/
function register(eventName, element, cb) {
BROWSER_PREFIX.forEach(function (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
*/
var BaseDynamicComponent = /** @class */ (function () {
/**
* @param {?} el
* @param {?} renderer
*/
function BaseDynamicComponent(el, renderer) {
this.el = el;
this.renderer = renderer;
}
/**
* @return {?}
*/
BaseDynamicComponent.prototype.activateAnimationListener = function () {
var _this = this;
if (this.animationEnd)
return;
this.animationEnd = new Subject();
this.animationEnd$ = this.animationEnd.asObservable();
register('TransitionEnd', this.el.nativeElement, function (e) { return _this.onEnd(e); });
register('AnimationEnd', this.el.nativeElement, function (e) { return _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 {?}
*/
BaseDynamicComponent.prototype.setStyle = function (prop, value) {
this.renderer.setStyle(this.el.nativeElement, prop, value);
return this;
};
/**
* @return {?}
*/
BaseDynamicComponent.prototype.forceReflow = function () {
this.el.nativeElement.offsetWidth;
};
/**
* @param {?} css
* @param {?=} forceReflow
* @return {?}
*/
BaseDynamicComponent.prototype.addClass = function (css, forceReflow) {
var _this = this;
if (forceReflow === void 0) { forceReflow = false; }
css.split(' ')
.forEach(function (c) { return _this.renderer.addClass(_this.el.nativeElement, c); });
if (forceReflow)
this.forceReflow();
};
/**
* @param {?} css
* @param {?=} forceReflow
* @return {?}
*/
BaseDynamicComponent.prototype.removeClass = function (css, forceReflow) {
var _this = this;
if (forceReflow === void 0) { forceReflow = false; }
css.split(' ')
.forEach(function (c) { return _this.renderer.removeClass(_this.el.nativeElement, c); });
if (forceReflow) {
this.forceReflow();
}
};
/**
* @return {?}
*/
BaseDynamicComponent.prototype.ngOnDestroy = function () {
if (this.animationEnd && !this.animationEnd.closed) {
this.animationEnd.complete();
}
};
/**
* @return {?}
*/
BaseDynamicComponent.prototype.myAnimationEnd$ = function () {
var _this = this;
return this.animationEnd$.pipe(filter(function (e) { return 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 {?}
*/
BaseDynamicComponent.prototype._addComponent = function (instructions) {
var /** @type {?} */ cmpRef = createComponent(instructions);
cmpRef.changeDetectorRef.detectChanges();
return cmpRef;
};
/**
* @param {?} event
* @return {?}
*/
BaseDynamicComponent.prototype.onEnd = function (event) {
if (!this.animationEnd.closed) {
this.animationEnd.next(event);
}
};
return BaseDynamicComponent;
}());
/**
* Represents the modal backdrop shaped by CSS.
*/
var CSSBackdrop = /** @class */ (function (_super) {
__extends(CSSBackdrop, _super);
/**
* @param {?} el
* @param {?} renderer
*/
function CSSBackdrop(el, renderer) {
var _this = _super.call(this, el, renderer) || this;
_this.activateAnimationListener();
var /** @type {?} */ style = {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
};
Object.keys(style).forEach(function (k) { return _this.setStyle(k, style[k]); });
return _this;
}
return CSSBackdrop;
}(BaseDynamicComponent));
CSSBackdrop.decorators = [
{ type: Component, args: [{
selector: 'css-backdrop',
host: {
'[attr.class]': 'cssClass',
'[attr.style]': 'styleStr'
},
encapsulation: ViewEncapsulation.None,
template: ""
},] },
];
/** @nocollapse */
CSSBackdrop.ctorParameters = function () { return [
{ type: ElementRef, },
{ type: Renderer2, },
]; };
/**
* A component that acts as a top level container for an open modal window.
*/
var CSSDialogContainer = /** @class */ (function (_super) {
__extends(CSSDialogContainer, _super);
/**
* @param {?} dialog
* @param {?} el
* @param {?} renderer
*/
function CSSDialogContainer(dialog, el, renderer) {
var _this = _super.call(this, el, renderer) || this;
_this.dialog = dialog;
_this.activateAnimationListener();
return _this;
}
return CSSDialogContainer;
}(BaseDynamicComponent));
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 = function () { return [
{ 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';
// TODO: use DI factory for this.
// TODO: consolidate dup code
var /** @type {?} */ isDoc = !(typeof document === 'undefined' || !document);
/**
* Represents the modal overlay.
*/
var ModalOverlay = /** @class */ (function (_super) {
__extends(ModalOverlay, _super);
/**
* @param {?} dialogRef
* @param {?} vcr
* @param {?} el
* @param {?} renderer
*/
function ModalOverlay(dialogRef, vcr, el, renderer) {
var _this = _super.call(this, el, renderer) || this;
_this.dialogRef = dialogRef;
_this.vcr = vcr;
_this.activateAnimationListener();
return _this;
}
/**
* \@internal
* @template T
* @param {?} content
* @return {?}
*/
ModalOverlay.prototype.getProjectables = function (content) {
var /** @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 {?}
*/
ModalOverlay.prototype.embedComponent = function (config) {
var /** @type {?} */ ctx = (config);
return this.vcr.createEmbeddedView(this.template, /** @type {?} */ ({
$implicit: ctx
}));
};
/**
* @template T
* @param {?} type
* @param {?=} projectableNodes
* @return {?}
*/
ModalOverlay.prototype.addComponent = function (type, projectableNodes) {
if (projectableNodes === void 0) { projectableNodes = []; }
return _super.prototype._addComponent.call(this, {
component: type,
vcRef: this.innerVcr,
projectableNodes: projectableNodes
});
};
/**
* @return {?}
*/
ModalOverlay.prototype.fullscreen = function () {
var _this = this;
var /** @type {?} */ style = {
position: 'fixed',
top: 0,
left: 0,
bottom: 0,
right: 0,
'z-index': 1500
};
Object.keys(style).forEach(function (k) { return _this.setStyle(k, style[k]); });
};
/**
* @return {?}
*/
ModalOverlay.prototype.insideElement = function () {
var _this = this;
var /** @type {?} */ style = {
position: 'absolute',
overflow: 'hidden',
width: '100%',
height: '100%',
top: 0,
left: 0,
bottom: 0,
right: 0
};
Object.keys(style).forEach(function (k) { return _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 {?}
*/
ModalOverlay.prototype.setContainerStyle = function (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 {?}
*/
ModalOverlay.prototype.setClickBoundary = function (element) {
var _this = this;
var /** @type {?} */ target;
var /** @type {?} */ elListener = function (event) { return target = /** @type {?} */ (event.target); };
var /** @type {?} */ docListener = function (event) {
if (_this.dialogRef.context.isBlocking || !_this.dialogRef.overlay.isTopMost(_this.dialogRef)) {
return;
}
var /** @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(function () {
element.removeEventListener('click', elListener, false);
element.removeEventListener('touchstart', elListener, false);
document.removeEventListener('click', docListener, false);
document.removeEventListener('touchend', docListener, false);
});
setTimeout(function () {
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 {?}
*/
ModalOverlay.prototype.canDestroy = function () {
var /** @type {?} */ completer = new PromiseCompleter();
if (!Array.isArray(this.beforeDestroyHandlers)) {
completer.resolve();
}
else {
// run destroy notification but protect against halt.
var /** @type {?} */ id_1 = setTimeout(function () {
id_1 = null;
completer.reject();
}, 1000);
var /** @type {?} */ resolve = function () {
if (id_1 === null)
return;
clearTimeout(id_1);
completer.resolve();
};
Promise.all(this.beforeDestroyHandlers.map(function (fn) { return 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 {?}
*/
ModalOverlay.prototype.beforeDestroy = function (fn) {
if (!this.beforeDestroyHandlers) {
this.beforeDestroyHandlers = [];
}
this.beforeDestroyHandlers.push(fn);
};
/**
* @param {?} event
* @return {?}
*/
ModalOverlay.prototype.documentKeypress = function (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 {?}
*/
ModalOverlay.prototype.ngOnDestroy = function () {
_super.prototype.ngOnDestroy.call(this);
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();
}
};
return ModalOverlay;
}(BaseDynamicComponent));
ModalOverlay.decorators = [
{ type: Component, args: [{
selector: 'modal-overlay',
host: {
'(body:keydown)': 'documentKeypress($event)'
},
encapsulation: ViewEncapsulation.None,
template: "<div #container>\n <ng-template #innerView></ng-template>\n</div>\n<ng-template #template let-ctx>\n <ng-container *ngComponentOutlet=\"ctx.component; injector: ctx.injector; content: ctx.projectableNodes\"></ng-container>\n</ng-template>"
},] },
];
/** @nocollapse */
ModalOverlay.ctorParameters = function () { return [
{ 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
*/
var /** @type {?} */ BASKET_GROUP = {};
/**
* A dumb stack implementation over an array.
* @template T
*/
var DialogRefStack = /** @class */ (function () {
function DialogRefStack() {
this._stack = [];
this._stackMap = new Map();
}
Object.defineProperty(DialogRefStack.prototype, "length", {
/**
* @return {?}
*/
get: function () {
return this._stack.length;
},
enumerable: true,
configurable: true
});
/**
* @param {?=} result
* @return {?}
*/
DialogRefStack.prototype.closeAll = function (result) {
if (result === void 0) { result = null; }
for (var /** @type {?} */ i = 0, /** @type {?} */ len = this._stack.length; i < len; i++) {
this._stack.pop().close(result);
}
};
/**
* @param {?} dialogRef
* @param {?=} group
* @return {?}
*/
DialogRefStack.prototype.push = function (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 {?}
*/
DialogRefStack.prototype.pushManaged = function (dialogRef, group) {
var _this = this;
this.push(dialogRef, group);
dialogRef.onDestroy.subscribe(function () { return _this.remove(dialogRef); });
};
/**
* @return {?}
*/
DialogRefStack.prototype.pop = function () {
var /** @type {?} */ dialogRef = this._stack.pop();
this._stackMap.delete(dialogRef);
return dialogRef;
};
/**
* Remove a DialogRef from the stack.
* @param {?} dialogRef
* @return {?}
*/
DialogRefStack.prototype.remove = function (dialogRef) {
var /** @type {?} */ idx = this.indexOf(dialogRef);
if (idx > -1) {
this._stack.splice(idx, 1);
this._stackMap.delete(dialogRef);
}
};
/**
* @param {?} index
* @return {?}
*/
DialogRefStack.prototype.index = function (index) {
return this._stack[index];
};
/**
* @param {?} dialogRef
* @return {?}
*/
DialogRefStack.prototype.indexOf = function (dialogRef) {
return this._stack.indexOf(dialogRef);
};
/**
* @param {?} dialogRef
* @return {?}
*/
DialogRefStack.prototype.groupOf = function (dialogRef) {
return this._stackMap.get(dialogRef);
};
/**
* @param {?} group
* @return {?}
*/
DialogRefStack.prototype.groupBy = function (group) {
var /** @type {?} */ arr = [];
if (group) {
this._stackMap.forEach(function (value, key) {
if (value === group) {
arr.push(key);
}
});
}
return arr;
};
/**
* @param {?} group
* @return {?}
*/
DialogRefStack.prototype.groupLength = function (group) {
var /** @type {?} */ count = 0;
if (group) {
this._stackMap.forEach(function (value) {
if (value === group) {
count++;
}
});
}
return count;
};
return DialogRefStack;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
var /** @type {?} */ _stack = new DialogRefStack();
var Overlay = /** @class */ (function () {
/**
* @param {?} _modalRenderer
* @param {?} injector
*/
function Overlay(_modalRenderer, injector) {
this._modalRenderer = _modalRenderer;
this.injector = injector;
}
Object.defineProperty(Overlay.prototype, "stackLength", {
/**
* @return {?}
*/
get: function () {
return _stack.length;
},
enumerable: true,
configurable: true
});
/**
* 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 {?}
*/
Overlay.prototype.isTopMost = function (dialogRef) {
return _stack.indexOf(dialogRef) === _stack.length - 1;
};
/**
* @param {?} dialogRef
* @return {?}
*/
Overlay.prototype.stackPosition = function (dialogRef) {
return _stack.indexOf(dialogRef);
};
/**
* @param {?} dialogRef
* @return {?}
*/
Overlay.prototype.groupStackLength = function (dialogRef) {
return _stack.groupLength(_stack.groupOf(dialogRef));
};
/**
* @param {?=} result
* @return {?}
*/
Overlay.prototype.closeAll = function (result) {
if (result === void 0) { 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 {?}
*/
Overlay.prototype.open = function (config, group) {
var _this = this;
var /** @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(function (vc) { return _this.createOverlay(config.renderer || _this._modalRenderer, vc, config, group); });
};
/**
* @param {?} renderer
* @param {?} vcRef
* @param {?} config
* @param {?} group
* @return {?}
*/
Overlay.prototype.createOverlay = function (renderer, vcRef, config, group) {
if (config.context) {
config.context.normalize();
}
if (!config.injector) {
config.injector = this.injector;
}
var /** @type {?} */ dialog = new DialogRef(this, config.context || {});
dialog.inElement = config.context && !!config.context.inElement;
var /** @type {?} */ cmpRef = renderer.render(dialog, vcRef, config.injector);
Object.defineProperty(dialog, 'overlayRef', { value: cmpRef });
_stack.pushManaged(dialog, group);
return dialog;
};
return Overlay;
}());
Overlay.decorators = [
{ type: Injectable },
];
/** @nocollapse */
Overlay.ctorParameters = function () { return [
{ type: OverlayRenderer, },
{ type: Injector, },
]; };
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
var DOMOverlayRenderer = /** @class */ (function () {
/**
* @param {?} appRef
* @param {?} injector
*/
function DOMOverlayRenderer(appRef, injector) {
this.appRef = appRef;
this.injector = injector;
this.isDoc = !(typeof document === 'undefined' || !document);
}
/**
* @param {?} dialog
* @param {?} vcRef
* @param {?=} injector
* @return {?}
*/
DOMOverlayRenderer.prototype.render = function (dialog, vcRef, injector) {
var _this = this;
if (!injector) {
injector = this.injector;
}
var /** @type {?} */ cmpRef = createComponent({
component: ModalOverlay,
vcRef: 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(function () { return _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;
};
return DOMOverlayRenderer;
}());
DOMOverlayRenderer.decorators = [
{ type: Injectable },
];
/** @nocollapse */
DOMOverlayRenderer.ctorParameters = function () { return [
{ 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
*/
var Modal = /** @class */ (function () {
/**
* @param {?} overlay
*/
function Modal(overlay) {
this.overlay = overlay;
}
/**
* @return {?}
*/
Modal.prototype.alert = function () {
throw unsupportedDropInError('alert');
};
/**
* @return {?}
*/
Modal.prototype.prompt = function () {
throw unsupportedDropInError('prompt');
};
/**
* @return {?}
*/
Modal.prototype.confirm = function () {
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 {?}
*/
Modal.prototype.open = function (content, config) {
config = config || /** @type {?} */ ({});
var /** @type {?} */ dialogs = this.overlay.open(config, this.constructor);
if (dialogs.length > 1) {
console.warn("Attempt to open more then 1 overlay detected.\n Multiple modal copies are not supported at the moment, \n 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 {?}
*/
Modal.prototype.createBackdrop = function (dialogRef, BackdropComponent) {
return dialogRef.overlayRef.instance.addComponent(BackdropComponent);
};
/**
* @template T
* @param {?} dialogRef
* @param {?} ContainerComponent
* @param {?} content
* @return {?}
*/
Modal.prototype.createContainer = function (dialogRef, ContainerComponent, content) {
var /** @type {?} */ nodes = dialogRef.overlayRef.instance.getProjectables(content);
return dialogRef.overlayRef.instance.addComponent(ContainerComponent, nodes);
};
return Modal;
}());
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
// TODO: use DI factory for this.
// TODO: consolidate dup code
var /** @type {?} */ isDoc$1 = !(typeof document === 'undefined' || !document);
var /** @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 function (event) {
var /** @type {?} */ current = event.target;
do {
if (current === element) {
return;
}
} while (current.parentNode && (current = current.parentNode));
handler(event);
};
}
var DOMOutsideEventPlugin = /** @class */ (function () {
function DOMOutsideEventPlugin() {
if (!isDoc$1 || typeof document.addEventListener !== 'function') {
this.addEventListener = /** @type {?} */ (noop);
}
}
/**
* @param {?} eventName
* @return {?}
*/
DOMOutsideEventPlugin.prototype.supports = function (eventName) {
return eventMap.hasOwnProperty(eventName);
};
/**
* @param {?} element
* @param {?} eventName
* @param {?} handler
* @return {?}
*/
DOMOutsideEventPlugin.prototype.addEventListener = function (element, eventName, handler) {
var /** @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 orig