<commit_before>/**
 * Copyright 2004-present Facebook. All Rights Reserved.
 *
 * @providesModule Portal
 * @flow
 */
'use strict';

var React = require('React');
var StyleSheet = require('StyleSheet');
var View = require('View');

var _portalRef: any;

// Unique identifiers for modals.
var lastUsedTag = 0;

/*
 * A container that renders all the modals on top of everything else in the application.
 *
 * Portal makes it possible for application code to pass modal views all the way up to
 * the root element created in `renderApplication`.
 *
 * Never use `<Portal>` in your code. There is only one Portal instance rendered
 * by the top-level `renderApplication`.
 */
var Portal = React.createClass({
  statics: {
    /**
     * Use this to create a new unique tag for your component that renders
     * modals. A good place to allocate a tag is in `componentWillMount`
     * of your component.
     * See `showModal` and `closeModal`.
     */
    allocateTag: function(): string {
      return '__modal_' + (++lastUsedTag);
    },

    /**
     * Render a new modal.
     * @param tag A unique tag identifying the React component to render.
     * This tag can be later used in `closeModal`.
     * @param component A React component to be rendered.
     */
    showModal: function(tag: string, component: any) {
      if (!_portalRef) {
        console.error('Calling showModal but no Portal has been rendered.');
        return;
      }
      _portalRef._showModal(tag, component);
    },

    /**
     * Remove a modal from the collection of modals to be rendered.
     * @param tag A unique tag identifying the React component to remove.
     * Must exactly match the tag previously passed to `showModal`.
     */
    closeModal: function(tag: string) {
      if (!_portalRef) {
        console.error('Calling closeModal but no Portal has been rendered.');
        return;
      }
      _portalRef._closeModal(tag);
    },

    /**
     * Get an array of all the open modals, as identified by their tag string.
     */
    getOpenModals: function(): Array<string> {
      if (!_portalRef) {
        console.error('Calling getOpenModals but no Portal has been rendered.');
        return [];
      }
      return _portalRef._getOpenModals();
    }
  },

  getInitialState: function() {
    return {modals: {}};
  },

  _showModal: function(tag: string, component: any) {
    // This way state is chained through multiple calls to
    // _showModal, _closeModal correctly.
    this.setState((state) => {
      var modals = state.modals;
      modals[tag] = component;
      return {modals};
    });
  },

  _closeModal: function(tag: string) {
    if (!this.state.modals.hasOwnProperty(tag)) {
      return;
    }
    // This way state is chained through multiple calls to
    // _showModal, _closeModal correctly.
    this.setState((state) => {
      var modals = state.modals;
      delete modals[tag];
      return {modals};
    });
  },

  _getOpenModals: function(): Array<string> {
    return Object.keys(this.state.modals);
  },

  render: function() {
    _portalRef = this;
    if (!this.state.modals) {
      return null;
    }
    var modals = [];
    for (var tag in this.state.modals) {
      modals.push(this.state.modals[tag]);
    }
    if (modals.length === 0) {
      return null;
    }
    return (
      <View style={styles.modalsContainer}>
        {modals}
      </View>
    );
  }
});

var styles = StyleSheet.create({
  modalsContainer: {
    position: 'absolute',
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
  },
});

module.exports = Portal;
<commit_msg>[ReactNative] make sending accessibility events from JS possible and fix dialog<commit_after>/**
 * Copyright 2004-present Facebook. All Rights Reserved.
 *
 * @providesModule Portal
 * @flow
 */
'use strict';

var Platform = require('Platform');
var React = require('React');
var RCTUIManager = require('NativeModules').UIManager;
var StyleSheet = require('StyleSheet');
var View = require('View');

var _portalRef: any;

// Unique identifiers for modals.
var lastUsedTag = 0;

/*
 * A container that renders all the modals on top of everything else in the application.
 *
 * Portal makes it possible for application code to pass modal views all the way up to
 * the root element created in `renderApplication`.
 *
 * Never use `<Portal>` in your code. There is only one Portal instance rendered
 * by the top-level `renderApplication`.
 */
var Portal = React.createClass({
  statics: {
    /**
     * Use this to create a new unique tag for your component that renders
     * modals. A good place to allocate a tag is in `componentWillMount`
     * of your component.
     * See `showModal` and `closeModal`.
     */
    allocateTag: function(): string {
      return '__modal_' + (++lastUsedTag);
    },

    /**
     * Render a new modal.
     * @param tag A unique tag identifying the React component to render.
     * This tag can be later used in `closeModal`.
     * @param component A React component to be rendered.
     */
    showModal: function(tag: string, component: any) {
      if (!_portalRef) {
        console.error('Calling showModal but no Portal has been rendered.');
        return;
      }
      _portalRef._showModal(tag, component);
    },

    /**
     * Remove a modal from the collection of modals to be rendered.
     * @param tag A unique tag identifying the React component to remove.
     * Must exactly match the tag previously passed to `showModal`.
     */
    closeModal: function(tag: string) {
      if (!_portalRef) {
        console.error('Calling closeModal but no Portal has been rendered.');
        return;
      }
      _portalRef._closeModal(tag);
    },

    /**
     * Get an array of all the open modals, as identified by their tag string.
     */
    getOpenModals: function(): Array<string> {
      if (!_portalRef) {
        console.error('Calling getOpenModals but no Portal has been rendered.');
        return [];
      }
      return _portalRef._getOpenModals();
    },

    notifyAccessibilityService: function() {
      if (!_portalRef) {
        console.error('Calling closeModal but no Portal has been rendered.');
        return;
      }
      _portalRef._notifyAccessibilityService();
    },
  },

  getInitialState: function() {
    return {modals: {}};
  },

  _showModal: function(tag: string, component: any) {
    // This way state is chained through multiple calls to
    // _showModal, _closeModal correctly.
    this.setState((state) => {
      var modals = state.modals;
      modals[tag] = component;
      return {modals};
    });
  },

  _closeModal: function(tag: string) {
    if (!this.state.modals.hasOwnProperty(tag)) {
      return;
    }
    // This way state is chained through multiple calls to
    // _showModal, _closeModal correctly.
    this.setState((state) => {
      var modals = state.modals;
      delete modals[tag];
      return {modals};
    });
  },

  _getOpenModals: function(): Array<string> {
    return Object.keys(this.state.modals);
  },

  _notifyAccessibilityService: function() {
    if (Platform.OS === 'android') {
      // We need to send accessibility event in a new batch, as otherwise
      // TextViews have no text set at the moment of populating event.
      setTimeout(() => {
        if (this._getOpenModals().length > 0) {
          RCTUIManager.sendAccessibilityEvent(
            React.findNodeHandle(this),
            RCTUIManager.AccessibilityEventTypes.typeWindowStateChanged);
        }
      }, 0);
    }
  },

  render: function() {
    _portalRef = this;
    if (!this.state.modals) {
      return null;
    }
    var modals = [];
    for (var tag in this.state.modals) {
      modals.push(this.state.modals[tag]);
    }
    if (modals.length === 0) {
      return null;
    }
    return (
      <View
        style={styles.modalsContainer}
        importantForAccessibility="yes">
        {modals}
      </View>
    );
  }
});

var styles = StyleSheet.create({
  modalsContainer: {
    position: 'absolute',
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
  },
});

module.exports = Portal;
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Pasos = mongoose.model('Pasos');

  //GET - Return all Pasos in the DB
  exports.findAllPasos = function(req, res) {
  	console.log(Pasos);
  	Pasos.find(function(err, pasos) {
  		console.log(pasos);
  		if(!err) {
  			res.send(pasos);
  		} else {
  			console.log('ERROR: ' + err);
  		}
  	});
  };

  //GET - Return a User with specified ID
  exports.findPasoById = function(req, res) {
      Pasos.findById(req.params.id,function(err, paso) {
      if(!err) {
        res.send(paso);
      } else {
        console.log('ERROR: ' + err);
      }
    });
  };

  //GET - Return a User with specified UserName
  exports.findUserByIdentificacion = function(req, res) {
    //Pasos.findById(req.param.id, function(err, guia) {
      Pasos.find({Identificacion:req.params.Identificacion},function(err, paso) {
      console.log(req.params);
      if(!err) {
        res.send(paso);
      } else {
        console.log('ERROR: ' + err);
      }
    });
  };

  //POST - Insert a new User in the DB
  exports.addUser = function(req, res) {
    console.log('POST');
    console.log(req.body);

    try
    {
        var paso = new Pasos({
            Identificacion: req.body.Identificacion,
            Clave: req.body.Clave,
            Sede: req.body.Sede,
            Plan: req.body.Plan,
            Dia_Plan: req.body.Dia_Plan,
            Mes_Plan: req.body.Mes_Plan,
            Ano_Plan: req.body.Ano_Plan,
            Paso: req.body.Paso
      });

      paso.save(function(err) {
        if(!err) {
          console.log('User "'+ req.body.BasicInfo.Name +'" Created Succefull');
        } else {
          console.log('ERROR: ' + err);
        }
      });

      res.send(paso);
    }
    catch(error)
    {
      console.log(error);
    }

  };

  //PUT - Update a User already exists
  exports.updateUser = function(req, res)
  {
    Pasos.findById(req.params.id, function(err, paso) {
      paso.Paso = req.body.paso.Paso

      paso.save(function(err) {
        if(!err)
        {
          console.log('User "'+ req.body.BasicInfo.Name +'" Updated Succefull');
        }
        else
        {
          console.log('ERROR: ' + err);
        }

        res.send(paso);
      });
    });
  };

  //DELETE - Delete a User with specified ID
  exports.deleteUser = function(req, res) {
      Pasos.findById(req.params.id, function (err, paso) {
          console.log(JSON.stringify(paso));
      paso.remove(function(err) {
        if(!err) {
      console.log('User with Id "'+ req.params.id +'" Removed Succefull');
        } else {
      console.log('ERROR: ' + err);
        }
      })
    });
  }<commit_msg>Mejora 2<commit_after>var mongoose = require('mongoose');
