<commit_before>/* globals Actors  */

import React from 'react';
import ReactDOM from 'react-dom';

const actions = [
  {label: "browse", icon: "👆", cursor: "pointer"},
  {label: "move", icon: "👈", cursor: "move"},
  {label: "text", icon: "🔤", cursor: "text"},
  {label: "image", icon: "🏞", cursor: "crosshair"},
  {label: "button", icon: "⏺", cursor: "crosshair"},
  {label: "field", icon: "💬", cursor: "default"},
];

let child = null;
let offsetX = 0;
let offsetY = 0;
let selection = null;
let ants = 0;

class ImagePicker extends React.Component {
  onClick(x, e) {
    this.props.onPick(x);
    e.stopPropagation();
    e.preventDefault();
  }

  *generateImages() {
    let i = 0;
    for (let x of [
      "🏔", "⛰", "🌋", "🗻", "🏕", "🏖", "🏜", "🏝",
      "🏞", "🏟", "🏗", "🏘", "🏙", "🏭", "🏯", "🏰",
      "🗼", "🗽", "⛲", "⛺", "🌁", "🌃", "🌄", "🌅",
      "🌆", "🌇", "🌉", "🌌", "🎠", "🎡", "🎢", "🚢"]) {
      yield <button
        key={ `image:${i++}` }
        onClick={ this.onClick.bind(this, x) }
        style={{
          height: "32px",
          width: "32px",
          padding: "0px",
          fontSize: "32px",
          backgroundColor: "transparent",
          border: "none",
          cursor: "pointer"
        }}>
        { x }
      </button>;
    }
  }

  render() {
    return

      { Array.from(this.generateImages()) }

;
  }
}

class Editing extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    }
  }

  componentDidMount() {
    if (this.editor) {
      this.editor.focus();
    }
  }

  componentDidUpdate() {
    if (this.editor) {
      this.editor.focus();
    }
  }

  onChange(e) {
    this.setState({value: e.target.value});
  }

  onSubmit(e) {
    e.preventDefault();
    this.props.commit(this.state.value);
    render();
  }

  render() {
    return

      <form style={{
        backgroundColor: "white",
        boxSizing: "border-box",
        border: "1px solid black",
        padding: "6px"
      }} onSubmit={ this.onSubmit.bind(this) }>

          { this.props.help }

        <input ref={ (e) => { this.editor = e; } }
          style={{
            fontSize: "12pt",
            fontFamily: "serif",
            border: "none",
            width: "100%"
          }}
          value={ this.state.value }
          onChange={ this.onChange.bind(this) } />
      </form>
      { this.props.children }

;
  }
}

class SimpleEditor extends React.Component {
  render() {
    return <div style={{
      fontSize: "12pt",
      fontFamily: "serif",
      position: "absolute",
      left: `${ this.props.editing.x - 20 }px`,
      top: `${ this.props.editing.y - 50 }px`
    }}>
      <Editing help={ this.props.help } commit={ this.props.commit } />

;
  }
}

class Button extends React.Component {
  onClick(e) {
    e.stopPropagation();
    this.props.onClick(this.props.action.label, this.props.action.cursor);
  }

  render() {
    const border = this.props.active ? "1px solid black" : "transparent";
    return
      { this.props.action.icon || "🌈" }
    ;
  }
}

class Toolbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      action: props.action,
      animating: false,
      originX: 0,
      originY: 0,
      offsetX: offsetX,
      offsetY: offsetY
    };
  }

  *generateButtons() {
    for (let i = 0; i < actions.length; i++) {
      let action = actions[i];
      yield <Button
        onClick={ this.onClickButton.bind(this) }
        key={ `button${i}` }
        action={ action }
        active={ action.label === this.state.action } />;
    }
  }

  onClickButton(action, cursor) {
    //console.log("BUTTON", action);
    selection = null;
    this.setState({"action": action});
    this.props.setCursor(cursor);
    this.props.setAction(action);
  }

  onMouseDownTitleBar(e) {
    this.setState({animating: true, originX: e.clientX - this.state.offsetX, originY: e.clientY - this.state.offsetY});
    e.preventDefault();
    e.stopPropagation();
  }

  onMouseMoveTitleBar(e) {
    if (this.state.animating) {
      this.setState({offsetX: e.clientX - this.state.originX, offsetY: e.clientY - this.state.originY});
      e.preventDefault();
      e.stopPropagation();
    }
  }

  onMouseUpTitleBar(e) {
    this.setState({animating: false});
    offsetX = this.state.offsetX;
    offsetY = this.state.offsetY;
    e.preventDefault();
    e.stopPropagation();
  }

  onClickTitleBar(e) {
    e.preventDefault();
    e.stopPropagation();
  }

  render() {
    return <div style={{
      position: "absolute",
      right: `${ - this.state.offsetX }px`,
      top: `${ this.state.offsetY }px`,
      width: "74px",
      boxSizing: "border-box",
      border: "1px solid #ababab",
      backgroundColor: "#efefef"
    }}>

      { Array.from(this.generateButtons()) }

;
  }
}

class Editor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cursor: "pointer",
      action: "browse",
      mousedown: false
    }
  }

  setCursor(type) {
    this.setState({
      cursor: type
    });
  }

  setAction(type) {
    this.setState({
      action: type
    });
  }

  onClick(e) {
    const x = e.clientX;
    const y = e.clientY;

    if (this.state.action === "text" || this.state.action === "image" ||
      this.state.action === "button" || this.state.action === "field") {
      this.setState({editing:
        {type: this.state.action, state: this.state.action, x: x, y: y}
      });
      render();
    } else {
      this.props.child.cast("action", {action: this.state.action, type: "click", x, y});
    }
  }

  onMouseDown(e) {
    if (this.state.action === "browse" || this.state.action === "move") {
      this.setState({mousedown: true});
      this.props.child.cast("action", {action: this.state.action, type: "mousedown", x: e.clientX, y: e.clientY});
    }
  }

  onMouseMove(e) {
    if (this.state.mousedown) {
      this.props.child.cast("action", {action: this.state.action, type: "mousemove", x: e.clientX, y: e.clientY});
    }
  }

  onMouseUp(e) {
    if (this.state.mousedown) {
      this.setState({mousedown: false});
      this.props.child.cast("action", {action: this.state.action, type: "mouseup", x: e.clientX, y: e.clientY});
    }
  }

  commit(entity) {
    if (entity) {
      this.props.child.cast("add", {
        action: this.state.action,
        x: this.state.editing.x,
        y: this.state.editing.y - 12,
        state: entity
      });
    }
    this.setState({editing: null});
  }

  pick(entity) {
    console.log("PICK", entity);
    this.props.child.cast("add", {
      action: "emoji",
      x: this.state.editing.x,
      y: this.state.editing.y - 12,
      state: entity
    });

    this.setState({editing: null});
  }

  render() {
    let showSelection = null;
    if (selection) {
      showSelection = <Selection
        top={ selection.top } left={ selection.left }
        height={ selection.height } width={ selection.width } />
    }

    let editor = null;
    let editing = this.state.editing;
    if (editing) {
      if (editing.type === "text") {
        editor = <SimpleEditor
          editing={ editing }
          help="Type text"
          commit={ this.commit.bind(this) } />;
      } else if (editing.type === "button") {
        editor = <SimpleEditor
          editing={ editing }
          help="Enter button label"
          commit={ this.commit.bind(this) } />;
      } else if (editing.type === "field") {
        editor = <SimpleEditor
          editing={ editing }
          help="Enter field name"
          commit={ this.commit.bind(this) } />;
      } else if (editing.type === "image") {
        editor =

          <div style={{
            fontSize: "16pt",
            fontFamily: "serif",
            position: "absolute",
            left: `${ editing.x - 8 }px`,
            top: `${ editing.y - 12 }px`
          }}>
            ➕

          <Editing
            help="Enter image url"
            commit={ this.commit.bind(this) }>

              Or choose image
              <ImagePicker onPick={ this.pick.bind(this) } />

          </Editing>

;
      }
      editor =

        { editor }

;
    } else {
      editor = <Toolbar
        child={ this.props.child }
        action={ this.state.action }
        setAction={ this.setAction.bind(this) }
        setCursor={ this.setCursor.bind(this) }/>;
    }

    return

      { editor }
      { showSelection }

;
  }
}

class Selection extends React.Component {
  render() {
    return <div style={{
      borderImage: "url('selection.gif') 1 1 1 1 repeat repeat",
      borderStyle: "dashed",
      borderWidth: "1px",
      pointerEvents: "none",
      position: "absolute",
      top: `${ this.props.top }px`,
      left: `${ this.props.left }px`,
      width: `${ this.props.width }px`,
      height: `${ this.props.height }px`,
    }}>
;
  }
}

function render() {
  ReactDOM.render(<Editor child={ child } />, document.getElementById("root"));
}

async function main() {
  console.log("HELO client");

  child = Actors.spawn("child", {background: true});
  child.cast("hello", {message: "hello whirled", from: Actors.address()});

  render();

  let [pat, msg] = await Actors.recv("response");
  console.log("RESPONSE", pat, msg);
  msg.from.cast("responseresponse", {msg: "ha!"});

  while (true) {
    let [pat, msg] = await Actors.recv(["selected", "deselected"]);
    if (pat === "selected") {
      selection = msg;
      render();
    } else if (pat === "deselected") {
      selection = null;
      render();
    }
  }
}

main();
<commit_msg>Add a little space<commit_after>/* globals Actors  */

import React from 'react';
import ReactDOM from 'react-dom';

const actions = [
  {label: "browse", icon: "👆", cursor: "pointer"},
  {label: "move", icon: "👈", cursor: "move"},
  {label: "text", icon: "🔤", cursor: "text"},
  {label: "image", icon: "🏞", cursor: "crosshair"},
  {label: "button", icon: "⏺", cursor: "crosshair"},
  {label: "field", icon: "💬", cursor: "default"},
];

let child = null;
let offsetX = 0;
let offsetY = 0;
let selection = null;
let ants = 0;

class ImagePicker extends React.Component {
  onClick(x, e) {
    this.props.onPick(x);
    e.stopPropagation();
    e.preventDefault();
  }

  *generateImages() {
    let i = 0;
    for (let x of [
      "🏔", "⛰", "🌋", "🗻", "🏕", "🏖", "🏜", "🏝",
      "🏞", "🏟", "🏗", "🏘", "🏙", "🏭", "🏯", "🏰",
      "🗼", "🗽", "⛲", "⛺", "🌁", "🌃", "🌄", "🌅",
      "🌆", "🌇", "🌉", "🌌", "🎠", "🎡", "🎢", "🚢"]) {
      yield <button
        key={ `image:${i++}` }
        onClick={ this.onClick.bind(this, x) }
        style={{
          height: "32px",
          width: "32px",
          padding: "0px",
          fontSize: "32px",
          backgroundColor: "transparent",
          border: "none",
          cursor: "pointer"
        }}>
        { x }
      </button>;
    }
  }

