<commit_before>jQuery(function($){

inicio();
 $(window).load(function(){

        $(".sticky-nav").sticky({ topSpacing: 0 });

    });

/* ==================================================
   Login fancybox
================================================== */
$("#login")
    .attr('rel', 'gallery')
    .fancybox({
        maxWidth	: 700,
		maxHeight	: 500,
       openEffect	: 'elastic',
    	closeEffect	: 'elastic',
        helpers : {
            title : null
        }
    });

/* ==================================================
   Mobile Navigation
================================================== */
var mobileMenuClone = $('#menu').clone().attr('id', 'navigation-mobile');

 function mobileNav(){
	var windowWidth = $(window).width();

	if( windowWidth <= 979 ) {
		if( $('#mobile-nav').length > 0 ) {
			mobileMenuClone.insertAfter('#menu');
			$('#navigation-mobile #menu-nav').attr('id', 'menu-nav-mobile');
		}
	} else {
		$('#navigation-mobile').css('display', 'none');
		if ($('#mobile-nav').hasClass('open')) {
			$('#mobile-nav').removeClass('open');
		}
	}
}

 function listenerMenu(){
	$('#mobile-nav').on('click', function(e){

        $(this).toggleClass('open');

		if ($('#mobile-nav').hasClass('open')) {
			$('#navigation-mobile').slideDown(500, 'easeOutExpo');
		} else {
			$('#navigation-mobile').slideUp(500, 'easeOutExpo');
		}
		e.preventDefault();
	});

	$('#menu-nav-mobile a').on('click', function(){
		$('#mobile-nav').removeClass('open');
		$('#navigation-mobile').slideUp(350, 'easeOutExpo');
	});
}

/* ==================================================
   Slider Options
================================================== */
  function slider(){
	$.supersized({
		// Functionality
		slideshow               :   1,			// Slideshow on/off
		autoplay				:	1,			// Slideshow starts playing automatically
		start_slide             :   1,			// Start slide (0 is random)
		stop_loop				:	0,			// Pauses slideshow on last slide
		random					: 	0,			// Randomize slide order (Ignores start slide)
		slide_interval          :   4000,		// Length between transitions
		transition              :   1, 			// 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
		transition_speed		:	2000,		// Speed of transition
		new_window				:	1,			// Image links open in new window/tab
		pause_hover             :   0,			// Pause slideshow on hover
		keyboard_nav            :   1,			// Keyboard navigation on/off
		performance				:	1,			// 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
		image_protect			:	1,			// Disables image dragging and right click with Javascript

		// Size & Position
		min_width		        :   0,			// Min width allowed (in pixels)
		min_height		        :   0,			// Min height allowed (in pixels)
		vertical_center         :   1,			// Vertically center background
		horizontal_center       :   1,			// Horizontally center background
		fit_always				:	0,			// Image will never exceed browser width or height (Ignores min. dimensions)
		fit_portrait         	:   1,			// Portrait images will not exceed browser height
		fit_landscape			:   0,			// Landscape images will not exceed browser width

		// Components
		slide_links				:	'blank',	// Individual links for each slide (Options: false, 'num', 'name', 'blank')
		thumb_links				:	0,			// Individual thumb links for each slide
		thumbnail_navigation    :   0,			// Thumbnail navigation
		slides 					:  	[			// Slideshow Images

											{image : 'http://invisibledisabilities.org/wp-content/gallery/pamphlets/fragrance-free-zone.jpg', title : '

', thumb : '', url : ''},
											{image : '../images/profilePictures/5.jpg', title : '

', thumb : '', url : ''},
											{image : 'http://gsr2r.com/blog/wp-content/uploads/2013/11/bigstock_Office_Life_-_Happy_People_Hav_4098282.jpg ', title : '

', thumb : '', url : ''},
											{image : '../images/slider-images/image03.jpg', title : '

', thumb : '', url : ''}
									],

		// Theme Options
		progress_bar			:	0,			// Timer for each slide
		mouse_scrub				:	0

	});

}

/* ==================================================
   Navigation Fix
================================================== */

 function nav(){
	//$('.sticky-nav').waypoint('sticky');
         $(".sticky-nav").sticky({ topSpacing: 0 });
}

/* ==================================================
   Filter Works
================================================== */

 function filter(){
	if($('#projects').length > 0){
		var $container = $('#projects');

		$container.imagesLoaded(function() {
			$container.isotope({
			  // options
			  animationEngine: 'best-available',
			  itemSelector : '.item-thumbs',
			  layoutMode : 'fitRows'
			});
		});

		// filter items when filter link is clicked
		var $optionSets = $('#options .option-set'),
			$optionLinks = $optionSets.find('a');

		  $optionLinks.click(function(){
			var $this = $(this);
			// don't proceed if already selected
			if ( $this.hasClass('selected') ) {
			  return false;
			}
			var $optionSet = $this.parents('.option-set');
			$optionSet.find('.selected').removeClass('selected');
			$this.addClass('selected');

			// make option object dynamically, i.e. { filter: '.my-filter-class' }
			var options = {},
				key = $optionSet.attr('data-option-key'),
				value = $this.attr('data-option-value');
			// parse 'false' as false boolean
			value = value === 'false' ? false : value;
			options[ key ] = value;
			if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
			  // changes in layout modes need extra logic
			  changeLayoutMode( $this, options )
			} else {
			  // otherwise, apply new options
			  $container.isotope( options );
			}

			return false;
		});
	}
}

/* ==================================================
   FancyBox
================================================== */

 function fancyBox(){
	if($('.fancybox').length > 0 || $('.fancybox-media').length > 0 || $('.fancybox-various').length > 0){

		$(".fancybox").fancybox({
				padding : 0,
				beforeShow: function () {
					this.title = $(this.element).attr('title');
					this.title = '
' + this.title + '
' + '
' + $(this.element).parent().find('img').attr('alt') + '
';
				},
				helpers : {
					title : { type: 'inside' },
				}
			});

		$('.fancybox-media').fancybox({
			openEffect  : 'none',
			closeEffect : 'none',
			helpers : {
				media : {}
			}
		});
	}
}

/* ==================================================
   Contact Form
================================================== */
/*
BRUSHED.contactForm = function(){
	$("#contact-submit").on('click',function() {
		$contact_form = $('#contact-form');

		var fields = $contact_form.serialize();

		$.ajax({
			type: "POST",
			url: "_include/php/contact.php",
			data: fields,
			dataType: 'json',
			success: function(response) {

				if(response.status){
					$('#contact-form input').val('');
					$('#contact-form textarea').val('');
				}

				$('#response').empty().html(response.html);
			}
		});
		return false;
	});
}
*/

/* ==================================================
   Twitter Feed
================================================== */
/*
BRUSHED.tweetFeed = function(){

	var valueTop = -64; // Margin Top Value

    $("#ticker").tweet({
          modpath: '_include/js/twitter/',
          username: "Bluxart", // Change this with YOUR ID
          page: 1,
          avatar_size: 0,
          count: 10,
		  template: "{text}{time}",
		  filter: function(t){ return ! /^@\w+/.test(t.tweet_raw_text); },
          loading_text: "loading ..."
	}).bind("loaded", function() {
	  var ul = $(this).find(".tweet_list");
	  var ticker = function() {
		setTimeout(function() {
			ul.find('li:first').animate( {marginTop: valueTop + 'px'}, 500, 'linear', function() {
				$(this).detach().appendTo(ul).removeAttr('style');
			});
		  ticker();
		}, 5000);
	  };
	  ticker();
	});

}*/

/* ==================================================
   Menu Highlight
================================================== */

function menu(){
	$('#menu-nav, #menu-nav-mobile').onePageNav({
		currentClass: 'current',
    	changeHash: false,
    	scrollSpeed: 750,
    	scrollOffset: 30,
    	scrollThreshold: 0.5,
		easing: 'easeOutExpo',
		filter: ':not(.external)'
	});
}

/* ==================================================
   Next Section
================================================== */

 function goSection(){
        $('#nextsection').on('click', function(){
		$target = $($(this).attr('href')).offset().top-30;

		$('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo');
		return false;
	});
}

/* ==================================================
   GoUp
================================================== */

function goUp(){
    	$('#goUp').on('click', function(){
		$target = $($(this).attr('href')).offset().top-30;

		$('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo');
		return false;
	});
}

/* ==================================================
	Scroll to Top
================================================== */
 function scrollToTop(){

	var windowWidth = $(window).width(),
		didScroll = false;

	var $arrow = $('#back-to-top');

	$arrow.click(function(e) {
		$('body,html').animate({ scrollTop: "0" }, 750, 'easeOutExpo' );
		e.preventDefault();
	})

	$(window).scroll(function() {
		didScroll = true;
	});

	setInterval(function() {
		if( didScroll ) {
			didScroll = false;

			if( $(window).scrollTop() > 1000 ) {
				$arrow.css('display', 'block');
			} else {
				$arrow.css('display', 'none');
			}
		}
	}, 250);
}

/* ==================================================
   Thumbs / Social Effects
================================================== */

 function utils(){

	$('.item-thumbs').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

	$('.image-wrap').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

	$('#social ul li').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

}

/* ==================================================
   Accordion
================================================== */

 function accordion(){
	var accordion_trigger = $('.accordion-heading.accordionize');

	accordion_trigger.delegate('.accordion-toggle','click', function(event){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
		   	$(this).addClass('inactive');
		}
		else{
		  	accordion_trigger.find('.active').addClass('inactive');
		  	accordion_trigger.find('.active').removeClass('active');
		  	$(this).removeClass('inactive');
		  	$(this).addClass('active');
	 	}
		event.preventDefault();
	});
}

/* ==================================================
   Toggle
================================================== */

 function toggle(){
	var accordion_trigger_toggle = $('.accordion-heading.togglize');

	accordion_trigger_toggle.delegate('.accordion-toggle','click', function(event){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
		   	$(this).addClass('inactive');
		}
		else{
		  	$(this).removeClass('inactive');
		  	$(this).addClass('active');
	 	}
		event.preventDefault();
	});
}

/* ==================================================
   Tooltip
================================================== */

 function toolTip(){
    $('a[data-toggle=tooltip]').tooltip();
}

/* ==================================================
	Init
================================================== */

function inicio(){
//	Modernizr.load([
//	{
//		test: Modernizr.placeholder,
//		nope: '<?//php echo Yii::app()->request->baseUrl; ?>/js/placeholder.js',
//		complete : function() {
//				if (!Modernizr.placeholder) {
//						Placeholders.init({
//						live: true,
//						hideOnFocus: false,
//						className: "yourClass",
//						textColor: "#999"
//						});
//				}
//		}
//	}
//	]);

	// Preload the page with jPreLoader
	$('body').jpreLoader({
		splashID: "#jSplash",
		showSplash: true,
		showPercentage: true,
		autoClose: true,
		splashFunction: function() {
			$('#circle').delay(250).animate({'opacity' : 1}, 500, 'linear');
		}
	});

        $(".sticky-nav").sticky({ topSpacing: 0 });

        //var BRUSHED = window.BRUSHED || {};
        slider();

	nav();
	mobileNav();
	listenerMenu();
	menu();
	goSection();
	goUp();
	filter();
	fancyBox();
	//contactForm();
	//tweetFeed();
	scrollToTop();
	utils();
	accordion();
	toggle();
	toolTip();

$(window).resize(function(){
	BRUSHED.mobileNav();
});
}

});
<commit_msg>table publication's<commit_after>jQuery(function($){

inicio();
 $(window).load(function(){

        $(".sticky-nav").sticky({ topSpacing: 0 });

    });

/* ==================================================
   Login fancybox
================================================== */
$("#login")
    .attr('rel', 'gallery')
    .fancybox({
        maxWidth	: 700,
		maxHeight	: 500,
       openEffect	: 'elastic',
    	closeEffect	: 'elastic',
        helpers : {
            title : null
        }
    });

/* ==================================================
   Mobile Navigation
================================================== */
var mobileMenuClone = $('#menu').clone().attr('id', 'navigation-mobile');

 function mobileNav(){
	var windowWidth = $(window).width();

	if( windowWidth <= 979 ) {
		if( $('#mobile-nav').length > 0 ) {
			mobileMenuClone.insertAfter('#menu');
			$('#navigation-mobile #menu-nav').attr('id', 'menu-nav-mobile');
		}
	} else {
		$('#navigation-mobile').css('display', 'none');
		if ($('#mobile-nav').hasClass('open')) {
			$('#mobile-nav').removeClass('open');
		}
	}
}

 function listenerMenu(){
	$('#mobile-nav').on('click', function(e){

        $(this).toggleClass('open');

		if ($('#mobile-nav').hasClass('open')) {
			$('#navigation-mobile').slideDown(500, 'easeOutExpo');
		} else {
			$('#navigation-mobile').slideUp(500, 'easeOutExpo');
		}
		e.preventDefault();
	});

	$('#menu-nav-mobile a').on('click', function(){
		$('#mobile-nav').removeClass('open');
		$('#navigation-mobile').slideUp(350, 'easeOutExpo');
	});
}

/* ==================================================
   Slider Options
================================================== */
  function slider(){
	$.supersized({
		// Functionality
		slideshow               :   1,			// Slideshow on/off
		autoplay				:	1,			// Slideshow starts playing automatically
		start_slide             :   1,			// Start slide (0 is random)
		stop_loop				:	0,			// Pauses slideshow on last slide
		random					: 	0,			// Randomize slide order (Ignores start slide)
		slide_interval          :   4000,		// Length between transitions
		transition              :   1, 			// 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
		transition_speed		:	2000,		// Speed of transition
		new_window				:	1,			// Image links open in new window/tab
		pause_hover             :   0,			// Pause slideshow on hover
		keyboard_nav            :   1,			// Keyboard navigation on/off
		performance				:	1,			// 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
		image_protect			:	1,			// Disables image dragging and right click with Javascript

		// Size & Position
		min_width		        :   0,			// Min width allowed (in pixels)
		min_height		        :   0,			// Min height allowed (in pixels)
		vertical_center         :   1,			// Vertically center background
		horizontal_center       :   1,			// Horizontally center background
		fit_always				:	0,			// Image will never exceed browser width or height (Ignores min. dimensions)
		fit_portrait         	:   1,			// Portrait images will not exceed browser height
		fit_landscape			:   0,			// Landscape images will not exceed browser width

		// Components
		slide_links				:	'blank',	// Individual links for each slide (Options: false, 'num', 'name', 'blank')
		thumb_links				:	0,			// Individual thumb links for each slide
		thumbnail_navigation    :   0,			// Thumbnail navigation
		slides 					:  	[			// Slideshow Images

											{image : 'http://invisibledisabilities.org/wp-content/gallery/pamphlets/fragrance-free-zone.jpg', title : '

', thumb : '', url : ''},
											{image : '../images/profilePictures/5.jpg', title : '

', thumb : '', url : ''},
											{image : 'http://gsr2r.com/blog/wp-content/uploads/2013/11/bigstock_Office_Life_-_Happy_People_Hav_4098282.jpg ', title : '

', thumb : '', url : ''},
											{image : '../images/slider-images/image03.jpg', title : '

', thumb : '', url : ''}
									],

		// Theme Options
		progress_bar			:	0,			// Timer for each slide
		mouse_scrub				:	0

	});

}

/* ==================================================
   Navigation Fix
================================================== */

 function nav(){
	//$('.sticky-nav').waypoint('sticky');
         $(".sticky-nav").sticky({ topSpacing: 0 });
}

/* ==================================================
   Filter Works
================================================== */

 function filter(){
	if($('#projects').length > 0){
		var $container = $('#projects');

		$container.imagesLoaded(function() {
			$container.isotope({
			  // options
			  animationEngine: 'best-available',
			  itemSelector : '.item-thumbs',
			  layoutMode : 'fitRows'
			});
		});

		// filter items when filter link is clicked
		var $optionSets = $('#options .option-set'),
			$optionLinks = $optionSets.find('a');

		  $optionLinks.click(function(){
			var $this = $(this);
			// don't proceed if already selected
			if ( $this.hasClass('selected') ) {
			  return false;
			}
			var $optionSet = $this.parents('.option-set');
			$optionSet.find('.selected').removeClass('selected');
			$this.addClass('selected');

			// make option object dynamically, i.e. { filter: '.my-filter-class' }
			var options = {},
				key = $optionSet.attr('data-option-key'),
				value = $this.attr('data-option-value');
			// parse 'false' as false boolean
			value = value === 'false' ? false : value;
			options[ key ] = value;
			if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
			  // changes in layout modes need extra logic
			  changeLayoutMode( $this, options )
			} else {
			  // otherwise, apply new options
			  $container.isotope( options );
			}

			return false;
		});
	}
}

/* ==================================================
   FancyBox
================================================== */

 function fancyBox(){
	if($('.fancybox').length > 0 || $('.fancybox-media').length > 0 || $('.fancybox-various').length > 0){

		$(".fancybox").fancybox({
				padding : 0,
				beforeShow: function () {
					this.title = $(this.element).attr('title');
					this.title = '
' + this.title + '
' + '
' + $(this.element).parent().find('img').attr('alt') + '
';
				},
				helpers : {
					title : { type: 'inside' },
				}
			});

		$('.fancybox-media').fancybox({
			openEffect  : 'none',
			closeEffect : 'none',
			helpers : {
				media : {}
			}
		});
	}
}

/* ==================================================
   Contact Form
================================================== */
/*
BRUSHED.contactForm = function(){
	$("#contact-submit").on('click',function() {
		$contact_form = $('#contact-form');

		var fields = $contact_form.serialize();

		$.ajax({
			type: "POST",
			url: "_include/php/contact.php",
			data: fields,
			dataType: 'json',
			success: function(response) {

				if(response.status){
					$('#contact-form input').val('');
					$('#contact-form textarea').val('');
				}

				$('#response').empty().html(response.html);
			}
		});
		return false;
	});
}
*/

/* ==================================================
   Twitter Feed
================================================== */
/*
BRUSHED.tweetFeed = function(){

	var valueTop = -64; // Margin Top Value

    $("#ticker").tweet({
          modpath: '_include/js/twitter/',
          username: "Bluxart", // Change this with YOUR ID
          page: 1,
          avatar_size: 0,
          count: 10,
		  template: "{text}{time}",
		  filter: function(t){ return ! /^@\w+/.test(t.tweet_raw_text); },
          loading_text: "loading ..."
	}).bind("loaded", function() {
	  var ul = $(this).find(".tweet_list");
	  var ticker = function() {
		setTimeout(function() {
			ul.find('li:first').animate( {marginTop: valueTop + 'px'}, 500, 'linear', function() {
				$(this).detach().appendTo(ul).removeAttr('style');
			});
		  ticker();
		}, 5000);
	  };
	  ticker();
	});

}*/

/* ==================================================
   Menu Highlight
================================================== */

function menu(){
	$('#menu-nav, #menu-nav-mobile').onePageNav({
		currentClass: 'current',
    	changeHash: false,
    	scrollSpeed: 750,
    	scrollOffset: 30,
    	scrollThreshold: 0.5,
		easing: 'easeOutExpo',
		filter: ':not(.external)'
	});
}

/* ==================================================
   Next Section
================================================== */

 function goSection(){
        $('#nextsection').on('click', function(){
		$target = $($(this).attr('href')).offset().top-30;

		$('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo');
		return false;
	});
}

/* ==================================================
   GoUp
================================================== */

function goUp(){
    	$('#goUp').on('click', function(){
		$target = $($(this).attr('href')).offset().top-30;

		$('body, html').animate({scrollTop : $target}, 750, 'easeOutExpo');
		return false;
	});
}

/* ==================================================
	Scroll to Top
================================================== */
 function scrollToTop(){

	var windowWidth = $(window).width(),
		didScroll = false;

	var $arrow = $('#back-to-top');

	$arrow.click(function(e) {
		$('body,html').animate({ scrollTop: "0" }, 750, 'easeOutExpo' );
		e.preventDefault();
	})

	$(window).scroll(function() {
		didScroll = true;
	});

	setInterval(function() {
		if( didScroll ) {
			didScroll = false;

			if( $(window).scrollTop() > 1000 ) {
				$arrow.css('display', 'block');
			} else {
				$arrow.css('display', 'none');
			}
		}
	}, 250);
}

/* ==================================================
   Thumbs / Social Effects
================================================== */

 function utils(){

	$('.item-thumbs').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

	$('.image-wrap').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

	$('#social ul li').bind('touchstart', function(){
		$(".active").removeClass("active");
      	$(this).addClass('active');
    });

}

/* ==================================================
   Accordion
================================================== */

 function accordion(){
	var accordion_trigger = $('.accordion-heading.accordionize');

	accordion_trigger.delegate('.accordion-toggle','click', function(event){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
		   	$(this).addClass('inactive');
		}
		else{
		  	accordion_trigger.find('.active').addClass('inactive');
		  	accordion_trigger.find('.active').removeClass('active');
		  	$(this).removeClass('inactive');
		  	$(this).addClass('active');
	 	}
		event.preventDefault();
	});
}

/* ==================================================
   Toggle
================================================== */

 function toggle(){
	var accordion_trigger_toggle = $('.accordion-heading.togglize');

	accordion_trigger_toggle.delegate('.accordion-toggle','click', function(event){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
		   	$(this).addClass('inactive');
		}
		else{
		  	$(this).removeClass('inactive');
		  	$(this).addClass('active');
	 	}
		event.preventDefault();
	});
}

/* ==================================================
   Tooltip
================================================== */

 function toolTip(){
    $('a[data-toggle=tooltip]').tooltip();
}

/* ==================================================
	Init
================================================== */

function inicio(){
//	Modernizr.load([
//	{
//		test: Modernizr.placeholder,
//		nope: '<?//php echo Yii::app()->request->baseUrl; ?>/js/placeholder.js',
//		complete : function() {
//				if (!Modernizr.placeholder) {
//						Placeholders.init({
//						live: true,
//						hideOnFocus: false,
//						className: "yourClass",
//						textColor: "#999"
//						});
//				}
//		}
//	}
//	]);

	// Preload the page with jPreLoader
	$('body').jpreLoader({
		splashID: "#jSplash",
		showSplash: true,
		showPercentage: true,
		autoClose: true,
		splashFunction: function() {
			$('#circle').delay(250).animate({'opacity' : 1}, 500, 'linear');
		}
	});

        $(".sticky-nav").sticky({ topSpacing: 0 });

        //var BRUSHED = window.BRUSHED || {};
        slider();

	nav();
	mobileNav();
	listenerMenu();
	menu();
	goSection();
	goUp();
	filter();
	fancyBox();
	//contactForm();
	//tweetFeed();
	scrollToTop();
	utils();
	accordion();
	toggle();
	toolTip();

$(window).resize(function(){
	mobileNav();
});
}

});
<|endoftext|>


