ngx-modialog-11
Version:
Modal / Dialog for Angular
1,772 lines • 74.7 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('rxjs'), require('rxjs/operators'), require('@angular/common'), require('@angular/platform-browser')) :
typeof define === 'function' && define.amd ? define('ngxModialog', ['exports', '@angular/core', 'rxjs', 'rxjs/operators', '@angular/common', '@angular/platform-browser'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ngxModialog = {}, global.ng.core, global.rxjs, global.rxjs.operators, global.ng.common, global.ng.platformBrowser));
}(this, (function (exports, core, rxjs, operators, common, platformBrowser) { 'use strict';
var PRIVATE_PREFIX = '$$';
var RESERVED_REGEX = /^(\$\$).*/;
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
*/
function getAssignedPropertyNames(subject) {
return Object.getOwnPropertyNames(subject)
.filter(function (name) { return RESERVED_REGEX.test(name); })
.map(function (name) { return name.substr(2); });
}
function privateKey(name) {
return PRIVATE_PREFIX + name;
}
function objectDefinePropertyValue(obj, propertyName, value) {
Object.defineProperty(obj, propertyName, {
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
*/
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.
* @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.
*/
function setAssignMethod(obj, propertyName, writeOnce) {
var _this = this;
if (writeOnce === void 0) { writeOnce = false; }
validateMethodName.call(obj, propertyName);
var 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.
* @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
*/
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 key = privateKey(propertyName), srcKey_1 = privateKey(srcPropertyName);
Object.defineProperty(obj, key, {
configurable: false,
enumerable: false,
get: function () { return obj[srcKey_1]; }
});
}
}
/**
* Represent a fluent API factory wrapper for defining FluentAssign instances.
*/
var FluentAssignFactory = /** @class */ (function () {
function FluentAssignFactory(fluentAssign) {
this._fluentAssign =
fluentAssign instanceof FluentAssign ? fluentAssign : 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.
*/
FluentAssignFactory.prototype.setMethod = function (name, defaultValue) {
setAssignMethod(this._fluentAssign, name);
if (defaultValue !== undefined) {
this._fluentAssign[name](defaultValue);
}
return this;
};
Object.defineProperty(FluentAssignFactory.prototype, "fluentAssign", {
/**
* The FluentAssign instance.
*/
get: function () {
return this._fluentAssign;
},
enumerable: false,
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' }
*/
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) {
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.
* @param defaultValues An object representing default values for the instance.
* @param initialSetters A list of initial setters for the instance.
*/
FluentAssign.compose = function (defaultValues, initialSetters) {
return FluentAssign.composeWith(new FluentAssign(defaultValues, initialSetters));
};
/**
* Returns a FluentAssignFactory<Z> where Z is an instance of FluentAssign<?> or a derived
* class of it.
* @param fluentAssign An instance of FluentAssign<?> or a derived class of FluentAssign<?>.
*/
FluentAssign.composeWith = function (fluentAssign) {
return new FluentAssignFactory(fluentAssign);
};
FluentAssign.prototype.toJSON = function () {
var _this = this;
return getAssignedPropertyNames(this)
.reduce(function (obj, name) {
var key = privateKey(name);
// re-define property descriptors (we dont want their value)
var 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__() : {});
};
return FluentAssign;
}());
/**
* Simple object extend
* @param m1
* @param m2
*/
function extend(m1, m2) {
var m = {};
for (var attr in m1) {
if (m1.hasOwnProperty(attr)) {
m[attr] = m1[attr];
}
}
for (var attr in m2) {
if (m2.hasOwnProperty(attr)) {
m[attr] = m2[attr];
}
}
return m;
}
/**
* Simple, not optimized, array union of unique values.
* @param arr1
* @param arr2
*/
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
*/
function supportsKey(keyCode, config) {
if (!Array.isArray(config)) {
return config !== null;
}
return config.indexOf(keyCode) > -1;
}
/**
* Given an object representing a key/value map of css properties, returns a valid css string
* representing the object.
* Example:
* console.log(toStyleString({
* position: 'absolute',
* width: '100%',
* height: '100%',
* top: '0',
* left: '0',
* right: '0',
* bottom: '0'
* }));
* // position:absolute;width:100%;height:100%;top:0;left:0;right:0;bottom:0
* @param obj
*/
function toStyleString(obj) {
return Object.getOwnPropertyNames(obj)
.map(function (k) { return k + ":" + obj[k]; })
.join(';');
// let objStr = JSON.stringify(obj);
// return objStr.substr(1, objStr.length - 2)
// .replace(/,/g, ';')
// .replace(/"/g, '');
}
var PromiseCompleter = /** @class */ (function () {
function PromiseCompleter() {
var _this = this;
this.promise = new Promise(function (res, rej) {
_this.resolve = res;
_this.reject = rej;
});
}
return PromiseCompleter;
}());
function noop() {
}
function createComponent(instructions) {
var injector = instructions.injector || instructions.vcRef.injector;
var cmpFactory = injector.get(core.ComponentFactoryResolver).resolveComponentFactory(instructions.component);
if (instructions.vcRef) {
return instructions.vcRef.createComponent(cmpFactory, instructions.vcRef.length, injector, instructions.projectableNodes);
}
else {
return cmpFactory.create(injector);
}
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); };
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m)
if (!exports.hasOwnProperty(p))
exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function () {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
;
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n])
i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try {
step(g[n](v));
}
catch (e) {
settle(q[0][3], e);
} }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
}
else {
cooked.raw = raw;
}
return cooked;
}
;
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (Object.hasOwnProperty.call(mod, k))
result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
var DialogBailOutError = /** @class */ (function (_super) {
__extends(DialogBailOutError, _super);
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));
/**
* API to an open modal window.
*/
var DialogRef = /** @class */ (function () {
function DialogRef(overlay, context) {
this.overlay = overlay;
this.context = context;
this._resultDeferred = new PromiseCompleter();
this._onDestroy = new rxjs.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.
*/
get: function () {
return this._resultDeferred.promise;
},
enumerable: false,
configurable: true
});
/**
* Set a close/dismiss guard
* @param guard
*/
DialogRef.prototype.setCloseGuard = function (guard) {
this.closeGuard = guard;
};
/**
* Close the modal with a return value, i.e: result.
*/
DialogRef.prototype.close = function (result) {
var _this = this;
if (result === void 0) { result = null; }
var _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.
*/
DialogRef.prototype.dismiss = function () {
var _this = this;
var _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.
*/
DialogRef.prototype.bailOut = function () {
if (this.destroyed !== true) {
this.destroyed = true;
this._onDestroy.next(null);
this._onDestroy.complete();
this._resultDeferred.reject(new DialogBailOutError());
}
};
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();
}
}
};
DialogRef.prototype._destroy = function () {
this._onDestroy.next(null);
this._onDestroy.complete();
this.overlayRef.destroy();
};
DialogRef.prototype._fireHook = function (name) {
var guard = this.closeGuard, fn = guard && typeof guard[name] === 'function' && guard[name];
return Promise.resolve(fn ? fn.call(guard) : false);
};
return DialogRef;
}());
(function (DROP_IN_TYPE) {
DROP_IN_TYPE[DROP_IN_TYPE["alert"] = 0] = "alert";
DROP_IN_TYPE[DROP_IN_TYPE["prompt"] = 1] = "prompt";
DROP_IN_TYPE[DROP_IN_TYPE["confirm"] = 2] = "confirm";
})(exports.DROP_IN_TYPE || (exports.DROP_IN_TYPE = {}));
var OverlayRenderer = /** @class */ (function () {
function OverlayRenderer() {
}
return OverlayRenderer;
}());
var vcRefCollection = {};
function getVCRef(key) {
return vcRefCollection[key] ? vcRefCollection[key].slice() : [];
}
function setVCRef(key, vcRef) {
if (!vcRefCollection.hasOwnProperty(key)) {
vcRefCollection[key] = [];
}
vcRefCollection[key].push(vcRef);
}
function delVCRef(key, vcRef) {
if (!vcRef) {
vcRefCollection[key] = [];
}
else {
var coll = vcRefCollection[key] || [], 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 vcRefStore = { getVCRef: getVCRef, setVCRef: setVCRef, delVCRef: delVCRef };
/**
* 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)
*/
// tslint:disable-next-line:directive-class-suffix
var OverlayDialogBoundary = /** @class */ (function () {
function OverlayDialogBoundary(el, dialogRef) {
if (dialogRef && el.nativeElement) {
dialogRef.overlayRef.instance.setClickBoundary(el.nativeElement);
}
}
return OverlayDialogBoundary;
}());
OverlayDialogBoundary.decorators = [
{ type: core.Directive, args: [{
// tslint:disable-next-line:directive-selector
selector: '[overlayDialogBoundary]'
},] }
];
/** @nocollapse */
OverlayDialogBoundary.ctorParameters = function () { return [
{ type: core.ElementRef },
{ type: DialogRef }
]; };
// tslint:disable-next-line:directive-class-suffix
var OverlayTarget = /** @class */ (function () {
function OverlayTarget(vcRef) {
this.vcRef = vcRef;
}
Object.defineProperty(OverlayTarget.prototype, "targetKey", {
set: function (value) {
this._targetKey = value;
if (value) {
vcRefStore.setVCRef(value, this.vcRef);
}
},
enumerable: false,
configurable: true
});
OverlayTarget.prototype.ngOnDestroy = function () {
if (this._targetKey) {
vcRefStore.delVCRef(this._targetKey, this.vcRef);
}
};
return OverlayTarget;
}());
OverlayTarget.decorators = [
{ type: core.Directive, args: [{
// tslint:disable-next-line:directive-selector
selector: '[overlayTarget]'
},] }
];
/** @nocollapse */
OverlayTarget.ctorParameters = function () { return [
{ type: core.ViewContainerRef }
]; };
OverlayTarget.propDecorators = {
targetKey: [{ type: core.Input, args: ['overlayTarget',] }]
};
var BROWSER_PREFIX = ['webkit', 'moz', 'MS', 'o', ''];
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 () {
function BaseDynamicComponent(el, renderer) {
this.el = el;
this.renderer = renderer;
}
BaseDynamicComponent.prototype.activateAnimationListener = function () {
var _this = this;
if (this.animationEnd) {
return;
}
this.animationEnd = new rxjs.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
*/
BaseDynamicComponent.prototype.setStyle = function (prop, value) {
this.renderer.setStyle(this.el.nativeElement, prop, value);
return this;
};
BaseDynamicComponent.prototype.forceReflow = function () {
this.el.nativeElement.offsetWidth;
};
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();
}
};
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();
}
};
BaseDynamicComponent.prototype.ngOnDestroy = function () {
if (this.animationEnd && !this.animationEnd.closed) {
this.animationEnd.complete();
}
};
BaseDynamicComponent.prototype.myAnimationEnd$ = function () {
var _this = this;
return this.animationEnd$.pipe(operators.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.
*/
BaseDynamicComponent.prototype._addComponent = function (instructions) {
var cmpRef = createComponent(instructions);
cmpRef.changeDetectorRef.detectChanges();
return cmpRef;
};
BaseDynamicComponent.prototype.onEnd = function (event) {
if (!this.animationEnd.closed) {
this.animationEnd.next(event);
}
};
return BaseDynamicComponent;
}());
/**
* Represents the modal backdrop shaped by CSS.
*/
// tslint:disable-next-line:component-class-suffix
var CSSBackdrop = /** @class */ (function (_super) {
__extends(CSSBackdrop, _super);
function CSSBackdrop(el, renderer) {
var _this = _super.call(this, el, renderer) || this;
_this.activateAnimationListener();
var 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: core.Component, args: [{
// tslint:disable-next-line:component-selector
selector: 'css-backdrop',
host: {
'[attr.class]': 'cssClass',
'[attr.style]': 'styleStr'
},
encapsulation: core.ViewEncapsulation.None,
template: ""
},] }
];
/** @nocollapse */
CSSBackdrop.ctorParameters = function () { return [
{ type: core.ElementRef },
{ type: core.Renderer2 }
]; };
/**
* A component that acts as a top level container for an open modal window.
*/
// tslint:disable-next-line:component-class-suffix
var CSSDialogContainer = /** @class */ (function (_super) {
__extends(CSSDialogContainer, _super);
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: core.Component, args: [{
// tslint:disable-next-line:component-selector
selector: 'css-dialog-container',
host: {
'tabindex': '-1',
'role': 'dialog'
},
encapsulation: core.ViewEncapsulation.None,
template: "\n <ng-content></ng-content>"
},] }
];
/** @nocollapse */
CSSDialogContainer.ctorParameters = function () { return [
{ type: DialogRef },
{ type: core.ElementRef },
{ type: core.Renderer2 }
]; };
// export { FadeInBackdrop } from './fade-in-backdrop';
// export { SplitScreenBackdrop } from './split-screen-backdrop';
// TODO: use DI factory for this.
// TODO: consolidate dup code
var isDoc = !(typeof document === 'undefined' || !document);
/**
* Represents the modal overlay.
*/
// tslint:disable-next-line:component-class-suffix
var ModalOverlay = /** @class */ (function (_super) {
__extends(ModalOverlay, _super);
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
*/
ModalOverlay.prototype.getProjectables = function (content) {
var nodes;
if (typeof content === 'string') {
nodes = [[this.renderer.createText("" + content)]];
}
else if (content instanceof core.TemplateRef) {
nodes = [this.vcr.createEmbeddedView(content, { $implicit: this.dialogRef.context, dialogRef: this.dialogRef }).rootNodes];
}
else {
nodes = [this.embedComponent({ component: content }).rootNodes];
}
return nodes;
};
ModalOverlay.prototype.embedComponent = function (config) {
var ctx = config;
return this.vcr.createEmbeddedView(this.template, {
$implicit: ctx
});
};
ModalOverlay.prototype.addComponent = function (type, projectableNodes) {
if (projectableNodes === void 0) { projectableNodes = []; }
return _super.prototype._addComponent.call(this, {
component: type,
vcRef: this.innerVcr,
projectableNodes: projectableNodes
});
};
ModalOverlay.prototype.fullscreen = function () {
var _this = this;
var 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]); });
};
ModalOverlay.prototype.insideElement = function () {
var _this = this;
var 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
*/
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
*/
ModalOverlay.prototype.setClickBoundary = function (element) {
var _this = this;
var target;
var elListener = function (event) { return target = event.target; };
var docListener = function (event) {
if (_this.dialogRef.context.isBlocking || !_this.dialogRef.overlay.isTopMost(_this.dialogRef)) {
return;
}
var 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.
*/
ModalOverlay.prototype.canDestroy = function () {
var completer = new PromiseCompleter();
if (!Array.isArray(this.beforeDestroyHandlers)) {
completer.resolve();
}
else {
// run destroy notification but protect against halt.
var id_1 = setTimeout(function () {
id_1 = null;
completer.reject();
}, 1000);
var 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
*/
ModalOverlay.prototype.beforeDestroy = function (fn) {
if (!this.beforeDestroyHandlers) {
this.beforeDestroyHandlers = [];
}
this.beforeDestroyHandlers.push(fn);
};
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, this.dialogRef.context.keyboard)) {
this.dialogRef.dismiss();
}
};
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: core.Component, args: [{
// tslint:disable-next-line:component-selector
selector: 'modal-overlay',
encapsulation: core.ViewEncapsulation.None,
template: "<div #container>\r\n <ng-template #innerView></ng-template>\r\n</div>\r\n<ng-template #template let-ctx>\r\n <ng-container *ngComponentOutlet=\"ctx.component; injector: ctx.injector; content: ctx.projectableNodes\"></ng-container>\r\n</ng-template>"
},] }
];
/** @nocollapse */
ModalOverlay.ctorParameters = function () { return [
{ type: DialogRef },
{ type: core.ViewContainerRef },
{ type: core.ElementRef },
{ type: core.Renderer2 }
]; };
ModalOverlay.propDecorators = {
container: [{ type: core.ViewChild, args: ['container', { read: core.ElementRef, static: true },] }],
innerVcr: [{ type: core.ViewChild, args: ['innerView', { read: core.ViewContainerRef, static: true },] }],
template: [{ type: core.ViewChild, args: ['template', { static: true },] }],
documentKeypress: [{ type: core.HostListener, args: ['body:keydown', ['$event'],] }]
};
var BASKET_GROUP = {};
/**
* A dumb stack implementation over an array.
*/
var DialogRefStack = /** @class */ (function () {
function DialogRefStack() {
this._stack = [];
this._stackMap = new Map();
}
Object.defineProperty(DialogRefStack.prototype, "length", {
get: function () {
return this._stack.length;
},
enumerable: false,
configurable: true
});
DialogRefStack.prototype.closeAll = function (result) {
if (result === void 0) { result = null; }
for (var i = 0, len = this._stack.length; i < len; i++) {
this._stack.pop().close(result);
}
};
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
*/
DialogRefStack.prototype.pushManaged = function (dialogRef, group) {
var _this = this;
this.push(dialogRef, group);
dialogRef.onDestroy.subscribe(function () { return _this.remove(dialogRef); });
};
DialogRefStack.prototype.pop = function () {
var dialogRef = this._stack.pop();
this._stackMap.delete(dialogRef);
return dialogRef;
};
/**
* Remove a DialogRef from the stack.
* @param dialogRef
*/
DialogRefStack.prototype.remove = function (dialogRef) {
var idx = this.indexOf(dialogRef);
if (idx > -1) {
this._stack.splice(idx, 1);
this._stackMap.delete(dialogRef);
}
};
DialogRefStack.prototype.index = function (index) {
return this._stack[index];
};
DialogRefStack.prototype.indexOf = function (dialogRef) {
return this._stack.indexOf(dialogRef);
};
DialogRefStack.prototype.groupOf = function (dialogRef) {
return this._stackMap.get(dialogRef);
};
DialogRefStack.prototype.groupBy = function (group) {
var arr = [];
if (group) {
this._stackMap.forEach(function (value, key) {
if (value === group) {
arr.push(key);
}
});
}
return arr;
};
DialogRefStack.prototype.groupLength = function (group) {
var count = 0;
if (group) {
this._stackMap.forEach(function (value) {
if (value === group) {
count++;
}
});
}
return count;
};
return DialogRefStack;
}());
var _stack = new DialogRefStack();
var Overlay = /** @class */ (function () {
function Overlay(_modalRenderer, injector) {
this._modalRenderer = _modalRenderer;
this.injector = injector;
}
Object.defineProperty(Overlay.prototype, "stackLength", {
get: function () {
return _stack.length;
},
enumerable: false,
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
*/
Overlay.prototype.isTopMost = function (dialogRef) {
return _stack.indexOf(dialogRef) === _stack.length - 1;
};
Overlay.prototype.stackPosition = function (dialogRef) {
return _stack.indexOf(dialogRef);
};
Overlay.prototype.groupStackLength = function (dialogRef) {
return _stack.groupLength(_stack.groupOf(dialogRef));
};
Overlay.prototype.closeAll = function (result) {
if (result === void 0) { result = null; }
_stack.closeAll(result);
};
/**
* Creates an overlay and returns a dialog ref.
* @param config instructions how to create the overlay
* @param group A token to associate the new overlay with, used for reference (stacks usually)
*/
Overlay.prototype.open = function (config, group) {
var _this = this;
var viewContainer = config.viewContainer;
var containers = [];
if (typeof viewContainer === 'string') {
containers = vcRefStore.getVCRef(viewContainer);
}
else if (Array.isArray(viewContainer)) {
containers = viewContainer;
}
else if (viewContainer) {
containers = [viewContainer];
}
else {
containers = [null];
}
return containers
.map(function (vc) { return _this.createOverlay(config.renderer || _this._modalRenderer, vc, config, group); });
};
Overlay.prototype.createOverlay = function (renderer, vcRef, config, group) {
if (config.context) {
config.context.normalize();
}
if (!config.injector) {
config.injector = this.injector;
}
var dialog = new DialogRef(this, config.context || {});
dialog.inElement = config.context && !!config.context.inElement;
var cmpRef = renderer.render(dialog, vcRef, config.injector);
Object.defineProperty(dialog, 'overlayRef', { value: cmpRef });
_stack.pushManaged(dialog, group);
return dialog;
};
return Overlay;
}());
Overlay.decorators = [
{ type: core.Injectable }
];
/** @nocollapse */
Overlay.ctorParameters = function () { return [
{ type: OverlayRenderer },
{ type: core.Injector }
]; };
var DOMOverlayRenderer = /** @class */ (function () {
function DOMOverlayRenderer(appRef, injector) {
this.appRef = appRef;
this.injector = injector;
this.isDoc = !(typeof document === 'undefined' || !document);
}
DOMOverlayRenderer.prototype.render = function (dialog, vcRef, injector) {
var _this = this;
if (!injector) {
injector = this.injector;
}
var cmpRef = createComponent({
component: ModalOverlay,
vcRef: vcRef,
injector: core.Injector.create({
providers: [
{ provide: DialogRef, useValue: dialog }
],
parent: 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: core.Injectable }
];
/** @nocollapse */
DOMOverlayRenderer.ctorParameters = function () { return [
{ type: core.ApplicationRef },
{ type: core.Injector }
]; };
function unsupportedDropInError(dropInName) {
return new Error("Unsupported Drop-In " + dropInName);
}
var Modal = /** @class */ (function () {
function Modal(overlay) {
this.overlay = overlay;
}
Modal.prototype.alert = function () {
throw unsupportedDropInError('alert');
};
Modal.prototype.prompt = function () {
throw unsupportedDropInError('prompt');
};
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.
*/
Modal.prototype.open = function (content, config) {
config = config || {};
var 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);
};
Modal.prototype.createBackdrop = function (dialogRef, BackdropComponent) {
return dialogRef.overlayRef.instance.addComponent(BackdropComponent);
};
Modal.prototype.createContainer = function (dialogRef, ContainerComponent, content) {
var nodes = dialogRef.overlayRef.instance.getProjectables(content);
return dialogRef.overlayRef.instance.addComponent(ContainerComponent, nodes);
};
return Modal;
}());
// heavily inspired by:
// TODO: use DI factory for this.
// TODO: consolidate dup code
var isDoc$1 = !(typeof document === 'undefined' || !document);
var 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
*/
function bubbleNonAncestorHandlerFactory(element, handler) {
return function (event) {
var 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 = noop;
}
}
DOMOutsideEventPlugin.prototype.supports = function (eventName) {
return eventMap.hasOwnProperty(eventName);
};
DOMOutsideEventPlugin.prototype.addEventListener = function (element, eventName, handler) {
var 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.
var onceOnOutside = function () {
var listener = bubbleNonAncestorHandlerFactory(element, function (evt) { return zone.runGuarded(function () { return handler(evt); }); });
// mimic BrowserDomAdapter.onAndCancel
document.addEventListener(eventMap[eventName], listener, false);
return function () { 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(function () {
var fn;
setTimeout(function () { return fn = onceOnOutside(); }, 0);
return function () {
if (fn) {
fn();
}
};
});
};
return DOMOutsideEventPlugin;
}());
DOMOutsideEventPlugin.decorators = [
{ type: core.Injectable }
];
/** @nocollapse */
DOMOutsideEventPlugin.ctorParameters = function () { return []; };
var ɵ0 = function supportsKey(keyCode) {
return this.keyboard.indexOf(keyCode) > -1;
};
var DEFAULT_VALUES = {
inElement: false,
isBlocking: true,
keyboard: [27],
supportsKey: ɵ0
};
var DEFAULT_SETTERS = [
'inElement',
'isBlocking',
'keyboard'
];
var OverlayContext = /** @class */ (function () {
function OverlayContext() {
}
OverlayContext.prototype.normalize = function () {
if (this.isBlocking !== false) {
this.isBlocking = true;
}
if (this.keyboard === null) {
this.keyboard = [];
}
else if (typeof this.keyboard === 'number') {
this.keyboard = [this.keyboard];
}
else if (!Array.isArray(this.keyboard)) {
this.keyboard = DEFAULT_VALUES.keyboard;
}
};
return OverlayContext;
}());
/**
* A core context builder for a modal window instance, used to define the context upon
* a modal choose it's behaviour.
*/
var OverlayContextBuilder = /** @class */ (function (_super) {
__extends(OverlayContextBuilder, _super);
function OverlayContextBuilder(defaultValues, initialSetters, baseType) {
return _super.call(this, extend(DEFAULT_VALUES, defaultValues || {}), arrayUnion(DEFAULT_SETTERS, initialSetters || []), baseType || OverlayContext // https://github.com/Microsoft/TypeScript/issues/7234
) || this;
}
/**
* Returns an new OverlayConfig with a context property representing the data in this builder.
* @param base A base configuration that the result will extend
*/
OverlayContextBuilder.prototype.toOverlayConfig = function (base) {
return extend(base || {}, {
context: this.toJSON()
});
};
return OverlayContextBuilder;
}(FluentAssign));
/**
* 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.
*
* @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
*/
function overlayConfigFactory(context, baseContextType, baseConfig) {
return new OverlayContextBuilder(context, undefined, baseContextType).toOverlayConfig(baseConfig);
}
var DEFAULT_VALUES$1 = {};
var DEFAULT_SETTERS$1 = [
'message'
];
var ModalContext = /** @class */ (function (_super) {
__extends(ModalContext, _super);
function ModalContext() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ModalContext;
}(OverlayContext));
/**
* A core context builder for a modal window instance, used to define the context upon
* a modal choose it's behaviour.
*/
var ModalContextBuilder = /** @class */ (function (_super) {
__extends(ModalContextBuilder, _super);
function ModalContextBuilder(defaultValues, initialSetters, baseType) {
return _super.call(this, extend(DEFAULT_VALUES$1, defaultValues || {}), arrayUnion(DEFAULT_SETTERS$1, initialSetters || []), baseType) || this;
}
return ModalContextBuilder;
}(OverlayContextBuilder));
var DEFAULT_SETTERS$2 = [
'component'
];
var ModalOpenContext = /** @class */ (function (_super) {
__extends(ModalOpenContext, _super);
function ModalOpenContext() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ModalOpenContext;
}(ModalContext));
/**
* A Modal Context that knows about the modal service, and so can open a modal window on demand.
* Use the fluent API to configure the preset and then invoke the 'open' method to open a modal
* based on the context.
*/
var ModalOpenContextBuilder = /** @class */ (function (_super) {
__extends(ModalOpenContextBuilder, _super);
function ModalOpenContextBuilder(defaultValues, initialSetters, baseType) {
return _super.call(this, defaultValues || {}, arrayUnion(DEFAULT_SETTERS$2, initialSetters || []), baseType) || this;
}
/**
* Hook to alter config and return bindings.
* @param config
*/
ModalOpenContextBuilder.prototype.$$beforeOpen = function (config) { };
/**
* Open a modal window based on the configuration of this config instance.
* @param viewContainer If set opens the modal inside the supplied viewContainer
*/
ModalOpenContextBuilder.prototype.open = function (viewContainer) {
var context = this.toJSON();
if (!(context.modal instanceof Modal)) {
return Promise.reject(new Error('Configuration Error: modal service not set.'));
}
this.$$beforeOpen(context);
var overlayConfig = {
context: context,
viewContainer: viewContainer
};
return context.modal.open(context.component, overlayConfig);
};
return ModalOpenContextBuilder;
}(ModalContextBuilder));
var ModalModule = /** @class */ (function () {
function ModalModule() {
}
/**
* Returns a ModalModule pre-loaded with a list of dynamically inserted components.
* Since dynamic components are not analysed by the angular compiler they must register manually
* using entryComponents, this is an easy way to do it.
* @param entryComponents A list of dynamically inserted components (dialog's).
*/
ModalModule.withComponents = function (entryComponents) {
return {
ngModule: ModalModule,
providers: [
{ provide: core.ANALYZE_FOR_ENTRY_COMPONENTS, useValue: entryComponents, multi: true }
]
};
};
/**
* Returns a NgModule for use in the root Module.
* @param entryComponents A list of dynamically inserted components (dialog's).
*/
ModalModule.forRoot = function (entryComponents) {
return {
ngModule: ModalModule,
providers: [
{ provide: OverlayRenderer, useClass: DOMOverlayRenderer },
{ provide: platformBrowser.EVENT_MANAGER_PLUGINS, useClass: DOMOutsideEventPlugin, multi: true },
{ provide: core.ANALYZE_FOR_ENTRY_COMPONENTS, useValue: entryComponents || [], multi: true }
]
};
};
return ModalModule;
}());
ModalModule.decorators = [
{ type: core.NgModule, args: [{
declarations: [
ModalOverlay,
CSSBackdrop,
CSSDialogContainer,
OverlayDialogBoundary,
OverlayTarget
],
imports: [common.CommonModule],
exports: [
CSSBackdrop,
CSSDialogContainer,
OverlayDialogBoundary,
OverlayTarget
],
providers: [
Overlay
],
entryComponents: [
ModalOverlay,
CSSBackdrop,
CSSDialogContainer
]
},] }
];
/**
* Generated bundle index. Do not edit.
*/
exports.BaseDynamicComponent = BaseDynamicComponent;
exports.CSSBackdrop = CSSBackdrop;
exports.CSSDialogContainer = CSSDialogContainer;
exports.DEFAULT_VALUES = DEFAULT_VALUES$1;
exports.DOMOverlayRenderer = DOMOverlayRenderer;
exports.DialogBailOutError = DialogBailOutError;
exports.DialogRef = DialogRef;
exports.FluentAssign = FluentAssign;
exports.FluentAssignFactory = FluentAssignFactory;
exports.Modal = Modal;
exports.ModalContext = ModalContext;
exports.ModalContextBuilder = ModalContextBuilder;
exports.ModalModule = ModalModule;
exports.ModalOpenContext = ModalOpenContext;
exports.ModalOpenContextBuilder = ModalOpenContextBuilder;
exports.ModalOverlay = ModalOverlay;
exports.Overlay = Overlay;
exports.OverlayContext = OverlayContext;
exports.OverlayContextBuilder = OverlayContextBuilder;
exports.OverlayDialogBoundary = OverlayDialogBoundary;
exports.OverlayRenderer = OverlayRenderer;
exports.OverlayTarget = OverlayTarget;
exports.PromiseCompleter = PromiseCompleter;
exports.arrayUnion = arrayUnion;
exports.createComponent = createComponent;
exports.extend = extend;
exports.overlayConfigFactory = overlayConfigFactory;
exports.privateKey = privateKey;
exports.setAssignAlias = setAssignAlias;
exports.setAssignMethod = setAssignMethod;
exports.ɵa = DOMOutsideEventPlugin;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=ngx-modialog-11.umd.js.map