  render() {
    return

      { Array.from(this.generateImages()) }

;
  }
}

class Editing extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ""
    }
  }

  componentDidMount() {
    if (this.editor) {
      this.editor.focus();
    }
  }

  componentDidUpdate() {
    if (this.editor) {
      this.editor.focus();
    }
  }

  onChange(e) {
    this.setState({value: e.target.value});
  }

  onSubmit(e) {
    e.preventDefault();
    this.props.commit(this.state.value);
    render();
  }

  render() {
    return

      <form style={{
        backgroundColor: "white",
        boxSizing: "border-box",
        border: "1px solid black",
        padding: "6px"
      }} onSubmit={ this.onSubmit.bind(this) }>

          { this.props.help }

        <input ref={ (e) => { this.editor = e; } }
          style={{
            fontSize: "12pt",
            fontFamily: "serif",
            border: "none",
            width: "100%"
          }}
          value={ this.state.value }
          onChange={ this.onChange.bind(this) } />
      </form>
      { this.props.children }

;
  }
}

class SimpleEditor extends React.Component {
  render() {
    return <div style={{
      fontSize: "12pt",
      fontFamily: "serif",
      position: "absolute",
      left: `${ this.props.editing.x - 20 }px`,
      top: `${ this.props.editing.y - 62 }px`
    }}>
      <Editing help={ this.props.help } commit={ this.props.commit } />

;
  }
}

class Button extends React.Component {
  onClick(e) {
    e.stopPropagation();
    this.props.onClick(this.props.action.label, this.props.action.cursor);
  }

  render() {
    const border = this.props.active ? "1px solid black" : "transparent";
    return
      { this.props.action.icon || "🌈" }
    ;
  }
}

class Toolbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      action: props.action,
      animating: false,
      originX: 0,
      originY: 0,
      offsetX: offsetX,
      offsetY: offsetY
    };
  }

  *generateButtons() {
    for (let i = 0; i < actions.length; i++) {
      let action = actions[i];
      yield <Button
        onClick={ this.onClickButton.bind(this) }
        key={ `button${i}` }
        action={ action }
        active={ action.label === this.state.action } />;
    }
  }

  onClickButton(action, cursor) {
    //console.log("BUTTON", action);
    selection = null;
    this.setState({"action": action});
    this.props.setCursor(cursor);
    this.props.setAction(action);
  }

  onMouseDownTitleBar(e) {
    this.setState({animating: true, originX: e.clientX - this.state.offsetX, originY: e.clientY - this.state.offsetY});
    e.preventDefault();
    e.stopPropagation();
  }

  onMouseMoveTitleBar(e) {
    if (this.state.animating) {
      this.setState({offsetX: e.clientX - this.state.originX, offsetY: e.clientY - this.state.originY});
      e.preventDefault();
      e.stopPropagation();
    }
  }

  onMouseUpTitleBar(e) {
    this.setState({animating: false});
    offsetX = this.state.offsetX;
    offsetY = this.state.offsetY;
    e.preventDefault();
    e.stopPropagation();
  }

  onClickTitleBar(e) {
    e.preventDefault();
    e.stopPropagation();
  }

  render() {
    return <div style={{
      position: "absolute",
      right: `${ - this.state.offsetX }px`,
      top: `${ this.state.offsetY }px`,
      width: "74px",
      boxSizing: "border-box",
      border: "1px solid #ababab",
      backgroundColor: "#efefef"
    }}>

      { Array.from(this.generateButtons()) }

;
  }
}

class Editor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      cursor: "pointer",
      action: "browse",
      mousedown: false
    }
  }

  setCursor(type) {
    this.setState({
      cursor: type
    });
  }

  setAction(type) {
    this.setState({
      action: type
    });
  }

  onClick(e) {
    const x = e.clientX;
    const y = e.clientY;

    if (this.state.action === "text" || this.state.action === "image" ||
      this.state.action === "button" || this.state.action === "field") {
      this.setState({editing:
        {type: this.state.action, state: this.state.action, x: x, y: y}
      });
      render();
    } else {
      this.props.child.cast("action", {action: this.state.action, type: "click", x, y});
    }
  }

  onMouseDown(e) {
    if (this.state.action === "browse" || this.state.action === "move") {
      this.setState({mousedown: true});
      this.props.child.cast("action", {action: this.state.action, type: "mousedown", x: e.clientX, y: e.clientY});
    }
  }

  onMouseMove(e) {
    if (this.state.mousedown) {
      this.props.child.cast("action", {action: this.state.action, type: "mousemove", x: e.clientX, y: e.clientY});
    }
  }

  onMouseUp(e) {
    if (this.state.mousedown) {
      this.setState({mousedown: false});
      this.props.child.cast("action", {action: this.state.action, type: "mouseup", x: e.clientX, y: e.clientY});
    }
  }

  commit(entity) {
    if (entity) {
      this.props.child.cast("add", {
        action: this.state.action,
        x: this.state.editing.x,
        y: this.state.editing.y - 12,
        state: entity
      });
    }
    this.setState({editing: null});
  }

  pick(entity) {
    console.log("PICK", entity);
    this.props.child.cast("add", {
      action: "emoji",
      x: this.state.editing.x,
      y: this.state.editing.y - 12,
      state: entity
    });

    this.setState({editing: null});
  }

  render() {
    let showSelection = null;
    if (selection) {
      showSelection = <Selection
        top={ selection.top } left={ selection.left }
        height={ selection.height } width={ selection.width } />
    }

    let editor = null;
    let editing = this.state.editing;
    if (editing) {
      if (editing.type === "text") {
        editor = <SimpleEditor
          editing={ editing }
          help="Type text"
          commit={ this.commit.bind(this) } />;
      } else if (editing.type === "button") {
        editor = <SimpleEditor
          editing={ editing }
          help="Enter button label"
          commit={ this.commit.bind(this) } />;
      } else if (editing.type === "field") {
        editor = <SimpleEditor
          editing={ editing }
          help="Enter field name"
          commit={ this.commit.bind(this) } />;
      } else if (editing.type === "image") {
        editor =

          <div style={{
            fontSize: "16pt",
            fontFamily: "serif",
            position: "absolute",
            left: `${ editing.x - 8 }px`,
            top: `${ editing.y - 12 }px`
          }}>
            ➕

          <Editing
            help="Enter image url"
            commit={ this.commit.bind(this) }>

              Or choose image
              <ImagePicker onPick={ this.pick.bind(this) } />

          </Editing>

;
      }
      editor =

        { editor }

;
    } else {
      editor = <Toolbar
        child={ this.props.child }
        action={ this.state.action }
        setAction={ this.setAction.bind(this) }
        setCursor={ this.setCursor.bind(this) }/>;
    }

    return

      { editor }
      { showSelection }

;
  }
}

class Selection extends React.Component {
  render() {
    return <div style={{
      borderImage: "url('selection.gif') 1 1 1 1 repeat repeat",
      borderStyle: "dashed",
      borderWidth: "1px",
      pointerEvents: "none",
      position: "absolute",
      top: `${ this.props.top }px`,
      left: `${ this.props.left }px`,
      width: `${ this.props.width }px`,
      height: `${ this.props.height }px`,
    }}>
;
  }
}

function render() {
  ReactDOM.render(<Editor child={ child } />, document.getElementById("root"));
}

async function main() {
  console.log("HELO client");

  child = Actors.spawn("child", {background: true});
  child.cast("hello", {message: "hello whirled", from: Actors.address()});

  render();

  let [pat, msg] = await Actors.recv("response");
  console.log("RESPONSE", pat, msg);
  msg.from.cast("responseresponse", {msg: "ha!"});

  while (true) {
    let [pat, msg] = await Actors.recv(["selected", "deselected"]);
    if (pat === "selected") {
      selection = msg;
      render();
    } else if (pat === "deselected") {
      selection = null;
      render();
    }
  }
}

main();
<|endoftext|>


<commit_before>/**
 * This is the base configure file for the build process.
 * (Do NOT modify unless you want to apply to all build configures)
 *
 * Base Path
 * ---------
 * All path are based on the project root. [not this configure file]
 *
 * Configure
 * ---------
 * 1. plugins:
 * 	  	settings for the plugins.
 * 2. control aspects:
 * 		dist path,
 * 		production[minify?gzip?],
 * 		watch [incremental build?],
 * 		js[es6?commonjs? + vendor],
 * 		css,
 * 		template,
 * 		assets (copy, rename (with jsminification))
 *
 * Override (create another configure)
 * -----------------------------------
 * Use the following code:
 *
 * ```
 *
 * var extend = require('extend');
 * var base = require('./base.js');
 * exports.config = extend(true, base, {
 * 		//deep extending the base configure...
 * });
 *
 * ```
 *
 * Gotcha
 * ------
 * Enable es6 only affects commonjs modules.
 * You can NOT use es6 in this build tool without 'require()'.
 *
 *
 * @author Tim Lauv
 * @created 2015.02.19
 *
 */

exports.config = {

	//---------------dist path--------------
	output: 'public',

	//----------------watch-----------------
	watching: false,

	//-----------minified & gzipped?--------
	//production build will ignore the watching flag above.
	production: false,

	//--------------js targets--------------
	//[] --> use concat only,
	//'.js' --> as commonjs module and use browserify
	//
	es6: true, //only applies to commonjs targets
	js: {
		//app.js
		app: 'app/main.js',

		//vendor.js
		vendor: [
			'libs/bower_components/jquery/dist/jquery.js',
			'libs/vendor/jquery-ui/position.js',
			'libs/bower_components/director/build/director.js',
			'libs/bower_components/reactive/reactive.js',
			'libs/vendor/kube/js/kube.js'
		]
	},

	//--------------css targets-------------
	//[] --> use concat only,
	//'.less' - lessc,
	//'.scss' - scss (TBI)
	//
	css: {
		//main.css
		main: 'app/main.less',

		//vendor.css
		vendor: [
			'libs/bower_components/fontawesome/css/font-awesome.css',
			'libs/vendor/kube/css/kube.css'
		]
	},

	//------------templates.json------------
	//
	templates: ['app/**/*.tpl.html'],

	//----------------assets----------------
	//'string' --> as glob, copy as is
	//{key: value} --> copy & rename/path
	//
	//note that overlapping path will be merged.
	//
	assets: [
		'assets/**/*',
		{'libs/bower_components/modernizr/modernizr.js':'js/modernizr.js'},
		{'libs/bower_components/fontawesome/fonts':'fonts'}
	],

	//----------gulp plugin configs---------
	//
	plugins: {

		less: {},
		autoprefixer: {},
		cleancss: {},

		babelify: {}, //es6
		browserify: {}, //commonjs

		uglify: {},
		gzip: {}

	},
};<commit_msg>Refined base configure.<commit_after>/**
 * This is the base configure file for the build process.
 * (Do NOT modify unless you want to apply to all build configures)
 *
 * Base Path
 * ---------
 * All path are based on the project root. [not this configure file]
 *
 * Configure
 * ---------
 * 1. plugins:
 * 	  	settings for the plugins.
 * 2. control aspects:
 * 		dist path,
 * 		production[minify?gzip?],
 * 		watch [incremental build?],
 * 		js[es6?commonjs? + vendor],
 * 		css,
 * 		template,
 * 		assets (copy, rename (with jsminification))
 *
 * Override (create another configure)
 * -----------------------------------
 * Use the following code:
 *
 * ```
 *
 * var extend = require('extend');
 * var base = require('./base.js');
 * exports.config = extend(true, base, {
 * 		//deep extending the base configure...
 * });
 *
 * ```
 *
 * Gotcha
 * ------
 * Enable es6 only affects commonjs modules.
 * You can NOT use es6 in this build tool without commonjs 'require()'.
 *
 *
 * @author Tim Lauv
 * @created 2015.02.19
 *
 */

