<commit_before>$(function () {
	'use strict';
	var is_canceled=false;
	var is_paused=false;
	var data_resume = null;
	$('#start_upload').attr('disabled', true);
	$('#pause_upload').attr('disabled', true);
	$('#resume_upload').attr('disabled', true);
	$('#cancel_upload').attr('disabled', true);

	var authentication = {
			username: chunked_uploads_endpoints.username,
			api_key: chunked_uploads_endpoints.api_key
	}

	$('#fileupload').fileupload({
        url: chunked_uploads_endpoints.upload_url,
	   	dataType: 'json',
	   	maxChunkSize: 1048576,
	    singleFileUploads: false,
	   	maxNumberOfFiles: 1,
	    multipart: false,
	    xhrFields: {
	        withCredentials: true
	    },
	    headers: authentication,
	    add: function (e, data) {
	    	$('#start_upload').attr('disabled', false);

	    	$('#start_upload').one('click', function (e) {
	            e.preventDefault();
	            chunked_uploads_endpoints.jqXHR = data.submit();
	        });
	    },
	    done: function (e, data) {
	    	chunked_uploads_endpoints.done_url = chunked_uploads_endpoints.done_url.replace('00000000-0000-0000-0000-000000000000', data.result[0].upload_uuid);
	    	$.ajax({
	    		type: "POST",
	    		dataType: "json",
	    		headers: authentication,
	    		url: chunked_uploads_endpoints.done_url,
	    		xhrFields: {withCredentials: true},
	    		success: function(current_upload){
	    			if (typeof chunked_uploads_video_url === "function") {
	    				chunked_uploads_video_url(current_upload[0].video_url);
	    			}
	    		}
			});

	        $('#start_upload').hide();
    		$('#pause_upload').hide();
    		$('#resume_upload').hide();
    		$('#cancel_upload').hide();

	    },
	    progressall: function (e, data) {
	    	var progress = parseInt(data.loaded / data.total * 100, 10);
	        $('.progress').css(
	            'width',
	            progress + '%'
	        );
    	},
	    send: function(e, data) {
	    	$("#fileupload").hide();
	    	$('#start_upload').hide();
            $('#pause_upload').attr('disabled', false);
        	$('#cancel_upload').attr('disabled', false);
	    },
	    fail: function(e, data) {
	    	data_resume = data;
	    	if (typeof chunked_uploads_error === "function") {
    			chunked_uploads_error(true);
    		}
	    }
    });

    $('#cancel_upload').click(function (e) {
		if (!is_paused){
			is_canceled = true;
			chunked_uploads_endpoints.jqXHR.abort();
	    	$('#pause_upload').attr('disabled', true);
			$('#resume_upload').attr('disabled', true);
			setTimeout(function() {
				$.ajax({
					  dataType: "json",
					  url: chunked_uploads_endpoints.upload_url,
					  headers: authentication,
					  xhrFields: {withCredentials: true},
					  success: function(current_upload){
						  $.ajax({
			    	    		type: current_upload[0].delete_type,
			    	    		url: current_upload[0].delete_url,
			    	    		headers: authentication,
			    		  });
					  }
				});
			},1000);
		}
		else{
			$.ajax({
				  dataType: "json",
				  url: chunked_uploads_endpoints.upload_url,
				  xhrFields: {withCredentials: true},
				  headers: authentication,
				  success: function(current_upload){
					  $.ajax({
		    	    		type: current_upload[0].delete_type,
		    	    		url: current_upload[0].delete_url,
		    	    		headers: authentication,
		    		  });
				  }
			});
		}
	});

	$('#pause_upload').click(function (e) {
		is_paused = true;
		chunked_uploads_endpoints.jqXHR.abort();
		$('#pause_upload').attr('disabled', true);
		$('#resume_upload').attr('disabled', false);
	});

	$('#resume_upload').click(function (e) {
		is_paused = false;
		$.ajax({
			  dataType: "json",
			  url: chunked_uploads_endpoints.upload_url,
			  headers: authentication,
			  xhrFields: {withCredentials: true},
			  success: function(current_upload){
				  data_resume.uploadedBytes = current_upload[0].size;
				  chunked_uploads_endpoints.jqXHR = data_resume.submit();
			  }
		});
		$('#resume_upload').attr('disabled', true);
		$('#pause_upload').attr('disabled', false);
	});

	if ('onLine' in navigator) {
        //event listener on connection found
		window.addEventListener('online', function(){
    		is_paused = false;
    		$.ajax({
    			  dataType: "json",
    			  url: chunked_uploads_endpoints.upload_url,
    			  headers: authentication,
    			  xhrFields: {withCredentials: true},
    			  success: function(current_upload){
    				  data_resume.uploadedBytes = current_upload[0].size;
    				  chunked_uploads_endpoints.jqXHR = data_resume.submit();
    			  }
    		});
    		$('#resume_upload').attr('disabled', true);
    		$('#pause_upload').attr('disabled', false);
        });

		//event listener on connection lost
        window.addEventListener('offline', function(){
        	if (chunked_uploads_endpoints.jqXHR != null){
	    		is_paused = true;
	    		$('#pause_upload').attr('disabled', true);
	    		$('#resume_upload').attr('disabled', true);
	    		chunked_uploads_endpoints.jqXHR.abort();
        	}
        });
    };

});<commit_msg>add errors callback and comments<commit_after>$(function () {
	'use strict';
	var is_canceled=false;
	var is_paused=false;
	var data_resume = null;
	$('#start_upload').attr('disabled', true);
	$('#pause_upload').attr('disabled', true);
	$('#resume_upload').attr('disabled', true);
	$('#cancel_upload').attr('disabled', true);

	var authentication = {
			username: chunked_uploads_endpoints.username,
			api_key: chunked_uploads_endpoints.api_key
	}

	$('#fileupload').fileupload({
        url: chunked_uploads_endpoints.upload_url,
	   	dataType: 'json',
	   	maxChunkSize: 1048576,
	    singleFileUploads: false,
	   	maxNumberOfFiles: 1,
	    multipart: false,
	    xhrFields: {
	        withCredentials: true
	    },
	    headers: authentication,
	    add: function (e, data) {
	    	$('#start_upload').attr('disabled', false);
	    	$('#start_upload').one('click', function (e) {
	            e.preventDefault();
	            chunked_uploads_endpoints.jqXHR = data.submit();
	        });
	    },
	    start: function (e, data){
	    	if (typeof chunked_uploads_start === "function") {
	    		chunked_uploads_start(true);
			}
	    },
	    done: function (e, data) {
	    	chunked_uploads_endpoints.done_url = chunked_uploads_endpoints.done_url.replace('00000000-0000-0000-0000-000000000000', data.result[0].upload_uuid);
	    	$.ajax({
	    		type: "POST",
	    		dataType: "json",
	    		headers: authentication,
	    		url: chunked_uploads_endpoints.done_url,
	    		xhrFields: {withCredentials: true},
	    		success: function(current_upload){
	    			if (current_upload[0].state=="FAIL"){
	    				if (typeof chunked_uploads_error === "function") {
	    					chunked_uploads_error();
		    			}
	    			}
	    			else{
	    				if (typeof chunked_uploads_video_url === "function") {
		    				chunked_uploads_video_url(current_upload[0].video_url);
		    			}
	    			}
	    		},
	    		error: function(){
	    			if (typeof chunked_uploads_error === "function") {
    					chunked_uploads_error();
	    			}
	    		}
			});

	        $('#start_upload').hide();
    		$('#pause_upload').hide();
    		$('#resume_upload').hide();
    		$('#cancel_upload').hide();

	    },
	    progressall: function (e, data) {
	    	var progress = parseInt(data.loaded / data.total * 100, 10);
	        $('.progress').css(
	            'width',
	            progress + '%'
	        );
    	},
	    send: function(e, data) {
	    	$("#fileupload").hide();
	    	$('#start_upload').hide();
            $('#pause_upload').attr('disabled', false);
        	$('#cancel_upload').attr('disabled', false);
	    },
	    fail: function(e, data) {
	    	data_resume = data;
	    	if (typeof chunked_uploads_error === "function") {
    			chunked_uploads_error();
    		}
	    }
    });

    $('#cancel_upload').click(function (e) {
    	if (!is_paused){
    		//if cancel is clicked during the upload
			is_canceled = true;
			//stop the download
			chunked_uploads_endpoints.jqXHR.abort();
	    	$('#pause_upload').attr('disabled', true);
			$('#resume_upload').attr('disabled', true);
			//wait 1s before sending a DELETE request to the server
			setTimeout(function() {
				$.ajax({
					  dataType: "json",
					  url: chunked_uploads_endpoints.upload_url,
					  headers: authentication,
					  xhrFields: {withCredentials: true},
					  success: function(current_upload){
						  $.ajax({
			    	    		type: current_upload[0].delete_type,
			    	    		url: current_upload[0].delete_url,
			    	    		headers: authentication,
			    		  });
					  }
				});
			},1000);
		}
		else{
			//if cancel is clicked while pause we send the DELETE request
			$.ajax({
				  dataType: "json",
				  url: chunked_uploads_endpoints.upload_url,
				  xhrFields: {withCredentials: true},
				  headers: authentication,
				  success: function(current_upload){
					  $.ajax({
		    	    		type: current_upload[0].delete_type,
		    	    		url: current_upload[0].delete_url,
		    	    		headers: authentication,
		    		  });
				  }
			});
		}
	});

	$('#pause_upload').click(function (e) {
		is_paused = true;
		chunked_uploads_endpoints.jqXHR.abort();
		$('#pause_upload').attr('disabled', true);
		$('#resume_upload').attr('disabled', false);
	});

	$('#resume_upload').click(function (e) {
		is_paused = false;
		$.ajax({
			  dataType: "json",
			  url: chunked_uploads_endpoints.upload_url,
			  headers: authentication,
			  xhrFields: {withCredentials: true},
			  success: function(current_upload){
				  data_resume.uploadedBytes = current_upload[0].size;
				  chunked_uploads_endpoints.jqXHR = data_resume.submit();
			  }
		});
		$('#resume_upload').attr('disabled', true);
		$('#pause_upload').attr('disabled', false);
	});

	//connection listener
	if ('onLine' in navigator) {
        //event listener on connection found
		window.addEventListener('online', function(){
    		is_paused = false;
    		$.ajax({
    			  dataType: "json",
    			  url: chunked_uploads_endpoints.upload_url,
    			  headers: authentication,
    			  xhrFields: {withCredentials: true},
    			  success: function(current_upload){
    				  data_resume.uploadedBytes = current_upload[0].size;
    				  chunked_uploads_endpoints.jqXHR = data_resume.submit();
    			  }
    		});
    		$('#resume_upload').attr('disabled', true);
    		$('#pause_upload').attr('disabled', false);
        });

		//event listener on connection lost
        window.addEventListener('offline', function(){
        	if (chunked_uploads_endpoints.jqXHR != null){
	    		is_paused = true;
	    		$('#pause_upload').attr('disabled', true);
	    		$('#resume_upload').attr('disabled', true);
	    		chunked_uploads_endpoints.jqXHR.abort();
        	}
        });
    };

});<|endoftext|>


