<commit_before>/**
 * Module : Kero percent
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-10 10:33:09
 */

import {BaseAdapter} from '../core/baseAdapter';
import {ValueMixin} from '../core/valueMixin';
import {EnableMixin} from '../core/enableMixin';
import {RequiredMixin} from '../core/requiredMixin';
import {ValidateMixin} from '../core/validateMixin';
import {getJSObject} from 'tinper-sparrow/js/util';
import {makeDOM} from 'tinper-sparrow/js/dom';
import {on,off,stopEvent} from 'tinper-sparrow/js/event';
import {Radio} from 'tinper-neoui/js/neoui-radio';
import {compMgr} from 'tinper-sparrow/js/compMgr';
import {addClass} from 'tinper-sparrow/js/dom';
import {env} from 'tinper-sparrow/js/env';

var RadioAdapter = BaseAdapter.extend({
    mixins: [ValueMixin, EnableMixin,RequiredMixin, ValidateMixin],
    init: function (options) {
        var self = this;
        //RadioAdapter.superclass.initialize.apply(this, arguments);
        this.dynamic = false;
        this.otherValue = this.options['otherValue'] || '其他';
        if(this.options['datasource'] || this.options['hasOther']){
            // 存在datasource或者有其他选项，将当前dom元素保存，以后用于复制新的dom元素
            if(env.isIE){
                this.radioTemplateHTML = this.element.innerHTML;
            }else{
                this.radioTemplateArray = [];
                for (var i= 0, count = this.element.childNodes.length; i< count; i++){
                    this.radioTemplateArray.push(this.element.childNodes[i]);
                }
            }

        }
        if (this.options['datasource']) {
            this.dynamic = true;
            this.datasource = getJSObject(this.viewModel, this.options['datasource']);
            if(this.datasource)
                this.setComboData(this.datasource);
        } else {
            this.comp = new Radio(this.element);
            this.element['u.Radio'] = this.comp;
            this.eleValue = this.comp._btnElement.value;

            this.comp.on('change', function(event){
                if (self.slice) return;
                var modelValue = self.dataModel.getValue(self.field);
                //var valueArr = modelValue == '' ?  [] : modelValue.split(',');
                if (self.comp._btnElement.checked){
                    self.dataModel.setValue(self.field, self.eleValue);
                }
            });
        }

        // 如果存在其他
        if(this.options['hasOther']){
            var node = null;
            if(env.isIE){
                var nowHtml = this.element.innerHTML;
                this.element.innerHTML = nowHtml + this.radioTemplateHTML;
            }else{
                for(var j=0; j<this.radioTemplateArray.length; j++){
                    this.element.appendChild(this.radioTemplateArray[j].cloneNode(true));
                }
            }

            var LabelS = this.element.querySelectorAll('.u-radio');
            self.lastLabel = LabelS[LabelS.length -1];
            var allRadioS = this.element.querySelectorAll('[type=radio]');
            self.lastRadio = allRadioS[allRadioS.length -1];
            var nameDivs = this.element.querySelectorAll('.u-radio-label');
            self.lastNameDiv = nameDivs[nameDivs.length -1];
            self.lastNameDiv.innerHTML = '其他';
            self.otherInput = makeDOM('<input type="text" disabled style="vertical-align: middle;line-height: normal;">');
            self.lastNameDiv.parentNode.appendChild(self.otherInput);
            self.lastRadio.value = '';

            var comp;
            if(self.lastLabel['u.Radio']) {
                comp = self.lastLabel['u.Radio'];
            } else {
                comp = new Radio(self.lastLabel);
            }
            self.lastLabel['u.Radio'] = comp;
            self.otherComp = comp;
            comp.on('change', function(){
                if (comp._btnElement.checked){
                    if(self.otherInput.value){
                        self.dataModel.setValue(self.field, self.otherInput.value);
                    }else{
                        self.dataModel.setValue(self.field, self.otherValue);
                    }
                    // 选中后可编辑
                    comp.element.querySelectorAll('input[type="text"]').forEach(function(ele){
                        ele.removeAttribute('disabled');
                    });
                } else {
                    comp.element.querySelectorAll('input[type="text"]').forEach(function(ele){
                        ele.setAttribute('disabled',true);
                    });
                }
            });

            on(self.otherInput,'blur',function(e){
                self.otherComp.trigger('change');
            })
            on(self.otherInput,'click',function(e){
                stopEvent(e);
            })
        }

        this.dataModel.ref(this.field).subscribe(function(value) {
            self.modelValueChange(value)
        })

    },
    setComboData: function (comboData) {

        var self = this;
        this.datasource = comboData;
        this.element.innerHTML = '';
        if(env.isIE){
            var htmlStr = ''
            for (var i = 0, len = comboData.length; i < len; i++) {
                htmlStr　+= this.radioTemplateHTML;
            }
            this.element.innerHTML = htmlStr;
        }else{
            for (var i = 0, len = comboData.length; i < len; i++) {
                for(var j=0; j<this.radioTemplateArray.length; j++){
                    this.element.appendChild(this.radioTemplateArray[j].cloneNode(true));
                }
                //this.radioTemplate.clone().appendTo(this.element)
            }
        }

        var allRadio = this.element.querySelectorAll('[type=radio]');
        var allName = this.element.querySelectorAll('.u-radio-label');
        for (var k = 0; k < allRadio.length; k++) {
            allRadio[k].value = comboData[k].pk || comboData[k].value;
            allName[k].innerHTML = comboData[k].name
        }

        this.radioInputName = allRadio[0].name;

        this.element.querySelectorAll('.u-radio').forEach(function (ele) {
            var comp = new Radio(ele);
            ele['u.Radio'] = comp;

            comp.on('change', function(event){
                if (comp._btnElement.checked){
                    self.dataModel.setValue(self.field, comp._btnElement.value);
                }
                // 其他元素input输入框不能进行编辑
                var allChild = comp.element.parentNode.children;
                var siblingAry =[];
                for(var i=0; i<allChild.length; i++){
                    if(allChild[i] == comp.element){

                    } else {
                        siblingAry.push(allChild[i])
                    }
                }
                siblingAry.forEach(function(children){
                    var childinput = children.querySelectorAll('input[type="text"]')
                    if(childinput){
                        childinput.forEach(function(inputele){
                            inputele.setAttribute('disabled','true')
                        });
                    }
                });
            });
        })
    },

    modelValueChange: function (value) {
        if (this.slice) return;
        var fetch = false;
        if (this.dynamic){
            if(this.datasource){
                this.trueValue = value;
                this.element.querySelectorAll('.u-radio').forEach(function (ele) {
                    var comp =  ele['u.Radio'];
                    if(comp){
                        var inptuValue = comp._btnElement.value;
                        if (inptuValue && inptuValue == value) {
                            fetch = true;
                            addClass(comp.element,'is-checked')
                            comp._btnElement.click();
                        }
                    }
                })
            }
        }else{
            if (this.eleValue == value){
                fetch = true;
                this.slice = true;
                addClass(this.comp.element,'is-checked')
                this.comp._btnElement.click();
                this.slice = false;
            }
        }
        if(this.options.hasOther && !fetch && value){
            if(!this.enable){
                this.lastRadio.removeAttribute('disabled');
            }
            u.addClass(this.lastLabel,'is-checked')
            this.lastRadio.checked = true;
            if(value != this.otherValue){
                this.otherInput.value = value;
            }
            this.lastRadio.removeAttribute('disabled');
            this.otherInput.removeAttribute('disabled');
            if(!this.enable){
                this.lastRadio.setAttribute('disabled',true);
            }
        }
    },

    setEnable: function (enable) {
        this.enable = (enable === true || enable === 'true');
        if (this.dynamic){
            if(this.datasource){
                this.element.querySelectorAll('.u-radio').forEach(function (ele) {
                    var comp =  ele['u.Radio'];
                    if(comp){
                        if (enable === true || enable === 'true'){
                            comp.enable();
                        }else{
                            comp.disable();
                        }
                    }
                })
            }
        }else{
            if (this.enable){
                this.comp.enable();
            }else{
                this.comp.disable();
            }
        }
    }
})

compMgr.addDataAdapter({
	adapter: RadioAdapter,
	name: 'u-radio'
});
export {RadioAdapter};
<commit_msg>增加判断避免js错误<commit_after>/**
 * Module : Kero percent
 * Author : Kvkens(yueming@yonyou.com)
 * Date	  : 2016-08-10 10:33:09
 */

import {BaseAdapter} from '../core/baseAdapter';
import {ValueMixin} from '../core/valueMixin';
import {EnableMixin} from '../core/enableMixin';
import {RequiredMixin} from '../core/requiredMixin';
import {ValidateMixin} from '../core/validateMixin';
import {getJSObject} from 'tinper-sparrow/js/util';
import {makeDOM} from 'tinper-sparrow/js/dom';
import {on,off,stopEvent} from 'tinper-sparrow/js/event';
import {Radio} from 'tinper-neoui/js/neoui-radio';
import {compMgr} from 'tinper-sparrow/js/compMgr';
import {addClass} from 'tinper-sparrow/js/dom';
import {env} from 'tinper-sparrow/js/env';