exports.config = {

	//---------------dist path--------------
	output: 'public',

	//----------------watch-----------------
	watching: false,

	//-----------minified & gzipped?--------
	//production build will ignore the watch flag above.
	production: false,

	//--------------js targets--------------
	//[] --> use concat only,
	//'.js' --> as commonjs module and use browserify
	//
	es6: true, //only applies to commonjs targets
	js: {
		//app.js
		app: 'app/main.js',

		//vendor.js
		vendor: [
			'libs/bower_components/jquery/dist/jquery.js',
			'libs/vendor/jquery-ui/position.js',
			'libs/bower_components/director/build/director.js',
			'libs/bower_components/reactive/reactive.js',
			'libs/vendor/kube/js/kube.js'
		]
	},

	//--------------css targets-------------
	//[] --> use concat only,
	//'.less' - lessc,
	//'.scss' - scss (TBI)
	//
	css: {
		//main.css
		main: 'app/main.less',

		//vendor.css
		vendor: [
			'libs/bower_components/fontawesome/css/font-awesome.css',
			'libs/vendor/kube/css/kube.css'
		]
	},

	//------------templates.json------------
	//
	templates: ['app/**/*.tpl.html'],

	//----------------assets----------------
	//'string' --> as glob, copy as is
	//{key: value} --> copy & rename/path
	//
	//note that overlapping path will be merged.
	//
	assets: [
		'assets/**/*',
		{'libs/bower_components/modernizr/modernizr.js':'js/modernizr.js'},
		{'libs/bower_components/fontawesome/fonts':'fonts'}
	],

	//----------gulp plugin configs---------
	//
	plugins: {

		less: {},
		autoprefixer: {},
		cleancss: {},

		babelify: {}, //es6
		browserify: {}, //commonjs

		uglify: {},
		gzip: {}

	},
};<|endoftext|>


<commit_before>/*jslint indent: 4, white: true, browser: true, continue: true, vars: true, plusplus: true, sloppy: true, eqeq: true */
/*global $, jQuery, builder */
builder.selenium2.io.addLangFormatter({
    name : "Perl - WebDriver",
    extension : ".t",
    not : "! ",
    start : "#!perl\n\nuse strict;\nuse warnings;\nuse Test::More;\nuse Selenium::Remote::Driver;\n\nmy $wd = Selenium::Remote::Driver->new();\n",
    end : "\ndone_testing();\n",
    lineForType : {
        "get" : "ok( $wd->get({url}) );\n",
        "goBack" : "ok( $wd->go_back() );\n",
        "goForward" : "ok( $wd->go_forward() );\n",
        "refresh" : "ok( $wd->refresh() );\n",
        'clickElement' : "ok( $wd->find_element({locator}, {locatorBy})->click() );\n",
        "mouseOverElement":
            "ok( $wd->find_element({locator}, {locatorBy})->hover() );\n",
        "setElementText":
            "{\n    my $el = $wd->find_element({locator}, {locatorBy});\n" +
            "    ok( $el->click() );\n" +
            "    ok( $el->clear() );\n" +
            "    ok( $el->send_keys({text}) );\n}\n",
        "sendKeysToElement":
            "{\n    my $el = $wd->find_element({locator}, {locatorBy});\n" +
            "    ok( $el->click() );\n" +
            "    ok( $el->send_keys({text}) );\n}\n",
        "setElementSelected":
            "{\n    my $el = $wd->find_element({locator}, {locatorBy});\n" +
            "    if (! $el->is_selected()) {\n        ok( $el->click() );\n    }\n}\n",
        "setElementNotSelected":
            "{\n    my $el = $wd->find_element({locator}, {locatorBy});\n" +
            "    if ($el->is_selected()) {\n        ok( $el->click() );\n    }\n}\n",
        "submitElement":
            "ok( $wd->find_element({locator}, {locatorBy})->submit() );\n",
        "addCookie":
            function (step, escapeValue, userParams, doSubs) {
                var name = escapeValue(step.type, step.name),
                    value = escapeValue(step.type, step.value),
                    path = "/",
                    domain = "",
                    secure = 0;
                var i, kv;
                var opts = step.options.split(",");
                for (i = 0; i < opts.length; i++) {
                    kv = opts[i].trim().split("=");
                    if (kv.length === 1) { continue; }
                    if (kv[0] === "path") {
                        path = escapeValue(step.type, kv[1]);
                    }
                }
                return "ok( $wd->add_cookie('" + name + "', '" + value + "', '" + path + "', '" + domain + "', 0) );\n";
            },
        "deleteCookie": "ok( $wd->delete_cookie_named({name}) );\n",
        "switchToFrame": "ok( $wd->switch_to_frame({identifier}) );\n",
        "switchToFrameByIndex": "ok( $wd->switch_to_frame({index}) );\n",
        "switchToWindow": "ok( $wd->switch_to_window({name}) );\n",
        "switchToDefaultContent": "ok( $wd->switch_to_frame(NULL) );\n",
        "answerAlert": "ok( $wd->send_keys_to_alert({text}) );\n" +
                        "ok( $wd->accept_alert );\n",
        "acceptAlert": "ok( $wd->accept_alert );\n",
        "dismissAlert": "ok( $wd->dismiss_alert );\n",
        "saveScreenshot" : "ok( $wd->screenshot() );\n",
        "print": "print {text};\n",
        "store": "${{variable}:varType} = {text};\n"
    },
    locatorByForType : function (stepType, locatorType, locatorIndex) {
        // Valid identifiers in Perl: class, class_name, css, id, link,
        // link_text, partial_link_text, tag_name, name or xpath.
        // Defaults to 'xpath'.
        return {
            "class"        : '"class"',
            "id"           : '"id"',
            "link text"    : '"link_text"',
            "xpath"        : '"xpath"',
            "css selector" : '"css"',
            "name"         : '"name"'
        }[locatorType];
    },
    assert : function (step, escapeValue, doSubs, getter) {
        // Test should stop if step fails
        if (step.negated) {
            return doSubs(
                "if ({getter} eq {cmp}) {\n" +
                "    BAIL_OUT \"!{stepTypeName} failed\";\n" +
                "}\n",
                getter
            );
        }
        return doSubs(
            "if ({getter} ne {cmp}) {\n" +
            "    BAIL_OUT \"!{stepTypeName} failed\";\n" +
            "}\n",
            getter
        );
    },
    verify : function (step, escapeValue, doSubs, getter) {
        // Test should continue if step fails
        if (step.negated) {
            return doSubs("isnt( {getter}, {cmp} )\n", getter);
        }
        return doSubs("is( {getter}, {cmp} )\n", getter);
    },
    waitFor : "",
    store : "${{variable}:varType} = {getter};\n",
    boolean_assert:
      "if ( {posNot} {getter} ) {\n" +
      " die (\"{negNot}{stepTypeName} failed\");\n" +
      "}\n",
    boolean_verify:
      "if ( {posNot} {getter} ) {\n" +
      " print \"{negNot}{stepTypeName} failed\";\n" +
      "}\n",
    boolean_waitFor: "",
    boolean_store : "${{variable}:varType} = {getter};\n",
    boolean_getters: {
      // "TextPresent": {
      //   getter: "(strpos($wd->find_element(\"//html\", \"xpath\")->get_text(), {text}) ne false)",
      //   vartype: ""
      // },
      // "ElementPresent": {
      //   getter: "(strlen($wd->find_element({locator}, {locatorBy})) != 0)",
      //   vartype: ""
      // },
      // "CookiePresent": {
      //   getter: "($wd->get_all_cookie({name}))",
      //   vartype: ""
      // },
      // "AlertPresent": {
      //   getter: "alert_present($wd)",
      //   vartype: ""
      // },
      "ElementSelected": {
        getter: "$wd->find_element({locator}, {locatorBy})->is_selected()",
        vartype: ""
      }
    },
    getters: {
      "BodyText": {
        getter: '$wd->find_element("//html", "xpath")->get_text();',
        cmp: "{text}",
        vartype: ""
      },
      "PageSource": {
        getter: "$wd->get_page_source();",
        cmp: "{source}",
        vartype: ""
      },
      "Text": {
        getter: "$wd->find_element({locator}, {locatorBy})->get_text();",
        cmp: "{text}",
        vartype: ""
      },
      "CurrentUrl": {
        getter: "$wd->get_current_url();",
        cmp: "{url}",
        vartype: ""
      },
      "Title": {
        getter: "$wd->get_title();",
        cmp: "{title}",
        vartype: ""
      },
      "ElementValue": {
        getter: "$wd->find_element({locator}, {locatorBy})->get_value();",
        cmp: "{value}",
        vartype: ""
      },
      "ElementAttribute": {
        getter: "$wd->find_element({locator}, {locatorBy})->get_attribute({attributeName});",
        cmp: "{value}",
        vartype: "String"
      },
      "CookieByName": {
        getter: "(\n" +
         "    map { $_->{'value'} }\n" +
         "    grep { $_->{'name'} eq {name} }\n" +
         "    @{ $wd->get_all_cookies() }\n" +
         ")[0]",
        cmp: "{value}",
        vartype: ""
      },
      "AlertText": {
        getter: "$wd->get_alert_text()",
        cmp: "{text}",
        vartype: ""
      },
      "Eval": {
        getter: "$wd->execute_script({script})",
        cmp: "{value}",
        vartype: ""
      }
    },
    /**
     * Processes a parameter value into an appropriately escaped expression. Mentions of variables
     * with the ${foo} syntax are transformed into expressions that concatenate the variables and
     * literals.
     * For example:
     * a${b}c
     * becomes:
     * "a" . b . "c"
     *
     */
    escapeValue : function (stepType, value, pName) {
        if (stepType.name.startsWith("store") && pName == "variable") {
            return value;
        }
        if (stepType.name == "switchToFrameByIndex" && pName == "index") {
            return value;
        }
        // This function takes a string literal and escapes it and wraps it in quotes.
        function esc(v) {
            return "\"" + v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
        }

        // The following is a transducer that produces the escaped expression by going over each
        // character of the input.
        var output = ""; // Escaped expression.
        var lastChunk = ""; // Accumulates letters of the current literal.
        var hasDollar = false; // Whether we've just encountered a $ character.
        var insideVar = false; // Whether we are reading in the name of a variable.
        var varName = ""; // Accumulates letters of the current variable.
        var i, ch;
        for (i = 0; i < value.length; i++) {
            ch = value.substring(i, i + 1);
            if (insideVar) {
                if (ch == "}") {
                    // We've finished reading in the name of a variable.
                    // If this isn't the start of the expression, use + to concatenate it.
                    if (output.length > 0) {
                        output += " . ";
                    }
                    output += "$" + varName;
                    insideVar = false;
                    hasDollar = false;
                    varName = "";
                } else {
                    // This letter is part of the name of the variable we're reading in.
                    varName += ch;
                }
            } else {
                // We're not currently reading in the name of a variable.
                if (hasDollar) {
                    // But we *have* just encountered a $, so if this character is a {, we are about to
                    // do a variable.
                    if (ch == "{") {
                        insideVar = true;
                        if (lastChunk.length > 0) {
                            // Add the literal we've read in to the text.
                            if (output.length > 0) {
                                output += " . ";
                            }
                            output += esc(lastChunk);
                        }
                        lastChunk = "";
                    } else {
                        // No, it was just a lone $.
                        hasDollar = false;
                        lastChunk += "$" + ch;
                    }
                } else {
                    // This is the "normal case" - accumulating the letters of a literal. Unless the letter
                    // is a $, in which case this may be the start of a...
                    if (ch == "$") {
                        hasDollar = true;
                    } else {
                        lastChunk += ch;
                    }
                }
            }
        }
        // Append the final literal, if any, to the output.
        if (lastChunk.length > 0) {
            if (output.length > 0) {
                output += " . ";
            }
            output += esc(lastChunk);
        }
        return output;
    },
    usedVar : function (varName, varType) {
        return "$" + varName;
    },
    unusedVar : function (varName, varType) {
        return "my $" + varName;
    }
});
<commit_msg>Removed extra semicolons in getters<commit_after>/*jslint indent: 4, white: true, browser: true, continue: true, vars: true, plusplus: true, sloppy: true, eqeq: true */
/*global $, jQuery, builder */
builder.selenium2.io.addLangFormatter({
    name : "Perl - WebDriver",
    extension : ".t",
    not : "! ",
    start : "#!perl\n\nuse strict;\nuse warnings;\nuse Test::More;\nuse Selenium::Remote::Driver;\n\nmy $wd = Selenium::Remote::Driver->new();\n",
    end : "\ndone_testing();\n",
    lineForType : {
        "get" : "ok( $wd->get({url}) );\n",
        "goBack" : "ok( $wd->go_back() );\n",
        "goForward" : "ok( $wd->go_forward() );\n",
        "refresh" : "ok( $wd->refresh() );\n",
        'clickElement' : "ok( $wd->find_element({locator}, {locatorBy})->click() );\n",
        "mouseOverElement":
            "ok( $wd->find_element({locator}, {locatorBy})->hover() );\n",
        "setElementText":
            "{\n    my $el = $wd->find_element({locator}, {locatorBy});\n" +
            "    ok( $el->click() );\n" +
            "    ok( $el->clear() );\n" +
            "    ok( $el->send_keys({text}) );\n}\n",
        "sendKeysToElement":
            "{\n    my $el = $wd->find_element({locator}, {locatorBy});\n" +
            "    ok( $el->click() );\n" +
            "    ok( $el->send_keys({text}) );\n}\n",
        "setElementSelected":
            "{\n    my $el = $wd->find_element({locator}, {locatorBy});\n" +
            "    if (! $el->is_selected()) {\n        ok( $el->click() );\n    }\n}\n",
        "setElementNotSelected":
            "{\n    my $el = $wd->find_element({locator}, {locatorBy});\n" +
            "    if ($el->is_selected()) {\n        ok( $el->click() );\n    }\n}\n",
        "submitElement":
            "ok( $wd->find_element({locator}, {locatorBy})->submit() );\n",
        "addCookie":
            function (step, escapeValue, userParams, doSubs) {
                var name = escapeValue(step.type, step.name),
                    value = escapeValue(step.type, step.value),
                    path = "/",
                    domain = "",
                    secure = 0;
                var i, kv;
                var opts = step.options.split(",");
                for (i = 0; i < opts.length; i++) {
                    kv = opts[i].trim().split("=");
                    if (kv.length === 1) { continue; }
                    if (kv[0] === "path") {
                        path = escapeValue(step.type, kv[1]);
                    }
                }
                return "ok( $wd->add_cookie('" + name + "', '" + value + "', '" + path + "', '" + domain + "', 0) );\n";
            },
        "deleteCookie": "ok( $wd->delete_cookie_named({name}) );\n",
        "switchToFrame": "ok( $wd->switch_to_frame({identifier}) );\n",
        "switchToFrameByIndex": "ok( $wd->switch_to_frame({index}) );\n",
        "switchToWindow": "ok( $wd->switch_to_window({name}) );\n",
        "switchToDefaultContent": "ok( $wd->switch_to_frame(NULL) );\n",
        "answerAlert": "ok( $wd->send_keys_to_alert({text}) );\n" +
                        "ok( $wd->accept_alert );\n",
        "acceptAlert": "ok( $wd->accept_alert );\n",
        "dismissAlert": "ok( $wd->dismiss_alert );\n",
        "saveScreenshot" : "ok( $wd->screenshot() );\n",
        "print": "print {text};\n",
        "store": "${{variable}:varType} = {text};\n"
    },
    locatorByForType : function (stepType, locatorType, locatorIndex) {
        // Valid identifiers in Perl: class, class_name, css, id, link,
        // link_text, partial_link_text, tag_name, name or xpath.
        // Defaults to 'xpath'.
        return {
            "class"        : '"class"',
            "id"           : '"id"',
            "link text"    : '"link_text"',
            "xpath"        : '"xpath"',
            "css selector" : '"css"',
            "name"         : '"name"'
        }[locatorType];
    },
    assert : function (step, escapeValue, doSubs, getter) {
        // Test should stop if step fails
        if (step.negated) {
            return doSubs(
                "if ({getter} eq {cmp}) {\n" +
                "    BAIL_OUT \"!{stepTypeName} failed\";\n" +
                "}\n",
                getter
            );
        }
        return doSubs(
            "if ({getter} ne {cmp}) {\n" +
            "    BAIL_OUT \"!{stepTypeName} failed\";\n" +
            "}\n",
            getter
        );
    },
    verify : function (step, escapeValue, doSubs, getter) {
        // Test should continue if step fails
        if (step.negated) {
            return doSubs("isnt( {getter}, {cmp} )\n", getter);
        }
        return doSubs("is( {getter}, {cmp} )\n", getter);
    },
    waitFor : "",
    store : "${{variable}:varType} = {getter};\n",
    boolean_assert:
      "if ( {posNot} {getter} ) {\n" +
      " die (\"{negNot}{stepTypeName} failed\");\n" +
      "}\n",
    boolean_verify:
      "if ( {posNot} {getter} ) {\n" +
      " print \"{negNot}{stepTypeName} failed\";\n" +
      "}\n",
    boolean_waitFor: "",
    boolean_store : "${{variable}:varType} = {getter};\n",
    boolean_getters: {
      // "TextPresent": {
      //   getter: "(strpos($wd->find_element(\"//html\", \"xpath\")->get_text(), {text}) ne false)",
      //   vartype: ""
      // },
      // "ElementPresent": {
      //   getter: "(strlen($wd->find_element({locator}, {locatorBy})) != 0)",
      //   vartype: ""
      // },
      // "CookiePresent": {
      //   getter: "($wd->get_all_cookie({name}))",
      //   vartype: ""
      // },
      // "AlertPresent": {
      //   getter: "alert_present($wd)",
      //   vartype: ""
      // },
      "ElementSelected": {
        getter: "$wd->find_element({locator}, {locatorBy})->is_selected()",
        vartype: ""
      }
    },
    getters: {
      "BodyText": {
        getter: '$wd->find_element("//html", "xpath")->get_text()',
        cmp: "{text}",
        vartype: ""
      },
      "PageSource": {
        getter: "$wd->get_page_source()",
        cmp: "{source}",
        vartype: ""
      },
      "Text": {
        getter: "$wd->find_element({locator}, {locatorBy})->get_text()",
        cmp: "{text}",
        vartype: ""
      },
      "CurrentUrl": {
        getter: "$wd->get_current_url()",
        cmp: "{url}",
        vartype: ""
      },
      "Title": {
        getter: "$wd->get_title()",
        cmp: "{title}",
        vartype: ""
      },
      "ElementValue": {
        getter: "$wd->find_element({locator}, {locatorBy})->get_value()",
        cmp: "{value}",
        vartype: ""
      },
      "ElementAttribute": {
        getter: "$wd->find_element({locator}, {locatorBy})->get_attribute({attributeName})",
        cmp: "{value}",
        vartype: "String"
      },
      "CookieByName": {
        getter: "(\n" +
         "    map { $_->{'value'} }\n" +
         "    grep { $_->{'name'} eq {name} }\n" +
         "    @{ $wd->get_all_cookies() }\n" +
         ")[0]",
        cmp: "{value}",
        vartype: ""
      },
      "AlertText": {
        getter: "$wd->get_alert_text()",
        cmp: "{text}",
        vartype: ""
      },
      "Eval": {
        getter: "$wd->execute_script({script})",
        cmp: "{value}",
        vartype: ""
      }
    },
    /**
     * Processes a parameter value into an appropriately escaped expression. Mentions of variables
     * with the ${foo} syntax are transformed into expressions that concatenate the variables and
     * literals.
     * For example:
     * a${b}c
     * becomes:
     * "a" . b . "c"
     *
     */
    escapeValue : function (stepType, value, pName) {
        if (stepType.name.startsWith("store") && pName == "variable") {
            return value;
        }
        if (stepType.name == "switchToFrameByIndex" && pName == "index") {
            return value;
        }
        // This function takes a string literal and escapes it and wraps it in quotes.
        function esc(v) {
            return "\"" + v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\"";
        }

        // The following is a transducer that produces the escaped expression by going over each
        // character of the input.
        var output = ""; // Escaped expression.
        var lastChunk = ""; // Accumulates letters of the current literal.
        var hasDollar = false; // Whether we've just encountered a $ character.
        var insideVar = false; // Whether we are reading in the name of a variable.
        var varName = ""; // Accumulates letters of the current variable.
        var i, ch;
        for (i = 0; i < value.length; i++) {
            ch = value.substring(i, i + 1);
            if (insideVar) {
                if (ch == "}") {
                    // We've finished reading in the name of a variable.
                    // If this isn't the start of the expression, use + to concatenate it.
                    if (output.length > 0) {
                        output += " . ";
                    }
                    output += "$" + varName;
                    insideVar = false;
                    hasDollar = false;
                    varName = "";
                } else {
                    // This letter is part of the name of the variable we're reading in.
                    varName += ch;
                }
            } else {
                // We're not currently reading in the name of a variable.
                if (hasDollar) {
                    // But we *have* just encountered a $, so if this character is a {, we are about to
                    // do a variable.
                    if (ch == "{") {
                        insideVar = true;
                        if (lastChunk.length > 0) {
                            // Add the literal we've read in to the text.
                            if (output.length > 0) {
                                output += " . ";
                            }
                            output += esc(lastChunk);
                        }
                        lastChunk = "";
                    } else {
                        // No, it was just a lone $.
                        hasDollar = false;
                        lastChunk += "$" + ch;
                    }
                } else {
                    // This is the "normal case" - accumulating the letters of a literal. Unless the letter
                    // is a $, in which case this may be the start of a...
                    if (ch == "$") {
                        hasDollar = true;
                    } else {
                        lastChunk += ch;
                    }
                }
            }
        }
        // Append the final literal, if any, to the output.
        if (lastChunk.length > 0) {
            if (output.length > 0) {
                output += " . ";
            }
            output += esc(lastChunk);
        }
        return output;
    },
    usedVar : function (varName, varType) {
        return "$" + varName;
    },
    unusedVar : function (varName, varType) {
        return "my $" + varName;
    }
});
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var fs = require('fs');
var path = require('path');
var httpStatusCodes = ['200', '404', '500'];