<commit_before>import { match } from '@ember/object/computed';
import { assign } from '@ember/polyfills';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { setProperties, computed, set, get } from '@ember/object';
import { addSeconds } from 'date-fns';

const DEFAULTS = {
  token: null,
  rewrap_token: null,
  errors: [],
  wrap_info: null,
  creation_time: null,
  creation_ttl: null,
  data: '{\n}',
  unwrap_data: null,
  details: null,
  wrapTTL: null,
  sum: null,
  random_bytes: null,
  input: null,
};

const WRAPPING_ENDPOINTS = ['lookup', 'wrap', 'unwrap', 'rewrap'];

export default Component.extend(DEFAULTS, {
  store: service(),
  wizard: service(),
  // putting these attrs here so they don't get reset when you click back
  //random
  bytes: 32,
  //hash
  format: 'base64',
  algorithm: 'sha2-256',

  tagName: '',
  unwrapActiveTab: 'data',

  didReceiveAttrs() {
    this._super(...arguments);
    this.checkAction();
  },

  selectedAction: null,

  reset() {
    if (this.isDestroyed || this.isDestroying) {
      return;
    }
    setProperties(this, DEFAULTS);
  },

  checkAction() {
    const currentAction = get(this, 'selectedAction');
    const oldAction = get(this, 'oldSelectedAction');

    if (currentAction !== oldAction) {
      this.reset();
    }
    set(this, 'oldSelectedAction', currentAction);
  },

  dataIsEmpty: match('data', new RegExp(DEFAULTS.data)),

  expirationDate: computed('creation_time', 'creation_ttl', function() {
    const { creation_time, creation_ttl } = this.getProperties('creation_time', 'creation_ttl');
    if (!(creation_time && creation_ttl)) {
      return null;
    }

    return addSeconds(creation_time, creation_ttl);
  }),

  handleError(e) {
    set(this, 'errors', e.errors);
  },

  handleSuccess(resp, action) {
    let props = {};
    let secret = (resp && resp.data) || resp.auth;
    if (secret && action === 'unwrap') {
      let details = {
        'Request ID': resp.request_id,
        'Lease ID': resp.lease_id || 'None',
        Renewable: resp.renewable ? 'Yes' : 'No',
        'Lease Duration': resp.lease_duration || 'None',
      };
      props = assign({}, props, { unwrap_data: secret }, { details: details });
    }
    props = assign({}, props, secret);
    if (resp && resp.wrap_info) {
      const keyName = action === 'rewrap' ? 'rewrap_token' : 'token';
      props = assign({}, props, { [keyName]: resp.wrap_info.token });
    }
    if (props.token || props.rewrap_token || props.unwrap_data || action === 'lookup') {
      this.get('wizard').transitionFeatureMachine(this.get('wizard.featureState'), 'CONTINUE');
    }
    setProperties(this, props);
  },

  getData() {
    const action = get(this, 'selectedAction');
    if (WRAPPING_ENDPOINTS.includes(action)) {
      return get(this, 'dataIsEmpty')
        ? { token: (get(this, 'token') || '').trim() }
        : JSON.parse(get(this, 'data'));
    }
    if (action === 'random') {
      return this.getProperties('bytes');
    }

    if (action === 'hash') {
      return this.getProperties('input', 'format', 'algorithm');
    }
  },

  actions: {
    doSubmit(evt) {
      evt.preventDefault();
      const action = get(this, 'selectedAction');
      const wrapTTL = action === 'wrap' ? get(this, 'wrapTTL') : null;
      const data = this.getData();
      setProperties(this, {
        errors: null,
        wrap_info: null,
        creation_time: null,
        creation_ttl: null,
      });

      get(this, 'store')
        .adapterFor('tools')
        .toolAction(action, data, { wrapTTL })
        .then(resp => this.handleSuccess(resp, action), (...errArgs) => this.handleError(...errArgs));
    },

    onClear() {
      this.reset();
    },

    codemirrorUpdated(val, codemirror) {
      codemirror.performLint();
      const hasErrors = codemirror.state.lint.marked.length > 0;
      setProperties(this, {
        buttonDisabled: hasErrors,
        data: val,
      });
    },
  },
});
<commit_msg>return correct format of random data generator (#5945)<commit_after>import { match } from '@ember/object/computed';
import { assign } from '@ember/polyfills';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { setProperties, computed, set, get } from '@ember/object';
import { addSeconds } from 'date-fns';

const DEFAULTS = {
  token: null,
  rewrap_token: null,
  errors: [],
  wrap_info: null,
  creation_time: null,
  creation_ttl: null,
  data: '{\n}',
  unwrap_data: null,
  details: null,
  wrapTTL: null,
  sum: null,
  random_bytes: null,
  input: null,
};

const WRAPPING_ENDPOINTS = ['lookup', 'wrap', 'unwrap', 'rewrap'];

export default Component.extend(DEFAULTS, {
  store: service(),
  wizard: service(),
  // putting these attrs here so they don't get reset when you click back
  //random
  bytes: 32,
  //hash
  format: 'base64',
  algorithm: 'sha2-256',

  tagName: '',
  unwrapActiveTab: 'data',

  didReceiveAttrs() {
    this._super(...arguments);
    this.checkAction();
  },

  selectedAction: null,

  reset() {
    if (this.isDestroyed || this.isDestroying) {
      return;
    }
    setProperties(this, DEFAULTS);
  },

  checkAction() {
    const currentAction = get(this, 'selectedAction');
    const oldAction = get(this, 'oldSelectedAction');

    if (currentAction !== oldAction) {
      this.reset();
    }
    set(this, 'oldSelectedAction', currentAction);
  },

  dataIsEmpty: match('data', new RegExp(DEFAULTS.data)),

  expirationDate: computed('creation_time', 'creation_ttl', function() {
    const { creation_time, creation_ttl } = this.getProperties('creation_time', 'creation_ttl');
    if (!(creation_time && creation_ttl)) {
      return null;
    }

    return addSeconds(creation_time, creation_ttl);
  }),

  handleError(e) {
    set(this, 'errors', e.errors);
  },

  handleSuccess(resp, action) {
    let props = {};
    let secret = (resp && resp.data) || resp.auth;
    if (secret && action === 'unwrap') {
      let details = {
        'Request ID': resp.request_id,
        'Lease ID': resp.lease_id || 'None',
        Renewable: resp.renewable ? 'Yes' : 'No',
        'Lease Duration': resp.lease_duration || 'None',
      };
      props = assign({}, props, { unwrap_data: secret }, { details: details });
    }
    props = assign({}, props, secret);
    if (resp && resp.wrap_info) {
      const keyName = action === 'rewrap' ? 'rewrap_token' : 'token';
      props = assign({}, props, { [keyName]: resp.wrap_info.token });
    }
    if (props.token || props.rewrap_token || props.unwrap_data || action === 'lookup') {
      this.get('wizard').transitionFeatureMachine(this.get('wizard.featureState'), 'CONTINUE');
    }
    setProperties(this, props);
  },

  getData() {
    const action = get(this, 'selectedAction');
    if (WRAPPING_ENDPOINTS.includes(action)) {
      return get(this, 'dataIsEmpty')
        ? { token: (get(this, 'token') || '').trim() }
        : JSON.parse(get(this, 'data'));
    }
    if (action === 'random') {
      return this.getProperties('bytes', 'format');
    }

    if (action === 'hash') {
      return this.getProperties('input', 'format', 'algorithm');
    }
  },

  actions: {
    doSubmit(evt) {
      evt.preventDefault();
      const action = get(this, 'selectedAction');
      const wrapTTL = action === 'wrap' ? get(this, 'wrapTTL') : null;
      const data = this.getData();
      setProperties(this, {
        errors: null,
        wrap_info: null,
        creation_time: null,
        creation_ttl: null,
      });

      get(this, 'store')
        .adapterFor('tools')
        .toolAction(action, data, { wrapTTL })
        .then(resp => this.handleSuccess(resp, action), (...errArgs) => this.handleError(...errArgs));
    },

    onClear() {
      this.reset();
    },

    codemirrorUpdated(val, codemirror) {
      codemirror.performLint();
      const hasErrors = codemirror.state.lint.marked.length > 0;
      setProperties(this, {
        buttonDisabled: hasErrors,
        data: val,
      });
    },
  },
});
<|endoftext|>


<commit_before>function createSourceLinks() {
    $('.method_details_list .source_code').
        before("[View source]");
    $('.toggleSource').toggle(function() {
       $(this).parent().next().slideDown(100);
       $(this).text("Hide source");
    },
    function() {
        $(this).parent().next().slideUp(100);
        $(this).text("View source");
    });
}

function createDefineLinks() {
    var tHeight = 0;
    $('.defines').after(" more...");
    $('.toggleDefines').toggle(function() {
        tHeight = $(this).parent().prev().height();
        $(this).prev().show();
        $(this).parent().prev().height($(this).parent().height());
        $(this).text("(less)");
    },
    function() {
        $(this).prev().hide();
        $(this).parent().prev().height(tHeight);
        $(this).text("more...")
    });
}

function createFullTreeLinks() {
    var tHeight = 0;
    $('.inheritanceTree').toggle(function() {
        tHeight = $(this).parent().prev().height();
        $(this).prev().prev().hide();
        $(this).prev().show();
        $(this).text("(hide)");
        $(this).parent().prev().height($(this).parent().height());
    },
    function() {
        $(this).prev().prev().show();
        $(this).prev().hide();
        $(this).parent().prev().height(tHeight);
        $(this).text("show all")
    });
}

function fixBoxInfoHeights() {
    $('dl.box dd.r1, dl.box dd.r2').each(function() {
       $(this).prev().height($(this).height());
    });
}

function searchFrameLinks() {
  $('#method_list_link').click(function() {
    toggleSearchFrame(this, relpath + 'method_list.html');
  });

  $('#class_list_link').click(function() {
    toggleSearchFrame(this, relpath + 'class_list.html');
  });

  $('#file_list_link').click(function() {
    toggleSearchFrame(this, relpath + 'file_list.html');
  });
}

function toggleSearchFrame(id, link) {
  var frame = $('#search_frame');
  $('#search a').removeClass('active').addClass('inactive');
  if (frame.attr('src') == link && frame.css('display') != "none") {
    frame.slideUp(100);
    $('#search a').removeClass('active inactive');
  }
  else {
    $(id).addClass('active').removeClass('inactive');
    frame.attr('src', link).slideDown(100);
  }
}

function linkSummaries() {
  $('.summary_signature').click(function() {
    document.location = $(this).find('a').attr('href');
  });
}

function framesInit() {
  if (window.top.frames.main) {
    document.body.className = 'frames';
    $('#menu .noframes a').attr('href', document.location);
    $('html head title', window.parent.document).text($('html head title').text());
  }
}

function keyboardShortcuts() {
  if (window.top.frames.main) return;
  $(document).keypress(function(evt) {
    if (evt.altKey || evt.ctrlKey || evt.metaKey || evt.shiftKey) return;
    if (evt.originalTarget.nodeName == "INPUT" ||
        evt.originalTarget.nodeName == "TEXTAREA") return;
    switch (evt.charCode) {
      case 67: case 99:  $('#class_list_link').click(); break;  // 'c'
      case 77: case 109: $('#method_list_link').click(); break; // 'm'
      case 70: case 102: $('#file_list_link').click(); break;   // 'f'
    }
  });
}

function summaryToggle() {
  $('.summary_toggle').click(function() {
    localStorage.summaryCollapsed = $(this).text();
    $(this).text($(this).text() == "collapse" ? "expand" : "collapse");
    var next = $(this).parent().parent().next();
    if (next.hasClass('compact')) {
      next.toggle();
      next.next().toggle();
    }
    else if (next.hasClass('summary')) {
      var list = $('
');
      list.html(next.html());
      list.find('.summary_desc, .note').remove();
      list.find('a').each(function() {
        $(this).html($(this).find('strong').html());
        $(this).parent().html($(this)[0].outerHTML);
      });
      next.before(list);
      next.toggle();
    }
    return false;
  });
  if (localStorage) {
    if (localStorage.summaryCollapsed == "collapse") $('.summary_toggle').click();
    else localStorage.summaryCollapsed = "expand";
  }
}

function fixOutsideWorldLinks() {
  $('a').each(function() {
    if (window.location.host != this.host) this.target = '_parent';
  });
}

function generateTOC() {
  if ($('#filecontents').length == 0) return;
  var _toc = $('

');
  var show = false;
  var toc = _toc;
  var counter = 0;
  var tags = ['h2', 'h3', 'h4', 'h5', 'h6'];
  if ($('#filecontents h1').length > 1) tags.unshift('h1');
  for (i in tags) { tags[i] = '#filecontents ' + tags[i] }
  var lastTag = parseInt(tags[0][1]);
  $(tags.join(', ')).each(function() {
    if (this.id == "filecontents") return;
    show = true;
    var thisTag = parseInt(this.tagName[1]);
    if (this.id.length == 0) this.id = "__toc__section" + (counter++);
    if (thisTag > lastTag) {
      for (var i = 0; i < thisTag - lastTag; i++) {
        var tmp = $('
'); toc.append(tmp); toc = tmp;
      }
    }
    if (thisTag < lastTag) {
      for (var i = 0; i < lastTag - thisTag; i++) toc = toc.parent();
    }
    toc.append('
' + $(this).text() + '
');
    lastTag = thisTag;
  });
  if (!show) return;
  html = '

Table of Contents (left)

';
  $('#content').prepend(html);
  $('#toc').append(_toc);
  $('#toc .hide_toc').toggle(function() {
    $('#toc .top').slideUp('fast');
    $('#toc').toggleClass('hidden');
    $('#toc .title small').toggle();
  }, function() {
    $('#toc .top').slideDown('fast');
    $('#toc').toggleClass('hidden');
    $('#toc .title small').toggle();
  });
  $('#toc .float_toc').toggle(function() {
    $(this).text('float');
    $('#toc').toggleClass('nofloat');
  }, function() {
    $(this).text('left')
    $('#toc').toggleClass('nofloat');
  });
}

$(framesInit);
$(createSourceLinks);
$(createDefineLinks);
$(createFullTreeLinks);
$(fixBoxInfoHeights);
$(searchFrameLinks);
$(linkSummaries);
$(keyboardShortcuts);
$(summaryToggle);
$(fixOutsideWorldLinks);
$(generateTOC);<commit_msg>Change TOC anchor links to use pretty anchors<commit_after>function createSourceLinks() {
    $('.method_details_list .source_code').
        before("[View source]");
    $('.toggleSource').toggle(function() {
       $(this).parent().next().slideDown(100);
       $(this).text("Hide source");
    },
    function() {
        $(this).parent().next().slideUp(100);
        $(this).text("View source");
    });
}

function createDefineLinks() {
    var tHeight = 0;
    $('.defines').after(" more...");
    $('.toggleDefines').toggle(function() {
        tHeight = $(this).parent().prev().height();
        $(this).prev().show();
        $(this).parent().prev().height($(this).parent().height());
        $(this).text("(less)");
    },
    function() {
        $(this).prev().hide();
        $(this).parent().prev().height(tHeight);
        $(this).text("more...")
    });
}

function createFullTreeLinks() {
    var tHeight = 0;
    $('.inheritanceTree').toggle(function() {
        tHeight = $(this).parent().prev().height();
        $(this).prev().prev().hide();
        $(this).prev().show();
        $(this).text("(hide)");
        $(this).parent().prev().height($(this).parent().height());
    },
    function() {
        $(this).prev().prev().show();
        $(this).prev().hide();
        $(this).parent().prev().height(tHeight);
        $(this).text("show all")
    });
}

function fixBoxInfoHeights() {
    $('dl.box dd.r1, dl.box dd.r2').each(function() {
       $(this).prev().height($(this).height());
    });
}

function searchFrameLinks() {
  $('#method_list_link').click(function() {
    toggleSearchFrame(this, relpath + 'method_list.html');
  });

  $('#class_list_link').click(function() {
    toggleSearchFrame(this, relpath + 'class_list.html');
  });

  $('#file_list_link').click(function() {
    toggleSearchFrame(this, relpath + 'file_list.html');
  });
}

function toggleSearchFrame(id, link) {
  var frame = $('#search_frame');
  $('#search a').removeClass('active').addClass('inactive');
  if (frame.attr('src') == link && frame.css('display') != "none") {
    frame.slideUp(100);
    $('#search a').removeClass('active inactive');
  }
  else {
    $(id).addClass('active').removeClass('inactive');
    frame.attr('src', link).slideDown(100);
  }
}

function linkSummaries() {
  $('.summary_signature').click(function() {
    document.location = $(this).find('a').attr('href');
  });
}

function framesInit() {
  if (window.top.frames.main) {
    document.body.className = 'frames';
    $('#menu .noframes a').attr('href', document.location);
    $('html head title', window.parent.document).text($('html head title').text());
  }
}

function keyboardShortcuts() {
  if (window.top.frames.main) return;
  $(document).keypress(function(evt) {
    if (evt.altKey || evt.ctrlKey || evt.metaKey || evt.shiftKey) return;
    if (evt.originalTarget.nodeName == "INPUT" ||
        evt.originalTarget.nodeName == "TEXTAREA") return;
    switch (evt.charCode) {
      case 67: case 99:  $('#class_list_link').click(); break;  // 'c'
      case 77: case 109: $('#method_list_link').click(); break; // 'm'
      case 70: case 102: $('#file_list_link').click(); break;   // 'f'
    }
  });
}

function summaryToggle() {
  $('.summary_toggle').click(function() {
    localStorage.summaryCollapsed = $(this).text();
    $(this).text($(this).text() == "collapse" ? "expand" : "collapse");
    var next = $(this).parent().parent().next();
    if (next.hasClass('compact')) {
      next.toggle();
      next.next().toggle();
    }
    else if (next.hasClass('summary')) {
      var list = $('
');
      list.html(next.html());
      list.find('.summary_desc, .note').remove();
      list.find('a').each(function() {
        $(this).html($(this).find('strong').html());
        $(this).parent().html($(this)[0].outerHTML);
      });
      next.before(list);
      next.toggle();
    }
    return false;
  });
  if (localStorage) {
    if (localStorage.summaryCollapsed == "collapse") $('.summary_toggle').click();
    else localStorage.summaryCollapsed = "expand";
  }
}

function fixOutsideWorldLinks() {
  $('a').each(function() {
    if (window.location.host != this.host) this.target = '_parent';
  });
}

function generateTOC() {
  if ($('#filecontents').length == 0) return;
  var _toc = $('

');
  var show = false;
  var toc = _toc;
  var counter = 0;
  var tags = ['h2', 'h3', 'h4', 'h5', 'h6'];
  if ($('#filecontents h1').length > 1) tags.unshift('h1');
  for (i in tags) { tags[i] = '#filecontents ' + tags[i] }
  var lastTag = parseInt(tags[0][1]);
  $(tags.join(', ')).each(function() {
    if (this.id == "filecontents") return;
    show = true;
    var thisTag = parseInt(this.tagName[1]);
    if (this.id.length == 0) {
      var proposedId = $(this).text().replace(/[^a-z]/ig, '_');
      if ($('#' + proposedId).length > 0) proposedId += counter++;
      this.id = proposedId;
    }
    if (thisTag > lastTag) {
      for (var i = 0; i < thisTag - lastTag; i++) {
        var tmp = $('
'); toc.append(tmp); toc = tmp;
      }
    }
    if (thisTag < lastTag) {
      for (var i = 0; i < lastTag - thisTag; i++) toc = toc.parent();
    }
    toc.append('
' + $(this).text() + '
');
    lastTag = thisTag;
  });
  if (!show) return;
  html = '

Table of Contents (left)

';
  $('#content').prepend(html);
  $('#toc').append(_toc);
  $('#toc .hide_toc').toggle(function() {
    $('#toc .top').slideUp('fast');
    $('#toc').toggleClass('hidden');
    $('#toc .title small').toggle();
  }, function() {
    $('#toc .top').slideDown('fast');
    $('#toc').toggleClass('hidden');
    $('#toc .title small').toggle();
  });
  $('#toc .float_toc').toggle(function() {
    $(this).text('float');
    $('#toc').toggleClass('nofloat');
  }, function() {
    $(this).text('left')
    $('#toc').toggleClass('nofloat');
  });
}

$(framesInit);
$(createSourceLinks);
$(createDefineLinks);
$(createFullTreeLinks);
$(fixBoxInfoHeights);
$(searchFrameLinks);
$(linkSummaries);
$(keyboardShortcuts);
$(summaryToggle);
$(fixOutsideWorldLinks);
$(generateTOC);<|endoftext|>


<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

// jshint esversion: 6
// jshint strict: global

'use strict';

// This gulpfile makes use of new JavaScript features.
// Babel handles this without us having to do anything. It just works.
// You can read more about the new JavaScript features here:
// https://babeljs.io/docs/learn-es2015/

import path from 'path';
import gulp from 'gulp';
import del from 'del';
import {Server} from 'karma';
import runSequence from 'run-sequence';
import browserify from 'browserify';
import babelify from 'babelify';
import source from 'vinyl-source-stream';
import browserSync from 'browser-sync';
import swPrecache from 'sw-precache';
import gulpLoadPlugins from 'gulp-load-plugins';
import {output as pagespeed} from 'psi';
import pkg from './package.json';

const $ = gulpLoadPlugins();
const bs = browserSync.create();
const babelOptions = {
	presets: ['es2015']
};

// Lint JavaScript
gulp.task('lint', () =>
  gulp.src('app/scripts/**/*.js')
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.if(!bs.active, $.eslint.failOnError()))
);

// Optimize images
gulp.task('images', () => {
  gulp.src('app/images/**/*')
    .pipe($.imagemin({ // DEBUG removed $.cache( before imagemin
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));

		gulp.src('../third_party/images/**/*')
			.pipe($.imagemin({ // DEBUG removed $.cache( before imagemin
				progressive: true,
				interlaced: true
			}))
			.pipe(gulp.dest('dist/images'))
			.pipe($.size({title: 'product images'}))
}

);

// Copy all files at the root level (app)
gulp.task('copy', () =>
  gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}))
);

// Compile and automatically prefix stylesheets
gulp.task('styles', () => {
  const AUTOPREFIXER_BROWSERS = [
    'ie >= 10',
    'ie_mob >= 10',
    'ff >= 30',
    'chrome >= 34',
    'safari >= 7',
    'opera >= 23',
    'ios >= 7',
    'android >= 4.4',
    'bb >= 10'
  ];

  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
    'app/styles/**/*.scss',
    'app/styles/**/*.css'
  ])
    .pipe($.newer('.tmp/styles'))
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      precision: 10
    }).on('error', $.sass.logError))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate and minify styles
    .pipe($.if('*.css', $.cssnano()))
    .pipe($.size({title: 'styles'}))
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest('dist/styles'));
});

