<commit_before>var vm   = require ('vm');
var fs   = require ('fs');
var path = require ('path');

var scadHelperScript = fs.readFileSync (path.resolve (__dirname, '../standalone/openscad.js')).toString ();

// TODO: use trie https://github.com/jeresig/trie-js/blob/master/Bits.js
// var dict = new FrozenTrie( parts[2], parts[1], parts[0] );
// dict.lookup( "test" );
var suggestMethods = {
  // 3d primitives
  cube: {
    type: 'function',
    snippet: "cube({size: ${1:[1, 1, 1]}, center: ${2:[true, true, true]}})$3",
    description: ''
  },
  sphere: {
    type: 'function',
    snippet: "sphere({r: ${1:1}, center: ${2:[true, true, true]}})$3",
    description: ''
  },
  // geodesicSphere: {},
  cylinder: {
    type: 'function',
    snippet: "cylinder({r: ${1:1}, h: ${2:1}, center: ${3:[true, true, true]}})$4",
    description: ''
  },
  // torus: {},
  // polyhedron: {},

  translate: {
    type: 'method',
    snippet: "translate([${1:0}, ${2:0}, ${3:0}])$4",
    description: ''
  },

  rotateX: {
    type: 'method',
    snippet: "rotateX(${1:0})$2",
    description: ''
  },

  rotateY: {
    type: 'method',
    snippet: "rotateY(${1:0})$2",
    description: ''
  },

  rotateZ: {
    type: 'method',
    snippet: "rotateZ(${1:0})$2",
    description: ''
  },

  union: {
    type: 'function',
    snippet: "union($1)",
  },
  difference: {
    type: 'function',
    snippet: "difference($1)",
  },
  intersection: {
    type: 'function',
    snippet: "intersection($1)",
  },
};

function getSCADHelpers () {
  var sandbox = {
    require: require
  };

  vm.createContext(sandbox);

  // vm.runInContext (OpenJsCad.includeJscad.toString ().replace ('function', 'function include'), sandbox, {
  // });

  vm.runInContext (scadHelperScript, sandbox, {
    // filename <string> Specifies the filename used in stack traces produced by this script.
    lineOffset: 1, // <number> Specifies the line number offset that is displayed in stack traces produced by this script.
    columnOffset: 1, // <number> Specifies the column number offset that is displayed in stack traces produced by this script.
    // displayErrors <boolean> When true, if an Error error occurs while compiling the code, the line of code causing the error is attached to the stack trace.
    // timeout <number> Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.
  });

  console.log (Object.keys (sandbox));

  // vm.runInContext ("if(typeof(getParameterDefinitions) == 'function') {params = getParameterDefinitions();}", sandbox, {});

  // params = sandbox.params;

}

// getSCADHelpers ();

function JSCADCompletion () {
  var result = this;
  if (this instanceof JSCADCompletion) {
  } else {
    result = new JSCADCompletion ();
  }

  result.minSuggestionLength = atom.config.get('autocomplete-plus.minimumWordLength') || result.minSuggestionLength;

  return result;
}

JSCADCompletion.prototype = {
  selector: '.source.js, .source.jscad',
  disableForSelector: '.source.js .comment, .source.jscad .comment',
  inclusionPriority: 100,

  minSuggestionLength: 2,

  // inclusionPriority (optional): A number to indicate its priority to be included in a suggestions request. The default provider has an inclusion priority of 0. Higher priority providers can suppress lower priority providers with excludeLowerPriority.
  // excludeLowerPriority (optional): Will not use lower priority providers when this provider is used.
  // suggestionPriority (optional): A number to determine the sort order of suggestions. The default provider has an suggestion priority of 1
  // dispose (optional): Will be called if your provider is being destroyed by autocomplete+
  // onDidInsertSuggestion (optional): Function that is called when a suggestion from your provider was inserted into the buffer
  // editor: the TextEditor your suggestion was inserted in
  // triggerPosition: A Point where autocomplete was triggered
  // suggestion: The suggestion object that was inserted.

  getSuggestions ({editor, bufferPosition, scopeDescriptor, prefix}) {

    console.log (this);

    var line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]);

    var suggestions = [];

    if (prefix.match (/\W/) || prefix.length < this.minSuggestionLength)
      return suggestions;

    console.log (line, scopeDescriptor, prefix, line.substr (line.length - prefix.length - 1, 1));

    var prevChar;
    if (line.length > prefix.length) {
      prevChar = line.substr (line.length - prefix.length - 1, 1);
    }

    Object.keys (suggestMethods).forEach (m => {
      if (m.indexOf (prefix) >= 0) {
        // issue: https://github.com/atom/autocomplete-plus/issues/781
        if (prevChar === '.') {
          // assume methods only
          if (suggestMethods[m].type === 'method')
            suggestions.push (Object.assign ({}, suggestMethods[m], {replacementPrefix: null}));
        } else {
          // only functions accepted
          if (suggestMethods[m].type !== 'method')
            suggestions.push (Object.assign ({}, suggestMethods[m], {replacementPrefix: null}));
        }

      }
    })

    return suggestions;

    return new Promise(function(resolve) {
      // Find your suggestions here
      var suggestion = {
        text: 'someText', // OR
        snippet: 'someText(${1:myArg})',
        displayText: 'someText', // (optional)
        replacementPrefix: 'so', // (optional)
        type: 'function', // (optional)
        leftLabel: '', // (optional)
        leftLabelHTML: '', // (optional)
        rightLabel: '', // (optional)
        rightLabelHTML: '', // (optional)
        className: '', // (optional)
        iconHTML: '', // (optional)
        description: '', // (optional)
        descriptionMoreURL: '' // (optional)
      };
      return resolve([suggestion]);
    });
  }
};

module.exports = JSCADCompletion;
<commit_msg>completion module<commit_after>var vm   = require ('vm');
var fs   = require ('fs');
var path = require ('path');

var scadHelperScript = fs.readFileSync (path.resolve (__dirname, '../standalone/openscad.js')).toString ();

// TODO: use trie https://github.com/jeresig/trie-js/blob/master/Bits.js
// var dict = new FrozenTrie( parts[2], parts[1], parts[0] );
// dict.lookup( "test" );
var suggestMethods = {
  // 3d primitives
  cube: {
    type: 'function',
    snippet: "cube({size: ${1:[1, 1, 1]}, center: ${2:[true, true, true]}})$3",
    description: 'cube',
    descriptionMoreURL: "https://en.wikibooks.org/wiki/OpenJSCAD_User_Guide#Cube"
  },
  sphere: {
    type: 'function',
    snippet: "sphere({r: ${1:1}, center: ${2:[true, true, true]}})$3",
    description: 'sphere',
    descriptionMoreURL: "https://en.wikibooks.org/wiki/OpenJSCAD_User_Guide#Sphere"
  },
  // geodesicSphere: {},
  cylinder: {
    type: 'function',
    snippet: "cylinder({r: ${1:1}, h: ${2:1}, center: ${3:[true, true, true]}})$4",
    description: 'cylinder',
    descriptionMoreURL: "https://en.wikibooks.org/wiki/OpenJSCAD_User_Guide#Cylinder"
  },
  torus: {
    type: 'function',
    snippet: "torus({$1})$2",
    description: 'torus',
    descriptionMoreURL: "https://en.wikibooks.org/wiki/OpenJSCAD_User_Guide#Torus"
  },
  polyhedron: {
    type: 'function',
    snippet: "polyhedron({$1})$2",
    description: 'polyhedron',
    descriptionMoreURL: "https://en.wikibooks.org/wiki/OpenJSCAD_User_Guide#Polyhedron"
  },

  vector_text: {
    type: 'function',
    snippet: "vector_text(${1:0}, ${2:0}, ${3:'A'})$4",
    description: ''
  }

  vector_text: {
    type: 'function',
    snippet: "vector_text(${1:0}, ${2:0}, ${3:'A'})$4",
    description: ''
  },

  scale: {
    type: 'method',
    snippet: "scale($1)$2",
  },

  translate: {
    type: 'method',
    snippet: "translate([${1:0}, ${2:0}, ${3:0}])$4",
    description: ''
  },

  rotateX: {
    type: 'method',
    snippet: "rotateX(${1:0})$2",
    description: ''
  },

  rotateY: {
    type: 'method',
    snippet: "rotateY(${1:0})$2",
    description: ''
  },

  rotateZ: {
    type: 'method',
    snippet: "rotateZ(${1:0})$2",
    description: ''
  },

  // combine
  union: {
    type: 'function',
    snippet: "union($1)$2",
  },
  difference: {
    type: 'function',
    snippet: "difference($1)$2",
  },
  substract: {
    type: 'method',
    snippet: "substract($1)$2",
  },
  intersection: {
    type: 'function',
    snippet: "intersection($1)$2",
  },
  intersect: {
    type: 'method',
    snippet: "intersect($1)$2",
  },

  hull: {
    type: 'function',
    snippet: "hull($1)$2",
  },

  chain_hull: {
    type: 'function',
    snippet: "chain_hull($1)$2",
  },

  // extrude
  linear_extrude: {
    type: 'function',
    snippet: "linear_extrude($1)$2",
    description: 'linear extrusion for 2D models'
  },
  extrude: {
    type: 'method',
    snippet: "extrude($1)$2",
    description: 'linear extrusion for 2D models'
  },
  rectangular_extrude: {
    type: 'function',
    snippet: "rectangular_extrude($1)$2",
    description: 'rectangular extrusion for 2D models'
  },
  rectangularExtrude: {
    type: 'method',
    snippet: "rectangularExtrude($1)$2",
    description: 'rectangular extrusion for 2D models'
  },
  rotate_extrude: {
    type: 'function',
    snippet: "rotate_extrude($1)$2",
  },

  setColor: {
    type: 'method',
    snippet: "setColor($1)$2",
  },
};

function getSCADHelpers () {
  var sandbox = {
    require: require
  };

  vm.createContext(sandbox);

  // vm.runInContext (OpenJsCad.includeJscad.toString ().replace ('function', 'function include'), sandbox, {
  // });

  vm.runInContext (scadHelperScript, sandbox, {
    // filename <string> Specifies the filename used in stack traces produced by this script.
    lineOffset: 1, // <number> Specifies the line number offset that is displayed in stack traces produced by this script.
    columnOffset: 1, // <number> Specifies the column number offset that is displayed in stack traces produced by this script.
    // displayErrors <boolean> When true, if an Error error occurs while compiling the code, the line of code causing the error is attached to the stack trace.
    // timeout <number> Specifies the number of milliseconds to execute code before terminating execution. If execution is terminated, an Error will be thrown.
  });

  console.log (Object.keys (sandbox));

  // vm.runInContext ("if(typeof(getParameterDefinitions) == 'function') {params = getParameterDefinitions();}", sandbox, {});

  // params = sandbox.params;

}

// getSCADHelpers ();

function JSCADCompletion () {
  var result = this;
  if (this instanceof JSCADCompletion) {
  } else {
    result = new JSCADCompletion ();
  }

  result.minSuggestionLength = atom.config.get('autocomplete-plus.minimumWordLength') || result.minSuggestionLength;

  return result;
}