module.exports = yeoman.Base.extend({
  prompting: function () {
    console.log('ADD HTTPCODES');
  },
  end: function () {
    var cb = this.async();
    console.log('options', this.config.getAll());
    var configOptions = this.config.getAll();
    addHTTPCodes(configOptions, cb);
  }
});

//
// FORMATING FUNCTIONS
//
var capitalizeFirstLetter = function (string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
};
//
// JOB HANDELING FUNCTIONS
//
var addHTTPCodes = function (options, cb) {
  /*
  **  Reading the copied json file and adding the required paramaters
  */
  fs.readFile(path.resolve('swaggerConfig/input.json'), 'utf8', function (error, jsonObj) {
    if (error) {
      throw error;
    }
    console.log('WE MADE IT', options);
    var inputJSON = JSON.parse(jsonObj);
    var apiPaths = options.JSONExtraction;
    apiPaths.forEach(function (apiPath) {
      addToPaths(inputJSON, options, apiPath);
    });
    // /*
    // ** saving final json file for future references
    // */
    fs.writeFile('swaggerConfig/input.json', JSON.stringify(inputJSON), function (err) {
      if (err) {
        return console.log(err);
      }
      console.log('The Json file is saved!');
      cb();
    });
  });
};

var addToPaths = function (inputJSON, options, apiPath) {
  if (inputJSON.paths === {} || typeof inputJSON.paths['/' + apiPath.resourceName + 's'] === 'undefined') {
    inputJSON.paths['/' + apiPath.resourceName + 's'] = {};
  }
  //
  // For each httpMethod
  //
  var httpMethods = apiPath.HTTPMethods;
  httpMethods.forEach(function (httpMethod) {
    inputJSON.paths['/' + apiPath.resourceName + 's'][httpMethod] = {};
    var httpOptions = {};
    httpOptions.description = capitalizeFirstLetter(httpMethod) + 's all ' + apiPath.resourceName + 's from the system that the user has access to';
    httpOptions.operationId = httpMethod + capitalizeFirstLetter(apiPath.resourceName);
    httpOptions.produces = options.APIOverviewProps.APIProduces;
    httpOptions.responses = {};
    //
    // Adding HTTP Response Code
    //
    var responses = {};
    httpStatusCodes.forEach(function (httpStatusCode) {
      responses[httpStatusCode] = {};
      responses[httpStatusCode].description = apiPath.resourceName + ' response';
      // responses[httpStatusCode].schema = {};
      // responses[httpStatusCode].schema.type = 'array';
      // responses[httpStatusCode].schema.items = {};
      // responses[httpStatusCode].schema.items.$ref = '#/definitions/' + apiPath.resourceName;
    });
    httpOptions.responses = responses;
    inputJSON.paths['/' + apiPath.resourceName + 's'][httpMethod] = httpOptions;
  });
};
<commit_msg>commiting back httpstatuscodes index.js<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var fs = require('fs');
var path = require('path');
var jsonSchemaGenerator = require('json-schema-generator');
var httpStatusCodes = ['200', '404', '500'];

module.exports = yeoman.Base.extend({
  prompting: function () {
    console.log('ADD HTTPCODES');
  },
  end: function () {
    var cb = this.async();
    console.log('options', this.config.getAll());
    var configOptions = this.config.getAll();
    addHTTPCodes(configOptions, cb);
  }
});

//
// FORMATING FUNCTIONS
//
var capitalizeFirstLetter = function (string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
};
//
// JOB HANDELING FUNCTIONS
//
var addHTTPCodes = function (options, cb) {
  /*
  **  Reading the copied json file and adding the required paramaters
  */
  fs.readFile(path.resolve('swaggerConfig/input.json'), 'utf8', function (error, jsonObj) {
    if (error) {
      throw error;
    }
    console.log('WE MADE IT', options);
    var inputJSON = JSON.parse(jsonObj);
    var apiPaths = options.JSONExtraction;
    apiPaths.forEach(function (apiPath) {
      addToDefinitions(inputJSON, apiPath);
      addToPaths(inputJSON, options, apiPath);
    });
    // /*
    // ** saving final json file for future references
    // */
    fs.writeFile('swaggerConfig/input.json', JSON.stringify(inputJSON), function (err) {
      if (err) {
        return console.log(err);
      }
      console.log('The Json file is saved!');
      cb();
    });
  });
};

/*
** This method converts provider json to schema object and adds to definitions
*/
var addToDefinitions = function(inputJSON, apiPath){
  var contents = fs.readFileSync(path.resolve(apiPath.JSONFilePath), 'utf8');
  var schemaObj = jsonSchemaGenerator(JSON.parse(contents));
  inputJSON.definitions[apiPath.resourceName] = {};
  inputJSON.definitions[apiPath.resourceName] = schemaObj;
}

/*
** This method add's user selected paths with appropriate error codes
*/
var addToPaths = function (inputJSON, options, apiPath) {
  if (inputJSON.paths === {} || typeof inputJSON.paths['/' + apiPath.resourceName + 's'] === 'undefined') {
    inputJSON.paths['/' + apiPath.resourceName + 's'] = {};
  }
  //
  // For each httpMethod
  //
  var httpMethods = apiPath.HTTPMethods;
  httpMethods.forEach(function (httpMethod) {
    inputJSON.paths['/' + apiPath.resourceName + 's'][httpMethod] = {};
    var httpOptions = {};
    httpOptions.description = capitalizeFirstLetter(httpMethod) + 's all ' + apiPath.resourceName + 's from the system that the user has access to';
    httpOptions.operationId = httpMethod + capitalizeFirstLetter(apiPath.resourceName);
    httpOptions.produces = options.APIOverviewProps.APIProduces;
    httpOptions.responses = {};
    //
    // Adding HTTP Response Code
    //
    var responses = {};
    httpStatusCodes.forEach(function (httpStatusCode) {
      responses[httpStatusCode] = {};
      responses[httpStatusCode].description = apiPath.resourceName + ' response';
      responses[httpStatusCode].schema = {};
      responses[httpStatusCode].schema.type = 'array';
      responses[httpStatusCode].schema.items = {};
      responses[httpStatusCode].schema.items.$ref = '#/definitions/' + apiPath.resourceName;
    });
    httpOptions.responses = responses;
    inputJSON.paths['/' + apiPath.resourceName + 's'][httpMethod] = httpOptions;
  });
};
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2015 mruddy
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// this code is designed to communicate with a Davis Wireless Vantage Pro2 (Part #: 06152) or Davis Vantage VUE (Part #: 06357) via a Davis WeatherLinkIP for Vantage Stations (Part #: 06555)
// protocol specification: http://www.davisnet.com/support/weather/download/VantageSerialProtocolDocs_v261.pdf
// according to the spec: "The LOOP2 packet is NOT supported in Vantage Pro and only supported in Vantage Pro2 (Firmware 1.90 or later) and Vantage Vue."
var destHost = process.argv[2];
var destPort = process.argv[3];
var consecutiveWakeups = 0;

var closeSocket = function() {
  if (socket) {
    socket.destroy();
    socket = null;
  }
};

var wakeup = function() {
  if (socket) {
    socket.write('\n'); // try to awaken the console
    socket.setTimeout(1200); // give it 1.2 seconds to respond
    consecutiveWakeups++;
    if (consecutiveWakeups > 3) {
      closeSocket();
    }
  }
};

console.log(new Date().toISOString() + ', station process created, destHost=' + destHost + ', destPort=' + destPort);

var socket = require('net').connect({ port: destPort, host: destHost} , function() {
  wakeup();
}).on('timeout', function() {
  wakeup();
}).on('data', function(buf) {
  consecutiveWakeups = 0;
  if (buf && (2 === buf.length) && (0xa === buf[0]) && (0xd === buf[1])) {
    socket.write('LPS 2 1\n'); // request sensor data from the weather station
  } else if (buf && (100 === buf.length) && (0x06 === buf[0]) && (0x4c === buf[1]) && (0x4f === buf[2]) && (0x4f === buf[3]) && (0x01 === buf[5]) && (0xff === buf[6]) && (0x7f === buf[7])) {
    // this is a LOOP2 response. 0x6 is the ack byte.
    var wx = {
      ot: ((buf[14] << 8) | buf[13]) / 10, // outside temperature in 1/10 degree F
      ws: buf[15], // wind speed in MPH
      wd: (buf[18] << 8) | buf[17], // wind direction in degrees
      wgs: ((buf[24] << 8) | buf[23]) / 10, // 10-min wind gust speed 0.1 MPH
      wgd: (buf[26] << 8) | buf[25], // 10-min wind gust direction
      oh: buf[34], // outside humidity
      instant: new Date().getTime()
    };
    process.send(wx);
    socket.setTimeout(2000); // basically, wait until the next polling interval
  }
}).on('error', function(err) {
  console.log(new Date().toISOString() + ', socket error, err=' + err + ', code=' + err.code);
});

