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