JSCADCompletion.prototype = {
  selector: '.source.js, .source.jscad',
  disableForSelector: '.source.js .comment, .source.jscad .comment',
  inclusionPriority: 100,

  minSuggestionLength: 2,

  // inclusionPriority (optional): A number to indicate its priority to be included in a suggestions request. The default provider has an inclusion priority of 0. Higher priority providers can suppress lower priority providers with excludeLowerPriority.
  // excludeLowerPriority (optional): Will not use lower priority providers when this provider is used.
  // suggestionPriority (optional): A number to determine the sort order of suggestions. The default provider has an suggestion priority of 1
  // dispose (optional): Will be called if your provider is being destroyed by autocomplete+
  // onDidInsertSuggestion (optional): Function that is called when a suggestion from your provider was inserted into the buffer
  // editor: the TextEditor your suggestion was inserted in
  // triggerPosition: A Point where autocomplete was triggered
  // suggestion: The suggestion object that was inserted.

  getSuggestions ({editor, bufferPosition, scopeDescriptor, prefix}) {

    var line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]);

    var suggestions = [];

    if (prefix.match (/\W/) || prefix.length < this.minSuggestionLength)
      return suggestions;

    // console.log (line, scopeDescriptor, prefix, line.substr (line.length - prefix.length - 1, 1));

    var prevChar;
    if (line.length > prefix.length) {
      prevChar = line.substr (line.length - prefix.length - 1, 1);
    }

    Object.keys (suggestMethods).forEach (m => {
      if (m.indexOf (prefix) >= 0) {
        // issue: https://github.com/atom/autocomplete-plus/issues/781
        if (prevChar === '.') {
          // assume methods only
          if (suggestMethods[m].type === 'method')
            suggestions.push (Object.assign ({}, suggestMethods[m], {replacementPrefix: null}));
        } else {
          // only functions accepted
          if (suggestMethods[m].type !== 'method')
            suggestions.push (Object.assign ({}, suggestMethods[m], {replacementPrefix: null}));
        }

      }
    })

    return suggestions;

    return new Promise(function(resolve) {
      // Find your suggestions here
      var suggestion = {
        text: 'someText', // OR
        snippet: 'someText(${1:myArg})',
        displayText: 'someText', // (optional)
        replacementPrefix: 'so', // (optional)
        type: 'function', // (optional)
        leftLabel: '', // (optional)
        leftLabelHTML: '', // (optional)
        rightLabel: '', // (optional)
        rightLabelHTML: '', // (optional)
        className: '', // (optional)
        iconHTML: '', // (optional)
        description: '', // (optional)
        descriptionMoreURL: '' // (optional)
      };
      return resolve([suggestion]);
    });
  }
};

module.exports = JSCADCompletion;
<|endoftext|>


<commit_before>(function(lib, undefined) {
    /*global lib*/
    "use strict";

    function NodeList(elements) {
        if (this === lib.dom) {
            return new NodeList(elements);
        }

        if (!elements) {
            return;
        }

        if (lib.dom.isTypeOf(elements, lib.dom.ELEMENT_NODE | lib.dom.DOCUMENT_NODE)) {
            this.push(elements);
        } else if (elements instanceof NodeList) {
            return elements;
        } else {
            elements = lib.array.toArray(elements);
            lib.array.forEach(elements, lib.bind(function(element) {
                if (lib.dom.isTypeOf(element, lib.dom.ELEMENT_NODE | lib.dom.DOCUMENT_NODE)) {
                    this.push(element);
                }
            }, this));
        }
    }

    lib.util.inherits(NodeList, Array);

    lib.extend(NodeList.prototype, {
        toString: function toString() {
            return this.join(", ");
        },

        valueOf: function valueOf() {
            return this;
        },

        item: function item(index) {
            return this[index];
        },

        /* array extensions */
        concat: function concat() {
            var args = lib.array.toArray(arguments);
            lib.array.forEach(args, lib.bind(function(arg) {
                lib.array.forEach(arg, lib.bind(function(elem) {
                    this.push(elem);
                }, this));
            }, this));
        },

        slice: function slice() {
            return lib.dom.NodeList(Array.prototype.slice.apply(this, arguments));
        },

        toArray: function toArray() {
            return lib.array.toArray(this);
        },

        indexOf: function indexOf(object, fromIndex) {
            return lib.array.indexOf(this, object, fromIndex);
        },

        lastIndexOf: function lastIndexOf(object, fromIndex) {
            return lib.array.lastIndexOf(this, object, fromIndex);
        },

        inArray: function inArray(object) {
            return lib.array.inArray(this, object);
        },

        forEach: function forEach(callback, thisObject) {
            lib.array.forEach(this, callback, thisObject);
        },

        every: function every(callback, thisObject) {
            return lib.array.every(this, callback, thisObject);
        },

        some: function some(callback, thisObject) {
            return lib.array.some(this, callback, thisObject);
        },

        filter: function filter(callback, thisObject) {
            return new NodeList(lib.array.filter(this, callback, thisObject));
        },

        map: function map(callback, thisObject) {
            return new NodeList(lib.array.map(this, callback, thisObject));
        },

        reduce: function reduce(callback, initialValue) {
            return lib.array.reduce(this, callback, initialValue);
        },

        reduceRight: function reduceRight(callback, initialValue) {
            return lib.array.reduceRight(this, callback, initialValue);
        },

        /* dom helpers */
        byTag: function byTag(tag) {
            var out = lib.dom.NodeList();
            this.forEach(function(elem) {
                out.concat(lib.dom.byTag(tag, elem));
            });
            return out;
        },

        byQuery: function byQuery(query) {
            var out = null;
            this.forEach(function(elem) {
                if (!out) {
                    out = lib.dom.byQuery(query, elem);
                }
            });
            return out;
        },

        byQueryAll: function byQueryAll(query) {
            var out = lib.dom.NodeList();
            this.forEach(function(elem) {
                out.concat(lib.dom.byQueryAll(query, elem));
            });
            return out;
        },

        byClass: function byClass(klass, tag) {
            var out = lib.dom.NodeList();
            this.forEach(function(elem) {
                out.concat(lib.dom.byClass(klass, tag, elem));
            });
            return out;
        }
    });

    lib.dom.NodeList = NodeList;
})(lib);
<commit_msg>straight forward object construction instead of longer shorthand<commit_after>(function(lib, undefined) {
    /*global lib*/
    "use strict";

    function NodeList(elements) {
        if (this === lib.dom) {
            return new NodeList(elements);
        }

        if (!elements) {
            return;
        }

        if (lib.dom.isTypeOf(elements, lib.dom.ELEMENT_NODE | lib.dom.DOCUMENT_NODE)) {
            this.push(elements);
        } else if (elements instanceof NodeList) {
            return elements;
        } else {
            elements = lib.array.toArray(elements);
            lib.array.forEach(elements, lib.bind(function(element) {
                if (lib.dom.isTypeOf(element, lib.dom.ELEMENT_NODE | lib.dom.DOCUMENT_NODE)) {
                    this.push(element);
                }
            }, this));
        }
    }

    lib.util.inherits(NodeList, Array);

    lib.extend(NodeList.prototype, {
        toString: function toString() {
            return this.join(", ");
        },

        valueOf: function valueOf() {
            return this;
        },

        item: function item(index) {
            return this[index];
        },

        /* array extensions */
        concat: function concat() {
            var args = lib.array.toArray(arguments);
            lib.array.forEach(args, lib.bind(function(arg) {
                lib.array.forEach(arg, lib.bind(function(elem) {
                    this.push(elem);
                }, this));
            }, this));
        },

        slice: function slice() {
            return new NodeList(Array.prototype.slice.apply(this, arguments));
        },

        toArray: function toArray() {
            return lib.array.toArray(this);
        },

        indexOf: function indexOf(object, fromIndex) {
            return lib.array.indexOf(this, object, fromIndex);
        },

        lastIndexOf: function lastIndexOf(object, fromIndex) {
            return lib.array.lastIndexOf(this, object, fromIndex);
        },

        inArray: function inArray(object) {
            return lib.array.inArray(this, object);
        },

        forEach: function forEach(callback, thisObject) {
            lib.array.forEach(this, callback, thisObject);
        },

        every: function every(callback, thisObject) {
            return lib.array.every(this, callback, thisObject);
        },

        some: function some(callback, thisObject) {
            return lib.array.some(this, callback, thisObject);
        },

        filter: function filter(callback, thisObject) {
            return new NodeList(lib.array.filter(this, callback, thisObject));
        },

        map: function map(callback, thisObject) {
            return new NodeList(lib.array.map(this, callback, thisObject));
        },

        reduce: function reduce(callback, initialValue) {
            return lib.array.reduce(this, callback, initialValue);
        },

        reduceRight: function reduceRight(callback, initialValue) {
            return lib.array.reduceRight(this, callback, initialValue);
        },

        /* dom helpers */
        byTag: function byTag(tag) {
            var out = new NodeList();
            this.forEach(function(elem) {
                out.concat(lib.dom.byTag(tag, elem));
            });
            return out;
        },

        byQuery: function byQuery(query) {
            var out = null;
            this.forEach(function(elem) {
                if (!out) {
                    out = lib.dom.byQuery(query, elem);
                }
            });
            return out;
        },

        byQueryAll: function byQueryAll(query) {
            var out = new NodeList();
            this.forEach(function(elem) {
                out.concat(lib.dom.byQueryAll(query, elem));
            });
            return out;
        },

        byClass: function byClass(klass, tag) {
            var out = new NodeList();
            this.forEach(function(elem) {
                out.concat(lib.dom.byClass(klass, tag, elem));
            });
            return out;
        }
    });

    lib.dom.NodeList = NodeList;
})(lib);
<|endoftext|>


<commit_before>import React from 'react'
import Loading from '../loading'
import EditPerms from './group/edit_perms'
import EditUsers from './group/edit_users'

let Table=function(props){
  let max=3
  return (

          {props.headers.map( (h) =>(
            {h}
          ))}

          {props.data.slice(0,max).map( (u) => (

              {u}

          ) ) }

      {(props.data.length > max) ? `And ${props.data.length - max} more...`: ""}

  )
}