<commit_msg>change how i access the buffer<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2015 mruddy
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// this code is designed to communicate with a Davis Wireless Vantage Pro2 (Part #: 06152) or Davis Vantage VUE (Part #: 06357) via a Davis WeatherLinkIP for Vantage Stations (Part #: 06555)
// protocol specification: http://www.davisnet.com/support/weather/download/VantageSerialProtocolDocs_v261.pdf
// according to the spec: "The LOOP2 packet is NOT supported in Vantage Pro and only supported in Vantage Pro2 (Firmware 1.90 or later) and Vantage Vue."
var destHost = process.argv[2];
var destPort = process.argv[3];
var consecutiveWakeups = 0;

var closeSocket = function() {
  if (socket) {
    socket.destroy();
    socket = null;
  }
};

var wakeup = function() {
  if (socket) {
    socket.write('\n'); // try to awaken the console
    socket.setTimeout(1200); // give it 1.2 seconds to respond
    consecutiveWakeups++;
    if (consecutiveWakeups > 3) {
      closeSocket();
    }
  }
};

console.log(new Date().toISOString() + ', station process created, destHost=' + destHost + ', destPort=' + destPort);

var socket = require('net').connect({ port: destPort, host: destHost} , function() {
  wakeup();
}).on('timeout', function() {
  wakeup();
}).on('data', function(buf) {
  consecutiveWakeups = 0;
  if (buf && (2 === buf.length) && (0xa === buf[0]) && (0xd === buf[1])) {
    socket.write('LPS 2 1\n'); // request sensor data from the weather station
  } else if (buf && (100 === buf.length) && (0x06 === buf[0]) && (0x4c === buf[1]) && (0x4f === buf[2]) && (0x4f === buf[3]) && (0x01 === buf[5]) && (0xff === buf[6]) && (0x7f === buf[7])) {
    // this is a LOOP2 response. 0x6 is the ack byte.
    var wx = {
      ot: ((buf[14] << 8) | buf[13]) / 10, // outside temperature in 1/10 degree F
      ws: buf.readUInt8(15), // wind speed in MPH
      wd: buf.readUInt16LE(17), // wind direction in degrees
      wgs: buf.readUInt16LE(23), // 10-min wind gust speed 0.1 MPH
      wgd: buf.readUInt16LE(25), // 10-min wind gust direction in degrees
      oh: buf.readUInt8(34), // outside humidity
      instant: new Date().getTime()
    };
    process.send(wx);
    socket.setTimeout(2000); // basically, wait until the next polling interval
  }
}).on('error', function(err) {
  console.log(new Date().toISOString() + ', socket error, err=' + err + ', code=' + err.code);
});

<|endoftext|>


<commit_before>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 5/6/13
 * Time: 9:03 PM
 */

define([], function defineDebuggerActions() {

    /**
     * Define Debugger Workspace
     * @constructor
     */
    var Actions = function Actions() {

    };

    return Actions.extend({

        /**
         * Config predefined scope
         */
        configScope: function configScope() {

            /**
             * Define edit mode
             * @type {Boolean}
             */
            this.editMode = false;

            this.actions = [
                'add-item',
                'remove-items',
                'remove-all-items',
                'locate-item'
            ];

            this.extendSelectors({
                edit: 'li.edit-mode',
                actions: 'ul.actions',
                items: 'ul.items-info',
                count: 'li.items-count'
            });

        },

        /**
         * Extend debugger selectors
         * @param {*} opts
         */
        extendSelectors: function extendSelectors(opts) {
            this.selectors = {};
            $.each(opts || {}, function each(i, selector) {
                this.selectors[i] = [this.debugger.info, selector].join(' ');
            }.bind(this));

        },

        /**
         * Render page items actions
         * @returns {string}
         */
        renderItemsActions: function renderItemsActions() {
            return [
                '

',
                this._renderActions(),
                this._renderEnableEditMode(),
                '

'
            ].join('');
        },

        /**
         * Render generic action
         * @returns {string}
         * @private
         */
        _renderActions: function _renderActions() {
            var html = [];
            $.each(this.actions, function each(i, action) {
                var fn = this['_' + action.toCamel() + 'Button'];
                if (this.debugger.base.isFunction(fn)) {
                    html.push(fn.bind(this)());
                }
            }.bind(this));
            return html.join('');
        },

        /**
         * Render add new item button
         * @returns {string}
         * @private
         */
        _addItemButton: function _addItemButton() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                style: 'disabled',
                title: 'Add item'
            });
        },

        /**
         * Render remove item button
         * @returns {string}
         * @private
         */
        _removeItemsButton: function _removeItemsButton() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                style: 'disabled select',
                title: 'Remove items'
            });
        },

        /**
         * Render remove items button
         * @returns {string}
         * @private
         */
        _removeAllItemsButton: function _removeAllItemsButton() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                style: 'disabled select',
                title: 'Remove all items'
            });
        },

        /**
         * Render locate item button
         * @returns {string}
         * @private
         */
        _locateItemButton: function _locateItemButton() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                style: 'disabled select',
                title: 'Locate item'
            });
        },

        /**
         * Render enable edit mode
         * @returns {string}
         * @private
         */
        _renderEnableEditMode: function _renderEnableEditMode() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                title: 'Edit mode'
            });
        },

        /**
         * Render items info
         * @param {*} scope
         * @returns {string}
         */
        renderItemsInfo: function renderItemsInfo(scope) {
            return [
                '
',
                this.debugger.component.renderBlock('Items', [
                    this.renderItemsActions(),
                    this._getItemsCount(scope),
                    this.renderItemsList(scope)
                ], true),
                '
'
            ].join(' ');
        },

        /**
         * Render page items list
         * @param scope
         * @returns {string}
         */
        renderItemsList: function renderItemsList(scope) {
            var html = ['

'];
            html.push(this.getItemsList(scope));
            html.push('

');
            return html.join('');
        },

        /**
         * Get page item list
         * @param scope
         * @returns {string}
         */
        getItemsList: function getItemsList(scope) {
            var html = [];
            $.each(scope.items, function each(uuid, item) {
                html.push([
                    '
', uuid , '
'
                ].join(''));
            });

            return html.join('');
        },

        /**
         * Update page item list
         * @param page
         */
        updateItems: function updateItems(page) {
            $(this.selectors.items).html(
                this.getItemsList(page)
            );

            var $count = $(this.selectors.count);

            $count.before(
                this._getItemsCount(page)
            ).remove();

            this._bindItemsList(page);
            this.$select.addClass('select');
        },

        /**
         * Get items count
         * @param {*} page
         * @returns {string}
         * @private
         */
        _getItemsCount: function _getItemsCount(page) {
            return this.debugger.component.renderInlineOf('Count', page);
        },

        /**
         * Get page item action button
         * @param {String} action
         * @returns {*|jQuery|HTMLElement}
         * @private
         */
        _getItemAction: function _getItemAction(action) {
            return $('li.' + action, this.selectors.actions);
        },

        /**
         * Bind enable page item edit mode,
         * @param {*} scope
         */
        bindEnableItemsEditMode: function bindEnableItemsEditMode(scope) {
            $(this.selectors.edit).on('click.edit', function edit(e) {
                this._enableItemsEditMode(e, scope);
            }.bind(this));
        },

        /**
         * Bind item list
         * @param scope
         * @private
         */
        _bindItemsList: function _bindItemsList(scope) {
            this.$select = this.debugger.base.define(
                this.$select,
                $('.select', this.selectors.actions)
            );

            if (this.editMode) {
                $('li', this.selectors.items).on('click.select', function select(e) {
                    var $li = $(e.target),
                        item = scope.items[$li.text()];

                    if ($li.hasClass('select')) {
                        scope.logger.debug('Unselect', item);
                        $li.removeClass('select');
                        this.$select.addClass('select');
                    } else {
                        scope.logger.debug('Select', item);
                        $li.addClass('select');
                        this.$select.removeClass('select');
                    }

                    var $select = $('li.select', this.selectors.items),
                        $locate = this._getItemAction('locate-item');

                    $select.length === 1 ?
                        $locate.removeClass('disabled select') :
                        $locate.addClass('disabled select');

                }.bind(this));
            }
        },

        /**
         * Unbind item list
         * @private
         */
        _unbindItemsList: function _unbindItemsList() {
            $('li', this.selectors.items).unbind('click.select');
        },

        /**
         * Enable item edit mode
         * @param {*} e
         * @param {*} scope
         * @private
         */
        _enableItemsEditMode: function _enableItemsEditMode(e, scope) {
            var $this = $(e.target),
                $disabled = $('li[rel="disabled"]', $this.parent('ul'));
            if ($disabled.hasClass('disabled')) {
                scope.logger.debug('Activate edit mode');
                $disabled.removeClass('disabled');
                $this.addClass('active');
                this.editMode = true;
                this._bindItemsList(scope);
                this._bindAddNewItem(scope);
                this._bindRemoveItems(scope);
                this._bindRemoveAllItems(scope);
                this._bindLocateItem(scope);
            } else {
                this._disableItemsEditMode($this, scope);
            }
        },

        /**
         * Disable page item edit mode
         * @param {*} $this
         * @param {*} scope
         * @private
         */
        _disableItemsEditMode: function _disableItemsEditMode($this, scope) {
            var $disabled = $('li[rel="disabled"]', $this.parent('ul'));

            scope.logger.debug('Deactivate edit mode');
            $disabled.addClass('disabled');
            $this.removeClass('active');
            this._unbindAddNewItem(scope);
            this._unbindRemoveItems(scope);
            this._unbindRemoveAllItems(scope);
            this._unbindLocateItem(scope);
            this._unbindItemsList();
            this.editMode = false;
        },

        /**
         * Bind add new item
         * @param {*} scope
         * @private
         */
        _bindAddNewItem: function _bindAddNewItem(scope) {
            scope.logger.debug('Bind edit mode');
            this._getItemAction('add-item').on('click.add', function (e) {
                scope.api.createItem([], true);
                this._getItemAction('remove-items').removeClass('disabled');
            }.bind(this));
        },

        /**
         * Unbind add new item
         * @param {*} scope
         * @private
         */
        _unbindAddNewItem: function _unbindAddNewItem(scope) {
            scope.logger.debug('Unbind Add item');
            this._getItemAction('add-item').unbind('click.add');
        },

        /**
         * Bind remove items
         * @param scope
         * @private
         */
        _bindRemoveItems: function _bindRemoveItems(scope) {
            scope.logger.debug('Bind remove items');
            this._getItemAction('remove-items').on('click.remove', function remove(e) {
                if ($('li.select', this.selectors.items).length === 0) {
                    scope.logger.warn('Select items before remove');
                    return false;
                }
                this._removeItems(scope);
            }.bind(this));
        },

        /**
         * Unbind remove items
         * @param {*} scope
         * @private
         */
        _unbindRemoveItems: function _unbindRemoveItems(scope) {
            scope.logger.debug('Unbind remove items');
            this._getItemAction('remove-items').unbind('click.remove');
            $('li', this.selectors.items).removeClass('select');
        },

        /**
         * Bind remove all items
         * @param scope
         * @private
         */
        _bindRemoveAllItems: function _bindRemoveAllItems(scope) {
            var $lis = $('li', this.selectors.items),
                $action = this._getItemAction('remove-all-items');
            scope.logger.debug('Bind remove all items');

            if ($lis.length === 0) {
                $action.addClass('disabled');
            }

            $action.on('click.remove', function remove(e) {
                if ($lis.length === 0) {
                    scope.logger.warn('Add items before remove');
                    return false;
                }
                this._removeAllItems(scope);
            }.bind(this));
        },

        /**
         * Unbind remove all items
         * @param {*} scope
         * @private
         */
        _unbindRemoveAllItems: function _unbindRemoveAllItems(scope) {
            scope.logger.debug('Unbind remove all items');
            this._getItemAction('remove-items').unbind('click.remove');
            $('li', this.selectors.items).removeClass('select');
        },

        /**
         * Bind locate item
         * @param scope
         * @private
         */
        _bindLocateItem: function _bindLocateItem(scope) {
            scope.logger.debug('Bind locate item');

            this._getItemAction('locate-item').on('click.locate', function locate(e) {
                this._locateItem(scope);
            }.bind(this));
        },

        /**
         * Unbind remove all items
         * @param {*} scope
         * @private
         */
        _unbindLocateItem: function _unbindLocateItem(scope) {
            scope.logger.debug('Unbind locate item');
            this._getItemAction('locate-item').unbind('click.locate');
//            $('li', this.selectors.items).removeClass('select');
        },

        _locateItem: function _locateItem(scope) {
//            var $li = $('li.select', this.selectors.items);
//
//            if ($li.length !== 1) {
//                page.logger.warn('Select one item before locate');
//                return false;
//            }
//
//            var uuid = $li.text(),
//                item = page.model.getItemByUUID(uuid);
//
//            if (!this.debugger.base.isDefined(item)) {
//                page.logger.warn('Undefined item', uuid);
//                return false;
//            }
//
//            page.logger.warn('Locate', item);

        },

        /**
         * Remove items
         * @param {*} scope
         * @private
         */
        _removeItems: function _removeItems(scope) {
            var items = {};
            $.each($('li.select', this.selectors.items), function each(i, v) {
                var uuid = $(v).text();
                items[uuid] = scope.model.getItemByUUID(uuid);
            });

            scope.logger.debug('Start remove items', items);
            scope.api.destroyItems(items);

        },

        /**
         * Remove items
         * @param {*} scope
         * @private
         */
        _removeAllItems: function _removeAllItems(scope) {
            $('li', this.selectors.items).addClass('select');
            this._getItemAction('remove-items').addClass('disabled');
            scope.logger.debug('Start remove all items');
            this._removeItems(scope);
        }
    });
});
<commit_msg>fix remove all items<commit_after>/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 5/6/13
 * Time: 9:03 PM
 */