<commit_before>import DS from "ember-data";

export default DS.Adapter.extend({
    params: function(){
      return {
        Bucket: 'am-testblog', /* required */
      };
    },
    list: function(){
      debugger
      var s3 = new AWS.S3({region: 'us-west-2', maxRetries: 5});

      var params = this.params();

      return new Ember.RSVP.Promise(function(resolve, reject){
        s3.listObjects(params, function(err, data) {
          if (err) {
            reject(err);
          } // an error occurred
          resolve( data );  // successful response
        });
      });
    },

    getArticle: function(key){
      var s3 = new AWS.S3({region: 'us-west-2', maxRetries: 5});

      var params = this.params();
      params['Key'] = key;

      return new Ember.RSVP.Promise(function(resolve, reject){
        s3.getObject(params, function(err, data) {
          if (err) {
            reject(err); // an error occurred
          }
          resolve( data );  // successful response
        });
      });
    },

    createRecord: function(store, type, snapshot) {
      var s3 = new AWS.S3({region: 'us-west-2', maxRetries: 5});

      var params = this.params();
      params['Key']  = snapshot.get('Key');
      params['Body'] = snapshot.get('Body');

      return new Ember.RSVP.Promise(function(resolve, reject) {
        s3.putObject(params, function(err, data) {
          if (err) {
            reject(err); // an error occurred
          }
          resolve( data );  // successful response
        });
      });
    },

    updateRecord: function(store, type, snapshot) {
      var s3 = new AWS.S3({region: 'us-west-2', maxRetries: 5});

      var params = this.params();
      params['Key']  = snapshot.get('Key');
      params['Body'] = snapshot.get('Body');

      return new Ember.RSVP.Promise(function(resolve, reject) {
        s3.putObject(params, function(err, data) {
          if (err) {
            reject(err); // an error occurred
          }
          resolve( data );  // successful response
        });
      });
    },

    deleteRecord: function(store, type, snapshot) {

      var s3 = new AWS.S3({region: 'us-west-2', maxRetries: 5});

      var params = this.params();
      params['Key']  = snapshot.get('Key');

      return new Ember.RSVP.Promise(function(resolve, reject) {
        s3.deleteObject(params, function(err, data) {
          if (err) {
            reject(err); // an error occurred
          }
          resolve( data );  // successful response
        });
      });
    },

    find: function (store, type, id){
      return this.getArticle(id);
    },

    findAll: function(){
      return this.list();
    }
  });