let Groups=React.createClass({
  componentDidMount: function(){
    if (!this.props.groups)
      this.props.loadGroups()
    if (!this.props.users)
      this.props.loadUsers()
  },
  contextTypes: {
    router: React.PropTypes.object
  },
  setModal : function( what, data ){
    let modal=what && { what, data }

    console.log("Set router state modal %o", modal)

    this.context.router.push( {
      pathname: this.props.location.pathname,
      state: { modal }
    } )
  },
  handleEditUsers : function(g){
    this.setModal('edit_users', g)
  },
  handleEditPerms : function(g){
    this.setModal('edit_perms', g)
  },
  handleUpdatePermissions : function(g, new_perms){
    let to_remove_perms=$.makeArray( $(g.perms).not(new_perms) )
    let to_add_perms=$.makeArray( $(new_perms).not(g.perms) )

    this.props.onUpdatePerms(g.name, to_add_perms, to_remove_perms)
    this.setModal(false)
  },
  handleUpdateUsers : function(g, current){
    let to_add = $.makeArray( $(current).not(g.users) )
    let to_remove = $.makeArray( $(g.users).not(current) )

    this.props.onUpdateUsers(g.name, to_add, to_remove)
    this.setModal(false)
  },
  render(){
    let modal=[]
    let router_state=this.props.location.state
    let modal_state=(router_state && router_state.modal && router_state.modal) || {}
    switch(modal_state.what){
      case 'edit_perms':
        modal=(
          <EditPerms
            group={modal_state.data}
            onClose={ () => this.setModal(false) }
            onUpdatePermissions={(perms) =>
              this.handleUpdatePermissions(modal_state.data, perms) }
          />
        )
        break;
      case 'edit_users':
        modal=(
          <EditUsers
            group={modal_state.data}
            onClose={ () => this.setModal(false) }
            onSubmit={(users) =>
              this.handleUpdateUsers(modal_state.data, users) }
            allUsers={this.props.all_users}
          />
        )
        break;
    }

    let props=this.props
    if (!props.groups){
      return (
        <Loading>
        Loading groups
        </Loading>
      )
    }

    let self=this

    function Group(g){
      return (

{g.name}

            Users
            { ev.preventDefault(); self.handleEditUsers(g) }} title="Edit users" href="#!">

            Permissions
            { ev.preventDefault(); self.handleEditPerms(g) }} title="Edit users" href="#!">

      )
    }

    return (

Groups and permissions

        {props.groups.map(Group)}

        {modal}

    )
  }
})

export default Groups
<commit_msg>Groups users and permissions in two columns.<commit_after>import React from 'react'
import Loading from '../loading'
import EditPerms from './group/edit_perms'
import EditUsers from './group/edit_users'

let Table=function(props){
  let max=3
  return (

          {props.headers.map( (h) =>(
            {h}
          ))}

          {props.data.slice(0,max).map( (u) => (

              {u}

          ) ) }

      {(props.data.length > max) ? `And ${props.data.length - max} more...`: ""}

  )
}

let Groups=React.createClass({
  componentDidMount: function(){
    if (!this.props.groups)
      this.props.loadGroups()
    if (!this.props.users)
      this.props.loadUsers()
  },
  contextTypes: {
    router: React.PropTypes.object
  },
  setModal : function( what, data ){
    let modal=what && { what, data }

    console.log("Set router state modal %o", modal)

    this.context.router.push( {
      pathname: this.props.location.pathname,
      state: { modal }
    } )
  },
  handleEditUsers : function(g){
    this.setModal('edit_users', g)
  },
  handleEditPerms : function(g){
    this.setModal('edit_perms', g)
  },
  handleUpdatePermissions : function(g, new_perms){
    let to_remove_perms=$.makeArray( $(g.perms).not(new_perms) )
    let to_add_perms=$.makeArray( $(new_perms).not(g.perms) )

    this.props.onUpdatePerms(g.name, to_add_perms, to_remove_perms)
    this.setModal(false)
  },
  handleUpdateUsers : function(g, current){
    let to_add = $.makeArray( $(current).not(g.users) )
    let to_remove = $.makeArray( $(g.users).not(current) )

    this.props.onUpdateUsers(g.name, to_add, to_remove)
    this.setModal(false)
  },
  render(){
    let modal=[]
    let router_state=this.props.location.state
    let modal_state=(router_state && router_state.modal && router_state.modal) || {}
    switch(modal_state.what){
      case 'edit_perms':
        modal=(
          <EditPerms
            group={modal_state.data}
            onClose={ () => this.setModal(false) }
            onUpdatePermissions={(perms) =>
              this.handleUpdatePermissions(modal_state.data, perms) }
          />
        )
        break;
      case 'edit_users':
        modal=(
          <EditUsers
            group={modal_state.data}
            onClose={ () => this.setModal(false) }
            onSubmit={(users) =>
              this.handleUpdateUsers(modal_state.data, users) }
            allUsers={this.props.all_users}
          />
        )
        break;
    }

    let props=this.props
    if (!props.groups){
      return (
        <Loading>
        Loading groups
        </Loading>
      )
    }

    let self=this

    function Group(g){
      return (

{g.name}

                Users
                { ev.preventDefault(); self.handleEditUsers(g) }} title="Edit users" href="#!">

                Permissions
                { ev.preventDefault(); self.handleEditPerms(g) }} title="Edit users" href="#!">

      )
    }

    return (

Groups and permissions

        {props.groups.map(Group)}

        {modal}

    )
  }
})

export default Groups
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

global.WEB = false;

const lua          = require('../../src/lua.js');
const lauxlib      = require('../../src/lauxlib.js');
const lualib       = require('../../src/lualib.js');

const readlineSync = require('readline-sync');

const stdin = lua.to_luastring("=stdin");
const _PROMPT = lua.to_luastring("_PROMPT");
const _PROMPT2 = lua.to_luastring("_PROMPT2");

const report = function(L, status) {
    if (status !== lua.LUA_OK) {
        lauxlib.lua_writestringerror(`${lua.lua_tojsstring(L, -1)}\n`);
        lua.lua_pop(L, 1);
    }
    return status;
};

const msghandler = function(L) {
    let msg = lua.lua_tostring(L, 1);
    if (msg === null) {  /* is error object not a string? */
        if (lauxlib.luaL_callmeta(L, 1, "__tostring") &&  /* does it have a metamethod */
          lua.lua_type(L, -1) == lua.LUA_TSTRING)  /* that produces a string? */
            return 1;  /* that is the message */
        else
            msg = lua.lua_pushstring(L, lua.to_luastring(`(error object is a ${lua.to_jsstring(lauxlib.luaL_typename(L, 1))} value)`));
    }
    lauxlib.luaL_traceback(L, L, msg, 1);  /* append a standard traceback */
    return 1;  /* return the traceback */
};

const docall = function(L, narg, nres) {
    let base = lua.lua_gettop(L) - narg;
    lua.lua_pushcfunction(L, msghandler);
    lua.lua_insert(L, base);
    let status = lua.lua_pcall(L, narg, nres, base);
    lua.lua_remove(L, base);
    return status;
};

const dochunk = function(L, status) {
    if (status === lua.LUA_OK) {
        status = docall(L, 0, 0);
    }
    return report(L, status);
};

const dofile = function(L, name) {
    return dochunk(L, lauxlib.luaL_loadfile(L, lua.to_luastring(name)));
};

const dostring = function(L, s, name) {
    let buffer = lua.to_luastring(s);
    return dochunk(L, lauxlib.luaL_loadbuffer(L, buffer, buffer.length, lua.to_luastring(name)));
};

const dolibrary = function(L, name) {
    lua.lua_getglobal(L, lua.to_luastring("require"));
    lua.lua_pushliteral(L, name);
    let status = docall(L, 1, 1);  /* call 'require(name)' */
    if (status === lua.LUA_OK)
        lua.lua_setglobal(L, lua.to_luastring(name));  /* global[name] = require return */
    return report(L, status);
};

let progname = process.argv[1];

const print_usage = function(badoption) {
    lauxlib.lua_writestringerror(`${progname}: `);
    if (badoption[1] === "e" || badoption[1] === "l")
        lauxlib.lua_writestringerror(`'${badoption}' needs argument\n`);
    else
        lauxlib.lua_writestringerror(`'unrecognized option '${badoption}'\n`);
    lauxlib.lua_writestringerror(
        `usage: ${progname} [options] [script [args]]\n` +
        "Available options are:\n" +
        "  -e stat  execute string 'stat'\n" +
        "  -i       enter interactive mode after executing 'script'\n" +
        "  -l name  require library 'name'\n" +
        "  -v       show version information\n" +
        "  -E       ignore environment variables\n" +
        "  --       stop handling options\n" +
        "  -        stop handling options and execute stdin\n"
    );
};

const L = lauxlib.luaL_newstate();

let script = 2; // Where to start args from
let has_E = false;
let has_i = false;
let has_v = false;
let has_e = false;

(function() {
    let i;
    for (i = 2; i<process.argv.length; i++) {
        script = i;
        if (process.argv[i][0] != "-") {
            return;
        }
        switch(process.argv[i][1]) {
        case '-':
            if (process.argv[i][2]) {
                print_usage(process.argv[script]);
                return process.exit(1);
            }
            script = i + 1;
            return;
        case void 0: /* script name is '-' */
            return;
        case 'E':
            has_E = true;
            break;
        case 'i':
            has_i = true;
            /* (-i implies -v) */
            /* falls through */
        case 'v':
            if (process.argv[i].length > 2) {
                /* invalid option */
                print_usage(process.argv[script]);
                return process.exit(1);
            }
            has_v = true;
            break;
        case 'e':
            has_e = true;
            /* falls through */
        case 'l':  /* both options need an argument */
            if (process.argv[i].length < 3) {  /* no concatenated argument? */
                i++;  /* try next 'process.argv' */
                if (process.argv.length <= i || process.argv[i][0] === '-') {
                    /* no next argument or it is another option */
                    print_usage(process.argv[script]);
                    return process.exit(1);
                }
            }
            break;
        default:  /* invalid option */
            print_usage(process.argv[script]);
            return process.exit(1);
        }
    }
    script = i;
})();

if (has_v)
    console.log(lua.FENGARI_COPYRIGHT);

if (has_E) {
    /* signal for libraries to ignore env. vars. */
    lua.lua_pushboolean(L, 1);
    lua.lua_setfield(L, lua.LUA_REGISTRYINDEX, lua.to_luastring("LUA_NOENV"));
}

/* open standard libraries */
lualib.luaL_openlibs(L);

/* create table 'arg' */
lua.lua_createtable(L, process.argv.length - (script + 1), script + 1);
for (let i = 0; i < process.argv.length; i++) {
    lua.lua_pushliteral(L, process.argv[i]);
    lua.lua_seti(L, -2, i - script); /* TODO: rawseti */
}
lua.lua_setglobal(L, lua.to_luastring("arg"));

if (!has_E) {
    /* run LUA_INIT */
    let name = "LUA_INIT"+lua.LUA_VERSUFFIX;
    let init = process.env[name];
    if (!init) {
        name = "LUA_INIT";
        init = process.env[name];
    }
    if (init) {
        let status;
        if (init[0] === '@') {
            status = dofile(L, init.substring(1));
        } else {
            status = dostring(L, init, name);
        }
        if (status !== lua.LUA_OK) {
            return process.exit(1);
        }
    }
}

/* execute arguments -e and -l */
for (let i = 1; i < script; i++) {
    let option = process.argv[i][1];
    if (option == 'e' || option == 'l') {
        let extra = process.argv[i].substring(2); /* both options need an argument */
        if (extra.length === 0)
            extra = process.argv[++i];
        let status;
        if (option == 'e') {
            status = dostring(L, extra, "=(command line)");
        } else {
            status = dolibrary(L, extra);
        }
        if (status !== lua.LUA_OK) {
            return process.exit(1);
        }
    }
}