var RadioAdapter = BaseAdapter.extend({
    mixins: [ValueMixin, EnableMixin,RequiredMixin, ValidateMixin],
    init: function (options) {
        var self = this;
        //RadioAdapter.superclass.initialize.apply(this, arguments);
        this.dynamic = false;
        this.otherValue = this.options['otherValue'] || '其他';
        if(this.options['datasource'] || this.options['hasOther']){
            // 存在datasource或者有其他选项，将当前dom元素保存，以后用于复制新的dom元素
            if(env.isIE){
                this.radioTemplateHTML = this.element.innerHTML;
            }else{
                this.radioTemplateArray = [];
                for (var i= 0, count = this.element.childNodes.length; i< count; i++){
                    this.radioTemplateArray.push(this.element.childNodes[i]);
                }
            }

        }
        if (this.options['datasource']) {
            this.dynamic = true;
            this.datasource = getJSObject(this.viewModel, this.options['datasource']);
            if(this.datasource)
                this.setComboData(this.datasource);
        } else {
            this.comp = new Radio(this.element);
            this.element['u.Radio'] = this.comp;
            this.eleValue = this.comp._btnElement.value;

            this.comp.on('change', function(event){
                if (self.slice) return;
                var modelValue = self.dataModel.getValue(self.field);
                //var valueArr = modelValue == '' ?  [] : modelValue.split(',');
                if (self.comp._btnElement.checked){
                    self.dataModel.setValue(self.field, self.eleValue);
                }
            });
        }

        // 如果存在其他
        if(this.options['hasOther']){
            var node = null;
            if(env.isIE){
                var nowHtml = this.element.innerHTML;
                this.element.innerHTML = nowHtml + this.radioTemplateHTML;
            }else{
                for(var j=0; j<this.radioTemplateArray.length; j++){
                    this.element.appendChild(this.radioTemplateArray[j].cloneNode(true));
                }
            }

            var LabelS = this.element.querySelectorAll('.u-radio');
            self.lastLabel = LabelS[LabelS.length -1];
            var allRadioS = this.element.querySelectorAll('[type=radio]');
            self.lastRadio = allRadioS[allRadioS.length -1];
            var nameDivs = this.element.querySelectorAll('.u-radio-label');
            self.lastNameDiv = nameDivs[nameDivs.length -1];
            self.lastNameDiv.innerHTML = '其他';
            self.otherInput = makeDOM('<input type="text" disabled style="vertical-align: middle;line-height: normal;">');
            self.lastNameDiv.parentNode.appendChild(self.otherInput);
            self.lastRadio.value = '';

            var comp;
            if(self.lastLabel['u.Radio']) {
                comp = self.lastLabel['u.Radio'];
            } else {
                comp = new Radio(self.lastLabel);
            }
            self.lastLabel['u.Radio'] = comp;
            self.otherComp = comp;
            comp.on('change', function(){
                if (comp._btnElement.checked){
                    if(self.otherInput.value){
                        self.dataModel.setValue(self.field, self.otherInput.value);
                    }else{
                        self.dataModel.setValue(self.field, self.otherValue);
                    }
                    // 选中后可编辑
                    comp.element.querySelectorAll('input[type="text"]').forEach(function(ele){
                        ele.removeAttribute('disabled');
                    });
                } else {
                    comp.element.querySelectorAll('input[type="text"]').forEach(function(ele){
                        ele.setAttribute('disabled',true);
                    });
                }
            });

            on(self.otherInput,'blur',function(e){
                self.otherComp.trigger('change');
            })
            on(self.otherInput,'click',function(e){
                stopEvent(e);
            })
        }

        this.dataModel.ref(this.field).subscribe(function(value) {
            self.modelValueChange(value)
        })

    },
    setComboData: function (comboData) {

        var self = this;
        this.datasource = comboData;
        this.element.innerHTML = '';
        if(env.isIE){
            var htmlStr = ''
            for (var i = 0, len = comboData.length; i < len; i++) {
                htmlStr　+= this.radioTemplateHTML;
            }
            this.element.innerHTML = htmlStr;
        }else{
            for (var i = 0, len = comboData.length; i < len; i++) {
                for(var j=0; j<this.radioTemplateArray.length; j++){
                    this.element.appendChild(this.radioTemplateArray[j].cloneNode(true));
                }
                //this.radioTemplate.clone().appendTo(this.element)
            }
        }

        var allRadio = this.element.querySelectorAll('[type=radio]');
        var allName = this.element.querySelectorAll('.u-radio-label');
        for (var k = 0; k < allRadio.length; k++) {
            allRadio[k].value = comboData[k].pk || comboData[k].value;
            allName[k].innerHTML = comboData[k].name
        }

        this.radioInputName = '';
        if(allRadio.length > 0){
            this.radioInputName = allRadio[0].name;
        }

        this.element.querySelectorAll('.u-radio').forEach(function (ele) {
            var comp = new Radio(ele);
            ele['u.Radio'] = comp;

            comp.on('change', function(event){
                if (comp._btnElement.checked){
                    self.dataModel.setValue(self.field, comp._btnElement.value);
                }
                // 其他元素input输入框不能进行编辑
                var allChild = comp.element.parentNode.children;
                var siblingAry =[];
                for(var i=0; i<allChild.length; i++){
                    if(allChild[i] == comp.element){

                    } else {
                        siblingAry.push(allChild[i])
                    }
                }
                siblingAry.forEach(function(children){
                    var childinput = children.querySelectorAll('input[type="text"]')
                    if(childinput){
                        childinput.forEach(function(inputele){
                            inputele.setAttribute('disabled','true')
                        });
                    }
                });
            });
        })
    },

    modelValueChange: function (value) {
        if (this.slice) return;
        var fetch = false;
        if (this.dynamic){
            if(this.datasource){
                this.trueValue = value;
                this.element.querySelectorAll('.u-radio').forEach(function (ele) {
                    var comp =  ele['u.Radio'];
                    if(comp){
                        var inptuValue = comp._btnElement.value;
                        if (inptuValue && inptuValue == value) {
                            fetch = true;
                            addClass(comp.element,'is-checked')
                            comp._btnElement.click();
                        }
                    }
                })
            }
        }else{
            if (this.eleValue == value){
                fetch = true;
                this.slice = true;
                addClass(this.comp.element,'is-checked')
                this.comp._btnElement.click();
                this.slice = false;
            }
        }
        if(this.options.hasOther && !fetch && value){
            if(!this.enable){
                this.lastRadio.removeAttribute('disabled');
            }
            u.addClass(this.lastLabel,'is-checked')
            this.lastRadio.checked = true;
            if(value != this.otherValue){
                this.otherInput.value = value;
            }
            this.lastRadio.removeAttribute('disabled');
            this.otherInput.removeAttribute('disabled');
            if(!this.enable){
                this.lastRadio.setAttribute('disabled',true);
            }
        }
    },

    setEnable: function (enable) {
        this.enable = (enable === true || enable === 'true');
        if (this.dynamic){
            if(this.datasource){
                this.element.querySelectorAll('.u-radio').forEach(function (ele) {
                    var comp =  ele['u.Radio'];
                    if(comp){
                        if (enable === true || enable === 'true'){
                            comp.enable();
                        }else{
                            comp.disable();
                        }
                    }
                })
            }
        }else{
            if (this.enable){
                this.comp.enable();
            }else{
                this.comp.disable();
            }
        }
    }
})

compMgr.addDataAdapter({
	adapter: RadioAdapter,
	name: 'u-radio'
});
export {RadioAdapter};
<|endoftext|>


<commit_before>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

 This Source Code is subject to the terms of the Mozilla Public
 License, v2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 ------------------------------------------------------------------
  CodeMirror JavaScript editor
 ------------------------------------------------------------------