<commit_msg>refactor: adapter promises<commit_after>import DS from "ember-data";

export default DS.Adapter.extend({
    params: function(){
      return {
        Bucket: 'am-testblog', /* required */
      };
    },

    apiPromise: function(awsFunction, params){
      var s3 = new AWS.S3({region: 'us-west-2', maxRetries: 5});

      return new Ember.RSVP.Promise(function(resolve, reject){
        var apiFunction = s3[awsFunction];
        if (apiFunction){
          apiFunction = apiFunction.bind(s3);
          apiFunction(params, function(err, data) {
            if (err) {
              reject(err);
            }
            resolve(data);
          });
        } else {
          reject("Function is not a valid AWS S3 API method.");
        }
      });
    },

    createRecord: function(store, type, snapshot) {
      var params = this.params();
      params['Key']  = snapshot.get('Key');
      params['Body'] = snapshot.get('Body');

      return this.apiPromise('putObject', params);
    },

    updateRecord: function(store, type, snapshot) {
      var params = this.params();
      params['Key']  = snapshot.get('Key');
      params['Body'] = snapshot.get('Body');

      return this.apiPromise('putObject', params);
    },

    deleteRecord: function(store, type, snapshot) {
      var params = this.params();
      params['Key']  = snapshot.get('Key');

      return this.apiPromise('deleteObject', params);
    },

    find: function (store, type, id){
      var params = this.params();
      params['Key'] = id;

      return this.apiPromise('getObject', params);
    },

    findAll: function(){
      var params = this.params();

      return this.apiPromise('listObjects', params);
    }
  });
<|endoftext|>


<commit_before>'use strict';

var m = require('mithril');
var URI = require('URIjs');
var $ = require('jquery');
var Raven = require('raven-js');

var Fangorn = require('js/fangorn').Fangorn;
var waterbutler = require('js/waterbutler');
var $osf = require('js/osfHelpers');

function changeState(grid, item, version) {
    item.data.version = version;
    grid.updateFolder(null, item);
}

function _downloadEvent(event, item, col) {
    event.stopPropagation();
    window.location = waterbutler.buildTreeBeardDownload(item);
}