var Pasos = mongoose.model('Pasos');

  //GET - Return all Pasos in the DB
  exports.findAllPasos = function(req, res) {
  	console.log(Pasos);
  	Pasos.find(function(err, pasos) {
  		console.log(pasos);
  		if(!err) {
  			res.send(pasos);
  		} else {
  			console.log('ERROR: ' + err);
  		}
  	});
  };

  //GET - Return a User with specified ID
  exports.findPasoById = function(req, res) {
      Pasos.findById(req.params.id,function(err, paso) {
      if(!err) {
        res.send(paso);
      } else {
        console.log('ERROR: ' + err);
      }
    });
  };

  //GET - Return a User with specified UserName
  exports.findUserByIdentificacion = function(req, res) {
    //Pasos.findById(req.param.id, function(err, guia) {
      Pasos.find({Identificacion:req.params.Identificacion},function(err, paso) {
      console.log(req.params);
      if(!err) {
        res.send(paso);
      } else {
        console.log('ERROR: ' + err);
      }
    });
  };

  //POST - Insert a new User in the DB
  exports.addUser = function(req, res) {
    console.log('POST');
    console.log(req.body);

    try
    {
        var paso = new Pasos({
            Identificacion: req.body.Identificacion,
            Clave: req.body.Clave,
            Sede: req.body.Sede,
            Plan: req.body.Plan,
            Dia_Plan: req.body.Dia_Plan,
            Mes_Plan: req.body.Mes_Plan,
            Ano_Plan: req.body.Ano_Plan,
            Paso: req.body.Paso
      });

      paso.save(function(err) {
        if(!err) {
          console.log('User "'+ req.body.BasicInfo.Name +'" Created Succefull');
        } else {
          console.log('ERROR: ' + err);
        }
      });

      res.send(paso);
    }
    catch(error)
    {
      console.log(error);
    }

  };

  //PUT - Update a User already exists
  exports.updateUser = function(req, res)
  {
      Pasos.findById(req.params.id, function (err, paso) {
          paso.Identificacion = req.body.Identificacion,
          paso.Clave = req.body.paso.Clave,
          paso.Sede = req.body.paso.Sede,
          paso.Plan = req.body.paso.Plan,
          paso.Dia_Plan = req.body.paso.Dia_Plan,
          paso.Mes_Plan = req.body.paso.Mes_Plan,
          paso.Ano_Plan = req.body.paso.Ano_Plan,
          paso.Paso = req.body.paso.Paso

      paso.save(function(err) {
        if(!err)
        {
            console.log('User "' + req.body.paso.Identificacion + '" Updated Succefull');
        }
        else
        {
          console.log('ERROR: ' + err);
        }

        res.send(paso);
      });
    });
  };

  //DELETE - Delete a User with specified ID
  exports.deleteUser = function(req, res) {
      Pasos.findById(req.params.id, function (err, paso) {
          console.log(JSON.stringify(paso));
      paso.remove(function(err) {
        if(!err) {
            console.log('User with Id "' + req.params.id + '" Removed Succefull');
            res.send(paso);
        } else {
      console.log('ERROR: ' + err);
        }
      })
    });
  }<|endoftext|>


<commit_before>'use strict';

require('jquery-minicolors');
require('ionrangeslider');

var loadImage  = require('./loadimage');
var components = require('./components');
var commands   = require('./commands');
var effects    = require('./effects');

var templates = require('json!./db/templates.json')
  .reduce(function (templates, template) {
    templates[template.id] = template;
    return templates;
  }, {});

var layers = [];

var defaults = {
  t: 'ahoge',
  m: 'キャリーさんも\nそう思う',
  c: undefined,
  b: '#ffffff',
  f: '#ffffff',
  s: undefined,
  l: '"Textar", "MS PGothic", "IPAMonaPGothic", "Mona", sans-serif',
  e: 'fill',
  o: '1',
  u: '#000000',
  h: '0',
  d: '#ffffff',
  egt: '外道',
  eot: '全滅した…',
  v: 0
};

function filter(text) {
  return text.replace(/\$([\w+])\(([^)]+)\)/g, function (all, id, arg) {
    var command = commands[id];
    return command ? command.apply(null, arg.split(/,/)) : '';
  });
}

var animationTimer;

function render(canvas) {
  var ctx = canvas.getContext('2d');

  ctx.imageSmoothingEnabled = true;

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  var animate = layers.some(function (layer) {
    return layer.animate;
  });

  if (animate) {
    animationTimer = setInterval(function () {
      renderLayers(ctx);
    }, 33);
  } else {
    renderLayers(ctx);
  }
}

function renderLayers(ctx) {
  layers.forEach(function (layer) {
    layer.render(ctx);
  });
}

function exportToImage() {
  var canvas = document.querySelector('#canvas');
  $('#export_content').attr('src', canvas.toDataURL());
  $('#export').modal('show');
}

function stopAnimation() {
  if (!animationTimer) {
    return;
  }

  clearInterval(animationTimer);
  animationTimer = null;
}

function clearLayers() {
  layers.forEach(function (layer) {
    layer.dispose();
  });

  layers = [];
}

function addLayer(layer) {
  layers.push(layer);

  layers.sort(function (a, b) {
    return a.zIndex - b.zIndex;
  });
}

function createLayers(template, options) {
  var layers = [];

  // 背景色
  var bgColor = new components.Fill({
    color: options.backgroundColor,
    scale: options.scale,
    zIndex: 0
  });
  layers.push(bgColor);

  // 背景画像
  var bgImage = new components.Image({
    src: template.bg,
    scale: options.scale,
    zIndex: 1000
  });
  layers.push(bgImage);

  // 看板文字
  var lines = filter(options.message)
    .split(/\r\n?|\n/)
    .map(function (line) {
      return line.replace(/\s/g, ' ');
    });

  var board = template.board;
  var boardText = new components[board.dir == 'horizontal' ? 'HorizontalText' : 'VerticalText']({
    scale: options.scale,
    lines: lines,
    board: template.board,
    fontSize: options.fontSize,
    fontFamily: options.fontFamily,
    foregroundColor: options.foregroundColor,
    outline: options.outline,
    outlineColor: options.outlineColor,
    shadow: options.shadow,
    shadowColor: options.shadowColor,
    zIndex: 1000
  });
  layers.push(boardText);

  // エフェクト
  var effectLayers = options.effects.map(function (effectMeta) {
    var effect = effects[effectMeta.id];

    return effect.layers.map(function (layerMeta) {
      var layerOptions = Object.create(layerMeta.options);

      layerOptions.zIndex = layerMeta.zIndex;

      switch (effectMeta.id + '.' + layerMeta.id) {
        case 'crystal.text':
          layerOptions.fontSize = 32;
          layerOptions.fontFamily = options.fontFamily;
          layerOptions.gedouText = effectMeta.options.gedouText;
          break;

        case 'gedou.text':
          layerOptions.fontFamily = options.fontFamily;
          layerOptions.gedouText = effectMeta.options.gedouText;
          break;

        case 'gameover.text':
          layerOptions.fontSize = options.fontSize;
          layerOptions.fontFamily = options.fontFamily;
          layerOptions.gameoverText = effectMeta.options.gameoverText;
          break;
      }

      return new layerMeta.component(layerOptions);
    });
  });

  layers = Array.prototype.concat.apply(layers, effectLayers);

  return layers;
}

var threadId = 0;
var loaderTimer;
var loaded;
var retained = true;

function update() {
  if (retained) {
    return;
  }

  if (loaderTimer) {
    clearTimeout(loaderTimer);
  }

  loaded = false;
  loaderTimer = setTimeout(function () {
    if (loaded) {
      return;
    }

    $('#loader').show();
  }, 300);

  stopAnimation();
  clearLayers();

  var template = templates[$('[name=template]:input').val()];

  var effects = $('[name=effect]:input:checked').map(function () {
    var options = {};

    switch (this.value) {
      case 'gedou':
        options.gedouText = $('[name=gedou_text]:input').val();
        break;

      case 'gameover':
        options.gameoverText = $('[name=gameover_text]:input').val();
        break;
      }

    return {id: this.value, options: options};
  }).get();

  var options = {
    template       : template,
    message        : $('textarea[name=message]').val(),
    scale          : parseFloat($('[name=scale]:input').val()),
    backgroundColor: $('input[name=backgroundColor]').minicolors('rgbaString'),
    foregroundColor: $('input[name=foregroundColor]').minicolors('rgbaString'),
    fontSize       : $('select[name=fontSize]').val(),
    fontFamily     : $('select[name=fontFamily]').val(),
    outline        : !!parseInt($('input[name=outline]:checked').val()),
    outlineColor   : $('input[name=outlineColor]').minicolors('rgbaString'),
    shadow         : !!parseInt($('input[name=shadow]:checked').val()),
    shadowColor    : $('input[name=shadowColor]').minicolors('rgbaString'),
    effects        : effects
  };

  $('#template_name').text(template.name);

  var canvas = document.querySelector('#canvas');
  var ctx = canvas.getContext('2d');

  loadImage(template.bg, function (bg) {
    var scale = options.scale;
    var width = (template.width ? template.width : bg.width) * scale;
    var height = (template.height ? template.height : bg.height) * scale;
    canvas.width = width;
    canvas.height= height;

    createLayers(template, options).forEach(function (layer) {
      addLayer(layer);
    });

    var progress = 0, goal = layers.length, currentThreadId = ++threadId;
    var onPrepared = function (layer) {
      if (layer.disposed || currentThreadId !== threadId) {
        return;
      }

      if (++progress === goal) {
        render(canvas);

        if (!loaded) {
          $('#loader').hide();
          loaded = true;
        }
      }
    };

    layers.forEach(function (layer) {
      layer.prepare(ctx, onPrepared);
    });
  });

  var gedouText = effects.reduce(function (e, text) {
    return e.id == 'gedou' ? e.options.gedouText : text;
  }, '');

  var url = location.protocol + '//' +
    location.host +
    location.pathname +
    '?t=' + encodeURIComponent(template.id) +
    '&m=' + encodeURIComponent(encode(options.message)) +
    '&b=' + encodeURIComponent(options.backgroundColor) +
    '&f=' + encodeURIComponent(options.foregroundColor) +
    '&c=' + encodeURIComponent(options.scale) +
    '&s=' + encodeURIComponent(options.fontSize) +
    '&e=' + encodeURIComponent(effects.map(function (effect) { return effect.id; }).join(',')) +
    '&l=' + encodeURIComponent(options.outline ? 1 : 0) +
    '&u=' + encodeURIComponent(options.outlineColor) +
    '&h=' + encodeURIComponent(options.shadow ? 1 : 0) +
    '&d=' + encodeURIComponent(options.shadowColor) +
    '&gt=' + encodeURIComponent(encode(gedouText)) +
    '&v=1';
  $('input[name=url]').val(url);
}

function prepareTemplateList() {
  var $list = $('#template_list');

  if ($list.data('initialized')) {
    return;
  }

  $list.data('initialized', true);

  $.each(templates, function (id, template) {
    var author = $('
')
      .append($('')
        .text(template.name))
      .append($(' />')
        .text('@' + (template.author || '名無しさんピンキー')))
      .html();

    $('')
      .attr('src', template.thumbnail)
      .attr('title', author)
      .tooltip({
        html: true
      })
      .wrap('
')
      .parent()
      .attr('data-template-id', template.id)
      .appendTo($list);
  });
}

function prepareForm() {
  var $templateDialog = $('#chooser');

  $('#template_list').on('click', 'li', function (event) {
    event.preventDefault();

    var id = $(event.currentTarget).attr('data-template-id');
    var template = templates[id];

    $('[name=template]:input').val(template.id);

    $('[name=fontSize]:input').val(template.board.fontSize);

    var shadow = template.board.shadow;
    $('input[name=shadow]').prop('checked', !!shadow);

    if (shadow) {
      $('input[name=shadowColor]')
        .val(shadow)
        .minicolors('opacity', template.board.shadowAlpha || 0.25);
    }

    var slider = $('[name=scale]:input').data('ionRangeSlider');
    slider.update({from: template.scale});

    // ion.rangeSlider 経由でイベントが発火する
    update();

    $templateDialog.modal('hide');
  });

  $('#template').click(function (event) {
    event.preventDefault();
    prepareTemplateList();
    $templateDialog.modal('show');
  });

  var $fontSize = $('select[name=fontSize]');
  for (var size = 8; size <= 128; size++) {
    $('<option />')
      .text(size + 'px')
      .val(size)
      .appendTo($fontSize);
  }

  var $fontFamily = $('[name=fontFamily]:input');
  $fontFamily.mousedown(function () {
    if (!$fontFamily.data('loaded')) {
      var fonts = document.querySelector('#font_finder').getDeviceFonts();
      fonts.forEach(function (font) {
        $('<option />').text(font).appendTo($fontFamily);
      });
      $fontFamily.data('loaded', true);
    }
  });

  var $effectList = $('#effect_list').on('change', '[name=effect]:input', function () {
    update();
  });

  $.map(effects, function (effect, id) {
    $('<input type="checkbox" name="effect" />')
      .val(id)
      .wrap('')
      .parent()
      .append($('').text(effect.name))
      .wrap('
')
      .parent()
      .appendTo($effectList);
  });

  var selector = [
    'input[name=backgroundColor]',
    'input[name=foregroundColor]',
    '[name=scale]:input',
    'select[name=fontSize]',
    'select[name=fontFamily]',
    'input[name=outline]',
    'input[name=outlineColor]',
    'input[name=shadow]',
    'input[name=shadowColor]',
    'input[name=gedou_text]'
  ].join(',');
  $(selector).change(update);

  $('[name=message]:input').keyup(update);

  $('button[name=export]').click(function (e) {
    e.preventDefault();
    try {
      exportToImage();
    } catch (e) {
      window.alert('画像出力できませんでした。他のブラウザでお試し下さい。');
    }
  });

  $('input[name=url]').click(function () {
    this.select();
  }).popover();

  $('input[name=backgroundColor], input[name=foregroundColor], input[name=outlineColor], input[name=shadowColor]').minicolors({
    opacity: true,
    position: 'bottom right'
  });

  $('.author-list a').tooltip();

  $('[name=scale]:input').ionRangeSlider({
    min: 0.1,
    max: 5,
    step: 0.01,
    prettify: function (value) {
      return (Math.round(value * 10000) / 100) + '%';
    }
  });

  $('[name=shrink]:input').change(function () {
    $('#canvas')[this.checked ? 'addClass' : 'removeClass']('canvas-shrink');
  })
    .prop('checked', true)
    .trigger('change');

  // エフェクト: 外道
  $('[name=effect][value=gedou]:input').change(function () {
    $('#gedou_options').toggle(this.checked);
  });

  $('[name=gedou_text]').keyup(update);

  // エフェクト: ゲームオーバー
  $('[name=effect][value=gameover]:input').change(function () {
    $('#gameover_options').toggle(this.checked);
  });

  $('[name=gameover_text]').keyup(update);
}

function encode(string) {
  return btoa(window.unescape(encodeURIComponent(string)));
}

function decode(string) {
  return decodeURIComponent(window.escape(atob(string)));
}

function initialize() {
  prepareForm();

  var encoded = false;
  location.search.substring(1).split('&')
    .map(function (pair) {
      return pair.split('=').map(decodeURIComponent);
    })
    .map(function (kv) {
      encoded = encoded || (kv[0] == 'v' && !!parseInt(kv[1]));
      return kv;
    })
    .map(function (kv) {
      if (kv[0] in defaults) {
        var e = encoded && (kv[0] == 'm' || kv[0] == 'gt');
        defaults[kv[0]] = e ? decode(kv[1]) : kv[1];
      }
    });

  var template = templates[defaults.t] || templates['ahoge'];

  if (!defaults.c) {
    defaults.c = template.scale;
  }

  if (!defaults.s) {
    defaults.s = template.board.fontSize;
  }

  $('<option />')
    .text('デフォルトフォント')
    .val(defaults.l)
    .appendTo($('select[name=fontFamily]'));

  $('[name=template]:input').val(defaults.t);
  $('textarea[name=message]').val(defaults.m);
  $('input[name=backgroundColor]').minicolors('value', defaults.b);
  $('input[name=foregroundColor]').minicolors('value', defaults.f);
  $('select[name=fontSize]').val(defaults.s);
  $('select[name=fontFamily]').val(defaults.l);
  $('input[name=outline]').prop('checked', !!parseInt(defaults.o));
  $('input[name=outlineColor]').minicolors('value', defaults.u);
  $('input[name=shadow]').prop('checked', !!parseInt(defaults.h));
  $('input[name=shadowColor]').minicolors('value', defaults.d);

  defaults.e.split('').forEach(function (id) {
    if (id in effects) {
      $('[name=effect]').find('[value=' + id + ']').prop('checked', true);
    }
  });

  $('input[name=gedou_text]').val(defaults.egt);
  $('#gedou_options').toggle(defaults.e == 'gedou');

  $('input[name=gameover_text]').val(defaults.eot);
  $('#gameover_options').toggle(defaults.e == 'gameover');

  $('[name=scale]:input').data('ionRangeSlider').update({from: defaults.c});

  // for bootstrap/collapse.js
  $('[name=outline]:input, [name=shadow]:input').each(function () {
    var $input = $(this);
    $($input.attr('data-target'))[this.checked ? 'addClass' : 'removeClass']('in');
  });

  retained = false;
}

$(function () {
  initialize();
  update();
});
<commit_msg>コピペ用URLでアクセスすると表示が異常になる不具合を修正<commit_after>'use strict';

require('jquery-minicolors');
require('ionrangeslider');

var loadImage  = require('./loadimage');
var components = require('./components');
var commands   = require('./commands');
var effects    = require('./effects');

var templates = require('json!./db/templates.json')
  .reduce(function (templates, template) {
    templates[template.id] = template;
    return templates;
  }, {});

var layers = [];

var defaults = {
  t: 'ahoge',
  m: 'キャリーさんも\nそう思う',
  c: undefined,
  b: '#ffffff',
  f: '#ffffff',
  s: undefined,
  l: '"Textar", "MS PGothic", "IPAMonaPGothic", "Mona", sans-serif',
  e: 'fill',
  o: '1',
  u: '#000000',
  h: '0',
  d: '#ffffff',
  egt: '外道',
  eot: '全滅した…',
  v: 0
};

function filter(text) {
  return text.replace(/\$([\w+])\(([^)]+)\)/g, function (all, id, arg) {
    var command = commands[id];
    return command ? command.apply(null, arg.split(/,/)) : '';
  });
}

var animationTimer;

function render(canvas) {
  var ctx = canvas.getContext('2d');

  ctx.imageSmoothingEnabled = true;

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  var animate = layers.some(function (layer) {
    return layer.animate;
  });

  if (animate) {
    animationTimer = setInterval(function () {
      renderLayers(ctx);
    }, 33);
  } else {
    renderLayers(ctx);
  }
}

function renderLayers(ctx) {
  layers.forEach(function (layer) {
    layer.render(ctx);
  });
}

function exportToImage() {
  var canvas = document.querySelector('#canvas');
  $('#export_content').attr('src', canvas.toDataURL());
  $('#export').modal('show');
}

function stopAnimation() {
  if (!animationTimer) {
    return;
  }

  clearInterval(animationTimer);
  animationTimer = null;
}

function clearLayers() {
  layers.forEach(function (layer) {
    layer.dispose();
  });

  layers = [];
}

function addLayer(layer) {
  layers.push(layer);

  layers.sort(function (a, b) {
    return a.zIndex - b.zIndex;
  });
}

function createLayers(template, options) {
  var layers = [];

  // 背景色
  var bgColor = new components.Fill({
    color: options.backgroundColor,
    scale: options.scale,
    zIndex: 0
  });
  layers.push(bgColor);

  // 背景画像
  var bgImage = new components.Image({
    src: template.bg,
    scale: options.scale,
    zIndex: 1000
  });
  layers.push(bgImage);

  // 看板文字
  var lines = filter(options.message)
    .split(/\r\n?|\n/)
    .map(function (line) {
      return line.replace(/\s/g, ' ');
    });

  var board = template.board;
  var boardText = new components[board.dir == 'horizontal' ? 'HorizontalText' : 'VerticalText']({
    scale: options.scale,
    lines: lines,
    board: template.board,
    fontSize: options.fontSize,
    fontFamily: options.fontFamily,
    foregroundColor: options.foregroundColor,
    outline: options.outline,
    outlineColor: options.outlineColor,
    shadow: options.shadow,
    shadowColor: options.shadowColor,
    zIndex: 1000
  });
  layers.push(boardText);

  // エフェクト
  var effectLayers = options.effects.map(function (effectMeta) {
    var effect = effects[effectMeta.id];

    return effect.layers.map(function (layerMeta) {
      var layerOptions = Object.create(layerMeta.options);

      layerOptions.zIndex = layerMeta.zIndex;

      switch (effectMeta.id + '.' + layerMeta.id) {
        case 'crystal.text':
          layerOptions.fontSize = 32;
          layerOptions.fontFamily = options.fontFamily;
          layerOptions.gedouText = effectMeta.options.gedouText;
          break;

        case 'gedou.text':
          layerOptions.fontFamily = options.fontFamily;
          layerOptions.gedouText = effectMeta.options.gedouText;
          break;

        case 'gameover.text':
          layerOptions.fontSize = options.fontSize;
          layerOptions.fontFamily = options.fontFamily;
          layerOptions.gameoverText = effectMeta.options.gameoverText;
          break;
      }

      return new layerMeta.component(layerOptions);
    });
  });

  layers = Array.prototype.concat.apply(layers, effectLayers);

  return layers;
}

var threadId = 0;
var loaderTimer;
var loaded;
var retained = true;

function update() {
  if (retained) {
    return;
  }

  if (loaderTimer) {
    clearTimeout(loaderTimer);
  }

  loaded = false;
  loaderTimer = setTimeout(function () {
    if (loaded) {
      return;
    }

    $('#loader').show();
  }, 300);

  stopAnimation();
  clearLayers();

  var template = templates[$('[name=template]:input').val()];

  var effects = $('[name=effect]:input:checked').map(function () {
    var options = {};

    switch (this.value) {
      case 'gedou':
        options.gedouText = $('[name=gedou_text]:input').val();
        break;

      case 'gameover':
        options.gameoverText = $('[name=gameover_text]:input').val();
        break;
      }

    return {id: this.value, options: options};
  }).get();

  var options = {
    template       : template,
    message        : $('textarea[name=message]').val(),
    scale          : parseFloat($('[name=scale]:input').val()),
    backgroundColor: $('input[name=backgroundColor]').val(),
    foregroundColor: $('input[name=foregroundColor]').val(),
    fontSize       : $('select[name=fontSize]').val(),
    fontFamily     : $('select[name=fontFamily]').val(),
    outline        : !!parseInt($('input[name=outline]:checked').val()),
    outlineColor   : $('input[name=outlineColor]').val(),
    shadow         : !!parseInt($('input[name=shadow]:checked').val()),
    shadowColor    : $('input[name=shadowColor]').val(),
    effects        : effects
  };

  $('#template_name').text(template.name);

  var canvas = document.querySelector('#canvas');
  var ctx = canvas.getContext('2d');

  loadImage(template.bg, function (bg) {
    var scale = options.scale;
    var width = (template.width ? template.width : bg.width) * scale;
    var height = (template.height ? template.height : bg.height) * scale;
    canvas.width = width;
    canvas.height= height;

    createLayers(template, options).forEach(function (layer) {
      addLayer(layer);
    });

    var progress = 0, goal = layers.length, currentThreadId = ++threadId;
    var onPrepared = function (layer) {
      if (layer.disposed || currentThreadId !== threadId) {
        return;
      }

      if (++progress === goal) {
        render(canvas);

        if (!loaded) {
          $('#loader').hide();
          loaded = true;
        }
      }
    };

    layers.forEach(function (layer) {
      layer.prepare(ctx, onPrepared);
    });
  });

  var gedouText = effects.reduce(function (e, text) {
    return e.id == 'gedou' ? e.options.gedouText : text;
  }, '');

  var url = location.protocol + '//' +
    location.host +
    location.pathname +
    '?t=' + encodeURIComponent(template.id) +
    '&m=' + encodeURIComponent(encode(options.message)) +
    '&b=' + encodeURIComponent(options.backgroundColor) +
    '&f=' + encodeURIComponent(options.foregroundColor) +
    '&c=' + encodeURIComponent(options.scale) +
    '&s=' + encodeURIComponent(options.fontSize) +
    '&e=' + encodeURIComponent(effects.map(function (effect) { return effect.id; }).join(',')) +
    '&o=' + encodeURIComponent(options.outline ? 1 : 0) +
    '&u=' + encodeURIComponent(options.outlineColor) +
    '&h=' + encodeURIComponent(options.shadow ? 1 : 0) +
    '&d=' + encodeURIComponent(options.shadowColor) +
    '&gt=' + encodeURIComponent(encode(gedouText)) +
    '&v=1';
  $('input[name=url]').val(url);
}

function prepareTemplateList() {
  var $list = $('#template_list');

  if ($list.data('initialized')) {
    return;
  }

  $list.data('initialized', true);

  $.each(templates, function (id, template) {
    var author = $('
')
      .append($('')
        .text(template.name))
      .append($(' />')
        .text('@' + (template.author || '名無しさんピンキー')))
      .html();

    $('')
      .attr('src', template.thumbnail)
      .attr('title', author)
      .tooltip({
        html: true
      })
      .wrap('
')
      .parent()
      .attr('data-template-id', template.id)
      .appendTo($list);
  });
}

function prepareForm() {
  var $templateDialog = $('#chooser');

  $('#template_list').on('click', 'li', function (event) {
    event.preventDefault();

    var id = $(event.currentTarget).attr('data-template-id');
    var template = templates[id];

    $('[name=template]:input').val(template.id);

    $('[name=fontSize]:input').val(template.board.fontSize);

    var shadow = template.board.shadow;
    $('input[name=shadow]').prop('checked', !!shadow);

    if (shadow) {
      $('input[name=shadowColor]')
        .val(shadow)
        .minicolors('opacity', template.board.shadowAlpha || 0.25);
    }

    var slider = $('[name=scale]:input').data('ionRangeSlider');
    slider.update({from: template.scale});

    // ion.rangeSlider 経由でイベントが発火する
    update();

    $templateDialog.modal('hide');
  });

  $('#template').click(function (event) {
    event.preventDefault();
    prepareTemplateList();
    $templateDialog.modal('show');
  });

  var $fontSize = $('select[name=fontSize]');
  for (var size = 8; size <= 128; size++) {
    $('<option />')
      .text(size + 'px')
      .val(size)
      .appendTo($fontSize);
  }

  var $fontFamily = $('[name=fontFamily]:input');
  $fontFamily.mousedown(function () {
    if (!$fontFamily.data('loaded')) {
      var fonts = document.querySelector('#font_finder').getDeviceFonts();
      fonts.forEach(function (font) {
        $('<option />').text(font).appendTo($fontFamily);
      });
      $fontFamily.data('loaded', true);
    }
  });

  var $effectList = $('#effect_list').on('change', '[name=effect]:input', function () {
    update();
  });

  $.map(effects, function (effect, id) {
    $('<input type="checkbox" name="effect" />')
      .val(id)
      .wrap('')
      .parent()
      .append($('').text(effect.name))
      .wrap('
')
      .parent()
      .appendTo($effectList);
  });

  var selector = [
    'input[name=backgroundColor]',
    'input[name=foregroundColor]',
    '[name=scale]:input',
    'select[name=fontSize]',
    'select[name=fontFamily]',
    'input[name=outline]',
    'input[name=outlineColor]',
    'input[name=shadow]',
    'input[name=shadowColor]',
    'input[name=gedou_text]'
  ].join(',');
  $(selector).change(update);

  $('[name=message]:input').keyup(update);

  $('button[name=export]').click(function (e) {
    e.preventDefault();
    try {
      exportToImage();
    } catch (e) {
      window.alert('画像出力できませんでした。他のブラウザでお試し下さい。');
    }
  });

  $('input[name=url]').click(function () {
    this.select();
  }).popover();

  $('input[name=backgroundColor], input[name=foregroundColor], input[name=outlineColor], input[name=shadowColor]').minicolors({
    opacity: true,
    position: 'bottom right'
  });

  $('.author-list a').tooltip();

  $('[name=scale]:input').ionRangeSlider({
    min: 0.1,
    max: 5,
    step: 0.01,
    prettify: function (value) {
      return (Math.round(value * 10000) / 100) + '%';
    }
  });

  $('[name=shrink]:input').change(function () {
    $('#canvas')[this.checked ? 'addClass' : 'removeClass']('canvas-shrink');
  })
    .prop('checked', true)
    .trigger('change');

  // エフェクト: 外道
  $('[name=effect][value=gedou]:input').change(function () {
    $('#gedou_options').toggle(this.checked);
  });

  $('[name=gedou_text]').keyup(update);

  // エフェクト: ゲームオーバー
  $('[name=effect][value=gameover]:input').change(function () {
    $('#gameover_options').toggle(this.checked);
  });

  $('[name=gameover_text]').keyup(update);
}

function encode(string) {
  return btoa(window.unescape(encodeURIComponent(string)));
}

function decode(string) {
  return decodeURIComponent(window.escape(atob(string)));
}

function initialize() {
  prepareForm();

  var encoded = false;
  location.search.substring(1).split('&')
    .map(function (pair) {
      return pair.split('=').map(decodeURIComponent);
    })
    .map(function (kv) {
      encoded = encoded || (kv[0] == 'v' && !!parseInt(kv[1]));
      return kv;
    })
    .map(function (kv) {
      if (kv[0] in defaults) {
        var e = encoded && (kv[0] == 'm' || kv[0] == 'gt');
        defaults[kv[0]] = e ? decode(kv[1]) : kv[1];
      }
    });

  var template = templates[defaults.t] || templates['ahoge'];

  if (!defaults.c) {
    defaults.c = template.scale;
  }

  if (!defaults.s) {
    defaults.s = template.board.fontSize;
  }

  $('<option />')
    .text('デフォルトフォント')
    .val(defaults.l)
    .appendTo($('select[name=fontFamily]'));

  $('[name=template]:input').val(defaults.t);
  $('textarea[name=message]').val(defaults.m);
  $('input[name=backgroundColor]').minicolors('value', defaults.b);
  $('input[name=foregroundColor]').minicolors('value', defaults.f);
  $('select[name=fontSize]').val(defaults.s);
  $('select[name=fontFamily]').val(defaults.l);
  $('input[name=outline]').prop('checked', !!parseInt(defaults.o));
  $('input[name=outlineColor]').minicolors('value', defaults.u);
  $('input[name=shadow]').prop('checked', !!parseInt(defaults.h));
  $('input[name=shadowColor]').minicolors('value', defaults.d);

  defaults.e.split(',').forEach(function (id) {
    if (id in effects) {
      $('[name=effect][value=' + id + ']').prop('checked', true);
    }
  });

  $('input[name=gedou_text]').val(defaults.egt);
  $('#gedou_options').toggle(defaults.e == 'gedou');

  $('input[name=gameover_text]').val(defaults.eot);
  $('#gameover_options').toggle(defaults.e == 'gameover');

  $('[name=scale]:input').data('ionRangeSlider').update({from: defaults.c});

  // for bootstrap/collapse.js
  $('[name=outline]:input, [name=shadow]:input').each(function () {
    var $input = $(this);
    $($input.attr('data-target'))[this.checked ? 'addClass' : 'removeClass']('in');
  });

  retained = false;
}

$(function () {
  initialize();
  update();
});
<|endoftext|>


<commit_before>var focused 			= 0
	, isFullScreen 	= false
	, videos 				= document.getElementsByTagName("video") 	//htmlCollection
		videos 				= [].slice.call(videos) 									//array

videos[0].playbackRate = 1.8;

// focus listener
document.addEventListener('click', function(event){

	var e = event.target

	if(e.tagName != 'VIDEO')
	{
		focused = -1;
		return;
	}
	// else: video clicked, but which one?
	focused = videos.findIndex(function(event){
		return event.id == e.id;
	})

	//event.preventDefault()
	//togglePause(videos[focused])
})

// keyboard shortcuts listener
document.addEventListener('keydown', function(event){

	if (focused == -1)
		return;

	event.preventDefault()

	var key = event.code

	// else: video focused
	switch(key)
	{
		case 'Space':
		case 'KeyK':
		case 'KeyS':
			togglePause(videos[focused])
			break;

		case 'ArrowLeft':
		case 'KeyA':
			videos[focused].currentTime -= 5
			break;

		case 'ArrowRight':
		case 'KeyD':
			videos[focused].currentTime += 5
			break;

		case 'ArrowUp':
			videos[focused].volume *= 1.25
			break;

		case 'ArrowDown':
			videos[focused].volume /= 1.25
			break;

		case 'KeyJ':
			videos[focused].currentTime -= 10
			break;

		case 'KeyL':
			videos[focused].currentTime += 10
			break;

		case 'KeyF':
			toggleFullScreen(videos[focused])
			break;

		case 'Escape':
			exitFullScreen(videos[focused])
			break;

		case 'Comma':
			videos[focused].playbackRate /= 1.1;
			console.log(videos[focused].playbackRate)
			break;

		case 'Period':
			videos[focused].playbackRate *= 1.1;
			console.log(videos[focused].playbackRate)
			break;
	}
})

var togglePause = function(v)
{
	if (v.paused)
		v.play()
	else
		v.pause()
}

var toggleFullScreen = function(v)
{
	// firefox
	if (v.mozRequestFullScreen)
	{
		if (isFullScreen)
  	  exitFullScreen(v)
  	else
	 		v.mozRequestFullScreen()
	}

	// chrome
	else // if (v.webkitRequestFullScreen)
	{
		if (isFullScreen)
	 		exitFullScreen(v)
  	else
  	  v.webkitRequestFullScreen()
	}
}

var exitFullScreen = function(v)
{
	if (v.exitFullscreen)
    v.exitFullscreen()

	else if (v.mozCancelFullScreen)
    v.mozCancelFullScreen()

	else if (v.webkitExitFullscreen)
    v.webkitExitFullscreen()
}

/* fullscreen */

document.addEventListener("fullscreenchange", function () {
    isFullScreen = !isFullScreen;
}, false);

document.addEventListener("mozfullscreenchange", function () {
    isFullScreen = !isFullScreen;
}, false);

document.addEventListener("webkitfullscreenchange", function () {
    isFullScreen = !isFullScreen;
}, false);

document.addEventListener("msfullscreenchange", function () {
    isFullScreen = !isFullScreen;
}, false);<commit_msg>tab f<commit_after>var focused 		= 0
	, isFullScreen 	= false
	, videos 		= document.getElementsByTagName("video") 	//htmlCollection
	videos 			= [].slice.call(videos) 									//array

videos[0].playbackRate = 1.8;

// focus listener
document.addEventListener('click', function(event){

	var e = event.target

	if(e.tagName != 'VIDEO')
	{
		focused = -1;
		return;
	}
	// else: video clicked, but which one?
	focused = videos.findIndex(function(event){
		return event.id == e.id;
	})

	//event.preventDefault()
	//togglePause(videos[focused])
})

// keyboard shortcuts listener
document.addEventListener('keydown', function(event){

	if (focused == -1)
		return;

	event.preventDefault()

	var key = event.code

	// else: video focused
	switch(key)
	{
		case 'Space':
		case 'KeyK':
		case 'KeyS':
			togglePause(videos[focused])
			break;

		case 'ArrowLeft':
		case 'KeyA':
			videos[focused].currentTime -= 5
			break;

		case 'ArrowRight':
		case 'KeyD':
			videos[focused].currentTime += 5
			break;

		case 'ArrowUp':
			videos[focused].volume *= 1.25
			break;

		case 'ArrowDown':
			videos[focused].volume /= 1.25
			break;

		case 'KeyJ':
			videos[focused].currentTime -= 10
			break;

		case 'KeyL':
			videos[focused].currentTime += 10
			break;

		case 'KeyF':
			toggleFullScreen(videos[focused])
			break;

		case 'Escape':
			exitFullScreen(videos[focused])
			break;

		case 'Comma':
			videos[focused].playbackRate /= 1.1;
			console.log(videos[focused].playbackRate)
			break;

		case 'Period':
			videos[focused].playbackRate *= 1.1;
			console.log(videos[focused].playbackRate)
			break;
	}
})

var togglePause = function(v)
{
	if (v.paused)
		v.play()
	else
		v.pause()
}

var toggleFullScreen = function(v)
{
	// firefox
	if (v.mozRequestFullScreen)
	{
		if (isFullScreen)
  	  exitFullScreen(v)
  	else
	 		v.mozRequestFullScreen()
	}

	// chrome
	else // if (v.webkitRequestFullScreen)
	{
		if (isFullScreen)
	 		exitFullScreen(v)
  	else
  	  v.webkitRequestFullScreen()
	}
}

var exitFullScreen = function(v)
{
	if (v.exitFullscreen)
    v.exitFullscreen()

	else if (v.mozCancelFullScreen)
    v.mozCancelFullScreen()

	else if (v.webkitExitFullscreen)
    v.webkitExitFullscreen()
}

/* fullscreen */

document.addEventListener("fullscreenchange", function () {
    isFullScreen = !isFullScreen;
}, false);

document.addEventListener("mozfullscreenchange", function () {
    isFullScreen = !isFullScreen;
}, false);

document.addEventListener("webkitfullscreenchange", function () {
    isFullScreen = !isFullScreen;
}, false);

document.addEventListener("msfullscreenchange", function () {
    isFullScreen = !isFullScreen;
}, false);<|endoftext|>


<commit_before>var Observer = require('../observe/observer')
var scopeEvents = ['set', 'mutate', 'add', 'delete']

/**
 * Setup instance scope.
 * The scope is reponsible for prototypal inheritance of
 * parent instance propertiesm abd all binding paths and
 * expressions of the current instance are evaluated against its scope.
 *
 * This should only be called once during _init().
 */

exports._initScope = function () {
  var parent = this.$parent
  var scope = this.$scope = parent
    ? Object.create(parent.$scope)
    : {}
  // create scope observer
  this._observer = Observer.create(scope, {
    callbackContext: this,
    doNotAlterProto: true
  })

  if (!parent) return

  // relay change events that sent down from
  // the scope prototype chain.
  var ob = this._observer
  var pob = parent._observer
  var listeners = this._scopeListeners = {}
  scopeEvents.forEach(function (event) {
    var cb = listeners[event] = function (key, a, b) {
      // since these events come from upstream,
      // we only emit them if we don't have the same keys
      // shadowing them in current scope.
      if (!scope.hasOwnProperty(key)) {
        ob.emit(event, key, a, b)
      }
    }
    pob.on(event, cb)
  })
}

/**
 * Teardown scope and remove listeners attached to parent scope.
 * Only called once during $destroy().
 */

exports._teardownScope = function () {
  this.$scope = null
  if (!this.$parent) return
  var pob = this.$parent._observer
  var listeners = this._scopeListeners
  scopeEvents.forEach(function (event) {
    pob.off(event, listeners[event])
  })
}<commit_msg>allow $parent/$root access on $scope<commit_after>var Observer = require('../observe/observer')
var scopeEvents = ['set', 'mutate', 'add', 'delete']

/**
 * Setup instance scope.
 * The scope is reponsible for prototypal inheritance of
 * parent instance propertiesm abd all binding paths and
 * expressions of the current instance are evaluated against its scope.
 *
 * This should only be called once during _init().
 */

exports._initScope = function () {
  var parent = this.$parent
  var scope = this.$scope = parent
    ? Object.create(parent.$scope)
    : {}
  // create scope observer
  this._observer = Observer.create(scope, {
    callbackContext: this,
    doNotAlterProto: true
  })

  if (!parent) return

  // scope parent accessor
  Object.defineProperty(scope, '$parent', {
    get: function () {
      return parent.$scope
    }
  })

  // scope root accessor
  var self = this
  Object.defineProperty(scope, '$root', {
    get: function () {
      return self.$root.$scope
    }
  })

  // relay change events that sent down from
  // the scope prototype chain.
  var ob = this._observer
  var pob = parent._observer
  var listeners = this._scopeListeners = {}
  scopeEvents.forEach(function (event) {
    var cb = listeners[event] = function (key, a, b) {
      // since these events come from upstream,
      // we only emit them if we don't have the same keys
      // shadowing them in current scope.
      if (!scope.hasOwnProperty(key)) {
        ob.emit(event, key, a, b)
      }
    }
    pob.on(event, cb)
  })
}

/**
 * Teardown scope and remove listeners attached to parent scope.
 * Only called once during $destroy().
 */

exports._teardownScope = function () {
  this.$scope = null
  if (!this.$parent) return
  var pob = this.$parent._observer
  var listeners = this._scopeListeners
  scopeEvents.forEach(function (event) {
    pob.off(event, listeners[event])
  })
}<|endoftext|>


<commit_before>/* globals module */
module.exports = {
  afterInstall: function() {
    var _this = this;
    var imports = '  app.import(\'vendor/font-icon.css\');\n' +
      '  app.import(\'vendor/fonts/icons.eot\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.otf\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.svg\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.ttf\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.woff\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.woff2\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.eot\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.otf\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.svg\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.ttf\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.woff\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.woff2\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/serviceImages/close.png\', { destDir: \'assets/serviceImages\' });\n' +
      '  app.import(\'vendor/serviceImages/close-hover.png\', { destDir: \'assets/serviceImages\' });\n' +
      '  app.import(\'vendor/serviceImages/Plus.png\', { destDir: \'assets/serviceImages\' });\n' +
      '  app.import(\'vendor/serviceImages/Minus.png\', { destDir: \'assets/serviceImages\' });\n';
    var options = '    jscsOptions: {\n' +
      '      enabled: true,\n' +
      '      esnext: true,\n' +
      '      configPath: \'./.jscsrc\'\n' +
      '    },\n' +
      '    lessOptions: {\n' +
      '      paths: [\n' +
      '        \'bower_components/semantic-ui\'\n' +
      '      ]\n' +
      '    },\n' +
      '    SemanticUI: {\n' +
      '      import: {\n' +
      '        css: false,\n' +
      '        javascript: true,\n' +
      '        images: false,\n' +
      '        fonts: true\n' +
      '      }\n' +
      '    }\n';

    /*
      Following packages should be installed as dependencies of `ember-flexberry-data`:
      `ember-browserify`, `dexie`.
	  Also `app/browserify.js` should be removed when check this.
    */

    return this.insertIntoFile(
      'ember-cli-build.js',
      imports,
      {
        before: '  return app.toTree();\n'
      }
    ).then(function() {
      return _this.insertIntoFile(
        'ember-cli-build.js',
        options,
        {
          after: '  var app = new EmberApp(defaults, {\n'
        }
      );
    }).then(function() {
      return _this.insertIntoFile(
        'ember-cli-build.js',
        options,
        {
          after: '  var app = new EmberAddon(defaults, {\n'
        }
      );
    }).then(function() {
      return _this.insertIntoFile(
        'app/index.html',
        '    <script src="//cdn.polyfill.io/v1/polyfill.js?features=es6"></script>',
        {
          after: '    <script src="assets/dummy.js"></script>\n'
        }
      );
    }).then(function() {
      return _this.addBowerPackagesToProject([
        { name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
        { name: 'flatpickr-calendar', source: 'git://github.com/chmln/flatpickr.git', target: '2.3.4' },
        { name: 'blueimp-file-upload', target: '9.11.2' },
        { name: 'devicejs', target: '0.2.7' }
      ]);
    }).then(function() {
      return _this.addBowerPackageToProject('semantic-ui','git://github.com/Flexberry/Semantic-UI.git#fixed-abort');
    }).then(function() {
      return _this.addAddonsToProject({
        packages: [
          { name: 'ember-moment', target: '6.0.0' },
          { name: 'ember-link-action', target: '0.0.34' },
          { name: 'ember-cli-less', target: '1.5.4' },
          { name: 'broccoli-jscs', target: '1.2.2' },
          { name: 'ember-browserify', target: '1.1.9' }
        ]
      });
    }).then(function () {
      return _this.addPackagesToProject([
        { name: 'dexie', target: '1.4.2' },
        { name: 'node-uuid', target: '1.4.7' },
        { name: 'inflection', target: '1.10.0' }
      ]);
    }).then(function () {
      return _this.addPackageToProject('semantic-ui-ember','git://github.com/Flexberry/Semantic-UI-Ember.git#version-0.9.3');
    });
  },

  normalizeEntityName: function() {}
};
<commit_msg>Add polyfill into index.html for addon generation<commit_after>/* globals module */
module.exports = {
  afterInstall: function() {
    var _this = this;
    var imports = '  app.import(\'vendor/font-icon.css\');\n' +
      '  app.import(\'vendor/fonts/icons.eot\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.otf\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.svg\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.ttf\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.woff\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/icons.woff2\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.eot\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.otf\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.svg\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.ttf\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.woff\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/fonts/crim.woff2\', { destDir: \'assets/fonts\' });\n' +
      '  app.import(\'vendor/serviceImages/close.png\', { destDir: \'assets/serviceImages\' });\n' +
      '  app.import(\'vendor/serviceImages/close-hover.png\', { destDir: \'assets/serviceImages\' });\n' +
      '  app.import(\'vendor/serviceImages/Plus.png\', { destDir: \'assets/serviceImages\' });\n' +
      '  app.import(\'vendor/serviceImages/Minus.png\', { destDir: \'assets/serviceImages\' });\n';
    var options = '    jscsOptions: {\n' +
      '      enabled: true,\n' +
      '      esnext: true,\n' +
      '      configPath: \'./.jscsrc\'\n' +
      '    },\n' +
      '    lessOptions: {\n' +
      '      paths: [\n' +
      '        \'bower_components/semantic-ui\'\n' +
      '      ]\n' +
      '    },\n' +
      '    SemanticUI: {\n' +
      '      import: {\n' +
      '        css: false,\n' +
      '        javascript: true,\n' +
      '        images: false,\n' +
      '        fonts: true\n' +
      '      }\n' +
      '    }\n';

    /*
      Following packages should be installed as dependencies of `ember-flexberry-data`:
      `ember-browserify`, `dexie`.
	  Also `app/browserify.js` should be removed when check this.
    */

    return this.insertIntoFile(
      'ember-cli-build.js',
      imports,
      {
        before: 'return app.toTree();\n'
      }
    ).then(function() {
      return _this.insertIntoFile(
        'ember-cli-build.js',
        options,
        {
          after: 'var app = new EmberApp(defaults, {\n'
        }
      );
    }).then(function() {
      return _this.insertIntoFile(
        'ember-cli-build.js',
        options,
        {
          after: 'var app = new EmberAddon(defaults, {\n'
        }
      );
    }).then(function() {
      return _this.insertIntoFile(
        'app/index.html',
        '    <script src="//cdn.polyfill.io/v1/polyfill.js?features=es6"></script>',
        {
          after: '<script src="assets/dummy.js"></script>\n'
        }
      );
    }).then(function() {
      return _this.insertIntoFile(
        'tests/index.html',
        '    <script src="//cdn.polyfill.io/v1/polyfill.js?features=es6"></script>',
        {
          after: '<script src="assets/dummy.js"></script>\n'
        }
      );
    }).then(function() {
      return _this.insertIntoFile(
        'tests/dummy/app/index.html',
        '    <script src="//cdn.polyfill.io/v1/polyfill.js?features=es6"></script>',
        {
          after: '<script src="assets/dummy.js"></script>\n'
        }
      );
    }).then(function() {
      return _this.addBowerPackagesToProject([
        { name: 'semantic-ui-daterangepicker', target: '5d46ed2e6e5a0bf398bb6a5df82e06036dfc46be' },
        { name: 'flatpickr-calendar', source: 'git://github.com/chmln/flatpickr.git', target: '2.3.4' },
        { name: 'blueimp-file-upload', target: '9.11.2' },
        { name: 'devicejs', target: '0.2.7' }
      ]);
    }).then(function() {
      return _this.addBowerPackageToProject('semantic-ui','git://github.com/Flexberry/Semantic-UI.git#fixed-abort');
    }).then(function() {
      return _this.addAddonsToProject({
        packages: [
          { name: 'ember-moment', target: '6.0.0' },
          { name: 'ember-link-action', target: '0.0.34' },
          { name: 'ember-cli-less', target: '1.5.4' },
          { name: 'broccoli-jscs', target: '1.2.2' },
          { name: 'ember-browserify', target: '1.1.9' }
        ]
      });
    }).then(function () {
      return _this.addPackagesToProject([
        { name: 'dexie', target: '1.4.2' },
        { name: 'node-uuid', target: '1.4.7' },
        { name: 'inflection', target: '1.10.0' }
      ]);
    }).then(function () {
      return _this.addPackageToProject('semantic-ui-ember','git://github.com/Flexberry/Semantic-UI-Ember.git#version-0.9.3');
    });
  },

  normalizeEntityName: function() {}
};
<|endoftext|>


<commit_before>// Copyright 2017 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Class for SSML rendering of descriptions.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */
goog.provide('sre.SsmlRenderer');

goog.require('sre.Engine');
goog.require('sre.XmlRenderer');

/**
 * @constructor
 * @extends {sre.XmlRenderer}
 */
sre.SsmlRenderer = function() {
  sre.SsmlRenderer.base(this, 'constructor');
};
goog.inherits(sre.SsmlRenderer, sre.XmlRenderer);

/**
 * @override
 */
sre.SsmlRenderer.prototype.finalize = function(str) {
  return '<?xml version="1.0"?><speak version="1.1"' +
      ' xmlns="http://www.w3.org/2001/10/synthesis">' +
      '<prosody rate="' + sre.Engine.getInstance().getRate() + '%">' +
      this.getSeparator() + str + this.getSeparator() + '</prosody></speak>';
};

/**
 * @override
 */
sre.SsmlRenderer.prototype.pause = function(pause) {
  return '<break ' + 'time="' +
      this.pauseValue(pause[sre.Engine.personalityProps.PAUSE]) + 'ms"/>';
};

/**
 * @override
 */
sre.SsmlRenderer.prototype.prosodyElement = function(attr, value) {
  value = this.applyScaleFunction(value);
  var valueStr = value < 0 ? value.toString() : '+' + value;
  return '<prosody ' + attr.toLowerCase() + '="' + Math.floor(valueStr) +
      (attr === sre.Engine.personalityProps.VOLUME ? '>' : '%">');
};

/**
 * @override
 */
sre.SsmlRenderer.prototype.closeTag = function(tag) {
  return '</prosody>';
};
<commit_msg>Fixes issue #326.<commit_after>// Copyright 2017 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Class for SSML rendering of descriptions.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */
goog.provide('sre.SsmlRenderer');

goog.require('sre.Engine');
goog.require('sre.XmlRenderer');

/**
 * @constructor
 * @extends {sre.XmlRenderer}
 */
sre.SsmlRenderer = function() {
  sre.SsmlRenderer.base(this, 'constructor');
};
goog.inherits(sre.SsmlRenderer, sre.XmlRenderer);

/**
 * @override
 */
sre.SsmlRenderer.prototype.finalize = function(str) {
  return '<?xml version="1.0"?><speak version="1.1"' +
      ' xmlns="http://www.w3.org/2001/10/synthesis">' +
      '<prosody rate="' + sre.Engine.getInstance().getRate() + '%">' +
      this.getSeparator() + str + this.getSeparator() + '</prosody></speak>';
};

/**
 * @override
 */
sre.SsmlRenderer.prototype.pause = function(pause) {
  return '<break ' + 'time="' +
      this.pauseValue(pause[sre.Engine.personalityProps.PAUSE]) + 'ms"/>';
};

/**
 * @override
 */
sre.SsmlRenderer.prototype.prosodyElement = function(attr, value) {
  value = Math.floor(this.applyScaleFunction(value));
  var valueStr = value < 0 ? value.toString() : '+' + value.toString();
  return '<prosody ' + attr.toLowerCase() + '="' + valueStr +
      (attr === sre.Engine.personalityProps.VOLUME ? '>' : '%">');
};

/**
 * @override
 */
sre.SsmlRenderer.prototype.closeTag = function(tag) {
  return '</prosody>';
};
<|endoftext|>


<commit_before>/**
 * @summary     ConditionalPaging
 * @description Hide paging controls when the amount of pages is <= 1
 * @version     1.0.0
 * @file        dataTables.conditionalPaging.js
 * @author      Matthew Hasbach (https://github.com/mjhasbach)
 * @contact     hasbach.git@gmail.com
 * @copyright   Copyright 2015 Matthew Hasbach
 *
 * License      MIT - http://datatables.net/license/mit
 *
 * This feature plugin for DataTables hides paging controls when the amount
 * of pages is <= 1. The controls can either appear / disappear or fade in / out
 *
 * @example
 *    $('#myTable').DataTable({
 *        conditionalPaging: true
 *    });
 *
 * @example
 *    $('#myTable').DataTable({
 *        conditionalPaging: {
 *            style: 'fade',
 *            speed: 500 // optional
 *        }
 *    });
 */

(function(window, document, $) {
    $(document).on('init.dt', function(e, dtSettings) {
        var options = dtSettings.oInit.conditionalPaging;

        if ($.isPlainObject(options) || options === true) {
            var config = $.isPlainObject(options) ? options : {},
                api = new $.fn.dataTable.Api(dtSettings),
                speed = 'slow',
                conditionalPaging = function() {
                    var $paging = $(api.table().container()).find('div.dataTables_paginate');

                    if (api.page.info().pages <= 1) {
                        if (config.style === 'fade') {
                            $paging.stop().fadeTo(speed, 0);
                        }
                        else {
                            $paging.css('visibility', 'hidden');
                        }
                    }
                    else {
                        if (config.style === 'fade') {
                            $paging.stop().fadeTo(speed, 1);
                        }
                        else {
                            $paging.css('visibility', '');
                        }
                    }
                };

            if ($.isNumeric(config.speed) || $.type(config.speed) === 'string') {
                speed = config.speed;
            }

            conditionalPaging();

            api.on('draw.dt', conditionalPaging);
        }
    });
})(window, document, jQuery);<commit_msg>Fixed a bug in which the paging controls would fade out after table initialization if the "fade" style was chosen<commit_after>/**
 * @summary     ConditionalPaging
 * @description Hide paging controls when the amount of pages is <= 1
 * @version     1.0.0
 * @file        dataTables.conditionalPaging.js
 * @author      Matthew Hasbach (https://github.com/mjhasbach)
 * @contact     hasbach.git@gmail.com
 * @copyright   Copyright 2015 Matthew Hasbach
 *
 * License      MIT - http://datatables.net/license/mit
 *
 * This feature plugin for DataTables hides paging controls when the amount
 * of pages is <= 1. The controls can either appear / disappear or fade in / out
 *
 * @example
 *    $('#myTable').DataTable({
 *        conditionalPaging: true
 *    });
 *
 * @example
 *    $('#myTable').DataTable({
 *        conditionalPaging: {
 *            style: 'fade',
 *            speed: 500 // optional
 *        }
 *    });
 */

(function(window, document, $) {
    $(document).on('init.dt', function(e, dtSettings) {
        var options = dtSettings.oInit.conditionalPaging;

        if ($.isPlainObject(options) || options === true) {
            var config = $.isPlainObject(options) ? options : {},
                api = new $.fn.dataTable.Api(dtSettings),
                speed = 'slow',
                conditionalPaging = function(e) {
                    var $paging = $(api.table().container()).find('div.dataTables_paginate'),
                        pages = api.page.info().pages;

                    if ($.isPlainObject(e)) {
                        if (pages <= 1) {
                            if (config.style === 'fade') {
                                $paging.stop().fadeTo(speed, 0);
                            }
                            else {
                                $paging.css('visibility', 'hidden');
                            }
                        }
                        else {
                            if (config.style === 'fade') {
                                $paging.stop().fadeTo(speed, 1);
                            }
                            else {
                                $paging.css('visibility', '');
                            }
                        }
                    }
                    else if (pages <= 1) {
                        if (config.style === 'fade') {
                            $paging.css('opacity', 0);
                        }
                        else {
                            $paging.css('visibility', 'hidden');
                        }
                    }
                };

            if ($.isNumeric(config.speed) || $.type(config.speed) === 'string') {
                speed = config.speed;
            }

            conditionalPaging();

            api.on('draw.dt', conditionalPaging);
        }
    });
})(window, document, jQuery);<|endoftext|>


<commit_before>'use strict';
var ConversationService;
$(document).ready(function(){

  var $conversationContainer =  $("#conversation-container");

  var conversationId = chrome.extension.getBackgroundPage().focusedConversationId;
  ConversationService = chrome.extension.getBackgroundPage().ConversationService;

  ConversationService.getConversation(conversationId).then(function(conversation){
    var messages = conversation.messages;
    for(var i = 0; i < messages.length; i++) {
      var message = messages[i];
      updateConversation(message.from, messages[i].message);
      scrollToBottom();
    }
  });

  chrome.storage.onChanged.addListener(function(changes, namespace) {
    ConversationService.getConversation(conversationId).then(function(conversation){
      var messages = conversation.messages;
      for (var i = 0; i < changes.conversations.oldValue.length; i++) {
            var tempConversation = changes.conversations.oldValue[i];
            if (tempConversation.id == conversationId) {
              if(tempConversation.messages.length < messages.length) {
                var message = messages[messages.length-1];
                updateConversation(message.from, message.message);
                scrollToBottom();
              }
              break;
            }
      }
    });
  });

  $('#send-button').on('click',function(event) {
    event.preventDefault();
    sendMessage(conversationId);
  });

  $("#reply-text-area").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        sendMessage(conversationId);
    }
  });

});

function updateConversation(from, message) {
  var $conversationContainer =  $("#conversation-container");
  message = format(message);
  $conversationContainer.append("
" + from + " : " + message + "
");
}

function format(message) {
  message = linkifyUrls(message);
  return message;
}

function linkifyUrls(text) {
  var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function(url) {
    return '' + url + '';
  });
}

function scrollToBottom() {
  var elem = document.getElementById('conversation-container');
  elem.scrollTop = elem.scrollHeight;
}

function sendMessage(conversationId) {
  var text = $('#reply-text-area').val();
  var payload = '{"autemTextMessage" : {"from":"me",' + '"to":"' + conversationId + '","message":"'+ text +'"}}';
  ConversationService.sendMessage(conversationId, payload);
  $('#reply-text-area').val('');
}<commit_msg>focus text area when opening convo<commit_after>'use strict';
var ConversationService;
$(document).ready(function(){
  $("#reply-text-area").focus();
  var $conversationContainer =  $("#conversation-container");

  var conversationId = chrome.extension.getBackgroundPage().focusedConversationId;
  ConversationService = chrome.extension.getBackgroundPage().ConversationService;

  ConversationService.getConversation(conversationId).then(function(conversation){
    var messages = conversation.messages;
    for(var i = 0; i < messages.length; i++) {
      var message = messages[i];
      updateConversation(message.from, messages[i].message);
      scrollToBottom();
    }
  });

  chrome.storage.onChanged.addListener(function(changes, namespace) {
    ConversationService.getConversation(conversationId).then(function(conversation){
      var messages = conversation.messages;
      for (var i = 0; i < changes.conversations.oldValue.length; i++) {
            var tempConversation = changes.conversations.oldValue[i];
            if (tempConversation.id == conversationId) {
              if(tempConversation.messages.length < messages.length) {
                var message = messages[messages.length-1];
                updateConversation(message.from, message.message);
                scrollToBottom();
              }
              break;
            }
      }
    });
  });

  $('#send-button').on('click',function(event) {
    event.preventDefault();
    sendMessage(conversationId);
  });

  $("#reply-text-area").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        sendMessage(conversationId);
    }
  });

});