const pushargs = function(L) {
    if (lua.lua_getglobal(L, lua.to_luastring("arg")) !== lua.LUA_TTABLE)
        lauxlib.luaL_error(L, lua.to_luastring("'arg' is not a table"));
    let n = lauxlib.luaL_len(L, -1);
    lauxlib.luaL_checkstack(L, n+3, lua.to_luastring("too many arguments to script"));
    let i;
    for (i=1; i<=n; i++)
        lua.lua_rawgeti(L, -i, i);
    lua.lua_remove(L, -i);
    return n;
};

const handle_script = function(L, argv) {
    let fname = argv[0];
    let status;
    if (fname === "-" && argv[-1] !== "--")
        fname = null;  /* stdin */
    else
        fname = lua.to_luastring(fname);
    status = lauxlib.luaL_loadfile(L, fname);
    if (status === lua.LUA_OK) {
        let n = pushargs(L); /* push arguments to script */
        status = docall(L, n, lua.LUA_MULTRET);
    }
    return report(L, status);
};

const doREPL = function(L) {
    for (;;) {
        lua.lua_getglobal(L, _PROMPT);
        let input = readlineSync.prompt({
            prompt: lua.lua_tojsstring(L, -1) || '> '
        });
        lua.lua_pop(L, 1);

        if (input.length === 0)
            continue;

        let status;
        {
            let buffer = lua.to_luastring("return " + input);
            status = lauxlib.luaL_loadbuffer(L, buffer, buffer.length, stdin);
        }
        if (status !== lua.LUA_OK) {
            lua.lua_pop(L, 1);
            let buffer = lua.to_luastring(input);
            if (lauxlib.luaL_loadbuffer(L, buffer, buffer.length, stdin) === lua.LUA_OK) {
                status = lua.LUA_OK;
            }
        }
        while (status === lua.LUA_ERRSYNTAX && lua.lua_tojsstring(L, -1).endsWith("<eof>")) {
            /* continuation */
            lua.lua_pop(L, 1);
            lua.lua_getglobal(L, _PROMPT2);
            input += "\n" + readlineSync.prompt({
                prompt: lua.lua_tojsstring(L, -1) || '>> '
            });
            lua.lua_pop(L, 1);
            let buffer = lua.to_luastring(input);
            status = lauxlib.luaL_loadbuffer(L, buffer, buffer.length, stdin);
        }
        if (status === lua.LUA_OK) {
            status = docall(L, 0, lua.LUA_MULTRET);
        }
        if (status === lua.LUA_OK) {
            let n = lua.lua_gettop(L);
            if (n > 0) {  /* any result to be printed? */
                lua.lua_getglobal(L, lua.to_luastring("print"));
                lua.lua_insert(L, 1);
                if (lua.lua_pcall(L, n, 0, 0) != lua.LUA_OK) {
                    lauxlib.lua_writestringerror(`error calling 'print' (${lua.lua_tojsstring(L, -1)})\n`);
                }
            }
        } else {
            report(L, status);
        }
        lua.lua_settop(L, 0);  /* remove eventual returns */
    }
};

if (script < process.argv.length &&  /* execute main script (if there is one) */
    handle_script(L, process.argv.slice(script)) !== lua.LUA_OK) {
    /* success */
} else if (has_i) {
    doREPL(L);
} else if (script == process.argv.length && !has_e && !has_v) {  /* no arguments? */
    if (process.stdin.isTTY) {  /* running in interactive mode? */
        console.log(lua.FENGARI_COPYRIGHT);
        doREPL(L);  /* do read-eval-print loop */
    } else {
        dofile(L, null);
    }
}
<commit_msg>tests/manual-tests/lua-cli.js: Add missing lua.to_luastring call in msghandler<commit_after>#!/usr/bin/env node
"use strict";

global.WEB = false;

const lua          = require('../../src/lua.js');
const lauxlib      = require('../../src/lauxlib.js');
const lualib       = require('../../src/lualib.js');

const readlineSync = require('readline-sync');

const stdin = lua.to_luastring("=stdin");
const _PROMPT = lua.to_luastring("_PROMPT");
const _PROMPT2 = lua.to_luastring("_PROMPT2");

const report = function(L, status) {
    if (status !== lua.LUA_OK) {
        lauxlib.lua_writestringerror(`${lua.lua_tojsstring(L, -1)}\n`);
        lua.lua_pop(L, 1);
    }
    return status;
};

const msghandler = function(L) {
    let msg = lua.lua_tostring(L, 1);
    if (msg === null) {  /* is error object not a string? */
        if (lauxlib.luaL_callmeta(L, 1, lua.to_luastring("__tostring")) &&  /* does it have a metamethod */
          lua.lua_type(L, -1) == lua.LUA_TSTRING)  /* that produces a string? */
            return 1;  /* that is the message */
        else
            msg = lua.lua_pushstring(L, lua.to_luastring(`(error object is a ${lua.to_jsstring(lauxlib.luaL_typename(L, 1))} value)`));
    }
    lauxlib.luaL_traceback(L, L, msg, 1);  /* append a standard traceback */
    return 1;  /* return the traceback */
};

const docall = function(L, narg, nres) {
    let base = lua.lua_gettop(L) - narg;
    lua.lua_pushcfunction(L, msghandler);
    lua.lua_insert(L, base);
    let status = lua.lua_pcall(L, narg, nres, base);
    lua.lua_remove(L, base);
    return status;
};

const dochunk = function(L, status) {
    if (status === lua.LUA_OK) {
        status = docall(L, 0, 0);
    }
    return report(L, status);
};

const dofile = function(L, name) {
    return dochunk(L, lauxlib.luaL_loadfile(L, lua.to_luastring(name)));
};

const dostring = function(L, s, name) {
    let buffer = lua.to_luastring(s);
    return dochunk(L, lauxlib.luaL_loadbuffer(L, buffer, buffer.length, lua.to_luastring(name)));
};

const dolibrary = function(L, name) {
    lua.lua_getglobal(L, lua.to_luastring("require"));
    lua.lua_pushliteral(L, name);
    let status = docall(L, 1, 1);  /* call 'require(name)' */
    if (status === lua.LUA_OK)
        lua.lua_setglobal(L, lua.to_luastring(name));  /* global[name] = require return */
    return report(L, status);
};

let progname = process.argv[1];

const print_usage = function(badoption) {
    lauxlib.lua_writestringerror(`${progname}: `);
    if (badoption[1] === "e" || badoption[1] === "l")
        lauxlib.lua_writestringerror(`'${badoption}' needs argument\n`);
    else
        lauxlib.lua_writestringerror(`'unrecognized option '${badoption}'\n`);
    lauxlib.lua_writestringerror(
        `usage: ${progname} [options] [script [args]]\n` +
        "Available options are:\n" +
        "  -e stat  execute string 'stat'\n" +
        "  -i       enter interactive mode after executing 'script'\n" +
        "  -l name  require library 'name'\n" +
        "  -v       show version information\n" +
        "  -E       ignore environment variables\n" +
        "  --       stop handling options\n" +
        "  -        stop handling options and execute stdin\n"
    );
};

const L = lauxlib.luaL_newstate();

let script = 2; // Where to start args from
let has_E = false;
let has_i = false;
let has_v = false;
let has_e = false;

(function() {
    let i;
    for (i = 2; i<process.argv.length; i++) {
        script = i;
        if (process.argv[i][0] != "-") {
            return;
        }
        switch(process.argv[i][1]) {
        case '-':
            if (process.argv[i][2]) {
                print_usage(process.argv[script]);
                return process.exit(1);
            }
            script = i + 1;
            return;
        case void 0: /* script name is '-' */
            return;
        case 'E':
            has_E = true;
            break;
        case 'i':
            has_i = true;
            /* (-i implies -v) */
            /* falls through */
        case 'v':
            if (process.argv[i].length > 2) {
                /* invalid option */
                print_usage(process.argv[script]);
                return process.exit(1);
            }
            has_v = true;
            break;
        case 'e':
            has_e = true;
            /* falls through */
        case 'l':  /* both options need an argument */
            if (process.argv[i].length < 3) {  /* no concatenated argument? */
                i++;  /* try next 'process.argv' */
                if (process.argv.length <= i || process.argv[i][0] === '-') {
                    /* no next argument or it is another option */
                    print_usage(process.argv[script]);
                    return process.exit(1);
                }
            }
            break;
        default:  /* invalid option */
            print_usage(process.argv[script]);
            return process.exit(1);
        }
    }
    script = i;
})();

if (has_v)
    console.log(lua.FENGARI_COPYRIGHT);

if (has_E) {
    /* signal for libraries to ignore env. vars. */
    lua.lua_pushboolean(L, 1);
    lua.lua_setfield(L, lua.LUA_REGISTRYINDEX, lua.to_luastring("LUA_NOENV"));
}

/* open standard libraries */
lualib.luaL_openlibs(L);

/* create table 'arg' */
lua.lua_createtable(L, process.argv.length - (script + 1), script + 1);
for (let i = 0; i < process.argv.length; i++) {
    lua.lua_pushliteral(L, process.argv[i]);
    lua.lua_seti(L, -2, i - script); /* TODO: rawseti */
}
lua.lua_setglobal(L, lua.to_luastring("arg"));

if (!has_E) {
    /* run LUA_INIT */
    let name = "LUA_INIT"+lua.LUA_VERSUFFIX;
    let init = process.env[name];
    if (!init) {
        name = "LUA_INIT";
        init = process.env[name];
    }
    if (init) {
        let status;
        if (init[0] === '@') {
            status = dofile(L, init.substring(1));
        } else {
            status = dostring(L, init, name);
        }
        if (status !== lua.LUA_OK) {
            return process.exit(1);
        }
    }
}

/* execute arguments -e and -l */
for (let i = 1; i < script; i++) {
    let option = process.argv[i][1];
    if (option == 'e' || option == 'l') {
        let extra = process.argv[i].substring(2); /* both options need an argument */
        if (extra.length === 0)
            extra = process.argv[++i];
        let status;
        if (option == 'e') {
            status = dostring(L, extra, "=(command line)");
        } else {
            status = dolibrary(L, extra);
        }
        if (status !== lua.LUA_OK) {
            return process.exit(1);
        }
    }
}

const pushargs = function(L) {
    if (lua.lua_getglobal(L, lua.to_luastring("arg")) !== lua.LUA_TTABLE)
        lauxlib.luaL_error(L, lua.to_luastring("'arg' is not a table"));
    let n = lauxlib.luaL_len(L, -1);
    lauxlib.luaL_checkstack(L, n+3, lua.to_luastring("too many arguments to script"));
    let i;
    for (i=1; i<=n; i++)
        lua.lua_rawgeti(L, -i, i);
    lua.lua_remove(L, -i);
    return n;
};

const handle_script = function(L, argv) {
    let fname = argv[0];
    let status;
    if (fname === "-" && argv[-1] !== "--")
        fname = null;  /* stdin */
    else
        fname = lua.to_luastring(fname);
    status = lauxlib.luaL_loadfile(L, fname);
    if (status === lua.LUA_OK) {
        let n = pushargs(L); /* push arguments to script */
        status = docall(L, n, lua.LUA_MULTRET);
    }
    return report(L, status);
};

