Skip to content

Instantly share code, notes, and snippets.

@jittagornp
Last active January 29, 2017 09:34
Show Gist options
  • Save jittagornp/7df0a6990409d47c1c8b82b6bf4e2e12 to your computer and use it in GitHub Desktop.
Save jittagornp/7df0a6990409d47c1c8b82b6bf4e2e12 to your computer and use it in GitHub Desktop.
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/11/29
*/
var app = angular.module('app', [
'ui.bootstrap',
'ipCookie',
'ui.router',
'ngAnimate',
'ui-notification',
'ngSanitize'
]);
app.constant('doss', window.doss);
app.constant('logConfig', window.logConfig);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/23
*/
app.factory('component.AbstractCenterDialog', [
'component.Dialog',
function (Dialog) {
var $ = jQuery;
var $win = $(window);
/**
* class AbstractCenterDialog extends Dialog
*
* @param {String} templateId
*/
var AbstractCenterDialog = function (templateId) {
Dialog.call(this, templateId);
this.cssClassName += ' dip--dialog--centerDialog';
};
angular.extend(AbstractCenterDialog.prototype, Dialog.prototype);
/**
* @return {AbstractCenterDialog} dialog instance
*/
AbstractCenterDialog.create = function () {
return new AbstractCenterDialog();
};
/**
* @param {String} title
* @return {AbstractCenterDialog} dialog instance
*/
AbstractCenterDialog.prototype.setTitle = function (title) {
this.data.title = title;
return this;
};
function $dialog() {
return $('.dip--dialog--centerDialog .modal-content');
}
function repositionDialog() {
var $el = $dialog();
var height = $el.height();
var width = $el.width();
$el.css({
'margin-top': (-1) * (height / 2),
'margin-left': (-1) * (width / 2)
});
}
$win.off('resize.dip--dialog--centerDialog')
.on('resize.dip--dialog--centerDialog', repositionDialog);
function repositionWithDelay() {
var timeout = setTimeout(function () {
clearTimeout(timeout);
repositionDialog();
}, 50);
}
/**
* open the dialog
*/
AbstractCenterDialog.prototype.open = function () {
Dialog.prototype.open.call(this);
repositionWithDelay();
};
return AbstractCenterDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/26
*/
app.factory('component.AbstractFullPageDialog', [
'component.Dialog',
function (Dialog) {
var $ = jQuery;
var $win = $(window);
var $toolbar = $('.dip--toolbar');
/**
* class AbstractFullPageDialog extends Dialog
*
* @param {String} templateId
*/
var AbstractFullPageDialog = function (templateId) {
Dialog.call(this, templateId);
this.cssClassName = 'dip--dialog--fullPageDialog';
};
angular.extend(AbstractFullPageDialog.prototype, Dialog.prototype);
/**
* @return {FullPageDialog} dialog instance
*/
AbstractFullPageDialog.create = function () {
return new AbstractFullPageDialog();
};
/**
* @param {String} title
* @return {FullPageDialog} dialog instance
*/
AbstractFullPageDialog.prototype.setTitle = function (title) {
this.data.title = title;
return this;
};
function $dialog() {
return $('.dip--dialog--fullPageDialog .modal-content');
}
function resizeDialog() {
var $el = $dialog();
var $header = $el.find('.modal-header');
var $body = $el.find('.modal-body');
var $footer = $el.find('.modal-footer');
$el.height($win.height() - $toolbar.height() * 2);
$body.height($el.height() - $header.height() - $footer.height() - 60); //60 is padding space
}
$win.off('resize.dip--dialog--fullPageDialog')
.on('resize.dip--dialog--fullPageDialog', resizeDialog);
function resizeWithDelay() {
var timeout = setTimeout(function () {
clearTimeout(timeout);
resizeDialog();
}, 100);
}
/**
* open the dialog
*/
AbstractFullPageDialog.prototype.open = function () {
Dialog.prototype.open.call(this);
resizeWithDelay();
};
return AbstractFullPageDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/26
*/
app.factory('component.AbstractFullPageIframeDialog', [
'component.AbstractFullPageDialog',
function (AbstractFullPageDialog) {
var $ = jQuery;
/**
* class AbstractFullPageIframeDialog extends AbstractFullPageDialog
*
* @param {String} templateId
*/
var AbstractFullPageIframeDialog = function (templateId) {
AbstractFullPageDialog.call(this, templateId);
this.cssClassName += ' dip--dialog--fullPageIframeDialog';
};
angular.extend(AbstractFullPageIframeDialog.prototype, AbstractFullPageDialog.prototype);
/**
* @return {AbstractFullPageIframeDialog} dialog instance
*/
AbstractFullPageIframeDialog.create = function () {
return new AbstractFullPageIframeDialog();
};
function $dialog() {
return $('.dip--dialog--fullPageDialog .modal-content');
}
function showAjaxLoading() {
var timeout = setTimeout(function () {
clearTimeout(timeout);
var $el = $dialog();
$el.find('iframe').css('visibility', 'visible');
$el.find('.dip--dialog__ajax-loading--body').hide();
}, 1000);
}
/**
* open the dialog
*/
AbstractFullPageIframeDialog.prototype.open = function () {
AbstractFullPageDialog.prototype.open.call(this);
showAjaxLoading();
};
return AbstractFullPageIframeDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/23
*/
app.factory('component.AgentDialog', [
'component.AbstractFullPageDialog',
function (AbstractFullPageDialog) {
/**
* class AgentDialog extends AbstractFullPageDialog
*/
var AgentDialog = function () {
AbstractFullPageDialog.call(this, 'agentDialog');
this.cssClassName += ' dip--dialog--agentDialog';
};
angular.extend(AgentDialog.prototype, AbstractFullPageDialog.prototype);
/**
* @return {AgentDialog} dialog instance
*/
AgentDialog.create = function () {
return new AgentDialog();
};
return AgentDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/12
*/
app.factory('component.AjaxLoadingDialog', [
'component.Dialog',
function (Dialog) {
/**
* class AjaxLoadingDialog extends Dialog
*/
var AjaxLoadingDialog = function () {
Dialog.call(this, 'ajaxLoadingDialog');
this.cssClassName = 'dip--dialog--ajaxLoadingDialog';
};
angular.extend(AjaxLoadingDialog.prototype, Dialog.prototype);
/**
* @return {AlertDialog} dialog instance
*/
AjaxLoadingDialog.create = function () {
return new AjaxLoadingDialog();
};
/**
* @param {String} message
* @return {AlertDialog} dialog instance
*/
AjaxLoadingDialog.prototype.setMessage = function (message) {
this.data.message = message;
return this;
};
return AjaxLoadingDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/10
*/
app.factory('component.AlertDialog', [
'component.Dialog',
function (Dialog) {
/**
* class AlertDialog extends Dialog
*/
var AlertDialog = function () {
Dialog.call(this, 'alertDialog');
this.data.buttonLabel = 'ตกลง';
this.cssClassName = 'dip--dialog--alertDialog';
};
angular.extend(AlertDialog.prototype, Dialog.prototype);
/**
* @return {AlertDialog} dialog instance
*/
AlertDialog.create = function () {
return new AlertDialog();
};
/**
* @param {String} title
* @return {AlertDialog} dialog instance
*/
AlertDialog.prototype.setTitle = function (title) {
this.data.title = title;
return this;
};
/**
* @param {String} message
* @return {AlertDialog} dialog instance
*/
AlertDialog.prototype.setMessage = function (message) {
this.data.message = message;
return this;
};
/**
* @param {String} buttonLabel
* @return {AlertDialog} dialog instance
*/
AlertDialog.prototype.setButtonLabel = function (buttonLabel) {
this.data.buttonLabel = buttonLabel;
return this;
};
return AlertDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/27
*/
app.factory('component.ConfirmAutofillFormDialog', [
'component.AbstractFullPageIframeDialog',
function (AbstractFullPageIframeDialog) {
/**
* class ConfirmAutofillFormDialog extends AbstractFullPageDialog
*/
var ConfirmAutofillFormDialog = function () {
AbstractFullPageIframeDialog.call(this, 'confirmAutofillFormDialog');
this.cssClassName += ' dip--dialog--confirmDialogAutofillFormDialog';
this.data.pdfUrl = null;
this.withLoadingMessage('กำลังยืนยันข้อมูล');
};
angular.extend(ConfirmAutofillFormDialog.prototype, AbstractFullPageIframeDialog.prototype);
/**
* @return {ConfirmAutofillFormDialog} dialog instance
*/
ConfirmAutofillFormDialog.create = function () {
return new ConfirmAutofillFormDialog();
};
/**
* @param {String} url
* @return {ConfirmAutofillFormDialog} dialog instance
*/
ConfirmAutofillFormDialog.prototype.setPdfUrl = function (url) {
this.data.pdfUrl = url;
return this;
};
/**
* @param {Function} callback
* @return {ConfirmAutofillFormDialog} dialog instance
*/
ConfirmAutofillFormDialog.prototype.onAsyncConfirm = function (callback) {
var $this = this;
$this.onAsyncClose(function ($dialog, button) {
if (button === 'CONFIRM') {
if (callback) {
callback.call($this, $dialog, button);
}
} else {
$dialog.close(button);
}
});
return this;
};
return ConfirmAutofillFormDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/10
*/
app.factory('component.ConfirmDialog', [
'component.Dialog',
function (Dialog) {
/**
* class ConfirmDialog extends Dialog
*
* @param {String} templateId_opt
*/
var ConfirmDialog = function (templateId_opt) {
Dialog.call(this, templateId_opt || 'confirmDialog');
this.data.cancelButtonLabel = 'ยกเลิก';
this.data.confirmButtonLabel = 'ยืนยัน';
this.cssClassName = 'dip--dialog--confirmDialog';
};
angular.extend(ConfirmDialog.prototype, Dialog.prototype);
/**
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.create = function () {
return new ConfirmDialog();
};
/**
* @param {String} title
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.prototype.setTitle = function (title) {
this.data.title = title;
return this;
};
/**
* @param {String} message
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.prototype.setMessage = function (message) {
this.data.message = message;
return this;
};
/**
* @param {String} buttonLabel
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.prototype.setCancelButtonLabel = function (buttonLabel) {
this.data.cancelButtonLabel = buttonLabel;
return this;
};
/**
* @param {String} buttonLabel
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.prototype.setConfirmButtonLabel = function (buttonLabel) {
this.data.confirmButtonLabel = buttonLabel;
return this;
};
/**
* @param {Function} callback
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.prototype.onConfirm = function (callback) {
var $this = this;
$this.onClose(function (button) {
if (button === 'CONFIRM') {
if (callback) {
callback.call($this, button);
}
}
});
return this;
};
/**
* @param {Function} callback
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.prototype.onCancel = function (callback) {
var $this = this;
$this.onClose(function (button) {
if (button !== 'CONFIRM') {
if (callback) {
callback.call($this, button);
}
}
});
return this;
};
/**
* @param {Function} callback
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.prototype.onAsyncConfirm = function (callback) {
var $this = this;
$this.onAsyncClose(function ($dialog, button) {
if (button === 'CONFIRM') {
if (callback) {
callback.call($this, $dialog, button);
}
} else {
$dialog.close(button);
}
});
return this;
};
/**
* @param {Function} callback
* @return {ConfirmDialog} dialog instance
*/
ConfirmDialog.prototype.onAsyncCancel = function (callback) {
var $this = this;
$this.onAsyncClose(function ($dialog, button) {
if (button !== 'CONFIRM') {
if (callback) {
callback.call($this, $dialog, button);
}
} else {
$dialog.close(button);
}
});
return this;
};
return ConfirmDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/09
*/
app.factory('component.Dialog', [
'$uibModal',
function ($uibModal) {
jQuery(document).on('mousewheel', '.modal-open', function (e) {
if (e.target.id === 'el') {
return;
}
e.preventDefault();
e.stopPropagation();
});
/**
* class Dialog
*
* @param {String} templateId
*/
var Dialog = function (templateId) {
this.templateId = templateId;
this.data = {_ajaxLoadingShow: false, loadingMessage: 'กำลังดำเนินการ...'};
this.closeCallbacks = [];
this.alterCloseCallbacks = [];
this.cssClassName = '';
this.animation = true;
this.$dialog = null;
};
/**
* @param {String} templateId
* @return {Dialog} dialog instance
*/
Dialog.fromTemplateId = function (templateId) {
return new Dialog(templateId);
};
/**
* @param {String} message
* @return {Dialog} dialog instance
*/
Dialog.prototype.withLoadingMessage = function (message) {
this.data.loadingMessage = message + '...';
return this;
};
/**
* @param {Object} cssClassName
* @return {Dialog} dialog instance
*/
Dialog.prototype.withCssClassName = function (cssClassName) {
this.cssClassName = cssClassName;
return this;
};
/**
* @param {boolean} animation
* @return {Dialog} dialog instance
*/
Dialog.prototype.setAnimation = function (animation) {
this.animation = animation;
return this;
};
/**
* @param {Function} callback
* @return {Dialog} dialog instance
*/
Dialog.prototype.onAsyncClose = function (callback) {
this.closeCallbacks.push(callback);
return this;
};
/**
* @param {Function} callback
* @return {Dialog} dialog instance
*/
Dialog.prototype.onClose = function (callback) {
var $this = this;
$this.onAsyncClose(function ($dialog, button) {
$dialog.close(button);
if (callback) {
callback.call($this, button);
}
});
return this;
};
/**
* @param {Function} callback
* @return {Dialog} dialog instance
*/
Dialog.prototype.onAfterClose = function (callback) {
this.alterCloseCallbacks.push(callback);
return this;
};
function ProxyHideAjaxLoading(closeFunc, $instance) {
return function () {
$instance.data._ajaxLoadingShow = false;
var value = closeFunc.apply(this, arguments);
var len = $instance.alterCloseCallbacks.length;
for (var i = 0; i < len; i++) {
$instance.alterCloseCallbacks[i].call($instance);
}
return value;
};
}
/**
* open target dialog by template id
*/
Dialog.prototype.open = function () {
var $this = this;
$this.$dialog = $uibModal.open({
templateUrl: this.templateId,
windowClass: 'white-overlay ' + ' ' + (this.cssClassName ? this.cssClassName : ''),
backdrop: false,
keyboard: false,
animation: this.animation,
controller: function ($scope) {
$scope.data = $this.data;
var hasCloseCallback = !!$this.closeCallbacks.length;
$scope.close = function (button) {
if (hasCloseCallback) {
$this.data._ajaxLoadingShow = true;
var length = $this.closeCallbacks.length;
for (var i = 0; i < length; i++) {
$this.closeCallbacks[i]($this.$dialog, button);
}
} else {
$this.$dialog.close(button);
}
};
}
});
$this.$dialog.close = (ProxyHideAjaxLoading)($this.$dialog.close, this);
return $this;
};
Dialog.prototype.close = function () {
if (this.$dialog) {
this.$dialog.close();
}
};
return Dialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/23
*/
app.factory('component.DownloadMSWordDialog', [
'component.AbstractFullPageIframeDialog',
function (AbstractFullPageIframeDialog) {
/**
* class DownloadMSWordDialog extends AbstractFullPageIframeDialog
*/
var DownloadMSWordDialog = function () {
AbstractFullPageIframeDialog.call(this, 'downloadMSWordDialog');
this.cssClassName += ' dip--dialog--downloadMSWordDialog';
this.data.pdfUrl = null;
this.data.msWordUrl = null;
this.withLoadingMessage('กำลังดาวน์โหลดแบบฟอร์ม');
};
angular.extend(DownloadMSWordDialog.prototype, AbstractFullPageIframeDialog.prototype);
/**
* @return {DownloadMSWordDialog} dialog instance
*/
DownloadMSWordDialog.create = function () {
return new DownloadMSWordDialog();
};
/**
* @param {String} url
* @return {DownloadMSWordDialog} dialog instance
*/
DownloadMSWordDialog.prototype.setMSWordUrl = function (url) {
this.data.msWordUrl = url;
return this;
};
/**
* @param {String} url
* @return {DownloadMSWordDialog} dialog instance
*/
DownloadMSWordDialog.prototype.setPdfUrl = function (url) {
this.data.pdfUrl = url;
return this;
};
/**
* @param {Function} callback
* @return {DownloadMSWordDialog} dialog instance
*/
DownloadMSWordDialog.prototype.onAsyncDownload = function (callback) {
var $this = this;
$this.onAsyncClose(function ($dialog, button) {
if (button === 'DOWNLOAD') {
if (callback) {
callback.call($this, $dialog, button);
}
} else {
$dialog.close(button);
}
});
return this;
};
return DownloadMSWordDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/28
*/
app.factory('component.EditPictureDialog', [
'component.AbstractCenterDialog',
function (AbstractCenterDialog) {
/**
* class EditPictureDialog extends AbstractCenterDialog
*/
var EditPictureDialog = function () {
AbstractCenterDialog.call(this, 'editPictureDialog');
this.cssClassName += ' dip--dialog--editPictureDialog';
this.withLoadingMessage('กำลังแก้ไขรูปภาพ');
};
angular.extend(EditPictureDialog.prototype, AbstractCenterDialog.prototype);
/**
* @return {EditPictureDialog} dialog instance
*/
EditPictureDialog.create = function () {
return new EditPictureDialog();
};
/**
* @param {Function} callback
* @return {EditPictureDialog} dialog instance
*/
EditPictureDialog.prototype.onAsyncOK = function (callback) {
var $this = this;
$this.onAsyncClose(function ($dialog, button) {
if (button === 'OK') {
if (callback) {
callback.call($this, $dialog, button);
}
} else {
$dialog.close(button);
}
});
return this;
};
return EditPictureDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/12
*/
app.factory('component.Notification', [
'Notification',
function (Noti) {
/**
* @component Notification
*/
var Notification = function () {
this.title = null;
this.message = null;
};
/**
* @returns {Notification}
*/
Notification.create = function () {
return new Notification();
};
/**
* @param {String} title
* @returns {Notification}
*/
Notification.prototype.setTitle = function (title) {
this.title = title;
return this;
};
/**
* @param {String} message
* @returns {Notification}
*/
Notification.prototype.setMessage = function (message) {
this.message = message;
return this;
};
Notification.prototype.show = function () {
Noti({
title: this.title,
message: this.message
});
};
return Notification;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/28
*/
app.factory('component.OfficialFeeWaiverDialog', [
'component.AbstractCenterDialog',
function (AbstractCenterDialog) {
/**
* class OfficialFeeWaiverDialog extends AbstractCenterDialog
*/
var OfficialFeeWaiverDialog = function () {
AbstractCenterDialog.call(this, 'officialFeeWaiverDialog');
this.cssClassName += ' dip--dialog--officialFeeWaiverDialog';
};
angular.extend(OfficialFeeWaiverDialog.prototype, AbstractCenterDialog.prototype);
/**
* @return {OfficialFeeWaiverDialog} dialog instance
*/
OfficialFeeWaiverDialog.create = function () {
return new OfficialFeeWaiverDialog();
};
return OfficialFeeWaiverDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/23
*/
app.factory('component.SendFormDialog', [
'component.AbstractFullPageIframeDialog',
function (AbstractFullPageIframeDialog) {
/**
* class SendFormDialog extends AbstractFullPageIframeDialog
*/
var SendFormDialog = function () {
AbstractFullPageIframeDialog.call(this, 'sendFormDialog');
this.cssClassName += ' dip--dialog--sendFormDialog';
this.data.pdfUrl = null;
this.withLoadingMessage('กำลังทำลายเซ็นต์ดิจิตอล (Digital Signature)');
};
angular.extend(SendFormDialog.prototype, AbstractFullPageIframeDialog.prototype);
/**
* @return {SendFormDialog} dialog instance
*/
SendFormDialog.create = function () {
return new SendFormDialog();
};
/**
* @param {String} url
* @return {SendFormDialog} dialog instance
*/
SendFormDialog.prototype.setPdfUrl = function (url) {
this.data.pdfUrl = url;
return this;
};
/**
* @param {Function} callback
* @return {SendFormDialog} dialog instance
*/
SendFormDialog.prototype.onAsyncSend = function (callback) {
var $this = this;
$this.onAsyncClose(function ($dialog, button) {
if (button === 'SEND') {
if (callback) {
callback.call($this, $dialog, button);
}
} else {
$dialog.close(button);
}
});
return this;
};
return SendFormDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/23
*/
app.factory('component.ShowPdfDialog', [
'component.AbstractFullPageIframeDialog',
function (AbstractFullPageIframeDialog) {
/**
* class ShowPdfDialog extends AbstractFullPageIframeDialog
*/
var ShowPdfDialog = function () {
AbstractFullPageIframeDialog.call(this, 'showPdfDialog');
this.cssClassName += ' dip--dialog--showPdfDialog';
this.data.pdfUrl = null;
};
angular.extend(ShowPdfDialog.prototype, AbstractFullPageIframeDialog.prototype);
/**
* @return {ShowPdfDialog} dialog instance
*/
ShowPdfDialog.create = function () {
return new ShowPdfDialog();
};
/**
* @param {String} url
* @return {ShowPdfDialog} dialog instance
*/
ShowPdfDialog.prototype.setPdfUrl = function (url) {
this.data.pdfUrl = url;
return this;
};
return ShowPdfDialog;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/04
*/
app.config([
'$httpProvider',
function ($httpProvider) {
$httpProvider.interceptors.push([
'csrfToken',
function (csrfToken) {
return {
request: function (config) {
config.headers['X-XSRF-TOKEN'] = csrfToken;
return config;
}
};
}
]);
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/12
*/
app.config([
'NotificationProvider',
function (NotificationProvider) {
NotificationProvider.setOptions({
delay: 5000,
startTop: 40,
startRight: 30,
verticalSpacing: 20,
horizontalSpacing: 20,
positionX: 'right',
positionY: 'bottom'
});
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/08
*/
app.config([
'$httpProvider',
function ($httpProvider) {
$httpProvider.interceptors.push([
'$q',
'validator.UIFieldValidator',
function ($q, UIFieldValidator) {
function isValidateFail(err){
return err.type === 'ValidatedFailError';
}
function mapErrByFieldName(err) {
UIFieldValidator.showError(err.field, err.code, err.message);
}
function mapErrByCode(err) {
UIFieldValidator.showErrorByCode(err.code, err.message);
}
return {
responseError: function (rejection) {
var err = rejection.data;
if (isValidateFail(err)) {
angular.forEach(err.field_errors, mapErrByFieldName);
angular.forEach(err.errors, mapErrByCode);
}
return $q.reject(rejection);
}
};
}
]);
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/12
*/
app.directive('ngBack', [
'$window',
function ($window) {
return function (scope, element, attrs) {
element.bind('click', function (event) {
scope.$apply(function () {
$window.history.back();
});
event.preventDefault();
});
};
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/20
*/
app.directive('ngCalendarpicker', [
'$window',
function ($window) {
var $ = jQuery;
return function (scope, element, attrs) {
$(element).calendarsPicker({
calendar: $.calendars.instance('thai', 'th')
});
};
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/21
*/
app.directive('ngFocusOnscrolled', function () {
var MOUSEWHEEL_STEP = 20;
return function (scope, element, attr) {
element.bind('mousewheel DOMMouseScroll', function (e) {
var scrollTo = null;
var $self = jQuery(this);
if (!$self.hasScrollBar()) {
return;
}
if (e.type === 'mousewheel') {
scrollTo = (e.originalEvent.wheelDelta * -1);
} else if (e.type === 'DOMMouseScroll') {
scrollTo = MOUSEWHEEL_STEP * e.originalEvent.detail;
}
if (scrollTo) {
e.preventDefault();
$self.scrollTop(scrollTo + $self.scrollTop());
}
});
};
});
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/18
*/
app.directive('ngReload', [
'$window',
function ($window) {
return function (scope, element, attrs) {
element.bind('click', function (event) {
var $el = jQuery(this);
var url = $el.attr('href');
scope.$apply(function () {
$window.location.href = url;
});
event.preventDefault();
});
};
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/28
*/
app.directive('ngTextareaAutosize', function () {
return function (scope, element, attr) {
autosize(element);
};
});
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/29
*/
app.factory('enum.Enumerate', [
'util.StringUtils',
'util.MethodNameUtils',
function (StringUtils, MethodNameUtils) {
var hasText = StringUtils.hasText;
var isArray = angular.isArray;
var isObject = angular.isObject;
var isString = angular.isString;
var forEach = angular.forEach;
/*
* Example 1
* ---------
*
* var ArticleStatus = Enumerate([
* {
* name: 'PUBLISHED',
* description: 'published'
* },
* {
* name: 'DRAFT',
* description: 'draft'
* }
* ]);
*
* Using
*
* ArticleStatus.PUBLISHED
* ArticleStatus.PUBLISHED.getName()
* ArticleStatus.PUBLISHED.getDescription()
*
* ArticleStatus.DRAFF
* ArticleStatus.DRAFF.getName()
* ArticleStatus.DRAFF.getDescription()
*
* =========================================
*
* Example 2
* ---------
*
* var LikeRefType = Enumerate([
* 'POST',
* 'COMMENT'
* ]);
*
* Using
*
* LikeRefType.POST
* LikeRefType.POST.getName()
* LikeRefType.COMMENT
* LikeRefType.COMMENT.getName()
*/
return (function (values, optional) {
if (!isArray(values)) {
throw new Error('invalid arguments type, require Array.');
}
if (values.length < 1) {
throw new Error('require values.');
}
/**
* enum Enumerate
*
* @param {String | Object} value
*/
var Enumerate = function (value) {
this.name = null; /* String */
if (isObject(value)) {
initObject.call(this, value);
return;
}
if (isString(value)) {
this.name = value;
return;
}
throw new Error('invalid arguments.');
};
function initObject(value) {
if (!hasText(value.name)) {
throw new Error('require attribute name.');
}
forEach(value, function (val, attr) {
this[attr] = val;
}, this);
}
/**
* keep all enums in this attributes
*/
Enumerate._values = [];
/**
* @return {Array<Enumerate>}
*/
Enumerate.values = function () {
return Enumerate._values;
};
function findByName(values, name) {
var e = null;
forEach(values, function (val) {
if (val.name === name) {
e = val;
return false;
}
});
return e;
}
/**
* @param {String} name
* @returns {Enumerate}
*/
Enumerate.valueOf = function (name) {
var valid = hasText(name)
&& name !== 'null'
&& name !== 'undefined';
if (!valid) {
return null;
}
var e = findByName(Enumerate._values, name);
if (!e) {
throw new Error('not found enum of value "' + name + '".');
}
return e;
};
/**
* @returns {String}
*/
Enumerate.prototype.toString = function () {
return this.name;
};
/**
* @param {String | Enumerate} name
* @returns {Boolean}
*/
Enumerate.prototype.is = function (name) {
if (isString(name)) {
return this.name === name;
}
return this === name;
};
optional && forEach(optional, function (val, attr) {
Enumerate.prototype[attr] = val;
});
function getAttrNames(values) {
var value = values[0];
if (isString(value)) {
return ['name'];
}
var attrs = [];
forEach(value, function (value, attr) {
attrs.push(attr);
});
var isNotFoundName = attrs.indexOf('name') === -1;
if (isNotFoundName) {
attrs.push('name');
}
return attrs;
}
var attrs = getAttrNames(values);
forEach(attrs, function (attr) {
var getter = MethodNameUtils.toGetterName(attr);
Enumerate.prototype[getter] = function () {
return this[attr];
};
});
forEach(values, function (value) {
var name = isObject(value) ? value.name : value;
var e = findByName(Enumerate._values, name);
if (!e) {
e = new Enumerate(value);
Enumerate._values.push(e);
}
Object.freeze(e);
Enumerate[name] = e;
});
Object.freeze(Enumerate._values);
Object.freeze(Enumerate);
return Enumerate;
});
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/11/29
*/
app.factory('logger.Logger', [
function () {
/**
* @param {String} moduleName
* @returns {Logger}
*/
return function (moduleName) {
/**
* class Logger
*/
var Logger = function () {
this.moduleName = moduleName;
};
function getMessageTitle(type) {
return type + ' [' + moduleName + '] : ';
}
if (window.console) {
Logger.prototype.info = window.console.info.bind(window.console, getMessageTitle('INFO'));
Logger.prototype.debug = window.console.debug.bind(window.console, getMessageTitle('DEBUG'));
Logger.prototype.warn = window.console.warn.bind(window.console, getMessageTitle('WARN'));
Logger.prototype.error = window.console.error.bind(window.console, getMessageTitle('ERROR'));
} else {
Logger.prototype.info = function () { };
Logger.prototype.debug = function () { };
Logger.prototype.warn = function () { };
Logger.prototype.error = function () { };
}
return Logger;
};
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/11/29
*/
app.factory('logger.LoggerFactory', [
'logConfig',
'logger.Logger',
function (config, Logger) {
var enabledInfo = config ? config.enabledInfo : true;
var enabledDebug = config ? config.enabledDebug : true;
var enabledWarn = config ? config.enabledWarn : true;
var enabledError = config ? config.enabledError : true;
/**
* class LoggerFactory
*/
var LoggerFactory = function () {
throw new Error('Unsupported new instance.');
};
/**
* @param {String} moduleName
* @returns {Logger} log
*/
LoggerFactory.getLogger = function (moduleName) {
var log = new (Logger(moduleName));
if (!enabledInfo) {
log.info = function () {};
}
if (!enabledDebug) {
log.debug = function () {};
}
if (!enabledWarn) {
log.warn = function () {};
}
if (!enabledError) {
log.error = function () {};
}
return log;
};
return LoggerFactory;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/04
*/
app.provider('csrfToken', [
function () {
var token = jQuery('meta[name=csrf_token]').attr('content');
this.$get = function () {
return token;
};
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/08
*/
app.provider('isomorphicState', [
function () {
var el = document.getElementById('iso-state');
var dataState = angular.element(el).attr('data-state');
var state = dataState ? JSON.parse(dataState) : null;
this.$get = function () {
return state;
};
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/10
*/
app.config([
'doss',
'$stateProvider',
function (doss, $stateProvider) {
var loaded = {
'dashboard/form/all': false,
'dashboard/form/draft': false,
'dashboard/form/send': false
};
var timeout = setTimeout(function () {
clearTimeout(timeout);
angular.forEach(
loaded,
function (value, key) {
loaded[key] = true;
}
);
}, 500);
var allResolver = {
initData: [
'$q',
'$timeout',
function ($q, $timeout) {
var defer = $q.defer();
$timeout(function () {
defer.resolve(null);
});
return defer.promise;
}
]
};
var draftResolver = {
initData: [
'$q',
'$timeout',
function ($q, $timeout) {
var defer = $q.defer();
$timeout(function () {
defer.resolve(null);
});
return defer.promise;
}
]
};
var sendResolver = {
initData: [
'$q',
'$timeout',
function ($q, $timeout) {
var defer = $q.defer();
$timeout(function () {
defer.resolve(null);
});
return defer.promise;
}
]
};
$stateProvider
.state('dashboard/form/all', {
url: '/dashboard/form',
views: {
main: {
templateUrl: function () {
if (!loaded['dashboard/form/all']) {
return null;
}
return doss.config.host + '/template/dashboard/form';
},
resolve: allResolver,
controller: [
'$scope',
'initData',
function ($scope, initData) {
}
]
}
}
})
.state('dashboard/form/draft', {
url: '/dashboard/form/draft',
views: {
main: {
templateUrl: function () {
if (!loaded['dashboard/form/draft']) {
return null;
}
return doss.config.host + '/template/dashboard/form/draft';
},
resolve: draftResolver,
controller: [
'$scope',
'initData',
function ($scope, initData) {
}
]
}
}
})
.state('dashboard/form/send', {
url: '/dashboard/form/send',
views: {
main: {
templateUrl: function () {
if (!loaded['dashboard/form/send']) {
return null;
}
return doss.config.host + '/template/dashboard/form/send';
},
resolve: sendResolver,
controller: [
'$scope',
'initData',
function ($scope, initData) {
}
]
}
}
});
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/08
*/
app.run(function () {
if (window.doss && window.doss.config && window.doss.config.enabledConsoleWarning) {
console.log("%cคำเตือน!", "background-color : yellow; color : red; font-size : 18pt;");
console.warn("%cอย่าเอาโค๊ด (code) ใด ๆ ที่คุณไม่เข้าใจมาวางในคอลโซล (console) นี้ ถ้าไม่อยากถูกแฮ็ค (hack)", 'font-size : 12pt;');
console.warn("%cคอนโซลนี้มีไว้สำหรับนักพัฒนา (โปรแกรมเมอร์) เท่านั้น! ถ้าใครบอกให้ทำอะไรตรงคอลโซลนี้ ให้สันนิษฐานก่อนว่าคุณกำลังโดนหลอก", 'font-size : 12pt;');
}
});
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/08
*/
app.run(function () {
jQuery(document).on(
'keyup',
'.dip--validate-error',
function (event) {
//if not key Enter
if (event.keyCode !== 13) {
var $el = $(this);
var $parent = $el.parents('.form-group');
$parent.removeClass('has-danger');
$el.removeClass('form-control-danger');
$el.removeClass('dip--validate-error');
$el.siblings('.dip--validate-message').text('');
}
}
);
});
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/20
*/
app.run(function () {
jQuery(document).on(
'click',
'.dip--form__calendar-button .btn',
function (e) {
var $el = jQuery(e.target);
$el.parents('.dip--form__calendar')
.find('.is-calendarsPicker')
.focus();
}
);
});
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/21
*/
(function ($) {
function getPadding(pos) {
var padding = this.css('padding-' + pos);
if (!padding) {
return 0;
}
return parseInt(padding.replace('px', ''), 10);
}
$.fn.hasScrollBar = function () {
var h = this.height()
+ getPadding.call(this, 'top')
+ getPadding.call(this, 'bottom');
return this.get(0).scrollHeight > h;
};
$.fn.autoScrollBar = function () {
this.css({
'height': 'auto',
'overflow-y': 'hidden'
}).height(this.scrollHeight);
};
})(jQuery);
/**
* @author jittagornp
* create 22/08/2015
*/
app.run([
'$timeout',
function ($timeout) {
$timeout(function () {
var $main = jQuery('[ui-view=main]');
$main.siblings().appendTo($main);
}, 500);
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/29
*/
app.run([
'$state',
'$rootScope',
function ($state, $rootScope) {
$rootScope.$on(
'$stateChangeStart',
function (event, toState, toParams, fromState, fromParams) {
jQuery('[ui-view=main]').empty();
}
);
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/08
*/
app.run(function () {
jQuery(document).on(
'keydown',
'input.form-control',
function (e) {
//if keyboard is 'enter'
if (e.keyCode === 13) {
jQuery('.dip--form__submit-button').click();
}
}
);
});
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/29
*/
app.factory('util.JSTypeUtils', [
function () {
var JSTypeUtils = function () {
throw new Error('Unsupported new instance.');
};
/**
* @param {Any} any
* @return {String}
*/
JSTypeUtils.typeOf = function (any) {
return Object.prototype
.toString
.call(any)
.split(/.*\s(.*?)\]/)[1];
};
return JSTypeUtils;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/29
*/
app.factory('util.MethodNameUtils', [
'util.StringUtils',
function (StringUtils) {
var hasText = StringUtils.hasText;
var MethodNameUtils = function () {
throw new Error('Unsupported new instance.');
};
/**
* @param {String} name
* @return {String}
*/
MethodNameUtils.toGetterName = function (name) {
if (!hasText(name)) {
throw new Error('require name.');
}
if (name.length === 1) {
return 'get' + name[0].toUpperCase();
}
return 'get' + name[0].toUpperCase() + name.substring(1);
};
return MethodNameUtils;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/10
*/
app.factory('util.NameBuilder', [
'util.StringUtils',
function (StringUtils) {
var hasText = StringUtils.hasText;
/**
* class NameBuilder
*
* @param {String} firstName
*/
var NameBuilder = function (firstName) {
this.firstName = firstName;
this.middleName = null;
this.lastName = null;
};
/**
* @param {String} firstName
* @return {NameBuilder} instance
*/
NameBuilder.fromFirstName = function (firstName) {
return new NameBuilder(firstName);
};
/**
* @param {String} middleName
* @return {NameBuilder}
*/
NameBuilder.prototype.andMiddleName = function (middleName) {
this.middleName = middleName;
return this;
};
/**
* @param {String} lastName
* @return {NameBuilder}
*/
NameBuilder.prototype.andLastName = function (lastName) {
this.lastName = lastName;
return this;
};
/**
* @return {String}
*/
NameBuilder.prototype.build = function () {
if (!hasText(this.firstName)) {
this.firstName = '';
}
if (!hasText(this.middleName)) {
this.middleName = '';
}
if (!hasText(this.lastName)) {
this.lastName = '';
}
return (this.firstName + ' ' + this.middleName + ' ' + this.lastName)
.replace(' ', ' ')
.trim();
};
return NameBuilder;
}
]);
/**
* @author jittagornp
* create 13/01/2016
*/
app.factory('util.OneTimeConditionLock', [
function () {
/**
* @util OneTimeConditionLock
*/
var OneTimeConditionLock = function () {
this.lock = false;
};
function testByOtherCondition(condition, otherCondition_opt, lock, unlock) {
if (condition) {
if (!this.lock) {
this.lock = true;
lock && lock();
}
} else if (otherCondition_opt) {
if (this.lock) {
this.lock = false;
unlock && unlock();
}
}
}
function testByCondition(condition, lock, unlock) {
if (condition) {
if (!this.lock) {
this.lock = true;
lock && lock();
}
} else {
if (this.lock) {
this.lock = false;
unlock && unlock();
}
}
}
/**
* @param {Boolean} condition
* @param {Function} lock
* @param {Function} unlock
* @param {Boolean} otherCondition_opt
*/
OneTimeConditionLock.prototype.test = function (condition, lock, unlock, otherCondition_opt) {
if (typeof otherCondition_opt !== 'undefined') {
testByOtherCondition.call(this,
condition,
otherCondition_opt,
lock,
unlock
);
} else {
testByCondition.call(this,
condition,
lock,
unlock
);
}
};
return OneTimeConditionLock;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/10
*/
app.factory('util.PasswordStarGenerator', [
'util.StringUtils',
function (StringUtils) {
var hasText = StringUtils.hasText;
/**
* class PasswordStarGenerator
*/
var PasswordStarGenerator = function () {
throw new Error('Unsupported new instance.');
};
/**
* @param {String} password
* @return {String}
*/
PasswordStarGenerator.generate = function (password) {
if (!hasText(password)) {
return '';
}
var output = '';
var length = password.length;
for (var i = 0; i < length; i++) {
output = output + '*';
}
return output;
};
return PasswordStarGenerator;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2017/01/27
*/
app.factory('util.ScreenUtils', [
function () {
var $ = jQuery;
var $screen = $('html, body');
var ANIMATE_SPEED_MILLISEC = 300;
/**
* class ScreenUtils
*/
var ScreenUtils = function () {
throw new Error('Unsupported new instance.');
};
ScreenUtils.animate2Top = function () {
$screen.animate({
scrollTop: 0
}, ANIMATE_SPEED_MILLISEC);
};
ScreenUtils.animate2Bottom = function () {
$screen.animate({
scrollTop: $(document).height()
}, ANIMATE_SPEED_MILLISEC);
};
return ScreenUtils;
}
]);
/**
* @author jittagornp <http://jittagornp.me>
* create : 2016/12/10
*/
app.factory('util.StringUtils', [
function () {
var StringUtils = function () {
throw new Error('Unsupported new instance.');
};
/**
* @param {String} str
* @return {Boolean}
*/
StringUtils.hasText = function (str) {
if (!str) {
return false;
}
return (str + '').length > 0;
};
return StringUtils;
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment