<commit_before>
var langList = config.langList

Promise.all([getVoices(), getSettings(["languages", "preferredVoices"]), domReady()]).then(spread(initialize));

function initialize(voices, settings) {
  setI18nText();

  //create checkboxes
  var langs = voices.groupBy(function(voice) {
    return voice.lang ? voice.lang.split('-',1)[0] : "<any>";
  })
  createCheckboxes(langs);

  //toggle check state
  var selectedLangs = settings.languages ? settings.languages.split(',') : [];
  var isSelected = function() {
    return selectedLangs.includes($(this).data("lang"));
  };
  $("input[data-lang]").filter(isSelected).prop("checked", true);

  $(".voice-list").hide().filter(isSelected).show();
  $(".voice-list").each(function() {
    var preferredVoice = settings.preferredVoices && settings.preferredVoices[$(this).data("lang")];
    if (preferredVoice) $("input[type=radio][data-voice='" + preferredVoice + "']", this).prop("checked", true);
    else $("input[type=radio]:first", this).prop("checked", true);
  })

  //event hooks
  $("input[data-lang]").click(function() {
    $(".voice-list[data-lang=" + $(this).data("lang") + "]").toggle(this.checked);
    saveLanguages();
  })
  $(".voice-list").change(function() {
    savePreferredVoices();
  })
  $("#back-button").click(function() {
    location.href = "options.html";
  })
}

function createCheckboxes(voicesForLang) {
  for (var item of langList) {
    if (!voicesForLang[item.code]) continue;

    var div = $("<div>").addClass("form-check").appendTo("#lang-list");
    var label = $("<label>").addClass("form-check-label").appendTo(div);
    $("<input>").attr("type", "checkbox").addClass("form-check-input").attr("data-lang", item.code).appendTo(label);
    $("<span>").text(item.name).appendTo(label);

    div = $("<div>").addClass("form-check voice-list").attr("data-lang", item.code).appendTo("#lang-list");
    label = $("<label>").addClass("form-check-label d-block").appendTo(div);
    $("<input>").attr("type", "radio").attr("name", item.code).appendTo(label);
    $("<span>").text("Auto select").appendTo(label);
    for (var voice of voicesForLang[item.code]) {
      label = $("<label>").addClass("form-check-label d-block").appendTo(div);
      $("<input>").attr("type", "radio").attr("name", item.code).attr("data-voice", voice.voiceName).appendTo(label);
      $("<span>").text(voice.voiceName).appendTo(label);
    }
  }
}

function saveLanguages() {
  updateSettings({
    languages: $("input[data-lang]:checked")
      .get()
      .map(function(elem) {return $(elem).data("lang")})
      .join(',')
  })
}

function savePreferredVoices() {
  updateSettings({
    preferredVoices: $(".voice-list")
      .get()
      .groupBy(function(elem) {
        return $(elem).data("lang");
      },
      function(accum, elem) {
        return $("input[type=radio]:checked", elem).data("voice");
      })
  })
}
<commit_msg>in languages page, alias 'cmn' and 'yue' to 'zh' so that voices like GoogleWavenet Mandarin shows up properly under "Chinese (Zhongwen)"<commit_after>
var langList = config.langList

Promise.all([getVoices(), getSettings(["languages", "preferredVoices"]), domReady()]).then(spread(initialize));

function initialize(voices, settings) {
  setI18nText();

  //create checkboxes
  var langs = voices.groupBy(function(voice) {
    if (voice.lang) {
      var code = voice.lang.split('-',1)[0]
      var alias = {
        yue: "zh",
        cmn: "zh",
      }
      return alias[code] || code
    }
    else {
      return "<any>"
    }
  })
  createCheckboxes(langs);

  //toggle check state
  var selectedLangs = settings.languages ? settings.languages.split(',') : [];
  var isSelected = function() {
    return selectedLangs.includes($(this).data("lang"));
  };
  $("input[data-lang]").filter(isSelected).prop("checked", true);

  $(".voice-list").hide().filter(isSelected).show();
  $(".voice-list").each(function() {
    var preferredVoice = settings.preferredVoices && settings.preferredVoices[$(this).data("lang")];
    if (preferredVoice) $("input[type=radio][data-voice='" + preferredVoice + "']", this).prop("checked", true);
    else $("input[type=radio]:first", this).prop("checked", true);
  })

  //event hooks
  $("input[data-lang]").click(function() {
    $(".voice-list[data-lang=" + $(this).data("lang") + "]").toggle(this.checked);
    saveLanguages();
  })
  $(".voice-list").change(function() {
    savePreferredVoices();
  })
  $("#back-button").click(function() {
    location.href = "options.html";
  })
}

function createCheckboxes(voicesForLang) {
  for (var item of langList) {
    if (!voicesForLang[item.code]) continue;

    var div = $("<div>").addClass("form-check").appendTo("#lang-list");
    var label = $("<label>").addClass("form-check-label").appendTo(div);
    $("<input>").attr("type", "checkbox").addClass("form-check-input").attr("data-lang", item.code).appendTo(label);
    $("<span>").text(item.name).appendTo(label);

    div = $("<div>").addClass("form-check voice-list").attr("data-lang", item.code).appendTo("#lang-list");
    label = $("<label>").addClass("form-check-label d-block").appendTo(div);
    $("<input>").attr("type", "radio").attr("name", item.code).appendTo(label);
    $("<span>").text("Auto select").appendTo(label);
    for (var voice of voicesForLang[item.code]) {
      label = $("<label>").addClass("form-check-label d-block").appendTo(div);
      $("<input>").attr("type", "radio").attr("name", item.code).attr("data-voice", voice.voiceName).appendTo(label);
      $("<span>").text(voice.voiceName).appendTo(label);
    }
  }
}

function saveLanguages() {
  updateSettings({
    languages: $("input[data-lang]:checked")
      .get()
      .map(function(elem) {return $(elem).data("lang")})
      .join(',')
  })
}

function savePreferredVoices() {
  updateSettings({
    preferredVoices: $(".voice-list")
      .get()
      .groupBy(function(elem) {
        return $(elem).data("lang");
      },
      function(accum, elem) {
        return $("input[type=radio]:checked", elem).data("voice");
      })
  })
}
<|endoftext|>


<commit_before>// Any javascript required by the META-SHARE editor

$(document).ready(function() {

	// Resource editor: content info stuff
  function compute_new_id(prefix) {
	var counter = 0;
    while (true) {
      var existing = $('#'+prefix+'-'+counter);
      if (existing.length === 0) break;
      counter++;
    }
    return prefix+'-'+counter;
  }

  function maybe_show_one_more_field(prefix) {
	var new_id = compute_new_id(prefix);
	var new_name = new_id.substr(3); // skip initial 'id_'
	var inputItem = $('#'+new_id);
	if (inputItem.length === 0) {
		// need to create it by cloning
		var protodiv = $('#'+prefix+'-protodiv');
		var newInput = protodiv.find('input').clone().attr({'id': new_id, 'name': new_name}).css('display', 'inline');
		newInput.change(handle_input_update);
		protodiv.before(newInput);
		var newH1 = protodiv.find('h1').clone();
		var newAdd = newH1.find('a.protoadd').attr('id', 'add_'+new_id).css('display', 'inline');
		var newEdit = newH1.find('a.protoedit').attr('id', 'edit_'+new_id).css('display', 'none');
		protodiv.before(newH1);
	}
  }

  function handle_input_update() {
		var input_id = $(this).attr('id');
		var input_value = $(this).attr('value');
		var editA = $('#edit_' + input_id)
		var addA = $('#add_' + input_id)

		if (input_id.localeCompare("has_value") == 0 && $('#'+input_id).attr('value')){
			var temp = $('#'+input_id).attr('class');
			$('a#'+temp).attr('class', '');
		}
		if (input_value) { // edit
			var protoHref = editA.attr('proto-href');
			editA.attr('href', protoHref+input_value+'/').css('display', 'inline');
			addA.css('display', 'none');
			var prefix = input_id.substr(0, input_id.lastIndexOf('-'));
			//for every input with this name, remove error class from all menu items
			if(prefix){
				$("input[name^='" + prefix.substr(3) + "-']").each(function(){
					$(this).next("h1").children("a").removeClass("error");
				});
			}
			if ($('#'+prefix+'-protodiv').length > 0) {
				maybe_show_one_more_field(prefix);
			}
		} else { // add
			editA.css('display', 'none');
			addA.css('display', 'inline');
		}
	  }

  $('#contentInfoStuff input').change(handle_input_update);
  // end of Resource editor: content info stuff

  // Cancel button
  $('input[name="_cancel"]').click(function() {
	  var popup = $('input[name="_popup"][value="1"]');
	  if (popup.length > 0) {
		  window.close();
	  } else {
		  window.location = "../";
	  }
  });
  // End of Cancel button

});

// Drop-down menu
var timeout         = 500;
var closetimer		= 0;
var ddmenuitem      = 0;