const doREPL = function(L) {
    for (;;) {
        lua.lua_getglobal(L, _PROMPT);
        let input = readlineSync.prompt({
            prompt: lua.lua_tojsstring(L, -1) || '> '
        });
        lua.lua_pop(L, 1);

        if (input.length === 0)
            continue;

        let status;
        {
            let buffer = lua.to_luastring("return " + input);
            status = lauxlib.luaL_loadbuffer(L, buffer, buffer.length, stdin);
        }
        if (status !== lua.LUA_OK) {
            lua.lua_pop(L, 1);
            let buffer = lua.to_luastring(input);
            if (lauxlib.luaL_loadbuffer(L, buffer, buffer.length, stdin) === lua.LUA_OK) {
                status = lua.LUA_OK;
            }
        }
        while (status === lua.LUA_ERRSYNTAX && lua.lua_tojsstring(L, -1).endsWith("<eof>")) {
            /* continuation */
            lua.lua_pop(L, 1);
            lua.lua_getglobal(L, _PROMPT2);
            input += "\n" + readlineSync.prompt({
                prompt: lua.lua_tojsstring(L, -1) || '>> '
            });
            lua.lua_pop(L, 1);
            let buffer = lua.to_luastring(input);
            status = lauxlib.luaL_loadbuffer(L, buffer, buffer.length, stdin);
        }
        if (status === lua.LUA_OK) {
            status = docall(L, 0, lua.LUA_MULTRET);
        }
        if (status === lua.LUA_OK) {
            let n = lua.lua_gettop(L);
            if (n > 0) {  /* any result to be printed? */
                lua.lua_getglobal(L, lua.to_luastring("print"));
                lua.lua_insert(L, 1);
                if (lua.lua_pcall(L, n, 0, 0) != lua.LUA_OK) {
                    lauxlib.lua_writestringerror(`error calling 'print' (${lua.lua_tojsstring(L, -1)})\n`);
                }
            }
        } else {
            report(L, status);
        }
        lua.lua_settop(L, 0);  /* remove eventual returns */
    }
};

if (script < process.argv.length &&  /* execute main script (if there is one) */
    handle_script(L, process.argv.slice(script)) !== lua.LUA_OK) {
    /* success */
} else if (has_i) {
    doREPL(L);
} else if (script == process.argv.length && !has_e && !has_v) {  /* no arguments? */
    if (process.stdin.isTTY) {  /* running in interactive mode? */
        console.log(lua.FENGARI_COPYRIGHT);
        doREPL(L);  /* do read-eval-print loop */
    } else {
        dofile(L, null);
    }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node --use_strict

function isPrime(num) {
  let num_sqr = Math.sqrt(num)

  if(num_sqr % 1 == 0) return false

  for(let i=2; i<num_sqr; i++)
    if(num % i == 0) return false

  return true
}

var primes = []
let i = 2;

while(primes.length < parseInt(process.argv[2])) {
  if(isPrime(i)) primes.push(i)
  i++
}

console.log(primes)
<commit_msg>formatting<commit_after>#!/usr/bin/env node --use_strict

function isPrime(num) {
  let num_sqr = Math.sqrt(num)

  if(num_sqr % 1 == 0) return false

  for(let i=2; i<num_sqr; i++)
    if(num % i == 0) return false

  return true
}

var primes = []
let i = 2

while(primes.length < parseInt(process.argv[2])) {
  if(isPrime(i)) primes.push(i)
  i++
}

console.log(primes)
<|endoftext|>


<commit_before>var common = {};

common.INPUT_TYPES = new Set(["INPUT", "TEXTAREA"]);

common._request =
function _request(method, url, callback)
{
    let request = new XMLHttpRequest();
    let response = {
        "completed": false,
    };

    request.onreadystatechange = function()
    {
        if (request.readyState != 4)
            {return;}

        if (callback == null)
            {return;}

        if (request.status != 0)
        {
            response.completed = true;
            response.data = JSON.parse(request.responseText);
        }
        response.meta = {
            "request_url": url,
            "status": request.status
        }
        callback(response);
    };
    let asynchronous = true;
    request.open(method, url, asynchronous);
    return request;
}

common.get =
function get(url, callback)
{
    request = common._request("GET", url, callback);
    request.send();
}

common.post =
function post(url, data, callback)
{
    request = common._request("POST", url, callback);
    request.send(data);
}

common.bind_box_to_button =
function bind_box_to_button(box, button, ctrl_enter)
{
    /*
    Bind a textbox to a button so that pressing Enter within the textbox is the
    same as clicking the button.

    If `ctrl_enter` is true, then you must press ctrl+Enter to trigger the
    button, which is important for textareas.

    Thanks Yaroslav Yakovlev
    http://stackoverflow.com/a/9343095
    */
    let bound_box_hook = function(event)
    {
        if (event.key !== "Enter")
            {return;}

        ctrl_success = !ctrl_enter || (event.ctrlKey);

        if (! ctrl_success)
            {return;}

        button.click();
    }
    box.addEventListener("keyup", bound_box_hook);
}

common.create_message_bubble =
function create_message_bubble(message_area, message_positivity, message_text, lifespan)
{
    if (lifespan === undefined)
    {
        lifespan = 8000;
    }
    let message = document.createElement("div");
    message.className = "message_bubble " + message_positivity;
    let span = document.createElement("span");
    span.innerHTML = message_text;
    message.appendChild(span);
    message_area.appendChild(message);
    setTimeout(function(){message_area.removeChild(message);}, lifespan);
}

common.delete_all_children =
function delete_all_children(element)
{
    while (element.firstChild)
    {
        element.removeChild(element.firstChild);
    }
}

common.entry_with_history_hook =
function entry_with_history_hook(event)
{
    const box = event.target;

    if (box.entry_history === undefined)
        {box.entry_history = [];}

    if (box.entry_history_pos === undefined)
        {box.entry_history_pos = null;}

    if (event.key === "Enter")
    {
        if (box.value === "")
            {return;}
        box.entry_history.push(box.value);
        box.entry_history_pos = null;
    }
    else if (event.key === "Escape")
    {
        box.entry_history_pos = null;
        box.value = "";
    }

    if (box.entry_history.length == 0)
        {return}

    if (box.entry_history_pos !== null && box.value !== box.entry_history[box.entry_history_pos])
        {return;}

    if (event.key === "ArrowUp")
    {
        if (box.entry_history_pos === null)
            {box.entry_history_pos = box.entry_history.length - 1;}
        else if (box.entry_history_pos == 0)
            {;}
        else
            {box.entry_history_pos -= 1;}

        if (box.entry_history_pos === null)
            {box.value = "";}
        else
            {box.value = box.entry_history[box.entry_history_pos];}

        setTimeout(function(){box.selectionStart = box.value.length;}, 0);
    }
    else if (event.key === "ArrowDown")
    {
        if (box.entry_history_pos === null)
            {;}
        else if (box.entry_history_pos == box.entry_history.length-1)
            {box.entry_history_pos = null;}
        else
            {box.entry_history_pos += 1;}

        if (box.entry_history_pos === null)
            {box.value = "";}
        else
            {box.value = box.entry_history[box.entry_history_pos];}

        setTimeout(function(){box.selectionStart = box.value.length;}, 0);
    }
}

common.html_to_element =
function html_to_element(html)
{
    let template = document.createElement("template");
    template.innerHTML = html.trim();
    return template.content.firstElementChild;
}

common.init_atag_merge_params =
function init_atag_merge_params(a)
{
    /*
    To create an <a> tag where the ?parameters written on the href are merged
    with the parameters of the current page URL, give it the class
    "merge_params". If the URL and href contain the same parameter, the href
    takes priority.

    Optional:
        data-merge-params: A whitelist of parameter names, separated by commas
            or spaces. Only these parameters will be merged from the page URL.

        data-merge-params-except: A blacklist of parameter names, separated by
            commas or spaces. All parameters except these will be merged from
            the page URL.

    Example:
        URL: ?filter=hello&orderby=score
        href: "?orderby=date"
        Result: "?filter=hello&orderby=date"
    */
    const page_params = Array.from(new URLSearchParams(window.location.search));
    let to_merge;

    if (a.dataset.mergeParams)
    {
        let keep = new Set(a.dataset.mergeParams.split(/[\s,]+/));
        to_merge = page_params.filter(key_value => keep.has(key_value[0]));
        delete a.dataset.mergeParams;
    }
    else if (a.dataset.mergeParamsExcept)
    {
        let remove = new Set(a.dataset.mergeParamsExcept.split(/[\s,]+/));
        to_merge = page_params.filter(key_value => (! remove.has(key_value[0])));
        delete a.dataset.mergeParamsExcept;
    }
    else
    {
        to_merge = page_params;
    }

    to_merge = to_merge.concat(Array.from(new URLSearchParams(a.search)));
    const new_params = new URLSearchParams();
    for (const [key, value] of to_merge)
        { new_params.set(key, value); }
    a.search = new_params.toString();
    a.classList.remove("merge_params");
}

common.init_all_atag_merge_params =
function init_all_atag_merge_params()
{
    const page_params = Array.from(new URLSearchParams(window.location.search));
    let as = Array.from(document.getElementsByClassName("merge_params"));
    for (const a of as)
    {
        common.init_atag_merge_params(a);
    }
}

common.init_button_with_confirm =
function init_button_with_confirm(button)
{
    /*
    To create a button that requires a second confirmation step, assign it the
    class "button_with_confirm".

    Required:
        data-onclick: String that would normally be the button's onclick.
            This is done so that if the button_with_confirm fails to initialize,
            the button will be non-operational as opposed to being operational
            but with no confirmation. For dangerous actions I think this is a
            worthwhile move though it could lead to feature downtime.

    Optional:
        data-prompt: Text that appears next to the confirm button. Default is
            "Are you sure?".

        data-prompt-class: CSS class for the prompt span.

        data-confirm: Text inside the confirm button. Default is to inherit the
            original button's text.

        data-confirm-class: CSS class for the confirm button. Default is to
            inheret all classes of the original button, except for
            "button_with_confirm" of course.

        data-cancel: Text inside the cancel button. Default is "Cancel".

        data-cancel-class: CSS class for the cancel button.

        data-holder-class: CSS class for the new span that holds the menu.
    */
    button.classList.remove("button_with_confirm");

    let holder = document.createElement("span");
    holder.className = button.dataset.holderClass || "";
    holder.classList.add("confirm_holder");
    button.parentElement.insertBefore(holder, button);
    button.parentElement.removeChild(button);

    let holder_stage1 = document.createElement("span");
    holder_stage1.classList.add("confirm_holder_stage1");
    holder_stage1.appendChild(button);
    holder.appendChild(holder_stage1);

    let holder_stage2 = document.createElement("span");
    holder_stage2.classList.add("confirm_holder_stage2");
    holder_stage2.classList.add("hidden");
    holder.appendChild(holder_stage2);

    let prompt;
    let input_source;
    if (button.dataset.isInput)
    {
        prompt = document.createElement("input");
        prompt.placeholder = button.dataset.prompt || "";
        input_source = prompt;
    }
    else
    {
        prompt = document.createElement("span");
        prompt.innerText = (button.dataset.prompt || "Are you sure?") + " ";
        input_source = undefined;
    }
    prompt.className = button.dataset.promptClass || "";
    holder_stage2.appendChild(prompt)
    delete button.dataset.prompt;
    delete button.dataset.promptClass;

    let button_confirm = document.createElement("button");
    button_confirm.innerText = (button.dataset.confirm || button.innerText).trim();
    if (button.dataset.confirmClass === undefined)
    {
        button_confirm.className = button.className;
        button_confirm.classList.remove("button_with_confirm");
    }
    else
    {
        button_confirm.className = button.dataset.confirmClass;
    }
    button_confirm.input_source = input_source;
    holder_stage2.appendChild(button_confirm);
    holder_stage2.appendChild(document.createTextNode(" "));
    if (button.dataset.isInput)
    {
        common.bind_box_to_button(prompt, button_confirm);
    }
    delete button.dataset.confirm;
    delete button.dataset.confirmClass;
    delete button.dataset.isInput;

    let button_cancel = document.createElement("button");
    button_cancel.innerText = button.dataset.cancel || "Cancel";
    button_cancel.className = button.dataset.cancelClass || "";
    holder_stage2.appendChild(button_cancel);
    delete button.dataset.cancel;
    delete button.dataset.cancelClass;

    // If this is stupid, let me know.
    let confirm_onclick = `
        let holder = event.target.parentElement.parentElement;
        holder.getElementsByClassName("confirm_holder_stage1")[0].classList.remove("hidden");
        holder.getElementsByClassName("confirm_holder_stage2")[0].classList.add("hidden");
    ` + button.dataset.onclick;
    button_confirm.onclick = Function(confirm_onclick);
    button.removeAttribute("onclick");
    button.onclick = function(event)
    {
        let holder = event.target.parentElement.parentElement;
        holder.getElementsByClassName("confirm_holder_stage1")[0].classList.add("hidden");
        holder.getElementsByClassName("confirm_holder_stage2")[0].classList.remove("hidden");
        let input = holder.getElementsByTagName("input")[0];
        if (input)
        {
            input.focus();
        }
    }

    button_cancel.onclick = function(event)
    {
        let holder = event.target.parentElement.parentElement;
        holder.getElementsByClassName("confirm_holder_stage1")[0].classList.remove("hidden");
        holder.getElementsByClassName("confirm_holder_stage2")[0].classList.add("hidden");
    }
    delete button.dataset.onclick;
}

common.init_all_button_with_confirm =
function init_all_button_with_confirm()
{
    let buttons = Array.from(document.getElementsByClassName("button_with_confirm"));
    for (const button of buttons)
    {
        common.init_button_with_confirm(button);
    }
}

common.init_enable_on_pageload =
function init_enable_on_pageload(element)
{
    /*
    To create an input element which is disabled at first, and is enabled when
    the DOM has completed loading, give it the disabled attribute and the
    class "enable_on_pageload".
    */
    element.disabled = false;
    element.classList.remove("enable_on_pageload");
}

common.init_all_enable_on_pageload =
function init_all_enable_on_pageload()
{
    let elements = Array.from(document.getElementsByClassName("enable_on_pageload"));
    for (const element of elements)
    {
        common.init_enable_on_pageload(element);
    }
}

common.init_entry_with_history =
function init_entry_with_history(input)
{
    input.addEventListener("keydown", common.entry_with_history_hook);
    input.classList.remove("entry_with_history");
}

common.init_all_entry_with_history =
function init_all_entry_with_history()
{
    const inputs = Array.from(document.getElementsByClassName("entry_with_history"));
    for (const input of inputs)
    {
        common.init_entry_with_history(input);
    }
}

common.init_tabbed_container =
function init_tabbed_container(tabbed_container)
{
    let button_container = document.createElement("div");
    button_container.className = "tab_buttons";
    tabbed_container.prepend(button_container);
    let tabs = Array.from(tabbed_container.getElementsByClassName("tab"));
    for (const tab of tabs)
    {
        tab.classList.add("hidden");
        let tab_id = tab.dataset.tabId || tab.dataset.tabTitle;
        tab.dataset.tabId = tab_id;
        tab.style.borderTopColor = "transparent";

        let button = document.createElement("button");
        button.className = "tab_button tab_button_inactive";
        button.onclick = common.tabbed_container_switcher;
        button.innerText = tab.dataset.tabTitle;
        button.dataset.tabId = tab_id;
        button_container.append(button);
    }
    tabs[0].classList.remove("hidden");
    button_container.firstElementChild.classList.remove("tab_button_inactive");
    button_container.firstElementChild.classList.add("tab_button_active");
}

common.init_all_tabbed_container =
function init_all_tabbed_container()
{
    let tabbed_containers = Array.from(document.getElementsByClassName("tabbed_container"));
    for (const tabbed_container of tabbed_containers)
    {
        common.init_tabbed_container(tabbed_container);
    }
}

common.tabbed_container_switcher =
function tabbed_container_switcher(event)
{
    let tab_button = event.target;
    if (tab_button.classList.contains("tab_button_active"))
        { return; }

    let tab_id = tab_button.dataset.tabId;
    let tab_buttons = tab_button.parentElement.getElementsByClassName("tab_button");
    let tabs = tab_button.parentElement.parentElement.getElementsByClassName("tab");
    for (const tab_button of tab_buttons)
    {
        if (tab_button.dataset.tabId === tab_id)
        {
            tab_button.classList.remove("tab_button_inactive");
            tab_button.classList.add("tab_button_active");
        }
        else
        {
            tab_button.classList.remove("tab_button_active");
            tab_button.classList.add("tab_button_inactive");
        }
    }
    for (const tab of tabs)
    {
        if (tab.dataset.tabId === tab_id)
            { tab.classList.remove("hidden"); }
        else
            { tab.classList.add("hidden"); }
    }
}

common.refresh =
function refresh()
{
    window.location.reload();
}

common.on_pageload =
function on_pageload()
{
    common.init_all_atag_merge_params();
    common.init_all_button_with_confirm();
    common.init_all_enable_on_pageload();
    common.init_all_entry_with_history();
    common.init_all_tabbed_container();
}
document.addEventListener("DOMContentLoaded", common.on_pageload);
<commit_msg>Use className instead of classList for initialization.<commit_after>var common = {};

common.INPUT_TYPES = new Set(["INPUT", "TEXTAREA"]);

common._request =
function _request(method, url, callback)
{
    let request = new XMLHttpRequest();
    let response = {
        "completed": false,
    };

    request.onreadystatechange = function()
    {
        if (request.readyState != 4)
            {return;}

        if (callback == null)
            {return;}

        if (request.status != 0)
        {
            response.completed = true;
            response.data = JSON.parse(request.responseText);
        }
        response.meta = {
            "request_url": url,
            "status": request.status
        }
        callback(response);
    };
    let asynchronous = true;
    request.open(method, url, asynchronous);
    return request;
}

common.get =
function get(url, callback)
{
    request = common._request("GET", url, callback);
    request.send();
}

common.post =
function post(url, data, callback)
{
    request = common._request("POST", url, callback);
    request.send(data);
}

common.bind_box_to_button =
function bind_box_to_button(box, button, ctrl_enter)
{
    /*
    Bind a textbox to a button so that pressing Enter within the textbox is the
    same as clicking the button.

    If `ctrl_enter` is true, then you must press ctrl+Enter to trigger the
    button, which is important for textareas.

    Thanks Yaroslav Yakovlev
    http://stackoverflow.com/a/9343095
    */
    let bound_box_hook = function(event)
    {
        if (event.key !== "Enter")
            {return;}

        ctrl_success = !ctrl_enter || (event.ctrlKey);

        if (! ctrl_success)
            {return;}

        button.click();
    }
    box.addEventListener("keyup", bound_box_hook);
}

common.create_message_bubble =
function create_message_bubble(message_area, message_positivity, message_text, lifespan)
{
    if (lifespan === undefined)
    {
        lifespan = 8000;
    }
    let message = document.createElement("div");
    message.className = "message_bubble " + message_positivity;
    let span = document.createElement("span");
    span.innerHTML = message_text;
    message.appendChild(span);
    message_area.appendChild(message);
    setTimeout(function(){message_area.removeChild(message);}, lifespan);
}

common.delete_all_children =
function delete_all_children(element)
{
    while (element.firstChild)
    {
        element.removeChild(element.firstChild);
    }
}

common.entry_with_history_hook =
function entry_with_history_hook(event)
{
    const box = event.target;

    if (box.entry_history === undefined)
        {box.entry_history = [];}

    if (box.entry_history_pos === undefined)
        {box.entry_history_pos = null;}

    if (event.key === "Enter")
    {
        if (box.value === "")
            {return;}
        box.entry_history.push(box.value);
        box.entry_history_pos = null;
    }
    else if (event.key === "Escape")
    {
        box.entry_history_pos = null;
        box.value = "";
    }

    if (box.entry_history.length == 0)
        {return}

    if (box.entry_history_pos !== null && box.value !== box.entry_history[box.entry_history_pos])
        {return;}

    if (event.key === "ArrowUp")
    {
        if (box.entry_history_pos === null)
            {box.entry_history_pos = box.entry_history.length - 1;}
        else if (box.entry_history_pos == 0)
            {;}
        else
            {box.entry_history_pos -= 1;}

        if (box.entry_history_pos === null)
            {box.value = "";}
        else
            {box.value = box.entry_history[box.entry_history_pos];}

        setTimeout(function(){box.selectionStart = box.value.length;}, 0);
    }
    else if (event.key === "ArrowDown")
    {
        if (box.entry_history_pos === null)
            {;}
        else if (box.entry_history_pos == box.entry_history.length-1)
            {box.entry_history_pos = null;}
        else
            {box.entry_history_pos += 1;}

        if (box.entry_history_pos === null)
            {box.value = "";}
        else
            {box.value = box.entry_history[box.entry_history_pos];}

        setTimeout(function(){box.selectionStart = box.value.length;}, 0);
    }
}

common.html_to_element =
function html_to_element(html)
{
    let template = document.createElement("template");
    template.innerHTML = html.trim();
    return template.content.firstElementChild;
}

common.init_atag_merge_params =
function init_atag_merge_params(a)
{
    /*
    To create an <a> tag where the ?parameters written on the href are merged
    with the parameters of the current page URL, give it the class
    "merge_params". If the URL and href contain the same parameter, the href
    takes priority.

    Optional:
        data-merge-params: A whitelist of parameter names, separated by commas
            or spaces. Only these parameters will be merged from the page URL.

        data-merge-params-except: A blacklist of parameter names, separated by
            commas or spaces. All parameters except these will be merged from
            the page URL.

    Example:
        URL: ?filter=hello&orderby=score
        href: "?orderby=date"
        Result: "?filter=hello&orderby=date"
    */
    const page_params = Array.from(new URLSearchParams(window.location.search));
    let to_merge;

    if (a.dataset.mergeParams)
    {
        let keep = new Set(a.dataset.mergeParams.split(/[\s,]+/));
        to_merge = page_params.filter(key_value => keep.has(key_value[0]));
        delete a.dataset.mergeParams;
    }
    else if (a.dataset.mergeParamsExcept)
    {
        let remove = new Set(a.dataset.mergeParamsExcept.split(/[\s,]+/));
        to_merge = page_params.filter(key_value => (! remove.has(key_value[0])));
        delete a.dataset.mergeParamsExcept;
    }
    else
    {
        to_merge = page_params;
    }

    to_merge = to_merge.concat(Array.from(new URLSearchParams(a.search)));
    const new_params = new URLSearchParams();
    for (const [key, value] of to_merge)
        { new_params.set(key, value); }
    a.search = new_params.toString();
    a.classList.remove("merge_params");
}

common.init_all_atag_merge_params =
function init_all_atag_merge_params()
{
    const page_params = Array.from(new URLSearchParams(window.location.search));
    let as = Array.from(document.getElementsByClassName("merge_params"));
    for (const a of as)
    {
        common.init_atag_merge_params(a);
    }
}

common.init_button_with_confirm =
function init_button_with_confirm(button)
{
    /*
    To create a button that requires a second confirmation step, assign it the
    class "button_with_confirm".

    Required:
        data-onclick: String that would normally be the button's onclick.
            This is done so that if the button_with_confirm fails to initialize,
            the button will be non-operational as opposed to being operational
            but with no confirmation. For dangerous actions I think this is a
            worthwhile move though it could lead to feature downtime.

    Optional:
        data-prompt: Text that appears next to the confirm button. Default is
            "Are you sure?".

        data-prompt-class: CSS class for the prompt span.

        data-confirm: Text inside the confirm button. Default is to inherit the
            original button's text.

        data-confirm-class: CSS class for the confirm button. Default is to
            inheret all classes of the original button, except for
            "button_with_confirm" of course.

        data-cancel: Text inside the cancel button. Default is "Cancel".

        data-cancel-class: CSS class for the cancel button.

        data-holder-class: CSS class for the new span that holds the menu.
    */
    button.classList.remove("button_with_confirm");

    let holder = document.createElement("span");
    holder.className = button.dataset.holderClass || "";
    holder.classList.add("confirm_holder");
    button.parentElement.insertBefore(holder, button);
    button.parentElement.removeChild(button);

    let holder_stage1 = document.createElement("span");
    holder_stage1.className = "confirm_holder_stage1";
    holder_stage1.appendChild(button);
    holder.appendChild(holder_stage1);

    let holder_stage2 = document.createElement("span");
    holder_stage2.className = "confirm_holder_stage2 hidden";
    holder.appendChild(holder_stage2);

    let prompt;
    let input_source;
    if (button.dataset.isInput)
    {
        prompt = document.createElement("input");
        prompt.placeholder = button.dataset.prompt || "";
        input_source = prompt;
    }
    else
    {
        prompt = document.createElement("span");
        prompt.innerText = (button.dataset.prompt || "Are you sure?") + " ";
        input_source = undefined;
    }
    prompt.className = button.dataset.promptClass || "";
    holder_stage2.appendChild(prompt)
    delete button.dataset.prompt;
    delete button.dataset.promptClass;

    let button_confirm = document.createElement("button");
    button_confirm.innerText = (button.dataset.confirm || button.innerText).trim();
    if (button.dataset.confirmClass === undefined)
    {
        button_confirm.className = button.className;
        button_confirm.classList.remove("button_with_confirm");
    }
    else
    {
        button_confirm.className = button.dataset.confirmClass;
    }
    button_confirm.input_source = input_source;
    holder_stage2.appendChild(button_confirm);
    holder_stage2.appendChild(document.createTextNode(" "));
    if (button.dataset.isInput)
    {
        common.bind_box_to_button(prompt, button_confirm);
    }
    delete button.dataset.confirm;
    delete button.dataset.confirmClass;
    delete button.dataset.isInput;

    let button_cancel = document.createElement("button");
    button_cancel.innerText = button.dataset.cancel || "Cancel";
    button_cancel.className = button.dataset.cancelClass || "";
    holder_stage2.appendChild(button_cancel);
    delete button.dataset.cancel;
    delete button.dataset.cancelClass;

    // If this is stupid, let me know.
    let confirm_onclick = `
        let holder = event.target.parentElement.parentElement;
        holder.getElementsByClassName("confirm_holder_stage1")[0].classList.remove("hidden");
        holder.getElementsByClassName("confirm_holder_stage2")[0].classList.add("hidden");
    ` + button.dataset.onclick;
    button_confirm.onclick = Function(confirm_onclick);

    button.removeAttribute("onclick");
    button.onclick = function(event)
    {
        let holder = event.target.parentElement.parentElement;
        holder.getElementsByClassName("confirm_holder_stage1")[0].classList.add("hidden");
        holder.getElementsByClassName("confirm_holder_stage2")[0].classList.remove("hidden");
        let input = holder.getElementsByTagName("input")[0];
        if (input)
        {
            input.focus();
        }
    }

    button_cancel.onclick = function(event)
    {
        let holder = event.target.parentElement.parentElement;
        holder.getElementsByClassName("confirm_holder_stage1")[0].classList.remove("hidden");
        holder.getElementsByClassName("confirm_holder_stage2")[0].classList.add("hidden");
    }
    delete button.dataset.onclick;
}

common.init_all_button_with_confirm =
function init_all_button_with_confirm()
{
    let buttons = Array.from(document.getElementsByClassName("button_with_confirm"));
    for (const button of buttons)
    {
        common.init_button_with_confirm(button);
    }
}

common.init_enable_on_pageload =
function init_enable_on_pageload(element)
{
    /*
    To create an input element which is disabled at first, and is enabled when
    the DOM has completed loading, give it the disabled attribute and the
    class "enable_on_pageload".
    */
    element.disabled = false;
    element.classList.remove("enable_on_pageload");
}

common.init_all_enable_on_pageload =
function init_all_enable_on_pageload()
{
    let elements = Array.from(document.getElementsByClassName("enable_on_pageload"));
    for (const element of elements)
    {
        common.init_enable_on_pageload(element);
    }
}

common.init_entry_with_history =
function init_entry_with_history(input)
{
    input.addEventListener("keydown", common.entry_with_history_hook);
    input.classList.remove("entry_with_history");
}

common.init_all_entry_with_history =
function init_all_entry_with_history()
{
    const inputs = Array.from(document.getElementsByClassName("entry_with_history"));
    for (const input of inputs)
    {
        common.init_entry_with_history(input);
    }
}

common.init_tabbed_container =
function init_tabbed_container(tabbed_container)
{
    let button_container = document.createElement("div");
    button_container.className = "tab_buttons";
    tabbed_container.prepend(button_container);
    let tabs = Array.from(tabbed_container.getElementsByClassName("tab"));
    for (const tab of tabs)
    {
        tab.classList.add("hidden");
        let tab_id = tab.dataset.tabId || tab.dataset.tabTitle;
        tab.dataset.tabId = tab_id;
        tab.style.borderTopColor = "transparent";

        let button = document.createElement("button");
        button.className = "tab_button tab_button_inactive";
        button.onclick = common.tabbed_container_switcher;
        button.innerText = tab.dataset.tabTitle;
        button.dataset.tabId = tab_id;
        button_container.append(button);
    }
    tabs[0].classList.remove("hidden");
    button_container.firstElementChild.classList.remove("tab_button_inactive");
    button_container.firstElementChild.classList.add("tab_button_active");
}

common.init_all_tabbed_container =
function init_all_tabbed_container()
{
    let tabbed_containers = Array.from(document.getElementsByClassName("tabbed_container"));
    for (const tabbed_container of tabbed_containers)
    {
        common.init_tabbed_container(tabbed_container);
    }
}

common.tabbed_container_switcher =
function tabbed_container_switcher(event)
{
    let tab_button = event.target;
    if (tab_button.classList.contains("tab_button_active"))
        { return; }

    let tab_id = tab_button.dataset.tabId;
    let tab_buttons = tab_button.parentElement.getElementsByClassName("tab_button");
    let tabs = tab_button.parentElement.parentElement.getElementsByClassName("tab");
    for (const tab_button of tab_buttons)
    {
        if (tab_button.dataset.tabId === tab_id)
        {
            tab_button.classList.remove("tab_button_inactive");
            tab_button.classList.add("tab_button_active");
        }
        else
        {
            tab_button.classList.remove("tab_button_active");
            tab_button.classList.add("tab_button_inactive");
        }
    }
    for (const tab of tabs)
    {
        if (tab.dataset.tabId === tab_id)
            { tab.classList.remove("hidden"); }
        else
            { tab.classList.add("hidden"); }
    }
}

common.refresh =
function refresh()
{
    window.location.reload();
}

common.on_pageload =
function on_pageload()
{
    common.init_all_atag_merge_params();
    common.init_all_button_with_confirm();
    common.init_all_enable_on_pageload();
    common.init_all_entry_with_history();
    common.init_all_tabbed_container();
}
document.addEventListener("DOMContentLoaded", common.on_pageload);
<|endoftext|>


<commit_before>const smash = require("../../../../smash.js");
const queryString = require("query-string");
const logger = smash.logger();
const errorUtil = smash.errorUtil();
const Context = require("./context.js");
const DASH = "-";

class Event {
	constructor(rawEvent, context, terminate) {
		if (typeof rawEvent !== 'object') {
			throw new errorUtil.TypeError("First parameter of Event() must be an object, ", rawEvent);
		}
		this._rawEvent = rawEvent;
		Object.assign(this, rawEvent);
		this.context = context;
		if (typeof terminate !== 'object') {
			throw new errorUtil.TypeError("Third parameter of Event() must be a object, ", terminate);
		}
		if (typeof terminate.terminate !== 'function') {
			throw new errorUtil.TypeError("Third parameter of Event() must be an object with a function called terminate, ", terminate.terminate);
		}
		if (terminate.terminate.length !== 2) {
			throw new Error("Third parameter of Event() must be an object with a function called terminate witch takes 2 parameters: error, data, " + terminate.terminate.length + " given");
		}
		this.requestContext = rawEvent.requestContext;
		this.processService();
		this.setupRequestId(rawEvent);
		this.apiId = this.requestContext.apiId;
		this.httpMethod = this.requestContext.httpMethod;
		this._terminate = terminate;
		this.permissionContext = null;
		this.extraContextData = {
			uriQuery: queryString.stringify(this._rawEvent.queryStringParameters),
			cookie: this._rawEvent.headers.Cookie,
		};
	}

	processService() {
		if (this.requestContext && this.requestContext.domainPrefix) {
			if (this.requestContext.domainPrefix.indexOf(DASH) > 0) {
				this.service = this.requestContext.domainPrefix.split(DASH);
				this.service.shift();
				this.service = this.service.join(DASH);
			} else {
				this.service = this.requestContext.domainPrefix;
			}
		}
		return this;
	}

	generatePermissionContext(data) {
		this.permissionContext = new Context(data);
		return this;
	}

	setupRequestId({ requestContext }) {
		if (requestContext && requestContext.requestId) {
			this.requestId = requestContext.requestId;
			logger.info("RequestId: " + this.requestId);
		}
		return this;
	}

	_generatePolicy(effect, context) {
		const authResponse = {
			principalId: context.principalId,
			context: { ...this.extraContextData, ...context.rawObject() },
		};
		if (effect && this.methodArn) {
			authResponse.policyDocument = {
				Version: '2012-10-17',
				Statement: [
					{
						Action: 'execute-api:Invoke',
						Effect: effect,
						Resource: smash.getCurrentEvent().methodArn,
					},
				],
			};
		}
		return authResponse;
	}

	terminate(error, data) {
		this._terminate.terminate(error, data);
		return this;
	}

	addExtraContextData(data) {
		this.extraContextData = { ...this.extraContextData, ...data };
		return this;
	}

	allow() {
		if (this.permissionContext) {
			this.terminate(null, this._generatePolicy("Allow", this.permissionContext));
		} else {
			this.internalServerError(errorUtil.internalServerError("Method generatePermissionContext(data) must be called before allow(), " + errorUtil.typeOf(this.permissionContext)));
		}
		return this;
	}

	deny() {
		if (this.permissionContext) {
			this.terminate(null, this._generatePolicy("Deny", this.permissionContext));
		} else {
			this.internalServerError(errorUtil.internalServerError("Method generatePermissionContext(data) must be called before deny(), " + errorUtil.typeOf(this.permissionContext)));
		}
		return this;
	}

	unauthorized(error) {
		if (error) {
			logger.error("Unauthorized", error);
		} else {
			logger.error("Unauthorized");
		}
		this.terminate("Unauthorized");
		return this;
	}

	internalServerError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.printError();
		this.terminate("Internal server error");
		return this;
	}

	handleError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.printError();
		if (errorUtil.isUnauthorizedError(error) === true) {
			this.unauthorized(error);
		} else if (errorUtil.isForbiddenError(error) === true) {
			this.deny(error);
		} else {
			this.internalServerError(error);
		}
		return this;
	}
}