**/
"use strict";
(function(){
  var codeMirror;
  var codeMirrorDirty = false;

  function init() {
    $('
<textarea id="code" name="code"></textarea>
').appendTo(".editor--code .editor__canvas");
    // The code editor
    codeMirror = CodeMirror.fromTextArea(document.getElementById("code"), {
      width: "100%",
      height: "100%",
      lineNumbers: true,
      matchBrackets: true,
      mode: {name: "javascript", globalVars: false},
      lineWrapping: true,
      showTrailingSpace: true,
      lint: {
        es5         : true, // if ES5 syntax should be allowed
        evil        : true, // don't warn on use of strings in setInterval
        laxbreak    : true  // don't warn about newlines in expressions
      },
      highlightSelectionMatches: {showToken: /\w/},
      foldGutter: {rangeFinder: new CodeMirror.fold.combine(CodeMirror.fold.brace, CodeMirror.fold.comment)},
      gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"],
      extraKeys: {
        "Tab" : function(cm) {
          if (cm.somethingSelected()) {
            cm.indentSelection("add");
          } else { // make sure the tab key indents with spaces
            cm.replaceSelection(cm.getOption("indentWithTabs")? "\t":
              Array(cm.getOption("indentUnit") + 1).join(" "), "end", "+input");
          }
        }
      }
    });
  }

  function getCode() {
    return codeMirror.getValue();
  }

  function setCode(code) {
    codeMirror.setValue(code);
    codeMirrorDirty = true;
  }

  /** Called this when we switch modes from blockly - the editor needs a prod to update if the code
   * was set when it was invisible */
  function madeVisible() {
    if (codeMirrorDirty) {
      codeMirrorDirty = false;
      // important we do it a bit later so things have had time to lay out
      setTimeout(function () {
        codeMirror.refresh();
      }, 1);
    }
  }

  Espruino.Core.EditorJavaScript = {
    init : init,
    getCode : getCode,
    setCode : setCode,
    madeVisible : madeVisible,
    getCodeMirror : function () { return codeMirror; }
  };
}());
<commit_msg>don't warn about commas at the start of the line<commit_after>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

 This Source Code is subject to the terms of the Mozilla Public
 License, v2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 ------------------------------------------------------------------
  CodeMirror JavaScript editor
 ------------------------------------------------------------------
**/
"use strict";
(function(){
  var codeMirror;
  var codeMirrorDirty = false;

  function init() {
    $('
<textarea id="code" name="code"></textarea>
').appendTo(".editor--code .editor__canvas");
    // The code editor
    codeMirror = CodeMirror.fromTextArea(document.getElementById("code"), {
      width: "100%",
      height: "100%",
      lineNumbers: true,
      matchBrackets: true,
      mode: {name: "javascript", globalVars: false},
      lineWrapping: true,
      showTrailingSpace: true,
      lint: {
        es5         : true, // if ES5 syntax should be allowed
        evil        : true, // don't warn on use of strings in setInterval
        laxbreak    : true,  // don't warn about newlines in expressions
        laxcomma    : true  // don't warn about commas at the start of the line
      },
      highlightSelectionMatches: {showToken: /\w/},
      foldGutter: {rangeFinder: new CodeMirror.fold.combine(CodeMirror.fold.brace, CodeMirror.fold.comment)},
      gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"],
      extraKeys: {
        "Tab" : function(cm) {
          if (cm.somethingSelected()) {
            cm.indentSelection("add");
          } else { // make sure the tab key indents with spaces
            cm.replaceSelection(cm.getOption("indentWithTabs")? "\t":
              Array(cm.getOption("indentUnit") + 1).join(" "), "end", "+input");
          }
        }
      }
    });
  }

  function getCode() {
    return codeMirror.getValue();
  }

  function setCode(code) {
    codeMirror.setValue(code);
    codeMirrorDirty = true;
  }

  /** Called this when we switch modes from blockly - the editor needs a prod to update if the code
   * was set when it was invisible */
  function madeVisible() {
    if (codeMirrorDirty) {
      codeMirrorDirty = false;
      // important we do it a bit later so things have had time to lay out
      setTimeout(function () {
        codeMirror.refresh();
      }, 1);
    }
  }

  Espruino.Core.EditorJavaScript = {
    init : init,
    getCode : getCode,
    setCode : setCode,
    madeVisible : madeVisible,
    getCodeMirror : function () { return codeMirror; }
  };
}());
<|endoftext|>


<commit_before>const table = require("./tableVirtualScroll")
const clickable = require("./clickable")
const activeStyle = require("./activeStyle")
const activeItem = require("../core/activeItem")

module.exports = (arg1, arg2) => {
  const opts = arg2 ? arg1 : {}
  const columns = arg2 ? arg2 : arg1

  // si pas de next, on utilise la nouvelle convention "openItem", sinon la convention "setActiveItem/ensureItemVisible/next"
  return table(
    {
      rowMixin: activeStyle(
        clickable.mixin(
          opts.next
            ? activeItem(ctx => () => ctx.value, opts.next)
            : ctx =>
                ctx.openItem
                  ? () => ctx.openItem(ctx.value)
                  : () => {
                      ctx.setActiveItem(ctx.value)
                      ctx.ensureItemVisible && ctx.ensureItemVisible(true)
                    }
        )
      ),
      itemHeight: opts.itemHeight,
    },
    columns
  )
}
<commit_msg>Extracted rowMixin from tableWithActiveItem<commit_after>const table = require("./tableVirtualScroll")
const clickable = require("./clickable")
const activeStyle = require("./activeStyle")
const activeItem = require("../core/activeItem")

// si pas de next, on utilise la nouvelle convention "openItem", sinon la convention "setActiveItem/ensureItemVisible/next"
const rowMixin = (opts = {}) =>
  activeStyle(
    clickable.mixin(
      opts.next
        ? activeItem(ctx => () => ctx.value, opts.next)
        : ctx =>
            ctx.openItem
              ? () => ctx.openItem(ctx.value)
              : () => {
                  ctx.setActiveItem(ctx.value)
                  ctx.ensureItemVisible && ctx.ensureItemVisible(true)
                }
    )
  )

const tableGenerator = (arg1, arg2) => {
  const opts = arg2 ? arg1 : {}
  const columns = arg2 ? arg2 : arg1

  return table(
    {
      rowMixin: rowMixin(opts),
      itemHeight: opts.itemHeight,
    },
    columns
  )
}
tableGenerator.rowMixin = rowMixin

module.exports = tableGenerator
<|endoftext|>


<commit_before>FileList={
	update:function(fileListHtml) {
		$('#fileList').empty().html(fileListHtml);
	},
	addFile:function(name,size,lastModified,loading){
		var img=(loading)?OC.imagePath('core', 'loading.gif'):OC.imagePath('core', 'filetypes/file');
		var html='
';
		if(name.indexOf('.')!=-1){
			var basename=name.substr(0,name.indexOf('.'));
			var extention=name.substr(name.indexOf('.'));
		}else{
			var basename=name;
			var extention=false;
		}
		html+='<input type="checkbox" />';
		html+=''+basename
		if(extention){
			html+=''+extention+'';
		}
		html+='	';
		if(size!='Pending'){
			simpleSize=simpleFileSize(size);
		}else{
			simpleSize='Pending';
		}
		sizeColor = Math.round(200-size/(1024*1024)*2);
		lastModifiedTime=Math.round(lastModified.getTime() / 1000);
		modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*14);
		html+=''+simpleSize+'	';
		html+=''+relative_modified_date(lastModified.getTime() / 1000)+'	';
		html+='
';
		FileList.insertElement(name,'file',$(html));
		if(loading){
			$('tr[data-file="'+name+'"]').data('loading',true);
		}else{
			$('tr[data-file="'+name+'"] td.filename').draggable(dragOptions);
		}
	},
	addDir:function(name,size,lastModified){
		var html='
';
		html+='<input type="checkbox" />'+name+'	';
		if(size!='Pending'){
			simpleSize=simpleFileSize(size);
		}else{
			simpleSize='Pending';
		}
		sizeColor = Math.round(200-Math.pow((size/(1024*1024)),2));
		lastModifiedTime=Math.round(lastModified.getTime() / 1000);
		modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*5);
		html+=''+simpleSize+'	';
		html+=''+relative_modified_date(lastModified.getTime() / 1000)+'	';
		html+='
';

		FileList.insertElement(name,'dir',$(html));
		$('tr[data-file="'+name+'"] td.filename').draggable(dragOptions);
		$('tr[data-file="'+name+'"] td.filename').droppable(folderDropOptions);
	},
	refresh:function(data) {
		result = jQuery.parseJSON(data.responseText);
		if(typeof(result.data.breadcrumb) != 'undefined'){
			updateBreadcrumb(result.data.breadcrumb);
		}
		FileList.update(result.data.files);
		resetFileActionPanel();
	},
	remove:function(name){
		$('tr[data-file="'+name+'"] td.filename').draggable('destroy');
		$('tr[data-file="'+name+'"]').remove();
		if($('tr[data-file]').length==0){
			$('#emptyfolder').show();
			$('.file_upload_filename').addClass('highlight');
		}
	},
	insertElement:function(name,type,element){
		//find the correct spot to insert the file or folder
		var fileElements=$('tr[data-file][data-type="'+type+'"]');
		var pos;
		if(name.localeCompare($(fileElements[0]).attr('data-file'))<0){
			pos=-1;
		}else if(name.localeCompare($(fileElements[fileElements.length-1]).attr('data-file'))>0){
			pos=fileElements.length-1;
		}else{
			for(var pos=0;pos<fileElements.length-1;pos++){
				if(name.localeCompare($(fileElements[pos]).attr('data-file'))>0 && name.localeCompare($(fileElements[pos+1]).attr('data-file'))<0){
					break;
				}
			}
		}
		if(fileElements.length){
			if(pos==-1){
				$(fileElements[0]).before(element);
			}else{
				$(fileElements[pos]).after(element);
			}
		}else if(type=='dir' && $('tr[data-file]').length>0){
			$('tr[data-file]').first().before(element);
		}else{
			$('#fileList').append(element);
		}
		$('#emptyfolder').hide();
		$('.file_upload_filename').removeClass('highlight');
	},
	loadingDone:function(name){
		$('tr[data-file="'+name+'"]').data('loading',false);
		var mime=$('tr[data-file="'+name+'"]').data('mime');
		$('tr[data-file="'+name+'"] td.filename').attr('style','background-image:url('+getMimeIcon(mime)+')');
		$('tr[data-file="'+name+'"] td.filename').draggable(dragOptions);
	},
	isLoading:function(name){
		return $('tr[data-file="'+name+'"]').data('loading');
	},
	rename:function(name){
		var tr=$('tr[data-file="'+name+'"]');
		tr.data('renaming',true);
		var td=tr.children('td.filename');
		var input=$('<input value="'+name+'" class="filename"></input>');
		var form=$('<form action="#"></form>')
		form.append(input);
		td.children('a.name').text('');
		td.children('a.name').append(form)
		input.focus();
		form.submit(function(event){
			event.stopPropagation();
			event.preventDefault();
			var newname=input.val();
			tr.data('renaming',false);
			tr.attr('data-file',newname);
			td.children('a.name').empty();
			if(newname.indexOf('.')>0){
				basename=newname.substr(0,newname.indexOf('.'));
			}else{
				basename=newname;
			}
			var span=$('');
			span.text(basename);
			td.children('a.name').append(span);
			if(newname.indexOf('.')>0){
				span.append($(''+newname.substr(newname.indexOf('.'))+''));
			}
			$.ajax({
				url: 'ajax/rename.php',
				data: "dir="+$('#dir').val()+"&newname="+encodeURIComponent(newname)+"&file="+encodeURIComponent(name)
			});
		});
		form.click(function(event){
			event.stopPropagation();
			event.preventDefault();
		});
		input.blur(function(){
			form.trigger('submit');
		});
	},
	delete:function(files){
		if(FileList.deleteFiles){//finish any ongoing deletes first
			FileList.finishDelete(function(){
				FileList.delete(files);
			});
			return;
		}
		if(files.substr){
			files=[files];
		}
		$.each(files,function(index,file){
			$('tr[data-file="'+file+'"]').hide();
			$('tr[data-file="'+file+'"]').find('input[type="checkbox"]').removeAttr('checked');
			$('tr[data-file="'+file+'"]').removeClass('selected');
		});
		procesSelection();
		FileList.deleteCanceled=false;
		FileList.deleteFiles=files;
		$('#notification').text(t('files','undo deletion'));
		$('#notification').fadeIn();
	},
	finishDelete:function(ready,sync){
		if(!FileList.deleteCanceled && FileList.deleteFiles){
			var fileNames=FileList.deleteFiles.join(';');
			$.ajax({
				url: 'ajax/delete.php',
				async:!sync,
				data: "dir="+$('#dir').val()+"&files="+encodeURIComponent(fileNames),
				complete: function(data){
					boolOperationFinished(data, function(){
						$('#notification').fadeOut();
						$.each(FileList.deleteFiles,function(index,file){
// 							alert(file);
							FileList.remove(file);
						});
						FileList.deleteCanceled=true;
						FileList.deleteFiles=null;
						if(ready){
							ready();
						}
					});
				}
			});
		}
	}
}