// Define Fangorn Button Actions
var _dataverseItemButtons = {
    view: function (ctrl, args, children) {
        var buttons = [];
        var tb = args.treebeard;
        var item = args.item;
        function _uploadEvent(event, item, col) {
            event.stopPropagation();
            tb.dropzone.hiddenFileInput.click();
            tb.dropzoneItemCache = item;
        }
        function dataversePublish(event, item, col) {
            var both = !item.data.dataverseIsPublished;
            var url = item.data.urls.publish;
            var host = item.data.host;
            var toPublish = both ? 'Dataverse and dataset' : 'dataset';
            // Set the modal content to reflect the file's external host
            var modalContent = [
                // for now, only display custom publish text for UVA's dataverse
                m('p.m-md', item.data.host == 'dataverse.lib.virginia.edu' ? item.data.hostCustomPublishText : ''),
                m('p.m-md', both ? 'This dataset cannot be published until the ' + item.data.dataverse + ' Dataverse is published. ' : ''),
                m('p.m-md', 'By publishing this ' + toPublish + ', all content will be made available through ' + host + ' using their internal privacy settings, regardless of your OSF project settings. '),
                m('p.font-thick.m-md', both ? 'Do you want to publish this Dataverse AND this dataset?' : 'Are you sure you want to publish this dataset?')
            ];
            var modalActions =
                [m('button.btn.btn-default', {
                    'onclick': function () {
                        tb.modal.dismiss();
                    }
                }, 'Cancel'),
                m('button.btn.btn-primary', {
                    'onclick': function () {
                        publishDataset();
                    }
                }, 'Publish')];

            tb.modal.update(modalContent, modalActions, m('h3.break-word.modal-title', 'Publish this ' + toPublish + '?'));

            function publishDataset() {
                tb.modal.dismiss();
                item.notify.update('Publishing ' + toPublish, 'info', 1, 1);
                $.osf.putJSON(
                    url,
                    {'publish_both': both}
                ).done(function (data) {
                    item.notify.update();
                    var modalContent = [
                        m('p.m-md', 'Your content has been published.')
                    ];
                    var modalActions = [
                        m('button.btn.btn-primary', {
                            'onclick': function () {
                                tb.modal.dismiss();
                            }
                        }, 'Got it')

                    ];
                    tb.modal.update(modalContent, modalActions, m('h3.break-word.modal-title', 'Successfully published'));
                    item.data.dataverseIsPublished = true;
                    item.data.datasetIsPublished = true;
                    item.data.datasetDraftModified = false;
                    item.data.hasPublishedFiles = item.children.length > 0;
                    item.data.version = item.data.hasPublishedFiles ? 'latest-published' : 'latest';
                    for (var i = 0; i < item.children.length; i++) { // Brute force the child files to be set as "latest-published" without page reload
                        item.children[i].data.extra.datasetVersion = item.data.version;
                    }
                }).fail(function (xhr, status, error) {
                    var statusCode = xhr.responseJSON.code;
                    var message;
                    switch (statusCode) {
                    case 405:
                        message = 'Error: This dataset cannot be published until ' + item.data.dataverse + ' Dataverse is published.';
                        break;
                    case 409:
                        message = 'This dataset version has already been published.';
                        break;
                    default:
                        message = 'Error: Something went wrong when attempting to publish your dataset.';
                        Raven.captureMessage('Could not publish dataset', {
                            extra: {
                                url: url,
                                textStatus: status,
                                error: error
                            }
                        });
                    }

                    var modalContent = [
                        m('p.m-md', message)
                    ];
                    var modalActions = [
                        m('button.btn.btn-primary', {
                            'onclick': function () {
                                tb.modal.dismiss();
                            }
                        }, 'Okay')
                    ];
                    tb.modal.update(modalContent, modalActions);
                });
            }
        }
        if (item.data.addonFullname) {
            var options = [
                m('option', {selected: item.data.version === 'latest', value: 'latest'}, 'Draft')
            ];
            if (item.data.datasetIsPublished) {
                options.push(m('option', {selected: item.data.version === 'latest-published', value: 'latest-published'}, 'Published'));
            }
            buttons.push(
                m.component(Fangorn.Components.dropdown, {
                    'label': 'Version: ',
                    onchange: function (e) {
                        changeState(tb, item, e.target.value);
                    },
                    icon: 'fa fa-external-link',
                    className: 'text-info'
                }, options)
            );
        }
        if (tb.options.placement !== 'fileview') {
            if (item.kind === 'folder' && item.data.addonFullname && item.data.version === 'latest' && item.data.permissions.edit) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            _uploadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-upload',
                        className: 'text-success'
                    }, 'Upload')
                );
                // Only allow the Publish button to appear if the draft dataset is modified
                if(item.data.datasetDraftModified) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                dataversePublish.call(tb, event, item);
                            },
                            icon: 'fa fa-globe',
                            className: 'text-primary'
                        }, 'Publish')
                    );
                }
            } else if (item.kind === 'folder' && !item.data.addonFullname) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            _uploadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-upload',
                        className: 'text-success'
                    }, 'Upload')
                );
            } else if (item.kind === 'file') {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            _downloadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-download',
                        className: 'text-primary'
                    }, 'Download')
                );
                if (item.parent().data.version === 'latest' && item.data.permissions.edit) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                Fangorn.ButtonEvents._removeEvent.call(tb, event, [item]);
                            },
                            icon: 'fa fa-trash',
                            className: 'text-danger'
                        }, 'Delete')
                    );
                }
                if (item.data.permissions && item.data.permissions.view) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function(event) {
                                gotoFile(item);
                            },
                            icon: 'fa fa-external-link',
                            className : 'text-info'
                        }, 'View'));

                }
            }
        }
        return m('span', buttons);
    }
};

function gotoFile (item) {
    var redir = new URI(item.data.nodeUrl);
    window.location = redir
        .segment('files')
        .segment(item.data.provider)
        .segment(item.data.extra.fileId)
        .query({version: item.data.extra.datasetVersion})
        .toString();
}

function _fangornDataverseTitle(item, col) {
    var tb = this;
    if (item.data.isAddonRoot && item.connected === false) { // as opposed to undefined, avoids unnecessary setting of this value
        return Fangorn.Utils.connectCheckTemplate.call(this, item);
    }
    var version = item.data.version === 'latest-published' ? 'Published' : 'Draft';
    if (item.data.addonFullname) {
        var contents = [m('dataverse-name', item.data.name + ' (' + version + ')')];
        if (item.data.hasPublishedFiles) {
            if (item.data.permissions.edit) {
                // Default to version in url parameters for file view page
                var urlParams = $osf.urlParams();
                if (urlParams.version && urlParams.version !== item.data.version) {
                    item.data.version = urlParams.version;
                }
            } else {
                contents.push(
                    m('span.text-muted', '[Published]')
                );
            }
        } else {
            contents.push(
                m('span.text.text-muted', '[Draft]')
            );
        }
        return m('span', contents);
    } else {
        return m('span', [
            m('dataverse-name.fg-file-links', {
                onclick: function () {
                    gotoFile(item);
                }
            }, item.data.name
                )
        ]);
    }
}

function _fangornColumns(item) {
    var tb = this;
    var columns = [];
    columns.push({
        data : 'name',
        folderIcons : true,
        filter : true,
        custom: _fangornDataverseTitle
    });
    if (tb.options.placement === 'project-files') {
        columns.push(
        {
            data  : 'size',
            sortInclude : false,
            filter : false,
            custom : function() {return m('');}
        });
        columns.push(
        {
            data  : 'downloads',
            sortInclude : false,
            filter : false,
            custom : function() {return m('');}
        });
        columns.push({
            data: 'version',
            filter: false,
            sortInclude : false,
            custom: function() {return m('');}
        });
    }
    if(tb.options.placement !== 'fileview') {
        columns.push({
            data : 'modified',
            filter: false,
            custom : function() {return m('');}
        });
    }
    return columns;
}

function _fangornFolderIcons(item) {
    if (item.data.iconUrl) {
        return m('img', {
            src: item.data.iconUrl,
            style: {
                width: '16px',
                height: 'auto'
            }
        }, ' ');
    }
    return undefined;
}

function _fangornLazyLoad(item) {
    return waterbutler.buildTreeBeardMetadata(item, {version: item.data.version});
}

function _canDrop(item) {
    return item.data.provider &&
        item.kind === 'folder' &&
        item.data.permissions.edit &&
        item.data.version === 'latest';
}

Fangorn.config.dataverse = {
    folderIcon: _fangornFolderIcons,
    resolveRows: _fangornColumns,
    lazyload:_fangornLazyLoad,
    canDrop: _canDrop,
    itemButtons: _dataverseItemButtons
};
<commit_msg>Add m.trust() for custom publish text that may contain HTML<commit_after>'use strict';

var m = require('mithril');
var URI = require('URIjs');
var $ = require('jquery');
var Raven = require('raven-js');

var Fangorn = require('js/fangorn').Fangorn;
var waterbutler = require('js/waterbutler');
var $osf = require('js/osfHelpers');

function changeState(grid, item, version) {
    item.data.version = version;
    grid.updateFolder(null, item);
}

function _downloadEvent(event, item, col) {
    event.stopPropagation();
    window.location = waterbutler.buildTreeBeardDownload(item);
}

// Define Fangorn Button Actions
var _dataverseItemButtons = {
    view: function (ctrl, args, children) {
        var buttons = [];
        var tb = args.treebeard;
        var item = args.item;
        function _uploadEvent(event, item, col) {
            event.stopPropagation();
            tb.dropzone.hiddenFileInput.click();
            tb.dropzoneItemCache = item;
        }
        function dataversePublish(event, item, col) {
            var both = !item.data.dataverseIsPublished;
            var url = item.data.urls.publish;
            var host = item.data.host;
            var toPublish = both ? 'Dataverse and dataset' : 'dataset';
            // Set the modal content to reflect the file's external host
            var modalContent = [
                // for now, only display custom publish text for UVA's dataverse
                m('p.m-md', item.data.host == 'dataverse.lib.virginia.edu' ? m.trust(item.data.hostCustomPublishText) : ''),
                m('p.m-md', both ? 'This dataset cannot be published until the ' + item.data.dataverse + ' Dataverse is published. ' : ''),
                m('p.m-md', 'By publishing this ' + toPublish + ', all content will be made available through ' + host + ' using their internal privacy settings, regardless of your OSF project settings. '),
                m('p.font-thick.m-md', both ? 'Do you want to publish this Dataverse AND this dataset?' : 'Are you sure you want to publish this dataset?')
            ];
            var modalActions =
                [m('button.btn.btn-default', {
                    'onclick': function () {
                        tb.modal.dismiss();
                    }
                }, 'Cancel'),
                m('button.btn.btn-primary', {
                    'onclick': function () {
                        publishDataset();
                    }
                }, 'Publish')];

            tb.modal.update(modalContent, modalActions, m('h3.break-word.modal-title', 'Publish this ' + toPublish + '?'));

            function publishDataset() {
                tb.modal.dismiss();
                item.notify.update('Publishing ' + toPublish, 'info', 1, 1);
                $.osf.putJSON(
                    url,
                    {'publish_both': both}
                ).done(function (data) {
                    item.notify.update();
                    var modalContent = [
                        m('p.m-md', 'Your content has been published.')
                    ];
                    var modalActions = [
                        m('button.btn.btn-primary', {
                            'onclick': function () {
                                tb.modal.dismiss();
                            }
                        }, 'Got it')

                    ];
                    tb.modal.update(modalContent, modalActions, m('h3.break-word.modal-title', 'Successfully published'));
                    item.data.dataverseIsPublished = true;
                    item.data.datasetIsPublished = true;
                    item.data.datasetDraftModified = false;
                    item.data.hasPublishedFiles = item.children.length > 0;
                    item.data.version = item.data.hasPublishedFiles ? 'latest-published' : 'latest';
                    for (var i = 0; i < item.children.length; i++) { // Brute force the child files to be set as "latest-published" without page reload
                        item.children[i].data.extra.datasetVersion = item.data.version;
                    }
                }).fail(function (xhr, status, error) {
                    var statusCode = xhr.responseJSON.code;
                    var message;
                    switch (statusCode) {
                    case 405:
                        message = 'Error: This dataset cannot be published until ' + item.data.dataverse + ' Dataverse is published.';
                        break;
                    case 409:
                        message = 'This dataset version has already been published.';
                        break;
                    default:
                        message = 'Error: Something went wrong when attempting to publish your dataset.';
                        Raven.captureMessage('Could not publish dataset', {
                            extra: {
                                url: url,
                                textStatus: status,
                                error: error
                            }
                        });
                    }

                    var modalContent = [
                        m('p.m-md', message)
                    ];
                    var modalActions = [
                        m('button.btn.btn-primary', {
                            'onclick': function () {
                                tb.modal.dismiss();
                            }
                        }, 'Okay')
                    ];
                    tb.modal.update(modalContent, modalActions);
                });
            }
        }
        if (item.data.addonFullname) {
            var options = [
                m('option', {selected: item.data.version === 'latest', value: 'latest'}, 'Draft')
            ];
            if (item.data.datasetIsPublished) {
                options.push(m('option', {selected: item.data.version === 'latest-published', value: 'latest-published'}, 'Published'));
            }
            buttons.push(
                m.component(Fangorn.Components.dropdown, {
                    'label': 'Version: ',
                    onchange: function (e) {
                        changeState(tb, item, e.target.value);
                    },
                    icon: 'fa fa-external-link',
                    className: 'text-info'
                }, options)
            );
        }
        if (tb.options.placement !== 'fileview') {
            if (item.kind === 'folder' && item.data.addonFullname && item.data.version === 'latest' && item.data.permissions.edit) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            _uploadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-upload',
                        className: 'text-success'
                    }, 'Upload')
                );
                // Only allow the Publish button to appear if the draft dataset is modified
                if(item.data.datasetDraftModified) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                dataversePublish.call(tb, event, item);
                            },
                            icon: 'fa fa-globe',
                            className: 'text-primary'
                        }, 'Publish')
                    );
                }
            } else if (item.kind === 'folder' && !item.data.addonFullname) {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            _uploadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-upload',
                        className: 'text-success'
                    }, 'Upload')
                );
            } else if (item.kind === 'file') {
                buttons.push(
                    m.component(Fangorn.Components.button, {
                        onclick: function (event) {
                            _downloadEvent.call(tb, event, item);
                        },
                        icon: 'fa fa-download',
                        className: 'text-primary'
                    }, 'Download')
                );
                if (item.parent().data.version === 'latest' && item.data.permissions.edit) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function (event) {
                                Fangorn.ButtonEvents._removeEvent.call(tb, event, [item]);
                            },
                            icon: 'fa fa-trash',
                            className: 'text-danger'
                        }, 'Delete')
                    );
                }
                if (item.data.permissions && item.data.permissions.view) {
                    buttons.push(
                        m.component(Fangorn.Components.button, {
                            onclick: function(event) {
                                gotoFile(item);
                            },
                            icon: 'fa fa-external-link',
                            className : 'text-info'
                        }, 'View'));

                }
            }
        }
        return m('span', buttons);
    }
};

function gotoFile (item) {
    var redir = new URI(item.data.nodeUrl);
    window.location = redir
        .segment('files')
        .segment(item.data.provider)
        .segment(item.data.extra.fileId)
        .query({version: item.data.extra.datasetVersion})
        .toString();
}

function _fangornDataverseTitle(item, col) {
    var tb = this;
    if (item.data.isAddonRoot && item.connected === false) { // as opposed to undefined, avoids unnecessary setting of this value
        return Fangorn.Utils.connectCheckTemplate.call(this, item);
    }
    var version = item.data.version === 'latest-published' ? 'Published' : 'Draft';
    if (item.data.addonFullname) {
        var contents = [m('dataverse-name', item.data.name + ' (' + version + ')')];
        if (item.data.hasPublishedFiles) {
            if (item.data.permissions.edit) {
                // Default to version in url parameters for file view page
                var urlParams = $osf.urlParams();
                if (urlParams.version && urlParams.version !== item.data.version) {
                    item.data.version = urlParams.version;
                }
            } else {
                contents.push(
                    m('span.text-muted', '[Published]')
                );
            }
        } else {
            contents.push(
                m('span.text.text-muted', '[Draft]')
            );
        }
        return m('span', contents);
    } else {
        return m('span', [
            m('dataverse-name.fg-file-links', {
                onclick: function () {
                    gotoFile(item);
                }
            }, item.data.name
                )
        ]);
    }
}

function _fangornColumns(item) {
    var tb = this;
    var columns = [];
    columns.push({
        data : 'name',
        folderIcons : true,
        filter : true,
        custom: _fangornDataverseTitle
    });
    if (tb.options.placement === 'project-files') {
        columns.push(
        {
            data  : 'size',
            sortInclude : false,
            filter : false,
            custom : function() {return m('');}
        });
        columns.push(
        {
            data  : 'downloads',
            sortInclude : false,
            filter : false,
            custom : function() {return m('');}
        });
        columns.push({
            data: 'version',
            filter: false,
            sortInclude : false,
            custom: function() {return m('');}
        });
    }
    if(tb.options.placement !== 'fileview') {
        columns.push({
            data : 'modified',
            filter: false,
            custom : function() {return m('');}
        });
    }
    return columns;
}

function _fangornFolderIcons(item) {
    if (item.data.iconUrl) {
        return m('img', {
            src: item.data.iconUrl,
            style: {
                width: '16px',
                height: 'auto'
            }
        }, ' ');
    }
    return undefined;
}

function _fangornLazyLoad(item) {
    return waterbutler.buildTreeBeardMetadata(item, {version: item.data.version});
}

function _canDrop(item) {
    return item.data.provider &&
        item.kind === 'folder' &&
        item.data.permissions.edit &&
        item.data.version === 'latest';
}

Fangorn.config.dataverse = {
    folderIcon: _fangornFolderIcons,
    resolveRows: _fangornColumns,
    lazyload:_fangornLazyLoad,
    canDrop: _canDrop,
    itemButtons: _dataverseItemButtons
};
<|endoftext|>


<commit_before>cc.Class({
    extends: cc.Component,

    properties: {
        background: cc.Sprite,
        mapBackground: cc.Sprite,
        labelBackground: cc.Prefab,

        manager: {
            default: null
        },
        tiles: [],
        tile: cc.Prefab,

        tileOriginX: 0,
        tileOriginY: 0,
        tileSpace: 10,

        maxNumLabel: cc.Label,
        describeLabel: cc.Label,
        score: 0,
        scoreLabel: cc.Label,
        bestScore: 0,
        bestScoreLabel: cc.Label,
    },

    // use this for initialization
    onLoad: function () {
        this.setupTiles();

        let storageBestScore = cc.sys.localStorage.getItem('bestScore');
        if (!storageBestScore) {
            storageBestScore = 0;
        }
        this.updateBestScore(storageBestScore);

        this.setupMapBackground();
        this.setupEventListener();
    },

    setTilePosition: function (tile, toRow, toCol) {
        let x = this.tileOriginX + this.tileSpace + toCol * (this.tileSpace + this.manager.tileSize.width);
        let y = this.tileOriginY + this.tileSpace + toRow * (this.tileSpace + this.manager.tileSize.height);
        tile.setPosition(x, y);
        tile.row = toRow;
        tile.col = toCol;
    },

    /**
     * 初始化主地图数据
     */
    setupTiles: function () {
        this.manager = require("Manager");
        if (this.manager.order == 3) {
            this.tiles = [
                [null, null, null],
                [null, null, null],
                [null, null, null]
            ];
            this.maxNumLabel.string = "1024";
            this.describeLabel.string = "Join the numbers\nto get to 1024";
        } else if (this.manager.order == 4) {
            this.tiles = [
                [null, null, null, null],
                [null, null, null, null],
                [null, null, null, null],
                [null, null, null, null]
            ];
            this.maxNumLabel.string = "2048";
            this.describeLabel.string = "Join the numbers\nto get to 2048";
        } else if (this.manager.order == 5) {
            this.tiles = [
                [null, null, null, null, null],
                [null, null, null, null, null],
                [null, null, null, null, null],
                [null, null, null, null, null],
                [null, null, null, null, null]
            ];
            this.maxNumLabel.string = "8192";
            this.describeLabel.string = "Join the numbers\nto get to 8192";
        }

    },

    /**
     * 初始化游戏背景, 左下角是起点
     */
    setupMapBackground: function () {
        this.background.node.color = this.manager.backgroundColor();
        this.mapBackground.node.color = this.manager.scoreBoardColor();

        let labelInstance = cc.instantiate(this.labelBackground);
        this.manager.tileSize.width = labelInstance.width;
        this.manager.tileSize.height = labelInstance.height;

        let rows = this.manager.getRowCount();
        let cols = this.manager.getColCount();

        let mapWidth = (this.manager.tileSize.width + this.tileSpace) * rows + this.tileSpace;
        let mapHeight = (this.manager.tileSize.height + this.tileSpace) * cols + this.tileSpace;
        this.mapBackground.node.width = mapWidth;
        this.mapBackground.node.height = mapHeight;
        this.tileOriginX = -1 * (mapWidth - this.manager.tileSize.width) / 2;
        this.tileOriginY = -1 * (mapHeight - this.manager.tileSize.height) / 2;

        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                let label = cc.instantiate(this.labelBackground);
                this.setTilePosition(label, i, j);
                this.mapBackground.node.addChild(label);
            }
        }

        this.createRandomTile();
        this.createRandomTile();
    },

    /**
     * 初始化系统事件监听
     */
    setupEventListener: function () {
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
    },

    /**
     * 键盘按钮抬起时的事件响应
     * @param event
     */
    onKeyUp: function (event) {
        var isMoved = false;
        switch (event.keyCode) {
            case cc.KEY.up: {
                isMoved = this.moveUp();
                break;
            }
            case cc.KEY.down: {
                isMoved = this.moveDown();
                break;
            }
            case cc.KEY.left: {
                isMoved = this.moveLeft();
                break;
            }
            case cc.KEY.right: {
                isMoved = this.moveRight();
                break;
            }
        }

        if (isMoved) {
            this.createRandomTile();
        }
    },

    /**
     * 增加分数
     */
    addScore: function (add) {
        this.score += add;

        this.scoreLabel.string = this.score.toString();

        if (this.score > this.bestScore) {
            this.updateBestScore(this.score);
        }
    },

    /**
     * 清空分数
     */
    clearScore: function () {
        this.score = 0;

        this.scoreLabel.string = this.score.toString();
    },

    /**
     * 更新最高分数
     * @param newBestScore
     */
    updateBestScore: function (newBestScore) {
        this.bestScore = newBestScore;
        this.bestScoreLabel.string = this.bestScore.toString();

        cc.sys.localStorage.setItem('bestScore', this.bestScore);
    },

    /**
     * restart 按钮的监听
     */
    handleRestart: function () {
        this.setupTiles();
        this.setupMapBackground();

        this.score = 0;
        this.scoreLabel.string = this.score.toString();
    },

    createRandomTile: function () {
        var isCreated = false;

        var count = 0;
        let rows = this.manager.getRowCount();
        let cols = this.manager.getColCount();
        let totalCount = rows * cols;
        var row;
        var col;
        while (true) {
            if (count >= totalCount) {// 格子满了
                break;
            }

            row = Math.floor(Math.random() * rows);
            col = Math.floor(Math.random() * cols);
            if (this.tiles[row][col] == null) {
                var tile = cc.instantiate(this.tile);
                this.tiles[row][col] = tile;
                this.setTilePosition(tile, row, col);
                this.mapBackground.node.addChild(tile);
                isCreated = true;
                break;
            }

            count++;
        }

        return isCreated;
    },

    mergeTiles: function (tile, toTile) {

    },

    moveTilePosition: function (tile, fromRow, fromCol, toRow, toCol) {
        this.tiles[toRow][toCol] = tile;
        this.tiles[fromRow][fromCol] = null;
        this.setTilePosition(tile, toRow, toCol);
    },

    moveUp: function () {
        // return this.moveTile(function (i, j) {
        //     return [3-i, j];
        // }, function (row, col) {
        //     return [(row + 1 >= 4) ? -1 : (row + 1), col];
        // });

        let rowsCount = this.manager.getRowCount();
        let colsCount = this.manager.getColCount();
        return this.moveVertically(colsCount, rowsCount,
            function (fromRow) {
                return (rowsCount - 1 - fromRow);
            }
        );
    },

    moveDown: function () {
        let rowsCount = this.manager.getRowCount();
        let colsCount = this.manager.getColCount();
        return this.moveVertically(colsCount, rowsCount,
            function (fromRow) {
                return fromRow;
            }
        );
    },

    moveLeft: function () {
        let rowsCount = this.manager.getRowCount();
        let colsCount = this.manager.getColCount();
        return this.moveHorizontally(rowsCount, colsCount,
            function (fromCol) {
                return fromCol;
            }
        );
    },

    moveRight: function () {
        let rowsCount = this.manager.getRowCount();
        let colsCount = this.manager.getColCount();
        return this.moveHorizontally(rowsCount, colsCount,
            function (fromCol) {
                return (colsCount - 1 - fromCol);
            }
        );
    },

    //竖向
    moveVertically: function (outerCount, innerCount, getRealRow) {
        let isMoved = false;

        for (var col = 0; col < outerCount; col++) {
            //比较节点
            var tagRow = 0;
            var tagTile = this.tiles[getRealRow(tagRow)][col];

            for (var row = 1; row < innerCount; row++) {
                let realRow = getRealRow(row);
                var tile = this.tiles[realRow][col];
                if (tile == null) {
                    continue;
                }

                if (tagTile == null) {
                    this.moveTilePosition(tile, realRow, col, getRealRow(tagRow), col);
                    tagTile = tile;
                    isMoved = true;
                    continue;
                }

                let tagNode = tagTile.getComponent('Tile');
                let curNode = tile.getComponent('Tile');
                let tmpRow = getRealRow(tagRow + 1);

                if (tagNode.tag != curNode.tag) {
                    if (realRow != tmpRow) {
                        this.moveTilePosition(tile, realRow, col, tmpRow, col);
                        tagRow++;
                        isMoved = true;
                    } else {
                        tagRow = row;
                    }
                    tagTile = tile;
                } else {
                    // 加分
                    let Manager = require("Manager");
                    let addScore = Math.pow(Manager.cardinality, curNode.tag + 1);
                    this.addScore(addScore);

                    // 合并
                    tagNode.tag += 1;
                    tagNode.updateTag();

                    // 删除没有用的节点
                    tile.removeFromParent();
                    this.tiles[realRow][col] = null;

                    //更新比较节点
                    tagRow++;
                    tagTile = this.tiles[getRealRow(tagRow)][col];

                    isMoved = true;
                }

            }
        }

        return isMoved;
    },

    //横向
    moveHorizontally: function (outerCount, innerCount, getRealCol) {
        let isMoved = false;

        for (var row = 0; row < outerCount; row++) {
            //比较节点
            var tagCol = 0;
            var tagTile = this.tiles[row][getRealCol(tagCol)];

            for (var col = 1; col < innerCount; col++) {
                let realCol = getRealCol(col);
                var tile = this.tiles[row][realCol];
                if (tile == null) {
                    continue;
                }

                if (tagTile == null) {
                    this.moveTilePosition(tile, row, realCol, row, getRealCol(tagCol));
                    tagTile = tile;
                    isMoved = true;
                    continue;
                }

                let tagNode = tagTile.getComponent('Tile');
                let curNode = tile.getComponent('Tile');
                let tmpCol = getRealCol(tagCol + 1);

                if (tagNode.tag != curNode.tag) {
                    if (realCol != tmpCol) {
                        this.moveTilePosition(tile, row, realCol, row, tmpCol);
                        tagCol++;
                        isMoved = true;
                    } else {
                        tagCol = col;
                    }
                    tagTile = tile;
                } else {
                    // 加分
                    let Manager = require("Manager");
                    let addScore = Math.pow(Manager.cardinality, curNode.tag + 1);
                    this.addScore(addScore);

                    // 合并
                    tagNode.tag += 1;
                    tagNode.updateTag();

                    // 删除没有用的节点
                    tile.removeFromParent();
                    this.tiles[row][realCol] = null;

                    //更新比较节点
                    tagCol++;
                    tagTile = this.tiles[row][getRealCol(tagCol)];
                    isMoved = true;
                }

            }
        }

        return isMoved;
    },

});
<commit_msg>update<commit_after>cc.Class({
    extends: cc.Component,

    properties: {
        background: cc.Sprite,
        mapBackground: cc.Sprite,
        labelBackground: cc.Prefab,

        manager: {
            default: null
        },
        tiles: [],
        tile: cc.Prefab,

        tileOriginX: 0,
        tileOriginY: 0,
        tileSpace: 10,

        maxNumLabel: cc.Label,
        describeLabel: cc.Label,
        score: 0,
        scoreLabel: cc.Label,
        bestScore: 0,
        bestScoreLabel: cc.Label,
    },

    // use this for initialization
    onLoad: function () {
        this.setupTiles();

        let storageBestScore = cc.sys.localStorage.getItem('bestScore');
        if (!storageBestScore) {
            storageBestScore = 0;
        }
        this.updateBestScore(storageBestScore);

        this.setupMapBackground();
        this.setupEventListener();
    },

    setTilePosition: function (tile, toRow, toCol, animated) {
        let x = this.tileOriginX + this.tileSpace + toCol * (this.tileSpace + this.manager.tileSize.width);
        let y = this.tileOriginY + this.tileSpace + toRow * (this.tileSpace + this.manager.tileSize.height);

        if (animated) {
            let moveTo = cc.moveTo(0.35, cc.p(x, y));
            tile.runAction(moveTo);
        } else {
            tile.setPosition(x, y);
        }

        tile.row = toRow;
        tile.col = toCol;
    },

    /**
     * 初始化主地图数据
     */
    setupTiles: function () {
        this.manager = require("Manager");
        if (this.manager.order == 3) {
            this.tiles = [
                [null, null, null],
                [null, null, null],
                [null, null, null]
            ];
            this.maxNumLabel.string = "1024";
            this.describeLabel.string = "Join the numbers\nto get to 1024";
        } else if (this.manager.order == 4) {
            this.tiles = [
                [null, null, null, null],
                [null, null, null, null],
                [null, null, null, null],
                [null, null, null, null]
            ];
            this.maxNumLabel.string = "2048";
            this.describeLabel.string = "Join the numbers\nto get to 2048";
        } else if (this.manager.order == 5) {
            this.tiles = [
                [null, null, null, null, null],
                [null, null, null, null, null],
                [null, null, null, null, null],
                [null, null, null, null, null],
                [null, null, null, null, null]
            ];
            this.maxNumLabel.string = "8192";
            this.describeLabel.string = "Join the numbers\nto get to 8192";
        }

    },

    /**
     * 初始化游戏背景, 左下角是起点
     */
    setupMapBackground: function () {
        this.background.node.color = this.manager.backgroundColor();
        this.mapBackground.node.color = this.manager.scoreBoardColor();

        let labelInstance = cc.instantiate(this.labelBackground);
        this.manager.tileSize.width = labelInstance.width;
        this.manager.tileSize.height = labelInstance.height;

        let rows = this.manager.getRowCount();
        let cols = this.manager.getColCount();

        let mapWidth = (this.manager.tileSize.width + this.tileSpace) * rows + this.tileSpace;
        let mapHeight = (this.manager.tileSize.height + this.tileSpace) * cols + this.tileSpace;
        this.mapBackground.node.width = mapWidth;
        this.mapBackground.node.height = mapHeight;
        this.tileOriginX = -1 * (mapWidth - this.manager.tileSize.width) / 2;
        this.tileOriginY = -1 * (mapHeight - this.manager.tileSize.height) / 2;

        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                let label = cc.instantiate(this.labelBackground);
                this.setTilePosition(label, i, j, false);
                this.mapBackground.node.addChild(label);
            }
        }

        this.createRandomTile();
        this.createRandomTile();
    },

    /**
     * 初始化系统事件监听
     */
    setupEventListener: function () {
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
    },

    /**
     * 键盘按钮抬起时的事件响应
     * @param event
     */
    onKeyUp: function (event) {
        var isMoved = false;
        switch (event.keyCode) {
            case cc.KEY.up: {
                isMoved = this.moveUp();
                break;
            }
            case cc.KEY.down: {
                isMoved = this.moveDown();
                break;
            }
            case cc.KEY.left: {
                isMoved = this.moveLeft();
                break;
            }
            case cc.KEY.right: {
                isMoved = this.moveRight();
                break;
            }
        }

        if (isMoved) {
            this.createRandomTile();
        }
    },

    /**
     * 增加分数
     */
    addScore: function (add) {
        this.score += add;

        this.scoreLabel.string = this.score.toString();

        if (this.score > this.bestScore) {
            this.updateBestScore(this.score);
        }
    },

    /**
     * 清空分数
     */
    clearScore: function () {
        this.score = 0;

        this.scoreLabel.string = this.score.toString();
    },

    /**
     * 更新最高分数
     * @param newBestScore
     */
    updateBestScore: function (newBestScore) {
        this.bestScore = newBestScore;
        this.bestScoreLabel.string = this.bestScore.toString();

        cc.sys.localStorage.setItem('bestScore', this.bestScore);
    },

    /**
     * restart 按钮的监听
     */
    handleRestart: function () {
        this.setupTiles();
        this.setupMapBackground();

        this.score = 0;
        this.scoreLabel.string = this.score.toString();
    },

    createRandomTile: function () {
        var isCreated = false;

        var count = 0;
        let rows = this.manager.getRowCount();
        let cols = this.manager.getColCount();
        let totalCount = rows * cols;
        var row;
        var col;
        while (true) {
            if (count >= totalCount) {// 格子满了
                break;
            }

            row = Math.floor(Math.random() * rows);
            col = Math.floor(Math.random() * cols);
            if (this.tiles[row][col] == null) {
                var tile = cc.instantiate(this.tile);
                this.tiles[row][col] = tile;
                this.setTilePosition(tile, row, col, false);
                this.mapBackground.node.addChild(tile);
                isCreated = true;
                break;
            }

            count++;
        }

        return isCreated;
    },

    mergeTiles: function (tile, toTile) {

    },

    moveTilePosition: function (tile, fromRow, fromCol, toRow, toCol) {
        this.tiles[toRow][toCol] = tile;
        this.tiles[fromRow][fromCol] = null;
        this.setTilePosition(tile, toRow, toCol, true);
    },

    moveUp: function () {
        // return this.moveTile(function (i, j) {
        //     return [3-i, j];
        // }, function (row, col) {
        //     return [(row + 1 >= 4) ? -1 : (row + 1), col];
        // });

        let rowsCount = this.manager.getRowCount();
        let colsCount = this.manager.getColCount();
        return this.moveVertically(colsCount, rowsCount,
            function (fromRow) {
                return (rowsCount - 1 - fromRow);
            }
        );
    },

    moveDown: function () {
        let rowsCount = this.manager.getRowCount();
        let colsCount = this.manager.getColCount();
        return this.moveVertically(colsCount, rowsCount,
            function (fromRow) {
                return fromRow;
            }
        );
    },

    moveLeft: function () {
        let rowsCount = this.manager.getRowCount();
        let colsCount = this.manager.getColCount();
        return this.moveHorizontally(rowsCount, colsCount,
            function (fromCol) {
                return fromCol;
            }
        );
    },

    moveRight: function () {
        let rowsCount = this.manager.getRowCount();
        let colsCount = this.manager.getColCount();
        return this.moveHorizontally(rowsCount, colsCount,
            function (fromCol) {
                return (colsCount - 1 - fromCol);
            }
        );
    },

    //竖向
    moveVertically: function (outerCount, innerCount, getRealRow) {
        let isMoved = false;

        for (var col = 0; col < outerCount; col++) {
            //比较节点
            var tagRow = 0;
            var tagTile = this.tiles[getRealRow(tagRow)][col];

            for (var row = 1; row < innerCount; row++) {
                let realRow = getRealRow(row);
                var tile = this.tiles[realRow][col];
                if (tile == null) {
                    continue;
                }

                if (tagTile == null) {
                    this.moveTilePosition(tile, realRow, col, getRealRow(tagRow), col);
                    tagTile = tile;
                    isMoved = true;
                    continue;
                }

                let tagNode = tagTile.getComponent('Tile');
                let curNode = tile.getComponent('Tile');
                let tmpRow = getRealRow(tagRow + 1);

                if (tagNode.tag != curNode.tag) {
                    if (realRow != tmpRow) {
                        this.moveTilePosition(tile, realRow, col, tmpRow, col);
                        tagRow++;
                        isMoved = true;
                    } else {
                        tagRow = row;
                    }
                    tagTile = tile;
                } else {
                    // 加分
                    let Manager = require("Manager");
                    let addScore = Math.pow(Manager.cardinality, curNode.tag + 1);
                    this.addScore(addScore);

                    // 合并
                    tagNode.tag += 1;
                    tagNode.updateTag();

                    // 删除没有用的节点
                    tile.removeFromParent();
                    this.tiles[realRow][col] = null;

                    //更新比较节点
                    tagRow++;
                    tagTile = this.tiles[getRealRow(tagRow)][col];

                    isMoved = true;
                }

            }
        }

        return isMoved;
    },

    //横向
    moveHorizontally: function (outerCount, innerCount, getRealCol) {
        let isMoved = false;

        for (var row = 0; row < outerCount; row++) {
            //比较节点
            var tagCol = 0;
            var tagTile = this.tiles[row][getRealCol(tagCol)];

            for (var col = 1; col < innerCount; col++) {
                let realCol = getRealCol(col);
                var tile = this.tiles[row][realCol];
                if (tile == null) {
                    continue;
                }

                if (tagTile == null) {
                    this.moveTilePosition(tile, row, realCol, row, getRealCol(tagCol));
                    tagTile = tile;
                    isMoved = true;
                    continue;
                }

                let tagNode = tagTile.getComponent('Tile');
                let curNode = tile.getComponent('Tile');
                let tmpCol = getRealCol(tagCol + 1);

                if (tagNode.tag != curNode.tag) {
                    if (realCol != tmpCol) {
                        this.moveTilePosition(tile, row, realCol, row, tmpCol);
                        tagCol++;
                        isMoved = true;
                    } else {
                        tagCol = col;
                    }
                    tagTile = tile;
                } else {
                    // 加分
                    let Manager = require("Manager");
                    let addScore = Math.pow(Manager.cardinality, curNode.tag + 1);
                    this.addScore(addScore);

                    // 合并
                    tagNode.tag += 1;
                    tagNode.updateTag();

                    // 删除没有用的节点
                    tile.removeFromParent();
                    this.tiles[row][realCol] = null;

                    //更新比较节点
                    tagCol++;
                    tagTile = this.tiles[row][getRealCol(tagCol)];
                    isMoved = true;
                }

            }
        }

        return isMoved;
    },

});
<|endoftext|>