gulp.task('scripts', () => {
  return browserify([
    './app/scripts/main.js'
  ], { debug: true, paths: ['app/scripts/modules/'] })
    .transform(babelify, { presets: ['es2015']  })
    .bundle()
    .pipe(source('main.min.js'))
    .on('error', err => { console.log('ERROR:', err.message); })
    .pipe(gulp.dest('dist/scripts/'));
});

// Scan your HTML for assets & optimize them
gulp.task('html', () => {
  return gulp.src('app/**/*.html')
    .pipe($.useref({
      searchPath: '{.tmp,app}',
      noAssets: true
    }))

    // Minify any HTML
    .pipe($.if('*.html', $.htmlmin({
      removeComments: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeRedundantAttributes: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true,
      removeOptionalTags: true
    })))
    // Output files
    .pipe($.if('*.html', $.size({title: 'html', showFiles: true})))
    .pipe(gulp.dest('dist'));
});

// Clean output directory
gulp.task('clean', () => del(['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Run unit tests
gulp.task('test', (done) => {
  new Server({
    configFile: __dirname + '/tests/test-all.conf.js',
    singleRun: true
  }, done).start();
});

// Build and serve the output from the dist build
gulp.task('serve', ['default'], () =>
  bs.init({
    notify: false,
    logPrefix: 'WSK',
    // Allow scroll syncing across breakpoints
    scrollElementMapping: ['main', '.mdl-layout'],
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist',
    port: 3001,
		// Implement a simple server running at /checkout.
		// This logs the form data and returns a dummy payment response.
		middleware: [(req, res, next) => {
			const url = require('url');
			const parseBody = require('body/form');
    	let urlObj = url.parse(req.url, true),
        method = req.method;
		  if (method !== 'POST' || urlObj.path !== '/checkout' ) {
				next();
			} else {
			  parseBody(req, (err, text) => {
					if (err) {
						res.status = 500;
						res.end('Failed with error ' + err);
					} else {
						console.log(text);
						res.writeHead(200, {'Content-Type': 'application/json'});
						// A successful payment request always returns a provider-specific
						// JSON object. We're looknig for "success" in the code later.
						res.end('{"success": true, "id": 12345}');
					}
				});
			}
    }]
  })
);

// Build production files, the default task
gulp.task('default', ['clean'], cb =>
  runSequence(
    'styles',
    ['html', 'scripts', 'images', 'copy'],
    // ['lint', 'html', 'scripts', 'images', 'copy'],
    'generate-service-worker',
    cb
  )
);

// Run PageSpeed Insights
gulp.task('pagespeed', cb =>
  // Update the below URL to the public URL of your site
  pagespeed('example.com', {
    strategy: 'mobile'
    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, cb)
);

// Copy over the scripts that are used in importScripts as part of the generate-service-worker task.
gulp.task('copy-sw-scripts', () => {
  return gulp.src(['node_modules/sw-toolbox/sw-toolbox.js', 'app/scripts/sw/runtime-caching.js'])
    .pipe(gulp.dest('dist/scripts/sw'));
});

// See http://www.html5rocks.com/en/tutorials/service-worker/introduction/ for
// an in-depth explanation of what service workers are and why you should care.
// Generate a service worker file that will provide offline functionality for
// local resources. This should only be done for the 'dist' directory, to allow
// live reload to work as expected when serving from the 'app' directory.
gulp.task('generate-service-worker', ['copy-sw-scripts'], () => {
  const rootDir = 'dist';
  const filepath = path.join(rootDir, 'service-worker.js');

  return swPrecache.write(filepath, {
    // Used to avoid cache conflicts when serving on localhost.
    cacheId: pkg.name || 'modern-furniture-store',
    // sw-toolbox.js needs to be listed first. It sets up methods used in runtime-caching.js.
    importScripts: [
      'scripts/sw/sw-toolbox.js',
      'scripts/sw/runtime-caching.js'
    ],
    staticFileGlobs: [
      // Add/remove glob patterns to match your directory setup.
      `${rootDir}/images/**/*`,
      `${rootDir}/scripts/**/*.js`,
      `${rootDir}/styles/**/*.css`,
      `${rootDir}/*.{html,json}`
    ],
    // Translates a static file path to the relative URL that it's served from.
    // This is '/' rather than path.sep because the paths returned from
    // glob always use '/'.
    stripPrefix: rootDir + '/',
		// Escape to sw-toolbox to handle non-local files
		runtimeCaching: [{
  		urlPattern: /^https:\/\/code\.getmdl\.io\//,
  		handler: 'networkFirst'
		}],

  });
});

// Load custom tasks from the `tasks` directory
// Run: `npm install --save-dev require-dir` from the command-line
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
<commit_msg>Update for new test config location<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2015 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

// jshint esversion: 6
// jshint strict: global

'use strict';

// This gulpfile makes use of new JavaScript features.
// Babel handles this without us having to do anything. It just works.
// You can read more about the new JavaScript features here:
// https://babeljs.io/docs/learn-es2015/

import path from 'path';
import gulp from 'gulp';
import del from 'del';
import {Server} from 'karma';
import runSequence from 'run-sequence';
import browserify from 'browserify';
import babelify from 'babelify';
import source from 'vinyl-source-stream';
import browserSync from 'browser-sync';
import swPrecache from 'sw-precache';
import gulpLoadPlugins from 'gulp-load-plugins';
import {output as pagespeed} from 'psi';
import pkg from './package.json';

const $ = gulpLoadPlugins();
const bs = browserSync.create();
const babelOptions = {
	presets: ['es2015']
};

// Lint JavaScript
gulp.task('lint', () =>
  gulp.src('app/scripts/**/*.js')
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.if(!bs.active, $.eslint.failOnError()))
);

// Optimize images
gulp.task('images', () => {
  gulp.src('app/images/**/*')
    .pipe($.imagemin({ // DEBUG removed $.cache( before imagemin
      progressive: true,
      interlaced: true
    }))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));

		gulp.src('../third_party/images/**/*')
			.pipe($.imagemin({ // DEBUG removed $.cache( before imagemin
				progressive: true,
				interlaced: true
			}))
			.pipe(gulp.dest('dist/images'))
			.pipe($.size({title: 'product images'}))
}

);

// Copy all files at the root level (app)
gulp.task('copy', () =>
  gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}))
);

