How to use builder method in storybook-root

Best JavaScript code snippet using storybook-root

ld-course-builder.js

Source:ld-course-builder.js Github

copy

Full Screen

1jQuery(document).ready(function($) {2 //"use strict";3 var course_id = 0;4 var cb_form_unsaved = false;5 var builder_items_count = 0;6 var ld_builder_new_step_ajax_pid = '';7 //console.log('learndash_course_builder_assets[%o]', learndash_course_builder_assets);8 var touch = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;9 var touchEvent = touch ? 'touchstart' : 'hover';10 11 if ( jQuery( '#learndash_course_builder_box_wrap' ).length ) {12 course_id = jQuery( '#learndash_course_builder_box_wrap' ).data('ld-course-id');13 }14 if ( jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).length ) {15 // set the first selector set to open by default. 16 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container' ).each(function (index, item) {17 if ( index == 0 ) {18 jQuery( '.learndash-selector-post-listing', item).slideDown('slow', function(){19 jQuery( '.learndash-selector-header .ld-course-builder-action-show-hide', item).removeClass('ld-course-builder-action-show');20 jQuery( '.learndash-selector-header .ld-course-builder-action-show-hide', item).addClass('ld-course-builder-action-hide');21 });22 } else {23 jQuery('.learndash-selector-post-listing', item).hide();24 jQuery( '.learndash-selector-header .ld-course-builder-action-show-hide', item).addClass('ld-course-builder-action-show');25 jQuery( '.learndash-selector-header .ld-course-builder-action-show-hide', item).removeClass('ld-course-builder-action-hide');26 }27 // Since we are looping the selectors we initialize the disabled items28 var selector_type = jQuery(item).data('ld-type');29 if ( typeof selector_type !== 'undefined' ) {30 selector_update_disabled_items( selector_type );31 selector_update_empty( selector_type );32 }33 });34 //course_builder_box_wrap_resize();35 /*36 function course_builder_box_wrap_resize( e ) {37 jQuery( window ).resize(function() {38 console.log('in resize');39 40 //var ld_course_builder_box_wrap_width = jQuery( '#learndash_course_builder_box_wrap' ).width();41 //console.log('ld_course_builder_box_wrap_width[%o]', ld_course_builder_box_wrap_width);42 //if ( ld_course_builder_box_wrap_width < 500 ) {43 // jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).css( 'width', '40%' );44 // jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items' ).css( 'width', 'calc(60% - 5px)' );45 //} else {46 // jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).css( 'width', '30%' );47 // jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items' ).css( 'width', 'calc(70% - 5px)' );48 //}49 50 51 // First we want to adjust the column widths of the selectors and step items. 52 //var ld_course_builder_box_wrap_width = jQuery( '#learndash_course_builder_box_wrap' ).width();53 //console.log('ld_course_builder_box_wrap_width[%o]', ld_course_builder_box_wrap_width);54 55 //var ld_course_builder_selectors_width = jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).outerWidth();56 //console.log('ld_course_builder_selectors_width[%o]', ld_course_builder_selectors_width);57 58 //var new_Width = ld_course_builder_box_wrap_width - ld_course_builder_selectors_width;59 //console.log('new_Width[%o]', new_Width);60 //jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items' ).width(new_Width-25);61 62 // trigger resize on any edit title elements63 //course_builder_resize_title_edit();64 });65 }66 */67 //jQuery( document ).trigger( 'resize' );68 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).on( 'click', '.ld-course-builder-action-show-hide', selector_show_hide );69 function selector_show_hide( event, action ) {70 event.stopImmediatePropagation();71 72 var parent_title_el = jQuery( event.currentTarget).parents('h3');73 var parent_items_el = jQuery(parent_title_el).parent();74 var post_listing = jQuery( parent_items_el ).find('.learndash-selector-post-listing');75 if ( ( typeof action === 'undefined' ) || ( ( action != 'open') && ( action != 'close' ) ) ) {76 if ( jQuery( post_listing ).is(":visible") ) {77 action = 'close';78 } else {79 action = 'open';80 }81 } 82 if ( action == 'open' ) {83 jQuery( post_listing ).slideDown('slow', function(){84 jQuery( event.currentTarget).removeClass('ld-course-builder-action-show');85 jQuery( event.currentTarget).addClass('ld-course-builder-action-hide');86 87 });88 } else {89 jQuery( post_listing ).slideUp('slow', function(){90 jQuery( event.currentTarget).addClass('ld-course-builder-action-show');91 jQuery( event.currentTarget).removeClass('ld-course-builder-action-hide');92 });93 }94 }95 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).on( 'click', 'li', selector_click_item );96 function selector_click_item ( event ) {97 var selector_container = selector_get_type_from_item( event.currentTarget );98 if ( jQuery( event.currentTarget ).hasClass( 'ld-disabled' ) ) {99 jQuery( event.currentTarget ).removeClass( 'ld-selected' );100 } else {101 102 if ( jQuery( event.currentTarget ).hasClass( 'ld-selected' ) ) {103 jQuery( event.currentTarget ).removeClass( 'ld-selected' );104 } else {105 jQuery( event.currentTarget ).addClass( 'ld-selected' );106 }107 }108 }109 jQuery( '#learndash_course_builder_box_wrap' ).on( 'click', '.learndash_selectors .pager-info button', selector_pager_click );110 function selector_pager_click( e ) {111 e.stopImmediatePropagation();112 var selector_container = jQuery(e.currentTarget).parents( '.learndash-selector-container' );113 114 if ( typeof selector_container !== 'undefined' ) {115 var selector_type = jQuery(selector_container).data('ld-type');116 if ( typeof selector_type !== 'undefined' ) {117 118 var selector_paged = jQuery(e.currentTarget ).data('page');119 if ( typeof selector_type === 'undefined' ) {120 selector_paged = 1;121 }122 selector_pager_process( selector_paged, selector_type, selector_container );123 }124 }125 return false;126 }127 function selector_pager_process( selector_paged, selector_type, selector_container ) {128 var post_data = {129 'action': 'learndash_course_builder_selector_pager',130 'course_id': course_id,131 'query_args': {132 'post_type': selector_type,133 'paged': selector_paged134 },135 };136 jQuery.ajax({137 type: "POST",138 url: ajaxurl,139 dataType: "json",140 cache: false,141 data: post_data,142 error: function(jqXHR, textStatus, errorThrown ) {143 //console.log('init: error HTTP Status['+jqXHR.status+'] '+errorThrown);144 },145 success: function(reply_data) {146 if ( typeof reply_data !== 'undefined') {147 148 if (typeof reply_data['selector_pager'] !== 'undefined') {149 jQuery('.pager-info', selector_container).html( reply_data['selector_pager'] );150 }151 if (typeof reply_data['selector_rows'] !== 'undefined') {152 jQuery('ul.learndash-selector-post-listing', selector_container).html( reply_data['selector_rows'] );153 jQuery('ul.learndash-selector-post-listing li', selector_container).draggable( draggable_objects[selector_type] );154 155 selector_update_disabled_items( selector_type );156 }157 }158 }159 });160 }161 jQuery( '#learndash_course_builder_box_wrap' ).on( 'focus', '.learndash_selectors .learndash-selector-search input', selector_search );162 function selector_search( e ) {163 // Set time for .20 seconds. 1/5 of a second. 164 //var search_timeout = 200; 165 166 var selector_container = jQuery(e.currentTarget).parents( '.learndash-selector-container' );167 168 if ( typeof selector_container !== 'undefined' ) {169 var selector_type = jQuery(selector_container).data('ld-type');170 if ( typeof selector_type !== 'undefined' ) {171 // Hold reference to our interval loop for key press172 var search_val = '';173 174 var post_data = {175 'action': 'learndash_course_builder_selector_search',176 'course_id': course_id,177 'query_args': {178 'post_type': selector_type,179 'paged': 1,180 's': ''181 },182 };183 184 jQuery(e.currentTarget).on('keyup touchend', function(){185 search_val = jQuery(e.currentTarget).val();186 187 if ( search_val == '' ) {188 jQuery('.learndash-selector-pager', selector_container).show();189 selector_pager_process( 1, selector_type, selector_container );190 191 } else {192 jQuery('.learndash-selector-pager', selector_container).hide();193 194 if ( ( search_val.length >= 3 ) && ( search_val != post_data.query_args.s ) ) {195 post_data.query_args.s = search_val;196 197 jQuery.ajax({198 type: "POST",199 url: ajaxurl,200 dataType: "json",201 cache: false,202 data: post_data,203 error: function(jqXHR, textStatus, errorThrown ) {204 //console.log('init: error HTTP Status['+jqXHR.status+'] '+errorThrown);205 },206 success: function(reply_data) {207 208 if ( typeof reply_data !== 'undefined') {209 if ( typeof reply_data['selector_rows'] !== 'undefined') {210 jQuery('ul.learndash-selector-post-listing', selector_container).html( reply_data['selector_rows'] );211 jQuery('ul.learndash-selector-post-listing li', selector_container).draggable( draggable_objects[selector_type] );212 213 selector_update_disabled_items( selector_type );214 }215 }216 }217 });218 }219 }220 });221 }222 }223 }224 }225 function build_html_element_map( ) {226 var builder_items = new Object();227 228 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items .ld-course-builder-lesson-items' ).children().each(function( lesson_item_idx, lesson_item) {229 var lesson_id = jQuery( lesson_item ).data('ld-id');230 231 builder_items_count += 1;232 builder_items['sfwd-lessons:'+lesson_id.toString()] = {};233 jQuery('.ld-course-builder-lesson-topic-items', lesson_item ).children().each(function( topic_item_idx, topic_item) {234 235 var topic_id = jQuery( topic_item ).data('ld-id');236 237 builder_items_count += 1;238 builder_items['sfwd-lessons:'+lesson_id.toString()]['sfwd-topic:'+topic_id.toString()] = {};239 240 jQuery('.ld-course-builder-topic-quiz-items', topic_item).children().each(function( topic_quiz_item_idx, topic_quiz_item) {241 var topic_quiz_id = jQuery( topic_quiz_item ).data('ld-id');242 builder_items['sfwd-lessons:'+lesson_id.toString()]['sfwd-topic:'+topic_id.toString()]['sfwd-quiz:'+topic_quiz_id.toString()] = {};243 });244 });245 jQuery('.ld-course-builder-lesson-quiz-items', lesson_item).children().each(function( lesson_quiz_item_idx, lesson_quiz_item) {246 var lesson_quiz_id = jQuery( lesson_quiz_item ).data('ld-id');247 builder_items['sfwd-lessons:'+lesson_id.toString()]['sfwd-quiz:'+lesson_quiz_id.toString()] = {};248 });249 250 });251 var has_global_quizzes = false;252 jQuery('#learndash_course_builder_box_wrap .learndash_builder_items .ld-course-builder-course-quiz-items' ).children().each(function( quiz_item_idx, quiz_item) {253 var quiz_id = jQuery( quiz_item ).data('ld-id');254 has_global_quizzes = true;255 builder_items['sfwd-quiz:'+quiz_id.toString()] = {};256 });257 258 if ( has_global_quizzes == true )259 builder_items_count += 1;260 return builder_items;261 }262 // The following taken from https://jsfiddle.net/KyleMit/Geupm/2/263 /////////////////////////////////////////////////////////////////264 var draggable_objects = [];265 266 draggable_objects['sfwd-lessons'] = {267 cancel: '.ld-disabled',268 handle: ".ld-course-builder-action-lesson-move",269 connectToSortable: '#learndash_course_builder_box_wrap .ld-course-builder-lesson-items',270 helper: function() {271 var selected = jQuery('#learndash-selector-post-listing-sfwd-lessons li.ld-selected');272 273 if (selected.length === 0) {274 selected = $(this);275 }276 277 return ld_course_builder_draggable_helper( selected );278 } 279 };280 281 draggable_objects['sfwd-topic'] = {282 cancel: '.ld-disabled',283 handle: ".ld-course-builder-action-topic-move",284 connectToSortable: '#learndash_course_builder_box_wrap .ld-course-builder-topic-items',285 //cursor: 'move',286 helper: function() {287 var selected = jQuery('#learndash-selector-post-listing-sfwd-topic li.ld-selected');288 if (selected.length === 0) {289 selected = $(this);290 }291 return ld_course_builder_draggable_helper( selected );292 }293 };294 295 draggable_objects['sfwd-quiz'] = {296 cancel: '.ld-disabled',297 handle: ".ld-course-builder-action-quiz-move",298 connectToSortable: '#learndash_course_builder_box_wrap .ld-course-builder-quiz-items',299 //cursor: 'move',300 helper: function() {301 var selected = jQuery('#learndash-selector-post-listing-sfwd-quiz li.ld-selected');302 if (selected.length === 0) {303 selected = $(this);304 }305 return ld_course_builder_draggable_helper( selected );306 }307 };308 309 // Common helper function for the draggables310 function ld_course_builder_draggable_helper( selected ) {311 312 var container = $('<div/>').attr('id', 'ld-selector-draggable-group');313 if ( ( typeof selected !== 'undefined' ) && ( selected.length ) ) {314 var max_width = 0;315 jQuery(selected).each(function( selected_idx, selected_el ) {316 //console.log('selected_el[%o]', selected_el );317 jQuery('.ld-course-builder-sub-actions', selected_el).hide();318 var el_width = jQuery(selected_el).outerWidth();319 if ( el_width > max_width )320 max_width = el_width;321 });322 323 container.css('list-style', 'none');324 container.css('width', max_width + 'px');325 container.append(selected.clone());326 }327 return container;328 }329 330 var sortable_objects = [];331 332 sortable_objects['sfwd-lessons'] = {333 //containment: "#learndash_course_builder_box_wrap",334 items: "> div.ld-course-builder-lesson-item",335 handle: ".ld-course-builder-action-lesson-move",336 tolerance: 'pointer',337 opacity: 0.7,338 revert: 300,339 delay: 150,340 dropOnEmpty: true,341 placeholder: "movable-placeholder",342 start: function(e, ui) {343 ui.placeholder.height(ui.helper.outerHeight());344 jQuery('li', ui.helper).css('clear', 'both');345 jQuery( 'span.ld-course-builder-sub-actions', ui.helper ).hide(); 346 },347 stop: function(event, ui) {348 var element_id = jQuery( ui.item ).attr('id');349 350 if ( element_id == 'ld-selector-draggable-group' ) {351 var new_lessons = '';352 353 var ld_selected = jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-sfwd-lessons').data('ld-selected');354 if ( typeof ld_selected === 'undefined' ) {355 ld_selected = [];356 }357 ui.item.children('li').each( function( ) {358 var inner_el = this;359 var element_ld_id = jQuery( inner_el ).data('ld-id');360 ld_selected.push( parseInt( element_ld_id ) );361 jQuery( 'span.ld-course-builder-sub-actions', inner_el ).hide();362 363 //var edit_href = jQuery( 'span.ld-course-builder-sub-actions a.ld-course-builder-action-edit', inner_el ).attr('href');364 //jQuery( 'span.ld-course-builder-sub-actions a.ld-course-builder-action-edit', inner_el ).attr('href', edit_href+'&course_id='+learndash_course_builder_assets['course_id'] );365 366 new_lessons = new_lessons+'<div id="ld-course-builder-lesson-item-'+element_ld_id+'" class="ld-course-builder-item ld-course-builder-lesson-item" data-ld-type="sfwd-lessons" data-ld-id="'+element_ld_id+'">'+jQuery( inner_el ).html()+'</div>';367 368 if ( typeof element_ld_id !== 'undefined' ) {369 selector_set_item_disabled( 'sfwd-lessons', element_ld_id, true);370 selector_set_item_selected( 'sfwd-lessons', element_ld_id, false );371 }372 });373 jQuery( ui.item ).replaceWith( new_lessons );374 375 // after the Lesson(s) added we reset the jQuery UI sortable logic to include the new child items376 jQuery("#learndash_course_builder_box_wrap .ld-course-builder-topic-items").sortable( sortable_objects['sfwd-topic'] );377 jQuery("#learndash_course_builder_box_wrap .ld-course-builder-quiz-items").sortable( sortable_objects['sfwd-quiz'] );378 ld_selected = jQuery.unique( ld_selected ); 379 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-sfwd-lessons' ).data( 'ld-selected', ld_selected );380 381 update_course_builder_steps_element();382 383 } else {384 jQuery( 'span.ld-course-builder-sub-actions', ui.item ).hide();385 update_course_builder_steps_element();386 }387 }388 };389 390 sortable_objects['sfwd-topic'] = {391 //containment: "#learndash_course_builder_box_wrap",392 items: "> div.ld-course-builder-topic-item",393 handle: ".ld-course-builder-action-topic-move",394 connectWith: '.ld-course-builder-topic-items',395 placeholder: "movable-placeholder",396 tolerance: 'pointer',397 opacity: 0.7,398 revert: 300,399 delay: 150,400 dropOnEmpty: true,401 start: function(e, ui) {402 ui.placeholder.height(ui.helper.outerHeight());403 ui.placeholder.width('100%');404 jQuery( 'span.ld-course-builder-sub-actions', ui.helper ).hide();405 406 //console.log('ui.item[%o]', ui.item );407 408 //var parent_builder_item = jQuery( ui.item ).parents('.ld-course-builder-item').first();409 //console.log('parent_builder_item[%o]', parent_builder_item );410 //if ( typeof ld_selected === 'undefined' ) {411 // var parent_id_start = jQuery( parent_builder_item ).attr('id');412 // console.log('parent_id_start[%o]', parent_id_start );413 //} 414 },415 stop: function(event, ui) {416 var element_id = jQuery( ui.item ).attr('id');417 if ( element_id == 'ld-selector-draggable-group' ) {418 419 var new_lessons = '';420 var ld_selected = jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-sfwd-topic').data('ld-selected');421 if ( typeof ld_selected === 'undefined' ) {422 ld_selected = [];423 }424 ui.item.children('li').each( function( ) {425 var inner_el = this;426 var element_ld_id = jQuery( inner_el ).data('ld-id');427 ld_selected.push( parseInt( element_ld_id ) );428 jQuery( 'span.ld-course-builder-sub-actions', inner_el ).hide();429 430 //var edit_href = jQuery( 'span.ld-course-builder-sub-actions a.ld-course-builder-action-edit', inner_el ).attr('href');431 //jQuery( 'span.ld-course-builder-sub-actions a.ld-course-builder-action-edit', inner_el ).attr('href', edit_href+'&course_id='+learndash_course_builder_assets['course_id'] );432 433 new_lessons = new_lessons+'<div id="ld-course-builder-topic-item-'+element_ld_id+'" class="ld-course-builder-item ld-course-builder-topic-item" data-ld-type="sfwd-topic" data-ld-id="'+element_ld_id+'">'+jQuery( inner_el ).html()+'</div>';434 if ( typeof element_ld_id !== 'undefined' ) {435 selector_set_item_disabled( 'sfwd-topic', element_ld_id, true);436 jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-sfwd-topic li#ld-post-'+element_ld_id).removeClass('ld-selected');437 }438 });439 jQuery( ui.item ).replaceWith( new_lessons );440 // after the Lesson(s) added we reset the jQuery UI sortable logic to include the new child items441 jQuery("#learndash_course_builder_box_wrap .ld-course-builder-quiz-items").sortable( sortable_objects['sfwd-quiz'] );442 ld_selected = jQuery.unique( ld_selected );443 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-sfwd-topic' ).data( 'ld-selected', ld_selected );444 445 update_course_builder_steps_element();446 447 } else {448 jQuery( ui.item ).addClass('ld-course-builder-item-update');449 450 //var parent_builder_item = jQuery( ui.item ).parents('.ld-course-builder-item').first();451 //console.log('parent_builder_item[%o]', parent_builder_item );452 //if ( typeof ld_selected === 'undefined' ) {453 // var parent_id_end = jQuery( parent_builder_item ).attr('id');454 // console.log('parent_id_end[%o]', parent_id_end );455 //}456 457 jQuery( 'span.ld-course-builder-sub-actions', ui.item ).hide();458 update_course_builder_steps_element();459 }460 }461 };462 463 sortable_objects['sfwd-quiz'] = {464 //containment: "#learndash_course_builder_box_wrap",465 items: "> div.ld-course-builder-quiz-item",466 handle: ".ld-course-builder-action-quiz-move",467 connectWith: '.ld-course-builder-quiz-items',468 placeholder: "movable-placeholder",469 tolerance: 'pointer',470 opacity: 0.7,471 revert: 300,472 delay: 150,473 dropOnEmpty: true,474 start: function(e, ui) {475 ui.placeholder.height(ui.helper.outerHeight());476 ui.placeholder.width('100%');477 jQuery( 'span.ld-course-builder-sub-actions', ui.helper ).hide(); 478 },479 stop: function(event, ui) {480 var element_id = jQuery( ui.item ).attr('id');481 if ( element_id == 'ld-selector-draggable-group' ) {482 483 var new_lessons = '';484 var ld_selected = jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-sfwd-quiz').data('ld-selected');485 if ( typeof ld_selected === 'undefined' ) {486 ld_selected = [];487 }488 ui.item.children('li').each( function( ) {489 var inner_el = this;490 var element_ld_id = jQuery( inner_el ).data('ld-id');491 ld_selected.push( parseInt( element_ld_id ) );492 493 jQuery( 'span.ld-course-builder-sub-actions', inner_el ).hide();494 495 //var edit_href = jQuery( 'span.ld-course-builder-sub-actions a.ld-course-builder-action-edit', inner_el ).attr('href');496 //jQuery( 'span.ld-course-builder-sub-actions a.ld-course-builder-action-edit', inner_el ).attr('href', edit_href+'&course_id='+learndash_course_builder_assets['course_id'] );497 498 new_lessons = new_lessons+'<div id="ld-course-builder-quiz-item-'+element_ld_id+'" class="ld-course-builder-item ld-course-builder-quiz-item" data-ld-type="sfwd-quiz" data-ld-id="'+element_ld_id+'">'+jQuery( inner_el ).html()+'</div>';499 500 if ( typeof element_ld_id !== 'undefined' ) {501 selector_set_item_disabled( 'sfwd-quiz', element_ld_id, true);502 jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-sfwd-quiz li#ld-post-'+element_ld_id).removeClass('ld-selected');503 }504 });505 jQuery( ui.item ).replaceWith( new_lessons );506 ld_selected = jQuery.unique( ld_selected );507 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-sfwd-quiz' ).data( 'ld-selected', ld_selected );508 update_course_builder_steps_element();509 510 } else if ( element_id == 'ld-draggable-builder-group' ) {511 512 ui.item.children('div').each( function( ) {513 var inner_el = this;514 jQuery(inner_el).removeClass('ld-selected');515 });516 517 } else {518 jQuery( ui.item ).addClass('ld-course-builder-item-update');519 jQuery( 'span.ld-course-builder-sub-actions', ui.item ).hide();520 update_course_builder_steps_element();521 }522 },523 };524 525 // Draggable / Sortable Lessons526 jQuery('#learndash_course_builder_box_wrap .learndash_selectors ul#learndash-selector-post-listing-sfwd-lessons li').draggable( draggable_objects['sfwd-lessons'] );527 jQuery('#learndash_course_builder_box_wrap .learndash_builder_items .ld-course-builder-lesson-items').sortable( sortable_objects['sfwd-lessons'] );528 529 530 // Draggable / Sortable Topics531 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors ul#learndash-selector-post-listing-sfwd-topic li' ).draggable( draggable_objects['sfwd-topic'] );532 jQuery( '#learndash_course_builder_box_wrap .ld-course-builder-topic-items' ).sortable( sortable_objects['sfwd-topic'] );533 // Draggable / Sortable Quizzes534 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors ul#learndash-selector-post-listing-sfwd-quiz li' ).draggable( draggable_objects['sfwd-quiz'] );535 jQuery( '#learndash_course_builder_box_wrap .ld-course-builder-quiz-items' ).sortable( sortable_objects['sfwd-quiz'] );536 function update_course_builder_steps_element() {537 cb_form_unsaved = true;538 539 builder_items_count = 0;540 541 var builder_elements = build_html_element_map();542 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items .ld-course-steps-total .ld-course-steps-value').html( builder_items_count ); 543 544 var builder_elements_str = JSON.stringify( builder_elements );545 jQuery( '#learndash_course_builder_box_wrap input#learndash_course_builder_data' ).val(builder_elements_str);546 }547 548 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items').on('click', '.ld-course-builder-action-show-hide', show_hide_sub_elements ); 549 function show_hide_sub_elements( e, action ) {550 e.stopImmediatePropagation();551 552 var builder_item = jQuery( e.currentTarget).parents('.ld-course-builder-item').first();553 var closest_sub_items = jQuery( builder_item ).find('.ld-course-builder-sub-items').first();554 555 if ( ( typeof action === 'undefined' ) || ( ( action != 'open') && ( action != 'close' ) ) ) {556 if ( jQuery( closest_sub_items ).is(":visible") ) {557 action = 'close';558 } else {559 action = 'open';560 }561 } 562 563 if ( action == 'open' ) {564 jQuery( closest_sub_items ).slideDown('slow', function(){565 jQuery( e.currentTarget).removeClass('ld-course-builder-action-show');566 jQuery( e.currentTarget).addClass('ld-course-builder-action-hide'); 567 });568 } else {569 jQuery( closest_sub_items ).slideUp('slow', function(){570 jQuery( e.currentTarget).addClass('ld-course-builder-action-show');571 jQuery( e.currentTarget).removeClass('ld-course-builder-action-hide');572 573 });574 }575 }576 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items' ).on( 'click', '.ld-course-builder-action-remove', builder_remove_element );577 578 function builder_remove_element( event ) {579 var remove_item = jQuery( event.currentTarget ).closest( '.ld-course-builder-item' );580 if ( ( typeof remove_item === 'undefined' ) || ( remove_item === '' ) )581 return;582 583 var remove_item_id = jQuery( remove_item ).attr('data-ld-id');584 var remove_item_type = jQuery( remove_item ).attr('data-ld-type');585 var confirm_title = learndash_course_builder_assets['confirm_remove_'+remove_item_type];586 if ( confirm_title === '' ) {587 confirm_title = 'Confirm delete';588 }589 // Be nice and add the title to the confirm popup590 var remove_item_title = jQuery( 'span.ld-course-builder-title-text', remove_item ).html();591 if ( remove_item_title !== '' ) {592 confirm_title += '\r\n\r\n' + remove_item_title;593 }594 if ( confirm( confirm_title ) ) {595 var child_items = jQuery( remove_item ).find('.ld-course-builder-item');596 if ( typeof child_items !== 'undefined' ) {597 jQuery( child_items ).each(function( child_item_idx, child_item ) {598 var item_type = jQuery( child_item ).attr( 'data-ld-type' );599 var item_id = jQuery(child_item).attr('data-ld-id');600 if (( typeof item_type !== 'undefined' ) && ( typeof item_id !== 'undefined' )) {601 selector_set_item_disabled(item_type, item_id, false);602 }603 });604 }605 606 selector_set_item_disabled( remove_item_type, remove_item_id, false);607 608 // Finally remove DOM element609 jQuery( remove_item ).remove();610 611 update_course_builder_steps_element();612 }613 }614 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).on( 'click', '.ld-course-builder-action-trash', builder_trash_element );615 function builder_trash_element( event ) {616 var trash_item = jQuery( event.currentTarget ).closest( 'li' );617 if ( ( typeof trash_item === 'undefined' ) || ( trash_item === '' ) )618 return;619 620 var trash_item_id = jQuery( trash_item ).attr('data-ld-id'); 621 var trash_item_type = jQuery( trash_item ).attr('data-ld-type');622 623 var confirm_title = learndash_course_builder_assets['confirm_trash_'+trash_item_type];624 if ( confirm_title === '' ) {625 confirm_title = 'Confirm delete';626 }627 // Be nice and add the title to the confirm popup628 var trash_item_title = jQuery( 'span.ld-course-builder-title-text', trash_item ).html();629 if ( trash_item_title !== '' ) {630 confirm_title += '\r\n\r\n' + trash_item_title;631 }632 if ( confirm( confirm_title ) ) {633 jQuery( trash_item ).remove();634 selector_update_empty( trash_item_type );635 var post_data = {636 'action': 'learndash_course_builder_selector_trash_step',637 'step_args': {638 'post_id': trash_item_id,639 'post_type': trash_item_type,640 },641 };642 jQuery.ajax({643 type: "POST",644 url: ajaxurl,645 dataType: "json",646 cache: false,647 data: post_data,648 error: function(jqXHR, textStatus, errorThrown ) {649 //console.log('init: error HTTP Status['+jqXHR.status+'] '+errorThrown);650 },651 success: function(reply_data) {652 if ( typeof reply_data !== 'undefined') {653 if ( reply_data['status'] === true ) {654 655 }656 }657 }658 });659 }660 }661 662 // Simple handler to show when changes have been made663 window.onbeforeunload = function() {664 if ( cb_form_unsaved === true ) {665 return learndash_course_builder_assets.learndash_upload_message;666 }667 }668 // If we are submitting the form then don't show the warning. 669 var parent_form = jQuery( '#learndash_course_builder_box_wrap' ).parents( 'form' );670 if ( typeof parent_form !== 'undefined' ) {671 jQuery( parent_form ).submit(function() {672 cb_form_unsaved = false;673 });674 }675 if ( touchEvent == 'hover' ) {676 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items' ).on( 'mouseover', '.ld-course-builder-actions', builder_step_show_element_actions );677 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items' ).on( 'mouseleave', '.ld-course-builder-actions', builder_step_hide_element_actions );678 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).on( 'mouseover', '.ld-course-builder-actions', builder_step_show_element_actions );679 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).on( 'mouseleave', '.ld-course-builder-actions', builder_step_hide_element_actions );680 } else if ( touchEvent == 'touchstart' ) {681 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items' ).on( 'click', '.ld-course-builder-actions', builder_step_show_element_actions );682 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors' ).on( 'click', '.ld-course-builder-actions', builder_step_show_element_actions );683 }684 685 function builder_step_show_element_actions( event ) {686 event.stopImmediatePropagation();687 var element_move_action = jQuery( event.currentTarget );688 var sub_actions = jQuery( '.ld-course-builder-sub-actions', element_move_action );689 if ( typeof sub_actions !== 'undefined' ) {690 691 // We need to check if the element is being dragged. If it is being dragged it will have 692 // a parent container div#ld-selector-draggable-group in that case we hide the sub-actions. 693 var parent_id = jQuery(element_move_action).closest('div#ld-selector-draggable-group').attr('id'); 694 if ( typeof parent_id === 'undefined' ) { 695 if ( jQuery( sub_actions ).is(':visible' ) ) {696 if ( touchEvent == 'touchstart' ) {697 //jQuery( sub_actions ).hide( 'slide', {direction: 'left'}, 150);698 jQuery( sub_actions ).hide();699 }700 } else {701 // First hide all visible sub-action elements 702 if ( touchEvent == 'touchstart' ) {703 jQuery( '#learndash_course_builder_box_wrap .ld-course-builder-sub-actions').hide();704 }705 706 var pos = jQuery(element_move_action).position();707 var width = jQuery(element_move_action).outerWidth();708 var sub_actions_width = jQuery(sub_actions).outerWidth();709 if ( jQuery( 'body' ).hasClass( 'rtl' ) ) {710 var position_left = (pos.left - sub_actions_width + 5) + "px";711 } else {712 var position_left = (pos.left + width) + "px";713 }714 jQuery( sub_actions ).css({715 'background-color': "#B8B8B8",716 height: '20px',717 position: "absolute",718 top: pos.top + "px",719 left: position_left720 }).show();721 //}).show( 'slide', {direction: 'left'}, 600);722 }723 } 724 } 725 }726 727 function builder_step_hide_element_actions( event ) {728 var element_move_action = jQuery( event.currentTarget );729 var sub_actions = jQuery( '.ld-course-builder-sub-actions', element_move_action );730 if ( typeof sub_actions !== 'undefined' ) {731 //jQuery( sub_actions ).hide( 'slide', {direction: 'left'}, 600);732 jQuery( sub_actions ).hide();733 }734 } 735 736 jQuery( '#learndash_course_builder_box_wrap' ).on( 'mouseover', '.ld-course-builder-title', builder_edit_title_show_pencil );737 jQuery( '#learndash_course_builder_box_wrap' ).on( 'mouseleave', '.ld-course-builder-title', builder_edit_title_hide_pencil );738 function builder_edit_title_show_pencil( event ) {739 event.stopImmediatePropagation();740 var show_pencil = true;741 // Disable showing the pencil on disabled items. 742 var parent_el = jQuery( event.currentTarget ).closest('.ld-course-builder-item')[0];743 if ( typeof parent_el !== 'undefined' ) {744 if ( jQuery( parent_el ).hasClass('ld-disabled' ) ) {745 show_pencil = false;746 }747 if ( jQuery( parent_el ).hasClass('ld-course-builder-title-edit' ) ) {748 show_pencil = false;749 }750 if ( show_pencil == true ) {751 jQuery( '.ld-course-builder-edit-title-pencil', event.currentTarget ).show();752 }753 }754 }755 756 function builder_edit_title_hide_pencil( event ) {757 event.stopImmediatePropagation();758 jQuery( '.ld-course-builder-edit-title-pencil', event.currentTarget ).hide();759 }760 761 jQuery( '#learndash_course_builder_box_wrap' ).on( 'click', '.ld-course-builder-title', builder_edit_title );762 function builder_edit_title( event ) {763 event.stopImmediatePropagation();764 var title_el = event.currentTarget;765 var parent_el = jQuery( title_el ).parents('.ld-course-builder-item');766 if ( typeof parent_el !== 'undefined' ) {767 768 if ( jQuery( parent_el ).hasClass('ld-disabled') ) return;769 if ( jQuery( parent_el ).hasClass('ld-course-builder-title-edit') ) return;770 else jQuery( parent_el ).addClass('ld-course-builder-title-edit');771 if ( jQuery( parent_el ).hasClass('ld-selected') ) jQuery( parent_el ).removeClass('ld-selected');772 //jQuery( parent_el ).addClass('ld-course-builder-title-edit');773 774 // Hide the actions menu when editing title. This prevents moving the element also yields more space775 jQuery( '.ld-course-builder-actions', parent_el ).hide();776 777 var title_org = jQuery( '.ld-course-builder-title-text', title_el ).html();778 //jQuery( '.ld-course-builder-title-text', title_el ).html( '<input style="width:'+parent_el_width+'px" type="text" value="'+title_org+'" />' );779 jQuery( '.ld-course-builder-title-text', title_el ).html( '<input type="text" value="'+title_org+'" />' );780 781 jQuery( '.ld-course-builder-title-text input', title_el ).focus();782 jQuery( '.ld-course-builder-title-text input', title_el ).select();783 784 jQuery( '.ld-course-builder-edit-title-pencil', title_el ).hide();785 jQuery( '.ld-course-builder-edit-title-ok', title_el ).show();786 jQuery( '.ld-course-builder-edit-title-cancel', title_el ).show();787 jQuery( title_el ).on( 'click', '.ld-course-builder-edit-title-ok', function( event_confirm ) {788 event_confirm.stopImmediatePropagation();789 var parent_el = jQuery( event_confirm.currentTarget ).parents('.ld-course-builder-item');790 791 jQuery( parent_el ).removeClass( 'ld-course-builder-title-edit' );792 var title_new = jQuery( '.ld-course-builder-title-text input', title_el ).val();793 jQuery( '.ld-course-builder-title-text input', title_el ).remove();794 jQuery( '.ld-course-builder-edit-title-ok', title_el ).hide();795 jQuery( '.ld-course-builder-edit-title-cancel', title_el ).hide();796 // Re-show the actions menu797 jQuery( '.ld-course-builder-actions', parent_el ).show();798 if ( ( title_new != '' ) && ( title_new != title_org ) ) {799 jQuery( '.ld-course-builder-title-text', title_el ).html(title_new);800 801 var parent_el = jQuery( title_el ).parents('.ld-course-builder-item');802 if ( typeof parent_el !== 'undefined') {803 var step_id = jQuery(parent_el).data('ld-id');804 var step_type = jQuery(parent_el).data('ld-type');805 var post_data = {806 'action': 'learndash_course_builder_selector_set_step_title',807 'new_title': title_new,808 'step_args': {809 'post_id': step_id,810 'post_type': step_type,811 },812 };813 jQuery.ajax({814 type: "POST",815 url: ajaxurl,816 dataType: "json",817 cache: false,818 data: post_data,819 error: function(jqXHR, textStatus, errorThrown ) {820 //console.log('init: error HTTP Status['+jqXHR.status+'] '+errorThrown);821 },822 success: function(reply_data) {823 if ( ( typeof reply_data['status'] !== 'undefined' ) && ( reply_data['status'] === true ) ) {824 var selector_item = jQuery( '#learndash_course_builder_box_wrap .learndash_selectors li#ld-post-'+step_id );825 jQuery( '.ld-course-builder-title-text', selector_item ).html( title_new );826 827 //var builder_item = jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items div#ld-course-builder-lesson-item-'+step_id );828 var builder_item = jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items #ld-post-'+step_id );829 jQuery( '.ld-course-builder-title-text', builder_item ).html( title_new );830 }831 }832 });833 }834 } else {835 jQuery( '.ld-course-builder-title-text', title_el ).html( title_org );836 }837 });838 jQuery( title_el ).on( 'click', '.ld-course-builder-edit-title-cancel', function( event_cancel ) {839 event_cancel.stopImmediatePropagation();840 841 var parent_el = jQuery( event_cancel.currentTarget ).parents('.ld-course-builder-item');842 843 jQuery( parent_el ).removeClass('ld-course-builder-title-edit');844 jQuery( '.ld-course-builder-title-text input', title_el ).remove();845 jQuery( '.ld-course-builder-edit-title-ok', title_el ).hide();846 jQuery( '.ld-course-builder-edit-title-cancel', title_el ).hide();847 // Re-show the actions menu848 jQuery( '.ld-course-builder-actions', parent_el ).show();849 850 if ( jQuery( '.ld-course-builder-action-show-hide', parent_el ).length ) {851 var selector_container = course_buider_get_parent_selector_container( parent_el );852 if ( ( typeof selector_container !== 'undefined' ) && ( jQuery( selector_container ).hasClass( 'learndash_builder_items' ) ) ) {853 jQuery( '.ld-course-builder-action-show-hide', parent_el ).show();854 }855 }856 jQuery( '.ld-course-builder-title-text', title_el ).html( title_org );857 });858 }859 }860 861 // Utility function. We need to see if an element is on the left or right side of CB. 862 function course_buider_get_parent_selector_container( el ) {863 if ( typeof el !== 'undefined' ) {864 var selector_container = jQuery( el ).closest( '.learndash_selectors' );865 if ( ( typeof selector_container !== 'undefined' ) && ( selector_container.length > 0 ) ) {866 return selector_container[0];867 } else {868 var builder_container = jQuery( el ).closest( '.learndash_builder_items' );869 if ( ( typeof builder_container !== 'undefined' ) && ( builder_container.length > 0 ) ) {870 return builder_container[0];871 }872 }873 }874 }875 876 function selector_update_disabled_items( selector_type, disabled_ids ) {877 if ( selector_type !== '' ) {878 var selector_container = jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container[data-ld-type="'+selector_type+'"]' );879 if ( typeof selector_container !== 'undefined' ) {880 881 var selected_items = jQuery(selector_container).data('ld-selected');882 if (( typeof selected_items !== 'undefined' ) && ( selected_items.length )) {883 jQuery.each(selected_items, function( index, value ) {884 selector_set_item_disabled( selector_type, value, true);885 });886 }887 }888 }889 }890 891 function selector_update_empty( selector_type ) {892 893 if ( selector_type !== '' ) {894 var selector_container = jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container[data-ld-type="'+selector_type+'"]' );895 896 if ( jQuery( 'ul#learndash-selector-post-listing-'+selector_type+' li', selector_container ).length ) {897 jQuery( '.learndash-selector-pager', selector_container ).show();898 jQuery( '.learndash-selector-search', selector_container ).show();899 } else {900 jQuery( '.learndash-selector-pager', selector_container ).hide();901 jQuery( '.learndash-selector-search', selector_container ).hide();902 }903 } 904 }905 906 907 function selector_set_item_disabled( selector_type, selected_id, disabled ) {908 if ( ( selector_type !== '' ) && ( selected_id !== '' ) ) {909 var disabled_items = jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-'+selector_type).data('ld-selected');910 if ( typeof disabled_items === 'undefined' ) {911 disabled_items = [];912 }913 914 var changed = false;915 if ( disabled === true ) {916 jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-'+selector_type+' ul.learndash-selector-post-listing li[data-ld-id="'+selected_id+'"]' ).addClass( 'ld-disabled' );917 if ( disabled_items.indexOf( parseInt( selected_id ) ) === -1 ) {918 disabled_items.push( parseInt( selected_id ) );919 changed = true;920 }921 922 } else {923 jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-'+selector_type+' ul.learndash-selector-post-listing li[data-ld-id="'+selected_id+'"]' ).removeClass( 'ld-disabled' );924 disabled_items = disabled_items.filter(function(e) { return e !== parseInt(selected_id) });925 changed = true;926 }927 if ( changed == true ) {928 jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-'+selector_type).data('ld-selected', disabled_items );929 }930 }931 }932 933 function selector_set_item_selected( selector_type, selected_id, selected ) {934 if ( ( selector_type !== '' ) || ( selected_id !== '' ) ) {935 936 if ( selected === true ) {937 jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-'+selector_type+' ul.learndash-selector-post-listing li[data-ld-id="'+selected_id+'"]').addClass( 'ld-selected' );938 } else {939 jQuery('#learndash_course_builder_box_wrap .learndash_selectors .learndash-selector-container-'+selector_type+' ul.learndash-selector-post-listing li[data-ld-id="'+selected_id+'"]').removeClass( 'ld-selected' );940 }941 }942 }943 944 function selector_get_type_from_item( el ) {945 if ( el !== '' ) {946 var selector_container = jQuery( el ).closest( '.learndash-selector-container' );947 if ( typeof selector_container !== 'undefined' ) {948 var selector_type = jQuery(selector_container).data('ld-type');949 return selector_type;950 }951 }952 }953 954 jQuery('.learndash_selectors').on('click', '.ld-course-builder-action-add', builder_add_new_step );955 function builder_add_new_step( event ) {956 event.stopImmediatePropagation();957 958 // Check to ensure we are not adding too quickly. This will show the spinner.959 if ( !jQuery( event.currentTarget ).hasClass( 'ld-course-builder-action-add-pending' ) ) {960 jQuery( event.currentTarget ).addClass( 'ld-course-builder-action-add-pending' );961 var selector_container = jQuery( event.currentTarget ).closest( '.learndash-selector-container' );962 if ( typeof selector_container !== 'undefined' ) {963 var selector_show_hide = jQuery( selector_container ).find( '.ld-course-builder-action-show-hide' );964 if ( jQuery( selector_show_hide ).hasClass( 'ld-course-builder-action-show' ) ) {965 jQuery( '.ld-course-builder-action-show-hide', selector_container ).trigger( 'click', ['open'] );966 }967 968 var selector_type = jQuery(selector_container).data('ld-type'); 969 if ( typeof selector_type !== 'undefined' ) {970 971 var d = new Date();972 var n = d.getTime();973 var new_item_id = 'new-step-'+n;974 975 var first_item = jQuery( '.learndash-row-placeholder li', selector_container ).clone();976 //console.log('first_item[%o]', first_item);977 978 jQuery( first_item ).attr('id', new_item_id );979 jQuery( first_item ).attr('data-ld-id', '' );980 jQuery( first_item ).removeClass( 'ld-disabled' );981 jQuery( first_item ).removeClass( 'ld-selected' );982 jQuery( first_item ).removeClass( 'ld-course-builder-title-edit' );983 jQuery( first_item ).addClass( 'ld-new-step' );984 var title_el = jQuery( '.ld-course-builder-header .ld-course-builder-title', first_item );985 if ( jQuery( title_el ).hasClass( 'ld-course-builder-title-edit' ) ) { 986 if ( jQuery( 'input[type="text"]', title_el ).length ) {987 jQuery( 'input[type="text"]', title_el ).remove();988 }989 }990 991 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors ul#learndash-selector-post-listing-'+selector_type ).prepend( first_item );992 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors ul#learndash-selector-post-listing-'+selector_type+' li' ).draggable( draggable_objects[selector_type] );993 jQuery( '#learndash_course_builder_box_wrap #'+new_item_id+' .ld-course-builder-title-text' ).trigger( 'click' );994 995 selector_update_empty( selector_type );996 997 builder_trigger_new_steps_ajax( );998 // now hide the spinner999 jQuery( event.currentTarget ).removeClass('ld-course-builder-action-add-pending');1000 }1001 }1002 }1003 }1004 1005 function builder_trigger_new_steps_ajax( ) {1006 1007 if ( ld_builder_new_step_ajax_pid == '' ) {1008 1009 if ( jQuery( '#learndash_course_builder_box_wrap .ld-new-step' ).length ) {1010 var new_items_set = {};1011 //jQuery( '#learndash_course_builder_box_wrap .ld-new-step' ).slice(0, 2).each( function( item_idx, item_el ) {1012 jQuery( '#learndash_course_builder_box_wrap .ld-new-step' ).each( function( item_idx, item_el ) {1013 1014 var new_item = {};1015 new_item.item_id = jQuery( item_el ).attr( 'id' );1016 new_item.post_type = jQuery( item_el ).data( 'ld-type' );1017 1018 if ( jQuery( 'input[type="text"]', item_el ).length ) {1019 new_item.post_title = jQuery( 'input[type="text"]', item_el ).val();1020 } else {1021 new_item.post_title = jQuery( '.ld-course-builder-title-text', item_el ).val();1022 }1023 new_items_set[new_item.item_id] = new_item;1024 });1025 if ( Object.keys(new_items_set).length > 0 ) {1026 1027 var post_data = {1028 'action': 'learndash_course_builder_selector_new_step',1029 'new_steps': new_items_set1030 };1031 ld_builder_new_step_ajax_pid = jQuery.ajax({1032 type: "POST",1033 url: ajaxurl,1034 dataType: "json",1035 cache: false,1036 data: post_data,1037 error: function(jqXHR, textStatus, errorThrown ) {1038 //console.log('init: error HTTP Status['+jqXHR.status+'] '+errorThrown);1039 },1040 success: function(reply_data) {1041 if ( typeof reply_data !== 'undefined') {1042 if ( typeof reply_data['new_steps'] !== 'undefined' ) {1043 jQuery.each( reply_data['new_steps'], function ( old_step_id, new_step_set ) {1044 if ( jQuery( '#learndash_course_builder_box_wrap #'+old_step_id ).length ) {1045 if ( jQuery( '#learndash_course_builder_box_wrap #'+old_step_id ).hasClass( 'ld-new-step' ) ) {1046 jQuery( '#learndash_course_builder_box_wrap #'+old_step_id ).removeClass( 'ld-new-step' );1047 jQuery( '#learndash_course_builder_box_wrap #'+old_step_id ).attr('data-ld-id', new_step_set.post_id );1048 jQuery( '#learndash_course_builder_box_wrap #'+old_step_id+' a.ld-course-builder-action-view' ).attr('href', new_step_set.view_url.replace(/&amp;/g, '&' ) );1049 jQuery( '#learndash_course_builder_box_wrap #'+old_step_id+' a.ld-course-builder-action-edit' ).attr('href', new_step_set.edit_url.replace(/&amp;/g, '&' ) );1050 jQuery( '#learndash_course_builder_box_wrap #'+old_step_id ).attr('id', 'ld-post-'+new_step_set.post_id );1051 } 1052 } 1053 });1054 }1055 }1056 ld_builder_new_step_ajax_pid = '';1057 builder_trigger_new_steps_ajax();1058 }1059 });1060 }1061 }1062 } 1063 }1064 1065 jQuery('#learndash_course_builder_box_wrap .learndash_selectors').on('click', '.ld-show-all', builder_show_all_selectors );1066 function builder_show_all_selectors( event ) {1067 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors h3.learndash-selector-header .ld-course-builder-action-show-hide').trigger('click', ['open'] );1068 }1069 jQuery('#learndash_course_builder_box_wrap .learndash_selectors').on('click', '.ld-hide-all', builder_hide_all_selectors );1070 function builder_hide_all_selectors( event ) {1071 jQuery( '#learndash_course_builder_box_wrap .learndash_selectors h3.learndash-selector-header .ld-course-builder-action-show-hide').trigger('click', ['close'] );1072 }1073 1074 1075 jQuery('#learndash_course_builder_box_wrap .learndash_builder_items').on('click', '.ld-show-all', builder_show_all_builders );1076 function builder_show_all_builders( event ) {1077 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items .ld-course-builder-action-show-hide').trigger('click', ['open'] );1078 }1079 jQuery('#learndash_course_builder_box_wrap .learndash_builder_items').on('click', '.ld-hide-all', builder_hide_all_builders );1080 function builder_hide_all_builders( event ) {1081 jQuery( '#learndash_course_builder_box_wrap .learndash_builder_items .ld-course-builder-action-show-hide').trigger('click', ['close'] );1082 }1083 1084 // Enf of functions...

Full Screen

Full Screen

ModuleBuilder.js

Source:ModuleBuilder.js Github

copy

Full Screen

1/*********************************************************************************2 * SugarCRM Community Edition is a customer relationship management program developed by3 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.4 * 5 * This program is free software; you can redistribute it and/or modify it under6 * the terms of the GNU Affero General Public License version 3 as published by the7 * Free Software Foundation with the addition of the following permission added8 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK9 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY10 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.11 * 12 * This program is distributed in the hope that it will be useful, but WITHOUT13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS14 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more15 * details.16 * 17 * You should have received a copy of the GNU Affero General Public License along with18 * this program; if not, see http://www.gnu.org/licenses or write to the Free19 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA20 * 02110-1301 USA.21 * 22 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,23 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.24 * 25 * The interactive user interfaces in modified source and object code versions26 * of this program must display Appropriate Legal Notices, as required under27 * Section 5 of the GNU Affero General Public License version 3.28 * 29 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,30 * these Appropriate Legal Notices must retain the display of the "Powered by31 * SugarCRM" logo. If the display of the logo is not reasonably feasible for32 * technical reasons, the Appropriate Legal Notices must display the words33 * "Powered by SugarCRM".34 ********************************************************************************/35function treeinit() {}36if(typeof('console') == 'undefined'){37console = {38 log: function(message){39 }}40}41(function() {42 var sw = YAHOO.SUGAR,43 Event = YAHOO.util.Event,44 Connect = YAHOO.util.Connect,45 Dom = YAHOO.util.Dom;46 47function createTreePanel(treeData, params) {48 var tree = new YAHOO.widget.TreeView(params.id);49 var root = tree.getRoot();50 addChildNodes(root, treeData);51 52 return tree;53}54function addChildNodes(parentNode, parentData) {55 var nodes = parentData.nodes || parentData.children;56 for (i in nodes) {57 if (typeof(nodes[i]) == 'object') {58 nodes[i].data.href = 'javascript:void(0);';59 var node = new YAHOO.widget.TextNode(nodes[i].data, parentNode)60 node.action = nodes[i].data.action;61 if (typeof(nodes[i].nodes) == 'object') {62 addChildNodes(node, nodes[i]);63 }64 }65 }66}67if (typeof(ModuleBuilder) == 'undefined') {68 ModuleBuilder = {69 init: function(){70 //Check if we shoudln't be in studio and need to load the normal ajaxUI71 var aRegex = /#.*ajaxUILoc=([^&]*)/.exec(window.location);72 var ajaxLoc = aRegex ? aRegex[1] : false;73 if (ajaxLoc) {74 window.location = "index.php?action=ajaxui#ajaxUILoc=" + ajaxLoc;75 return;76 }77 //Setup the basic ajax request settings78 Connect.extraParams = {79 to_pdf: true80 };81 Connect.url = 'index.php?to_pdf=1&sugar_body_only=1';82 Connect.method = 'POST';83 Connect.timeout = 300000; 84 85 //Setup and read cookie settings86 //Ext.state.Manager.setProvider(new Ext.state.CookieProvider());87 88 if (SUGAR.themes.tempHideLeftCol)89 SUGAR.themes.tempHideLeftCol();90 91 var Ck = YAHOO.util.Cookie;92 93 //Setup the main layout94 var tp = ModuleBuilder.tabPanel = new YAHOO.widget.TabView("mbtabs");95 tp.addTab(new YAHOO.widget.Tab({ 96 label: SUGAR.language.get('ModuleBuilder', 'LBL_SECTION_MAIN'),97 scroll : true,98 content : "<div> </div>",99 id : "center",100 active : true101 }));102 var viewHeight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;103 var heightOffset = $('#dcmenu').length > 0 ? $('#dcmenu').height() : $('#header').height();104 var mp = ModuleBuilder.mainPanel = new YAHOO.widget.Layout('mblayout', {105 border: false,106 height: viewHeight - heightOffset - 40,107 //autoHeight: true108 //frame: true,109 units: [//ModuleBuilder.tree, ModuleBuilder.tabPanel,110 {111 position: 'center',112 body : 'mbcenter',113 scroll : true114 },{115 position: "left",116 header: "Tree",117 collapse: true,118 width: 230,119 minWidth: 100,120 resize: true,121 scroll : true,122 body : "<div id='mbTree'/>"123 },{124 id: 'help',125 header: SUGAR.language.get('ModuleBuilder', 'LBL_SECTION_HELP'),126 position:'right',127 body: 'mbhelp',128 scroll: true,129 width: 250,130 minWidth: 200,131 resize: true,132 collapse: true133 },{134 header: SUGAR.util.getAndRemove("footerHTML").innerHTML,135 position: 'bottom',136 id: 'mbfooter',137 height: 30,138 border: false139 }]140 });141 mp.render();142 143 ModuleBuilder.nextYear = new Date();144 ModuleBuilder.nextYear.setDate(ModuleBuilder.nextYear.getDate() + 360);145 146 var nextyear = ModuleBuilder.nextYear;147 148 if (Ck.getSub("ModuleBuilder", "helpHidden") == "true") {149 mp.getUnitByPosition('right').collapse();150 }151 if (Ck.getSub("ModuleBuilder", "treeHidden") == "true") {152 mp.getUnitByPosition('left').collapse();153 }154 155 var centerEl = mp.getUnitByPosition('center').get('wrap');156 tp.appendTo(centerEl);157 158 //YUI does not take the resizers into account when calculating panel size.159 var correctW = function(){160 var w = (this.body.offsetWidth - 7) + "px";161 this.body.style.width = w;162 this.header.style.width = w;163 if (typeof Studio2 != "undefined")164 Studio2.resizeDivs();165 if (typeof resizeDDLists == "function")166 resizeDDLists();167 };168 mp.getUnitByPosition('right').on("resize", correctW); 169 mp.getUnitByPosition('right').on("collapse", function(){170 Ck.setSub("ModuleBuilder", "helpHidden", "true");171 mp.get("element").querySelector(".yui-layout-clip-right .collapse").id = "expand_help";172 });173 mp.getUnitByPosition('right').on("expand", function(){174 Ck.setSub("ModuleBuilder", "helpHidden", "false");175 });176 mp.getUnitByPosition('left').on("resize", correctW);177 mp.getUnitByPosition('left').on("collapse", function(){178 Ck.setSub("ModuleBuilder", "treeHidden", "true");179 mp.get("element").querySelector(".yui-layout-clip-left .collapse").id = "expand_tree";180 });181 mp.getUnitByPosition('left').on("expand", function(){182 Ck.setSub("ModuleBuilder", "treeHidden", "false");183 });184 mp.resize(true);185 Event.on(window, 'resize', ModuleBuilder.autoSetLayout, this, true);186 187 var tree = ModuleBuilder.tree = createTreePanel(TREE_DATA, {188 id: 'mbTree'189 });190 tree.setCollapseAnim("TVSlideOut");191 tree.setExpandAnim("TVSlideIn");192 //tree.subscribe("labelClick", ModuleBuilder.handleTreeClick);193 tree.subscribe("clickEvent", ModuleBuilder.handleTreeClick);194 tree.render();195 196 //Setup Browser History197 var mbContent = YAHOO.util.History.getBookmarkedState('mbContent');198 199 if (ModuleBuilder.mode == 'mb') {200 mp.getUnitByPosition('left').header.firstChild.innerHTML = SUGAR.language.get('ModuleBuilder', 'LBL_SECTION_PACKAGES');201 mbContent = mbContent ? mbContent : 'module=ModuleBuilder&action=package&package=';202 }203 else if (ModuleBuilder.mode == 'studio') {204 ModuleBuilder.MBpackage = ''; // set to empty so other views can recognize that dealing with an deployed, rather than undeployed, module205 mp.getUnitByPosition('left').header.firstChild.innerHTML = SUGAR.language.get('ModuleBuilder', 'LBL_SECTION_MODULES');206 mbContent = mbContent ? mbContent :'module=ModuleBuilder&action=wizard';207 }208 else if (ModuleBuilder.mode == 'dropdowns') {209 mp.getUnitByPosition('left').header.firstChild.innerHTML = SUGAR.language.get('ModuleBuilder', 'LBL_SECTION_DROPDOWNS');210 mbContent = mbContent ? mbContent : 'module=ModuleBuilder&action=dropdowns';211 }212 else {213 mp.getUnitByPosition('left').collapse(false);214 mbContent = mbContent ? mbContent : 'module=ModuleBuilder&action=home';215 }216 YAHOO.util.History.register('mbContent', mbContent, ModuleBuilder.navigate);217 YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");218 ModuleBuilder.getContent(mbContent);219 220 if (SUGAR.themes.tempHideLeftCol) SUGAR.themes.tempHideLeftCol();221 ModuleBuilder.autoSetLayout();222 223 ModuleBuilder.tabPanel.on('activeTabChange', function(e) {224 ModuleBuilder.helpLoad( e.newValue.get("id") ) ;225 });226 227 if (Dom.get("HideHandle")){228 if (SUGAR.themes.tempHideLeftCol){229 SUGAR.themes.tempHideLeftCol();230 }231 }232 //We need to add ID's to the collapse buttons for automated testing233 Dom.getElementsByClassName("collapse", "div", mp.getUnitByPosition('left').header)[0].id = "collapse_tree";234 Dom.getElementsByClassName("collapse", "div", mp.getUnitByPosition('right').header)[0].id = "collapse_help";235 },236 //Empty layout manager237 layoutValidation: {238 popup_window: null,239 popup: function(){240 ModuleBuilder.layoutValidation.popup_window = new YAHOO.widget.SimpleDialog("emptyLayout", {241 width: "400px",242 draggable: true,243 constraintoviewport: true,244 modal: true,245 fixedcenter: true,246 text: SUGAR.language.get('ModuleBuilder', 'ERROR_MINIMUM_FIELDS'),247 bodyStyle: "padding:5px",248 buttons: [{249 text: SUGAR.language.get('ModuleBuilder', 'LBL_BTN_CLOSE'),250 isDefault:true,251 handler: function(){252 ModuleBuilder.layoutValidation.popup_window.hide()253 }254 }]255 });256 ModuleBuilder.layoutValidation.popup_window.render(document.body);257 ModuleBuilder.layoutValidation.popup_window.show();258 }259 },260 //Layout history manager261 history: {262 popup_window: false,263 reverted: false,264 params: { },265 browse: function(module, layout, subpanel){266 subpanel = subpanel ? subpanel : "";267 if (!module && ModuleBuilder.module != "undefined") {268 module = ModuleBuilder.module;269 } 270 if (!ModuleBuilder.history.popup_window) {271 ModuleBuilder.history.popup_window = new YAHOO.SUGAR.AsyncPanel('histWindow', {272 width: 300,273 draggable: true,274 close: true,275 constraintoviewport: true,276 fixedcenter: false277 });278 }279 var module_str = module;280 if(typeof SUGAR.language.languages['app_list_strings']['moduleList'][module] != 'undefined'){281 module_str = SUGAR.language.languages['app_list_strings']['moduleList'][module];282 } 283 ModuleBuilder.history.popup_window.setHeader( module_str + ' : ' + SUGAR.language.get('ModuleBuilder', 'LBL_' + layout.toUpperCase()) + SUGAR.language.get('ModuleBuilder', 'LBL_HISTORY_TITLE'));284 ModuleBuilder.history.popup_window.setBody("test");285 ModuleBuilder.history.popup_window.render(document.body);286 ModuleBuilder.history.params = {287 module: 'ModuleBuilder',288 histAction: 'browse',289 action: 'history',290 view_package: ModuleBuilder.MBpackage,291 view_module: module,292 view: layout,293 subpanel: subpanel294 };295 ModuleBuilder.history.popup_window.load(ModuleBuilder.paramsToUrl(ModuleBuilder.history.params));296 ModuleBuilder.history.popup_window.show();297 ModuleBuilder.history.popup_window.center();298 },299 preview: function(module, layout, id, subpanel) {300 var prevPanel = ModuleBuilder.findTabById('preview:' + id);301 if (!prevPanel) {302 ModuleBuilder.history.params = {303 module: 'ModuleBuilder',304 histAction: 'preview',305 action: 'history',306 view_package: ModuleBuilder.MBpackage,307 view_module: module,308 view: layout,309 sid: id,310 subpanel: subpanel311 };312 prevPanel = new YAHOO.SUGAR.ClosableTab({313 dataSrc: Connect.url + "&" + ModuleBuilder.paramsToUrl(ModuleBuilder.history.params),314 label: SUGAR.language.get("ModuleBuilder", "LBL_MB_PREVIEW"),315 id: 'preview:' + id,316 scroll: true,317 cacheData: true,318 active :true319 }, ModuleBuilder.tabPanel);320 prevPanel.closable = true;321 ModuleBuilder.tabPanel.addTab(prevPanel);322 } else {323 ModuleBuilder.tabPanel.set("activeTab", prevPanel);324 }325 326 },327 revert: function(module, layout, id, subpanel){328 var prevTab = ModuleBuilder.tabPanel.getTabIndex("preview:" + id);329 if(prevTab) ModuleBuilder.tabPanel.removeTab(prevTab);330 331 ModuleBuilder.history.params = {332 module: 'ModuleBuilder',333 histAction: 'restore',334 action: 'history',335 view_package: ModuleBuilder.MBpackage,336 view_module: module,337 view: layout,338 sid: id,339 subpanel: subpanel340 }341 ModuleBuilder.asyncRequest(ModuleBuilder.history.params, function(){342 ModuleBuilder.history.reverted = true;343 ModuleBuilder.getContent(ModuleBuilder.contentURL);344 ModuleBuilder.state.isDirty = true;345 });346 },347 cleanup: function() {348 if (ModuleBuilder.history.reverted && ModuleBuilder.history.params.histAction) {349 ModuleBuilder.history.params.histAction = 'unrestore';350 ModuleBuilder.asyncRequest({params: ModuleBuilder.history.params});351 }352 ModuleBuilder.history.params = { };353 ModuleBuilder.history.reverted = false;354 },355 update: function() {356 if (ModuleBuilder.history.popup_window && ModuleBuilder.history.popup_window.cfg.getProperty("visible")) {357 var historyButton = YAHOO.util.Dom.get('historyBtn');358 if (historyButton) {359 historyButton.onclick();360 } else {361 ModuleBuilder.history.popup_window.hide();362 }363 }364 }365 },366 state: {367 isDirty: false,368 saving: false,369 hideFailedMesage: false,370 intended_view: {371 url: null,372 successCall: null373 },374 current_view: {375 url: null,376 successCall: null377 },378 save_url_for_current_view: null,379 popup_window: null,380 setupState: function(){381 //ModuleBuilder.state.popup();382 document.body.setAttribute("onclose", "ModuleBuilder.state.popup(); ModuleBuilder.state.popup_window.show()");383 return;384 },385 onSaveClick: function(){386 //set dirty = false387 //call the save method of the current view.388 //call the intended action.389 ModuleBuilder.state.isDirty = false;390 var saveBtn = document.getElementById("saveBtn");391 if (!saveBtn) {392 var mbForm = document.forms[1];393 if (mbForm)394 var mbButtons = mbForm.getElementsByTagName("input");395 if (mbButtons) {396 for (var button = 0; button < mbButtons.length; button++) {397 var name = mbButtons[button].getAttribute("name");398 if (name && (name.toUpperCase() == "SAVEBTN" || name.toUpperCase() == "LSAVEBTN")) {399 saveBtn = mbButtons[button];400 break;401 }402 }403 }404 else {405 alert(SUGAR.language.get('ModuleBuilder', 'LBL_NO_SAVE_ACTION'));406 }407 }408 if (saveBtn) {409 //After the save call completes, load the next page410 ModuleBuilder.state.saving = true;411 eval(saveBtn.getAttributeNode('onclick').value);412 }413 ModuleBuilder.state.popup_window.hide();414 },415 onDontSaveClick: function(){416 //set dirty to false417 //call the intended action.418 ModuleBuilder.state.isDirty = false;419 ModuleBuilder.history.cleanup();420 ModuleBuilder.getContent(ModuleBuilder.state.intended_view.url, ModuleBuilder.state.intended_view.successCall);421 ModuleBuilder.state.popup_window.hide();422 },423 loadOnSaveComplete: function() {424 ModuleBuilder.state.saving = false;425 ModuleBuilder.getContent(ModuleBuilder.state.intended_view.url, ModuleBuilder.state.intended_view.successCall);426 },427 popup: function(){428 if(false == YAHOO.lang.isObject(ModuleBuilder.state.popup_window) || ModuleBuilder.state.popup_window.id != 'confirmUnsaved'){429 ModuleBuilder.state.popup_window = new YAHOO.widget.SimpleDialog("confirmUnsaved", {430 width: "400px",431 draggable: true,432 constraintoviewport: true,433 modal: true,434 fixedcenter: true,435 text: SUGAR.language.get('ModuleBuilder', 'LBL_CONFIRM_DONT_SAVE'),436 bodyStyle: "padding:5px",437 buttons: [{438 text: SUGAR.language.get('ModuleBuilder', 'LBL_BTN_DONT_SAVE'),439 handler: ModuleBuilder.state.onDontSaveClick440 }, {441 text: SUGAR.language.get('ModuleBuilder', 'LBL_BTN_CANCEL'),442 isDefault:true,443 handler: function(){444 ModuleBuilder.state.popup_window.hide()445 }446 },{447 text: SUGAR.language.get('ModuleBuilder', 'LBL_BTN_SAVE_CHANGES'),448 handler: ModuleBuilder.state.onSaveClick449 }]450 });451 ModuleBuilder.state.popup_window.setHeader(SUGAR.language.get('ModuleBuilder', 'LBL_CONFIRM_DONT_SAVE_TITLE'));452 }453 if(ModuleBuilder.disablePopupPrompt != 1){454 ModuleBuilder.state.popup_window.render(document.body);455 }else{456 ModuleBuilder.state.onDontSaveClick();457 }458 }459 },460 copyFromView: function(module, layout){461 var url = ModuleBuilder.contentURL;462 ModuleBuilder.getContent(url+"&copyFromEditView=true");463 ModuleBuilder.contentURL = url;464 ModuleBuilder.state.intended_view.url = url;465 ModuleBuilder.state.isDirty = true;466 },467 //AJAX Navigation Functions468 navigate : function(url) {469 //Check if we are just registering the url470 if (url != ModuleBuilder.contentURL) {471 ModuleBuilder.getContent(url);472 }473 },474 getContent: function(url, successCall){475 if (!url) return;476 477 if (url.substring(0, 11) == "javascript:")478 {479 eval(url.substring(11));480 return;481 }482 483 //save a pointer to intended action484 ModuleBuilder.state.intended_view.url = url;485 ModuleBuilder.state.intended_view.successCall = successCall;486 if(ModuleBuilder.state.isDirty){ //prompt to save current data.487 //check if we are editing a property of the current view (such views open up in new tabs)488 //if so we leave the state dirty and return489 temp_url = url.toLowerCase();490 if(null == temp_url.match(/&action=editproperty/)){491 ModuleBuilder.state.popup();492 ModuleBuilder.state.popup_window.show();493 return;494 }495 }else{496 ModuleBuilder.state.current_view.url = url;497 ModuleBuilder.state.current_view.successCall = successCall;498 }499 500 ModuleBuilder.contentURL = url;501 if (typeof(successCall) != 'function') {502 if (ModuleBuilder.callInProgress)503 return;504 ModuleBuilder.callInProgress = true;505 successCall = ModuleBuilder.updateContent;506 }507 ModuleBuilder.asyncRequest(url, successCall);508 },509 updateContent: function(o){510 ModuleBuilder.callInProgress = false;511 //Check if a save action was called and now we need to move-on512 if (ModuleBuilder.state.saving) {513 ModuleBuilder.state.loadOnSaveComplete();514 return;515 }516 ajaxStatus.flashStatus(SUGAR.language.get('app_strings', 'LBL_REQUEST_PROCESSED'), 2000);517 if(ModuleBuilder.checkForErrors(o))518 return false; 519 520 try {521 var ajaxResponse = YAHOO.lang.JSON.parse((o.responseText));522 } catch (err) {523 YAHOO.SUGAR.MessageBox.show({524 title: SUGAR.language.get('ModuleBuilder', 'ERROR_GENERIC_TITLE'),525 msg: o.responseText,526 width: 500527 });528 return false;529 }530 531 532 if (ajaxResponse.tpl){533 var t = new YAHOO.SUGAR.Template(ajaxResponse.tpl);534 ModuleBuilder.ajaxData = ajaxResponse.data;535 ModuleBuilder.tabPanel.getTab(0).set(t.exec(ajaxResponse.data));536 SUGAR.util.evalScript(t.exec(ajaxResponse.data));537 return true;538 }539 540 for (var maj in ajaxResponse) {541 var name = 'mb' + maj;542 var comp = ModuleBuilder.mainPanel.getUnitById(maj);543 if (!comp) {544 var tabs = ModuleBuilder.tabPanel.get("tabs");545 for (i in tabs) {546 if (tabs[i].get && tabs[i].get("id") == maj)547 comp = tabs[i];548 }549 }550 551 if (name == 'mbwest') { //refresh package_tree!552 var tree = ModuleBuilder.tree;553 var root = tree.root;554 tree.maxAnim = 0;555 tree.collapseAll();556 while (root.hasChildren()) {557 tree.removeNode(root.children[0], true);558 }559 addChildNodes(root, ajaxResponse.west.content.tree_data);560 tree.maxAnim = 2;561 tree.render();562 }563 else {564 if (!comp) {565 if(ajaxResponse[maj].action == 'deactivate') continue;566 comp = new YAHOO.SUGAR.ClosableTab({567 content: "<div class='bodywrapper'><script>ModuleBuilder.scriptTest=true;</script>" + ((maj == 'center') ? "<div>" + ajaxResponse[maj].crumb + "</div>" :"")568 + ajaxResponse[maj].content + "</div>",569 label: ajaxResponse[maj].title,570 id: maj,571 scroll: true,572 closable: true,573 active :true574 }, ModuleBuilder.tabPanel);575 comp.closable = true;576 ModuleBuilder.scriptTest = false;577 ModuleBuilder.tabPanel.set("activeTab", comp);578 ModuleBuilder.tabPanel.addTab(comp);579 //Text if the browser automatically evaluated the content's script tags or not. If not, manually evaluate them.580 if (!ModuleBuilder.scriptTest)581 SUGAR.util.evalScript(ajaxResponse[maj].content);582 } else {583 //Store Center pane changes in browser history584 YAHOO.util.History.navigate('mbContent', ModuleBuilder.contentURL);585 if (name == 'mbcenter') {586 ModuleBuilder.closeAllTabs();587 comp = ModuleBuilder.tabPanel.getTab(0);588 }589 ModuleBuilder.tabPanel.set("activeTab", comp);590 comp.set('content', "<div class='bodywrapper'><div>" + ajaxResponse[maj].crumb + "</div>" + ajaxResponse[maj].content + "</div>");591 if (ajaxResponse[maj].title != "no_change")592 comp.set('label', ajaxResponse[maj].title);593 SUGAR.util.evalScript(ajaxResponse[maj].content); 594 }595 }596 ModuleBuilder.history.update();597 }598 },599 checkForErrors: function(o){600 if (SUGAR.util.isLoginPage(o.responseText))601 return true;602 if (o.responseText.substr(0, 1) == "<") {603 YAHOO.SUGAR.MessageBox.show({604 title: SUGAR.language.get('ModuleBuilder', 'ERROR_GENERIC_TITLE'),605 msg: o.responseText,606 width: 500607 });608 return true;609 }610 611 612 return false;613 },614 submitForm: function(formname, successCall){615 ajaxStatus.showStatus(SUGAR.language.get('ModuleBuilder', 'LBL_AJAX_LOADING'));616 if (typeof(successCall) == 'undefined') {617 successCall = ModuleBuilder.updateContent;618 }619 else {620 ModuleBuilder.callLock = true;621 }622 Connect.setForm(document.getElementById(formname) || document.forms[formname]);623 Connect.asyncRequest(624 Connect.method, 625 Connect.url, 626 {success: successCall, failure: ModuleBuilder.failed}627 );628 },629 setMode: function(reqMode){630 ModuleBuilder.mode = reqMode;631 },632 main: function(type){633 document.location.href = 'index.php?module=ModuleBuilder&action=index&type=' + type;634 },635 failed: function(o){636 if(!ModuleBuilder.state.hideFailedMesage){637 ajaxStatus.flashStatus(SUGAR.language.get('ModuleBuilder', 'LBL_AJAX_FAILED_DATA'), 2000);638 }639 },640 //Wizard Functions641 buttonDown: function(button, name, list){642 if (typeof(name) != 'undefined') {643 for (i in ModuleBuilder.buttons[list]) {644 ModuleBuilder.buttons[list][i].className = 'wizardButton';645 }646 ModuleBuilder.buttonSelect(name, list);647 }648 button.className = 'wizardButtonDown';649 },650 buttonOver: function(button){651 button.className = 'button';652 },653 buttonOut: function(button, name, list){654 if (typeof(name) != 'undefined') {655 if (ModuleBuilder.buttonGetSelected(list) != name) {656 button.className = 'wizardButton'657 }658 }659 else {660 button.className = 'wizardButton'661 }662 },663 buttonAdd: function(id, name, list){664 if (typeof(ModuleBuilder.buttons[list]) == 'undefined') {665 ModuleBuilder.buttons[list] = {};666 }667 ModuleBuilder.buttons[list][name] = document.getElementById(id);668 },669 buttonGetSelected: function(list){670 if (typeof(ModuleBuilder.selected[list]) == 'undefined') {671 return false;672 }673 return ModuleBuilder.selected[list];674 },675 buttonSelect: function(name, list){676 ModuleBuilder.selected[list] = name;677 },678 buttonToForm: function(form, field, list){679 var theField = eval('document.' + form + '.' + field);680 theField.value = ModuleBuilder.buttonGetSelected(list);681 },682 getTitle: function(title, breadCrumb){683 return "<h2>" + title + "</h2><br>" + breadCrumb;684 },685 closeAllTabs: function() {686 var tabs = ModuleBuilder.tabPanel.get('tabs');687 for (var i = tabs.length - 1; i > -1; i--) {688 var tab = tabs[i];689 if (tab.close) {690 tab.close();691 }692 }693 },694 //Help Functions695 helpRegister: function(name){696 var formname = 'document.' + name;697 var form = eval(formname);698 var i = 0;699 for (i = 0; i < form.elements.length; i++) {700 if (typeof(form.elements[i].type) != 'undefined' && typeof(form.elements[i].name) != 'undefined' && form.elements[i].type != 'hidden') {701 form.elements[i].onmouseover = function(){702 ModuleBuilder.helpToggle(this.name)703 };704 form.elements[i].onmouseout = function(){705 ModuleBuilder.helpToggle('default')706 };707 }708 }709 },710 helpUnregisterByID: function (id){711 var elm = document.getElementById(id);712 if (elm) {713 elm.onmouseover = function() {};714 elm.onmouseout = function() {};715 }716 return;717 },718 helpRegisterByID: function(name, tag){719 var parent = document.getElementById(name);720 var children = parent.getElementsByTagName(tag);721 for (var i = 0; i < children.length; i++) {722 if (children[i].id != 'undefined') {723 children[i].onmouseover = function(){724 ModuleBuilder.helpToggle(this.id)725 };726 //children[i].onmouseover = function(){alert(this.id)};727 children[i].onmouseout = function(){728 ModuleBuilder.helpToggle('default')729 };730 }731 }732 },733 helpSetup: function(group, def, panel){734 if (!ModuleBuilder.panelHelp) ModuleBuilder.panelHelp = [];735 736 // setup the linkage between this tab/panel and the relevant help737 var id = ModuleBuilder.tabPanel.get("activeTab").get("id") ;738 ModuleBuilder.panelHelp [ id ] = { lang: group , def: def } ;739 740 // get the help text if required741 if ( ! ModuleBuilder.AllHelpLang ) ModuleBuilder.AllHelpLang = SUGAR.language.get('ModuleBuilder', 'help');742 if (group && def) {743 ModuleBuilder.helpLang = ModuleBuilder.AllHelpLang[group];744 ModuleBuilder.helpDefault = def;745 } 746 747 ModuleBuilder.helpToggle('default');748 },749 helpLoad: function(panelId){750 if (!ModuleBuilder.panelHelp) return;751 752 if ( ! ModuleBuilder.AllHelpLang ) ModuleBuilder.AllHelpLang = SUGAR.language.get('ModuleBuilder', 'help');753 754 if ( ModuleBuilder.panelHelp [ panelId ] )755 {756 ModuleBuilder.helpLang = ModuleBuilder.AllHelpLang[ ModuleBuilder.panelHelp [ panelId ].lang ];757 ModuleBuilder.helpDefault = ModuleBuilder.panelHelp [ panelId ].def ;758 ModuleBuilder.helpToggle('default');759 }760 },761 helpToggle: function(name){762 if (name == 'default')763 name = ModuleBuilder.helpDefault;764 if (ModuleBuilder.helpLang != null && typeof(ModuleBuilder.helpLang[name]) != 'undefined') {765 document.getElementById('mbhelp').innerHTML = ModuleBuilder.helpLang[name];766 }767 },768 handleSave: function(form, callBack){769 if (check_form(form)) {770 ModuleBuilder.state.isDirty=false;771 ModuleBuilder.submitForm(form, callBack);772 }773 },774 //Tree Functions775 handleTreeClick: function(o) {776 var node = o.node;777 ModuleBuilder.getContent(node.data.action);778 return false;779 },780 treeSubscribe:function(tree){781 tree.subscribe("labelClick", ModuleBuilder.treeLabelClick);782 },783 treeRefresh:function(type){784 ModuleBuilder.getContent('module=ModuleBuilder&action=ViewTree&tree=' + type);785 },786 //MB Specific787 addModule: function(MBpackage){788 ModuleBuilder.getContent('module=ModuleBuilder&action=module&view_package=' + MBpackage);789 },790 viewModule: function(MBpackage, module){791 ModuleBuilder.getContent('module=ModuleBuilder&action=module&view_package=' + MBpackage + '&view_module=' + module);792 },793 packageDelete: function(MBpackage){794 ajaxStatus.showStatus(SUGAR.language.get('ModuleBuilder', 'LBL_AJAX_DELETING'));795 if (confirm(SUGAR.language.get('ModuleBuilder', 'LBL_JS_REMOVE_PACKAGE'))) {796 ModuleBuilder.getContent('module=ModuleBuilder&action=DeletePackage&package=' + MBpackage);797 var node = ModuleBuilder.tree.getNodeByProperty('id', 'package_tree/' + MBpackage);798 if (node) ModuleBuilder.tree.removeNode(node, true);799 }800 },801 packagePublish: function(form){802 if (check_form(form)) {803 ajaxStatus.showStatus(SUGAR.language.get('ModuleBuilder', 'LBL_AJAX_BUILDPROGRESS'));804 ModuleBuilder.submitForm(form, ModuleBuilder.packageBuild);805 }806 },807 packageBuild: function(o){808 //make sure no user changes were made809 document.CreatePackage.action.value = 'BuildPackage';810 document.CreatePackage.submit();811 ajaxStatus.flashStatus(SUGAR.language.get('app_strings', 'LBL_REQUEST_PROCESSED'), 2000);812 ModuleBuilder.callLock = false;813 },814 packageDeploy: function(form, deployed){815 var confirmed = true;816 if (deployed){817 confirmed = confirm(SUGAR.language.get('ModuleBuilder', 'LBL_JS_DEPLOY_PACKAGE'));818 }819 if (confirmed && check_form(form)) {820 ajaxStatus.showStatus(SUGAR.language.get('ModuleBuilder', 'LBL_AJAX_DEPLOYPROGRESS'));821 ModuleBuilder.submitForm(form, ModuleBuilder.packageInstall);822 }823 },824 packageInstall: function(o){825 //make sure no user changes were made826 document.CreatePackage.action.value = 'displaydeploy';827 ModuleBuilder.callLock = false;828 ModuleBuilder.submitForm('CreatePackage', ModuleBuilder.packageInstallCleanup);829 },830 packageInstallCleanup: function(o){831 //make sure no user changes were made832 document.CreatePackage.action.value = 'displaydeploy';833 ModuleBuilder.callLock = false;834 ModuleBuilder.submitForm('CreatePackage');835 },836 beginDeploy: function(p){837 ModuleBuilder.asyncRequest('module=ModuleBuilder&action=DeployPackage&package=' + p, ModuleBuilder.deployComplete);838 },839 deployComplete: function(o){840 var resp = o.responseText;841 842 //check if the deploy completed843 if (!resp.match(/^\s*(\s*(Table already exists : [\w_]*)(<br>)*\s*)*complete$/m))844 {845 //Unknown error occured, warn the user846 alert(SUGAR.language.get("ModuleBuilder", "LBL_DEPLOY_FAILED"));847 }848 //Cleanup in the background849 ModuleBuilder.asyncRequest(850 'module=Administration&action=RebuildRelationship&silent=true',851 function(){}852 );853 ModuleBuilder.asyncRequest(854 'module=Administration&action=RebuildDashlets&silent=true',855 function(){} 856 );857 858 ModuleBuilder.failed = function(){};859 ModuleBuilder.state.hideFailedMesage = true;860 //Reload the page861 window.setTimeout("window.location.assign(window.location.href.split('#')[0])", 2000);862 863 864 },865 packageExport: function(form){866 if (check_form(form)) {867 ajaxStatus.showStatus(SUGAR.language.get('ModuleBuilder', 'LBL_AJAX_BUILDPROGRESS'));868 ModuleBuilder.submitForm(form, ModuleBuilder.packageExportProject);869 }870 },871 packageExportProject: function(o){872 //make sure no user changes were made873 document.CreatePackage.action.value = 'ExportPackage';874 document.CreatePackage.submit();875 ajaxStatus.flashStatus(SUGAR.language.get('app_strings', 'LBL_REQUEST_PROCESSED'), 2000);876 ModuleBuilder.callLock = false;877 },878 moduleDelete: function(MBpackage, module){879 ajaxStatus.showStatus(SUGAR.language.get('ModuleBuilder', 'LBL_AJAX_DELETING'));880 if (confirm(SUGAR.language.get('ModuleBuilder', 'LBL_JS_REMOVE_MODULE'))) {881 ModuleBuilder.getContent('module=ModuleBuilder&action=DeleteModule&package=' + MBpackage + '&view_module=' + module);882 var node = ModuleBuilder.tree.getNodeByProperty('id', 'package_tree/' + MBpackage + '/' + module);883 if (node) ModuleBuilder.tree.removeNode(node, true);884 }885 },886 moduleViewFields: function(o){887 ModuleBuilder.callLock = false;888 ModuleBuilder.getContent('module=ModuleBuilder&action=modulefields&view_package=' + ModuleBuilder.MBpackage + 889 '&view_module=' + ModuleBuilder.module);890 },891 moduleLoadField: function(name, type){892 if (typeof(type) == 'undefined')893 type = 0;894 if (typeof(formsWithFieldLogic) != 'undefined')895 formsWithFieldLogic = 'undefined';896 ModuleBuilder.getContent('module=ModuleBuilder&action=modulefield&view_package=' + ModuleBuilder.MBpackage + 897 '&view_module=' + ModuleBuilder.module + '&field=' + name + '&type=' + type);898 },899 moduleLoadLabels: function(type){900 if (typeof(type) == 'undefined')901 type = 0;902 else903 if (type == "studio") {904 ModuleBuilder.getContent('module=ModuleBuilder&action=editLabels&view_module=' + ModuleBuilder.module);905 }906 else907 if (type == "mb") {908 ModuleBuilder.getContent('module=ModuleBuilder&action=modulelabels&view_package=' + ModuleBuilder.MBpackage + '&view_module=' + ModuleBuilder.module + '&type=' + type);909 }910 },911 moduleViewRelationships: function(o){912 ModuleBuilder.callLock = false;913 ModuleBuilder.getContent('module=ModuleBuilder&action=relationships&view_package=' + ModuleBuilder.MBpackage + '&view_module=' + ModuleBuilder.module);914 },915 moduleLoadRelationship2: function(name, resetLabel, checkLanguage) {916 if (resetLabel && Dom.get('rhs_label')) {917 Dom.get('rhs_label').value = "";918 }919 var panel = ModuleBuilder.findTabById('relEditor');920 if (!panel) {921 panel = new YAHOO.SUGAR.ClosableTab({922 label: SUGAR.language.get("ModuleBuilder", "LBL_RELATIONSHIP_EDIT"),923 id: 'relEditor',924 scroll: true,925 cacheData: true,926 active :true927 }, ModuleBuilder.tabPanel);928 ModuleBuilder.tabPanel.addTab(panel);929 } else {930 ModuleBuilder.tabPanel.set("activeTab", panel);931 }932 var rtField = Dom.get('relationship_type_field');933 var relType = rtField ? rtField.options[rtField.selectedIndex].value: "";934 if (name == "") {935 name = Dom.get('rel_name_id') ? Dom.get('rel_name_id').value : "";936 }937 var params = {938 module: 'ModuleBuilder',939 action: 'relationship',940 view_package: ModuleBuilder.MBpackage,941 view_module: ModuleBuilder.module,942 relationship_name: name,943 relationship_type: relType,944 lhs_module: Dom.get('lhs_mod_field') ? Dom.get('lhs_mod_field').value : document.forms.relform ? document.forms.relform.lhs_module.value : "",945 rhs_module: Dom.get('rhs_mod_field') ? Dom.get('rhs_mod_field').value : "",946 lhs_label: Dom.get('lhs_label') ? Dom.get('lhs_label').value : "",947 rhs_label: Dom.get('rhs_label') ? Dom.get('rhs_label').value : "",948 json: false,949 id:'relEditor'950 };951 if(checkLanguage){952 params['relationship_lang'] = Dom.get('relationship_lang').value;953 params['ajaxLoad'] = '1';954 }955 ModuleBuilder.asyncRequest(params, function(o) {956 ajaxStatus.hideStatus();957 var tab = ModuleBuilder.findTabById('relEditor');958 tab.set("content", o.responseText);959 SUGAR.util.evalScript(o.responseText);960 });961 },962 moduleDropDown: function(name, field){963 ModuleBuilder.getContent('module=ModuleBuilder&action=dropdown&view_package=' + ModuleBuilder.MBpackage + '&view_module=' + ModuleBuilder.module + '&dropdown_name=' + name + '&field=' + field);964 },965 moduleViewLayouts: function(o){966 ModuleBuilder.callLock = false;967 ModuleBuilder.getContent('module=ModuleBuilder&MB=1&action=wizard&view_package=' + ModuleBuilder.MBpackage + '&view_module=' + ModuleBuilder.module);968 },969 findTabById : function(id) {970 var tabs = ModuleBuilder.tabPanel.get("tabs");971 for (var i = 0; i < tabs.length; i++) {972 if (tabs[i].get("id") == id)973 return tabs[i];974 }975 return null;976 }, 977 autoSetLayout: function(){978 var mp = ModuleBuilder.mainPanel;979 var c = Dom.get("mblayout");980 mp.set("height", Dom.getViewportHeight() - Dom.getY(c) - 30);981 mp.set("width", Dom.getViewportWidth() - 40);982 mp.resize(true);983 var tabEl = ModuleBuilder.tabPanel.get("element");984 Dom.setStyle(tabEl.firstChild.nextSibling, "overflow-y", "auto");985 Dom.setStyle(tabEl.firstChild.nextSibling, "height", tabEl.offsetHeight - ModuleBuilder.tabPanel.get("element").firstChild.offsetHeight - 5 + "px");986 //Resize editor layouts987 if (document.getElementById('toolbox')) Studio2.resizeDivs();988 if (document.getElementById('edittabs')) resizeDDLists();989 },990 paramsToUrl : function (params) {991 url = "";992 for (i in params) {993 url += i + "=" + params[i] + "&";994 }995 return url;996 },997 asyncRequest : function(params, callback) {998 var url;999 if (typeof params == "object") {1000 url = ModuleBuilder.paramsToUrl(params);1001 } else {1002 url = params;1003 }1004 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING_PAGE'));1005 Connect.asyncRequest(1006 Connect.method, 1007 Connect.url + '&' + url, 1008 {success: callback, failure: ModuleBuilder.failed}1009 );1010 },1011 refreshGlobalDropDown: function(o){1012 // just clear the callLock; the convention is that this is done in a handler rather than in updateContent1013 ModuleBuilder.callLock = false;1014 ModuleBuilder.updateContent(o);1015 },1016 refreshDropDown: function(){1017 ModuleBuilder.callLock = false;1018 document.popup_form.action.value = 'RefreshField';1019 document.popup_form.new_dropdown.value = ModuleBuilder.refreshDD_name;1020 SimpleList.refreshDD_name = '';1021 ModuleBuilder.submitForm("popup_form");1022 },1023 dropdownChanged: function(value){1024 var select = document.getElementById('default[]').options;1025 while(select.length > 0) {1026 select[0] = null;1027 }1028 ModuleBuilder.asyncRequest(1029 'module=ModuleBuilder&action=get_app_list_string&key=' + value +1030 '&view_package=' + ModuleBuilder.MBpackage + '&view_module=' + ModuleBuilder.module,1031 ModuleBuilder.dropdownChangedCallback1032 );1033 },1034 dropdownChangedCallback : function(o) {1035 var ajaxResponse = YAHOO.lang.JSON.parse(o.responseText);1036 var select = document.getElementById('default[]').options;1037 var count = 0;1038 for (var key in ajaxResponse) {1039 select[count] = new Option(ajaxResponse[key], key);1040 count++;1041 }1042 ajaxStatus.flashStatus(SUGAR.language.get('app_strings', 'LBL_REQUEST_PROCESSED'), 2000);1043 },1044 setSelectedOption : function (sel, option)1045 {1046 var sel = Dom.get(sel);1047 for (var i = 0; i < sel.options.length; i++)1048 {1049 if(sel.options[i].value == option) {1050 sel.selectedIndex = i;1051 return true;1052 }1053 }1054 return false;1055 }1056 };1057 ModuleBuilder.buttons = {};1058 ModuleBuilder.selected = {};1059 ModuleBuilder.callLock = false;1060}...

Full Screen

Full Screen

instanceTestFactory.js

Source:instanceTestFactory.js Github

copy

Full Screen

1const instanceTestFactory = [2 [3 "Empty module without imports argument",4 function() {5 return {6 buffer: emptyModuleBinary,7 args: [],8 exports: {},9 verify: () => {},10 };11 }12 ],13 [14 "Empty module with undefined imports argument",15 function() {16 return {17 buffer: emptyModuleBinary,18 args: [undefined],19 exports: {},20 verify: () => {},21 };22 }23 ],24 [25 "Empty module with empty imports argument",26 function() {27 return {28 buffer: emptyModuleBinary,29 args: [{}],30 exports: {},31 verify: () => {},32 };33 }34 ],35 [36 "getter order for imports object",37 function() {38 const builder = new WasmModuleBuilder();39 builder.addImportedGlobal("module", "global1", kWasmI32);40 builder.addImportedGlobal("module2", "global3", kWasmI32);41 builder.addImportedMemory("module", "memory", 0, 128);42 builder.addImportedGlobal("module", "global2", kWasmI32);43 const buffer = builder.toBuffer();44 const order = [];45 const imports = {46 get module() {47 order.push("module getter");48 return {49 get global1() {50 order.push("global1 getter");51 return 0;52 },53 get global2() {54 order.push("global2 getter");55 return 0;56 },57 get memory() {58 order.push("memory getter");59 return new WebAssembly.Memory({ "initial": 64, maximum: 128 });60 },61 }62 },63 get module2() {64 order.push("module2 getter");65 return {66 get global3() {67 order.push("global3 getter");68 return 0;69 },70 }71 },72 };73 const expected = [74 "module getter",75 "global1 getter",76 "module2 getter",77 "global3 getter",78 "module getter",79 "memory getter",80 "module getter",81 "global2 getter",82 ];83 return {84 buffer,85 args: [imports],86 exports: {},87 verify: () => assert_array_equals(order, expected),88 };89 }90 ],91 [92 "imports",93 function() {94 const builder = new WasmModuleBuilder();95 builder.addImport("module", "fn", kSig_v_v);96 builder.addImportedGlobal("module", "global", kWasmI32);97 builder.addImportedMemory("module", "memory", 0, 128);98 builder.addImportedTable("module", "table", 0, 128);99 const buffer = builder.toBuffer();100 const imports = {101 "module": {102 "fn": function() {},103 "global": 0,104 "memory": new WebAssembly.Memory({ "initial": 64, maximum: 128 }),105 "table": new WebAssembly.Table({ "element": "anyfunc", "initial": 64, maximum: 128 }),106 },107 get "module2"() {108 assert_unreached("Should not get modules that are not imported");109 },110 };111 return {112 buffer,113 args: [imports],114 exports: {},115 verify: () => {},116 };117 }118 ],119 [120 "imports with empty module names",121 function() {122 const builder = new WasmModuleBuilder();123 builder.addImport("", "fn", kSig_v_v);124 builder.addImportedGlobal("", "global", kWasmI32);125 builder.addImportedMemory("", "memory", 0, 128);126 builder.addImportedTable("", "table", 0, 128);127 const buffer = builder.toBuffer();128 const imports = {129 "": {130 "fn": function() {},131 "global": 0,132 "memory": new WebAssembly.Memory({ "initial": 64, maximum: 128 }),133 "table": new WebAssembly.Table({ "element": "anyfunc", "initial": 64, maximum: 128 }),134 },135 };136 return {137 buffer,138 args: [imports],139 exports: {},140 verify: () => {},141 };142 }143 ],144 [145 "imports with empty names",146 function() {147 const builder = new WasmModuleBuilder();148 builder.addImport("a", "", kSig_v_v);149 builder.addImportedGlobal("b", "", kWasmI32);150 builder.addImportedMemory("c", "", 0, 128);151 builder.addImportedTable("d", "", 0, 128);152 const buffer = builder.toBuffer();153 const imports = {154 "a": { "": function() {} },155 "b": { "": 0 },156 "c": { "": new WebAssembly.Memory({ "initial": 64, maximum: 128 }) },157 "d": { "": new WebAssembly.Table({ "element": "anyfunc", "initial": 64, maximum: 128 }) },158 };159 return {160 buffer,161 args: [imports],162 exports: {},163 verify: () => {},164 };165 }166 ],167 [168 "exports with empty name: function",169 function() {170 const builder = new WasmModuleBuilder();171 builder172 .addFunction("", kSig_v_d)173 .addBody([])174 .exportFunc();175 const buffer = builder.toBuffer();176 const exports = {177 "": { "kind": "function", "name": "0", "length": 1 },178 };179 return {180 buffer,181 args: [],182 exports,183 verify: () => {},184 };185 }186 ],187 [188 "exports with empty name: table",189 function() {190 const builder = new WasmModuleBuilder();191 builder.setTableBounds(1);192 builder.addExportOfKind("", kExternalTable, 0);193 const buffer = builder.toBuffer();194 const exports = {195 "": { "kind": "table", "length": 1 },196 };197 return {198 buffer,199 args: [],200 exports,201 verify: () => {},202 };203 }204 ],205 [206 "exports with empty name: global",207 function() {208 const builder = new WasmModuleBuilder();209 builder.addGlobal(kWasmI32, true)210 .exportAs("")211 .init = 7;212 const buffer = builder.toBuffer();213 const exports = {214 "": { "kind": "global", "value": 7 },215 };216 return {217 buffer,218 args: [],219 exports,220 verify: () => {},221 };222 }223 ],224 [225 "No imports",226 function() {227 const builder = new WasmModuleBuilder();228 builder229 .addFunction("fn", kSig_v_d)230 .addBody([])231 .exportFunc();232 builder233 .addFunction("fn2", kSig_v_v)234 .addBody([])235 .exportFunc();236 builder.setTableBounds(1);237 builder.addExportOfKind("table", kExternalTable, 0);238 builder.addGlobal(kWasmI32, true)239 .exportAs("global")240 .init = 7;241 builder.addGlobal(kWasmF64, true)242 .exportAs("global2")243 .init = 1.2;244 builder.addMemory(4, 8, true);245 const buffer = builder.toBuffer();246 const exports = {247 "fn": { "kind": "function", "name": "0", "length": 1 },248 "fn2": { "kind": "function", "name": "1", "length": 0 },249 "table": { "kind": "table", "length": 1 },250 "global": { "kind": "global", "value": 7 },251 "global2": { "kind": "global", "value": 1.2 },252 "memory": { "kind": "memory", "size": 4 },253 };254 return {255 buffer,256 args: [],257 exports,258 verify: () => {},259 };260 }261 ],262 [263 "exports and imports",264 function() {265 const value = 102;266 const builder = new WasmModuleBuilder();267 const index = builder.addImportedGlobal("module", "global", kWasmI32);268 builder269 .addFunction("fn", kSig_i_v)270 .addBody([271 kExprGlobalGet,272 index,273 kExprReturn,274 ])275 .exportFunc();276 const buffer = builder.toBuffer();277 const imports = {278 "module": {279 "global": value,280 },281 };282 const exports = {283 "fn": { "kind": "function", "name": "0", "length": 0 },284 };285 return {286 buffer,287 args: [imports],288 exports,289 verify: instance => assert_equals(instance.exports.fn(), value)290 };291 }292 ],293 [294 "i64 exports and imports",295 function() {296 const value = 102n;297 const builder = new WasmModuleBuilder();298 const index = builder.addImportedGlobal("module", "global", kWasmI64);299 builder300 .addFunction("fn", kSig_l_v)301 .addBody([302 kExprGlobalGet,303 index,304 kExprReturn,305 ])306 .exportFunc();307 const index2 = builder.addImportedGlobal("module", "global2", kWasmI64);308 builder.addExportOfKind("global", kExternalGlobal, index2);309 const buffer = builder.toBuffer();310 const imports = {311 "module": {312 "global": value,313 "global2": 2n ** 63n,314 },315 };316 const exports = {317 "fn": { "kind": "function", "name": "0", "length": 0 },318 "global": { "kind": "global", "value": -(2n ** 63n) },319 };320 return {321 buffer,322 args: [imports],323 exports,324 verify: instance => assert_equals(instance.exports.fn(), value)325 };326 }327 ],328 [329 "import with i32-returning function",330 function() {331 const builder = new WasmModuleBuilder();332 const fnIndex = builder.addImport("module", "fn", kSig_i_v);333 const fn2 = builder334 .addFunction("fn2", kSig_v_v)335 .addBody([336 kExprCallFunction,337 fnIndex,338 kExprReturn,339 ])340 .exportFunc();341 const buffer = builder.toBuffer();342 let called = false;343 const imports = {344 "module": {345 "fn": function() {346 called = true;347 return 6n;348 },349 },350 };351 return {352 buffer,353 args: [imports],354 exports: {355 "fn2": { "kind": "function", "name": String(fn2.index), "length": 0 },356 },357 verify: instance => {358 assert_throws_js(TypeError, () => instance.exports.fn2());359 assert_true(called, "Should have called into JS");360 }361 };362 }363 ],364 [365 "import with function that takes and returns i32",366 function() {367 const builder = new WasmModuleBuilder();368 const fnIndex = builder.addImport("module", "fn", kSig_i_i);369 const fn2 = builder370 .addFunction("fn2", kSig_i_v)371 .addBody([372 kExprI32Const, 0x66,373 kExprCallFunction,374 fnIndex,375 kExprReturn,376 ])377 .exportFunc();378 const buffer = builder.toBuffer();379 let called = false;380 const imports = {381 "module": {382 "fn": function(n) {383 called = true;384 assert_equals(n, -26);385 return { valueOf() { return 6; } };386 },387 },388 };389 return {390 buffer,391 args: [imports],392 exports: {393 "fn2": { "kind": "function", "name": String(fn2.index), "length": 0 },394 },395 verify: instance => {396 assert_equals(instance.exports.fn2(), 6);397 assert_true(called, "Should have called into JS");398 }399 };400 }401 ],402 [403 "import with i64-returning function",404 function() {405 const builder = new WasmModuleBuilder();406 const fnIndex = builder.addImport("module", "fn", kSig_l_v);407 const fn2 = builder408 .addFunction("fn2", kSig_v_v)409 .addBody([410 kExprCallFunction,411 fnIndex,412 kExprReturn,413 ])414 .exportFunc();415 const buffer = builder.toBuffer();416 let called = false;417 const imports = {418 "module": {419 "fn": function() {420 called = true;421 return 6;422 },423 },424 };425 return {426 buffer,427 args: [imports],428 exports: {429 "fn2": { "kind": "function", "name": String(fn2.index), "length": 0 },430 },431 verify: instance => {432 assert_throws_js(TypeError, () => instance.exports.fn2());433 assert_true(called, "Should have called into JS");434 }435 };436 }437 ],438 [439 "import with function that takes and returns i64",440 function() {441 const builder = new WasmModuleBuilder();442 const fnIndex = builder.addImport("module", "fn", kSig_l_l);443 const fn2 = builder444 .addFunction("fn2", kSig_l_v)445 .addBody([446 kExprI64Const, 0x66,447 kExprCallFunction,448 fnIndex,449 kExprReturn,450 ])451 .exportFunc();452 const buffer = builder.toBuffer();453 let called = false;454 const imports = {455 "module": {456 "fn": function(n) {457 called = true;458 assert_equals(n, -26n);459 return { valueOf() { return 6n; } };460 },461 },462 };463 return {464 buffer,465 args: [imports],466 exports: {467 "fn2": { "kind": "function", "name": String(fn2.index), "length": 0 },468 },469 verify: instance => {470 assert_equals(instance.exports.fn2(), 6n);471 assert_true(called, "Should have called into JS");472 }473 };474 }475 ],476 [477 "import with i32-taking function",478 function() {479 const builder = new WasmModuleBuilder();480 const fn = builder481 .addFunction("fn", kSig_v_i)482 .addBody([483 kExprReturn,484 ])485 .exportFunc();486 const buffer = builder.toBuffer();487 return {488 buffer,489 args: [],490 exports: {491 "fn": { "kind": "function", "name": String(fn.index), "length": 1 },492 },493 verify: instance => assert_throws_js(TypeError, () => instance.exports.fn(6n))494 };495 }496 ],497 [498 "import with i64-taking function",499 function() {500 const builder = new WasmModuleBuilder();501 const fn = builder502 .addFunction("fn", kSig_v_l)503 .addBody([504 kExprReturn,505 ])506 .exportFunc();507 const buffer = builder.toBuffer();508 return {509 buffer,510 args: [],511 exports: {512 "fn": { "kind": "function", "name": String(fn.index), "length": 1 },513 },514 verify: instance => assert_throws_js(TypeError, () => instance.exports.fn(6))515 };516 }517 ],518 [519 "export i64-returning function",520 function() {521 const builder = new WasmModuleBuilder();522 const fn = builder523 .addFunction("fn", kSig_l_v)524 .addBody([525 kExprI64Const, 0x66,526 kExprReturn,527 ])528 .exportFunc();529 const buffer = builder.toBuffer();530 return {531 buffer,532 args: [],533 exports: {534 "fn": { "kind": "function", "name": String(fn.index), "length": 0 },535 },536 verify: instance => assert_equals(instance.exports.fn(), -26n)537 };538 }539 ],540 [541 "i32 mutable WebAssembly.Global import",542 function() {543 const initial = 102;544 const value = new WebAssembly.Global({ "value": "i32", "mutable": true }, initial);545 const builder = new WasmModuleBuilder();546 const index = builder.addImportedGlobal("module", "global", kWasmI32, true);547 const fn = builder548 .addFunction("fn", kSig_i_v)549 .addBody([550 kExprGlobalGet,551 index,552 kExprReturn,553 ])554 .exportFunc();555 const buffer = builder.toBuffer();556 const imports = {557 "module": {558 "global": value,559 },560 };561 const exports = {562 "fn": { "kind": "function", "name": String(fn.index), "length": 0 },563 };564 return {565 buffer,566 args: [imports],567 exports,568 verify: instance => {569 assert_equals(instance.exports.fn(), initial);570 const after = 201;571 value.value = after;572 assert_equals(instance.exports.fn(), after);573 }574 };575 }576 ],577 [578 "i64 mutable WebAssembly.Global import",579 function() {580 const initial = 102n;581 const value = new WebAssembly.Global({ "value": "i64", "mutable": true }, initial);582 const builder = new WasmModuleBuilder();583 const index = builder.addImportedGlobal("module", "global", kWasmI64, true);584 const fn = builder585 .addFunction("fn", kSig_l_v)586 .addBody([587 kExprGlobalGet,588 index,589 kExprReturn,590 ])591 .exportFunc();592 const buffer = builder.toBuffer();593 const imports = {594 "module": {595 "global": value,596 },597 };598 const exports = {599 "fn": { "kind": "function", "name": String(fn.index), "length": 0 },600 };601 return {602 buffer,603 args: [imports],604 exports,605 verify: instance => {606 assert_equals(instance.exports.fn(), initial);607 const after = 201n;608 value.value = after;609 assert_equals(instance.exports.fn(), after);610 }611 };612 }613 ],614 [615 "Multiple i64 arguments",616 function() {617 const builder = new WasmModuleBuilder();618 const fn = builder619 .addFunction("fn", kSig_l_ll)620 .addBody([621 kExprLocalGet, 1,622 ])623 .exportFunc();624 const buffer = builder.toBuffer();625 const exports = {626 "fn": { "kind": "function", "name": String(fn.index), "length": 2 },627 };628 return {629 buffer,630 args: [],631 exports,632 verify: instance => {633 const fn = instance.exports.fn;634 assert_equals(fn(1n, 0n), 0n);635 assert_equals(fn(1n, 123n), 123n);636 assert_equals(fn(1n, -123n), -123n);637 assert_equals(fn(1n, "5"), 5n);638 assert_throws_js(TypeError, () => fn(1n, 5));639 }640 };641 }642 ],643 [644 "stray argument",645 function() {646 return {647 buffer: emptyModuleBinary,648 args: [{}, {}],649 exports: {},650 verify: () => {}651 };652 }653 ],...

Full Screen

Full Screen

test_utilities.py

Source:test_utilities.py Github

copy

Full Screen

1# Copyright 2020 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Utility functions that support testing.16All functions that can be commonly used by various tests are in this file.17"""18from __future__ import absolute_import19from __future__ import division20from __future__ import print_function21from flatbuffers.python import flatbuffers22from tensorflow.lite.python import schema_py_generated as schema_fb23def BuildMockModel():24 """Creates a flatbuffer object containing an example model."""25 builder = flatbuffers.Builder(1024)26 schema_fb.BufferStart(builder)27 buffer0_offset = schema_fb.BufferEnd(builder)28 schema_fb.BufferStartDataVector(builder, 10)29 builder.PrependUint8(0)30 builder.PrependUint8(1)31 builder.PrependUint8(2)32 builder.PrependUint8(3)33 builder.PrependUint8(4)34 builder.PrependUint8(5)35 builder.PrependUint8(6)36 builder.PrependUint8(7)37 builder.PrependUint8(8)38 builder.PrependUint8(9)39 buffer1_data_offset = builder.EndVector(10)40 schema_fb.BufferStart(builder)41 schema_fb.BufferAddData(builder, buffer1_data_offset)42 buffer1_offset = schema_fb.BufferEnd(builder)43 schema_fb.BufferStart(builder)44 buffer2_offset = schema_fb.BufferEnd(builder)45 schema_fb.ModelStartBuffersVector(builder, 3)46 builder.PrependUOffsetTRelative(buffer2_offset)47 builder.PrependUOffsetTRelative(buffer1_offset)48 builder.PrependUOffsetTRelative(buffer0_offset)49 buffers_offset = builder.EndVector(3)50 string0_offset = builder.CreateString('input_tensor')51 schema_fb.TensorStartShapeVector(builder, 3)52 builder.PrependInt32(1)53 builder.PrependInt32(2)54 builder.PrependInt32(5)55 shape0_offset = builder.EndVector(3)56 schema_fb.TensorStart(builder)57 schema_fb.TensorAddName(builder, string0_offset)58 schema_fb.TensorAddShape(builder, shape0_offset)59 schema_fb.TensorAddType(builder, 0)60 schema_fb.TensorAddBuffer(builder, 0)61 tensor0_offset = schema_fb.TensorEnd(builder)62 schema_fb.QuantizationParametersStartMinVector(builder, 5)63 builder.PrependFloat32(0.5)64 builder.PrependFloat32(2.0)65 builder.PrependFloat32(5.0)66 builder.PrependFloat32(10.0)67 builder.PrependFloat32(20.0)68 quant1_min_offset = builder.EndVector(5)69 schema_fb.QuantizationParametersStartMaxVector(builder, 5)70 builder.PrependFloat32(10.0)71 builder.PrependFloat32(20.0)72 builder.PrependFloat32(-50.0)73 builder.PrependFloat32(1.0)74 builder.PrependFloat32(2.0)75 quant1_max_offset = builder.EndVector(5)76 schema_fb.QuantizationParametersStartScaleVector(builder, 5)77 builder.PrependFloat32(3.0)78 builder.PrependFloat32(4.0)79 builder.PrependFloat32(5.0)80 builder.PrependFloat32(6.0)81 builder.PrependFloat32(7.0)82 quant1_scale_offset = builder.EndVector(5)83 schema_fb.QuantizationParametersStartZeroPointVector(builder, 5)84 builder.PrependInt64(1)85 builder.PrependInt64(2)86 builder.PrependInt64(3)87 builder.PrependInt64(-1)88 builder.PrependInt64(-2)89 quant1_zero_point_offset = builder.EndVector(5)90 schema_fb.QuantizationParametersStart(builder)91 schema_fb.QuantizationParametersAddMin(builder, quant1_min_offset)92 schema_fb.QuantizationParametersAddMax(builder, quant1_max_offset)93 schema_fb.QuantizationParametersAddScale(builder, quant1_scale_offset)94 schema_fb.QuantizationParametersAddZeroPoint(builder,95 quant1_zero_point_offset)96 quantization1_offset = schema_fb.QuantizationParametersEnd(builder)97 string1_offset = builder.CreateString('constant_tensor')98 schema_fb.TensorStartShapeVector(builder, 3)99 builder.PrependInt32(1)100 builder.PrependInt32(2)101 builder.PrependInt32(5)102 shape1_offset = builder.EndVector(3)103 schema_fb.TensorStart(builder)104 schema_fb.TensorAddName(builder, string1_offset)105 schema_fb.TensorAddShape(builder, shape1_offset)106 schema_fb.TensorAddType(builder, 0)107 schema_fb.TensorAddBuffer(builder, 1)108 schema_fb.TensorAddQuantization(builder, quantization1_offset)109 tensor1_offset = schema_fb.TensorEnd(builder)110 string2_offset = builder.CreateString('output_tensor')111 schema_fb.TensorStartShapeVector(builder, 3)112 builder.PrependInt32(1)113 builder.PrependInt32(2)114 builder.PrependInt32(5)115 shape2_offset = builder.EndVector(3)116 schema_fb.TensorStart(builder)117 schema_fb.TensorAddName(builder, string2_offset)118 schema_fb.TensorAddShape(builder, shape2_offset)119 schema_fb.TensorAddType(builder, 0)120 schema_fb.TensorAddBuffer(builder, 2)121 tensor2_offset = schema_fb.TensorEnd(builder)122 schema_fb.SubGraphStartTensorsVector(builder, 3)123 builder.PrependUOffsetTRelative(tensor2_offset)124 builder.PrependUOffsetTRelative(tensor1_offset)125 builder.PrependUOffsetTRelative(tensor0_offset)126 tensors_offset = builder.EndVector(3)127 schema_fb.SubGraphStartInputsVector(builder, 1)128 builder.PrependInt32(0)129 inputs_offset = builder.EndVector(1)130 schema_fb.SubGraphStartOutputsVector(builder, 1)131 builder.PrependInt32(2)132 outputs_offset = builder.EndVector(1)133 schema_fb.OperatorCodeStart(builder)134 schema_fb.OperatorCodeAddBuiltinCode(builder, schema_fb.BuiltinOperator.ADD)135 schema_fb.OperatorCodeAddVersion(builder, 1)136 code_offset = schema_fb.OperatorCodeEnd(builder)137 schema_fb.ModelStartOperatorCodesVector(builder, 1)138 builder.PrependUOffsetTRelative(code_offset)139 codes_offset = builder.EndVector(1)140 schema_fb.OperatorStartInputsVector(builder, 2)141 builder.PrependInt32(0)142 builder.PrependInt32(1)143 op_inputs_offset = builder.EndVector(2)144 schema_fb.OperatorStartOutputsVector(builder, 1)145 builder.PrependInt32(2)146 op_outputs_offset = builder.EndVector(1)147 schema_fb.OperatorStart(builder)148 schema_fb.OperatorAddOpcodeIndex(builder, 0)149 schema_fb.OperatorAddInputs(builder, op_inputs_offset)150 schema_fb.OperatorAddOutputs(builder, op_outputs_offset)151 op_offset = schema_fb.OperatorEnd(builder)152 schema_fb.SubGraphStartOperatorsVector(builder, 1)153 builder.PrependUOffsetTRelative(op_offset)154 ops_offset = builder.EndVector(1)155 string3_offset = builder.CreateString('subgraph_name')156 schema_fb.SubGraphStart(builder)157 schema_fb.SubGraphAddName(builder, string3_offset)158 schema_fb.SubGraphAddTensors(builder, tensors_offset)159 schema_fb.SubGraphAddInputs(builder, inputs_offset)160 schema_fb.SubGraphAddOutputs(builder, outputs_offset)161 schema_fb.SubGraphAddOperators(builder, ops_offset)162 subgraph_offset = schema_fb.SubGraphEnd(builder)163 schema_fb.ModelStartSubgraphsVector(builder, 1)164 builder.PrependUOffsetTRelative(subgraph_offset)165 subgraphs_offset = builder.EndVector(1)166 string4_offset = builder.CreateString('model_description')167 schema_fb.ModelStart(builder)168 schema_fb.ModelAddOperatorCodes(builder, codes_offset)169 schema_fb.ModelAddSubgraphs(builder, subgraphs_offset)170 schema_fb.ModelAddDescription(builder, string4_offset)171 schema_fb.ModelAddBuffers(builder, buffers_offset)172 model_offset = schema_fb.ModelEnd(builder)173 builder.Finish(model_offset)174 model_data = builder.Output()...

Full Screen

Full Screen

builder_name_schema.py

Source:builder_name_schema.py Github

copy

Full Screen

1# Copyright 2014 The Chromium Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4""" Utilities for dealing with builder names. This module obtains its attributes5dynamically from builder_name_schema.json. """6import json7import os8# All of these global variables are filled in by _LoadSchema().9# The full schema.10BUILDER_NAME_SCHEMA = None11# Character which separates parts of a builder name.12BUILDER_NAME_SEP = None13# Builder roles.14BUILDER_ROLE_CANARY = 'Canary'15BUILDER_ROLE_BUILD = 'Build'16BUILDER_ROLE_HOUSEKEEPER = 'Housekeeper'17BUILDER_ROLE_PERF = 'Perf'18BUILDER_ROLE_TEST = 'Test'19BUILDER_ROLES = (BUILDER_ROLE_CANARY,20 BUILDER_ROLE_BUILD,21 BUILDER_ROLE_HOUSEKEEPER,22 BUILDER_ROLE_PERF,23 BUILDER_ROLE_TEST)24# Suffix which distinguishes trybots from normal bots.25TRYBOT_NAME_SUFFIX = None26def _LoadSchema():27 """ Load the builder naming schema from the JSON file. """28 def _UnicodeToStr(obj):29 """ Convert all unicode strings in obj to Python strings. """30 if isinstance(obj, unicode):31 return str(obj)32 elif isinstance(obj, dict):33 return dict(map(_UnicodeToStr, obj.iteritems()))34 elif isinstance(obj, list):35 return list(map(_UnicodeToStr, obj))36 elif isinstance(obj, tuple):37 return tuple(map(_UnicodeToStr, obj))38 else:39 return obj40 builder_name_json_filename = os.path.join(41 os.path.dirname(__file__), 'builder_name_schema.json')42 builder_name_schema_json = json.load(open(builder_name_json_filename))43 global BUILDER_NAME_SCHEMA44 BUILDER_NAME_SCHEMA = _UnicodeToStr(45 builder_name_schema_json['builder_name_schema'])46 global BUILDER_NAME_SEP47 BUILDER_NAME_SEP = _UnicodeToStr(48 builder_name_schema_json['builder_name_sep'])49 global TRYBOT_NAME_SUFFIX50 TRYBOT_NAME_SUFFIX = _UnicodeToStr(51 builder_name_schema_json['trybot_name_suffix'])52 # Since the builder roles are dictionary keys, just assert that the global53 # variables above account for all of them.54 assert len(BUILDER_ROLES) == len(BUILDER_NAME_SCHEMA)55 for role in BUILDER_ROLES:56 assert role in BUILDER_NAME_SCHEMA57_LoadSchema()58def MakeBuilderName(role, extra_config=None, is_trybot=False, **kwargs):59 schema = BUILDER_NAME_SCHEMA.get(role)60 if not schema:61 raise ValueError('%s is not a recognized role.' % role)62 for k, v in kwargs.iteritems():63 if BUILDER_NAME_SEP in v:64 raise ValueError('%s not allowed in %s.' % (BUILDER_NAME_SEP, v))65 if not k in schema:66 raise ValueError('Schema does not contain "%s": %s' %(k, schema))67 if extra_config and BUILDER_NAME_SEP in extra_config:68 raise ValueError('%s not allowed in %s.' % (BUILDER_NAME_SEP,69 extra_config))70 name_parts = [role]71 name_parts.extend([kwargs[attribute] for attribute in schema])72 if extra_config:73 name_parts.append(extra_config)74 if is_trybot:75 name_parts.append(TRYBOT_NAME_SUFFIX)76 return BUILDER_NAME_SEP.join(name_parts)77def BuilderNameFromObject(obj, is_trybot=False):78 """Create a builder name based on properties of the given object.79 Args:80 obj: the object from which to create the builder name. The object must81 have as properties:82 - A valid builder role, as defined in the JSON file83 - All properties listed in the JSON file for that role84 - Optionally, an extra_config property85 is_trybot: bool; whether or not the builder is a trybot.86 Returns:87 string which combines the properties of the given object into a valid88 builder name.89 """90 schema = BUILDER_NAME_SCHEMA.get(obj.role)91 if not schema:92 raise ValueError('%s is not a recognized role.' % obj.role)93 name_parts = [obj.role]94 for attr_name in schema:95 attr_val = getattr(obj, attr_name)96 name_parts.append(attr_val)97 extra_config = getattr(obj, 'extra_config', None)98 if extra_config:99 name_parts.append(extra_config)100 if is_trybot:101 name_parts.append(TRYBOT_NAME_SUFFIX)102 return BUILDER_NAME_SEP.join(name_parts)103def IsTrybot(builder_name):104 """ Returns true if builder_name refers to a trybot (as opposed to a105 waterfall bot). """106 return builder_name.endswith(TRYBOT_NAME_SUFFIX)107def GetWaterfallBot(builder_name):108 """Returns the name of the waterfall bot for this builder. If it is not a109 trybot, builder_name is returned unchanged. If it is a trybot the name is110 returned without the trybot suffix."""111 if not IsTrybot(builder_name):112 return builder_name113 return _WithoutSuffix(builder_name, BUILDER_NAME_SEP + TRYBOT_NAME_SUFFIX)114def TrybotName(builder_name):115 """Returns the name of the trybot clone of this builder.116 If the given builder is a trybot, the name is returned unchanged. If not, the117 TRYBOT_NAME_SUFFIX is appended.118 """119 if builder_name.endswith(TRYBOT_NAME_SUFFIX):120 return builder_name121 return builder_name + BUILDER_NAME_SEP + TRYBOT_NAME_SUFFIX122def _WithoutSuffix(string, suffix):123 """ Returns a copy of string 'string', but with suffix 'suffix' removed.124 Raises ValueError if string does not end with suffix. """125 if not string.endswith(suffix):126 raise ValueError('_WithoutSuffix: string %s does not end with suffix %s' % (127 string, suffix))128 return string[:-len(suffix)]129def DictForBuilderName(builder_name):130 """Makes a dictionary containing details about the builder from its name."""131 split_name = builder_name.split(BUILDER_NAME_SEP)132 def pop_front():133 try:134 return split_name.pop(0)135 except:136 raise ValueError('Invalid builder name: %s' % builder_name)137 result = {'is_trybot': False}138 if split_name[-1] == TRYBOT_NAME_SUFFIX:139 result['is_trybot'] = True140 split_name.pop()141 if split_name[0] in BUILDER_NAME_SCHEMA.keys():142 key_list = BUILDER_NAME_SCHEMA[split_name[0]]143 result['role'] = pop_front()144 for key in key_list:145 result[key] = pop_front()146 if split_name:147 result['extra_config'] = pop_front()148 if split_name:149 raise ValueError('Invalid builder name: %s' % builder_name)150 else:151 raise ValueError('Invalid builder name: %s' % builder_name)...

Full Screen

Full Screen

ct-footer-builder.js

Source:ct-footer-builder.js Github

copy

Full Screen

1import {2 createElement,3 Fragment,4 useRef,5 Component,6 useEffect,7 useMemo,8 createPortal,9 useState,10 useCallback,11 createContext,12 useReducer,13} from '@wordpress/element'14import { __ } from 'ct-i18n'15import ColumnsBuilder from '../../customizer/panels-builder/columns/ColumnsBuilder'16import AvailableItems from '../../customizer/panels-builder/columns/AvailableItems'17import { builderReducer } from '../../customizer/panels-builder/columns/builderReducer'18export const DragDropContext = createContext({})19const getDocument = (x) =>20 x.document || x.contentDocument || x.contentWindow.document21export const fetchCurrentFooter = () => {22 const document = getDocument(23 wp.customize.previewer.container.find('iframe')[0]24 )25 if (26 wp.customize.previewer.container27 .find('iframe')[0]28 .contentDocument.querySelector('footer.site-footer')29 ) {30 return wp.customize.previewer.container31 .find('iframe')[0]32 .contentDocument.querySelector('footer.site-footer').dataset.id33 }34 return null35}36const FooterBuilder = ({37 value: allBuilderSections,38 option,39 onChange: onBuilderValueChange,40}) => {41 const currentFooter = useRef(null)42 if (currentFooter.current === null) {43 currentFooter.current = (44 allBuilderSections.sections.find(45 ({ id }) => id.indexOf(fetchCurrentFooter()) > -146 ) || allBuilderSections.sections[0]47 ).id48 }49 useEffect(() => {50 let {51 __forced_static_footer__,52 __should_refresh__,53 ...old54 } = wp.customize('footer_placements')()55 Object.keys(old).map((key) => {56 if (parseFloat(key)) {57 delete old[key]58 }59 })60 wp.customize('footer_placements')({61 ...old,62 __forced_static_footer__: (63 allBuilderSections.sections.find(64 ({ id }) => id.indexOf(fetchCurrentFooter()) > -165 ) || allBuilderSections.sections[0]66 ).id,67 })68 return () => {69 const { __forced_static_footer__, ...old } = wp.customize(70 'footer_placements'71 )()72 wp.customize('footer_placements')({73 __should_refresh__: true,74 [Math.random()]: 'update',75 ...old,76 })77 }78 }, [])79 const [builderValueCollection, builderValueDispatchInternal] = useReducer(80 builderReducer,81 {82 ...allBuilderSections,83 ...(currentFooter.current84 ? {85 __forced_static_footer__: currentFooter.current,86 }87 : {}),88 }89 )90 const [builderCollapsed, setBuilderCollapsed] = useState(false)91 const builderValue = useMemo(92 () =>93 builderValueCollection.sections.find(94 ({ id }) =>95 id === builderValueCollection.__forced_static_footer__96 ) || builderValueCollection.sections[0],97 [builderValueCollection]98 )99 const [isDragging, setIsDragging] = useState(false)100 const inlinedItemsFromBuilder = builderValue.rows.reduce(101 (currentItems, { columns }) => [102 ...currentItems,103 ...(columns || []).reduce((c, items) => [...c, ...items], []),104 ],105 []106 )107 const builderValueDispatch = useCallback(108 (payload) =>109 builderValueDispatchInternal({110 ...payload,111 onBuilderValueChange,112 }),113 [builderValueDispatchInternal, onBuilderValueChange]114 )115 const setList = (lists) =>116 builderValueDispatch({117 type: 'SET_LIST',118 onBuilderValueChange,119 payload: {120 lists,121 },122 })123 useEffect(() => {124 return () => {125 document126 .querySelector('.wp-full-overlay')127 .classList.remove('ct-builder-collapsed')128 }129 }, [])130 return (131 <Fragment>132 <DragDropContext.Provider133 value={{134 isDragging,135 setIsDragging,136 setList,137 builderValueDispatch,138 builderValueCollection,139 builderValue,140 onChange: ({ id, value }) => setList({ [id]: value }),141 }}>142 <AvailableItems143 builderValue={builderValue}144 inlinedItemsFromBuilder={inlinedItemsFromBuilder}145 builderValueDispatch={builderValueDispatch}146 builderValueCollection={builderValueCollection}147 />148 {createPortal(149 <div className="ct-builder-footer">150 <ul className="ct-view-switch">151 <li152 className="ct-builder-toggle"153 onClick={() => {154 setBuilderCollapsed(!builderCollapsed)155 if (builderCollapsed) {156 document157 .querySelector('.wp-full-overlay')158 .classList.remove(159 'ct-builder-collapsed'160 )161 } else {162 document163 .querySelector('.wp-full-overlay')164 .classList.add(165 'ct-builder-collapsed'166 )167 }168 }}>169 {builderCollapsed170 ? __('Show Builder', 'blocksy')171 : __('Hide Builder', 'blocksy')}172 </li>173 </ul>174 <ColumnsBuilder builderValue={builderValue} />175 </div>,176 document.querySelector('.ct-panel-builder')177 )}178 </DragDropContext.Provider>179 </Fragment>180 )181}182FooterBuilder.renderingConfig = { design: 'none' }...

Full Screen

Full Screen

fullscreen.js

Source:fullscreen.js Github

copy

Full Screen

1(function ($, fwe, _, localized) {2 fwe.on('fw:option-type:builder:init', function (data) {3 if (!data.$elements.length) {4 return;5 }6 if (!$('#post_ID').length) {7 /**8 * Don't enable fullscreen if not on post edit page9 * Because this script requires the Publish and Preview post buttons10 */11 return;12 }13 var elements = {14 $saveButton: $('#publish'),15 $previewButton: $('#post-preview')16 };17 var utils = {18 toogleFullscreen: function ($builder) {19 if ($builder.hasClass('builder-fullscreen')) {20 utils.fullscreenOff.call($builder);21 utils.unsetStorageItem();22 } else {23 utils.fullscreenOn.call($builder);24 }25 },26 getFullscreenHeight: function () {27 var $diffHeight = parseInt($('.builder-items-types').height() + 80);28 return parseInt($('body').height() - $diffHeight);29 },30 selectBackdrop: function ($builder) {31 return $builder.next('.fw-option-type-builder-fullscreen-backdrop');32 },33 fullscreenOn: function () {34 var $builder = $(this);35 utils.selectBackdrop($builder).removeClass('fw-hidden');36 $builder.addClass('builder-fullscreen');37 $(document.body).css('overflow-y', 'hidden'); // remove body scroll38 $builder.find('> .builder-items-types .fullscreen-btn .text').text(localized.l10n.exit_fullscreen);39 $builder.find('> .builder-items-types .fullscreen-btn .icon').removeClass('icon-fullscreen-on').addClass('icon-fullscreen-off');40 $builder.find('> .builder-root-items')41 .css({'max-height': utils.getFullscreenHeight() + 'px'})42 .on('scroll.builder-fullscreen', function(){43 $builder.find('> .builder-items-types').css(44 'border-bottom-color',45 $(this).scrollTop() ? '#eee' : ''46 );47 });48 },49 fullscreenOff: function () {50 var $builder = $(this);51 utils.selectBackdrop($builder).addClass('fw-hidden');52 $builder.removeClass('builder-fullscreen');53 $(document.body).css('overflow-y', '');54 $builder.find('> .builder-items-types .fullscreen-btn .text').text(localized.l10n.fullscreen);55 $builder.find('> .builder-items-types .fullscreen-btn .icon').removeClass('icon-fullscreen-off').addClass('icon-fullscreen-on');56 $builder.find('> .builder-root-items')57 .css({'max-height': ''})58 .off('.builder-fullscreen');59 $builder.find('> .builder-items-types').css('border-bottom-color', '');60 },61 getPostId: function () {62 return $('#post_ID').val();63 },64 setStorageItem: function () {65 return $.ajax({66 type: "post",67 dataType: "json",68 url: ajaxurl,69 data: {70 'action': 'fw_builder_fullscreen_set_storage_item',71 'post_id': utils.getPostId()72 }73 });74 },75 unsetStorageItem: function () {76 return $.ajax({77 type: "post",78 dataType: "json",79 url: ajaxurl,80 data: {81 'action': 'fw_builder_fullscreen_unset_storage_item',82 'post_id': utils.getPostId()83 }84 });85 }86 };87 data.$elements.each(function(){88 var $builder = $(this);89 $builder.find('.fw-options-tabs-list ul').before(90 '<div class="fullscreen-btn">'+91 ' <div class="icon icon-fullscreen-on"></div>'+92 ' <div class="text">'+ localized.l10n.fullscreen +'</div>'+93 '</div>'94 );95 $builder.find('> .builder-items-types .fullscreen-btn').on('click', function(e){96 e.preventDefault();97 utils.toogleFullscreen($builder);98 });99 utils.selectBackdrop($builder)100 .on('click', '.preview', function (e) {101 e.preventDefault();102 utils.setStorageItem();103 elements.$previewButton.trigger('click');104 })105 .one('click', '.button-primary', function (e) {106 e.preventDefault();107 utils.selectBackdrop($builder).removeClass('fw-hidden');108 utils.setStorageItem().done(function () {109 elements.$saveButton.focus().trigger('click');110 });111 });112 if ($builder.hasClass('builder-fullscreen')) {113 $builder.removeClass('builder-fullscreen');114 utils.toogleFullscreen($builder);115 }116 });117 });...

Full Screen

Full Screen

BUILD

Source:BUILD Github

copy

Full Screen

1package(2 default_visibility = [3 "//visibility:public",4 ],5 licenses = ["notice"], # Apache 2.06)7cc_library(8 name = "op_builder",9 srcs = [10 "activation_builder.cc",11 "arg_min_max_builder.cc",12 "arithmetic_builder.cc",13 "concat_builder.cc",14 "conv_2d_builder.cc",15 "l2_normalization_builder.cc",16 "matmul_builder.cc",17 "neg_op_builder.cc",18 "op_builder.cc",19 "pad_builder.cc",20 "pool_2d_builder.cc",21 "reduce_builder.cc",22 "reshape_builder.cc",23 "resize_bilinear_builder.cc",24 "resize_nearest_neighbor_builder.cc",25 "softmax_builder.cc",26 "space_to_depth_builder.cc",27 "split_builder.cc",28 "transpose_builder.cc",29 "transpose_conv_2d_builder.cc",30 ],31 hdrs = [32 "activation_builder.h",33 "arg_min_max_builder.h",34 "arithmetic_builder.h",35 "concat_builder.h",36 "conv_2d_builder.h",37 "l2_normalization_builder.h",38 "matmul_builder.h",39 "neg_op_builder.h",40 "op_builder.h",41 "pad_builder.h",42 "pool_2d_builder.h",43 "reduce_builder.h",44 "reshape_builder.h",45 "resize_bilinear_builder.h",46 "resize_nearest_neighbor_builder.h",47 "softmax_builder.h",48 "space_to_depth_builder.h",49 "split_builder.h",50 "transpose_builder.h",51 "transpose_conv_2d_builder.h",52 ],53 tags = [54 "manual",55 "nobuilder",56 ],57 deps = [58 ":op_factory",59 "//tensorflow/lite:kernel_api",60 "//tensorflow/lite/c:common",61 "//tensorflow/lite/experimental/delegates/hexagon:hexagon_implementation",62 "//tensorflow/lite/experimental/delegates/hexagon/hexagon_nn:hexagon_nn_header",63 "//tensorflow/lite/kernels:kernel_util",64 "//tensorflow/lite/kernels:padding",65 "//tensorflow/lite/kernels/internal:optimized_base",66 "@hexagon_nn//:hexagon_nn_ops",67 ],68)69cc_library(70 name = "op_factory",71 hdrs = ["op_factory.h"],72 tags = [73 "manual",74 "nobuilder",75 ],...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react';2import { withKnobs } from '@storybook/addon-knobs';3import { withInfo } from '@storybook/addon-info';4import { withA11y } from '@storybook/addon-a11y';5import { withReadme } from 'storybook-readme';6import { withTests } from '@storybook/addon-jest';7import { withConsole } from '@storybook/addon-console';8import { withViewport } from '@storybook/addon-viewport';9import { withBackgrounds } from '@storybook/addon-backgrounds';10import { withOptions } from '@storybook/addon-options';11import { withGraphQL } from 'storybook-addon-graphql';12import { withPerformance } from 'storybook-addon-performance';13import { withLinks } from '@storybook/addon-links';14import { withPropsTable } from 'storybook-addon-react-docgen';15import { withNotes } from '@storybook/addon-notes';16import { withCsf } from '@storybook/addon-csf';17import { withI18n } from 'storybook-addon-i18n';18import { withHtml } from '@whitespace/storybook-addon-html/react';19import { withPercy } from '@percy-io/percy-storybook';20const stories = storiesOf('Example', module);21stories.addDecorator(withKnobs);22stories.addDecorator(withInfo);23stories.addDecorator(withA11y);24stories.addDecorator(withReadme);25stories.addDecorator(withTests);26stories.addDecorator(withConsole);27stories.addDecorator(withViewport);28stories.addDecorator(withBackgrounds);29stories.addDecorator(withOptions);30stories.addDecorator(withGraphQL);31stories.addDecorator(withPerformance);32stories.addDecorator(withLinks);33stories.addDecorator(withPropsTable);34stories.addDecorator(withNotes);35stories.addDecorator(withCsf);36stories.addDecorator(withI18n);37stories.addDecorator(withHtml);38stories.addDecorator(withPercy);39stories.add('Example', () => (40));41import '@storybook/addon-actions/register';42import '@storybook/addon-knobs/register';43import '@storybook/addon-links/register';44import '@storybook/addon-notes/register';45import '@storybook/addon-a11y/register';46import '@storybook/addon-options/register';47import '@storybook/addon-viewport/register';48import '@storybook/addon-backgrounds/register';49import '@storybook/addon-console/register';50import 'storybook-addon-graphql/register';51import 'storybook-addon-performance/register';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react';2import { withKnobs, text, boolean, number } from '@storybook/addon-knobs/react';3import { withInfo } from '@storybook/addon-info';4import { withReadme } from 'storybook-readme';5import { withDocs } from 'storybook-readme';6import { withDocsCustom } from 'storybook-readme';7import { withDocsOnly } from 'storybook-readme';8import { withDocsOnlyCustom } from 'storybook-readme';9import { withDocsCustomOptions } from 'storybook-readme';10import { withDocsOnlyCustomOptions } from 'storybook-readme';11import { withDocsCustomOptionsAndReadme } from 'storybook-readme';12import { withDocsOnlyCustomOptionsAndReadme } from 'storybook-readme';13import { withDocsCustomOptionsAndReadmeCustom } from 'storybook-readme';14import { withDocsOnlyCustomOptionsAndReadmeCustom } from 'storybook-readme';15import { withDocsCustomOptionsAndReadmeCustomOptions } from 'storybook-readme';16import { withDocsOnlyCustomOptionsAndReadmeCustomOptions } from 'storybook-readme';17import { withReadmeCustom } from 'storybook-readme';18import { withReadmeCustomOptions } from 'storybook-readme';19import { withReadmeCustomOptionsAndReadmeCustom } from 'storybook-readme';20import { withReadmeCustomOptionsAndReadmeCustomOptions } from 'storybook-readme';21import { withReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustom } from 'storybook-readme';22import { withReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptions } from 'storybook-readme';23import { withReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustom } from 'storybook-readme';24import { withReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptions } from 'storybook-readme';25import { withReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustom } from 'storybook-readme';26import { withReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustom } from 'storybook-readme';27import { withReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndReadmeCustomOptionsAndRead

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator } from "@storybook/react";2import { withRootDecorator } from "storybook-root-decorator";3import { ThemeProvider } from "styled-components";4import theme from "./theme";5addDecorator(6 withRootDecorator({7 theme: <ThemeProvider theme={theme} />8 })9);10const theme = {11 colors: {12 }13};14export default theme;15module.exports = {16};17import React from "react";18import { ThemeProvider } from "styled-components";19import theme from "../theme";20 Story => (21 <ThemeProvider theme={theme}>22];23import React from "react";24import { ThemeProvider } from "styled-components";25import theme from "../theme";26 Story => (27 <ThemeProvider theme={theme}>28];29import React from "react";30import { ThemeProvider } from "styled-components";31import theme from "../theme";32 Story => (33 <ThemeProvider theme={theme}>34];35import React from "react";36import { ThemeProvider } from "styled-components";37import theme from "../theme";38 Story => (39 <ThemeProvider theme={theme}>40];41import React from "react";42import { ThemeProvider } from "styled-components";43import theme from "../theme";44 Story => (45 <ThemeProvider theme={theme}>46];47import React from "react";48import { ThemeProvider } from "styled-components";49import theme from "../theme";50 Story => (51 <ThemeProvider theme={theme}>52];53import React from "react";

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react-native';2import { withKnobs } from '@storybook/addon-knobs';3import { withNotes } from '@storybook/addon-notes';4import { withCentered } from 'storybook-addon-centered/react-native';5import { withStoryRoot } from 'storybook-root';6const story = storiesOf('test', module)7 .addDecorator(withCentered)8 .addDecorator(withKnobs)9 .addDecorator(withNotes)10 .addDecorator(withStoryRoot);11story.add('test', () => (12));13import { configure } from '@storybook/react-native';14import './addons';15configure(() => {16 require('../test');17}, module);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withRootDecorator } from 'storybook-root-decorator';2import { addDecorator } from '@storybook/react';3addDecorator(withRootDecorator());4addDecorator(5 withRootDecorator({6 rootProps: {7 style: {8 },9 },10 })11);12import { withRootDecorator } from 'storybook-root-decorator';13import { addDecorator } from '@storybook/react';14addDecorator(withRootDecorator);15addDecorator(16 withRootDecorator({17 rootProps: {18 style: {19 },20 },21 })22);23import { withRootDecorator } from 'storybook-root-decorator';24import { addDecorator } from '@storybook/react';25addDecorator(withRootDecorator());26addDecorator(27 withRootDecorator({28 rootProps: {29 style: {30 },31 },32 })33);34import { withRootDecorator } from 'storybook-root-decorator';35import { addDecorator } from '@storybook/react';36addDecorator(withRootDecorator);37addDecorator(38 withRootDecorator({39 rootProps: {40 style: {41 },42 },43 })44);45import { withRootDecorator } from 'storybook-root-decorator';46import { addDecorator } from '@storybook/react';47addDecorator(withRootDecorator());48addDecorator(49 withRootDecorator({50 rootProps: {51 style: {52 },53 },54 })55);56import { withRootDecorator } from 'storybook-root-decorator';57import { addDecorator } from '@storybook/react';58addDecorator(withRootDecorator);59addDecorator(60 withRootDecorator({61 rootProps: {62 style: {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withKnobs } from '@storybook/addon-knobs';2import { storiesOf } from '@storybook/react';3import React from 'react';4import { Button } from 'antd';5import { Button as Button2 } from 'antd';6export default {7};8export const Default = () => (9 <Button type="primary" onClick={() => alert('clicked')}>10);11export const Default2 = () => (12 <Button2 type="primary" onClick={() => alert('clicked')}>13);14import { configure, addDecorator } from '@storybook/react';15import { withKnobs } from '@storybook/addon-knobs';16import { withInfo } from '@storybook/addon-info';17import { withA11y } from '@storybook/addon-a11y';18import { withPerformance } from 'storybook-addon-performance';19import { withTests } from '@storybook/addon-jest';20import { withConsole } from '@storybook/addon-console';21import { withNotes } from '@storybook/addon-notes';22import { withViewport } from '@storybook/addon-viewport';23import { withPaddings } from 'storybook-addon-paddings';24import { withBackgrounds } from '@storybook/addon-backgrounds';25import { withActions } from '@storybook/addon-actions';26import { withOptions } from '@storybook/addon-options';27import { withLinks } from '@storybook/addon-links';28import { withStorysource } from '@storybook/addon-storysource';29import { withContexts } from '@storybook/addon-contexts/react';30import { withSmartKnobs } from 'storybook-addon-smart-knobs';31import { withCSSResources } from '@storybook/addon-cssresources';32import { withI18n } from 'storybook-addon-i18n';33import { withA11y as withA11y2 } from '@storybook/addon-a11y';34import { withInfo as withInfo2 } from '@storybook/addon-info';35import { withTests as withTests2 } from '@storybook/addon-jest';36import { withConsole as withConsole2 } from '@storybook/addon-console';37import { withNotes as withNotes2 } from '@storybook/addon-notes';38import { withViewport as withViewport2 } from '@storybook/addon-viewport';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withRootDecorator } from 'storybook-root-decorator';2import { addDecorator } from '@storybook/react';3addDecorator(withRootDecorator({4}));5import { decorator } from 'storybook-root-decorator';6export default {7};8export const test = () => <div>test</div>;9import { decorator } from 'storybook-root-decorator';10export const decorators = [decorator];11const { decorator } = require('storybook-root-decorator');12module.exports = {13 stories: ['../src/**/*.stories.(js|jsx|ts|tsx)'],14 core: {15 },16 webpackFinal: async (config) => {17 config.module.rules.push({18 test: /\.(ts|tsx)$/,19 {20 loader: require.resolve('ts-loader'),21 },22 {23 loader: require.resolve('react-docgen-typescript-loader'),24 },25 });26 config.resolve.extensions.push('.ts', '.tsx');27 return config;28 },29};30import { decorator } from 'storybook-root-decorator';31export const decorators = [decorator];32const { decorator } = require('storybook-root-decorator');33module.exports = {34 stories: ['../src/**/*.stories.(js|jsx|ts|tsx)'],

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator } from '@storybook/react';2import { withRoot } from 'storybook-root-decorator';3addDecorator(4 withRoot({5 style: {6 },7 })8);9import '../test.js';10import { addons } from '@storybook/addons';11import { themes } from '@storybook/theming';12addons.setConfig({13});

Full Screen

Using AI Code Generation

copy

Full Screen

1const storybookRoot = require('storybook-root')2storybookRoot()3 .setStorybookPath('storybook')4 .setStorybookConfigPath('storybook/config.js')5 .setStorybookConfigPath('storybook/addons.js')6 .setStorybookConfigPath('storybook/sto

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful