(function(window) { if(window.PrimeFaces) { PrimeFaces.debug("PrimeFaces already loaded, ignoring duplicate execution."); return; } var PrimeFaces = { escapeClientId : function(id) { return "#" + id.replace(/:/g,"\\:"); }, cleanWatermarks : function(){ $.watermark.hideAll(); }, showWatermarks : function(){ $.watermark.showAll(); }, addSubmitParam : function(parent, params) { var form = $(this.escapeClientId(parent)); for(var key in params) { form.append(""); } return this; }, /** * Submits a form and clears ui-submit-param after that to prevent dom caching issues */ submit : function(formId, target) { var form = $(this.escapeClientId(formId)); if(target) { form.attr('target', target); } form.submit().children('input.ui-submit-param').remove(); }, attachBehaviors : function(element, behaviors) { $.each(behaviors, function(event, fn) { element.bind(event, function(e) { fn.call(element, e); }); }); }, getCookie : function(name) { return $.cookie(name); }, setCookie : function(name, value, cfg) { $.cookie(name, value, cfg); }, deleteCookie: function(name, cfg) { $.removeCookie(name, cfg); }, cookiesEnabled: function() { var cookieEnabled = (navigator.cookieEnabled) ? true : false; if(typeof navigator.cookieEnabled === 'undefined' && !cookieEnabled) { document.cookie="testcookie"; cookieEnabled = (document.cookie.indexOf("testcookie") !== -1) ? true : false; } return (cookieEnabled); }, skinInput : function(input) { input.hover( function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); } ).focus(function() { $(this).addClass('ui-state-focus'); }).blur(function() { $(this).removeClass('ui-state-focus'); }); //aria input.attr('role', 'textbox') .attr('aria-disabled', input.is(':disabled')) .attr('aria-readonly', input.prop('readonly')); if(input.is('textarea')) { input.attr('aria-multiline', true); } return this; }, skinButton : function(button) { button.mouseover(function(){ var el = $(this); if(!button.prop('disabled')) { el.addClass('ui-state-hover'); } }).mouseout(function() { $(this).removeClass('ui-state-active ui-state-hover'); }).mousedown(function() { var el = $(this); if(!button.prop('disabled')) { el.addClass('ui-state-active').removeClass('ui-state-hover'); } }).mouseup(function() { $(this).removeClass('ui-state-active').addClass('ui-state-hover'); }).focus(function() { $(this).addClass('ui-state-focus'); }).blur(function() { $(this).removeClass('ui-state-focus ui-state-active'); }).keydown(function(e) { if(e.keyCode === $.ui.keyCode.SPACE || e.keyCode === $.ui.keyCode.ENTER || e.keyCode === $.ui.keyCode.NUMPAD_ENTER) { $(this).addClass('ui-state-active'); } }).keyup(function() { $(this).removeClass('ui-state-active'); }); //aria var role = button.attr('role'); if(!role) { button.attr('role', 'button'); } button.attr('aria-disabled', button.prop('disabled')); return this; }, skinSelect : function(select) { select.mouseover(function() { var el = $(this); if(!el.hasClass('ui-state-focus')) el.addClass('ui-state-hover'); }).mouseout(function() { $(this).removeClass('ui-state-hover'); }).focus(function() { $(this).addClass('ui-state-focus').removeClass('ui-state-hover'); }).blur(function() { $(this).removeClass('ui-state-focus ui-state-hover'); }); return this; }, //Deprecated, use PrimeFaces.env.isIE instead isIE: function(version) { return PrimeFaces.env.isIE(version); }, info: function(log) { if(this.logger) { this.logger.info(log); } }, debug: function(log) { if(this.logger) { this.logger.debug(log); } }, warn: function(log) { if(this.logger) { this.logger.warn(log); } if (PrimeFaces.isDevelopmentProjectStage() && window.console) { console.log(log); } }, error: function(log) { if(this.logger) { this.logger.error(log); } if (PrimeFaces.isDevelopmentProjectStage() && window.console) { console.log(log); } }, isDevelopmentProjectStage: function() { return PrimeFaces.settings.projectStage === 'Development'; }, setCaretToEnd: function(element) { if(element) { element.focus(); var length = element.value.length; if(length > 0) { if(element.setSelectionRange) { element.setSelectionRange(0, length); } else if (element.createTextRange) { var range = element.createTextRange(); range.collapse(true); range.moveEnd('character', 1); range.moveStart('character', 1); range.select(); } } } }, changeTheme: function(newTheme) { if(newTheme && newTheme !== '') { var themeLink = $('link[href*="javax.faces.resource/theme.css"]'); // portlet if (themeLink.length === 0) { themeLink = $('link[href*="javax.faces.resource=theme.css"]'); } var themeURL = themeLink.attr('href'), plainURL = themeURL.split('&')[0], oldTheme = plainURL.split('ln=')[1], newThemeURL = themeURL.replace(oldTheme, 'primefaces-' + newTheme); themeLink.attr('href', newThemeURL); } }, escapeRegExp: function(text) { return text.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); }, escapeHTML: function(value) { return value.replace(/&/g,'&').replace(//g,'>'); }, clearSelection: function() { if(window.getSelection) { if(window.getSelection().empty) { window.getSelection().empty(); } else if(window.getSelection().removeAllRanges) { window.getSelection().removeAllRanges(); } } else if(document.selection && document.selection.empty) { try { document.selection.empty(); } catch(error) { //ignore IE bug } } }, getSelection: function() { var text = ''; if (window.getSelection) { text = window.getSelection(); } else if (document.getSelection) { text = document.getSelection(); } else if (document.selection) { text = document.selection.createRange().text; } return text; }, hasSelection: function() { return this.getSelection().length > 0; }, cw : function(widgetConstructor, widgetVar, cfg, resource) { PrimeFaces.createWidget(widgetConstructor, widgetVar, cfg, resource); }, createWidget : function(widgetConstructor, widgetVar, cfg, resource) { if(PrimeFaces.widget[widgetConstructor]) { var widget = PrimeFaces.widgets[widgetVar]; //ajax update if(widget && (widget.constructor === PrimeFaces.widget[widgetConstructor])) { widget.refresh(cfg); } //page init else { PrimeFaces.widgets[widgetVar] = new PrimeFaces.widget[widgetConstructor](cfg); if(PrimeFaces.settings.legacyWidgetNamespace) { window[widgetVar] = PrimeFaces.widgets[widgetVar]; } } } // widget script not loaded -> lazy load script + stylesheet else { var scriptURI = PrimeFaces.getFacesResource(resource + '/' + resource + '.js', 'primefaces'); var cssURI = PrimeFaces.getFacesResource(resource + '/' + resource + '.css', 'primefaces'); //load css var cssResource = ''; $('head').append(cssResource); //load script and initialize widget PrimeFaces.getScript(scriptURI, function() { setTimeout(function() { PrimeFaces.widgets[widgetVar] = new PrimeFaces.widget[widgetConstructor](cfg); }, 100); }); } }, /** * Builds a resource URL for given parameters. * * @param {string} name The name of the resource. For example: primefaces.js * @param {string} library The library of the resource. For example: primefaces * @param {string} version The version of the library. For example: 5.1 * @returns {string} The resource URL. */ getFacesResource : function(name, library, version) { var scriptURI = $('script[src*="/javax.faces.resource/' + PrimeFaces.getCoreScriptName() + '"]').attr('src'); // portlet if (!scriptURI) { scriptURI = $('script[src*="javax.faces.resource=' + PrimeFaces.getCoreScriptName() + '"]').attr('src'); } scriptURI = scriptURI.replace(PrimeFaces.getCoreScriptName(), name); scriptURI = scriptURI.replace('ln=primefaces', 'ln=' + library); if (version) { var extractedVersion = new RegExp('[?&]v=([^&]*)').exec(scriptURI)[1]; scriptURI = scriptURI.replace('v=' + extractedVersion, 'v=' + version); } var prefix = window.location.protocol + '//' + window.location.host; return scriptURI.indexOf(prefix) >= 0 ? scriptURI : prefix + scriptURI; }, getCoreScriptName: function() { return 'primefaces.js'; }, inArray: function(arr, item) { for(var i = 0; i < arr.length; i++) { if(arr[i] === item) { return true; } } return false; }, isNumber: function(value) { return typeof value === 'number' && isFinite(value); }, getScript: function(url, callback) { $.ajax({ type: "GET", url: url, success: callback, dataType: "script", cache: true }); }, focus : function(id, context) { var selector = ':not(:submit):not(:button):input:visible:enabled'; setTimeout(function() { if(id) { var jq = $(PrimeFaces.escapeClientId(id)); if(jq.is(selector)) { jq.focus(); } else { jq.find(selector).eq(0).focus(); } } else if(context) { $(PrimeFaces.escapeClientId(context)).find(selector).eq(0).focus(); } else { $(selector).eq(0).focus(); } }, 250); // remember that a custom focus has been rendered // this avoids to retain the last focus after ajax update PrimeFaces.customFocus = true; }, monitorDownload: function(start, complete) { if(this.cookiesEnabled()) { if(start) { start(); } window.downloadMonitor = setInterval(function() { var downloadComplete = PrimeFaces.getCookie('primefaces.download'); if(downloadComplete === 'true') { if(complete) { complete(); } clearInterval(window.downloadMonitor); PrimeFaces.setCookie('primefaces.download', null); } }, 250); } }, /** * Scrolls to a component with given client id */ scrollTo: function(id) { var offset = $(PrimeFaces.escapeClientId(id)).offset(); $('html,body').animate({ scrollTop:offset.top , scrollLeft:offset.left },{ easing: 'easeInCirc' },1000); }, /** * Aligns container scrollbar to keep item in container viewport, algorithm copied from jquery-ui menu widget */ scrollInView: function(container, item) { if(item.length === 0) { return; } var borderTop = parseFloat(container.css('borderTopWidth')) || 0, paddingTop = parseFloat(container.css('paddingTop')) || 0, offset = item.offset().top - container.offset().top - borderTop - paddingTop, scroll = container.scrollTop(), elementHeight = container.height(), itemHeight = item.outerHeight(true); if(offset < 0) { container.scrollTop(scroll + offset); } else if((offset + itemHeight) > elementHeight) { container.scrollTop(scroll + offset - elementHeight + itemHeight); } }, calculateScrollbarWidth: function() { if(!this.scrollbarWidth) { if(PrimeFaces.env.browser.msie) { var $textarea1 = $('') .css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'), $textarea2 = $('') .css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'); this.scrollbarWidth = $textarea1.width() - $textarea2.width(); $textarea1.add($textarea2).remove(); } else { var $div = $('
') .css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 }) .prependTo('body').append('
').find('div') .css({ width: '100%', height: 200 }); this.scrollbarWidth = 100 - $div.width(); $div.parent().remove(); } } return this.scrollbarWidth; }, bcn: function(element, event, functions) { if(functions) { for(var i = 0; i < functions.length; i++) { var retVal = functions[i].call(element, event); if(retVal === false) { if(event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } break; } } } }, bcnu: function(ext, fns) { if(fns) { for(var i = 0; i < fns.length; i++) { var retVal = fns[i].call(ext); if(retVal === false) { break; } } } }, /** * moved to core.dialog.js */ openDialog: function(cfg) { PrimeFaces.dialog.DialogHandler.openDialog(cfg); }, closeDialog: function(cfg) { PrimeFaces.dialog.DialogHandler.closeDialog(cfg); }, showMessageInDialog: function(msg) { PrimeFaces.dialog.DialogHandler.showMessageInDialog(msg); }, confirm: function(msg) { PrimeFaces.dialog.DialogHandler.confirm(msg); }, deferredRenders: [], addDeferredRender: function(widgetId, containerId, fn) { this.deferredRenders.push({widget: widgetId, container: containerId, callback: fn}); }, removeDeferredRenders: function(widgetId) { for(var i = (this.deferredRenders.length - 1); i >= 0; i--) { var deferredRender = this.deferredRenders[i]; if(deferredRender.widget === widgetId) { this.deferredRenders.splice(i, 1); } } }, invokeDeferredRenders: function(containerId) { var widgetsToRemove = []; for(var i = 0; i < this.deferredRenders.length; i++) { var deferredRender = this.deferredRenders[i]; if(deferredRender.container === containerId) { var rendered = deferredRender.callback.call(); if(rendered) { widgetsToRemove.push(deferredRender.widget); } } } for(var j = 0; j < widgetsToRemove.length; j++) { this.removeDeferredRenders(widgetsToRemove[j]); } }, zindex : 1000, customFocus : false, detachedWidgets : [], PARTIAL_REQUEST_PARAM : "javax.faces.partial.ajax", PARTIAL_UPDATE_PARAM : "javax.faces.partial.render", PARTIAL_PROCESS_PARAM : "javax.faces.partial.execute", PARTIAL_SOURCE_PARAM : "javax.faces.source", BEHAVIOR_EVENT_PARAM : "javax.faces.behavior.event", PARTIAL_EVENT_PARAM : "javax.faces.partial.event", RESET_VALUES_PARAM : "primefaces.resetvalues", IGNORE_AUTO_UPDATE_PARAM : "primefaces.ignoreautoupdate", VIEW_STATE : "javax.faces.ViewState", CLIENT_WINDOW : "javax.faces.ClientWindow", VIEW_ROOT : "javax.faces.ViewRoot", CLIENT_ID_DATA : "primefaces.clientid" }; /** * PrimeFaces Namespaces */ PrimeFaces.settings = {}; PrimeFaces.util = {}; PrimeFaces.widgets = {}; /** * Locales */ PrimeFaces.locales = { 'en_US': { closeText: 'Close', prevText: 'Previous', nextText: 'Next', monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], dayNamesMin: ['S', 'M', 'T', 'W ', 'T', 'F ', 'S'], weekHeader: 'Week', firstDay: 0, isRTL: false, showMonthAfterYear: false, yearSuffix:'', timeOnlyTitle: 'Only Time', timeText: 'Time', hourText: 'Hour', minuteText: 'Minute', secondText: 'Second', currentText: 'Current Date', ampm: false, month: 'Month', week: 'week', day: 'Day', allDayText: 'All Day' } }; PF = function(widgetVar) { var widgetInstance = PrimeFaces.widgets[widgetVar]; if (!widgetInstance) { PrimeFaces.error("Widget for var '" + widgetVar + "' not available!"); } return widgetInstance; }; //expose globally window.PrimeFaces = PrimeFaces; })(window); PrimeFaces.env = { mobile : false, touch : false, ios: false, browser : null, init : function() { this.mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(window.navigator.userAgent); this.touch = 'ontouchstart' in window || window.navigator.msMaxTouchPoints || PrimeFaces.env.mobile; this.ios = /iPhone|iPad|iPod/i.test(window.navigator.userAgent); this.resolveUserAgent(); }, //adapted from jquery browser plugin resolveUserAgent: function() { if($.browser) { this.browser = $.browser; } else { var matched, browser; jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(opr)[\/]([\w.]+)/.exec( ua ) || /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; var platform_match = /(ipad)/.exec( ua ) || /(iphone)/.exec( ua ) || /(android)/.exec( ua ) || /(windows phone)/.exec( ua ) || /(win)/.exec( ua ) || /(mac)/.exec( ua ) || /(linux)/.exec( ua ) || /(cros)/i.exec( ua ) || []; return { browser: match[ 3 ] || match[ 1 ] || "", version: match[ 2 ] || "0", platform: platform_match[ 0 ] || "" }; }; matched = jQuery.uaMatch( window.navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; browser.versionNumber = parseInt(matched.version); } if ( matched.platform ) { browser[ matched.platform ] = true; } // These are all considered mobile platforms, meaning they run a mobile browser if ( browser.android || browser.ipad || browser.iphone || browser[ "windows phone" ] ) { browser.mobile = true; } // These are all considered desktop platforms, meaning they run a desktop browser if ( browser.cros || browser.mac || browser.linux || browser.win ) { browser.desktop = true; } // Chrome, Opera 15+ and Safari are webkit based browsers if ( browser.chrome || browser.opr || browser.safari ) { browser.webkit = true; } // IE11 has a new token so we will assign it msie to avoid breaking changes if ( browser.rv ) { var ie = "msie"; matched.browser = ie; browser[ie] = true; } // Opera 15+ are identified as opr if ( browser.opr ) { var opera = "opera"; matched.browser = opera; browser[opera] = true; } // Stock Android browsers are marked as Safari on Android. if ( browser.safari && browser.android ) { var android = "android"; matched.browser = android; browser[android] = true; } // Assign the name and platform variable browser.name = matched.browser; browser.platform = matched.platform; this.browser = browser; $.browser = browser; } }, isIE: function(version) { return (version === undefined) ? this.browser.msie: (this.browser.msie && parseInt(this.browser.version, 10) === version); }, isLtIE: function(version) { return (this.browser.msie) ? parseInt(this.browser.version, 10) < version : false; } }; PrimeFaces.env.init(); /** * AJAX parameter shortcut mapping for PrimeFaces.ab */ PrimeFaces.AB_MAPPING = { 's': 'source', 'f': 'formId', 'p': 'process', 'u': 'update', 'e': 'event', 'a': 'async', 'g': 'global', 'd': 'delay', 't': 'timeout', 'iau': 'ignoreAutoUpdate', 'ps': 'partialSubmit', 'psf': 'partialSubmitFilter', 'rv': 'resetValues', 'fi': 'fragmentId', 'fu': 'fragmentUpdate', 'pa': 'params', 'onst': 'onstart', 'oner': 'onerror', 'onsu': 'onsuccess', 'onco': 'oncomplete' }; /** * Ajax shortcut */ PrimeFaces.ab = function(cfg, ext) { for (var option in cfg) { if (!cfg.hasOwnProperty(option)) { continue; } // just pass though if no mapping is available if (this.AB_MAPPING[option]) { cfg[this.AB_MAPPING[option]] = cfg[option]; delete cfg[option]; } } PrimeFaces.ajax.Request.handle(cfg, ext); }; PrimeFaces.ajax = { VIEW_HEAD : "javax.faces.ViewHead", VIEW_BODY : "javax.faces.ViewBody", Utils: { getContent: function(node) { var content = ''; for(var i = 0; i < node.childNodes.length; i++) { content += node.childNodes[i].nodeValue; } return content; }, updateFormStateInput: function(name, value, xhr) { var trimmedValue = $.trim(value); var forms = null; if (xhr && xhr.pfSettings && xhr.pfSettings.portletForms) { forms = $(xhr.pfSettings.portletForms); } else { forms = $('form'); } var parameterNamespace = ''; if (xhr && xhr.pfArgs && xhr.pfArgs.parameterNamespace) { parameterNamespace = xhr.pfArgs.parameterNamespace; } for (var i = 0; i < forms.length; i++) { var form = forms.eq(i); if (form.attr('method') === 'post') { var input = form.children("input[name='" + parameterNamespace + name + "']"); if (input.length > 0) { input.val(trimmedValue); } else { form.append(''); } } } }, updateElement: function(id, content, xhr) { if (id.indexOf(PrimeFaces.VIEW_STATE) !== -1) { PrimeFaces.ajax.Utils.updateFormStateInput(PrimeFaces.VIEW_STATE, content, xhr); } else if (id.indexOf(PrimeFaces.CLIENT_WINDOW) !== -1) { PrimeFaces.ajax.Utils.updateFormStateInput(PrimeFaces.CLIENT_WINDOW, content, xhr); } else if (id === PrimeFaces.VIEW_ROOT) { // reset PrimeFaces JS state window.PrimeFaces = null; var cache = $.ajaxSetup()['cache']; $.ajaxSetup()['cache'] = true; $('head').html(content.substring(content.indexOf("") + 6, content.lastIndexOf(""))); $.ajaxSetup()['cache'] = cache; var bodyStartTag = new RegExp("]*>", "gi").exec(content)[0]; var bodyStartIndex = content.indexOf(bodyStartTag) + bodyStartTag.length; $('body').html(content.substring(bodyStartIndex, content.lastIndexOf(""))); } else if (id === PrimeFaces.ajax.VIEW_HEAD) { // reset PrimeFaces JS state window.PrimeFaces = null; var cache = $.ajaxSetup()['cache']; $.ajaxSetup()['cache'] = true; $('head').html(content.substring(content.indexOf("") + 6, content.lastIndexOf(""))); $.ajaxSetup()['cache'] = cache; } else if (id === PrimeFaces.ajax.VIEW_BODY) { var bodyStartTag = new RegExp("]*>", "gi").exec(content)[0]; var bodyStartIndex = content.indexOf(bodyStartTag) + bodyStartTag.length; $('body').html(content.substring(bodyStartIndex, content.lastIndexOf(""))); } else { $(PrimeFaces.escapeClientId(id)).replaceWith(content); } } }, Queue: { delays: {}, requests: new Array(), xhrs: new Array(), offer: function(request) { if(request.delay) { var sourceId = null, $this = this, sourceId = (typeof(request.source) === 'string') ? request.source: $(request.source).attr('id'), createTimeout = function() { return setTimeout(function() { $this.requests.push(request); if($this.requests.length === 1) { PrimeFaces.ajax.Request.send(request); } }, request.delay); }; if(this.delays[sourceId]) { clearTimeout(this.delays[sourceId].timeout); this.delays[sourceId].timeout = createTimeout(); } else { this.delays[sourceId] = { timeout: createTimeout() }; } } else { this.requests.push(request); if(this.requests.length === 1) { PrimeFaces.ajax.Request.send(request); } } }, poll: function() { if(this.isEmpty()) { return null; } var processed = this.requests.shift(), next = this.peek(); if(next) { PrimeFaces.ajax.Request.send(next); } return processed; }, peek: function() { if(this.isEmpty()) { return null; } return this.requests[0]; }, isEmpty: function() { return this.requests.length === 0; }, addXHR: function(xhr) { this.xhrs.push(xhr); }, removeXHR: function(xhr) { var index = $.inArray(xhr, this.xhrs); if(index > -1) { this.xhrs.splice(index, 1); } }, abortAll: function() { for(var i = 0; i < this.xhrs.length; i++) { this.xhrs[i].abort(); } this.xhrs = new Array(); this.requests = new Array(); } }, Request: { handle: function(cfg, ext) { cfg.ext = ext; if(cfg.async) { PrimeFaces.ajax.Request.send(cfg); } else { PrimeFaces.ajax.Queue.offer(cfg); } }, send: function(cfg) { PrimeFaces.debug('Initiating ajax request.'); PrimeFaces.customFocus = false; var global = (cfg.global === true || cfg.global === undefined) ? true : false, form = null, sourceId = null; if(cfg.onstart) { var retVal = cfg.onstart.call(this, cfg); if(retVal === false) { PrimeFaces.debug('Ajax request cancelled by onstart callback.'); //remove from queue if(!cfg.async) { PrimeFaces.ajax.Queue.poll(); } return false; //cancel request } } if(cfg.ext && cfg.ext.onstart) { cfg.ext.onstart.call(this, cfg); } if(global) { $(document).trigger('pfAjaxStart'); } //source can be a client id or an element defined by this keyword if(typeof(cfg.source) === 'string') { sourceId = cfg.source; } else { sourceId = $(cfg.source).attr('id'); } if(cfg.formId) { //Explicit form is defined form = $(PrimeFaces.escapeClientId(cfg.formId)); } else { //look for a parent of source form = $(PrimeFaces.escapeClientId(sourceId)).parents('form:first'); //source has no parent form so use first form in document if (form.length === 0) { form = $('form').eq(0); } } PrimeFaces.debug('Form to post ' + form.attr('id') + '.'); var postURL = form.attr('action'), encodedURLfield = form.children("input[name*='javax.faces.encodedURL']"), postParams = []; //portlet support var porletFormsSelector = null; if(encodedURLfield.length > 0) { porletFormsSelector = 'form[action="' + postURL + '"]'; postURL = encodedURLfield.val(); } PrimeFaces.debug('URL to post ' + postURL + '.'); // See #6857 - parameter namespace for porlet var parameterNamespace = PrimeFaces.ajax.Request.extractParameterNamespace(form); //partial ajax PrimeFaces.ajax.Request.addParam(postParams, PrimeFaces.PARTIAL_REQUEST_PARAM, true, parameterNamespace); //source PrimeFaces.ajax.Request.addParam(postParams, PrimeFaces.PARTIAL_SOURCE_PARAM, sourceId, parameterNamespace); //resetValues if (cfg.resetValues) { PrimeFaces.ajax.Request.addParam(postParams, PrimeFaces.RESET_VALUES_PARAM, true, parameterNamespace); } //ignoreAutoUpdate if (cfg.ignoreAutoUpdate) { PrimeFaces.ajax.Request.addParam(postParams, PrimeFaces.IGNORE_AUTO_UPDATE_PARAM, true, parameterNamespace); } //process var processArray = PrimeFaces.ajax.Request.resolveComponentsForAjaxCall(cfg, 'process'); if(cfg.fragmentId) { processArray.push(cfg.fragmentId); } var processIds = processArray.length > 0 ? processArray.join(' ') : '@all'; if (processIds !== '@none') { PrimeFaces.ajax.Request.addParam(postParams, PrimeFaces.PARTIAL_PROCESS_PARAM, processIds, parameterNamespace); } //update var updateArray = PrimeFaces.ajax.Request.resolveComponentsForAjaxCall(cfg, 'update'); if(cfg.fragmentId && cfg.fragmentUpdate) { updateArray.push(cfg.fragmentId); } if(updateArray.length > 0) { PrimeFaces.ajax.Request.addParam(postParams, PrimeFaces.PARTIAL_UPDATE_PARAM, updateArray.join(' '), parameterNamespace); } //behavior event if(cfg.event) { PrimeFaces.ajax.Request.addParam(postParams, PrimeFaces.BEHAVIOR_EVENT_PARAM, cfg.event, parameterNamespace); var domEvent = cfg.event; if(cfg.event === 'valueChange') domEvent = 'change'; else if(cfg.event === 'action') domEvent = 'click'; PrimeFaces.ajax.Request.addParam(postParams, PrimeFaces.PARTIAL_EVENT_PARAM, domEvent, parameterNamespace); } else { PrimeFaces.ajax.Request.addParam(postParams, sourceId, sourceId, parameterNamespace); } //params if(cfg.params) { PrimeFaces.ajax.Request.addParams(postParams, cfg.params, parameterNamespace); } if(cfg.ext && cfg.ext.params) { PrimeFaces.ajax.Request.addParams(postParams, cfg.ext.params, parameterNamespace); } /** * Only add params of process components and their children * if partial submit is enabled and there are components to process partially */ if(cfg.partialSubmit && processIds.indexOf('@all') === -1) { var formProcessed = false, partialSubmitFilter = cfg.partialSubmitFilter||':input'; if(processIds.indexOf('@none') === -1) { for (var i = 0; i < processArray.length; i++) { var jqProcess = $(PrimeFaces.escapeClientId(processArray[i])); var componentPostParams = null; if(jqProcess.is('form')) { componentPostParams = jqProcess.serializeArray(); formProcessed = true; } else if(jqProcess.is(':input')) { componentPostParams = jqProcess.serializeArray(); } else { componentPostParams = jqProcess.find(partialSubmitFilter).serializeArray(); } $.merge(postParams, componentPostParams); } } //add form state if necessary if (!formProcessed) { PrimeFaces.ajax.Request.addParamFromInput(postParams, PrimeFaces.VIEW_STATE, form, parameterNamespace); PrimeFaces.ajax.Request.addParamFromInput(postParams, PrimeFaces.CLIENT_WINDOW, form, parameterNamespace); PrimeFaces.ajax.Request.addParamFromInput(postParams, 'dsPostWindowId', form, parameterNamespace); PrimeFaces.ajax.Request.addParamFromInput(postParams, 'dspwid', form, parameterNamespace); } } else { $.merge(postParams, form.serializeArray()); } //serialize var postData = $.param(postParams); PrimeFaces.debug('Post Data:' + postData); var xhrOptions = { url : postURL, type : "POST", cache : false, dataType : "xml", data : postData, portletForms: porletFormsSelector, source: cfg.source, global: false, beforeSend: function(xhr, settings) { xhr.setRequestHeader('Faces-Request', 'partial/ajax'); xhr.pfSettings = settings; xhr.pfArgs = {}; // default should be an empty object if(global) { $(document).trigger('pfAjaxSend', [xhr, this]); } }, error: function(xhr, status, errorThrown) { if(cfg.onerror) { cfg.onerror.call(this, xhr, status, errorThrown); } if(cfg.ext && cfg.ext.onerror) { cfg.ext.onerror.call(this, xhr, status, errorThrown); } if(global) { $(document).trigger('pfAjaxError', [xhr, this, errorThrown]); } PrimeFaces.error('Request return with error:' + status + '.'); }, success: function(data, status, xhr) { PrimeFaces.debug('Response received succesfully.'); var parsed; //call user callback if(cfg.onsuccess) { parsed = cfg.onsuccess.call(this, data, status, xhr); } //extension callback that might parse response if(cfg.ext && cfg.ext.onsuccess && !parsed) { parsed = cfg.ext.onsuccess.call(this, data, status, xhr); } if(global) { $(document).trigger('pfAjaxSuccess', [xhr, this]); } //do not execute default handler as response already has been parsed if(parsed) { return; } else { PrimeFaces.ajax.Response.handle(data, status, xhr); } PrimeFaces.debug('DOM is updated.'); }, complete: function(xhr, status) { if(cfg.oncomplete) { cfg.oncomplete.call(this, xhr, status, xhr.pfArgs); } if(cfg.ext && cfg.ext.oncomplete) { cfg.ext.oncomplete.call(this, xhr, status, xhr.pfArgs); } if(global) { $(document).trigger('pfAjaxComplete', [xhr, this]); } PrimeFaces.debug('Response completed.'); PrimeFaces.ajax.Queue.removeXHR(xhr); if(!cfg.async) { PrimeFaces.ajax.Queue.poll(); } } }; if (cfg.timeout) { xhrOptions['timeout'] = cfg.timeout; } PrimeFaces.ajax.Queue.addXHR($.ajax(xhrOptions)); }, resolveComponentsForAjaxCall: function(cfg, type) { var expressions = ''; if (cfg[type]) { expressions += cfg[type]; } if (cfg.ext && cfg.ext[type]) { expressions += " " + cfg.ext[type]; } return PrimeFaces.expressions.SearchExpressionFacade.resolveComponents(expressions); }, addParam: function(params, name, value, parameterNamespace) { // add namespace if not available if (parameterNamespace || !name.indexOf(parameterNamespace) === 0) { params.push({ name:parameterNamespace + name, value:value }); } else { params.push({ name:name, value:value }); } }, addParams: function(params, paramsToAdd, parameterNamespace) { for (var i = 0; i < paramsToAdd.length; i++) { var param = paramsToAdd[i]; // add namespace if not available if (parameterNamespace && !param.name.indexOf(parameterNamespace) === 0) { param.name = parameterNamespace + param.name; } params.push(param); } }, addParamFromInput: function(params, name, form, parameterNamespace) { var input = null; if (parameterNamespace) { input = form.children("input[name*='" + name + "']"); } else { input = form.children("input[name='" + name + "']"); } if (input && input.length > 0) { var value = input.val(); PrimeFaces.ajax.Request.addParam(params, name, value, parameterNamespace); } }, extractParameterNamespace: function(form) { var input = form.children("input[name*='" + PrimeFaces.VIEW_STATE + "']"); if (input && input.length > 0) { var name = input[0].name; if (name.length > PrimeFaces.VIEW_STATE.length) { return name.substring(0, name.indexOf(PrimeFaces.VIEW_STATE)); } } return null; } }, Response: { handle: function(xml, status, xhr, updateHandler) { var partialResponseNode = xml.getElementsByTagName("partial-response")[0]; for (var i = 0; i < partialResponseNode.childNodes.length; i++) { var currentNode = partialResponseNode.childNodes[i]; switch (currentNode.nodeName) { case "redirect": PrimeFaces.ajax.ResponseProcessor.doRedirect(currentNode); break; case "changes": var activeElementId = $(document.activeElement).attr('id'); for (var j = 0; j < currentNode.childNodes.length; j++) { var currentChangeNode = currentNode.childNodes[j]; switch (currentChangeNode.nodeName) { case "update": PrimeFaces.ajax.ResponseProcessor.doUpdate(currentChangeNode, xhr, updateHandler); break; case "delete": PrimeFaces.ajax.ResponseProcessor.doDelete(currentChangeNode); break; case "insert": PrimeFaces.ajax.ResponseProcessor.doInsert(currentChangeNode); break; case "attributes": PrimeFaces.ajax.ResponseProcessor.doAttributes(currentChangeNode); break; case "eval": PrimeFaces.ajax.ResponseProcessor.doEval(currentChangeNode); break; case "extension": PrimeFaces.ajax.ResponseProcessor.doExtension(currentChangeNode, xhr); break; } } PrimeFaces.ajax.Response.handleReFocus(activeElementId); PrimeFaces.ajax.Response.destroyDetachedWidgets(); break; case "eval": PrimeFaces.ajax.ResponseProcessor.doEval(currentNode); break; case "extension": PrimeFaces.ajax.ResponseProcessor.doExtension(currentNode, xhr); break; case "error": PrimeFaces.ajax.ResponseProcessor.doError(currentNode, xhr); break; } } }, handleReFocus : function(activeElementId) { // re-focus element if (PrimeFaces.customFocus === false && activeElementId // do we really need to refocus? we just check the current activeElement here && activeElementId !== $(document.activeElement).attr('id')) { var elementToFocus = $(PrimeFaces.escapeClientId(activeElementId)); elementToFocus.focus(); // double check it - required for IE setTimeout(function() { if (!elementToFocus.is(":focus")) { elementToFocus.focus(); } }, 150); } PrimeFaces.customFocus = false; }, destroyDetachedWidgets : function() { // destroy detached widgets for (var i = 0; i < PrimeFaces.detachedWidgets.length; i++) { var widgetVar = PrimeFaces.detachedWidgets[i]; var widget = PF(widgetVar); if (widget) { if (widget.isDetached()) { PrimeFaces.widgets[widgetVar] = null; widget.destroy(); try { delete widget; } catch (e) {} } } } PrimeFaces.detachedWidgets = []; } }, ResponseProcessor: { doRedirect : function(node) { window.location = node.getAttribute('url'); }, doUpdate : function(node, xhr, updateHandler) { var id = node.getAttribute('id'), content = PrimeFaces.ajax.Utils.getContent(node); if (updateHandler && updateHandler.widget && updateHandler.widget.id === id) { updateHandler.handle.call(updateHandler.widget, content); } else { PrimeFaces.ajax.Utils.updateElement(id, content, xhr); } }, doEval : function(node) { var textContent = node.textContent || node.innerText || node.text; $.globalEval(textContent); }, doExtension : function(node, xhr) { if (xhr) { if (node.getAttribute("ln") === "primefaces" && node.getAttribute("type") === "args") { var textContent = node.textContent || node.innerText || node.text; // it's possible that pfArgs are already defined e.g. if portlet parameter namespacing is enabled // the "parameterNamespace" will be encoded on document start // the other parameters will be encoded on document end // --> see PrimePartialResponseWriter if (xhr.pfArgs) { var json = $.parseJSON(textContent); for (var name in json) { xhr.pfArgs[name] = json[name]; } } else { xhr.pfArgs = $.parseJSON(textContent); } } } }, doError : function(node, xhr) { // currently nothing... }, doDelete : function(node) { var id = node.getAttribute('id'); $(PrimeFaces.escapeClientId(id)).remove(); }, doInsert : function(node) { if (!node.childNodes) { return false; } for (var i = 0; i < node.childNodes.length; i++) { var childNode = node.childNodes[i]; var id = childNode.getAttribute('id'); var jq = $(PrimeFaces.escapeClientId(id)); var content = PrimeFaces.ajax.Utils.getContent(childNode); if (childNode.nodeName === "after") { $(content).insertAfter(jq); } else if (childNode.nodeName === "before") { $(content).insertBefore(jq); } } }, doAttributes : function(node) { if (!node.childNodes) { return false; } var id = node.getAttribute('id'); var jq = $(PrimeFaces.escapeClientId(id)); for (var i = 0; i < node.childNodes.length; i++) { var attrNode = node.childNodes[i]; var attrName = attrNode.getAttribute("name"); var attrValue = attrNode.getAttribute("value"); if (!attrName) { return; } if (!attrValue || attrValue === null) { attrValue = ""; } jq.attr(attrName, attrValue); } } }, //Backward compatibility AjaxRequest: function(cfg, ext) { return PrimeFaces.ajax.Request.handle(cfg, ext); } }; PrimeFaces.expressions = {}; PrimeFaces.expressions.SearchExpressionFacade = { resolveComponentsAsSelector: function(expressions) { var splittedExpressions = PrimeFaces.expressions.SearchExpressionFacade.splitExpressions(expressions); var elements = $(); if (splittedExpressions) { for (var i = 0; i < splittedExpressions.length; ++i) { var expression = $.trim(splittedExpressions[i]); if (expression.length > 0) { // skip unresolvable keywords if (expression == '@none' || expression == '@all') { continue; } // just a id if (expression.indexOf("@") == -1) { elements = elements.add( $(document.getElementById(expression))); } // @widget else if (expression.indexOf("@widgetVar(") == 0) { var widgetVar = expression.substring(11, expression.length - 1); var widget = PrimeFaces.widgets[widgetVar]; if (widget) { elements = elements.add( $(document.getElementById(widget.id))); } else { PrimeFaces.error("Widget for widgetVar \"" + widgetVar + "\" not avaiable"); } } // PFS else if (expression.indexOf("@(") == 0) { //converts pfs to jq selector e.g. @(div.mystyle :input) to div.mystyle :input elements = elements.add( $(expression.substring(2, expression.length - 1))); } } } } return elements; }, resolveComponents: function(expressions) { var splittedExpressions = PrimeFaces.expressions.SearchExpressionFacade.splitExpressions(expressions), ids = []; if (splittedExpressions) { for (var i = 0; i < splittedExpressions.length; ++i) { var expression = $.trim(splittedExpressions[i]); if (expression.length > 0) { // just a id or passtrough keywords if (expression.indexOf("@") == -1 || expression == '@none' || expression == '@all') { if (!PrimeFaces.inArray(ids, expression)) { ids.push(expression); } } // @widget else if (expression.indexOf("@widgetVar(") == 0) { var widgetVar = expression.substring(11, expression.length - 1), widget = PrimeFaces.widgets[widgetVar]; if (widget) { if (!PrimeFaces.inArray(ids, widget.id)) { ids.push(widget.id); } } else { PrimeFaces.error("Widget for widgetVar \"" + widgetVar + "\" not avaiable"); } } // PFS else if (expression.indexOf("@(") == 0) { //converts pfs to jq selector e.g. @(div.mystyle :input) to div.mystyle :input var elements = $(expression.substring(2, expression.length - 1)); for (var j = 0; j < elements.length; j++) { var element = $(elements[j]), clientId = element.data(PrimeFaces.CLIENT_ID_DATA) || element.attr('id'); if (!PrimeFaces.inArray(ids, clientId)) { ids.push(clientId); } } } } } } return ids; }, splitExpressions: function(expression) { if (PrimeFaces.isIE(7)) { expression = expression.split(''); } var expressions = []; var buffer = ''; var parenthesesCounter = 0; for (var i = 0; i < expression.length; i++) { var c = expression[i]; if (c === '(') { parenthesesCounter++; } if (c === ')') { parenthesesCounter--; } if ((c === ' ' || c === ',') && parenthesesCounter === 0) { // lets add token inside buffer to our tokens expressions.push(buffer); // now we need to clear buffer buffer = ''; } else { buffer += c; } } // lets not forget about part after the separator expressions.push(buffer); return expressions; } }; /* Simple JavaScript Inheritance * By John Resig http://ejohn.org/ * MIT Licensed. */ // Inspired by base2 and Prototype (function(){ var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function(){}; // Create a new Class that inherits from this class Class.extend = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if ( !initializing && this.init ) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.prototype.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })(); PrimeFaces.widget = {}; /** * BaseWidget for PrimeFaces Widgets */ PrimeFaces.widget.BaseWidget = Class.extend({ init: function(cfg) { this.cfg = cfg; this.id = cfg.id; this.jqId = PrimeFaces.escapeClientId(this.id); this.jq = $(this.jqId); this.widgetVar = cfg.widgetVar; //remove script tag $(this.jqId + '_s').remove(); if (this.widgetVar) { var $this = this; this.jq.on("remove", function() { PrimeFaces.detachedWidgets.push($this.widgetVar); }); } }, //used in ajax updates, reloads the widget configuration refresh: function(cfg) { return this.init(cfg); }, //will be called when the widget after a ajax request if the widget is detached destroy: function() { PrimeFaces.debug("Destroyed detached widget: " + this.widgetVar); }, //checks if the given widget is detached isDetached: function() { return document.getElementById(this.id) === null; }, //returns jquery object representing the main dom element related to the widget getJQ: function(){ return this.jq; }, /** * Removes the widget's script block from the DOM. * * @param {string} clientId The id of the widget. */ removeScriptElement: function(clientId) { $(PrimeFaces.escapeClientId(clientId) + '_s').remove(); } }); /** * Widgets that require to be visible to initialize properly for hidden container support */ PrimeFaces.widget.DeferredWidget = PrimeFaces.widget.BaseWidget.extend({ renderDeferred: function() { if(this.jq.is(':visible')) { this._render(); } else { var container = this.jq.closest('.ui-hidden-container'), $this = this; if(container.length) { this.addDeferredRender(this.id, container, function() { return $this.render(); }); } } }, render: function() { if(this.jq.is(':visible')) { this._render(); return true; } else { return false; } }, /** * Must be overriden */ _render: function() { throw 'Unsupported Operation'; }, destroy: function() { this._super(); PrimeFaces.removeDeferredRenders(this.id); }, addDeferredRender: function(widgetId, container, callback) { PrimeFaces.addDeferredRender(widgetId, container.attr('id'), callback); if(container.is(':hidden')) { var parentContainer = this.jq.closest('.ui-hidden-container'); if(parentContainer.length) { this.addDeferredRender(widgetId, container.parent().closest('.ui-hidden-container'), callback); } } } }); PrimeFaces.dialog = {}; PrimeFaces.dialog.DialogHandler = { openDialog: function(cfg) { var dialogId = cfg.sourceComponentId + '_dlg'; if(document.getElementById(dialogId)) { return; } var dialogWidgetVar = cfg.sourceComponentId.replace(/:/g, '_') + '_dlgwidget', dialogDOM = $('
') .append('
'); if(cfg.options.closable !== false) { dialogDOM.children('.ui-dialog-titlebar') .append(''); } dialogDOM.append('
' + '').appendTo(this.content); if(this.cfg.iframeTitle) { this.iframe.attr('title', this.cfg.iframeTitle); } this.links.click(function(e) { if(!$this.iframeLoaded) { $this.content.addClass('ui-lightbox-loading').css({ width: $this.cfg.width ,height: $this.cfg.height }); $this.show(); $this.iframe.on('load', function() { $this.iframeLoaded = true; $this.content.removeClass('ui-lightbox-loading'); }) .attr('src', $this.links.eq(0).attr('href')); } else { $this.show(); } var title = $this.links.eq(0).attr('title'); if(title) { $this.captionText.text(title); $this.caption.slideDown(); } e.preventDefault(); }); }, bindCommonEvents: function() { var $this = this, hideNS = PrimeFaces.env.ios ? 'touchstart.' + this.id: 'click.' + this.id, resizeNS = 'resize.' + this.id; this.closeIcon.mouseover(function() { $(this).addClass('ui-state-hover'); }) .mouseout(function() { $(this).removeClass('ui-state-hover'); }) this.closeIcon.click(function(e) { $this.hide(); e.preventDefault(); }); //hide when outside is clicked $(document.body).off(hideNS).on(hideNS, function (e) { if($this.isHidden()) { return; } //do nothing if target is the link var target = $(e.target); if(target.data('primefaces-lightbox-trigger')) { return; } //hide if mouse is outside of lightbox var offset = $this.panel.offset(), pageX, pageY; if(e.originalEvent.touches) { pageX = e.originalEvent.touches[0].pageX; pageY = e.originalEvent.touches[0].pageY; } else { pageX = e.pageX; pageY = e.pageY; } if(pageX < offset.left || pageX > offset.left + $this.panel.width() || pageY < offset.top || pageY > offset.top + $this.panel.height()) { e.preventDefault(); $this.hide(); } }); //sync window resize $(window).off(resizeNS).on(resizeNS, function() { if(!$this.isHidden()) { $(document.body).children('.ui-widget-overlay').css({ 'width': $(document).width() ,'height': $(document).height() }); } }); }, show: function() { this.center(); this.panel.css('z-index', ++PrimeFaces.zindex).show(); if(!this.isModalActive()) { this.enableModality(); } if(this.cfg.onShow) { this.cfg.onShow.call(this); } }, hide: function() { this.panel.fadeOut(); this.disableModality(); this.caption.hide(); if(this.cfg.mode == 'image') { this.imageDisplay.hide().attr('src', '').removeAttr('style'); this.hideNavigators(); } if(this.cfg.onHide) { this.cfg.onHide.call(this); } }, center: function() { var win = $(window), left = (win.width() / 2 ) - (this.panel.width() / 2), top = (win.height() / 2 ) - (this.panel.height() / 2); this.panel.css({ 'left': left, 'top': top }); }, enableModality: function() { $(document.body).append('
'). children(this.jqId + '_modal').css({ 'width': $(document).width() ,'height': $(document).height() ,'z-index': this.panel.css('z-index') - 1 }); }, disableModality: function() { $(document.body).children(this.jqId + '_modal').remove(); }, isModalActive: function() { return $(document.body).children(this.jqId + '_modal').length === 1; }, showNavigators: function() { this.navigators.zIndex(this.imageDisplay.zIndex() + 1).show(); }, hideNavigators: function() { this.navigators.hide(); }, addOnshowHandler: function(fn) { this.onshowHandlers.push(fn); }, isHidden: function() { return this.panel.is(':hidden'); }, showURL: function(opt) { if(opt.width) this.iframe.attr('width', opt.width); if(opt.height) this.iframe.attr('height', opt.height); this.iframe.attr('src', opt.src); this.captionText.text(opt.title||''); this.caption.slideDown(); this.show(); } }); /** * PrimeFaces Menu Widget */ PrimeFaces.widget.Menu = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); if(this.cfg.overlay) { this.initOverlay(); } this.keyboardTarget = this.jq.children('.ui-helper-hidden-accessible'); }, initOverlay: function() { var $this = this; this.trigger = PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector(this.cfg.trigger); //mark trigger and descandants of trigger as a trigger for a primefaces overlay this.trigger.data('primefaces-overlay-target', true).find('*').data('primefaces-overlay-target', true); /* * we might have two menus with same ids if an ancestor of a menu is updated, * if so remove the previous one and refresh jq */ if(this.jq.length > 1){ $(document.body).children(this.jqId).remove(); this.jq = $(this.jqId); this.jq.appendTo(document.body); } else if(this.jq.parent().is(':not(body)')) { this.jq.appendTo(document.body); } this.cfg.pos = { my: this.cfg.my ,at: this.cfg.at ,of: this.trigger } this.trigger.bind(this.cfg.triggerEvent + '.ui-menu', function(e) { var trigger = $(this); if($this.jq.is(':visible')) { $this.hide(); } else { $this.show(); if(trigger.is(':button')) { trigger.addClass('ui-state-focus'); } e.preventDefault(); } }); //hide overlay on document click var hideNS = 'mousedown.' + this.id; $(document.body).off(hideNS).on(hideNS, function (e) { if($this.jq.is(":hidden")) { return; } //do nothing if mousedown is on trigger var target = $(e.target); if(target.is($this.trigger.get(0))||$this.trigger.has(target).length > 0) { return; } //hide if mouse is outside of overlay except trigger var offset = $this.jq.offset(); if(e.pageX < offset.left || e.pageX > offset.left + $this.jq.width() || e.pageY < offset.top || e.pageY > offset.top + $this.jq.height()) { $this.hide(e); } }); //Hide overlay on resize var resizeNS = 'resize.' + this.id; $(window).off(resizeNS).on(resizeNS, function() { if($this.jq.is(':visible')) { $this.align(); } }); //dialog support this.setupDialogSupport(); }, setupDialogSupport: function() { var dialog = this.trigger.parents('.ui-dialog:first'); if(dialog.length == 1) { this.jq.css('position', 'fixed'); } }, show: function() { this.align(); this.jq.css('z-index', ++PrimeFaces.zindex).show(); }, hide: function() { this.jq.fadeOut('fast'); if(this.trigger && this.trigger.is(':button')) { this.trigger.removeClass('ui-state-focus'); } }, align: function() { var fixedPosition = this.jq.css('position') == 'fixed', win = $(window), positionOffset = fixedPosition ? '-' + win.scrollLeft() + ' -' + win.scrollTop() : null; this.cfg.pos.offset = positionOffset; this.jq.css({left:'', top:''}).position(this.cfg.pos); } }); /** * PrimeFaces TieredMenu Widget */ PrimeFaces.widget.TieredMenu = PrimeFaces.widget.Menu.extend({ init: function(cfg) { this._super(cfg); this.cfg.toggleEvent = this.cfg.toggleEvent||'hover'; this.links = this.jq.find('a.ui-menuitem-link:not(.ui-state-disabled)'); this.rootLinks = this.jq.find('> ul.ui-menu-list > .ui-menuitem > .ui-menuitem-link'); this.bindEvents(); }, bindEvents: function() { this.bindItemEvents(); this.bindKeyEvents(); this.bindDocumentHandler(); }, bindItemEvents: function() { if(this.cfg.toggleEvent === 'hover') this.bindHoverModeEvents(); else if(this.cfg.toggleEvent === 'click') this.bindClickModeEvents(); }, bindHoverModeEvents: function() { var $this = this; this.links.mouseenter(function() { var link = $(this), menuitem = link.parent(); var activeSibling = menuitem.siblings('.ui-menuitem-active'); if(activeSibling.length === 1) { activeSibling.find('li.ui-menuitem-active').each(function() { $this.deactivate($(this)); }); $this.deactivate(activeSibling); } if($this.cfg.autoDisplay||$this.active) { if(menuitem.hasClass('ui-menuitem-active')) $this.reactivate(menuitem); else $this.activate(menuitem); } else { $this.highlight(menuitem); } }); this.rootLinks.click(function(e) { var link = $(this), menuitem = link.parent(), submenu = menuitem.children('ul.ui-menu-child'); $this.itemClick = true; if(submenu.length === 1) { if(submenu.is(':visible')) { $this.active = false; $this.deactivate(menuitem); } else { $this.active = true; $this.highlight(menuitem); $this.showSubmenu(menuitem, submenu); } } }); this.links.filter('.ui-submenu-link').click(function(e) { $this.itemClick = true; e.preventDefault(); }); this.jq.find('ul.ui-menu-list').mouseleave(function(e) { if($this.activeitem) { $this.deactivate($this.activeitem); } e.stopPropagation(); }); }, bindClickModeEvents: function() { var $this = this; this.links.mouseenter(function() { var menuitem = $(this).parent(); if(!menuitem.hasClass('ui-menuitem-active')) { menuitem.addClass('ui-menuitem-highlight').children('a.ui-menuitem-link').addClass('ui-state-hover'); } }) .mouseleave(function() { var menuitem = $(this).parent(); if(!menuitem.hasClass('ui-menuitem-active')) { menuitem.removeClass('ui-menuitem-highlight').children('a.ui-menuitem-link').removeClass('ui-state-hover'); } }); this.links.filter('.ui-submenu-link').on('click.tieredMenu', function(e) { var link = $(this), menuitem = link.parent(), submenu = menuitem.children('ul.ui-menu-child'); $this.itemClick = true; var activeSibling = menuitem.siblings('.ui-menuitem-active'); if(activeSibling.length) { activeSibling.find('li.ui-menuitem-active').each(function() { $this.deactivate($(this)); }); $this.deactivate(activeSibling); } if(submenu.length) { if(submenu.is(':visible')) { $this.deactivate(menuitem); menuitem.addClass('ui-menuitem-highlight').children('a.ui-menuitem-link').addClass('ui-state-hover'); } else { menuitem.addClass('ui-menuitem-active').children('a.ui-menuitem-link').removeClass('ui-state-hover').addClass('ui-state-active'); $this.showSubmenu(menuitem, submenu); } } e.preventDefault(); }); }, bindKeyEvents: function() { //not implemented }, bindDocumentHandler: function() { var $this = this, clickNS = 'click.' + this.id; $(document.body).off(clickNS).on(clickNS, function(e) { if($this.itemClick) { $this.itemClick = false; return; } $this.reset(); }); }, deactivate: function(menuitem, animate) { this.activeitem = null; menuitem.children('a.ui-menuitem-link').removeClass('ui-state-hover ui-state-active'); menuitem.removeClass('ui-menuitem-active ui-menuitem-highlight'); if(animate) menuitem.children('ul.ui-menu-child').fadeOut('fast'); else menuitem.children('ul.ui-menu-child').hide(); }, activate: function(menuitem) { this.highlight(menuitem); var submenu = menuitem.children('ul.ui-menu-child'); if(submenu.length == 1) { this.showSubmenu(menuitem, submenu); } }, reactivate: function(menuitem) { this.activeitem = menuitem; var submenu = menuitem.children('ul.ui-menu-child'), activeChilditem = submenu.children('li.ui-menuitem-active:first'), _self = this; if(activeChilditem.length == 1) { _self.deactivate(activeChilditem); } }, highlight: function(menuitem) { this.activeitem = menuitem; menuitem.children('a.ui-menuitem-link').addClass('ui-state-hover'); menuitem.addClass('ui-menuitem-active'); }, showSubmenu: function(menuitem, submenu) { var pos ={ my: 'left top', at: 'right top', of: menuitem, collision: 'flipfit' }; submenu.css('z-index', ++PrimeFaces.zindex) .show() .position(pos); }, reset: function() { var $this = this; this.active = false; this.jq.find('li.ui-menuitem-active').each(function() { $this.deactivate($(this), true); }); } }); /** * PrimeFaces Menubar Widget */ PrimeFaces.widget.Menubar = PrimeFaces.widget.TieredMenu.extend({ showSubmenu: function(menuitem, submenu) { var win = $(window), submenuOffsetTop = null, submenuCSS = { 'z-index': ++PrimeFaces.zindex }; if(menuitem.parent().hasClass('ui-menu-child')) { submenuCSS.left = menuitem.outerWidth(); submenuCSS.top = 0; submenuOffsetTop = menuitem.offset().top - win.scrollTop(); } else { submenuCSS.left = 0; submenuCSS.top = menuitem.outerHeight(); menuitem.offset().top - win.scrollTop(); submenuOffsetTop = menuitem.offset().top + submenuCSS.top - win.scrollTop(); } //adjust height within viewport submenu.css('height', 'auto'); if((submenuOffsetTop + submenu.outerHeight()) > win.height()) { submenuCSS.overflow = 'auto'; submenuCSS.height = win.height() - (submenuOffsetTop + 20); } submenu.css(submenuCSS).show(); }, //@Override bindKeyEvents: function() { var $this = this; this.keyboardTarget.on('focus.menubar', function(e) { $this.highlight($this.links.eq(0).parent()); }) .on('blur.menubar', function() { $this.reset(); }) .on('keydown.menu', function(e) { var currentitem = $this.activeitem; if(!currentitem) { return; } var isRootLink = !currentitem.closest('ul').hasClass('ui-menu-child'), keyCode = $.ui.keyCode; switch(e.which) { case keyCode.LEFT: if(isRootLink) { var prevItem = currentitem.prevAll('.ui-menuitem:not(.ui-menubar-options):first'); if(prevItem.length) { $this.deactivate(currentitem); $this.highlight(prevItem); } e.preventDefault(); } else { if(currentitem.hasClass('ui-menu-parent') && currentitem.children('.ui-menu-child').is(':visible')) { $this.deactivate(currentitem); $this.highlight(currentitem); } else { var parentItem = currentitem.parent().parent(); $this.deactivate(currentitem); $this.deactivate(parentItem); $this.highlight(parentItem); } } break; case keyCode.RIGHT: if(isRootLink) { var nextItem = currentitem.nextAll('.ui-menuitem:not(.ui-menubar-options):first'); if(nextItem.length) { $this.deactivate(currentitem); $this.highlight(nextItem); } e.preventDefault(); } else { if(currentitem.hasClass('ui-menu-parent')) { var submenu = currentitem.children('.ui-menu-child'); if(submenu.is(':visible')) $this.highlight(submenu.children('.ui-menuitem:first')); else $this.activate(currentitem); } } break; case keyCode.UP: if(!isRootLink) { var prevItem = currentitem.prev('.ui-menuitem'); if(prevItem.length) { $this.deactivate(currentitem); $this.highlight(prevItem); } } e.preventDefault(); break; case keyCode.DOWN: if(isRootLink) { var submenu = currentitem.children('ul.ui-menu-child'); if(submenu.is(':visible')) $this.highlight(submenu.children('.ui-menuitem:first')); else $this.activate(currentitem); } else { var nextItem = currentitem.next('.ui-menuitem'); if(nextItem.length) { $this.deactivate(currentitem); $this.highlight(nextItem); } } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: currentitem.children('.ui-menuitem-link').trigger('click'); $this.jq.blur(); e.preventDefault(); break; } }); } }); /** * PrimeFaces SlideMenu Widget */ PrimeFaces.widget.SlideMenu = PrimeFaces.widget.Menu.extend({ init: function(cfg) { this._super(cfg); //elements this.submenus = this.jq.find('ul.ui-menu-list'); this.wrapper = this.jq.children('div.ui-slidemenu-wrapper'); this.content = this.wrapper.children('div.ui-slidemenu-content'); this.rootList = this.content.children('ul.ui-menu-list'); this.links = this.jq.find('a.ui-menuitem-link:not(.ui-state-disabled)'); this.backward = this.wrapper.children('div.ui-slidemenu-backward'); this.rendered = false; //config this.stack = []; this.jqWidth = this.jq.width(); if(!this.jq.hasClass('ui-menu-dynamic')) { if(this.jq.is(':not(:visible)')) { var hiddenParent = this.jq.closest('.ui-hidden-container'), hiddenParentWidgetVar = hiddenParent.data('widget'), $this = this; if(hiddenParentWidgetVar) { var hiddenParentWidget = PF(hiddenParentWidgetVar); if(hiddenParentWidget) { hiddenParentWidget.addOnshowHandler(function() { return $this.render(); }); } } } else { this.render(); } } this.bindEvents(); }, bindEvents: function() { var $this = this; this.links.mouseenter(function() { $(this).addClass('ui-state-hover'); }) .mouseleave(function() { $(this).removeClass('ui-state-hover'); }) .click(function(e) { var link = $(this), submenu = link.next(); if(submenu.length) { $this.forward(submenu); e.preventDefault(); } }); this.backward.click(function() { $this.back(); }); }, forward: function(submenu) { var _self = this; this.push(submenu); var rootLeft = -1 * (this.depth() * this.jqWidth); submenu.show().css({ left: this.jqWidth }); this.rootList.animate({ left: rootLeft }, 500, 'easeInOutCirc', function() { if(_self.backward.is(':hidden')) { _self.backward.fadeIn('fast'); } }); }, back: function() { var _self = this, last = this.pop(), depth = this.depth(); var rootLeft = -1 * (depth * this.jqWidth); this.rootList.animate({ left: rootLeft }, 500, 'easeInOutCirc', function() { if(last !== null) { last.hide(); } if(depth == 0) { _self.backward.fadeOut('fast'); } }); }, push: function(submenu) { this.stack.push(submenu); }, pop: function() { return this.stack.length !== 0 ? this.stack.pop() : null; }, last: function() { return this.stack[this.stack.length - 1]; }, depth: function() { return this.stack.length; }, render: function() { this.submenus.width(this.jq.width()); this.wrapper.height(this.rootList.outerHeight(true) + this.backward.outerHeight(true)); this.content.height(this.rootList.outerHeight(true)); this.rendered = true; }, show: function() { this.align(); this.jq.css('z-index', ++PrimeFaces.zindex).show(); if(!this.rendered) { this.render(); } } }); /** * PrimeFaces PlainMenu Widget */ PrimeFaces.widget.PlainMenu = PrimeFaces.widget.Menu.extend({ init: function(cfg) { this._super(cfg); this.menuitemLinks = this.jq.find('.ui-menuitem-link:not(.ui-state-disabled)'); //events this.bindEvents(); if(this.cfg.toggleable) { this.collapsedIds = []; this.stateKey = 'menu-' + this.id; this.restoreState(); } }, bindEvents: function() { var $this = this; this.menuitemLinks.mouseenter(function(e) { if($this.jq.is(':focus')) { $this.jq.blur(); } $(this).addClass('ui-state-hover'); }) .mouseleave(function(e) { $(this).removeClass('ui-state-hover'); }); if(this.cfg.overlay) { this.menuitemLinks.click(function() { $this.hide(); }); } if(this.cfg.toggleable) { this.jq.find('> .ui-menu-list > .ui-widget-header').on('mouseover.menu', function() { $(this).addClass('ui-state-hover'); }) .on('mouseout.menu', function() { $(this).removeClass('ui-state-hover'); }) .on('click.menu', function(e) { var header = $(this); if(header.find('> h3 > .ui-icon').hasClass('ui-icon-triangle-1-s')) $this.collapseSubmenu(header, true); else $this.expandSubmenu(header, true); PrimeFaces.clearSelection(); e.preventDefault(); }); } this.keyboardTarget.on('focus.menu', function() { $this.menuitemLinks.eq(0).addClass('ui-state-hover'); }) .on('blur.menu', function() { $this.menuitemLinks.filter('.ui-state-hover').removeClass('ui-state-hover'); }) .on('keydown.menu', function(e) { var currentLink = $this.menuitemLinks.filter('.ui-state-hover'), keyCode = $.ui.keyCode; switch(e.which) { case keyCode.UP: var prevItem = currentLink.parent().prevAll('.ui-menuitem:first'); if(prevItem.length) { currentLink.removeClass('ui-state-hover'); prevItem.children('.ui-menuitem-link').addClass('ui-state-hover'); } e.preventDefault(); break; case keyCode.DOWN: var nextItem = currentLink.parent().nextAll('.ui-menuitem:first'); if(nextItem.length) { currentLink.removeClass('ui-state-hover'); nextItem.children('.ui-menuitem-link').addClass('ui-state-hover'); } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: currentLink.trigger('click'); $this.jq.blur(); e.preventDefault(); break; } }); }, collapseSubmenu: function(header, stateful) { var items = header.nextUntil('li.ui-widget-header'); header.attr('aria-expanded', false) .find('> h3 > .ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e'); items.hide(); if(stateful) { this.collapsedIds.push(header.attr('id')); this.saveState(); } }, expandSubmenu: function(header, stateful) { var items = header.nextUntil('li.ui-widget-header'); header.attr('aria-expanded', false) .find('> h3 > .ui-icon').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s'); items.show(); if(stateful) { var id = header.attr('id'); this.collapsedIds = $.grep(this.collapsedIds, function(value) { return (value !== id); }); this.saveState(); } }, saveState: function() { PrimeFaces.setCookie(this.stateKey, this.collapsedIds.join(',')); }, restoreState: function() { var collapsedIdsAsString = PrimeFaces.getCookie(this.stateKey); if(collapsedIdsAsString) { this.collapsedIds = collapsedIdsAsString.split(','); for(var i = 0 ; i < this.collapsedIds.length; i++) { this.collapseSubmenu($(PrimeFaces.escapeClientId(this.collapsedIds[i])), false); } } }, clearState: function() { PrimeFaces.setCookie(this.stateKey, null); } }); /* * PrimeFaces MenuButton Widget */ PrimeFaces.widget.MenuButton = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.menuId = this.jqId + '_menu'; this.button = this.jq.children('button'); this.menu = this.jq.children('.ui-menu'); this.menuitems = this.jq.find('.ui-menuitem'); this.cfg.disabled = this.button.is(':disabled'); if(!this.cfg.disabled) { this.bindEvents(); this.appendPanel(); } }, bindEvents: function() { var $this = this; //button visuals this.button.mouseover(function(){ if(!$this.button.hasClass('ui-state-focus')) { $this.button.addClass('ui-state-hover'); } }).mouseout(function() { if(!$this.button.hasClass('ui-state-focus')) { $this.button.removeClass('ui-state-hover ui-state-active'); } }).mousedown(function() { $(this).removeClass('ui-state-focus ui-state-hover').addClass('ui-state-active'); }).mouseup(function() { var el = $(this); el.removeClass('ui-state-active') if($this.menu.is(':visible')) { el.addClass('ui-state-hover'); $this.hide(); } else { el.addClass('ui-state-focus'); $this.show(); } }).focus(function() { $(this).addClass('ui-state-focus'); }).blur(function() { $(this).removeClass('ui-state-focus'); }); //mark button and descandants of button as a trigger for a primefaces overlay this.button.data('primefaces-overlay-target', true).find('*').data('primefaces-overlay-target', true); //menuitem visuals this.menuitems.mouseover(function(e) { var element = $(this); if(!element.hasClass('ui-state-disabled')) { element.addClass('ui-state-hover'); } }).mouseout(function(e) { $(this).removeClass('ui-state-hover'); }).click(function() { $this.button.removeClass('ui-state-focus'); $this.hide(); }); /** * handler for document mousedown to hide the overlay **/ var hideNS = 'mousedown.' + this.id; $(document.body).off(hideNS).on(hideNS, function (e) { //do nothing if hidden already if($this.menu.is(":hidden") || $this.cfg.disabled) { return; } //do nothing if mouse is on button var target = $(e.target); if(target.is($this.button)||$this.button.has(target).length > 0) { return; } //hide overlay if mouse is outside of overlay except button var offset = $this.menu.offset(); if(e.pageX < offset.left || e.pageX > offset.left + $this.menu.width() || e.pageY < offset.top || e.pageY > offset.top + $this.menu.height()) { $this.button.removeClass('ui-state-focus ui-state-hover'); $this.hide(); } }); //Realign overlay on window resize var resizeNS = 'resize.' + this.id; $(window).unbind(resizeNS).bind(resizeNS, function() { if($this.menu.is(':visible')) { $this.alignPanel(); } }); //aria this.button.attr('role', 'button').attr('aria-disabled', this.button.is(':disabled')); }, appendPanel: function() { var container = this.cfg.appendTo ? PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector(this.cfg.appendTo): $(document.body); if(!container.is(this.jq)) { container.children(this.menuId).remove(); this.menu.appendTo(container); } }, show: function() { this.alignPanel(); this.menu.show(); }, hide: function() { this.menu.fadeOut('fast'); }, alignPanel: function() { this.menu.css({left:'', top:'','z-index': ++PrimeFaces.zindex}); if(this.menu.parent().is(this.jq)) { this.menu.css({ left: 0, top: this.jq.innerHeight() }); } else { this.menu.position({ my: 'left top' ,at: 'left bottom' ,of: this.button }); } } }); /** * PrimeFaces ContextMenu Widget */ PrimeFaces.widget.ContextMenu = PrimeFaces.widget.TieredMenu.extend({ init: function(cfg) { cfg.autoDisplay = true; this._super(cfg); this.cfg.selectionMode = this.cfg.selectionMode||'multiple'; var _self = this, documentTarget = (this.cfg.target === undefined); //event this.cfg.event = this.cfg.event||'contextmenu'; //target this.jqTargetId = documentTarget ? document : PrimeFaces.escapeClientId(this.cfg.target); this.jqTarget = $(this.jqTargetId); //append to body if(!this.jq.parent().is(document.body)) { this.jq.appendTo('body'); } //attach contextmenu if(documentTarget) { $(document).off('contextmenu.ui-contextmenu').on('contextmenu.ui-contextmenu', function(e) { _self.show(e); }); } else { if(this.cfg.type === 'DataTable') { this.bindDataTable(); } else if(this.cfg.type === 'TreeTable') { this.bindTreeTable(); } else if(this.cfg.type === 'Tree') { this.bindTree(); } else { var event = this.cfg.event + '.ui-contextmenu'; $(document).off(event, this.jqTargetId).on(event, this.jqTargetId, null, function(e) { _self.show(e); }); } } }, bindDataTable: function() { var rowSelector = this.jqTargetId + ' tbody.ui-datatable-data > tr.ui-widget-content.ui-datatable-selectable:not(.ui-datatable-empty-message)', event = this.cfg.event + '.datatable', $this = this; $(document).off(event, rowSelector) .on(event, rowSelector, null, function(e) { var widget = PrimeFaces.widgets[$this.cfg.targetWidgetVar]; if(widget.cfg.selectionMode) { widget.onRowRightClick(e, this, $this.cfg.selectionMode); $this.show(e); } else if(widget.cfg.editMode === 'cell') { var target = $(e.target), cell = target.is('td.ui-editable-column') ? target : target.parents('td.ui-editable-column:first'); if(widget.contextMenuCell) { widget.contextMenuCell.removeClass('ui-state-highlight'); } widget.contextMenuClick = true; widget.contextMenuCell = cell; widget.contextMenuCell.addClass('ui-state-highlight'); $this.show(e); } }); }, bindTreeTable: function() { var rowSelector = this.jqTargetId + ' .ui-treetable-data > ' + (this.cfg.nodeType ? 'tr.ui-treetable-selectable-node.' + this.cfg.nodeType : 'tr.ui-treetable-selectable-node'), event = this.cfg.event + '.treetable', _self = this; $(document).off(event, rowSelector) .on(event, rowSelector, null, function(e) { PrimeFaces.widgets[_self.cfg.targetWidgetVar].onRowRightClick(e, $(this)); _self.show(e); e.preventDefault(); }); }, bindTree: function() { var nodeContentSelector = this.jqTargetId + ' .ui-tree-selectable', nodeEvent = this.cfg.nodeType ? this.cfg.event + '.treenode.' + this.cfg.nodeType : this.cfg.event + '.treenode', containerEvent = this.cfg.event + '.tree', $this = this; $(document).off(nodeEvent, nodeContentSelector) .on(nodeEvent, nodeContentSelector, null, function(e) { var nodeContent = $(this); if($this.cfg.nodeType === undefined || nodeContent.parent().data('nodetype') === $this.cfg.nodeType) { PrimeFaces.widgets[$this.cfg.targetWidgetVar].nodeRightClick(e, nodeContent); $this.show(e); e.preventDefault(); } }); $(document).off(containerEvent, this.jqTargetId) .on(containerEvent, this.jqTargetId, null, function(e) { if(PrimeFaces.widgets[$this.cfg.targetWidgetVar].isEmpty()) { $this.show(e); e.preventDefault(); } }); }, refresh: function(cfg) { var jqId = PrimeFaces.escapeClientId(cfg.id), instances = $(jqId); if(instances.length > 1) { $(document.body).children(jqId).remove(); } this.init(cfg); }, bindItemEvents: function() { this._super(); var _self = this; //hide menu on item click this.links.bind('click', function() { _self.hide(); }); }, bindDocumentHandler: function() { var $this = this, clickNS = 'click.' + this.id; //hide overlay when document is clicked $(document.body).off(clickNS).on(clickNS, function(e) { if($this.jq.is(":hidden")) { return; } $this.hide(); }); }, show: function(e) { if(this.cfg.targetFilter && $(e.target).is(':not(' + this.cfg.targetFilter + ')')) { return; } //hide other contextmenus if any $(document.body).children('.ui-contextmenu:visible').hide(); var win = $(window), left = e.pageX, top = e.pageY, width = this.jq.outerWidth(), height = this.jq.outerHeight(); //collision detection for window boundaries if((left + width) > (win.width())+ win.scrollLeft()) { left = left - width; } if((top + height ) > (win.height() + win.scrollTop())) { top = top - height; } if(this.cfg.beforeShow) { var retVal = this.cfg.beforeShow.call(this, e); if(retVal === false) { return; } } this.jq.css({ 'left': left, 'top': top, 'z-index': ++PrimeFaces.zindex }).show(); e.preventDefault(); }, hide: function() { var _self = this; //hide submenus this.jq.find('li.ui-menuitem-active').each(function() { _self.deactivate($(this), true); }); this.jq.fadeOut('fast'); }, isVisible: function() { return this.jq.is(':visible'); }, getTarget: function() { return this.jqTarget; } }); /** * PrimeFaces MegaMenu Widget */ PrimeFaces.widget.MegaMenu = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.cfg.vertical = this.jq.hasClass('ui-megamenu-vertical'); this.rootList = this.jq.children('ul.ui-menu-list'); this.rootLinks = this.rootList.find('> li.ui-menuitem > a.ui-menuitem-link:not(.ui-state-disabled)'); this.subLinks = this.jq.find('.ui-menu-child a.ui-menuitem-link:not(.ui-state-disabled)'); if(this.cfg.activeIndex !== undefined) { this.rootLinks.eq(this.cfg.activeIndex).addClass('ui-state-active'); } this.bindEvents(); }, bindEvents: function() { var $this = this; this.rootLinks.mouseenter(function(e) { var link = $(this), menuitem = link.parent(); var current = menuitem.siblings('.ui-menuitem-active'); if(current.length > 0) { $this.deactivate(current, false); } if($this.cfg.autoDisplay||$this.active) { $this.activate(menuitem); } else { $this.highlight(menuitem); } }); if(this.cfg.autoDisplay === false) { this.rootLinks.data('primefaces-megamenu', this.id).find('*').data('primefaces-megamenu', this.id) this.rootLinks.click(function(e) { var link = $(this), menuitem = link.parent(), submenu = link.next(); if(submenu.length === 1) { if(submenu.is(':visible')) { $this.active = false; $this.deactivate(menuitem, true); } else { $this.active = true; $this.activate(menuitem); } } e.preventDefault(); }); } else { this.rootLinks.filter('.ui-submenu-link').click(function(e) { e.preventDefault(); }); } this.subLinks.mouseenter(function() { $(this).addClass('ui-state-hover'); }) .mouseleave(function() { $(this).removeClass('ui-state-hover'); }); this.rootList.mouseleave(function(e) { var activeitem = $this.rootList.children('.ui-menuitem-active'); if(activeitem.length === 1) { $this.deactivate(activeitem, false); } }); this.rootList.find('> li.ui-menuitem > ul.ui-menu-child').mouseleave(function(e) { e.stopPropagation(); }); $(document.body).click(function(e) { var target = $(e.target); if(target.data('primefaces-megamenu') === $this.id) { return; } $this.active = false; $this.deactivate($this.rootList.children('li.ui-menuitem-active'), true); }); }, deactivate: function(menuitem, animate) { var link = menuitem.children('a.ui-menuitem-link'), submenu = link.next(); menuitem.removeClass('ui-menuitem-active'); link.removeClass('ui-state-hover'); if(submenu.length > 0) { if(animate) submenu.fadeOut('fast'); else submenu.hide(); } }, highlight: function(menuitem) { var link = menuitem.children('a.ui-menuitem-link'); menuitem.addClass('ui-menuitem-active'); link.addClass('ui-state-hover'); }, activate: function(menuitem) { var submenu = menuitem.children('.ui-menu-child'), $this = this; $this.highlight(menuitem); if(submenu.length > 0) { $this.showSubmenu(menuitem, submenu); } }, showSubmenu: function(menuitem, submenu) { var pos = null; if(this.cfg.vertical) { pos = { my: 'left top', at: 'right top', of: menuitem, collision: 'flipfit' }; } else { pos = { my: 'left top', at: 'left bottom', of: menuitem, collision: 'flipfit' }; } submenu.css('z-index', ++PrimeFaces.zindex) .show() .position(pos); } }); /** * PrimeFaces PanelMenu Widget */ PrimeFaces.widget.PanelMenu = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.headers = this.jq.find('> .ui-panelmenu-panel > h3.ui-panelmenu-header:not(.ui-state-disabled)'); this.menuitemLinks = this.jq.find('.ui-menuitem-link:not(.ui-state-disabled)'); this.treeLinks = this.jq.find('.ui-menu-parent > .ui-menuitem-link:not(.ui-state-disabled)'); this.bindEvents(); this.stateKey = 'panelMenu-' + this.id; this.restoreState(); }, bindEvents: function() { var _self = this; this.headers.mouseover(function() { var element = $(this); if(!element.hasClass('ui-state-active')) { element.addClass('ui-state-hover'); } }).mouseout(function() { var element = $(this); if(!element.hasClass('ui-state-active')) { element.removeClass('ui-state-hover'); } }).click(function(e) { var header = $(this); if(header.hasClass('ui-state-active')) _self.collapseRootSubmenu($(this)); else _self.expandRootSubmenu($(this), false); e.preventDefault(); }); this.menuitemLinks.mouseover(function() { $(this).addClass('ui-state-hover'); }).mouseout(function() { $(this).removeClass('ui-state-hover'); }); this.treeLinks.click(function(e) { var link = $(this), submenu = link.parent(), submenuList = link.next(); if(submenuList.is(':visible')) _self.collapseTreeItem(submenu); else _self.expandTreeItem(submenu, false); e.preventDefault(); }); }, collapseRootSubmenu: function(header) { var panel = header.next(); header.attr('aria-expanded', false).removeClass('ui-state-active ui-corner-top').addClass('ui-state-hover ui-corner-all') .children('.ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e'); panel.attr('aria-hidden', true).slideUp('normal', 'easeInOutCirc'); this.removeAsExpanded(panel); }, expandRootSubmenu: function(header, restoring) { var panel = header.next(); header.attr('aria-expanded', false).addClass('ui-state-active ui-corner-top').removeClass('ui-state-hover ui-corner-all') .children('.ui-icon').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s'); if(restoring) { panel.attr('aria-hidden', false).show(); } else { panel.attr('aria-hidden', false).slideDown('normal', 'easeInOutCirc'); this.addAsExpanded(panel); } }, expandTreeItem: function(submenu, restoring) { submenu.find('> .ui-menuitem-link > .ui-panelmenu-icon').addClass('ui-icon-triangle-1-s'); submenu.children('.ui-menu-list').show(); if(!restoring) { this.addAsExpanded(submenu); } }, collapseTreeItem: function(submenu) { submenu.find('> .ui-menuitem-link > .ui-panelmenu-icon').removeClass('ui-icon-triangle-1-s'); submenu.children('.ui-menu-list').hide(); this.removeAsExpanded(submenu); }, saveState: function() { var expandedNodeIds = this.expandedNodes.join(','); PrimeFaces.setCookie(this.stateKey, expandedNodeIds); }, restoreState: function() { var expandedNodeIds = PrimeFaces.getCookie(this.stateKey); if(expandedNodeIds) { this.collapseAll(); this.expandedNodes = expandedNodeIds.split(','); for(var i = 0 ; i < this.expandedNodes.length; i++) { var element = $(PrimeFaces.escapeClientId(this.expandedNodes[i])); if(element.is('div.ui-panelmenu-content')) this.expandRootSubmenu(element.prev(), true); else if(element.is('li.ui-menu-parent')) this.expandTreeItem(element, true); } } else { this.expandedNodes = []; var activeHeaders = this.headers.filter('.ui-state-active'), activeTreeSubmenus = this.jq.find('.ui-menu-parent > .ui-menu-list:not(.ui-helper-hidden)'); for(var i = 0; i < activeHeaders.length; i++) { this.expandedNodes.push(activeHeaders.eq(i).next().attr('id')); } for(var i = 0; i < activeTreeSubmenus.length; i++) { this.expandedNodes.push(activeTreeSubmenus.eq(i).parent().attr('id')); } } }, removeAsExpanded: function(element) { var id = element.attr('id'); this.expandedNodes = $.grep(this.expandedNodes, function(value) { return value != id; }); this.saveState(); }, addAsExpanded: function(element) { this.expandedNodes.push(element.attr('id')); this.saveState(); }, clearState: function() { PrimeFaces.setCookie(this.stateKey, null); }, collapseAll: function() { this.headers.filter('.ui-state-active').each(function() { var header = $(this); header.removeClass('ui-state-active').children('.ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e').removeClass('ui-icon-triangle-1-s'); header.next().addClass('ui-helper-hidden'); }); this.jq.find('.ui-menu-parent > .ui-menu-list:not(.ui-helper-hidden)').each(function() { $(this).addClass('ui-helper-hidden').prev().children('.ui-panelmenu-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e'); }); } }); /** * PrimeFaces TabMenu Widget */ PrimeFaces.widget.TabMenu = PrimeFaces.widget.Menu.extend({ init: function(cfg) { this._super(cfg); this.items = this.jq.find('> .ui-tabmenu-nav > li:not(.ui-state-disabled)'); this.bindEvents(); }, bindEvents: function() { this.items.on('mouseover.tabmenu', function(e) { var element = $(this); if(!element.hasClass('ui-state-active')) { element.addClass('ui-state-hover'); } }) .on('mouseout.tabmenu', function(e) { $(this).removeClass('ui-state-hover'); }); } }); /** * PrimeFaces Message Widget */ PrimeFaces.widget.Message = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); var text = this.jq.children('.ui-message-error-detail').text(); if(text) { $(PrimeFaces.escapeClientId(this.cfg.target)).data('tooltip', text); } } }); /** * PrimeFaces NotificationBar Widget */ PrimeFaces.widget.NotificationBar = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); var _self = this; //relocate this.jq.css(this.cfg.position, '0').appendTo($('body')); //display initially if(this.cfg.autoDisplay) { $(this.jq).css('display','block') } //bind events this.jq.children('.ui-notificationbar-close').click(function() { _self.hide(); }); }, show: function() { if(this.cfg.effect === 'slide') $(this.jq).slideDown(this.cfg.effect); else if(this.cfg.effect === 'fade') $(this.jq).fadeIn(this.cfg.effect); else if(this.cfg.effect === 'none') $(this.jq).show(); }, hide: function() { if(this.cfg.effect === 'slide') $(this.jq).slideUp(this.cfg.effect); else if(this.cfg.effect === 'fade') $(this.jq).fadeOut(this.cfg.effect); else if(this.cfg.effect === 'none') $(this.jq).hide(); }, isVisible: function() { return this.jq.is(':visible'); }, toggle: function() { if(this.isVisible()) this.hide(); else this.show(); } }); /** * PrimeFaces Panel Widget */ PrimeFaces.widget.Panel = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.header = this.jq.children('div.ui-panel-titlebar'); this.title = this.header.children('span.ui-panel-title'); this.content = $(this.jqId + '_content'); this.bindEvents(); }, bindEvents: function() { if(this.cfg.toggleable) { this.bindToggler(); } if(this.cfg.closable) { this.bindCloser(); } //visuals for action items this.header.find('.ui-panel-titlebar-icon').on('mouseover.panel',function() { $(this).addClass('ui-state-hover'); }).on('mouseout.panel',function() { $(this).removeClass('ui-state-hover'); }); }, toggle: function() { if(this.cfg.collapsed) { this.expand(); PrimeFaces.invokeDeferredRenders(this.id); } else { this.collapse(); } }, expand: function() { this.toggleState(false, 'ui-icon-plusthick', 'ui-icon-minusthick'); if(this.cfg.toggleOrientation === 'vertical') this.slideDown(); else if(this.cfg.toggleOrientation === 'horizontal') this.slideRight(); }, collapse: function() { this.toggleState(true, 'ui-icon-minusthick', 'ui-icon-plusthick'); if(this.cfg.toggleOrientation === 'vertical') this.slideUp(); else if(this.cfg.toggleOrientation === 'horizontal') this.slideLeft(); }, slideUp: function() { this.content.slideUp(this.cfg.toggleSpeed, 'easeInOutCirc'); }, slideDown: function() { this.content.slideDown(this.cfg.toggleSpeed, 'easeInOutCirc'); }, slideLeft: function() { var _self = this; this.originalWidth = this.jq.width(); this.title.hide(); this.toggler.hide(); this.content.hide(); this.jq.animate({ width: '42px' }, this.cfg.toggleSpeed, 'easeInOutCirc', function() { _self.toggler.show(); _self.jq.addClass('ui-panel-collapsed-h'); }); }, slideRight: function() { var _self = this, expandWidth = this.originalWidth||'100%'; this.toggler.hide(); this.jq.animate({ width: expandWidth }, this.cfg.toggleSpeed, 'easeInOutCirc', function() { _self.jq.removeClass('ui-panel-collapsed-h'); _self.title.show(); _self.toggler.show(); _self.content.css({ 'visibility': 'visible' ,'display': 'block' ,'height': 'auto' }); }); }, toggleState: function(collapsed, removeIcon, addIcon) { this.toggler.children('span.ui-icon').removeClass(removeIcon).addClass(addIcon); this.cfg.collapsed = collapsed; this.toggleStateHolder.val(collapsed); this.fireToggleEvent(); }, fireToggleEvent: function() { if(this.cfg.behaviors) { var toggleBehavior = this.cfg.behaviors['toggle']; if(toggleBehavior) { toggleBehavior.call(this); } } }, close: function() { if(this.visibleStateHolder) { this.visibleStateHolder.val(false); } var $this = this; this.jq.fadeOut(this.cfg.closeSpeed, function(e) { if($this.cfg.behaviors) { var closeBehavior = $this.cfg.behaviors['close']; if(closeBehavior) { closeBehavior.call($this); } } } ); }, show: function() { var $this = this; $(this.jqId).fadeIn(this.cfg.closeSpeed, function() { PrimeFaces.invokeDeferredRenders($this.id); }); this.visibleStateHolder.val(true); }, bindToggler: function() { var _self = this; this.toggler = $(this.jqId + '_toggler'); this.toggleStateHolder = $(this.jqId + '_collapsed'); this.toggler.click(function() {_self.toggle();}); }, bindCloser: function() { var _self = this; this.closer = $(this.jqId + '_closer'); this.visibleStateHolder = $(this.jqId + "_visible"); this.closer.click(function() {_self.close();}); } }); /** * PrimeFaces Poll Widget */ PrimeFaces.widget.Poll = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this.cfg = cfg; this.id = this.cfg.id; this.active = false; if(this.cfg.autoStart) { this.start(); } }, refresh: function(cfg) { if(this.isActive()) { this.stop(); } this.init(cfg); }, start: function() { this.timer = setInterval(this.cfg.fn, (this.cfg.frequency * 1000)); this.active = true; }, stop: function() { clearInterval(this.timer); this.active = false; }, handleComplete: function(xhr, status, args) { if(args.stop) { this.stop(); } }, isActive: function() { return this.active; } }); /** * PrimeFaces OrderList Widget */ PrimeFaces.widget.OrderList = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.list = this.jq.find('.ui-orderlist-list'), this.items = this.list.children('.ui-orderlist-item'); this.input = $(this.jqId + '_values'); this.cfg.effect = this.cfg.effect||'fade'; this.cfg.disabled = this.jq.hasClass('ui-state-disabled'); var $this = this; if(!this.cfg.disabled) { this.generateItems(); this.setupButtons(); this.bindEvents(); //Enable dnd this.list.sortable({ revert: 1, start: function(event, ui) { PrimeFaces.clearSelection(); } ,update: function(event, ui) { $this.onDragDrop(event, ui); } }); } }, generateItems: function() { var $this = this; this.list.children('.ui-orderlist-item').each(function() { var item = $(this), itemValue = item.data('item-value'); $this.input.append(''); }); }, bindEvents: function() { var $this = this; this.items.on('mouseover.orderList', function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) $(this).addClass('ui-state-hover'); }) .on('mouseout.orderList', function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) $(this).removeClass('ui-state-hover'); }) .on('mousedown.orderList', function(e) { var element = $(this), metaKey = (e.metaKey||e.ctrlKey); if(!metaKey) { element.removeClass('ui-state-hover').addClass('ui-state-highlight') .siblings('.ui-state-highlight').removeClass('ui-state-highlight'); $this.fireItemSelectEvent(element); } else { if(element.hasClass('ui-state-highlight')) { element.removeClass('ui-state-highlight'); $this.fireItemUnselectEvent(element); } else { element.removeClass('ui-state-hover').addClass('ui-state-highlight'); $this.fireItemSelectEvent(element); } } }); }, setupButtons: function() { var $this = this; PrimeFaces.skinButton(this.jq.find('.ui-button')); this.jq.find(' .ui-orderlist-controls .ui-orderlist-button-move-up').click(function() {$this.moveUp($this.sourceList);}); this.jq.find(' .ui-orderlist-controls .ui-orderlist-button-move-top').click(function() {$this.moveTop($this.sourceList);}); this.jq.find(' .ui-orderlist-controls .ui-orderlist-button-move-down').click(function() {$this.moveDown($this.sourceList);}); this.jq.find(' .ui-orderlist-controls .ui-orderlist-button-move-bottom').click(function() {$this.moveBottom($this.sourceList);}); }, onDragDrop: function(event, ui) { ui.item.removeClass('ui-state-highlight'); this.saveState(); this.fireReorderEvent(); }, saveState: function() { this.input.children().remove(); this.generateItems(); }, moveUp: function() { var $this = this; this.items.filter('.ui-state-highlight').each(function() { var item = $(this); if(!item.is(':first-child')) { item.hide($this.cfg.effect, {}, 'fast', function() { item.insertBefore(item.prev()).show($this.cfg.effect, {}, 'fast', function() { $this.saveState(); $this.fireReorderEvent(); }); }); } }); }, moveTop: function() { var $this = this; this.items.filter('.ui-state-highlight').each(function() { var item = $(this); if(!item.is(':first-child')) { item.hide($this.cfg.effect, {}, 'fast', function() { item.prependTo(item.parent()).show($this.cfg.effect, {}, 'fast', function(){ $this.saveState(); $this.fireReorderEvent(); }); }); } }); }, moveDown: function() { var $this = this; $(this.items.filter('.ui-state-highlight').get().reverse()).each(function() { var item = $(this); if(!item.is(':last-child')) { item.hide($this.cfg.effect, {}, 'fast', function() { item.insertAfter(item.next()).show($this.cfg.effect, {}, 'fast', function() { $this.saveState(); $this.fireReorderEvent(); }); }); } }); }, moveBottom: function() { var $this = this; this.items.filter('.ui-state-highlight').each(function() { var item = $(this); if(!item.is(':last-child')) { item.hide($this.cfg.effect, {}, 'fast', function() { item.appendTo(item.parent()).show($this.cfg.effect, {}, 'fast', function() { $this.saveState(); $this.fireReorderEvent(); }); }); } }); }, hasBehavior: function(event) { if(this.cfg.behaviors) { return this.cfg.behaviors[event] != undefined; } return false; }, fireItemSelectEvent: function(item) { if(this.hasBehavior('select')) { var itemSelectBehavior = this.cfg.behaviors['select'], ext = { params: [ {name: this.id + '_itemIndex', value: item.index()} ] }; itemSelectBehavior.call(this, ext); } }, fireItemUnselectEvent: function(item) { if(this.hasBehavior('unselect')) { var itemUnselectBehavior = this.cfg.behaviors['unselect'], ext = { params: [ {name: this.id + '_itemIndex', value: item.index()} ] }; itemUnselectBehavior.call(this, ext); } }, fireReorderEvent: function() { if(this.hasBehavior('reorder')) { this.cfg.behaviors['reorder'].call(this); } } }); /** * PrimeFaces OutputPanel Widget */ PrimeFaces.widget.OutputPanel = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.cfg.global = this.cfg.global||false; if(this.cfg.deferred) { if(this.cfg.deferredMode === 'load') { this.loadContent(); } else if(this.cfg.deferredMode === 'visible') { if(this.visible()) this.loadContent(); else this.bindScrollMonitor(); } } }, loadContent: function() { var $this = this, options = { source: this.id, process: this.id, update: this.id, async: true, ignoreAutoUpdate: true, global: this.cfg.global, params: [ {name: this.id + '_load', value: true} ], onsuccess: function(responseXML, status, xhr) { PrimeFaces.ajax.Response.handle(responseXML, status, xhr, { widget: $this, handle: function(content) { this.jq.html(content); } }); return true; }, onerror: function(xhr, status, errorThrown) { $this.jq.html(''); } }; if(this.cfg.delay) { setTimeout(function() { PrimeFaces.ajax.Request.handle(options); }, parseInt(this.cfg.delay)); } else { PrimeFaces.ajax.Request.handle(options); } }, bindScrollMonitor: function() { var $this = this, win = $(window); win.off('scroll.' + this.id).on('scroll.' + this.id, function() { if($this.visible()) { $this.unbindScrollMonitor(); $this.loadContent(); } }); }, visible: function() { var win = $(window), scrollTop = win.scrollTop(), height = win.height(), top = this.jq.offset().top, bottom = top + this.jq.innerHeight(); if((top >= scrollTop && top <= (scrollTop + height)) || (bottom >= scrollTop && bottom <= (scrollTop + height))) { return true; } }, unbindScrollMonitor: function() { $(window).off('scroll.' + this.id); } }); /** * PrimeFaces OverlayPanel Widget */ PrimeFaces.widget.OverlayPanel = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.content = this.jq.children('div.ui-overlaypanel-content') //configuration this.cfg.my = this.cfg.my||'left top'; this.cfg.at = this.cfg.at||'left bottom'; this.cfg.showEvent = this.cfg.showEvent||'click.ui-overlaypanel'; this.cfg.hideEvent = this.cfg.hideEvent||'click.ui-overlaypanel'; this.cfg.dismissable = (this.cfg.dismissable === false) ? false : true; if(this.cfg.showCloseIcon) { this.closerIcon = $('').appendTo(this.jq); } //prevent duplicate elements if(this.jq.length > 1) { $(document.body).children(this.jqId).remove(); this.jq = $(this.jqId); } if(this.cfg.appendToBody) { this.jq.appendTo(document.body); } this.bindCommonEvents(); if(this.cfg.target) { this.target = PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector(this.cfg.target); this.bindTargetEvents(); //dialog support this.setupDialogSupport(); } }, bindTargetEvents: function() { var $this = this; //mark target and descandants of target as a trigger for a primefaces overlay this.target.data('primefaces-overlay-target', this.id).find('*').data('primefaces-overlay-target', this.id); //show and hide events for target if(this.cfg.showEvent === this.cfg.hideEvent) { var event = this.cfg.showEvent; this.target.on(event, function(e) { $this.toggle(); }); } else { var showEvent = this.cfg.showEvent + '.ui-overlaypanel', hideEvent = this.cfg.hideEvent + '.ui-overlaypanel'; this.target.off(showEvent + ' ' + hideEvent).on(showEvent, function(e) { if(!$this.isVisible()) { $this.show(); } }) .on(hideEvent, function(e) { if($this.isVisible()) { $this.hide(); } }); } $this.target.off('keydown.ui-overlaypanel keyup.ui-overlaypanel').on('keydown.ui-overlaypanel', function(e) { var keyCode = $.ui.keyCode, key = e.which; if(key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) { e.preventDefault(); } }) .on('keyup.ui-overlaypanel', function(e) { var keyCode = $.ui.keyCode, key = e.which; if(key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) { $this.toggle(); e.preventDefault(); } }); }, bindCommonEvents: function() { var $this = this; if(this.cfg.showCloseIcon) { this.closerIcon.on('mouseover.ui-overlaypanel', function() { $(this).addClass('ui-state-hover'); }) .on('mouseout.ui-overlaypanel', function() { $(this).removeClass('ui-state-hover'); }) .on('click.ui-overlaypanel', function(e) { $this.hide(); e.preventDefault(); }); } //hide overlay when mousedown is at outside of overlay if(this.cfg.dismissable) { var hideNS = 'mousedown.' + this.id; $(document.body).off(hideNS).on(hideNS, function (e) { if($this.jq.hasClass('ui-overlay-hidden')) { return; } //do nothing on target mousedown if($this.target) { var target = $(e.target); if($this.target.is(target)||$this.target.has(target).length > 0) { return; } } //hide overlay if mousedown is on outside var offset = $this.jq.offset(); if(e.pageX < offset.left || e.pageX > offset.left + $this.jq.outerWidth() || e.pageY < offset.top || e.pageY > offset.top + $this.jq.outerHeight()) { $this.hide(); } }); } //Hide overlay on resize var resizeNS = 'resize.' + this.id; $(window).off(resizeNS).on(resizeNS, function() { if($this.jq.hasClass('ui-overlay-visible')) { $this.align(); } }); }, toggle: function() { if(!this.isVisible()) this.show(); else this.hide(); }, show: function(target) { if(!this.loaded && this.cfg.dynamic) this.loadContents(target); else this._show(target); }, _show: function(target) { var $this = this; this.align(target); //replace visibility hidden with display none for effect support, toggle marker class this.jq.removeClass('ui-overlay-hidden').addClass('ui-overlay-visible').css({ 'display':'none' ,'visibility':'visible' }); if(this.cfg.showEffect) { this.jq.show(this.cfg.showEffect, {}, 200, function() { $this.postShow(); }); } else { this.jq.show(); this.postShow(); } }, align: function(target) { var fixedPosition = this.jq.css('position') == 'fixed', win = $(window), positionOffset = fixedPosition ? '-' + win.scrollLeft() + ' -' + win.scrollTop() : null, targetId = target||this.cfg.target; this.jq.css({'left':'', 'top':'', 'z-index': ++PrimeFaces.zindex}) .position({ my: this.cfg.my ,at: this.cfg.at ,of: document.getElementById(targetId) ,offset: positionOffset }); }, hide: function() { var $this = this; if(this.cfg.hideEffect) { this.jq.hide(this.cfg.hideEffect, {}, 200, function() { $this.postHide(); }); } else { this.jq.hide(); this.postHide(); } }, postShow: function() { if(this.cfg.onShow) { this.cfg.onShow.call(this); } this.applyFocus(); }, postHide: function() { //replace display block with visibility hidden for hidden container support, toggle marker class this.jq.removeClass('ui-overlay-visible').addClass('ui-overlay-hidden').css({ 'display':'block' ,'visibility':'hidden' }); if(this.cfg.onHide) { this.cfg.onHide.call(this); } }, setupDialogSupport: function() { var dialog = this.target.closest('.ui-dialog'); if(dialog.length == 1) { //set position as fixed to scroll with dialog this.jq.css('position', 'fixed'); //append to body if not already appended by user choice if(!this.cfg.appendToBody) { this.jq.appendTo(document.body); } } }, loadContents: function(target) { var $this = this, options = { source: this.id, process: this.id, update: this.id, params: [ {name: this.id + '_contentLoad', value: true} ], onsuccess: function(responseXML, status, xhr) { PrimeFaces.ajax.Response.handle(responseXML, status, xhr, { widget: $this, handle: function(content) { this.content.html(content); this.loaded = true; } }); return true; }, oncomplete: function() { $this._show(target); } }; PrimeFaces.ajax.Request.handle(options); }, isVisible: function() { return this.jq.hasClass('ui-overlay-visible'); }, applyFocus: function() { this.jq.find(':not(:submit):not(:button):input:visible:enabled:first').focus(); } }); PrimeFaces.widget.Paginator = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this.cfg = cfg; this.jq = $(); var _self = this; $.each(this.cfg.id, function(index, id){ _self.jq = _self.jq.add($(PrimeFaces.escapeClientId(id))); }); //elements this.pagesContainer = this.jq.children('.ui-paginator-pages'); this.pageLinks = this.pagesContainer.children('.ui-paginator-page'); this.rppSelect = this.jq.children('.ui-paginator-rpp-options'); this.jtpSelect = this.jq.children('.ui-paginator-jtp-select'); this.firstLink = this.jq.children('.ui-paginator-first'); this.prevLink = this.jq.children('.ui-paginator-prev'); this.nextLink = this.jq.children('.ui-paginator-next'); this.endLink = this.jq.children('.ui-paginator-last'); this.currentReport = this.jq.children('.ui-paginator-current'); //metadata this.cfg.rows = this.cfg.rows == 0 ? this.cfg.rowCount : this.cfg.rows; this.cfg.pageCount = Math.ceil(this.cfg.rowCount / this.cfg.rows)||1; this.cfg.pageLinks = this.cfg.pageLinks||10; this.cfg.currentPageTemplate = this.cfg.currentPageTemplate||'({currentPage} of {totalPages})'; //event bindings this.bindEvents(); }, bindEvents: function(){ var $this = this; //visuals for first,prev,next,last buttons this.jq.children('span.ui-state-default').on('mouseover.paginator', function(){ var item = $(this); if(!item.hasClass('ui-state-disabled')) { item.addClass('ui-state-hover'); } }) .on('mouseout.paginator', function() { $(this).removeClass('ui-state-hover'); }) .on('focus.paginator', function() { var item = $(this); if(!item.hasClass('ui-state-disabled')) { item.addClass('ui-state-focus'); } }) .on('blur.paginator', function() { $(this).removeClass('ui-state-focus'); }) .on('keydown.paginator', function(e) { var key = e.which, keyCode = $.ui.keyCode; if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) { $(this).trigger('click'); e.preventDefault(); } }); //page links this.bindPageLinkEvents(); //records per page selection PrimeFaces.skinSelect(this.rppSelect); this.rppSelect.change(function(e) { if(!$(this).hasClass("ui-state-disabled")){ $this.setRowsPerPage(parseInt($(this).val())); } }); //jump to page PrimeFaces.skinSelect(this.jtpSelect); this.jtpSelect.change(function(e) { if(!$(this).hasClass("ui-state-disabled")){ $this.setPage(parseInt($(this).val())); } }); //First page link this.firstLink.click(function() { PrimeFaces.clearSelection(); if(!$(this).hasClass("ui-state-disabled")){ $this.setPage(0); } }); //Prev page link this.prevLink.click(function() { PrimeFaces.clearSelection(); if(!$(this).hasClass("ui-state-disabled")){ $this.setPage($this.cfg.page - 1); } }); //Next page link this.nextLink.click(function() { PrimeFaces.clearSelection(); if(!$(this).hasClass("ui-state-disabled")){ $this.setPage($this.cfg.page + 1); } }); //Last page link this.endLink.click(function() { PrimeFaces.clearSelection(); if(!$(this).hasClass("ui-state-disabled")){ $this.setPage($this.cfg.pageCount - 1); } }); }, bindPageLinkEvents: function(){ var $this = this; this.pagesContainer.children('.ui-paginator-page').on('click.paginator', function(e) { var link = $(this); if(!link.hasClass('ui-state-disabled')&&!link.hasClass('ui-state-active')) { $this.setPage(parseInt(link.text()) - 1); } }) .on('mouseover.paginator', function() { var item = $(this); if(!item.hasClass('ui-state-disabled')&&!item.hasClass('ui-state-active')) { item.addClass('ui-state-hover'); } }) .on('mouseout.paginator', function() { $(this).removeClass('ui-state-hover'); }) .on('focus.paginator', function() { $(this).addClass('ui-state-focus'); }) .on('blur.paginator', function() { $(this).removeClass('ui-state-focus'); }) .on('keydown.paginator', function(e) { var key = e.which, keyCode = $.ui.keyCode; if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) { $(this).trigger('click'); e.preventDefault(); } }); }, updateUI: function() { //boundaries if(this.cfg.page === 0) { this.disableElement(this.firstLink); this.disableElement(this.prevLink); } else { this.enableElement(this.firstLink); this.enableElement(this.prevLink); } if(this.cfg.page === (this.cfg.pageCount - 1)) { this.disableElement(this.nextLink); this.disableElement(this.endLink); } else { this.enableElement(this.nextLink); this.enableElement(this.endLink); } //current page report var startRecord = (this.cfg.rowCount === 0) ? 0 : (this.cfg.page * this.cfg.rows) + 1, endRecord = (this.cfg.page * this.cfg.rows) + this.cfg.rows; if(endRecord > this.cfg.rowCount) { endRecord = this.cfg.rowCount; } var text = this.cfg.currentPageTemplate .replace("{currentPage}", this.cfg.page + 1) .replace("{totalPages}", this.cfg.pageCount) .replace("{totalRecords}", this.cfg.rowCount) .replace("{startRecord}", startRecord) .replace("{endRecord}", endRecord); this.currentReport.text(text); //rows per page dropdown this.rppSelect.children('option').prop('selected', false).filter('option[value=' + this.cfg.rows + ']').prop('selected', true); //jump to page dropdown if(this.jtpSelect.length > 0) { this.jtpSelect.children().remove(); for(var i=0; i < this.cfg.pageCount; i++) { this.jtpSelect.append(""); } this.jtpSelect.children('option[value=' + (this.cfg.page) + ']').prop('selected','selected'); } //page links this.updatePageLinks(); }, updatePageLinks: function() { var start, end, delta, focusedElement = $(document.activeElement), focusContainer, tabindex; if(focusedElement.hasClass('ui-paginator-page')) { var pagesContainerIndex = this.pagesContainer.index(focusedElement.parent()); if(pagesContainerIndex >= 0) { focusContainer = this.pagesContainer.eq(pagesContainerIndex); tabindex = focusedElement.index(); } } //calculate visible page links this.cfg.pageCount = Math.ceil(this.cfg.rowCount / this.cfg.rows)||1; var visiblePages = Math.min(this.cfg.pageLinks, this.cfg.pageCount); //calculate range, keep current in middle if necessary start = Math.max(0, Math.ceil(this.cfg.page - ((visiblePages) / 2))); end = Math.min(this.cfg.pageCount - 1, start + visiblePages - 1); //check when approaching to last page delta = this.cfg.pageLinks - (end - start + 1); start = Math.max(0, start - delta); //update dom this.pagesContainer.children().remove(); for(var i = start; i <= end; i++) { var styleClass = 'ui-paginator-page ui-state-default ui-corner-all'; if(this.cfg.page == i) { styleClass += " ui-state-active"; } this.pagesContainer.append('' + (i + 1) + '') } if(focusContainer) { focusContainer.children().eq(tabindex).trigger('focus'); } this.bindPageLinkEvents(); }, setPage: function(p, silent) { if(p >= 0 && p < this.cfg.pageCount && this.cfg.page != p){ var newState = { first: this.cfg.rows * p, rows: this.cfg.rows, page: p }; if(silent) { this.cfg.page = p; this.updateUI(); } else { this.cfg.paginate.call(this, newState); } } }, setRowsPerPage: function(rpp) { var first = this.cfg.rows * this.cfg.page, page = parseInt(first / rpp); this.cfg.rows = rpp; this.cfg.pageCount = Math.ceil(this.cfg.rowCount / this.cfg.rows); this.cfg.page = -1; this.setPage(page); }, setTotalRecords: function(value) { this.cfg.rowCount = value; this.cfg.pageCount = Math.ceil(value / this.cfg.rows)||1; this.cfg.page = 0; this.updateUI(); }, getCurrentPage: function() { return this.cfg.page; }, getFirst: function() { return (this.cfg.rows * this.cfg.page); }, getContainerHeight: function(margin) { var height = 0; for(var i = 0; i < this.jq.length; i++) { height += this.jq.eq(i).outerHeight(margin); } return height; }, disableElement: function(element) { element.removeClass('ui-state-hover ui-state-focus ui-state-active').addClass('ui-state-disabled').attr('tabindex', -1); element.removeClass('ui-state-hover ui-state-focus ui-state-active').addClass('ui-state-disabled').attr('tabindex', -1); }, enableElement: function(element) { element.removeClass('ui-state-disabled').attr('tabindex', 0); } }); /** * PrimeFaces PickList Widget */ PrimeFaces.widget.PickList = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.sourceList = this.jq.find('ul.ui-picklist-source'); this.targetList = this.jq.find('ul.ui-picklist-target'); this.sourceInput = $(this.jqId + '_source'); this.targetInput = $(this.jqId + '_target'); this.items = this.jq.find('.ui-picklist-item:not(.ui-state-disabled)'); if(this.cfg.showCheckbox) { this.checkboxes = this.items.find('div.ui-chkbox > div.ui-chkbox-box'); } //generate input options this.generateItems(this.sourceList, this.sourceInput); this.generateItems(this.targetList, this.targetInput); if(this.cfg.disabled) { $(this.jqId + ' li.ui-picklist-item').addClass('ui-state-disabled'); $(this.jqId + ' button').attr('disabled', 'disabled').addClass('ui-state-disabled'); } else { var $this = this, reordered = true; //Sortable lists $(this.jqId + ' ul').sortable({ cancel: '.ui-state-disabled,.ui-chkbox-box', connectWith: this.jqId + ' .ui-picklist-list', revert: 1, update: function(event, ui) { $this.unselectItem(ui.item); $this.saveState(); if(reordered) { $this.fireReorderEvent(); reordered = false; } }, receive: function(event, ui) { $this.fireTransferEvent(ui.item, ui.sender, ui.item.parents('ul.ui-picklist-list:first'), 'dragdrop'); }, start: function(event, ui) { $this.itemListName = $this.getListName(ui.item); $this.dragging = true; }, stop: function(event, ui) { $this.dragging = false; }, beforeStop:function(event, ui) { if($this.itemListName !== $this.getListName(ui.item)) { reordered = false; } else { reordered = true; } } }); this.bindItemEvents(); this.bindButtonEvents(); this.bindFilterEvents(); } }, bindItemEvents: function() { var $this = this; this.items.on('mouseover.pickList', function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) { $(this).addClass('ui-state-hover'); } }) .on('mouseout.pickList', function(e) { $(this).removeClass('ui-state-hover'); }) .on('click.pickList', function(e) { //stop propagation if($this.checkboxClick||$this.dragging) { $this.checkboxClick = false; return; } var item = $(this), metaKey = (e.metaKey||e.ctrlKey); if(!e.shiftKey) { if(!metaKey) { $this.unselectAll(); } if(metaKey && item.hasClass('ui-state-highlight')) { $this.unselectItem(item, true); } else { $this.selectItem(item, true); $this.cursorItem = item; } } else { $this.unselectAll(); if($this.cursorItem && ($this.cursorItem.parent().is(item.parent()))) { var currentItemIndex = item.index(), cursorItemIndex = $this.cursorItem.index(), startIndex = (currentItemIndex > cursorItemIndex) ? cursorItemIndex : currentItemIndex, endIndex = (currentItemIndex > cursorItemIndex) ? (currentItemIndex + 1) : (cursorItemIndex + 1), parentList = item.parent(); for(var i = startIndex ; i < endIndex; i++) { var it = parentList.children('li.ui-picklist-item').eq(i); if(it.is(':visible')) { if(i === (endIndex - 1)) $this.selectItem(it, true); else $this.selectItem(it); } } } else { $this.selectItem(item, true); $this.cursorItem = item; } } }) .on('dblclick.pickList', function() { var item = $(this); if($(this).parent().hasClass('ui-picklist-source')) $this.transfer(item, $this.sourceList, $this.targetList, 'dblclick'); else $this.transfer(item, $this.targetList, $this.sourceList, 'dblclick'); PrimeFaces.clearSelection(); }); if(this.cfg.showCheckbox) { this.checkboxes.on('mouseover.pickList', function(e) { var chkbox = $(this); if(!chkbox.hasClass('ui-state-active')) chkbox.addClass('ui-state-hover'); }) .on('mouseout.pickList', function(e) { $(this).removeClass('ui-state-hover'); }) .on('click.pickList', function(e) { $this.checkboxClick = true; var item = $(this).closest('li.ui-picklist-item'); if(item.hasClass('ui-state-highlight')) { $this.unselectItem(item, true); } else { $this.selectItem(item, true); } }); } }, selectItem: function(item, silent) { item.removeClass('ui-state-hover').addClass('ui-state-highlight'); if(this.cfg.showCheckbox) { this.selectCheckbox(item.find('div.ui-chkbox-box')); } if(silent) { this.fireItemSelectEvent(item); } }, unselectItem: function(item, silent) { item.removeClass('ui-state-hover ui-state-highlight'); if(PrimeFaces.isIE(8)) { item.css('filter',''); } if(this.cfg.showCheckbox) { this.unselectCheckbox(item.find('div.ui-chkbox-box')); } if(silent) { this.fireItemUnselectEvent(item); } }, unselectAll: function() { var selectedItems = this.items.filter('.ui-state-highlight'); for(var i = 0; i < selectedItems.length; i++) { this.unselectItem(selectedItems.eq(i)); } }, selectCheckbox: function(chkbox) { chkbox.removeClass('ui-state-hover').addClass('ui-state-active').children('span.ui-chkbox-icon').removeClass('ui-icon-blank').addClass('ui-icon-check'); }, unselectCheckbox: function(chkbox) { chkbox.removeClass('ui-state-active').children('span.ui-chkbox-icon').addClass('ui-icon-blank').removeClass('ui-icon-check'); }, generateItems: function(list, input) { list.children('.ui-picklist-item').each(function() { var item = $(this), itemValue = PrimeFaces.escapeHTML(item.attr('data-item-value')), itemLabel = item.attr('data-item-label'), escapedItemLabel = (itemLabel) ? PrimeFaces.escapeHTML(itemLabel) : ''; input.append(''); }); }, bindButtonEvents: function() { var _self = this; //visuals PrimeFaces.skinButton(this.jq.find('.ui-button')); //events $(this.jqId + ' .ui-picklist-button-add').click(function() {_self.add();}); $(this.jqId + ' .ui-picklist-button-add-all').click(function() {_self.addAll();}); $(this.jqId + ' .ui-picklist-button-remove').click(function() {_self.remove();}); $(this.jqId + ' .ui-picklist-button-remove-all').click(function() {_self.removeAll();}); if(this.cfg.showSourceControls) { $(this.jqId + ' .ui-picklist-source-controls .ui-picklist-button-move-up').click(function() {_self.moveUp(_self.sourceList);}); $(this.jqId + ' .ui-picklist-source-controls .ui-picklist-button-move-top').click(function() {_self.moveTop(_self.sourceList);}); $(this.jqId + ' .ui-picklist-source-controls .ui-picklist-button-move-down').click(function() {_self.moveDown(_self.sourceList);}); $(this.jqId + ' .ui-picklist-source-controls .ui-picklist-button-move-bottom').click(function() {_self.moveBottom(_self.sourceList);}); } if(this.cfg.showTargetControls) { $(this.jqId + ' .ui-picklist-target-controls .ui-picklist-button-move-up').click(function() {_self.moveUp(_self.targetList);}); $(this.jqId + ' .ui-picklist-target-controls .ui-picklist-button-move-top').click(function() {_self.moveTop(_self.targetList);}); $(this.jqId + ' .ui-picklist-target-controls .ui-picklist-button-move-down').click(function() {_self.moveDown(_self.targetList);}); $(this.jqId + ' .ui-picklist-target-controls .ui-picklist-button-move-bottom').click(function() {_self.moveBottom(_self.targetList);}); } }, bindFilterEvents: function() { this.setupFilterMatcher(); this.sourceFilter = $(this.jqId + '_source_filter'); this.targetFilter = $(this.jqId + '_target_filter'); var _self = this; PrimeFaces.skinInput(this.sourceFilter); PrimeFaces.skinInput(this.targetFilter); this.sourceFilter.on('keyup', function(e) { _self.filter(this.value, _self.sourceList); }); this.targetFilter.on('keyup', function(e) { _self.filter(this.value, _self.targetList); }); }, setupFilterMatcher: function() { this.cfg.filterMatchMode = this.cfg.filterMatchMode||'startsWith'; this.filterMatchers = { 'startsWith': this.startsWithFilter ,'contains': this.containsFilter ,'endsWith': this.endsWithFilter ,'custom': this.cfg.filterFunction }; this.filterMatcher = this.filterMatchers[this.cfg.filterMatchMode]; }, filter: function(value, list) { var filterValue = $.trim(value).toLowerCase(), items = list.children('li.ui-picklist-item'), animated = this.isAnimated(); if(filterValue === '') { items.filter(':hidden').show(); } else { for(var i = 0; i < items.length; i++) { var item = items.eq(i), itemLabel = item.attr('data-item-label'), matches = this.filterMatcher(itemLabel, filterValue); if(matches) { if(animated) item.fadeIn('fast'); else item.show(); } else { if(animated) item.fadeOut('fast'); else item.hide(); } } } }, startsWithFilter: function(value, filter) { return value.toLowerCase().indexOf(filter) === 0; }, containsFilter: function(value, filter) { return value.toLowerCase().indexOf(filter) !== -1; }, endsWithFilter: function(value, filter) { return value.indexOf(filter, value.length - filter.length) !== -1; }, add: function() { var items = this.sourceList.children('li.ui-picklist-item.ui-state-highlight') this.transfer(items, this.sourceList, this.targetList, 'command'); }, addAll: function() { var items = this.sourceList.children('li.ui-picklist-item:visible:not(.ui-state-disabled)'); this.transfer(items, this.sourceList, this.targetList, 'command'); }, remove: function() { var items = this.targetList.children('li.ui-picklist-item.ui-state-highlight'); this.transfer(items, this.targetList, this.sourceList, 'command'); }, removeAll: function() { var items = this.targetList.children('li.ui-picklist-item:visible:not(.ui-state-disabled)'); this.transfer(items, this.targetList, this.sourceList, 'command'); }, moveUp: function(list) { var _self = this, animated = _self.isAnimated(), items = list.children('.ui-state-highlight'), itemsCount = items.length, movedCount = 0; if(itemsCount) { items.each(function() { var item = $(this); if(!item.is(':first-child')) { if(animated) { item.hide(_self.cfg.effect, {}, _self.cfg.effectSpeed, function() { item.insertBefore(item.prev()).show(_self.cfg.effect, {}, _self.cfg.effectSpeed, function() { movedCount++; if(movedCount === itemsCount) { _self.saveState(); _self.fireReorderEvent(); } }); }); } else { item.hide().insertBefore(item.prev()).show(); } } }); if(!animated) { this.saveState(); this.fireReorderEvent(); } } }, moveTop: function(list) { var _self = this, animated = _self.isAnimated(), items = list.children('.ui-state-highlight'), itemsCount = items.length, movedCount = 0; if(itemsCount) { items.each(function() { var item = $(this); if(!item.is(':first-child')) { if(animated) { item.hide(_self.cfg.effect, {}, _self.cfg.effectSpeed, function() { item.prependTo(item.parent()).show(_self.cfg.effect, {}, _self.cfg.effectSpeed, function(){ movedCount++; if(movedCount === itemsCount) { _self.saveState(); _self.fireReorderEvent(); } }); }); } else { item.hide().prependTo(item.parent()).show(); } } }); if(!animated) { this.saveState(); this.fireReorderEvent(); } } }, moveDown: function(list) { var _self = this, animated = _self.isAnimated(), items = list.children('.ui-state-highlight'), itemsCount = items.length, movedCount = 0; if(itemsCount) { $(items.get().reverse()).each(function() { var item = $(this); if(!item.is(':last-child')) { if(animated) { item.hide(_self.cfg.effect, {}, _self.cfg.effectSpeed, function() { item.insertAfter(item.next()).show(_self.cfg.effect, {}, _self.cfg.effectSpeed, function() { movedCount++; if(movedCount === itemsCount) { _self.saveState(); _self.fireReorderEvent(); } }); }); } else { item.hide().insertAfter(item.next()).show(); } } }); if(!animated) { this.saveState(); this.fireReorderEvent(); } } }, moveBottom: function(list) { var _self = this, animated = _self.isAnimated(), items = list.children('.ui-state-highlight'), itemsCount = items.length, movedCount = 0; if(itemsCount) { items.each(function() { var item = $(this); if(!item.is(':last-child')) { if(animated) { item.hide(_self.cfg.effect, {}, _self.cfg.effectSpeed, function() { item.appendTo(item.parent()).show(_self.cfg.effect, {}, _self.cfg.effectSpeed, function() { movedCount++; if(movedCount === itemsCount) { _self.saveState(); _self.fireReorderEvent(); } }); }); } else { item.hide().appendTo(item.parent()).show(); } } }); if(!animated) { this.saveState(); this.fireReorderEvent(); } } }, /** * Clear inputs and repopulate them from the list states */ saveState: function() { this.sourceInput.children().remove(); this.targetInput.children().remove(); this.generateItems(this.sourceList, this.sourceInput); this.generateItems(this.targetList, this.targetInput); this.cursorItem = null; }, transfer: function(items, from, to, type) { var $this = this, itemsCount = items.length, transferCount = 0; if(this.isAnimated()) { items.hide(this.cfg.effect, {}, this.cfg.effectSpeed, function() { var item = $(this); $this.unselectItem(item); item.appendTo(to).show($this.cfg.effect, {}, $this.cfg.effectSpeed, function() { transferCount++; //fire transfer when all items are transferred if(transferCount == itemsCount) { $this.saveState(); $this.fireTransferEvent(items, from, to, type); } }); }); } else { items.hide(); if(this.cfg.showCheckbox) { items.each(function() { $this.unselectItem($(this)); }); } items.appendTo(to).show(); this.saveState(); this.fireTransferEvent(items, from, to, type); } }, /** * Fire transfer ajax behavior event */ fireTransferEvent: function(items, from, to, type) { if(this.cfg.onTransfer) { var obj = {}; obj.items = items; obj.from = from; obj.to = to; obj.type = type; this.cfg.onTransfer.call(this, obj); } if(this.cfg.behaviors) { var transferBehavior = this.cfg.behaviors['transfer']; if(transferBehavior) { var ext = { params: [] }, paramName = this.id + '_transferred', isAdd = from.hasClass('ui-picklist-source'); items.each(function(index, item) { ext.params.push({name:paramName, value:$(item).attr('data-item-value')}); }); ext.params.push({name:this.id + '_add', value:isAdd}); transferBehavior.call(this, ext); } } }, getListName: function(element){ return element.parent().hasClass("ui-picklist-source") ? "source" : "target"; }, hasBehavior: function(event) { if(this.cfg.behaviors) { return this.cfg.behaviors[event] != undefined; } return false; }, fireItemSelectEvent: function(item) { if(this.hasBehavior('select')) { var itemSelectBehavior = this.cfg.behaviors['select'], ext = { params: [ {name: this.id + '_itemIndex', value: item.index()}, {name: this.id + '_listName', value: this.getListName(item)} ] }; itemSelectBehavior.call(this, ext); } }, fireItemUnselectEvent: function(item) { if(this.hasBehavior('unselect')) { var itemUnselectBehavior = this.cfg.behaviors['unselect'], ext = { params: [ {name: this.id + '_itemIndex', value: item.index()}, {name: this.id + '_listName', value: this.getListName(item)} ] }; itemUnselectBehavior.call(this, ext); } }, fireReorderEvent: function() { if(this.hasBehavior('reorder')) { this.cfg.behaviors['reorder'].call(this); } }, isAnimated: function() { return (this.cfg.effect && this.cfg.effect != 'none'); } }); /** * PrimeFaces ProgressBar widget */ PrimeFaces.widget.ProgressBar = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.jqValue = this.jq.children('.ui-progressbar-value'); this.jqLabel = this.jq.children('.ui-progressbar-label'); this.value = this.cfg.initialValue; this.cfg.global = (this.cfg.global === false) ? false : true; if(this.cfg.ajax) { this.cfg.formId = this.jq.closest('form').attr('id'); } this.enableARIA(); }, setValue: function(value) { if(value >= 0 && value<=100) { if(value == 0) { this.jqValue.hide().css('width', '0%').removeClass('ui-corner-right'); this.jqLabel.hide(); } else { this.jqValue.show().animate({ 'width': value + '%' }, 500, 'easeInOutCirc'); if(this.cfg.labelTemplate) { var formattedLabel = this.cfg.labelTemplate.replace(/{value}/gi, value); this.jqLabel.html(formattedLabel).show(); } } this.value = value; this.jq.attr('aria-valuenow', value); } }, getValue: function() { return this.value; }, start: function() { var $this = this; if(this.cfg.ajax) { this.progressPoll = setInterval(function() { var options = { source: $this.id, process: $this.id, formId: $this.cfg.formId, global: $this.cfg.global, async: true, oncomplete: function(xhr, status, args) { var value = args[$this.id + '_value']; $this.setValue(value); //trigger complete listener if(value === 100) { $this.fireCompleteEvent(); } } }; PrimeFaces.ajax.AjaxRequest(options); }, this.cfg.interval); } }, fireCompleteEvent: function() { clearInterval(this.progressPoll); if(this.cfg.behaviors) { var completeBehavior = this.cfg.behaviors['complete']; if(completeBehavior) { completeBehavior.call(this); } } }, cancel: function() { clearInterval(this.progressPoll); this.setValue(0); }, enableARIA: function() { this.jq.attr('role', 'progressbar') .attr('aria-valuemin', 0) .attr('aria-valuenow', this.value) .attr('aria-valuemax', 100); } }); /** * PrimeFaces Rating Widget */ PrimeFaces.widget.Rating = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.jqInput = $(this.jqId + '_input'); this.value = this.getValue(); this.stars = this.jq.children('.ui-rating-star'); this.cancel = this.jq.children('.ui-rating-cancel'); if(!this.cfg.disabled && !this.cfg.readonly) { this.bindEvents(); } if(this.cfg.readonly) { this.jq.children().css('cursor', 'default'); } }, bindEvents: function() { var _self = this; this.stars.click(function() { var value = _self.stars.index(this) + 1; //index starts from zero _self.setValue(value); }); this.cancel.hover(function() { $(this).toggleClass('ui-rating-cancel-hover'); }) .click(function() { _self.reset(); }); }, unbindEvents: function() { this.stars.unbind('click'); this.cancel.unbind('hover click'); }, getValue: function() { var inputVal = this.jqInput.val(); return inputVal == '' ? null : parseInt(inputVal); }, setValue: function(value) { //set hidden value this.jqInput.val(value); //update visuals this.stars.removeClass('ui-rating-star-on'); for(var i = 0; i < value; i++) { this.stars.eq(i).addClass('ui-rating-star-on'); } //invoke callback if(this.cfg.onRate) { this.cfg.onRate.call(this, value); } //invoke ajax rate behavior if(this.cfg.behaviors) { var rateBehavior = this.cfg.behaviors['rate']; if(rateBehavior) { rateBehavior.call(this); } } }, enable: function() { this.cfg.disabled = false; this.bindEvents(); this.jq.removeClass('ui-state-disabled'); }, disable: function() { this.cfg.disabled = true; this.unbindEvents(); this.jq.addClass('ui-state-disabled'); }, reset: function() { this.jqInput.val(''); this.stars.filter('.ui-rating-star-on').removeClass('ui-rating-star-on'); //invoke ajax cancel behavior if(this.cfg.behaviors) { var cancelBehavior = this.cfg.behaviors['cancel']; if(cancelBehavior) { cancelBehavior.call(this); } } } }); /** * PrimeFaces Resizable Widget */ PrimeFaces.widget.Resizable = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this.cfg = cfg; this.id = this.cfg.id; this.jqId = PrimeFaces.escapeClientId(this.id); this.jqTarget = $(PrimeFaces.escapeClientId(this.cfg.target)); if(this.cfg.ajaxResize) { this.cfg.formId = $(this.target).parents('form:first').attr('id'); } if (this.cfg.isContainment) { this.cfg.containment = PrimeFaces.escapeClientId(this.cfg.parentComponentId); } var _self = this; this.cfg.stop = function(event, ui) { if(_self.cfg.onStop) { _self.cfg.onStop.call(_self, event, ui); } _self.fireAjaxResizeEvent(event, ui); } this.cfg.start = function(event, ui) { if(_self.cfg.onStart) { _self.cfg.onStart.call(_self, event, ui); } } this.cfg.resize = function(event, ui) { if(_self.cfg.onResize) { _self.cfg.onResize.call(_self, event, ui); } } this.jqTarget.resizable(this.cfg); this.removeScriptElement(this.id); }, fireAjaxResizeEvent: function(event, ui) { if(this.cfg.behaviors) { var resizeBehavior = this.cfg.behaviors['resize']; if(resizeBehavior) { var ext = { params: [ {name: this.id + '_width', value: parseInt(ui.helper.width())}, {name: this.id + '_height', value: parseInt(ui.helper.height())} ] }; resizeBehavior.call(this, ext); } } } }); /** * PrimeFaces Slider Widget */ PrimeFaces.widget.Slider = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.cfg.displayTemplate = this.cfg.displayTemplate||(this.cfg.range ? '{min} - {max}' : '{value}'); if(this.cfg.range) { var inputIds = this.cfg.input.split(','); this.input = $(PrimeFaces.escapeClientId(inputIds[0]) + ',' + PrimeFaces.escapeClientId(inputIds[1])); } else { this.input = $(PrimeFaces.escapeClientId(this.cfg.input)); } if(this.cfg.display) { this.output = $(PrimeFaces.escapeClientId(this.cfg.display)); } this.jq.slider(this.cfg); this.bindEvents(); }, bindEvents: function() { var $this = this; this.jq.bind('slide', function(event, ui) { $this.onSlide(event, ui); }); if(this.cfg.onSlideStart) { this.jq.bind('slidestart', function(event, ui) { $this.cfg.onSlideStart.call(this, event, ui); }); } this.jq.bind('slidestop', function(event, ui) { $this.onSlideEnd(event, ui); }); this.input.on('keydown.slider', function (e) { var keyCode = $.ui.keyCode, key = e.which; switch(key) { case keyCode.UP: case keyCode.DOWN: case keyCode.LEFT: case keyCode.RIGHT: case keyCode.BACKSPACE: case keyCode.DELETE: case keyCode.END: case keyCode.HOME: case keyCode.TAB: break; default: var metaKey = e.metaKey||e.ctrlKey, isNumber = (key >= 48 && key <= 57) || (key >= 96 && key <= 105); //prevent special characters with alt and shift if(e.altKey || (e.shiftKey && !(key === keyCode.UP || key === keyCode.DOWN || key === keyCode.LEFT || key === keyCode.RIGHT))) { e.preventDefault(); } //prevent letters and allow letters with meta key such as ctrl+c if(!isNumber && !metaKey) { e.preventDefault(); } break; } }).on('keyup.slider', function (e) { $this.setValue($this.input.val()); }); }, onSlide: function(event, ui) { if(this.cfg.onSlide) { this.cfg.onSlide.call(this, event, ui); } if(this.cfg.range) { this.input.eq(0).val(ui.values[0]); this.input.eq(1).val(ui.values[1]); if(this.output) { this.output.html(this.cfg.displayTemplate.replace('{min}', ui.values[0]).replace('{max}', ui.values[1])); } } else { this.input.val(ui.value); if(this.output) { this.output.html(this.cfg.displayTemplate.replace('{value}', ui.value)); } } }, onSlideEnd: function(event, ui) { if(this.cfg.onSlideEnd) { this.cfg.onSlideEnd.call(this, event, ui); } if(this.cfg.behaviors) { var slideEndBehavior = this.cfg.behaviors['slideEnd']; if(slideEndBehavior) { var ext = { params: [ {name: this.id + '_slideValue', value: ui.value} ] }; slideEndBehavior.call(this, ext); } } }, getValue: function() { return this.jq.slider('value'); }, setValue: function(value) { this.jq.slider('value', value); }, getValues: function() { return this.jq.slider('values'); }, setValues: function(values) { this.jq.slider('values', values); }, enable: function() { this.jq.slider('enable'); }, disable: function() { this.jq.slider('disable'); } }); /** * PrimeFaces Spinner Widget */ PrimeFaces.widget.Spinner = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.input = this.jq.children('.ui-spinner-input'); this.upButton = this.jq.children('a.ui-spinner-up'); this.downButton = this.jq.children('a.ui-spinner-down'); this.cfg.step = this.cfg.step||1; this.cursorOffset = this.cfg.prefix ? this.cfg.prefix.length: 0; if(parseInt(this.cfg.step) === 0) { this.cfg.precision = this.cfg.step.toString().split(/[,]|[.]/)[1].length; } var maxlength = this.input.attr('maxlength'); if(maxlength) { this.cfg.maxlength = parseInt(maxlength); } this.updateValue(); this.addARIA(); if(this.input.prop('disabled')||this.input.prop('readonly')) { return; } this.bindEvents(); this.input.data(PrimeFaces.CLIENT_ID_DATA, this.id); PrimeFaces.skinInput(this.input); }, bindEvents: function() { var $this = this; this.jq.children('.ui-spinner-button') .on('mouseover.spinner', function() { $(this).addClass('ui-state-hover'); }) .on('mouseout.spinner', function() { $(this).removeClass('ui-state-hover ui-state-active'); if($this.timer) { clearInterval($this.timer); } }) .on('mouseup.spinner', function() { clearInterval($this.timer); $(this).removeClass('ui-state-active').addClass('ui-state-hover'); $this.input.trigger('change'); }) .on('mousedown.spinner', function(e) { var element = $(this), dir = element.hasClass('ui-spinner-up') ? 1 : -1; element.removeClass('ui-state-hover').addClass('ui-state-active'); if($this.input.is(':not(:focus)')) { $this.input.focus(); } $this.repeat(null, dir); //keep focused e.preventDefault(); }); this.input.on('keydown.spinner', function (e) { var keyCode = $.ui.keyCode; switch(e.which) { case keyCode.UP: $this.spin(1); break; case keyCode.DOWN: $this.spin(-1); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: $this.updateValue(); $this.format(); break; default: //do nothing break; } }) .on('keyup.spinner', function (e) { $this.updateValue(); var keyCode = $.ui.keyCode; if(e.which === keyCode.UP||e.which === keyCode.DOWN) { $this.input.trigger('change'); } }) .on('blur.spinner', function(e) { $this.format(); }) .on('mousewheel.spinner', function(event, delta) { if($this.input.is(':focus')) { if(delta > 0) $this.spin(1); else $this.spin(-1); return false; } }); }, repeat: function(interval, dir) { var $this = this, i = interval||500; clearTimeout(this.timer); this.timer = setTimeout(function() { $this.repeat(40, dir); }, i); this.spin(dir); }, toFixed: function (value, precision) { var power = Math.pow(10, precision||0); return String(Math.round(value * power) / power); }, spin: function(dir) { var step = this.cfg.step * dir, currentValue = this.value ? this.value : 0, newValue = null; if(this.cfg.precision) newValue = parseFloat(this.toFixed(currentValue + step, this.cfg.precision)); else newValue = parseInt(currentValue + step); if(this.cfg.maxlength !== undefined && newValue.toString().length > this.cfg.maxlength) { newValue = currentValue; } if(this.cfg.min !== undefined && newValue < this.cfg.min) { newValue = this.cfg.min; } if(this.cfg.max !== undefined && newValue > this.cfg.max) { newValue = this.cfg.max; } this.value = newValue; this.format(); this.input.attr('aria-valuenow', newValue); }, updateValue: function() { var value = this.input.val(); if($.trim(value) === '') { if(this.cfg.min !== undefined) this.value = this.cfg.min; else this.value = null; } else { if(this.cfg.prefix && value.indexOf(this.cfg.prefix) === 0) { value = value.substring(this.cfg.prefix.length, value.length); } else if(this.cfg.suffix && value.indexOf(this.cfg.suffix) === (value.length - this.cfg.suffix.length)) { value = value.substring(0, value.length - this.cfg.suffix.length); } if(this.cfg.precision) value = parseFloat(value); else value = parseInt(value); if(!isNaN(value)) { if(this.cfg.max !== undefined && value > this.cfg.max) { value = this.cfg.max; } if(this.cfg.min !== undefined && value < this.cfg.min) { value = this.cfg.min; } this.value = value; } } }, format: function() { if(this.value !== null) { var value = this.value; if(this.cfg.prefix) value = this.cfg.prefix + value; if(this.cfg.suffix) value = value + this.cfg.suffix; this.input.val(value); } }, addARIA: function() { this.input.attr('role', 'spinner'); this.input.attr('aria-multiline', false); this.input.attr('aria-valuenow', this.value); if(this.cfg.min !== undefined) this.input.attr('aria-valuemin', this.cfg.min); if(this.cfg.max !== undefined) this.input.attr('aria-valuemax', this.cfg.max); if(this.input.prop('disabled')) this.input.attr('aria-disabled', true); if(this.input.prop('readonly')) this.input.attr('aria-readonly', true); } }); /** * PrimeFaces Spotlight Widget */ PrimeFaces.widget.Spotlight = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.target = PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector(this.cfg.target); this.eventsToBlock = 'focus.' + this.id + ' mousedown.' + this.id + ' mouseup.' + this.id; if(!$(document.body).children('.ui-spotlight').length) { this.createMasks(); } }, createMasks: function() { $(document.body).append('
' + '
'); }, show: function() { var doc = $(document), body = $(document.body), offset = this.target.offset(), topMask = body.children('div.ui-spotlight-top'), bottomMask = body.children('div.ui-spotlight-bottom'), leftMask = body.children('div.ui-spotlight-left'), rightMask = body.children('div.ui-spotlight-right'); topMask.css({ 'left': 0, 'top': 0, 'width': doc.width(), 'height': offset.top }); var bottomTop = offset.top + this.target.outerHeight(); bottomMask.css({ 'left': 0, 'top': bottomTop, 'width': doc.width(), 'height': doc.height() - bottomTop }); leftMask.css({ 'left': 0, 'top': offset.top, 'width': offset.left, 'height': this.target.outerHeight() }); var rightLeft = offset.left + this.target.outerWidth(); rightMask.css({ 'left': rightLeft, 'top': offset.top, 'width': doc.width() - rightLeft, 'height': this.target.outerHeight() }); topMask.appendTo(document.body).show(); bottomMask.appendTo(document.body).show(); leftMask.appendTo(document.body).show(); rightMask.appendTo(document.body).show(); this.blockEvents(); }, blockEvents: function() { var $this = this; this.target.data('zindex',this.target.zIndex()).css('z-index', ++PrimeFaces.zindex); $(document).on('keydown.' + this.id, function(event) { var target = $(event.target); if(event.keyCode === $.ui.keyCode.TAB) { var tabbables = $this.target.find(':tabbable'); if(tabbables.length) { var first = tabbables.filter(':first'), last = tabbables.filter(':last'); if(target.is(document.body)) { first.focus(1); event.preventDefault(); } else if(event.target === last[0] && !event.shiftKey) { first.focus(1); event.preventDefault(); } else if (event.target === first[0] && event.shiftKey) { last.focus(1); event.preventDefault(); } } } else if(!target.is(document.body) && (target.zIndex() < $this.target.zIndex())) { event.preventDefault(); } }) .on(this.eventsToBlock, function(event) { if ($(event.target).zIndex() < $this.target.zIndex()) { event.preventDefault(); } }); }, unblockEvents: function() { $(document).off(this.eventsToBlock).off('keydown.' + this.id); }, hide: function() { $(document.body).children('.ui-spotlight').hide(); this.unblockEvents(); this.target.css('z-index', this.target.zIndex()); } }); /** * PrimeFaces Sticky Widget */ PrimeFaces.widget.Sticky = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this.cfg = cfg; this.id = this.cfg.id; this.target = $(PrimeFaces.escapeClientId(this.cfg.target)); this.cfg.margin = this.cfg.margin||0; this.initialState = { top: this.target.offset().top, width: this.target.width(), height: this.target.height() }; var win = $(window), $this = this; $(window).on('scroll.' + this.cfg.id, function() { if(win.scrollTop() > $this.initialState.top) { $this.fix(); } else { $this.restore(); } }); }, refresh: function(cfg) { $(window).off('scroll.' + this.cfg.id); this.init(cfg); }, fix: function() { if(!this.fixed) { this.target.css({ 'position': 'fixed', 'top': this.cfg.margin, 'z-index': ++PrimeFaces.zindex, 'width': this.initialState.width }) .addClass('ui-shadow ui-sticky'); $('
').height(this.initialState.height).insertBefore(this.target); this.fixed = true; } }, restore: function() { if(this.fixed) { this.target.css({ position: 'static', top: 'auto', 'width': this.initialState.width }) .removeClass('ui-shadow ui-sticky'); this.target.prev('.ui-sticky-ghost').remove(); this.fixed = false; } } }); /** * PrimeFaces TabView Widget */ PrimeFaces.widget.TabView = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.panelContainer = this.jq.children('.ui-tabs-panels'); this.stateHolder = $(this.jqId + '_activeIndex'); this.cfg.selected = parseInt(this.stateHolder.val()); this.focusedTabHeader = null; this.cfg.tabindex = this.cfg.tabindex||'0'; if(this.cfg.scrollable) { this.navscroller = this.jq.children('.ui-tabs-navscroller'); this.navcrollerLeft = this.navscroller.children('.ui-tabs-navscroller-btn-left'); this.navcrollerRight = this.navscroller.children('.ui-tabs-navscroller-btn-right'); this.navContainer = this.navscroller.children('.ui-tabs-nav'); this.firstTab = this.navContainer.children(':first-child'); this.lastTab = this.navContainer.children(':last-child'); this.scrollStateHolder = $(this.jqId + '_scrollState'); } else { this.navContainer = this.jq.children('.ui-tabs-nav'); } this.navContainerItems = this.navContainer.children('li'); for(var i = 0; i < this.navContainerItems.length; i++) { if(this.cfg.selected === i && !this.navContainerItems.eq(i).hasClass('ui-state-disabled')) { this.navContainerItems.eq(i).attr('tabindex', this.cfg.tabindex); } else { this.navContainerItems.eq(i).attr('tabindex', '-1'); } } this.bindEvents(); //Cache initial active tab if(this.cfg.dynamic && this.cfg.cache) { this.markAsLoaded(this.panelContainer.children().eq(this.cfg.selected)); } if(this.cfg.scrollable) { if(this.jq.is(':visible')) { this.initScrolling(); } else { var hiddenParent = this.jq.parent().closest('.ui-hidden-container'), hiddenParentWidgetVar = hiddenParent.data('widget'), $this = this; if(hiddenParentWidgetVar) { var hiddenParentWidget = PF(hiddenParentWidgetVar); if(hiddenParentWidget) { hiddenParentWidget.addOnshowHandler(this.id, function() { return $this.initScrolling(); }); } } } } }, bindEvents: function() { var $this = this; //Tab header events this.navContainer.children('li') .on('mouseover.tabview', function(e) { var element = $(this); if(!element.hasClass('ui-state-disabled')) { element.addClass('ui-state-hover'); } }) .on('mouseout.tabview', function(e) { var element = $(this); if(!element.hasClass('ui-state-disabled')) { element.removeClass('ui-state-hover'); } }) .on('click.tabview', function(e) { var element = $(this); if($(e.target).is(':not(.ui-icon-close)')) { var index = element.index(); if(!element.hasClass('ui-state-disabled') && index !== $this.cfg.selected) { $this.select(index); element.trigger('focus.tabview'); } } e.preventDefault(); }); //Closable tabs this.navContainer.find('li .ui-icon-close') .on('click.tabview', function(e) { var index = $(this).parent().index(); if($this.cfg.onTabClose) { var retVal = $this.cfg.onTabClose.call($this, index); if(retVal !== false) { $this.remove(index); } } else { $this.remove(index); } e.preventDefault(); }); //Scrolling if(this.cfg.scrollable) { this.navscroller.children('.ui-tabs-navscroller-btn') .on('mouseover.tabview', function() { var el = $(this); if(!el.hasClass('ui-state-disabled')) $(this).addClass('ui-state-hover'); }) .on('mouseout.tabview', function() { var el = $(this); if(!el.hasClass('ui-state-disabled')) $(this).removeClass('ui-state-hover ui-state-active'); }) .on('mousedown.tabview', function() { var el = $(this); if(!el.hasClass('ui-state-disabled')) $(this).removeClass('ui-state-hover').addClass('ui-state-active'); }) .on('mouseup.tabview', function() { var el = $(this); if(!el.hasClass('ui-state-disabled')) $(this).addClass('ui-state-hover').removeClass('ui-state-active'); }); this.navcrollerLeft.on('click.tabview', function(e) { $this.scroll(100); e.preventDefault(); }); this.navcrollerRight.on('click.tabview', function(e) { $this.scroll(-100); e.preventDefault(); }); } this.bindKeyEvents(); }, bindKeyEvents: function() { var $this = this; this.navContainer.children('li').on('focus.tabview', function() { $this.focusedTabHeader = $(this); if(!$this.focusedTabHeader.hasClass('ui-state-disabled')) { $this.navContainer.children('li[tabindex="'+ $this.cfg.tabindex +'"]').attr('tabindex', '-1').removeClass('ui-tabs-outline'); $this.focusedTabHeader.attr('tabindex', $this.cfg.tabindex).addClass('ui-tabs-outline'); } }) .on('blur.tabview', function(){ if($this.focusedTabHeader) { $this.focusedTabHeader.removeClass('ui-tabs-outline'); } }) .on('keydown.tabview', function(e) { var keyCode = $.ui.keyCode; switch(e.which) { case keyCode.LEFT: case keyCode.UP: if($this.focusedTabHeader) { if($this.cfg.scrollable && ($this.focusedTabHeader.index() === 0)) { break; } if($this.focusedTabHeader.index() === 0) { $this.focusedTabHeader = $this.navContainer.children('li:not(.ui-state-disabled):last'); } else { $this.focusedTabHeader = $this.focusedTabHeader.prevAll('li:not(.ui-state-disabled):first'); if(!$this.focusedTabHeader.length) { $this.focusedTabHeader = $this.navContainer.children('li:not(.ui-state-disabled):last'); } } $this.focusedTabHeader.trigger('focus.tabview'); if($this.cfg.scrollable) { var leftScroll = $this.focusedTabHeader.position().left < $this.navcrollerLeft.position().left; if(leftScroll) { $this.navcrollerLeft.trigger('click.tabview'); } } } e.preventDefault(); clearTimeout($this.activating); $this.activating = setTimeout(function() { $this.focusedTabHeader.trigger('click'); }, 500); break; case keyCode.RIGHT: case keyCode.DOWN: if($this.focusedTabHeader) { if($this.cfg.scrollable && ($this.focusedTabHeader.index() === ($this.getLength() - 1))) { break; } if($this.focusedTabHeader.index() === ($this.getLength() - 1)) { $this.focusedTabHeader = $this.navContainer.children('li:not(.ui-state-disabled):first'); } else { $this.focusedTabHeader = $this.focusedTabHeader.nextAll('li:not(.ui-state-disabled):first'); if(!$this.focusedTabHeader.length) { $this.focusedTabHeader = $this.navContainer.children('li:not(.ui-state-disabled):first'); } } $this.focusedTabHeader.trigger('focus.tabview'); if($this.cfg.scrollable) { var rightScroll = $this.focusedTabHeader.position().left + $this.focusedTabHeader.width() > $this.navcrollerRight.position().left; if(rightScroll) { $this.navcrollerRight.trigger('click.tabview'); } } } e.preventDefault(); clearTimeout($this.activating); $this.activating = setTimeout(function() { $this.focusedTabHeader.trigger('click'); }, 500); break; } }); }, initScrolling: function() { if(this.jq.is(':visible')) { var overflown = ((this.lastTab.position().left + this.lastTab.width()) - this.firstTab.position().left) > this.navscroller.innerWidth(); if(overflown) { this.navscroller.css('padding-left', '18px'); this.navcrollerLeft.show(); this.navcrollerRight.show(); this.restoreScrollState(); } return true; } else { return false; } }, scroll: function(step) { if(this.navContainer.is(':animated')) { return; } var oldMarginLeft = parseInt(this.navContainer.css('margin-left')), newMarginLeft = oldMarginLeft + step, viewportWidth = this.navscroller.innerWidth(), $this = this; if(step < 0) { var lastTabBoundry = this.lastTab.position().left + parseInt(this.lastTab.innerWidth()); if(lastTabBoundry > viewportWidth) this.navContainer.animate({'margin-left': newMarginLeft + 'px'}, 'fast', 'easeInOutCirc', function() { $this.saveScrollState(newMarginLeft); if((lastTabBoundry + step) < viewportWidth) $this.disableScrollerButton($this.navcrollerRight); if($this.navcrollerLeft.hasClass('ui-state-disabled')) $this.enableScrollerButton($this.navcrollerLeft); }); } else { if(newMarginLeft <= 0) { this.navContainer.animate({'margin-left': newMarginLeft + 'px'}, 'fast', 'easeInOutCirc', function() { $this.saveScrollState(newMarginLeft); if(newMarginLeft === 0) $this.disableScrollerButton($this.navcrollerLeft); if($this.navcrollerRight.hasClass('ui-state-disabled')) $this.enableScrollerButton($this.navcrollerRight); }); } } }, disableScrollerButton: function(btn) { btn.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active'); }, enableScrollerButton: function(btn) { btn.removeClass('ui-state-disabled'); }, saveScrollState: function(value) { this.scrollStateHolder.val(value); }, restoreScrollState: function() { var value = parseInt(this.scrollStateHolder.val()); if(value === 0) { this.disableScrollerButton(this.navcrollerLeft); } this.navContainer.css('margin-left', this.scrollStateHolder.val() + 'px'); }, /** * Selects an inactive tab given index */ select: function(index, silent) { //Call user onTabChange callback if(this.cfg.onTabChange && !silent) { var result = this.cfg.onTabChange.call(this, index); if(result === false) return false; } var newPanel = this.panelContainer.children().eq(index), shouldLoad = this.cfg.dynamic && !this.isLoaded(newPanel); //update state this.stateHolder.val(index); this.cfg.selected = index; if(shouldLoad) { this.loadDynamicTab(newPanel); } else { this.show(newPanel); if(this.hasBehavior('tabChange') && !silent) { this.fireTabChangeEvent(newPanel); } } return true; }, show: function(newPanel) { var headers = this.navContainer.children(), oldHeader = headers.filter('.ui-state-active'), newHeader = headers.eq(newPanel.index()), oldPanel = this.panelContainer.children('.ui-tabs-panel:visible'), _self = this; //aria oldPanel.attr('aria-hidden', true); oldHeader.attr('aria-expanded', false); oldHeader.attr('aria-selected', false); newPanel.attr('aria-hidden', false); newHeader.attr('aria-expanded', true); newHeader.attr('aria-selected', true); if(this.cfg.effect) { oldPanel.hide(this.cfg.effect, null, this.cfg.effectDuration, function() { oldHeader.removeClass('ui-state-focus ui-tabs-selected ui-state-active'); newHeader.addClass('ui-state-focus ui-tabs-selected ui-state-active'); newPanel.show(_self.cfg.effect, null, _self.cfg.effectDuration, function() { _self.postTabShow(newPanel); }); }); } else { oldHeader.removeClass('ui-state-focus ui-tabs-selected ui-state-active'); oldPanel.hide(); newHeader.addClass('ui-state-focus ui-tabs-selected ui-state-active'); newPanel.show(); this.postTabShow(newPanel); } }, /** * Loads tab contents with ajax */ loadDynamicTab: function(newPanel) { var $this = this, tabindex = newPanel.index(), options = { source: this.id, process: this.id, update: this.id, params: [ {name: this.id + '_contentLoad', value: true}, {name: this.id + '_newTab', value: newPanel.attr('id')}, {name: this.id + '_tabindex', value: tabindex} ], onsuccess: function(responseXML, status, xhr) { PrimeFaces.ajax.Response.handle(responseXML, status, xhr, { widget: $this, handle: function(content) { newPanel.html(content); if(this.cfg.cache) { this.markAsLoaded(newPanel); } } }); return true; }, oncomplete: function() { $this.show(newPanel); } }; if(this.hasBehavior('tabChange')) { var tabChangeBehavior = this.cfg.behaviors['tabChange']; tabChangeBehavior.call(this, options); } else { PrimeFaces.ajax.Request.handle(options); } }, /** * Removes a tab with given index */ remove: function(index) { var header = this.navContainer.children().eq(index), panel = this.panelContainer.children().eq(index); header.remove(); panel.remove(); var length = this.getLength(); if(length > 0) { if(index < this.cfg.selected) { this.cfg.selected--; } else if(index === this.cfg.selected) { var newIndex = (this.cfg.selected === (length)) ? (this.cfg.selected - 1): this.cfg.selected; this.select(newIndex, true); } } else { this.cfg.selected = -1; } this.fireTabCloseEvent(panel.attr('id'), index); }, getLength: function() { return this.navContainer.children().length; }, getActiveIndex: function() { return this.cfg.selected; }, fireTabChangeEvent: function(panel) { var tabChangeBehavior = this.cfg.behaviors['tabChange'], ext = { params: [ {name: this.id + '_newTab', value: panel.attr('id')}, {name: this.id + '_tabindex', value: panel.index()} ] }; tabChangeBehavior.call(this, ext); }, fireTabCloseEvent: function(id, index) { if(this.hasBehavior('tabClose')) { var tabCloseBehavior = this.cfg.behaviors['tabClose'], ext = { params: [ {name: this.id + '_closeTab', value: id}, {name: this.id + '_tabindex', value: index} ] }; tabCloseBehavior.call(this, ext); } }, hasBehavior: function(event) { if(this.cfg.behaviors) { return this.cfg.behaviors[event] !== undefined; } return false; }, markAsLoaded: function(panel) { panel.data('loaded', true); }, isLoaded: function(panel) { return panel.data('loaded') === true; }, disable: function(index) { this.navContainer.children().eq(index).addClass('ui-state-disabled'); }, enable: function(index) { this.navContainer.children().eq(index).removeClass('ui-state-disabled'); }, postTabShow: function(newPanel) { //execute user defined callback if(this.cfg.onTabShow) { this.cfg.onTabShow.call(this, newPanel.index()); } PrimeFaces.invokeDeferredRenders(this.id); } }); /** * PrimeFaces TagCloud Widget */ PrimeFaces.widget.TagCloud = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); var _self = this; this.jq.find('a').mouseover(function() { $(this).addClass('ui-state-hover'); }) .mouseout(function() { $(this).removeClass('ui-state-hover'); }) .click(function(e) { var link = $(this); if(link.attr('href') === '#') { _self.fireSelectEvent(link); e.preventDefault(); } }); }, fireSelectEvent: function(link) { if(this.cfg.behaviors) { var selectBehavior = this.cfg.behaviors['select']; if(selectBehavior) { var ext = { params: [ {name: this.id + '_itemIndex', value: link.parent().index()} ] }; selectBehavior.call(this, ext); } } } }); /** * PrimeFaces Tooltip Widget */ PrimeFaces.widget.Tooltip = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this.cfg = cfg; this.id = this.cfg.id; this.cfg.showEvent = this.cfg.showEvent ? this.cfg.showEvent + '.tooltip' : 'mouseover.tooltip'; this.cfg.hideEvent = this.cfg.hideEvent ? this.cfg.hideEvent + '.tooltip' : 'mouseout.tooltip'; this.cfg.showEffect = this.cfg.showEffect ? this.cfg.showEffect : 'fade'; this.cfg.hideEffect = this.cfg.hideEffect ? this.cfg.hideEffect : 'fade'; this.cfg.showDelay = this.cfg.showDelay||150; this.cfg.hideDelay = this.cfg.hideDelay||0; this.cfg.hideEffectDuration = this.cfg.target ? 250 : 1; if(this.cfg.target) this.bindTarget(); else this.bindGlobal(); this.removeScriptElement(this.id); }, refresh: function(cfg) { if(cfg.target) { if($(PrimeFaces.escapeClientId(cfg.id)).length > 1) $(document.body).children(PrimeFaces.escapeClientId(cfg.id)).remove(); } else { $(document.body).children('.ui-tooltip-global').remove(); } this._super(cfg); }, bindGlobal: function() { this.jq = $('
').appendTo('body'); this.cfg.globalSelector = this.cfg.globalSelector||'a,:input,:button'; this.cfg.escape = (this.cfg.escape === undefined) ? true : this.cfg.escape; var $this = this; $(document).off(this.cfg.showEvent + ' ' + this.cfg.hideEvent, this.cfg.globalSelector) .on(this.cfg.showEvent, this.cfg.globalSelector, function(e) { var element = $(this); if(element.prop('disabled')) { return; } if($this.cfg.trackMouse) { $this.mouseEvent = e; } var title = element.attr('title'); if(title) { element.data('tooltip', title).removeAttr('title'); } if(element.hasClass('ui-state-error')) { $this.jq.addClass('ui-state-error'); } var text = element.data('tooltip'); if(text) { if($this.cfg.escape) $this.jq.text(text); else $this.jq.html(text); $this.globalTitle = text; $this.target = element; $this.show(); } }) .on(this.cfg.hideEvent + '.tooltip', this.cfg.globalSelector, function() { if($this.globalTitle) { $this.hide(); $this.globalTitle = null; $this.target = null; $this.jq.removeClass('ui-state-error'); } }); var resizeNS = 'resize.tooltip'; $(window).unbind(resizeNS).bind(resizeNS, function() { if($this.jq.is(':visible')) { $this.align(); } }); }, bindTarget: function() { this.id = this.cfg.id; this.jqId = PrimeFaces.escapeClientId(this.id); this.jq = $(this.jqId); this.target = PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector(this.cfg.target); var $this = this; this.target.off(this.cfg.showEvent + ' ' + this.cfg.hideEvent) .on(this.cfg.showEvent, function(e) { if($this.cfg.trackMouse) { $this.mouseEvent = e; } var text = $.trim($this.jq.text()); if($this.jq.children().length > 0 || text !== '') { $this.show(); } }) .on(this.cfg.hideEvent + '.tooltip', function() { $this.hide(); }); this.jq.appendTo(document.body); if($.trim(this.jq.html()) === '') { this.jq.html(this.target.attr('title')); } this.target.removeAttr('title'); var resizeNS = 'resize.' + this.id; $(window).unbind(resizeNS).bind(resizeNS, function() { if($this.jq.is(':visible')) { $this.align(); } }); }, align: function() { this.jq.css({ left:'', top:'', 'z-index': ++PrimeFaces.zindex }); if(this.cfg.trackMouse && this.mouseEvent) { this.jq.position({ my: 'left top+15', at: 'right bottom', of: this.mouseEvent, collision: 'flipfit' }); this.mouseEvent = null; } else { this.jq.position({ my: 'left top', at: 'right bottom', of: this.target, collision: 'flipfit' }); } }, show: function() { if(this.target) { var $this = this; this.clearTimeout(); this.timeout = setTimeout(function() { $this._show(); }, this.cfg.showDelay); } }, _show: function() { var $this = this; if(this.cfg.beforeShow) { var retVal = this.cfg.beforeShow.call(this); if(retVal === false) { return; } } this.align(); if(this.cfg.trackMouse) { this.followMouse(); } this.jq.show(this.cfg.showEffect, {}, 250, function() { if($this.cfg.onShow) { $this.cfg.onShow.call(); } }); }, hide: function() { var $this = this; this.clearTimeout(); if(this.cfg.hideDelay) { this.timeout = setTimeout(function() { $this._hide(); }, this.cfg.hideDelay); } else { this._hide(); } }, _hide: function() { var $this = this; if(this.isVisible()) { this.jq.hide(this.cfg.hideEffect, {}, this.cfg.hideEffectDuration, function() { $(this).css('z-index', ''); if($this.cfg.trackMouse) { $this.unfollowMouse(); } if($this.cfg.onHide) { $this.cfg.onHide.call(); } }); } }, clearTimeout: function() { if(this.timeout) { clearTimeout(this.timeout); } }, followMouse: function() { var $this = this; this.target.on('mousemove.tooltip-track', function(e) { $this.jq.position({ my: 'left top+15', at: 'right bottom', of: e, collision: 'flipfit' }); }); }, unfollowMouse: function() { this.target.off('mousemove.tooltip-track'); }, isVisible: function() { return this.jq.is(':visible'); } }); /** * PrimeFaces Base Tree Widget */ PrimeFaces.widget.BaseTree = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.cfg.highlight = (this.cfg.highlight === false) ? false : true; this.focusedNode = null; if(this.cfg.selectionMode) { this.initSelection(); } this.bindEvents(); this.jq.data('widget', this); }, initSelection: function() { this.selectionHolder = $(this.jqId + '_selection'); var selectionsValue = this.selectionHolder.val(); this.selections = selectionsValue === '' ? [] : selectionsValue.split(','); if(this.isCheckboxSelection()) { this.preselectCheckbox(); } }, expandNode: function(node) { var $this = this; if(this.cfg.dynamic) { if(this.cfg.cache && $this.getNodeChildrenContainer(node).children().length > 0) { this.showNodeChildren(node); return; } if(node.data('processing')) { PrimeFaces.debug('Node is already being expanded, ignoring expand event.'); return; } node.data('processing', true); var options = { source: this.id, process: this.id, update: this.id, formId: this.cfg.formId, params: [ {name: this.id + '_expandNode', value: $this.getRowKey(node)} ], onsuccess: function(responseXML, status, xhr) { PrimeFaces.ajax.Response.handle(responseXML, status, xhr, { widget: $this, handle: function(content) { var nodeChildrenContainer = this.getNodeChildrenContainer(node); nodeChildrenContainer.append(content); this.showNodeChildren(node); if(this.cfg.draggable) { this.makeDraggable(nodeChildrenContainer.find('span.ui-treenode-content')); } if(this.cfg.droppable) { this.makeDropPoints(nodeChildrenContainer.find('li.ui-tree-droppoint')); this.makeDropNodes(nodeChildrenContainer.find('span.ui-treenode-droppable')); } } }); return true; }, oncomplete: function() { node.removeData('processing'); } }; if(this.hasBehavior('expand')) { var expandBehavior = this.cfg.behaviors['expand']; expandBehavior.call(this, options); } else { PrimeFaces.ajax.Request.handle(options); } } else { this.showNodeChildren(node); this.fireExpandEvent(node); } }, fireExpandEvent: function(node) { if(this.cfg.behaviors) { var expandBehavior = this.cfg.behaviors['expand']; if(expandBehavior) { var ext = { params: [ {name: this.id + '_expandNode', value: this.getRowKey(node)} ] }; expandBehavior.call(this, ext); } } }, fireCollapseEvent: function(node) { if(this.cfg.behaviors) { var collapseBehavior = this.cfg.behaviors['collapse']; if(collapseBehavior) { var ext = { params: [ {name: this.id + '_collapseNode', value: this.getRowKey(node)} ] }; collapseBehavior.call(this, ext); } } }, getNodeChildrenContainer: function(node) { throw "Unsupported Operation"; }, showNodeChildren: function(node) { throw "Unsupported Operation"; }, writeSelections: function() { this.selectionHolder.val(this.selections.join(',')); }, fireNodeSelectEvent: function(node) { if(this.isCheckboxSelection() && this.cfg.dynamic) { var $this = this, options = { source: this.id, process: this.id }; options.params = [ {name: this.id + '_instantSelection', value: this.getRowKey(node)} ]; options.oncomplete = function(xhr, status, args) { if(args.descendantRowKeys && args.descendantRowKeys !== '') { var rowKeys = args.descendantRowKeys.split(','); for(var i = 0; i < rowKeys.length; i++) { $this.addToSelection(rowKeys[i]); } $this.writeSelections(); } } if(this.hasBehavior('select')) { var selectBehavior = this.cfg.behaviors['select']; selectBehavior.call(this, options); } else { PrimeFaces.ajax.AjaxRequest(options); } } else { if(this.hasBehavior('select')) { var selectBehavior = this.cfg.behaviors['select'], ext = { params: [ {name: this.id + '_instantSelection', value: this.getRowKey(node)} ] }; selectBehavior.call(this, ext); } } }, fireNodeUnselectEvent: function(node) { if(this.cfg.behaviors) { var unselectBehavior = this.cfg.behaviors['unselect']; if(unselectBehavior) { var ext = { params: [ {name: this.id + '_instantUnselection', value: this.getRowKey(node)} ] }; unselectBehavior.call(this, ext); } } }, fireContextMenuEvent: function(node) { if(this.hasBehavior('contextMenu')) { var contextMenuBehavior = this.cfg.behaviors['contextMenu'], ext = { params: [ {name: this.id + '_contextMenuNode', value: this.getRowKey(node)} ] }; contextMenuBehavior.call(this, ext); } }, getRowKey: function(node) { return node.attr('data-rowkey'); }, isNodeSelected: function(node) { return $.inArray(this.getRowKey(node), this.selections) != -1; }, isSingleSelection: function() { return this.cfg.selectionMode == 'single'; }, isMultipleSelection: function() { return this.cfg.selectionMode == 'multiple'; }, isCheckboxSelection: function() { return this.cfg.selectionMode == 'checkbox'; }, addToSelection: function(rowKey) { if(!PrimeFaces.inArray(this.selections, rowKey)) { this.selections.push(rowKey); } }, removeFromSelection: function(rowKey) { this.selections = $.grep(this.selections, function(r) { return r !== rowKey; }); }, removeDescendantsFromSelection: function(rowKey) { var newSelections = []; for(var i = 0; i < this.selections.length; i++) { if(this.selections[i].indexOf(rowKey + '_') !== 0) newSelections.push(this.selections[i]); } this.selections = newSelections; }, hasBehavior: function(event) { if(this.cfg.behaviors) { return this.cfg.behaviors[event] != undefined; } return false; }, nodeClick: function(event, nodeContent) { PrimeFaces.clearSelection(); if($(event.target).is(':not(.ui-tree-toggler)')) { var node = nodeContent.parent(), selectable = nodeContent.hasClass('ui-tree-selectable'); if(this.cfg.onNodeClick) { this.cfg.onNodeClick.call(this, node, event); } if(selectable && (this.cfg.selectionMode||this.cfg.draggable)) { var selected = this.isNodeSelected(node), metaKey = event.metaKey||event.ctrlKey, shiftKey = event.shiftKey; if(this.isCheckboxSelection()) { this.toggleCheckboxNode(node); } else { if(selected && (metaKey)) { this.unselectNode(node); } else { if(this.isSingleSelection()||(this.isMultipleSelection() && !metaKey)) { this.unselectAllNodes(); } this.selectNode(node); this.cursorNode = node; } } if($(event.target).is(':not(:input:enabled)')) { this.focusNode(node); } } } }, nodeRightClick: function(event, nodeContent) { PrimeFaces.clearSelection(); if($(event.target).is(':not(.ui-tree-toggler)')) { var node = nodeContent.parent(), selectable = nodeContent.hasClass('ui-tree-selectable'); if(selectable && this.cfg.selectionMode) { var selected = this.isNodeSelected(node); if(!selected) { if(this.isCheckboxSelection()) { this.toggleCheckboxNode(node); } else { this.unselectAllNodes(); this.selectNode(node, true); } } this.fireContextMenuEvent(node); } } }, bindEvents: function() { throw "Unsupported Operation"; }, selectNode: function(node, silent) { throw "Unsupported Operation"; }, unselectNode: function(node, silent) { throw "Unsupported Operation"; }, unselectAllNodes: function() { throw "Unsupported Operation"; }, preselectCheckbox: function() { throw "Unsupported Operation"; }, toggleCheckboxNode: function(node) { throw "Unsupported Operation"; }, isEmpty: function() { throw "Unsupported Operation"; }, toggleCheckboxState: function(checkbox, checked) { if(checked) this.uncheck(checkbox); else this.check(checkbox); }, partialCheck: function(checkbox) { var box = checkbox.children('.ui-chkbox-box'), icon = box.children('.ui-chkbox-icon'), treeNode = checkbox.closest('.ui-treenode'), rowKey = this.getRowKey(treeNode); treeNode.find('> .ui-treenode-content > .ui-treenode-label').removeClass('ui-state-highlight'); icon.removeClass('ui-icon-blank ui-icon-check').addClass('ui-icon-minus'); treeNode.removeClass('ui-treenode-selected ui-treenode-unselected').addClass('ui-treenode-hasselected').attr('aria-checked', false).attr('aria-selected', false); this.removeFromSelection(rowKey); }, check: function(checkbox) { var box = checkbox.children('.ui-chkbox-box'), icon = box.children('.ui-chkbox-icon'), treeNode = checkbox.closest('.ui-treenode'), rowKey = this.getRowKey(treeNode); box.removeClass('ui-state-hover'); icon.removeClass('ui-icon-blank ui-icon-minus').addClass('ui-icon-check'); treeNode.removeClass('ui-treenode-hasselected ui-treenode-unselected').addClass('ui-treenode-selected').attr('aria-checked', true).attr('aria-selected', true); this.addToSelection(rowKey); }, uncheck: function(checkbox) { var box = checkbox.children('.ui-chkbox-box'), icon = box.children('.ui-chkbox-icon'), treeNode = checkbox.closest('.ui-treenode'), rowKey = this.getRowKey(treeNode); box.removeClass('ui-state-hover'); icon.removeClass('ui-icon-minus ui-icon-check').addClass('ui-icon-blank'); treeNode.removeClass('ui-treenode-hasselected ui-treenode-selected').addClass('ui-treenode-unselected').attr('aria-checked', false).attr('aria-selected', false); this.removeFromSelection(rowKey); }, isExpanded: function(node) { return this.getNodeChildrenContainer(node).is(':visible'); }, focusNode: function() { throw "Unsupported Operation"; } }); /** * PrimeFaces Vertical Tree Widget */ PrimeFaces.widget.VerticalTree = PrimeFaces.widget.BaseTree.extend({ init: function(cfg) { this._super(cfg); this.container = this.jq.children('.ui-tree-container'); this.cfg.rtl = this.jq.hasClass('ui-tree-rtl'); this.cfg.collapsedIcon = this.cfg.rtl ? 'ui-icon-triangle-1-w' : 'ui-icon-triangle-1-e'; if(this.cfg.draggable) { this.initDraggable(); } if(this.cfg.droppable) { this.initDroppable(); } }, bindEvents: function() { var $this = this, togglerSelector = '.ui-tree-toggler', nodeLabelSelector = '.ui-tree-selectable .ui-treenode-label', nodeContentSelector = '.ui-treenode-content'; this.jq.off('click.tree-toggle', togglerSelector) .on('click.tree-toggle', togglerSelector, null, function(e) { var toggleIcon = $(this), node = toggleIcon.closest('li'); if(toggleIcon.hasClass($this.cfg.collapsedIcon)) $this.expandNode(node); else $this.collapseNode(node); }); if(this.cfg.highlight && this.cfg.selectionMode) { this.jq.off('mouseout.tree mouseover.tree', nodeLabelSelector) .on('mouseout.tree', nodeLabelSelector, null, function() { var label = $(this); label.removeClass('ui-state-hover'); if($this.isCheckboxSelection()) { label.siblings('div.ui-chkbox').children('div.ui-chkbox-box').removeClass('ui-state-hover'); } }) .on('mouseover.tree', nodeLabelSelector, null, function() { var label = $(this); $(this).addClass('ui-state-hover'); if($this.isCheckboxSelection()) { label.siblings('div.ui-chkbox').children('div.ui-chkbox-box').addClass('ui-state-hover'); } }); } if(this.isCheckboxSelection()) { var checkboxSelector = '.ui-chkbox-box:not(.ui-state-disabled)'; this.jq.off('mouseout.tree-checkbox mouseover.tree-checkbox click.tree-checkbox', checkboxSelector) .on('mouseout.tree-checkbox', checkboxSelector, null, function() { $(this).removeClass('ui-state-hover').parent().siblings('span.ui-treenode-label').removeClass('ui-state-hover'); }) .on('mouseover.tree-checkbox', checkboxSelector, null, function() { $(this).addClass('ui-state-hover').parent().siblings('span.ui-treenode-label').addClass('ui-state-hover'); }); } this.jq.off('click.tree-content', nodeContentSelector) .on('click.tree-content', nodeContentSelector, null, function(e) { $this.nodeClick(e, $(this)); }); this.bindKeyEvents(); }, bindKeyEvents: function() { var $this = this; this.jq.on('mousedown.tree', function(e) { if($(e.target).is(':not(:input:enabled)')) { e.preventDefault(); } }) .on('focus.tree', function() { if(!$this.focusedNode) { $this.focusNode($this.getFirstNode()); } }); this.jq.off('keydown.tree blur.tree', '.ui-treenode-label').on('keydown.tree', '.ui-treenode-label', null, function(e) { if(!$this.focusedNode) { return; } var searchRowkey = "", keyCode = $.ui.keyCode; switch(e.which) { case keyCode.LEFT: var rowkey = $this.focusedNode.data('rowkey').toString(), keyLength = rowkey.length; if($this.isExpanded($this.focusedNode)) { $this.collapseNode($this.focusedNode); } else { var nodeToFocus = null; for(var i = 1; i < parseInt(keyLength / 2) + 1; i++){ searchRowkey = rowkey.substring(0, keyLength - 2 * i); nodeToFocus = $this.container.find("li:visible[data-rowkey = '" + searchRowkey + "']"); if(nodeToFocus.length) { $this.focusNode(nodeToFocus); break; } } } e.preventDefault(); break; case keyCode.RIGHT: if(!$this.focusedNode.hasClass('ui-treenode-leaf')) { var rowkey = $this.focusedNode.data('rowkey').toString(), keyLength = rowkey.length; if(!$this.isExpanded($this.focusedNode)) { $this.expandNode($this.focusedNode); } if(!$this.isExpanded($this.focusedNode) && !$this.cfg.dynamic) { searchRowkey = rowkey + '_0'; var nodeToFocus = $this.container.find("li:visible[data-rowkey = '" + searchRowkey + "']"); if(nodeToFocus.length) { $this.focusNode(nodeToFocus); } } } e.preventDefault(); break; case keyCode.UP: var nodeToFocus = null, prevNode = $this.focusedNode.prev(); if(prevNode.length) { nodeToFocus = prevNode.find('li.ui-treenode:visible:last'); if(!nodeToFocus.length) { nodeToFocus = prevNode; } } else { nodeToFocus = $this.focusedNode.closest('ul').parent('li'); } if(nodeToFocus.length) { $this.focusNode(nodeToFocus); } e.preventDefault(); break; case keyCode.DOWN: var nodeToFocus = null, firstVisibleChildNode = $this.focusedNode.find("> ul > li:visible:first"); if(firstVisibleChildNode.length) { nodeToFocus = firstVisibleChildNode; } else if($this.focusedNode.next().length) { nodeToFocus = $this.focusedNode.next(); } else { var rowkey = $this.focusedNode.data('rowkey').toString(); if(rowkey.length !== 1) { nodeToFocus = $this.searchDown($this.focusedNode); } } if(nodeToFocus && nodeToFocus.length) { $this.focusNode(nodeToFocus); } e.preventDefault(); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: case keyCode.SPACE: if($this.cfg.selectionMode) { var selectable = $this.focusedNode.children('.ui-treenode-content').hasClass('ui-tree-selectable'); if($this.cfg.onNodeClick) { $this.cfg.onNodeClick.call($this, $this.focusedNode, e); } if(selectable) { var selected = $this.isNodeSelected($this.focusedNode); if($this.isCheckboxSelection()) { $this.toggleCheckboxNode($this.focusedNode); } else { if(selected) { $this.unselectNode($this.focusedNode); } else { if($this.isSingleSelection()) { $this.unselectAllNodes(); } $this.selectNode($this.focusedNode); $this.cursorNode = $this.focusedNode; } } } } e.preventDefault(); break; } }) .on('blur.tree', '.ui-treenode-label', null, function(e) { if($this.focusedNode) { $this.getNodeLabel($this.focusedNode).removeClass('ui-treenode-outline'); $this.focusedNode = null; } }); }, searchDown: function(node) { var nextOfParent = node.closest('ul').parent('li').next(), nodeToFocus = null; if(nextOfParent.length) { nodeToFocus = nextOfParent; } else if(node.hasClass('ui-treenode-leaf') && node.closest('ul').parent('li').length == 0){ nodeToFocus = node; } else { var rowkey = node.data('rowkey').toString(); if(rowkey.length !== 1) { nodeToFocus = this.searchDown(node.closest('ul').parent('li')); } } return nodeToFocus; }, collapseNode: function(node) { var _self = this, nodeContent = node.find('> .ui-treenode-content'), toggleIcon = nodeContent.find('> .ui-tree-toggler'), nodeType = node.data('nodetype'), nodeIcon = toggleIcon.nextAll('span.ui-treenode-icon'), iconState = this.cfg.iconStates[nodeType], childrenContainer = node.children('.ui-treenode-children'); //aria nodeContent.find('> .ui-treenode-label').attr('aria-expanded', false); toggleIcon.addClass(_self.cfg.collapsedIcon).removeClass('ui-icon-triangle-1-s'); if(iconState) { nodeIcon.removeClass(iconState.expandedIcon).addClass(iconState.collapsedIcon); } if(this.cfg.animate) { childrenContainer.slideUp('fast', function() { _self.postCollapse(node, childrenContainer); }); } else { childrenContainer.hide(); this.postCollapse(node, childrenContainer); } }, postCollapse: function(node, childrenContainer) { if(this.cfg.dynamic && !this.cfg.cache) { childrenContainer.empty(); } this.fireCollapseEvent(node); }, //@Override getNodeChildrenContainer: function(node) { return node.children('.ui-treenode-children'); }, //@Override showNodeChildren: function(node) { var nodeContent = node.find('> .ui-treenode-content'), toggleIcon = nodeContent.find('> .ui-tree-toggler'), nodeType = node.data('nodetype'), nodeIcon = toggleIcon.nextAll('span.ui-treenode-icon'), iconState = this.cfg.iconStates[nodeType]; //aria nodeContent.find('> .ui-treenode-label').attr('aria-expanded', true); toggleIcon.addClass('ui-icon-triangle-1-s').removeClass(this.cfg.collapsedIcon); if(iconState) { nodeIcon.removeClass(iconState.collapsedIcon).addClass(iconState.expandedIcon); } if(this.cfg.animate) { node.children('.ui-treenode-children').slideDown('fast'); } else { node.children('.ui-treenode-children').show(); } }, unselectAllNodes: function() { this.selections = []; this.jq.find('.ui-treenode-label.ui-state-highlight').each(function() { $(this).removeClass('ui-state-highlight').closest('.ui-treenode').attr('aria-selected', false); }); }, selectNode: function(node, silent) { node.attr('aria-selected', true) .find('> .ui-treenode-content > .ui-treenode-label').removeClass('ui-state-hover').addClass('ui-state-highlight'); this.addToSelection(this.getRowKey(node)); this.writeSelections(); if(!silent) this.fireNodeSelectEvent(node); }, unselectNode: function(node, silent) { var rowKey = this.getRowKey(node); node.attr('aria-selected', false). find('> .ui-treenode-content > .ui-treenode-label').removeClass('ui-state-highlight ui-state-hover'); this.removeFromSelection(rowKey); this.writeSelections(); if(!silent) this.fireNodeUnselectEvent(node); }, toggleCheckboxNode: function(node) { var $this = this, checkbox = node.find('> .ui-treenode-content > .ui-chkbox'), checked = checkbox.find('> .ui-chkbox-box > .ui-chkbox-icon').hasClass('ui-icon-check'); this.toggleCheckboxState(checkbox, checked); if(this.cfg.propagateDown) { node.children('.ui-treenode-children').find('.ui-chkbox').each(function() { $this.toggleCheckboxState($(this), checked); }); if(this.cfg.dynamic) { this.removeDescendantsFromSelection(node.data('rowkey')); } } if(this.cfg.propagateUp) { node.parents('li.ui-treenode-parent').each(function() { var parentNode = $(this), parentsCheckbox = parentNode.find('> .ui-treenode-content > .ui-chkbox'), children = parentNode.find('> .ui-treenode-children > .ui-treenode'); if(checked) { if(children.filter('.ui-treenode-unselected').length === children.length) $this.uncheck(parentsCheckbox); else $this.partialCheck(parentsCheckbox); } else { if(children.filter('.ui-treenode-selected').length === children.length) $this.check(parentsCheckbox); else $this.partialCheck(parentsCheckbox); } }); } this.writeSelections(); if(checked) this.fireNodeUnselectEvent(node); else this.fireNodeSelectEvent(node); }, preselectCheckbox: function() { this.jq.find('.ui-chkbox-icon').not('.ui-icon-check').each(function() { var icon = $(this), node = icon.closest('li'); if(node.children('.ui-treenode-children').find('.ui-chkbox-icon.ui-icon-check').length > 0) { node.addClass('ui-treenode-hasselected'); icon.removeClass('ui-icon-blank').addClass('ui-icon-minus'); } }); }, check: function(checkbox) { this._super(checkbox); checkbox.siblings('span.ui-treenode-label').addClass('ui-state-highlight').removeClass('ui-state-hover'); }, uncheck: function(checkbox) { this._super(checkbox); checkbox.siblings('span.ui-treenode-label').removeClass('ui-state-highlight'); }, initDraggable: function() { this.makeDraggable(this.jq.find('span.ui-treenode-content')); }, initDroppable: function() { this.makeDropPoints(this.jq.find('li.ui-tree-droppoint')); this.makeDropNodes(this.jq.find('span.ui-treenode-droppable')); this.initDropScrollers(); }, makeDraggable: function(elements) { var $this = this, dragdropScope = this.cfg.dragdropScope||this.id; elements.draggable({ helper: function() { var el = $('
'); el.width($this.jq.width()); el.height(20); return el; }, appendTo: document.body, zIndex: ++PrimeFaces.zindex, revert: true, scope: dragdropScope }) .data({ 'dragsourceid': this.jqId, 'dragmode': this.cfg.dragMode }); }, makeDropPoints: function(elements) { var $this = this, dragdropScope = this.cfg.dragdropScope||this.id; elements.droppable({ hoverClass: 'ui-state-hover', accept: 'span.ui-treenode-content', tolerance: 'pointer', scope: dragdropScope, drop: function(event, ui) { var dragSource = $(ui.draggable.data('dragsourceid')).data('widget'), dragMode = ui.draggable.data('dragmode'), dropSource = $this, dropPoint = $(this), dropNode = dropPoint.closest('li.ui-treenode-parent'), dropNodeKey = $this.getRowKey(dropNode), dragNode = ui.draggable.closest('li.ui-treenode'), targetDragNode = $this.findTargetDragNode(dragNode, dragMode), dragNodeKey = $this.getRowKey(targetDragNode), dragNodeDropPoint = targetDragNode.next('li.ui-tree-droppoint'), oldParentNode = targetDragNode.parent().closest('li.ui-treenode-parent'), transfer = (dragSource.id !== dropSource.id); ui.helper.remove(); dropPoint.removeClass('ui-state-hover'); var validDrop = $this.validateDropPoint(dragNode, dropPoint); if(!validDrop) { return; } targetDragNode.hide().insertAfter(dropPoint); if(transfer) { if(dragSource.cfg.selectionMode) { dragSource.unselectSubtree(targetDragNode); } dragNodeDropPoint.remove(); $this.updateDragDropBindings(targetDragNode); } else { dragNodeDropPoint.insertAfter(targetDragNode); } if(oldParentNode.length && (oldParentNode.find('> ul.ui-treenode-children > li.ui-treenode').length === 0)) { $this.makeLeaf(oldParentNode); } targetDragNode.fadeIn(); if($this.isCheckboxSelection()) { $this.syncDNDCheckboxes(dragSource, oldParentNode, dropNode); } $this.syncDragDrop(); if(transfer) { dragSource.syncDragDrop(); } $this.fireDragDropEvent({ 'dragNodeKey': dragNodeKey, 'dropNodeKey': dropNodeKey, 'dragSource': dragSource.id, 'dndIndex': dropPoint.prevAll('li.ui-treenode').length, 'transfer': transfer }); } }); }, makeDropNodes: function(elements) { var $this = this, dragdropScope = this.cfg.dragdropScope||this.id; elements.droppable({ accept: '.ui-treenode-content', tolerance: 'pointer', scope: dragdropScope, over: function(event, ui) { $(this).children('.ui-treenode-label').addClass('ui-state-hover'); }, out: function(event, ui) { $(this).children('.ui-treenode-label').removeClass('ui-state-hover'); }, drop: function(event, ui) { var dragSource = $(ui.draggable.data('dragsourceid')).data('widget'), dragMode = ui.draggable.data('dragmode'), dropSource = $this, droppable = $(this), dropNode = droppable.closest('li.ui-treenode'), dropNodeKey = $this.getRowKey(dropNode), dragNode = ui.draggable.closest('li.ui-treenode'), targetDragNode = $this.findTargetDragNode(dragNode, dragMode), dragNodeKey = $this.getRowKey(targetDragNode), dragNodeDropPoint = targetDragNode.next('li.ui-tree-droppoint'), oldParentNode = targetDragNode.parent().closest('li.ui-treenode-parent'), childrenContainer = dropNode.children('.ui-treenode-children'), transfer = (dragSource.id !== dropSource.id); ui.helper.remove(); droppable.children('.ui-treenode-label').removeClass('ui-state-hover'); var validDrop = $this.validateDropNode(dragNode, dropNode, oldParentNode); if(!validDrop) { return; } if(childrenContainer.children('li.ui-treenode').length === 0) { $this.makeParent(dropNode); } targetDragNode.hide(); childrenContainer.append(targetDragNode); if(oldParentNode.length && (oldParentNode.find('> ul.ui-treenode-children > li.ui-treenode').length === 0)) { $this.makeLeaf(oldParentNode); } if(transfer) { if(dragSource.cfg.selectionMode) { dragSource.unselectSubtree(targetDragNode); } dragNodeDropPoint.remove(); $this.updateDragDropBindings(targetDragNode); } else { childrenContainer.append(dragNodeDropPoint); } targetDragNode.fadeIn(); if($this.isCheckboxSelection()) { $this.syncDNDCheckboxes(dragSource, oldParentNode, dropNode); } $this.syncDragDrop(); if(transfer) { dragSource.syncDragDrop(); } $this.fireDragDropEvent({ 'dragNodeKey': dragNodeKey, 'dropNodeKey': dropNodeKey, 'dragSource': dragSource.id, 'dndIndex': targetDragNode.prevAll('li.ui-treenode').length, 'transfer': transfer }); } }); }, initDropScrollers: function() { var $this = this, dragdropScope = this.cfg.dragdropScope||this.id; this.jq.prepend('
').append('
'); this.jq.children('div.ui-tree-scroller').droppable({ accept: '.ui-treenode-content', tolerance: 'pointer', scope: dragdropScope, over: function() { var step = $(this).hasClass('ui-tree-scrollertop') ? -10 : 10; $this.scrollInterval = setInterval(function() { $this.scroll(step); }, 100); }, out: function() { clearInterval($this.scrollInterval); } }); }, scroll: function(step) { this.container.scrollTop(this.container.scrollTop() + step); }, updateDragDropBindings: function(node) { //self droppoint node.after('
  • '); this.makeDropPoints(node.next('li.ui-tree-droppoint')); //descendant droppoints var subtreeDropPoints = node.find('li.ui-tree-droppoint'); subtreeDropPoints.droppable('destroy'); this.makeDropPoints(subtreeDropPoints); //descendant drop node contents var subtreeDropNodeContents = node.find('span.ui-treenode-content'); subtreeDropNodeContents.droppable('destroy'); this.makeDropNodes(subtreeDropNodeContents); if(this.cfg.draggable) { subtreeDropNodeContents.data({ 'dragsourceid': this.jqId, 'dragmode': this.cfg.dragMode }); } }, findTargetDragNode: function(dragNode, dragMode) { var targetDragNode = null; if(dragMode === 'self') { targetDragNode = dragNode; } else if(dragMode === 'parent') { targetDragNode = dragNode.parent().closest('li.ui-treenode'); } else if(dragMode === 'ancestor') { targetDragNode = dragNode.parent().parents('li.ui-treenode:last'); } if(targetDragNode.length === 0) { targetDragNode = dragNode; } return targetDragNode; }, findNodes: function(rowkeys) { var nodes = []; for(var i = 0; i < rowkeys.length; i++) { nodes.push($(this.jqId + '\\:' + rowkeys[i])); } return nodes; }, updateRowKeys: function() { var children = this.jq.find('> ul.ui-tree-container > li.ui-treenode'); this.updateChildrenRowKeys(children, null); }, updateChildrenRowKeys: function(children, rowkey) { var $this = this; children.each(function(i) { var childNode = $(this), oldRowKey = childNode.attr('data-rowkey'), newRowKey = (rowkey === null) ? i.toString() : rowkey + '_' + i; childNode.attr({ 'id': $this.id + ':' + newRowKey, 'data-rowkey' : newRowKey }); if(childNode.hasClass('ui-treenode-parent')) { $this.updateChildrenRowKeys(childNode.find('> ul.ui-treenode-children > li.ui-treenode'), newRowKey); } }); }, validateDropPoint: function(dragNode, dropPoint) { //dropped before or after if(dragNode.next().get(0) === dropPoint.get(0)||dragNode.prev().get(0) === dropPoint.get(0)) { return false; } //descendant of dropnode if(dragNode.has(dropPoint.get(0)).length) { return false; } //drop restriction if(this.cfg.dropRestrict) { if(this.cfg.dropRestrict === 'sibling' && dragNode.parent().get(0) !== dropPoint.parent().get(0)) { return false; } } return true; }, validateDropNode: function(dragNode, dropNode, oldParentNode) { //dropped on parent if(oldParentNode.get(0) === dropNode.get(0)) return false; //descendant of dropnode if(dragNode.has(dropNode.get(0)).length) { return false; } //drop restriction if(this.cfg.dropRestrict) { if(this.cfg.dropRestrict === 'sibling') { return false; } } return true; }, makeLeaf: function(node) { node.removeClass('ui-treenode-parent').addClass('ui-treenode-leaf'); node.find('> .ui-treenode-content > .ui-tree-toggler').addClass('ui-treenode-leaf-icon').removeClass('ui-tree-toggler ui-icon ui-icon-triangle-1-s'); node.children('.ui-treenode-children').hide().children().remove(); }, makeParent: function(node) { node.removeClass('ui-treenode-leaf').addClass('ui-treenode-parent'); node.find('> span.ui-treenode-content > span.ui-treenode-leaf-icon').removeClass('ui-treenode-leaf-icon').addClass('ui-tree-toggler ui-icon ui-icon-triangle-1-e'); node.children('.ui-treenode-children').append('
  • '); this.makeDropPoints(node.find('> ul.ui-treenode-children > li.ui-tree-droppoint')); }, syncDragDrop: function() { var $this = this; if(this.cfg.selectionMode) { var selectedNodes = this.findNodes(this.selections); this.updateRowKeys(); this.selections = []; $.each(selectedNodes, function(i, item) { $this.selections.push(item.attr('data-rowkey')); }); this.writeSelections(); } else { this.updateRowKeys(); } }, syncDNDCheckboxes: function(dragSource, oldParentNode, newParentNode) { if(oldParentNode.length) { dragSource.propagateDNDCheckbox(oldParentNode); } if(newParentNode.length) { this.propagateDNDCheckbox(newParentNode); } }, unselectSubtree: function(node) { var $this = this; if(this.isCheckboxSelection()) { var checkbox = node.find('> .ui-treenode-content > .ui-chkbox'); this.toggleCheckboxState(checkbox, true); node.children('.ui-treenode-children').find('.ui-chkbox').each(function() { $this.toggleCheckboxState($(this), true); }); } else { node.find('.ui-treenode-label.ui-state-highlight').each(function() { $(this).removeClass('ui-state-highlight').closest('li.ui-treenode').attr('aria-selected', false); }); } }, propagateDNDCheckbox: function(node) { var checkbox = node.find('> .ui-treenode-content > .ui-chkbox'), children = node.find('> .ui-treenode-children > .ui-treenode'); if(children.length) { if(children.filter('.ui-treenode-unselected').length === children.length) this.uncheck(checkbox); else if(children.filter('.ui-treenode-selected').length === children.length) this.check(checkbox); else this.partialCheck(checkbox); } var parent = node.parent().closest('.ui-treenode-parent'); if(parent.length) { this.propagateDNDCheckbox(parent); } }, fireDragDropEvent: function(event) { var $this = this, options = { source: this.id, process: event.transfer ? this.id + ' ' + event.dragSource : this.id }; options.params = [ {name: this.id + '_dragdrop', value: true}, {name: this.id + '_dragNode', value: event.dragNodeKey}, {name: this.id + '_dragSource', value: event.dragSource}, {name: this.id + '_dropNode', value: event.dropNodeKey}, {name: this.id + '_dndIndex', value: event.dndIndex} ]; if(this.hasBehavior('dragdrop')) { var dragdropBehavior = this.cfg.behaviors['dragdrop']; dragdropBehavior.call(this, options); } else { PrimeFaces.ajax.AjaxRequest(options); } }, isEmpty: function() { return (this.container.children().length === 0); }, getFirstNode: function() { return this.jq.find('> ul.ui-tree-container > li:first-child'); }, getNodeLabel: function(node) { return node.find('> span.ui-treenode-content > span.ui-treenode-label'); }, focusNode: function(node) { if(this.focusedNode) { this.getNodeLabel(this.focusedNode).removeClass('ui-treenode-outline'); } this.getNodeLabel(node).addClass('ui-treenode-outline').focus(); this.focusedNode = node; } }); /** * PrimeFaces Horizontal Tree Widget */ PrimeFaces.widget.HorizontalTree = PrimeFaces.widget.BaseTree.extend({ init: function(cfg) { this._super(cfg); if(PrimeFaces.isIE()) { this.drawConnectors(); } }, //@Override bindEvents: function() { var $this = this, selectionMode = this.cfg.selectionMode, togglerSelector = '.ui-tree-toggler', nodeContentSelector = '.ui-treenode-content.ui-tree-selectable'; this.jq.off('click.tree-toggle', togglerSelector) .on('click.tree-toggle', togglerSelector, null, function() { var icon = $(this), node = icon.closest('td.ui-treenode'); if(node.hasClass('ui-treenode-collapsed')) $this.expandNode(node); else $this.collapseNode(node); }); if(selectionMode && this.cfg.highlight) { this.jq.off('mouseout.tree mouseover.tree', nodeContentSelector) .on('mouseover.tree', nodeContentSelector, null, function() { var nodeContent = $(this); if(!nodeContent.hasClass('ui-state-highlight')) { nodeContent.addClass('ui-state-hover'); if($this.isCheckboxSelection()) { nodeContent.children('div.ui-chkbox').children('div.ui-chkbox-box').addClass('ui-state-hover'); } } }) .on('mouseout.tree', nodeContentSelector, null, function() { var nodeContent = $(this); if(!nodeContent.hasClass('ui-state-highlight')) { nodeContent.removeClass('ui-state-hover'); if($this.isCheckboxSelection()) { nodeContent.children('div.ui-chkbox').children('div.ui-chkbox-box').removeClass('ui-state-hover'); } } }); } this.jq.off('click.tree-content', nodeContentSelector) .on('click.tree-content', nodeContentSelector, null, function(e) { $this.nodeClick(e, $(this)); }); }, //@Override showNodeChildren: function(node) { node.attr('aria-expanded', true); var childrenContainer = node.next(), toggleIcon = node.find('> .ui-treenode-content > .ui-tree-toggler'), nodeType = node.data('nodetype'), iconState = this.cfg.iconStates[nodeType]; if(iconState) { toggleIcon.nextAll('span.ui-treenode-icon').removeClass(iconState.collapsedIcon).addClass(iconState.expandedIcon); } toggleIcon.addClass('ui-icon-minus').removeClass('ui-icon-plus'); node.removeClass('ui-treenode-collapsed'); childrenContainer.show(); if($.browser.msie) { this.drawConnectors(); } }, collapseNode: function(node) { var childrenContainer = node.next(), toggleIcon = node.find('> .ui-treenode-content > .ui-tree-toggler'), nodeType = node.data('nodetype'), iconState = this.cfg.iconStates[nodeType]; if(iconState) { toggleIcon.nextAll('span.ui-treenode-icon').addClass(iconState.collapsedIcon).removeClass(iconState.expandedIcon); } toggleIcon.removeClass('ui-icon-minus').addClass('ui-icon-plus'); node.addClass('ui-treenode-collapsed'); childrenContainer.hide(); if(this.cfg.dynamic && !this.cfg.cache) { childrenContainer.children('.ui-treenode-children').empty(); } this.fireCollapseEvent(node); if($.browser.msie) { this.drawConnectors(); } }, //@Override getNodeChildrenContainer: function(node) { return node.next('.ui-treenode-children-container').children('.ui-treenode-children'); }, selectNode: function(node, silent) { node.removeClass('ui-treenode-unselected').addClass('ui-treenode-selected').children('.ui-treenode-content').removeClass('ui-state-hover').addClass('ui-state-highlight'); this.addToSelection(this.getRowKey(node)); this.writeSelections(); if(!silent) this.fireNodeSelectEvent(node); }, unselectNode: function(node, silent) { var rowKey = this.getRowKey(node); node.removeClass('ui-treenode-selected').addClass('ui-treenode-unselected').children('.ui-treenode-content').removeClass('ui-state-highlight'); this.removeFromSelection(rowKey); this.writeSelections(); if(!silent) this.fireNodeUnselectEvent(node); }, unselectAllNodes: function() { this.selections = []; this.jq.find('.ui-treenode-content.ui-state-highlight').each(function() { $(this).removeClass('ui-state-highlight').closest('.ui-treenode').attr('aria-selected', false); }); }, preselectCheckbox: function() { var _self = this; this.jq.find('.ui-chkbox-icon').not('.ui-icon-check').each(function() { var icon = $(this), node = icon.closest('.ui-treenode'), childrenContainer = _self.getNodeChildrenContainer(node); if(childrenContainer.find('.ui-chkbox-icon.ui-icon-check').length > 0) { icon.removeClass('ui-icon-blank').addClass('ui-icon-minus'); } }); }, toggleCheckboxNode: function(node) { var $this = this, checkbox = node.find('> .ui-treenode-content > .ui-chkbox'), checked = checkbox.find('> .ui-chkbox-box > .ui-chkbox-icon').hasClass('ui-icon-check'); this.toggleCheckboxState(checkbox, checked); if(this.cfg.propagateDown) { node.next('.ui-treenode-children-container').find('.ui-chkbox').each(function() { $this.toggleCheckboxState($(this), checked); }); if(this.cfg.dynamic) { this.removeDescendantsFromSelection(node.data('rowkey')); } } if(this.cfg.propagateUp) { node.parents('td.ui-treenode-children-container').each(function() { var childrenContainer = $(this), parentNode = childrenContainer.prev('.ui-treenode-parent'), parentsCheckbox = parentNode.find('> .ui-treenode-content > .ui-chkbox'), children = childrenContainer.find('> .ui-treenode-children > table > tbody > tr > td.ui-treenode'); if(checked) { if(children.filter('.ui-treenode-unselected').length === children.length) $this.uncheck(parentsCheckbox); else $this.partialCheck(parentsCheckbox); } else { if(children.filter('.ui-treenode-selected').length === children.length) $this.check(parentsCheckbox); else $this.partialCheck(parentsCheckbox); } }); } this.writeSelections(); if(checked) this.fireNodeUnselectEvent(node); else this.fireNodeSelectEvent(node); }, check: function(checkbox) { this._super(checkbox); checkbox.parent('.ui-treenode-content').addClass('ui-state-highlight').removeClass('ui-state-hover'); }, uncheck: function(checkbox) { this._super(checkbox); checkbox.parent('.ui-treenode-content').removeClass('ui-state-highlight'); }, drawConnectors: function() { this.jq.find('table.ui-treenode-connector-table').each(function() { var table = $(this); table.height(0).height(table.parent().height()); }); }, isEmpty: function() { return this.jq.children('table').length === 0; }, focusNode: function(node) { //focus not supported in horizontal mode }, //@Override partialCheck: function(checkbox) { var box = checkbox.children('.ui-chkbox-box'), icon = box.children('.ui-chkbox-icon'), treeNode = checkbox.closest('.ui-treenode'), rowKey = this.getRowKey(treeNode); treeNode.find('> .ui-treenode-content').removeClass('ui-state-highlight'); icon.removeClass('ui-icon-blank ui-icon-check').addClass('ui-icon-minus'); treeNode.removeClass('ui-treenode-selected ui-treenode-unselected').addClass('ui-treenode-hasselected').attr('aria-checked', false).attr('aria-selected', false); this.removeFromSelection(rowKey); } }); /** * PrimeFaces TreeTable Widget */ PrimeFaces.widget.TreeTable = PrimeFaces.widget.DeferredWidget.extend({ init: function(cfg) { this._super(cfg); this.thead = $(this.jqId + '_head'); this.tbody = $(this.jqId + '_data'); this.renderDeferred(); }, _render: function() { if(this.cfg.scrollable) { this.setupScrolling(); } if(this.cfg.resizableColumns) { this.setupResizableColumns(); } this.bindEvents(); }, refresh: function(cfg) { this.columnWidthsFixed = false; this.init(cfg); }, bindEvents: function() { var $this = this, togglerSelector = '> tr > td:first-child > .ui-treetable-toggler'; //expand and collapse this.tbody.off('click.treeTable-toggle', togglerSelector) .on('click.treeTable-toggle', togglerSelector, null, function(e) { var toggler = $(this), node = toggler.closest('tr'); if(!node.data('processing')) { node.data('processing', true); if(toggler.hasClass('ui-icon-triangle-1-e')) $this.expandNode(node); else $this.collapseNode(node); } }); //selection if(this.cfg.selectionMode) { this.jqSelection = $(this.jqId + '_selection'); var selectionValue = this.jqSelection.val(); this.selections = selectionValue === "" ? [] : selectionValue.split(','); this.bindSelectionEvents(); } //sorting this.bindSortEvents(); }, bindSelectionEvents: function() { var $this = this, rowSelector = '> tr.ui-treetable-selectable-node'; this.tbody.off('mouseover.treeTable mouseout.treeTable click.treeTable', rowSelector) .on('mouseover.treeTable', rowSelector, null, function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) { element.addClass('ui-state-hover'); if($this.isCheckboxSelection() && !$this.cfg.nativeElements) { element.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box').addClass('ui-state-hover'); } } }) .on('mouseout.treeTable', rowSelector, null, function(e) { var element = $(this); if(!element.hasClass('ui-state-highlight')) { element.removeClass('ui-state-hover'); if($this.isCheckboxSelection() && !$this.cfg.nativeElements) { element.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box').removeClass('ui-state-hover'); } } }) .on('click.treeTable', rowSelector, null, function(e) { $this.onRowClick(e, $(this)); }); if(this.isCheckboxSelection()) { var checkboxSelector = this.cfg.nativeElements ? '> tr.ui-treetable-selectable-node > td:first-child :checkbox': '> tr.ui-treetable-selectable-node > td:first-child div.ui-chkbox-box'; this.tbody.off('click.treeTable-checkbox', checkboxSelector) .on('click.treeTable-checkbox', checkboxSelector, null, function(e) { var node = $(this).closest('tr.ui-treetable-selectable-node'); $this.toggleCheckboxNode(node); }); //initial partial selected visuals if(this.cfg.nativeElements) { this.indeterminateNodes(this.tbody.children('tr.ui-treetable-partialselected')); } } }, bindSortEvents: function() { var $this = this; this.sortableColumns = this.thead.find('> tr > th.ui-sortable-column'); this.sortableColumns.filter('.ui-state-active').each(function() { var columnHeader = $(this), sortIcon = columnHeader.children('span.ui-sortable-column-icon'), sortOrder = null; if(sortIcon.hasClass('ui-icon-triangle-1-n')) sortOrder = 'ASCENDING'; else sortOrder = 'DESCENDING'; columnHeader.data('sortorder', sortOrder); }); this.sortableColumns.on('mouseenter.treeTable', function() { var column = $(this); if(!column.hasClass('ui-state-active')) column.addClass('ui-state-hover'); }) .on('mouseleave.treeTable', function() { var column = $(this); if(!column.hasClass('ui-state-active')) column.removeClass('ui-state-hover'); }) .on('click.treeTable', function(e) { //Check if event target is not a clickable element in header content if($(e.target).is('th,span:not(.ui-c)')) { PrimeFaces.clearSelection(); var columnHeader = $(this), sortOrder = columnHeader.data('sortorder')||'DESCENDING'; if(sortOrder === 'ASCENDING') sortOrder = 'DESCENDING'; else if(sortOrder === 'DESCENDING') sortOrder = 'ASCENDING'; $this.sort(columnHeader, sortOrder); } }); }, sort: function(columnHeader, order) { var $this = this, options = { source: this.id, update: this.id, process: this.id, params: [ {name: this.id + '_sorting', value: true}, {name: this.id + '_sortKey', value: columnHeader.attr('id')}, {name: this.id + '_sortDir', value: order} ], onsuccess: function(responseXML, status, xhr) { PrimeFaces.ajax.Response.handle(responseXML, status, xhr, { widget: $this, handle: function(content) { this.tbody.html(content); columnHeader.siblings().filter('.ui-state-active').removeData('sortorder').removeClass('ui-state-active') .find('.ui-sortable-column-icon').removeClass('ui-icon-triangle-1-n ui-icon-triangle-1-s'); columnHeader.removeClass('ui-state-hover').addClass('ui-state-active').data('sortorder', order); var sortIcon = columnHeader.find('.ui-sortable-column-icon'); if(order === 'DESCENDING') sortIcon.removeClass('ui-icon-triangle-1-n').addClass('ui-icon-triangle-1-s'); else if(order === 'ASCENDING') sortIcon.removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-n'); } }); return true; }, oncomplete: function(xhr, status, args) { if($this.cfg.selectionMode && args.selection) { $this.selections = args.selection.split(','); $this.writeSelections(); } } }; if(this.hasBehavior('sort')) { var sortBehavior = this.cfg.behaviors['sort']; sortBehavior.call(this, options); } else { PrimeFaces.ajax.Request.handle(options); } }, expandNode: function(node) { var $this = this, nodeKey = node.attr('data-rk'), options = { source: this.id, process: this.id, update: this.id, params: [ {name: this.id + '_expand', value: nodeKey} ], onsuccess: function(responseXML, status, xhr) { PrimeFaces.ajax.Response.handle(responseXML, status, xhr, { widget: $this, handle: function(content) { node.after(content); node.find('.ui-treetable-toggler:first').addClass('ui-icon-triangle-1-s').removeClass('ui-icon-triangle-1-e'); node.attr('aria-expanded', true); $this.indeterminateNodes($this.tbody.children('tr.ui-treetable-partialselected')); } }); return true; }, oncomplete: function() { node.data('processing', false); } }; if(this.hasBehavior('expand')) { var expandBehavior = this.cfg.behaviors['expand']; expandBehavior.call(this, options); } else { PrimeFaces.ajax.Request.handle(options); } }, collapseNode: function(node) { var nodeKey = node.attr('data-rk'), nextNodes = node.nextAll(); for(var i = 0; i < nextNodes.length; i++) { var nextNode = nextNodes.eq(i), nextNodeRowKey = nextNode.attr('data-rk'); if(nextNodeRowKey.indexOf(nodeKey) !== -1) { nextNode.remove(); } else { break; } } node.attr('aria-expanded', false).find('.ui-treetable-toggler:first').addClass('ui-icon-triangle-1-e').removeClass('ui-icon-triangle-1-s'); node.data('processing', false); if(this.hasBehavior('collapse')) { var collapseBehavior = this.cfg.behaviors['collapse'], nodeKey = node.attr('data-rk'); var ext = { params : [ {name: this.id + '_collapse', value: nodeKey} ] }; collapseBehavior.call(this, ext); } }, onRowClick: function(event, node) { if($(event.target).is('td,span:not(.ui-c)')) { var selected = node.hasClass('ui-state-highlight'), metaKey = event.metaKey||event.ctrlKey, shiftKey = event.shiftKey; if(this.isCheckboxSelection()) { this.toggleCheckboxNode(node); } else { if(selected && metaKey) { this.unselectNode(node); } else { if(this.isSingleSelection()||(this.isMultipleSelection() && !metaKey)) { this.unselectAllNodes(); } if(this.isMultipleSelection() && shiftKey) { this.selectNodesInRange(node); } else { this.selectNode(node); this.cursorNode = node; } } } PrimeFaces.clearSelection(); } }, onRowRightClick: function(event, node) { var selected = node.hasClass('ui-state-highlight'); if(this.isCheckboxSelection()) { if(!selected) { this.toggleCheckboxNode(node); } } else { if(this.isSingleSelection() || !selected ) { this.unselectAllNodes(); } this.selectNode(node); } PrimeFaces.clearSelection(); }, selectNode: function(node, silent) { var nodeKey = node.attr('data-rk'); node.removeClass('ui-state-hover ui-treetable-partialselected').addClass('ui-state-highlight').attr('aria-selected', true); this.addToSelection(nodeKey); this.writeSelections(); if(this.isCheckboxSelection()) { if(this.cfg.nativeElements) node.find('> td:first-child > :checkbox').prop('checked', true).prop('indeterminate', false); else node.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box').removeClass('ui-state-hover').children('span.ui-chkbox-icon').removeClass('ui-icon-blank ui-icon-minus').addClass('ui-icon-check'); } if(!silent) { this.fireSelectNodeEvent(nodeKey); } }, unselectNode: function(node, silent) { var nodeKey = node.attr('data-rk'); node.removeClass('ui-state-highlight ui-treetable-partialselected').attr('aria-selected', false); this.removeSelection(nodeKey); this.writeSelections(); if(this.isCheckboxSelection()) { if(this.cfg.nativeElements) node.find('> td:first-child > :checkbox').prop('checked', false).prop('indeterminate', false); else node.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box > span.ui-chkbox-icon').addClass('ui-icon-blank').removeClass('ui-icon-check ui-icon-minus'); } if(!silent) { this.fireUnselectNodeEvent(nodeKey); } }, unselectAllNodes: function() { var selectedNodes = this.tbody.children('tr.ui-state-highlight'); for(var i = 0; i < selectedNodes.length; i++) { this.unselectNode(selectedNodes.eq(i), true); } this.selections = []; this.writeSelections(); }, selectNodesInRange: function(node) { if(this.cursorNode) { this.unselectAllNodes(); var currentNodeIndex = node.index(), cursorNodeIndex = this.cursorNode.index(), startIndex = (currentNodeIndex > cursorNodeIndex) ? cursorNodeIndex : currentNodeIndex, endIndex = (currentNodeIndex > cursorNodeIndex) ? (currentNodeIndex + 1) : (cursorNodeIndex + 1), nodes = this.tbody.children(); for(var i = startIndex ; i < endIndex; i++) { this.selectNode(nodes.eq(i), true); } } else { this.selectNode(node); } }, indeterminateNodes: function(nodes) { for(var i = 0; i < nodes.length; i++) { nodes.eq(i).find('> td:first-child > :checkbox').prop('indeterminate', true); } }, toggleCheckboxNode: function(node) {; var selected = node.hasClass('ui-state-highlight'), rowKey = node.data('rk'); //toggle itself if(selected) this.unselectNode(node, true); else this.selectNode(node, true); //propagate down var descendants = this.getDescendants(node); for(var i = 0; i < descendants.length; i++) { var descendant = descendants[i]; if(selected) this.unselectNode(descendant, true); else this.selectNode(descendant, true); } if(selected) { this.removeDescendantsFromSelection(node.data('rk')); } //propagate up var parentNode = this.getParent(node); if(parentNode) { this.propagateUp(parentNode); } this.writeSelections(); if(selected) this.fireUnselectNodeEvent(rowKey); else this.fireSelectNodeEvent(rowKey); }, getDescendants: function(node) { var nodeKey = node.attr('data-rk'), nextNodes = node.nextAll(), descendants = []; for(var i = 0; i < nextNodes.length; i++) { var nextNode = nextNodes.eq(i), nextNodeRowKey = nextNode.attr('data-rk'); if(nextNodeRowKey.indexOf(nodeKey) != -1) { descendants.push(nextNode); } else { break; } } return descendants; }, getChildren: function(node) { var nodeKey = node.attr('data-rk'), nextNodes = node.nextAll(), children = []; for(var i = 0; i < nextNodes.length; i++) { var nextNode = nextNodes.eq(i), nextNodeParentKey = nextNode.attr('data-prk'); if(nextNodeParentKey === nodeKey) { children.push(nextNode); } } return children; }, propagateUp: function(node) { var children = this.getChildren(node), allSelected = true, partialSelected = false, checkbox = this.cfg.nativeElements ? node.find('> td:first-child > :checkbox') : node.find('> td:first-child > div.ui-chkbox > div.ui-chkbox-box > span.ui-chkbox-icon'); for(var i = 0; i < children.length; i++) { var child = children[i], childSelected = child.hasClass('ui-state-highlight'); allSelected = allSelected&&childSelected; partialSelected = partialSelected||childSelected||child.hasClass('ui-treetable-partialselected'); } if(allSelected) { node.removeClass('ui-treetable-partialselected'); this.selectNode(node, true); } else if(partialSelected) { node.removeClass('ui-state-highlight').addClass('ui-treetable-partialselected'); if(this.cfg.nativeElements) checkbox.prop('indeterminate', true); else checkbox.removeClass('ui-icon-blank ui-icon-check').addClass('ui-icon-minus'); this.removeSelection(node.attr('data-rk')); } else { node.removeClass('ui-state-highlight ui-treetable-partialselected'); if(this.cfg.nativeElements) checkbox.prop('indeterminate', false).prop('checked', false); else checkbox.addClass('ui-icon-blank').removeClass('ui-icon-check ui-icon-minus'); this.removeSelection(node.attr('data-rk')); } var parent = this.getParent(node); if(parent) { this.propagateUp(parent); } }, getParent: function(node) { var parent = $(this.jqId + '_node_' + node.attr('data-prk')); return parent.length === 1 ? parent : null; }, hasBehavior: function(event) { if(this.cfg.behaviors) { return this.cfg.behaviors[event] != undefined; } return false; }, removeDescendantsFromSelection: function(rowKey) { this.selections = $.grep(this.selections, function(value) { return value.indexOf(rowKey + '_') !== 0; }); }, removeSelection: function(nodeKey) { this.selections = $.grep(this.selections, function(value) { return value !== nodeKey; }); }, addToSelection: function(rowKey) { if(!this.isSelected(rowKey)) { this.selections.push(rowKey); } }, isSelected: function(nodeKey) { return PrimeFaces.inArray(this.selections, nodeKey); }, isSingleSelection: function() { return this.cfg.selectionMode == 'single'; }, isMultipleSelection: function() { return this.cfg.selectionMode == 'multiple'; }, isCheckboxSelection: function() { return this.cfg.selectionMode == 'checkbox'; }, writeSelections: function() { this.jqSelection.val(this.selections.join(',')); }, fireSelectNodeEvent: function(nodeKey) { if(this.isCheckboxSelection()) { var $this = this, options = { source: this.id, process: this.id }; options.params = [ {name: this.id + '_instantSelection', value: nodeKey} ]; options.oncomplete = function(xhr, status, args) { if(args.descendantRowKeys && args.descendantRowKeys !== '') { var rowKeys = args.descendantRowKeys.split(','); for(var i = 0; i < rowKeys.length; i++) { $this.addToSelection(rowKeys[i]); } $this.writeSelections(); } } if(this.hasBehavior('select')) { var selectBehavior = this.cfg.behaviors['select']; selectBehavior.call(this, options); } else { PrimeFaces.ajax.AjaxRequest(options); } } else { if(this.hasBehavior('select')) { var selectBehavior = this.cfg.behaviors['select'], ext = { params: [ {name: this.id + '_instantSelection', value: nodeKey} ] }; selectBehavior.call(this, ext); } } }, fireUnselectNodeEvent: function(nodeKey) { if(this.hasBehavior('unselect')) { var unselectBehavior = this.cfg.behaviors['unselect'], ext = { params: [ {name: this.id + '_instantUnselection', value: nodeKey} ] }; unselectBehavior.call(this, ext); } }, setupScrolling: function() { this.scrollHeader = this.jq.children('div.ui-treetable-scrollable-header'); this.scrollBody = this.jq.children('div.ui-treetable-scrollable-body'); this.scrollFooter = this.jq.children('div.ui-treetable-scrollable-footer'); this.scrollStateHolder = $(this.jqId + '_scrollState'); this.scrollHeaderBox = this.scrollHeader.children('div.ui-treetable-scrollable-header-box'); this.scrollFooterBox = this.scrollFooter.children('div.ui-treetable-scrollable-footer-box'); this.headerTable = this.scrollHeaderBox.children('table'); this.bodyTable = this.scrollBody.children('table'); this.footerTable = this.scrollFooterBox.children('table'); this.headerCols = this.headerTable.find('> thead > tr > th'); this.footerCols = this.footerTable.find('> tfoot > tr > td'); var $this = this; if(this.cfg.scrollHeight) { if(this.cfg.scrollHeight.indexOf('%') !== -1) { this.adjustScrollHeight(); } if(this.hasVerticalOverflow()) { var marginRight = this.getScrollbarWidth(); this.scrollHeaderBox.css('margin-right', marginRight); this.scrollBody.css('padding-right', marginRight); this.scrollFooterBox.css('margin-right', marginRight); } } this.fixColumnWidths(); if(this.cfg.scrollWidth) { if(this.cfg.scrollWidth.indexOf('%') !== -1) { this.adjustScrollWidth(); } else { this.setScrollWidth(parseInt(this.cfg.scrollWidth)); } } this.cloneHead(); this.restoreScrollState(); this.scrollBody.scroll(function() { var scrollLeft = $this.scrollBody.scrollLeft(); $this.scrollHeaderBox.css('margin-left', -scrollLeft); $this.scrollFooterBox.css('margin-left', -scrollLeft); $this.saveScrollState(); }); this.scrollHeader.on('scroll.treeTable', function() { $this.scrollHeader.scrollLeft(0); }); this.scrollFooter.on('scroll.treeTable', function() { $this.scrollFooter.scrollLeft(0); }); var resizeNS = 'resize.' + this.id; $(window).unbind(resizeNS).bind(resizeNS, function() { if($this.jq.is(':visible')) { if($this.percentageScrollHeight) $this.adjustScrollHeight(); if($this.percentageScrollWidth) $this.adjustScrollWidth(); } }); }, cloneHead: function() { this.theadClone = this.headerTable.children('thead').clone(); this.theadClone.find('th').each(function() { var header = $(this); header.attr('id', header.attr('id') + '_clone'); }); this.theadClone.removeAttr('id').addClass('ui-treetable-scrollable-theadclone').height(0).prependTo(this.bodyTable); }, fixColumnWidths: function() { var $this = this; if(!this.columnWidthsFixed) { if(this.cfg.scrollable) { this.headerCols.each(function() { var headerCol = $(this), colIndex = headerCol.index(), width = headerCol.width(); headerCol.width(width); if($this.footerCols.length > 0) { var footerCol = $this.footerCols.eq(colIndex); footerCol.width(width); } }); } else { this.jq.find('> table > thead > tr > th').each(function() { var col = $(this); col.width(col.width()); }); } this.columnWidthsFixed = true; } }, adjustScrollHeight: function() { var relativeHeight = this.jq.parent().innerHeight() * (parseInt(this.cfg.scrollHeight) / 100), tableHeaderHeight = this.jq.children('.ui-treetable-header').outerHeight(true), tableFooterHeight = this.jq.children('.ui-treetable-footer').outerHeight(true), scrollersHeight = (this.scrollHeader.outerHeight(true) + this.scrollFooter.outerHeight(true)), height = (relativeHeight - (scrollersHeight + tableHeaderHeight + tableFooterHeight)); this.scrollBody.height(height); }, adjustScrollWidth: function() { var width = parseInt((this.jq.parent().innerWidth() * (parseInt(this.cfg.scrollWidth) / 100))); this.setScrollWidth(width); }, setOuterWidth: function(element, width) { var diff = element.outerWidth() - element.width(); element.width(width - diff); }, hasVerticalOverflow: function() { return (this.cfg.scrollHeight && this.bodyTable.outerHeight() > this.scrollBody.outerHeight()); }, setScrollWidth: function(width) { var $this = this; this.jq.children('.ui-widget-header').each(function() { $this.setOuterWidth($(this), width); }); this.scrollHeader.width(width); this.scrollBody.css('padding-right', 0).width(width); this.scrollFooter.width(width); }, getScrollbarWidth: function() { return $.browser.webkit ? '15' : PrimeFaces.calculateScrollbarWidth(); }, restoreScrollState: function() { var scrollState = this.scrollStateHolder.val(), scrollValues = scrollState.split(','); this.scrollBody.scrollLeft(scrollValues[0]); this.scrollBody.scrollTop(scrollValues[1]); }, saveScrollState: function() { var scrollState = this.scrollBody.scrollLeft() + ',' + this.scrollBody.scrollTop(); this.scrollStateHolder.val(scrollState); }, setupResizableColumns: function() { this.fixColumnWidths(); if(!this.cfg.liveResize) { this.resizerHelper = $('
    ').appendTo(this.jq); } this.thead.find('> tr > th.ui-resizable-column:not(:last-child)').prepend(' '); var resizers = this.thead.find('> tr > th > span.ui-column-resizer'), $this = this; resizers.draggable({ axis: 'x', start: function() { if($this.cfg.liveResize) { $this.jq.css('cursor', 'col-resize'); } else { var height = $this.cfg.scrollable ? $this.scrollBody.height() : $this.thead.parent().height() - $this.thead.height() - 1; $this.resizerHelper.height(height); $this.resizerHelper.show(); } }, drag: function(event, ui) { if($this.cfg.liveResize) { $this.resize(event, ui); } else { $this.resizerHelper.offset({ left: ui.helper.offset().left + ui.helper.width() / 2, top: $this.thead.offset().top + $this.thead.height() }); } }, stop: function(event, ui) { var columnHeader = ui.helper.parent(); ui.helper.css('left',''); if($this.cfg.liveResize) { $this.jq.css('cursor', 'default'); } else { $this.resize(event, ui); $this.resizerHelper.hide(); } var options = { source: $this.id, process: $this.id, params: [ {name: $this.id + '_colResize', value: true}, {name: $this.id + '_columnId', value: columnHeader.attr('id')}, {name: $this.id + '_width', value: columnHeader.width()}, {name: $this.id + '_height', value: columnHeader.height()} ] } if($this.hasBehavior('colResize')) { $this.cfg.behaviors['colResize'].call($this, options); } }, containment: this.jq }); }, resize: function(event, ui) { var columnHeader = ui.helper.parent(), nextColumnHeader = columnHeader.next(), change = null, newWidth = null, nextColumnWidth = null; if(this.cfg.liveResize) { change = columnHeader.outerWidth() - (event.pageX - columnHeader.offset().left), newWidth = (columnHeader.width() - change), nextColumnWidth = (nextColumnHeader.width() + change); } else { change = (ui.position.left - ui.originalPosition.left), newWidth = (columnHeader.width() + change), nextColumnWidth = (nextColumnHeader.width() - change); } if(newWidth > 15 && nextColumnWidth > 15) { columnHeader.width(newWidth); nextColumnHeader.width(nextColumnWidth); var colIndex = columnHeader.index(); if(this.cfg.scrollable) { this.theadClone.find(PrimeFaces.escapeClientId(columnHeader.attr('id') + '_clone')).width(newWidth); this.theadClone.find(PrimeFaces.escapeClientId(nextColumnHeader.attr('id') + '_clone')).width(nextColumnWidth); if(this.footerCols.length > 0) { var footerCol = this.footerCols.eq(colIndex), nextFooterCol = footerCol.next(); footerCol.width(newWidth); nextFooterCol.width(nextColumnWidth); } } } } }); /** * PrimeFaces Wizard Component */ PrimeFaces.widget.Wizard = PrimeFaces.widget.BaseWidget.extend({ init: function(cfg) { this._super(cfg); this.content = $(this.jqId + '_content'); this.backNav = $(this.jqId + '_back'); this.nextNav = $(this.jqId + '_next'); this.cfg.formId = this.jq.parents('form:first').attr('id'); this.currentStep = this.cfg.initialStep; var _self = this; //Step controls if(this.cfg.showStepStatus) { this.stepControls = $(this.jqId + ' .ui-wizard-step-titles li.ui-wizard-step-title'); } //Navigation controls if(this.cfg.showNavBar) { var currentStepIndex = this.getStepIndex(this.currentStep); //visuals PrimeFaces.skinButton(this.backNav); PrimeFaces.skinButton(this.nextNav); //events this.backNav.click(function() {_self.back();}); this.nextNav.click(function() {_self.next();}); if(currentStepIndex == 0) this.backNav.hide(); else if(currentStepIndex == this.cfg.steps.length - 1) this.nextNav.hide(); } }, back: function() { if(this.cfg.onback) { var value = this.cfg.onback.call(this); if(value == false) { return; } } var stepToGo = this.cfg.steps[this.getStepIndex(this.currentStep) - 1]; this.loadStep(stepToGo, true); }, next: function() { if(this.cfg.onnext) { var value = this.cfg.onnext.call(this); if(value == false) { return; } } var stepToGo = this.cfg.steps[this.getStepIndex(this.currentStep) + 1]; this.loadStep(stepToGo, false); }, loadStep: function(stepToGo, isBack) { var $this = this, options = { source: this.id, process: this.id, update: this.id, formId: this.cfg.formId, params: [ {name: this.id + '_wizardRequest', value: true}, {name: this.id + '_stepToGo', value: stepToGo} ], onsuccess: function(responseXML, status, xhr) { PrimeFaces.ajax.Response.handle(responseXML, status, xhr, { widget: $this, handle: function(content) { this.content.html(content); } }); return true; }, oncomplete: function(xhr, status, args) { $this.currentStep = args.currentStep; if(!args.validationFailed) { var currentStepIndex = $this.getStepIndex($this.currentStep); if($this.cfg.showNavBar) { if(currentStepIndex === $this.cfg.steps.length - 1) { $this.hideNextNav(); $this.showBackNav(); } else if(currentStepIndex === 0) { $this.hideBackNav(); $this.showNextNav(); } else { $this.showBackNav(); $this.showNextNav(); } } //update step status if($this.cfg.showStepStatus) { $this.stepControls.removeClass('ui-state-highlight'); $($this.stepControls.get(currentStepIndex)).addClass('ui-state-highlight'); } } } }; if(isBack) { options.params.push({name: this.id + '_backRequest', value: true}); } PrimeFaces.ajax.Request.handle(options); }, getStepIndex: function(step) { for(var i=0; i < this.cfg.steps.length; i++) { if(this.cfg.steps[i] == step) return i; } return -1; }, showNextNav: function() { this.nextNav.fadeIn(); }, hideNextNav: function() { this.nextNav.fadeOut(); }, showBackNav: function() { this.backNav.fadeIn(); }, hideBackNav: function() { this.backNav.fadeOut(); } });