define([], function defineDebuggerActions() {

    /**
     * Define Debugger Workspace
     * @constructor
     */
    var Actions = function Actions() {

    };

    return Actions.extend({

        /**
         * Config predefined scope
         */
        configScope: function configScope() {

            /**
             * Define edit mode
             * @type {Boolean}
             */
            this.editMode = false;

            this.actions = [
                'add-item',
                'remove-items',
                'remove-all-items',
                'locate-item'
            ];

            this.extendSelectors({
                edit: 'li.edit-mode',
                actions: 'ul.actions',
                items: 'ul.items-info',
                count: 'li.items-count'
            });

        },

        /**
         * Extend debugger selectors
         * @param {*} opts
         */
        extendSelectors: function extendSelectors(opts) {
            this.selectors = {};
            $.each(opts || {}, function each(i, selector) {
                this.selectors[i] = [this.debugger.info, selector].join(' ');
            }.bind(this));

        },

        /**
         * Render page items actions
         * @returns {string}
         */
        renderItemsActions: function renderItemsActions() {
            return [
                '

',
                this._renderActions(),
                this._renderEnableEditMode(),
                '

'
            ].join('');
        },

        /**
         * Render generic action
         * @returns {string}
         * @private
         */
        _renderActions: function _renderActions() {
            var html = [];
            $.each(this.actions, function each(i, action) {
                var fn = this['_' + action.toCamel() + 'Button'];
                if (this.debugger.base.isFunction(fn)) {
                    html.push(fn.bind(this)());
                }
            }.bind(this));
            return html.join('');
        },

        /**
         * Render add new item button
         * @returns {string}
         * @private
         */
        _addItemButton: function _addItemButton() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                style: 'disabled',
                title: 'Add item'
            });
        },

        /**
         * Render remove item button
         * @returns {string}
         * @private
         */
        _removeItemsButton: function _removeItemsButton() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                style: 'disabled select',
                title: 'Remove items'
            });
        },

        /**
         * Render remove items button
         * @returns {string}
         * @private
         */
        _removeAllItemsButton: function _removeAllItemsButton() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                style: 'disabled select',
                title: 'Remove all items'
            });
        },

        /**
         * Render locate item button
         * @returns {string}
         * @private
         */
        _locateItemButton: function _locateItemButton() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                style: 'disabled select',
                title: 'Locate item'
            });
        },

        /**
         * Render enable edit mode
         * @returns {string}
         * @private
         */
        _renderEnableEditMode: function _renderEnableEditMode() {
            return this.debugger.component.renderInlineAction({
                rel: 'disabled',
                title: 'Edit mode'
            });
        },

        /**
         * Render items info
         * @param {*} scope
         * @returns {string}
         */
        renderItemsInfo: function renderItemsInfo(scope) {
            return [
                '
',
                this.debugger.component.renderBlock('Items', [
                    this.renderItemsActions(),
                    this._getItemsCount(scope),
                    this.renderItemsList(scope)
                ], true),
                '
'
            ].join(' ');
        },

        /**
         * Render page items list
         * @param scope
         * @returns {string}
         */
        renderItemsList: function renderItemsList(scope) {
            var html = ['

'];
            html.push(this.getItemsList(scope));
            html.push('

');
            return html.join('');
        },

        /**
         * Get page item list
         * @param scope
         * @returns {string}
         */
        getItemsList: function getItemsList(scope) {
            var html = [];
            $.each(scope.items, function each(uuid, item) {
                html.push([
                    '
', uuid , '
'
                ].join(''));
            });

            return html.join('');
        },

        /**
         * Update page item list
         * @param page
         */
        updateItems: function updateItems(page) {
            $(this.selectors.items).html(
                this.getItemsList(page)
            );

            var $count = $(this.selectors.count);

            $count.before(
                this._getItemsCount(page)
            ).remove();

            this._bindItemsList(page);
            this.$select.addClass('select');
        },

        /**
         * Get items count
         * @param {*} page
         * @returns {string}
         * @private
         */
        _getItemsCount: function _getItemsCount(page) {
            return this.debugger.component.renderInlineOf('Count', page);
        },

        /**
         * Get page item action button
         * @param {String} action
         * @returns {*|jQuery|HTMLElement}
         * @private
         */
        _getItemAction: function _getItemAction(action) {
            return $('li.' + action, this.selectors.actions);
        },

        /**
         * Bind enable page item edit mode,
         * @param {*} scope
         */
        bindEnableItemsEditMode: function bindEnableItemsEditMode(scope) {
            $(this.selectors.edit).on('click.edit', function edit(e) {
                this._enableItemsEditMode(e, scope);
            }.bind(this));
        },

        /**
         * Bind item list
         * @param scope
         * @private
         */
        _bindItemsList: function _bindItemsList(scope) {
            this.$select = this.debugger.base.define(
                this.$select,
                $('.select', this.selectors.actions)
            );

            if (this.editMode) {
                $('li', this.selectors.items).on('click.select', function select(e) {
                    var $li = $(e.target),
                        item = scope.items[$li.text()];

                    if ($li.hasClass('select')) {
                        scope.logger.debug('Unselect', item);
                        $li.removeClass('select');
                        this.$select.addClass('select');
                    } else {
                        scope.logger.debug('Select', item);
                        $li.addClass('select');
                        this.$select.removeClass('select');
                    }

                    var $select = $('li.select', this.selectors.items),
                        $locate = this._getItemAction('locate-item');

                    $select.length === 1 ?
                        $locate.removeClass('disabled select') :
                        $locate.addClass('disabled select');

                }.bind(this));
            }
        },

        /**
         * Unbind item list
         * @private
         */
        _unbindItemsList: function _unbindItemsList() {
            $('li', this.selectors.items).unbind('click.select');
        },

        /**
         * Enable item edit mode
         * @param {*} e
         * @param {*} scope
         * @private
         */
        _enableItemsEditMode: function _enableItemsEditMode(e, scope) {
            var $this = $(e.target),
                $disabled = $('li[rel="disabled"]', $this.parent('ul'));
            if ($disabled.hasClass('disabled')) {
                scope.logger.debug('Activate edit mode');
                $disabled.removeClass('disabled');
                $this.addClass('active');
                this.editMode = true;
                this._bindItemsList(scope);
                this._bindAddNewItem(scope);
                this._bindRemoveItems(scope);
                this._bindRemoveAllItems(scope);
                this._bindLocateItem(scope);
            } else {
                this._disableItemsEditMode($this, scope);
            }
        },

        /**
         * Disable page item edit mode
         * @param {*} $this
         * @param {*} scope
         * @private
         */
        _disableItemsEditMode: function _disableItemsEditMode($this, scope) {
            var $disabled = $('li[rel="disabled"]', $this.parent('ul'));

            scope.logger.debug('Deactivate edit mode');
            $disabled.addClass('disabled');
            $this.removeClass('active');
            this._unbindAddNewItem(scope);
            this._unbindRemoveItems(scope);
            this._unbindRemoveAllItems(scope);
            this._unbindLocateItem(scope);
            this._unbindItemsList();
            this.editMode = false;
        },

        /**
         * Bind add new item
         * @param {*} scope
         * @private
         */
        _bindAddNewItem: function _bindAddNewItem(scope) {
            scope.logger.debug('Bind edit mode');
            this._getItemAction('add-item').on('click.add', function (e) {
                scope.api.createItem([], true);
                this._getItemAction('remove-items').removeClass('disabled');
            }.bind(this));
        },

        /**
         * Unbind add new item
         * @param {*} scope
         * @private
         */
        _unbindAddNewItem: function _unbindAddNewItem(scope) {
            scope.logger.debug('Unbind Add item');
            this._getItemAction('add-item').unbind('click.add');
        },

        /**
         * Bind remove items
         * @param scope
         * @private
         */
        _bindRemoveItems: function _bindRemoveItems(scope) {
            scope.logger.debug('Bind remove items');
            this._getItemAction('remove-items').on('click.remove', function remove(e) {
                if ($('li.select', this.selectors.items).length === 0) {
                    scope.logger.warn('Select items before remove');
                    return false;
                }
                this._removeItems(scope);
            }.bind(this));
        },

        /**
         * Unbind remove items
         * @param {*} scope
         * @private
         */
        _unbindRemoveItems: function _unbindRemoveItems(scope) {
            scope.logger.debug('Unbind remove items');
            this._getItemAction('remove-items').unbind('click.remove');
            $('li', this.selectors.items).removeClass('select');
        },

        /**
         * Bind remove all items
         * @param scope
         * @private
         */
        _bindRemoveAllItems: function _bindRemoveAllItems(scope) {
            var $lis = $('li', this.selectors.items),
                $action = this._getItemAction('remove-all-items');
            scope.logger.debug('Bind remove all items');

            if ($lis.length === 0) {
                $action.addClass('disabled');
            }

            $action.on('click.remove', function remove(e) {
                if ($lis.length === 0) {
                    scope.logger.warn('Add items before remove');
                    return false;
                }
                this._removeAllItems(scope);
            }.bind(this));
        },

        /**
         * Unbind remove all items
         * @param {*} scope
         * @private
         */
        _unbindRemoveAllItems: function _unbindRemoveAllItems(scope) {
            scope.logger.debug('Unbind remove all items');
            this._getItemAction('remove-items').unbind('click.remove');
            $('li', this.selectors.items).removeClass('select');
        },

        /**
         * Bind locate item
         * @param scope
         * @private
         */
        _bindLocateItem: function _bindLocateItem(scope) {
            scope.logger.debug('Bind locate item');

            this._getItemAction('locate-item').on('click.locate', function locate(e) {
                this._locateItem(scope);
            }.bind(this));
        },

        /**
         * Unbind remove all items
         * @param {*} scope
         * @private
         */
        _unbindLocateItem: function _unbindLocateItem(scope) {
            scope.logger.debug('Unbind locate item');
            this._getItemAction('locate-item').unbind('click.locate');
//            $('li', this.selectors.items).removeClass('select');
        },

        _locateItem: function _locateItem(scope) {
//            var $li = $('li.select', this.selectors.items);
//
//            if ($li.length !== 1) {
//                page.logger.warn('Select one item before locate');
//                return false;
//            }
//
//            var uuid = $li.text(),
//                item = page.model.getItemByUUID(uuid);
//
//            if (!this.debugger.base.isDefined(item)) {
//                page.logger.warn('Undefined item', uuid);
//                return false;
//            }
//
//            page.logger.warn('Locate', item);

        },

        /**
         * Remove items
         * @param {*} scope
         * @private
         */
        _removeItems: function _removeItems(scope) {
            var items = {};
            $.each($('li.select', this.selectors.items), function each(i, v) {
                var uuid = $(v).text();
                items[uuid] = scope.model.getItemByUUID(uuid);
            });

            scope.logger.debug('Start remove items', items);
            scope.api.destroyItems(items);

        },

        /**
         * Remove items
         * @param {*} scope
         * @private
         */
        _removeAllItems: function _removeAllItems(scope) {
            $('li', this.selectors.items).addClass('select');
            this._getItemAction('remove-all-items').addClass('disabled');
            scope.logger.debug('Start remove all items');
            this._removeItems(scope);
        }
    });
});
<|endoftext|>