// Compile and automatically prefix stylesheets
gulp.task('styles', () => {
  const AUTOPREFIXER_BROWSERS = [
    'ie >= 10',
    'ie_mob >= 10',
    'ff >= 30',
    'chrome >= 34',
    'safari >= 7',
    'opera >= 23',
    'ios >= 7',
    'android >= 4.4',
    'bb >= 10'
  ];

  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
    'app/styles/**/*.scss',
    'app/styles/**/*.css'
  ])
    .pipe($.newer('.tmp/styles'))
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      precision: 10
    }).on('error', $.sass.logError))
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate and minify styles
    .pipe($.if('*.css', $.cssnano()))
    .pipe($.size({title: 'styles'}))
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest('dist/styles'));
});

gulp.task('scripts', () => {
  return browserify([
    './app/scripts/main.js'
  ], { debug: true, paths: ['app/scripts/modules/'] })
    .transform(babelify, { presets: ['es2015']  })
    .bundle()
    .pipe(source('main.min.js'))
    .on('error', err => { console.log('ERROR:', err.message); })
    .pipe(gulp.dest('dist/scripts/'));
});

// Scan your HTML for assets & optimize them
gulp.task('html', () => {
  return gulp.src('app/**/*.html')
    .pipe($.useref({
      searchPath: '{.tmp,app}',
      noAssets: true
    }))

    // Minify any HTML
    .pipe($.if('*.html', $.htmlmin({
      removeComments: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeAttributeQuotes: true,
      removeRedundantAttributes: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true,
      removeOptionalTags: true
    })))
    // Output files
    .pipe($.if('*.html', $.size({title: 'html', showFiles: true})))
    .pipe(gulp.dest('dist'));
});

