Best JavaScript code snippet using cypress
editor.js
Source:editor.js
1/* jshint multistr:true */2(function($, undefined) {3 "use strict";4 // see https://github.com/spencertipping/jquery.fix.clone5 $.fn.fixedClone = function() {6 var result = $.fn.clone.apply(this, arguments),7 my_textareas = this.find('textarea').add(this.filter('textarea')),8 result_textareas = result.find('textarea').add(result.filter('textarea')),9 my_selects = this.find('select').add(this.filter('select')),10 result_selects = result.find('select').add(result.filter('select'));11 var i, l;12 for (i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());13 for (i = 0, l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;14 return result;15 };16 $(function() {17 ED.container = $('#vamtam_visual_editor');18 ED.savingBlocked = true;19 if (ED.container.length === 1) {20 var editor_button = $('<a class="vamtam-editor-toggle wp-switch-editor">Vamtam</a>');21 $('#content-html').before(editor_button);22 var postdivrich = $('#wp-content-editor-container, #post-status-info, #wp-content-media-buttons');23 var wp_ed_state = '';24 var wp_content_wrap = $("#wp-content-wrap");25 ED.container.html(ED.container.find('> .inside').html()).insertAfter('#wp-content-editor-container');26 ED.content = $('#visual_editor_content');27 ED.content.find('a').click(function(e) {28 e.preventDefault();29 });30 ED.isVisible = false;31 editor_button.click(function() {32 if (wp_content_wrap.is('.html-active')) switchEditors.go('content', 'tmce');33 switchEditors.go('content', 'html');34 wp_ed_state = wp_content_wrap[0].className.replace(/wp-editor-wrap\s*/, '');35 wp_content_wrap.removeClass(wp_ed_state);36 postdivrich.hide();37 ED.get_editor_html();38 ED.container.show();39 ED.content.show();40 $('#vamtam_ed_js_status').val("true");41 editor_button.addClass('active');42 ED.isVisible = true;43 wp_content_wrap.addClass( 'vamtam-editor-active' );44 });45 $('#content-html, #content-tmce').click(function(e) {46 if (!ED.isVisible) return;47 ED.isVisible = false;48 ED.saveHTML();49 postdivrich.show();50 ED.container.hide();51 $('#vamtam_ed_js_status').val("false");52 editor_button.removeClass('active');53 if (e.target.id.replace('content-', '') === 'html') wp_content_wrap.addClass('html-active');54 wp_content_wrap.removeClass( 'vamtam-editor-active' );55 $( window ).scroll();56 });57 if ($('#vamtam_ed_js_status').val() === 'true') editor_button.click();58 ED.init();59 $('#post').bind('submit.vamtameditor', function() {60 if(ED.isVisible && !ED.saved) {61 ED.allow_autosave = false;62 ED.saveHTML();63 ED.saved = true;64 $(this).submit();65 }66 });67 $('#submitdiv').bind('mouseneter.vamtameditor', function() {68 ED.saveHTML();69 });70 }71 });72 var ED = {73 init: function() {74 ED.controls();75 ED.dragdrop.init();76 ED.elementButtons();77 ED.toolbox = $('#vamtam-editor-toolbox');78 ED.form = $('#visual_editor_edit_form');79 ED.dragdrop.refresh();80 ED.shortcodes.init();81 },82 controls: function() {83 $('body').on('click', '.column-remove', function(e) {84 e.preventDefault();85 if (confirm("Are you sure you want to delete this section?")) {86 $(this).closest(".column").remove();87 ED.dragdrop.empty_notice();88 ED.saveHTML();89 }90 });91 $('body').on('click', '.column-edit', function(e) {92 ED.edit_form.show($(this).closest('.column'));93 e.preventDefault();94 });95 $('body').on('click', '.column-clone', function(e) {96 var c = $(this).closest('.column'),97 cloned = c.fixedClone();98 cloned99 .attr('id', cloned.attr('id') + (new Date().getTime()))100 .removeClass('ui-draggable')101 .insertAfter(c);102 ED.dragdrop.empty_notice();103 ED.dragdrop.refresh();104 e.preventDefault();105 });106 $('body').on('click', '.column-decrease, .column-increase', function(e) {107 var column = $(this).closest(".column"),108 size = ED.getColumnSize(column),109 new_size = size[$(e.target).hasClass('column-decrease') ? 'smaller' : 'larger'];110 if (new_size) {111 column.removeClass(size.size).addClass(new_size);112 $(column).find(".column-size:first").html(ED.getColumnSize(column).size_str);113 ED.saveHTML();114 }115 e.preventDefault();116 });117 $('body').on('click', '.vamtam-save-element', function(e) {118 ED.edit_form.save();119 e.preventDefault();120 });121 $('body').on('click', '.vamtam-cancel-element', function(e) {122 ED.edit_form.cancel();123 e.preventDefault();124 });125 ED.container.on('click', '.handlediv', function(e) {126 var c = $(this).closest('.column').toggleClass('expanded');127 if (c.hasClass('expanded')) {128 var s = c.find('.inner-sortable');129 if ($(this).is('.inner-sortable')) s.add($(this));130 s.each(function() {131 if ($(this).data('sortable')) $(this).sortable("option", "disabled", false);132 });133 }134 e.preventDefault();135 });136 },137 get_editor_html: function(refresh) {138 ED.savingBlocked = true;139 var expanded = [];140 if(refresh) {141 ED.content.find('.column.expandable').each(function() {142 expanded.push($(this).hasClass('expanded'));143 });144 }145 ED.content.html('').addClass('spinner');146 var content = switchEditors._wp_Nop( document.getElementById( 'content' ).value );147 $.ajax({148 type: "POST",149 url: ajaxurl,150 data: {151 action: 'vamtam_editor_init_html',152 content: content153 },154 success: function(data) {155 ED.content.html(data).removeClass('spinner').find('.column').each(function() {156 ED.do_action($(this), 'init');157 });158 ED.dragdrop.refresh();159 ED.shortcodes.accordion.reload();160 ED.shortcodes.tabs.reload();161 if(refresh) {162 ED.content.find('.column.expandable').each(function(i) {163 if(expanded[i])164 $(this).addClass('expanded');165 });166 }167 ED.savingBlocked = false;168 ED.container.find(".vamtam-editor-error").on("selectstart mousedown mousemove", function(e) {169 e.stopPropagation();170 return true;171 });172 ED.container.find(".vamtam-ed-param-holder.html-content").bind("mousedown", function(e) {173 e.stopPropagation();174 });175 }176 });177 },178 dragdrop: {179 init: function() {180 $('.droppable_source', ED.container).draggable({181 revert: "invalid",182 zIndex: 300,183 cursorAt: {184 left: 10,185 top: 10186 },187 cursor: "move",188 helper: 'clone',189 start: function(event) {190 $(event.target).css({opacity:0.4});191 $('.vamtam-dd-active').removeClass('vamtam-dd-active');192 event.stopPropagation();193 },194 stop: function(event) {195 $(event.target).css({opacity:1});196 $('.vamtam-dd-active').removeClass('vamtam-dd-active');197 }198 });199 this.refresh();200 },201 refresh: function() {202 ED.rowClasses($(".vamtam_main_sortable"));203 try {204 $('.vamtam_sortable.ui-draggable', ED.container).draggable('destroy');205 $('.inner-sortable.ui-droppable', ED.container).droppable('destroy');206 } catch(e) {}207 $('.vamtam_sortable', ED.container).draggable({208 appendTo: ED.content,209 handle: '> .controls',210 scroll: true,211 zIndex: 1000,212 cursorAt: { left: 20 },213 cursor: 'move',214 helper: 'clone',215 start: function(event) {216 $(event.target).css({opacity:0.4});217 $('.vamtam-dd-active').removeClass('vamtam-dd-active');218 event.stopPropagation();219 },220 stop: function(event) {221 $(event.target).css({opacity:1});222 $('.vamtam-dd-active').removeClass('vamtam-dd-active');223 }224 });225 ED.dragdrop.empty_notice();226 $('.inner-sortable', ED.container).droppable({227 tolerance: 'pointer',228 greedy: true,229 accept: '.vamtam_sortable, .droppable_source',230 hoverClass: "ui-state-active",231 over: function() {232 $(this).addClass('vamtam-dd-active');233 },234 out: function() {235 $(this).removeClass('vamtam-dd-active');236 },237 drop: function(event, ui) {238 ED.dragdrop.empty_notice();239 var self = $(this);240 if(ui.draggable.hasClass('droppable_source')) {241 ED.createElement(event.target, ui.draggable, "ED.rowClasses", function(data) {242 ED.content.removeClass('spinner');243 ED.dragdrop.insert(data, self, ui.offset);244 });245 } else {246 ED.dragdrop.insert(ui.draggable, self, ui.offset);247 }248 }249 }).disableSelection();250 ED.saveHTML();251 },252 insert: function(draggable, droppable, d_offset) {253 var elements = droppable.find('>.vamtam_sortable'),254 method = 'after',255 toEl = false,256 offsets = [],257 max_offset_top = 0;258 if(droppable.hasClass('expandable'))259 droppable.addClass('expanded');260 if(elements.length > 0) {261 elements.each(function(i, e) {262 var offset = $(e).offset();263 if(offset.top >= d_offset.top)264 return false;265 var row = Math.round(offset.top);266 if(!offsets[row])267 offsets[row] = [];268 offsets[row].push({269 left: offset.left,270 index: i271 });272 max_offset_top = Math.max(max_offset_top, row);273 });274 if(offsets.length === 0) {275 toEl = droppable.find('.vamtam_sortable:first');276 method = 'before';277 } else {278 $(offsets[max_offset_top]).each(function(i, e) {279 if(e.left >= d_offset.left)280 return false;281 toEl = elements.eq(e.index);282 });283 if(toEl === false) {284 toEl = elements.eq(offsets[max_offset_top][0].index);285 method = 'before';286 }287 }288 } else {289 toEl = droppable;290 method = 'append';291 }292 toEl[method](draggable.css({left: 0, top: 0, opacity: 1}));293 ED.dragdrop.refresh();294 },295 empty_notice: function() {296 var span_class = 'inner-sortable-empty-notice',297 sortables = $('.inner-sortable', ED.container);298 sortables.find('.'+span_class).remove();299 sortables.append('<span class="'+span_class+'">'+VAMTAMED_LANG.empty_notice+'</span>');300 sortables.filter(':has(> .column)').find('>.'+span_class).remove();301 }302 },303 elementButtons: function() {304 $('.clickable_action', ED.container).click(function(e) {305 var self = $(this);306 if(self.hasClass('added')) return false;307 if(!ED.creteTarget)308 ED.createTarget = $(".vamtam_main_sortable", ED.container);309 ED.createElement(ED.createTarget, self, "ED.dragdrop.refresh", function() {310 ED.content.removeClass('spinner');311 });312 self.addClass('added a-icon-checkmark');313 setTimeout(function() {314 self.removeClass('added a-icon-checkmark');315 }, 800);316 e.preventDefault();317 });318 },319 parseColumn: function(column) {320 var data = column[0].className.match(/column-(\d)-(\d)/);321 if (data) return data;322 return ['column-1-1', 1, 1];323 },324 getColumnSize: function(column) {325 var size = ED.parseColumn(column);326 var sizes = ['1-1', '1-6', '1-5', '1-4', '1-3', '2-5', '1-2', '3-5', '2-3', '3-4', '4-5', '5-6', '1-1', '1-6'];327 var index = sizes.indexOf(size[1] + '-' + size[2], size[2] === "1" ? 1 : 0);328 for(var i in sizes) {329 if (sizes[i]) sizes[i] = 'column-' + sizes[i];330 }331 return {332 size: size[0],333 larger: sizes[index + 1],334 smaller: sizes[index - 1],335 size_str: size[1] + '/' + size[2]336 };337 },338 /**339 * Fills in TinyMCE's content with the updated shortcode settings340 */341 saveHTML: function(callback) {342 if (ED.savingBlocked) {343 console.log('ED.saveHTML is blocked');344 return;345 }346 ED.rowClasses(ED.content);347 if ($(".vamtam_main_sortable").html().indexOf('<!-- vamtam editor error -->') > -1) {348 console.log("ED.saveHTML can't save - there's a parser error");349 return;350 }351 var shortcodes = ED.generate_shortcodes($(".vamtam_main_sortable"));352 if (tinyMCE.get('content')) {353 tinyMCE.get('content').setContent(354 switchEditors.wpautop(shortcodes), {355 format: 'raw'356 });357 }358 $('#content').val(shortcodes);359 if (ED.allow_autosave) {360 window.wp.autosave();361 } else {362 ED.allow_autosave = true;363 }364 if(callback)365 callback();366 },367 /**368 * Since we can't use .row wrappers, this function adds .first and .last classes369 * to the first and last element in each visible row370 */371 rowClasses: function(base_el) {372 base_el = $(base_el);373 var fill = 0,374 width = 0,375 level_1 = $(base_el).children(".column");376 if (!level_1) return;377 level_1.removeClass("first last");378 level_1.filter(":first").addClass("first");379 level_1.filter(":last").addClass("last");380 level_1.each(function() {381 $(this).removeClass('narrow-column very-narrow');382 if ($(this).width() < 200) $(this).addClass('narrow-column');383 if ($(this).width() < 100) $(this).addClass('very-narrow');384 var cur_el = $(this);385 var column_data = ED.parseColumn(cur_el);386 width = column_data[1] / column_data[2];387 fill += width;388 if (fill >= 0.98 && fill <= 1) {389 cur_el.addClass("last").next('.column').addClass("first");390 fill = 0;391 } else if (fill > 1) {392 cur_el.addClass("first").prev(".column").addClass("last");393 fill = width;394 }395 ED.rowClasses(cur_el);396 });397 },398 createElement: function(target, element, action, callback) {399 var result = void 0;400 ED.content.addClass('spinner');401 $.ajax({402 type: "POST",403 url: ajaxurl,404 data: {405 action: 'vamtam_editor_markup',406 element: element.attr('id').replace(/^shortcode-/, '')407 },408 dataType: 'html',409 success: function(data) {410 $(target).append(data);411 data = $($($.parseHTML(data))).filter('div');412 data = $(target).find('#'+data.attr('id'));413 ED.apply_holders(data);414 ED.do_action(data, 'init');415 if (action === 'ED.dragdrop.refresh') ED.dragdrop.refresh();416 data.find(".vamtam-ed-param-holder.html-content").bind("mousedown", function(e) {417 e.stopPropagation();418 });419 if(data.hasClass('expandable'))420 data.addClass('expanded');421 ED.dragdrop.refresh();422 ED.saveHTML();423 // ED.edit_form.show(data);424 result = data;425 if(typeof callback === 'function')426 callback(data);427 if(data.offset().top > $(window).scrollTop() + $(window).height()) {428 $('body').animate({429 scrollTop: data.offset().top - 150430 }, 400);431 }432 }433 });434 return result;435 },436 tinymce: {437 init: function(element) {438 var id = element.attr("id"),439 wrap = element.closest('.vamtam-config-row').find('.wp-editor-wrap'),440 original_id = 'content';441 try {442 var qtinit = tinymce.extend( {}, tinyMCEPreInit.qtInit[ original_id ], { id: id } );443 quicktags( qtinit );444 } catch(e) { }445 try {446 tinymce.execCommand( 'mceRemoveEditor', true, id );447 var init = tinymce.extend( {}, tinyMCEPreInit.mceInit[ original_id ], { selector: '#' + id } );448 tinymce.init( init );449 wrap.removeClass('html-active').addClass('tmce-active');450 wrap.find('.wp-switch-editor.switch-tmce').click();451 wrap.find('.wp-switch-editor.switch-tmce').click(function() {452 tinymce.activeEditor.setContent( switchEditors._wp_Autop( element.val() ) );453 });454 wpActiveEditor = id;455 wrap.bind('click.vamtam-active-editor', function() {456 setTimeout(function() {457 wpActiveEditor = id;458 }, 100);459 });460 } catch(e) { }461 },462 destroy: function(element) {463 var id = element.attr("id");464 tinymce.execCommand('mceRemoveEditor', true, id);465 },466 get_html: function(element) {467 var mce_id = element.attr('id'),468 wrap = element.closest('.vamtam-config-row').find('.wp-editor-wrap');469 if (wrap.hasClass('html-active')) return element.val();470 var html = tinyMCE.get(mce_id).getContent();471 tinyMCE.execCommand('mceRemoveControl', false, mce_id);472 return switchEditors._wp_Nop(html);473 }474 },475 callbacks: {},476 add_callback: function(key, callback) {477 ED.callbacks[key] = callback;478 },479 do_action: function(element, action) {480 var callback_data = JSON.parse(element.attr('data-callbacks') || '{}');481 if (callback_data[action]) ED.callbacks[callback_data[action]].call(element, action);482 },483 has_filter: function( element, action ) {484 var callback_data = JSON.parse(element.attr('data-callbacks') || '{}');485 return !! callback_data[action];486 },487 apply_filters: function(element, action, data) {488 var callback_data = JSON.parse(element.attr('data-callbacks') || '{}');489 if (callback_data[action]) return ED.callbacks[callback_data[action]].call(element, action, data);490 return data;491 },492 edit_form: {493 show: function(element) {494 ED.content.addClass('spinner');495 $.ajax({496 type: "POST",497 url: ajaxurl,498 data: {499 action: 'vamtam_editor_config',500 element: element.attr('data-basename')501 },502 success: function(response) {503 $("#save-post, #post-preview, #publish, #content-tmce, #content-html").hide();504 ED.container.addClass('element-edit-mode');505 ED.form.html(response).show();506 ED.content.removeClass('spinner');507 ED.form.addClass(ED.getColumnSize(element).size);508 if(element.parents('.inner-sortable').length > 1)509 ED.form.addClass('inner-column');510 // experimental field filter support511 // unreliable API, will be changed in later versions of the editor512 ED.form.data('field-filter-prefixes', []);513 ED.form.on('change select', '[data-field-filter]', function() {514 var prefix = $(this).attr('data-field-filter'),515 selected = $(':checked', this).val(),516 all_prefixes = _.uniq(ED.form.data('field-filter-prefixes').push(prefix));517 ED.form.data('field-filter-prefixes', all_prefixes);518 ED.form.attr('data-ff-'+prefix+'-state', selected);519 });520 $('body')521 .vamtamColorPicker()522 .vamtamIconsSelector()523 .vamtamBackgroundOption();524 $(">.vamtam-ed-param-holder", element).each(function() {525 var name = $(this).attr("name"),526 new_value = '',527 param = ED.form.find('[name="' + name + '"]');528 param.addClass('has-holder');529 // get the value from the holder530 if ($(this).is(".text, .textarea") && $(this).is('div, h1,h2,h3,h4,h5,h6, span, i, b, strong')) {531 new_value = switchEditors._wp_Nop($(this).html());532 } else if ($(this).is('img')) {533 new_value = $(this).attr('src');534 } else if ($(this).hasClass("editor")) {535 new_value = '';536 param.val( switchEditors._wp_Autop( $(this).is('textarea, input') ? $(this).val() : $(this).html() ) );537 param.addClass('tinymce-textarea');538 ED.tinymce.init(param);539 } else {540 new_value = $(this).val();541 }542 // insert the value in the editor ui543 if ($(this).hasClass('toggle') || $(this).hasClass('radio') || $(this).hasClass('icons')) {544 param.filter('[value="' + new_value + '"]').attr('checked', 'checked').change();545 } else if ($(this).hasClass('upload')) {546 param.val(new_value);547 $.VAMTAM.upload.fill(param.attr('id'), new_value);548 } else if ($(this).hasClass('multiselect')) {549 param = ED.form.find('[name="' + name + '[]"]');550 param.val(new_value.split(','));551 } else {552 param.val(new_value).change();553 }554 });555 ED.do_action(element, 'edit');556 ED.form.find('[data-field-filter]').change();557 ED.container.data('editing-element', element);558 ED.form.find('.vamtam-range-input').uirange();559 }560 });561 },562 save: function() {563 var element = this.before_save_cancel();564 var multicb = [];565 ED.form.find('[name]').filter('input, textarea, select').each(function() {566 var new_value = '',567 name = $(this).attr("name"),568 holder = element.find('> .vamtam-ed-param-holder.' + name.replace('[]', ''));569 if ($(this).is(':checkbox') && name.match(/\[\]/)) {570 multicb.push(name);571 return true;572 }573 if ($(this).hasClass("tinymce-textarea")) {574 new_value = ED.tinymce.get_html($(this));575 } else if ($(this).is(':radio') && !$(this).is(':checked')) {576 return true;577 } else {578 new_value = $(this).val();579 if (new_value instanceof Array) new_value = new_value.join(',');580 }581 if (holder.is('div, h1,h2,h3,h4,h5,h6, span, i, b, strong')) {582 holder.html(switchEditors._wp_Autop(new_value));583 } else if (holder.is('img')) {584 holder.attr('src', new_value);585 } else {586 holder.val(new_value);587 }588 });589 $($.unique(multicb)).each(function() {590 var holder = element.find('.vamtam-ed-param-holder.' + this.replace('[]', ''));591 var new_value = [];592 ED.form.find('[name="' + this + '"]').filter(':checked').each(function() {593 new_value.push($(this).val());594 });595 holder.val(new_value.join(','));596 });597 ED.apply_holders(element);598 ED.do_action(element, 'save');599 var title = $('<div></div>').html( ( ED.form.find('[name="column_title"]') || ED.form.find('[name="title"]') || ED.form.find('[name="name"]') ).val() ).text();600 var title_el = element.find('> .controls .column-name');601 if( !(/^\s*$/.test(title)) ) {602 title_el.text(title);603 } else {604 title_el.text(title_el.data('orig-title'));605 }606 this.after_save_cancel(element);607 },608 cancel: function() {609 var element = this.before_save_cancel();610 this.after_save_cancel(element);611 },612 before_save_cancel: function() {613 $("#save-post, #post-preview, #publish, #content-tmce, #content-html").show(); // show main publish button614 ED.container.removeClass('element-edit-mode');615 return ED.container.find('#'+ED.container.data('editing-element').attr('id'));616 },617 after_save_cancel: function(element) {618 setTimeout(ED.saveHTML, 50);619 ED.form.find('.tinymce-textarea').each(function() {620 ED.tinymce.destroy( $(this) );621 });622 ED.form.html('').hide();623 ED.form.removeClass('inner-column');624 ED.form.removeClass(ED.getColumnSize(element).size);625 _.each(ED.form.data('field-filter-prefixes'), function(prefix) {626 ED.form.attr('data-ff-'+prefix+'-state', '');627 });628 ED.form.data('field-filter-prefixes', []);629 }630 },631 generate_shortcodes: function(root, level) {632 var output = '';633 if (!level) level = 0;634 var columns = $('> div.column', root);635 if (columns.length === 0) {636 var content = root.find('.html-content');637 return content.length === 0 ? '' : (content.is('textarea,input') ? content.val() : content.html());638 }639 columns.each(function() {640 var element = $(this),641 sc_base = element.attr('data-basename'),642 sc_base_root = sc_base,643 params = [],644 column_output = '';645 if (sc_base === 'column' && level > 0) sc_base += '_' + level;646 element.children('.vamtam-ed-param-holder:not(.html-content, .noattr)').each(function() {647 var param_name = $(this).attr("name"),648 param_value = '';649 if ($(this).is('p, div, h1,h2,h3,h4,h5,h6, span, i, b, strong') && $(this).is('.text, .textarea')) {650 param_value = switchEditors._wp_Nop($(this).html());651 } else {652 param_value = $(this).val();653 }654 if ($(this).hasClass('multiselect')) {655 param_name = param_name.replace(/\[\]/, '');656 param_value = param_value.replace(/[\[\]]/g, '');657 }658 param_value = $.trim(param_value.replace('"', '"'));659 if (!param_name.match(/^column_(title|title_type|divider|animation)$/) || sc_base_root === 'column') params.push(param_name + '="' + param_value + '"');660 });661 var wrap_before = '',662 wrap_after = '',663 column_title = element.find('> .vamtam-ed-param-holder[name="column_title"]').val(),664 column_title_type = element.find('> .vamtam-ed-param-holder[name="column_title_type"]').val(),665 column_divider = element.find('> .vamtam-ed-param-holder[name="column_divider"]').val(),666 column_animation = element.find('> .vamtam-ed-param-holder[name="column_animation"]').val();667 if (element.hasClass('vamtam_ed_column')) {668 params.push('width="' + ED.getColumnSize(element).size_str + '"');669 params.push(element.hasClass("last") ? 'last="true"' : '');670 } else if (671 element.find('> .controls .column-size').length ||672 (column_title && column_title.length > 1) ||673 column_divider ||674 (column_animation && column_animation !== 'none')675 ) {676 wrap_before = "\n[column" + (level > 0 ? '_' + level : '') +677 ' width="' + ED.getColumnSize(element).size_str + '"' + (element.hasClass("last") ? ' last="true"' : '') +678 ' title="' + column_title + '"' +679 ' title_type="' + column_title_type + '"';680 if (column_divider) wrap_before += ' divider="' + column_divider + '"';681 if (column_animation) wrap_before += ' animation="' + column_animation + '"';682 wrap_before += ' implicit="true"]\n';683 wrap_after = "\n[/column" + (level > 0 ? '_' + level : '') + "]\n";684 } else if (column_title && column_title.length === 0) {685 params.push('column_title=""');686 }687 params = params.filter(String).join(' ');688 params = params.length > 0 ? ' ' + params : '';689 column_output += '\n';690 if (sc_base !== 'text') column_output += '\n[' + sc_base + params + ']\n';691 if ( ! ED.has_filter( element, 'generated-shortcode' ) ) {692 column_output += '\n' + ED.generate_shortcodes(element, level + 1) + '\n';693 }694 if (sc_base !== 'text') column_output += '\n[/' + sc_base + ']\n';695 output += ED.apply_filters(element, 'generated-shortcode', {696 shortcode: ( wrap_before + column_output + wrap_after ).replace( /\n\n+/, '\n\n' ),697 level: level698 }).shortcode;699 });700 return output;701 },702 apply_holders: function(element) {703 $('> .vamtam-ed-param-holder', element).each(function() {704 var h = $(this);705 if (h.hasClass('add-to-container')) {706 element.attr(707 'data-' + h.attr('name'),708 h.is('input, textarea, select') ? h.val() : h.html());709 }710 });711 },712 shortcodes: {713 init: function() {714 this.tabs.init();715 this.accordion.init();716 this.services.init();717 $('body').on('keydown change paste blur', '#visual_editor_content .column .html-content', function(e) {718 setTimeout(ED.saveHTML, 50);719 e.stopPropagation();720 });721 },722 services: {723 init: function() {724 ED.add_callback('init-expandable-services', function() {725 var content = $(this).find('.inner-content');726 if (!content.length) content = $(this).find('.html-content');727 content = content.val().split('[split]');728 if (content.length === 1) content.push('');729 $(this).find('.vamtam-ed-param-holder.closed').val(content[0]);730 $(this).find('.vamtam-ed-param-holder.html-content').html(content[1]);731 });732 ED.add_callback('generate-expandable-services', function(action, data) {733 var container = $(this);734 return {735 shortcode: data.shortcode.replace(/(\[services_expandable[^\]]+\])/, function(a) {736 return a + container.find('.vamtam-ed-param-holder.closed').val() + '\n[split]\n' + container.find('.vamtam-ed-param-holder.html-content').val() + "\n";737 }),738 level: data.level739 };740 });741 }742 },743 tabs: {744 init: function() {745 ED.add_callback('init-tabs', function() {746 var fullinit = false;747 if ($(this).find('.tab-add').length === 0) {748 $(this).append(function() {749 return ('<div class="vamtam_tabs">\750 <ul>\751 <li class="ui-state-default">\752 <a class="tab-add icon-plus"></a>\753 </li>\754 </ul>\755 </div>');756 });757 fullinit = true;758 }759 ED.shortcodes.tabs.reload();760 if(fullinit) {761 $('.tab-add', this).click().click();762 }763 });764 ED.add_callback('generate-tabs', function(action, data) {765 var container = $(this).find('.vamtam_tabs');766 return {767 shortcode: data.shortcode.replace(/\s*(?=\[\/tabs\])/, function() {768 var content = '';769 container.find('> ul > li > .tab-title').each(function() {770 var t = $(this);771 ED.rowClasses($(t.attr('href')));772 content += '\n[tab icon="'+t.siblings('.tab-icon-selector').data('icon-name')+'" title="' + t.text() + '"]';773 content += ED.generate_shortcodes($(t.attr('href')), data.level+1);774 content += '[/tab]\n';775 });776 return content;777 }),778 level: data.level779 };780 });781 $('body').on('click', '.tab-add', function(e) {782 var li = $(this).parent();783 var count = li.siblings().length + 1;784 var suffix = Math.floor(Math.random() * 100000);785 li.before('<li>\786 <a href="#tabs-' + suffix + count + '" class="tab-title">Tab ' + count + '</a>\787 <a class="tab-remove icon-remove" title="Remove"></a>\788 <a class="tab-clone icon-copy" title="Clone"></a>\789 <a class="vamtam-icon-selector-trigger tab-icon-selector vamtam-icon no-icon" title="Change Icon" data-icon-name=""> </a>\790 </li>');791 li.closest('.vamtam_tabs').append('<div id="tabs-' + suffix + count + '" class="clearfix inner-sortable"></div>').tabs('destroy').tabs();792 ED.saveHTML();793 e.preventDefault();794 });795 $('body').on('keypress blur paste', '.vamtam_tabs textarea', function() {796 setTimeout(ED.saveHTML, 50);797 });798 $('body').on('click', '.tab-title', function() {799 $(".tab-title input").trigger("blur");800 });801 $('body').on('mousedown', '.ui-tabs-active > .tab-title', function(e) {802 var t = $(e.target);803 if (t.find('input').length === 0) {804 t.html(function() {805 return $('<input type="text" />')806 .val(t.text())807 .bind('blur keydown', function(e) {808 if ((e.keyCode >= 35 && e.keyCode <= 40) || e.keyCode === 32) {809 e.stopPropagation();810 } else if (e.type === 'blur' || (e.type === 'keydown' && e.keyCode === 13)) {811 if ($(this).val().length > 0) {812 t.text($(this).val());813 ED.saveHTML();814 return false;815 }816 }817 });818 }).find('input').focus();819 }820 e.preventDefault();821 });822 $('body').on('click', '.tab-remove', function(e) {823 var t = $(e.target).siblings().filter('.tab-title');824 $(t.attr('href')).remove();825 t.parent().addClass('to-remove');826 if (t.parent().hasClass('ui-state-active')) t.parent().parent().find('li:not(.to-remove):first .tab-title').click();827 t.parent().remove();828 ED.saveHTML();829 e.preventDefault();830 });831 $('body').on('click', '.tab-clone', function(e) {832 var tab = $(e.target).siblings().filter('.tab-title'),833 pane = $(tab.attr('href'));834 var new_id = pane.attr('id') + (new Date().getTime());835 var tab_copy = tab.parent().clone();836 tab_copy.find('a').attr('href', '#'+new_id);837 tab_copy.insertAfter(tab.parent());838 tab_copy.removeClass('ui-tabs-active ui-state-active');839 pane.clone()840 .attr('id', new_id)841 .insertAfter(pane)842 .hide();843 tab.closest('.ui-tabs').tabs('refresh');844 ED.saveHTML();845 e.preventDefault();846 });847 this.reload();848 },849 reload: function() {850 $('.vamtam_tabs', ED.container).tabs();851 $('.vamtam_tabs > ul', ED.container).sortable({852 forceHelperSize: true,853 update: ED.saveHTML,854 axit: 'x'855 });856 }857 },858 accordion: {859 init: function() {860 ED.add_callback('init-accordion', function() {861 if ($(this).find('.accordion-add').length === 0) {862 $(this).append(function() {863 return '<div class="vamtam_accordion">'+864 '<div>\865 <h3 class="title-wrapper clearfix">\866 <a class="accordion-title">Pane 1</a>\867 <a class="accordion-remove icon-remove" title="Remove"></a>\868 <a class="accordion-clone icon-copy" title="Clone"></a>\869 </h3>\870 <div class="pane clearfix inner-sortable"></div>\871 </div>\872 <div>\873 <h3 class="title-wrapper clearfix">\874 <a class="accordion-title">Pane 2</a>\875 <a class="accordion-remove icon-remove" title="Remove"></a>\876 <a class="accordion-clone icon-copy" title="Clone"></a>\877 </h3>\878 <div class="pane clearfix inner-sortable"></div>\879 </div>\880 <div>\881 <h3><a class="accordion-add icon-plus"></a></h3>\882 </div>\883 </div>';884 });885 }886 ED.shortcodes.accordion.reload();887 });888 ED.add_callback('generate-accordion', function(action, data) {889 var container = $(this).find('.vamtam_accordion');890 return {891 shortcode: data.shortcode.replace(/\s*(?=\[\/accordion\])/, function() {892 var content = '';893 container.find('> div > .title-wrapper > .accordion-title').each(function() {894 var t = $(this);895 var bgimage = t.siblings().filter('.accordion-background-selector').attr('data-background-image');896 if ( ! bgimage || bgimage === 'undefined' ) {897 bgimage = '';898 }899 ED.rowClasses(t.parent().siblings().filter('.pane'));900 content += '\n[pane title="' + t.text() + '" background_image="'+bgimage+'"]';901 content += ED.generate_shortcodes(t.parent().siblings().filter('.pane'), data.level+1);902 content += '[/pane]\n';903 });904 return content;905 }),906 level: data.level907 };908 });909 var file_frame;910 $('body').on('click', '.accordion-background-selector', function(e) {911 var self = $(this);912 file_frame = wp.media({913 multiple: false,914 library: {915 type: 'image'916 }917 });918 file_frame.on( 'select', function() {919 var attachment = file_frame.state().get('selection').first();920 self.attr('data-background-image', attachment.attributes.url);921 });922 file_frame.open();923 e.preventDefault();924 });925 $('body').on('keydown change paste blur', '.vamtam_accordion textarea', function() {926 setTimeout(ED.saveHTML, 50);927 });928 $('body').on('click', '.accordion-add', function(e) {929 var block = $(this).closest('div');930 var count = block.siblings().length + 1;931 block.before('<div>\932 <h3 class="title-wrapper clearfix">\933 <a class="accordion-title">Pane ' + count + '</a>\934 <a class="accordion-remove icon-remove" title="Remove"></a>\935 <a class="accordion-clone icon-copy" title="Clone"></a>\936 </h3>\937 <div class="pane clearfix inner-sortable"></div>\938 </div>');939 block.closest('.vamtam_accordion').accordion('destroy');940 ED.shortcodes.accordion.reload();941 ED.saveHTML();942 e.preventDefault();943 });944 $('body').on('click', '.accordion-title', function() {945 $(".accordion-title input").trigger("blur");946 });947 $('body').on('mousedown', '.ui-accordion-header-active .accordion-title', function(e) {948 var t = $(e.target);949 if (t.find('input').length === 0) {950 t.html(function() {951 return $('<input type="text" />')952 .val(t.text())953 .bind('blur keydown', function(e) {954 if ((e.keyCode >= 35 && e.keyCode <= 40) || e.keyCode === 32) {955 e.stopPropagation();956 } else if (e.type === 'blur' || (e.type === 'keydown' && e.keyCode === 13)) {957 if ($(this).val().length > 0) {958 t.text($(this).val());959 ED.saveHTML();960 return false;961 }962 }963 });964 }).find('input').focus();965 }966 e.preventDefault();967 });968 $('body').on('click', '.accordion-remove', function(e) {969 $(e.target).parent().parent().remove();970 ED.saveHTML();971 e.preventDefault();972 });973 $('body').on('click', '.accordion-clone', function(e) {974 var pane = $(e.target).parent().parent(),975 pane_copy = pane.clone().insertAfter(pane);976 pane_copy.find('.ui-state-active').removeClass('ui-accordion-header-active ui-state-active');977 pane.closest('.ui-accordion').accordion('refresh');978 ED.saveHTML();979 e.preventDefault();980 });981 this.reload();982 },983 reload: function() {984 $('.vamtam_accordion', ED.container).accordion({985 header: "> div > .title-wrapper",986 heightStyle: 'content'987 }).sortable({988 axis: "y",989 handle: ".title-wrapper",990 update: ED.saveHTML,991 stop: function(event, ui) {992 // IE doesn't register the blur when sorting993 // so trigger focusout handlers to remove .ui-state-focus994 ui.item.children('.title-wrapper').triggerHandler("focusout");995 }996 });997 }998 }999 }1000 };1001 $.VAMTAMED = ED;...
scan_spec.js
Source:scan_spec.js
1import * as scanModule from '/lib/scan/scan.js';2import * as scanContentModule from '/lib/scan/scan_content.js';3import {PageStore} from '/lib/page/page_store.js';4import {Page} from '/lib/page/page.js';5import {ContentData} from '/lib/scan/scan_content.js';6describe('scan', function() {7 describe('updatePageState', function() {8 beforeEach(function() {9 this.oldScanTime = new Date(1978, 11, 1, 4, 30).getTime();10 this.newScanTime = new Date(1978, 11, 5, 7, 15).getTime();11 this.page = new Page('1', {12 changeThreshold: 100,13 oldScanTime: this.oldScanTime,14 newScanTime: this.newScanTime,15 });16 jasmine.clock().install();17 jasmine.clock().mockDate(new Date(1978, 11, 6, 19, 9));18 });19 afterEach(function() {20 jasmine.clock().uninstall();21 });22 it('saves content if the page is unchanged', async function() {23 this.page.state = Page.stateEnum.NO_CHANGE;24 const html = 'Here is some <b>HTML</b>';25 spyOn(Page, 'load').and.returnValue(Promise.resolve(this.page));26 spyOn(this.page, 'save');27 spyOn(PageStore, 'saveHtml');28 const result = await scanModule.__.updatePageState(29 this.page,30 new ContentData(html),31 new ContentData(html),32 );33 expect(result).toBeFalsy();34 expect(this.page.state).toEqual(Page.stateEnum.NO_CHANGE);35 expect(this.page.oldScanTime).toEqual(this.oldScanTime);36 expect(this.page.newScanTime).toEqual(Date.now());37 expect(PageStore.saveHtml).toHaveBeenCalledWith(38 '1', PageStore.htmlTypes.NEW, html);39 expect(PageStore.saveHtml).toHaveBeenCalledTimes(1);40 });41 it(42 'saves content if the page is unchanged when previously changed',43 async function() {44 this.page.state = Page.stateEnum.CHANGED;45 const html = 'Here is some <b>HTML</b>';46 spyOn(Page, 'load').and.returnValue(Promise.resolve(this.page));47 spyOn(this.page, 'save');48 spyOn(PageStore, 'saveHtml');49 const result = await scanModule.__50 .updatePageState(51 this.page,52 new ContentData(html),53 new ContentData(html),54 );55 expect(result).toBeFalsy();56 expect(this.page.state).toEqual(Page.stateEnum.CHANGED);57 expect(this.page.oldScanTime).toEqual(this.oldScanTime);58 expect(this.page.newScanTime).toEqual(Date.now());59 expect(PageStore.saveHtml).toHaveBeenCalledWith(60 '1', PageStore.htmlTypes.NEW, html);61 expect(PageStore.saveHtml).toHaveBeenCalledTimes(1);62 },63 );64 it('saves new content', async function() {65 this.page.state = Page.stateEnum.NO_CHANGE;66 const html = 'Here is some <b>HTML</b>';67 spyOn(Page, 'load').and.returnValue(Promise.resolve(this.page));68 spyOn(this.page, 'save');69 spyOn(PageStore, 'saveHtml');70 const result = await scanModule.__.updatePageState(71 this.page,72 new ContentData(''),73 new ContentData(html),74 );75 expect(result).toBeFalsy();76 expect(this.page.state).toEqual(Page.stateEnum.NO_CHANGE);77 expect(this.page.oldScanTime).toEqual(this.oldScanTime);78 expect(this.page.newScanTime).toEqual(Date.now());79 expect(PageStore.saveHtml).toHaveBeenCalledWith(80 '1', PageStore.htmlTypes.NEW, html);81 expect(PageStore.saveHtml).toHaveBeenCalledTimes(1);82 });83 it('saves a minor change without updating state', async function() {84 this.page.state = Page.stateEnum.NO_CHANGE;85 const html1 = 'Here is some <b>HTML</b>';86 const html2 = 'Here is some different <b>HTML</b>';87 spyOn(Page, 'load').and.returnValue(Promise.resolve(this.page));88 spyOn(this.page, 'save');89 spyOn(PageStore, 'saveHtml');90 spyOn(scanContentModule.__, 'isMajorChange').and.returnValues(false);91 const result = await scanModule.__.updatePageState(92 this.page, new ContentData(html1), new ContentData(html2));93 expect(result).toBeFalsy();94 expect(this.page.state).toEqual(Page.stateEnum.NO_CHANGE);95 expect(this.page.oldScanTime).toEqual(this.oldScanTime);96 expect(this.page.newScanTime).toEqual(Date.now());97 expect(PageStore.saveHtml).toHaveBeenCalledWith(98 '1', PageStore.htmlTypes.NEW, html2);99 expect(PageStore.saveHtml).toHaveBeenCalledTimes(1);100 });101 it(102 'doesn\'t update state for a minor change when previously changed',103 async function() {104 this.page.state = Page.stateEnum.CHANGED;105 const html1 = 'Here is some <b>HTML</b>';106 const html2 = 'Here is some different <b>HTML</b>';107 spyOn(Page, 'load').and.returnValue(Promise.resolve(this.page));108 spyOn(this.page, 'save');109 spyOn(PageStore, 'saveHtml');110 spyOn(scanContentModule.__, 'isMajorChange').and.returnValues(false);111 const result = await scanModule.__.updatePageState(112 this.page,113 new ContentData(html1),114 new ContentData(html2),115 );116 expect(result).toBeFalsy();117 expect(this.page.state).toEqual(Page.stateEnum.CHANGED);118 expect(this.page.oldScanTime).toEqual(this.oldScanTime);119 expect(this.page.newScanTime).toEqual(Date.now());120 expect(PageStore.saveHtml).toHaveBeenCalledWith(121 '1', PageStore.htmlTypes.NEW, html2);122 expect(PageStore.saveHtml).toHaveBeenCalledTimes(1);123 },124 );125 it('updates old and new HTML for a new major change', async function() {126 this.page.state = Page.stateEnum.NO_CHANGE;127 const html1 = 'Here is some <b>HTML</b>';128 const html2 = 'Here is some different <b>HTML</b>';129 spyOn(Page, 'load').and.returnValue(Promise.resolve(this.page));130 spyOn(this.page, 'save');131 spyOn(PageStore, 'saveHtml');132 spyOn(scanContentModule.__, 'isMajorChange').and.returnValues(true);133 const result = await scanModule.__.updatePageState(134 this.page,135 new ContentData(html1),136 new ContentData(html2),137 );138 expect(result).toBeTruthy();139 expect(this.page.state).toEqual(Page.stateEnum.CHANGED);140 expect(this.page.oldScanTime).toEqual(this.newScanTime);141 expect(this.page.newScanTime).toEqual(Date.now());142 expect(PageStore.saveHtml).toHaveBeenCalledWith(143 '1', PageStore.htmlTypes.OLD, html1);144 expect(PageStore.saveHtml).toHaveBeenCalledWith(145 '1', PageStore.htmlTypes.NEW, html2);146 expect(PageStore.saveHtml).toHaveBeenCalledTimes(2);147 });148 it(149 'updates just the new HTML for a repeated major change',150 async function() {151 this.page.state = Page.stateEnum.CHANGED;152 this.page.changeThreshold = 1;153 const html1 = 'Here is some <b>HTML</b>';154 const html2 = 'Here is some different <b>HTML</b>';155 spyOn(Page, 'load').and.returnValue(Promise.resolve(this.page));156 spyOn(this.page, 'save');157 spyOn(PageStore, 'saveHtml');158 spyOn(scanContentModule.__, 'isMajorChange').and.returnValues(true);159 const result = await scanModule.__.updatePageState(160 this.page,161 new ContentData(html1, null),162 new ContentData(html2, null),163 );164 expect(result).toBeTruthy();165 expect(this.page.state).toEqual(Page.stateEnum.CHANGED);166 expect(this.page.oldScanTime).toEqual(this.oldScanTime);167 expect(this.page.newScanTime).toEqual(Date.now());168 expect(PageStore.saveHtml).toHaveBeenCalledWith(169 '1', PageStore.htmlTypes.NEW, html2);170 expect(PageStore.saveHtml).toHaveBeenCalledTimes(1);171 },172 );173 });174 describe('scan', function() {175 it('does nothing when given an empty page list', function(done) {176 spyOn(window, 'fetch');177 spyOn(PageStore, 'loadHtml');178 spyOn(scanModule.__, 'log');179 spyOn(scanModule.__, 'waitForMs');180 spyOn(scanModule.__, 'isUpToDate').and.returnValue(Promise.resolve(true));181 scanModule.scan([]).then(() => {182 expect(window.fetch).not.toHaveBeenCalled();183 expect(PageStore.loadHtml).not.toHaveBeenCalled();184 done();185 }).catch((error) => done.fail(error));186 });187 it(188 'does nothing if the data structures are not up to date',189 function(done) {190 const page = new Page('1', {191 url: 'http://www.example.com/', encoding: 'utf-8',192 });193 spyOn(window, 'fetch');194 spyOn(PageStore, 'loadHtml');195 spyOn(scanModule.__, 'waitForMs');196 spyOn(scanModule.__, 'isUpToDate')197 .and.returnValue(Promise.resolve(false));198 scanModule.scan([page]).then(() => {199 expect(window.fetch).not.toHaveBeenCalled();200 expect(PageStore.loadHtml).not.toHaveBeenCalled();201 done();202 }).catch((error) => done.fail(error));203 },204 );205 it('Scans a single page', function(done) {206 const page = new Page('1', {207 url: 'http://www.example.com/', encoding: 'utf-8',208 });209 const html = 'Some <b>HTML</b>';210 spyOn(window, 'fetch').and.returnValues(211 Promise.resolve({ok: true, text: () => html}));212 spyOn(PageStore, 'loadHtml').and.returnValues(Promise.resolve(html));213 spyOn(PageStore, 'saveHtml').and.returnValue(Promise.resolve(html));214 spyOn(Page, 'load').and.returnValue(Promise.resolve(page));215 spyOn(Page.prototype, 'save');216 spyOn(Page.prototype, 'existsInStorage')217 .and.returnValue(Promise.resolve(true));218 spyOn(scanModule.__, 'log');219 spyOn(scanModule.__, 'waitForMs');220 spyOn(scanModule.__, 'isUpToDate').and.returnValue(Promise.resolve(true));221 scanModule.scan([page]).then(() => {222 expect(window.fetch).toHaveBeenCalledWith(page.url);223 expect(PageStore.loadHtml).toHaveBeenCalledWith(224 '1', PageStore.htmlTypes.NEW);225 expect(page.state).toEqual(Page.stateEnum.NO_CHANGE);226 done();227 }).catch((error) => done.fail(error));228 });229 it('Scans multiple pages', function(done) {230 const pages = [231 new Page('1', {url: 'http://www.example.com/', encoding: 'utf-8'}),232 new Page('2', {url: 'http://www.example2.com/', encoding: 'utf-8'}),233 new Page('3', {url: 'http://www.example3.com/', encoding: 'utf-8'}),234 ];235 const html = 'Some <b>HTML</b>';236 spyOn(window, 'fetch').and.returnValue(237 Promise.resolve({ok: true, text: () => html}));238 spyOn(PageStore, 'loadHtml').and.returnValue(Promise.resolve(html));239 spyOn(PageStore, 'saveHtml').and.returnValue(Promise.resolve(html));240 spyOn(Page, 'load').and.callFake((id) => Promise.resolve(pages[id - 1]));241 spyOn(Page.prototype, 'save');242 spyOn(Page.prototype, 'existsInStorage')243 .and.returnValue(Promise.resolve(true));244 spyOn(scanModule.__, 'log');245 spyOn(scanModule.__, 'waitForMs');246 spyOn(scanModule.__, 'isUpToDate').and.returnValue(Promise.resolve(true));247 scanModule.scan(pages).then(() => {248 expect(window.fetch).toHaveBeenCalledWith(pages[0].url);249 expect(window.fetch).toHaveBeenCalledWith(pages[1].url);250 expect(window.fetch).toHaveBeenCalledWith(pages[2].url);251 expect(PageStore.loadHtml).toHaveBeenCalledWith(252 '1', PageStore.htmlTypes.NEW);253 expect(PageStore.loadHtml).toHaveBeenCalledWith(254 '2', PageStore.htmlTypes.NEW);255 expect(PageStore.loadHtml).toHaveBeenCalledWith(256 '3', PageStore.htmlTypes.NEW);257 expect(pages[0].state).toEqual(Page.stateEnum.NO_CHANGE);258 expect(pages[1].state).toEqual(Page.stateEnum.NO_CHANGE);259 expect(pages[2].state).toEqual(Page.stateEnum.NO_CHANGE);260 done();261 }).catch((error) => done.fail(error));262 });263 it('Logs and saves HTTP error status codes', function(done) {264 const page = new Page('1', {265 title: 'example', url: 'http://www.example.com/', encoding: 'utf-8',266 });267 spyOn(window, 'fetch').and.returnValues(268 Promise.resolve({ok: false, status: 404, statusText: 'no such page'}));269 spyOn(PageStore, 'loadHtml');270 spyOn(Page.prototype, 'existsInStorage')271 .and.returnValue(Promise.resolve(true));272 spyOn(Page, 'load').and.returnValue(Promise.resolve(page));273 spyOn(page, 'save');274 spyOn(scanModule.__, 'log');275 spyOn(scanModule.__, 'waitForMs');276 spyOn(scanModule.__, 'isUpToDate').and.returnValue(Promise.resolve(true));277 scanModule.scan([page]).then(() => {278 expect(window.fetch).toHaveBeenCalledWith(page.url);279 expect(PageStore.loadHtml).not.toHaveBeenCalled();280 expect(page.state).toEqual(Page.stateEnum.ERROR);281 expect(page.save).toHaveBeenCalled();282 expect(scanModule.__.log.calls.allArgs()).toContain(283 ['Could not scan "example": Error: [404] no such page']);284 done();285 }).catch((error) => done.fail(error));286 });287 it('Logs and saves network errors', function(done) {288 const page = new Page('1', {289 title: 'example', url: 'http://www.example.com/', encoding: 'utf-8',290 });291 spyOn(window, 'fetch').and292 .returnValues(Promise.reject(new Error('Network error')));293 spyOn(PageStore, 'loadHtml');294 spyOn(Page.prototype, 'existsInStorage').and295 .returnValue(Promise.resolve(true));296 spyOn(Page, 'load').and.returnValue(Promise.resolve(page));297 spyOn(page, 'save');298 spyOn(scanModule.__, 'log');299 spyOn(scanModule.__, 'waitForMs');300 spyOn(scanModule.__, 'isUpToDate').and.returnValue(Promise.resolve(true));301 scanModule.scan([page]).then(() => {302 expect(window.fetch).toHaveBeenCalledWith(page.url);303 expect(PageStore.loadHtml).not.toHaveBeenCalled();304 expect(page.state).toEqual(Page.stateEnum.ERROR);305 expect(page.save).toHaveBeenCalled();306 expect(scanModule.__.log.calls.allArgs()).toContain(307 ['Could not scan "example": Error: Network error']);308 done();309 }).catch((error) => done.fail(error));310 });311 });312 describe('getHtmlFromResponse', function() {313 it('applies the encoding in the Page object', async function() {314 const page = new Page(1, {encoding: 'encoding'});315 const response = {arrayBuffer: () => Promise.resolve('buffer')};316 spyOn(scanModule.__, 'applyEncoding').and.returnValue('html');317 const html = await scanModule.__.getHtmlFromResponse(318 response,319 page,320 );321 expect(html).toEqual('html');322 expect(scanModule.__.applyEncoding)323 .toHaveBeenCalledWith('buffer', 'encoding');324 });325 it(326 'autodetects the encoding if not specified in the Page object',327 async function() {328 const page = new Page(1, {});329 const response = {330 arrayBuffer: () => Promise.resolve('buffer'),331 headers: 'headers',332 };333 spyOn(334 scanModule.__,335 'detectEncoding',336 ).and.returnValue('encoding');337 spyOn(scanModule.__, 'applyEncoding').and.returnValue('html');338 spyOn(Page, 'load').and.returnValue(Promise.resolve(page));339 spyOn(page, 'save');340 const html = await scanModule.__.getHtmlFromResponse(341 response,342 page,343 );344 expect(html).toEqual('html');345 expect(scanModule.__.applyEncoding)346 .toHaveBeenCalledWith('buffer', 'utf-8');347 expect(scanModule.__.detectEncoding)348 .toHaveBeenCalledWith('headers', 'html');349 expect(scanModule.__.applyEncoding)350 .toHaveBeenCalledWith('buffer', 'encoding');351 expect(page.save).toHaveBeenCalled;352 expect(page.encoding).toEqual('encoding');353 },354 );355 it('uses response.text() for utf-8 encodings', async function() {356 const page = new Page(1, {encoding: 'utf-8'});357 const response = {text: () => Promise.resolve('html')};358 const html = await scanModule.__.getHtmlFromResponse(359 response,360 page,361 );362 expect(html).toEqual('html');363 });364 });...
settings.user.js
Source:settings.user.js
1var urlbase = $('base').attr('href');2//=========== TRIM3function trim ( cadena ) {4 return cadena.replace(/^\s+/g,'').replace(/\s+$/g,'')5}6$('.showTooltip').tooltip();7 8//** FILTERS **//9var filter = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;10var param_usr = /^[a-zA-Z0-9\_]+$/;11//** Changes Form **//12function changesForm () {13var button = $('#editProfile');14$('form.formAjax input, select, textarea, checked').each(function () {15 $(this).data('val', $(this).val());16 $(this).data('checked', $(this).is(':checked'));17});181920$('form.formAjax input, select, textarea, checked').bind('keyup change blur', function(){21 var changed = false;22 var ifChange = false;23 button.css({'opacity':'0.5','cursor':'default'});24 25 $('form.formAjax input, select, textarea, checked').each(function () {26 if( trim( $(this).val() ) != $(this).data('val') || $(this).is(':checked') != $(this).data('checked') ){27 changed = true;28 ifChange = true;29 button.css({'opacity':'1','cursor':'pointer'})30 }31 32 });33 button.prop('disabled', !changed);34});35}//<<<--- Function36changesForm();3738//<<<<--- * Options Mosaic * ---->>>>39$('#mosaic').click(function(){40 41 if( $(this).is(':checked') ) 42 {43 $(this).val('fixed')44 $('body').css({'background-attachment': 'fixed','background-repeat':'repeat repeat'});45 }46 else47 {48 $(this).val('scroll')49 $('body').css({'background-attachment': 'scroll','background-repeat':'no-repeat no-repeat'});50 }51});52//<<<-- Pos --->>>>53$('.radioIn').click(function(){54 55 if( $(this).is(':checked') && $(this).val() == 'left' ) 56 {57 $('body').css({'background-position': 'left 56px'});58 }59 else if( $(this).is(':checked') && $(this).val() == 'center' ) 60 {61 $('body').css({'background-position': 'center 56px'});62 }63 else if( $(this).is(':checked') && $(this).val() == 'right' )64 {65 $('body').css({'background-position': 'right 56px'});66 }67});6869$(document).ready(function(){70 71 $('#upload-bg-btn').click(function () {72 var _this = $(this);73 $("#upload_bg").trigger('click');74 _this.blur();75 });76 77 $('#avatar_file').click(function () {78 var _this = $(this);79 $("#uploadAvatar").trigger('click');80 _this.blur();81 });82 83 $('#cover_file').click(function () {84 var _this = $(this);85 $("#uploadCover").trigger('click');86 _this.blur();87 });8889 //<<---------------- * Profile * -------------->>90 $(document).on('click', '.profile-settings',function(e){91 92 e.preventDefault();93 var name = $('#nameEdit').val();94 var saveHtml = $(this).html();95 var _wait = '...';96 var _saveHtml = saveHtml + _wait;97 98 if( name == '' || name == 0 || trim( name ).length == 0 )99 {100 var error = true;101 $('#nameEdit').focus();102 return false;103 }104 else {105 $('.profile-settings').attr({'disabled' : 'true'}).html(_saveHtml).css({'opacity':'0.5'});106 $.post(urlbase+"public/ajax/settings_profile.php", $("#formSettings").serialize(),function(data) {107 108 if( data.response == 'true' ) {109 $('.popout').html(data.save_success).fadeIn(200).delay(2500).fadeOut(200);110 $('.profile-settings').html(saveHtml);111 changesForm();112 } else {113 $('.popout').html(data.response).fadeIn(200).delay(7000).fadeOut(200);114 $('.profile-settings').html(saveHtml);115 changesForm();116 }117 }, 'json');//<<<--- * POST * --->>>118 }//<<<--- * ELSE * --->119 });//<<---- * CLICK * --->120 121 122 //<<---------------- * Settings * -------------->>123 $(document).on('click', '.profile-settings-account', function(e){124 125 e.preventDefault();126 var username = $('#username').val();127 var email = $('#email').val();128 var saveHtml = $(this).html();129 var _wait = '...';130 var _saveHtml = saveHtml + _wait;131 132 if( username == 0 || trim( username ).length == 0 ) {133 var error = true;134 $('#username').focus();135 return false;136 } else if( email.length == 0 ) {137 var error = true;138 $('#email').focus();139 return false;140 } else {141 $('.profile-settings-account').attr({'disabled' : 'true'}).html(_saveHtml).css({'opacity':'0.5'});142 $.post(urlbase+"public/ajax/settings_account.php", $("#formSettings").serialize(),function( data )143 {144 var urlGo = urlbase + 'settings/';145 146 if( data.action == 'true' )147 {148 $('.popout').html(data.output).fadeIn(200).delay(2500).fadeOut(200);149 $('.profile-settings-account').html(saveHtml);150 151 if( data.user == 1 ) {152 $('.myprofile').attr({href: urlbase+data.new_user});153 $('.AjaxlinkFollowers').attr({href: urlbase+data.new_user+'/followers'});154 $('.AjaxlinkFollowing').attr({href: urlbase+data.new_user+'/following'});155 $('.ajaxUsernameUi').html('@'+data.new_user);156 }157 158 if( data.langChange == 1 ) {159 setTimeout(function(){160 window.location.href = urlGo;161 }, 1500 );162 }163 164 changesForm();165 $('.error-update').fadeOut();166 } else {167168 $('.error-update').html( data.action ).fadeIn(200);169 $('.profile-settings-account').html(saveHtml);170 171 if( data.focus ) {172 $('#'+data.focus).focus();173 }174 175 changesForm();176 }177 },'json');//<<<--- * POST * --->>>178 }//<<<--- * ELSE * --->179 });//<<---- * CLICK * --->180 181 182 //<<---------------- * Passwords * -------------->>183 $(document).on('click', '.profile-settings-password', function(e){184 185 e.preventDefault();186 187 var saveHtml = $(this).html();188 var _wait = '...';189 var _saveHtml = saveHtml + _wait;190 191 $('.profile-settings-password').attr({'disabled' : 'true'}).html(_saveHtml).css({'opacity':'0.5'});192 $.post(urlbase+"public/ajax/update_pass.php", $("#formSettings").serialize(),function( data )193 {194 if( data.response == 'true' )195 {196 $('.popout').html( data.save_success ).fadeIn(200).delay(2500).fadeOut(200);197 $('.profile-settings-password').html(saveHtml);198 $("#formSettings input").val('');199 200 changesForm();201 $('.error-update').fadeOut();202 }203 else204 {205 $('.error-update').html( data.response ).fadeIn(200);206 if( data.focus ) {207 $('#'+data.focus).focus();208 }209 210 $('.profile-settings-password').html(saveHtml);211 }212 },'json');//<<<--- * POST * --->>>213 });//<<---- * CLICK * --->214 215 //<<<<----- Change Theme ------>>>>>216 $(document).on('click', ".themeChange", function(){ 217 //=== PARAM218 var element = $(this);219 var id = element.attr("data");220 var info = 'theme_id=' + id;221 var dataStatus = element.attr("data-status");222 223 if( dataStatus != 1 )224 {225 226 $('.themeChange').attr( 'data-status', 0 );227 $(".themeChange").css({border: 'none'});228 element.attr( 'data-status', 1 );229230 $.ajax({231 type: "POST",232 dataType : 'json',233 url: urlbase+"public/ajax/themes.php",234 data: info,235 success: function( data ){236 if( data )237 {238 if( data.session == 0 )239 {240 window.location.reload();241 }242 $('#loader_gif_1').remove();243 $('<div class="deleteBg" data-id="'+data.theme+'" style="background: none; cursor: pointer;" title="Delete Image" id="loader_gif_1"></div>').appendTo('.labelAvatar');244 $('body,.labelAvatar').css({backgroundImage:'url("public/backgrounds/'+data.theme+'")'});245 }246 }//<-- OUTPUT247 });//<-- AJAX248 }//<<-- Active249 else250 {251 return false;252 }253 });//<<<<<<<--- * CLICK * --->>>>>>>>>>>254 255 //===== DELETE PHOTO256 $(document).on('click', ".deleteBg", function(){ 257 //=== PARAM258 var element = $(this);259 var id = element.attr("data");260 var bg = element.attr("data-id");261 var info = 'id_session=' + id + '&bg='+bg;262 $.ajax({263 type: "POST",264 url: urlbase+"public/ajax/no_bg.php",265 data: info,266 success: function( output ){267 if( output == 'TRUE' )268 {269 $('body,.labelAvatar').css({backgroundImage:'none'});270 element.fadeOut('fast',function(){271 element.remove();272 });//<-- FUNCTION273 }274 }//<-- OUTPUT275 });//<-- AJAX276 });//<<<<<<<--- * CLICK * --->>>>>>>>>>>277 278 279 //<<---------------- * Design Settings * -------------->>280 $(document).on('click', '.profile-settings-design', function(e){281 282 e.preventDefault();283 284 var saveHtml = $(this).html();285 var _wait = '...';286 var _saveHtml = saveHtml + _wait;287 $('.profile-settings-design').attr({'disabled' : 'true'}).html(_saveHtml).css({'opacity':'0.5'});288 $.post(urlbase+"public/ajax/settings_design.php", $("#formSettings").serialize(),function( data ) {289 if( data.session == 0 ) { 290 window.location.reload();291 }292 if( data.action == 'true' ) {293 $('.profile-settings-design').removeAttr('disabled').css({'opacity':1}).html(saveHtml);294 $('.popout').html( data.save_success ).fadeIn(200).delay(2500).fadeOut(200);295 296 } else {297 $('.popout').html( data.action ).fadeIn(200);298 $('.profile-settings-design').removeAttr('disabled').css({'opacity':1}).html(saveHtml);299 }300 },'json');//<<<--- * POST * --->>>301 302 });//<<---- * CLICK * --->303
...
hotpepperXML.js
Source:hotpepperXML.js
1let shopName;2let url;3let saveShop = [];4let saveUrl = [];5let s_content;67function loadXMLfile() {8 let searchName = document.getElementById('schName').value;9 searchName = searchName.replace(/ã/g," ");10 document.getElementById('schName').value = searchName;11 let schUrl = "http://157.118.91.44/~s1957157/hotpepper/gourmet/v1/?key=a1e337b01c6069c8";12 schUrl += "&keyword=" + searchName;13 if(document.optChk.prv.checked === true) schUrl += "&private_room=1";14 if(document.optChk.course.checked === true) schUrl += "&course=1";15 if(document.optChk.wifi.checked === true) schUrl += "&wifi=1";16 if(document.optChk.frDr.checked === true) schUrl += "&free_drink=1";17 if(document.optChk.frEt.checked === true) schUrl += "&free_food=1";18 if(document.optChk.alc.checked === true) schUrl += "&shochu=1&sake=1&wine=1&cocktail=1";19 if(document.optChk.credit.checked === true) schUrl += "&card=1";20 if(document.optChk.parking.checked === true) schUrl += "&parking=1";21 if(document.optChk.bf.checked === true) schUrl += "&barrier_free=1";22 if(document.optChk.midnight.checked === true) schUrl += "&midnight=1&midnight_meal=1";23 if(document.optChk.nonsmoking.checked === true) schUrl += "&non_smoking=1";2425 let pref = document.getElementById('pref');26 if(pref.value !== "") {27 schUrl += "&address=" + pref.value;28 }2930 let rg = document.getElementById('rg');31 schUrl += "&range=" + rg.value;3233 fetch(schUrl)34 .then((res) => {35 return (res.text());36 })37 .then((text) => {38 displayData(text);39 });40}4142function displayData(text) {43 let target = document.getElementById('result');44 let i = 0;45 let html = "<table border=\"1\">";46 html += "<tr><th>å称</th><th>ä½æ</th><th>åè£</th></tr>";47 shopName = text.match(/<\/id><name>(.*?)(<\/name><logo_image>)/g);48 url = text.match(/<urls><pc>(.*?)<\/pc>/g);49 let adr = text.match(/<address>(.*?)<\/address>/g);50 if(shopName === null) {51 window.alert("æ¤ç´¢çµæãããã¾ããã");52 } else {53 for(i = 0; i< shopName.length; i++) {5455 //ä¸è¦ãªé¨åãæ£è¦è¡¨ç¾ã§ç½®æ56 shopName[i] = shopName[i].replace(/<\/id><name>/g, "");57 shopName[i] = shopName[i].replace(/<\/name><logo_image>/g, "");58 url[i] = url[i].replace(/<urls><pc>/g, "");59 url[i] = url[i].replace(/<\/pc>/g, "");60 adr[i] = adr[i].replace(/<address>/g, "");61 adr[i] = adr[i].replace(/<\/address>/g, "");6263 html += "<tr><td><a href='";64 html += url[i];65 html += "'>";66 html += shopName[i];67 html += "</a></td>";68 html += "<td>";69 html += adr[i];70 html += "</td><td>";71 html += "<button id=\"saver\" type=\"button\" onclick=\"saveNum(" + i + ")\">ä¿å</button>";72 html += "</td></tr>";73 }74 html += "</table>";75 target.innerHTML = html;76 }77}7879function saveNum(num) {80 s_content = document.getElementById('saved');81 saveShop[saveShop.length] = shopName[num];82 saveUrl[saveUrl.length] = url[num];8384 drawSvContent();85}8687function removeNum(num) {88 if(saveShop.length === 1) {89 saveShop.length = 0;90 saveUrl.length = 0;91 s_content.innerHTML = "";92 } else if (num === 0) {93 saveShop.shift();94 saveUrl.shift();95 drawSvContent();96 } else {97 saveShop.splice(num, num);98 saveUrl.splice(num, num);99 drawSvContent();100 }101}102103function drawSvContent() {104 let saveHtml = "<h2>ä¿åããåè£</h2>";105 saveHtml += "<table border=\"1\">";106 saveHtml += "<tr><th>å称</th><th>æä½</th></tr>";107108 for (let i = 0; i < saveShop.length; i++) {109 saveHtml += "<tr><td><a href='";110 saveHtml += saveUrl[i];111 saveHtml += "'>";112 saveHtml += saveShop[i];113 saveHtml += "</td><td>";114 saveHtml += "<button id=\"saver\" type=\"button\" onclick=\"removeNum(" + i + ")\">åé¤</button>";115 saveHtml += "</td></tr>";116 }117 saveHtml += "</table>";118 saveHtml += "<button id=\"saver\" type=\"button\" onclick=\"saveBrowser()\">åè£ããã©ã¦ã¶ã«ä¿å</button>";119 saveHtml += "<button id=\"saver\" type=\"button\" onclick=\"delAll()\">åè£ãå
¨æ¶å»</button>";120121 s_content.innerHTML = saveHtml;122}123124function delAll() {125 saveShop.length = 0;126 saveUrl.length = 0;127 s_content.innerHTML = "";128}129130function saveBrowser() {131 if(localStorage.getItem("savedShop") !== null) {132 if(confirm("ååä¿åããåè£ãä¸æ¸ããã¾ããããããã§ããï¼") === true) {133 localStorage.setItem("savedShop", JSON.stringify(saveShop));134 localStorage.setItem("savedUrl", JSON.stringify(saveUrl));135 window.alert("ãã©ã¦ã¶ã«åè£ãä¸æ¸ãä¿åãã¾ããã");136 } else {137 window.alert("ãã£ã³ã»ã«ãã¾ããã")138 }139 } else {140 localStorage.setItem("savedShop", JSON.stringify(saveShop));141 localStorage.setItem("savedUrl", JSON.stringify(saveUrl));142 window.alert("ãã©ã¦ã¶ã«åè£ãä¿åãã¾ããã");143 }144}145146function loadBrowser() {147 let pastSaveShop = localStorage.getItem("savedShop");148 let pastSaveUrl = localStorage.getItem("savedUrl");149 pastSaveShop = JSON.parse(pastSaveShop);150 pastSaveUrl = JSON.parse(pastSaveUrl);151 let p_content = document.getElementById('past_saved');152153 let pastSavedHtml = "<h2>ååä¿åããåè£</h2>";154 if(pastSaveShop === null) {155 pastSavedHtml += "ååä¿åããåè£ã¯ããã¾ããã"156 } else {157 pastSavedHtml += "<table border=\"1\">";158 pastSavedHtml += "<tr><th>å称</th></tr>";159160 for(let i = 0; i < pastSaveShop.length; i++) {161 pastSavedHtml += "<tr><td><a href='";162 pastSavedHtml += pastSaveUrl[i];163 pastSavedHtml += "'>";164 pastSavedHtml += pastSaveShop[i];165 pastSavedHtml += "</td></tr>";166 }167 pastSavedHtml += "</table>";168 }169170 p_content.innerHTML = pastSavedHtml;
...
popup.js
Source:popup.js
1var currentURL;2$('#langselect').attr('disabled', true);3$('#langselect').css('opacity', '0.5');4$('#savetranslation').attr('disabled', true);5$('#savetranslation').css('opacity', '0.5');6$('#savehtml').attr('disabled', true);7$('#savehtml').css('opacity', '0.5');8$('#savepdf').attr('disabled', true);9$('#savepdf').css('opacity', '0.5');10$('#loadtranslation').attr('disabled', true);11$('#loadfile').attr('disabled', true);12$('#loadtranslation').css('opacity', '0.5');13chrome.tabs.query({14 'active': true,15 'lastFocusedWindow': true16}, function (tabs) {17 currentURL = tabs[0].url18 $("#urldisp").text(shortenURL(currentURL));19});20$(document).ready(function() {21 chrome.storage.local.get(['sellang'], function (result) {22 $(".langselect").val(result.sellang)23 });24 console.log("Hello")25 chrome.runtime.sendMessage({26 type: "get-iftranslate",27 }, function (response) {28 console.log(response.iftranslate)29 console.log("What?")30 if (response.iftranslate == true) {31 $('#globaltoggle').bootstrapToggle('on')32 }33 });34 console.log("Sir")35 // chrome.storage.local.get({userSites: []}, function (result) {36 // userSites = result.userSites;37 // if (userSites.includes(currentURL)) {38 // $('#highlighter').bootstrapToggle('on')39 // chrome.runtime.sendMessage({40 // type: "contentscript",41 // phrase: "True"42 // });43 // } else {44 // $('#highlighter').bootstrapToggle('off')45 // }46 // });47 // chrome.storage.local.get(['globaltoggle'], function (result) {48 // if (result.globaltoggle) {49 // $('#globaltoggle').bootstrapToggle(result.globaltoggle)50 // } else {51 // $('#globaltoggle').bootstrapToggle('on')52 // chrome.storage.local.set({53 // globaltoggle: 'on'54 // });55 // }56 // });57});58Array.prototype.removeDuplicates = function () {59 return this.filter(function (item, index, self) {60 return self.indexOf(item) == index;61 });62};63function shortenURL(url) {64 var maxLength = 20 + 3;65 maxLength = maxLength-3;66 var newURL = url67 if (url.length > maxLength){68 // newURL = url.slice(0, maxLength/2 + 7) + '...' + url.slice(url.length-maxLength/2)69 newURL = url.slice(8).split("/")70 newURL = url.slice(0,8) + newURL[0] + '/.../' + newURL[newURL.length -2] + '/'71 }72 return newURL73}74var userSites;75// $("#globaltoggle").change(function () {76 77// var checked = $(this).prop('checked')78// chrome.runtime.sendMessage({79// type: "set-iftranslate",80// phrase: checked,81// currentURL: currentURL82// });83// })84$("#globaltoggle").change(function () {85 var checked = $(this).prop('checked')86 console.log(checked)87 if (checked) {88 // $('body').css('background-color', '#eee');89 // $('body').css('opacity', '1');90 91 // chrome.storage.local.set({92 // globaltoggle: 'on'93 // });94 chrome.runtime.sendMessage({95 type: "set-iftranslate",96 phrase: true97 });98 // $('#highlighter').attr('disabled', false);99 // $('#highlighter-tooltip').css('color', '#000');100 $('#langselect').attr('disabled', false);101 $('#langselect').attr('opacity', '1');102 $('#savetranslation').attr('disabled', false);103 $('#savetranslation').css('opacity', '1');104 $('#savehtml').attr('disabled', false);105 $('#savehtml').css('opacity', '1');106 // $('#loadtranslation').attr('disabled', false);107 // $('#loadfile').attr('disabled', false);108 // $('#loadtranslation').css('opacity', '1');109 } else {110 // $('body').css('opacity', '0.5');111 // $('body').css('background', 'repeating-linear-gradient(45deg, #cccccc 10%, #dddddd 10%)');112 // chrome.storage.local.set({113 // globaltoggle: 'off'114 // });115 chrome.runtime.sendMessage({116 type: "set-iftranslate",117 phrase: false118 });119 // $('#highlighter').attr('disabled', true);120 // $('#highlighter-tooltip').css('color', '#777');121 $('#langselect').attr('disabled', true);122 $('#langselect').css('opacity', '0.5');123 $('#savetranslation').attr('disabled', true);124 $('#savetranslation').css('opacity', '0.5');125 $('#savehtml').attr('disabled', true);126 $('#savehtml').css('opacity', '0.5');127 // $('#loadtranslation').attr('disabled', true);128 // $('#loadfile').attr('disabled', true);129 // $('#loadtranslation').css('opacity', '0.5');130 }131})132$(".langselect").change(function () {133 chrome.runtime.sendMessage({134 type: "langselect",135 phrase: $(this).val()136 });137})138$('#savetranslation').click(function(){139 chrome.runtime.sendMessage({140 type: "savetranslations"141 });142})143$('#savehtml').click(function () {144 chrome.runtime.sendMessage({145 type: "savehtml"146 });...
view.js
Source:view.js
1<script type="text/javascript">2$(document).ready(function() {3 var cert_text = null;4 var cert_key = null;5 $('#cert').on('click', function() {6 var original = $('#cert_input')[0];7 var clone = $(original).clone().attr('id', 'cert_input_clone');8 var saveHtml = $(original).html();9 $(original).html('');10 $(clone).dialog({11 title: "Certificate Cert: Hit Ctrl-C to Copy",12 width: 800,13 height: 550,14 modal: true,15 open: function(event, ui) {16 cert_text = $(saveHtml).text();17 $('<textarea id="tmp"/>').appendTo($(this)).val(cert_text).focus().select();18 },19 close: function(event, ui) {20 $('#tmp').remove();21 $(clone).remove();22 $(original).html(saveHtml);23 },24 buttons: [25 {26 text: 'Ok',27 click: function() {28 $(this).dialog("close");29 },30 class: 'btn btn-primary',31 }],32 }).keyup(function(e) {33 if( e.keyCode == 67 && e.ctrlKey )34 {35 if( isTextSelected($('#tmp')[0]) )36 {37 $(this).dialog("close");38 }39 else40 {41 alert("Please select the text.");42 }43 }44 });45 });46 $('#key').on('click', function() {47 var original = $('#cert_key')[0];48 var clone = $(original).clone().attr('id', 'cert_key_clone');49 var saveHtml = $(original).html();50 $(original).html('');51 $(clone).dialog({52 title: "Certificate Key: Hit Ctrl-C to Copy",53 width: 800,54 height: 680,55 modal: true,56 open: function(event, ui) {57 cert_key = $(saveHtml).text();58 $('<textarea id="tmp"/>').appendTo($(this)).val(cert_key).focus().select();59 },60 close: function(event, ui) {61 $('#tmp').remove();62 $(clone).remove();63 $(original).html(saveHtml);64 },65 buttons: [66 {67 text: 'Ok',68 click: function() {69 $(this).dialog("close");70 },71 class: 'btn btn-primary', 72 }],73 }).keyup(function(e) {74 if( e.keyCode == 67 && e.ctrlKey )75 {76 if( isTextSelected($('#tmp')[0]) )77 {78 $(this).dialog("close");79 }80 else81 {82 alert("Please select the text.");83 }84 }85 });86 });87 if( $('#revokeca').length )88 {89 $('#revokeca').confirm({90 title: 'Revoke CA?',91 text: 'This will invalidate all existing certificates. Are you sure?',92 });93 }94});...
ToolbarHepler.js
Source:ToolbarHepler.js
12var buildToolBar = function () {3 var tb = new Ext.Toolbar();4 tb.add({ xtype: 'button', text: 'Save', handler: saveHtml });5 tb.add({ xtype: 'button', text: 'Cancel', handler: saveHtml });6 tb.add({ xtype: 'button', text: 'Validate', handler: saveHtml });7 tb.add("->");8 tb.add({ text: "Refresh", iconCls: "icon-arrowrefresh", handler: function () {9 // Ext.getCmp(id).reload(true)10 } 11 });12};13var buildBottomBar = function () {14 var tb = new Ext.Toolbar();15 tb.add({ xtype: 'button', text: 'Save', handler: saveHtml });16 tb.add({ xtype: 'button', text: 'Add Height', iconCls: 'add', handler: function () {17 var height = Ext.getCmp("htmleditorID").getHeight();18 Ext.getCmp("htmleditorID").setHeight(height + 100);19 }20 });21 tb.add({ xtype: 'button', text: 'Delete Height', handler: function () {22 var height = Ext.getCmp("htmleditorID").getHeight();23 if (height > 200)24 height = height - 100;25 Ext.getCmp("htmleditorID").setHeight(height);26 }27 });28 tb.add({ xtype: 'button', text: 'Cancel', handler: saveHtml });...
index.js
Source:index.js
2var path = require('path');3var fs = require('fs');4var debug = require('debug')('mydebug:weedSave');5module.exports = saveHtml;6function saveHtml(data,next) {7 debug('saveHtml');8 var self = this;9 var resp = data.response;10 if(!resp||!resp.body){11 return next();12 }13 var html = resp.body;14 wfs.Pweedfsclient().then(function(client){15 client.write(new Buffer(html), {replication: 000},function(err,fileInfo) {16 if(!err&&fileInfo){17 debug('saveHtml SUCCESS',fileInfo);18 // var savepath = path.resolve('./lib/engine/data/fileInfos')+'/'+fileInfo.fid+'.json';19 // fs.writeFile(savepath,JSON.stringify(fileInfo),function(e) {20 // debug(e);...
Using AI Code Generation
1describe('My First Test', () => {2 it('Does not do much!', () => {3 cy.contains('type').click()4 cy.saveHtml()5 })6})7Cypress.Commands.add('saveHtml', () => {8 cy.document().then((doc) => {9 cy.writeFile('cypress/fixtures/test.html', doc.documentElement.outerHTML)10 })11})12Cypress.Commands.add('saveHtml', () => {13 cy.get('div').then((div) => {14 cy.writeFile('cypress/fixtures/test.html', div[0].outerHTML)15 })16})17Cypress.Commands.add('saveHtml', () => {18 cy.get('div').then((div) => {19 cy.writeFile('cypress/fixtures/test.html', div[0].outerHTML)20 })21})22Cypress.Commands.add('saveHtml', () => {23 cy.get('div').then((div) => {24 cy.writeFile('cypress/fixtures/test.html', div[0].outerHTML)25 })26})27Cypress.Commands.add('saveHtml', () => {28 cy.get('div').then((div) => {29 cy.writeFile('cypress/fixtures/test.html', div[0].outerHTML)30 })31})32Cypress.Commands.add('saveHtml', (fileName) => {33 cy.document().then((doc) => {34 cy.writeFile('cypress/fixtures/' + fileName, doc.documentElement.outer
Using AI Code Generation
1cy.saveHtml();2cy.saveHtml();3cy.saveHtml();4Cypress.Commands.add('saveHtml', () => {5 cy.document().then((doc) => {6 const html = doc.documentElement.outerHTML;7 cy.writeFile('cypress/fixtures/html.html', html);8 });9});10describe('Test', () => {11 it('Test', () => {12 cy.get('#lst-ib').type('Hello World');13 cy.get('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)').click();14 cy.saveHtml();15 });16});
Using AI Code Generation
1cy.saveHtml()2cy.saveHtml()3cy.saveHtml()4cy.saveHtml()5cy.saveHtml()6cy.saveHtml()
Using AI Code Generation
1Cypress.Commands.add('saveHtml', (fileName, options) => {2 cy.window().then(win => {3 cy.writeFile(fileName, html, options)4 })5})6describe('Test', () => {7 it('should save html', () => {8 cy.saveHtml('google.html')9 })10})11Cypress.Commands.add('saveHtml', (fileName, options) => {12 cy.window().then(win => {13 cy.writeFile(fileName, html, options)14 })15})16describe('Save HTML', () => {17 it('Save HTML', () => {18 cy.saveHtml('google.html')19 })20})21Cypress.Commands.add('saveHtml', (fileName, options) => {22 cy.window().then(win => {23 cy.writeFile(fileName, html, options)24 })25})26describe('Save HTML', () => {27 it('Save HTML', () => {28 cy.saveHtml('google.html')29 })30})
Using AI Code Generation
1const fs = require('fs')2Cypress.on('test:after:run', (test, runnable) => {3 if (test.state === 'failed') {4 cy.saveHtml()5 }6})7Cypress.Commands.add('saveHtml', () => {8 cy.document().then(doc => {9 fs.writeFile(10 })11})12{13 "reporterOptions": {14 }15}16"scripts": {17}18"scripts": {19}20"scripts": {21}22"scripts": {23}24"scripts": {25}26"scripts": {27}28"scripts": {
Using AI Code Generation
1cy.saveHtml("myHtml.html");2Cypress.Commands.add("saveHtml", (filename) => {3 cy.document().then((doc) => {4 cy.writeFile(filename, doc.documentElement.outerHTML);5 });6});
Using AI Code Generation
1cy.saveHtml('html', 'html.html');2Cypress.Commands.add('saveHtml', (fileName, fileExtension) => {3 cy.document().then(doc => {4 const html = doc.documentElement.outerHTML;5 cy.writeFile(fileName + '.' + fileExtension, html);6 });7});8cy.saveHtml('html', 'html.html');9Cypress.Commands.add('saveHtml', (fileName, fileExtension) => {10 cy.document().then(doc => {11 const html = doc.documentElement.outerHTML;12 const date = new Date();13 date.getFullYear() +14 (date.getMonth() + 1) +15 date.getDate() +16 date.getHours() +17 date.getMinutes() +18 date.getSeconds();19 cy.writeFile(20 );21 });22});
Using AI Code Generation
1Cypress.Commands.add('saveHtml', (fileName, selector) => {2 cy.get(selector).then((element) => {3 cy.writeFile(fileName, element.html(), { log: false })4 })5})6Cypress.Commands.add('saveHtml', (fileName, selector) => {7 cy.get(selector).then((element) => {8 cy.writeFile(fileName, element.html(), { log: false })9 })10})11Cypress.Commands.add('saveHtml', (fileName, selector) => {12 cy.get(selector).then((element) => {13 cy.writeFile(fileName, element.html(), { log: false })14 })15})16Cypress.Commands.add('saveHtml', (fileName, selector) => {17 cy.get(selector).then((element) => {18 cy.writeFile(fileName, element.html(), { log: false })19 })20})21Cypress.Commands.add('saveHtml', (fileName, selector) => {22 cy.get(selector).then((element) => {23 cy.writeFile(fileName, element.html(), { log: false })24 })25})26Cypress.Commands.add('saveHtml', (fileName, selector) => {27 cy.get(selector).then((element) => {28 cy.writeFile(fileName, element.html(), { log: false })29 })30})
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!