$(document).ready(function(){
	$('#notification').hide();
	$('#notification').click(function(){
		FileList.deleteCanceled=true;
		$('#notification').fadeOut();
		$.each(FileList.deleteFiles,function(index,file){
			$('tr[data-file="'+file+'"]').show();
// 			alert(file);
		});
		FileList.deleteFiles=null;
	});
	$(window).bind('beforeunload', function (){
		FileList.finishDelete(null,true);
	});
});
<commit_msg>Get file extension using lastIndexOf instead of indexOf in case there is a '.' in file name<commit_after>FileList={
	update:function(fileListHtml) {
		$('#fileList').empty().html(fileListHtml);
	},
	addFile:function(name,size,lastModified,loading){
		var img=(loading)?OC.imagePath('core', 'loading.gif'):OC.imagePath('core', 'filetypes/file');
		var html='
';
		if(name.indexOf('.')!=-1){
			var basename=name.substr(0,name.indexOf('.'));
			var extention=name.substr(name.lastIndexOf('.'));
		}else{
			var basename=name;
			var extention=false;
		}
		html+='<input type="checkbox" />';
		html+=''+basename
		if(extention){
			html+=''+extention+'';
		}
		html+='	';
		if(size!='Pending'){
			simpleSize=simpleFileSize(size);
		}else{
			simpleSize='Pending';
		}
		sizeColor = Math.round(200-size/(1024*1024)*2);
		lastModifiedTime=Math.round(lastModified.getTime() / 1000);
		modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*14);
		html+=''+simpleSize+'	';
		html+=''+relative_modified_date(lastModified.getTime() / 1000)+'	';
		html+='
';
		FileList.insertElement(name,'file',$(html));
		if(loading){
			$('tr[data-file="'+name+'"]').data('loading',true);
		}else{
			$('tr[data-file="'+name+'"] td.filename').draggable(dragOptions);
		}
	},
	addDir:function(name,size,lastModified){
		var html='
';
		html+='<input type="checkbox" />'+name+'	';
		if(size!='Pending'){
			simpleSize=simpleFileSize(size);
		}else{
			simpleSize='Pending';
		}
		sizeColor = Math.round(200-Math.pow((size/(1024*1024)),2));
		lastModifiedTime=Math.round(lastModified.getTime() / 1000);
		modifiedColor=Math.round((Math.round((new Date()).getTime() / 1000)-lastModifiedTime)/60/60/24*5);
		html+=''+simpleSize+'	';
		html+=''+relative_modified_date(lastModified.getTime() / 1000)+'	';
		html+='
';

		FileList.insertElement(name,'dir',$(html));
		$('tr[data-file="'+name+'"] td.filename').draggable(dragOptions);
		$('tr[data-file="'+name+'"] td.filename').droppable(folderDropOptions);
	},
	refresh:function(data) {
		result = jQuery.parseJSON(data.responseText);
		if(typeof(result.data.breadcrumb) != 'undefined'){
			updateBreadcrumb(result.data.breadcrumb);
		}
		FileList.update(result.data.files);
		resetFileActionPanel();
	},
	remove:function(name){
		$('tr[data-file="'+name+'"] td.filename').draggable('destroy');
		$('tr[data-file="'+name+'"]').remove();
		if($('tr[data-file]').length==0){
			$('#emptyfolder').show();
			$('.file_upload_filename').addClass('highlight');
		}
	},
	insertElement:function(name,type,element){
		//find the correct spot to insert the file or folder
		var fileElements=$('tr[data-file][data-type="'+type+'"]');
		var pos;
		if(name.localeCompare($(fileElements[0]).attr('data-file'))<0){
			pos=-1;
		}else if(name.localeCompare($(fileElements[fileElements.length-1]).attr('data-file'))>0){
			pos=fileElements.length-1;
		}else{
			for(var pos=0;pos<fileElements.length-1;pos++){
				if(name.localeCompare($(fileElements[pos]).attr('data-file'))>0 && name.localeCompare($(fileElements[pos+1]).attr('data-file'))<0){
					break;
				}
			}
		}
		if(fileElements.length){
			if(pos==-1){
				$(fileElements[0]).before(element);
			}else{
				$(fileElements[pos]).after(element);
			}
		}else if(type=='dir' && $('tr[data-file]').length>0){
			$('tr[data-file]').first().before(element);
		}else{
			$('#fileList').append(element);
		}
		$('#emptyfolder').hide();
		$('.file_upload_filename').removeClass('highlight');
	},
	loadingDone:function(name){
		$('tr[data-file="'+name+'"]').data('loading',false);
		var mime=$('tr[data-file="'+name+'"]').data('mime');
		$('tr[data-file="'+name+'"] td.filename').attr('style','background-image:url('+getMimeIcon(mime)+')');
		$('tr[data-file="'+name+'"] td.filename').draggable(dragOptions);
	},
	isLoading:function(name){
		return $('tr[data-file="'+name+'"]').data('loading');
	},
	rename:function(name){
		var tr=$('tr[data-file="'+name+'"]');
		tr.data('renaming',true);
		var td=tr.children('td.filename');
		var input=$('<input value="'+name+'" class="filename"></input>');
		var form=$('<form action="#"></form>')
		form.append(input);
		td.children('a.name').text('');
		td.children('a.name').append(form)
		input.focus();
		form.submit(function(event){
			event.stopPropagation();
			event.preventDefault();
			var newname=input.val();
			tr.data('renaming',false);
			tr.attr('data-file',newname);
			td.children('a.name').empty();
			if(newname.indexOf('.')>0){
				basename=newname.substr(0,newname.lastIndexOf('.'));
			}else{
				basename=newname;
			}
			var span=$('');
			span.text(basename);
			td.children('a.name').append(span);
			if(newname.indexOf('.')>0){
				span.append($(''+newname.substr(newname.lastIndexOf('.'))+''));
			}
			$.ajax({
				url: 'ajax/rename.php',
				data: "dir="+$('#dir').val()+"&newname="+encodeURIComponent(newname)+"&file="+encodeURIComponent(name)
			});
		});
		form.click(function(event){
			event.stopPropagation();
			event.preventDefault();
		});
		input.blur(function(){
			form.trigger('submit');
		});
	},
	delete:function(files){
		if(FileList.deleteFiles){//finish any ongoing deletes first
			FileList.finishDelete(function(){
				FileList.delete(files);
			});
			return;
		}
		if(files.substr){
			files=[files];
		}
		$.each(files,function(index,file){
			$('tr[data-file="'+file+'"]').hide();
			$('tr[data-file="'+file+'"]').find('input[type="checkbox"]').removeAttr('checked');
			$('tr[data-file="'+file+'"]').removeClass('selected');
		});
		procesSelection();
		FileList.deleteCanceled=false;
		FileList.deleteFiles=files;
		$('#notification').text(t('files','undo deletion'));
		$('#notification').fadeIn();
	},
	finishDelete:function(ready,sync){
		if(!FileList.deleteCanceled && FileList.deleteFiles){
			var fileNames=FileList.deleteFiles.join(';');
			$.ajax({
				url: 'ajax/delete.php',
				async:!sync,
				data: "dir="+$('#dir').val()+"&files="+encodeURIComponent(fileNames),
				complete: function(data){
					boolOperationFinished(data, function(){
						$('#notification').fadeOut();
						$.each(FileList.deleteFiles,function(index,file){
// 							alert(file);
							FileList.remove(file);
						});
						FileList.deleteCanceled=true;
						FileList.deleteFiles=null;
						if(ready){
							ready();
						}
					});
				}
			});
		}
	}
}

$(document).ready(function(){
	$('#notification').hide();
	$('#notification').click(function(){
		FileList.deleteCanceled=true;
		$('#notification').fadeOut();
		$.each(FileList.deleteFiles,function(index,file){
			$('tr[data-file="'+file+'"]').show();
// 			alert(file);
		});
		FileList.deleteFiles=null;
	});
	$(window).bind('beforeunload', function (){
		FileList.finishDelete(null,true);
	});
});
<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Main ScreenView container for Buttons portion of the UI component demo.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var OutsideBackgroundNode = require( 'SCENERY_PHET/OutsideBackgroundNode' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Property = require( 'AXON/Property' );
  var RectangularPushButton = require( 'SUN/experimental/buttons/RectangularPushButton' );
  var RefreshButton = require( 'SUN/experimental/buttons/RefreshButton' );
  var ResetAllButton = require( 'SCENERY_PHET/ResetAllButton' );
  var ReturnToLevelSelectButton = require( 'SUN/experimental/buttons/ReturnToLevelSelectButton' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var SoundToggleButton2 = require( 'SUN/experimental/buttons/SoundToggleButton2' );
  var Text = require( 'SCENERY/nodes/Text' );
  var TimerToggleButton2 = require( 'SUN/experimental/buttons/TimerToggleButton2' );
  var ToggleButton2 = require( 'SUN/experimental/buttons/ToggleButton2' );
  var Vector2 = require( 'DOT/Vector2' );

  // Constants
  var BUTTON_FONT = new PhetFont( { size: 20 } );
  var BUTTON_CAPTION_FONT = new PhetFont( { size: 16 } );

  function ButtonsView() {
    ScreenView.call( this, { renderer: 'svg' } );

    // background
    this.addChild( new OutsideBackgroundNode( -this.layoutBounds.width, -this.layoutBounds.height, this.layoutBounds.width * 3, this.layoutBounds.height * 3,
      {
        skyHeight: this.layoutBounds.height * 1.55
      } ) );

    // Set up a property for testing button enable/disable.
    var buttonsEnabled = new Property( true );

    // convenience vars for layout
    var rightEdge = this.layoutBounds.width * 0.6;
    var buttonSpacing = 10;

    // Text area for outputting test information
    var outputText = new Text( '---', { font: new PhetFont( 16 ), bottom: this.layoutBounds.height - 5, left: this.layoutBounds + 10  } );
    this.addChild( outputText );

    // add refresh button and caption
    var refreshButton = new RefreshButton(
      {
        listener: function() { outputText.text = 'Refresh pressed'; },
        right: rightEdge,
        top: 10
      } );
    this.addChild( refreshButton );
    var refreshButtonLabel = new Text( 'Refresh Button: ', { font: BUTTON_CAPTION_FONT, right: refreshButton.left - 5, centerY: refreshButton.centerY } );
    this.addChild( refreshButtonLabel );

    // add return to level select button and caption
    var returnToLevelSelectButton = new ReturnToLevelSelectButton(
      {
        listener: function() { outputText.text = 'Return to level select pressed'; },
        centerX: refreshButton.centerX,
        top: refreshButton.bottom + buttonSpacing
      } );
    this.addChild( returnToLevelSelectButton );
    var returnToLevelSelectButtonLabel = new Text( 'Return to Level Selection Button: ', { font: BUTTON_CAPTION_FONT, right: returnToLevelSelectButton.left - 5, centerY: returnToLevelSelectButton.centerY } );
    this.addChild( returnToLevelSelectButtonLabel );

    // add sound toggle button
    var soundEnabled = new Property( true );
    var soundToggleButton = new SoundToggleButton2( soundEnabled, { centerX: refreshButton.centerX, top: returnToLevelSelectButton.bottom + buttonSpacing } );
    this.addChild( soundToggleButton );
    var soundToggleButtonLabel = new Text( 'Sound Toggle Button: ', { font: BUTTON_CAPTION_FONT, right: soundToggleButton.left - 5, centerY: soundToggleButton.centerY } );
    this.addChild( soundToggleButtonLabel );

    // add timer toggle button
    var timerEnabled = new Property( true );
    var timerToggleButton = new TimerToggleButton2( timerEnabled, { centerX: refreshButton.centerX, y: soundToggleButton.bottom + 5 } );
    this.addChild( timerToggleButton );
    var timerToggleButtonLabel = new Text( 'Timer Toggle Button: ', { font: BUTTON_CAPTION_FONT, right: timerToggleButton.left - 5, centerY: timerToggleButton.centerY } );
    this.addChild( timerToggleButtonLabel );

    // add reset all button and caption
    var resetAllButton = new ResetAllButton( function() {
        outputText.text = 'Reset All pressed';
        buttonsEnabled.reset();
        soundEnabled.reset();
        timerEnabled.reset();
      },
      { radius: 22, centerX: refreshButton.centerX, top: timerToggleButton.bottom + buttonSpacing } );
    this.addChild( resetAllButton );
    var resetAllButtonLabel = new Text( 'Reset All Button: ', { font: BUTTON_CAPTION_FONT, right: resetAllButton.left - 5, centerY: resetAllButton.centerY } );
    this.addChild( resetAllButtonLabel );

    // Test button behavior.
    var buttonA = new RectangularPushButton(
      new Text( '--- A ---', { font: BUTTON_FONT } ),
      {
        listener: function() { outputText.text = 'Button A pressed'; },
        left: 100,
        top: 300
      } );
    this.addChild( buttonA );
    var buttonB = new RectangularPushButton(
      new Text( '--- B ---', { font: BUTTON_FONT } ),
      {
        listener: function() { outputText.text = 'Button B pressed'; },
        left: buttonA.right + 10,
        centerY: buttonA.centerY,
        baseColor: new Color( 250, 0, 0 )
      } );
    this.addChild( buttonB );

    var buttonC = new RectangularPushButton(
      new Text( '--- C ---', { font: BUTTON_FONT } ),
      {
        listener: function() { outputText.text = 'Button C pressed'; },
        left: buttonB.right + 10,
        centerY: buttonB.centerY,
        baseColor: new Color( 204, 102, 204 )
      } );
    this.addChild( buttonC );

    var fireOnDownButton = new RectangularPushButton(
      new Text( 'Fire on Down Button', { font: BUTTON_FONT } ),
      {
        listener: function() { outputText.text = 'Fire on down button pressed'; },
        left: buttonC.right + 30,
        centerY: buttonC.centerY,
        baseColor: new Color( 255, 255, 61 ),
        fireOnDown: true
      } );
    this.addChild( fireOnDownButton );

    // Hook up button enable property
    buttonsEnabled.link( function( enabled ) {
      buttonA.enabled = enabled;
      buttonB.enabled = enabled;
      buttonC.enabled = enabled;
      fireOnDownButton.enabled = enabled;
      refreshButton.enabled = enabled;
      returnToLevelSelectButton.enabled = enabled;
      soundToggleButton.enabled = enabled;
      timerToggleButton.enabled = enabled;
    } );

    var buttonEnableButton = new ToggleButton2(
      new Text( 'Disable Buttons', { font: BUTTON_CAPTION_FONT } ),
      new Text( 'Enable Buttons', { font: BUTTON_CAPTION_FONT } ),
      buttonsEnabled,
      { baseColor: new Color( 204, 255, 51 ), left: buttonA.left, top: buttonA.bottom + 30 }
    );
    this.addChild( buttonEnableButton );
  }

  return inherit( ScreenView, ButtonsView, {
    step: function( timeElapsed ) {
      // Does nothing for now.
    }
  } );
} );
<commit_msg>Improved interface to OutsideBackgroundNode.<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Main ScreenView container for Buttons portion of the UI component demo.
 *
 * @author John Blanco
 */