// Clean output directory
gulp.task('clean', () => del(['.tmp', 'dist/*', '!dist/.git'], {dot: true}));

// Run unit tests
gulp.task('test', (done) => {
  new Server({
    configFile: __dirname + '/test-all.conf.js',
    singleRun: true
  }, done).start();
});

// Build and serve the output from the dist build
gulp.task('serve', ['default'], () =>
  bs.init({
    notify: false,
    logPrefix: 'WSK',
    // Allow scroll syncing across breakpoints
    scrollElementMapping: ['main', '.mdl-layout'],
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: 'dist',
    port: 3001,
		// Implement a simple server running at /checkout.
		// This logs the form data and returns a dummy payment response.
		middleware: [(req, res, next) => {
			const url = require('url');
			const parseBody = require('body/form');
    	let urlObj = url.parse(req.url, true),
        method = req.method;
		  if (method !== 'POST' || urlObj.path !== '/checkout' ) {
				next();
			} else {
			  parseBody(req, (err, text) => {
					if (err) {
						res.status = 500;
						res.end('Failed with error ' + err);
					} else {
						console.log(text);
						res.writeHead(200, {'Content-Type': 'application/json'});
						// A successful payment request always returns a provider-specific
						// JSON object. We're looknig for "success" in the code later.
						res.end('{"success": true, "id": 12345}');
					}
				});
			}
    }]
  })
);

// Build production files, the default task
gulp.task('default', ['clean'], cb =>
  runSequence(
    'styles',
    ['html', 'scripts', 'images', 'copy'],
    // ['lint', 'html', 'scripts', 'images', 'copy'],
    'generate-service-worker',
    cb
  )
);

// Run PageSpeed Insights
gulp.task('pagespeed', cb =>
  // Update the below URL to the public URL of your site
  pagespeed('example.com', {
    strategy: 'mobile'
    // By default we use the PageSpeed Insights free (no API key) tier.
    // Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
    // key: 'YOUR_API_KEY'
  }, cb)
);

// Copy over the scripts that are used in importScripts as part of the generate-service-worker task.
gulp.task('copy-sw-scripts', () => {
  return gulp.src(['node_modules/sw-toolbox/sw-toolbox.js', 'app/scripts/sw/runtime-caching.js'])
    .pipe(gulp.dest('dist/scripts/sw'));
});

// See http://www.html5rocks.com/en/tutorials/service-worker/introduction/ for
// an in-depth explanation of what service workers are and why you should care.
// Generate a service worker file that will provide offline functionality for
// local resources. This should only be done for the 'dist' directory, to allow
// live reload to work as expected when serving from the 'app' directory.
gulp.task('generate-service-worker', ['copy-sw-scripts'], () => {
  const rootDir = 'dist';
  const filepath = path.join(rootDir, 'service-worker.js');

  return swPrecache.write(filepath, {
    // Used to avoid cache conflicts when serving on localhost.
    cacheId: pkg.name || 'modern-furniture-store',
    // sw-toolbox.js needs to be listed first. It sets up methods used in runtime-caching.js.
    importScripts: [
      'scripts/sw/sw-toolbox.js',
      'scripts/sw/runtime-caching.js'
    ],
    staticFileGlobs: [
      // Add/remove glob patterns to match your directory setup.
      `${rootDir}/images/**/*`,
      `${rootDir}/scripts/**/*.js`,
      `${rootDir}/styles/**/*.css`,
      `${rootDir}/*.{html,json}`
    ],
    // Translates a static file path to the relative URL that it's served from.
    // This is '/' rather than path.sep because the paths returned from
    // glob always use '/'.
    stripPrefix: rootDir + '/',
		// Escape to sw-toolbox to handle non-local files
		runtimeCaching: [{
  		urlPattern: /^https:\/\/code\.getmdl\.io\//,
  		handler: 'networkFirst'
		}],

  });
});

// Load custom tasks from the `tasks` directory
// Run: `npm install --save-dev require-dir` from the command-line
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
<|endoftext|>


<commit_before>'use strict';

/* Directives */
angular.module('openAwesome.directives', []);
angular.module('openAwesome.directives').directive('dynatable', function () {
    return {
        scope: {
            dynatable: '='
        },
        link: function (scope, element) {
//            function osNameWriter(column, record) {
//                if (column.id === 'hostname') {
//                    return '' + record[column.id] + '	';
//                }
//                else if (column.id === 'os_name' && angular.isDefined(record.icon)) {
//                    return '	';
//                }
//                return '' + record[column.id] + '	';
//            }

            element.dynatable({
//                writers: {
//                    _cellWriter: osNameWriter
//                },
                features: {
                    sort: false,
                    pushState: false,
                    paginate: false,
                    recordCount: false,
                    search: false
                },
                table: {
                    defaultColumnIdStyle: 'underscore'
                },
                dataset: {
//                    ajax: true,
//                    ajaxUrl: 'data/system_list.json',
//                    ajaxOnLoad: true,
                    records: []
                },
                inputs: {
                    processingText: ''
                }
            });
        }
    };
});

angular.module('openAwesome.directives').directive('systemComponent', function () {
    return {
        templateUrl: 'partials/system-component.html',
        scope: {
            systemComponent: '='
        },
        link: function (scope) {
            scope.isArray = angular.isArray;
            scope.isString = angular.isString;
            scope.humanize = function (text) {
                return angular.isString(text) ? text.replace(/(_)/g, ' ') : text;
            };

            scope.toggleMoreInfo = function (item) {
                item.isMoreInfoVisible = !item.isMoreInfoVisible;
            };

            scope.displayName = angular.isDefined(scope.systemComponent.displayName) ?
                scope.systemComponent.displayName :
                scope.humanize(scope.systemComponent.name);

            if (angular.isDefined(scope.systemComponent.promise)) {
                scope.systemComponent.promise.then(function (system) {
                    scope.component = system[scope.systemComponent.name];
                    scope.isMultipleComponents = angular.isArray(scope.component);
                    scope.isStringArray = scope.isMultipleComponents && scope.component.length > 0 && angular.isString(scope.component[0]);
                    scope.itemHeaderTemplateUrl = '/system-' + scope.systemComponent.name + '-item-header.html';
                    if (scope.isMultipleComponents && !scope.isStringArray) {
                        for (var i in scope.component) {
                            scope.component[i].isMoreInfoVisible = false;
                        }
                    }
                });
            } else if (angular.isDefined(scope.systemComponent.component)) {
                scope.component = scope.systemComponent.component;
                scope.isMultipleComponents = angular.isArray(scope.component);
                scope.isStringArray = scope.isMultipleComponents && scope.component.length > 0 && angular.isString(scope.component[0]);
                scope.itemHeaderTemplateUrl = '/system-' + scope.systemComponent.name + '-item-header.html';
                if (scope.isMultipleComponents && !scope.isStringArray) {
                    for (var i in scope.component) {
                        scope.component[i].isMoreInfoVisible = false;
                    }
                }
            }
        }
    };
});