module.exports = Event;
<commit_msg>Test if native module works<commit_after>const smash = require("../../../../smash.js");
const queryString = require("query-string");
const queryStringNative = require("querystring");
const logger = smash.logger();
const errorUtil = smash.errorUtil();
const Context = require("./context.js");
const DASH = "-";

class Event {
	constructor(rawEvent, context, terminate) {
		if (typeof rawEvent !== 'object') {
			throw new errorUtil.TypeError("First parameter of Event() must be an object, ", rawEvent);
		}
		this._rawEvent = rawEvent;
		Object.assign(this, rawEvent);
		this.context = context;
		if (typeof terminate !== 'object') {
			throw new errorUtil.TypeError("Third parameter of Event() must be a object, ", terminate);
		}
		if (typeof terminate.terminate !== 'function') {
			throw new errorUtil.TypeError("Third parameter of Event() must be an object with a function called terminate, ", terminate.terminate);
		}
		if (terminate.terminate.length !== 2) {
			throw new Error("Third parameter of Event() must be an object with a function called terminate witch takes 2 parameters: error, data, " + terminate.terminate.length + " given");
		}
		this.requestContext = rawEvent.requestContext;
		this.processService();
		this.setupRequestId(rawEvent);
		this.apiId = this.requestContext.apiId;
		this.httpMethod = this.requestContext.httpMethod;
		this._terminate = terminate;
		this.permissionContext = null;
		if (queryString.stringify(this._rawEvent.queryStringParameters) !== queryStringNative.stringify(this._rawEvent.queryStringParameters)) {
			logger.info("Query string diff");
		}
		this.extraContextData = {
			uriQuery: queryString.stringify(this._rawEvent.queryStringParameters),
			cookie: this._rawEvent.headers.Cookie,
		};
	}

