Best JavaScript code snippet using ng-mocks
script.js
Source:script.js
1/* 2 * ÐодÑÐ»Ñ Ð¿Ð¾Ð´ÐºÐ»ÑÑаеÑÑÑ Ð½Ð° ÑÑÑаниÑе наÑÑÑоек плагина.3 */4var triggerGuarantee = (function () {5 return {6 lang: [], // Ð»Ð¾ÐºÐ°Ð»Ñ Ð¿Ð»Ð°Ð³Ð¸Ð½Ð° 7 supportCkeditor: null,8 init: function () {9 // ÑÑÑановка локали плагина 10 admin.ajaxRequest({11 mguniqueurl: "action/seLocalesToPlug",12 pluginName: 'trigger-guarantee'13 },14 function (response) {15 triggerGuarantee.lang = response.data;16 });17 $('.admin-center').on('click', '.section-trigger-guarantee .add-new-button', function () {18 triggerGuarantee.showModal('add');19 });20 $('.admin-center').on('click', '.section-trigger-guarantee .choose-icon', function () {21 if ($(this).hasClass('opend')) {22 $('.section-trigger-guarantee .font-awesome-icons').toggle();23 } else {24 $(this).addClass('opend');25 triggerGuarantee.showIcons();26 }27 });28// $('.admin-center').on('mouseover', '.section-trigger-guarantee .font-awesome-icons span .fa', function() {29// $(this).addClass('fa-3x');30// });31// $('.admin-center').on('mouseleave', '.section-trigger-guarantee .font-awesome-icons span .fa', function() {32// $(this).removeClass('fa-3x');33// });34 $('.admin-center').on('click', '.section-trigger-guarantee .font-awesome-icons .fa', function () {35 var className = $(this).attr('class');36 $('.section-trigger-guarantee .add-trigger-element .img').html('<i class="' + className + ' fa-4x"></i>');37 $('.section-trigger-guarantee #add-plug-modal input[name="icon"] ').val(className);38 $('.section-trigger-guarantee .font-awesome-icons').slideUp();39 });40 $('.admin-center').on('click', '.section-trigger-guarantee #add-plug-modal .save-button', function () {41 var id = $(this).data('id');42 triggerGuarantee.saveField(id);43 });44 if ($('.section-trigger-guarantee .trigger-guarantee-elements tr').length > 0) {45 $('.section-trigger-guarantee .trigger-guarantee-save').show();46 }47 $('.admin-center').on('click', '.section-trigger-guarantee .save-button.trigger', function () {48 if ($('.section-trigger-guarantee table .trigger-guarantee-elements tr').length > 0) {49 var id = $(this).attr('id');50 var next_id = $(this).data('nextid');51 triggerGuarantee.saveTrigger(id, next_id);52 } else {53 admin.indication('error', 'ÐеобÑ
одимо добавиÑÑ ÑлеменÑÑ!');54 return false;55 }56 });57 // изменени внеÑнего вида ÑлеменÑов ÑÑиггеÑов58 $('.admin-center').on('change', '.section-trigger-guarantee .list-option input, .list-option select', function () {59 triggerGuarantee.applySettings();60 })61 // ÐÑÐ±Ð¾Ñ ÐºÐ°ÑÑинки62 $('.admin-center').on('click', '.section-trigger-guarantee .browseImage', function () {63 admin.openUploader('triggerGuarantee.getImage');64 });65 $('.admin-center').on('click', '.section-trigger-guarantee .open-trigger', function () {66 if ($(this).parents('li').hasClass('is-active')) {67 return true;68 } else {69 var id = $(this).attr('id');70 $(this).parents('ul').find('li').removeClass('is-active');71 $(this).parents('li').addClass('is-active');72 triggerGuarantee.clearTrigger();73 if (id) {74 admin.ajaxRequest({75 mguniqueurl: "action/getTrigger",76 pluginHandler: 'trigger-guarantee', // плагин Ð´Ð»Ñ Ð¾Ð±ÑабоÑки запÑоÑа77 id: id,78 },79 function (response) {80 triggerGuarantee.fillFieldTrigger(response.data);81 }82 );83 }84 }85 });86 // ÐÑÐ²Ð¾Ð´Ð¸Ñ Ð¼Ð¾Ð´Ð°Ð»Ñное окно Ð´Ð»Ñ ÑедакÑиÑованиÑ87 $('.admin-center').on('click', '.section-trigger-guarantee .trigger-guarantee-elements .edit-row', function () {88 var id = $(this).data('id');89 triggerGuarantee.showModal('edit', id, 0);90 });91 // вÑÐ±Ð¾Ñ ÑлеменÑа из ÑÑÑеÑÑвÑÑÑиÑ
92 $('.admin-center').on('click', '.section-trigger-guarantee .add-exist-button', function () {93 $('.widget-table-wrapper .trigger-guarantee-all-elements').show();94 $('html, body').animate({scrollTop: $('.trigger-guarantee-all-elements').offset().top - 100}, 800);95 });96 // вÑÐ±Ð¾Ñ Ð·Ð°ÐºÑÑÑÑ ÑаблиÑÑ Ñ ÑÑÑеÑÑвÑÑÑими ÑлеменÑами97 $('.admin-center').on('click', '.section-trigger-guarantee .close-trigger-table', function () {98 $('.widget-table-wrapper .trigger-guarantee-all-elements').slideUp(400);99 });100 // вÑÐ±Ð¾Ñ ÑлеменÑа из ÑаблиÑÑ101 $('.admin-center').on('click', '.section-trigger-guarantee .trigger-guarantee-tbody .trigger-item', function () {102 var id = $(this).parents('tr').data('id');103 var parent = $(this).parents('tr').find('.parent').data('parent');104 $('.widget-table-wrapper .trigger-guarantee-all-elements').hide();105 triggerGuarantee.showModal('edit', id, parent);106 })107 // Ñдаление елеменÑа из ÑÑиггеÑа108 $('.admin-center').on('click', '.section-trigger-guarantee .trigger-guarantee-elements .delete-row', function () {109 var id = $(this).data('id');110 if (id) {111 if (confirm('УдалиÑÑ ÑÐ»ÐµÐ¼ÐµÐ½Ñ ÑÑиггеÑа?')) {112 admin.ajaxRequest({113 mguniqueurl: "action/deleteElement", // дейÑÑÐ²Ð¸Ñ Ð´Ð»Ñ Ð²ÑÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð½Ð° ÑеÑвеÑе114 pluginHandler: 'trigger-guarantee', // плагин Ð´Ð»Ñ Ð¾Ð±ÑабоÑки запÑоÑа115 id: id116 },117 function (response) {118 admin.indication(response.status, response.msg);119 if (response.status == 'success') {120 $('.section-trigger-guarantee .trigger-guarantee-elements tr[data-id=' + id + ']').remove();121 $('.section-trigger-guarantee .trigger-guarantee-table tr[data-id=' + id + ']').remove();122 }123 })124 }125 }126 });127 // Ñдаление вÑего ÑÑиггеÑа128 $('.admin-center').on('click', '.section-trigger-guarantee .delete-trigger', function () {129 var id = $(this).data('id');130 if (id) {131 if (confirm('УдалиÑÑ ÑÑÐ¸Ð³Ð³ÐµÑ Ð¸ вÑе его ÑлеменÑÑ?')) {132 admin.ajaxRequest({133 mguniqueurl: "action/deleteTrigger", // дейÑÑÐ²Ð¸Ñ Ð´Ð»Ñ Ð²ÑÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð½Ð° ÑеÑвеÑе134 pluginHandler: 'trigger-guarantee', // плагин Ð´Ð»Ñ Ð¾Ð±ÑабоÑки запÑоÑа135 id: id136 },137 function (response) {138 admin.indication(response.status, response.msg);139 if (response.status == 'success') {140 admin.refreshPanel();141 }142 })143 }144 }145 });146 },147 /* оÑкÑÑÐ²Ð°ÐµÑ Ð¼Ð¾Ð´Ð°Ð»Ñное окно 148 * @param {type} type -Ñип окна, Ð´Ð»Ñ ÑедакÑиÑÐ¾Ð²Ð°Ð½Ð¸Ñ Ð¸Ð»Ð¸ Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ149 * @param {type} id - Ð½Ð¾Ð¼ÐµÑ Ð·Ð°Ð¿Ð¸Ñи, коÑоÑÐ°Ñ Ð¾ÑкÑÑÑа на ÑедакÑиÑование150 * @returns {undefined}151 */152 showModal: function (type, id, parent) {153 switch (type) {154 case 'add':155 {156 triggerGuarantee.clearField();157 break;158 }159 case 'edit':160 {161 try {162 if (CKEDITOR.instances['html_content']) {163 CKEDITOR.instances['html_content'].destroy();164 }165 } catch (e) {166 }167 triggerGuarantee.clearField();168 triggerGuarantee.fillField(id, parent);169 break;170 }171 default:172 {173 break;174 }175 }176 admin.openModal($('#add-plug-modal'));177 $('textarea[data-name=html_content]').ckeditor();178 },179 /**180 * ÐÑиÑÑка модалÑного окна181 */182 clearField: function () {183 $('.section-trigger-guarantee #add-plug-modal .save-button').data('id', '');184 $('.section-trigger-guarantee textarea[data-name=html_content]').val('');185 $('.section-trigger-guarantee .add-trigger-element img').removeAttr('src');186 $('.section-trigger-guarantee .add-trigger-element .img').html('');187 $('.section-trigger-guarantee #add-plug-modal input[name="icon"] ').val('');188 triggerGuarantee.supportCkeditor = '';189 },190 /**191 * Ðаполнение модалÑного окна даннÑми из ÐÐ192 * @param {type} id193 * @returns {undefined}194 */195 fillField: function (id, parent) {196 admin.ajaxRequest({197 mguniqueurl: "action/getEntity", // дейÑÑÐ²Ð¸Ñ Ð´Ð»Ñ Ð²ÑÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð½Ð° ÑеÑвеÑе198 pluginHandler: 'trigger-guarantee', // плагин Ð´Ð»Ñ Ð¾Ð±ÑабоÑки запÑоÑа199 id: id // id запиÑи200 },201 function (response) {202 triggerGuarantee.supportCkeditor = response.data.text;203 if (parent == '0') {204 $('.section-trigger-guarantee #add-plug-modal .save-button').data('id', response.data.id);205 }206 $('.section-trigger-guarantee #add-plug-modal .img').html(response.data.icon)207 $('.section-trigger-guarantee #add-plug-modal input[name="icon"] ').val(response.data.icon); 208 $('.section-trigger-guarantee #add-plug-modal textarea[data-name=html_content]').ckeditor(function () {209 this.setData(triggerGuarantee.supportCkeditor);210 }); 211 }212 );213 },214 /**215 * загÑÑÐ¶Ð°ÐµÑ Ð¸ÐºÐ¾Ð½ÐºÐ¸ из font-awesome216 */217 showIcons: function () {218 admin.ajaxRequest({219 mguniqueurl: "action/getIcons", // дейÑÑÐ²Ð¸Ñ Ð´Ð»Ñ Ð²ÑÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð½Ð° ÑеÑвеÑе220 pluginHandler: 'trigger-guarantee' // плагин Ð´Ð»Ñ Ð¾Ð±ÑабоÑки запÑоÑа221 },222 function (response) {223 $('.section-trigger-guarantee .font-awesome-icons').append(response.data);224 $('.section-trigger-guarantee .font-awesome-icons').show();225 }226 );227 },228 /**229 * СоÑ
Ñанение даннÑÑ
из модалÑного окна230 * @param {type} id231 * @returns {undefined}232 */233 saveField: function (id) {234 $('.section-trigger-guarantee .add-trigger-element .img').attr('alt', 'tempAlt');235 var text = $('.section-trigger-guarantee .add-trigger-element textarea[data-name=html_content]').val();236 var icon = $('.section-trigger-guarantee .add-trigger-element .img').html().replace('alt="tempAlt"', 'alt="'+text+'"').replace("alt='tempAlt'", "alt='"+text+"'");237 var parent = $('.section-trigger-guarantee .add-new-button').attr('id');238 admin.ajaxRequest({239 mguniqueurl: "action/saveEntity", // дейÑÑÐ²Ð¸Ñ Ð´Ð»Ñ Ð²ÑÐ¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð½Ð° ÑеÑвеÑе240 pluginHandler: 'trigger-guarantee', // плагин Ð´Ð»Ñ Ð¾Ð±ÑабоÑки запÑоÑа241 id: id,242 text: text,243 icon: icon,244 parent: parent ? parent : 0,245 },246 function (response) {247 admin.indication(response.status, response.msg);248 var elem = '<tr data-id=' + response.data.row.id + '>\249 <td >\250 <div class="trigger-item">\251 <span class="trigger-icon">' + icon + '</span>\252 <span class="trigger-text">' + text + '</span>\253 </div>\254 </td>\255 <td class="actions">\256 <ul class="action-list">\257 <li class="mover"\258 data-id="' + response.data.row.id + '">\259 <a href="javascript:void(0);"><i class="fa fa-arrows ui-sortable-handle"></i></a>\260 </li>\261 <li class="edit-row"\262 data-id="' + response.data.row.id + '">\263 <a class="tool-tip-bottom fa fa-pencil" href="javascript:void(0);"\264 title="' + triggerGuarantee.lang['EDIT'] + '"></a>\265 </li>\266 <li class="delete-row"\267 data-id="' + response.data.row.id + '">\268 <a class="tool-tip-bottom fa fa-trash" href="javascript:void(0);"\269 title="' + triggerGuarantee.lang['DELETE'] + '"></a>\270 </li>\271 </ul>\272 </td></tr>';273 var trigger = (parent ? 'ТÑÐ¸Ð³Ð³ÐµÑ â' + parent : '');274 var tr = '<tr data-id=' + response.data.row.id + '>\275 <td>\276 ' + response.data.row.id + '\277 </td>\278 <td>\279 <div class="trigger-item">\280 <span class="trigger-icon">' + icon + '</span>\281 <span class="trigger-text">' + text + '</span>\282 </div>\283 </td>\284 <td class="parent" data-parent="' + parent + '">\285 ' + trigger + '</td>\286 </tr>';287 if (id && ($('.section-trigger-guarantee .trigger-guarantee-elements tr[data-id=' + id + ']')).length != 0) {288 $('.section-trigger-guarantee table .trigger-guarantee-elements tr[data-id=' + id + ']').replaceWith(elem);289 } else {290 $('.section-trigger-guarantee table .trigger-guarantee-elements').append(elem);291 }292 if (id && ($('.section-trigger-guarantee .trigger-guarantee-table tr[data-id=' + id + ']')).length != 0) {293 $('.section-trigger-guarantee .trigger-guarantee-table tr[data-id=' + id + ']').replaceWith(tr);294 } else {295 $('.section-trigger-guarantee .trigger-guarantee-table').append(tr);296 }297 admin.closeModal($('#add-plug-modal')); 298 triggerGuarantee.applySettings();299 }300 );301 },302 /**303 * ÑÑнкÑÐ¸Ñ Ð´Ð»Ñ Ð¿Ñиема Ñайла из аплоадеÑа304 */305 getImage: function (file) {306 $('.section-trigger-guarantee #add-plug-modal input[name="icon"]').val(file.url);307 if ($('.section-trigger-guarantee #add-plug-modal img').length != 0) {308 $('.section-trigger-guarantee #add-plug-modal img').attr('src', file.url);309 $('.section-trigger-guarantee #add-plug-modal img').attr('width', '170');310 $('.section-trigger-guarantee #add-plug-modal img').attr('alt', 'tempAlt');311 } else {312 $('.section-trigger-guarantee #add-plug-modal .img').html('<img class="img" width="170" alt="tempAlt" src="' + file.url + '">');313 }314 },315 /**316 * пÑименение наÑÑÑоек к ÑлеменÑам ÑÑиггеÑа317 * 318 */319 applySettings: function () {320 var form = $('.section-trigger-guarantee .list-option select[name=form]').val();321 var radius = (form == 'circle' ? '50%' : 0);322 var float = $('.section-trigger-guarantee .list-option select[name=place]').val();323 var width = $('.section-trigger-guarantee .list-option input[name=width]').val();324 var unit = $('.section-trigger-guarantee .list-option select[name=unit]').val() == 1 ? '%' : 'px';325 width = width + unit;326 $('.section-trigger-guarantee .list-option .trigger-width').text(width);327 var height = $('.section-trigger-guarantee .list-option input[name=height]').val();328 $('.section-trigger-guarantee .list-option .trigger-height').text(height + 'px');329 if (float == 'left') {330 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-icon').css('float', 'none');331 } else if (float == 'top') {332 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-icon').css('display', 'block');333 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-icon').css('float', 'none');334 }335 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-icon img').css('border-radius', radius);336 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-icon i').css('border-radius', radius);337 var color = $('.section-trigger-guarantee .list-option input[name="color_icon"]').val();338 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-icon i').css('color', '#' + color);339 var colorBack = $('.section-trigger-guarantee .list-option input[name="background_icon"]').val();340 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-icon i').css('background-color', '#' + colorBack);341 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-icon img').css('background-color', '#' + colorBack);342 var background = $('.section-trigger-guarantee .list-option input[name="background"]').val();343 $('.section-trigger-guarantee table .trigger-guarantee-elements tr .trigger-item').css('background-color', '#' + background);344 $('.section-trigger-guarantee table .trigger-item').css('width', width);345 $('.section-trigger-guarantee table .trigger-item').css('height', height);346 var size = $('.section-trigger-guarantee .list-option input[name="fontSize"]').val();347 $('.section-trigger-guarantee table .trigger-icon i').css("font-size", size+"em");348 },349 /** 350 * ÑоÑ
ÑанÑем ÑÑÐ¸Ð³Ð³ÐµÑ Ð² его ÑлеменÑами и наÑÑÑоками351 */352 saveTrigger: function (id, next_id) {353 var obj = '{';354 $('.section-trigger-guarantee .list-option input, .list-option select').each(function () {355 obj += '"' + $(this).attr('name') + '":"' + ($(this).val()) + '",';356 });357 obj += '}';358 //пÑеобÑазÑем полÑÑеннÑе даннÑе в JS обÑÐµÐºÑ Ð´Ð»Ñ Ð¿ÐµÑедаÑи на ÑеÑвеÑ359 var data = eval("(" + obj + ")");360 var title = $('.section-trigger-guarantee input[name="title-trigger"]').val();361 var elements = triggerGuarantee.createElementsList();362 admin.ajaxRequest({363 mguniqueurl: "action/saveTrigger",364 pluginHandler: 'trigger-guarantee', // плагин Ð´Ð»Ñ Ð¾Ð±ÑабоÑки запÑоÑа365 id: id,366 settings: data,367 title: title,368 elements: elements,369 new_id: next_id,370 },371 function (response) {372 admin.indication(response.status, response.msg);373 if (!id) {374 admin.refreshPanel();375 }376 }377 );378 },379 // маÑÑив Ñ id ÑлеменÑов ÑÑиггеÑа380 createElementsList: function () {381 var elem = [];382 $('.section-trigger-guarantee table .trigger-guarantee-elements tr').each(function () {383 elem.push($(this).data('id'));384 });385 return elem;386 },387 // 388 clearTrigger: function () {389 $('.section-trigger-guarantee .list-option select').each(function () {390 $(this).val('');391 });392 $('.section-trigger-guarantee .list-option input[name="color_icon"]').val('000');393 $('.section-trigger-guarantee .list-option input[name="background_icon"]').val('fff');394 $('.section-trigger-guarantee .list-option input[name="background"]').val('fff');395 $('.section-trigger-guarantee .list-option input[name="color_icon"]').css('border-color', '#000');396 $('.section-trigger-guarantee .list-option input[name="background"], .list-option input[name="background_icon"]').css('border-color', '#fff');397 $('.section-trigger-guarantee input[name="title-trigger"]').val('');398 $('.section-trigger-guarantee table .trigger-guarantee-elements tr').remove();399 var next_id = $('.section-trigger-guarantee .main-settings-trigger .short-code').data('id');400 $('.section-trigger-guarantee .main-settings-trigger .short-code').text(next_id);401 $('.section-trigger-guarantee .save-button.trigger').removeAttr('id');402 $('.section-trigger-guarantee .delete-trigger').data('id', '');403 $('.section-trigger-guarantee .add-new-button').removeAttr('id');404 $('.section-trigger-guarantee .list-option select[name=unit]').val('1');405 $('.section-trigger-guarantee .list-option input[name=fontSize]').val('4');406 },407 fillFieldTrigger: function (data) {408 $('.section-trigger-guarantee .list-option select[name="form"]').val(data.settings.form);409 $('.section-trigger-guarantee .list-option select[name="place"]').val(data.settings.place);410 $('.section-trigger-guarantee .list-option input[name="width"]').val(data.settings.width);411 $('.section-trigger-guarantee .list-option input[name="height"]').val(data.settings.height);412 $('.section-trigger-guarantee .list-option select[name="layout"]').val(data.settings.layout ? data.settings.layout : 'vert');413 $('.section-trigger-guarantee .list-option input[name="color_icon"]').val(data.settings.color_icon);414 $('.section-trigger-guarantee .list-option input[name="background_icon"]').val(data.settings.background_icon);415 $('.section-trigger-guarantee .list-option input[name="background"]').val(data.settings.background);416 $('.section-trigger-guarantee .list-option input[name="color_icon"]').css('cssText', 'border-color: #' + data.settings.color_icon + ' !important');417 $('.section-trigger-guarantee .list-option input[name="background"]').css('cssText', 'border-color: #' + data.settings.background + ' !important');418 $('.section-trigger-guarantee .list-option input[name="background_icon"]').css('cssText', 'border-color: #' + data.settings.background_icon + ' !important');419 $('.section-trigger-guarantee input[name="title-trigger"]').val(data.title);420 $('.section-trigger-guarantee .main-settings-trigger .short-code').text(data.id);421 $('.section-trigger-guarantee .save-button.trigger').attr('id', data.id);422 $('.section-trigger-guarantee .delete-trigger').data('id', data.id);423 $('.section-trigger-guarantee .add-new-button').attr('id', data.id);424 $('.section-trigger-guarantee .list-option select[name=unit]').val(data.settings.unit? data.settings.unit : '1');425 $('.section-trigger-guarantee .list-option input[name="fontSize"]').val(data.settings.fontSize);426 function buildRow(el) {427 var row = '<tr data-id=' + el.id + '>\428 <td >\429 <div class="trigger-item">\430 <span class="trigger-icon">' + el.icon + '</span>\431 <span class="trigger-text">' + el.text + '</span>\432 </div>\433 </td>\434 <td class="actions">\435 <ul class="action-list">\436 <li class="mover"\437 data-id="' + el.id + '">\438 <a href="javascript:void(0);"><i class="fa fa-arrows ui-sortable-handle"></i></a>\439 </li>\440 <li class="edit-row"\441 data-id="' + el.id + '">\442 <a class="tool-tip-bottom fa fa-pencil" href="javascript:void(0);"\443 title="' + triggerGuarantee.lang['EDIT'] + '"></a>\444 </li>\445 <li class="delete-row"\446 data-id="' + el.id + '">\447 <a class="tool-tip-bottom fa fa-trash" href="javascript:void(0);"\448 title="' + triggerGuarantee.lang['DELETE'] + '"></a>\449 </li>\450 </ul>\451 </td></tr>';452 $('.section-trigger-guarantee table .trigger-guarantee-elements').append(row);453 }454 data.elements.forEach(buildRow);455 triggerGuarantee.applySettings();456 },457 }458})();...
TriggerField.js
Source:TriggerField.js
1/*!2 * Ext JS Library 3.1.13 * Copyright(c) 2006-2010 Ext JS, LLC4 * licensing@extjs.com5 * http://www.extjs.com/license6 */7/**8 * @class Ext.form.TriggerField9 * @extends Ext.form.TextField10 * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).11 * The trigger has no default action, so you must assign a function to implement the trigger click handler by12 * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox13 * for which you can provide a custom implementation. For example:14 * <pre><code>15var trigger = new Ext.form.TriggerField();16trigger.onTriggerClick = myTriggerFn;17trigger.applyToMarkup('my-field');18</code></pre>19 *20 * However, in general you will most likely want to use TriggerField as the base class for a reusable component.21 * {@link Ext.form.DateField} and {@link Ext.form.ComboBox} are perfect examples of this.22 *23 * @constructor24 * Create a new TriggerField.25 * @param {Object} config Configuration options (valid {@Ext.form.TextField} config options will also be applied26 * to the base TextField)27 * @xtype trigger28 */29Ext.form.TriggerField = Ext.extend(Ext.form.TextField, {30 /**31 * @cfg {String} triggerClass32 * An additional CSS class used to style the trigger button. The trigger will always get the33 * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.34 */35 /**36 * @cfg {Mixed} triggerConfig37 * <p>A {@link Ext.DomHelper DomHelper} config object specifying the structure of the38 * trigger element for this Field. (Optional).</p>39 * <p>Specify this when you need a customized element to act as the trigger button for a TriggerField.</p>40 * <p>Note that when using this option, it is the developer's responsibility to ensure correct sizing, positioning41 * and appearance of the trigger. Defaults to:</p>42 * <pre><code>{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass}</code></pre>43 */44 /**45 * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default46 * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.47 * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details. Defaults to:</p>48 * <pre><code>{tag: "input", type: "text", size: "16", autocomplete: "off"}</code></pre>49 */50 defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},51 /**52 * @cfg {Boolean} hideTrigger <tt>true</tt> to hide the trigger element and display only the base53 * text field (defaults to <tt>false</tt>)54 */55 hideTrigger:false,56 /**57 * @cfg {Boolean} editable <tt>false</tt> to prevent the user from typing text directly into the field,58 * the field will only respond to a click on the trigger to set the value. (defaults to <tt>true</tt>).59 */60 editable: true,61 /**62 * @cfg {Boolean} readOnly <tt>true</tt> to prevent the user from changing the field, and63 * hides the trigger. Superceeds the editable and hideTrigger options if the value is true.64 * (defaults to <tt>false</tt>)65 */66 readOnly: false,67 /**68 * @cfg {String} wrapFocusClass The class added to the to the wrap of the trigger element. Defaults to69 * <tt>x-trigger-wrap-focus</tt>.70 */71 wrapFocusClass: 'x-trigger-wrap-focus',72 /**73 * @hide74 * @method autoSize75 */76 autoSize: Ext.emptyFn,77 // private78 monitorTab : true,79 // private80 deferHeight : true,81 // private82 mimicing : false,83 actionMode: 'wrap',84 defaultTriggerWidth: 17,85 // private86 onResize : function(w, h){87 Ext.form.TriggerField.superclass.onResize.call(this, w, h);88 var tw = this.getTriggerWidth();89 if(Ext.isNumber(w)){90 this.el.setWidth(w - tw);91 }92 this.wrap.setWidth(this.el.getWidth() + tw);93 },94 getTriggerWidth: function(){95 var tw = this.trigger.getWidth();96 if(!this.hideTrigger && tw === 0){97 tw = this.defaultTriggerWidth;98 }99 return tw;100 },101 // private102 alignErrorIcon : function(){103 if(this.wrap){104 this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);105 }106 },107 // private108 onRender : function(ct, position){109 this.doc = Ext.isIE ? Ext.getBody() : Ext.getDoc();110 Ext.form.TriggerField.superclass.onRender.call(this, ct, position);111 this.wrap = this.el.wrap({cls: 'x-form-field-wrap x-form-field-trigger-wrap'});112 this.trigger = this.wrap.createChild(this.triggerConfig ||113 {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass});114 this.initTrigger();115 if(!this.width){116 this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());117 }118 this.resizeEl = this.positionEl = this.wrap;119 },120 updateEditState: function(){121 if(this.rendered){122 if (this.readOnly) {123 this.el.dom.readOnly = true;124 this.el.addClass('x-trigger-noedit');125 this.mun(this.el, 'click', this.onTriggerClick, this);126 this.trigger.setDisplayed(false);127 } else {128 if (!this.editable) {129 this.el.dom.readOnly = true;130 this.el.addClass('x-trigger-noedit');131 this.mon(this.el, 'click', this.onTriggerClick, this);132 } else {133 this.el.dom.readOnly = false;134 this.el.removeClass('x-trigger-noedit');135 this.mun(this.el, 'click', this.onTriggerClick, this);136 }137 this.trigger.setDisplayed(!this.hideTrigger);138 }139 this.onResize(this.width || this.wrap.getWidth());140 }141 },142 setHideTrigger: function(hideTrigger){143 if(hideTrigger != this.hideTrigger){144 this.hideTrigger = hideTrigger;145 this.updateEditState();146 }147 },148 /**149 * @param {Boolean} value True to allow the user to directly edit the field text150 * Allow or prevent the user from directly editing the field text. If false is passed,151 * the user will only be able to modify the field using the trigger. Will also add152 * a click event to the text field which will call the trigger. This method153 * is the runtime equivalent of setting the 'editable' config option at config time.154 */155 setEditable: function(editable){156 if(editable != this.editable){157 this.editable = editable;158 this.updateEditState();159 }160 },161 /**162 * @param {Boolean} value True to prevent the user changing the field and explicitly163 * hide the trigger.164 * Setting this to true will superceed settings editable and hideTrigger.165 * Setting this to false will defer back to editable and hideTrigger. This method166 * is the runtime equivalent of setting the 'readOnly' config option at config time.167 */168 setReadOnly: function(readOnly){169 if(readOnly != this.readOnly){170 this.readOnly = readOnly;171 this.updateEditState();172 }173 },174 afterRender : function(){175 Ext.form.TriggerField.superclass.afterRender.call(this);176 this.updateEditState();177 },178 // private179 initTrigger : function(){180 this.mon(this.trigger, 'click', this.onTriggerClick, this, {preventDefault:true});181 this.trigger.addClassOnOver('x-form-trigger-over');182 this.trigger.addClassOnClick('x-form-trigger-click');183 },184 // private185 onDestroy : function(){186 Ext.destroy(this.trigger, this.wrap);187 if (this.mimicing){188 this.doc.un('mousedown', this.mimicBlur, this);189 }190 delete this.doc;191 Ext.form.TriggerField.superclass.onDestroy.call(this);192 },193 // private194 onFocus : function(){195 Ext.form.TriggerField.superclass.onFocus.call(this);196 if(!this.mimicing){197 this.wrap.addClass(this.wrapFocusClass);198 this.mimicing = true;199 this.doc.on('mousedown', this.mimicBlur, this, {delay: 10});200 if(this.monitorTab){201 this.on('specialkey', this.checkTab, this);202 }203 }204 },205 // private206 checkTab : function(me, e){207 if(e.getKey() == e.TAB){208 this.triggerBlur();209 }210 },211 // private212 onBlur : Ext.emptyFn,213 // private214 mimicBlur : function(e){215 if(!this.isDestroyed && !this.wrap.contains(e.target) && this.validateBlur(e)){216 this.triggerBlur();217 }218 },219 // private220 triggerBlur : function(){221 this.mimicing = false;222 this.doc.un('mousedown', this.mimicBlur, this);223 if(this.monitorTab && this.el){224 this.un('specialkey', this.checkTab, this);225 }226 Ext.form.TriggerField.superclass.onBlur.call(this);227 if(this.wrap){228 this.wrap.removeClass(this.wrapFocusClass);229 }230 },231 beforeBlur : Ext.emptyFn,232 // private233 // This should be overriden by any subclass that needs to check whether or not the field can be blurred.234 validateBlur : function(e){235 return true;236 },237 /**238 * The function that should handle the trigger's click event. This method does nothing by default239 * until overridden by an implementing function. See Ext.form.ComboBox and Ext.form.DateField for240 * sample implementations.241 * @method242 * @param {EventObject} e243 */244 onTriggerClick : Ext.emptyFn245 /**246 * @cfg {Boolean} grow @hide247 */248 /**249 * @cfg {Number} growMin @hide250 */251 /**252 * @cfg {Number} growMax @hide253 */254});255/**256 * @class Ext.form.TwinTriggerField257 * @extends Ext.form.TriggerField258 * TwinTriggerField is not a public class to be used directly. It is meant as an abstract base class259 * to be extended by an implementing class. For an example of implementing this class, see the custom260 * SearchField implementation here:261 * <a href="http://extjs.com/deploy/ext/examples/form/custom.html">http://extjs.com/deploy/ext/examples/form/custom.html</a>262 */263Ext.form.TwinTriggerField = Ext.extend(Ext.form.TriggerField, {264 /**265 * @cfg {Mixed} triggerConfig266 * <p>A {@link Ext.DomHelper DomHelper} config object specifying the structure of the trigger elements267 * for this Field. (Optional).</p>268 * <p>Specify this when you need a customized element to contain the two trigger elements for this Field.269 * Each trigger element must be marked by the CSS class <tt>x-form-trigger</tt> (also see270 * <tt>{@link #trigger1Class}</tt> and <tt>{@link #trigger2Class}</tt>).</p>271 * <p>Note that when using this option, it is the developer's responsibility to ensure correct sizing,272 * positioning and appearance of the triggers.</p>273 */274 /**275 * @cfg {String} trigger1Class276 * An additional CSS class used to style the trigger button. The trigger will always get the277 * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.278 */279 /**280 * @cfg {String} trigger2Class281 * An additional CSS class used to style the trigger button. The trigger will always get the282 * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.283 */284 initComponent : function(){285 Ext.form.TwinTriggerField.superclass.initComponent.call(this);286 this.triggerConfig = {287 tag:'span', cls:'x-form-twin-triggers', cn:[288 {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},289 {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}290 ]};291 },292 getTrigger : function(index){293 return this.triggers[index];294 },295 initTrigger : function(){296 var ts = this.trigger.select('.x-form-trigger', true);297 var triggerField = this;298 ts.each(function(t, all, index){299 var triggerIndex = 'Trigger'+(index+1);300 t.hide = function(){301 var w = triggerField.wrap.getWidth();302 this.dom.style.display = 'none';303 triggerField.el.setWidth(w-triggerField.trigger.getWidth());304 this['hidden' + triggerIndex] = true;305 };306 t.show = function(){307 var w = triggerField.wrap.getWidth();308 this.dom.style.display = '';309 triggerField.el.setWidth(w-triggerField.trigger.getWidth());310 this['hidden' + triggerIndex] = false;311 };312 if(this['hide'+triggerIndex]){313 t.dom.style.display = 'none';314 this['hidden' + triggerIndex] = true;315 }316 this.mon(t, 'click', this['on'+triggerIndex+'Click'], this, {preventDefault:true});317 t.addClassOnOver('x-form-trigger-over');318 t.addClassOnClick('x-form-trigger-click');319 }, this);320 this.triggers = ts.elements;321 },322 getTriggerWidth: function(){323 var tw = 0;324 Ext.each(this.triggers, function(t, index){325 var triggerIndex = 'Trigger' + (index + 1),326 w = t.getWidth();327 if(w === 0 && !this['hidden' + triggerIndex]){328 tw += this.defaultTriggerWidth;329 }else{330 tw += w;331 }332 }, this);333 return tw;334 },335 // private336 onDestroy : function() {337 Ext.destroy(this.triggers);338 Ext.form.TwinTriggerField.superclass.onDestroy.call(this);339 },340 /**341 * The function that should handle the trigger's click event. This method does nothing by default342 * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}343 * for additional information.344 * @method345 * @param {EventObject} e346 */347 onTrigger1Click : Ext.emptyFn,348 /**349 * The function that should handle the trigger's click event. This method does nothing by default350 * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}351 * for additional information.352 * @method353 * @param {EventObject} e354 */355 onTrigger2Click : Ext.emptyFn356});...
StimulusBuilder.py
Source:StimulusBuilder.py
...38 if self.shared == 0:39 class empty_class: pass40 self.shared = empty_class4142 def add_trigger(self, t, message):43 self.parent.Trigger.add_trigger_event(t, 0.1, message)4445 def trigger_set_white(self):46 self.shared.trigger_state.value = 147 #return time.clock()48 return datetime.datetime.now()4950 def trigger_set_black(self):51 self.shared.trigger_state.value = 05253 def trigger_routine(self, time):5455 if self.first:56 if self.build_trigger:
...
Trigger.js
Source:Trigger.js
1xdescribe("Ext.layout.component.field.Trigger", function(){2 var text, trigger, width, height;3 4 afterEach(function(){5 Ext.destroy(text, trigger);6 text = trigger = width = null;7 });8 9 describe("shrink wrap", function(){10 11 describe("without label", function() {12 13 it("should have the same size as a text field with a single trigger", function(){14 text = new Ext.form.field.Text({15 renderTo: Ext.getBody(),16 shrinkWrap: 317 });18 trigger = new Ext.form.field.Trigger({19 renderTo: Ext.getBody(),20 shrinkWrap: 321 });22 width = text.getWidth();23 24 expect(trigger.getWidth()).toBe(width);25 expect(trigger.inputEl.getWidth()).toBe(width - trigger.getTriggerWidth());26 });27 28 it("should have the same size as a text field with a 3 triggers", function(){29 text = new Ext.form.field.Text({30 renderTo: Ext.getBody(),31 shrinkWrap: 332 });33 trigger = new Ext.form.field.Trigger({34 renderTo: Ext.getBody(),35 shrinkWrap: 3,36 trigger1Cls: 'foo',37 trigger2Cls: 'bar',38 trigger3Cls: 'baz'39 });40 width = text.getWidth();41 42 expect(trigger.getWidth()).toBe(width);43 expect(trigger.inputEl.getWidth()).toBe(width - trigger.getTriggerWidth());44 });45 46 it("should respect an inputWidth", function(){47 trigger = new Ext.form.field.Trigger({48 renderTo: Ext.getBody(),49 shrinkWrap: 3,50 inputWidth: 20051 });52 expect(trigger.getWidth()).toBe(200);53 expect(trigger.inputEl.getWidth()).toBe(200 - trigger.getTriggerWidth());54 });55 });56 57 describe("with label", function(){58 59 describe("labelAlign: 'left'", function() {60 61 it("should take into account labelWidth", function(){62 text = new Ext.form.field.Text({63 renderTo: Ext.getBody(),64 shrinkWrap: 3,65 labelWidth: 150,66 fieldLabel: 'A label'67 });68 trigger = new Ext.form.field.Trigger({69 renderTo: Ext.getBody(),70 shrinkWrap: 3,71 labelWidth: 150,72 fieldLabel: 'A label'73 });74 width = text.getWidth();75 76 expect(trigger.getWidth()).toBe(width);77 expect(trigger.inputEl.getWidth()).toBe(width - trigger.getTriggerWidth() - trigger.labelWidth - trigger.labelPad);78 });79 80 it("should take into account labelPad", function(){81 text = new Ext.form.field.Text({82 renderTo: Ext.getBody(),83 shrinkWrap: 3,84 labelPad: 20,85 fieldLabel: 'A label'86 });87 trigger = new Ext.form.field.Trigger({88 renderTo: Ext.getBody(),89 shrinkWrap: 3,90 labelPad: 20,91 fieldLabel: 'A label'92 });93 width = text.getWidth();94 95 expect(trigger.getWidth()).toBe(width);96 expect(trigger.inputEl.getWidth()).toBe(width - trigger.getTriggerWidth() - trigger.labelWidth - trigger.labelPad);97 });98 });99 100 describe("labelAlign: 'top'", function(){101 it("should take ignore labelWidth", function(){102 text = new Ext.form.field.Text({103 renderTo: Ext.getBody(),104 shrinkWrap: 3,105 labelWidth: 150,106 fieldLabel: 'A label',107 labelAlign: 'top'108 });109 trigger = new Ext.form.field.Trigger({110 renderTo: Ext.getBody(),111 shrinkWrap: 3,112 labelWidth: 150,113 fieldLabel: 'A label',114 labelAlign: 'top'115 });116 width = text.getWidth();117 118 expect(trigger.getWidth()).toBe(width);119 expect(trigger.inputEl.getWidth()).toBe(width - trigger.getTriggerWidth());120 });121 122 it("should take into account labelPad", function(){123 text = new Ext.form.field.Text({124 renderTo: Ext.getBody(),125 shrinkWrap: 3,126 labelPad: 20,127 fieldLabel: 'A label',128 labelAlign: 'top'129 });130 trigger = new Ext.form.field.Trigger({131 renderTo: Ext.getBody(),132 shrinkWrap: 3,133 labelPad: 20,134 fieldLabel: 'A label',135 labelAlign: 'top'136 });137 width = text.getWidth();138 139 expect(trigger.getWidth()).toBe(width);140 expect(trigger.inputEl.getWidth()).toBe(width - trigger.getTriggerWidth());141 });142 });143 });144 145 });146 147 describe("configured", function() {148 describe("height", function() {149 beforeEach(function() {150 text = new Ext.form.field.Text({151 renderTo: Ext.getBody(),152 height: 200153 });154 trigger = new Ext.form.field.Trigger({155 renderTo: Ext.getBody(),156 height: 200157 });158 159 height = text.getHeight();160 });161 162 it("should have the same height as text field", function() {163 expect(trigger.getHeight()).toBe(height);164 // AND165 expect(trigger.inputEl.getHeight()).toBe(height);166 });167 });168 169 describe("width", function() {170 beforeEach(function() {171 text = new Ext.form.field.Text({172 renderTo: Ext.getBody(),173 width: 300174 });175 176 trigger = new Ext.form.field.Trigger({177 renderTo: Ext.getBody(),178 hideTrigger: true,179 width: 300180 });181 182 width = text.getWidth();183 });184 185 it("should have the same width as text field w/o trigger", function() {186 expect(trigger.getWidth()).toBe(width);187 // AND188 expect(trigger.inputEl.getWidth()).toBe(width);189 });190 191 it("should have the same overall width as text field w/ trigger", function() {192 var outerWidth = trigger.getWidth();193 194 expect(outerWidth).toBe(width);195 196 var inputWidth = trigger.inputEl.getWidth(),197 triggerWidth = 0;198 199 for (var i = 0, l = trigger.triggerEl.elements.length; i < l; i++) {200 var el = trigger.triggerEl.elements[i];201 202 triggerWidth += el.getWidth();203 }204 205 expect(inputWidth + triggerWidth).toBe(width);206 });207 });208 });...
ve.ui.TriggerRegistry.js
Source:ve.ui.TriggerRegistry.js
1/*!2 * VisualEditor UserInterface TriggerRegistry class.3 *4 * @copyright 2011-2020 VisualEditor Team and others; see http://ve.mit-license.org5 */6/**7 * Trigger registry.8 *9 * @class10 * @extends OO.Registry11 * @constructor12 */13ve.ui.TriggerRegistry = function VeUiTriggerRegistry() {14 // Parent constructor15 ve.ui.TriggerRegistry.super.call( this );16 this.triggersByString = {};17};18/* Inheritance */19OO.inheritClass( ve.ui.TriggerRegistry, OO.Registry );20/* Methods */21/**22 * Register a constructor with the factory.23 *24 * The only supported platforms are 'mac' and 'pc'. All platforms not identified as 'mac' will be25 * considered to be 'pc', including 'win', 'linux', 'solaris', etc.26 *27 * @param {string|string[]} name Symbolic name or list of symbolic names28 * @param {ve.ui.Trigger[]|Object} triggers Trigger object(s) or map of trigger object(s) keyed by29 * platform name e.g. 'mac' or 'pc'30 * @throws {Error} Trigger must be an instance of ve.ui.Trigger31 * @throws {Error} Incomplete trigger32 */33ve.ui.TriggerRegistry.prototype.register = function ( name, triggers ) {34 var i, l, triggerList, trigger,35 platform = ve.getSystemPlatform(),36 platformKey = platform === 'mac' ? 'mac' : 'pc';37 if ( ve.isPlainObject( triggers ) ) {38 if ( Object.prototype.hasOwnProperty.call( triggers, platformKey ) ) {39 triggerList = Array.isArray( triggers[ platformKey ] ) ? triggers[ platformKey ] : [ triggers[ platformKey ] ];40 } else {41 return;42 }43 } else {44 triggerList = Array.isArray( triggers ) ? triggers : [ triggers ];45 }46 // Validate arguments47 for ( i = 0, l = triggerList.length; i < l; i++ ) {48 trigger = triggerList[ i ];49 if ( !( triggerList[ i ] instanceof ve.ui.Trigger ) ) {50 throw new Error( 'Trigger must be an instance of ve.ui.Trigger' );51 }52 if ( !triggerList[ i ].isComplete() ) {53 throw new Error( 'Incomplete trigger' );54 }55 this.triggersByString[ trigger.toString() ] = name;56 }57 ve.ui.TriggerRegistry.super.prototype.register.call( this, name, triggerList );58};59/**60 * Get trigger name from its string representation61 *62 * @param {string} triggerString Normalized trigger string (generated by Trigger.toString)63 * @return {string|undefined} Trigger name, if found64 */65ve.ui.TriggerRegistry.prototype.getNameByTrigger = function ( triggerString ) {66 return this.triggersByString[ triggerString ];67};68/**69 * Get trigger messages for a trigger by name70 *71 * @param {string} name Symbolic name72 * @return {string[]} List of trigger messages73 */74ve.ui.TriggerRegistry.prototype.getMessages = function ( name ) {75 return ( this.lookup( name ) || [] ).map( function ( trigger ) {76 return trigger.getMessage();77 } );78};79/* Initialization */80ve.ui.triggerRegistry = new ve.ui.TriggerRegistry();81/* Registrations */82ve.ui.triggerRegistry.register(83 'undo', { mac: new ve.ui.Trigger( 'cmd+z' ), pc: new ve.ui.Trigger( 'ctrl+z' ) }84);85ve.ui.triggerRegistry.register(86 'redo', {87 mac: [88 new ve.ui.Trigger( 'cmd+shift+z' ),89 new ve.ui.Trigger( 'cmd+y' )90 ],91 pc: [92 new ve.ui.Trigger( 'ctrl+shift+z' ),93 new ve.ui.Trigger( 'ctrl+y' )94 ]95 }96);97ve.ui.triggerRegistry.register(98 'bold', { mac: new ve.ui.Trigger( 'cmd+b' ), pc: new ve.ui.Trigger( 'ctrl+b' ) }99);100ve.ui.triggerRegistry.register(101 'italic', { mac: new ve.ui.Trigger( 'cmd+i' ), pc: new ve.ui.Trigger( 'ctrl+i' ) }102);103ve.ui.triggerRegistry.register(104 'link', { mac: new ve.ui.Trigger( 'cmd+k' ), pc: new ve.ui.Trigger( 'ctrl+k' ) }105);106ve.ui.triggerRegistry.register(107 'clear', {108 mac: [109 new ve.ui.Trigger( 'cmd+\\' )110 ],111 pc: [112 new ve.ui.Trigger( 'ctrl+\\' ),113 new ve.ui.Trigger( 'ctrl+m' )114 ]115 }116);117ve.ui.triggerRegistry.register(118 'underline', { mac: new ve.ui.Trigger( 'cmd+u' ), pc: new ve.ui.Trigger( 'ctrl+u' ) }119);120ve.ui.triggerRegistry.register(121 'code', { mac: new ve.ui.Trigger( 'cmd+shift+6' ), pc: new ve.ui.Trigger( 'ctrl+shift+6' ) }122);123ve.ui.triggerRegistry.register(124 'strikethrough', { mac: new ve.ui.Trigger( 'cmd+shift+5' ), pc: new ve.ui.Trigger( 'ctrl+shift+5' ) }125);126ve.ui.triggerRegistry.register(127 'subscript', { mac: new ve.ui.Trigger( 'cmd+,' ), pc: new ve.ui.Trigger( 'ctrl+,' ) }128);129ve.ui.triggerRegistry.register(130 'superscript', { mac: new ve.ui.Trigger( 'cmd+.' ), pc: new ve.ui.Trigger( 'ctrl+.' ) }131);132ve.ui.triggerRegistry.register(133 'indent', {134 mac: [135 new ve.ui.Trigger( 'tab' ),136 new ve.ui.Trigger( 'cmd+]' )137 ],138 pc: [139 new ve.ui.Trigger( 'tab' ),140 new ve.ui.Trigger( 'ctrl+]' )141 ]142 }143);144ve.ui.triggerRegistry.register(145 'outdent', {146 mac: [147 new ve.ui.Trigger( 'shift+tab' ),148 new ve.ui.Trigger( 'cmd+[' )149 ],150 pc: [151 new ve.ui.Trigger( 'shift+tab' ),152 new ve.ui.Trigger( 'ctrl+[' )153 ]154 }155);156ve.ui.triggerRegistry.register(157 'commandHelp', {158 mac: [159 new ve.ui.Trigger( 'cmd+/' ),160 new ve.ui.Trigger( 'cmd+shift+/' ) // =cmd+? on most systems, but not all161 ],162 pc: [163 new ve.ui.Trigger( 'ctrl+/' ),164 new ve.ui.Trigger( 'ctrl+shift+/' ) // =ctrl+? on most systems, but not all165 ]166 }167);168// Ctrl+0-7 below are not mapped to Cmd+0-7 on Mac because Chrome reserves those for switching tabs169ve.ui.triggerRegistry.register(170 'paragraph', new ve.ui.Trigger( 'ctrl+0' )171);172ve.ui.triggerRegistry.register(173 'heading1', new ve.ui.Trigger( 'ctrl+1' )174);175ve.ui.triggerRegistry.register(176 'heading2', new ve.ui.Trigger( 'ctrl+2' )177);178ve.ui.triggerRegistry.register(179 'heading3', new ve.ui.Trigger( 'ctrl+3' )180);181ve.ui.triggerRegistry.register(182 'heading4', new ve.ui.Trigger( 'ctrl+4' )183);184ve.ui.triggerRegistry.register(185 'heading5', new ve.ui.Trigger( 'ctrl+5' )186);187ve.ui.triggerRegistry.register(188 'heading6', new ve.ui.Trigger( 'ctrl+6' )189);190ve.ui.triggerRegistry.register(191 'preformatted', new ve.ui.Trigger( 'ctrl+7' )192);193ve.ui.triggerRegistry.register(194 'blockquote', new ve.ui.Trigger( 'ctrl+8' )195);196ve.ui.triggerRegistry.register(197 'selectAll', { mac: new ve.ui.Trigger( 'cmd+a' ), pc: new ve.ui.Trigger( 'ctrl+a' ) }198);199ve.ui.triggerRegistry.register(200 'delete', { mac: new ve.ui.Trigger( 'ctrl+d' ) }201);202ve.ui.triggerRegistry.register(203 'pasteSpecial', {204 mac: new ve.ui.Trigger( 'cmd+option+shift+v' ),205 pc: new ve.ui.Trigger( 'ctrl+shift+v' )206 }207);208// Clipboard handlers are registered for use by the commandHelpRegistry.209// Cut/copy/paste are handled by native events.210ve.ui.triggerRegistry.register(211 'cut', {212 mac: new ve.ui.Trigger( 'cmd+x' ),213 pc: new ve.ui.Trigger( 'ctrl+x' )214 }215);216ve.ui.triggerRegistry.register(217 'copy', {218 mac: new ve.ui.Trigger( 'cmd+c' ),219 pc: new ve.ui.Trigger( 'ctrl+c' )220 }221);222ve.ui.triggerRegistry.register(223 'paste', {224 mac: new ve.ui.Trigger( 'cmd+v' ),225 pc: new ve.ui.Trigger( 'ctrl+v' )226 }227);228ve.ui.triggerRegistry.register(229 'findAndReplace', { mac: new ve.ui.Trigger( 'cmd+f' ), pc: new ve.ui.Trigger( 'ctrl+f' ) }230);231ve.ui.triggerRegistry.register(232 'changeDirectionality', { mac: new ve.ui.Trigger( 'cmd+shift+x' ), pc: new ve.ui.Trigger( 'ctrl+shift+x' ) }233);234ve.ui.triggerRegistry.register(235 'findNext', {236 mac: new ve.ui.Trigger( 'cmd+g' ),237 pc: [238 new ve.ui.Trigger( 'ctrl+g' ),239 new ve.ui.Trigger( 'f3' )240 ]241 }242);243ve.ui.triggerRegistry.register(244 'findPrevious', {245 mac: new ve.ui.Trigger( 'cmd+shift+g' ),246 pc: [247 new ve.ui.Trigger( 'shift+ctrl+g' ),248 new ve.ui.Trigger( 'shift+f3' )249 ]250 }251);252ve.ui.triggerRegistry.register(253 'enterTableCell', [254 new ve.ui.Trigger( 'enter' ),255 new ve.ui.Trigger( 'shift+enter' ),256 new ve.ui.Trigger( 'f2' )257 ]258);259ve.ui.triggerRegistry.register(260 'submit', {261 mac: new ve.ui.Trigger( 'cmd+enter' ),262 pc: new ve.ui.Trigger( 'ctrl+enter' )263 }264);265ve.ui.triggerRegistry.register(266 'focusContext', {267 mac: new ve.ui.Trigger( 'cmd+shift+enter' ),268 pc: new ve.ui.Trigger( 'ctrl+shift+enter' )269 }...
input.trigger.js
Source:input.trigger.js
...76 actions = this.options.triggerAction.split('|')77 $.each(actions, function(index, action) {78 self.updateTargetAction(action, status)79 })80 $(window).trigger('resize')81 this.$el.trigger('oc.triggerOn.afterUpdate', status)82 }83 TriggerOn.prototype.updateTargetAction = function(action, status) {84 if (action == 'show') {85 this.$el86 .toggleClass('hide', !status)87 .trigger('hide.oc.triggerapi', [!status])88 }89 else if (action == 'hide') {90 this.$el91 .toggleClass('hide', status)92 .trigger('hide.oc.triggerapi', [status])93 }94 else if (action == 'enable') {95 this.$el96 .prop('disabled', !status)97 .toggleClass('control-disabled', !status)98 .trigger('disable.oc.triggerapi', [!status])99 }100 else if (action == 'disable') {101 this.$el102 .prop('disabled', status)103 .toggleClass('control-disabled', status)104 .trigger('disable.oc.triggerapi', [status])105 }106 else if (action == 'empty' && status) {107 this.$el108 .not('input[type=checkbox], input[type=radio], input[type=button], input[type=submit]')109 .val('')110 this.$el111 .not(':not(input[type=checkbox], input[type=radio])')112 .prop('checked', false)113 this.$el114 .trigger('empty.oc.triggerapi')115 .trigger('change')116 }117 if (action == 'show' || action == 'hide') {118 this.fixButtonClasses()119 }120 }121 TriggerOn.prototype.fixButtonClasses = function() {122 var group = this.$el.closest('.btn-group')123 if (group.length > 0 && this.$el.is(':last-child'))124 this.$el.prev().toggleClass('last', this.$el.hasClass('hide'))125 }126 TriggerOn.DEFAULTS = {127 triggerAction: false,128 triggerCondition: false,129 triggerClosestParent: undefined,...
sample.js
Source:sample.js
1"use strict";2var test = require("reducers/test/util/test")3var event = require("reducers/test/util/event")4var take = require("reducers/take")5var concat = require("reducers/concat")6var delay = require("reducers/delay")7var end = require("reducible/end")8var sample = require("../sample")9exports["test input ends sampled"] = test(function(assert) {10 var stop = event()11 var input = event()12 var trigger = event()13 var sampled = sample(input, trigger)14 var actual = concat(sampled, stop)15 assert(actual, [3, 5, 5, 5], "trigger ends sample")16 input.send(1)17 input.send(2)18 input.send(3)19 trigger.send()20 input.send(4)21 input.send(5)22 trigger.send()23 trigger.send()24 trigger.send()25 input.send(6)26 input.send(end)27 assert.ok(input.isReduced, "input is reduced")28 assert.ok(!trigger.isReduced, "trigger is not reduced")29 input.send(6)30 trigger.send()31 assert.ok(trigger.isReduced, "trigger is reduced on next yield")32 trigger.send()33 trigger.send()34 input.send(7)35 stop.send(end)36})37exports["test trigger ends sampled"] = test(function(assert) {38 var stop = event()39 var input = event()40 var trigger = event()41 var sampled = sample(input, trigger)42 var actual = concat(sampled, stop)43 assert(actual, [3, 5, 5], "input ends sample")44 input.send(1)45 input.send(2)46 input.send(3)47 trigger.send()48 input.send(4)49 input.send(5)50 trigger.send()51 trigger.send()52 trigger.send(end)53 assert.ok(trigger.isReduced, "trigger is reduced")54 assert.ok(!input.isReduced, "input is not reduced")55 input.send(6)56 assert.ok(input.isReduced, "input is reduced on next yield")57 input.send(7)58 stop.send(end)59})60exports["test trigger starts early"] = test(function(assert) {61 var stop = event()62 var input = event()63 var trigger = event()64 var sampled = sample(input, trigger)65 var actual = concat(sampled, stop)66 assert(actual, [1, 3, 5, 5], "early trigger")67 trigger.send()68 trigger.send()69 trigger.send()70 input.send(1)71 input.send(2)72 input.send(3)73 trigger.send()74 input.send(4)75 input.send(5)76 trigger.send()77 trigger.send()78 trigger.send(end)79 assert.ok(trigger.isReduced, "trigger is reduced")80 assert.ok(!input.isReduced, "input is not reduced")81 input.send(6)82 assert.ok(input.isReduced, "input is reduced on next yield")83 input.send(7)84 stop.send(end)85})86exports["test stop reduction before end"] = test(function(assert) {87 var input = event()88 var trigger = event()89 var stop = event()90 var pairs = take(sample(input, trigger), 6)91 var actual = concat(pairs, stop)92 assert(actual, [2, 2, 3, 3, 4, 4], "either end ends coreduction")93 input.send(1)94 input.send(2)95 trigger.send()96 trigger.send()97 input.send(3)98 trigger.send()99 input.send(3)100 trigger.send()101 input.send(4)102 trigger.send()103 trigger.send()104 assert.ok(trigger.isReduced, "trigger is closed")105 assert.ok(!input.isReduced, "input is not reduced yet")106 input.send(5)107 assert.ok(input.isReduced, "input is reduced on next yield")108 trigger.send()109 input.send(6)110 trigger.send()111 stop.send(end)112})113exports["test error in trigger propagates"] = test(function(assert) {114 var boom = Error("Boom!!")115 var input = event()116 var trigger = event()117 var actual = delay(sample(input, trigger))118 assert(actual, {119 error: boom,120 values: [2, 2, 3, 3, 4, 4]121 }, "error propagate to reducer and stops reducibles")122 input.send(1)123 input.send(2)124 trigger.send()125 trigger.send()126 input.send(3)127 trigger.send()128 input.send(3)129 trigger.send()130 input.send(4)131 trigger.send()132 trigger.send()133 trigger.send(boom)134 assert.ok(trigger.isReduced, "trigger is closed or error")135 assert.ok(!input.isReduced, "input is not closed yet")136 input.send(5)137 assert.ok(input.isReduced, "input is reduced on next yield")138 trigger.send()139 input.send(6)140 trigger.send()141})142exports["test error in input propagates"] = test(function(assert) {143 var boom = Error("Boom!!")144 var input = event()145 var trigger = event()146 var actual = delay(sample(input, trigger))147 assert(actual, {148 error: boom,149 values: [2, 2, 3, 3, 4, 4]150 }, "error propagate to reducer and stops reducibles")151 input.send(1)152 input.send(2)153 trigger.send()154 trigger.send()155 input.send(3)156 trigger.send()157 input.send(3)158 trigger.send()159 input.send(4)160 trigger.send()161 trigger.send()162 input.send(boom)163 assert.ok(!trigger.isReduced, "trigger is not yet")164 assert.ok(input.isReduced, "input is closed on error")165 trigger.send()166 assert.ok(trigger.isReduced, "trigger is reduced on next yield")167 trigger.send()168 input.send(6)169 trigger.send()170})171exports["test assembler"] = test(function(assert) {172 var stop = event()173 var input = event()174 var trigger = event()175 var sampled = sample(input, trigger, function(value, beat) {176 return value + beat177 })178 var actual = concat(sampled, stop)179 assert(actual, ["3a", "5b", "5c", "5d"], "trigger ends sample")180 input.send(1)181 input.send(2)182 input.send(3)183 trigger.send("a")184 input.send(4)185 input.send(5)186 trigger.send("b")187 trigger.send("c")188 trigger.send("d")189 input.send(6)190 input.send(end)191 assert.ok(input.isReduced, "input is reduced")192 assert.ok(!trigger.isReduced, "trigger is not reduced")193 input.send(6)194 trigger.send("e")195 assert.ok(trigger.isReduced, "trigger is reduced on next yield")196 trigger.send("f")197 trigger.send("g")198 input.send(7)199 stop.send(end)200})201exports["test assemble with prior trigger"] = test(function(assert) {202 var stop = event()203 var input = event()204 var trigger = event()205 var sampled = sample(input, trigger, function(value, trigger) {206 return value + trigger207 })208 var actual = concat(sampled, stop)209 assert(actual, ["1c", "3d", "5e", "5f"], "early trigger")210 trigger.send("a")211 trigger.send("b")212 trigger.send("c")213 input.send(1)214 input.send(2)215 input.send(3)216 trigger.send("d")217 input.send(4)218 input.send(5)219 trigger.send("e")220 trigger.send("f")221 trigger.send(end)222 assert.ok(trigger.isReduced, "trigger is reduced")223 assert.ok(!input.isReduced, "input is not reduced")224 input.send(6)225 assert.ok(input.isReduced, "input is reduced on next yield")226 input.send(7)227 stop.send(end)...
edit-trigger-test.js
Source:edit-trigger-test.js
...40 }),41 trigger = jQuery('.translate-edit-icon'),42 editElement = jQuery('.edit'),43 container = jQuery('.container');44 editElement.trigger('mousemove');45 assertEquals(true, trigger.is(':visible'));46 container.trigger('mousemove');47 assertEquals(true, trigger.is(':hidden'));48 editTrigger.editTrigger('destroy');49};50EditTriggerTest.prototype.testTriggerClick = function() {51 /*:DOC += <div class="edit">text</div>52 <script id="translate-inline-icon" type="text/x-magento-template">53 <img alt="<%= data.alt %>" src="<%= data.img %>" height="16" width="16" class="translate-edit-icon">54 </script>55 */56 var editTrigger = jQuery('body').editTrigger({57 editSelector: '.edit'58 }),59 trigger = jQuery('.translate-edit-icon'),60 editElement = jQuery('.edit'),61 editTriggered = false;62 $('body').on('edit.editTrigger', function() { editTriggered = true; });63 editElement.trigger('mousemove');64 trigger.trigger('click');65 assertEquals(true, editTriggered);66 editTrigger.editTrigger('destroy');67};68EditTriggerTest.prototype.testDestroy = function() {69 var editTrigger = jQuery('body').editTrigger(),70 editProcessed = false,71 mousemoveProcessed = false;72 73 $('body')74 .on('edit.editTrigger', function() {editProcessed = true;})75 .on('mousemove.editTrigger', function() {mousemoveProcessed = true;});76 77 editTrigger.editTrigger('destroy'); 78 assertEquals(false, !!editTrigger.data('mageEditTrigger'));79 $('body').trigger('edit.editTrigger');80 assertEquals(false, editProcessed);81 82 $('body').trigger('mousemove.editTrigger');83 assertEquals(false, mousemoveProcessed);84};85var EditTriggerTestAsync = AsyncTestCase('EditTriggerTestAsync');86EditTriggerTestAsync.prototype.testHideEditTriggerWithDelay = function(queue) {87 /*:DOC += <div class="container" style="height:100px;">88 <div class="edit">text</div>89 </div>90 <script id="translate-inline-icon" type="text/x-magento-template">91 <img alt="<%= data.alt %>" src="<%= data.img %>" height="16" width="16" class="translate-edit-icon">92 </script>93 */94 var editTrigger = jQuery(document).editTrigger({95 editSelector: '.edit',96 delay: 100097 }),98 trigger = jQuery('.translate-edit-icon'),99 editElement = jQuery('.edit'),100 container = jQuery('.container'),101 visibleOnMouseout,102 hiddenAfterDelay;103 editElement.trigger('mousemove');104 container.trigger('mousemove');105 queue.call('Step 1: Start hiding with delay', function(callbacks) {106 visibleOnMouseout = trigger.is(':visible');107 setTimeout(callbacks.add(function() {108 hiddenAfterDelay = trigger.is(':hidden');109 }), 1050);110 });111 queue.call('Step 2: Check is trigger are hidden after delay', function() {112 assertEquals(true, visibleOnMouseout);113 assertEquals(true, hiddenAfterDelay);114 editTrigger.editTrigger('destroy');115 });...
Using AI Code Generation
1import { trigger } from 'ng-mocks';2import { Component, DebugElement } from '@angular/core';3import { ComponentFixture, TestBed } from '@angular/core/testing';4import { By } from '@angular/platform-browser';5@Component({6 template: '<div (click)="onClick()">Click me</div>',7})8class TestComponent {9 public onClick() {10 }11}12describe('TestComponent', () => {13 let component: TestComponent;14 let fixture: ComponentFixture<TestComponent>;15 let div: DebugElement;16 beforeEach(() => {17 TestBed.configureTestingModule({18 });19 fixture = TestBed.createComponent(TestComponent);20 component = fixture.componentInstance;21 div = fixture.debugElement.query(By.css('div'));22 });23 it('should call onClick', () => {24 const spy = spyOn(component, 'onClick');25 trigger(div, 'click');26 expect(spy).toHaveBeenCalled();27 });28});29import { TestComponent } from './test';30describe('TestComponent', () => {31 it('should call onClick', () => {32 const spy = spyOn(TestComponent.prototype, 'onClick');33 trigger(TestComponent, 'click');34 expect(spy).toHaveBeenCalled();35 });36});37import { TestComponent } from './test';38describe('TestComponent', () => {39 it('should call onClick', () => {40 const spy = spyOn(TestComponent.prototype, 'onClick');41 trigger(TestComponent, 'click');42 expect(spy).toHaveBeenCalled();43 });44});45import { TestComponent } from './test';46describe('TestComponent', () => {47 it('should call onClick', () => {48 const spy = spyOn(TestComponent.prototype, 'onClick');49 trigger(TestComponent, 'click');50 expect(spy).toHaveBeenCalled();51 });52});53import { TestComponent } from './test';54describe('TestComponent', () => {55 it('should call onClick', () => {56 const spy = spyOn(TestComponent.prototype, 'onClick');57 trigger(TestComponent, 'click');58 expect(spy).toHaveBeenCalled();59 });60});
Using AI Code Generation
1import { ComponentFixture, TestBed } from '@angular/core/testing';2import { By } from '@angular/platform-browser';3import { MyComponent } from './my.component';4describe('MyComponent', () => {5 let component: MyComponent;6 let fixture: ComponentFixture<MyComponent>;7 beforeEach(() => {8 TestBed.configureTestingModule({9 });10 fixture = TestBed.createComponent(MyComponent);11 component = fixture.componentInstance;12 fixture.detectChanges();13 });14 it('should trigger click', () => {15 const spy = spyOn(component, 'onClick');16 const button = fixture.debugElement.query(By.css('button'));17 button.triggerEventHandler('click', {});18 expect(spy).toHaveBeenCalled();19 });20});
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { MyComponent } from './my.component';3beforeEach(() => MockBuilder(MyComponent));4it('triggers click', () => {5 const fixture = MockRender(MyComponent);6 const button = ngMocks.find('button');7 ngMocks.trigger(button, 'click');8 expect(fixture.point.componentInstance.clicked).toBe(true);9});10import { Component } from '@angular/core';11@Component({12 template: '<button (click)="clicked = true">Click me</button>',13})14export class MyComponent {15 public clicked = false;16}17import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';18import { MyComponent } from './my.component';19beforeEach(() => MockBuilder(MyComponent));20it('triggers click', () => {21 const fixture = MockRender(MyComponent);22 const button = ngMocks.find('button');23 ngMocks.trigger(button, 'click');24 expect(fixture.point.componentInstance.clicked).toBe(true);25});26import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';27import { MyComponent } from './my.component';28beforeEach(() => MockBuilder(MyComponent));29it('triggers click', () => {30 const fixture = MockRender(MyComponent);31 const button = ngMocks.find('button');32 ngMocks.trigger(button, 'click');33 expect(fixture.point.componentInstance.clicked).toBe(true);34});35import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';36import { MyComponent } from './my.component';37beforeEach(() => MockBuilder(MyComponent));38it('triggers click', () => {39 const fixture = MockRender(MyComponent);40 const button = ngMocks.find('button');41 ngMocks.trigger(button, 'click');42 expect(fixture.point.componentInstance.clicked).toBe(true);43});44import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';45import { MyComponent } from './my.component';46beforeEach(() => MockBuilder(MyComponent));47it('triggers click', () => {48 const fixture = MockRender(MyComponent);49 const button = ngMocks.find('button');50 ngMocks.trigger(button, 'click');51 expect(fixture
Using AI Code Generation
1import { trigger } from 'ng-mocks';2import { Component } from '@angular/core';3import { TestBed } from '@angular/core/testing';4import { By } from '@angular/platform-browser';5@Component({6 <div (click)="onClick($event)">click me</div>7})8class TargetComponent {9 public onClick(event: any): void {10 console.log(event);11 }12}13describe('TargetComponent', () => {14 it('triggers click', () => {15 TestBed.configureTestingModule({16 });17 const fixture = TestBed.createComponent(TargetComponent);18 fixture.detectChanges();19 const debugElement = fixture.debugElement.query(By.css('div'));20 trigger(debugElement, 'click');21 });22});23import { trigger } from 'ng-mocks';24import { Component } from '@angular/core';25import { TestBed } from '@angular/core/testing';26import { By } from '@angular/platform-browser';27@Component({28 <div (click)="onClick($event)">click me</div>29})30class TargetComponent {31 public onClick(event: any): void {32 console.log(event);33 }34}35describe('TargetComponent', () => {36 it('triggers click', () => {37 TestBed.configureTestingModule({38 });39 const fixture = TestBed.createComponent(TargetComponent);40 fixture.detectChanges();41 const debugElement = fixture.debugElement.query(By.css('div'));42 trigger(debugElement, 'click', { button: 1 });43 });44});45import { trigger } from 'ng-mocks';46import { Component } from '@angular/core';47import { TestBed } from '@angular/core/testing';48import { By } from '@angular/platform-browser';49@Component({50 <div (click)="onClick($event)">click me</div>51})52class TargetComponent {53 public onClick(event: any): void {54 console.log(event);55 }56}57describe('TargetComponent', () => {58 it('triggers click', () => {59 TestBed.configureTestingModule({60 });61 const fixture = TestBed.createComponent(TargetComponent
Using AI Code Generation
1import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';2import { AppModule } from './app.module';3import { AppComponent } from './app.component';4describe('AppComponent', () => {5 beforeEach(() => MockBuilder(AppComponent, AppModule));6 it('should render the component', () => {7 const fixture = MockRender(AppComponent);
Using AI Code Generation
1import { ngMocks } from 'ng-mocks';2import { ngMocks } from 'ng-mocks';3describe('AppComponent', () => {4 let fixture: ComponentFixture<AppComponent>;5 beforeEach(() => {6 fixture = ngMocks.faster(TestBed.configureTestingModule({7 }).createComponent(AppComponent));8 });9 it('should create', () => {10 expect(fixture).toBeDefined();11 });12});13ngMocks.faster<T>(component: ComponentFixture<T>): ComponentFixture<T>;14import { ngMocks } from 'ng-mocks';15describe('AppComponent', () => {16 let fixture: ComponentFixture<AppComponent>;17 beforeEach(() => {18 fixture = ngMocks.faster(TestBed.configureTestingModule({19 }).createComponent(AppComponent));20 });21 it('should create', () => {22 expect(fixture).toBeDefined();23 });24});25ngMocks.flush<T>(component: ComponentFixture<T>): ComponentFixture<T>;26import { ngMocks } from 'ng-mocks';27describe('AppComponent', () => {28 let fixture: ComponentFixture<AppComponent>;29 beforeEach(() => {30 fixture = ngMocks.faster(TestBed.configureTestingModule({31 }).createComponent(AppComponent));32 });33 it('should create', () => {34 expect(fixture).toBeDefined();35 });36});37ngMocks.find<T>(component: ComponentFixture<T>, selector: string): DebugElement | null;38import { ngMocks } from 'ng-mocks';39describe('AppComponent', () => {40 let fixture: ComponentFixture<AppComponent>;41 beforeEach(() => {42 fixture = ngMocks.flush(TestBed.configureTestingModule({43 }).createComponent(AppComponent));44 });45 it('should create', () => {
Using AI Code Generation
1describe('TestComponent', () => {2 let component: TestComponent;3 let fixture: ComponentFixture<TestComponent>;4 beforeEach(async(() => {5 TestBed.configureTestingModule({6 })7 .compileComponents();8 }));9 beforeEach(() => {10 fixture = TestBed.createComponent(TestComponent);11 component = fixture.componentInstance;12 });13 it('should create', () => {14 expect(component).toBeTruthy();15 });16 it('should call the method when button is clicked', () => {17 spyOn(component, 'onButtonClick');18 const button = fixture.debugElement.nativeElement.querySelector('button');19 button.click();20 expect(component.onButtonClick).toHaveBeenCalled();21 });22 it('should call the method when button is clicked', () => {23 spyOn(component, 'onButtonClick');24 const button = fixture.debugElement.nativeElement.querySelector('button');25 button.click();26 expect(component.onButtonClick).toHaveBeenCalled();27 });28 it('should call the method when button is clicked', () => {29 const button = fixture.debugElement.nativeElement.querySelector('button');30 button.click();31 expect(component.onButtonClick).toHaveBeenCalled();32 });33 it('should call the method when button is clicked', () => {34 const button = fixture.debugElement.nativeElement.querySelector('button');35 button.click();36 expect(component.onButtonClick).toHaveBeenCalled();37 });38 it('should call the method when button is clicked', () => {39 const button = fixture.debugElement.nativeElement.querySelector('button');40 button.click();41 expect(component.onButtonClick).toHaveBeenCalled();42 });43 it('should call the method when button is clicked', () => {44 const button = fixture.debugElement.nativeElement.querySelector('button');45 button.click();46 expect(component.onButtonClick).toHaveBeenCalled();47 });48 it('should call the method when button is clicked', () => {49 const button = fixture.debugElement.nativeElement.querySelector('button');50 button.click();51 expect(component.onButtonClick).toHaveBeenCalled();52 });53 it('should call the method when button is clicked', () => {54 const button = fixture.debugElement.nativeElement.querySelector('button');55 button.click();56 expect(component.onButtonClick).toHaveBeenCalled();57 });58 it('should call the method when button is clicked', () => {59 const button = fixture.debugElement.nativeElement.querySelector('button');60 button.click();61 expect(component.onButtonClick).toHaveBeenCalled();62 });63 it('should call the method when button is clicked', () =>
Using AI Code Generation
1import { TestBed } from '@angular/core/testing';2import { MockBuilder, MockRender, ngMocks } from 'ng-mocks';3import { TargetComponent } from './target.component';4describe('Trigger:target', () => {5 beforeEach(() => MockBuilder(TargetComponent));6 it('renders the target component', () => {7 const fixture = MockRender(TargetComponent);8 expect(fixture.point.componentInstance).toBeDefined();9 });10 it('triggers click', () => {11 const fixture = MockRender(TargetComponent);12 const button = ngMocks.find('button');13 ngMocks.trigger(button, 'click');14 fixture.detectChanges();15 expect(ngMocks.formatText(fixture.debugElement)).toEqual('clicked');16 });17});18import { MockInstance } from 'ng-mocks';19const mockInstance = MockInstance.of(OriginalClass, 'method');20import { Injectable } from '@angular/core';21@Injectable()22export class TargetService {23 public get(): string {24 return 'original';25 }26}27import { TestBed } from '@angular/core/testing';28import { MockBuilder, MockRender, MockInstance } from 'ng-mocks';29import { TargetComponent } from './target.component';30import { TargetService } from './target.service';31describe('MockInstance:target', () => {32 beforeEach(() => MockBuilder(TargetComponent));33 it('renders the target component', () => {34 const fixture = MockRender(TargetComponent);35 expect(fixture.point.componentInstance).toBeDefined();36 });37 it('mocks the target service', () => {38 const fixture = MockRender(TargetComponent);39 const mockInstance = MockInstance.of(TargetService, 'get');40 mockInstance.mockReturnValue('mocked');41 expect(ngMocks.formatText(fixture.debugElement)).toEqual('mocked');42 });43});
Using AI Code Generation
1import { MockBuilder, MockedComponentFixture, MockRender, ngMocks } from 'ng-mocks';2import { TestComponent } from './test.component';3describe('TestComponent', () => {4 ngMocks.faster();5 let component: TestComponent;6 let fixture: MockedComponentFixture<TestComponent>;7 beforeEach(() => MockBuilder(TestComponent));8 beforeEach(() => {9 fixture = MockRender(TestComponent);10 component = fixture.point.componentInstance;11 });12 it('should emit an event when button is clicked', () => {13 const spy = spyOn(component.clicked, 'emit');14 ngMocks.trigger(fixture.point.componentInstance.button.nativeElement, 'click');15 expect(spy).toHaveBeenCalled();16 });17});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!