angular.module('openAwesome.directives').directive('updateInProgress', function () {
    return {
        restrict: 'AE',
        replace: true,
        transclude: true,
        template: '

Loading...
' +
            '

',
        scope: {
            updateInProgress: '='
        },
        link: function (scope, element) {
            var loadingIndicator = element.find('.loading-indicator');
            var loadedContent = element.find('.loaded-content');
            loadingIndicator.css('padding-top', '80px')
                .css('padding-bottom', '80px');
            var toggleIndicator = function (isResolved) {
                isResolved ? loadingIndicator.hide() : loadingIndicator.show();
                isResolved ? loadedContent.show() : loadedContent.hide();
            };
            typeof scope.updateInProgress === 'boolean' ?
                scope.$watch('updateInProgress', toggleIndicator) :
                scope.$watch('updateInProgress.$resolved', toggleIndicator);
        }
    };
});<commit_msg>Remove unused/unneeded promise logic<commit_after>'use strict';

/* Directives */
angular.module('openAwesome.directives', []);
angular.module('openAwesome.directives').directive('dynatable', function () {
    return {
        scope: {
            dynatable: '='
        },
        link: function (scope, element) {
//            function osNameWriter(column, record) {
//                if (column.id === 'hostname') {
//                    return '' + record[column.id] + '	';
//                }
//                else if (column.id === 'os_name' && angular.isDefined(record.icon)) {
//                    return '	';
//                }
//                return '' + record[column.id] + '	';
//            }

            element.dynatable({
//                writers: {
//                    _cellWriter: osNameWriter
//                },
                features: {
                    sort: false,
                    pushState: false,
                    paginate: false,
                    recordCount: false,
                    search: false
                },
                table: {
                    defaultColumnIdStyle: 'underscore'
                },
                dataset: {
//                    ajax: true,
//                    ajaxUrl: 'data/system_list.json',
//                    ajaxOnLoad: true,
                    records: []
                },
                inputs: {
                    processingText: ''
                }
            });
        }
    };
});

angular.module('openAwesome.directives').directive('systemComponent', function () {
    return {
        templateUrl: 'partials/system-component.html',
        scope: {
            systemComponent: '='
        },
        link: function (scope) {
            scope.isArray = angular.isArray;
            scope.isString = angular.isString;
            scope.humanize = function (text) {
                return angular.isString(text) ? text.replace(/(_)/g, ' ') : text;
            };

            scope.toggleMoreInfo = function (item) {
                item.isMoreInfoVisible = !item.isMoreInfoVisible;
            };

            scope.displayName = angular.isDefined(scope.systemComponent.displayName) ?
                scope.systemComponent.displayName :
                scope.humanize(scope.systemComponent.name);

            if (angular.isDefined(scope.systemComponent.component)) {
                scope.component = scope.systemComponent.component;
                scope.isMultipleComponents = angular.isArray(scope.component);
                scope.isStringArray = scope.isMultipleComponents && scope.component.length > 0 && angular.isString(scope.component[0]);
                scope.itemHeaderTemplateUrl = '/system-' + scope.systemComponent.name + '-item-header.html';
                if (scope.isMultipleComponents && !scope.isStringArray) {
                    for (var i in scope.component) {
                        scope.component[i].isMoreInfoVisible = false;
                    }
                }
            }
        }
    };
});

angular.module('openAwesome.directives').directive('updateInProgress', function () {
    return {
        restrict: 'AE',
        replace: true,
        transclude: true,
        template: '

Loading...
' +
            '

',
        scope: {
            updateInProgress: '='
        },
        link: function (scope, element) {
            var loadingIndicator = element.find('.loading-indicator');
            var loadedContent = element.find('.loaded-content');
            loadingIndicator.css('padding-top', '80px')
                .css('padding-bottom', '80px');
            var toggleIndicator = function (isResolved) {
                isResolved ? loadingIndicator.hide() : loadingIndicator.show();
                isResolved ? loadedContent.show() : loadedContent.hide();
            };
            typeof scope.updateInProgress === 'boolean' ?
                scope.$watch('updateInProgress', toggleIndicator) :
                scope.$watch('updateInProgress.$resolved', toggleIndicator);
        }
    };
});<|endoftext|>


<commit_before>var PermanentLinkJS = function() {
	"use strict";

	var query = {};

	function reset(){
		query = {};
		set_hash();
		return query;
	}

	function set(key, val) {
		if (typeof key == 'object'){
			try{
				for (var k in key){
					query[k] = key[k];
				}
			}catch(err){
				console.error("Error set query: %s", err.message);
			}
		}else{
			try{
				query[key] = val;
				set_hash();
			}catch(err){
				console.error("Error set query: %s", err.message);
			}
		}
		return query;
	}

	function get_parameters(str) {
		str = str || location.hash;
		return str.replace("#", "").split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this;}.bind({}))[0];
	}

	function set_from_location(){
		return (query = get_parameters());
	}

	function kill(k){
		delete query[k];
		set_hash();
		return query;
	}

	function to_string(o){
		var s = [];
		for(var k in o){
			s.push([k, o[k]].join("="));
		}
		return s.join("&");
	}

	function set_hash(q) {
		q = typeof q == "string" ? q : to_string(q || query);
		try{
			return (location.hash = q);
		}catch(err){
			console.error("Error set_hash: %s", err.message);
		}
	}

	this.get_query = function() { return query; };

	this.reset = reset;
	this.get_parameters = get_parameters;
	this.to_string = to_string;
	this.set_hash = set_hash;
	this.set = set;
	this.kill = kill;
	this.set_from_location = set_from_location;
};

// Elecciones class
var ElecionesApp = function(list_partidos, results){
	"use strict";
	// set self class var
	var s = this;
	s.list_partidos = list_partidos;
	s.r_general = results.general;
	s.comuna_active_path = null;
	// s.r_internas = results.inernas;

	function set_data_active(str){
		$("#selected h4").html(str).fadeIn();
	}

	function select_comuna(polygon){
		var id = polygon.id.replace(/c/i, "");
		var com_name = "Comuna "+ id;
		set_data_active(com_name);

		// set polygon active
		// var bbox = polygon.getBBox();
		// console.log(bbox.x);
		// $("svg").css("transform", "translateX("+bbox.x+"px) translateY("+bbox.x+"px) scale(2)")
		s.remove_comuna_active_path();
		s.comuna_active_path = $(polygon).clone();
		s.comuna_active_path.attr("class","comuna_active_path");
		$("svg").append(s.comuna_active_path);
		s.q.set("comuna", id);

	}

	(function init(){
			// bind events
			var candidato_btn = $('input[type="radio"]');
			candidato_btn.on('click.select_condidato', function(el){
				var $el = $(this);
				$('li.active:has(input)').removeClass('active');
				$el.closest('li').addClass('active');

				set_data_active(this.value);
				s.q.set("candidato", this.value);

			});

			// change dropdown
			$('select#opts').change(function(e){
				s.change_dropdown($(this).val());
			});

			// template para el select de internas
			s.tmpl_opts = Handlebars.compile($('#tmpl_opts').html());
			$("#opts").html( s.tmpl_opts(s.list_partidos) );

			// template para listado de resultados por partido
			s.cont_results = $("#results"); // contenedor ul para los partidos (barras)
			s.tmpl_li_partido = Handlebars.compile($('#tmpl_li_partido').html());
			s.draw_ul_list(s.r_general.total);

			// template tooltip
			s.tooltip = $("#tooltip"); // contenedor ul para los partidos (barras)
			s.tmpl_tooltip = Handlebars.compile($('#tmpl_tooltip').html());

			// click mapa
			$('polygon').on('click.on_comuna', function(e){
				select_comuna(this);
			});

			tooltip(); // esta en scripts.js
	})();

	// init();
};

ElecionesApp.prototype.reset = function (){
	// resetea el los filtros
	$("#selected h4").fadeOut(function(){
		$(this).html("");
	});
	this.remove_comuna_active_path();
};

ElecionesApp.prototype.barios_x_com = {
	'c1':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c2':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c3':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c4':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c5':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c6':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c7':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c8':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c9':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c10':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c11':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c12':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c13':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c14':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c15':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar."
};

ElecionesApp.prototype.draw_ul_list = function(data){
	this.cont_results.html(this.tmpl_li_partido(data));
};

ElecionesApp.prototype.draw_tooltip = function(data){
	this.tooltip.html(this.tmpl_tooltip(data));
};

ElecionesApp.prototype.remove_comuna_active_path = function(){
	if(this.comuna_active_path){
		this.comuna_active_path.remove();
	}
};

ElecionesApp.prototype.change_dropdown = function(val){
	var x_fuerza = 'x_fuerza';
	// if(x_fuerza == val){
	// 	$('#x_interna').hide();
	// 	$('#x_fuerza').show();
	// }else{
	// 	$('#x_fuerza').hide();
	// 	$('#x_interna').show();
	// }

	if(x_fuerza == val){
		this.draw_ul_list(this.r_general.total);
	}else{

	}
	// set path
	this.q.set('fuerza', val);
};

