How to use handleElement method in Playwright Internal

Best JavaScript code snippet using playwright-internal

handle_element.js

Source:handle_element.js Github

copy

Full Screen

1(function($) {2 "use strict";3 $.IGModal = $.IGModal || {};4 $.HandleElement = $.HandleElement || {};5 $.PbDoing = $.PbDoing || {};6 $.HandleSetting = $.HandleSetting || {};7 $.options = {8 min_column_span : 2,9 layout_span : 12,10 new_sub_element : false,11 curr_iframe_ : null,12 clicked_column : null,13 if_childmodal : 0,14 modal_settings : {15 modalId: 'jsn_view_modal'16 },17 effect: 'easeOutCubic'18 }19 var clk_title_el , append_title_el;20 var el_type; // save type of editing shortcode: element/widget21 var input_enter;22 /**23 * 1. Common24 * 2. Resizable25 * 3. PageBuilder26 * 4. Modal27 */28 /***************************************************************************29 * 1. Common30 **************************************************************************/31 // alias for jQuery32 $.HandleElement.selector = function(curr_iframe, element) {33 var $selector = (curr_iframe != null && curr_iframe.contents() != null) ? curr_iframe.contents().find(element) : window.parent.jQuery.noConflict()(element);34 return $selector;35 },36 // Capitalize first character of whole string37 $.HandleElement.capitalize = function(text) {38 return text.charAt(0).toUpperCase()39 + text.slice(1).toLowerCase();40 },41 // Capitalize first character of each word42 $.HandleElement.ucwords = function(text) {43 return (text + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {44 return $1.toUpperCase();45 });46 },47 // Remove underscore character from string48 $.HandleElement.remove_underscore_ucwords = function(text) {49 var arr = text.split('_');50 return $.HandleElement.ucwords( arr.join(' ') ).replace(/^(Wp)\s+/g, '');51 },52 // Strip HTML tag from string53 $.HandleElement.strip_tags = function(input, allowed) {54 // Make sure the allowed argument is a string containing only tags in lowercase (<a><b><c>)55 allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');56 var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;57 return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {58 return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';59 });60 },61 // Get n first words of string62 $.HandleElement.sliceContent = function(text, limit) {63 text = unescape(text);64 text = text.replace(/\+/g, ' ');65 text = $.HandleElement.strip_tags(text);66 var arr = text.split(' ');67 arr = arr.slice(0, limit ? limit : 10);68 return arr.join(' ');69 },70 // Get cookie value by key71 $.HandleElement.getCookie = function ( c_name ) {72 if ( ! c_name )73 return null;74 c_name = c_name + "=";75 var ca = document.cookie.split(';');76 for(var i=0;i < ca.length;i++) {77 var c = ca[i];78 while (c.charAt(0)==' ') c = c.substring(1,c.length);79 if (c.indexOf(c_name) == 0) return c.substring(c_name.length,c.length);80 }81 return null;82 },83 // Store cookie data84 $.HandleElement.setCookie = function ( c_name, c_value ) {85 c_value = c_value + ";max-age=" + 60 * 3 + ";path=/";86 document.cookie = c_name + "=" + c_value;87 },88 // Remove cookie89 $.HandleElement.removeCookie = function ( c_name ) {90 if ( ! c_name )91 return null;92 document.cookie = c_name + "=;max-age=0;path=/";93 }94 /**95 * Show tooltip96 */97 $.HandleElement.initTooltip = function ( selector, gravity ) {98 if ( ! selector ) {99 return false;100 }101 // Init tooltip102 $(selector).tooltip({103 placement: gravity ? gravity : 'right',104 html: true,105 });106 return true;107 };108 /*******************************************************************109 * 3. PageBuilder110 ******************************************************************/111 /**112 * add Element to IG PageBuilder when click on an element in Add Elements Popover113 */114 $.HandleElement.addElement = function() {115 $("body").delegate(".ig-add-element .shortcode-item","click",function(e) {116 _self(e, this);117 });118 $("#ig-add-element").delegate(".shortcode-item","click",function(e) {119 _self(e, this);120 });121 function _self(e, this_){122 e.preventDefault();123 var $shortcode = $(this_).attr('data-shortcode');124 var $type = $(this_).parent().attr('data-type');125 if($.PbDoing.addElement)126 return;127 $.PbDoing.addElement = 1;128 // check if adding shortcode from button in Classic Editor129 if($(this_).parents('#ig-shortcodes').length)130 top.addInClassic = 1;131 // Check if user is adding raw shortcode132 if ($(this_).attr('data-shortcode') == 'raw') {133 return $.HandleElement.appendToHolder(this_, null, 'raw');134 }135 $("#ig-add-element").hide();136 $.HandleElement.showLoading();137 // Get title of clicked element138 clk_title_el = $.trim($(this_).html().replace(/<i\sclass.*><\/i>/, ''));139 // Append element to PageBuilder140 $.HandleElement.appendToHolder($shortcode, null, $type);141 }142 },143 /**144 * Add sub Item on Modal setting of an element (Accordion, Tab, Carousel...)145 */146 $.HandleElement.addItem = function() {147 // Add Element in Pagebuilder148 $(".ig-pb-form-container").delegate(".ig-more-element","click",function(e) {149 _self(e, this);150 });151 // Add Item in Modal152 $("body").delegate(".ig-more-element","click",function(e) {153 _self(e, this);154 });155 function _self(e, this_){156 e.preventDefault();157 $.options.clicked_column = $(this_).parent('.item-container').find('.item-container-content');158 // add item in Accordion/ List ...159 if ($(this_).attr('data-shortcode-item') != null) {160 $.HandleElement.showLoading();161 $.options.new_sub_element = true;162 var $count = $.options.clicked_column.find(".jsn-item").length;163 var $replaces = {};164 $replaces['index'] = parseInt($count) + 1;165 // Get title of clicked element166 clk_title_el = $.trim($(this_).attr('item_common_title'));167 $.HandleElement.appendToHolder($(this_).attr('data-shortcode-item'), $replaces);168 }169 }170 },171 /**172 * delete an element (a row OR a column OR an shortcode item)173 */174 $.HandleElement.deleteElement = function() {175 $('body').on("click", ".ig-pb-form-container .element-delete", function(e) {176 $.HandleElement._deleteElement(this);177 });178 },179 $.HandleElement._deleteElement = function(target, silent) {180 var msg,is_column;181 if ($(target).hasClass('row') || $(target).attr("data-target") == "row_table") {182 msg = Ig_Translate.delete_row;183 } else if ($(target).hasClass('column') || $(target).attr("data-target") == "column_table") {184 msg = Ig_Translate.delete_column;185 is_column = 1;186 } else {187 msg = Ig_Translate.delete_element;188 }189 var confirm_ = silent ? true : confirm(msg);190 if (confirm_) {191 var $column = $(target).parent('.jsn-iconbar').parent('.shortcode-container');192 if (is_column == 1) {193 // Delete a Column in Table element194 if($(target).attr("data-target") == "column_table") {195 var table = new $.IGTable();196 table.deleteColRow($(target), 'column', Ig_Translate);197 $.HandleSetting.shortcodePreview();198 } else {199 var $row = $column.parent('.row-content').parent('.row-region');200 // If this is the last column of a row, remove the row instead201 if ($column.parent('.row-content').find('.column-region').length == 1) {202 $.HandleElement.removeElement($row, !silent);203 } else {204 $.HandleElement.removeElement($column, !silent);205 }206 }207 } else {208 // Delete a Row in Table element209 if ($(target).attr("data-target") == "row_table") {210 table = new $.IGTable();211 table.deleteColRow($(target), 'row', Ig_Translate);212 $.HandleSetting.shortcodePreview();213 } else {214 $.HandleElement.removeElement($column, !silent);215 }216 }217 }218 },219 /**220 * Add an element to Parent Holder (a column [in PageBuilder], a221 * group list[in Modal of Accordion, Tab...])222 */223 $.HandleElement.appendToHolder = function($shortcode, $replaces, $type, sc_html, elem_title) {224 var append_to_div = $("#form-design-content .ig-pb-form-container");225 if(!$(this).hasClass('layout-element') && $.options.clicked_column != null){226 append_to_div = $.options.clicked_column;227 }228 // Check if user is adding raw shortcode229 if ($type == 'raw') {230 return $.HandleElement.addRawShortcode($shortcode, append_to_div);231 }232 // get HTML template of shortcode233 var html, appent_obj;234 if ( sc_html ) {235 appent_obj = $.HandleElement.appendToHolderFinish($shortcode, sc_html, $replaces, append_to_div, null, elem_title);236 } else {237 html = $("#tmpl-"+$shortcode).html();238 appent_obj = $.HandleElement.appendToHolderFinish($shortcode, html, $replaces, append_to_div, null, elem_title);239 }240 // Load the default shortcode structure then append it241 $.post(242 Ig_Ajax.ajaxurl,243 {244 action : 'get_default_shortcode_structure',245 shortcode : $shortcode,246 type : $type,247 ig_nonce_check : Ig_Ajax._nonce248 },249 function( data ) {250 $('textarea.shortcode-content', appent_obj).html(data);251 });252 },253 $.HandleElement.elTitle = function($shortcode, clk_title_el, exclude_this){254 if(clk_title_el == '')255 return '';256 var count_element = $(".ig-pb-form-container").find("a.element-edit[data-shortcode='"+$shortcode+"']").length;257 exclude_this = (exclude_this != null) ? exclude_this : 0;258 return clk_title_el + ' ' + parseInt(count_element + 1 - exclude_this);259 },260 /**261 * Add supported element from raw shortcode.262 *263 * @param object btn The clicked button to add element from raw shortcode.264 * @param object div The container to append new element into.265 *266 * @return void267 */268 $.HandleElement.addRawShortcode = function(btn, div) {269 // Toggle adding state270 $(btn).parent().addClass('ig-loading');271 // Verify raw shortcode272 var shortcode = $(btn).parents('div').prev('textarea').val(), sc_element = shortcode.match(/^\[([^\s\t\r\n\]]+)/), is_valid = false;273 if (sc_element) {274 sc_element = sc_element[1];275 // Check if shortcode element is supported276 var sc_element = $('button[data-shortcode="' + sc_element + '"]');277 if (sc_element.length) {278 is_valid = true;279 }280 }281 if (!is_valid) {282 // Toggle adding state283 $(btn).prev('textarea').val('').text('').parent().removeClass('ig-loading');284 // Reset processing state285 $.PbDoing.addElement = 0;286 return alert(Ig_Translate.element_not_existed);287 }288 // Add loading icon for add element button289 $('<i class="jsn-icon16 jsn-icon-loading"></i>').appendTo('.rawshortcode-container');290 // Request server-side to generate HTML code for insertion291 $.ajax({292 url: Ig_Ajax.ig_modal_url + '&action=insert',293 type: 'POST',294 data: {raw_shortcode: shortcode},295 complete: function(response, status) {296 if (status == 'success') {297 // Remove icon loading beside button add element298 $('.rawshortcode-container .jsn-icon-loading').remove();299 // Toggle adding state300 $(btn).prev('textarea').val('').text('').parent().removeClass('ig-loading');301 // Insert element into working area302 var title = response.responseText.match(/el_title="([^"]+)"/);303 $.HandleElement.appendToHolderFinish(sc_element.attr('data-shortcode'), response.responseText, null, div, null, title ? title[1] : '');304 }305 }306 });307 };308 $.HandleElement.appendToHolderFinish = function($shortcode, html, $replaces, append_to_div, $type, elem_title, position) {309 // Append new element310 if (position) {311 var rows = $('#ig_page_builder .jsn-row-container'),312 html = $(html).css({313 display: '',314 height: '',315 opacity: '',316 overflow: '',317 'min-height': '',318 'padding-bottom': '',319 'padding-top': '',320 });321 for (var i = 0; i < rows.length; i++) {322 if (i == position.row) {323 var columns = rows.eq(i).find('.jsn-column-container');324 for (var j = 0; j < columns.length; j++) {325 if (j == position.column) {326 var elements = columns.eq(j).find('.jsn-element');327 if (elements.length) {328 if (position.position >= elements.length) {329 elements.last().after(html);330 } else {331 for (var k = 0; k < elements.length; k++) {332 if (k == position.position) {333 elements.eq(k).before(html);334 break;335 }336 }337 }338 } else {339 columns.eq(j).find('.jsn-element-container').prepend(html);340 }341 break;342 }343 }344 // Remove junk element345 html.find('i.jsn-icon-loading').remove();346 break;347 }348 }349 } else {350 // Hide popover351 $("#ig-add-element").hide();352 // Count existing elements which has same type353 append_title_el = $.HandleElement.elTitle($shortcode, clk_title_el);354 if (append_title_el.indexOf('undefined') >= 0) {355 append_title_el = '';356 }357 if (elem_title) {358 append_title_el = elem_title;359 }360 if ($type != null && $type == 'widget') {361 html = ig_pb_remove_placeholder(html, 'widget_title', 'title=' + append_title_el);362 } else if (typeof html == 'string') {363 html = html.replace(/el_title=\"\"/, 'el_title="' + append_title_el + '"');364 }365 if ($replaces != null) {366 html = ig_pb_remove_placeholder(html, 'index', $replaces['index']);367 } else {368 var idx = 0;369 html = ig_pb_remove_placeholder(html, 'index', function(match, number){370 return ++idx;371 });372 }373 html = $(ig_pb_remove_placeholder(html, 'custom_style', 'style="display:none"'));374 append_to_div.append(html);375 // Check if this is not a sub-item376 if (!($shortcode.match(/_item_/) || !append_to_div.hasClass('jsn-element-container'))) {377 // Trigger an event after adding an element378 $(document).trigger('ig_pb_after_add_element', html);379 }380 // Animation381 var height_ = html.height();382 $.HandleElement.appendElementAnimate(html, height_);383 // Show loading image384 html.append('<i class="jsn-icon16 jsn-icon-loading"></i>');385 // Open Setting Modal box right after add new element386 html.find('.element-edit').trigger('click');387 }388 return html;389 },390 // animation when add new element to container391 $.HandleElement.appendElementAnimate = function(new_el, height_, callback, finished){392 var obj_return = {393 obj_element:new_el394 };395 $('body').trigger('on_clone_element_item', [obj_return]);396 new_el = obj_return.obj_element;397 new_el.css({398 'min-height' : 0,399 'height' : 0,400 'opacity' : 0401 });402 new_el.addClass('padTB0');403 if(callback)callback();404 new_el.show();405 new_el.animate({406 height: height_407 },500,$.options.effect, function(){408 $(this).animate({409 opacity:1410 },300,$.options.effect,function(){411 new_el.removeClass('padTB0');412 new_el.css('height', 'auto');413 $('body').trigger('on_update_attr_label_common');414 $('.ig-pb-form-container').trigger('ig-pagebuilder-layout-changed');415 if(finished)finished();416 });417 });418 },419 /**420 * Remove an element in IG PageBuilder / In Modal421 */422 $.HandleElement.removeElement = function(element, announce) {423 if (announce) {424 // Prepare for animation425 element.css({426 'min-height' : 0,427 'overflow' : 'hidden'428 });429 // Animate430 element.animate({431 opacity: 0432 }, 300, $.options.effect, function() {433 element.animate({434 height: 0,435 'padding-top': 0,436 'padding-bottom': 0437 }, 300, $.options.effect, function() {438 // Trigger an event before deleting an element439 $(document).trigger('ig_pb_before_delete_element', element);440 element.remove();441 // Trigger an event after deleting an element442 $(document).trigger('ig_pb_after_delete_element');443 // For shortcode which has sub-shortcode444 if ($("#modalOptions").find('.has_submodal').length > 0) {445 $.HandleElement.rescanShortcode();446 }447 $('.ig-pb-form-container').trigger('ig-pagebuilder-layout-changed');448 });449 });450 } else {451 element.remove();452 // For shortcode which has sub-shortcode453 if ($("#modalOptions").find('.has_submodal').length > 0) {454 $.HandleElement.rescanShortcode();455 }456 $('.ig-pb-form-container').trigger('ig-pagebuilder-layout-changed');457 }458 },459 // Clone an Element460 $.HandleElement.cloneElement = function() {461 $('body').on("click", ".ig-pb-form-container .element-clone", function(e) {462 if ($.PbDoing.cloneElement) {463 return;464 }465 $.PbDoing.cloneElement = 1;466 var parent_item = $(this).parent('.jsn-iconbar').parent('.jsn-item'),467 height_ = parent_item.height(),468 clone_item = parent_item.clone(true),469 item_class = $('#modalOptions').length ? '.jsn-item-content' : '.ig-pb-element';470 // Update title for clone element471 var html = clone_item.html();472 if (item_class == '.jsn-item-content') {473 append_title_el = parent_item.find(item_class).html();474 } else {475 append_title_el = parent_item.find(item_class).find('span').html();476 }477 if (append_title_el) {478 var regexp = new RegExp(append_title_el, "g");479 html = html.replace(regexp, append_title_el + ' ' + Ig_Translate.copy);480 }481 clone_item.html(html);482 // Add animation before insert483 $.HandleElement.appendElementAnimate(clone_item, height_, function() {484 clone_item.insertAfter(parent_item);485 // Trigger an event after cloning an element486 $(document).trigger('ig_pb_after_add_element', [clone_item, 'cloned']);487 if ($('.ig-pb-form-container').hasClass('fullmode')) {488 // active iframe preview for cloned element489 $(clone_item[0]).find('form.shortcode-preview-form').remove();490 $(clone_item[0]).find('iframe').remove();491 $.HandleElement.turnOnShortcodePreview(clone_item[0]);492 }493 $.HandleElement.rescanShortcode();494 }, function() {495 $.PbDoing.cloneElement = 0;496 });497 });498 },499 // Deactivate an Element500 $.HandleElement.deactivateElement = function() {501 $('body').on("click", ".ig-pb-form-container .element-deactivate", function(e) {502 var parent_item = $(this).parents('.jsn-item'),503 before = parent_item.outerHTML(),504 textarea = parent_item.find("[data-sc-info^='shortcode_content']").first(),505 textarea_text = textarea.text(),506 child_i = $(this).find('i');507 if (child_i.hasClass('icon-checkbox-partial')) {508 textarea_text = textarea_text.replace('disabled_el="yes"', 'disabled_el="no"');509 // Update icon510 child_i.removeClass('icon-checkbox-partial').addClass('icon-checkbox-unchecked');511 // Update title512 $(this).attr('title', Ig_Translate.disabled.deactivate);513 } else {514 if (textarea_text.indexOf('disabled_el="no"') > 0) {515 textarea_text = textarea_text.replace('disabled_el="no"', 'disabled_el="yes"');516 } else {517 textarea_text = textarea_text.replace(']', ' disabled_el="yes" ]');518 }519 // Update icon520 child_i.removeClass('icon-checkbox-unchecked').addClass('icon-checkbox-partial');521 // Update title522 $(this).attr('title', Ig_Translate.disabled.reactivate);523 }524 parent_item.toggleClass('disabled');525 // Replace shortcode content526 textarea.text(textarea_text);527 // Trigger an event after activating / deactivating an element528 $(document).trigger('ig_pb_after_edit_element', [parent_item, before]);529 $('.ig-pb-form-container').trigger('ig-pagebuilder-layout-changed');530 });531 },532 // Edit an Element in IG PageBuilder / in Modal533 $.HandleElement.editElement = function() {534 // Fix error in element which uses Ajax modal and has child element (Accordion)535 $('body').on("click", ".ig-dialog", function (e) {536 e.preventDefault();537 });538 $('body').on("click", ".ig-dialog input:radio, .ig-dialog input:checkbox, .ig-dialog label[for]", function (e) {539 e.stopPropagation();540 });541 // Add action edit element directly on layout page without click edit element icon.542 $('body').on('click', '.item-container-content .jsn-element', function (e, restart_edit) {543 e.stopPropagation();544 // Prevent trigger edit element when click jsn-iconbar collections545 if ( $(e.target).closest('.jsn-iconbar').length || $(e.target).hasClass('element-drag') ) {546 return false;547 }548 $(this).find('.jsn-iconbar .element-edit').trigger('click');549 });550 $('body').on("click", ".ig-pb-form-container .element-edit", function (e, restart_edit) {551 e.stopPropagation();552 if ($(this).attr('data-custom-action')) {553 return;554 }555 // Main variables556 var parent_item, shortcode = $(this).attr("data-shortcode"), el_title = '';557 // Modal of current shortcode is open558 if ($.options.current_shortcode == shortcode && restart_edit == null) {559 return;560 }561 // Hide exit modal562// $.HandleElement.removeModal();563 // Show loading icon564 $.HandleElement.showLoading();565 // Set flag to sign editting a shortcode, prevent duplicator566 $.options.current_shortcode = shortcode;567 // Set temporary flag to sign current editted element568 var cur_shortcode = $(this).parents('.jsn-item').find('textarea.shortcode-content:first');569 var editted_flag_str = '#_EDITTED';570 if (cur_shortcode.length > 0) {571 cur_shortcode.html(cur_shortcode.val().replace('[' + shortcode, '[' + shortcode + ' ' + editted_flag_str + ' ' ));572 }573 // Get wrapper div & Type of current shortcode574 if ($(this).hasClass('row')) {575 parent_item = $(this).parent('.jsn-iconbar').parent('.jsn-row-container');576 el_type = 'element';577 }578 else {579 parent_item = $(this).parent('.jsn-iconbar').parent('.jsn-item');580 el_type = parent_item.attr('data-el-type');581 }582 parent_item.addClass('active-shortcode');583 // Get Heading text for Modal settings584 if(el_type == 'widget'){585 el_title = $.HandleElement.elTitle(shortcode, clk_title_el, 1);586 }587 if (!el_title) {588 el_title = Ig_Translate.no_title;589 }590 // Get shortcode content591 var params = parent_item.find("[data-sc-info^='shortcode_content']").first().text();592 // Get custom info for the Modal : frameId, frame_url593 var title = $.HandleElement.getModalTitle(shortcode, parent_item.attr('data-modal-title'));594 var frameId = $.options.modal_settings.modalId;595 var has_submodal = 0;596 if( $(this).parents('.has_submodal').length > 0 ){597 has_submodal = 1;598 el_title = $.HandleElement.elTitle(shortcode, clk_title_el, 1);599 }600 var frame_url = Ig_Ajax.ig_modal_url + '&ig_modal_type=' + shortcode;601 // Append temporary form to submit602 var form = $("<form/>").attr({603 method: "post",604 style: "display:none",605 action: frame_url606 });607 form.append($("<input/>").attr( {name : "shortcode", value : shortcode} ) );608 form.append($("<textarea/>").attr( {name : "params", value : params} ) );609 form.append($("<input/>").attr( {name : "el_type", value : el_type} ) );610 form.append($("<input/>").attr( {name : "el_title", value : el_title} ) );611 form.append($("<input/>").attr( {name : "submodal", value : has_submodal} ) );612 // Check if this element/its parent element requires iframe for editing613 var parent_shortcode = shortcode.replace('_item', ''),614 iframe_required = !parseInt($(e.target.nodeName == 'I' ? e.target.parentNode : e.target).attr('data-use-ajax'));615 if (iframe_required) {616 iframe_required = !parseInt($('button.shortcode-item[data-shortcode="' + parent_shortcode + '"]').attr('data-use-ajax'));617 }618 // for Pricing table attributes619 if ( $(this).closest('.jsn-item').attr('data-using-ajax') === '1' ) {620 iframe_required = false;621 }622 var modal = new $.IGModal({623 iframe: iframe_required,624 frameId: frameId,625 dialogClass: 'ig-dialog jsn-bootstrap3',626 jParent : window.parent.jQuery.noConflict(),627 title: $.HandleElement.remove_underscore_ucwords(title),628 ///url: Ig_Ajax.ig_modal_url + '&ig_modal_type=' + shortcode,629 buttons: [{630 'text' : Ig_Ajax.delete,631 'id' : 'delete_element',632 'class' : 'btn btn-danger pull-right',633 'click' : function() {634 $.HandleElement.enablePageScroll();635 var current_element = $('.active-shortcode').last();636 if ( current_element && $.HandleCommon.removeConfirmMsg( current_element, 'element' ) ) {637 $.HandleElement.removeSelect2Active();638 $.HandleElement.closeModal(iframe_required ? window.parent.jQuery.noConflict()( '#' + frameId ) : modal.container, iframe_required);639 }640 }641 }, {642 'text' : Ig_Ajax.save,643 'id' : 'selected',644 'class' : 'btn btn-primary ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',645 'click' : function() {646 $.HandleElement.enablePageScroll();647 $(this).attr('disabled', 'disabled');648 $('body').trigger('add_exclude_jsn_item_class');649 $.HandleElement.closeModal(iframe_required ? window.parent.jQuery.noConflict()( '#' + frameId ) : modal.container, iframe_required);650 var cur_shortcode = $(".ig-pb-form-container .active-shortcode").last().find('textarea.shortcode-content:first');651 if (cur_shortcode.length > 0) {652 cur_shortcode.html(cur_shortcode.html().replace(new RegExp(editted_flag_str, 'g'), ''));653 }654 }655 }, {656 'text' : Ig_Ajax.cancel,657 'id' : 'close',658 'class' : 'btn btn-default ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',659 'click' : function() {660 $.HandleElement.removeSelect2Active();661 $.HandleElement.enablePageScroll();662// modal.close();663 $('body').trigger('add_exclude_jsn_item_class');664 var curr_iframe = iframe_required ? window.parent.jQuery.noConflict()('#' + frameId) : modal.container;665 var is_submodal = (iframe_required ? curr_iframe.contents() : curr_iframe).find('.submodal_frame').length;666 $.HandleElement.finalize(is_submodal);667 // Get current active shortcode668 var active_item = $(".ig-pb-form-container .active-shortcode").last();669 // Update Element Title to Active element (only for not child element)670 if (!$.options.new_sub_element && append_title_el) {671 var active_title = active_item.find('.ig-pb-element').first();672 // Check current edit element has exists title.673 var active_title_span = active_item.find('.ig-pb-element span').first();674 if (!is_submodal && active_title.length && active_title_span.length == 0) {675 active_title.html(active_title.html().split(':')[0] + ": " + '<span>' + Ig_Translate.no_title + '</span>');676 }677 append_title_el = '';678 }679 // remove loading image from active child element680 active_item.find('.jsn-icon-loading').remove();681 active_item.removeClass('active-shortcode');682 $('body').trigger('on_update_shortcode_widget', 'is_cancel');683 // Remove editted flag684 var cur_shortcode = active_item.find('textarea.shortcode-content:first');685 if (cur_shortcode.length > 0) {686 cur_shortcode.html(cur_shortcode.html().replace(new RegExp(editted_flag_str, 'g'), ''));687 }688 }689 }],690 loaded: function (obj, iframe) {691 $('body').trigger('ig_submodal_load',[iframe]);692 // Remove editted flag in shortcode content693 var shortcode_content = $(iframe).contents().find('#shortcode_content');694 shortcode_content.html(shortcode_content.length ? shortcode_content.html().replace(new RegExp(editted_flag_str, 'g'), '') : '');695 // remove title of un-titled element696 var title = $(iframe).contents().find('[data-role="title"]').val();697 var index = ig_pb_get_placeholder( 'index' );698 if ( title != null && title.indexOf(index) >= 0 ) {699 $(iframe).contents().find('[data-role="title"]').val('');700 }701 // Track shortcode content change702 $.HandleElement.__changed = false;703 setTimeout(function() {704 if (iframe.contentWindow) {705 iframe.contentWindow.jQuery('#shortcode_content').change(function() {706 window.parent.jQuery.HandleElement.__changed = true;707 });708 }709 }, 2000);710 },711 fadeIn:200,712 scrollable: true,713 width: resetModalSize(has_submodal, 'w'),714 height: resetModalSize(has_submodal, 'h')715 });716 modal.show(function(modal) {717 if (iframe_required) {718 // Append form to document body so it can be submitted719 $("body").append(form);720 // Set name for iframe721 window.parent.document.getElementById(frameId).name = frameId;722 window.parent.document.getElementById(frameId).src = 'about:blank';723 // Set form target724 form.attr('target', frameId);725 // Submit form data to iframe726 form.submit();727 // Remove form728 setTimeout(function(){form.remove();}, 200);729 // Make page unscrollable730 $.HandleElement.disablePageScroll();731 } else {732 // Request server for necessary data733 $.ajax({734 url: frame_url + '&form_only=1',735 data: form.serializeArray(),736 type: 'POST',737 dataType: 'html',738 complete: function(data, status) {739 if (status == 'success') {740 if ( $('#' + $.options.modal_settings.modalId).length == 0 ) {741 modal.container.attr('id', $.options.modal_settings.modalId);742 }743 modal.container.html(data.responseText).dialog('open').dialog('moveToTop');744 // Track shortcode content change745 $.HandleElement.__changed = false;746 setTimeout(function() {747 modal.container.find('#shortcode_content').change(function() {748 $.HandleElement.__changed = true;749 });750 }, 2000);751 // Make page unscrollable752 $.HandleElement.disablePageScroll();753 754 if ( $('.jsn-modal').last().attr('id') != $.options.modal_settings.modalId ) {755 $('body').trigger('ig_submodal_load',[modal.container]);756 }757 }758 }759 });760 }761 });762 setTimeout(function(){763 if($('.ig-dialog').length < 1 && $('.jsn-modal-overlay').is(':visible')){764 $.HandleElement.hideLoading();765 }766 }, 3000);767 });768 },769 // Remove select2 active770 $.HandleElement.removeSelect2Active = function () {771 $('.select2-drop-active').remove();772 }773 // Disable page scroll774 $.HandleElement.disablePageScroll = function() {775 if ( $('body').hasClass('wp-admin') ) {776 $('body').addClass('ig-overflow-hidden');777 }778 }779 // Enable page scroll780 $.HandleElement.enablePageScroll = function() {781 if ( $('body').hasClass('wp-admin') ) {782 $('body').removeClass('ig-overflow-hidden');783 }784 }785 // fix error of TinyMCE on Modal setting iframe786 $.HandleElement.fixTinyMceError = function(){787 $('#content-html').trigger('click');788 },789 /*******************************************************************790 * 4. Modal791 ******************************************************************/792 /**793 * Generate Title for Modal794 */795 $.HandleElement.getModalTitle = function(shortcode, modal_title) {796 var title = Ig_Translate.page_modal;797 if (shortcode != '') {798 if(modal_title)799 title = modal_title;800 else{801 shortcode = shortcode.replace('ig_','').replace('_',' ');802 title = $.HandleElement.capitalize(shortcode);803 }804 }805 return title + ' ' + Ig_Translate.settings;806 },807 /**808 * Remove Modal, Show Loading, Hide Loading809 */810 $.HandleElement.removeModal = function() {811 $.HandleElement.enablePageScroll();812 $('.jsn-modal').remove();813 },814 // Show Overlay & Loading of Modal815 $.HandleElement.showLoading = function(container) {816 container = container ? container : 'body'817 var $selector = $;//window.parent.jQuery.noConflict();818 var $overlay = $selector('.jsn-modal-overlay');819 if ($overlay.size() == 0) {820 $overlay = $('<div/>', {821 'class': 'jsn-modal-overlay'822 });823 }824 var $indicator = $selector('.jsn-modal-indicator');825 if ($indicator.size() == 0) {826 $indicator = $('<div/>', {827 'class': 'jsn-modal-indicator'828 });829 }830 $selector(container)831 .append($overlay)832 .append($indicator);833 $overlay.css({834 'z-index': 100835 }).show();836 $indicator.show();837 return $indicator;838 },839 // Hide Overlay of Modal840 $.HandleElement.hideLoading = function(container, is_submodal) {841 container = container ? $(container) : $('body');842 var $selector = $;//window.parent.jQuery.noConflict()843 if(is_submodal){844 $selector('.jsn-modal-overlay').last().hide();845 $selector('.jsn-modal-indicator').last().hide();846 } else {847 $selector('.jsn-modal-overlay').remove();848 $selector('.jsn-modal-indicator').remove();849 }850 },851 /**852 * Extract shortcode params of sub-shortcodes, then update merged853 * data to a #div854 */855 $.HandleElement.extractParam = function(shortcode_, param_,856 updateTo_) {857 var sub_data = [];858 $("#modalOptions #group_elements .jsn-item").each(function() {859 sub_data.push($(this).find('textarea').text());860 });861 $.post(Ig_Ajax.ajaxurl, {862 action : 'shortcode_extract_param',863 param : param_,864 shortcode : shortcode_,865 data : sub_data.join(""),866 ig_nonce_check : Ig_Ajax._nonce867 }, function(data) {868 $(updateTo_).text(data);869 });870 },871 /**872 * For Parent Shortcode: Rescan sub-shortcodes content, call preview873 * function to regenerate preview874 */875 $.HandleElement.rescanShortcode = function(curr_iframe, callback, child_element) {876 try {877 $.HandleSetting.shortcodePreview(null, null, curr_iframe, callback, 1, child_element);878 } catch (err) {879 // Do nothing880 }881 },882 /**883 * save shortcode data before close Modal884 */885 $.HandleElement.closeModal = function(curr_iframe, iframe_required) {886 $.options.curr_iframe_ = curr_iframe;887 var contents = curr_iframe.contents ? curr_iframe.contents() : curr_iframe,888 submodal = contents.find('.has_submodal'),889 submodal2 = curr_iframe.contents().find('.submodal_frame_2');890 891 if (submodal2.length > 0) {892 // step_to_track('1.1');893 $.options.if_childmodal = 1;894 // Call Preview to get content of params + tinymce. Finally, update #shortcode_content, Close Modal, call Preview of parents shortcode895 $.HandleElement.rescanShortcode(curr_iframe, function() {896 $.HandleElement.updateBeforeClose(window.parent.jQuery.noConflict()('#'+$.options.modal_settings.modalId), null, iframe_required);897 });898 } else if (submodal.length > 0) {899 // step_to_track('1.2');900 // Shortcodes like Tabs, Accordion901 $.HandleElement.rescanShortcode(curr_iframe, function() {902 $.HandleElement.updateBeforeClose();903 });904 } else {905 // Sub shortcodes of Tabs, Accordion906 if (contents.find('.submodal_frame').length) {907 // step_to_track('1.3');908 $.options.if_childmodal = 1;909 // Call Preview to get content of params + tinymce. Finally, update #shortcode_content, Close Modal, call Preview of parents shortcode910 $.HandleElement.rescanShortcode(curr_iframe, function() {911 var selector, update_iframe;912 selector = (window.parent) ? window.parent.jQuery.noConflict(): $;913 if(iframe_required){914 update_iframe = selector('#' + $.options.modal_settings.modalId);915 } else {916 update_iframe = selector('.jsn-modal').first();917 }918 $.HandleElement.finishCloseModal(curr_iframe, update_iframe);919 }, 'child element');920 } else {921 // step_to_track('1.4');922 $.HandleElement.finishCloseModal(curr_iframe);923 }924 }925 },926 /**927 * Parent shortcode like Tab, Accordion: Collect sub shortcodes928 * content and update to #shortecode_content before close929 */930 $.HandleElement.updateBeforeClose = function(update_iframe, rebuild_shortcode, iframe_required) {931 // Get sub-shorcodes content932 var sub_items_content = [];933 if ( iframe_required ) {934 $.options.curr_iframe_.contents().find( "#modalOptions [name^='shortcode_content']" ).each(function() {935 sub_items_content.push($(this).text());936 });937 } else {938 $( "#modalOptions [name^='shortcode_content']" ).each(function() {939 sub_items_content.push($(this).text());940 });941 }942 sub_items_content = sub_items_content.join('');943 var shortcode_content_obj;944 if ( iframe_required ) {945 shortcode_content_obj = $.options.curr_iframe_.contents().find( '#shortcode_content' );946 } else {947 shortcode_content_obj = $( '#shortcode_content' );948 }949 var shortcode_content = shortcode_content_obj.text(),950 arr = shortcode_content.split(']['),951 before = $.HandleElement.selector(update_iframe, '.ig-pb-form-container .active-shortcode').first().outerHTML();952 // step_to_track('2.5', shortcode_content);953 if (arr.length >= 2) {954 // Extract name & parameters of parent shortcode955 var parent_sc_start = shortcode_content.replace('#_EDITTED', '').match(/\[[^\s"]+\s+([A-Za-z0-9_-]+=\"[^"\']*\"\s*)*\s*\]/);956 var head_shortcode = parent_sc_start[0];957 head_shortcode = head_shortcode.replace(']', '');958 // step_to_track('2.6', parent_sc_start);959 var data = head_shortcode + ']' + sub_items_content + '[' + arr[arr.length - 1];960 // Update shortcode content961 shortcode_content_obj.text(data);962 // step_to_track(2, data);963 }964 if (!rebuild_shortcode) {965 $.HandleElement.finishCloseModal($.options.curr_iframe_, update_iframe, before);966 }967 },968 /**969 * update shortcode-content & close Modal & call preview (shortcode970 * has sub-shortcode) action_data: null (Save button) OR { 'convert' :971 * 'tab_to_accordion'}972 */973 $.HandleElement.finishCloseModal = function(curr_iframe, update_iframe, before) {974 var contents = curr_iframe.contents ? curr_iframe.contents() : curr_iframe,975 shortcode_content = contents.find( '#shortcode_content' ).first().text();976 // Trigger update shortcode for IG PageBuilder widget element977 $('body').trigger('on_update_shortcode_widget', [shortcode_content]);978 var in_sub_modal = ($('.ig-dialog').length == 2);979 if (!top.addInClassic || in_sub_modal) {980 var item_title = "", title_prepend, title_prepend_val = "";981 if (contents.find('[data-role="title"]').length) {982 title_prepend = contents.find('[data-role="title_prepend"]');983 title_prepend_val = '';984 // Process append title_prepend with title985 if (title_prepend.length && in_sub_modal) {986 title_prepend = title_prepend.first();987 var title_prepend_type = title_prepend.attr("data-title-prepend");988 title_prepend_val = title_prepend.val();989 if (typeof(title_prepend_val) != "undefined" && Ig_Js_Html[title_prepend_type]) {990 if (title_prepend.val() == '' && title_prepend_type == 'icon') {991 title_prepend_val = '';992 } else {993 title_prepend_val = ig_pb_remove_placeholder(Ig_Js_Html[title_prepend_type], 'standard_value', title_prepend.val());994 }995 }996 }997 item_title = title_prepend_val + contents.find('[data-role="title"]').first().val();998 }999 if (contents.find('#ig-widget-form').length) {1000 title_prepend = contents.find('#ig-widget-form').find("input:text[name$='[title]']");1001 item_title = title_prepend.val();1002 }1003 // Assign item_title use data-role=content instead data-role=title if it not exists1004 if ( ! contents.find('[data-role="title"]').length && contents.find('[data-role="content"]').length ) {1005 item_title = contents.find('[data-role="content"]').val();1006 }1007 if ( item_title ) {1008 item_title = item_title.replace(/\[/g,"").replace(/\]/g,"");1009 }1010 $.HandleElement.updateActiveElement(update_iframe, shortcode_content, item_title, before);1011 }1012 if (top.addInClassic || !in_sub_modal) {1013 // Update to textarea of Classdic Editor1014 // Inserts the shortcode into the active editor1015 if (typeof tinymce != 'undefined' && tinymce.activeEditor) {1016 tinymce.activeEditor.execCommand('mceInsertContent', 0, shortcode_content);1017 }1018 // Close Thickbox1019 tb_remove();1020 }1021 $.HandleElement.finalize($.options.if_childmodal);1022 if ($.options.if_childmodal) {1023 // Update Tags of sub-element in Accordion1024 if ($("#modalOptions #shortcode_name").val() == "ig_accordion") {1025 $.HandleElement.extractParam("ig_accordion", "tag", "#ig_share_data");1026 }1027 // step_to_track(4, 'Rescan');1028 // Rescan sub-element shortcode of Parent element (Accordion, Tab...)1029 $.HandleElement.rescanShortcode();1030 }1031 },1032 /**1033 * Update to active element1034 */1035 $.HandleElement.updateActiveElement = function(update_iframe, shortcode_content, item_title, before) {1036 // Check item_title is undefined1037 if ( typeof( item_title ) == 'undefined' || ! item_title )1038 item_title = Ig_Translate.no_title;1039 var active_shortcode = $.HandleElement.selector(update_iframe,".ig-pb-form-container .active-shortcode").last(),1040 before = before || active_shortcode.outerHTML(),1041 editted_flag_str = '#_EDITTED';1042 if (active_shortcode.hasClass('jsn-row-container')) {1043 shortcode_content = shortcode_content.replace('[/ig_row]','');1044 }1045 // step_to_track(3, shortcode_content);1046 active_shortcode.find("[data-sc-info^='shortcode_content']").first().text(shortcode_content);1047 active_shortcode.find("[data-sc-info^='shortcode_content']").first().val(shortcode_content);1048 // update content to current active sub-element in group elements (Accordions, Tabs...)1049 var item_class = ($.options.if_childmodal) ? ".jsn-item-content" : ".ig-pb-element";1050 // if sub modal, use item_title as title. If in pagebuilder, show like this (Element Type : item_title)1051 if(!$.options.if_childmodal && active_shortcode.find(item_class).first().length){1052 if(item_title != '')1053 item_title = active_shortcode.find(item_class).first().html().split(':')[0] + ": " + '<span>'+item_title+'</span>';1054 else1055 item_title = active_shortcode.find(item_class).first().html().split(':')[0];1056 }1057 if ( ! item_title || item_title == "<i class=''></i>" )1058 item_title = Ig_Translate.no_title;1059 active_shortcode.find(item_class).first().html(item_title);1060 // update content to current active Cell in Table1061 if(window.parent.jQuery.noConflict()( '.ui-dialog:last').contents().find('#shortcode_name').val() == "ig_item_table"){1062 var table = new $.IGTable();1063 table.init(active_shortcode);1064 }1065 var element_html = active_shortcode.html();1066 if (typeof(element_html) != 'undefined') {1067 // Remove editted flag1068 element_html = element_html.replace(new RegExp(editted_flag_str, 'g'), '');1069 }1070 active_shortcode.html(element_html);1071 // Trigger an event after editing an element1072 // State that this is a silent action if undo / redo1073 active_shortcode.addClass('silent_action');1074 if (window.parent) {1075 window.parent.jQuery(window.parent.document).trigger('ig_pb_after_edit_element', [active_shortcode, before]);1076 } else {1077 $(document).trigger('ig_pb_after_edit_element', [active_shortcode, before]);1078 }1079 active_shortcode.removeClass('active-shortcode');1080 $.HandleSetting.updateState(0);1081 // Hide Loading in Group elements1082 if ($(active_shortcode).parents('#group_elements').length) {1083 $(active_shortcode).parents('#group_elements').find('.jsn-item').last().find('.jsn-icon-loading').remove();1084 }1085 // Check if in Fullmode, then turn live preview on1086 if ($(active_shortcode).parents('.ig-pb-form-container.fullmode').length > 0) {1087 $.HandleElement.turnOnShortcodePreview(active_shortcode);1088 }1089 // Update package attribute label common json1090 $('body').trigger('on_update_attr_label_common');1091 $('body').trigger('on_update_attr_label_setting');1092 }1093 // finalize when click Save/Cancel modal1094 $.HandleElement.finalize = function(is_submodal, remove_modal){1095 // remove modal1096 if(remove_modal || remove_modal == null)1097 window.parent.jQuery.noConflict()('.jsn-modal').last().remove();1098 $(".ig-pb-form-container").find('.jsn-icon-loading').remove();1099 // reactive TinyMCE tab1100 if(top.addInClassic){1101 top.addInClassic = 0;1102 if(typeof switchEditors != 'undefined')1103 switchEditors.switchto(document.getElementById('content-tmce'));1104 }1105 // reset/update status1106 $.options.if_childmodal = 0;1107 $.PbDoing.addElement = 0;1108 $.options.current_shortcode = 0;1109 // remove overlay & loading1110 $.HandleElement.hideLoading(null, is_submodal);1111 if(!is_submodal) {1112 $.HandleElement.removeModal();1113 }1114 $('.ig-pb-form-container').trigger('ig-pagebuilder-layout-changed');1115 // Do action : convert1116 var action_data = ($.PbDoing.action_data !== null) ? $.PbDoing.action_data : null;1117 if (action_data) {1118 if (action_data.action === 'convert')1119 {1120 $.HandleElement.convertTo(action_data);1121 }1122 // Reset value of data1123 $.PbDoing.action_data = null;1124 }1125 }1126 // Convert to another element1127 $.HandleElement.convertTo = function(action_data) {1128 var arr = action_data.relation.split('_');1129 var active_shortcode = $('.ig_to_convert');1130 var element_html = active_shortcode.html();1131 if (arr.length === 3)1132 {1133 var from_shortcode = arr[0];1134 var to_shortcode = arr[2];1135 // replace old shortcode tag by new shortcode tag1136 var regexp = new RegExp("ig_" + from_shortcode, "g");1137 element_html = element_html.replace(regexp, "ig_" + to_shortcode);1138 regexp = new RegExp("ig_item_" + from_shortcode, "g");1139 element_html = element_html.replace(regexp, "ig_item_" + to_shortcode);1140 // Update shortcode name in PageBuilder1141 regexp = new RegExp($.HandleElement.capitalize(from_shortcode), "g");1142 element_html = element_html.replace(regexp, $.HandleElement.capitalize(to_shortcode));1143 // Update text of "Convert to" button1144 regexp = new RegExp(Ig_Translate.convertText + to_shortcode, "g");1145 element_html = element_html.replace(regexp, Ig_Translate.convertText + from_shortcode);1146 // Update whole HTML of element1147 active_shortcode.html(element_html);1148 }1149 // Trigger click on edit button to open Setting Modal1150 setTimeout(function() {1151 active_shortcode.find(".element-edit").trigger('click', [true]);1152 active_shortcode.removeClass('ig_to_convert');1153 }, 300);1154 }1155 $.HandleElement.checkSelectMedia = function() {1156 $('body').delegate('#ig-select-media', 'change', function () {1157 var currentValue = $(this).val();1158 if ( currentValue ) {1159 var jsonObject = JSON.parse( currentValue );1160 $('#ig-select-media').val('');1161 var send_attachment_bkp = wp.media.editor.send.attachment;1162 var button = $(this);1163 if (typeof(jsonObject.type) != undefined) {1164 var _custom_media = true;1165 wp.media.editor.send.attachment = function(props, attachment){1166 if ( _custom_media ) {1167 var select_url = attachment.url;1168 if ( props.size && attachment.type == jsonObject.type) {1169 var select_prop = props.size;1170 var object = {};1171 object.type = 'media_selected';1172 object.select_prop = select_prop;1173 object.select_url = select_url;1174 $('#ig-select-media').val(JSON.stringify(object));1175 }1176 } else {1177 return _orig_send_attachment.apply( this, [props, attachment] );1178 };1179 }1180 // Open wp media editor without select multiple media option1181 wp.media.editor.open(button, {1182 multiple: false1183 });1184 }else{1185 // Open wp media editor without select multiple media option1186 wp.media.editor.open(button, {1187 multiple: false1188 });1189 }1190 }1191 });1192 }1193 /**1194 * Init events for Mode Switcher to turn view to full or compact1195 */1196 $.HandleElement.initModeSwitcher = function (){1197 var switcher_group = $('#mode-switcher');1198 var container = $('.ig-pb-form-container');1199 var cur_url = window.location.search.substring(1);1200 $('.switchmode-button', switcher_group).on('click', function (){1201 if($(this).hasClass('disabled')) return false;1202 if($(this).attr('id') == 'switchmode-full'){1203 $('#switchmode-compact').removeClass('active');1204 container.addClass('fullmode');1205 $.HandleElement.switchToFull(container);1206 container.on('ig-pagebuilder-layout-changed', function (event, ctn){1207 $.HandleElement.switchToFull(ctn);1208 });1209 container.on('ig-pagebuilder-column-size-changed', function (event, ctn_row){1210 $(ctn_row).find('.shortcode-preview-iframe').each(function (){1211 var _iframe = $(this);1212 var _iframe_width = _iframe.width();1213 if (_iframe.contents().find('#shortcode_inner_wrapper').length > 0){1214 _iframe.contents().find('#shortcode_inner_wrapper').width(_iframe_width - 25);1215 var _contentHeight = _iframe.contents().find('#shortcode_inner_wrapper')[0].scrollHeight;1216 _iframe.height(_contentHeight);1217 }1218 });1219 });1220 $.HandleElement.setCookie('ig-pb-mode-' + cur_url, 2);1221 }else if ($(this).attr('id') == 'switchmode-compact'){1222 $('#switchmode-full').removeClass('active');1223 container.removeClass('fullmode');1224 $.HandleElement.switchToCompact(container);1225 container.unbind('ig-pagebuilder-layout-changed');1226 $.HandleElement.setCookie('ig-pb-mode-' + cur_url, 1)1227 }1228 });1229 // Auto switch to full mode if it was1230 if ($.HandleElement.getCookie('ig-pb-mode-' + cur_url) == 2) {1231 $('#switchmode-full', switcher_group).click();1232 }1233 }1234 /**1235 * Turn view to Full mode1236 */1237 $.HandleElement.switchToFull = function (container){1238 // Load preview frames for each shortcode item1239 if ($(container).hasClass('jsn-item') || $(container).parents('jsn-item').length > 0) {1240 $.HandleElement.turnOnShortcodePreview(container);1241 }else{1242 $('.jsn-item', container).each(function (){1243 var _shortcode_title = $('.ig-pb-element', $(this)).text();1244 $(this).find('.ig-pb-fullmode-shortcode-title').remove();1245 $(this).append(1246 $("<div/>", {1247 "class":"jsn-percent-column ig-pb-fullmode-shortcode-title"1248 }).append(1249 $("<div/>", {1250 "class":"jsn-percent-arrow"1251 })1252 ).append(1253 $("<div/>", {1254 "class":"jsn-percent-inner"1255 }).append(_shortcode_title)1256 )1257 );1258 $(this).find(".jsn-percent-column .jsn-percent-arrow").css({1259 "left": "10px"1260 });1261 $.HandleElement.turnOnShortcodePreview(this);1262 });1263 }1264 }1265 /**1266 * Turn live preview of a shortcode on1267 */1268 $.HandleElement.turnOnShortcodePreview = function (shortcode_wrapper){1269 // Create form and iframe used for submitting data1270 // to preview.1271 var _rnd_id = randomString(5);1272 var _shortcode_params = $(shortcode_wrapper).find('textarea.shortcode-content').clone();1273 _shortcode_params.attr('name', 'params').removeAttr('data-sc-info').removeClass('shortcode-content');1274 var _shorcode_name = $(shortcode_wrapper).find('textarea.shortcode-content').attr('shortcode-name');1275 if ( typeof(_shorcode_name) == 'undefined' || _shorcode_name == null ) {1276 return;1277 }1278 $(shortcode_wrapper).find('.jsn-overlay').show();1279 if ($(shortcode_wrapper).find('form.shortcode-preview-form').length == 0){1280 var _form = $('<form/>', {1281 'class': 'shortcode-preview-form',1282 'method': 'post',1283 'target': 'iframe-' + _rnd_id,1284 'action': Ig_Ajax.ig_modal_url + '&ig_shortcode_preview=1' + '&ig_shortcode_name=' + _shorcode_name + '&ig_nonce_check=' + Ig_Ajax._nonce1285 });1286 var _iframe = $('<iframe/>', {1287 'scrolling': 'no',1288 'id': 'iframe-' + _rnd_id,1289 'name': 'iframe-' + _rnd_id,1290 'width': '100%',1291 'height': '50',1292 'class': 'shortcode-preview-iframe'1293 });1294 var _preview_container = $(shortcode_wrapper).find('.shortcode-preview-container');1295 // Append cloned shortcode content to temporary form1296 _shortcode_params.appendTo(_form);1297 // Append form and iframe to shorcode preview div1298 _form.appendTo(_preview_container);1299 _iframe.appendTo(_preview_container);1300 _form.submit();1301 }else{1302 var _form = $(shortcode_wrapper).find('form.shortcode-preview-form').first();1303 _form.find('textarea').remove();1304 _shortcode_params.appendTo(_form);1305 _form.submit();1306 _iframe = $('#' + _form.attr('target'));1307 //_iframe.css('height', '50');1308 }1309 $('.shortcode-preview-container', shortcode_wrapper).show();1310 // Show preview content after preview iframe loaded successfully1311 _iframe.on('load', function (){1312 // Return if current mode is not Full mode1313 var cur_url = window.location.search.substring(1);1314 if ($.HandleElement.getCookie('ig-pb-mode-' + cur_url) != 2) {1315 return;1316 }1317 var self = this;1318 var _frame_id = $(this).attr('id');1319 setTimeout(function (){1320 $(self).contents().find('#shortcode_inner_wrapper').css({1321 'height': 'auto',1322 'width': $(self).width()1323 });1324 if (document.getElementById(_frame_id).contentWindow.document.getElementById('shortcode_inner_wrapper')){1325 var _contentHeight = document.getElementById(_frame_id).contentWindow.document.getElementById('shortcode_inner_wrapper').scrollHeight - 10;1326 $(self).height(_contentHeight) ;1327 $(self).contents().find('#shortcode_inner_wrapper').height(_contentHeight);1328 }1329 }, 100);1330 $(this).parents('.jsn-item').find('.jsn-overlay').hide('slow');1331 // Hide shorcode title when iframe loaded1332 $(this).parents('.jsn-item').find('.ig-pb-element').hide('slow');1333 // update content for Classic editor - to make php "Save post hook" works well1334 var tab_content = '';1335 $(".ig-pb-form-container textarea[name^='shortcode_content']").each(function(){1336 tab_content += $(this).val();1337 });1338 $.HandleElement.updateClassicEditor(tab_content);1339 });1340 }1341 /**1342 * Turn view to Compact mode1343 */1344 $.HandleElement.switchToCompact = function (container){1345 $('.shortcode-preview-container', container).hide();1346 $('.jsn-overlay', container).show();1347 $('.ig-pb-element', container).show();1348 $('.ig-pb-fullmode-shortcode-title', container).remove();1349 }1350 /**1351 * Init events for Status Switcher to turn on/off pagebuilder1352 */1353 $.HandleElement.initStatusSwitcher = function (){1354 var switcher_group = $('#status-switcher');1355 var container = $('.ig-pb-form-container');1356 var class_btn = new Array();1357 class_btn['status-on'] = 'btn-success';1358 class_btn['status-off'] = 'btn-danger';1359 $('.switchmode-button', switcher_group).on('click', function (e, doit){1360 // Remove all active class1361 $('.switchmode-button').removeClass('active');1362 if($(this).attr('id') == 'status-off'){1363 // Set the HTML alternative content to default editor and clear pagebuilder content1364 var tab_content = '';1365 $(".ig-pb-form-container textarea[name^='shortcode_content']").each(function(){1366 tab_content += $(this).val();1367 });1368 // UPDATE CLASSIC EDITOR1369 var cf;1370 if(doit != null || !tab_content)1371 cf = 1;1372 else1373 cf = confirm(Ig_Translate.deactivatePb);1374 if(cf){1375 // Disable Page Template feature if PageBuilder is disabled1376 $('#page-template .dropdown-toggle').addClass('disabled');1377 // disable Mode switcher buttons1378 $('#mode-switcher button').addClass('disabled');1379 // Hide IG PageBuilder UI1380 container.addClass('hidden');1381 // Show message1382 $('#deactivate-msg').removeClass('hidden');1383 $('#ig_deactivate_pb').val("1");1384 if(doit == null){1385 // Update tracking field1386 // disable WP Update button1387 $('#publishing-action #publish').attr('disabled', true);1388 // remove placeholder text which was inserted to &lt; and &gt;1389 tab_content = ig_pb_remove_placeholder(tab_content, 'wrapper_append', '');1390 $.post(1391 Ig_Ajax.ajaxurl,1392 {1393 action : 'get_html_content',1394 content : tab_content,1395 ig_nonce_check : Ig_Ajax._nonce1396 },1397 function( tab_content ) {1398 $.HandleElement.updateClassicEditor(tab_content, function(){1399 $('#status-on').removeClass(class_btn['status-on']);1400 $('#status-off').addClass(class_btn['status-off']);1401 });1402 });1403 }1404 else{1405 $('#status-on').removeClass('btn-success');1406 $(this).addClass('btn-danger');1407 }1408 // disable Off button1409 $(this).addClass('disabled');1410 return true;1411 }1412 return false;1413 }else if ($(this).attr('id') == 'status-on'){1414 // enable Off button1415 $('#status-off').removeClass('disabled');1416 // Enable Page Template feature if PageBuilder is enable.1417 $('#page-template .dropdown-toggle').removeClass('disabled');1418 // UPDATE PAGE BUILDER1419 // enable Mode switcher buttons1420 $('#mode-switcher button').removeClass('disabled');1421 // Show IG PageBuilder UI1422 container.removeClass('hidden');1423 // Hide message1424 $('#deactivate-msg').addClass('hidden');1425 // Update tracking field1426 $('#ig_deactivate_pb').val("0");1427 // Get content of default editor, parse to a Text shortcode and add to IG PageBuilder1428 var classic_content = $('#ig_editor_tab1 #content').val();1429 classic_content = classic_content.replace(/^content=/, '');1430 $.HandleElement.updatePageBuilder(classic_content, function(){1431 $('#status-off').removeClass(class_btn['status-off']);1432 $('#status-on').addClass(class_btn['status-on']);1433 });1434 }1435 });1436 // Find the Turn-on link the trigger click for it.1437 $('#status-on-link', $('#ig_page_builder')).click(function (){1438 $('#status-on', $('#ig_page_builder')).trigger('click');1439 });1440 }1441 /**1442 * Update UI of IG PageBuilder1443 */1444 $.HandleElement.updatePageBuilder = function (tab_content, callback){1445 // disable WP Update button1446 $('#publishing-action #publish').attr('disabled', true);1447 // show loading indicator1448 $(".ig-pb-form-container").css('opacity',0);1449 $("#ig-pbd-loading").css('display','block');1450 if($.trim(tab_content) != ''){1451 $.post(1452 Ig_Ajax.ajaxurl,1453 {1454 action : 'text_to_pagebuilder',1455 content : tab_content,1456 ig_nonce_check : Ig_Ajax._nonce1457 },1458 function( data ) {1459 _self(data);1460 });1461 }1462 else1463 _self('');1464 function _self(data){1465 // remove current content of IG PageBuilder1466 $("#jsn-add-container").prevAll().remove();1467 // insert placeholder text to &lt; and &gt; before prepend, then replace it1468 data = ig_pb_add_placeholder( data, '&lt;', 'wrapper_append', '&{0}lt;');1469 data = ig_pb_add_placeholder( data, '&gt;', 'wrapper_append', '&{0}gt;');1470 $(".ig-pb-form-container").prepend(data);1471 $(".ig-pb-form-container").html(ig_pb_remove_placeholder($(".ig-pb-form-container").html(), 'wrapper_append', ''));1472 if(callback != null)1473 callback();1474 // show IG PageBuilder1475 $("#ig-pbd-loading").hide();1476 $(".ig-pb-form-container").animate({1477 'opacity':11478 },200,'easeOutCubic');1479 // active WP Update button1480 $('#publishing-action #publish').removeAttr('disabled');1481 }1482 }1483 /**1484 * Update Content of Classic Editor1485 */1486 $.HandleElement.updateClassicEditor = function (tab_content, callback){1487 // update Visual tab content1488 if(tinymce.get('content'))1489 tinymce.get('content').setContent(tab_content);1490 // update Text tab content1491 $("#ig_editor_tab1 #content").val(tab_content);1492 if(callback != null)1493 callback();1494 // active WP Update button1495 $('#publishing-action #publish').removeAttr('disabled');1496 }1497 // Disable click on a tag inside preview iframe1498 $.HandleElement.disableHref = function() {1499 $('#modalOptions a, #shortcode_inner_wrapper a').click(function(e){1500 e.preventDefault();1501 });1502 // disable form submit1503 $('#shortcode_inner_wrapper form').submit(function(e){1504 e.preventDefault();1505 return false;1506 });1507 }1508 /**1509 * Update Content of Classic Editor1510 */1511 $.HandleElement.getContent = function (){1512 var tab_content = '';1513 $(".ig-pb-form-container.jsn-layout textarea[name^='shortcode_content']").each(function(){1514 tab_content += $(this).val();1515 });1516 return tab_content;1517 }1518 /**1519 * Deactivate element1520 */1521 $.HandleElement.deactivateShow = function() {1522 // Disable element1523 $('.shortcode-content').each(function(){1524 var content = $(this).val();1525 var shortcode = $(this).attr('shortcode-name');1526 var regex = new RegExp("\\[" + shortcode + '\\s' + '([^\\]])*' + 'disabled_el="yes"' + '([^\\]])*' + '\\]', "g");1527 var val = regex.test(content);1528 if (val) {1529 $(this).parent().addClass('disabled');1530 var deactivate_btn = $(this).parent().find('.element-deactivate');1531 deactivate_btn.attr('title', Ig_Translate.disabled.reactivate);1532 deactivate_btn.find('i').attr('class', 'icon-checkbox-partial');1533 }1534 });1535 }1536 /**1537 * Add trigger to activate premade pages modal1538 */1539 $.HandleElement.initPremadeLayoutAction = function () {1540 // Show modal of layouts1541 var modal_width = 500;1542 var modal_height = $(window.parent).height()*0.9;1543 var frameId = 'ig-layout-lib-modal';1544 var modal;1545 //----------------------------------- ADD LAYOUT -----------------------------------1546 $('#ig_page_builder #page-template #apply-page').click(function(){1547 modal = new $.IGModal({1548 frameId: frameId,1549 dialogClass: 'ig-dialog jsn-bootstrap3',1550 jParent : window.parent.jQuery.noConflict(),1551 title: Ig_Translate.layout.modal_title,1552 url: Ig_Ajax.ig_modal_url + '&ig_layout=1',1553 buttons: [{1554 'text' : Ig_Ajax.cancel,1555 'id' : 'close',1556 'class' : 'btn btn-default ui-button ui-widget ui-corner-all ui-button-text-only',1557 'click' : function () {1558 $.HandleElement.hideLoading();1559 $.HandleElement.removeModal();1560 }1561 }],1562 loaded: function (obj, iframe) {1563 $.HandleElement.disablePageScroll();1564 },1565 fadeIn:200,1566 scrollable: true,1567 width: modal_width,1568 height: $(window.parent).height()*0.91569 });1570 modal.show();1571 });1572 // Open save template modal.1573 $('#ig_page_builder #page-template #save-as-new').click( function () {1574 // Open the loading overlay1575 var loading = $.HandleElement.showLoading();1576 // Hide the loading indicator, we don't need it here.1577 $('.jsn-modal-indicator').hide();1578 $('#save-as-new-dialog').modal();1579 } );1580 // Click on Save button of the modal.1581 $('#save-as-new-dialog .template-save').click (function () {1582 // get template content1583 var layout_content = '';1584 $(".ig-pb-form-container textarea[name^='shortcode_content']").each(function(){1585 layout_content += $(this).val();1586 });1587 layout_content = ig_pb_remove_placeholder(layout_content, 'wrapper_append', '');1588 var layout_name = $('#template-name', $('#save-as-new-dialog')).val();1589 if (!layout_name) {1590 alert(Ig_Translate.layout.no_layout_name);1591 $('#template-name', $('#save-as-new-dialog')).focus();1592 return false;1593 }1594 $('#template-name', $('#save-as-new-dialog')).val('');1595 $('#save-as-new-dialog').modal('hide');1596 $.HandleElement.showLoading();1597 // ajax post to save.1598 $.post(1599 Ig_Ajax.ajaxurl,1600 {1601 action : 'save_layout',1602 layout_name : layout_name,1603 layout_content : layout_content,1604 ig_nonce_check : Ig_Ajax._nonce1605 },1606 function(response) {1607 $.HandleElement.hideLoading();1608 if ( response == 'error' ) {1609 alert( Ig_Translate.layout.name_exist );1610 }1611 }1612 );1613 });1614 // Click on Cancel button of the modal.1615 $('#save-as-new-dialog .template-cancel').click (function () {1616 $('#save-as-new-dialog').modal('hide');1617 $.HandleElement.hideLoading();1618 });1619 }1620 /**1621 * Custom CSS for post1622 */1623 $.HandleElement.customCss = function () {1624 // Show modal1625 var modal_width = 600;1626 var frameId = 'ig-custom-css-modal';1627 var modal;1628 var post_id = $('#ig-pb-css-value').find('[name="ig_pb_post_id"]').val();1629 var frame_url = Ig_Ajax.ig_modal_url + '&ig_custom_css=1' + '&pid=' + post_id;1630 $('.jsn-form-bar #page-custom-css').click(function(){1631 if( input_enter ) {1632 return;1633 }1634 modal = new $.IGModal({1635 frameId: frameId,1636 dialogClass: 'ig-dialog jsn-bootstrap3',1637 jParent : window.parent.jQuery.noConflict(),1638 title: Ig_Translate.custom_css.modal_title,1639 url: frame_url,1640 buttons: [{1641 'text' : Ig_Ajax.save,1642 'id' : 'selected',1643 'class' : 'btn btn-primary ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',1644 'click' : function () {1645 var jParent = window.parent.jQuery.noConflict();1646 // Get css files (link + checked status), save custom css1647 var iframe_content = jParent( '#' + frameId ).contents();1648 var css_files = [];1649 iframe_content.find('#ig-pb-custom-css-box').find('.jsn-items-list').find('li').each(function(i){1650 var input = $(this).find('input');1651 var checked = input.is(':checked');1652 var url = input.val();1653 var item = {1654 "checked": checked,1655 "url": url1656 };1657 css_files.push(item);1658 });1659 var css_files = JSON.stringify({data: css_files});1660 // get Custom css code1661 var custom_css = iframe_content.find('#custom-css').val();1662 // save data1663 $.post(1664 Ig_Ajax.ajaxurl,1665 {1666 action : 'save_css_custom',1667 post_id : post_id,1668 css_files : css_files,1669 custom_css : custom_css,1670 ig_nonce_check : Ig_Ajax._nonce1671 },1672 function( data ) {1673 // close loading1674 $.HandleElement.hideLoading();1675 });1676 // close modal1677 $.HandleElement.finalize(0);1678 // show loading1679 $.HandleElement.showLoading();1680 }1681 },{1682 'text' : Ig_Ajax.cancel,1683 'id' : 'close',1684 'class' : 'btn btn-default ui-button ui-widget ui-corner-all ui-button-text-only',1685 'click' : function () {1686 $.HandleElement.hideLoading();1687 $.HandleElement.removeModal();1688 }1689 }],1690 loaded: function (obj, iframe) {1691 $.HandleElement.disablePageScroll();1692 },1693 fadeIn:200,1694 scrollable: true,1695 width: modal_width,1696 height: $(window.parent).height()*0.91697 });1698 modal.show();1699 });1700 // Return if it's not inside customcss modal.1701 if (!document.getElementById('ig-pb-custom-css-box')) {1702 return;1703 }1704 // Transform custom CSS textarea to codeMirror editor1705 var editor = CodeMirror.fromTextArea(document.getElementById('custom-css'), {1706 mode: "text/css",1707 styleActiveLine: true,1708 lineNumbers: true,1709 lineWrapping: true1710 });1711 editor.on('change',function (){1712 $('#custom-css').html(editor.getValue());1713 });1714 // Set editor's height to fullfill the modal1715 $(window).resize(function() {1716 editor.setSize('100%' , $(window).height() - 250);1717 });1718 /**1719 * Action inside Modal1720 */1721 var parent = $('#ig-pb-custom-css-box');1722 var css_files = parent.find('.jsn-items-list');1723 // sort the CSS files list1724 css_files.sortable();1725 parent.find('#items-list-edit, #items-list-save').click(function(e){1726 e.preventDefault();1727 $(this).toggleClass('hidden');1728 $(this).parent().find('.btn').not(this).toggleClass('hidden');1729 css_files.toggleClass('hidden');1730 parent.find('.items-list-edit-content').toggleClass('hidden');1731 // get current css files, add to textarea value1732 if( $(this).is('#items-list-edit') ) {1733 var files = '';1734 css_files.find('input').each(function(){1735 files += $(this).val() + '\n';1736 });1737 var textarea = parent.find('.items-list-edit-content').find('textarea');1738 textarea.val(files);1739 textarea.focus();1740 }1741 });1742 // Save Css files1743 parent.find('#items-list-save').click(function(e){1744 e.preventDefault();1745 /**1746 * Add file to CSS files list1747 */1748 // store exist urls1749 var exist_urls = new Array();1750 // store valid urls1751 var valid_urls = new Array();1752 // get HTML template of an item in CSS files list1753 var custom_css_item_html = $('#tmpl-ig-custom-css-item').html();1754 // get list of files url1755 var files = parent.find('.items-list-edit-content').find('textarea').val();1756 files = files.split("\n");1757 css_files.empty();1758 $.each(files, function(i, file){1759 var regex = /^[^\s]+\.[^\s]+/i;1760 // check if input is something like abc.xyz1761 if (regex.test(file))1762 {1763 css_files.append(custom_css_item_html.replace(/VALUE/g, file).replace(/CHECKED/g, ''));1764 valid_urls[i] = file;1765 }1766 });1767 // add loading icon1768 css_files.find('li.jsn-item').each(function(){1769 var file = $(this).find('input').val();1770 // if file is not checked whether exists or not, add loading icon1771 if( $.inArray( file, exist_urls ) < 0 ) {1772 $(this).append('<i class="jsn-icon16 jsn-icon-loading"></i>');1773 }1774 });1775 var hide_file = function(css_files, file) {1776 var item = css_files.find('input[value="'+file+'"]');1777 item.attr('disabled', 'disabled');1778 item.parents('li').attr('data-title', Ig_Translate.custom_css.file_not_found);1779 // remove loading icon1780 item.parents('li.jsn-item').find('.jsn-icon-loading').remove();1781 }1782 // check if file exists1783 $.each(valid_urls, function(i, file){1784 if (!file) {1785 return;1786 }1787 var file_ = file;1788 // check if is relative path1789 var regex = /^(?:(?:https?|ftp):\/\/)/i;1790 if (!regex.test(file))1791 {1792 // add WP root path to url to check1793 file_ = Ig_Translate.site_url + '/' + file;1794 }1795 // check if file exists or not1796 $.ajax({1797 url: file_,1798 statusCode: {1799 404: function () {1800 hide_file(css_files, file);1801 }1802 },1803 success: function () {1804 exist_urls[i] = file;1805 var item = css_files.find('input[value="'+file+'"]');1806 // check the checbox1807 item.attr('checked', 'checked');1808 // remove loading icon1809 item.parents('li.jsn-item').find('.jsn-icon-loading').remove();1810 },1811 error: function () {1812 hide_file(css_files, file);1813 }1814 });1815 });1816 });1817 // show tooltip1818 $.HandleElement.initTooltip( '[data-toggle="tooltip"]', 'auto left' );1819 }1820 /**1821 * Recognize when hit Enter on textbox1822 */1823 $.HandleElement.inputEnter = function() {1824 $("input:text").keypress(function (e) {1825 if (e.keyCode == 13) {1826 input_enter = 1;1827 } else {1828 input_enter = 0;1829 }1830 });1831 }1832 /**1833 * Extract shortcode parameters1834 */1835 $.HandleElement.extractScParam = function(shortcode_content) {1836 var result = {};1837 var regexp = /(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/g;1838 var res = shortcode_content.match(regexp);1839 for (var i = 0; i < res.length; i++){1840 var key_val = res[i];1841 if( ! ( key_val.indexOf('[') >= 0 || key_val.indexOf('=') < 0 ) ) {1842 var arr = key_val.split('=');1843 var key = arr[0];1844 var value = $.trim(arr[1]);1845 value = value.replace(/(^"|"$)/g, '');1846 result[key] = value;1847 }1848 }1849 return result;1850 }1851 /**1852 * Renerate a random string1853 */1854 function randomString(length) {1855 var result = '';1856 var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';1857 for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];1858 return result;1859 }1860 /**1861 * Method to resize modal when window resized1862 */1863 function resetModalSize(has_submodal, _return) {1864 var modal_width, modal_height;1865 if( has_submodal == 0 ){1866 modal_width = ($(window).width() > 750) ? 750 : $(window).width()*0.9;1867 modal_height = $(window.parent).height()*0.9;1868 }1869 else{1870 modal_width = (parent.document.body.clientWidth > 800) ? 800 : parent.document.body.clientWidth*0.9;1871 modal_height = parent.document.body.clientHeight*0.95;1872 }1873 if (_return == 'w'){1874 return modal_width;1875 }else{1876 return modal_height;1877 }1878 }1879 // Init IG PageBuilder element1880 $.HandleElement.init = function() {1881 $.HandleElement.inputEnter();1882 $.HandleElement.addItem();1883 $.HandleElement.addElement();1884 $.HandleElement.deleteElement();1885 $.HandleElement.editElement();1886 $.HandleElement.cloneElement();1887 $.HandleElement.deactivateElement();1888 $.HandleElement.deactivateShow();1889 $.HandleElement.initPremadeLayoutAction();1890 $.HandleElement.customCss();1891 $.HandleElement.checkSelectMedia();1892 $.HandleElement.initModeSwitcher();1893 $.HandleElement.initStatusSwitcher();1894 $.HandleElement.disableHref();1895 };1896 $(document).ready($.HandleElement.init);...

Full Screen

Full Screen

handle.js

Source:handle.js Github

copy

Full Screen

1/**2 * @version $Id$3 * @package JSN_PageBuilder4 * @author JoomlaShine Team <support@joomlashine.com>5 * @copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved.6 * @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html7 *8 * Websites: http://www.joomlashine.com9 * Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html10 */11var addedElementContainer;12var isAddNewElement;13//var JSNPBParentModal;14(function ($) {15 $.HandleElement = $.HandleElement || {};16 $.PbDoing = $.PbDoing || {};17 $.HandleElement.initAddElement = function () {18 // Set column where Add element button is clicked19 $("#form-container").on('jsnpb-add-more-element-click', function (event, obj) {20 addedElementContainer = $(obj).closest('.jsn-column').find('.jsn-element-container');21 });22 $('.shortcode-item').on('click', function (e) {23 e.preventDefault();24 if ($.PbDoing.addElement)25 return;26 $.PbDoing.addElement = 1;27 var shortcodeName = $(this).closest('li.jsn-item').attr('data-value');28 // remove spaces between29 shortcodeName = shortcodeName.replace(' ', '');30 $("#pb-add-element").dialog("close");31 isAddNewElement = true;32 var modalTitle = $(this).closest('.jsn-item').attr('data-modal-title');33 $.HandleElement._showSettingModal(shortcodeName, false, false, modalTitle, $(this));34 });35 };36 /**37 * Method to init event to Edit Element button38 */39 $.HandleElement.initEditElement = function () {40 $("#form-container").delegate(".element-edit", "click", function (e, restart_edit) {41 $.HandleElement.showLoading();42 if ($.PbDoing.editElement)43 return;44 $.PbDoing.editElement = 1;45 // Get parameters of edited element.46 var shortcodeContenObj = $(this).closest('.jsn-item').find('[name="shortcode_content[]"]');47 var params = shortcodeContenObj.val();48 var shortcodeName = shortcodeContenObj.attr('shortcode-name');49 addedElementContainer = $(this).closest('.jsn-item');50 var modalTitle = '';51 if ($(this).closest('.jsn-item').attr('data-name')) {52 modalTitle = $(this).closest('.jsn-item').attr('data-name');53 }54 if (typeof( shortcodeName ) == 'undefined' && $(this).attr('data-shortcode') != '') {55 shortcodeName = $(this).attr('data-shortcode');56 params = $(this).closest('.jsn-row-container').find('[name="shortcode_content[]"]').first().text();57 }58 $.HandleElement.editElement(shortcodeName, params, modalTitle, $(this));59 // Trigger progressbar60 $('#param-progress_bar_style').trigger('change');61 });62 // Add action edit element directly on layout page without click edit element icon.63 $("#form-container").on('click', '.item-container-content .jsn-element', function (e, restart_edit) {64 e.stopPropagation();65 // Prevent trigger edit element when click jsn-iconbar collections66 if ($(e.target).closest('.jsn-iconbar').length || $(e.target).hasClass('element-drag')) {67 return false;68 }69 $(this).find('.jsn-iconbar .element-edit').trigger('click');70 });71 }72 $.HandleElement.enableProcessing = function () {73 window.parent.jQuery.noConflict()('body').addClass('jsn_processing');74 }75 $.HandleElement.disableProcessing = function () {76 window.parent.jQuery.noConflict()('body').removeClass('jsn_processing');77 }78 /**79 * Method to process params before opening setting popup80 */81 $.HandleElement.editElement = function (shortcodeName, params, modalTitle, _this, isAdd) {82 params = JSON.stringify(params);83 $.post(84 JSNPbParams.rootUrl + 'administrator/index.php?option=com_pagebuilder&task=shortcode.savesession&tmpl=component&shortcode=' + shortcodeName,85 {86 params: params,87 shortcode: shortcodeName88 },89 function (data) {90 isAddNewElement = false;91 var isEdit = (isAdd == true) ? false : true;92 if (shortcodeName.search('_item') > 0) {93 $.HandleElement._showSettingModal(shortcodeName, true, isEdit, modalTitle, _this);94 } else {95 $.HandleElement._showSettingModal(shortcodeName, false, isEdit, modalTitle, _this);96 }97 }98 );99 }100 /**101 * Open setting Modal102 * This modal is used for subelements also103 */104 $.HandleElement._showSettingModal = function (shortcodeName, isSubmodal, isEdit, modalTitle, _this) {105 if (typeof( shortcodeName ) == 'undefined')106 return;107 // count element items.108 var count = 0;109 if (isEdit === false) {110 $('.jsn-item textarea[shortcode-name="' + shortcodeName + '"]').each(function () {111 count++;112 });113 }114 //if (!isSubmodal) {115 $.HandleElement.showLoading();116 //}117 var modalW, modalH;118 //modalW = (parent.document.body.clientWidth > 800) ? 800 : parent.document.body.clientWidth*0.9;119 modalW = parent.document.body.clientWidth * 0.9;120 modalH = parent.document.body.clientHeight * 0.75;121 if (!modalTitle && shortcodeName != '') {122 modalTitle = shortcodeName.replace('pb_', '');123 modalTitle = modalTitle.slice(0, 1).toUpperCase() + modalTitle.slice(1);124 modalTitle = modalTitle.replace('_item', ' Item');125 }126 // Open add element Modal127 var modal = new $.JSNModal({128 frameId: 'jsn_view_modal',129 jParent: window.parent.jQuery.noConflict(),130 title: modalTitle + ' Settings',131 url: JSNPbParams.rootUrl + 'administrator/index.php?option=com_pagebuilder&view=shortcodesetting&tmpl=component&shortcode=' + shortcodeName,132 buttons: [{133 'text': 'Save',134 'id': 'selected',135 'class': 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',136 'click': function () {137 if (!window.parent.jQuery.noConflict()('body').hasClass('jsn_processing')) {138 $.HandleElement.enableProcessing();139 var iframe = $(this).find('iframe');140 // TODO save data.141 // Update changed params142 $('body').trigger('before_save_modal', [_this]);143 iframe[0].contentWindow.JoomlaShine.jQuery.ShortcodeSetting.updateShortcodeParams();144 var params = iframe.contents().find('#shortcode_content').val();145 var el_title = '';146 el_title = iframe.contents().find('input[data-role="title"]').val();147 if (iframe.contents().find('textarea[data-role="title"]').length) {148 el_title = iframe.contents().find('textarea[data-role="title"]').val();149 }150 var shortcode = iframe.contents().find('#shortcode_name').val();151 $.post(152 JSNPbParams.rootUrl + '/administrator/index.php?option=com_pagebuilder&task=shortcode.generateHolder',153 {154 'params': encodeURIComponent(params),155 'shortcode': shortcode,156 'el_title': el_title157 },158 function (data) {159 if (shortcode == 'pb_row' && typeof( _this ) != 'undefined') {160 params = params.replace('[/pb_row]', '');161 _this.closest('.jsn-row-container').find('[name="shortcode_content[]"]').first().text(params);162 }163 $('body').trigger('jsnpb_before_changed');164 if (isEdit) {165 $(addedElementContainer).replaceWith(data);166 } else {167 $(addedElementContainer).append(data);168 }169 $.HandleElement.finalize();170 window.parent.jQuery.noConflict()('.jsn-modal-overlay').remove();171 window.parent.jQuery.noConflict()('.jsn-modal-indicator').remove();172 $('body').trigger('jsnpb_changed');173 $.HandleElement.initEditElement();174 $('#pb_previewing').val('1');175 $.HandleElement.disableProcessing();176 if (isSubmodal == true) {177 $.ShortcodeSetting.shortcodePreview();178 $("body").css({overflow: 'auto'});179 } else {180 $("body").css({overflow: 'auto'});181 }182 }183 );184 }185 }186 }, {187 'text': 'Cancel',188 'id': 'close',189 'class': 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',190 'click': function () {191 $.HandleElement.finalize();192 window.parent.jQuery.noConflict()('.jsn-modal-overlay').remove();193 window.parent.jQuery.noConflict()('.jsn-modal-indicator').remove();194 $("body").css({overflow: 'auto'});195 }196 }],197 loaded: function (obj, iframe) {198 $("body").css({overflow: 'hidden'});199 // Replace PB_INDEX_TRICK with count element items.200 var role_title = '';201 if (typeof( isEdit ) !== undefined && isEdit === false) {202 role_title = $(iframe).contents().find('#modalOptions input[data-role="title"]').val();203 if (role_title) {204 role_title = role_title.replace(/PB_INDEX_TRICK/g, count + 1);205 }206 } else {207 role_title = $(iframe).contents().find('#modalOptions input[data-role="title"]').val();208 if (role_title) {209 role_title = role_title.replace(/PB_INDEX_TRICK/g, 1);210 }211 }212 $(iframe).contents().find('#modalOptions input[data-role="title"]').attr('value', role_title);213 $(iframe).contents().find('#modalOptions input[data-role="title"]').val(role_title);214 // JSNPBParentModal = modal;215 //JSNPBParentModal.container.closest('.ui-dialog').css('z-index', parseInt(window.parent.JSNPBParentModal.container.closest('.ui-dialog').css('z-index')) + 4);216 // Bind trigger event when load googlemap item217 if (isSubmodal == true) {218 obj.container.closest('.ui-dialog').css('z-index', 10011);219 $('body').trigger('pb_submodal_load', [iframe]);220 }221 $(window).resize(function () {222 modalW = parent.document.body.clientWidth * 0.9;223 modalH = parent.document.body.clientHeight * 0.75;224 winW = parent.document.body.clientWidth;225 $('.jsn-master .jsn-elementselector .jsn-items-list').css('overflow', 'auto').css('height', modalH - 220);226 $("#pb-add-element").css('height', modalH - 200);227 $('.ui-dialog').css('width', modalW);228 $('.ui-dialog').css('left', winW / 2 - modalW / 2);229 });230 $(document).keyup(function (e) {231 var keyCode = (e.keyCode ? e.keyCode : e.which)232 if (keyCode == 27) {233 $.HandleElement.finalize();234 $("body").css({overflow: 'auto'});235 }236 });237 },238 fadeIn: 200,239 scrollable: true,240 width: modalW,241 height: modalH242 });243 modal.show();244 }245 // finalize when click Save/Cancel modal246 $.HandleElement.finalize = function (remove_modal) {247 $('body').trigger('on_update_attr_label_common');248 $('body').trigger('on_update_attr_label_setting');249 // Remove Modal250 if (remove_modal || remove_modal == null)251 {252 window.parent.jQuery.noConflict()('.jsn-modal').last().remove();253 }254 $("#form-container").find('.jsn-icon-loading').remove();255 // remove overlay & loading256 $.HandleElement.hideLoading();257 $.HandleElement.removeModal();258 $.PbDoing.addElement = 0;259 $.PbDoing.editElement = 0;260 }261 /**262 * Remove Modal, Show Loading, Hide Loading263 */264 $.HandleElement.removeModal = function () {265 $('.jsn-modal').remove();266 },267 /**268 * Show loading indicator269 */270 $.HandleElement.showLoading = function () {271 var $selector = $;//window.parent.jQuery.noConflict();272 var $overlay = $selector('.jsn-modal-overlay');273 if ($overlay.size() == 0) {274 $overlay = $('<div/>', {'class': 'jsn-modal-overlay'});275 }276 var $indicator = $selector('.jsn-modal-indicator');277 if ($indicator.size() == 0) {278 $indicator = $('<div/>', {'class': 'jsn-modal-indicator'});279 }280 $selector('body')281 .append($overlay)282 .append($indicator);283 $overlay.css({'z-index': 100}).show();284 $indicator.show();285 }286 $.HandleElement.hideLoading = function () {287 var $selector = $;//window.parent.jQuery.noConflict()288 $selector('.jsn-modal-overlay').hide();289 $selector('.jsn-modal-indicator').hide();290 }291 /**292 * delete an element (a row OR a column OR an shortcode item)293 */294 $.HandleElement.deleteElement = function () {295 $("#form-container").delegate(".element-delete", "click", function () {296 var msg, is_column;297 if ($(this).hasClass('row') || $(this).attr("data-target") == "row_table") {298 msg = "Are you sure you want to remove row?";299 } else if ($(this).hasClass('column') || $(this).attr("data-target") == "column_table") {300 msg = "Are you sure you want to remove column?";301 is_column = 1;302 } else {303 msg = "Are you sure you want to remove element?";304 }305 var confirm_ = confirm(msg);306 if (confirm_) {307 var $column = $(this).parent('.jsn-iconbar').parent('.shortcode-container');308 if (is_column == 1) {309 // Delete a Column in Table element310 if ($(this).attr("data-target") == "column_table") {311 var table = new $.PBTable();312 table.deleteColRow($(this), 'column');313 //$.HandleSetting.shortcodePreview();314 } else {315 var $row = $column.parent('.row-content').parent('.row-region');316 // if is last column of row, remove parent row317 if ($column.parent('.row-content').find('.column-region').length == 1) {318 $.HandleElement.removeElement($row);319 } else {320 $.HandleElement.removeElement($column);321 }322 }323 }324 else {325 // Delete a Row in Table element326 if ($(this).attr("data-target") == "row_table") {327 table = new $.PBTable();328 table.deleteColRow($(this), 'row');329 //$.HandleSetting.shortcodePreview();330 } else {331 $.HandleElement.removeElement($column);332 }333 }334 $.ShortcodeSetting.shortcodePreview();335 }336 });337 };338 // Clone an Element339 $.HandleElement.cloneElement = function () {340 $('#form-container').delegate('.element-clone', 'click', function () {341 if ($.PbDoing.cloneElement)342 return;343 $.PbDoing.cloneElement = 1;344 var parent_item = $(this).parent('.jsn-iconbar').parent('.jsn-item');345 var height_ = parent_item.height();346 var clone_item = parent_item.clone(true);347 var item_class = $('#modalOptions').length ? '.jsn-item-content' : '.pb-plg-element';348 // Update title for clone element349 var html = clone_item.html();350 if (item_class == '.jsn-item-content'){351 append_title_el = parent_item.find(item_class).html();352 }353 else {354 append_title_el = parent_item.find(item_class).find('span').html();355 if (typeof( append_title_el ) == 'undefined') {356 append_title_el = parent_item.find(item_class).html();357 }358 }359 var regexp = new RegExp(append_title_el, "g");360 // var regexpAttr = new RegExp(prtbl_item_attr_id, "g");361 html = html.replace(regexp, append_title_el + ' ' + JSNPbParams.pbstrings.COPY);362 clone_item.html(html);363 var textarea_content = clone_item.find("[name^='shortcode_content']").text();364 textarea_content = textarea_content.replace(/(prtbl_item_attr_id=")([^\"]+)(")/, '$1' + $.HandleElement.randomString(8) + '$3');365 clone_item.find("[name^='shortcode_content']").text(textarea_content);366 //prtbl_item_attr_id367 // Add animation before insert368 $.HandleElement.appendElementAnimate(clone_item, height_, function () {369 clone_item.insertAfter(parent_item);370 if ($('#form-container').hasClass('fullmode')) {371 // active iframe preview for cloned element372 $(clone_item[0]).find('form.shortcode-preview-form').remove();373 $(clone_item[0]).find('iframe').remove();374 //$.HandleElement.turnOnShortcodePreview(clone_item[0]);375 }376 }, function () {377 $('body').trigger('jsnpb_changed');378 $.PbDoing.cloneElement = 0;379 });380 $('#pb_previewing').val('1');381 $.ShortcodeSetting.shortcodePreview();382 });383 }384 $.HandleElement.randomString = function(length) {385 var result = '';386 var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'387 for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];388 return result;389 }390 /**391 * Remove an element in Pagebuilder / In Modal392 */393 $.HandleElement.removeElement = function (element) {394 $('body').trigger('jsnpb_changed');395 element.css({396 'min-height': 0,397 'overflow': 'hidden'398 });399 element.animate({400 opacity: 0401 }, 300, 'easeOutCubic', function () {402 element.animate({403 height: 0,404 'padding-top': 0,405 'padding-bottom': 0406 }, 300, 'easeOutCubic', function () {407 element.remove();408 $('body').trigger('on_after_delete_element');409 $('body').trigger('jsnpb_changed');410 // for shortcode which has sub-shortcode411 if ($("#modalOptions").find('.has_submodal').length > 0) {412 $.HandleElement.rescanShortcode();413 }414 });415 });416 }417 /**418 * For Parent Shortcode: Rescan sub-shortcodes content, call preview419 * function to regenerate preview420 */421 $.HandleElement.rescanShortcode = function (curr_iframe, callback) {422 try {423 $.ShortcodeSetting.shortcodePreview(null, null, curr_iframe, callback);424 } catch (err) {425 console.log(err);426 }427 }428 // Animation when add new element to container429 $.HandleElement.appendElementAnimate = function (new_el, height_, callback, finished) {430 $('body').trigger('jsnpb_changed');431 var obj_return = {432 obj_element: new_el433 };434 $('body').trigger('on_clone_element_item', [obj_return]);435 new_el = obj_return.obj_element;436 new_el.css({437 'opacity': 0438 });439 new_el.addClass('padTB0');440 if (callback)callback();441 new_el.show();442 new_el.animate({443 height: height_444 }, 500, 'easeOutCubic', function () {445 $(this).animate({446 opacity: 1447 }, 300, 'easeOutCubic', function () {448 new_el.removeClass('padTB0');449 new_el.css('height', 'auto');450 $('body').trigger('on_update_attr_label_common');451 $('body').trigger('on_update_attr_label_setting');452 if (finished)finished();453 });454 });455 }456 $.HandleElement.sliceContent = function (text) {457 text = unescape(text);458 text = text.replace(/\+/g, ' ');459 var arr = text.split(' ');460 arr = arr.slice(0, 10);461 return arr.join(' ');462 }463 /**464 * Traverse parameters, get theirs values465 */466 $.HandleElement.traverseParam = function( $selector, child_element ){467 var sc_content = '';468 var params_arr = {};469 $selector.each( function ()470 {471 if ( ! $(this).hasClass( 'pb_hidden_depend' ) )472 {473 $(this).find( '[id^="param-"]' ).each(function()474 {475 // Bypass the Copy style group476 if ( $(this).attr('id') == 'param-copy_style_from' ) {477 return;478 }479 if(480 $(this).parents(".tmce-active").length == 0 && ! $(this).hasClass('tmce-active')481 && $(this).parents(".html-active").length == 0 && ! $(this).hasClass('html-active')482 && ! $(this).parents("[id^='parent-param']").hasClass( 'pb_hidden_depend' )483 && ( child_element || ! $(this).closest('.form-group').parent().hasClass('sub-element-settings'))484 && $(this).attr('id').indexOf('parent-') == -1485 )486 {487 var id = $(this).attr('id');488 if($(this)){489 sc_content = $(this).val();//.replace(/\[/g,"&#91;").replace(/\]/g,"&#93;");490 }else{491 if(($(this).is(":radio") || $(this).is(":checkbox")) && !$(this).is(":checked"));492 else{493 if(!params_arr[id.replace('param-','')] || id.replace('param-', '') == 'title_font_face_type' || id.replace('param-', '') == 'title_font_face_value' || id.replace('param-','') == 'font_face_type' || id.replace('param-','') == 'font_face_value' || id.replace('param-', '') == 'image_type_post' || id.replace('param-', '') == 'image_type_page' || id.replace('param-', '') == 'image_type_category' ) {494 params_arr[id.replace('param-','')] = $(this).val();495 } else {496 params_arr[id.replace('param-','')] += '__#__' + $(this).val();497 }498 }499 }500 }501 });502 }503 });504 return { sc_content : sc_content, params_arr : params_arr };505 }506 /**507 * Generate shortcode content508 */509 $.HandleElement.generateShortcodeContent = function(shortcode_name, params_arr, sc_content){510 var tmp_content = [];511 tmp_content.push('['+ shortcode_name);512 // wrap key, value of params to this format: key = "value"513 $.each(params_arr, function(key, value){514 if ( value ) {515 if ( value instanceof Array ) {516 value = value.toString();517 }518 tmp_content.push(key + '="' + value.replace(/\"/g,"&quot;").replace(/\[/g,"").replace(/\]/g,"") + '"');519 }520 });521 // step_to_track(6,tmp_content);522 tmp_content.push(']' + sc_content + '[/' + shortcode_name + ']');523 tmp_content = tmp_content.join( ' ' );524 return tmp_content;525 }526 $.HandleElement.customCss = function () {527 //show modal528 setTimeout(function () {529 var modalw = $(window.parent).width() * 0.9;530 var modalh = $(window.parent).height() * 0.9;531 var framId = 'custom-css-modal';532 var modal;533 var content_id = $('#top-btn-actions').find('[name="pb_content_id"]').val();534 var frame_url = JSNPbParams.rootUrl + 'administrator/index.php?option=com_pagebuilder&view=builder&tmpl=component&pb_custom_css=1&id=' + content_id;535 $('button.page-custom-css').on('click', function (e) {536 if ($(this).find('.btn').hasClass('disabled')) {537 return;538 }539 modal = new $.JSNModal({540 frameId: framId,541 jParent: window.parent.jQuery.noConflict(),542 title: 'Custom Css',543 url: frame_url,544 buttons: [{545 'text': 'Save',546 'id': 'selected',547 'class': 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',548 'click': function () {549 var jParent = window.parent.jQuery.noConflict();550 // get css file (link + checked status), save custom css551 var iframe_content = jParent('#' + framId).contents();552 var css_files = [];553 iframe_content.find('#pb-custom-css-box').find('.jsn-items-list').find('li').each(function (i) {554 var input = $(this).find('input');555 var checked = input.is(':checked');556 var url = input.val();557 var item = {558 'checked': checked,559 'url': url560 };561 css_files.push(item);562 });563 var css_files = JSON.stringify({data: css_files});564 //get custom css code565 var custom_css = iframe_content.find('#custom-css').val();566 //save data567 $.post(568 JSNPbParams.rootUrl + 'administrator/index.php?option=com_pagebuilder&task=builder.save_css_custom',569 {570 action: 'save_css_custom',571 content_id: content_id,572 css_files: css_files,573 css_custom: custom_css574 },575 function (data) {576 //close loading577 $.HandleElement.hideLoading();578 });579 //close modal580 $.HandleElement.finalize(0);581 //show loading582 //$.HandleElement.showLoading();583 }584 }, {585 'text': 'Cancel',586 'id': 'close',587 'class': 'ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only',588 'click': function () {589 $.HandleElement.hideLoading();590 $.HandleElement.removeModal();591 $('body').css({overflow: 'auto'});592 }593 }],594 loaded: function () {595 },596 fadeIn: 200,597 scrollable: true,598 width: modalw,599 height: modalh600 });601 modal.show();602 });603 }, 200);604 }605 $.HandleElement.init = function () {606 $.HandleElement.customCss();607 }608 $(document).ready($.HandleElement.init);...

Full Screen

Full Screen

ResizeHandle.js

Source:ResizeHandle.js Github

copy

Full Screen

1/*2 * Copyright (c) 2008-2014 CoNWeT Lab., Universidad Politécnica de Madrid3 *4 * This file is part of Wirecloud Platform.5 *6 * Wirecloud Platform is free software: you can redistribute it and/or7 * modify it under the terms of the GNU Affero General Public License as8 * published by the Free Software Foundation, either version 3 of the9 * License, or (at your option) any later version.10 *11 * Wirecloud is distributed in the hope that it will be useful, but WITHOUT12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public14 * License for more details.15 *16 * You should have received a copy of the GNU Affero General Public License17 * along with Wirecloud Platform. If not, see18 * <http://www.gnu.org/licenses/>.19 *20 */21/*global EzWebEffectBase, Wirecloud */22(function () {23 "use strict";24 var returnTrue = function returnTrue() {25 return true;26 };27 var ResizeHandle = function ResizeHandle(resizableElement, handleElement, data, onStart, onResize, onFinish, canBeResized) {28 var xDelta = 0, yDelta = 0;29 var xStart = 0, yStart = 0;30 var scrollDelta, scrollStart = 0;31 var dragboardCover;32 var x, y;33 var endresize, resize, startresize, scroll;34 canBeResized = canBeResized ? canBeResized : returnTrue;35 // remove the events36 endresize = function endresize(e) {37 // Only attend to left button (or right button for left-handed persons) events38 if (e.type === 'mouseup' && e.button !== 0) {39 return;40 } else if (e.type === 'touchend' && e.touches.length > 0) {41 return;42 }43 document.removeEventListener("mouseup", endresize, false);44 document.removeEventListener("touchend", endresize, false);45 document.removeEventListener("mousemove", resize, false);46 document.removeEventListener("touchmove", resize, false);47 dragboardCover.parentNode.removeEventListener("scroll", scroll, true);48 dragboardCover.parentNode.removeChild(dragboardCover);49 dragboardCover = null;50 handleElement.removeEventListener("mouseup", endresize, false);51 handleElement.removeEventListener("touchend", endresize, false);52 handleElement.removeEventListener("mousemove", resize, false);53 handleElement.removeEventListener("touchmove", resize, false);54 onFinish(resizableElement, handleElement, data);55 // Restore start event listener56 handleElement.addEventListener("mousedown", startresize, false);57 handleElement.addEventListener("touchstart", startresize, false);58 document.removeEventListener('mousedown', Wirecloud.Utils.preventDefaultListener, false); // reenable text selection59 document.removeEventListener('contextmenu', Wirecloud.Utils.preventDefaultListener, false); // reenable context menu60 };61 // fire each time the mouse is moved while resizing62 resize = function resize(e) {63 var clientX, clientY;64 if ('touches' in e) {65 clientX = e.touches[0].clientX;66 clientY = e.touches[0].clientY;67 // Work around chrome bug: https://code.google.com/p/chromium/issues/detail?id=15077968 e.preventDefault();69 } else {70 clientX = e.clientX;71 clientY = e.clientY;72 }73 xDelta = clientX - xStart;74 yDelta = clientY - yStart;75 onResize(resizableElement, handleElement, data, x + xDelta, y + yDelta - scrollDelta);76 };77 // fire each time the dragboard is scrolled while dragging78 scroll = function scroll() {79 var dragboard = dragboardCover.parentNode;80 dragboardCover.style.height = dragboard.scrollHeight + "px";81 var scrollTop = parseInt(dragboard.scrollTop, 10);82 scrollDelta = scrollStart - scrollTop;83 onResize(resizableElement, handleElement, data, x + xDelta, y + yDelta - scrollDelta);84 };85 // initiate the resizing86 startresize = function startresize(e) {87 // Only attend to left button (or right button for left-handed persons) events88 if (e.type === 'mousedown' && e.button !== 0) {89 return;90 }91 if (!canBeResized(resizableElement, data)) {92 return false;93 }94 document.addEventListener('contextmenu', Wirecloud.Utils.preventDefaultListener, false); // disable context menu95 document.addEventListener('mousedown', Wirecloud.Utils.preventDefaultListener, false); // disable text selection96 handleElement.removeEventListener("mousedown", startresize, false);97 handleElement.removeEventListener("touchstart", startresize, false);98 if ('touches' in e) {99 xStart = e.touches[0].clientX;100 yStart = e.touches[0].clientY;101 } else {102 xStart = e.clientX;103 yStart = e.clientY;104 }105 x = resizableElement.offsetLeft + handleElement.offsetLeft + (handleElement.offsetWidth / 2);106 y = resizableElement.offsetTop + handleElement.offsetTop + (handleElement.offsetHeight / 2);107 document.addEventListener("mouseup", endresize, false);108 document.addEventListener("touchend", endresize, false);109 document.addEventListener("mousemove", resize, false);110 document.addEventListener("touchmove", resize, false);111 var dragboard = EzWebEffectBase.findDragboardElement(resizableElement);112 dragboardCover = document.createElement("div");113 dragboardCover.className = "cover";114 dragboardCover.addEventListener("mouseup", endresize, true);115 dragboardCover.addEventListener("mousemove", resize, true);116 dragboardCover.style.zIndex = "1000000";117 dragboardCover.style.position = "absolute";118 dragboardCover.style.top = "0";119 dragboardCover.style.left = "0";120 dragboardCover.style.width = "100%";121 dragboardCover.style.height = dragboard.scrollHeight + "px";122 scrollStart = dragboard.scrollTop;123 scrollDelta = 0;124 dragboard.addEventListener("scroll", scroll, true);125 dragboard.insertBefore(dragboardCover, dragboard.firstChild);126 handleElement.addEventListener("mouseup", endresize, false);127 handleElement.addEventListener("touchend", endresize, false);128 handleElement.addEventListener("mousemove", resize, false);129 handleElement.addEventListener("touchmove", resize, false);130 onStart(resizableElement, handleElement, data);131 return false;132 };133 // Add event listener134 handleElement.addEventListener("mousedown", startresize, false);135 handleElement.addEventListener("touchstart", startresize, false);136 this.setResizableElement = function (element) {137 resizableElement = element;138 };139 this.destroy = function () {140 handleElement.removeEventListener("mousedown", startresize, true);141 startresize = null;142 resize = null;143 scroll = null;144 endresize = null;145 data = null;146 handleElement = null;147 };148 };149 Wirecloud.ui.ResizeHandle = ResizeHandle;...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

1"user strict";23const container = document.querySelector(".container");456function keyCode (event){7 if (event.which === 82) {8 container.style.backgroundColor= 'red'}9 else if (event.which === 77) {10 container.style.backgroundColor= 'purple'}11 }12 13container.addEventListener("keydown", keyCode);1415// 'use strict';16// const handleElement = document.querySelector ('.document'); 17// console.log(handleElement)18// function changeElement(event) {19// if (event.key === 'r') {20// handleElement.classList.add('documentR')21// handleElement.classList.remove('documentM')22// } else if (event.key === 'm') {23// handleElement.classList.add('documentM')24// handleElement.classList.remove('documentR')25// }26// console.log(event.key);27// } ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { handleElement } = require('playwright/lib/server/dom');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const element = await page.$('#searchInput');8 const elementHandle = await handleElement(element);9 console.log(elementHandle);10 await browser.close();11})();12{13 _context: {14 _delegate: {15 },16 _pageBindings: Map {},17 _pageDelegate: {18 },19 _pageOrError: Promise { <pending> },20 _pagePromise: Promise { <pending> },21 _timeoutSettings: TimeoutSettings {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { handleElement } = require('playwright/lib/server/dom')2const { chromium } = require('playwright')3const browser = await chromium.launch()4const context = await browser.newContext()5const page = await context.newPage()6const element = await page.$('input[name="q"]')7const handle = await handleElement(element)8console.log(handle)9await browser.close()10{11 _page: Page {12 _delegate: PageDelegate {},13 _timeoutSettings: TimeoutSettings { _defaultTimeout: 30000 },14 _pageBindings: Map(0) {},15 _pageBindingsReverse: Map(0) {},16 _workers: Set(0) {},17 _browserContext: BrowserContext {18 _delegate: BrowserContextDelegate {},19 _options: {20 },21 _permissions: Map(0) {},22 _timeoutSettings: TimeoutSettings { _defaultTimeout: 30000 },23 _browser: Browser {24 _delegate: BrowserDelegate {},25 _timeoutSettings: TimeoutSettings { _defaultTimeout: 30000 },26 _defaultContext: BrowserContext {27 _delegate: BrowserContextDelegate {},

Full Screen

Using AI Code Generation

copy

Full Screen

1const { handleElement } = require('playwright/lib/internal/frames');2const path = require('path');3const fs = require('fs');4const { chromium } = require('playwright');5(async () => {6 const browser = await chromium.launch();7 const context = await browser.newContext();8 const page = await context.newPage();9 const elementHandle = await page.$('#mydiv');10 const element = await handleElement(elementHandle);11 const screenshot = await element.screenshot({ path: 'screenshot.png' });12 console.log(screenshot);13 await browser.close();14})();15const { handleElement } = require('playwright/lib/internal/frames');16const path = require('path');17const fs = require('fs');18const { chromium } = require('playwright');19(async () => {20 const browser = await chromium.launch();21 const context = await browser.newContext();22 const page = await context.newPage();23 const elementHandle = await page.$('#mydiv');24 const element = await handleElement(elementHandle);25 const screenshot = await element.screenshot();26 console.log(screenshot);27 await browser.close();28})();29const { handleElement } = require('playwright/lib/internal/frames');30const path = require('path');31const fs = require('fs');32const { chromium } = require('playwright');33(async () => {34 const browser = await chromium.launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 const elementHandle = await page.$('#mydiv');38 const element = await handleElement(elementHandle);39 const screenshot = await element.screenshot({ path: 'screenshot.png', fullPage: true });40 console.log(screenshot);41 await browser.close();42})();43const { handleElement } = require('playwright/lib/internal/frames');44const path = require('path');45const fs = require('fs');46const { chromium } = require('playwright');47(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const handle = await page._delegate.handleElement({ selector: 'text=Get started' });7 console.log(handle);8 await browser.close();9})();10ElementHandle {11 _page: Page {12 _browserContext: BrowserContext {13 },14 _browser: Browser {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { handleElement } = require('playwright-core/lib/server/dom')2const { parseSelector } = require('playwright-core/lib/server/selectors/selectorParser')3const { createJSHandle } = require('playwright-core/lib/server/frames')4const { ElementHandle } = require('playwright-core/lib/server/dom')5const { Page } = require('playwright-core/lib/server/page')6const { Frame } = require('playwright-core/lib/server/frames')7const { ElementHandleChannel } = require('playwright-core/lib/server/channels')8const { DOMWorld } = require('playwright-core/lib/server/domWorld')9const { Protocol } = require('playwright-core/lib/server/protocol')10const { handleElement } = require('playwright-core/lib/server/dom')11const { parseSelector } = require('playwright-core/lib/server/selectors/selectorParser')12const { createJSHandle } = require('playwright-core/lib/server/frames')13const { ElementHandle } = require('playwright-core/lib/server/dom')14const { Page } = require('playwright-core/lib/server/page')15const { Frame } = require('playwright-core/lib/server/frames')16const { ElementHandleChannel } = require('playwright-core/lib/server/channels')17const { DOMWorld } = require('playwright-core/lib/server/domWorld')18const { Protocol } = require('playwright-core/lib/server/protocol')19const { handleElement } = require('playwright-core/lib/server/dom')20const { parseSelector } = require('playwright-core/lib/server/selectors/selectorParser')21const { createJSHandle } = require('playwright-core/lib/server/frames')22const { ElementHandle } = require('playwright-core/lib/server/dom')23const { Page } = require('playwright-core/lib/server/page')24const { Frame } = require('playwright-core/lib/server/frames')25const { ElementHandleChannel } = require('playwright-core/lib/server/channels')26const { DOMWorld } = require('playwright-core/lib/server/domWorld')27const { Protocol } = require('playwright-core/lib/server/protocol')28const { handleElement } = require('playwright-core/lib/server/dom')29const { parseSelector } = require('playwright-core/lib/server/select

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium, firefox, webkit } = require('playwright');2const { handleElement } = require('playwright/lib/server/dom.js').DOMWorld;3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const element = await page.$('h1');7 const handle = await handleElement(element);8 console.log(handle);9 await browser.close();10})();11 * @param {!ElementHandle} elementHandle12 * @return {!Promise<!ElementHandle>}13async function handleElement(elementHandle) {14 const context = elementHandle._context;15 const page = context._page;16 if (!page)17 throw new Error('Element is not connected to the DOM');18 const result = await page._delegate.evaluateHandle((injected, element) => {19 const context = injected._context;20 const node = context._createHandle(element);21 return context.evaluateHandle(element => element, node).asElement();22 }, elementHandle);23 return ElementHandle.from(result);24}25const handle = await handleElement(element);26console.log(handle);27ElementHandle {28 _context: JSHandle {29 _page: Page {30 _pageBindings: Map {},31 },

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2const { handleElement } = require('playwright/lib/client/selectorEngine');3const { ElementHandle } = require('playwright/lib/client/elementHandle');4const { Frame } = require('playwright/lib/client/frame');5(async () => {6 const browser = await chromium.launch({ headless: false });7 const context = await browser.newContext();8 const page = await context.newPage();9 const elementHandle = await page.$('text=Get started');10 const element = await handleElement(await elementHandle._context(), elementHandle);11 console.log(element);12 await browser.close();13})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { handleElement } = require('playwright/lib/protocol/protocol.js');2const { chromium } = require('playwright');3const { ElementHandle } = require('playwright/lib/cjs/pw/api/elementHandle.js');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const element = await page.$('text=Docs');9 const handle = await handleElement(page, element, new ElementHandle(page, element));10 console.log(handle);11})();12{13 objectId: '{"injectedScriptId":1,"id":1}',14 value: {15 attributes: {16 },17 }18}19{20 objectId: '{"injectedScriptId":1,"id":1}',21 value: {22 attributes: {23 },24 }25}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { handleElement } = require('playwright/lib/internal/frames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const handle = await handleElement(page.mainFrame(), 'text=Get Started');7 const element = await handle.asElement();8 await element.click();9 await browser.close();10})();

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful