<commit_before>var Subscriber, AtomJshint;
var JSHINT = require('./vendor/jshint').JSHINT;
var Subscriber = require('emissary').Subscriber;
var fs = require('fs');

module.exports = AtomJshint = (function(){

  var $ = require('atom').$;
  function AtomJsHint(){
    atom.workspace.eachEditor((function(self) {
      return function(editor) {
        return self.handleEvents(editor);
      };
    })(this));
    this.config = {globals:{},options:{}};
    this.loadConfig();
  }
  Subscriber.includeInto(AtomJsHint);

  AtomJsHint.prototype.destroy = function(){
    return this.unsubscribe();
  };

  AtomJsHint.prototype.handleEvents = function(editor) {
    var buffer = editor.getBuffer();
    var listenFor = [];
    if( atom.config.get('atom-jshint.hintOnModify') ){ listenFor.push('contents-modified'); }
    if( atom.config.get('atom-jshint.hintOnSave') ) { listenFor.push('saved'); }

    this.subscribe(atom.workspaceView, 'pane-container:active-pane-item-changed', function(){
      this.run(editor);
    }.bind(this));
    this.subscribe(buffer, listenFor.join(' '), (function(self) {
      return function() {
        return buffer.transact(function() {
          self.run(editor);
        });
      };
    })(this));
    this.subscribe(buffer, 'destroyed', (function(self) {
      return function() {
        return self.unsubscribe(buffer);
      };
    })(this));
  };

  AtomJsHint.prototype.run = function(editor){
    var self = this;
    var text = this.getContents();
    if( !text ) {
      this.resetState(editor);
      return;
    }
    if( !JSHINT(text, this.config.options, this.config.globals) ){
      //sometimes jshint creates a null object in the array
      var jsHintErrors = JSHINT.errors.filter(function (error) { return error !== null; });
      if( editor.cursors[0] ){
        self.updateStatus(jsHintErrors, editor.cursors[0].getBufferRow());
      }
      self.updateGutter(jsHintErrors);
      self.updatePane(jsHintErrors);
      this.subscribe(atom.workspaceView, 'cursor:moved', function () {
        if( editor.cursors[0] ){
          self.updateStatus(jsHintErrors, editor.cursors[0].getBufferRow());
        }
      });
      this.subscribe(editor, 'scroll-top-changed', function () {
        self.updateGutter(jsHintErrors);
      });
    } else {
      self.resetState(editor);
    }
  };

  AtomJsHint.prototype.resetState = function(editor){
    this.updateStatus(false);
    this.updateGutter([]);
    this.updatePane([]);
    atom.workspaceView.off('cursor:moved');
    this.unsubscribe(editor);
  };

  AtomJsHint.prototype.updatePane = function(errors){
    $('#jshint-status-pane').remove();
    if( !errors || !atom.config.get('atom-jshint.showErrorPanel') ) return;
    var html = $('
');
    errors.forEach(function(error){
      html.append('Line: ' + error.line + ' Char:' + error.character + ' ' + error.reason);
      html.append('
');
    });
    atom.workspaceView.prependToBottom(html);
  };

  AtomJsHint.prototype.updateGutter = function(errors){
    atom.workspaceView.eachEditorView(function(editorView){
      if (editorView.active) {
        var gutter = editorView.gutter;
        gutter.removeClassFromAllLines('atom-jshint-error');
        errors.forEach(function(error){
          gutter.addClassToLine(error.line - 1, 'atom-jshint-error');
        });
      }
    });
  };

  AtomJsHint.prototype.updateStatus = function(errors, row){
    var status = document.getElementById('jshint-status');
    var msg = '';
    if( status ) status.parentElement.removeChild(status);
    if( !errors ) return;
    if (row >= 0) {
      var lineErrors = errors.filter(function (error) {
        return error.line === row + 1;
      });
      if (lineErrors.length > 0) {
        msg = 'Error: ' + lineErrors[0].line + ':' + lineErrors[0].character + ' ' + lineErrors[0].reason;
      } else {
        msg = errors.length > 0 ? errors.length + ' JSHint error' + (errors.length>1?'s':'') : '';
      }
      atom.workspaceView.statusBar.appendLeft('' + msg + '');
    }
  };

  AtomJsHint.prototype.getContents = function(){
    var filename = atom.workspace.activePaneItem.getUri();
    if( filename.slice(-3) !== '.js' ) return false;
    var text = atom.workspace.activePaneItem.getText();
    if( !text ) return false;
    return text;
  };

  AtomJsHint.prototype.loadConfig = function(){
    if( fs.existsSync(atom.project.path + '/package.json') ){
      var packageJson = require(atom.project.path + '/package.json');
      if( packageJson.jshintConfig ) {
        return this.setConfig(packageJson.jshintConfig);
      }
    }
    if( fs.existsSync(atom.project.path + '/.jshintrc') ){
      var configFile = fs.readFileSync(atom.project.path + '/.jshintrc','UTF8');
      var conf = {};
      try {
        conf = JSON.parse(configFile);
      } catch(e){
        console.error('error parsing config file');
      }
      return this.setConfig(conf);
    }
  };

  AtomJsHint.prototype.setConfig = function(conf){
    var config = {globals:{},options:{}};
    config.globals = conf.globals || {};
    if( conf.global ) { delete conf.globals; }
    config.options = conf;
    this.config = config;
  };

  return AtomJsHint;

})();
<commit_msg>Check for activePaneItem<commit_after>var Subscriber, AtomJshint;
var JSHINT = require('./vendor/jshint').JSHINT;
var Subscriber = require('emissary').Subscriber;
var fs = require('fs');

module.exports = AtomJshint = (function(){

  var $ = require('atom').$;
  function AtomJsHint(){
    atom.workspace.eachEditor((function(self) {
      return function(editor) {
        return self.handleEvents(editor);
      };
    })(this));
    this.config = {globals:{},options:{}};
    this.loadConfig();
  }
  Subscriber.includeInto(AtomJsHint);

  AtomJsHint.prototype.destroy = function(){
    return this.unsubscribe();
  };

  AtomJsHint.prototype.handleEvents = function(editor) {
    var buffer = editor.getBuffer();
    var listenFor = [];
    if( atom.config.get('atom-jshint.hintOnModify') ){ listenFor.push('contents-modified'); }
    if( atom.config.get('atom-jshint.hintOnSave') ) { listenFor.push('saved'); }

    this.subscribe(atom.workspaceView, 'pane-container:active-pane-item-changed', function(){
      this.run(editor);
    }.bind(this));
    this.subscribe(buffer, listenFor.join(' '), (function(self) {
      return function() {
        return buffer.transact(function() {
          self.run(editor);
        });
      };
    })(this));
    this.subscribe(buffer, 'destroyed', (function(self) {
      return function() {
        return self.unsubscribe(buffer);
      };
    })(this));
  };

  AtomJsHint.prototype.run = function(editor){
    var self = this;
    var text = this.getContents();
    if( !text ) {
      this.resetState(editor);
      return;
    }
    if( !JSHINT(text, this.config.options, this.config.globals) ){
      //sometimes jshint creates a null object in the array
      var jsHintErrors = JSHINT.errors.filter(function (error) { return error !== null; });
      if( editor.cursors[0] ){
        self.updateStatus(jsHintErrors, editor.cursors[0].getBufferRow());
      }
      self.updateGutter(jsHintErrors);
      self.updatePane(jsHintErrors);
      this.subscribe(atom.workspaceView, 'cursor:moved', function () {
        if( editor.cursors[0] ){
          self.updateStatus(jsHintErrors, editor.cursors[0].getBufferRow());
        }
      });
      this.subscribe(editor, 'scroll-top-changed', function () {
        self.updateGutter(jsHintErrors);
      });
    } else {
      self.resetState(editor);
    }
  };

  AtomJsHint.prototype.resetState = function(editor){
    this.updateStatus(false);
    this.updateGutter([]);
    this.updatePane([]);
    atom.workspaceView.off('cursor:moved');
    this.unsubscribe(editor);
  };

  AtomJsHint.prototype.updatePane = function(errors){
    $('#jshint-status-pane').remove();
    if( !errors || !atom.config.get('atom-jshint.showErrorPanel') ) return;
    var html = $('
');
    errors.forEach(function(error){
      html.append('Line: ' + error.line + ' Char:' + error.character + ' ' + error.reason);
      html.append('
');
    });
    atom.workspaceView.prependToBottom(html);
  };

  AtomJsHint.prototype.updateGutter = function(errors){
    atom.workspaceView.eachEditorView(function(editorView){
      if (editorView.active) {
        var gutter = editorView.gutter;
        gutter.removeClassFromAllLines('atom-jshint-error');
        errors.forEach(function(error){
          gutter.addClassToLine(error.line - 1, 'atom-jshint-error');
        });
      }
    });
  };

  AtomJsHint.prototype.updateStatus = function(errors, row){
    var status = document.getElementById('jshint-status');
    var msg = '';
    if( status ) status.parentElement.removeChild(status);
    if( !errors ) return;
    if (row >= 0) {
      var lineErrors = errors.filter(function (error) {
        return error.line === row + 1;
      });
      if (lineErrors.length > 0) {
        msg = 'Error: ' + lineErrors[0].line + ':' + lineErrors[0].character + ' ' + lineErrors[0].reason;
      } else {
        msg = errors.length > 0 ? errors.length + ' JSHint error' + (errors.length>1?'s':'') : '';
      }
      atom.workspaceView.statusBar.appendLeft('' + msg + '');
    }
  };

  AtomJsHint.prototype.getContents = function(){
    if( !atom.workspace.activePaneItem ) return false;
    var filename = atom.workspace.activePaneItem.getUri();
    if( filename.slice(-3) !== '.js' ) return false;
    var text = atom.workspace.activePaneItem.getText();
    if( !text ) return false;
    return text;
  };

  AtomJsHint.prototype.loadConfig = function(){
    if( fs.existsSync(atom.project.path + '/package.json') ){
      var packageJson = require(atom.project.path + '/package.json');
      if( packageJson.jshintConfig ) {
        return this.setConfig(packageJson.jshintConfig);
      }
    }
    if( fs.existsSync(atom.project.path + '/.jshintrc') ){
      var configFile = fs.readFileSync(atom.project.path + '/.jshintrc','UTF8');
      var conf = {};
      try {
        conf = JSON.parse(configFile);
      } catch(e){
        console.error('error parsing config file');
      }
      return this.setConfig(conf);
    }
  };

  AtomJsHint.prototype.setConfig = function(conf){
    var config = {globals:{},options:{}};
    config.globals = conf.globals || {};
    if( conf.global ) { delete conf.globals; }
    config.options = conf;
    this.config = config;
  };

  return AtomJsHint;

})();
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {Disposable} from 'event-kit';

import {autobind, extractProps} from '../helpers';
import {RefHolderPropType} from '../prop-types';
import {TextEditorContext} from './atom-text-editor';
import RefHolder from '../models/ref-holder';

const gutterProps = {
  name: PropTypes.string.isRequired,
  priority: PropTypes.number.isRequired,
  visible: PropTypes.bool,
  type: PropTypes.oneOf(['line-number', 'decorated']),
  labelFn: PropTypes.func,
  onMouseDown: PropTypes.func,
  onMouseMove: PropTypes.func,
};

class BareGutter extends React.Component {
  static propTypes = {
    editorHolder: RefHolderPropType.isRequired,
    className: PropTypes.string,
    ...gutterProps,
  }

  static defaultProps = {
    visible: true,
    type: 'decorated',
    labelFn: () => {},
  }

  constructor(props) {
    super(props);
    autobind(this, 'observeEditor', 'forceUpdate');

    this.state = {
      gutter: null,
    };

    this.sub = new Disposable();
  }

  componentDidMount() {
    this.sub = this.props.editorHolder.observe(this.observeEditor);
  }

  componentDidUpdate(prevProps) {
    if (this.props.editorHolder !== prevProps.editorHolder) {
      this.sub.dispose();
      this.sub = this.props.editorHolder.observe(this.observeEditor);
    }
  }

  componentWillUnmount() {
    if (this.state.gutter !== null) {
      this.state.gutter.destroy();
    }
    this.sub.dispose();
  }

  render() {
    return null;
  }

  observeEditor(editor) {
    this.setState((prevState, props) => {
      if (prevState.gutter !== null) {
        prevState.gutter.destroy();
      }

      const options = extractProps(props, gutterProps);
      options.class = props.className;
      return {gutter: editor.addGutter(options)};
    });
  }
}

export default class Gutter extends React.Component {
  static propTypes = {
    editor: PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.state = {
      editorHolder: RefHolder.on(this.props.editor),
    };
  }

  static getDerivedStateFromProps(props, state) {
    const editorChanged = state.editorHolder.map(editor => editor !== props.editor).getOr(props.editor !== undefined);
    return editorChanged ? RefHolder.on(props.editor) : null;
  }

  render() {
    if (!this.state.editorHolder.isEmpty()) {
      return <BareGutter {...this.props} editorHolder={this.state.editorHolder} />;
    }

    return (
      <TextEditorContext.Consumer>
        {editorHolder => (
          <BareGutter {...this.props} editorHolder={editorHolder} />
        )}
      </TextEditorContext.Consumer>
    );
  }
}
<commit_msg>Gutters are sometimes disposed after their containing TextEditors<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {Disposable} from 'event-kit';

import {autobind, extractProps} from '../helpers';
import {RefHolderPropType} from '../prop-types';
import {TextEditorContext} from './atom-text-editor';
import RefHolder from '../models/ref-holder';

const gutterProps = {
  name: PropTypes.string.isRequired,
  priority: PropTypes.number.isRequired,
  visible: PropTypes.bool,
  type: PropTypes.oneOf(['line-number', 'decorated']),
  labelFn: PropTypes.func,
  onMouseDown: PropTypes.func,
  onMouseMove: PropTypes.func,
};

class BareGutter extends React.Component {
  static propTypes = {
    editorHolder: RefHolderPropType.isRequired,
    className: PropTypes.string,
    ...gutterProps,
  }

  static defaultProps = {
    visible: true,
    type: 'decorated',
    labelFn: () => {},
  }

  constructor(props) {
    super(props);
    autobind(this, 'observeEditor', 'forceUpdate');

    this.state = {
      gutter: null,
    };

    this.sub = new Disposable();
  }

  componentDidMount() {
    this.sub = this.props.editorHolder.observe(this.observeEditor);
  }

  componentDidUpdate(prevProps) {
    if (this.props.editorHolder !== prevProps.editorHolder) {
      this.sub.dispose();
      this.sub = this.props.editorHolder.observe(this.observeEditor);
    }
  }

  componentWillUnmount() {
    if (this.state.gutter !== null) {
      try {
        this.state.gutter.destroy();
      } catch (e) {
        // Gutter already destroyed. Disregard.
      }
    }
    this.sub.dispose();
  }

  render() {
    return null;
  }

  observeEditor(editor) {
    this.setState((prevState, props) => {
      if (prevState.gutter !== null) {
        prevState.gutter.destroy();
      }

      const options = extractProps(props, gutterProps);
      options.class = props.className;
      return {gutter: editor.addGutter(options)};
    });
  }
}

export default class Gutter extends React.Component {
  static propTypes = {
    editor: PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.state = {
      editorHolder: RefHolder.on(this.props.editor),
    };
  }

  static getDerivedStateFromProps(props, state) {
    const editorChanged = state.editorHolder.map(editor => editor !== props.editor).getOr(props.editor !== undefined);
    return editorChanged ? RefHolder.on(props.editor) : null;
  }

  render() {
    if (!this.state.editorHolder.isEmpty()) {
      return <BareGutter {...this.props} editorHolder={this.state.editorHolder} />;
    }

    return (
      <TextEditorContext.Consumer>
        {editorHolder => (
          <BareGutter {...this.props} editorHolder={editorHolder} />
        )}
      </TextEditorContext.Consumer>
    );
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import CounterReducer from './counter.reducer';
import { createStore } from 'redux';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

const reducer = new CounterReducer();
const store = createStore(reducer.counter);

const render = () => {
    document.querySelector('.App-intro').innerText = store.getState();
}

store.subscribe(render);
render();

document.addEventListener('click', () => {
    store.dispatch({ type: 'INCREMENT' });
})<commit_msg>Redux: Implementing Store from Scratch<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import CounterReducer from './counter.reducer';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

const createStore = (reducer) => {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = (action) => {
        state = reducer(state, action);
        listeners.forEach(listener => listener());
    };

    const subscribe = (listener) => {
        listeners.push(listener);
        return () => {
            listeners = listeners.filter(l => l !== listener);
        }
    };

    dispatch({});

    return { getState, dispatch, subscribe };
}

const reducer = new CounterReducer();
const store = createStore(reducer.counter);

const render = () => {
    document.querySelector('.App-intro').innerText = store.getState();
}

store.subscribe(render);
render();

document.addEventListener('click', () => {
    store.dispatch({ type: 'INCREMENT' });
})<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import Generator from 'yeoman-generator';
import pkgUp from 'pkg-up';

export default class extends Generator {
  constructor(args, opts) {
    super(args, opts);

    this.options.plugins = [
      'babel-plugin-transform-class-properties',
      'babel-plugin-transform-decorators-legacy',
      'babel-plugin-transform-object-rest-spread'
    ];

    this.options.otherPlugins = [
      [
        'babel-plugin-add-module-exports'
      ],
      [
        'babel-plugin-transform-runtime',
        'babel-plugin-external-helpers',
      ],
    ]
  }

  prompting() {
    return this.prompt([
      {
        type: 'confirm',
        name: 'compile',
        message: 'Compile further after converting with Babel?',
        default: true
      }
    ]).then(answers => {
      Object.assign(this.options, answers);
      this.options.plugins = this.options.otherPlugins[Number(answers.compile)]
                               .concat(this.options.plugins);
    });
  }

  writing() {
    pkgUp(this.destinationRoot()).then(pkgPath => {
      if (pkgPath === null) {
        this.options.dir = path.dirname(pkgPath);
        this._copyRc(this.options.dir + '/.babelrc');
      } else {
        this.options.dir = path.dirname(pkgPath);
        const rcPath = this.options.dir + '/.babelrc';
        try {
          fs.accessSync(rcPath, fs.constants.F_OK);
          fs.readFile(rcPath, 'utf-8', (err, contents) => {
            if (err !== null) {
              throw new Error(`What is wrong with ${rcPath}`);
            }

            try {
              let json = JSON.parse(contents);
              json.plugins = this._writePluginsToPkg(json);
              fs.writeFileSync(rcPath, JSON.stringify(json, null, 2));
            } catch (err) {
              throw new Error(err);
            }
          });
        } catch (err) {
          this._copyRc(rcPath);
        }
      }
    });
  }

  _copyRc(dest) {
    this.fs.copyTpl(
      this.templatePath('.babelrc'),
      dest,
      this.options
    );
  }

  _filterName(plugins) {
    return plugins.map(p => p.replace('babel-plugin-', ''));
  }

  _writePluginsToPkg(json) {
    const rcNames = this._filterName(this.options.plugins)
    rcNames.forEach(name => {
      if (json.plugins.indexOf(name) === -1) {
        json.plugins.push(name);
      }
    });

    const target = this.options.otherPlugins[Number(!this.options.compile)];
    const disablesNames = this._filterName(target);
    const filtered = json.plugins.filter(p => {
      return disablesNames.indexOf(p) === -1;
    });

    return filtered;
  }

  install() {
    process.chdir(this.options.dir);
    this.yarnInstall(this.options.plugins)
  }
}
<commit_msg>Fix lint<commit_after>import fs from 'fs';
import path from 'path';
import Generator from 'yeoman-generator';
import pkgUp from 'pkg-up';

export default class extends Generator {
  constructor(args, opts) {
    super(args, opts);

    this.options.plugins = [
      'babel-plugin-transform-class-properties',
      'babel-plugin-transform-decorators-legacy',
      'babel-plugin-transform-object-rest-spread'
    ];

    this.options.otherPlugins = [
      [
        'babel-plugin-add-module-exports'
      ],
      [
        'babel-plugin-transform-runtime',
        'babel-plugin-external-helpers'
      ]
    ];
  }

  prompting() {
    return this.prompt([
      {
        type: 'confirm',
        name: 'compile',
        message: 'Compile further after converting with Babel?',
        default: true
      }
    ]).then(answers => {
      Object.assign(this.options, answers);
      this.options.plugins = this.options.otherPlugins[Number(answers.compile)]
                               .concat(this.options.plugins);
    });
  }

  writing() {
    pkgUp(this.destinationRoot()).then(pkgPath => {
      if (pkgPath === null) {
        this.options.dir = path.dirname(pkgPath);
        this._copyRc(this.options.dir + '/.babelrc');
      } else {
        this.options.dir = path.dirname(pkgPath);
        const rcPath = this.options.dir + '/.babelrc';
        try {
          fs.accessSync(rcPath, fs.constants.F_OK);
          fs.readFile(rcPath, 'utf-8', (err, contents) => {
            if (err !== null) {
              throw new Error(`What is wrong with ${rcPath}`);
            }

            try {
              const json = JSON.parse(contents);
              json.plugins = this._writePluginsToPkg(json);
              fs.writeFileSync(rcPath, JSON.stringify(json, null, 2));
            } catch (err) {
              throw new Error(err);
            }
          });
        } catch (err) {
          this._copyRc(rcPath);
        }
      }
    });
  }

  _copyRc(dest) {
    this.fs.copyTpl(
      this.templatePath('.babelrc'),
      dest,
      this.options
    );
  }

  _filterName(plugins) {
    return plugins.map(p => p.replace('babel-plugin-', ''));
  }

  _writePluginsToPkg(json) {
    const rcNames = this._filterName(this.options.plugins);
    rcNames.forEach(name => {
      if (json.plugins.indexOf(name) === -1) {
        json.plugins.push(name);
      }
    });

    const target = this.options.otherPlugins[Number(!this.options.compile)];
    const disablesNames = this._filterName(target);
    const filtered = json.plugins.filter(p => {
      return disablesNames.indexOf(p) === -1;
    });

    return filtered;
  }

  install() {
    process.chdir(this.options.dir);
    this.yarnInstall(this.options.plugins);
  }
}
<|endoftext|>


<commit_before>module.exports = function init_request_handler(ip_or_host_url, port_num, server_type_str){

    const colors = require('./colors.js');
    function green(string){return colors.fg.green + string + colors.reset}
    function ret_false_if_undefined(bool){//return false if bool is not true or undefined
        if(bool) return bool;
        else return false;
    }
    let jsResp = function(){
        return "function str_random_gen(len){ "+
        "Array.prototype.fill||Object.defineProperty(Array.prototype,'fill',{value:function(t){if(null==this)throw new TypeError('this is null or not defined');for(var r=Object(this),e=r.length>>>0,i=arguments[1]>>0,n=i<0?Math.max(e+i,0):Math.min(i,e),o=arguments[2],a=void 0===o?e:o>>0,l=a<0?Math.max(e+a,0):Math.min(a,e);n<l;)r[n]=t,n++;return r}}); "+
        "let aZ = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; "+
        "let arr = new Array(len).fill(0); "+
        "return arr.map(function(x,i,a){ "+
        "return aZ[Math.floor(Math.random() * aZ.length)]; "+
        "}).join(''); "+
        "} "+
        "let browser_code = str_random_gen(10); "+
        "let src_string = 'http://localhost:1337/watch_refresh_client_script_'+browser_code+'.js'; "+
        "console.log('watch_refresh app code:', browser_code, 'https://www.npmjs.com/package/watch_refresh for info'); "+
        "let script_ele = document.createElement('script'); "+
        "function watch_refresh_cb_XYZ54(refresh_bool){ "+
        "if(refresh_bool === true)location.reload(); "+
        "if(script_ele.parentNode) script_ele.parentNode.removeChild(script_ele); "+
        "script_ele = undefined; "+
        "script_ele = document.createElement('script'); "+
        "script_ele.src = src_string; "+
        "setTimeout(function(){ "+
        "document.body.appendChild(script_ele); "+
        "}, 1000); "+
        "} "+
        "script_ele.src = src_string; "+
        "document.body.appendChild(script_ele); "
    }()

    if(ip_or_host_url === "127.0.0.1"){
        jsResp = jsResp.replace(
            "http://localhost:1337/watch_refresh_client_script_",
            server_type_str+"://localhost:"+port_num+"/watch_refresh_client_script_"
        )
    }else{
        jsResp = jsResp.replace(
            "http://localhost:1337/watch_refresh_client_script_",
            server_type_str+"://"+ip_or_host_url+":"+port_num+"/watch_refresh_client_script_"
        )

    }

    //random 10 digit keys are generated client side to identify each connecting browser
    let refresh_bools = {};
    let refresh_bools_times = {};
    let last_refresh_time = new Date()
    //this removes all old stored keys that were not used 10 seconds after a change was detected
    function clean_old_refresh_bool_keys(){
        setTimeout(
            ()=>{
                let refresh_bools_keys = Object.keys(refresh_bools_times)
                refresh_bools_keys.map((key)=>{
                    if(refresh_bools_times[key] !== last_refresh_time){
                        delete refresh_bools[key];
                        delete refresh_bools_times[key];
                    }
                })
            }
        , 10000)
    }
    return {
        //sets all keys to true //meaning these browsers must be refreshed
        refresh_true:function (){
            let refresh_bools_keys = Object.keys(refresh_bools)
            refresh_bools_keys.map((key)=>{
                refresh_bools[key] = true;
                let last_refresh_time = new Date()
                refresh_bools_times[key] = new Date(last_refresh_time.getTime())
            })
            clean_old_refresh_bool_keys()
        },

        request_handler:function(req, res){
            if(req.url === "/watch_refresh_client_script_init.js"){
                res.writeHead(200, {"Content-Type":"text/javascript"});
                res.write(jsResp)
            }else{
                if(req.url.indexOf("/watch_refresh_client_script_") !== -1){
                    //collect browser_code out of req.url
                    let browser_code = req.url + ""
                    browser_code = browser_code.replace("/watch_refresh_client_script_", "")
                    browser_code = browser_code.replace(".js", "")
                    if(browser_code.length === 10){//code length must be 10
                        res.writeHead(200, {"Content-Type":"text/javascript" , "Cache-Control": "no-cache"});//prevent form caching the script
                        res.write("watch_refresh_cb_XYZ54("+ret_false_if_undefined(refresh_bools[browser_code])+");")
                        if(refresh_bools[browser_code]){
                            //remove keys if it was set to true
                            delete refresh_bools[browser_code];
                            delete refresh_bools_times[browser_code];
                        }else{
                            //add key if it didnt exist
                            if(refresh_bools[browser_code] === undefined) console.log(green("added brwoser_code:") + browser_code + green(" to refresh_list"))
                            refresh_bools[browser_code] = false;
                        }
                    }
                }
            }
            res.end()
        }
    }

}<commit_msg>ipfix_chrome<commit_after>module.exports = function init_request_handler(ip_or_host_url, port_num, server_type_str){

    const colors = require('./colors.js');
    function green(string){return colors.fg.green + string + colors.reset}
    function ret_false_if_undefined(bool){//return false if bool is not true or undefined
        if(bool) return bool;
        else return false;
    }
    let jsResp = function(){
        return "function str_random_gen(len){ "+
        "Array.prototype.fill||Object.defineProperty(Array.prototype,'fill',{value:function(t){if(null==this)throw new TypeError('this is null or not defined');for(var r=Object(this),e=r.length>>>0,i=arguments[1]>>0,n=i<0?Math.max(e+i,0):Math.min(i,e),o=arguments[2],a=void 0===o?e:o>>0,l=a<0?Math.max(e+a,0):Math.min(a,e);n<l;)r[n]=t,n++;return r}}); "+
        "let aZ = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; "+
        "let arr = new Array(len).fill(0); "+
        "return arr.map(function(x,i,a){ "+
        "return aZ[Math.floor(Math.random() * aZ.length)]; "+
        "}).join(''); "+
        "} "+
        "let browser_code = str_random_gen(10); "+
        "let src_string = 'http://localhost:1337/watch_refresh_client_script_'+browser_code+'.js'; "+
        "console.log('watch_refresh app code:', browser_code, 'https://www.npmjs.com/package/watch_refresh for info'); "+
        "let script_ele = document.createElement('script'); "+
        "function watch_refresh_cb_XYZ54(refresh_bool){ "+
        "if(refresh_bool === true)location.reload(); "+
        "if(script_ele.parentNode) script_ele.parentNode.removeChild(script_ele); "+
        "script_ele = undefined; "+
        "script_ele = document.createElement('script'); "+
        "script_ele.src = src_string; "+
        "setTimeout(function(){ "+
        "document.body.appendChild(script_ele); "+
        "}, 1000); "+
        "} "+
        "script_ele.src = src_string; "+
        "document.body.appendChild(script_ele); "
    }()

    switch(ip_or_host_url){
        case "127.0.0.1" : {
            jsResp = jsResp.replace(
                "http://localhost:1337/watch_refresh_client_script_",
                server_type_str+"://"+"localhost"+":"+port_num+"/watch_refresh_client_script_"
            )
            break;
        }
        case "localhost" : {
            jsResp = jsResp.replace(
                "http://localhost:1337/watch_refresh_client_script_",
                server_type_str+"://"+"localhost"+":"+port_num+"/watch_refresh_client_script_"
            )
            break;
        }
        default : {
            jsResp = jsResp.replace(
                "http://localhost:1337/watch_refresh_client_script_",
                server_type_str+"://"+ip_or_host_url+":"+port_num+"/watch_refresh_client_script_"
            )
        }
    }

    //random 10 digit keys are generated client side to identify each connecting browser
    let refresh_bools = {};
    let refresh_bools_times = {};
    let last_refresh_time = new Date()
    //this removes all old stored keys that were not used 10 seconds after a change was detected
    function clean_old_refresh_bool_keys(){
        setTimeout(
            ()=>{
                let refresh_bools_keys = Object.keys(refresh_bools_times)
                refresh_bools_keys.map((key)=>{
                    if(refresh_bools_times[key] !== last_refresh_time){
                        delete refresh_bools[key];
                        delete refresh_bools_times[key];
                    }
                })
            }
        , 10000)
    }
    return {
        //sets all keys to true //meaning these browsers must be refreshed
        refresh_true:function (){
            let refresh_bools_keys = Object.keys(refresh_bools)
            refresh_bools_keys.map((key)=>{
                refresh_bools[key] = true;
                let last_refresh_time = new Date()
                refresh_bools_times[key] = new Date(last_refresh_time.getTime())
            })
            clean_old_refresh_bool_keys()
        },

        request_handler:function(req, res){
            if(req.url === "/watch_refresh_client_script_init.js"){
                res.writeHead(200, {"Content-Type":"text/javascript"});
                res.write(jsResp)
            }else{
                if(req.url.indexOf("/watch_refresh_client_script_") !== -1){
                    //collect browser_code out of req.url
                    let browser_code = req.url + ""
                    browser_code = browser_code.replace("/watch_refresh_client_script_", "")
                    browser_code = browser_code.replace(".js", "")
                    if(browser_code.length === 10){//code length must be 10
                        res.writeHead(200, {"Content-Type":"text/javascript" , "Cache-Control": "no-cache"});//prevent form caching the script
                        res.write("watch_refresh_cb_XYZ54("+ret_false_if_undefined(refresh_bools[browser_code])+");")
                        if(refresh_bools[browser_code]){
                            //remove keys if it was set to true
                            delete refresh_bools[browser_code];
                            delete refresh_bools_times[browser_code];
                        }else{
                            //add key if it didnt exist
                            if(refresh_bools[browser_code] === undefined) console.log(green("added brwoser_code:") + browser_code + green(" to refresh_list"))
                            refresh_bools[browser_code] = false;
                        }
                    }
                }
            }
            res.end()
        }
    }

}<|endoftext|>


<commit_before>'use strict';

var $ = {
  _: require('lodash'),
  'bower-config': require('bower-config'),
  chalk: require('chalk'),
  fs: require('fs'),
  glob: require('glob'),
  lodash: require('lodash'),
  path: require('path'),
  through2: require('through2')
};

var helpers = require('./lib/helpers');
var fileTypesDefault = require('./lib/default-file-types');

/**
 * Wire up the html files with the Bower packages.
 *
 * @param  {object} config  the global configuration object
 */
function wiredep(opts) {
  opts = opts || {};

  var cwd = opts.cwd ? $.path.resolve(opts.cwd) : process.cwd();

  var config = module.exports.config = helpers.createStore();

  config.set
    ('require.json', opts.requireJson || JSON.parse($.fs.readFileSync($.path.join(cwd, './require.json'))))
    ('cwd', cwd)
    ('detectable-file-types', [])
    ('exclude', Array.isArray(opts.exclude) ? opts.exclude : [ opts.exclude ])
    ('file-types', mergeFileTypesWithDefaults(opts.fileTypes))
    ('ignore-path', opts.ignorePath)
    ('src', [])
    ('stream', opts.stream ? opts.stream : {})
    ('warnings', []);

  if (!opts.stream && opts.src) {
    (Array.isArray(opts.src) ? opts.src : [opts.src]).
      forEach(function (pattern) {
        config.set('src', config.get('src').concat($.glob.sync(pattern)));
      });
  }

  console.log("OPT-SRC", opts.src);
  console.log("SRC", config.get('src'));

  require('./lib/require-structure-generator')(config);
  require('./lib/inject-dependencies')(config);

  if (config.get('warnings')) {
    helpers.warn(config.get('warnings'));
  }

  // return config.get('stream').src ||
  //   Object.keys(config.get('global-dependencies-sorted')).
  //     reduce(function (acc, depType) {
  //       if (config.get('global-dependencies-sorted')[depType].length) {
  //         acc[depType] = config.get('global-dependencies-sorted')[depType];
  //       }

  //       return acc;
  //     }, { packages: config.get('global-dependencies').get() });
}

function mergeFileTypesWithDefaults(optsFileTypes) {
  var fileTypes = $._.clone(fileTypesDefault, true);

  $._(optsFileTypes).each(function (fileTypeConfig, fileType) {
    fileTypes[fileType] = fileTypes[fileType] || {};
    $._.each(fileTypeConfig, function (config, configKey) {
      if ($._.isPlainObject(fileTypes[fileType][configKey])) {
        fileTypes[fileType][configKey] =
          $._.assign(fileTypes[fileType][configKey], config);
      } else {
        fileTypes[fileType][configKey] = config;
      }
    });
  });

  return fileTypes;
}

wiredep.stream = function (opts) {
  opts = opts || {};

  return $.through2.obj(function (file, enc, cb) {
    if (file.isNull()) {
      this.push(file);
      return cb();
    }

    if (file.isStream()) {
      this.emit('error', 'Streaming not supported');
      return cb();
    }

    try {
      opts.stream = {
        src: file.contents.toString(),
        path: file.path,
        fileType: $.path.extname(file.path).substr(1)
      };

      file.contents = new Buffer(wiredep(opts));
    } catch (err) {
      this.emit('error', err);
    }

    this.push(file);
    cb();
  });
};

module.exports = wiredep;
<commit_msg>Remove of ignore path and exclude and also temporary comment stream support<commit_after>'use strict';

var $ = {
  _: require('lodash'),
  'bower-config': require('bower-config'),
  chalk: require('chalk'),
  fs: require('fs'),
  glob: require('glob'),
  lodash: require('lodash'),
  path: require('path'),
  through2: require('through2')
};

var helpers = require('./lib/helpers');
var fileTypesDefault = require('./lib/default-file-types');

/**
 * Wire up the html files with the Bower packages.
 *
 * @param  {object} config  the global configuration object
 */
function require_wiredep(opts) {
  opts = opts || {};

  var cwd = opts.cwd ? $.path.resolve(opts.cwd) : process.cwd();

  var config = module.exports.config = helpers.createStore();

  config.set
    ('require.json', opts.requireJson || JSON.parse($.fs.readFileSync($.path.join(cwd, './require.json'))))
    ('cwd', cwd)
    ('detectable-file-types', [])
    ('file-types', mergeFileTypesWithDefaults(opts.fileTypes))
    ('src', [])
    ('stream', opts.stream ? opts.stream : {})
    ('warnings', []);

  if (!opts.stream && opts.src) {
    (Array.isArray(opts.src) ? opts.src : [opts.src]).
      forEach(function (pattern) {
        config.set('src', config.get('src').concat($.glob.sync(pattern)));
      });
  }

  require('./lib/require-structure-generator')(config);
  require('./lib/inject-dependencies')(config);

  if (config.get('warnings')) {
    helpers.warn(config.get('warnings'));
  }

  return "Testowe";
}

function mergeFileTypesWithDefaults(optsFileTypes) {
  var fileTypes = $._.clone(fileTypesDefault, true);

  $._(optsFileTypes).each(function (fileTypeConfig, fileType) {
    fileTypes[fileType] = fileTypes[fileType] || {};
    $._.each(fileTypeConfig, function (config, configKey) {
      if ($._.isPlainObject(fileTypes[fileType][configKey])) {
        fileTypes[fileType][configKey] =
          $._.assign(fileTypes[fileType][configKey], config);
      } else {
        fileTypes[fileType][configKey] = config;
      }
    });
  });

  return fileTypes;
}

// require_wiredep.stream = function (opts) {
//   opts = opts || {};

//   return $.through2.obj(function (file, enc, cb) {
//     if (file.isNull()) {
//       this.push(file);
//       return cb();
//     }

//     if (file.isStream()) {
//       this.emit('error', 'Streaming not supported');
//       return cb();
//     }

//     try {
//       opts.stream = {
//         src: file.contents.toString(),
//         path: file.path,
//         fileType: $.path.extname(file.path).substr(1)
//       };

//       file.contents = new Buffer(wiredep(opts));
//     } catch (err) {
//       this.emit('error', err);
//     }

//     this.push(file);
//     cb();
//   });
// };

module.exports = require_wiredep;
<|endoftext|>


<commit_before>/*globals formSerialize, JsonRefs, IMF, getJSON, jml, URLSearchParams*/
/*jslint vars:true, todo:true*/
(function () {'use strict';

// Todo: change $ref usages to utilize JSON Reference ( https://github.com/whitlockjc/json-refs ) + JSON Pointer-aware library ( https://github.com/manuelstofer/json-pointer ?)

document.title = "Sacred Writings Browser";

// Need for directionality even if language specified (and we don't want to require it as a param)
getJSON('appdata/languages.json', function (langData) {

var langs = langData.languages;

function getDirectionForLanguageCode (code) {
    return langs.find(function (lang) {
        return lang.code === code;
    }).direction;
}

function paramChange () {

    document.body.parentNode.replaceChild(document.createElement('body'), document.body);

    var params = new URLSearchParams(location.hash.slice(1));
    function $p (param) {
        return params.get(param);
    }
    function followParams () {
        location.hash = '#' + params.toString();
    }

    var language = $p('lang');

    if (!language) {
        jml('div', {'class': 'focus'},
            [['select', {size: langs.length, $on: {change: function (e) {
                params.set('lang', e.target.selectedOptions[0].value);
                followParams();
            }}}, langs.map(function (lang) {
                return ['option', {value: lang.code}, [lang.name]];
            })]], document.body

            /* Works too:
            langs.map(function (lang) {
                return ['div', [
                    ['a', {href: '#', dataset: {code: lang.code}}, [lang.name]]
                ]];
            }), document.body
            */
        );
        return;
    }

    var lang = language.split('.');

    var work = $p('work');
    var result = $p('result');

    function workSelect (l, defineFormatter) {

        var ta = defineFormatter('tablealias');

        var direction = getDirectionForLanguageCode(lang[0]);

        getJSON('appdata/files.json', function (dbs) {
            var fileGroups = dbs.groups;
            function getMetadata (file, property, cb) {
                var currDir = window.location.href.replace(/(index\.html)?#.*$/, '');
                JsonRefs.resolveRefs({$ref: currDir + file + (property ? '#/' + property : '') }, {
                    // Temporary fix for lack of resolution of relative references: https://github.com/whitlockjc/json-refs/issues/11
                    processContent: function (content) {
                        var json = JSON.parse(content);
                        Object.keys(JsonRefs.findRefs(json)).forEach(function (path) {
                            var lastParent;
                            var value = JsonRefs.pathFromPointer(path).reduce(function (json, pathSeg) {
                                lastParent = json;
                                return json[pathSeg];
                            }, json);
                            lastParent.$ref = currDir + file.slice(0, file.lastIndexOf('/') + 1) + value;
                        });
                        return json;
                    }
                },
                function (err, rJson, metadata) {
                    if (err) {throw err;}
                    cb(rJson, metadata);
                });
            }
            jml(
                'div',
                {'class': 'focus ' + direction},
                fileGroups.map(function (fileGroup, i) {
                    return ['div', [
                        (i > 0 ? ['br', 'br', 'br'] : ''),
                        ['div', [l(fileGroup.directions)]],
                        ['br'],
                        ['select', {'class': 'file', dataset: {name: fileGroup.name}, $on: {change: function (e) {
                            // Submit
                            // alert(e.target.dataset.name);

                            // Use the following to dynamically add specific file schema in place of generic table schema if validating against files.jsonschema
                            // filesSchema.properties.groups.items.properties.files.items.properties.file.anyOf.splice(1, 1, {$ref: schemaFile});

                            var dataset = e.target.selectedOptions[0].dataset;
                            var schemaFile = dataset.schemaFile;
                            var metadataFile = dataset.metadataFile;

                            /*
                            params.set('file', dataset.file);
                            params.set();
                            params.set();
                            followParams();
                            */

                            var schemaProperty = '', metadataProperty = '';

                            if (!dataset.schemaFile) {
                                schemaFile = dataset.file;
                                schemaProperty = 'schema';
                            }
                            if (!dataset.metadataFile) {
                                metadataFile = dataset.file;
                                metadataProperty = 'metadata';
                            }

                            getMetadata(schemaFile, schemaProperty, function (schema) {
                                getMetadata(metadataFile, metadataProperty, function (metadata) {

                                    // todo: alias fields

                                    alert('1:'+JSON.stringify(schema));
                                    alert('2:'+JSON.stringify(metadata));

                                });
                            });
                        }}},
                            fileGroup.files.map(function (file) {
                                // Todo: Allow use of dbs and fileGroup together in base directories?
                                var baseDir = (dbs.baseDirectory || fileGroup.baseDirectory) + '/';
                                var schemaBaseDir = (dbs.schemaBaseDirectory || fileGroup.schemaBaseDirectory) + '/';
                                var metadataBaseDir = (dbs.schemaBaseDirectory || fileGroup.schemaBaseDirectory) + '/';
                                return ['option', {
                                    value: file.name,
                                    dataset: {
                                        file: baseDir + file.file.$ref,
                                        schemaFile: file.schemaFile ? (schemaBaseDir + file.schemaFile) : '',
                                        metadataFile: file.metadataFile ? (metadataBaseDir + file.metadataFile) : ''
                                    }
                                }, [ta(file.name)]];
                            })
                        ],
                        ['p', [
                            ['input', {type: 'button', value: "Go"}]
                        ]]
                    ]];
                }),
                document.body
            );
        }, function (err) {
            alert(err);
        });

        /*
        Add back to files.json when overcome memory issue when exporting to JSON from BL
        ,
        {
            "name": "Other Writings",
            "directions": "choosewritings_bahai_writingsotherdb",
            "baseDirectory": "other-works",
            "files": [
                {"file": "Collins.json", "name": "collins"},
                {"file": "lights.json", "name": "lights"}
            ]
        }
        */
    }

    function displayWork (l, defineFormatter) {

    }

    function displayResults (l, defineFormatter) {

    }

    function localeCallback () {
        if (!work) {
            workSelect.apply(null, arguments);
            return;
        }
        if (!result) {
            displayWork.apply(null, arguments);
            return;
        }

        displayResults.apply(null, arguments);
    }

    IMF({
        languages: lang,
        localeFileResolver: function (code) {
            return langData.localeFileBasePath + langs.find(function (lang) {
                return lang.code === code;
            }).locale.$ref; // Todo: We might instead resolve all $ref (as with https://github.com/whitlockjc/json-refs ) and replace IMF() loadLocales behavior with our own now resolved locales; see https://github.com/jdorn/json-editor/issues/132
        },
        callback: localeCallback
    });

}

// INIT/ADD EVENTS

paramChange();
window.addEventListener('hashchange', paramChange, false);

}, function (err) {
    alert(err);
});

}());
<commit_msg>allow work name in URL (toward displaying work options)<commit_after>/*globals formSerialize, JsonRefs, IMF, getJSON, jml, URLSearchParams*/
/*jslint vars:true, todo:true*/
(function () {'use strict';

// Todo: change $ref usages to utilize JSON Reference ( https://github.com/whitlockjc/json-refs ) + JSON Pointer-aware library ( https://github.com/manuelstofer/json-pointer ?)

document.title = "Sacred Writings Browser";

// We use getJSON instead of JsonRefs as we do not need to resolve the locales here
// Need for directionality even if language specified (and we don't want to require it as a param)
getJSON('appdata/languages.json', function (langData) {

var langs = langData.languages;

function getDirectionForLanguageCode (code) {
    return langs.find(function (lang) {
        return lang.code === code;
    }).direction;
}

function paramChange () {

    document.body.parentNode.replaceChild(document.createElement('body'), document.body);

    var params = new URLSearchParams(location.hash.slice(1));
    function $p (param) {
        return params.get(param);
    }
    function followParams () {
        location.hash = '#' + params.toString();
    }

    var language = $p('lang');

    if (!language) {
        jml('div', {'class': 'focus'},
            [['select', {size: langs.length, $on: {change: function (e) {
                params.set('lang', e.target.selectedOptions[0].value);
                followParams();
            }}}, langs.map(function (lang) {
                return ['option', {value: lang.code}, [lang.name]];
            })]], document.body

            /* Works too:
            langs.map(function (lang) {
                return ['div', [
                    ['a', {href: '#', dataset: {code: lang.code}}, [lang.name]]
                ]];
            }), document.body
            */
        );
        return;
    }

    var lang = language.split('.');

    var work = $p('work');
    var result = $p('result');

    function workSelect (l, defineFormatter) {

        var direction = getDirectionForLanguageCode(lang[0]);

        // We use getJSON instead of JsonRefs as we do not necessarily need to resolve the file contents here
        getJSON('appdata/files.json', function (dbs) {
            var fileGroups = dbs.groups;

            var ta = defineFormatter('tablealias');
            jml(
                'div',
                {'class': 'focus ' + direction},
                fileGroups.map(function (fileGroup, i) {
                    return ['div', [
                        (i > 0 ? ['br', 'br', 'br'] : ''),
                        ['div', [l(fileGroup.directions)]],
                        ['br'],
                        ['select', {'class': 'file', dataset: {name: fileGroup.name}, $on: {change: function (e) {
                            params.set('work', e.target.value);
                            followParams();
                        }}}, fileGroup.files.map(function (file) {
                            return ['option', {value: file.name}, [ta(file.name)]];
                        })],
                        ['p', [
                            ['input', {type: 'button', value: "Go"}]
                        ]]
                    ]];
                }),
                document.body
            );
        }, function (err) {
            alert(err);
        });

        /*
        Add back to files.json when overcome memory issue when exporting to JSON from BL
        ,
        {
            "name": "Other Writings",
            "directions": "choosewritings_bahai_writingsotherdb",
            "baseDirectory": "other-works",
            "files": [
                {"file": "Collins.json", "name": "collins"},
                {"file": "lights.json", "name": "lights"}
            ]
        }
        */
    }

    function displayWork (l, defineFormatter) {
        getJSON('appdata/files.json', function (dbs) {

            // Use the following to dynamically add specific file schema in place of generic table schema if validating against files.jsonschema
            // filesSchema.properties.groups.items.properties.files.items.properties.file.anyOf.splice(1, 1, {$ref: schemaFile});
            // Todo: Allow use of dbs and fileGroup together in base directories?
            function getMetadata (file, property, cb) {
                var currDir = window.location.href.replace(/(index\.html)?#.*$/, '');
                JsonRefs.resolveRefs({$ref: currDir + file + (property ? '#/' + property : '') }, {
                    // Temporary fix for lack of resolution of relative references: https://github.com/whitlockjc/json-refs/issues/11
                    processContent: function (content) {
                        var json = JSON.parse(content);
                        Object.keys(JsonRefs.findRefs(json)).forEach(function (path) {
                            var lastParent;
                            var value = JsonRefs.pathFromPointer(path).reduce(function (json, pathSeg) {
                                lastParent = json;
                                return json[pathSeg];
                            }, json);
                            lastParent.$ref = currDir + file.slice(0, file.lastIndexOf('/') + 1) + value;
                        });
                        return json;
                    }
                },
                function (err, rJson, metadata) {
                    if (err) {throw err;}
                    cb(rJson, metadata);
                });
            }

            var fileData;
            var fileGroup = dbs.groups.find(function (fileGroup) {
                fileData = fileGroup.files.find(function (file) {
                    return work === file.name;
                });
                return !!fileData;
            });

            var baseDir = (dbs.baseDirectory || fileGroup.baseDirectory) + '/';
            var schemaBaseDir = (dbs.schemaBaseDirectory || fileGroup.schemaBaseDirectory) + '/';
            var metadataBaseDir = (dbs.schemaBaseDirectory || fileGroup.schemaBaseDirectory) + '/';

            var file = baseDir + fileData.file.$ref;
            var schemaFile = fileData.schemaFile ? (schemaBaseDir + fileData.schemaFile) : '';
            var metadataFile = fileData.metadataFile ? (metadataBaseDir + fileData.metadataFile) : '';

            var schemaProperty = '', metadataProperty = '';

            if (!schemaFile) {
                schemaFile = file;
                schemaProperty = 'schema';
            }
            if (!metadataFile) {
                metadataFile = file;
                metadataProperty = 'metadata';
            }

            getMetadata(schemaFile, schemaProperty, function (schema) {
                getMetadata(metadataFile, metadataProperty, function (metadata) {

                    // todo: alias fields

                    alert('1:'+JSON.stringify(schema));
                    alert('2:'+JSON.stringify(metadata));

                });
            });

        }, function (err) {
            alert(err);
        });
    }

    function displayResults (l, defineFormatter) {

    }

    function localeCallback () {
        if (!work) {
            workSelect.apply(null, arguments);
            return;
        }
        if (!result) {
            displayWork.apply(null, arguments);
            return;
        }

        displayResults.apply(null, arguments);
    }

    IMF({
        languages: lang,
        localeFileResolver: function (code) {
            return langData.localeFileBasePath + langs.find(function (lang) {
                return lang.code === code;
            }).locale.$ref; // Todo: We might instead resolve all $ref (as with https://github.com/whitlockjc/json-refs ) and replace IMF() loadLocales behavior with our own now resolved locales; see https://github.com/jdorn/json-editor/issues/132
        },
        callback: localeCallback
    });

}

// INIT/ADD EVENTS

paramChange();
window.addEventListener('hashchange', paramChange, false);

}, function (err) {
    alert(err);
});

}());
<|endoftext|>


<commit_before>/**
 * Import gulp and the settings object
 */

var gulp = require('gulp');
var settings = require('./settings');

/**
 * Import gulp tasks
 */

var js = require('./js');
var css = require('./css');
var public = require('./public');
var serve = require('./serve');
var assets = require('./assets');
var clean = require('./clean');
var test = require('./test');

/**
 * Register tasks in gulp
 */

gulp

  /**
   * JavaScript related tasks
   */

  .task('js:lint', js.lint)
  .task('js:build', ['public'], js.build)
  .task('js:dist', ['public'], js.dist)
  .task('js:watch', ['public'], js.watch)

  /**
   * CSS related tasks
   */

  .task('css:lint', css.lint)
  .task('css:build', css.build)
  .task('css:dist', css.dist)
  .task('css:watch', ['css:build'], css.watch)

  /**
   * Copy assets (images, fonts)
   */

  .task('assets', ['public'], assets)
  .task('public', public)

  /**
   * Delete generated files
   */

  .task('clean', clean)

  /**
   * Start server
   */

  .task('serve', serve)

  /**
   * Bulk tasks
   */

  .task('watch', ['js:watch', 'css:watch'])
  .task('build', ['js:build', 'css:build', 'assets'])

  /**
   * Build/watch/serve
   */

  .task('bws', ['assets', 'watch', 'serve'])
  .task('default', ['build', 'serve'])
<commit_msg>disable tests temporarly #1220<commit_after>/**
 * Import gulp and the settings object
 */

var gulp = require('gulp');
var settings = require('./settings');

/**
 * Import gulp tasks
 */

var js = require('./js');
var css = require('./css');
var public = require('./public');
var serve = require('./serve');
var assets = require('./assets');
var clean = require('./clean');
// var test = require('./test');

/**
 * Register tasks in gulp
 */

gulp

  /**
   * JavaScript related tasks
   */

  .task('js:lint', js.lint)
  .task('js:build', ['public'], js.build)
  .task('js:dist', ['public'], js.dist)
  .task('js:watch', ['public'], js.watch)

  /**
   * CSS related tasks
   */

  .task('css:lint', css.lint)
  .task('css:build', css.build)
  .task('css:dist', css.dist)
  .task('css:watch', ['css:build'], css.watch)

  /**
   * Copy assets (images, fonts)
   */

  .task('assets', ['public'], assets)
  .task('public', public)

  /**
   * Delete generated files
   */

  .task('clean', clean)

  /**
   * Start server
   */

  .task('serve', serve)

  /**
   * Bulk tasks
   */

  .task('watch', ['js:watch', 'css:watch'])
  .task('build', ['js:build', 'css:build', 'assets'])

  /**
   * Build/watch/serve
   */

  .task('bws', ['assets', 'watch', 'serve'])
  .task('default', ['build', 'serve'])
<|endoftext|>


<commit_before>/* @flow */

import { CompositeDisposable } from 'sb-event-kit'
import type { Linter } from './types'

export default class BusySignal {
  provider: ?Object;
  executing: Set<{
    linter: Linter,
    filePath: ?string,
  }>;
  subscriptions: CompositeDisposable;

  constructor() {
    this.executing = new Set()
    this.subscriptions = new CompositeDisposable()
  }
  attach(registry: Object) {
    this.provider = registry.create()
    this.update()
  }
  update() {
    const provider = this.provider
    if (!provider) {
      return
    }
    provider.clear()
    const fileMap: Map<?string, Array<string>> = new Map()

    for (const { filePath, linter } of this.executing) {
      let names = fileMap.get(filePath)
      if (!names) {
        fileMap.set(filePath, names = [])
      }
      names.push(linter.name)
    }

    for (const [filePath, names] of fileMap) {
      const path = filePath ? ` on ${atom.project.relativizePath(filePath)[1]}` : ''
      provider.add(`${names.join(', ')}${path}`)
    }
    fileMap.clear()
  }
  getExecuting(linter: Linter, filePath: ?string): ?Object {
    for (const entry of this.executing) {
      if (entry.linter === linter && entry.filePath === filePath) {
        return entry
      }
    }
    return null
  }
  didBeginLinting(linter: Linter, filePath: ?string) {
    if (this.getExecuting(linter, filePath)) {
      return
    }
    this.executing.add({ linter, filePath })
    this.update()
  }
  didFinishLinting(linter: Linter, filePath: ?string) {
    const entry = this.getExecuting(linter, filePath)
    if (entry) {
      this.executing.delete(entry)
      this.update()
    }
  }
  dispose() {
    if (this.provider) {
      this.provider.clear()
    }
    this.executing.clear()
    this.subscriptions.dispose()
  }
}
<commit_msg>:new: Respect new config in busy service consumer<commit_after>/* @flow */

import { CompositeDisposable } from 'sb-event-kit'
import type { Linter } from './types'

export default class BusySignal {
  provider: ?Object;
  executing: Set<{
    linter: Linter,
    filePath: ?string,
  }>;
  useBusySignal: boolean;
  subscriptions: CompositeDisposable;

  constructor() {
    this.executing = new Set()
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(atom.config.observe('linter-ui-default.useBusySignal', (useBusySignal) => {
      this.useBusySignal = useBusySignal
    }))
  }
  attach(registry: Object) {
    this.provider = registry.create()
    this.update()
  }
  update() {
    const provider = this.provider
    if (!provider) return
    provider.clear()
    if (!this.useBusySignal) return
    const fileMap: Map<?string, Array<string>> = new Map()

    for (const { filePath, linter } of this.executing) {
      let names = fileMap.get(filePath)
      if (!names) {
        fileMap.set(filePath, names = [])
      }
      names.push(linter.name)
    }

    for (const [filePath, names] of fileMap) {
      const path = filePath ? ` on ${atom.project.relativizePath(filePath)[1]}` : ''
      provider.add(`${names.join(', ')}${path}`)
    }
    fileMap.clear()
  }
  getExecuting(linter: Linter, filePath: ?string): ?Object {
    for (const entry of this.executing) {
      if (entry.linter === linter && entry.filePath === filePath) {
        return entry
      }
    }
    return null
  }
  didBeginLinting(linter: Linter, filePath: ?string) {
    if (this.getExecuting(linter, filePath)) {
      return
    }
    this.executing.add({ linter, filePath })
    this.update()
  }
  didFinishLinting(linter: Linter, filePath: ?string) {
    const entry = this.getExecuting(linter, filePath)
    if (entry) {
      this.executing.delete(entry)
      this.update()
    }
  }
  dispose() {
    if (this.provider) {
      this.provider.clear()
    }
    this.executing.clear()
    this.subscriptions.dispose()
  }
}
<|endoftext|>


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

  if (!window) return;

  var Router = function Router() {
    this.handlers = [];
    this.currentHash = null;
    this.params = {};
  };

  $.extend(Router.prototype, {
    attach: function(component) {
      var target = component;
      for (var i = 0, len = this.handlers.length; i < len; i++) {
        if (this.handlers[i].component === component) return;
      }
      this.handlers.push({
        component: component,
        callback: function(params) { component.refresh(params) }
      });
    },
    detach: function(component) {
      for (var i = 0, len = this.handlers.length; i < len; i++) {
        if (this.handlers[i].component === component) {
          this.handlers.splice(i, 1);
          break;
        }
      }
    },
    visit: function(hash) {
      window.location.hash = hash;
      this.trigger();
    },
    trigger: function() {
      var hash;

      hash = window.location.href.split('#')[1] || '';
      if (hash != this.currentHash) {
        this.refresh();
        for (var i = 0, len = this.handlers.length; i < len; i++)
          this.handlers[i].callback.call(this, this.params);
        this.currentHash = hash;
      }
    },
    refresh: function() {
      var hash, ary;

      hash = window.location.href.split('#')[1] || '';
      ary = hash.split('/');
      this.params.collection = ary[0];
      this.params.id = ary[1];
      this.params.action = ary[2];
    }
  });

  function trigger() {
    window.CapeJS.router.trigger()
  }

  if (!window.CapeJS) window.CapeJS = {};
  window.CapeJS.router = new Router();
  window.CapeJS.visit = function(hash) { window.CapeJS.router.visit(hash) }

  if (window.addEventListener)
    window.addEventListener('hashchange', trigger, false)
  else
    window.attachEvent('onhashchange', trigger)
})();
<commit_msg>Rename Router#{visit,navigate}<commit_after>(function() {
  "use strict;"

  if (!window) return;

  var Router = function Router() {
    this.handlers = [];
    this.currentHash = null;
    this.params = {};
  };

  $.extend(Router.prototype, {
    attach: function(component) {
      var target = component;
      for (var i = 0, len = this.handlers.length; i < len; i++) {
        if (this.handlers[i].component === component) return;
      }
      this.handlers.push({
        component: component,
        callback: function(params) { component.refresh(params) }
      });
    },
    detach: function(component) {
      for (var i = 0, len = this.handlers.length; i < len; i++) {
        if (this.handlers[i].component === component) {
          this.handlers.splice(i, 1);
          break;
        }
      }
    },
    navigate: function(hash) {
      window.location.hash = hash;
      this.trigger();
    },
    trigger: function() {
      var hash;

      hash = window.location.href.split('#')[1] || '';
      if (hash != this.currentHash) {
        this.refresh();
        for (var i = 0, len = this.handlers.length; i < len; i++)
          this.handlers[i].callback.call(this, this.params);
        this.currentHash = hash;
      }
    },
    refresh: function() {
      var hash, ary;

      hash = window.location.href.split('#')[1] || '';
      ary = hash.split('/');
      this.params.collection = ary[0];
      this.params.id = ary[1];
      this.params.action = ary[2];
    }
  });

  function trigger() {
    window.CapeJS.router.trigger()
  }

  if (!window.CapeJS) window.CapeJS = {};
  window.CapeJS.router = new Router();
  window.CapeJS.navigate = function(hash) { window.CapeJS.router.navigate(hash) }

  if (window.addEventListener)
    window.addEventListener('hashchange', trigger, false)
  else
    window.attachEvent('onhashchange', trigger)
})();
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var glob = require('glob');
var _ = require('lodash');

/**
 * @see http://stackoverflow.com/a/4587130/167987
 * Uses lodash isEqual to perform non-strict object comparison
 */
function containsObject(obj, list) {
	var i;
	for (i = 0; i < list.length; i++) {
		if (_.isEqual(list[i], obj)) {
			return true;
		}
	}

	return false;
}

function comparePrefixArrays(prefixArray1, prefixArray2, message) {

	var prefixedViolations = {};
	var prefixManifest = {};
	var violations = [];

	prefixArray1.forEach(function(value) {

		if (!prefixedViolations.hasOwnProperty(value.prefix)) {
			prefixedViolations[value.prefix] = [];
		}

		prefixArray2.forEach(function(value2) {
			// Key not found
			var formattedMessage = message.replace('{2}', value.prefix);

			if (value.prefix !== value2.prefix) {
				// Don't override a true value with false - true is sticky
				if (!prefixManifest.hasOwnProperty(value.prefix) || !prefixManifest[value.prefix]) {
					prefixManifest[value.prefix] = false;
				}
			} else {
				prefixManifest[value.prefix] = true;
			}

			var messageObj = {
				line: value2.line,
				column: value2.column || 1,
				message: formattedMessage,
				severity: value2.severity
			};

			// console.log(prefixedViolations[value.prefix]);

			if (!containsObject(messageObj, prefixedViolations[value.prefix])) {
				prefixedViolations[value.prefix].push(messageObj);
			}

		});

	});

	// Delete the array of messages for prefix keys that *were* found
	for (var prefix in prefixManifest) {
		if (prefixManifest.hasOwnProperty(prefix)) {
			if (prefixManifest[prefix]) {
				delete prefixedViolations[prefix];
			} else {
				prefixedViolations[prefix].forEach(function(value) {
					violations.push(value);
				});
			}
		}
	}

	return violations;

}

function matchAll(str, regex) {
	var res = [];
	var m;
	if (regex.global) {
		while (m = regex.exec(str)) {
			res.push(m);
		}
	} else {
		if (m = regex.exec(str)) {
			res.push(m);
		}
	}
	return res;
}

function checkFile(filePath) {
	var violations = [];
	var prefixes = [];
	var prefixUsages = [];
	var lineNumber = 1;

	var lines = fs.readFileSync(filePath, 'utf8').replace(/\r\n/, '\n').split('\n');

	lines.forEach(function(line) {
		// console.log('Line from file:', line);
		var importSearch = line.match(/prefix=\"([A-Za-z0-9]+)\"/);

		if (importSearch !== null) {
			// console.log(importSearch);
			prefixes.push({
				prefix: importSearch[1],
				line: lineNumber,
				column: importSearch.index + 1,
				severity: 'error'
			});
		}

		var namespaceSearch = matchAll(line, /<([A-Za-z0-9]+)\:/g);

		if (namespaceSearch.length > 0) {
			// console.log(namespaceSearch);
			namespaceSearch.forEach(function(value) {
				prefixUsages.push({
					prefix: value[1],
					line: lineNumber,
					column: value.index + 1,
					severity: 'warning'
				});
			});
		}

		lineNumber += 1;

	});

	var unusedPrefixViolations = comparePrefixArrays(prefixes, prefixUsages, 'cfimported namespace prefix "{2}" not used');
	var unimportedPrefixViolations = comparePrefixArrays(prefixUsages, prefixes, 'used namespace prefix "{2}" not cfimported');

	violations = unimportedPrefixViolations.concat(unusedPrefixViolations);

	return violations;
}

module.exports = {

	check: function check(filePath, format) {
		var fileList = [];
		var violations = [];

		format = format || 'dump'; // Not relevant in node...

		// Resolve the path, if a relative path was passed in
		if (!path.isAbsolute(filePath)) {
			filePath = path.resolve(filePath);
		}

		// The path exists...
		if (fs.existsSync(filePath)) {
			try {
				// ...try a readdirSync and...
				fs.readdirSync(filePath);

				// (Add a trailing slash if not present)
				if (filePath.substr(-1) !== '/') {
					filePath += '/';
				}
				fileList = glob.sync(filePath + '**/*.cfm');
			} catch (e) {
				// ...if that fails, it's a file, not a directory
				fileList = [filePath];
			}
		}

		// console.log(fileList);

		// Loop over our file list, checking each file
		fileList.forEach(function(value) {
			var fileViolations = checkFile(value);
			// console.log(fileViolations);
			if (fileViolations.length > 0) {
				violations.push({
					filename: value,
					messages: fileViolations
				});
			}
		});

		// console.log(violations);

		return violations;

	}

};
<commit_msg>Use correct line and column (from value, not value2)<commit_after>var fs = require('fs');
var path = require('path');
var glob = require('glob');
var _ = require('lodash');

/**
 * @see http://stackoverflow.com/a/4587130/167987
 * Uses lodash isEqual to perform non-strict object comparison
 */
function containsObject(obj, list) {
	var i;
	for (i = 0; i < list.length; i++) {
		if (_.isEqual(list[i], obj)) {
			return true;
		}
	}

	return false;
}

function comparePrefixArrays(prefixArray1, prefixArray2, message) {

	var prefixedViolations = {};
	var prefixManifest = {};
	var violations = [];

	prefixArray1.forEach(function(value) {

		if (!prefixedViolations.hasOwnProperty(value.prefix)) {
			prefixedViolations[value.prefix] = [];
		}

		prefixArray2.forEach(function(value2) {
			// Key not found
			var formattedMessage = message.replace('{2}', value.prefix);

			if (value.prefix !== value2.prefix) {
				// Don't override a true value with false - true is sticky
				if (!prefixManifest.hasOwnProperty(value.prefix) || !prefixManifest[value.prefix]) {
					prefixManifest[value.prefix] = false;
				}
			} else {
				prefixManifest[value.prefix] = true;
			}

			var messageObj = {
				line: value.line,
				column: value.column || 1,
				message: formattedMessage,
				severity: value2.severity
			};

			// console.log(prefixedViolations[value.prefix]);

			if (!containsObject(messageObj, prefixedViolations[value.prefix])) {
				prefixedViolations[value.prefix].push(messageObj);
			}

		});

	});

	// Delete the array of messages for prefix keys that *were* found
	for (var prefix in prefixManifest) {
		if (prefixManifest.hasOwnProperty(prefix)) {
			if (prefixManifest[prefix]) {
				delete prefixedViolations[prefix];
			} else {
				prefixedViolations[prefix].forEach(function(value) {
					violations.push(value);
				});
			}
		}
	}

	return violations;

}

function matchAll(str, regex) {
	var res = [];
	var m;
	if (regex.global) {
		while (m = regex.exec(str)) {
			res.push(m);
		}
	} else {
		if (m = regex.exec(str)) {
			res.push(m);
		}
	}
	return res;
}

function checkFile(filePath) {
	var violations = [];
	var prefixes = [];
	var prefixUsages = [];
	var lineNumber = 1;

	var lines = fs.readFileSync(filePath, 'utf8').replace(/\r\n/, '\n').split('\n');

	lines.forEach(function(line) {
		// console.log('Line from file:', line);
		var importSearch = line.match(/prefix=\"([A-Za-z0-9]+)\"/);

		if (importSearch !== null) {
			// console.log(importSearch);
			prefixes.push({
				prefix: importSearch[1],
				line: lineNumber,
				column: importSearch.index + 1,
				severity: 'error'
			});
		}

		var namespaceSearch = matchAll(line, /<([A-Za-z0-9]+)\:/g);

		if (namespaceSearch.length > 0) {
			// console.log(namespaceSearch);
			namespaceSearch.forEach(function(value) {
				prefixUsages.push({
					prefix: value[1],
					line: lineNumber,
					column: value.index + 1,
					severity: 'warning'
				});
			});
		}

		lineNumber += 1;

	});

	var unusedPrefixViolations = comparePrefixArrays(prefixes, prefixUsages, 'cfimported namespace prefix "{2}" not used');
	var unimportedPrefixViolations = comparePrefixArrays(prefixUsages, prefixes, 'used namespace prefix "{2}" not cfimported');

	violations = unimportedPrefixViolations.concat(unusedPrefixViolations);

	return violations;
}

module.exports = {

	check: function check(filePath, format) {
		var fileList = [];
		var violations = [];

		format = format || 'dump'; // Not relevant in node...

		// Resolve the path, if a relative path was passed in
		if (!path.isAbsolute(filePath)) {
			filePath = path.resolve(filePath);
		}

		// The path exists...
		if (fs.existsSync(filePath)) {
			try {
				// ...try a readdirSync and...
				fs.readdirSync(filePath);

				// (Add a trailing slash if not present)
				if (filePath.substr(-1) !== '/') {
					filePath += '/';
				}
				fileList = glob.sync(filePath + '**/*.cfm');
			} catch (e) {
				// ...if that fails, it's a file, not a directory
				fileList = [filePath];
			}
		}

		// console.log(fileList);

		// Loop over our file list, checking each file
		fileList.forEach(function(value) {
			var fileViolations = checkFile(value);
			// console.log(fileViolations);
			if (fileViolations.length > 0) {
				violations.push({
					filename: value,
					messages: fileViolations
				});
			}
		});

		// console.log(violations);

		return violations;

	}

};
<|endoftext|>


<commit_before>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto(CallBack) {
        var Name        = 'Edit',
            Loading     = false,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Value,
            Edit        = this,
            Diff,
            Ace,
            Msg,
            Dialog      = DOM.Dialog,
            Key         = CloudCmd.Key,
            Images      = DOM.Images,
            Element;

       function init() {
            var lFunc, lIsFunc = Util.isFunction(CloudCmd.View);

            Loading   = true;
            if (lIsFunc)
                lFunc = CloudCmd.View;
            else
                lFunc = Util.exec;

            Util.loadOnLoad([
                Edit.show,
                load,
                lFunc
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f4', Edit.show);
        }

        this.show                       = function(pValue) {
            var lName       = DOM.getCurrentName(),
                lExt        = Util.getExtension(lName),
                lUseWorker  = Util.strCmp(lExt, ['.js', '.json']);

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.anyload({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position: absolute;',
                        not_append : true
                    });

                  initAce();
                }

                Ace.setOptions({
                    useWorker                   : lUseWorker,
                    enableBasicAutocompletion   : true,
                    enableSnippets              : true
                });

                if (Util.isString(pValue)) {
                    Ace.setValue(pValue);
                    CloudCmd.View.show(Element, focus);
                    Key.unsetBind();
                } else {
                    DOM.getCurrentData({
                        success    : function(pData) {
                            var lValue = '';

                            if (pData)
                                lValue = pData.data;

                            Value = lValue;
                            Ace.setValue(lValue);
                            CloudCmd.View.show(Element, focus);
                        }
                    });
                }
            }
        };

        this.hide                       =  function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function focus() {
            Ace.focus();
            Ace.clearSelection();
            Ace.moveCursorTo(0, 0);
        }

        function initAce() {
            var lSession;

            ace.require('ace/ext/language_tools');

            Ace         = ace.edit(Element);
            lSession    = Ace.getSession();

            Ace.setTheme('ace/theme/tomorrow_night_blue');
            lSession.setMode('ace/mode/javascript');
            Ace.setShowPrintMargin(false);
            Ace.setShowInvisibles(true);
            lSession.setUseSoftTabs(true);

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : function (pEditor) {
                    var lPath       = DOM.getCurrentPath(),
                        lValue      = Ace.getValue();

                    CloudCmd.getConfig(function(config) {
                        var isDiff = config.diff;

                        Util.ifExec(!isDiff, function(patch) {
                            var query,
                                isString    = Util.isString(patch),
                                length      = isString && patch.length < lValue.length;

                            Value       = lValue;

                            if (isString && length) {
                                lValue  = patch;
                                query   = '?patch';
                            }

                            DOM.checkStorageHash(lPath, function(error, equal) {
                                if (!error) {
                                    if (!equal)
                                        query = '';

                                    DOM.RESTful.save(lPath,  lValue, onSave, query);
                                }
                            });

                        }, function(callback) {
                            diff(lValue, callback);
                        });
                    });
                }
            });
        }

        function diff(pNewValue, pCallBack) {
            var libs = [
                    LIBDIR + 'diff.js',
                    LIBDIR + 'diff/diff-match-patch.js'
                ];

            DOM.anyLoadInParallel(libs, function() {
                var patch;

                if (!Diff)
                    Diff    = new DiffProto(diff_match_patch);

                patch       = Diff.createPatch(Value, pNewValue);

                Util.exec(pCallBack, patch);
            });
        }

        function load(pCallBack) {
            Util.time(Name + ' load');

            var lFiles  = [
                DIR + 'theme-tomorrow_night_blue.js',
                DIR + 'ext-language_tools.js',
                DIR + 'ace.js',
            ],
                lURL    = DOM.combineURL(lFiles);

            DOM.jsload(lURL, function() {
                Util.timeEnd(Name + ' load');
                Loading = false;
                Util.exec(pCallBack);
            });
        }

        function listener(pEvent) {
            var lF4, lKey, lIsBind = Key.isBind();

            if (lIsBind) {
                lF4     = Key.F4,
                lKey    = pEvent.keyCode;

                if(lKey === lF4)
                    Edit.show();
            }
        }

        function onSave(text, hash) {
            var ret,
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = DOM.getCurrentPath(),
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);
                DOM.saveDataToStorage(path, Value);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    DOM.RESTful.save(path, Value, onSave);
            }
        }

        this.showMessage    = function(text) {
            var parent,
                TWO_SECONDS = 2000;

            if (!Msg) {
                DOM.cssSet({
                    id      : 'msg-css',
                    inner   : '#view .msg {'        +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
                parent  = Element;

                Msg     = DOM.anyload({
                    name        : 'div',
                    className   : 'msg',
                    parent      : parent
                });
            }

            Msg.innerHTML = text;
            DOM.show(Msg);
            setTimeout(Util.retExec(DOM.hide, Msg), 2000);
        };

        init();
    }

})(CloudCmd, Util, DOM, CloudFunc);
<commit_msg>refactor(ace) add files to combine<commit_after>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto(CallBack) {
        var Name        = 'Edit',
            Loading     = false,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Value,
            Edit        = this,
            Diff,
            Ace,
            Msg,
            Dialog      = DOM.Dialog,
            Key         = CloudCmd.Key,
            Images      = DOM.Images,
            Element;

       function init() {
            var lFunc, lIsFunc = Util.isFunction(CloudCmd.View);

            Loading   = true;
            if (lIsFunc)
                lFunc = CloudCmd.View;
            else
                lFunc = Util.exec;

            Util.loadOnLoad([
                Edit.show,
                load,
                lFunc
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f4', Edit.show);
        }

        this.show                       = function(pValue) {
            var lName       = DOM.getCurrentName(),
                lExt        = Util.getExtension(lName),
                lUseWorker  = Util.strCmp(lExt, ['.js', '.json']);

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.anyload({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position: absolute;',
                        not_append : true
                    });

                  initAce();
                }

                Ace.setOptions({
                    useWorker                   : lUseWorker,
                    enableBasicAutocompletion   : true,
                    enableSnippets              : true
                });

                if (Util.isString(pValue)) {
                    Ace.setValue(pValue);
                    CloudCmd.View.show(Element, focus);
                    Key.unsetBind();
                } else {
                    DOM.getCurrentData({
                        success    : function(pData) {
                            var lValue = '';

                            if (pData)
                                lValue = pData.data;

                            Value = lValue;
                            Ace.setValue(lValue);
                            CloudCmd.View.show(Element, focus);
                        }
                    });
                }
            }
        };

        this.hide                       =  function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function focus() {
            Ace.focus();
            Ace.clearSelection();
            Ace.moveCursorTo(0, 0);
        }

        function initAce() {
            var lSession;

            Ace         = ace.edit(Element);
            lSession    = Ace.getSession();

            Ace.setTheme('ace/theme/tomorrow_night_blue');
            lSession.setMode('ace/mode/javascript');
            Ace.setShowPrintMargin(false);
            Ace.setShowInvisibles(true);
            lSession.setUseSoftTabs(true);

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : function (pEditor) {
                    var lPath       = DOM.getCurrentPath(),
                        lValue      = Ace.getValue();

                    CloudCmd.getConfig(function(config) {
                        var isDiff = config.diff;

                        Util.ifExec(!isDiff, function(patch) {
                            var query,
                                isString    = Util.isString(patch),
                                length      = isString && patch.length < lValue.length;

                            Value       = lValue;

                            if (isString && length) {
                                lValue  = patch;
                                query   = '?patch';
                            }

                            DOM.checkStorageHash(lPath, function(error, equal) {
                                if (!error) {
                                    if (!equal)
                                        query = '';

                                    DOM.RESTful.save(lPath,  lValue, onSave, query);
                                }
                            });

                        }, function(callback) {
                            diff(lValue, callback);
                        });
                    });
                }
            });
        }

        function diff(pNewValue, pCallBack) {
            var libs = [
                    LIBDIR + 'diff.js',
                    LIBDIR + 'diff/diff-match-patch.js'
                ];

            DOM.anyLoadInParallel(libs, function() {
                var patch;

                if (!Diff)
                    Diff    = new DiffProto(diff_match_patch);

                patch       = Diff.createPatch(Value, pNewValue);

                Util.exec(pCallBack, patch);
            });
        }

        function load(pCallBack) {
            Util.time(Name + ' load');

            var lFiles  = [
                DIR + 'theme-tomorrow_night_blue.js',
                DIR + 'ext-language_tools.js',
                DIR + 'ext-searchbox.js',
                DIR + 'snippets/javascript.js',
                DIR + 'mode-javascript.js',
            ],
                lAce    = DIR + 'ace.js',
                lURL    = DOM.combineURL(lFiles);

            DOM.anyLoadOnLoad([lURL, lAce], function() {
                Util.timeEnd(Name + ' load');
                Loading = false;
                Util.exec(pCallBack);
            });
        }

        function listener(pEvent) {
            var lF4, lKey, lIsBind = Key.isBind();

            if (lIsBind) {
                lF4     = Key.F4,
                lKey    = pEvent.keyCode;

                if(lKey === lF4)
                    Edit.show();
            }
        }

        function onSave(text, hash) {
            var ret,
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = DOM.getCurrentPath(),
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);
                DOM.saveDataToStorage(path, Value);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    DOM.RESTful.save(path, Value, onSave);
            }
        }

        this.showMessage    = function(text) {
            var parent,
                TWO_SECONDS = 2000;

            if (!Msg) {
                DOM.cssSet({
                    id      : 'msg-css',
                    inner   : '#view .msg {'        +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
                parent  = Element;

                Msg     = DOM.anyload({
                    name        : 'div',
                    className   : 'msg',
                    parent      : parent
                });
            }

            Msg.innerHTML = text;
            DOM.show(Msg);
            setTimeout(Util.retExec(DOM.hide, Msg), 2000);
        };

        init();
    }

})(CloudCmd, Util, DOM, CloudFunc);
<|endoftext|>