ElecionesApp.prototype.q = new PermanentLinkJS();<commit_msg>fix js<commit_after>var PermanentLinkJS = function() {
	"use strict";

	var query = {};

	function reset(){
		query = {};
		set_hash();
		return query;
	}

	function set(key, val) {
		if (typeof key == 'object'){
			try{
				for (var k in key){
					query[k] = key[k];
				}
			}catch(err){
				console.error("Error set query: %s", err.message);
			}
		}else{
			try{
				query[key] = val;
				set_hash();
			}catch(err){
				console.error("Error set query: %s", err.message);
			}
		}
		return query;
	}

	function get_parameters(str) {
		str = str || location.hash;
		return str.replace("#", "").split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this;}.bind({}))[0];
	}

	function set_from_location(){
		return (query = get_parameters());
	}

	function kill(k){
		delete query[k];
		set_hash();
		return query;
	}

	function to_string(o){
		var s = [];
		for(var k in o){
			s.push([k, o[k]].join("="));
		}
		return s.join("&");
	}

	function set_hash(q) {
		q = typeof q == "string" ? q : to_string(q || query);
		try{
			return (location.hash = q);
		}catch(err){
			console.error("Error set_hash: %s", err.message);
		}
	}

	this.get_query = function() { return query; };

	this.reset = reset;
	this.get_parameters = get_parameters;
	this.to_string = to_string;
	this.set_hash = set_hash;
	this.set = set;
	this.kill = kill;
	this.set_from_location = set_from_location;
};

// Elecciones class
var ElecionesApp = function(list_partidos, results){
	"use strict";
	// set self class var
	var s = this;
	s.list_partidos = list_partidos;
	s.r_general = results.general;
	s.comuna_active_path = null;
	// s.r_internas = results.inernas;

	function set_data_active(str){
		$("#selected h4").html(str).fadeIn();
	}

	function select_comuna(polygon){
		var id = polygon.id.replace(/c/i, "");
		var com_name = "Comuna "+ id;
		set_data_active(com_name);

		// set polygon active
		// var bbox = polygon.getBBox();
		// console.log(bbox.x);
		// $("svg").css("transform", "translateX("+bbox.x+"px) translateY("+bbox.x+"px) scale(2)")
		s.remove_comuna_active_path();
		s.comuna_active_path = $(polygon).clone();
		s.comuna_active_path.attr("class","comuna_active_path");
		$("svg").append(s.comuna_active_path);
		s.q.set("comuna", id);
		// lista de partidos x comuna
		// console.log(s.r_general.comunas['comuna_'+id]);
		s.draw_ul_list(s.r_general.comunas['comuna_'+id]);

	}

	(function init(){
			// bind events
			var candidato_btn = $('input[type="radio"]');
			candidato_btn.on('click.select_condidato', function(el){
				var $el = $(this);
				$('li.active:has(input)').removeClass('active');
				$el.closest('li').addClass('active');

				set_data_active(this.value);
				s.q.set("candidato", this.value);

			});

			// change dropdown
			$('select#opts').change(function(e){
				s.change_dropdown($(this).val());
			});

			// template para el select de internas
			s.tmpl_opts = Handlebars.compile($('#tmpl_opts').html());
			$("#opts").html( s.tmpl_opts(s.list_partidos) );

			// template para listado de resultados por partido
			s.cont_results = $("#results"); // contenedor ul para los partidos (barras)
			s.tmpl_li_partido = Handlebars.compile($('#tmpl_li_partido').html());
			s.draw_ul_list();

			// template tooltip
			s.tooltip = $("#tooltip"); // contenedor ul para los partidos (barras)
			s.tmpl_tooltip = Handlebars.compile($('#tmpl_tooltip').html());

			// click mapa
			$('polygon').on('click.on_comuna', function(e){
				select_comuna(this);
			});

			tooltip(); // esta en scripts.js
	})();

	// init();
};

ElecionesApp.prototype.reset = function (){
	// resetea el los filtros
	$("#selected h4").hide().html("");
	this.draw_ul_list();
	this.remove_comuna_active_path();
	this.q.kill("comuna");
};

ElecionesApp.prototype.barios_x_com = {
	'c1':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c2':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c3':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c4':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c5':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c6':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c7':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c8':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c9':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c10':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c11':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c12':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c13':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c14':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar.",
	'c15':"Agronomia, Chacarita, Paternal, Parque Chas, Villa Crespo, Villa Ortuzar."
};

ElecionesApp.prototype.draw_ul_list = function(data){
	if(!data){
		data = this.r_general.total;
	}
	this.cont_results.html(this.tmpl_li_partido(data));
};

ElecionesApp.prototype.draw_tooltip = function(data){
	this.tooltip.html(this.tmpl_tooltip(data));
};

ElecionesApp.prototype.remove_comuna_active_path = function(){
	if(this.comuna_active_path){
		this.comuna_active_path.remove();
	}

};

ElecionesApp.prototype.change_dropdown = function(val){
	var x_fuerza = 'x_fuerza';
	// if(x_fuerza == val){
	// 	$('#x_interna').hide();
	// 	$('#x_fuerza').show();
	// }else{
	// 	$('#x_fuerza').hide();
	// 	$('#x_interna').show();
	// }

	if(x_fuerza == val){
		this.draw_ul_list();
	}else{

	}
	// set path
	this.q.set('fuerza', val);
};

ElecionesApp.prototype.q = new PermanentLinkJS();<|endoftext|>


<commit_before>import * as Core from "./utils/Core"
import * as Collection from "./utils/collection"
import * as Text from "./utils/text"
import get from "./get"

