Best Python code snippet using molecule_python
um-members.js
Source:um-members.js
...10 data[ attr[0] ] = attr[1];11 });12 return data;13}14function um_get_data_for_directory( directory, search_key ) {15 var hash = um_members_get_hash( directory );16 var data = {};17 var url_data = um_parse_current_url();18 jQuery.each( url_data, function( key ) {19 if ( key.indexOf( '_' + hash ) !== -1 && url_data[ key ] !== '' ) {20 data[ key.replace( '_' + hash, '' ) ] = url_data[ key ];21 }22 });23 if ( ! search_key ) {24 return data;25 } else {26 if ( typeof data[ search_key ] !== 'undefined' ) {27 try {28 //data[ search_key ] = decodeURI( data[ search_key ] );29 data[ search_key ] = decodeURIComponent( data[ search_key ] );30 } catch(e) { // catches a malformed URI31 console.error(e);32 }33 }34 return data[ search_key ];35 }36}37function um_set_url_from_data( directory, key, value ) {38 var hash = um_members_get_hash( directory );39 var data = um_get_data_for_directory( directory );40 var other_directories = um_member_directories;41 var new_data = {};42 if ( jQuery.isArray( value ) ) {43 jQuery.each( value, function( i ) {44 value[ i ] = encodeURIComponent( value[ i ] );45 });46 value = value.join( '||' );47 } else if ( ! jQuery.isNumeric( value ) ) {48 value = value.split( '||' );49 jQuery.each( value, function( i ) {50 value[ i ] = encodeURIComponent( value[ i ] );51 });52 value = value.join( '||' );53 }54 if ( value !== '' ) {55 new_data[ key + '_' + hash ] = value;56 }57 jQuery.each( data, function( data_key ) {58 if ( key === data_key ) {59 if ( value !== '' ) {60 new_data[ data_key + '_' + hash ] = value;61 }62 } else {63 new_data[ data_key + '_' + hash ] = data[ data_key ];64 }65 });66 // added data of other directories to the url67 jQuery.each( um_member_directories, function( k ) {68 var dir_hash = um_member_directories[ k ];69 if ( dir_hash !== hash ) {70 var other_directory = jQuery( '.um-directory[data-hash="' + dir_hash + '"]' );71 var dir_data = um_get_data_for_directory( other_directory );72 jQuery.each( dir_data, function( data_key ) {73 new_data[ data_key + '_' + dir_hash ] = dir_data[ data_key ];74 });75 }76 });77 var query_strings = [];78 jQuery.each( new_data, function( data_key ) {79 query_strings.push( data_key + '=' + new_data[ data_key ] );80 });81 query_strings = wp.hooks.applyFilters( 'um_member_directory_url_attrs', query_strings );82 var query_string = '?' + query_strings.join( '&' );83 if ( query_string === '?' ) {84 query_string = '';85 }86 window.history.pushState("string", "UM Member Directory", window.location.origin + window.location.pathname + query_string );87}88function um_members_get_hash( directory ) {89 return directory.data( 'hash' );90}91function um_is_directory_busy( directory ) {92 var hash = um_members_get_hash( directory );93 return typeof um_members_directory_busy[ hash ] != 'undefined' && um_members_directory_busy[ hash ];94}95function um_members_show_preloader( directory ) {96 um_members_directory_busy[ um_members_get_hash( directory ) ] = true;97 directory.find('.um-members-overlay').show();98}99function um_members_hide_preloader( directory ) {100 um_members_directory_busy[ um_members_get_hash( directory ) ] = false;101 directory.find('.um-members-overlay').hide();102}103function um_set_range_label( slider, ui ) {104 var placeholder = '';105 var placeholder_s = slider.siblings( '.um-slider-range' ).data( 'placeholder-s' );106 var placeholder_p = slider.siblings( '.um-slider-range' ).data( 'placeholder-p' );107 if ( ui ) {108 if ( ui.values[ 0 ] === ui.values[ 1 ] ) {109 placeholder = placeholder_s.replace( '\{value\}', ui.values[ 0 ] )110 .replace( '\{field_label\}', slider.siblings( '.um-slider-range' )111 .data('label') );112 } else {113 placeholder = placeholder_p.replace( '\{min_range\}', ui.values[ 0 ] )114 .replace( '\{max_range\}', ui.values[ 1 ] )115 .replace( '\{field_label\}', slider.siblings( '.um-slider-range' )116 .data('label') );117 }118 } else {119 if ( slider.slider( "values", 0 ) === slider.slider( "values", 1 ) ) {120 placeholder = placeholder_s.replace( '\{value\}', slider.slider( "values", 0 ) )121 .replace( '\{field_label\}', slider.siblings( '.um-slider-range' )122 .data('label') );123 } else {124 placeholder = placeholder_p.replace( '\{min_range\}', slider.slider( "values", 0 ) )125 .replace( '\{max_range\}', slider.slider( "values", 1 ) )126 .replace( '\{field_label\}', slider.siblings( '.um-slider-range' )127 .data('label') );128 }129 }130 slider.siblings( '.um-slider-range' ).html( placeholder );131 slider.siblings( ".um_range_min" ).val( slider.slider( "values", 0 ) );132 slider.siblings( ".um_range_max" ).val( slider.slider( "values", 1 ) );133}134function um_get_search( directory ) {135 if ( directory.find('.um-search-line').length ) {136 return directory.find( '.um-search-line' ).val();137 } else {138 return '';139 }140}141function um_get_sort( directory ) {142 return directory.data( 'sorting' );143}144function um_get_current_page( directory ) {145 var page = directory.data( 'page' );146 if ( ! page || typeof page == 'undefined' ) {147 page = 1;148 }149 return page;150}151function um_time_convert( time, range ) {152 var hours = Math.floor( time / 60 );153 var minutes = time % 60;154 if ( minutes >= 60 ) {155 minutes = 0;156 hours = hours + 1;157 if ( hours >= 24 ) {158 hours = 0;159 }160 }161 if ( minutes < 10 ) {162 minutes = '0' + minutes;163 }164 return hours + ":" + minutes;165}166function um_ajax_get_members( directory, args ) {167 /**168 * Operates with the next data:169 *170 * 1) Page - getting from directory data 'page'171 * 2) Sort - getting from 'um-member-directory-sorting-options' field value172 * 3) Search - getting from 'um-search-line' field value173 * 4) Filters - getting from URL data by 'um_get_data_for_directory' function174 *175 */176 var hash = um_members_get_hash( directory );177 var page = um_get_current_page( directory );178 var search = um_get_search( directory );179 var sorting = um_get_sort( directory );180 var local_date = new Date();181 var gmt_hours = -local_date.getTimezoneOffset() / 60;182 var request = {183 directory_id: hash,184 page: page,185 search: search,186 sorting: sorting,187 gmt_offset: gmt_hours,188 post_refferer: directory.data('base-post'),189 nonce: um_scripts.nonce190 };191 if ( directory.find('.um-search-filter').length ) {192 directory.find('.um-search-filter').each( function() {193 var filter = jQuery(this);194 if ( filter.find( '.um-slider' ).length ) {195 var filter_name = filter.find( '.um-slider' ).data('field_name');196 var value_from = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );197 var value_to = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );198 if ( typeof value_from != 'undefined' || typeof value_to != 'undefined' ) {199 request[ filter_name ] = [ value_from, value_to ];200 }201 } else if ( filter.find( '.um-datepicker-filter' ).length ) {202 var filter_name = filter.find( '.um-datepicker-filter' ).data('filter_name');203 var value_from = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );204 var value_to = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );205 if ( typeof value_from != 'undefined' || typeof value_to != 'undefined') {206 request[ filter_name ] = [ value_from, value_to ];207 }208 } else if ( filter.find( '.um-timepicker-filter' ).length ) {209 var filter_name = filter.find( '.um-timepicker-filter' ).data('filter_name');210 var value_from = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );211 var value_to = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );212 if ( typeof value_from != 'undefined' ) {213 var value_from = value_from.split(':');214 var hours = value_from[0]*1;215 if ( hours < 10 ) {216 hours = '0' + hours;217 }218 var minutes = value_from[1]*1;219 if ( minutes < 10 ) {220 minutes = '0' + minutes;221 }222 value_from = hours + ':' + minutes + ':00';223 }224 if ( typeof value_to != 'undefined' ) {225 var val_to = value_to.split(':');226 var minutes = val_to[1]*1;227 var hours = val_to[0]*1;228 if ( hours < 10 ) {229 hours = '0' + hours;230 }231 if ( minutes < 10 ) {232 minutes = '0' + minutes;233 }234 value_to = hours + ':' + minutes + ':59';235 }236 if ( typeof value_from != 'undefined' || typeof value_to != 'undefined' ) {237 request[ filter_name ] = [ value_from, value_to ];238 }239 } else if ( filter.find( 'select' ).length ) {240 var filter_name = filter.find('select').attr('name');241 var value = um_get_data_for_directory( directory, 'filter_' + filter_name );242 if ( typeof value != 'undefined' ) {243 request[ filter_name ] = value.split( '||' );244 }245 } else {246 var filter_name = filter.find('input[type="text"]').attr('name');247 var value = um_get_data_for_directory( directory, 'filter_' + filter_name );248 if ( typeof value != 'undefined' ) {249 request[ filter_name ] = value;250 }251 }252 });253 }254 request = wp.hooks.applyFilters( 'um_member_directory_filter_request', request );255 wp.ajax.send( 'um_get_members', {256 data: request,257 success: function( answer ) {258 //set last data hard for using on layouts reloading259 um_member_directory_last_data[ hash ] = answer;260 um_build_template( directory, answer );261 var pagination_template = wp.template( 'um-members-pagination' );262 directory.find('.um-members-pagination-box').html( pagination_template( answer ) );263 directory.data( 'total_pages', answer.pagination.total_pages );264 if ( answer.pagination.total_pages ) {265 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );266 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );267 } else {268 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', true );269 directory.find( '.um-member-directory-view-type' ).addClass( 'um-disabled' );270 }271 //args.directory = directory;272 jQuery( document ).trigger('um_members_rendered', [ directory, answer ] );273 um_init_new_dropdown();274 um_members_hide_preloader( directory );275 },276 error: function( data ) {277 console.log( data );278 um_members_hide_preloader( directory );279 }280 });281}282function um_build_template( directory, data ) {283 var layout = directory.data('view_type');284 var template = wp.template( 'um-member-' + layout + '-' + um_members_get_hash( directory ) );285 directory.find('.um-members-grid, .um-members-list').remove();286 directory.find('.um-members-wrapper').prepend( template( data.users ) );287 var header_template = wp.template( 'um-members-header' );288 directory.find('.um-members-intro').remove();289 if ( typeof data.is_search != 'undefined' && data.is_search ) {290 directory.find('.um-members-wrapper').prepend( header_template( data ) );291 }292 directory.addClass('um-loaded');293 if ( directory.find('.um-members.um-members-grid').length ) {294 UM_Member_Grid( directory.find('.um-members.um-members-grid') );295 }296 jQuery( document ).trigger( 'um_build_template', [ directory, data ] );297 jQuery( window ).trigger( 'resize' );298 init_tipsy();299}300function UM_Member_Grid( container ) {301 if ( container.find( '.um-member' ).length ) {302 container.imagesLoaded( function() {303 var $grid = container.masonry({304 itemSelector: '.um-member',305 columnWidth: '.um-member',306 gutter: '.um-gutter-sizer'307 });308 $grid.on( 'layoutComplete', function( event, laidOutItems ) {309 jQuery( document ).trigger( "um_grid_initialized", [ event, laidOutItems ] );310 });311 });312 }313}314function um_get_filters_data( directory ) {315 var filters_data = [];316 directory.find('.um-search-filter').each( function() {317 var filter = jQuery(this);318 var filter_name,319 filter_title;320 var filter_type;321 if ( filter.find('input.um-datepicker-filter').length ) {322 filter_type = 'datepicker';323 filter.find('input.um-datepicker-filter').each( function() {324 var range = jQuery(this).data('range');325 if ( range === 'to' ) {326 return;327 }328 var filter_name = jQuery(this).data('filter_name');329 var filter_value_from = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );330 var filter_value_to = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );331 if ( typeof filter_value_from === 'undefined' && typeof filter_value_to === 'undefined' ) {332 return;333 }334 var from_val = jQuery(this).val();335 var to_val = directory.find('input.um-datepicker-filter[data-range="to"][data-filter_name="' + filter_name + '"]').val();336 var value;337 if ( from_val === to_val ) {338 value = to_val;339 } else if ( from_val !== '' && to_val !== '' ) {340 value = from_val + ' - ' + to_val;341 } else if ( from_val === '' ) {342 value = 'before ' + to_val;343 } else if ( to_val === '' ) {344 value = 'since ' + from_val;345 }346 filters_data.push( {'name':filter_name, 'label':jQuery(this).data('filter-label'), 'value_label': value, 'value':[filter_value_from, filter_value_to], 'type':filter_type} );347 });348 } else if( filter.find('input.um-timepicker-filter').length ) {349 filter_type = 'timepicker';350 filter.find('input.um-timepicker-filter').each( function() {351 var range = jQuery(this).data('range');352 if ( range === 'to' ) {353 return;354 }355 var filter_name = jQuery(this).data('filter_name');356 var filter_value_from = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );357 var filter_value_to = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );358 if ( typeof filter_value_from === 'undefined' && typeof filter_value_to === 'undefined' ) {359 return;360 }361 var from_val = jQuery(this).val();362 var to_val = directory.find('input.um-timepicker-filter[data-range="to"][data-filter_name="' + filter_name + '"]').val();363 var value;364 if ( from_val === to_val ) {365 value = to_val;366 } else if ( from_val !== '' && to_val !== '' ) {367 value = from_val + ' - ' + to_val;368 } else if ( from_val === '' ) {369 value = 'before ' + to_val;370 } else if ( to_val === '' ) {371 value = 'since ' + from_val;372 }373 filters_data.push( {'name':filter_name, 'label':jQuery(this).data('filter-label'), 'value_label': value, 'value':[filter_value_from, filter_value_to], 'type':filter_type} );374 });375 } else if( filter.find('select').length ) {376 filter_type = 'select';377 filter_name = filter.find('select').attr('name');378 filter_title = filter.find('select').data('placeholder');379 var filter_value = um_get_data_for_directory( directory, 'filter_' + filter_name );380 if ( typeof filter_value == 'undefined' ) {381 filter_value = [];382 } else {383 filter_value = filter_value.split( '||' );384 }385 jQuery.each( filter_value, function(i) {386 var filter_value_title = filter.find('select option[value="' + filter_value[ i ] + '"]').data('value_label');387 filters_data.push( {'name':filter_name, 'label':filter_title, 'value_label':filter_value_title, 'value':filter_value[ i ], 'type':filter_type} );388 });389 } else if( filter.find('input[type="text"]').length ) {390 filter_type = 'text';391 filter_name = filter.find('input[type="text"]').attr('name');392 filter_title = filter.find('input[type="text"]').attr('placeholder');393 var filter_value = um_get_data_for_directory( directory, 'filter_' + filter_name );394 if ( typeof filter_value == 'undefined' ) {395 filter_value = '';396 }397 if ( filter_value != '' ) {398 filters_data.push( {'name':filter_name, 'label':filter_title, 'value_label':filter_value, 'value':filter_value, 'type':filter_type} );399 }400 } else if( filter.find('div.ui-slider').length ) {401 filter_type = 'slider';402 filter_name = filter.find('div.ui-slider').data( 'field_name' );403 var filter_value_from = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );404 var filter_value_to = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );405 if ( typeof filter_value_from === 'undefined' && typeof filter_value_to === 'undefined' ) {406 return;407 }408 var filter_value_title;409 if ( filter_value_from === filter_value_to ) {410 filter_value_title = filter.find('div.um-slider-range').data( 'placeholder-s' ).replace( '\{value\}', filter_value_from )411 .replace( '\{field_label\}', filter.find('div.um-slider-range').data('label') );412 } else {413 filter_value_title = filter.find('div.um-slider-range').data( 'placeholder-p' ).replace( '\{min_range\}', filter_value_from )414 .replace( '\{max_range\}', filter_value_to )415 .replace( '\{field_label\}', filter.find('div.um-slider-range').data('label') );416 }417 filter_title = filter.find('div.um-slider-range').data('label');418 filters_data.push( {'name':filter_name, 'label':filter_title, 'value_label':filter_value_title, 'value':[filter_value_from, filter_value_to], 'type':filter_type} );419 }420 });421 return filters_data;422}423function um_change_tag( directory ) {424 var filters_data = um_get_filters_data( directory );425 directory.find('.um-members-filter-tag').remove();426 var filtered_line = directory.find('.um-filtered-line');427 if ( filtered_line.length ) {428 var filters_template = wp.template( 'um-members-filtered-line' );429 filtered_line.prepend( filters_template( {'filters': filters_data} ) );430 if ( directory.find( '.um-members-filter-remove' ).length === 0 ) {431 directory.find('.um-clear-filters').hide();432 directory.find('.um-clear-filters').parents('.um-member-directory-header-row').addClass( 'um-header-row-invisible' );433 } else {434 directory.find('.um-clear-filters').show();435 directory.find('.um-clear-filters').parents('.um-member-directory-header-row').removeClass( 'um-header-row-invisible' );436 }437 }438}439function um_run_search( directory ) {440 if ( um_is_directory_busy( directory ) ) {441 return;442 }443 um_members_show_preloader( directory );444 var pre_search = um_get_data_for_directory( directory, 'search' );445 var search = directory.find('.um-search-line').val();446 if ( search === pre_search || ( search === '' && typeof pre_search == 'undefined' ) ) {447 um_members_hide_preloader( directory );448 return;449 }450 directory.data( 'general_search', search );451 um_set_url_from_data( directory, 'search', search );452 //set 1st page after search453 directory.data( 'page', 1 );454 um_set_url_from_data( directory, 'page', '' );455 var ignore_after_search = false;456 ignore_after_search = wp.hooks.applyFilters( 'um_member_directory_ignore_after_search', ignore_after_search );457 if ( ! ignore_after_search ) {458 var show_after_search = directory.data('must-search');459 if ( show_after_search === 1 ) {460 var search = um_get_search( directory );461 if ( directory.find( '.um-members-filter-remove' ).length === 0 && ! search ) {462 directory.data( 'searched', 0 );463 directory.find('.um-members-grid, .um-members-list').remove();464 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', true );465 directory.find( '.um-member-directory-view-type' ).addClass( 'um-disabled' );466 um_members_hide_preloader( directory );467 return;468 }469 }470 }471 directory.data( 'searched', 1 );472 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );473 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );474 um_ajax_get_members( directory );475}476jQuery(document.body).ready( function() {477 jQuery( '.um-directory .um-search-filter select' ).each( function() {478 if ( jQuery(this).find('option:not(:disabled)').length === 1 ) {479 jQuery(this).prop('disabled', true);480 }481 jQuery(this).select2('destroy').select2();482 });483 /**484 * Change View Type Handlers485 */486 //UI for change view type button487 jQuery( document.body ).on( 'mouseover', '.um-directory .um-member-directory-view-type', function() {488 if ( jQuery(this).hasClass('um-disabled') ) {489 return;490 }491 var $obj = jQuery(this).find('.um-member-directory-view-type-a:visible');492 $obj.hide();493 if ( $obj.next().length ) {494 $obj.next().show().tipsy('show');495 } else {496 jQuery(this).find( '.um-member-directory-view-type-a:first' ).show().tipsy('show');497 }498 }).on( 'mouseout', '.um-directory .um-member-directory-view-type', function() {499 if ( jQuery(this).hasClass('um-disabled') ) {500 return;501 }502 jQuery(this).find('.um-member-directory-view-type-a').hide().tipsy('hide');503 jQuery(this).find('.um-member-directory-view-type-a[data-type="' + jQuery(this).parents( '.um-directory' ).data('view_type') + '"]').show();504 });505 //change layout handler506 jQuery( document.body ).on( 'click', '.um-directory .um-member-directory-view-type-a', function() {507 var directory = jQuery(this).parents('.um-directory');508 if ( um_is_directory_busy( directory ) ) {509 return false;510 }511 var $this = jQuery(this);512 var views = $this.parents('.um-member-directory-view-type');513 if ( views.hasClass('um-disabled') ) {514 return;515 }516 um_members_show_preloader( directory );517 var $obj = views.find('.um-member-directory-view-type-a:visible');518 $obj.hide();519 if ( $obj.next().length ) {520 $obj.next().show().tipsy('show');521 } else {522 views.find( '.um-member-directory-view-type-a:first' ).show().tipsy('show');523 }524 var data = um_member_directory_last_data[ um_members_get_hash( directory ) ];525 if ( data !== null ) {526 var layout = $this.data('type');527 um_set_url_from_data( directory, 'view_type', layout );528 directory.data( 'view_type', layout );529 um_build_template( directory, data );530 }531 um_members_hide_preloader( directory );532 });533 /**534 * END: Change View Type Handlers535 */536 /**537 * General Search538 */539 //searching540 jQuery( document.body ).on( 'click', '.um-directory .um-do-search', function() {541 var directory = jQuery(this).parents('.um-directory');542 um_run_search( directory );543 });544 //make search on Enter click545 jQuery( document.body ).on( 'keypress', '.um-directory .um-search-line', function(e) {546 if ( e.which === 13 ) {547 var directory = jQuery(this).parents('.um-directory');548 um_run_search( directory );549 }550 });551 /**552 * END: General Search553 */554 /**555 * Sorting556 */557 jQuery( document.body ).on( 'click', '.um-directory .um-member-directory-sorting-a .um-new-dropdown li a', function() {558 var directory = jQuery(this).parents('.um-directory');559 if ( um_is_directory_busy( directory ) ) {560 return;561 }562 if ( jQuery( this ).data('selected') === 1 ) {563 return;564 }565 um_members_show_preloader( directory );566 var sort = jQuery(this).data('value');567 directory.data( 'sorting', sort );568 um_set_url_from_data( directory, 'sort', sort );569 um_ajax_get_members( directory );570 jQuery( this ).parents('.um-new-dropdown').find('a').data('selected', 0).prop('data-selected', 0).attr('data-selected', 0);571 jQuery( this ).data('selected', 1).prop('data-selected', 1).attr('data-selected', 1);572 jQuery( this ).parents('.um-member-directory-sorting-a').find('> a').html( jQuery( this ).html() );573 });574 /**575 * END: Sorting576 */577 /**578 * Pagination579 */580 jQuery( document.body ).on( 'click', '.um-directory .pagi:not(.current)', function() {581 if ( jQuery(this).hasClass('disabled') ) {582 return;583 }584 var directory = jQuery(this).parents('.um-directory');585 if ( um_is_directory_busy( directory ) ) {586 return;587 }588 um_members_show_preloader( directory );589 var page;590 if ( 'first' === jQuery(this).data('page') ) {591 page = 1;592 } else if ( 'prev' === jQuery(this).data('page') ) {593 page = directory.data( 'page' )*1 - 1;594 } else if ( 'next' === jQuery(this).data('page') ) {595 page = directory.data( 'page' )*1 + 1;596 } else if ( 'last' === jQuery(this).data('page') ) {597 page = parseInt( directory.data( 'total_pages' ) );598 } else {599 page = parseInt( jQuery(this).data('page') );600 }601 if ( page === 1 ) {602 directory.find('.pagi[data-page="first"], .pagi[data-page="prev"]').addClass('disabled');603 directory.find('.pagi[data-page="prev"], .pagi[data-page="last"]').removeClass('disabled');604 } else if ( page === parseInt( directory.data( 'total_pages' ) ) ) {605 directory.find('.pagi[data-page="prev"], .pagi[data-page="last"]').addClass('disabled');606 directory.find('.pagi[data-page="first"], .pagi[data-page="prev"]').removeClass('disabled');607 } else {608 directory.find('.pagi[data-page="prev"], .pagi[data-page="last"]').removeClass('disabled');609 directory.find('.pagi[data-page="first"], .pagi[data-page="prev"]').removeClass('disabled');610 }611 directory.find('.pagi').removeClass('current');612 directory.find('.pagi[data-page="' + page + '"]').addClass('current');613 directory.data( 'page', page );614 if ( page === 1 ) {615 um_set_url_from_data( directory, 'page', '' );616 } else {617 um_set_url_from_data( directory, 'page', page );618 }619 um_ajax_get_members( directory );620 });621 //mobile pagination622 jQuery( document.body ).on( 'change', '.um-directory .um-members-pagi-dropdown', function() {623 var directory = jQuery(this).parents('.um-directory');624 if ( um_is_directory_busy( directory ) ) {625 return;626 }627 um_members_show_preloader( directory );628 var page = jQuery(this).val();629 directory.find('.pagi').removeClass('current');630 directory.find('.pagi[data-page="' + page + '"]').addClass('current');631 directory.data( 'page', page );632 if ( page === 1 ) {633 um_set_url_from_data( directory, 'page', '' );634 } else {635 um_set_url_from_data( directory, 'page', page );636 }637 um_ajax_get_members( directory );638 });639 /**640 * END: Pagination641 */642 /**643 * Profile Cards actions644 */645 jQuery( document.body ).on('click', '.um-directory .um-members.um-members-list .um-member-more a', function(e){646 e.preventDefault();647 var block = jQuery(this).parents('.um-member');648 block.find('.um-member-more').hide();649 block.find('.um-member-meta-main').slideDown();650 block.find('.um-member-less').fadeIn();651 return false;652 });653 jQuery( document.body ).on('click', '.um-directory .um-members.um-members-list .um-member-less a', function(e){654 e.preventDefault();655 var block = jQuery(this).parents('.um-member');656 block.find('.um-member-less').hide();657 block.find('.um-member-meta-main').slideUp();658 block.find('.um-member-more').fadeIn();659 return false;660 });661 jQuery( document.body ).on('click', '.um-directory .um-members.um-members-grid .um-member-more a', function(e){662 e.preventDefault();663 var block = jQuery(this).parents('.um-member');664 var container = jQuery(this).parents('.um-members');665 block.find('.um-member-more').hide();666 block.find('.um-member-meta').slideDown( function(){ UM_Member_Grid( container ) } );667 block.find('.um-member-less').fadeIn( );668 setTimeout(function(){ UM_Member_Grid( container ) }, 100);669 return false;670 });671 jQuery( document.body ).on('click', '.um-directory .um-members.um-members-grid .um-member-less a', function(e){672 e.preventDefault();673 var block = jQuery(this).parents('.um-member');674 var container = jQuery(this).parents('.um-members');675 block.find('.um-member-less').hide();676 block.find('.um-member-meta').slideUp( function() {677 block.find('.um-member-more').fadeIn();678 UM_Member_Grid( container );679 });680 return false;681 });682 /**683 * END: Profile Cards actions684 */685 //filters controls686 jQuery('.um-member-directory-filters-a').click( function() {687 var obj = jQuery(this);688 var search_bar = obj.parents('.um-directory').find('.um-search');689 if ( search_bar.is( ':visible' ) ) {690 search_bar.slideUp( 250, function(){691 obj.toggleClass('um-member-directory-filters-visible');692 search_bar.parents('.um-member-directory-header-row').toggleClass('um-header-row-invisible');693 });694 } else {695 search_bar.slideDown({696 duration: 250,697 start: function() {698 jQuery(this).css({699 display: "grid"700 });701 obj.toggleClass('um-member-directory-filters-visible');702 search_bar.parents('.um-member-directory-header-row').toggleClass('um-header-row-invisible');703 }704 } );705 }706 });707 //filtration process708 jQuery( document.body ).on( 'change', '.um-directory .um-search-filter select', function() {709 if ( jQuery(this).val() === '' ) {710 return;711 }712 var directory = jQuery(this).parents('.um-directory');713 if ( um_is_directory_busy( directory ) ) {714 return;715 }716 um_members_show_preloader( directory );717 var filter_name = jQuery(this).prop('name');718 var current_value = um_get_data_for_directory( directory, 'filter_' + filter_name );719 if ( typeof current_value == 'undefined' ) {720 current_value = [];721 } else {722 current_value = current_value.split( '||' );723 }724 if ( -1 === jQuery.inArray( jQuery(this).val(), current_value ) ) {725 current_value.push( jQuery(this).val() );726 current_value = current_value.join( '||' );727 um_set_url_from_data( directory, 'filter_' + filter_name, current_value );728 //set 1st page after filtration729 directory.data( 'page', 1 );730 um_set_url_from_data( directory, 'page', '' );731 }732 //disable options and disable select if all options are disabled733 jQuery(this).find('option[value="' + jQuery(this).val() + '"]').prop('disabled', true).hide();734 if ( jQuery(this).find('option:not(:disabled)').length === 1 ) {735 jQuery(this).prop('disabled', true);736 }737 jQuery(this).select2('destroy').select2();738 jQuery(this).val('').trigger( 'change' );739 um_ajax_get_members( directory );740 um_change_tag( directory );741 directory.data( 'searched', 1 );742 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );743 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );744 // if ( directory.find( '.um-search-filter select[data-um-parent="' + filter_name + '"]' ).length > 0 ) {745 // jQuery(this).trigger('change');746 // }747 });748 jQuery( document.body ).on( 'blur', '.um-directory .um-search-filter.um-text-filter-type input[type="text"]', function() {749 var directory = jQuery(this).parents('.um-directory');750 if ( um_is_directory_busy( directory ) ) {751 return;752 }753 var current_value = jQuery(this).val();754 var filter_name = jQuery(this).prop('name');755 var url_value = um_get_data_for_directory( directory, 'filter_' + filter_name );756 if ( typeof url_value == 'undefined' ) {757 url_value = '';758 }759 if ( current_value === url_value ) {760 return;761 }762 um_members_show_preloader( directory );763 um_set_url_from_data( directory, 'filter_' + filter_name, current_value );764 //set 1st page after filtration765 directory.data( 'page', 1 );766 um_set_url_from_data( directory, 'page', '' );767 um_ajax_get_members( directory );768 um_change_tag( directory );769 directory.data( 'searched', 1 );770 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );771 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );772 });773 //make search on Enter click774 jQuery( document.body ).on( 'keypress', '.um-directory .um-search-filter.um-text-filter-type input[type="text"]', function(e) {775 if ( e.which === 13 ) {776 var directory = jQuery(this).parents('.um-directory');777 if ( um_is_directory_busy( directory ) ) {778 return;779 }780 var current_value = jQuery(this).val();781 var filter_name = jQuery(this).prop('name');782 var url_value = um_get_data_for_directory( directory, 'filter_' + filter_name );783 if ( typeof url_value == 'undefined' ) {784 url_value = '';785 }786 if ( current_value === url_value ) {787 return;788 }789 um_members_show_preloader( directory );790 um_set_url_from_data( directory, 'filter_' + filter_name, current_value );791 //set 1st page after filtration792 directory.data( 'page', 1 );793 um_set_url_from_data( directory, 'page', '' );794 um_ajax_get_members( directory );795 um_change_tag( directory );796 directory.data( 'searched', 1 );797 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );798 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );799 }800 });801 jQuery( document.body ).on( 'click', '.um-directory .um-members-filter-remove', function() {802 var directory = jQuery(this).parents('.um-directory');803 if ( um_is_directory_busy(directory) || ! directory ) {804 return;805 }806 um_members_show_preloader(directory);807 var removeItem = jQuery(this).data('value');808 var filter_name = jQuery(this).data('name');809 var type = jQuery(this).data('type');810 if ( type === 'text' ) {811 um_set_url_from_data( directory, 'filter_' + filter_name,'' );812 jQuery( '.um-search-filter input[name="' + filter_name + '"]' ).val('');813 } else if ( type === 'select' ) {814 var current_value = um_get_data_for_directory( directory, 'filter_' + filter_name );815 if ( typeof current_value == 'undefined' ) {816 current_value = [];817 } else {818 current_value = current_value.split( '||' );819 }820 if ( -1 !== jQuery.inArray( removeItem.toString(), current_value ) ) {821 current_value = jQuery.grep( current_value, function( value ) {822 return value !== removeItem.toString();823 });824 }825 if ( ! current_value.length ) {826 current_value = '';827 }828 um_set_url_from_data( directory, 'filter_' + filter_name, current_value );829 var select = jQuery( '.um-search-filter select[name="' + filter_name + '"]' );830 select.find('option[value="' + removeItem + '"]').prop('disabled', false).show();831 //disable options and disable select if all options are disabled832 if ( select.find('option:not(:disabled)').length > 1 ) {833 select.prop('disabled', false);834 }835 select.select2('destroy').select2();836 if ( directory.find( '.um-search-filter select[data-um-parent="' + filter_name + '"]' ).length > 0 ) {837 select.trigger('change');838 }839 } else if ( type === 'slider' ) {840 um_set_url_from_data( directory, 'filter_' + filter_name + '_from','' );841 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', '' );842 var $slider = jQuery( '.um-search-filter #' + filter_name + '_min' ).siblings('.um-slider');843 var options = $slider.slider( 'option' );844 $slider.slider( 'values', [ options.min, options.max ] );845 jQuery( '.um-search-filter #' + filter_name + '_min' ).val('');846 jQuery( '.um-search-filter #' + filter_name + '_max' ).val('');847 um_set_range_label( $slider );848 } else if ( type === 'datepicker' ) {849 um_set_url_from_data( directory, 'filter_' + filter_name + '_from','' );850 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', '' );851 jQuery( '.um-search-filter #' + filter_name + '_from' ).val('');852 jQuery( '.um-search-filter #' + filter_name + '_to' ).val('');853 } else if ( type === 'timepicker' ) {854 um_set_url_from_data( directory, 'filter_' + filter_name + '_from','' );855 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', '' );856 jQuery( '.um-search-filter #' + filter_name + '_from' ).val('');857 jQuery( '.um-search-filter #' + filter_name + '_to' ).val('');858 }859 //set 1st page after filtration860 directory.data( 'page', 1 );861 um_set_url_from_data( directory, 'page', '' );862 jQuery(this).tipsy('hide');863 jQuery(this).parents('.um-members-filter-tag').remove();864 if ( directory.find( '.um-members-filter-remove' ).length === 0 ) {865 directory.find('.um-clear-filters').hide();866 } else {867 directory.find('.um-clear-filters').show();868 }869 var ignore_after_search = false;870 ignore_after_search = wp.hooks.applyFilters( 'um_member_directory_ignore_after_search', ignore_after_search );871 if ( ! ignore_after_search ) {872 var show_after_search = directory.data('must-search');873 if ( show_after_search === 1 ) {874 var search = um_get_search( directory );875 if ( directory.find( '.um-members-filter-remove' ).length === 0 && ! search ) {876 directory.data( 'searched', 0 );877 directory.find('.um-members-grid, .um-members-list').remove();878 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', true );879 directory.find( '.um-member-directory-view-type' ).addClass( 'um-disabled' );880 um_members_hide_preloader( directory );881 return;882 }883 }884 }885 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );886 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );887 um_ajax_get_members( directory );888 });889 jQuery( document.body ).on( 'click', '.um-directory .um-clear-filters-a', function() {890 var directory = jQuery(this).parents('.um-directory');891 if ( um_is_directory_busy( directory ) ) {892 return;893 }894 um_members_show_preloader( directory );895 directory.find( '.um-members-filter-remove' ).each( function() {896 var removeItem = jQuery(this).data('value');897 var filter_name = jQuery(this).data('name');898 var type = jQuery(this).data('type');899 if ( type === 'text' ) {900 um_set_url_from_data( directory, 'filter_' + filter_name,'' );901 jQuery( '.um-search-filter input[name="' + filter_name + '"]' ).val('');902 } else if ( type === 'select' ) {903 var current_value = um_get_data_for_directory( directory, 'filter_' + filter_name );904 if ( typeof current_value == 'undefined' ) {905 current_value = [];906 } else {907 current_value = current_value.split( '||' );908 }909 if ( -1 !== jQuery.inArray( removeItem.toString(), current_value ) ) {910 current_value = jQuery.grep( current_value, function( value ) {911 return value !== removeItem.toString();912 });913 }914 if ( ! current_value.length ) {915 current_value = '';916 }917 um_set_url_from_data( directory, 'filter_' + filter_name, current_value );918 var select = jQuery( '.um-search-filter select[name="' + filter_name + '"]' );919 select.find('option[value="' + removeItem + '"]').prop('disabled', false).show();920 //disable options and disable select if all options are disabled921 if ( select.find('option:not(:disabled)').length > 1 ) {922 select.prop('disabled', false);923 }924 select.select2('destroy').select2();925 if ( directory.find( '.um-search-filter select[data-um-parent="' + filter_name + '"]' ).length > 0 ) {926 select.trigger('change');927 }928 } else if ( type === 'slider' ) {929 um_set_url_from_data( directory, 'filter_' + filter_name + '_from','' );930 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', '' );931 var $slider = jQuery( '.um-search-filter #' + filter_name + '_min' ).siblings('.um-slider');932 var options = $slider.slider( 'option' );933 $slider.slider( 'values', [ options.min, options.max ] );934 jQuery( '.um-search-filter #' + filter_name + '_min' ).val('');935 jQuery( '.um-search-filter #' + filter_name + '_max' ).val('');936 um_set_range_label( $slider );937 } else if ( type === 'datepicker' ) {938 um_set_url_from_data( directory, 'filter_' + filter_name + '_from','' );939 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', '' );940 jQuery( '.um-search-filter #' + filter_name + '_from' ).val('');941 jQuery( '.um-search-filter #' + filter_name + '_to' ).val('');942 } else if ( type === 'timepicker' ) {943 um_set_url_from_data( directory, 'filter_' + filter_name + '_from','' );944 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', '' );945 jQuery( '.um-search-filter #' + filter_name + '_from' ).val('');946 jQuery( '.um-search-filter #' + filter_name + '_to' ).val('');947 }948 });949 //set 1st page after filtration950 directory.data( 'page', 1 );951 um_set_url_from_data( directory, 'page', '' );952 directory.find('.um-members-filter-tag').remove();953 //jQuery(this).hide();954 if ( directory.find( '.um-members-filter-remove' ).length === 0 ) {955 directory.find('.um-clear-filters').hide();956 directory.find('.um-clear-filters').parents('.um-member-directory-header-row').addClass( 'um-header-row-invisible' );957 } else {958 directory.find('.um-clear-filters').show();959 directory.find('.um-clear-filters').parents('.um-member-directory-header-row').removeClass( 'um-header-row-invisible' );960 }961 var ignore_after_search = false;962 ignore_after_search = wp.hooks.applyFilters( 'um_member_directory_ignore_after_search', ignore_after_search );963 if ( ! ignore_after_search ) {964 var show_after_search = directory.data('must-search');965 if ( show_after_search === 1 ) {966 var search = um_get_search( directory );967 if ( ! search ) {968 directory.data( 'searched', 0 );969 directory.find('.um-members-grid, .um-members-list').remove();970 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', true );971 directory.find( '.um-member-directory-view-type' ).addClass( 'um-disabled' );972 um_members_hide_preloader( directory );973 return;974 }975 }976 }977 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );978 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );979 um_ajax_get_members( directory );980 });981 /**982 * First Page Loading983 */984 //Init Directories985 jQuery( '.um-directory' ).each( function() {986 var directory = jQuery(this);987 var hash = um_members_get_hash( directory );988 um_member_directories.push( hash );989 // slideup/slidedown animation fix for grid filters bar990 if ( directory.find('.um-search').length ) {991 if ( ! directory.find('.um-search').is(':visible') ) {992 directory.find('.um-search').css({993 display: "grid"994 }).slideUp( 1 );995 }996 }997 //slider filter998 directory.find('.um-slider').each( function() {999 var slider = jQuery( this );1000 var directory = slider.parents('.um-directory');1001 var filter_name = slider.data('field_name');1002 var min_default_value = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );1003 var max_default_value = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );1004 if ( typeof min_default_value == 'undefined' ) {1005 min_default_value = parseInt( slider.data('min') );1006 }1007 if ( typeof max_default_value == 'undefined' ) {1008 max_default_value = parseInt( slider.data('max') );1009 }1010 var default_value = [ min_default_value, max_default_value ];1011 slider.slider({1012 range: true,1013 min: parseInt( slider.data('min') ),1014 max: parseInt( slider.data('max') ),1015 values: default_value,1016 create: function( event, ui ) {1017 //console.log( ui );1018 },1019 step: 1,1020 slide: function( event, ui ) {1021 um_set_range_label( jQuery( this ), ui );1022 },1023 stop: function( event, ui ) {1024 if ( ! um_is_directory_busy( directory ) ) {1025 um_set_url_from_data( directory, 'filter_' + filter_name + '_from', ui.values[0] );1026 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', ui.values[1] );1027 //set 1st page after filtration1028 directory.data( 'page', 1 );1029 um_set_url_from_data( directory, 'page', '' );1030 um_ajax_get_members( directory );1031 um_change_tag( directory );1032 directory.data( 'searched', 1 );1033 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );1034 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );1035 }1036 }1037 });1038 um_set_range_label( slider );1039 });1040 //datepicker filter1041 directory.find('.um-datepicker-filter').each( function() {1042 var elem = jQuery(this);1043 var min = new Date( elem.data('date_min')*1000 );1044 var max = new Date( elem.data('date_max')*1000 );1045 var $input = elem.pickadate({1046 selectYears: true,1047 min: min,1048 max: max,1049 formatSubmit: 'yyyy/mm/dd',1050 hiddenName: true,1051 onOpen: function() {1052 elem.blur();1053 },1054 onClose: function() {1055 elem.blur();1056 },1057 onSet: function( context ) {1058 if ( ! context.select ) {1059 return;1060 }1061 var directory = elem.parents('.um-directory');1062 if ( um_is_directory_busy( directory ) ) {1063 return;1064 }1065 um_members_show_preloader( directory );1066 var filter_name = elem.data( 'filter_name' );1067 var range = elem.data( 'range' );1068 var current_value_from = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );1069 var current_value_to = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );1070 if ( typeof current_value_from === "undefined" ) {1071 current_value_from = min / 1000;1072 }1073 if ( typeof current_value_to === "undefined" ) {1074 current_value_to = max / 1000;1075 }1076 var select_val = context.select / 1000;1077 var change_val = elem.val();1078 if ( range === 'from' ) {1079 current_value_from = select_val;1080 } else if ( range === 'to' ) {1081 current_value_to = select_val;1082 }1083 um_set_url_from_data( directory, 'filter_' + filter_name + '_from', current_value_from );1084 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', current_value_to );1085 //set 1st page after filtration1086 directory.data( 'page', 1 );1087 um_set_url_from_data( directory, 'page', '' );1088 um_ajax_get_members( directory );1089 um_change_tag( directory );1090 directory.data( 'searched', 1 );1091 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );1092 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );1093 }1094 });1095 var $picker = $input.pickadate('picker');1096 var $fname = elem.data('filter_name');1097 var $frange = elem.data('range');1098 var $directory = elem.parents('.um-directory');1099 var query_value = um_get_data_for_directory( $directory, 'filter_' + $fname + '_' + $frange );1100 if ( typeof query_value !== 'undefined' ) {1101 $picker.set( 'select', query_value*1000 );1102 }1103 });1104 //timepicker filter1105 directory.find('.um-timepicker-filter').each( function() {1106 var elem = jQuery(this);1107 var elemID = elem.attr('id');1108 var elem_filter_name = elem.data('filter_name');1109 //using arrays formatted as [HOUR,MINUTE]1110 var min = elem.attr('data-min');1111 var max = elem.attr('data-max');1112 var picker_min = min.split(':');1113 var picker_max = max.split(':');1114 var $input = elem.pickatime({1115 format: elem.data('format'),1116 interval: parseInt( elem.data('intervals') ),1117 min: [picker_min[0],picker_min[1]],1118 max: [picker_max[0],picker_max[1]],1119 formatSubmit: 'HH:i',1120 hiddenName: true,1121 onOpen: function() { elem.blur(); },1122 onClose: function() { elem.blur(); },1123 onSet: function( context ) {1124 if ( ! context.select ) {1125 return;1126 }1127 var directory = elem.parents('.um-directory');1128 if ( um_is_directory_busy( directory ) ) {1129 return;1130 }1131 um_members_show_preloader( directory );1132 var filter_name = elem.data( 'filter_name' );1133 var range = elem.data( 'range' );1134 var current_value_from = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );1135 var current_value_to = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );1136 if ( typeof current_value_from === "undefined" ) {1137 current_value_from = min;1138 }1139 if ( typeof current_value_to === "undefined" ) {1140 current_value_to = max;1141 }1142 if ( typeof context.select !== 'undefined' ) {1143 var select_val = um_time_convert( context.select, range );1144 //var select_val = context.select / 60;1145 if ( range === 'from' ) {1146 current_value_from = select_val;1147 } else if ( range === 'to' ) {1148 current_value_to = select_val;1149 }1150 } else {1151 if ( range === 'from' ) {1152 current_value_from = min;1153 } else if ( range === 'to' ) {1154 current_value_to = max;1155 }1156 }1157 var time = jQuery( '#' + elemID ).val();1158 if ( elem.data('range') === 'from' ) {1159 jQuery( '#' + elem_filter_name + '_to' ).pickatime('picker').set('min', time);1160 } else {1161 jQuery( '#' + elem_filter_name + '_from').pickatime('picker').set('max', time);1162 }1163 um_set_url_from_data( directory, 'filter_' + filter_name + '_from', current_value_from );1164 um_set_url_from_data( directory, 'filter_' + filter_name + '_to', current_value_to );1165 //set 1st page after filtration1166 directory.data( 'page', 1 );1167 um_set_url_from_data( directory, 'page', '' );1168 um_ajax_get_members( directory );1169 um_change_tag( directory );1170 directory.data( 'searched', 1 );1171 directory.find( '.um-member-directory-sorting-options' ).prop( 'disabled', false );1172 directory.find( '.um-member-directory-view-type' ).removeClass( 'um-disabled' );1173 }1174 });1175 // first loading timepicker select1176 var $picker = $input.pickatime('picker');1177 var $fname = elem.data('filter_name');1178 var $frange = elem.data('range');1179 var $directory = elem.parents('.um-directory');1180 var query_value = um_get_data_for_directory( $directory, 'filter_' + $fname + '_' + $frange );1181 if ( typeof query_value !== 'undefined' ) {1182 var arr = query_value.split(':');1183 $picker.set( 'select', arr[0]*60 + arr[1]*1 );1184 }1185 });1186 var ignore_after_search = false;1187 ignore_after_search = wp.hooks.applyFilters( 'um_member_directory_ignore_after_search', ignore_after_search );1188 if ( ! ignore_after_search ) {1189 var show_after_search = directory.data('must-search');1190 if ( show_after_search === 1 ) {1191 var search = um_get_search( directory );1192 var filters_data = um_get_filters_data( directory );1193 if ( ! filters_data.length && ! search ) {1194 return;1195 }1196 }1197 }1198 um_members_show_preloader( directory );1199 um_ajax_get_members( directory, {first_load:true} );1200 um_change_tag( directory );1201 });1202 //history events when back/forward and change window.location.hash1203 window.addEventListener( "popstate", function(e) {1204 jQuery( '.um-directory' ).each( function() {1205 var directory = jQuery(this);1206 var hash = um_members_get_hash( directory );1207 um_member_directories.push( hash );1208 um_members_show_preloader( directory );1209 // clear layout and header1210 directory.find('.um-members-grid, .um-members-list, .um-members-intro').remove();1211 // set search from history1212 if ( directory.find( '.um-member-directory-search-line' ).length ) {1213 var search = um_get_data_for_directory( directory, 'search' );1214 if ( typeof search == 'undefined' ) {1215 search = '';1216 }1217 directory.data( 'general_search', search );1218 directory.find('.um-search-line').val( search );1219 }1220 var page = um_get_data_for_directory( directory, 'page' );1221 if ( typeof page == 'undefined' ) {1222 page = 1;1223 } else if ( page > directory.data( 'total_pages' ) ) {1224 page = directory.data( 'total_pages' );1225 }1226 directory.data( 'page', page ).attr( 'data-page', page );1227 //sorting from history1228 if ( directory.find( '.um-member-directory-sorting' ).length ) {1229 var sort = um_get_data_for_directory( directory, 'sort' );1230 if ( typeof sort == 'undefined' ) {1231 sort = directory.find( '.um-new-dropdown[data-element=".um-member-directory-sorting-a"]' ).find('a[data-default="1"]').data('value');1232 }1233 directory.data( 'sorting', sort );1234 var sort_dropdown = directory.find( '.um-new-dropdown[data-element=".um-member-directory-sorting-a"]' );1235 sort_dropdown.find('a').data('selected', 0).prop('data-selected', 0).attr('data-selected', 0);1236 sort_dropdown.find('a[data-value="' + sort + '"]').data('selected', 1).prop('data-selected', 1).attr('data-selected', 1);1237 directory.find('.um-member-directory-sorting-a').find('> a').html( sort_dropdown.find('a[data-value="' + sort + '"]').html() );1238 }1239 //view type from history1240 if ( directory.find( '.um-member-directory-view-type' ).length ) {1241 var layout = um_get_data_for_directory( directory, 'view_type' );1242 if ( typeof layout == 'undefined' ) {1243 layout = directory.find( '.um-member-directory-view-type-a[data-default="1"]' ).data('type');1244 }1245 directory.data( 'view_type', layout );1246 directory.find('.um-member-directory-view-type .um-member-directory-view-type-a').hide();1247 directory.find('.um-member-directory-view-type .um-member-directory-view-type-a[data-type="' + layout + '"]').show();1248 }1249 //datepicker filter1250 directory.find('.um-datepicker-filter').each( function() {1251 var elem = jQuery(this);1252 var $picker = elem.pickadate('picker');1253 var $fname = elem.data('filter_name');1254 var $frange = elem.data('range');1255 var query_value = um_get_data_for_directory( directory, 'filter_' + $fname + '_' + $frange );1256 if ( typeof query_value !== 'undefined' ) {1257 $picker.set( 'select', query_value*1000 );1258 } else {1259 $picker.clear();1260 }1261 });1262 directory.find('.um-slider').each( function() {1263 var slider = jQuery( this );1264 var filter_name = slider.data('field_name');1265 var min_default_value = um_get_data_for_directory( directory, 'filter_' + filter_name + '_from' );1266 var max_default_value = um_get_data_for_directory( directory, 'filter_' + filter_name + '_to' );1267 if ( typeof min_default_value == 'undefined' ) {1268 min_default_value = slider.data('min');1269 }1270 min_default_value = parseInt( min_default_value );1271 if ( typeof max_default_value == 'undefined' ) {1272 max_default_value = slider.data('max');1273 }1274 max_default_value = parseInt( max_default_value );1275 slider.slider( 'values', [min_default_value, max_default_value] );1276 um_set_range_label( slider );1277 });1278 //timepicker filter1279 directory.find('.um-timepicker-filter').each( function() {1280 var elem = jQuery(this);1281 var $picker = elem.pickatime('picker');1282 var $fname = elem.data('filter_name');1283 var $frange = elem.data('range');1284 var query_value = um_get_data_for_directory( directory, 'filter_' + $fname + '_' + $frange );1285 if ( typeof query_value !== 'undefined' ) {1286 var arr = query_value.split(':');1287 $picker.set( 'select', arr[0]*60 );1288 } else {1289 $picker.clear();1290 }1291 });1292 var ignore_after_search = false;1293 ignore_after_search = wp.hooks.applyFilters( 'um_member_directory_ignore_after_search', ignore_after_search );1294 if ( ! ignore_after_search ) {1295 var show_after_search = directory.data('must-search');1296 if ( show_after_search === 1 ) {1297 var search = um_get_search( directory );1298 var filters_data = um_get_filters_data( directory );...
dictionary.ts
Source:dictionary.ts
...63 write_messages([]);64 return { map: dictionary, status: true, message: "Root created" };65}66// modifying67export function add_directory(68 dictionary: Map<number, directory>,69 parent_directory_path: string,70 name: string71): return_status {72 let parent_directory = get_directory_by_name(73 dictionary,74 parent_directory_path75 );76 let add: directory = {77 parent_directory: parent_directory_path,78 sub_directories: [],79 name: name.trim(),80 messages: [],81 type: "directory",82 search_result: false,83 id: uid(32),84 };85 let hash_value: number = hasher.hash(add);86 if (dictionary.has(hash_value)) {87 return {88 map: dictionary,89 status: false,90 message: "Directory path already exists",91 };92 }93 // set the subdirectory of the parent to the new directory94 parent_directory.sub_directories.push(get_path_from_root(add));95 dictionary = dictionary.set(hash_value, add);96 // update parent too97 dictionary = dictionary.set(hasher.hash(parent_directory), parent_directory);98 write_file(dictionary);99 let messages_search = get_all_messages_global_searchable(dictionary);100 write_messages(messages_search);101 return { map: dictionary, status: true, message: "Success" };102}103// modifying104export function add_message(105 dictionary: Map<number, directory>,106 directory_path: string,107 comserver: string = "",108 scripts: string[] = [],109 description: string = "",110 raw_message: string,111 notes: string = ""112): return_status {113 // check if directory exists114 let directory: directory = get_directory_by_name(dictionary, directory_path);115 let hash_value_directory: number = hasher.hash(directory);116 if (!dictionary.has(hash_value_directory)) {117 return {118 map: dictionary,119 status: false,120 message: "attempting to add into an invalid directory!",121 };122 }123 let directory_copy = parse(stringify(directory));124 let path: string = get_path_from_root(directory_copy);125 let message_to_add: message = {126 raw_message: raw_message.trim(),127 comserver: comserver.trim(),128 description: description.trim(),129 scripts: scripts.map((elm) => {130 return elm.trim();131 }),132 directory_path: path.trim(),133 type: "message",134 notes: notes,135 id: uid(36),136 };137 // check if this message exists in this instance of the map138 if (139 directory_copy.messages.filter(140 (m) => m.description === message_to_add.description141 ).length > 0142 ) {143 return {144 map: dictionary,145 status: false,146 message: "value already exists in this directory!",147 };148 }149 // add the message to the directory150 // @ts-ignore151 dictionary.get(hash_value_directory).messages.push(message_to_add);152 write_file(dictionary);153 let messages_search = get_all_messages_global_searchable(dictionary);154 write_messages(messages_search);155 return {156 map: dictionary,157 status: true,158 message: "value has been added into the directory!",159 };160}161// modifying162export function remove_directory(163 dictionary: Map<number, directory>,164 directory_string: string165): return_status {166 let directory: directory = get_directory_by_name(167 dictionary,168 directory_string169 );170 let parent: directory = get_directory_by_name(171 dictionary,172 get_parent_path_from_root(directory)173 );174 let hash_value_directory: number = hasher.hash(directory);175 if (!dictionary.has(hash_value_directory)) {176 return {177 map: dictionary,178 status: false,179 message: "directory doesn't exist!",180 };181 }182 // deletion needs to occur downstream so first find out all directories to delete and remove from map183 let search_queue = [get_path_from_root(directory)];184 let visited = new Map<string, boolean>();185 while (search_queue.length > 0) {186 let curr_node = search_queue.pop();187 // @ts-ignore188 let curr_node_dir = get_directory_by_name(dictionary, curr_node);189 // @ts-ignore190 visited.set(curr_node, true);191 for (let i = 0; i < curr_node_dir.sub_directories.length; i++) {192 if (visited.has(curr_node_dir.sub_directories[i])) {193 continue;194 }195 search_queue.push(curr_node_dir.sub_directories[i]);196 }197 }198 // remove all directories we have visited199 // remove from parents sub directories list200 for (let [key, value] of visited) {201 let hash_key = hasher.hash(key);202 // @ts-ignore203 dictionary.get(hash_key).messages = [];204 dictionary.delete(hash_key);205 }206 let directory_index: number = parent.sub_directories.indexOf(207 get_path_from_root(directory)208 );209 parent.sub_directories.splice(directory_index, 1);210 dictionary.set(hasher.hash(parent), parent);211 write_file(dictionary);212 let messages_search = get_all_messages_global_searchable(dictionary);213 write_messages(messages_search);214 return {215 map: dictionary,216 status: true,217 message: "directory has been removed!",218 };219}220// modifying221export function remove_message(222 dictionary: Map<number, directory>,223 message: message224): return_status {225 let directory: directory = get_directory_by_name(226 dictionary,227 message.directory_path228 );229 let hash_value_directory: number = hasher.hash(directory);230 if (!dictionary.has(hash_value_directory)) {231 return {232 map: dictionary,233 status: false,234 message: "directory doesn't exist!",235 };236 }237 let new_messages = [];238 let found = false;239 console.log(message, " - ", directory.messages);240 for (let i = 0; i < directory.messages.length; i++) {241 if (242 directory.messages[i].comserver === message.comserver &&243 directory.messages[i].description === message.description &&244 JSON.stringify(directory.messages[i].scripts) ===245 JSON.stringify(message.scripts) &&246 directory.messages[i].raw_message === message.raw_message247 ) {248 found = true;249 continue;250 }251 // @ts-ignore252 new_messages.push(directory.messages[i]);253 }254 if (!found) {255 return {256 map: dictionary,257 status: false,258 message:259 "message you are trying to delete doesn't exist in the directory!",260 };261 }262 // remove old unmodified message263 directory.messages = [...new_messages];264 dictionary.set(hash_value_directory, directory);265 write_file(dictionary);266 let messages_search = get_all_messages_global_searchable(dictionary);267 write_messages(messages_search);268 return {269 map: dictionary,270 status: true,271 message: "message was deleted from the directory!",272 };273}274// modifying275export function modify_directory(276 dictionary: Map<number, directory>,277 directory_path: string,278 name: string279): return_status {280 let directory: directory = get_directory_by_name(dictionary, directory_path);281 let parent: directory = get_directory_by_name(282 dictionary,283 get_parent_path_from_root(directory)284 );285 const old_path = get_path_from_root(directory);286 let hash_value_directory: number = hasher.hash(directory);287 if (!dictionary.has(hash_value_directory)) {288 return {289 map: dictionary,290 status: false,291 message: "Directory doesn't exist!",292 };293 }294 let hash_value_parent: number = hasher.hash(parent);295 directory.name = name;296 let new_value_hash: number = hasher.hash(directory);297 const new_path = get_path_from_root(directory);298 if (dictionary.has(new_value_hash)) {299 return {300 map: dictionary,301 status: false,302 message: "Name you are changing to already exists!",303 };304 }305 // since we are modifying (all dirs have only 1 parent we want to update the parents sub_directory list)306 let new_subs: string[] = [];307 for (let i = 0; i < parent.sub_directories.length; i++) {308 if (309 !dictionary.has(hasher.hash(parent.sub_directories[i])) ||310 hasher.hash(parent.sub_directories[i]) === hash_value_directory311 ) {312 continue;313 }314 // @ts-ignore315 new_subs.push(parent.sub_directories[i]);316 }317 // @ts-ignore318 new_subs.push(get_path_from_root(directory));319 parent.sub_directories = new_subs;320 dictionary.set(hash_value_parent, parent);321 // fix all subdirectories downstream from CURRENT directory322 let search_queue = [old_path];323 let visited = new Map<string, boolean>();324 while (search_queue.length > 0) {325 let curr_node = search_queue.pop();326 // @ts-ignore327 let curr_node_dir = get_directory_by_name(dictionary, curr_node);328 let curr_node_dir_hash = hasher.hash(curr_node_dir);329 curr_node_dir.parent_directory = curr_node_dir.parent_directory.replace(330 old_path,331 new_path332 );333 // fix the messages path334 for (let i = 0; i < curr_node_dir.messages.length; i++) {335 curr_node_dir.messages[i].directory_path = curr_node_dir.messages[336 i337 ].directory_path.replace(old_path, new_path);338 }339 // @ts-ignore340 visited.set(curr_node, true);341 for (let i = 0; i < curr_node_dir.sub_directories.length; i++) {342 if (visited.has(curr_node_dir.sub_directories[i])) {343 continue;344 }345 search_queue.push(curr_node_dir.sub_directories[i]);346 }347 // fix subs348 for (let i = 0; i < curr_node_dir.sub_directories.length; i++) {349 curr_node_dir.sub_directories[i] = curr_node_dir.sub_directories[350 i351 ].replace(old_path, new_path);352 }353 // recompute hash for the curr_node_dir since its changed parent354 dictionary.delete(curr_node_dir_hash);355 dictionary.set(hasher.hash(curr_node_dir), curr_node_dir);356 }357 dictionary.delete(hash_value_directory);358 dictionary.set(new_value_hash, directory);359 write_file(dictionary);360 let messages_search = get_all_messages_global_searchable(dictionary);361 write_messages(messages_search);362 return {363 map: dictionary,364 status: true,365 message: "changed name successfully!",366 };367}368// modifying369export function modify_message(370 dictionary: Map<number, directory>,371 message: message,372 raw_message: string = "",373 comserver: string = "",374 scripts: string[] = [],375 description: string = "",376 notes: string = ""377): return_status {378 let message_copy: message = parse(stringify(message));379 let directory: directory = parse(380 stringify(get_directory_by_name(dictionary, message_copy.directory_path))381 );382 let hash_value_directory: number = hasher.hash(directory);383 if (description === "") {384 return {385 map: dictionary,386 status: false,387 message: "name field must be populated!",388 };389 }390 if (!dictionary.has(hash_value_directory)) {391 return {392 map: dictionary,393 status: false,394 message: "directory doesn't exist!",395 };396 }397 // try retrieve this message398 let new_messages = [];399 let found = false;400 for (let i = 0; i < directory.messages.length; i++) {401 if (402 directory.messages[i].comserver === message.comserver &&403 directory.messages[i].description === message.description &&404 JSON.stringify(directory.messages[i].scripts) ===405 JSON.stringify(message.scripts) &&406 directory.messages[i].raw_message === message.raw_message &&407 directory.messages[i].notes === message.notes408 ) {409 found = true;410 continue;411 }412 if (directory.messages[i].description === description) {413 return {414 map: dictionary,415 status: false,416 message: "Cannot rename to exisiting directory name!",417 };418 }419 // @ts-ignore420 new_messages.push(directory.messages[i]);421 }422 if (!found) {423 return {424 map: dictionary,425 status: false,426 message:427 "message you are trying to modify doesn't exist in the directory!",428 };429 }430 // remove old unmodified message431 directory.messages = [...new_messages];432 message_copy.comserver = comserver;433 message_copy.raw_message = raw_message;434 message_copy.scripts = scripts;435 message_copy.notes = notes;436 message_copy.description = description;437 message_copy.id = message.id;438 directory.messages.push(message_copy);439 dictionary.set(hash_value_directory, directory);440 write_file(dictionary);441 let messages_search = get_all_messages_global_searchable(dictionary);442 write_messages(messages_search);443 return {444 map: dictionary,445 status: true,446 message: "message has been modified!",447 };448}449// modifying450export function search(451 dictionary: Map<number, directory>,452 search_query: string,453 parent_directory: string454): return_status {455 // step 1 need to get all messages456 let search_dir: directory = {457 parent_directory: parent_directory,458 sub_directories: [],459 name: "Search Results",460 messages: [],461 type: "directory",462 id: uid(32),463 search_result: true,464 };465 let hash_value: number = hasher.hash(search_dir);466 // @ts-ignore467 let all_messages = JSON.parse(read_messages());468 let item_results = search_messages(all_messages, search_query);469 console.log(item_results);470 // step 3 create new "Search Result Directory"471 search_dir.messages = item_results;472 console.log(search_dir);473 dictionary.set(hash_value, search_dir);474 return {475 map: dictionary,476 status: true,477 message: "search returned!",478 };479}480// modifying481export function search_filtered(482 dictionary: Map<number, directory>,483 search_query: string,484 comserver: string[],485 scripts: string[],486 parent_directory: string,487 project: string488): return_status {489 if (comserver.length === 0 && scripts.length === 0 && project === "") {490 return search(dictionary, search_query, parent_directory);491 }492 let search_dir: directory = {493 parent_directory: parent_directory,494 sub_directories: [],495 name: "Search Results",496 messages: [],497 type: "directory",498 id: uid(32),499 search_result: true,500 };501 let hash_value: number = hasher.hash(search_dir);502 // @ts-ignore503 let all_messages = JSON.parse(read_messages());504 // filter all messages505 let filtered_messages_map: Map<string, any> = new Map<string, any>();506 let flag: boolean = false;507 if (comserver.length === 0 && scripts.length === 0) {508 flag = true;509 }510 for (let i = 0; i < all_messages.length; i++) {511 if (512 project !== "" &&513 !all_messages[i].directory_path.trim().startsWith(project)514 ) {515 continue;516 }517 if (flag) {518 filtered_messages_map.set(all_messages[i].id, all_messages[i]);519 continue;520 }521 // go through each script/directory in filter to do this522 for (let j = 0; j < comserver.length; j++) {523 if (comserver[j].trim() === all_messages[i].comserver.trim()) {524 filtered_messages_map.set(all_messages[i].id, all_messages[i]);525 break;526 }527 }528 for (let j = 0; j < scripts.length; j++) {529 if (all_messages[i].scripts.indexOf(scripts[j].trim()) !== -1) {530 filtered_messages_map.set(all_messages[i].id, all_messages[i]);531 break;532 }533 }534 }535 let filtered_messages = [];536 for (let [key, value] of filtered_messages_map) {537 // @ts-ignore538 filtered_messages.push(value);539 }540 console.log(filtered_messages);541 let item_results = search_messages(filtered_messages, search_query);542 console.log(item_results);543 // step 3 create new "Search Result Directory"544 search_dir.messages = item_results;545 console.log(search_dir);546 dictionary.set(hash_value, search_dir);547 return {548 map: dictionary,549 status: true,550 message: "search returned!",551 };552}553// passive554export function get_all_messages(555 dictionary: Map<number, directory>,556 directory: directory557): message[] {558 let hash_value_directory: number = hasher.hash(directory);559 if (!dictionary.has(hash_value_directory)) {560 return [];561 }562 return directory.messages;563}564// passive565export function get_all_directories_from_current(566 dictionary: Map<number, directory>,567 name: string568): directory[] {569 let hash_value_directory: number = hasher.hash(name);570 if (!dictionary.has(hash_value_directory)) {571 return [];572 }573 let all_dirs_from_current: directory[] = [];574 // @ts-ignore575 let subs = dictionary.get(hash_value_directory).sub_directories;576 for (let i = 0; i < subs.length; i++) {577 all_dirs_from_current.push(get_directory_by_name(dictionary, subs[i]));578 }579 return all_dirs_from_current;580}581// add uids only need to ever do this once and now582export function add_uids_to_everything(dictionary: Map<number, directory>) {583 for (let [key, value] of dictionary) {584 let entry_copy: directory = parse(stringify(value));585 entry_copy.id = uid(32);586 for (let i = 0; i < entry_copy.messages.length; i++) {587 entry_copy.messages[i].id = uid(32);588 }589 dictionary.set(key, entry_copy);590 }591 write_file(dictionary);592 return {593 map: dictionary,594 status: true,595 message: "message has been modified!",596 };597}598// passive599export function map_scripts_to_comserver(600 dictionary: Map<number, directory>,601 project: string602): Map<string, string[]> {603 let ret: Map<string, string[]> = new Map<string, string[]>();604 for (let [key, value] of dictionary) {605 for (let i = 0; i < value.messages.length; i++) {606 if (607 project !== "" &&608 !value.messages[i].directory_path.trim().startsWith("root/" + project)609 ) {610 continue;611 }612 for (let j = 0; j < value.messages[i].scripts.length; j++) {613 if (value.messages[i].scripts[j].trim() === "") {614 continue;615 }616 if (ret.has(value.messages[i].scripts[j].trim())) {617 let new_vals = ret.get(value.messages[i].scripts[j].trim());618 if (new_vals?.indexOf(value.messages[i].comserver.trim()) === -1) {619 new_vals.push(value.messages[i].comserver.trim());620 ret.set(value.messages[i].scripts[j].trim(), new_vals);621 }622 } else {623 ret.set(value.messages[i].scripts[j].trim(), [624 value.messages[i].comserver.trim(),625 ]);626 }627 }628 }629 }630 return ret;631}632// passive633export function map_comserver_to_scripts(634 dictionary: Map<number, directory>,635 project: string636): Map<string, string[]> {637 let ret: Map<string, string[]> = new Map<string, string[]>();638 for (let [key, value] of dictionary) {639 for (let i = 0; i < value.messages.length; i++) {640 if (641 project !== "" &&642 !value.messages[i].directory_path.trim().startsWith("root/" + project)643 ) {644 continue;645 }646 if (value.messages[i].comserver.trim() === "") {647 continue;648 }649 if (ret.has(value.messages[i].comserver.trim())) {650 let new_vals = ret.get(value.messages[i].comserver.trim());651 for (let j = 0; j < value.messages[i].scripts.length; j++) {652 if (653 value.messages[i].scripts[j].trim() === "" ||654 // @ts-ignore655 new_vals.indexOf(value.messages[i].scripts[j].trim()) !== -1656 ) {657 continue;658 }659 new_vals?.push(value.messages[i].scripts[j].trim());660 }661 // @ts-ignore662 ret.set(value.messages[i].comserver.trim(), new_vals);663 } else {664 let new_vals = [];665 for (let j = 0; j < value.messages[i].scripts.length; j++) {666 if (667 value.messages[i].scripts[j].trim() === "" ||668 // @ts-ignore669 new_vals.indexOf(value.messages[i].scripts[j].trim()) !== -1670 ) {671 continue;672 }673 // @ts-ignore674 new_vals?.push(value.messages[i].scripts[j].trim());675 }676 ret.set(value.messages[i].comserver.trim(), new_vals);677 }678 }679 }680 return ret;681}682// passive683export function map_project_to_script_comserver(684 dictionary: Map<number, directory>685): Map<string, any> {686 // we want to compute the above maps on a per project basis!687 // step 1 get all children of root688 let ret: Map<string, any> = new Map<string, any>();689 let root = get_directory_by_name(dictionary, "root");690 let projects = root.sub_directories;691 projects.push("");692 for (let i = 0; i < projects.length; i++) {693 let maps = {694 scripts_comserver_map: map_scripts_to_comserver(695 dictionary,696 projects[i].replace("root/", "")697 ),698 comserver_scripts_map: map_comserver_to_scripts(699 dictionary,700 projects[i].replace("root/", "")701 ),702 };703 ret.set(projects[i], maps);704 }705 write_keys(global_variables.project_map, JSON.stringify(ret, replacer));706 console.log(ret);707 return ret;708}709// passive710export function get_all_messages_global_searchable(711 dictionary: Map<number, directory>712): message[] {713 let all_messages: message[] = [];714 console.log("HI");715 for (let [key, value] of dictionary) {716 if (value.search_result !== undefined && value.search_result !== true)717 all_messages.push(...value.messages);718 }719 all_messages = all_messages.map((elm) => ({720 ...elm,721 combined_keys:722 elm.raw_message +723 " " +724 elm.notes +725 " " +726 elm.scripts.toString() +727 " " +728 elm.comserver +729 " " +730 elm.description,731 }));732 console.log(all_messages);733 return all_messages;734}735// modifying736export function fix_directories(737 dictionary: Map<number, directory>738): Map<number, directory> {739 for (let [key, value] of dictionary) {740 let new_val = value;741 new_val.search_result = false;742 dictionary.set(key, new_val);743 }744 return dictionary;745}746export function move_message(747 dictionary: Map<number, directory>,748 message: message,749 target: string750): return_status {751 // step 1 find it752 let current_directory: directory = get_directory_by_name(753 dictionary,754 message.directory_path755 );756 let hash_value_current_directory: number = hasher.hash(current_directory);757 if (!dictionary.has(hash_value_current_directory)) {758 return {759 map: dictionary,760 status: false,761 message: "Source directory doesn't exist!",762 };763 }764 let target_directory: directory = get_directory_by_name(dictionary, target);765 let hash_value_target_directory: number = hasher.hash(target_directory);766 if (!dictionary.has(hash_value_target_directory)) {767 return {768 map: dictionary,769 status: false,770 message: "Target directory doesn't exist!",771 };772 }773 // step 2 add it to target directory774 let search = target_directory.messages.filter((item) => {775 return item.description === message.description;776 });777 let old_message_description = message.description;778 let count = 1;779 while (search.length !== 0) {780 message.description =781 old_message_description + " (" + count.toString() + ")";782 count++;783 search = target_directory.messages.filter((item) => {784 return item.description === message.description;785 });786 }787 message.directory_path = target;788 target_directory.messages.push(message);789 // step 3 delete it from current directory790 current_directory.messages = current_directory.messages.filter((item) => {791 return item.id !== message.id && item.description !== message.description;792 });793 // step 4 update maps794 dictionary.set(hash_value_target_directory, target_directory);795 dictionary.set(hash_value_current_directory, current_directory);796 write_file(dictionary);797 let messages_search = get_all_messages_global_searchable(dictionary);798 write_messages(messages_search);799 return {800 map: dictionary,801 status: true,802 message: "message was moved to " + target + "!",803 };804}805// step 0 check target directory, retrieve see if it exists806// step 1 compute hash of current directory, check if it exists807// step 2 check subdirectories of target if they have a directory with name ending path same, append (1) to it if it does808// step 3 add to subdirectory of target809// step 4 remove as subdirectory of current parent810// step 5 downstream renaming to match new destination811// step 6 fix map to remove previous hash of old directory and replace with new hash of current directory812// modifying813export function move_directory(814 dictionary: Map<number, directory>,815 directory: directory,816 target: string817): return_status {818 let target_directory: directory = get_directory_by_name(dictionary, target);819 let hash_value_target_directory: number = hasher.hash(target_directory);820 if (!dictionary.has(hash_value_target_directory)) {821 return {822 map: dictionary,823 status: false,824 message: "Target directory doesn't exist!",825 };826 }827 let hash_value_moving_directory: number = hasher.hash(directory);828 if (!dictionary.has(hash_value_target_directory)) {829 return {830 map: dictionary,831 status: false,832 message: "Directory you are moving doesn't exist!",833 };834 }835 let current_directory: directory = get_directory_by_name(836 dictionary,837 directory.parent_directory838 );839 let hash_value_current_directory: number = hasher.hash(840 directory.parent_directory841 );842 if (!dictionary.has(hash_value_target_directory)) {843 return {844 map: dictionary,845 status: false,846 message: "Current directory doesn't exist!",847 };848 }849 // step 2 check the ends of each subidrectory with the NAME of moving directory850 let search = target_directory.sub_directories.filter((item) => {851 let split = item.split("/");852 return split[split.length - 1] === directory.name;853 });854 let adding_string = "";855 let count = 1;856 console.log("length", search.length);857 while (search.length !== 0) {858 console.log(adding_string);859 adding_string = " (" + count + ")";860 count++;861 search = target_directory.sub_directories.filter((item) => {862 let split = item.split("/");863 return split[split.length - 1] === directory.name + adding_string;864 });865 }866 let old_path = directory.parent_directory + "/" + directory.name;867 // step 4868 current_directory.sub_directories = current_directory.sub_directories.filter(869 (item) => {870 let split = item.split("/");871 return split[split.length - 1] !== directory.name;872 }873 );874 directory.name += adding_string;875 // step 3876 let insert =877 target_directory.parent_directory !== ""878 ? target_directory.parent_directory +879 "/" +880 target_directory.name +881 "/" +882 directory.name883 : target_directory.name + "/" + directory.name;884 target_directory.sub_directories.push(insert);885 let new_path =886 target_directory.parent_directory !== ""887 ? target_directory.parent_directory +888 "/" +889 target_directory.name +890 "/" +891 directory.name892 : target_directory.name + "/" + directory.name;893 console.log(old_path, " -> ", new_path);894 let first = true;895 // fix all subdirectories downstream from CURRENT directory896 let search_queue = [old_path];897 let visited = new Map<string, boolean>();898 while (search_queue.length > 0) {899 console.log(search_queue);900 let curr_node = search_queue.pop();901 // @ts-ignore902 let curr_node_dir = get_directory_by_name(dictionary, curr_node);903 let curr_node_dir_hash = hasher.hash(curr_node_dir);904 console.log(905 "PARENT_DIRECTORY:",906 curr_node_dir.parent_directory,907 "\nOLD_PATH:",908 old_path,909 "\nNEW_PATH:",910 new_path911 );912 if (!first) {913 curr_node_dir.parent_directory = curr_node_dir.parent_directory.replace(914 old_path,915 new_path916 );917 } else {918 curr_node_dir.parent_directory = curr_node_dir.parent_directory.replace(919 old_path.split("/").slice(0, -1).join("/"),920 new_path.split("/").slice(0, -1).join("/")921 );922 if (curr_node_dir.id === directory.id) {923 curr_node_dir.name = directory.name;924 }925 first = false;926 }927 console.log("NEW PARENT_DIRECTORY:", curr_node_dir.parent_directory);928 // fix the messages path929 for (let i = 0; i < curr_node_dir.messages.length; i++) {930 curr_node_dir.messages[i].directory_path = curr_node_dir.messages[931 i932 ].directory_path.replace(old_path, new_path);933 }934 // @ts-ignore935 visited.set(curr_node, true);936 for (let i = 0; i < curr_node_dir.sub_directories.length; i++) {937 if (visited.has(curr_node_dir.sub_directories[i])) {938 continue;939 }940 search_queue.push(curr_node_dir.sub_directories[i]);941 }942 // fix subs943 for (let i = 0; i < curr_node_dir.sub_directories.length; i++) {944 console.log(945 curr_node_dir.sub_directories[i],946 "old path: ",947 old_path,948 "new_path:",949 new_path950 );951 curr_node_dir.sub_directories[i] = curr_node_dir.sub_directories[952 i953 ].replace(old_path, new_path);954 }955 console.log(curr_node_dir);956 // recompute hash for the curr_node_dir since its changed parent957 dictionary.delete(curr_node_dir_hash);958 dictionary.set(hasher.hash(curr_node_dir), curr_node_dir);959 }960 // directory.parent_directory = new_parent;961 dictionary.delete(hash_value_moving_directory);962 dictionary.set(hash_value_current_directory, current_directory);963 dictionary.set(hash_value_target_directory, target_directory);964 write_file(dictionary);965 let messages_search = get_all_messages_global_searchable(dictionary);966 write_messages(messages_search);967 return {968 map: dictionary,969 status: true,970 message: "directory was moved to + " + target + "!",971 };972}973export function copy_message(message: message) {974 // copy to clipboard the message975 console.log(message);976 localStorage.setItem(global_variables.clipboard, JSON.stringify(message));977}978export function copy_directory(directory: directory) {979 localStorage.setItem(global_variables.clipboard, JSON.stringify(directory));980}981export function paste_general(982 dictionary: Map<number, directory>983): return_status {984 let paste_object_string = window.localStorage.getItem(985 global_variables.clipboard986 );987 if (988 paste_object_string !== undefined &&989 paste_object_string !== null &&990 paste_object_string !== ""991 ) {992 let paste_object = JSON.parse(paste_object_string);993 if (paste_object.type === "message") {994 return paste_message(dictionary, paste_object);995 } else {996 return paste_directory(dictionary, paste_object);997 }998 } else {999 return {1000 map: dictionary,1001 status: false,1002 message: "Nothing in clipboard!",1003 };1004 }1005}1006export function paste_message(1007 dictionary: Map<number, directory>,1008 message: message1009): return_status {1010 let current_directory_string = window.localStorage.getItem(1011 global_variables.current_directory1012 );1013 if (1014 current_directory_string === null ||1015 current_directory_string === undefined1016 ) {1017 current_directory_string = "";1018 }1019 let current_directory: directory = get_directory_by_name(1020 dictionary,1021 current_directory_string1022 );1023 let hash_value_current_directory = hasher.hash(current_directory);1024 if (!dictionary.has(hash_value_current_directory)) {1025 return {1026 map: dictionary,1027 status: false,1028 message: "Current directory not found!",1029 };1030 }1031 let copy_message = JSON.parse(JSON.stringify(message));1032 let search = current_directory.messages.filter((item) => {1033 return item.description === copy_message.description;1034 });1035 let old_message_description = copy_message.description;1036 let count = 1;1037 while (search.length !== 0) {1038 console.log(search.length);1039 copy_message.description =1040 old_message_description + " (" + count.toString() + ")";1041 console.log(copy_message.description);1042 count++;1043 search = current_directory.messages.filter((item) => {1044 return item.description === copy_message.description;1045 });1046 }1047 copy_message.directory_path = current_directory_string;1048 copy_message.id = uid(16);1049 current_directory.messages.push(copy_message);1050 // step 4 update maps1051 dictionary.set(hash_value_current_directory, current_directory);1052 write_file(dictionary);1053 let messages_search = get_all_messages_global_searchable(dictionary);1054 write_messages(messages_search);1055 return {1056 map: dictionary,1057 status: true,1058 message: "message Pasted!",1059 };1060}1061export function paste_directory(1062 dictionary: Map<number, directory>,1063 directory: directory1064): return_status {1065 let current_directory_string = window.localStorage.getItem(1066 global_variables.current_directory1067 );1068 if (1069 current_directory_string === null ||1070 current_directory_string === undefined1071 ) {1072 current_directory_string = "";1073 }1074 let current_directory: directory = get_directory_by_name(1075 dictionary,1076 current_directory_string1077 );1078 let hash_value_current_directory = hasher.hash(current_directory);1079 if (!dictionary.has(hash_value_current_directory)) {1080 return {1081 map: dictionary,1082 status: false,1083 message: "Current directory not found!",1084 };1085 }1086 // cancer1087 let copy_directory = JSON.parse(JSON.stringify(directory));1088 copy_directory.id = uid(16);1089 let search = current_directory.sub_directories.filter((item) => {1090 let split = item.split("/");1091 return split[split.length - 1] === copy_directory.name;1092 });1093 let adding_string = "";1094 let count = 1;1095 console.log("length", search.length);1096 while (search.length !== 0) {1097 console.log(adding_string);1098 adding_string = " (" + count + ")";1099 count++;1100 search = current_directory.sub_directories.filter((item) => {1101 let split = item.split("/");1102 return split[split.length - 1] === copy_directory.name + adding_string;1103 });1104 }1105 let old_path = copy_directory.parent_directory + "/" + copy_directory.name;1106 copy_directory.name += adding_string;1107 // step 31108 let insert =1109 current_directory.parent_directory !== ""1110 ? current_directory.parent_directory +1111 "/" +1112 current_directory.name +1113 "/" +1114 copy_directory.name1115 : current_directory.name + "/" + copy_directory.name;1116 // current_directory.sub_directories.push(insert);1117 let new_path =1118 current_directory.parent_directory !== ""1119 ? current_directory.parent_directory +1120 "/" +1121 current_directory.name +1122 "/" +1123 copy_directory.name1124 : current_directory.name + "/" + copy_directory.name;1125 console.log(old_path, " -> ", new_path);1126 // fix all subdirectories downstream from CURRENT directory1127 let search_queue = [old_path];1128 let visited = new Map<string, boolean>();1129 while (search_queue.length > 0) {1130 console.log(search_queue);1131 let curr_node = search_queue.pop();1132 // @ts-ignore1133 console.log(curr_node);1134 let curr_node_dir = get_directory_by_name(dictionary, curr_node);1135 let insert_dir_full = (1136 curr_node_dir.parent_directory +1137 "/" +1138 curr_node_dir.name1139 ).replace(old_path, new_path);1140 let insert_parent = insert_dir_full.split("/").slice(0, -1).join("/");1141 let insert_name_split = insert_dir_full.split("/");1142 let insert_name = insert_name_split[insert_name_split.length - 1];1143 console.log("INSERT PARENT", insert_parent, "INSERT NAME", insert_name);1144 dictionary = add_directory(dictionary, insert_parent, insert_name).map;1145 // now we want to add all messages1146 for (let i = 0; i < curr_node_dir.messages.length; i++) {1147 console.log(curr_node_dir.messages[i]);1148 let msg = curr_node_dir.messages[i];1149 dictionary = add_message(1150 dictionary,1151 insert_dir_full,1152 msg.comserver,1153 msg.scripts,1154 msg.description,1155 msg.raw_message,1156 msg.notes1157 ).map;1158 }1159 // dictionary = add_directory(dictionary, )1160 visited.set(curr_node, true);1161 for (let i = 0; i < curr_node_dir.sub_directories.length; i++) {1162 if (visited.has(curr_node_dir.sub_directories[i])) {1163 continue;1164 }1165 search_queue.push(curr_node_dir.sub_directories[i]);1166 }1167 console.log(search_queue);1168 }1169 // directory.parent_directory = new_parent;1170 // dictionary.set(hash_value_current_directory, current_directory);1171 write_file(dictionary);1172 let messages_search = get_all_messages_global_searchable(dictionary);1173 write_messages(messages_search);...
navigator.py
Source:navigator.py
...303 item.setArt({'icon': poster, 'thumb': poster, 'poster': poster, 'tvshow.poster': poster, 'season.poster': poster, 'banner': banner, 'tvshow.banner': banner, 'season.banner': banner})304 item.setProperty('Fanart_Image', fanart)305 control.addItem(handle=int(sys.argv[1]), url=url, listitem=item, isFolder=False)306 control.content(int(sys.argv[1]), content)307 control.directory(int(sys.argv[1]), cacheToDisc=True)308 from resources.lib.modules import cache309 views.setView(content, {})310 except:311 return312 def accountCheck(self):313 if traktCredentials == False:314 control.idle()315 control.infoDialog(control.lang(32042).encode('utf-8'), sound=True, icon='WARNING')316 control.openSettings('2.12')317 sys.exit()318 def clearCache(self):319 control.idle()320 yes = control.yesnoDialog(control.lang(32056).encode('utf-8'), '', '')321 if not yes: return322 from resources.lib.modules import cache323 cache.clear()324 control.infoDialog(control.lang(32057).encode('utf-8'), sound=True, icon='INFO')325 def addDirectoryItem(self, name, query, thumb, icon, queue=False, isAction=True, isFolder=True):326 try: name = control.lang(name).encode('utf-8')327 except: pass328 url = '%s?action=%s' % (sysaddon, query) if isAction == True else query329 thumb = os.path.join(artPath, thumb) if not artPath == None else icon330 cm = []331 if queue == True: cm.append((queueMenu, 'RunPlugin(%s?action=queueItem)' % sysaddon))332 item = control.item(label=name)333 item.addContextMenuItems(cm)334 item.setArt({'icon': thumb, 'thumb': thumb})335 if not addonFanart == None: item.setProperty('Fanart_Image', addonFanart)336 control.addItem(handle=syshandle, url=url, listitem=item, isFolder=isFolder)337 def collectionsMovies(self):338 self.addDirectoryItem('Animal Kingdom', 'movies&url=tmdbanimal', 'animalkingdom.png', 'DefaultRecentlyAddedMovies.png')339 self.addDirectoryItem('Based On A True Story', 'movies&url=tmdbbased', 'truestories.png', 'DefaultRecentlyAddedMovies.png')340 self.addDirectoryItem('Cold War', 'movies&url=tmdbcold', 'cold.png', 'DefaultRecentlyAddedMovies.png')341 self.addDirectoryItem('Datenight', 'movies&url=tmdbdatenight', 'datenight.png', 'DefaultRecentlyAddedMovies.png')342 self.addDirectoryItem('DC Universe', 'movies&url=tmdbdc', 'dc.png', 'DefaultRecentlyAddedMovies.png')343 self.addDirectoryItem('Dont Do Drugs', 'movies&url=tmdb420', '420.png', 'DefaultRecentlyAddedMovies.png')344 self.addDirectoryItem('Fight Club', 'movies&url=tmdbfight', 'fight.png', 'DefaultRecentlyAddedMovies.png')345 self.addDirectoryItem('Gamers Paradise', 'movies&url=tmdbgamers', 'gamersparadise.png', 'DefaultRecentlyAddedMovies.png')346 self.addDirectoryItem('Gangster Hits', 'movies&url=tmdbmafia', 'mob.png', 'DefaultRecentlyAddedMovies.png')347 self.addDirectoryItem('Girls With Guns', 'movies&url=tmdbgwg', 'gwg.png', 'DefaultRecentlyAddedMovies.png')348 self.addDirectoryItem('Hack The Planet', 'movies&url=tmdbhack', 'hack.png', 'DefaultRecentlyAddedMovies.png')349 self.addDirectoryItem('The Heist', 'movies&url=tmdbheist', 'heists.png', 'DefaultRecentlyAddedMovies.png')350 self.addDirectoryItem('Immortal', 'movies&url=tmdbimmortal', 'immortal.png', 'DefaultRecentlyAddedMovies.png')351 self.addDirectoryItem('Its A Conspiracy', 'movies&url=tmdbconsp', 'consp.png', 'DefaultRecentlyAddedMovies.png')352 self.addDirectoryItem('Life in The Fast Lane', 'movies&url=tmdbfast', 'fast.png', 'DefaultRecentlyAddedMovies.png')353 self.addDirectoryItem('Marvel Universe', 'movies&url=tmdbmarvel', 'marvel.png', 'DefaultRecentlyAddedMovies.png')354 self.addDirectoryItem('Off The Shelf', 'movies&url=tmdbbooks', 'offtheshelf.png', 'DefaultRecentlyAddedMovies.png')355 self.addDirectoryItem('Out Of This World', 'movies&url=tmdbufo', 'ufo.png', 'DefaultRecentlyAddedMovies.png')356 self.addDirectoryItem('Snatched', 'movies&url=tmdbsnatched', 'snatched.png', 'DefaultRecentlyAddedMovies.png')357 self.addDirectoryItem('Stand-Up', 'movies&url=tmdbstandup', 'standup.png', 'DefaultRecentlyAddedMovies.png')358 self.addDirectoryItem('Streets of The Chi', 'movies&url=tmdbchi', 'chi.png', 'DefaultRecentlyAddedMovies.png')359 self.addDirectoryItem('Sports', 'movies&url=tmdbsports', 'sports.png', 'DefaultRecentlyAddedMovies.png')360 self.addDirectoryItem('The Art Of The Con', 'movies&url=tmdbconman', 'conman.png', 'DefaultRecentlyAddedMovies.png')361 self.addDirectoryItem('The Spy Who Streamed Me', 'movies&url=tmdbspy', 'spy.png', 'DefaultRecentlyAddedMovies.png')362 self.addDirectoryItem('Vigilante Justice', 'movies&url=tmdbvigilante', 'vigilante.png', 'DefaultRecentlyAddedMovies.png')363 self.addDirectoryItem('Welcome To The Hood', 'movies&url=tmdburban', 'hood.png', 'DefaultRecentlyAddedMovies.png')364 self.addDirectoryItem('What A Tragedy', 'movies&url=tmdbtragedy', 'tragedy.png', 'DefaultRecentlyAddedMovies.png')365 self.endDirectory()366 def kidsCollections(self):367 self.addDirectoryItem('Disney', 'movies&url=tmdbdisney', 'disney.png', 'DefaultRecentlyAddedMovies.png')368 self.addDirectoryItem('Dreamworks', 'movies&url=tmdbdreamworks', 'dreamworks.png', 'DefaultRecentlyAddedMovies.png')369 self.addDirectoryItem('Lego Collection', 'movies&url=tmdblego', 'lego.png', 'DefaultRecentlyAddedMovies.png')370 self.addDirectoryItem('Princesses', 'movies&url=tmdbprincess', 'princess.png', 'DefaultRecentlyAddedMovies.png')371 self.addDirectoryItem('Super Heroes', 'movies&url=tmdbhero', 'hero.png', 'DefaultRecentlyAddedMovies.png')372 self.addDirectoryItem('The Ultimate Kids Collection', 'movies&url=tmdbkidz', 'kidsfav.png', 'DefaultRecentlyAddedMovies.png')373 self.endDirectory()374 def holidayCollections(self):375 self.addDirectoryItem('Christmas', 'movies&url=tmdbchristmas', 'christmas.png', 'DefaultRecentlyAddedMovies.png')376 self.addDirectoryItem('Easter', 'movies&url=tmdbeaster', 'easter.png', 'DefaultRecentlyAddedMovies.png')377 self.addDirectoryItem('Halloween', 'movies&url=tmdbhalloween', 'halloween.png', 'DefaultRecentlyAddedMovies.png')378 self.addDirectoryItem('Independence Day', 'movies&url=tmdbfourth', 'fourth.png', 'DefaultRecentlyAddedMovies.png')379 self.addDirectoryItem('Thanksgiving', 'movies&url=tmdbthanks', 'thanks.png', 'DefaultRecentlyAddedMovies.png')380 self.addDirectoryItem('Valentines', 'movies&url=tmdbvalentines', 'valentines.png', 'DefaultRecentlyAddedMovies.png')381 self.endDirectory()382 def tvCollections(self):383 self.addDirectoryItem('Blast From The Past', 'tvshows&url=tmdbblast', 'blast.png', 'DefaultTVShows.png')384 self.addDirectoryItem('Blaze It TV', 'tvshows&url=tmdb420tv', '420.png', 'DefaultTVShows.png')385 self.addDirectoryItem('Datenight', 'tvshows&url=tmdbdatenighttv', 'datenight.png', 'DefaultTVShows.png')386 self.addDirectoryItem('Gamers Paradise', 'tvshows&url=tmdbgamers', 'gamersparadise.png', 'DefaultTVShows.png')387 self.addDirectoryItem('Hungry Yet', 'tvshows&url=tmdbcooking', 'hungry.png', 'DefaultTVShows.png')388 self.addDirectoryItem('Inked N Proud', 'tvshows&url=tmdbtats', 'inked.png', 'DefaultTVShows.png')389 self.addDirectoryItem('LMAO', 'tvshows&url=tmdblmao', 'lmao.PNG', 'DefaultTVShows.png')390 self.addDirectoryItem('Life in The Fast Lane', 'tvshows&url=tmdbfasttv', 'fast.png', 'DefaultTVShows.png')391 self.addDirectoryItem('Out Of This World', 'tvshows&url=tmdbufotv', 'ufo.png', 'DefaultTVShows.png')392 self.addDirectoryItem('Streets of The Chi', 'tvshows&url=tmdbchitv', 'chi.png', 'DefaultTVShows.png')393 self.addDirectoryItem('Sports', 'tvshows&url=tmdbsportstv', 'sports.png', 'DefaultTVShows.png')394 self.endDirectory()395 def kidstvCollections(self):396 self.addDirectoryItem('Animation Station', 'tvshows&url=tmdbanimationtv', 'lego.png', 'DefaultTVShows.png')397 self.addDirectoryItem('Back In The Day Cartoons', 'tvshows&url=tmdbcartoon', 'cartoon.png', 'DefaultTVShows.png')398 self.addDirectoryItem('Kids TV', 'tvshows&url=tmdbkids', 'kidsfav.png', 'DefaultTVShows.png')399 self.addDirectoryItem('Lil Ones', 'tvshows&url=tmdblittle', 'lil.png', 'DefaultTVShows.png')400 self.endDirectory()401 def endDirectory(self):402 # control.do_block_check(False)...
baselineoptimizer.py
Source:baselineoptimizer.py
...72 baseline_search_path = self._baseline_search_path(port, baseline_name)73 baseline_root = self._baseline_root(baseline_name)74 relative_paths = [self._filesystem.relpath(path, self._webkit_base) for path in baseline_search_path]75 return relative_paths + [baseline_root]76 def _join_directory(self, directory, baseline_name):77 # This code is complicated because both the directory name and the baseline_name have the virtual78 # test suite in the name and the virtual baseline name is not a strict superset of the non-virtual name.79 # For example, virtual/gpu/fast/canvas/foo-expected.png corresponds to fast/canvas/foo-expected.png and80 # the baseline directories are like platform/mac/virtual/gpu/fast/canvas. So, to get the path81 # to the baseline in the platform directory, we need to append jsut foo-expected.png to the directory.82 virtual_suite = self._virtual_suite(baseline_name)83 if virtual_suite:84 baseline_name_without_virtual = baseline_name[len(virtual_suite.name) + 1:]85 else:86 baseline_name_without_virtual = baseline_name87 return self._filesystem.join(self._scm.checkout_root, directory, baseline_name_without_virtual)88 def read_results_by_directory(self, baseline_name):89 results_by_directory = {}90 directories = reduce(set.union, map(set, [self._relative_baseline_search_paths(port, baseline_name) for port in self._ports.values()]))91 for directory in directories:92 path = self._join_directory(directory, baseline_name)93 if self._filesystem.exists(path):94 results_by_directory[directory] = self._filesystem.sha1(path)95 return results_by_directory96 def _results_by_port_name(self, results_by_directory, baseline_name):97 results_by_port_name = {}98 for port_name, port in self._ports.items():99 for directory in self._relative_baseline_search_paths(port, baseline_name):100 if directory in results_by_directory:101 results_by_port_name[port_name] = results_by_directory[directory]102 break103 return results_by_port_name104 @memoized105 def _directories_immediately_preceding_root(self, baseline_name):106 directories = set()107 for port in self._ports.values():108 directory = self._filesystem.relpath(self._baseline_search_path(port, baseline_name)[-1], self._webkit_base)109 directories.add(directory)110 return directories111 def _optimize_result_for_root(self, new_results_by_directory, baseline_name):112 # The root directory (i.e. LayoutTests) is the only one that doesn't correspond113 # to a specific platform. As such, it's the only one where the baseline in fallback directories114 # immediately before it can be promoted up, i.e. if win and mac115 # have the same baseline, then it can be promoted up to be the LayoutTests baseline.116 # All other baselines can only be removed if they're redundant with a baseline earlier117 # in the fallback order. They can never promoted up.118 directories_immediately_preceding_root = self._directories_immediately_preceding_root(baseline_name)119 shared_result = None120 root_baseline_unused = False121 for directory in directories_immediately_preceding_root:122 this_result = new_results_by_directory.get(directory)123 # If any of these directories don't have a baseline, there's no optimization we can do.124 if not this_result:125 return126 if not shared_result:127 shared_result = this_result128 elif shared_result != this_result:129 root_baseline_unused = True130 baseline_root = self._baseline_root(baseline_name)131 # The root baseline is unused if all the directories immediately preceding the root132 # have a baseline, but have different baselines, so the baselines can't be promoted up.133 if root_baseline_unused:134 if baseline_root in new_results_by_directory:135 del new_results_by_directory[baseline_root]136 return137 new_results_by_directory[baseline_root] = shared_result138 for directory in directories_immediately_preceding_root:139 del new_results_by_directory[directory]140 def _find_optimal_result_placement(self, baseline_name):141 results_by_directory = self.read_results_by_directory(baseline_name)142 results_by_port_name = self._results_by_port_name(results_by_directory, baseline_name)143 port_names_by_result = _invert_dictionary(results_by_port_name)144 new_results_by_directory = self._remove_redundant_results(results_by_directory, results_by_port_name, port_names_by_result, baseline_name)145 self._optimize_result_for_root(new_results_by_directory, baseline_name)146 return results_by_directory, new_results_by_directory147 def _remove_redundant_results(self, results_by_directory, results_by_port_name, port_names_by_result, baseline_name):148 new_results_by_directory = copy.copy(results_by_directory)149 for port_name, port in self._ports.items():150 current_result = results_by_port_name.get(port_name)151 # This happens if we're missing baselines for a port.152 if not current_result:153 continue;154 fallback_path = self._relative_baseline_search_paths(port, baseline_name)155 current_index, current_directory = self._find_in_fallbackpath(fallback_path, current_result, new_results_by_directory)156 for index in range(current_index + 1, len(fallback_path)):157 new_directory = fallback_path[index]158 if not new_directory in new_results_by_directory:159 # No result for this baseline in this directory.160 continue161 elif new_results_by_directory[new_directory] == current_result:162 # Result for new_directory are redundant with the result earlier in the fallback order.163 if current_directory in new_results_by_directory:164 del new_results_by_directory[current_directory]165 else:166 # The new_directory contains a different result, so stop trying to push results up.167 break168 return new_results_by_directory169 def _find_in_fallbackpath(self, fallback_path, current_result, results_by_directory):170 for index, directory in enumerate(fallback_path):171 if directory in results_by_directory and (results_by_directory[directory] == current_result):172 return index, directory173 assert False, "result %s not found in fallback_path %s, %s" % (current_result, fallback_path, results_by_directory)174 def _platform(self, filename):175 platform_dir = self.ROOT_LAYOUT_TESTS_DIRECTORY + self._filesystem.sep + 'platform' + self._filesystem.sep176 if filename.startswith(platform_dir):177 return filename.replace(platform_dir, '').split(self._filesystem.sep)[0]178 platform_dir = self._filesystem.join(self._scm.checkout_root, platform_dir)179 if filename.startswith(platform_dir):180 return filename.replace(platform_dir, '').split(self._filesystem.sep)[0]181 return '(generic)'182 def _move_baselines(self, baseline_name, results_by_directory, new_results_by_directory):183 data_for_result = {}184 for directory, result in results_by_directory.items():185 if not result in data_for_result:186 source = self._join_directory(directory, baseline_name)187 data_for_result[result] = self._filesystem.read_binary_file(source)188 scm_files = []189 fs_files = []190 for directory, result in results_by_directory.items():191 if new_results_by_directory.get(directory) != result:192 file_name = self._join_directory(directory, baseline_name)193 if self._scm.exists(file_name):194 scm_files.append(file_name)195 else:196 fs_files.append(file_name)197 if scm_files or fs_files:198 if scm_files:199 _log.debug(" Deleting (SCM):")200 for platform_dir in sorted(self._platform(filename) for filename in scm_files):201 _log.debug(" " + platform_dir)202 if self._skip_scm_commands:203 self._files_to_delete.extend(scm_files)204 else:205 self._scm.delete_list(scm_files)206 if fs_files:207 _log.debug(" Deleting (file system):")208 for platform_dir in sorted(self._platform(filename) for filename in fs_files):209 _log.debug(" " + platform_dir)210 for filename in fs_files:211 self._filesystem.remove(filename)212 else:213 _log.debug(" (Nothing to delete)")214 file_names = []215 for directory, result in new_results_by_directory.items():216 if results_by_directory.get(directory) != result:217 destination = self._join_directory(directory, baseline_name)218 self._filesystem.maybe_make_directory(self._filesystem.split(destination)[0])219 self._filesystem.write_binary_file(destination, data_for_result[result])220 file_names.append(destination)221 if file_names:222 _log.debug(" Adding:")223 for platform_dir in sorted(self._platform(filename) for filename in file_names):224 _log.debug(" " + platform_dir)225 if self._skip_scm_commands:226 # Have adds win over deletes.227 self._files_to_delete = list(set(self._files_to_delete) - set(file_names))228 self._files_to_add.extend(file_names)229 else:230 self._scm.add_list(file_names)231 else:232 _log.debug(" (Nothing to add)")233 def write_by_directory(self, results_by_directory, writer, indent):234 for path in sorted(results_by_directory):235 writer("%s%s: %s" % (indent, self._platform(path), results_by_directory[path][0:6]))236 def _optimize_subtree(self, baseline_name):237 basename = self._filesystem.basename(baseline_name)238 results_by_directory, new_results_by_directory = self._find_optimal_result_placement(baseline_name)239 if new_results_by_directory == results_by_directory:240 if new_results_by_directory:241 _log.debug(" %s: (already optimal)" % basename)242 self.write_by_directory(results_by_directory, _log.debug, " ")243 else:244 _log.debug(" %s: (no baselines found)" % basename)245 # This is just used for unittests. Intentionally set it to the old data if we don't modify anything.246 self.new_results_by_directory.append(results_by_directory)247 return True248 if self._results_by_port_name(results_by_directory, baseline_name) != self._results_by_port_name(new_results_by_directory, baseline_name):249 # This really should never happen. Just a sanity check to make sure the script fails in the case of bugs250 # instead of committing incorrect baselines.251 _log.error(" %s: optimization failed" % basename)252 self.write_by_directory(results_by_directory, _log.warning, " ")253 return False254 _log.debug(" %s:" % basename)255 _log.debug(" Before: ")256 self.write_by_directory(results_by_directory, _log.debug, " ")257 _log.debug(" After: ")258 self.write_by_directory(new_results_by_directory, _log.debug, " ")259 self._move_baselines(baseline_name, results_by_directory, new_results_by_directory)260 return True261 def _optimize_virtual_root(self, baseline_name, non_virtual_baseline_name):262 virtual_root_expected_baseline_path = self._filesystem.join(self._layout_tests_dir, baseline_name)263 if not self._filesystem.exists(virtual_root_expected_baseline_path):264 return265 root_sha1 = self._filesystem.sha1(virtual_root_expected_baseline_path)266 results_by_directory = self.read_results_by_directory(non_virtual_baseline_name)267 # See if all the immediate predecessors of the virtual root have the same expected result.268 for port in self._ports.values():269 directories = self._relative_baseline_search_paths(port, non_virtual_baseline_name)270 for directory in directories:271 if directory not in results_by_directory:272 continue273 if results_by_directory[directory] != root_sha1:274 return275 break276 _log.debug("Deleting redundant virtual root expected result.")277 if self._skip_scm_commands and virtual_root_expected_baseline_path in self._files_to_add:278 self._files_to_add.remove(virtual_root_expected_baseline_path)279 if self._scm.exists(virtual_root_expected_baseline_path):280 _log.debug(" Deleting (SCM): " + virtual_root_expected_baseline_path)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!