define( function( require ) {
  'use strict';
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var OutsideBackgroundNode = require( 'SCENERY_PHET/OutsideBackgroundNode' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Property = require( 'AXON/Property' );
  var RectangularPushButton = require( 'SUN/experimental/buttons/RectangularPushButton' );
  var RefreshButton = require( 'SUN/experimental/buttons/RefreshButton' );
  var ResetAllButton = require( 'SCENERY_PHET/ResetAllButton' );
  var ReturnToLevelSelectButton = require( 'SUN/experimental/buttons/ReturnToLevelSelectButton' );
  var ScreenView = require( 'JOIST/ScreenView' );
  var SoundToggleButton2 = require( 'SUN/experimental/buttons/SoundToggleButton2' );
  var Text = require( 'SCENERY/nodes/Text' );
  var TimerToggleButton2 = require( 'SUN/experimental/buttons/TimerToggleButton2' );
  var ToggleButton2 = require( 'SUN/experimental/buttons/ToggleButton2' );
  var Vector2 = require( 'DOT/Vector2' );

  // Constants
  var BUTTON_FONT = new PhetFont( { size: 20 } );
  var BUTTON_CAPTION_FONT = new PhetFont( { size: 16 } );

  function ButtonsView() {
    ScreenView.call( this, { renderer: 'svg' } );

    // background
    this.addChild( new OutsideBackgroundNode( this.layoutBounds.centerX, this.layoutBounds.centerY + 20, this.layoutBounds.width * 3, this.layoutBounds.height, this.layoutBounds.height ) );
    // Set up a property for testing button enable/disable.
    var buttonsEnabled = new Property( true );

    // convenience vars for layout
    var rightEdge = this.layoutBounds.width * 0.6;
    var buttonSpacing = 10;

    // Text area for outputting test information
    var outputText = new Text( '---', { font: new PhetFont( 16 ), bottom: this.layoutBounds.height - 5, left: this.layoutBounds + 10  } );
    this.addChild( outputText );

    // add refresh button and caption
    var refreshButton = new RefreshButton(
      {
        listener: function() { outputText.text = 'Refresh pressed'; },
        right: rightEdge,
        top: 10
      } );
    this.addChild( refreshButton );
    var refreshButtonLabel = new Text( 'Refresh Button: ', { font: BUTTON_CAPTION_FONT, right: refreshButton.left - 5, centerY: refreshButton.centerY } );
    this.addChild( refreshButtonLabel );

    // add return to level select button and caption
    var returnToLevelSelectButton = new ReturnToLevelSelectButton(
      {
        listener: function() { outputText.text = 'Return to level select pressed'; },
        centerX: refreshButton.centerX,
        top: refreshButton.bottom + buttonSpacing
      } );
    this.addChild( returnToLevelSelectButton );
    var returnToLevelSelectButtonLabel = new Text( 'Return to Level Selection Button: ', { font: BUTTON_CAPTION_FONT, right: returnToLevelSelectButton.left - 5, centerY: returnToLevelSelectButton.centerY } );
    this.addChild( returnToLevelSelectButtonLabel );

    // add sound toggle button
    var soundEnabled = new Property( true );
    var soundToggleButton = new SoundToggleButton2( soundEnabled, { centerX: refreshButton.centerX, top: returnToLevelSelectButton.bottom + buttonSpacing } );
    this.addChild( soundToggleButton );
    var soundToggleButtonLabel = new Text( 'Sound Toggle Button: ', { font: BUTTON_CAPTION_FONT, right: soundToggleButton.left - 5, centerY: soundToggleButton.centerY } );
    this.addChild( soundToggleButtonLabel );

    // add timer toggle button
    var timerEnabled = new Property( true );
    var timerToggleButton = new TimerToggleButton2( timerEnabled, { centerX: refreshButton.centerX, y: soundToggleButton.bottom + 5 } );
    this.addChild( timerToggleButton );
    var timerToggleButtonLabel = new Text( 'Timer Toggle Button: ', { font: BUTTON_CAPTION_FONT, right: timerToggleButton.left - 5, centerY: timerToggleButton.centerY } );
    this.addChild( timerToggleButtonLabel );

    // add reset all button and caption
    var resetAllButton = new ResetAllButton( function() {
        outputText.text = 'Reset All pressed';
        buttonsEnabled.reset();
        soundEnabled.reset();
        timerEnabled.reset();
      },
      { radius: 22, centerX: refreshButton.centerX, top: timerToggleButton.bottom + buttonSpacing } );
    this.addChild( resetAllButton );
    var resetAllButtonLabel = new Text( 'Reset All Button: ', { font: BUTTON_CAPTION_FONT, right: resetAllButton.left - 5, centerY: resetAllButton.centerY } );
    this.addChild( resetAllButtonLabel );

    // Test button behavior.
    var buttonA = new RectangularPushButton(
      new Text( '--- A ---', { font: BUTTON_FONT } ),
      {
        listener: function() { outputText.text = 'Button A pressed'; },
        left: 100,
        top: 300
      } );
    this.addChild( buttonA );
    var buttonB = new RectangularPushButton(
      new Text( '--- B ---', { font: BUTTON_FONT } ),
      {
        listener: function() { outputText.text = 'Button B pressed'; },
        left: buttonA.right + 10,
        centerY: buttonA.centerY,
        baseColor: new Color( 250, 0, 0 )
      } );
    this.addChild( buttonB );

    var buttonC = new RectangularPushButton(
      new Text( '--- C ---', { font: BUTTON_FONT } ),
      {
        listener: function() { outputText.text = 'Button C pressed'; },
        left: buttonB.right + 10,
        centerY: buttonB.centerY,
        baseColor: new Color( 204, 102, 204 )
      } );
    this.addChild( buttonC );

    var fireOnDownButton = new RectangularPushButton(
      new Text( 'Fire on Down Button', { font: BUTTON_FONT } ),
      {
        listener: function() { outputText.text = 'Fire on down button pressed'; },
        left: buttonC.right + 30,
        centerY: buttonC.centerY,
        baseColor: new Color( 255, 255, 61 ),
        fireOnDown: true
      } );
    this.addChild( fireOnDownButton );

    // Hook up button enable property
    buttonsEnabled.link( function( enabled ) {
      buttonA.enabled = enabled;
      buttonB.enabled = enabled;
      buttonC.enabled = enabled;
      fireOnDownButton.enabled = enabled;
      refreshButton.enabled = enabled;
      returnToLevelSelectButton.enabled = enabled;
      soundToggleButton.enabled = enabled;
      timerToggleButton.enabled = enabled;
    } );

    var buttonEnableButton = new ToggleButton2(
      new Text( 'Disable Buttons', { font: BUTTON_CAPTION_FONT } ),
      new Text( 'Enable Buttons', { font: BUTTON_CAPTION_FONT } ),
      buttonsEnabled,
      { baseColor: new Color( 204, 255, 51 ), left: buttonA.left, top: buttonA.bottom + 30 }
    );
    this.addChild( buttonEnableButton );
  }

  return inherit( ScreenView, ButtonsView, {
    step: function( timeElapsed ) {
      // Does nothing for now.
    }
  } );
} );
<|endoftext|>


<commit_before>'use strict'

/* IMPORT */

const {packages, workspace} = global.atom
const {registerSingleSubscription} = require(packages.resolvePackagePath('quick-spawn'))

/* DO THINGS */

// NOTE:
//  → Not every function-calls below is necessary
//  → Keep only what you need
registerWorkspaceBash()
registerSidebarBash()

/* DEFINE HOW TO DO THINGS */

// DESCRIPTION: registerWorkspaceBash
//  → Distinct:
//   * Registers for workspace
//   * Uses getTabDirectory() as first current-working-directory
//  → Returns 1 subscription
function registerWorkspaceBash () {
  return registerSingleSubscription({
    execCmd: 'bash', // required; program needs to be executed
    atomCmd: 'simple-bash:workspace', // required; registers an atom-command, appears as "Simple Bash: Workspace" in Command-Palette
    atomTarget: 'atom-workspace', // required; determines where to attach the atom-command
    workingDirectory: getTabDirectory, // optional; determines Bash's first working-directory, you can change it later by 'cd new-wdir'
    attached: false, // optional, default to false; determines whether Bash process should be attached to Atom process
    suspended: true, // optional, default to true; if false, Bash would be started right after quick-spawn's activation
    viewStdIO: ['stdin', 'stdout', 'stderr'], // optional, determines whether stdin, stdout and stderr should be shown; shows all three by default
    type: 'tab', // optional, default to 'tab'
    atomKeybinding: 'ctrl-shift-b s w', // optional
    atomMenuBar: ['Packages', 'Quick Spawn', 'Simple Bash'], // optional
    atomContextMenu: { // optional
      target: 'atom-workspace', // required
      path: ['Quick Spawn', 'Simple Bash'], // required
    },
    exitOnClose: true, // optional, default to true; should the spawned process be terminated when close the view
    closeOnExit: true, // optional, default to false; should the view be closed when bash exits
    detachedTextBox: 'none', // optional, default to 'none'
    __proto__: null // optional (of course); avoid the mess from Object.prototype
  })
}

// DESCRIPTION: registerSidebarBash
//  → Distinct:
//   * Registers for directory tree-view
//   * Uses getItemDirectory() as first current-working-directory
//  → Returns 1 subscription
function registerSidebarBash () {
  return registerSingleSubscription({})
}

// DESCRIPTION: getTabDirectory
function getTabDirectory () {
  return workspace.getActivePaneItem().getDirectoryPath()
}
<commit_msg>Complete function body of registerSidebarBash<commit_after>'use strict'

/* IMPORT */

const {packages, workspace} = global.atom
const {registerSingleSubscription} = require(packages.resolvePackagePath('quick-spawn'))

/* DO THINGS */

// NOTE:
//  → Not every function-calls below is necessary
//  → Keep only what you need
registerWorkspaceBash()
registerSidebarBash()

/* DEFINE HOW TO DO THINGS */

// DESCRIPTION: registerWorkspaceBash
//  → Distinct:
//   * Registers for workspace
//   * Uses getTabDirectory() as first current-working-directory
//  → Returns 1 subscription
function registerWorkspaceBash () {
  return registerSingleSubscription({
    execCmd: 'bash', // required; program needs to be executed
    atomCmd: 'simple-bash:workspace', // required; registers an atom-command, appears as "Simple Bash: Workspace" in Command-Palette
    atomTarget: 'atom-workspace', // required; determines where to attach the atom-command
    workingDirectory: getTabDirectory, // optional; determines Bash's first working-directory, you can change it later by 'cd new-wdir'
    attached: false, // optional, default to false; determines whether Bash process should be attached to Atom process
    suspended: true, // optional, default to true; if false, Bash would be started right after quick-spawn's activation
    viewStdIO: ['stdin', 'stdout', 'stderr'], // optional, determines whether stdin, stdout and stderr should be shown; shows all three by default
    type: 'tab', // optional, default to 'tab'
    atomKeybinding: 'ctrl-shift-b s w', // optional
    atomMenuBar: ['Packages', 'Quick Spawn', 'Simple Bash'], // optional
    atomContextMenu: { // optional
      target: 'atom-workspace', // required
      path: ['Quick Spawn', 'Simple Bash'], // required
    },
    exitOnClose: true, // optional, default to true; should the spawned process be terminated when close the view
    closeOnExit: true, // optional, default to false; should the view be closed when bash exits
    detachedTextBox: 'none', // optional, default to 'none'
    __proto__: null // optional (of course); avoid the mess from Object.prototype
  })
}

// DESCRIPTION: registerSidebarBash
//  → Distinct:
//   * Registers for directory tree-view
//   * Uses getItemDirectory() as first current-working-directory
//  → Returns 1 subscription
function registerSidebarBash () {
  const target = '.tree-view .entry'
  return registerSingleSubscription({
    execCmd: 'bash',
    atomCmd: 'simple-bash:tree-view-entry',
    atomTarget: target,
    workingDirectory: getItemDirectory,
    atomContextMenu: {
      target,
      path: ['Quick Spawn', 'Simple Bash', 'For this File/Folder']
    },
    closeOnExit: true,
    __proto__: null
  })
}

// DESCRIPTION: getTabDirectory
function getTabDirectory () {
  return workspace.getActivePaneItem().getDirectoryPath()
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (C) 2014, 2015 Push Technology Ltd.
 *
 * 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
 * http://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.
 *******************************************************************************/

var diffusion = require('diffusion');

// Connect to the server. Change these options to suit your own environment.
// Node.js will not accept self-signed certificates by default. If you have
// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0
// before running this example.
diffusion.connect({
    host   : 'diffusion.example.com',
    port   : 443,
    secure : true
}).then(function(session) {

    // 1. Subscriptions are how sessions receive streams of data from the server.

    // When subscribing, a topic selector is used to select which topics to subscribe to. Topics do not need to exist
    // at the time of subscription - the server dynamically resolves subscriptions as topics are added or removed.

    // Subscribe to the "foo" topic with an inline callback function
    var subscription = session.subscribe('foo', function(update) {
        // Log the new value whenever the 'foo' topic is updated
        // By default, we get a Buffer object which preserves binary
        // data.
        console.log(update);
    });

    // Callbacks can also be registered after the subscription has occurred
    subscription.on({
        update : function(value, topic, sub) {
            console.log('Update for topic: ' + topic, value);
        },
        subscribe : function(details, topic, sub) {
            console.log('Subscribed to topic: ' + topic);
        },
        unsubscribe : function(reason, topic, sub) {
            console.log('Unsubscribed from topic:' + topic);
            sub.close();
        }
    });

    // 2. Sessions may unsubscribe from any topic to stop receiving data

    // Unsubscribe from the "foo" topic. Sessions do not need to have previously been subscribed to the topics they are
    // unsubscribing from. Unsubscribing from a topic will result in the 'unsubscribe' callback registered above being
    // called.
    session.unsubscribe('foo');

    // 3. Subscriptions / Unsubscriptions can select multiple topics using Topic Selectors

    // Topic Selectors provide regex-like capabilities for subscribing to topics. These are resolved dynamically, much
    // like subscribing to a single topic.
    var subscription2 = session.subscribe('?foo/.*/[a-z]');

    // 4. Subscriptions can use transformers to convert update values

    // Subscribe to a topic and then convert all received values to JSON. Transforming a subscription creates a new
    // subscription stream, rather than modifying the original.
    session.subscribe('bar').transform(JSON.parse).on('update', function(value, topic) {
        console.log('Got JSON update for topic: ' + topic, value);
    });

    // 5. Metadata can be used within transformers to parse data

    // Create a simple metadata instance
    var meta = new diffusion.metadata.RecordContent();

    // Add a single record/field
    meta.addRecord('record', {
        'field' : meta.string('some-value')
    });

    // Subscribe to a topic and transform with the metadata
    session.subscribe('baz').transform(meta).on('update', function(value) {
        console.log('Field value: ', value.get('record').get('field'));
    });
});
<commit_msg>Remove trailing whitespace.<commit_after>/*******************************************************************************
 * Copyright (C) 2014, 2015 Push Technology Ltd.
 *
 * 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
 * http://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.
 *******************************************************************************/

var diffusion = require('diffusion');

// Connect to the server. Change these options to suit your own environment.
// Node.js will not accept self-signed certificates by default. If you have
// one of these, set the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0
// before running this example.
diffusion.connect({
    host   : 'diffusion.example.com',
    port   : 443,
    secure : true
}).then(function(session) {

    // 1. Subscriptions are how sessions receive streams of data from the server.

    // When subscribing, a topic selector is used to select which topics to subscribe to. Topics do not need to exist
    // at the time of subscription - the server dynamically resolves subscriptions as topics are added or removed.

    // Subscribe to the "foo" topic with an inline callback function
    var subscription = session.subscribe('foo', function(update) {
        // Log the new value whenever the 'foo' topic is updated
        // By default, we get a Buffer object which preserves binary
        // data.
        console.log(update);
    });

    // Callbacks can also be registered after the subscription has occurred
    subscription.on({
        update : function(value, topic, sub) {
            console.log('Update for topic: ' + topic, value);
        },
        subscribe : function(details, topic, sub) {
            console.log('Subscribed to topic: ' + topic);
        },
        unsubscribe : function(reason, topic, sub) {
            console.log('Unsubscribed from topic:' + topic);
            sub.close();
        }
    });

    // 2. Sessions may unsubscribe from any topic to stop receiving data

    // Unsubscribe from the "foo" topic. Sessions do not need to have previously been subscribed to the topics they are
    // unsubscribing from. Unsubscribing from a topic will result in the 'unsubscribe' callback registered above being
    // called.
    session.unsubscribe('foo');

    // 3. Subscriptions / Unsubscriptions can select multiple topics using Topic Selectors

    // Topic Selectors provide regex-like capabilities for subscribing to topics. These are resolved dynamically, much
    // like subscribing to a single topic.
    var subscription2 = session.subscribe('?foo/.*/[a-z]');

    // 4. Subscriptions can use transformers to convert update values

    // Subscribe to a topic and then convert all received values to JSON. Transforming a subscription creates a new
    // subscription stream, rather than modifying the original.
    session.subscribe('bar').transform(JSON.parse).on('update', function(value, topic) {
        console.log('Got JSON update for topic: ' + topic, value);
    });

    // 5. Metadata can be used within transformers to parse data

    // Create a simple metadata instance
    var meta = new diffusion.metadata.RecordContent();

    // Add a single record/field
    meta.addRecord('record', {
        'field' : meta.string('some-value')
    });

    // Subscribe to a topic and transform with the metadata
    session.subscribe('baz').transform(meta).on('update', function(value) {
        console.log('Field value: ', value.get('record').get('field'));
    });
});
<|endoftext|>


<commit_before>/**
 * @license
 * 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
 *
 *     http://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.
 */

__DATA({
  model_: 'foam.build.WebApplication',
  id: 'foam.apps.mbug.WebApp',
  controller: 'foam.apps.mbug.MBug',
  defaultView: 'foam.ui.layout.Window',
  version: "1.1.4",
  includeFoamCSS: false,
  precompileTemplates: true,
  appcacheManifest: true,
  icon: 'images/logo.png',
  resources: [
    'images/defaultlogo.png',
    'images/ic_add_24dp.png',
    'images/ic_add_black_24dp.png',
    'images/ic_arrow_back_24dp.png',
    'images/ic_arrow_back_24dp_black.png',
    'images/ic_arrow_drop_down_24dp.png',
    'images/ic_cancel_24dp.png',
    'images/ic_clear_24dp.png',
    'images/ic_clear_black_24dp.png',
    'images/ic_done_24dp.png',
    'images/ic_filter_24dp.png',
    'images/ic_keep_24dp.png',
    'images/ic_menu_24dp.png',
    'images/ic_search_24dp.png',
    'images/ic_sort_24dp.png',
    'images/ic_star_24dp.png',
    'images/ic_star_outline_24dp.png',
    'images/ic_star_outline_white_24dp.png',
    'images/ic_star_white_24dp.png',
    'images/logo.png',
    'images/projectBackground.png',
    'images/silhouette.png'
  ],
  htmlHeaders: [
    '<meta charset="utf-8"/>',
    '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1"/>',
    '<meta name="mobile-web-app-capable" content="yes"/>'
  ],
  coreFiles: [
    'firefox',
    'funcName',
    'safari',
    'stdlib',
    'WeakMap',
    'async',
    'parse',
    'event',
    'JSONUtil',
    'XMLUtil',
    'context',
    'JSONParser',
    'TemplateUtil',
    'FOAM',
    'FObject',
    'BootstrapModel',
    'mm1Model',
    'mm2Property',
    'mm3Types',
    'mm4Method',
    'mm5Misc',
    '../js/foam/ui/Window',
    'value',
    'view',
    '../js/foam/ui/FoamTagView',
    'HTMLParser',
    'mlang',
    'mlang2',
    'QueryParser',
    'visitor',
    'messaging',
    'dao',
    'arrayDAO',
    'index',
    'models',
    'oauth'
  ],
  extraModels: ['foam.ui.RelationshipView']
});
<commit_msg>Update MBug to 1.1.5<commit_after>/**
 * @license
 * 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
 *
 *     http://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.
 */

__DATA({
  model_: 'foam.build.WebApplication',
  id: 'foam.apps.mbug.WebApp',
  controller: 'foam.apps.mbug.MBug',
  defaultView: 'foam.ui.layout.Window',
  version: "1.1.5",
  includeFoamCSS: false,
  precompileTemplates: true,
  appcacheManifest: true,
  icon: 'images/logo.png',
  resources: [
    'images/defaultlogo.png',
    'images/ic_add_24dp.png',
    'images/ic_add_black_24dp.png',
    'images/ic_arrow_back_24dp.png',
    'images/ic_arrow_back_24dp_black.png',
    'images/ic_arrow_drop_down_24dp.png',
    'images/ic_cancel_24dp.png',
    'images/ic_clear_24dp.png',
    'images/ic_clear_black_24dp.png',
    'images/ic_done_24dp.png',
    'images/ic_filter_24dp.png',
    'images/ic_keep_24dp.png',
    'images/ic_menu_24dp.png',
    'images/ic_search_24dp.png',
    'images/ic_sort_24dp.png',
    'images/ic_star_24dp.png',
    'images/ic_star_outline_24dp.png',
    'images/ic_star_outline_white_24dp.png',
    'images/ic_star_white_24dp.png',
    'images/logo.png',
    'images/projectBackground.png',
    'images/silhouette.png'
  ],
  htmlHeaders: [
    '<meta charset="utf-8"/>',
    '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1"/>',
    '<meta name="mobile-web-app-capable" content="yes"/>'
  ],
  coreFiles: [
    'firefox',
    'funcName',
    'safari',
    'stdlib',
    'WeakMap',
    'async',
    'parse',
    'event',
    'JSONUtil',
    'XMLUtil',
    'context',
    'JSONParser',
    'TemplateUtil',
    'FOAM',
    'FObject',
    'BootstrapModel',
    'mm1Model',
    'mm2Property',
    'mm3Types',
    'mm4Method',
    'mm5Misc',
    '../js/foam/ui/Window',
    'value',
    'view',
    '../js/foam/ui/FoamTagView',
    'HTMLParser',
    'mlang',
    'mlang2',
    'QueryParser',
    'visitor',
    'messaging',
    'dao',
    'arrayDAO',
    'index',
    'models',
    'oauth'
  ],
  extraModels: ['foam.ui.RelationshipView']
});
<|endoftext|>


<commit_before>'use strict';

angular.module('farmbuild.soilSampleImporter.examples.paddockSelector', ['farmbuild.soilSampleImporter'])

    .run(function ($rootScope) {
        $rootScope.appVersion = farmbuild.examples.soilsampleimporter.version;
    })

    .controller('PaddockSelectorCtrl', function ($scope, $log, soilSampleImporter, paddockSelector, validations,
            collections) {
        //$scope.paddockSelection = paddockSelector.createNew();
        $scope.paddockSelection = {};
        $scope.noResult = false;
        $scope.paddockColumnIndex = paddockSelector.paddockColumnIndex;
        $scope.classificationTypes = [];
        $scope.paddocks = [];
        $scope.myFarmData = soilSampleImporter.find();

        for(var i=0; i<paddockSelector.types.length;i++) {
            var newClassificication = {};
            newClassificication.name=paddockSelector.types[i].name;
            $scope.classificationTypes.push(newClassificication);
        }

        $scope.changeClassification = function (paddockSelection, colIndex, classificationType, oldValueString) {
            if (!(validations.isEmpty(oldValueString))) {
                $log.info('removing previously selected classificationType '+oldValueString);
                //oldValue is string literal of previous value
                var prevClassification = JSON.parse(oldValueString);
                paddockSelector.declassifyColumn(paddockSelection, prevClassification, colIndex);
            }
            if (!(validations.isEmpty(classificationType))) {
                $log.info('adding newly selected classificationType '+classificationType + " to col "+colIndex);
                paddockSelector.classifyColumn(paddockSelection, classificationType, colIndex);
            }
        }

        $scope.changePaddock = function (paddockSelection, rowIndex, paddock, oldValueString) {
            if (!(validations.isEmpty(oldValueString))) {
                $log.info('removing previously selected paddock '+oldValueString);
                //oldValue is string literal of previous value
                var prevPaddock = JSON.parse(oldValueString);
                paddockSelector.disconnectRow(paddockSelection, prevPaddock, rowIndex);
            }
            if (!(validations.isEmpty(paddock))) {
                $log.info('adding newly selected paddock '+paddock + " to row "+rowIndex);
                paddockSelector.connectRow(paddockSelection, paddock, rowIndex);
            }
        }

        $scope.loadSoilSample = function ($fileContent) {
            try {
                var csv = d3.csv.parseRows($fileContent);
                for(var i=0; i<csv.length; i++) {
                    if (i==0) {
                        csv[i].splice(0, 0, "PaddockName");
                    }
                    else {
                        csv[i].splice(0, 0, '-1');
                    }
                }
                $log.info(csv);
                var header = csv.shift();
                $scope.paddockSelection = paddockSelector.createNew($scope.myFarmData,
                    header,
                    csv, 0);
                if (!$scope.paddockSelection) {
                    $scope.noResult = true;
                    return;
                }
                $scope.paddocks = paddockSelector.paddocks;
            } catch (e) {
                console.error('farmbuild.soilSampleImporter.loadsample > load: Your file should be in csv format: ', e);
                $scope.noResult = true;
            }
        }

        $scope.export = function (paddockSelection) {

            $scope.result = paddockSelector.save(paddockSelection);

            if ($scope.result) {
                soilSampleImporter.export(document, $scope.result);
            }
            else {
                $scope.noResult = true;
            }

        };
    })

    .directive('onReadFile', function ($parse, $log) {
        return {
            restrict: 'A',
            scope: false,
            link: function (scope, element, attrs) {
                var fn = $parse(attrs.onReadFile);

                element.on('change', function (onChangeEvent) {
                    //var file =  (onChangeEvent.srcElement || onChangeEvent.target).files[0]
                    var file =  (onChangeEvent.target).files[0]
                    $log.info('onReadFile.onChange... onChangeEvent.srcElement:%s, ' +
                        'onChangeEvent.target:%s, (onChangeEvent.srcElement || onChangeEvent.target).files[0]: %s',
                        onChangeEvent.srcElement, onChangeEvent.target,
                        file)

                    var reader = new FileReader();

                    reader.onload = function (onLoadEvent) {
                        //console.log('reader.onload', angular.toJson(onLoadEvent));
                        scope.$apply(function () {
                            fn(scope, {$fileContent: onLoadEvent.target.result});
                        });
                    };
                    reader.onerror = function (onLoadEvent) {
                        //console.log('reader.onload', angular.toJson(onLoadEvent));
                    };

                    reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);

                });
            }
        };
    });<commit_msg>clean up code<commit_after>'use strict';

angular.module('farmbuild.soilSampleImporter.examples.paddockSelector', ['farmbuild.soilSampleImporter'])

    .run(function ($rootScope) {
        $rootScope.appVersion = farmbuild.examples.soilsampleimporter.version;
    })

    .controller('PaddockSelectorCtrl', function ($scope, $log, soilSampleImporter, paddockSelector, validations,
            collections) {
        //$scope.paddockSelection = paddockSelector.createNew();
        $scope.paddockSelection = {};
        $scope.noResult = false;
        $scope.paddockColumnIndex = 0;
        $scope.classificationTypes = [];
        $scope.paddocks = [];
        $scope.myFarmData = soilSampleImporter.find();

        for(var i=0; i<paddockSelector.types.length;i++) {
            var newClassificication = {};
            newClassificication.name=paddockSelector.types[i].name;
            $scope.classificationTypes.push(newClassificication);
        }

        $scope.changeClassification = function (paddockSelection, colIndex, classificationType, oldValueString) {
            if (!(validations.isEmpty(oldValueString))) {
                $log.info('removing previously selected classificationType '+oldValueString);
                //oldValue is string literal of previous value
                var prevClassification = JSON.parse(oldValueString);
                paddockSelector.declassifyColumn(paddockSelection, prevClassification, colIndex);
            }
            if (!(validations.isEmpty(classificationType))) {
                $log.info('adding newly selected classificationType '+classificationType + " to col "+colIndex);
                paddockSelector.classifyColumn(paddockSelection, classificationType, colIndex);
            }
        }

        $scope.changePaddock = function (paddockSelection, rowIndex, paddock, oldValueString) {
            if (!(validations.isEmpty(oldValueString))) {
                $log.info('removing previously selected paddock '+oldValueString);
                //oldValue is string literal of previous value
                var prevPaddock = JSON.parse(oldValueString);
                paddockSelector.disconnectRow(paddockSelection, prevPaddock, rowIndex);
            }
            if (!(validations.isEmpty(paddock))) {
                $log.info('adding newly selected paddock '+paddock + " to row "+rowIndex);
                paddockSelector.connectRow(paddockSelection, paddock, rowIndex);
            }
        }

        $scope.loadSoilSample = function ($fileContent) {
            try {
                var csv = d3.csv.parseRows($fileContent);
                for(var i=0; i<csv.length; i++) {
                    if (i==0) {
                        csv[i].splice(0, 0, "PaddockName");
                    }
                    else {
                        csv[i].splice(0, 0, '-1');
                    }
                }
                var header = csv.shift();
                $scope.paddockSelection = paddockSelector.createNew($scope.myFarmData,
                    header,
                    csv, 0);
                if (!$scope.paddockSelection) {
                    $scope.noResult = true;
                    return;
                }
                $scope.paddocks = paddockSelector.paddocks;
            } catch (e) {
                console.error('farmbuild.soilSampleImporter.loadsample > load: Your file should be in csv format: ', e);
                $scope.noResult = true;
            }
        }

        $scope.export = function (paddockSelection) {

            $scope.result = paddockSelector.save(paddockSelection);

            if ($scope.result) {
                soilSampleImporter.export(document, $scope.result);
            }
            else {
                $scope.noResult = true;
            }

        };
    })

    .directive('onReadFile', function ($parse, $log) {
        return {
            restrict: 'A',
            scope: false,
            link: function (scope, element, attrs) {
                var fn = $parse(attrs.onReadFile);

                element.on('change', function (onChangeEvent) {
                    var file =  (onChangeEvent.target).files[0]
                    $log.info('onReadFile.onChange... onChangeEvent.srcElement:%s, ' +
                        'onChangeEvent.target:%s, (onChangeEvent.srcElement || onChangeEvent.target).files[0]: %s',
                        onChangeEvent.srcElement, onChangeEvent.target,
                        file)

                    var reader = new FileReader();

                    reader.onload = function (onLoadEvent) {

                        scope.$apply(function () {
                            fn(scope, {$fileContent: onLoadEvent.target.result});
                        });
                    };
                    reader.onerror = function (onLoadEvent) {

                    };

                    reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);

                });
            }
        };
    });<|endoftext|>