function updateConversation(from, message) {
  var $conversationContainer =  $("#conversation-container");
  message = format(message);
  $conversationContainer.append("
" + from + " : " + message + "
");
}

function format(message) {
  message = linkifyUrls(message);
  return message;
}

function linkifyUrls(text) {
  var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function(url) {
    return '' + url + '';
  });
}

function scrollToBottom() {
  var elem = document.getElementById('conversation-container');
  elem.scrollTop = elem.scrollHeight;
}

function sendMessage(conversationId) {
  var text = $('#reply-text-area').val();
  var payload = '{"autemTextMessage" : {"from":"me",' + '"to":"' + conversationId + '","message":"'+ text +'"}}';
  ConversationService.sendMessage(conversationId, payload);
  $('#reply-text-area').val('');
}<|endoftext|>


<commit_before>class Index {
    constructor() {
        this.indexArray = [];
    }
    readFile(file) {
        var reader = new FileReader();
        reader.readAsText(file);
        reader.onload = () => {
            var json = JSON.parse(reader.result);
            this.createIndex(json);
        }
    }

    createIndex(json) {
        console.log('CONtent', json);
        if (json != null) {
            var indexTerms = [];
            for (let object of json) {
                for (let key in object) {
                    if (object.hasOwnProperty(key)) {
                        let terms = object[key].toLowerCase().split(/\W+/);
                        for (let term of terms) {
                            //pushes a term into indexTerms array if the terms is not present
                            if (indexTerms.indexOf(term) < 0) {
                                indexTerms.push(term);
                            }
                        }
                    }
                }
            }

            var index = {};
            //index['file'] = file.name;
            for (let indexTerm of indexTerms) {
                var objects = [];
                var i = 0;
                for (let object of json) {
                    for (let key in object) {
                        if (object.hasOwnProperty(key)) {
                            let terms = object[key].toLowerCase().split(/\W+/);
                            if (terms.indexOf(indexTerm) > -1 & objects.indexOf(i) < 0) {
                                objects.push(i);
                            }
                        }
                    }
                    i++;
                }
                index[indexTerm] = objects;
            }
            this.indexArray.push(index);
            // display.innerText = 'Index created';
            // alert('index created');
            for (let [key, value] of Object.entries(index)) {
                termstable.innerHTML = termstable.innerHTML + '
' + key + '	' + (value.includes(0) ?
                        '  	' : ' 	') +
                    (value.includes(1) ? '	' : '	') + '
';
            }
        }
    }

    getIndex(file) {
        if (this.indexArray.length != 0) {
            for (let index of this.indexArray) {
                if (index.file == file) {
                    display.innerText = index.toSource();
                }
            }
        }
    }

    searchIndex(valuesToSearch) {
        if (this.indexArray.length != 0) {
            var results = [];
            var tokens = valuesToSearch.split(/\s*(,|\s)\s*/);
            if (tokens[0].indexOf('.json') > -1) {
                for (let index of this.indexArray) {
                    if (index.file == tokens[0]) {
                        var indexToUse = index;
                        break;

                    }
                }
                tokens.shift();
                for (let token of tokens) {
                    results.push(indexToUse[token.toLowerCase()]);

                }
            } else {
                for (let token of tokens) {
                    for (let index of this.indexArray) {
                        if (index[token.toLowerCase()] != undefined) {
                            results.push(index['file'] + " : " + index[token.toLowerCase()]);

                        }
                    }
                }
            }
            display.innerText = results;

        }
    }

}<commit_msg>Modularize data<commit_after>class Index {
    constructor() {
        this.indexArray = [];
    }
    readFile(file) {
        var reader = new FileReader();
        reader.readAsText(file);
        reader.onload = () => {
            var json = JSON.parse(reader.result);
            this.displayIndex(json);
            this.json = json;
        }
    }

    createIndex(json) {
        if (json != null) {
            var indexTerms = [];
            for (let object of json) {
                for (let key in object) {
                    if (object.hasOwnProperty(key)) {
                        let terms = object[key].toLowerCase().split(/\W+/g);
                        for (let term of terms) {
                            //pushes a term into indexTerms array if the terms is not present
                            if (indexTerms.indexOf(term) < 0) {
                                indexTerms.push(term);
                            }
                        }
                    }
                }
            }

            var index = {};
            for (let indexTerm of indexTerms) {
                var objects = [];
                var i = 0;
                for (let object of json) {
                    for (let key in object) {
                        if (object.hasOwnProperty(key)) {
                            let terms = object[key].toLowerCase().split(/\W+/g);
                            if (terms.indexOf(indexTerm) > -1 & objects.indexOf(i) < 0) {
                                objects.push(i);
                            }
                        }
                    }
                    i++;
                }
                index[indexTerm] = objects;
            }
            this.indexArray.push(index);
        }
    }

    displayIndex(json) {
        this.createIndex(json);
        let createdIndex = this.indexArray;
        let toBeDisplayed = createdIndex.shift();
        console.log(toBeDisplayed);
        for (let [key, value] of Object.entries(toBeDisplayed)) {
            termstable.innerHTML = termstable.innerHTML + '
' + key + '	' + (value.includes(0) ?
                    '  	' : ' 	') +
                (value.includes(1) ? '	' : '	') + '
';
        }

    }

    getIndex(file) {
        if (this.indexArray.length != 0) {
            for (let index of this.indexArray) {
                if (index.file == file) {
                    display.innerText = index.toSource();
                }
            }
        }
    }

    searchIndex(valuesToSearch) {
        this.createIndex(this.json);
        if (this.indexArray.length != 0) {
            var results = {};
            var tokens = valuesToSearch.split(/\s*(,|\s)\s*/);
            if (tokens[0].indexOf('.json') > -1) {
                for (let index of this.indexArray) {
                    if (index.file == tokens[0]) {
                        var indexToUse = index;
                        break;

                    }
                }
                tokens.shift();
                for (let token of tokens) {
                    results[token] = indexToUse[token.toLowerCase()];

                }
            } else {
                for (let token of tokens) {
                    for (let index of this.indexArray) {
                        if (index[token.toLowerCase()] != undefined) {
                            results[token] = index[token.toLowerCase()];
                        }
                    }
                }
            }

            return results;
        }
    }

    displaySearch(valuesToSearch) {
        let searchResults = this.searchIndex(valuesToSearch);
        for (let [key, value] of Object.entries(searchResults)) {
            termstable.innerHTML = '

Words

Document one

Document Two

' + key + '	' + (value.includes(0) ?
                    '  	' : ' 	') +
                (value.includes(1) ? '	' : '	') + '
';
        }

    }

}<|endoftext|>