<commit_before>/**
 * @class Touch
 */

EZ3.Touch = function(domElement, device) {
  this._domElement = domElement;
  this._device = device;
  this._pointers = [];

  this.enabled = false;
  this.onPress = new EZ3.Signal();
  this.onMove = new EZ3.Signal();
  this.onUp = new EZ3.Signal();
};

EZ3.Touch.prototype.constructor = EZ3.Touch;

EZ3.Touch.prototype._processTouchPress = function(event) {
  event.preventDefault();

  for (var i = 0; i < event.changedTouches.length; i++) {
    var id = event.changedTouches[i].identifier;

    if (!this._pointers[id])
      this._pointers[id] = new EZ3.TouchPointer(id);

    this._pointers[id].processPress(event.changedTouches[i], this.onPress, this.onMove);
  }
};

EZ3.Touch.prototype._processTouchMove = function(event) {
  event.preventDefault();

  for (var i = 0; i < event.changedTouches.length; i++)
    this._pointers[event.changedTouches[i].identifier].processMove(event.changedTouches[i], this.onMove);
};

EZ3.Touch.prototype._processTouchUp = function(event) {
  event.preventDefault();

  for (var i = 0; i < event.changedTouches.length; i++) {
    var id = event.changedTouches[i].identifier;

    if (!this._pointers[id])
      this._pointers[id] = new EZ3.TouchPointer(id);

    this._pointers[id].processUp(this.onUp);
  }
};

EZ3.Touch.prototype.enable = function() {
  if (this._device.touch) {
    var that = this;

    this.enabled = true;

    this._onTouchPress = function(event) {
      that._processTouchPress(event);
    };

    this._onTouchMove = function(event) {
      that._processTouchMove(event);
    };

    this._onTouchUp = function(event) {
      that._processTouchUp(event);
    };

    if (this._device.touch === EZ3.Device.TOUCH) {
      this._press = 'touchstart';
      this._move = 'touchmove';
      this._up = 'touchend';
    } else if (this._device.touch === EZ3.Device.POINTER) {
      this._press = 'pointerdown';
      this._move = 'pointermove';
      this._up = 'pointerup';
    } else {
      this._press = 'MSPointerDown';
      this._move = 'MSPointerMove';
      this._up = 'MSPointerUp';
    }

    this._domElement.addEventListener(this._press, this._onTouchPress, false);
    this._domElement.addEventListener(this._move, this._onTouchMove, false);
    this._domElement.addEventListener(this._up, this._onTouchUp, false);
  }
};

EZ3.Touch.prototype.disable = function() {
  if (this._device.touch) {
    this.enabled = false;

    this._domElement.removeEventListener(this._press, this._onTouchPress, false);
    this._domElement.removeEventListener(this._move, this._onTouchMove, false);
    this._domElement.removeEventListener(this._up, this._onTouchUp, false);

    delete this._onTouchPress;
    delete this._onTouchMove;
    delete this._onTouchUp;

    delete this._press;
    delete this._move;
    delete this._up;
  }
};

EZ3.Touch.prototype.getPointer = function(id) {
  if (!this._pointers[--id])
    this._pointers[id] = new EZ3.TouchPointer(id);

  return this._pointers[id];
};

EZ3.Touch.TAP = 0;
<commit_msg>Updated touch id<commit_after>/**
 * @class Touch
 */

EZ3.Touch = function(domElement, device) {
  this._domElement = domElement;
  this._device = device;
  this._pointers = [];
  this.count = -1;

  this.enabled = false;
  this.onPress = new EZ3.Signal();
  this.onMove = new EZ3.Signal();
  this.onUp = new EZ3.Signal();
};

EZ3.Touch.prototype.constructor = EZ3.Touch;

EZ3.Touch.prototype._processTouchPress = function(event) {
  event.preventDefault();

  for (var i = 0; i < event.changedTouches.length; i++) {
    //var id = event.changedTouches[i].identifier;
    this.count++;

    if (!this._pointers[this.count])
      this._pointers[this.count] = new EZ3.TouchPointer(this.count);

    this._pointers[this.count].processPress(event.changedTouches[i], this.onPress, this.onMove);
  }
};

EZ3.Touch.prototype._processTouchMove = function(event) {
  event.preventDefault();

  for (var i = 0; i < event.changedTouches.length; i++)
    this._pointers[i].processMove(event.changedTouches[i], this.onMove);
};

EZ3.Touch.prototype._processTouchUp = function(event) {
  event.preventDefault();

  for (var i = 0; i < event.changedTouches.length; i++) {
    //var id = event.changedTouches[i].identifier;
    if (!this._pointers[this.count])
      this._pointers[this.count] = new EZ3.TouchPointer(this.count);

    this._pointers[this.count].processUp(this.onUp);

    this.count--;
  }
};

EZ3.Touch.prototype.enable = function() {
  if (this._device.touch) {
    var that = this;

    this.enabled = true;

    this._onTouchPress = function(event) {
      that._processTouchPress(event);
    };

    this._onTouchMove = function(event) {
      that._processTouchMove(event);
    };

    this._onTouchUp = function(event) {
      that._processTouchUp(event);
    };

    if (this._device.touch === EZ3.Device.TOUCH) {
      this._press = 'touchstart';
      this._move = 'touchmove';
      this._up = 'touchend';
    } else if (this._device.touch === EZ3.Device.POINTER) {
      this._press = 'pointerdown';
      this._move = 'pointermove';
      this._up = 'pointerup';
    } else {
      this._press = 'MSPointerDown';
      this._move = 'MSPointerMove';
      this._up = 'MSPointerUp';
    }

    this._domElement.addEventListener(this._press, this._onTouchPress, false);
    this._domElement.addEventListener(this._move, this._onTouchMove, false);
    this._domElement.addEventListener(this._up, this._onTouchUp, false);
  }
};

EZ3.Touch.prototype.disable = function() {
  if (this._device.touch) {
    this.enabled = false;

    this._domElement.removeEventListener(this._press, this._onTouchPress, false);
    this._domElement.removeEventListener(this._move, this._onTouchMove, false);
    this._domElement.removeEventListener(this._up, this._onTouchUp, false);

    delete this._onTouchPress;
    delete this._onTouchMove;
    delete this._onTouchUp;

    delete this._press;
    delete this._move;
    delete this._up;
  }
};

EZ3.Touch.prototype.getPointer = function(id) {
  if (!this._pointers[--id])
    this._pointers[id] = new EZ3.TouchPointer(id);

  return this._pointers[id];
};

EZ3.Touch.TAP = 0;
<|endoftext|>