vuedl
Version:
Vue dialog helper
1,150 lines (940 loc) • 28.4 kB
JavaScript
import Vue from 'vue';
import { ensureComponentAsyncData, hasAsyncPreload } from 'vue-asyncable';
var Recordable = {
computed: {
$parameters: function $parameters() {
return this.$attrs || this.$options.propsData || this.$props || {};
},
isNewRecord: function () {
// console.log(this.$attrs, this.$props)
// const data = this.$attrs || this.$options.propsData || this.$props
return !this.$parameters || !this.$parameters[this.$options.primaryKey];
}
}
};
var Activable = {
name: 'Activable',
data: function data() {
return {
isActive: false
};
},
watch: {
isActive: function isActive(val) {
if (this._dialogInstance) {
if (this._dialogInstance.isActive !== undefined) {
this._dialogInstance.isActive = val;
}
} else {
if (this.$parent && this.$parent.isActive !== undefined) {
this.$parent.isActive = val;
}
}
}
},
methods: {
close: function close() {
this.isActive = false;
}
}
};
var Layoutable = {
name: 'Layoutable',
mixins: [Activable],
inheritAttrs: false,
props: {
width: {
type: [String, Number],
default: function () { return 450; }
},
persistent: Boolean
},
data: function data() {
return {
loading: false
};
},
computed: {
isLayout: function isLayout() {
return true;
},
getWidth: function getWidth() {
return typeof this.width === 'string' ? this.width : this.width + 'px';
}
},
watch: {
isActive: function isActive(val) {
if (!val) {
this._destroy();
}
}
},
mounted: function mounted() {
this.isActive = true;
},
methods: {
_destroy: function _destroy() {
this.$destroy();
},
dismiss: function dismiss() {
if (!this.persistent && !this.loading) {
this.isActive = false;
}
},
close: function close() {
this.isActive = false;
}
},
beforeDestroy: function beforeDestroy() {
if (typeof this.$el.remove === 'function') {
this.$el.remove();
} else if (this.$el.parentNode) {
this.$el.parentNode.removeChild(this.$el);
}
}
};
//
//
//
//
//
//
var script = {};
function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier
/* server only */
, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
if (typeof shadowMode !== 'boolean') {
createInjectorSSR = createInjector;
createInjector = shadowMode;
shadowMode = false;
} // Vue.extend constructor export interop.
var options = typeof script === 'function' ? script.options : script; // render functions
if (template && template.render) {
options.render = template.render;
options.staticRenderFns = template.staticRenderFns;
options._compiled = true; // functional template
if (isFunctionalTemplate) {
options.functional = true;
}
} // scopedId
if (scopeId) {
options._scopeId = scopeId;
}
var hook;
if (moduleIdentifier) {
// server build
hook = function hook(context) {
// 2.3 injection
context = context || // cached call
this.$vnode && this.$vnode.ssrContext || // stateful
this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__;
} // inject component styles
if (style) {
style.call(this, createInjectorSSR(context));
} // register component module identifier for async chunk inference
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier);
}
}; // used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook;
} else if (style) {
hook = shadowMode ? function () {
style.call(this, createInjectorShadow(this.$root.$options.shadowRoot));
} : function (context) {
style.call(this, createInjector(context));
};
}
if (hook) {
if (options.functional) {
// register for functional component in vue file
var originalRender = options.render;
options.render = function renderWithStyleInjection(h, context) {
hook.call(context);
return originalRender(h, context);
};
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate;
options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
}
}
return script;
}
var normalizeComponent_1 = normalizeComponent;
/* script */
var __vue_script__ = script;
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"dialog-layout"},[_c('dialog-child',_vm._b({ref:"dialog"},'dialog-child',_vm.$options.propsData,false))],1)};
var __vue_staticRenderFns__ = [];
/* style */
var __vue_inject_styles__ = undefined;
/* scoped */
var __vue_scope_id__ = undefined;
/* module identifier */
var __vue_module_identifier__ = undefined;
/* functional template */
var __vue_is_functional_template__ = false;
/* style inject */
/* style inject SSR */
var DefaultLayout = normalizeComponent_1(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
undefined,
undefined
);
/*
* vuedl
*
* (c) Savaryn Yaroslav <yariksav@gmail.com>
*
* Some functions was imported from nuxt.js/lib/app/utils.js
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
function destroyVueElement(vm) {
if (vm && !vm._isDestroyed && typeof vm.$destroy === 'function') {
vm.$destroy();
}
}
function findContainer(container) {
var found;
if (typeof container === 'string') {
found = document.querySelector(container);
} else {
found = container;
}
if (!found) {
found = document.body;
}
return found;
} // todo
// export function middlewareSeries (promises, appContext) {
// if (!promises.length || appContext._redirected || appContext._errored) {
// return Promise.resolve()
// }
// return promisify(promises[0], appContext)
// .then(() => {
// return middlewareSeries(promises.slice(1), appContext)
// })
// }
/*
* vuedl
*
* (c) Savaryn Yaroslav <yariksav@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var seed = 1;
var Dialog = function Dialog(component, ref) {
if ( ref === void 0 ) ref = {};
var layout = ref.layout;
var container = ref.container;
if (!component) {
throw Error('Component was not set');
}
this._layout = layout || {
component: DefaultLayout,
options: {}
};
this._component = component;
this._vm = null;
this._vmDialog = null;
this._options = {};
this.id = ++seed;
this._resolvers = [];
this.container = findContainer(container);
};
var prototypeAccessors = { showed: { configurable: true },element: { configurable: true },hasAsyncPreload: { configurable: true },vm: { configurable: true },vmd: { configurable: true } };
Dialog.prototype.show = function show (params, options) {
if ( params === void 0 ) params = {};
if ( options === void 0 ) options = {};
return new Promise(function ($return, $error) {
var Component, LayoutCtor, propsData, layout, dialog, container;
if (Vue.prototype.$isServer) {
return $return();
} // create dialog
Component = this._component;
if (typeof Component === 'object' && !Component.options) {
Component = Vue.extend(Object.assign({}, this._component));
} // add primary key mixin
if (Component.options.primaryKey) {
Component = Component.extend({
mixins: [Recordable]
});
}
if (this.hasAsyncPreload) {
return Promise.resolve(ensureComponentAsyncData(Component, Object.assign({}, this.context, {
params: params
}))).then(function ($await_2) {
try {
return $If_1.call(this);
} catch ($boundEx) {
return $error($boundEx);
}
}.bind(this), $error);
} // create layout
function $If_1() {
LayoutCtor = Vue.extend({
mixins: [Layoutable],
components: {
'dialog-child': Component
}
});
LayoutCtor = LayoutCtor.extend(this._layout.component);
Component.options.inheritAttrs = false;
propsData = Object.assign({}, this._layout.options, params, options && options.propsData);
layout = new LayoutCtor(Object.assign({}, this.context, options, {
propsData: propsData
}));
layout.$mount();
dialog = layout.$refs.dialog;
// if (!dialog) {
// throw Error('You heave to provide dialog-child component in layout: <dialog-child v-bind="$options.propsData" ref="dialog" />')
// }
layout.$on('hook:destroyed', this._onDestroyed.bind(this));
layout.$on('submit', this.onReturn.bind(this));
dialog && dialog.$on('submit', this.onReturn.bind(this));
this._vm = layout;
this._vm._dialogInstance = dialog;
this._vmDialog = dialog;
container = params.container ? findContainer(params.container) : this.container;
container.appendChild(layout.$el);
return $return(this);
}
return $If_1.call(this);
}.bind(this));
};
Dialog.prototype.wait = function wait () {
var this$1 = this;
return new Promise(function (resolve) {
this$1._resolvers.push(resolve);
});
};
Dialog.prototype._onDestroyed = function _onDestroyed () {
this.remove();
};
Dialog.prototype.remove = function remove () {
this.onDestroyed && this.onDestroyed(this);
this._processResultPromises();
destroyVueElement(this._vm);
destroyVueElement(this._vmDialog);
this._vm = null;
this._vmDialog = null;
};
Dialog.prototype._processResultPromises = function _processResultPromises (result) {
if (!this._resolvers.length) {
return;
}
this._resolvers.forEach(function (resolver) { return resolver(result); });
this._resolvers = [];
};
Dialog.prototype.onReturn = function onReturn (result) {
this._processResultPromises(result);
this.close();
};
prototypeAccessors.showed.get = function () {
return !!this._vm && !this._vm._isDestroyed;
};
prototypeAccessors.element.get = function () {
return this._vm && this._vm.$el;
};
prototypeAccessors.hasAsyncPreload.get = function () {
return this._component && hasAsyncPreload(this._component.options || this._component);
};
prototypeAccessors.vm.get = function () {
return this._vm;
};
prototypeAccessors.vmd.get = function () {
return this._vmDialog;
};
Dialog.prototype.close = function close () {
this._vm && this._vm.close();
};
Object.defineProperties( Dialog.prototype, prototypeAccessors );
/*
* vuedl
*
* (c) Savaryn Yaroslav <yariksav@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var Overlay = function Overlay(component) {
this._component = component;
this._vm = null;
};
Overlay.prototype.show = function show () {
if (!this._vm) {
var Ctor = Vue.extend(this._component);
this._vm = new Ctor();
this._vm.$mount();
document.body.appendChild(this._vm.$el);
}
this._vm.visible = true;
};
Overlay.prototype.hide = function hide () {
this._vm.visible = false;
};
Overlay.prototype.destroy = function destroy () {
if (this._vm) {
this._vm.$el.parentNode.removeChild(this._vm.$el);
this._vm.$destroy();
this._vm = null;
}
};
/*
* vuedl
*
* (c) Savaryn Yaroslav <yariksav@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var DialogManager = function DialogManager(ref) {
if ( ref === void 0 ) ref = {};
var context = ref.context;
var container = ref.container;
this._context = context || {};
Dialog.prototype.context = context || {};
this._components = {};
this._layouts = {};
this._overlays = {};
this._container = container;
this._emitter = new Vue({});
this._instances = [];
};
var prototypeAccessors$1 = { context: { configurable: true } };
prototypeAccessors$1.context.get = function () {
return this._context;
};
DialogManager.prototype.layout = function layout (name, component, options) {
if ( options === void 0 ) options = {};
this._layouts[name] = {
component: component,
options: options
};
};
DialogManager.prototype.getLayout = function getLayout (layout) {
if (typeof layout === 'function') {
var options = layout.call(this._context);
layout = this._layouts[options.name || 'default'];
return Object.assign({}, layout, {
options: options
});
}
if (typeof layout === 'object' && typeof layout.render === 'function') {
return {
component: layout
};
}
if (Array.isArray(layout)) {
var nameTmp = layout[0];
var optionsTmp = layout[1] || {};
var instance = typeof nameTmp === 'object' && typeof nameTmp.render === 'function' ? {
component: nameTmp
} : this._layouts[nameTmp];
return instance && {
component: instance.component,
options: Object.assign({}, instance.options, optionsTmp)
};
}
return this._layouts[layout];
};
DialogManager.prototype.overlay = function overlay (name, component) {
if (component === undefined) {
if (this._overlays[name]) {
return this._overlays[name];
} else {
throw new Error(("Overlay \"" + name + " not found\n Please register it by calling dialog.overlay('" + name + "', component)"));
}
}
this._overlays[name] = new Overlay(component);
};
DialogManager.prototype.getComponent = function getComponent (name) {
if (!this._components[name]) {
throw new Error(("Component \"" + name + "\" was not found.\n Please register it by calling dialog.register('" + name + "', component)"));
}
return this._components[name];
};
DialogManager.prototype.component = function component (name, component$1, options) {
var this$1 = this;
if ( options === void 0 ) options = {};
if (component$1 === undefined) {
return this._components[name];
}
this._components[name] = {
component: component$1,
options: options
};
Object.defineProperty(this, name, {
get: function () { return this$1.createFunctionWrapper(name); }
});
};
DialogManager.prototype.getComponentProperty = function getComponentProperty (component, name) {
return component.options ? component.options[name] : component[name];
};
DialogManager.prototype.create = function create (component) {
if (!component) {
throw new Error('Component is incorrect');
}
var layout = this.getLayout(this.getComponentProperty(component, 'layout') || 'default');
var dlg = new Dialog(component, {
layout: layout,
context: this._context,
container: this._container
});
this._emitter.$emit('created', {
dialog: dlg
});
return dlg;
};
DialogManager.prototype.show = function show (component, params) {
if ( params === void 0 ) params = {};
return new Promise(function ($return, $error) {
var dlg, overlayName, overlay;
dlg = this.create(component);
overlayName = dlg.hasAsyncPreload ? this.getComponentProperty(component, 'overlay') || 'default' : false;
overlay = overlayName && this._overlays[overlayName] && this.overlay(overlayName);
overlay && overlay.show();
var $Try_1_Catch = function (e) {
try {
this._emitter.$emit('error', {
error: e,
dialog: dlg
});
overlay && overlay.hide();
throw e;
} catch ($boundEx) {
return $error($boundEx);
}
}.bind(this);
try {
return Promise.resolve(dlg.show(params)).then(function ($await_2) {
try {
this._emitter.$emit('shown', {
dialog: dlg
});
overlay && overlay.hide();
dlg.onDestroyed = this.onDialogDestroyed.bind(this);
return $return(params.waitForResult ? dlg.wait() : dlg);
} catch ($boundEx) {
return $Try_1_Catch($boundEx);
}
}.bind(this), $Try_1_Catch);
} catch (e) {
$Try_1_Catch(e);
}
}.bind(this));
};
DialogManager.prototype.createFunctionWrapper = function createFunctionWrapper (name) {
var this$1 = this;
var cmp = this.getComponent(name);
return function (options) { return this$1.show(cmp.component, Object.assign({}, cmp.options, options)); };
};
DialogManager.prototype.showAndWait = function showAndWait (component, props) {
return new Promise(function ($return, $error) {
var dlg;
return Promise.resolve(this.show(component, props)).then(function ($await_3) {
try {
dlg = $await_3;
return $return(dlg.wait());
} catch ($boundEx) {
return $error($boundEx);
}
}, $error);
}.bind(this));
};
DialogManager.prototype.on = function on (event, callback) {
this._emitter.$on(event, callback);
};
DialogManager.prototype.off = function off (event, callback) {
this._emitter.$off(event, callback);
};
DialogManager.prototype.once = function once (event, callback) {
this._emitter.$once(event, callback);
};
DialogManager.prototype.onDialogDestroyed = function onDialogDestroyed (dialog) {
this._emitter.$emit('destroyed', {
dialog: dialog
});
};
Object.defineProperties( DialogManager.prototype, prototypeAccessors$1 );
//
//
//
//
//
//
//
//
//
//
//
//
var script$1 = {
name: 'VDialogOverlay',
props: {
zIndex: {
type: Number,
default: function () { return 1250; }
},
visible: {
type: Boolean,
default: function () { return false; }
}
}
};
/* script */
var __vue_script__$1 = script$1;
/* template */
var __vue_render__$1 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('transition',{attrs:{"name":"opacity"}},[(_vm.visible)?_c('div',{staticClass:"dialog-overlay-loading",style:({zIndex: _vm.zIndex})},[_vm._v("\n Loading…\n ")]):_vm._e()])};
var __vue_staticRenderFns__$1 = [];
/* style */
var __vue_inject_styles__$1 = undefined;
/* scoped */
var __vue_scope_id__$1 = undefined;
/* module identifier */
var __vue_module_identifier__$1 = undefined;
/* functional template */
var __vue_is_functional_template__$1 = false;
/* style inject */
/* style inject SSR */
var Overlay$1 = normalizeComponent_1(
{ render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 },
__vue_inject_styles__$1,
__vue_script__$1,
__vue_scope_id__$1,
__vue_is_functional_template__$1,
__vue_module_identifier__$1,
undefined,
undefined
);
/* @vue/component */
var Returnable = {
name: 'Returnable',
props: {
returnValue: null
},
data: function data() {
return {
originalValue: this.returnValue,
returnResovers: []
};
},
methods: {
return: function return$1(value) {
this.originalValue = value;
this.$root.$emit('submit', this.originalValue);
this.$emit('submit', this.originalValue);
}
}
};
var actionable = {
name: 'Actionable',
mixins: [Returnable],
data: function data() {
return {
loadingAction: null
};
},
props: {
actions: {
type: [Array, Object, Function],
default: function () { return []; }
},
handle: Function,
params: Object
},
computed: {
actionlist: function actionlist() {
var actions = [];
var acts = typeof this.actions === 'function' ? this.actions(this) : this.actions || [];
for (var key in acts) {
var action = acts[key];
if (typeof action === 'string') {
action = {
text: action
};
}
if (!action.key) {
action.key = isNaN(key) ? key : action.text || key;
}
if (['true', 'false'].indexOf(action.key) >= 0) {
action.key = JSON.parse(action.key);
}
if (!this.isActionVisible(action)) {
continue;
}
if (typeof action.icon === 'string') {
action.icon = {
text: action.icon
};
}
actions.push(action);
}
return actions;
}
},
methods: {
trigger: function trigger(name) {
var action = this.actionlist.find(function (action) { return action.key === name; });
if (action && !this.isActionDisabled(action) && this.isActionVisible(action)) {
this.onActionClick(action);
}
},
setLoadingToInstance: function setLoadingToInstance(vm, value) {
if (vm && vm.loading !== undefined) {
vm.loading = value;
}
},
setLoadingState: function setLoadingState(value) {
this.$emit('loading', value);
!value && (this.loadingAction = null);
this.setLoadingToInstance(this.$root, value);
this.setLoadingToInstance(this.$root._dialogInstance, value);
},
get: function get(param, def) {
if (param === undefined) {
return def;
}
if (typeof param === 'function') {
return param(this.params);
}
return param;
},
isActionDisabled: function isActionDisabled(action) {
return this.get(action.disabled, false);
},
isActionVisible: function isActionVisible(action) {
return this.get(action.visible, true);
},
isActionInLoading: function isActionInLoading(action) {
return this.loadingAction === action.key || this.get(action.loading);
},
onActionClick: function onActionClick(action) {
return new Promise(function ($return, $error) {
var closable, handle;
closable = action.closable === undefined || action.closable === true;
handle = action.handle || this.handle;
if (typeof handle === 'function') {
this.loadingAction = action.key;
this.setLoadingState(true);
var $Try_1_Post = function () {
try {
return $If_2.call(this);
} catch ($boundEx) {
return $error($boundEx);
}
}.bind(this);
var $Try_1_Catch = function (e) {
try {
this.setLoadingState(false);
console.log('error', e); // TODO
throw e;
} catch ($boundEx) {
return $error($boundEx);
}
}.bind(this);
try {
var ret;
return Promise.resolve(handle(this.params, action)).then(function ($await_3) {
try {
ret = $await_3;
this.setLoadingState(false);
if (ret !== false && closable) {
this.return(ret || action.key);
}
return $Try_1_Post();
} catch ($boundEx) {
return $Try_1_Catch($boundEx);
}
}.bind(this), $Try_1_Catch);
} catch (e) {
$Try_1_Catch(e);
}
} else {
closable && this.return(action.key);
return $If_2.call(this);
}
function $If_2() {
return $return();
}
}.bind(this));
}
}
};
var confirmable = {
name: 'Confirmable',
props: {
type: {
type: String
},
text: {
type: [String, Function],
reqiured: true
},
title: {
type: String
},
actions: {
type: [Array, Object, Function]
}
}
};
var notifications = [];
var gap = 10;
var insertNotification = function (vm) {
var position = vm.position;
var verticalOffset = gap;
notifications.filter(function (item) { return item.position === position; }).forEach(function (item) {
verticalOffset += item.$el.offsetHeight + gap;
});
notifications.push(vm);
vm.verticalOffset = verticalOffset;
};
var deleteNotification = function (vm) {
var index = notifications.findIndex(function (instance) { return instance === vm; });
if (index < 0) {
return;
}
notifications.splice(index, 1);
var len = notifications.length;
var position = vm.position;
if (!len) { return; }
var verticalOffset = gap;
notifications.filter(function (item) { return item.position === position; }).forEach(function (item) {
item.verticalOffset = verticalOffset;
verticalOffset += item.$el.offsetHeight + gap;
});
};
var notifiable = {
props: {
verticalOffset: Number,
showClose: {
type: Boolean,
default: function () { return true; }
},
position: {
type: String,
default: function () { return 'top-right'; }
},
timeout: {
type: [Number, Boolean],
default: function () { return 4500; }
},
width: {
type: Number,
default: function () { return 330; }
},
zIndex: {
type: Number,
default: function () { return 2000; }
}
},
data: function data() {
return {
activeTimeout: null
};
},
computed: {
horizontalClass: function horizontalClass() {
return this.position.indexOf('right') > -1 ? 'right' : 'left';
},
verticalProperty: function verticalProperty() {
return /^top-/.test(this.position) ? 'top' : 'bottom';
},
getStyle: function getStyle() {
var obj;
return ( obj = {}, obj[this.verticalProperty] = ((this.verticalOffset) + "px"), obj['max-width'] = ((this.width) + "px"), obj['z-index'] = this.zIndex, obj );
}
},
methods: {
_destroy: function _destroy() {
this.$el.addEventListener('transitionend', this.onTransitionEnd);
},
onTransitionEnd: function onTransitionEnd() {
this.$el.removeEventListener('transitionend', this.onTransitionEnd);
this.$destroy();
},
clearTimer: function clearTimer() {
clearTimeout(this.activeTimeout);
},
startTimer: function startTimer() {
if (this.timeout > 0) {
this.activeTimeout = setTimeout(this.close, this.timeout);
}
},
keydown: function keydown(e) {
if (e.keyCode === 46 || e.keyCode === 8) {
this.clearTimer(); // delete key
} else if (e.keyCode === 27) {
// esc key
this.close();
} else {
this.startTimer(); // any key
}
},
close: function close() {
this.isActive = false;
}
},
watch: {
isActive: function isActive(val) {
if (val) {
insertNotification(this);
} else {
deleteNotification(this);
}
}
},
mounted: function mounted() {
this.startTimer();
document.addEventListener('keydown', this.keydown);
},
beforeDestroy: function beforeDestroy() {
document.removeEventListener('keydown', this.keydown);
}
};
/* eslint-disable import/prefer-default-export */
// Import vue components
function install(Vue$$1, options) {
if ( options === void 0 ) options = {};
if (install.installed) { return; }
install.installed = true;
var property = options.property || '$dialog';
var manager = new DialogManager(options);
manager.overlay('default', Overlay$1);
if (!Vue$$1.prototype[property]) {
Object.defineProperty(Vue$$1.prototype, property, {
get: function get() {
return manager;
}
});
} else {
console.warn(("Property " + property + " is already defined in Vue prototype"));
}
} // Create module definition for Vue.use()
var plugin = {
install: install // To auto-install when vue is found
/* global window global */
};
var GlobalVue = null;
if (typeof window !== 'undefined') {
GlobalVue = window.Vue;
} else if (typeof global !== 'undefined') {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(plugin);
} // To allow use as module (npm/webpack/etc.) export components
export default plugin;
export { actionable as Actionable, Activable, confirmable as Confirmable, notifiable as Notifiable, Recordable, Returnable };