	processService() {
		if (this.requestContext && this.requestContext.domainPrefix) {
			if (this.requestContext.domainPrefix.indexOf(DASH) > 0) {
				this.service = this.requestContext.domainPrefix.split(DASH);
				this.service.shift();
				this.service = this.service.join(DASH);
			} else {
				this.service = this.requestContext.domainPrefix;
			}
		}
		return this;
	}

	generatePermissionContext(data) {
		this.permissionContext = new Context(data);
		return this;
	}

	setupRequestId({ requestContext }) {
		if (requestContext && requestContext.requestId) {
			this.requestId = requestContext.requestId;
			logger.info("RequestId: " + this.requestId);
		}
		return this;
	}

	_generatePolicy(effect, context) {
		const authResponse = {
			principalId: context.principalId,
			context: { ...this.extraContextData, ...context.rawObject() },
		};
		if (effect && this.methodArn) {
			authResponse.policyDocument = {
				Version: '2012-10-17',
				Statement: [
					{
						Action: 'execute-api:Invoke',
						Effect: effect,
						Resource: smash.getCurrentEvent().methodArn,
					},
				],
			};
		}
		return authResponse;
	}

	terminate(error, data) {
		this._terminate.terminate(error, data);
		return this;
	}

	addExtraContextData(data) {
		this.extraContextData = { ...this.extraContextData, ...data };
		return this;
	}

	allow() {
		if (this.permissionContext) {
			this.terminate(null, this._generatePolicy("Allow", this.permissionContext));
		} else {
			this.internalServerError(errorUtil.internalServerError("Method generatePermissionContext(data) must be called before allow(), " + errorUtil.typeOf(this.permissionContext)));
		}
		return this;
	}

	deny() {
		if (this.permissionContext) {
			this.terminate(null, this._generatePolicy("Deny", this.permissionContext));
		} else {
			this.internalServerError(errorUtil.internalServerError("Method generatePermissionContext(data) must be called before deny(), " + errorUtil.typeOf(this.permissionContext)));
		}
		return this;
	}

	unauthorized(error) {
		if (error) {
			logger.error("Unauthorized", error);
		} else {
			logger.error("Unauthorized");
		}
		this.terminate("Unauthorized");
		return this;
	}

	internalServerError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.printError();
		this.terminate("Internal server error");
		return this;
	}

	handleError(error) {
		if (errorUtil.isSmashError(error) === false) {
			error = errorUtil.internalServerError("First argument of handleError(error) must ba a SmashError, " + errorUtil.typeOf(error), error);
		}
		error.printError();
		if (errorUtil.isUnauthorizedError(error) === true) {
			this.unauthorized(error);
		} else if (errorUtil.isForbiddenError(error) === true) {
			this.deny(error);
		} else {
			this.internalServerError(error);
		}
		return this;
	}
}

module.exports = Event;
<|endoftext|>


<commit_before>'use strict';

module.exports = function (name) {
    var path = require('path'),
        testUtils = require('../../utils/test.js'),
        _ = require('underscore'),
        stylesheetGenerator = require('../../../lib/stylesheet/' + name + '.js');

    describe('Stylesheet/' + name, function () {
        var layout = {
                width: 150,
                height: 156,
                images: [
                    { path: '/bla/foo.png', x: 0, y: 0, width: 150, height: 12 },
                    { path: '/foo/bar.png', x: 0, y: 12, width: 150, height: 24 },
                    { path: '/images/test.png', x: 0, y: 36, width: 150, height: 12 }
                ]
            };

        it('should generate the correct ' + name + ' without any options', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/no-options.' + name;
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, {}, done);
        });

        it('should generate the correct ' + name + ' with a prefix specified', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/with-prefix.' + name;
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, { prefix: 'sprite' }, done);
        });

        it('should generate the correct ' + name + ' with a spritePath specified', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/with-spritePath.' + name;
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, { spritePath: '/this/is/my/spritepath.png' }, done);
        });

        it('should generate the correct ' + name + ' with a custom nameMapping specified', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/with-nameMapping.' + name,
                nameMapping = function (imagePath) {
                    return path.basename(imagePath, path.extname(imagePath)).split("").reverse().join("");
                };
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, { nameMapping: nameMapping }, done);
        });

        it('should generate the correct ' + name + ' with a pixelRatio specified', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/with-pixelRatio.' + name;
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, { pixelRatio: 2 }, done);
        });
    });
};<commit_msg>fix test prefix<commit_after>'use strict';

module.exports = function (name) {
    var path = require('path'),
        testUtils = require('../../utils/test.js'),
        _ = require('underscore'),
        stylesheetGenerator = require('../../../lib/stylesheet/' + name + '.js');

    describe('Stylesheet/' + name, function () {
        var layout = {
                width: 150,
                height: 156,
                images: [
                    { path: '/bla/foo.png', x: 0, y: 0, width: 150, height: 12 },
                    { path: '/foo/bar.png', x: 0, y: 12, width: 150, height: 24 },
                    { path: '/images/test.png', x: 0, y: 36, width: 150, height: 12 }
                ]
            };

        it('should generate the correct ' + name + ' without any options', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/no-options.' + name;
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, {}, done);
        });

        it('should generate the correct ' + name + ' with a prefix specified', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/with-prefix.' + name;
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, { prefix: 'sprite-' }, done);
        });

        it('should generate the correct ' + name + ' with a spritePath specified', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/with-spritePath.' + name;
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, { spritePath: '/this/is/my/spritepath.png' }, done);
        });

        it('should generate the correct ' + name + ' with a custom nameMapping specified', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/with-nameMapping.' + name,
                nameMapping = function (imagePath) {
                    return path.basename(imagePath, path.extname(imagePath)).split("").reverse().join("");
                };
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, { nameMapping: nameMapping }, done);
        });

        it('should generate the correct ' + name + ' with a pixelRatio specified', function (done) {
            var expectedStylesheetPath = 'test/fixtures/stylesheets/' + name + '/with-pixelRatio.' + name;
            testUtils.testStylesheetGeneration(stylesheetGenerator, layout, expectedStylesheetPath, { pixelRatio: 2 }, done);
        });
    });
};<|endoftext|>


<commit_before><commit_msg>Comment fixes<commit_after><|endoftext|>


<commit_before>define(function(require) {
    var Data = require('data');
    var MainState = require('state/main');

    var state = {};
    state.create = function() {
        var name = state.make.tilemap('level' + Data.currentLevel).properties.name;
        var text = state.add.text(400, 300, "Now Entering: " + name, {
            fill: 'white'
        });
        text.anchor.set(0.5);
        var timer = state.time.create();
        timer.add(1000, function() {
            state.game.state.add('main', MainState, true);
        });
        timer.start();
    };
    return state;
});<commit_msg>Center intro text.<commit_after>define(function(require) {
    var Data = require('data');
    var MainState = require('state/main');

    var state = {};
    state.create = function() {
        var name = state.make.tilemap('level' + Data.currentLevel).properties.name;
        var text = state.add.text(400, 300, "Now Entering:\n" + name, {
            fill: 'white',
            align: 'center'
        });
        text.anchor.set(0.5);
        var timer = state.time.create();
        timer.add(1000, function() {
            state.game.state.add('main', MainState, true);
        });
        timer.start();
    };
    return state;
});<|endoftext|>