function jsddm_open()
{	jsddm_canceltimer();
	jsddm_close();
	ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');}

function jsddm_close()
{	if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}

function jsddm_timer()
{	closetimer = window.setTimeout(jsddm_close, timeout);}

function jsddm_canceltimer()
{	if(closetimer)
	{	window.clearTimeout(closetimer);
		closetimer = null;}}

$(document).ready(function()
{	$('#jsddm > li').bind('mouseover', jsddm_open);
	$('#jsddm > li').bind('mouseout',  jsddm_timer);});

document.onclick = jsddm_close;

//enforce size requirement in audio
$(document).ready(function(){
	$('input[name="_save"]').click(function(){
		if( $('input#id_sizeinfotype_model_set-0-size').val() == '' && $('h1.customtitle').html().indexOf('Audio size') != -1){
			if($('input#id_sizeinfotype_model_set-0-size').parents('table').prev('ul').length == 0 ){
				$('input#id_sizeinfotype_model_set-0-size').parents('table').before('

This field is required.

');
			}
			return false;
		}
	});
});

<commit_msg>removed script to enforce corpus audio size, django code is now enforcing it<commit_after>// Any javascript required by the META-SHARE editor

$(document).ready(function() {

	// Resource editor: content info stuff
  function compute_new_id(prefix) {
	var counter = 0;
    while (true) {
      var existing = $('#'+prefix+'-'+counter);
      if (existing.length === 0) break;
      counter++;
    }
    return prefix+'-'+counter;
  }

  function maybe_show_one_more_field(prefix) {
	var new_id = compute_new_id(prefix);
	var new_name = new_id.substr(3); // skip initial 'id_'
	var inputItem = $('#'+new_id);
	if (inputItem.length === 0) {
		// need to create it by cloning
		var protodiv = $('#'+prefix+'-protodiv');
		var newInput = protodiv.find('input').clone().attr({'id': new_id, 'name': new_name}).css('display', 'inline');
		newInput.change(handle_input_update);
		protodiv.before(newInput);
		var newH1 = protodiv.find('h1').clone();
		var newAdd = newH1.find('a.protoadd').attr('id', 'add_'+new_id).css('display', 'inline');
		var newEdit = newH1.find('a.protoedit').attr('id', 'edit_'+new_id).css('display', 'none');
		protodiv.before(newH1);
	}
  }

  function handle_input_update() {
		var input_id = $(this).attr('id');
		var input_value = $(this).attr('value');
		var editA = $('#edit_' + input_id)
		var addA = $('#add_' + input_id)

		if (input_id.localeCompare("has_value") == 0 && $('#'+input_id).attr('value')){
			var temp = $('#'+input_id).attr('class');
			$('a#'+temp).attr('class', '');
		}
		if (input_value) { // edit
			var protoHref = editA.attr('proto-href');
			editA.attr('href', protoHref+input_value+'/').css('display', 'inline');
			addA.css('display', 'none');
			var prefix = input_id.substr(0, input_id.lastIndexOf('-'));
			//for every input with this name, remove error class from all menu items
			if(prefix){
				$("input[name^='" + prefix.substr(3) + "-']").each(function(){
					$(this).next("h1").children("a").removeClass("error");
				});
			}
			if ($('#'+prefix+'-protodiv').length > 0) {
				maybe_show_one_more_field(prefix);
			}
		} else { // add
			editA.css('display', 'none');
			addA.css('display', 'inline');
		}

	  }

  $('#contentInfoStuff input').change(handle_input_update);
  // end of Resource editor: content info stuff

  // Cancel button
  $('input[name="_cancel"]').click(function() {
	  var popup = $('input[name="_popup"][value="1"]');
	  if (popup.length > 0) {
		  window.close();
	  } else {
		  window.location = "../";
	  }
  });
  // End of Cancel button

});

// Drop-down menu
var timeout         = 500;
var closetimer		= 0;
var ddmenuitem      = 0;

function jsddm_open()
{	jsddm_canceltimer();
	jsddm_close();
	ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');}

function jsddm_close()
{	if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}

function jsddm_timer()
{	closetimer = window.setTimeout(jsddm_close, timeout);}

function jsddm_canceltimer()
{	if(closetimer)
	{	window.clearTimeout(closetimer);
		closetimer = null;}}

$(document).ready(function()
{	$('#jsddm > li').bind('mouseover', jsddm_open);
	$('#jsddm > li').bind('mouseout',  jsddm_timer);});

document.onclick = jsddm_close;
<|endoftext|>


<commit_before>/*
 * Configuration values needed in js codes
 *
 * NOTE:
 * Please use the following command to avoid accidentally committing personal changes
 * git update-index --assume-unchanged src/javascript/config.js
 *
 */

function getAppId() {
  return localStorage.getItem('config.app_id') ? localStorage.getItem('config.app_id') :
               /staging\.binary\.com/i.test(window.location.hostname) ? '1098' : '1';
}

function getSocketURL() {
    var server_url = localStorage.getItem('config.server_url');
    if(!server_url) server_url = (/staging\.binary\.com/i.test(window.location.hostname) ? 'www2' : 'ws') + '.binaryws.com';
    return 'wss://' + server_url + '/websockets/v3';
}
<commit_msg>update app_id<commit_after>/*
 * Configuration values needed in js codes
 *
 * NOTE:
 * Please use the following command to avoid accidentally committing personal changes
 * git update-index --assume-unchanged src/javascript/config.js
 *
 */

function getAppId() {
  return localStorage.getItem('config.app_id') ? localStorage.getItem('config.app_id') :
               /staging\.binary\.com/i.test(window.location.hostname) ? '1098' : '1003';
}

function getSocketURL() {
    var server_url = localStorage.getItem('config.server_url');
    if(!server_url) server_url = (/staging\.binary\.com/i.test(window.location.hostname) ? 'www2' : 'ws') + '.binaryws.com';
    return 'wss://' + server_url + '/websockets/v3';
}
<|endoftext|>


<commit_before>var loadImages = function(dataPath, groupName, pictureName){
	var groupName = groupName || 'picture';
		pictureName = pictureName || 'picture';

	function loadImages(selectedImgCount){
		log('selectedImgCount: '+selectedImgCount);

		var imagesCollection = [],
			fileManager = [NSFileManager defaultManager];

		if(tools.majorVersion() == 3){
			var scriptPath = sketch.scriptPath;
			var pluginFolder = scriptPath.match(/Plugins\/([\w -])*/)[0] + '/';
			var sketchPluginsPath = scriptPath.replace(/Plugins([\w \/ -])*.sketchplugin$/, '');
			imagesPath =  sketchPluginsPath + pluginFolder + dataPath;
		}
		log('imagesPath: '+imagesPath);
		var imagesFileNames = [fileManager contentsOfDirectoryAtPath:imagesPath error:nil],
			imgLen = [imagesFileNames count];

		log('imagesFileNames (before clean): '+imagesFileNames);

		// clean out invalid files
		var imagesFileNamesCleaned = [];
		for (var i = 0; i < imgLen; i++) {
			if (imagesFileNames[i] == '.DS_Store') {
				log('skipping '+imagesFileNames[i]);

			} else {
				imagesFileNamesCleaned.push(imagesFileNames[i]);
			}
		}

		log('imagesFileNamesCleaned: '+imagesFileNamesCleaned);

		var offset = 0;
		for (var i = 0; i < selectedImgCount; i++) {
      var filename = '';
			if (i+1 > imagesFileNamesCleaned.length) {
				// no more images (reached end) - move back and use the first ones
				filename = imagesFileNamesCleaned[offset++];
			} else {
				filename = imagesFileNamesCleaned[i];
			}

			var pathToFile = imagesPath+filename;

			if ([fileManager fileExistsAtPath: pathToFile]) {
				var newImage = [[NSImage alloc] initWithContentsOfFile:pathToFile];
				imagesCollection.push(newImage);
			}
		}

		return imagesCollection;
	};

	function main(){
		var allLayers = [[doc currentPage] layers],
			imagesCollection = loadImages([selection count]);

		for(var i = 0; i < [selection count]; i++){
			var layer = selection[i];
            if([layer class] == MSShapeGroup){
                var image = imagesCollection[i];
                var fill = layer.style().fills().firstObject();
                fill.setFillType(4);
                //log(tools.minorVersion())
                if(tools.minorVersion() >= 1){
                	var coll = layer.style().fills().firstObject().documentData().images();
                	[fill setPatternImage:image collection:coll]
                }
                else{
                	layer.style().fills().firstObject().setPatternImage( image );
                }
                layer.style().fills().firstObject().setPatternFillType(1);
            }
		}

		if([selection count] == 0) alert('Select at least one vector shape');
	}
	main();
};
<commit_msg>Generate unique when possible pictures<commit_after>var loadImages = function(dataPath, groupName, pictureName){
	var groupName = groupName || 'picture';
		pictureName = pictureName || 'picture';

	function loadImages(imgAmount){
		var fileManager = [NSFileManager defaultManager];
		var scriptPath = sketch.scriptPath;
		var pluginFolder = scriptPath.match(/Plugins\/([\w -])*/)[0] + "/";
		var sketchPluginsPath = scriptPath.replace(/Plugins([\w \/ -])*.sketchplugin$/, "");
		var imagesPath =  sketchPluginsPath + pluginFolder + dataPath;
		var imagesFileNames = [fileManager contentsOfDirectoryAtPath:imagesPath error:nil];
		var imageCount = [imagesFileNames count] -1;
		var selectedPaths = [];

		if(imgAmount > imageCount){
			while(imgAmount--) {
				var index = Math.floor(Math.random() * imageCount);
				do {
					index = index > imageCount ? 0 : index + 1;
					var fileName = imagesFileNames[index];
					var filePath = imagesPath + fileName;
				} while(![fileManager fileExistsAtPath: filePath] || fileName == '.DS_Store')

				selectedPaths.push(filePath);
			}
		}
		else{
			while(imgAmount--) {
				do {
					var index = Math.floor(Math.random() * imageCount);
					var fileName = imagesFileNames[index];
					var filePath = imagesPath + fileName;
					var match = selectedPaths.filter(function(selectedPath){return filePath == selectedPath;});
				} while(fileName == '.DS_Store' || ![fileManager fileExistsAtPath: filePath] || match.length >= 1);
				selectedPaths.push(filePath);
			}
		}

		return selectedPaths.map(function(imagePath){
			if ([fileManager fileExistsAtPath: imagePath]) {
				var image = [[NSImage alloc] initWithContentsOfFile:imagePath];
				return image;
			}
		})
	}

	function main(){
		var allLayers = [[doc currentPage] layers],
			imagesCollection = loadImages([selection count] + 1);

		for(var i = 0; i < [selection count]; i++){
			var layer = selection[i];
            if([layer class] == MSShapeGroup){
                var image = imagesCollection[i];
                var fill = layer.style().fills().firstObject();
                fill.setFillType(4);
                if(tools.minorVersion() >= 1){
                	var coll = layer.style().fills().firstObject().documentData().images();
                	[fill setPatternImage:image collection:coll]
                }
                else{
                	layer.style().fills().firstObject().setPatternImage( image );
                }
                layer.style().fills().firstObject().setPatternFillType(1);
            }
		}

		if([selection count] == 0) [doc showMessage:'Select at least one vector shape'];;
	}
	main();
}

<|endoftext|>


<commit_before>var warningMessage = 'The property %s can not show in inspector, \
because it keeps return new object. \
Please set visible to false in properties define in this class.';

function _fieldSection ( name, target, closable ) {
    //
    var fireSectionEL = new FireSection();
    fireSectionEL.name = name;
    fireSectionEL.closable = closable;
    fireSectionEL.$ = {};

    var isComponent = target instanceof Fire.Component;
    var isBuiltinComp = isComponent && !target._scriptUuid;

    var klass = target.constructor;
    if (klass.__props__) {
        for (var p = 0; p < klass.__props__.length; p++) {
            var propName = klass.__props__[p];
            var attrs = Fire.attr(klass, propName);

            // skip hide-in-inspector
            if ( attrs.hideInInspector ) {
                continue;
            }

            if ( isBuiltinComp && propName === '_scriptUuid' ) {
                continue;
            }

            // NOTE: this protects issues like fireball-x/dev#483
            if ( attrs.hasGetter ) {
                var val1 = target[propName];
                if ( typeof val1 === 'object' && val1 && !val1.equals ) {
                    var val2 = target[propName];
                    if ( val1 !== val2 ) {
                        Fire.warn( warningMessage, propName );
                        continue;
                    }
                }
            }

            var propEL = new FireProp();
            propEL.initWithAttrs(target, propName, attrs);

            fireSectionEL.$[propName] = propEL;
            fireSectionEL.appendChild( propEL );
        }
    }

    if ( fireSectionEL.closable ) {
        fireSectionEL.addEventListener('close', function ( event ) {
            event.stopPropagation();
            Editor.sendToMainWindow('engine:remove-component', {
                'component-id': target.id
            });
        });
    }

    return fireSectionEL;
}

Polymer({
    created: function () {
        this.target = null;
    },

    refresh: function () {
        // remove all children
        while (this.firstElementChild) {
            this.removeChild(this.firstElementChild);
        }

        if ( !this.target ) {
            return;
        }

        //
        var el;
        if ( this.target instanceof Fire.Asset ) {
            el = _fieldSection( 'Asset', this.target, false );
            this.appendChild( el );
        }
        else if ( this.target instanceof Editor.AssetMeta ) {
            el = _fieldSection( 'Meta', this.target, false );
            this.appendChild( el );
        }
        else if ( this.target instanceof Fire.Entity ) {
            var docfrag = document.createDocumentFragment();

            for ( var i = 0; i < this.target._components.length; ++i ) {
                var comp = this.target._components[i];
                el = _fieldSection( Fire.JS.getClassName(comp), comp, true );
                docfrag.appendChild(el);
            }

            this.appendChild( docfrag );
        }
    },
});
<commit_msg>Inspector: read property attributes from instance instead of classes<commit_after>var warningMessage = 'The property %s can not show in inspector, \
because it keeps return new object. \
Please set visible to false in properties define in this class.';

function _fieldSection ( name, target, closable ) {
    //
    var fireSectionEL = new FireSection();
    fireSectionEL.name = name;
    fireSectionEL.closable = closable;
    fireSectionEL.$ = {};

    var isComponent = target instanceof Fire.Component;
    var isBuiltinComp = isComponent && !target._scriptUuid;

    var klass = target.constructor;
    if (klass.__props__) {
        for (var p = 0; p < klass.__props__.length; p++) {
            var propName = klass.__props__[p];
            var attrs = Fire.attr(target, propName);

            // skip hide-in-inspector
            if ( attrs.hideInInspector ) {
                continue;
            }

            if ( isBuiltinComp && propName === '_scriptUuid' ) {
                continue;
            }

            // NOTE: this protects issues like fireball-x/dev#483
            if ( attrs.hasGetter ) {
                var val1 = target[propName];
                if ( typeof val1 === 'object' && val1 && !val1.equals ) {
                    var val2 = target[propName];
                    if ( val1 !== val2 ) {
                        Fire.warn( warningMessage, propName );
                        continue;
                    }
                }
            }

            var propEL = new FireProp();
            propEL.initWithAttrs(target, propName, attrs);

            fireSectionEL.$[propName] = propEL;
            fireSectionEL.appendChild( propEL );
        }
    }

    if ( fireSectionEL.closable ) {
        fireSectionEL.addEventListener('close', function ( event ) {
            event.stopPropagation();
            Editor.sendToMainWindow('engine:remove-component', {
                'component-id': target.id
            });
        });
    }

    return fireSectionEL;
}

Polymer({
    created: function () {
        this.target = null;
    },

    refresh: function () {
        // remove all children
        while (this.firstElementChild) {
            this.removeChild(this.firstElementChild);
        }

        if ( !this.target ) {
            return;
        }

        //
        var el;
        if ( this.target instanceof Fire.Asset ) {
            el = _fieldSection( 'Asset', this.target, false );
            this.appendChild( el );
        }
        else if ( this.target instanceof Editor.AssetMeta ) {
            el = _fieldSection( 'Meta', this.target, false );
            this.appendChild( el );
        }
        else if ( this.target instanceof Fire.Entity ) {
            var docfrag = document.createDocumentFragment();

            for ( var i = 0; i < this.target._components.length; ++i ) {
                var comp = this.target._components[i];
                el = _fieldSection( Fire.JS.getClassName(comp), comp, true );
                docfrag.appendChild(el);
            }

            this.appendChild( docfrag );
        }
    },
});
<|endoftext|>


<commit_before>import GLBoost from './globals'
import Element from './Element'
import GLContext from './GLContext'
import GLExtentionsManager from './GLExtentionsManager'
import BlendShapeShaderSource from './shaders/BlendShapeShader'
import Mesh from './Geometry'

export default class BlendShapeMesh extends Mesh {
  constructor(canvas) {
    super(canvas);

    class BlendShapeShader extends this._shader_for_non_material.constructor {
      constructor(canvas) {
        super(canvas);
        BlendShapeShader.mixin(BlendShapeShaderSource);
      }
    }

    this._shader_for_non_material = new BlendShapeShader(canvas);
    this._shaderClass = BlendShapeShader;
  }

  prepareForRender(existCamera_f, pointLight) {

    // before prepareForRender of 'Geometry' class, a new 'BlendShapeShader'(which extends default shader) is assigned.
    let materials = this._materials;
    if (materials) {
      for (let i=0; i<materials.length;i++) {
        materials[i].shader = new this._shaderClass(this._canvas);
      }
    }

    super.prepareForRender(existCamera_f, pointLight);
  }

  _setBlendWeightToGlslProgram(blendTarget, weight) {
    var materials = this._materials;
    if (materials) {
      for (let i=0; i<materials.length;i++) {
        this._gl.useProgram(materials[i].glslProgram);
        this._gl.uniform1f(materials[i].glslProgram['uniformFloatSampler_blendWeight_' + blendTarget], weight);
      }
    } else {
      this._gl.useProgram(this._glslProgram);
      this._gl.uniform1f(this._glslProgram['uniformFloatSampler_blendWeight_' + blendTarget], weight);
    }
  }

  set blendWeight_1(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET1, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_2(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET2, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_3(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET3, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_4(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET4, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_5(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET5, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_6(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET6, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_7(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET7, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_8(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET8, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_9(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET9, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_10(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET10, weight);
    gl.useProgram(currentProgram);
  }

}

GLBoost["BlendShapeMesh"] = BlendShapeMesh;
<commit_msg>(refs #7) Fix BlendShapeMesh's parent name.<commit_after>import GLBoost from './globals'
import Element from './Element'
import GLContext from './GLContext'
import GLExtentionsManager from './GLExtentionsManager'
import BlendShapeShaderSource from './shaders/BlendShapeShader'
import Geometry from './Geometry'

export default class BlendShapeMesh extends Geometry {
  constructor(canvas) {
    super(canvas);

    class BlendShapeShader extends this._shader_for_non_material.constructor {
      constructor(canvas) {
        super(canvas);
        BlendShapeShader.mixin(BlendShapeShaderSource);
      }
    }

    this._shader_for_non_material = new BlendShapeShader(canvas);
    this._shaderClass = BlendShapeShader;
  }

  prepareForRender(existCamera_f, pointLight) {

    // before prepareForRender of 'Geometry' class, a new 'BlendShapeShader'(which extends default shader) is assigned.
    let materials = this._materials;
    if (materials) {
      for (let i=0; i<materials.length;i++) {
        materials[i].shader = new this._shaderClass(this._canvas);
      }
    }

    super.prepareForRender(existCamera_f, pointLight);
  }

  _setBlendWeightToGlslProgram(blendTarget, weight) {
    var materials = this._materials;
    if (materials) {
      for (let i=0; i<materials.length;i++) {
        this._gl.useProgram(materials[i].glslProgram);
        this._gl.uniform1f(materials[i].glslProgram['uniformFloatSampler_blendWeight_' + blendTarget], weight);
      }
    } else {
      this._gl.useProgram(this._glslProgram);
      this._gl.uniform1f(this._glslProgram['uniformFloatSampler_blendWeight_' + blendTarget], weight);
    }
  }

  set blendWeight_1(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET1, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_2(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET2, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_3(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET3, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_4(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET4, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_5(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET5, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_6(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET6, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_7(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET7, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_8(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET8, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_9(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET9, weight);
    gl.useProgram(currentProgram);
  }
  set blendWeight_10(weight) {
    var gl = this._gl;
    var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);

    this._setBlendWeightToGlslProgram(GLBoost.BLENDTARGET10, weight);
    gl.useProgram(currentProgram);
  }

}

GLBoost["BlendShapeMesh"] = BlendShapeMesh;
<|endoftext|>


<commit_before>(function () {
    'use strict';

    window.i18n = {
        /**
         * Error message after submission
         *
         * "The account id provided is invalid"
         */
        invalidId: "Le compte fourni n'est pas valide.",

        /**
         * Form label
         *
         * "Your account ID:"
         */
        yourAcctId: "Votre compte :",

        /**
         * Form placeholder
         *
         * Please keep "@example.org" as a domain
         * since it's a reserved domain name (http://www.iana.org/domains/reserved)
         *
         * "user@example.org"
         */
        idPlaceholder: "utilisateur@example.org",

        /**
         * Checkbox label
         *
         * "Share as a bookmark"
         */
        shareAsBookmark: "Partager en format signet"
    };
}());
<commit_msg>Add French translation for 'submit' button<commit_after>(function () {
    'use strict';

    window.i18n = {
        /**
         * Error message after submission
         *
         * "The account id provided is invalid"
         */
        invalidId: "Le compte fourni n'est pas valide.",

        /**
         * Form label
         *
         * "Your account ID:"
         */
        yourAcctId: "Votre compte :",

        /**
         * Form placeholder
         *
         * Please keep "@example.org" as a domain
         * since it's a reserved domain name (http://www.iana.org/domains/reserved)
         *
         * "user@example.org"
         */
        idPlaceholder: "utilisateur@example.org",

        /**
         * Checkbox label
         *
         * "Share as a bookmark"
         */
        shareAsBookmark: "Partager en format signet",

        /**
         * Submit button
         *
         * "Share"
         */
        submit: "Partager"
    };
}());
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import {
  createPortal,
  unmountComponentAtNode as unmount,
  unstable_renderSubtreeIntoContainer as render,
} from 'react-dom';

const isReact16 = typeof createPortal === 'function';

/**
 * Creates a "Portal" for the children to be rendered in. Basically it will render the
 * children only when the `visible` prop is `true`. When it is visible, a new `component`
 * will be rendered as the first child in the body with the children inside.
 *
 * Unlike all the other components, `style` will not be applied for the `Portal`.
 */
export default class Portal extends PureComponent {
  static propTypes = {
    /**
     * An optional className to apply to the newly created `component` when visible.
     */
    className: PropTypes.string,

    /**
     * Boolean if the children are visible.
     */
    visible: PropTypes.bool.isRequired,

    /**
     * The children to render when visible.
     */
    children: PropTypes.element,

    /**
     * The component to render as. This should be a valid DOM element.
     */
    component: PropTypes.string.isRequired,

    /**
     * An optional function to call when the portal is opened.
     */
    onOpen: PropTypes.func,

    /**
     * An optional function to call when the portal is closed
     */
    onClose: PropTypes.func,

    /**
     * An optional DOM Node to render the portal into. The default is to render as
     * the first child in the `body`.
     */
    renderNode: PropTypes.object,

    /**
     * Boolean if the portal should render the children as the last child of the `renderNode`
     * or `body` instead of the first.
     */
    lastChild: PropTypes.bool,
  };

  static defaultProps = {
    component: 'span',
  };

  componentDidMount() {
    if (this.props.visible) {
      this._renderPortal(this.props);

      if (isReact16) {
        // Need to update after the renderPortal created the DOM element.
        this.forceUpdate();
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    const { visible, onOpen } = nextProps;
    if (this.props.visible === visible) {
      if (!isReact16) {
        // Need to just re-render the subtree
        this._renderPortal(nextProps);
      }

      return;
    }

    if (visible) {
      if (onOpen) {
        onOpen();
      }

      this._renderPortal(nextProps);
    } else {
      this._removePortal();
    }
  }

  componentWillUnmount() {
    this._removePortal();
  }

  _container = null;
  _portal = null;

  _applyStyles = (props) => {
    if (props.className) {
      this._container.className = props.className;
    }
  };

  _renderPortal = (props) => {
    if (!this._container) {
      this._container = document.createElement(props.component);

      this._applyStyles(props);
      const node = (props.renderNode || document.body);
      if (props.lastChild) {
        node.appendChild(this._container);
      } else {
        node.insertBefore(this._container, node.firstChild);
      }
    } else {
      this._applyStyles(props);
    }

    if (!isReact16) {
      this._portal = render(this, props.children, this._container);
    }
  };

  _removePortal = () => {
    if (this.props.onClose) {
      this.props.onClose();
    }

    if (this._container) {
      if (!isReact16) {
        unmount(this._container);
      }

      (this.props.renderNode || document.body).removeChild(this._container);
    }

    this._portal = null;
    this._container = null;
  };

  render() {
    const { component: Component, className, children, visible } = this.props;

    // When doing server side rendering, actually render the component as a direct child of its parent.
    // Once it has been rendered and working client side, it will be removed correctly.
    if (typeof window === 'undefined' && visible) {
      return <Component className={className}>{children}</Component>;
    } else if (isReact16 && visible && this._container && typeof window !== 'undefined') {
      return createPortal(children, this._container);
    }

    return null;
  }
}
<commit_msg>Fixed the React 15 Portals<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import {
  createPortal,
  unmountComponentAtNode as unmount,
  unstable_renderSubtreeIntoContainer as render,
} from 'react-dom';

const isReact16 = typeof createPortal === 'function';

/**
 * Creates a "Portal" for the children to be rendered in. Basically it will render the
 * children only when the `visible` prop is `true`. When it is visible, a new `component`
 * will be rendered as the first child in the body with the children inside.
 *
 * Unlike all the other components, `style` will not be applied for the `Portal`.
 */
export default class Portal extends PureComponent {
  static propTypes = {
    /**
     * An optional className to apply to the newly created `component` when visible.
     */
    className: PropTypes.string,

    /**
     * Boolean if the children are visible.
     */
    visible: PropTypes.bool.isRequired,

    /**
     * The children to render when visible.
     */
    children: PropTypes.element,

    /**
     * The component to render as. This should be a valid DOM element.
     */
    component: PropTypes.string.isRequired,

    /**
     * An optional function to call when the portal is opened.
     */
    onOpen: PropTypes.func,

    /**
     * An optional function to call when the portal is closed
     */
    onClose: PropTypes.func,

    /**
     * An optional DOM Node to render the portal into. The default is to render as
     * the first child in the `body`.
     */
    renderNode: PropTypes.object,

    /**
     * Boolean if the portal should render the children as the last child of the `renderNode`
     * or `body` instead of the first.
     */
    lastChild: PropTypes.bool,
  };

  static defaultProps = {
    component: 'span',
  };

  componentDidMount() {
    if (this.props.visible) {
      this._renderPortal(this.props);

      if (isReact16) {
        // Need to update after the renderPortal created the DOM element.
        this.forceUpdate();
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    const { visible, onOpen } = nextProps;
    if (this.props.visible === visible) {
      if (visible && !isReact16) {
        // Need to just re-render the subtree
        this._renderPortal(nextProps);
      }

      return;
    }

    if (visible) {
      if (onOpen) {
        onOpen();
      }

      this._renderPortal(nextProps);
    } else {
      this._removePortal();
    }
  }

  componentWillUnmount() {
    this._removePortal();
  }

  _container = null;
  _portal = null;

  _applyStyles = (props) => {
    if (props.className) {
      this._container.className = props.className;
    }
  };

  _renderPortal = (props) => {
    if (!this._container) {
      this._container = document.createElement(props.component);

      this._applyStyles(props);
      const node = (props.renderNode || document.body);
      if (props.lastChild) {
        node.appendChild(this._container);
      } else {
        node.insertBefore(this._container, node.firstChild);
      }
    } else {
      this._applyStyles(props);
    }

    if (!isReact16) {
      this._portal = render(this, props.children, this._container);
    }
  };

  _removePortal = () => {
    if (this.props.onClose) {
      this.props.onClose();
    }

    if (this._container) {
      if (!isReact16) {
        unmount(this._container);
      }

      (this.props.renderNode || document.body).removeChild(this._container);
    }

    this._portal = null;
    this._container = null;
  };

  render() {
    const { component: Component, className, children, visible } = this.props;

    // When doing server side rendering, actually render the component as a direct child of its parent.
    // Once it has been rendered and working client side, it will be removed correctly.
    if (typeof window === 'undefined' && visible) {
      return <Component className={className}>{children}</Component>;
    } else if (isReact16 && visible && this._container && typeof window !== 'undefined') {
      return createPortal(children, this._container);
    }

    return null;
  }
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import MediaQuery from 'react-responsive';
import styled from 'styled-components';

import { withEither, withMaybe } from '../components/higher-order-components/index';
import DesktopLudoPage from './DesktopLudoPage';
import MobilePlayingLudo from './MobilePlayingLudo';
import MobileReadyLudo from './MobileReadyLudo';

// rendering condition function
const isUserAuthToViewMobileReadyLudo = (props) => {
    const authToViewMobileReadyLudo = [ 0, 1, 2 ];
    return authToViewMobileReadyLudo.includes(props.router_ludoPageIndex);
};

// child components
const MobileLudoPage = withEither(isUserAuthToViewMobileReadyLudo, MobileReadyLudo)(MobilePlayingLudo);

class LudoPage extends Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
        this.props.handleIsOpeningReportPage(true);
    }

    componentWillUnmount() {
        this.props.handleIsOpeningReportPage(false);
    }

    /* components/_report-form.scss */
    render() {
        const {
            currentLudoReportData,
            currentUserId,
            handleDenounceBoxOpen,
            handleHasGotNewReport,
            handleShouldProfileUpdate,
            handleShouldReportUpdate,
            hasGotNewReport,
            params,
            router_currentFormValue,
            router_ludoPageIndex,
            userBasicData,
        } = this.props;

        return (

                <MediaQuery minWidth={769}>
                    <DesktopLudoPage
                        currentLudoReportData={currentLudoReportData}
                        currentUserId={currentUserId}
                        handleDenounceBoxOpen={handleDenounceBoxOpen}
                        handleHasGotNewReport={handleHasGotNewReport}
                        handleShouldProfileUpdate={handleShouldProfileUpdate}
                        handleShouldReportUpdate={handleShouldReportUpdate}
                        hasGotNewReport={hasGotNewReport}
                        ludoId={params.ludo_id}
                        router_currentFormValue={router_currentFormValue}
                        router_ludoPageIndex={router_ludoPageIndex}
                        userBasicData={userBasicData}
                    />
                </MediaQuery>
                <MediaQuery maxWidth={768}>
                    <MobileLudoPage
                        {...this.props}
                    />
                </MediaQuery>

        );
    }
}

export default LudoPage;
<commit_msg>Fix #84<commit_after>import React, { Component } from 'react';
import MediaQuery from 'react-responsive';
import styled from 'styled-components';

import { withEither, withMaybe } from '../components/higher-order-components/index';
import DesktopLudoPage from './DesktopLudoPage';
import MobilePlayingLudo from './MobilePlayingLudo';
import MobileReadyLudo from './MobileReadyLudo';

// rendering condition function
const isUserAuthToViewMobileReadyLudo = (props) => {
    const authToViewMobileReadyLudo = [ 0, 1, 2 ];
    return authToViewMobileReadyLudo.includes(props.router_ludoPageIndex);
};

// child components
const MobileLudoPage = withEither(isUserAuthToViewMobileReadyLudo, MobileReadyLudo)(MobilePlayingLudo);

class LudoPage extends Component {
    constructor(props) {
        super(props);
    }

    componentWillMount() {
        this.props.handleIsOpeningReportPage(true);
    }

    componentWillUnmount() {
        this.props.handleIsOpeningReportPage(false);
    }

    /* components/_report-form.scss */
    render() {
        const {
            currentLudoReportData,
            currentUserId,
            getUserBasicData,
            handleDenounceBoxOpen,
            handleHasGotNewReport,
            handleShouldProfileUpdate,
            handleShouldReportUpdate,
            hasGotNewReport,
            params,
            router_currentFormValue,
            router_ludoPageIndex,
            userBasicData,
        } = this.props;

        return (

                <MediaQuery minWidth={769}>
                    <DesktopLudoPage
                        currentLudoReportData={currentLudoReportData}
                        currentUserId={currentUserId}
                        getUserBasicData={getUserBasicData}
                        handleDenounceBoxOpen={handleDenounceBoxOpen}
                        handleHasGotNewReport={handleHasGotNewReport}
                        handleShouldProfileUpdate={handleShouldProfileUpdate}
                        handleShouldReportUpdate={handleShouldReportUpdate}
                        hasGotNewReport={hasGotNewReport}
                        ludoId={params.ludo_id}
                        router_currentFormValue={router_currentFormValue}
                        router_ludoPageIndex={router_ludoPageIndex}
                        userBasicData={userBasicData}
                    />
                </MediaQuery>
                <MediaQuery maxWidth={768}>
                    <MobileLudoPage
                        {...this.props}
                    />
                </MediaQuery>

        );
    }
}

export default LudoPage;
<|endoftext|>


<commit_before>"use strict";

/*global mediaWiki, jQuery*/

/*
 Search behaviour for a search box which is displayed as part of a Category when using the Steep skin.

 The search box will have suggestion as you type.

 The results will be constrained to be within the Category the user is viewing.

 For the standard search behaviour (which we are not using), see [https://github.com/wikimedia/mediawiki/blob/REL1_25/resources/src/mediawiki/mediawiki.searchSuggest.js].

 We are, however, using the same jQuery suggestions plugin [https://github.com/wikimedia/mediawiki/blob/REL1_25/resources/src/jquery/jquery.suggestions.js].
 */
(function(mw, $) {
    var isCategoryPage = function() {
	return mw.config.values.wgNamespaceNumber === mw.config.values.wgNamespaceIds.category;
    };

    mw.hook('wikipage.content').add(function(content) {
	if (!isCategoryPage()) {
	    return;
	}

	var category = mw.config.values.wgTitle,
	    inCategory = 'incategory:"' + category + '" ',
	    searchTitle = new mw.Title("Search", mw.config.values.wgNamespaceIds.special),
	    api = new mw.Api(),

	    queryOnSearchPage = function(query) {
		return searchTitle.getUrl()
		    + "?search=" + inCategory + query
		    + "&fulltext=1";
	    },

	    searchForms = $('.search-form')
		.on('submit', function(e) {
		    e.preventDefault();

		    window.location.assign(
		    	"?search=" + inCategory + $(this).find('input')[0].value
		    );
		}),
	    searchInputs = searchForms.find('input');

	searchInputs.suggestions({
	    fetch: function(query, response, maxRows) {
		var request = api
			.get({
			    action: 'query',
			    list: 'search',
			    srsearch: inCategory + query,
			    srlimit: maxRows
			})
			.done(function(data) {
			    if (data.warnings) {
				console.warn(data.warnings);
			    }

			    data.query.search.forEach(function(result) {
				result.toString = function() {
				    return result.title;
				};
			    });

			    response(data.query.search);
			});

		this.data('lastRequest', request);
	    },

	    cancel: function() {
		if (this.data().lastRequest) {
		    this.data().lastRequest.abort();
		}

		this.removeData('lastRequest');
	    },

	    result: {
		render: function(text, context) {
		    var title = new mw.Title(text.title, text.ns);

		    var a = $('<a>')
			    .attr('href', title.getUrl())
			    .attr('title', title.getName())
			    .addClass('mw-searchSuggest-link')
			    .text(title.getName());

		    this.append(a);
		},

		select: function(selected, context) {
		    window.location.assign(
			this.find('a').attr('href')
		    );
		    return false;
		}
	    },

	    special: {
		render: function(query, context) {
		    /*
		     Adds in a special element which takes you to the main search page.
		     */

		    this
			.on('click', function(e) {
			    e.stopPropagation();
			})
			.empty()
			.append(
			    $('<a>')
				.addClass('special-label')
				.attr(
				    'href',
				    queryOnSearchPage(query)
				)
				.text(mw.msg('searchsuggest-containing'))
				.append(
				    $('<div>')
					.addClass('special-query')
					.text(query)
				)
			)
			.show();
		},

		select: function(selected, context) {
		    window.location.assign(
			this.find('a').attr('href')
		    );
		    return false;
		}
	    }
	})
	    .on('cut paste drop focus', function() {
		/*
		 Pretend these events are keypresses, so that they'll trigger search.
		 */
		$(this).trigger('keypress');
	    });
    });

}(mediaWiki, jQuery));
<commit_msg>Search inside project now looks for categories and files as well.<commit_after>"use strict";

/*global mediaWiki, jQuery*/

/*
 Search behaviour for a search box which is displayed as part of a Category when using the Steep skin.

 The search box will have suggestion as you type.

 The results will be constrained to be within the Category the user is viewing.

 For the standard search behaviour (which we are not using), see [https://github.com/wikimedia/mediawiki/blob/REL1_25/resources/src/mediawiki/mediawiki.searchSuggest.js].

 We are, however, using the same jQuery suggestions plugin [https://github.com/wikimedia/mediawiki/blob/REL1_25/resources/src/jquery/jquery.suggestions.js].
 */
(function(mw, $) {
    var isCategoryPage = function() {
	return mw.config.values.wgNamespaceNumber === mw.config.values.wgNamespaceIds.category;
    };

    mw.hook('wikipage.content').add(function(content) {
	if (!isCategoryPage()) {
	    return;
	}

	var category = mw.config.values.wgTitle,
	    inCategory = 'incategory:"' + category + '" ',
	    searchTitle = new mw.Title("Search", mw.config.values.wgNamespaceIds.special),
	    api = new mw.Api(),

	    queryOnSearchPage = function(query) {
		return searchTitle.getUrl()
		    + "?search=" + inCategory + query
		    + "&fulltext=1";
	    },

	    searchForms = $('.search-form')
		.on('submit', function(e) {
		    e.preventDefault();

		    window.location.assign(
		    	"?search=" + inCategory + $(this).find('input')[0].value
		    );
		}),
	    searchInputs = searchForms.find('input');

	searchInputs.suggestions({
	    fetch: function(query, response, maxRows) {
		var request = api
			.get({
			    action: 'query',
			    list: 'search',
			    srsearch: inCategory + query,
			    srlimit: maxRows,
			    srnamespace: [
				mw.config.values.wgNamespaceIds[''],
				mw.config.values.wgNamespaceIds.category,
				mw.config.values.wgNamespaceIds.file
			    ]
			})
			.done(function(data) {
			    if (data.warnings) {
				console.warn(data.warnings);
			    }

			    data.query.search.forEach(function(result) {
				result.toString = function() {
				    return result.title;
				};
			    });

			    response(data.query.search);
			});

		this.data('lastRequest', request);
	    },

	    cancel: function() {
		if (this.data().lastRequest) {
		    this.data().lastRequest.abort();
		}

		this.removeData('lastRequest');
	    },

	    result: {
		render: function(text, context) {
		    var title = new mw.Title(text.title, text.ns),
			titleText = title.getNamespacePrefix() + title.getName();

		    var a = $('<a>')
			    .addClass("search-result-" + (title.getNamespacePrefix() || "page"))
			    .attr('href', title.getUrl())
			    .attr('title', titleText)
			    .addClass('mw-searchSuggest-link')
			    .text(titleText);

		    this.append(a);
		},

		select: function(selected, context) {
		    window.location.assign(
			this.find('a').attr('href')
		    );
		    return false;
		}
	    },

	    special: {
		render: function(query, context) {
		    /*
		     Adds in a special element which takes you to the main search page.
		     */

		    this
			.on('click', function(e) {
			    e.stopPropagation();
			})
			.empty()
			.append(
			    $('<a>')
				.addClass('special-label')
				.attr(
				    'href',
				    queryOnSearchPage(query)
				)
				.text(mw.msg('searchsuggest-containing'))
				.append(
				    $('<div>')
					.addClass('special-query')
					.text(query)
				)
			)
			.show();
		},

		select: function(selected, context) {
		    window.location.assign(
			this.find('a').attr('href')
		    );
		    return false;
		}
	    }
	})
	    .on('cut paste drop focus', function() {
		/*
		 Pretend these events are keypresses, so that they'll trigger search.
		 */
		$(this).trigger('keypress');
	    });
    });

}(mediaWiki, jQuery));
<|endoftext|>


<commit_before>Rickshaw.namespace('Rickshaw.Graph');

Rickshaw.Graph = function(args) {

	if (!args.element) throw "Rickshaw.Graph needs a reference to an element";

	this.element = args.element;
	this.series = args.series;

	this.defaults = {
		interpolation: 'cardinal',
		offset: 'zero',
		min: undefined,
		max: undefined,
		preserve: false
	};

	Rickshaw.keys(this.defaults).forEach( function(k) {
		this[k] = args[k] || this.defaults[k];
	}, this );

	this.window = {};

	this.updateCallbacks = [];

	var self = this;

	this.initialize = function(args) {

		this.validateSeries(args.series);

		this.series.active = function() { return self.series.filter( function(s) { return !s.disabled } ) };

		this.setSize({ width: args.width, height: args.height });

		this.element.classList.add('rickshaw_graph');
		this.vis = d3.select(this.element)
			.append("svg:svg")
			.attr('width', this.width)
			.attr('height', this.height);

		var renderers = [
			Rickshaw.Graph.Renderer.Stack,
			Rickshaw.Graph.Renderer.Line,
			Rickshaw.Graph.Renderer.Bar,
			Rickshaw.Graph.Renderer.Area,
			Rickshaw.Graph.Renderer.ScatterPlot,
			Rickshaw.Graph.Renderer.Multi
		];

		renderers.forEach( function(r) {
			if (!r) return;
			self.registerRenderer(new r( { graph: self } ));
		} );

		this.setRenderer(args.renderer || 'stack', args);
		this.discoverRange();
	};

	this.validateSeries = function(series) {

		if (!Array.isArray(series) && !(series instanceof Rickshaw.Series)) {
			var seriesSignature = Object.prototype.toString.apply(series);
			throw "series is not an array: " + seriesSignature;
		}

		var pointsCount;

		series.forEach( function(s) {

			if (!(s instanceof Object)) {
				throw "series element is not an object: " + s;
			}
			if (!(s.data)) {
				throw "series has no data: " + JSON.stringify(s);
			}
			if (!Array.isArray(s.data)) {
				throw "series data is not an array: " + JSON.stringify(s.data);
			}

			var x = s.data[0].x;
			var y = s.data[0].y;

			if (typeof x != 'number' || ( typeof y != 'number' && y !== null ) ) {
				throw "x and y properties of points should be numbers instead of " +
					(typeof x) + " and " + (typeof y);
			}

		}, this );
	};

	this.dataDomain = function() {

		// take from the first series
		var data = this.series[0].data;

		return [ data[0].x, data.slice(-1).shift().x ];

	};

	this.discoverRange = function() {

		var domain = this.renderer.domain();

		this.x = d3.scale.linear().domain(domain.x).range([0, this.width]);

		this.y = d3.scale.linear().domain(domain.y).range([this.height, 0]);

		this.y.magnitude = d3.scale.linear()
			.domain([domain.y[0] - domain.y[0], domain.y[1] - domain.y[0]])
			.range([0, this.height]);
	};

	this.render = function() {

		var stackedData = this.stackData();
		this.discoverRange();

		this.renderer.render();

		this.updateCallbacks.forEach( function(callback) {
			callback();
		} );
	};

	this.update = this.render;

	this.stackData = function() {

		var data = this.series.active()
			.map( function(d) { return d.data } )
			.map( function(d) { return d.filter( function(d) { return this._slice(d) }, this ) }, this);

		var preserve = this.preserve;
		if (!preserve) {
			this.series.forEach( function(series) {
				if (series.scale) {
					// data must be preserved when a scale is used
					preserve = true;
				}
			} );
		}

		data = preserve ? Rickshaw.clone(data) : data;

		this.series.forEach( function(series, index) {
			if (series.scale) {
				// apply scale to each series
				var seriesData = data[index];
				if(seriesData) {
					seriesData.forEach( function(d) {
						d.y = series.scale(d.y);
					} );
				}
			}
		} );

		this.stackData.hooks.data.forEach( function(entry) {
			data = entry.f.apply(self, [data]);
		} );

		var stackedData;

		if (!this.renderer.unstack) {

			this._validateStackable();

			var layout = d3.layout.stack();
			layout.offset( self.offset );
			stackedData = layout(data);
		}

		stackedData = stackedData || data;

		this.stackData.hooks.after.forEach( function(entry) {
			stackedData = entry.f.apply(self, [data]);
		} );

		var i = 0;
		this.series.forEach( function(series) {
			if (series.disabled) return;
			series.stack = stackedData[i++];
		} );

		this.stackedData = stackedData;
		return stackedData;
	};

	this._validateStackable = function() {

		var series = this.series;
		var pointsCount;

		series.forEach( function(s) {

			pointsCount = pointsCount || s.data.length;

			if (pointsCount && s.data.length != pointsCount) {
				throw "stacked series cannot have differing numbers of points: " +
					pointsCount + " vs " + s.data.length + "; see Rickshaw.Series.fill()";
			}

		}, this );
	};

	this.stackData.hooks = { data: [], after: [] };

	this._slice = function(d) {

		if (this.window.xMin || this.window.xMax) {

			var isInRange = true;

			if (this.window.xMin && d.x < this.window.xMin) isInRange = false;
			if (this.window.xMax && d.x > this.window.xMax) isInRange = false;

			return isInRange;
		}

		return true;
	};

	this.onUpdate = function(callback) {
		this.updateCallbacks.push(callback);
	};

	this.registerRenderer = function(renderer) {
		this._renderers = this._renderers || {};
		this._renderers[renderer.name] = renderer;
	};

	this.configure = function(args) {

		if (args.width || args.height) {
			this.setSize(args);
		}

		Rickshaw.keys(this.defaults).forEach( function(k) {
			this[k] = k in args ? args[k]
				: k in this ? this[k]
				: this.defaults[k];
		}, this );

		this.setRenderer(args.renderer || this.renderer.name, args);
	};

	this.setRenderer = function(r, args) {
		if (typeof r == 'function') {
			this.renderer = new r( { graph: self } );
			this.registerRenderer(this.renderer);
		} else {
			if (!this._renderers[r]) {
				throw "couldn't find renderer " + r;
			}
			this.renderer = this._renderers[r];
		}

		if (typeof args == 'object') {
			this.renderer.configure(args);
		}
	};

	this.setSize = function(args) {

		args = args || {};

		if (typeof window !== undefined) {
			var style = window.getComputedStyle(this.element, null);
			var elementWidth = parseInt(style.getPropertyValue('width'), 10);
			var elementHeight = parseInt(style.getPropertyValue('height'), 10);
		}

		this.width = args.width || elementWidth || 400;
		this.height = args.height || elementHeight || 250;

		this.vis && this.vis
			.attr('width', this.width)
			.attr('height', this.height);
	};

	this.initialize(args);
};
<commit_msg>Update Rickshaw.Graph.js<commit_after>Rickshaw.namespace('Rickshaw.Graph');

Rickshaw.Graph = function(args) {

	if (!args.element) throw "Rickshaw.Graph needs a reference to an element";

	this.element = args.element;
	this.series = args.series;

	this.defaults = {
		interpolation: 'cardinal',
		offset: 'zero',
		min: undefined,
		max: undefined,
		preserve: false
	};

	Rickshaw.keys(this.defaults).forEach( function(k) {
		this[k] = args[k] || this.defaults[k];
	}, this );

	this.window = {};

	this.updateCallbacks = [];

	var self = this;

	this.initialize = function(args) {

		this.validateSeries(args.series);

		this.series.active = function() { return self.series.filter( function(s) { return !s.disabled } ) };

		this.setSize({ width: args.width, height: args.height });

		this.element.classList.add('rickshaw_graph');
		this.vis = d3.select(this.element)
			.append("svg:svg")
			.attr('width', this.width)
			.attr('height', this.height);

		var renderers = [
			Rickshaw.Graph.Renderer.Stack,
			Rickshaw.Graph.Renderer.Line,
			Rickshaw.Graph.Renderer.Bar,
			Rickshaw.Graph.Renderer.Area,
			Rickshaw.Graph.Renderer.ScatterPlot,
			Rickshaw.Graph.Renderer.Multi
		];

		renderers.forEach( function(r) {
			if (!r) return;
			self.registerRenderer(new r( { graph: self } ));
		} );

		this.setRenderer(args.renderer || 'stack', args);
		this.discoverRange();
	};

	this.validateSeries = function(series) {

		if (!Array.isArray(series) && !(series instanceof Rickshaw.Series)) {
			var seriesSignature = Object.prototype.toString.apply(series);
			throw "series is not an array: " + seriesSignature;
		}

		var pointsCount;

		series.forEach( function(s) {

			if (!(s instanceof Object)) {
				throw "series element is not an object: " + s;
			}
			if (!(s.data)) {
				throw "series has no data: " + JSON.stringify(s);
			}
			if (!Array.isArray(s.data)) {
				throw "series data is not an array: " + JSON.stringify(s.data);
			}

			var x = s.data[0].x;
			var y = s.data[0].y;

			if (typeof x != 'number' || ( typeof y != 'number' && y !== null ) ) {
				throw "x and y properties of points should be numbers instead of " +
					(typeof x) + " and " + (typeof y);
			}

		}, this );
	};

	this.dataDomain = function() {

		// take from the first series
		var data = this.series[0].data;

		return [ data[0].x, data.slice(-1).shift().x ];

	};

	this.discoverRange = function() {

		var domain = this.renderer.domain();

		this.x = d3.scale.linear().domain(domain.x).range([0, this.width]);

		this.y = d3.scale.linear().domain(domain.y).range([this.height, 0]);

		this.y.magnitude = d3.scale.linear()
			.domain([domain.y[0] - domain.y[0], domain.y[1] - domain.y[0]])
			.range([0, this.height]);
	};

	this.render = function() {

		var stackedData = this.stackData();
		this.discoverRange();

		this.renderer.render();

		this.updateCallbacks.forEach( function(callback) {
			callback();
		} );
	};

	this.update = this.render;

	this.stackData = function() {

		var data = this.series.active()
			.map( function(d) { return d.data } )
			.map( function(d) { return d.filter( function(d) { return this._slice(d) }, this ) }, this);

		var preserve = this.preserve;
		if (!preserve) {
			this.series.forEach( function(series) {
				if (series.scale) {
					// data must be preserved when a scale is used
					preserve = true;
				}
			} );
		}

		data = preserve ? Rickshaw.clone(data) : data;

		this.series.active().forEach( function(series, index) {
			if (series.scale) {
				// apply scale to each series
				var seriesData = data[index];
				if(seriesData) {
					seriesData.forEach( function(d) {
						d.y = series.scale(d.y);
					} );
				}
			}
		} );

		this.stackData.hooks.data.forEach( function(entry) {
			data = entry.f.apply(self, [data]);
		} );

		var stackedData;

		if (!this.renderer.unstack) {

			this._validateStackable();

			var layout = d3.layout.stack();
			layout.offset( self.offset );
			stackedData = layout(data);
		}

		stackedData = stackedData || data;

		this.stackData.hooks.after.forEach( function(entry) {
			stackedData = entry.f.apply(self, [data]);
		} );

		var i = 0;
		this.series.forEach( function(series) {
			if (series.disabled) return;
			series.stack = stackedData[i++];
		} );

		this.stackedData = stackedData;
		return stackedData;
	};

	this._validateStackable = function() {

		var series = this.series;
		var pointsCount;

		series.forEach( function(s) {

			pointsCount = pointsCount || s.data.length;

			if (pointsCount && s.data.length != pointsCount) {
				throw "stacked series cannot have differing numbers of points: " +
					pointsCount + " vs " + s.data.length + "; see Rickshaw.Series.fill()";
			}

		}, this );
	};

	this.stackData.hooks = { data: [], after: [] };

	this._slice = function(d) {

		if (this.window.xMin || this.window.xMax) {

			var isInRange = true;

			if (this.window.xMin && d.x < this.window.xMin) isInRange = false;
			if (this.window.xMax && d.x > this.window.xMax) isInRange = false;

			return isInRange;
		}

		return true;
	};

	this.onUpdate = function(callback) {
		this.updateCallbacks.push(callback);
	};

	this.registerRenderer = function(renderer) {
		this._renderers = this._renderers || {};
		this._renderers[renderer.name] = renderer;
	};

	this.configure = function(args) {

		if (args.width || args.height) {
			this.setSize(args);
		}

		Rickshaw.keys(this.defaults).forEach( function(k) {
			this[k] = k in args ? args[k]
				: k in this ? this[k]
				: this.defaults[k];
		}, this );

		this.setRenderer(args.renderer || this.renderer.name, args);
	};

	this.setRenderer = function(r, args) {
		if (typeof r == 'function') {
			this.renderer = new r( { graph: self } );
			this.registerRenderer(this.renderer);
		} else {
			if (!this._renderers[r]) {
				throw "couldn't find renderer " + r;
			}
			this.renderer = this._renderers[r];
		}

		if (typeof args == 'object') {
			this.renderer.configure(args);
		}
	};

	this.setSize = function(args) {

		args = args || {};

		if (typeof window !== undefined) {
			var style = window.getComputedStyle(this.element, null);
			var elementWidth = parseInt(style.getPropertyValue('width'), 10);
			var elementHeight = parseInt(style.getPropertyValue('height'), 10);
		}

		this.width = args.width || elementWidth || 400;
		this.height = args.height || elementHeight || 250;

		this.vis && this.vis
			.attr('width', this.width)
			.attr('height', this.height);
	};

	this.initialize(args);
};
<|endoftext|>


<commit_before>const config = require('../config.js');
const { Pages } = require('./helpers/pages.js');

// [pageId]: [userId]
const pagesMap = {
  'TENGON': 'TENGON',
  'ZAG': 'ZAG',
  'MM': 'MM',
  'AK': 'AKT',
  'AKT': 'AKT',
  'RAG': 'RAG',
  'BEM': 'BEM',
  'HOP': 'HOP',
  'AAT': 'AKT',
  'MK': 'MK',
  'DON': 'DON',
}

const script = {
  title: `Add author to all pages`,
  run: (client) =>
    client.search({
      index: config.index,
      size: config.size.max,
      type: 'pages'
    })
    .then(result => {
      const pages = result.hits.hits;
      const newPages = [];
      pages.forEach(page => {
        newPages.push({
          ...page['_source'],
          author: pagesMap[page['_id']] || 'ADMIN',
          url: page['_id']
        })
      })
      return Promise.resolve(newPages)
    })
    .then(pages => Pages.run(client, pages))
};

module.exports = script;
<commit_msg>put author to mapping<commit_after>const config = require('../config.js');
const { Pages } = require('./helpers/pages.js');

// [pageId]: [userId]
const pagesMap = {
  'TENGON': 'TENGON',
  'ZAG': 'ZAG',
  'MM': 'MM',
  'AK': 'AKT',
  'AKT': 'AKT',
  'RAG': 'RAG',
  'BEM': 'BEM',
  'HOP': 'HOP',
  'AAT': 'AKT',
  'MK': 'MK',
  'DON': 'DON',
}

const script = {
  title: `Add author to all pages`,
  run: (client) =>
    client.indices.putMapping({
      index: config.index,
      type: "pages",
      body: {
        "properties": {
          "url": {
            "type": "keyword"
          },
          "title": {
            "type": "text"
          },
          "author": {
            "type": "text"
          },
          "text": {
            "type": "text"
          }
        }
      }
    })
    .then(() =>
      client.search({
        index: config.index,
        size: config.size.max,
        type: 'pages'
      })
      .then(result => {
        const pages = result.hits.hits;
        const newPages = [];
        pages.forEach(page => {
          newPages.push({
            ...page['_source'],
            author: pagesMap[page['_id']] || 'ADMIN',
            url: page['_id']
          })
        })
        return Promise.resolve(newPages)
      })
      .then(pages => Pages.run(client, pages)))
};

module.exports = script;
<|endoftext|>


<commit_before>Rickshaw.namespace('Rickshaw.Graph');

Rickshaw.Graph = function(args) {

	this.element = args.element;
	this.series = args.series;

	this.defaults = {
		interpolation: 'cardinal',
		offset: 'zero',
		min: undefined,
		max: undefined,
	};

	Rickshaw.keys(this.defaults).forEach( function(k) {
		this[k] = args[k] || this.defaults[k];
	}, this );

	this.window = {};

	this.updateCallbacks = [];

	var self = this;

	this.initialize = function(args) {

		this.validateSeries(args.series);

		this.series.active = function() { return self.series.filter( function(s) { return !s.disabled } ) };

		this.setSize({ width: args.width, height: args.height });

		this.element.classList.add('rickshaw_graph');
		this.vis = d3.select(this.element)
			.append("svg:svg")
			.attr('width', this.width)
			.attr('height', this.height);

		var renderers = [
			Rickshaw.Graph.Renderer.Stack,
			Rickshaw.Graph.Renderer.Line,
			Rickshaw.Graph.Renderer.Bar,
			Rickshaw.Graph.Renderer.Area,
			Rickshaw.Graph.Renderer.ScatterPlot
		];

		renderers.forEach( function(r) {
			if (!r) return;
			self.registerRenderer(new r( { graph: self } ));
		} );

		this.setRenderer(args.renderer || 'stack', args);
		this.discoverRange();
	};

	this.validateSeries = function(series) {

		if (!(series instanceof Array) && !(series instanceof Rickshaw.Series)) {
			var seriesSignature = Object.prototype.toString.apply(series);
			throw "series is not an array: " + seriesSignature;
		}

		var pointsCount;

		series.forEach( function(s) {

			if (!(s instanceof Object)) {
				throw "series element is not an object: " + s;
			}
			if (!(s.data)) {
				throw "series has no data: " + JSON.stringify(s);
			}
			if (!(s.data instanceof Array)) {
				throw "series data is not an array: " + JSON.stringify(s.data);
			}

			pointsCount = pointsCount || s.data.length;

			if (pointsCount && s.data.length != pointsCount) {
				throw "series cannot have differing numbers of points: " +
					pointsCount	+ " vs " + s.data.length + "; see Rickshaw.Series.zeroFill()";
			}

			var dataTypeX = typeof s.data[0].x;
			var dataTypeY = typeof s.data[0].y;

			if (dataTypeX != 'number' || dataTypeY != 'number') {
				throw "x and y properties of points should be numbers instead of " +
					dataTypeX + " and " + dataTypeY;
			}
		} );
	};

	this.dataDomain = function() {

		// take from the first series
		var data = this.series[0].data;

		return [ data[0].x, data.slice(-1).shift().x ];

	};

	this.discoverRange = function() {

		var domain = this.renderer.domain();

		this.x = d3.scale.linear().domain(domain.x).range([0, this.width]);

		this.y = d3.scale.linear().domain(domain.y).range([this.height, 0]);
		this.y.magnitude = d3.scale.linear().domain(domain.y).range([0, this.height]);

	};

	this.render = function() {

		var stackedData = this.stackData();
		this.discoverRange();

		this.renderer.render();

		this.updateCallbacks.forEach( function(callback) {
			callback();
		} );
	};

	this.update = this.render;

	this.stackData = function() {

		var data = this.series.active()
			.map( function(d) { return d.data } )
			.map( function(d) { return d.filter( function(d) { return this._slice(d) }, this ) }, this);

		this.stackData.hooks.data.forEach( function(entry) {
			data = entry.f.apply(self, [data]);
		} );

		var layout = d3.layout.stack();
		layout.offset( self.offset );

		var stackedData = layout(data);

		this.stackData.hooks.after.forEach( function(entry) {
			stackedData = entry.f.apply(self, [data]);
		} );

		var i = 0;
		this.series.forEach( function(series) {
			if (series.disabled) return;
			series.stack = stackedData[i++];
		} );

		this.stackedData = stackedData;
		return stackedData;
	};

	this.stackData.hooks = { data: [], after: [] };

	this._slice = function(d) {

		if (this.window.xMin || this.window.xMax) {

			var isInRange = true;

			if (this.window.xMin && d.x < this.window.xMin) isInRange = false;
			if (this.window.xMax && d.x > this.window.xMax) isInRange = false;

			return isInRange;
		}

		return true;
	};

	this.onUpdate = function(callback) {
		this.updateCallbacks.push(callback);
	};

	this.registerRenderer = function(renderer) {
		this._renderers = this._renderers || {};
		this._renderers[renderer.name] = renderer;
	};

	this.configure = function(args) {

		if (args.width || args.height) {
			this.setSize(args);
		}

		Rickshaw.keys(this.defaults).forEach( function(k) {
			this[k] = args[k] || this.defaults[k];
		}, this );

		this.setRenderer(args.renderer || this.renderer.name, args);
	};

	this.setRenderer = function(name, args) {

		if (!this._renderers[name]) {
			throw "couldn't find renderer " + name;
		}
		this.renderer = this._renderers[name];

		if (typeof args == 'object') {
			this.renderer.configure(args);
		}
	};

	this.setSize = function(args) {

		args = args || {};

		if (typeof window !== undefined) {
			var style = window.getComputedStyle(this.element, null);
			var elementWidth = parseInt(style.getPropertyValue('width'));
			var elementHeight = parseInt(style.getPropertyValue('height'));
		}

		this.width = args.width || elementWidth || 400;
		this.height = args.height || elementHeight || 250;

		this.vis && this.vis
			.attr('width', this.width)
			.attr('height', this.height);
	}

	this.initialize(args);
};
<commit_msg>don't clobber previously configured values with configure(); fixes #74<commit_after>Rickshaw.namespace('Rickshaw.Graph');

Rickshaw.Graph = function(args) {

	this.element = args.element;
	this.series = args.series;

	this.defaults = {
		interpolation: 'cardinal',
		offset: 'zero',
		min: undefined,
		max: undefined,
	};

	Rickshaw.keys(this.defaults).forEach( function(k) {
		this[k] = args[k] || this.defaults[k];
	}, this );

	this.window = {};

	this.updateCallbacks = [];

	var self = this;

	this.initialize = function(args) {

		this.validateSeries(args.series);

		this.series.active = function() { return self.series.filter( function(s) { return !s.disabled } ) };

		this.setSize({ width: args.width, height: args.height });

		this.element.classList.add('rickshaw_graph');
		this.vis = d3.select(this.element)
			.append("svg:svg")
			.attr('width', this.width)
			.attr('height', this.height);

		var renderers = [
			Rickshaw.Graph.Renderer.Stack,
			Rickshaw.Graph.Renderer.Line,
			Rickshaw.Graph.Renderer.Bar,
			Rickshaw.Graph.Renderer.Area,
			Rickshaw.Graph.Renderer.ScatterPlot
		];

		renderers.forEach( function(r) {
			if (!r) return;
			self.registerRenderer(new r( { graph: self } ));
		} );

		this.setRenderer(args.renderer || 'stack', args);
		this.discoverRange();
	};

	this.validateSeries = function(series) {

		if (!(series instanceof Array) && !(series instanceof Rickshaw.Series)) {
			var seriesSignature = Object.prototype.toString.apply(series);
			throw "series is not an array: " + seriesSignature;
		}

		var pointsCount;

		series.forEach( function(s) {

			if (!(s instanceof Object)) {
				throw "series element is not an object: " + s;
			}
			if (!(s.data)) {
				throw "series has no data: " + JSON.stringify(s);
			}
			if (!(s.data instanceof Array)) {
				throw "series data is not an array: " + JSON.stringify(s.data);
			}

			pointsCount = pointsCount || s.data.length;

			if (pointsCount && s.data.length != pointsCount) {
				throw "series cannot have differing numbers of points: " +
					pointsCount	+ " vs " + s.data.length + "; see Rickshaw.Series.zeroFill()";
			}

			var dataTypeX = typeof s.data[0].x;
			var dataTypeY = typeof s.data[0].y;

			if (dataTypeX != 'number' || dataTypeY != 'number') {
				throw "x and y properties of points should be numbers instead of " +
					dataTypeX + " and " + dataTypeY;
			}
		} );
	};

	this.dataDomain = function() {

		// take from the first series
		var data = this.series[0].data;

		return [ data[0].x, data.slice(-1).shift().x ];

	};

	this.discoverRange = function() {

		var domain = this.renderer.domain();

		this.x = d3.scale.linear().domain(domain.x).range([0, this.width]);

		this.y = d3.scale.linear().domain(domain.y).range([this.height, 0]);
		this.y.magnitude = d3.scale.linear().domain(domain.y).range([0, this.height]);

	};

	this.render = function() {

		var stackedData = this.stackData();
		this.discoverRange();

		this.renderer.render();

		this.updateCallbacks.forEach( function(callback) {
			callback();
		} );
	};

	this.update = this.render;

	this.stackData = function() {

		var data = this.series.active()
			.map( function(d) { return d.data } )
			.map( function(d) { return d.filter( function(d) { return this._slice(d) }, this ) }, this);

		this.stackData.hooks.data.forEach( function(entry) {
			data = entry.f.apply(self, [data]);
		} );

		var layout = d3.layout.stack();
		layout.offset( self.offset );

		var stackedData = layout(data);

		this.stackData.hooks.after.forEach( function(entry) {
			stackedData = entry.f.apply(self, [data]);
		} );

		var i = 0;
		this.series.forEach( function(series) {
			if (series.disabled) return;
			series.stack = stackedData[i++];
		} );

		this.stackedData = stackedData;
		return stackedData;
	};

	this.stackData.hooks = { data: [], after: [] };

	this._slice = function(d) {

		if (this.window.xMin || this.window.xMax) {

			var isInRange = true;

			if (this.window.xMin && d.x < this.window.xMin) isInRange = false;
			if (this.window.xMax && d.x > this.window.xMax) isInRange = false;

			return isInRange;
		}

		return true;
	};

	this.onUpdate = function(callback) {
		this.updateCallbacks.push(callback);
	};

	this.registerRenderer = function(renderer) {
		this._renderers = this._renderers || {};
		this._renderers[renderer.name] = renderer;
	};

	this.configure = function(args) {

		if (args.width || args.height) {
			this.setSize(args);
		}

		Rickshaw.keys(this.defaults).forEach( function(k) {
			this[k] = k in args ? args[k]
				: k in this ? this[k]
				: this.defaults[k];
		}, this );

		this.setRenderer(args.renderer || this.renderer.name, args);
	};

	this.setRenderer = function(name, args) {

		if (!this._renderers[name]) {
			throw "couldn't find renderer " + name;
		}
		this.renderer = this._renderers[name];

		if (typeof args == 'object') {
			this.renderer.configure(args);
		}
	};

	this.setSize = function(args) {

		args = args || {};

		if (typeof window !== undefined) {
			var style = window.getComputedStyle(this.element, null);
			var elementWidth = parseInt(style.getPropertyValue('width'));
			var elementHeight = parseInt(style.getPropertyValue('height'));
		}

		this.width = args.width || elementWidth || 400;
		this.height = args.height || elementHeight || 250;

		this.vis && this.vis
			.attr('width', this.width)
			.attr('height', this.height);
	}

	this.initialize(args);
};
<|endoftext|>