<commit_before>import React from 'react'
import PersonGroup from '../../../../components/person-group'
import {sortPeople, isPast} from '../../../../../shared/utils'
import RSVPIcon from '../../../../components/rsvp-icon'

export default Header

function Header({episode}) {
  const {
    title,
    timeHTML,
    dateDisplay,
    date,
    guests = [],
    descriptionHTML,
    hangoutUrl,
    numberDisplay,
  } = episode
  const past = episode.past || isPast(date)
  const sortedGuests = sortPeople(guests)
  return (

          JavaScript Air

          Episode {numberDisplay}: {title}

            {past ? '' : <RSVPIcon hangoutUrl={hangoutUrl} />}
            {' ' + dateDisplay} at

        <PersonGroup people={sortedGuests} />

  )
}

<commit_msg>Old habits die hard<commit_after>import React from 'react'
import PersonGroup from '../../../../components/person-group'
import {sortPeople, isPast} from '../../../../../shared/utils'
import RSVPIcon from '../../../../components/rsvp-icon'

export default Header

function Header({episode}) {
  const {
    title,
    timeHTML,
    dateDisplay,
    date,
    guests = [],
    descriptionHTML,
    hangoutUrl,
    numberDisplay,
  } = episode
  const past = episode.past || isPast(date)
  const sortedGuests = sortPeople(guests)
  return (

          JavaScript Air

          Episode {numberDisplay}: {title}

            {past ? '' : <RSVPIcon hangoutUrl={hangoutUrl} />}
            {' ' + dateDisplay} at

        <PersonGroup people={sortedGuests} />

  )
}