<commit_before>exports.port = 8848;
exports.directoryIndexes = true;
exports.documentRoot = __dirname;
exports.getLocations = function () {
    return [
        {
            location: /\/$/,
            handler: home( 'index.html' )
        },
        {
            location: /^\/redirect-local/,
            handler: redirect('redirect-target', false)
        },
        {
            location: /^\/redirect-remote/,
            handler: redirect('http://www.baidu.com', false)
        },
        {
            location: /^\/redirect-target/,
            handler: content('redirectd!')
        },
        {
            location: '/empty',
            handler: empty()
        },
        {
            location: /\.css($|\?)/,
            handler: [
                autocss()
            ]
        },
        {
            location: /\.less($|\?)/,
            handler: [
                file(),
                less()
            ]
        },
        {
            location: /\.styl($|\?)/,
            handler: [
                file(),
                stylus()
            ]
        },
        {
            location: /^\/data\//,
            handler: [
                mockup(),
                file()
            ]
        },
        {
            location: /^.*$/,
            handler: [
                file(),
                proxyNoneExists()
            ]
        }
    ];
};

function mockup() {
    return function( context ){
        var pathname = context.request.pathname;
        context.request.pathname = '/src/mockup/' + pathname + '.json';
    }
}

exports.injectResource = function ( res ) {
    for ( var key in res ) {
        global[ key ] = res[ key ];
    }
};
<commit_msg>ecomfe/edp#196<commit_after>function getLocations() {
    return [
        {
            location: /\/$/,
            handler: home( 'index.html' )
        },
        {
            location: /^\/redirect-local/,
            handler: redirect('redirect-target', false)
        },
        {
            location: /^\/redirect-remote/,
            handler: redirect('http://www.baidu.com', false)
        },
        {
            location: /^\/redirect-target/,
            handler: content('redirectd!')
        },
        {
            location: '/empty',
            handler: empty()
        },
        {
            location: /\.css($|\?)/,
            handler: [
                autocss()
            ]
        },
        {
            location: /\.less($|\?)/,
            handler: [
                file(),
                less()
            ]
        },
        {
            location: /\.styl($|\?)/,
            handler: [
                file(),
                stylus()
            ]
        },
        {
            location: /^\/data\//,
            handler: [
                mockup(),
                file()
            ]
        },
        {
            location: /^.*$/,
            handler: [
                file(),
                proxyNoneExists()
            ]
        }
    ];
};