<commit_before>class Index {
	constructor() {
		//constructor method is called when an instance of the Index class is created
		this.indexArray = [];
		/*this.indexArray class level array is instantiated to hold the indices of JSON files*/
	}

	createIndex(filePath) {
		//createIndex method takes the JSON file path as the argument
		var file = filePath.files[0];
		//getting the actual file
		var reader = new FileReader();
		//an instance of the FileReader class is created to read the contents of the file
		reader.onloadend = () => {
			//what happens after reading the file; we make it an arrow function so as to access the class level index array
			var json = JSON.parse(reader.result);
			//the result is returned as a string(readAsText), so it has to be parsed
			if (json != null) {
				//continues if the JSON file has content
				var indexTerms = [];
				//indexTerms array is instantiated to hold unique terms for the index
				for (let object of json) {
					/*from the returned JSON(json) we get the text values of each JSON object {}
					by looping through the JSON array []*/
					let text = object.text.toLowerCase();
					//the text values are lowercased
					let terms = text.split(/\W+/);
					//we then split the text values with non-word characters as separator to get the terms
					for (let term of terms) {
						/*we loop through the terms, adding each term only once to
						indexTerms array to create a unique array of terms for the index*/
						if (indexTerms.indexOf(term) < 0) {
							indexTerms.push(term);
						}
					}
				}

				var index = {};
				/*index object(dictionary) is instantiated to hold key(indexTerms) - value(positions of JSON objects containing the index term)
				pairs of the index*/
				index['filePath'] = filePath.value;
				//the file path is the first entry to the index object to distinguish the indices
				for (let indexTerm of indexTerms) {
					//we loop through the indexTerms, testing if each is contained in each of the text values of the JSON array
					var objects = [];
					//objects array is instantiated to hold the position(s) of the JSON object(s) containing the index term
					for (let i = 0; i < json.length; i++) {
						let text = json[i].text.toLowerCase();
						let terms = text.split(/\W+/);
						if (terms.indexOf(indexTerm) > -1) {
							objects.push(i);
						}
						/*if the index term is contained in the text value of the JSON object, the position of the JSON object is
						added to the objects array*/
					}
					index[indexTerm] = objects;
					/*a key-value pair is entered into the index with the key as the index term and the value as
					an array of position(s) of JSON object(s) containing the index term*/
				}
				this.indexArray.push(index);
				//the index is then added to the index array
				display.innerText = 'Index created';
			}
		}
		reader.readAsText(file);
		//the reader reads the file and returns a string of the content
	}

	getIndex(filePath) {
		//getIndex method takes the JSON file path as the argument
		if (this.indexArray.length != 0) {
			//continues if the index array has content
			for (let index of this.indexArray) {
				//we loop through the indices to find the index that matches the file path
				if (index.filePath == filePath) {
					display.innerText = index.toSource();
				}
				//when the index is gotten, it is returned
			}
		}
	}

	searchIndex(terms) {
		//searchIndex method takes a variable number of terms to search (...) as the argument
		var results = [];
		//results array is instantiated to hold results of the search
		var tokens = terms.split(/\s*(,|\s)\s*/);
		//the terms are split using commas and whitespaces(regex) as separator to tokens
		if (this.indexArray.length != 0) {
			if (tokens[0].indexOf('.json') > -1) {
				//if the first token is a JSON file, it will search the JSON file only
				for (let index of this.indexArray) {
					//we loop through the indices to establish the index to use using the file path
					if (index.filePath == tokens[0]) {
						var indexToUse = index;
						break;
					}
				}
				tokens.shift();
				//the first token(JSON file path) is removed
				for (let x of tokens) {
					//we loop through the remaining tokens and return the position(s) of the JSON object(s) containing the tokens
					if (Array.isArray(x)) {
						//if the token is an array, we return each of the items in the array
						for (let y of x) {
							if (Array.isArray(y)) {
								//if the item of the token array is another array, we return each of the items in the item array
								for (let z of y) {
									results.push(indexToUse[z.toLowerCase()]);
								}
							} else {
								results.push(indexToUse[y.toLowerCase()]);
								//if the item of the token array is not an array, we return the item
							}
						}
					} else {
						results.push(indexToUse[x.toLowerCase()]);
						//if the token is not an array, we return the token
					}
				}
				display.innerText = results;
				//results are then displayed
			} else {
				//if the first token is not a JSON file, it will search the entire index array
				for (let x of tokens) {
					if (Array.isArray(x)) {
						for (let y of x) {
							if (Array.isArray(y)) {
								for (let z of y) {
									for (let index of this.indexArray) {
										//we loop through the indices to get the index where the token is defined
										if (index[z.toLowerCase()] != undefined) {
											//when we get an index, its file path and the position(s) are returned
											results.push(index['filePath']+" : "+index[z.toLowerCase()]);
										}
									}
								}
							} else {
								for (let index of this.indexArray) {
									if (index[y.toLowerCase()] != undefined) {
										results.push(index['filePath']+" : "+index[y.toLowerCase()]);
									}
								}
							}
						}
					} else {
						for (let index of this.indexArray) {
							if (index[x.toLowerCase()] != undefined) {
								results.push(index['filePath']+" : "+index[x.toLowerCase()]);
							}
						}
					}
				}
			}
			display.innerText = results;
		}
	}
}