<|endoftext|>


<commit_before>import React from 'react';

import { emallson, Hordehobbs } from 'CONTRIBUTORS';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { change, date } from 'common/changelog';

export default [
  change(date(2020, 10, 14), "Add NoDamageShieldOfTheRighteous analyzer", Hordehobbs),
  change(date(2020, 10, 13), "Convert Consecration analyzer to Typescript.", Hordehobbs),
  change(date(2020, 10, 12), "Initial changes for Shadowlands Prepatch.", [emallson]),
  change(date(2020, 3, 29), <>Added support for <SpellLink id={SPELLS.LUCID_DREAMS.id} /> minor. Note that the major is still unsupported.</>, emallson),
  change(date(2019, 5, 17), <>Fixed an issue with <SpellLink id={SPELLS.JUDGMENT_CAST_PROTECTION.id} /> having its cooldown reset too often when using <SpellLink id={SPELLS.CRUSADERS_JUDGMENT_TALENT.id} />. Special thanks to Woliance for helping me work it out.</>, [emallson]),
  {
    date: new Date('16 February 2019'),
    contributors: [emallson],
    changes: <><SpellLink id={SPELLS.HAND_OF_THE_PROTECTOR_TALENT.id} /> cast delay is now only tracked for self-targeted casts.</>,
  },
  {
    date: new Date('29 December 2018'),
    contributors: [emallson],
    changes: <>Added support for Avenger's Valor to the Good <SpellLink id={SPELLS.SHIELD_OF_THE_RIGHTEOUS.id} /> casts check.</>,
  },
  {
    date: new Date('29 December 2018'),
    contributors: [emallson],
    changes: <>Moved <SpellLink id={SPELLS.ARDENT_DEFENDER.id} /> to the damage mitigation checklist item. Removed the "Use your defensive cooldowns" checklist item.</>,
  },
  {
    date: new Date('11 November 2018'),
    contributors: [emallson],
    changes: <>Added <SpellLink id={SPELLS.LIGHT_OF_THE_PROTECTOR.id} /> / <SpellLink id={SPELLS.HAND_OF_THE_PROTECTOR_TALENT.id} /> delay and overheal tracking.</>,
  },
  {
    date: new Date('30 October 2018'),
    contributors: [emallson],
    changes: <>Added <SpellLink id={SPELLS.SHIELD_OF_THE_RIGHTEOUS.id} /> cooldown reduction statistic.</>,
  },
  {
    date: new Date('28 October 2018'),
    contributors: [emallson],
    changes: <>Converted <SpellLink id={SPELLS.CONSECRATION_CAST.id} /> from buff uptime to hit tracking.</>,
  },
  {
    date: new Date('10 October 2018'),
    contributors: [emallson],
    changes: <>Added tracking for which <SpellLink id={SPELLS.SHIELD_OF_THE_RIGHTEOUS.id} /> casts are effective.</>,
  },
  {
    date: new Date('6 October 2018'),
    contributors: [emallson],
    changes: <>Added support for <SpellLink id={SPELLS.INSPIRING_VANGUARD.id} />, including the ability to exactly detect <SpellLink id={SPELLS.GRAND_CRUSADER.id} /> resets when this trait is taken.</>,
  },
];
<commit_msg>changelog<commit_after>import React from 'react';