export default function extract(data, path) {
  if (!Core.isCollection(data)) {
    return null;
  }

  if (Core.empty(path)) {
    return data;
  }

  if (!/[{\[]/.test(path)) {
    return get(data, path, null);
  }

  const key = "__set_item__";
  let tokens;
  let context = {[key]: [data]};

  if (path.indexOf("[") < 0) {
    tokens = path.split(".");
  } else {
    tokens = Text.tokenize(path, ".", "[", "]");
  }

  Collection.each(tokens, (token) => {
    let next = [];
    let [_token, conditions] = Text.splitConditions(token);

    Collection.each(context[key], (item) => {
      Collection.each(item, (v, k) => {
        if (Text.matchToken(k, _token)) {
          next.push(v);
        }
      });
    });

    if (conditions) {
      let filter = [];
      Collection.each(next, (item) => {
        if (Core.isCollection(item) && Text.matches(item, conditions)) {
          filter.push(item);
        }
      });
      next = filter;
    }
    context = {[key]: next};
  });

  return context[key];
}<commit_msg>Fix module path<commit_after>import * as Core from "./utils/core"
import * as Collection from "./utils/collection"
import * as Text from "./utils/text"
import get from "./get"

export default function extract(data, path) {
  if (!Core.isCollection(data)) {
    return null;
  }

  if (Core.empty(path)) {
    return data;
  }

  if (!/[{\[]/.test(path)) {
    return get(data, path, null);
  }

  const key = "__set_item__";
  let tokens;
  let context = {[key]: [data]};

  if (path.indexOf("[") < 0) {
    tokens = path.split(".");
  } else {
    tokens = Text.tokenize(path, ".", "[", "]");
  }

  Collection.each(tokens, (token) => {
    let next = [];
    let [_token, conditions] = Text.splitConditions(token);

    Collection.each(context[key], (item) => {
      Collection.each(item, (v, k) => {
        if (Text.matchToken(k, _token)) {
          next.push(v);
        }
      });
    });

    if (conditions) {
      let filter = [];
      Collection.each(next, (item) => {
        if (Core.isCollection(item) && Text.matches(item, conditions)) {
          filter.push(item);
        }
      });
      next = filter;
    }
    context = {[key]: next};
  });

  return context[key];
}<|endoftext|>


<commit_before>import React, { Component, Children } from 'react';
import PropTypes from 'prop-types';

// marker used for invalid or unknown value, likely due to error
const problemMarker = {};

class Federal extends Component {
  constructor(props) {
    super(props);

    // getting props
    const { store, actions } = Object.assign({
      store: {},
      actions: {}
    }, props);

    // initial state
    this.state = {
      store,
      dispatch: actionsToDispatch(this, actions)
    };
  }

  getChildContext() {
    return {
      store: this.state.store,
      dispatch: this.state.dispatch,
      federalRoot: this
    };
  }

  render() {
    const { children } = this.props;

    return !children ? null :
      React.isValidElement(children) ? Children.only(children) :
      Array.isArray(children) ? (
        {children}
      ) :
      null;
  }

  // contextTypes needed or else context is not exposed
  static childContextTypes = {
    store: PropTypes.object.isRequired,
    dispatch: PropTypes.object.isRequired,
    federalRoot: PropTypes.object.isRequired
  }
}

// method to 'connect'/bind a component to the Federal store
function connect(selector = store => store, actions = {}) {
  return function wrapper(InboundComponent) {
    // connecting a component wraps it with our own component, to enforce child contexts
    class FederalWrap extends Component {
      render() {
        const { store, dispatch, federalRoot } = this.context;

        // select will be used to reduce the number of props passed to the inbound component
        const storeSelected = typeof selector === 'function' ? selector(store) :
          Array.isArray(selector) ? selector.reduce((selection, currentSelector) => {
            return currentSelector(selection);
          }, store) :
          problemMarker;

        if (storeSelected === problemMarker) {
          throw new Error(`An invalid selector was passed to connect() for ${InboundComponent.displayName}`);
        }

        // dispatch may hav inherited or local actions
        const usedDispatch = Object.assign({}, dispatch, actionsToDispatch(federalRoot, actions));

        // props passed manually will override those in the store
        const usedProps = Object.assign({
          dispatch: usedDispatch
        }, storeSelected, this.props);

        // inbound component returned with overridden props, from the (selected) store
        return (
          <InboundComponent {...usedProps} />
        );
      }

      // contextTypes needed or else context is not exposed
      static contextTypes = {
        store: PropTypes.object.isRequired,
        dispatch: PropTypes.object.isRequired,
        federalRoot: PropTypes.object.isRequired
      }
    }

    return FederalWrap;
  };
}

function actionsToDispatch(parent, actions) {
  // building disptach methods, based on provided action methods
  return Object.keys(actions).reduce((mapping, actionName) => {
    // e.g. dispatch.setVal = ({ newVal: 12 }, () => { /* callback */ })
    mapping[actionName] = (data, callback = (() => {})) => {
      const state = parent.state;
      const oldStore = state.store;
      const newStore = actions[actionName](oldStore, data);

      // store value must change, or nothing is triggered
      if (newStore === oldStore) {
        return;
      }

      // state.store update will trigger children bound to context to update
      state.store = newStore;
      parent.setState(state, () => {
        if (process.env.NODE_ENV !== 'production') {
          prettyLog('Prev Store', oldStore);
          prettyLog('Federal Action', actionName);
          prettyLog('Next Store', newStore);
        }

        callback(oldStore, newStore);
      });
    };
    return mapping;
  }, {});
}

function prettyLog(label, data) {
  console.log(`%c ${padRight(label, 16)}`, 'color: #e4421e; font-style: italic; font-weight: bold', data);
}

function padRight(label, len) {
  return label.length >= len ? label :
    `${label}${' '.repeat(len - label.length)}`;
}

export default Federal;
export { connect };
<commit_msg>minor style changes<commit_after>import React, { Component, Children } from 'react';
import PropTypes from 'prop-types';

// marker used for invalid or unknown value, likely due to error
const problemMarker = {};

class Federal extends Component {
  constructor(props) {
    super(props);

    // getting props
    const { store, actions } = Object.assign({
      store: {},
      actions: {}
    }, props);

    // initial state
    this.state = {
      store,
      dispatch: actionsToDispatch(this, actions)
    };
  }

  getChildContext() {
    return {
      store: this.state.store,
      dispatch: this.state.dispatch,
      federalRoot: this
    };
  }

  render() {
    const { children } = this.props;

    return !children ? null :
      React.isValidElement(children) ? Children.only(children) :
      Array.isArray(children) ? (
        {children}
      ) :
      null;
  }

  // contextTypes needed or else context is not exposed
  static childContextTypes = {
    store: PropTypes.object.isRequired,
    dispatch: PropTypes.object.isRequired,
    federalRoot: PropTypes.object.isRequired
  }
}

// method to 'connect'/bind a component to the Federal store
function connect(selector = store => store, actions = {}) {
  return function wrapper(InboundComponent) {
    // connecting a component wraps it with our own component, to enforce child contexts
    class FederalWrap extends Component {
      render() {
        const { store, dispatch, federalRoot } = this.context;

        // select will be used to reduce the number of props passed to the inbound component
        const storeSelected = typeof selector === 'function' ? selector(store) :
          Array.isArray(selector) ? selector.reduce((selection, currentSelector) => currentSelector(selection), store) :
          problemMarker;

        if (storeSelected === problemMarker) {
          throw new Error(`An invalid selector was passed to connect() for ${InboundComponent.displayName}`);
        }

        // dispatch may hav inherited or local actions
        const usedDispatch = Object.assign({}, dispatch, actionsToDispatch(federalRoot, actions));

        // props passed manually will override those in the store
        const usedProps = Object.assign({
          dispatch: usedDispatch
        }, storeSelected, this.props);

        // inbound component returned with overridden props, from the (selected) store
        return (
          <InboundComponent {...usedProps} />
        );
      }

      // contextTypes needed or else context is not exposed
      static contextTypes = {
        store: PropTypes.object.isRequired,
        dispatch: PropTypes.object.isRequired,
        federalRoot: PropTypes.object.isRequired
      }
    }

    return FederalWrap;
  };
}

const noOp = () => {};
function actionsToDispatch(parent, actions) {
  // building disptach methods, based on provided action methods
  return Object.keys(actions).reduce((mapping, actionName) => {
    // e.g. dispatch.setVal = ({ newVal: 12 }, () => { /* callback */ })
    mapping[actionName] = (data, callback = noOp) => {
      const state = parent.state;
      const oldStore = state.store;
      const newStore = actions[actionName](oldStore, data);

      // store value must change, or nothing is triggered
      if (newStore === oldStore) {
        return;
      }

      // state.store update will trigger children bound to context to update
      state.store = newStore;
      parent.setState(state, () => {
        if (process.env.NODE_ENV !== 'production') {
          prettyLog('Prev Store', oldStore);
          prettyLog('Federal Action', actionName);
          prettyLog('Next Store', newStore);
        }

        callback(oldStore, newStore);
      });
    };
    return mapping;
  }, {});
}

function prettyLog(label, data) {
  console.log(`%c ${padRight(label, 16)}`, 'color: #e4421e; font-style: italic; font-weight: bold', data);
}

function padRight(label, len) {
  return label.length >= len ? label : `${label}${' '.repeat(len - label.length)}`;
}

export default Federal;
export { connect };
<|endoftext|>


<commit_before>var extractJSON = require('./extract-json');

function getPreWithSource() {
  var childNodes = document.body.childNodes;

  if (childNodes.length === 1) {

    var childNode = childNodes[0];

    if (childNode.nodeName === "PRE") {
      return childNode;
    } else if (childNode.nodeName === "#text") { // if Content-Type is text/html
      var pre = document.createElement("pre");
      pre.textContent = childNode.textContent;
      document.body.removeChild(childNode);
      document.body.appendChild(pre);
      return pre;
    }

  }

  return null
}

function isJSON(jsonStr) {
  var str = jsonStr;
  if (!str || str.length === 0) return false
  str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '')
  return (/^[\],:{}\s]*$/).test(str)
}

function isJSONP(jsonStr) {
  return isJSON(extractJSON(jsonStr));
}

function checkIfJson(sucessCallback, element) {
  var pre = element || getPreWithSource();
  if (pre !== null &&
    pre !== undefined &&
    (isJSON(pre.textContent) || isJSONP(pre.textContent))) {
    sucessCallback(pre);
  }
}

module.exports = checkIfJson;
<commit_msg>fix empty pre prepended to body when highlighting content-type text/html (closes #123)<commit_after>var extractJSON = require('./extract-json');

function getPreWithSource() {
  var childNodes = document.body.childNodes;

  if (childNodes.length === 1) {
    var childNode = childNodes[0];
    var nodeName = childNode.nodeName
    var textContent = childNode.textContent

    if (nodeName === "PRE") {
      return childNode;

    // if Content-Type is text/html
    } else if (nodeName === "#text" && !/^\s+$/g.test(textContent)) {
      if (process.env.NODE_ENV === 'development') {
        console.debug("[JSONViewer] Loaded from a text node, this might have returned content-type: text/html");
      }

      var pre = document.createElement("pre");
      pre.textContent = textContent;
      document.body.removeChild(childNode);
      document.body.appendChild(pre);
      return pre;
    }
  }

  return null
}

function isJSON(jsonStr) {
  var str = jsonStr;
  if (!str || str.length === 0) {
    return false
  }

  str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
  str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
  str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '')
  return (/^[\],:{}\s]*$/).test(str)
}

function isJSONP(jsonStr) {
  return isJSON(extractJSON(jsonStr));
}

function checkIfJson(sucessCallback, element) {
  var pre = element || getPreWithSource();

  if (pre !== null &&
    pre !== undefined &&
    (isJSON(pre.textContent) || isJSONP(pre.textContent))) {

    sucessCallback(pre);
  }
}

module.exports = checkIfJson;
<|endoftext|>


<commit_before>'use strict';

var defineProperty = Object.defineProperty
  , aFrom          = require('es5-ext/array/from')
  , remove         = require('es5-ext/array/#/remove')
  , d              = require('d')
  , value          = require('es5-ext/object/valid-object')
  , emit           = require('./').methods.emit

  , hasOwnProperty = Object.prototype.hasOwnProperty
  , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

module.exports = function (e1, e2) {
	var pipes, pipe, desc;

	(value(e1) && value(e2));
	if (typeof e1.emit !== 'function') {
		throw new TypeError(e1 + ' is not emitter');
	}

	pipe = {
		close: function () { remove.call(pipes, e2); }
	};
	if (hasOwnProperty.call(e1, '__eePipes__')) {
		(pipes = e1.__eePipes__).push(e2);
		return pipe;
	}
	defineProperty(e1, '__eePipes__', d(pipes = [e2]));
	desc = getOwnPropertyDescriptor(e1, 'emit');
	delete desc.get;
	delete desc.set;
	desc.value = function () {
		var i, emitter, data = aFrom(pipes);
		emit.apply(this, arguments);
		for (i = 0; (emitter = data[i]); ++i) emit.apply(emitter, arguments);
	};
	defineProperty(e1, 'emit', desc);
	return pipe;
};
<commit_msg>-- cleanup<commit_after>'use strict';

var aFrom          = require('es5-ext/array/from')
  , remove         = require('es5-ext/array/#/remove')
  , value          = require('es5-ext/object/valid-object')
  , d              = require('d')
  , emit           = require('./').methods.emit

  , defineProperty = Object.defineProperty
  , hasOwnProperty = Object.prototype.hasOwnProperty
  , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

module.exports = function (e1, e2) {
	var pipes, pipe, desc;

	(value(e1) && value(e2));
	if (typeof e1.emit !== 'function') {
		throw new TypeError(e1 + ' is not emitter');
	}

	pipe = {
		close: function () { remove.call(pipes, e2); }
	};
	if (hasOwnProperty.call(e1, '__eePipes__')) {
		(pipes = e1.__eePipes__).push(e2);
		return pipe;
	}
	defineProperty(e1, '__eePipes__', d(pipes = [e2]));
	desc = getOwnPropertyDescriptor(e1, 'emit');
	delete desc.get;
	delete desc.set;
	desc.value = function () {
		var i, emitter, data = aFrom(pipes);
		emit.apply(this, arguments);
		for (i = 0; (emitter = data[i]); ++i) emit.apply(emitter, arguments);
	};
	defineProperty(e1, 'emit', desc);
	return pipe;
};
<|endoftext|>