window.onload = () => {
	var instance = new Index();

	var filePath = document.getElementById('filePath');
	var createIndexButton = document.getElementById('createIndexButton');
	var terms = document.getElementById('terms');
	var searchButton = document.getElementById('searchButton');
	var display = document.getElementById('display');

	createIndexButton.addEventListener('click', function(e) {
		instance.createIndex(filePath);
	});

	searchButton.addEventListener('click', function(e) {
		instance.searchIndex(terms.value);
	});
}<commit_msg>Change the search index button<commit_after>class Index {
	constructor() {
		//constructor method is called when an instance of the Index class is created
		this.indexArray = [];
		/*this.indexArray class level array is instantiated to hold the indices of JSON files*/
	}

	createIndex(filePath) {
		//createIndex method takes the JSON file path as the argument
		var file = filePath.files[0];
		//getting the actual file
		var reader = new FileReader();
		//an instance of the FileReader class is created to read the contents of the file
		reader.readAsText(file);
		//the reader reads the file and returns a string of the content
		reader.onloadend = () => {
			//what happens after reading the file; we make it an arrow function so as to access the class level index array
			var json = JSON.parse(reader.result);
			//the result is returned as a string(readAsText), so it has to be parsed
			if (json != null) {
				//continues if the JSON file has content
				var indexTerms = [];
				//indexTerms array is instantiated to hold unique terms for the index
				for (let object of json) {
					/*from the returned JSON(json) we get the text values of each JSON object {}
					by looping through the JSON array []*/
					let text = object.text.toLowerCase();
					//the text values are lowercased
					let terms = text.split(/\W+/);
					//we then split the text values with non-word characters as separator to get the terms
					for (let term of terms) {
						/*we loop through the terms, adding each term only once to
						indexTerms array to create a unique array of terms for the index*/
						if (indexTerms.indexOf(term) < 0) {
							indexTerms.push(term);
						}
					}
				}

				var index = {};
				/*index object(dictionary) is instantiated to hold key(indexTerms) - value(positions of JSON objects containing the index term)
				pairs of the index*/
				index['filePath'] = filePath.value;
				//the file path is the first entry to the index object to distinguish the indices
				for (let indexTerm of indexTerms) {
					//we loop through the indexTerms, testing if each is contained in each of the text values of the JSON array
					var objects = [];
					//objects array is instantiated to hold the position(s) of the JSON object(s) containing the index term
					for (let i = 0; i < json.length; i++) {
						let text = json[i].text.toLowerCase();
						let terms = text.split(/\W+/);
						if (terms.indexOf(indexTerm) > -1) {
							objects.push(i);
						}
						/*if the index term is contained in the text value of the JSON object, the position of the JSON object is
						added to the objects array*/
					}
					index[indexTerm] = objects;
					/*a key-value pair is entered into the index with the key as the index term and the value as
					an array of position(s) of JSON object(s) containing the index term*/
				}
				this.indexArray.push(index);
				//the index is then added to the index array
				display.innerText = 'Index created';
			}
		}

	}

	getIndex(filePath) {
		display.innerText=this.indexArray.toSource();
		//getIndex method takes the JSON file path as the argument
		if (this.indexArray.length != 0) {
			//continues if the index array has content
			for (let index of this.indexArray) {
				//we loop through the indices to find the index that matches the file path
				if (index.filePath == filePath) {
					display.innerText = index.toSource();
				}
				//when the index is gotten, it is returned
			}
		}
	}

	searchIndex(terms) {
		//searchIndex method takes a variable number of terms to search (...) as the argument
		var results = [];
		//results array is instantiated to hold results of the search
		var tokens = terms.split(/\s*(,|\s)\s*/);
		//the terms are split using commas and whitespaces(regex) as separator to tokens
		if (this.indexArray.length != 0) {
			if (tokens[0].indexOf('.json') > -1) {
				//if the first token is a JSON file, it will search the JSON file only
				for (let index of this.indexArray) {
					//we loop through the indices to establish the index to use using the file path
					if (index.filePath == tokens[0]) {
						var indexToUse = index;
						break;
					}
				}
				tokens.shift();
				//the first token(JSON file path) is removed
				for (let x of tokens) {
					//we loop through the remaining tokens and return the position(s) of the JSON object(s) containing the tokens
					if (Array.isArray(x)) {
						//if the token is an array, we return each of the items in the array
						for (let y of x) {
							if (Array.isArray(y)) {
								//if the item of the token array is another array, we return each of the items in the item array
								for (let z of y) {
									results.push(indexToUse[z.toLowerCase()]);
								}
							} else {
								results.push(indexToUse[y.toLowerCase()]);
								//if the item of the token array is not an array, we return the item
							}
						}
					} else {
						results.push(indexToUse[x.toLowerCase()]);
						//if the token is not an array, we return the token
					}
				}
				display.innerText = results;
				//results are then displayed
			} else {
				//if the first token is not a JSON file, it will search the entire index array
				for (let x of tokens) {
					if (Array.isArray(x)) {
						for (let y of x) {
							if (Array.isArray(y)) {
								for (let z of y) {
									for (let index of this.indexArray) {
										//we loop through the indices to get the index where the token is defined
										if (index[z.toLowerCase()] != undefined) {
											//when we get an index, its file path and the position(s) are returned
											results.push(index['filePath']+" : "+index[z.toLowerCase()]);
										}
									}
								}
							} else {
								for (let index of this.indexArray) {
									if (index[y.toLowerCase()] != undefined) {
										results.push(index['filePath']+" : "+index[y.toLowerCase()]);
									}
								}
							}
						}
					} else {
						for (let index of this.indexArray) {
							if (index[x.toLowerCase()] != undefined) {
								results.push(index['filePath']+" : "+index[x.toLowerCase()]);
							}
						}
					}
				}
			}
			display.innerText = results;
			console.log(results);
		}
	}
}

window.onload = () => {
	var instance = new Index();

	var filePath = document.getElementById('filePath');
	var createIndexButton = document.getElementById('createIndexButton');
	var terms = document.getElementById('terms');
	var searchButton = document.getElementById('searchButton');
	var display = document.getElementById('display');

	createIndexButton.addEventListener('click', () =>{
		instance.createIndex(filePath);
	});

	searchButton.addEventListener('click', () => {
		instance.searchIndex(terms.value);
		//instance.getIndex(terms.value);
	});
}<|endoftext|>