import { emallson, Hordehobbs, Zeboot } from 'CONTRIBUTORS';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { change, date } from 'common/changelog';

export default [
  change(date(2020, 10, 18), 'Converted legacy listeners to new event filters', Zeboot),
  change(date(2020, 10, 14), "Add NoDamageShieldOfTheRighteous analyzer", Hordehobbs),
  change(date(2020, 10, 13), "Convert Consecration analyzer to Typescript.", Hordehobbs),
  change(date(2020, 10, 12), "Initial changes for Shadowlands Prepatch.", [emallson]),
  change(date(2020, 3, 29), <>Added support for <SpellLink id={SPELLS.LUCID_DREAMS.id} /> minor. Note that the major is still unsupported.</>, emallson),
  change(date(2019, 5, 17), <>Fixed an issue with <SpellLink id={SPELLS.JUDGMENT_CAST_PROTECTION.id} /> having its cooldown reset too often when using <SpellLink id={SPELLS.CRUSADERS_JUDGMENT_TALENT.id} />. Special thanks to Woliance for helping me work it out.</>, [emallson]),
  {
    date: new Date('16 February 2019'),
    contributors: [emallson],
    changes: <><SpellLink id={SPELLS.HAND_OF_THE_PROTECTOR_TALENT.id} /> cast delay is now only tracked for self-targeted casts.</>,
  },
  {
    date: new Date('29 December 2018'),
    contributors: [emallson],
    changes: <>Added support for Avenger's Valor to the Good <SpellLink id={SPELLS.SHIELD_OF_THE_RIGHTEOUS.id} /> casts check.</>,
  },
  {
    date: new Date('29 December 2018'),
    contributors: [emallson],
    changes: <>Moved <SpellLink id={SPELLS.ARDENT_DEFENDER.id} /> to the damage mitigation checklist item. Removed the "Use your defensive cooldowns" checklist item.</>,
  },
  {
    date: new Date('11 November 2018'),
    contributors: [emallson],
    changes: <>Added <SpellLink id={SPELLS.LIGHT_OF_THE_PROTECTOR.id} /> / <SpellLink id={SPELLS.HAND_OF_THE_PROTECTOR_TALENT.id} /> delay and overheal tracking.</>,
  },
  {
    date: new Date('30 October 2018'),
    contributors: [emallson],
    changes: <>Added <SpellLink id={SPELLS.SHIELD_OF_THE_RIGHTEOUS.id} /> cooldown reduction statistic.</>,
  },
  {
    date: new Date('28 October 2018'),
    contributors: [emallson],
    changes: <>Converted <SpellLink id={SPELLS.CONSECRATION_CAST.id} /> from buff uptime to hit tracking.</>,
  },
  {
    date: new Date('10 October 2018'),
    contributors: [emallson],
    changes: <>Added tracking for which <SpellLink id={SPELLS.SHIELD_OF_THE_RIGHTEOUS.id} /> casts are effective.</>,
  },
  {
    date: new Date('6 October 2018'),
    contributors: [emallson],
    changes: <>Added support for <SpellLink id={SPELLS.INSPIRING_VANGUARD.id} />, including the ability to exactly detect <SpellLink id={SPELLS.GRAND_CRUSADER.id} /> resets when this trait is taken.</>,
  },
];
<|endoftext|>