function mockup() {
    return function( context ){
        var pathname = context.request.pathname;
        context.request.pathname = '/src/mockup/' + pathname + '.json';
    }
}

exports.port = 8848;
exports.directoryIndexes = true;
exports.documentRoot = __dirname;
exports.init = function( config, start ){
    config.getLocations = getLocations;
    setTimeout( start, 3000 );
};
exports.injectResource = function ( res ) {
    for ( var key in res ) {
        global[ key ] = res[ key ];
    }
};
<|endoftext|>


<commit_before>/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/reportportal/service-ui
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

define(function (require, exports, module) {
    'use strict';

    var $ = require('jquery');
    var Backbone = require('backbone');
    var Epoxy = require('backbone-epoxy');
    var Util = require('util');
    var Localization = require('localization');

    var SelectDashboardItemView = Epoxy.View.extend({
        className: 'shared-widget-item',
        template: 'tpl-modal-add-shared-widget-item',
        bindings: {
            '[data-js-widget-select]': 'checked: active, disabled: added',
            ':el': 'classes: {"widget-already-added": added}, attr: {title: getAddedTitle}',
            '[data-js-widget-name]': 'text: name',
            '[data-js-gadget-name]': 'html: gadgetName',
            '[data-js-owner-name]': 'text: owner',
            '[data-js-description]': 'text: description'
        },
        computeds: {
            getAddedTitle: {
                deps: ['added'],
                get: function(added){
                    return added ? Localization.wizard.sharedWidgetAdded : '';
                }
            }
        },

        initialize: function(options) {
            this.render();
        },
        render: function() {
            this.$el.html(Util.templates(this.template, {}));
        },
        destroy: function() {
            this.undelegateEvents();
            this.stopListening();
            this.unbind();
            this.$el.remove();
        }
    });

    return SelectDashboardItemView;
});
<commit_msg>Fixed ES-Lint errors.<commit_after>/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/reportportal/service-ui
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

define(function (require) {
    'use strict';

    var Epoxy = require('backbone-epoxy');
    var Util = require('util');
    var Localization = require('localization');

    var SelectDashboardItemView = Epoxy.View.extend({
        className: 'shared-widget-item',
        template: 'tpl-modal-add-shared-widget-item',
        bindings: {
            '[data-js-widget-select]': 'checked: active, disabled: added',
            ':el': 'classes: {"widget-already-added": added}, attr: {title: getAddedTitle}',
            '[data-js-widget-name]': 'text: name',
            '[data-js-gadget-name]': 'html: gadgetName',
            '[data-js-owner-name]': 'text: owner',
            '[data-js-description]': 'text: description'
        },
        computeds: {
            getAddedTitle: {
                deps: ['added'],
                get: function (added) {
                    return added ? Localization.wizard.sharedWidgetAdded : '';
                }
            }
        },

        initialize: function () {
            this.render();
        },
        render: function () {
            this.$el.html(Util.templates(this.template, {}));
        },
        destroy: function () {
            this.undelegateEvents();
            this.stopListening();
            this.unbind();
            this.$el.remove();
        }
    });

    return SelectDashboardItemView;
});
<|endoftext|>


<commit_before>/**
 * Abstractions for how we use Accessibility Developer Tools
 */

function allRuleNames() {
    return axs.AuditRules.getRules().map(rule => rule.name);
}

// Creates an audit configuration that whitelists a single rule and limits the
// amount of tests to run
function createWhitelist(ruleName) {
    var config = new axs.AuditConfiguration();
    config.showUnsupportedRulesWarning = false;

    allRuleNames().forEach((name) => {
        if (name !== ruleName) {
            config.ignoreSelectors(name, "*");
        }
    });

    return config;
}

// Audits for a single rule (by name) and returns the results for only that
// rule
function audit(ruleName) {
    let whitelist = createWhitelist(ruleName);

    return axs.Audit.run(whitelist)
        .filter(result => result.rule.name === ruleName)[0];
}

module.exports = audit;
<commit_msg>automatically ignore tota11y UI elements in our axs audit wrapper<commit_after>/**
 * Abstractions for how we use Accessibility Developer Tools
 */

function allRuleNames() {
    return axs.AuditRules.getRules().map(rule => rule.name);
}

// Creates an audit configuration that whitelists a single rule and limits the
// amount of tests to run
function createWhitelist(ruleName) {
    var config = new axs.AuditConfiguration();
    config.showUnsupportedRulesWarning = false;

    // Ignore elements that are part of the toolbar
    config.ignoreSelectors(ruleName, ".tota11y *");

    allRuleNames().forEach((name) => {
        if (name !== ruleName) {
            config.ignoreSelectors(name, "*");
        }
    });

    return config;
}

// Audits for a single rule (by name) and returns the results for only that
// rule
function audit(ruleName) {
    let whitelist = createWhitelist(ruleName);

    return axs.Audit.run(whitelist)
        .filter(result => result.rule.name === ruleName)[0];
}

module.exports = audit;
<|endoftext|>