<commit_before>module.exports = {
  name: 'Store YouTube Info',
  section: 'Audio Control',

  subtitle (data) {
    const info = ['Video ID', 'Video URL', 'Video Title', 'Video Description', 'Video Owner', 'Video ChannelID', 'Video ThumbnailUrl', 'Video EmbedURL', 'Video Genre', 'Video Paid', 'Video Unlisted', 'Video isFamilyFriendly', 'Video Duration', 'Video Views', 'Video regionsAllowed', 'Video commentCount', 'Video  likeCount', 'Video  dislikeCount', 'Video  channelThumbnailUrl']
    return `YouTube ${info[parseInt(data.info)]}`
  },

  variableStorage (data, varType) {
    const type = parseInt(data.storage)
    if (type !== varType) return
    const info = parseInt(data.info)
    let dataType = 'Unknown YouTube Type'
    switch (info) {
      case 0:
        dataType = 'YouTube Video ID'
        break
      case 1:
        dataType = 'YouTube Video URL'
        break
      case 2:
        dataType = 'YouTube Video Title'
        break
      case 3:
        dataType = 'YouTube Video Description'
        break
      case 4:
        dataType = 'YouTube Video Owner'
        break
      case 5:
        dataType = 'YouTube Video ChannelID'
        break
      case 6:
        dataType = 'YouTube Video ThumbnailUrl'
        break
      case 7:
        dataType = 'YouTube Video EmbedURL'
        break
      case 8:
        dataType = 'YouTube Video Genre'
        break
      case 9:
        dataType = 'YouTube Video Paid'
        break
      case 10:
        dataType = 'YouTube Video Unlisted'
        break
      case 11:
        dataType = 'YouTube Video isFamilyFriendly'
        break
      case 12:
        dataType = 'YouTube Video Duration'
        break
      case 13:
        dataType = 'YouTube Video Views'
        break
      case 14:
        dataType = 'YouTube Video regionsAllowed'
        break
      case 15:
        dataType = 'YouTube Video commentCount'
        break
      case 16:
        dataType = 'YouTube Video likeCount'
        break
      case 17:
        dataType = 'YouTube Video dislikeCount'
        break
      case 18:
        dataType = 'YouTube Video channelThumbnailUrl'
        break
    }
    return ([data.varName, dataType])
  },

  fields: ['video', 'info', 'storage', 'varName'],

  html (isEvent, data) {
    return `

    Video to Search:

    <textarea id="video" rows="2" placeholder="Video ID or Video URL Goes here!" style="width: 95%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

    Source Info:

    <select id="info" class="round">
      <option value="0">Video ID</option>
      <option value="1">Video URL</option>
      <option value="2">Video Title</option>
      <option value="3">Video Description</option>
      <option value="4">Video Owner</option>
      <option value="5">Video ChannelID</option>
      <option value="6">Video ThumbnailUrl</option>
      <option value="7">Video EmbedURL</option>
      <option value="8">Video Genre</option>
      <option value="9">Video Paid</option>
      <option value="10">Video Unlisted</option>
      <option value="11">Video isFamilyFriendly</option>
      <option value="12">Video Duration(hh:mm:ss)</option>
      <option value="13">Video Views</option>
      <option value="14">Video regionsAllowed</option>
      <option value="15">Video commentCount</option>
      <option value="16">Video likeCount</option>
      <option value="17">Video dislikeCount</option>
      <option value="18">Video channelThumbnailUrl</option>
    </select>

      Store In:

      <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')">
        ${data.variables[0]}
      </select>

      Variable Name:

      <input id="varName" class="round" type="text">

`
  },

  init () {
    const { glob, document } = this

    glob.variableChange(document.getElementById('storage'), 'varNameContainer')
  },

  async action (cache) {
    const data = cache.actions[cache.index]
    const info = parseInt(data.info)
    const _this = this
    const video = this.evalMessage(data.video, cache)
    const Mods = this.getMods()
    const fetchVideoInfo = Mods.require('youtube-info')
    const TimeFormat = Mods.require('hh-mm-ss')
    const ytdl = Mods.require('ytdl-core')
    let result

    if (!video) return console.log('Please specify a video id to get video informations.')

    const songID = ytdl.getVideoID(video)

    fetchVideoInfo(songID, (err, videoInfo) => {
      if (err) return console.error(err)

      switch (info) {
        case 0:
          result = videoInfo.videoId
          break
        case 1:
          result = videoInfo.url
          break
        case 2:
          result = videoInfo.title
          break
        case 3:
          result = videoInfo.description
          break
        case 4:
          result = videoInfo.owner
          break
        case 5:
          result = videoInfo.channelId
          break
        case 6:
          result = videoInfo.thumbnailUrl
          break
        case 7:
          result = videoInfo.embedURL
          break
        case 8:
          result = videoInfo.genre
          break
        case 9:
          result = videoInfo.paid
          break
        case 10:
          result = videoInfo.unlisted
          break
        case 11:
          result = videoInfo.isFamilyFriendly
          break
        case 12:
          result = TimeFormat.fromS(videoInfo.duration) // check documentation/parameters ==> https://www.npmjs.com/package/hh-mm-ss
          // result = videoInfo.duration; just seconds =]]
          break
        case 13:
          result = videoInfo.views
          break
        case 14:
          result = videoInfo.regionsAllowed
          break
        case 15:
          result = videoInfo.commentCount
          break
        case 16:
          result = videoInfo.likeCount
          break
        case 17:
          result = videoInfo.dislikeCount
          break
        case 18:
          result = videoInfo.channelThumbnailUrl
          break
        default:
          break
      }

      if (result !== undefined) {
        const storage = parseInt(data.storage)
        const varName2 = _this.evalMessage(data.varName, cache)
        _this.storeValue(result, storage, varName2, cache)
      }
      _this.callNextAction(cache)
    })
  },

  mod () {}
}
<commit_msg>replace youtube-info with ytsr to fix 403 error (#468)<commit_after>module.exports = {
  name: 'Store YouTube Info',
  section: 'Audio Control',

  subtitle (data) {
    const info = ['Video ID', 'Video URL', 'Video Title', 'Video Description', 'Video Channel ID', 'Video Channel URL', 'Video Channel Name', 'Video Thumbnail URL', 'Video Duration', 'Video Publish Data', 'Video Views', 'Video is live?']
    return `YouTube ${info[parseInt(data.info)]}`
  },

  variableStorage (data, varType) {
    const type = parseInt(data.storage)
    if (type !== varType) return
    let dataType = 'Unknown Type'
    switch (parseInt(data.info)) {
      case 0: // Video ID
      case 2: // Video Title
      case 3: // Video Description
      case 5: // Video Channel ID
      case 4: // Video Channel Name
      case 12: // Video Duration
      case 21: // Video Publish Date
        dataType = 'Text'
        break
      case 1: // Video URL
      case 20: // Video Channel URL
        dataType = 'URL'
        break
      case 6: // Video Thumbnail URL
        dataType = 'Image URL'
        break
      case 19: // Video is live?
        dataType = 'Boolean'
        break
      case 13: // Video Views
        dataType = 'Number'
        break
    }
    return ([data.varName, dataType])
  },

  fields: ['video', 'info', 'storage', 'varName'],

  html (isEvent, data) {
    return `

    Video to Search:

    <textarea id="video" rows="2" placeholder="Video to search for goes here" style="width: 95%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>

    Source Info:

    <select id="info" class="round">
      <option value="0">Video ID</option>
      <option value="1">Video URL</option>
      <option value="2">Video Title</option>
      <option value="3">Video Description</option>
      <option value="4">Video Channel Name</option>
      <option value="5">Video Channel ID</option>
      <option value="20">Video Channel URL</option>
      <option value="6">Video Thumbnail URL</option>
      <option value="12">Video Duration</option>
      <option value="21">Video Publish Date</option>
      <option value="13">Video Views</option>
      <option value="19">Video is Live?</option>
    </select>

      Store In:

      <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')">
        ${data.variables[0]}
      </select>

      Variable Name:

      <input id="varName" class="round" type="text">

`
  },

  init () {
    const { glob, document } = this

    glob.variableChange(document.getElementById('storage'), 'varNameContainer')
  },

  async action (cache) {
    const data = cache.actions[cache.index]
    const info = parseInt(data.info)
    const _this = this
    const video = this.evalMessage(data.video, cache)
    const Mods = this.getMods()
    const TimeFormat = Mods.require('hh-mm-ss')
    const ytsr = Mods.require('ytsr')
    let result

    if (!video) return console.log('Please specify a video to get video informations.')

    ytsr(video, function (err, searchResults) {
      if (err) return console.error(err)
      const video = searchResults.item[0]

      switch (info) {
        case 0: // Video ID
          result = video.link.replace('https://www.youtube.com/watch?v=', '')
          break
        case 1: // Video URL
          result = video.link
          break
        case 2: // Video Title
          result = video.title.replace(/"/g, '"').replace(/&/g, '&').replace(/'/g, "'")
          break
        case 3: // Video Description
          result = video.description.replace(/"/g, '"').replace(/&/g, '&').replace(/'/g, "'")
          break
        case 4: // Video Channel Name
          result = video.author.name
          break
        case 5: // Video Channel ID
          result = video.author.ref.replace('https://www.youtube.com/channel/', '')
          break
        case 6: // Thumbnail URL (Default)
          result = video.thumbnail
          break
        case 12: // Video Duration
          result = TimeFormat.toS(video.duration)
          break
        case 13: // Video Views
          result = video.views
          break
        case 19: // is live?
          result = video.live
          break
        case 20: // Video Channel URL
          result = video.author.ref
          break
        case 21: // Video Publish Date
          result = video.uploaded_at
          break
        default:
          break
      }

      if (result !== undefined) {
        const storage = parseInt(data.storage)
        const varName2 = _this.evalMessage(data.varName, cache)
        _this.storeValue(result, storage, varName2, cache)
      }
      _this.callNextAction(cache)
    })
  },

  mod () {}
}
<|endoftext|>


<commit_before>/* globals requirejs, require */
"use strict";

let moduleIncludeMatchers = [];
let moduleExcludeMatchers = [];

export function addModuleIncludeMatcher(fn) {
  moduleIncludeMatchers.push(fn);
};

export function addModuleExcludeMatcher(fn) {
  moduleExcludeMatchers.push(fn);
};

function checkMatchers(matchers, moduleName) {
  return matchers.some(matcher => matcher(moduleName));
}

export default class TestLoader {
  constructor() {
    this._didLogMissingUnsee = false;
  }

  shouldLoadModule(moduleName) {
    return (moduleName.match(/[-_]test$/));
  }

  listModules() {
    return Object.keys(requirejs.entries);
  }

  listTestModules() {
    let moduleNames = this.listModules();
    let testModules = [];
    let moduleName;

    for (let i = 0; i < moduleNames.length; i++) {
      moduleName = moduleNames[i];

      if (checkMatchers(moduleExcludeMatchers, moduleName)) {
        continue;
      }

      if (checkMatchers(moduleIncludeMatchers, moduleName) || this.shouldLoadModule(moduleName)) {
        testModules.push(moduleName);
      }
    }

    return testModules;
  }

  loadModules() {
    let testModules = this.listTestModules();
    let testModule;

    for (let i = 0; i < testModules.length; i++) {
      testModule = testModules[i];
      this.require(testModule);
      this.unsee(testModule);
    }
  }

  require(moduleName) {
    try {
      require(moduleName);
    } catch(e) {
      this.moduleLoadFailure(moduleName, e);
    }
  }

  unsee(moduleName) {
    if (typeof require.unsee === 'function') {
      require.unsee(moduleName);
    } else if (!this._didLogMissingUnsee) {
      this._didLogMissingUnsee = true;
      if (typeof console !== 'undefined') {
        console.warn('unable to require.unsee, please upgrade loader.js to >= v3.3.0');
      }
    }
  }

  moduleLoadFailure(moduleName, error) {
    console.error('Error loading: ' + moduleName, error.stack);
  }

  static load() {
    new TestLoader().loadModules();
  }
};
<commit_msg>Remove unnecessary semicolons<commit_after>/* globals requirejs, require */
"use strict";

let moduleIncludeMatchers = [];
let moduleExcludeMatchers = [];

export function addModuleIncludeMatcher(fn) {
  moduleIncludeMatchers.push(fn);
}

export function addModuleExcludeMatcher(fn) {
  moduleExcludeMatchers.push(fn);
}

function checkMatchers(matchers, moduleName) {
  return matchers.some(matcher => matcher(moduleName));
}

export default class TestLoader {
  constructor() {
    this._didLogMissingUnsee = false;
  }

  shouldLoadModule(moduleName) {
    return (moduleName.match(/[-_]test$/));
  }

  listModules() {
    return Object.keys(requirejs.entries);
  }

  listTestModules() {
    let moduleNames = this.listModules();
    let testModules = [];
    let moduleName;

    for (let i = 0; i < moduleNames.length; i++) {
      moduleName = moduleNames[i];

      if (checkMatchers(moduleExcludeMatchers, moduleName)) {
        continue;
      }

      if (checkMatchers(moduleIncludeMatchers, moduleName) || this.shouldLoadModule(moduleName)) {
        testModules.push(moduleName);
      }
    }

    return testModules;
  }

  loadModules() {
    let testModules = this.listTestModules();
    let testModule;

    for (let i = 0; i < testModules.length; i++) {
      testModule = testModules[i];
      this.require(testModule);
      this.unsee(testModule);
    }
  }

  require(moduleName) {
    try {
      require(moduleName);
    } catch(e) {
      this.moduleLoadFailure(moduleName, e);
    }
  }

  unsee(moduleName) {
    if (typeof require.unsee === 'function') {
      require.unsee(moduleName);
    } else if (!this._didLogMissingUnsee) {
      this._didLogMissingUnsee = true;
      if (typeof console !== 'undefined') {
        console.warn('unable to require.unsee, please upgrade loader.js to >= v3.3.0');
      }
    }
  }

  moduleLoadFailure(moduleName, error) {
    console.error('Error loading: ' + moduleName, error.stack);
  }

  static load() {
    new TestLoader().loadModules();
  }
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import config from 'ember-get-config';

const {
  Component,
  computed,
  run,
  assert
} = Ember;

export default Component.extend({

  classNames: ['ag-grid-container'],
  tagName: 'div',
  theme: 'ag-fresh',
  width: '100%',
  height: '400px',
  gridOptions: undefined,

  containerStyle: computed('width', 'height', function () {
    let width = this.get('width');
    let height = this.get('height');

    assert('invalid width property; use auto, px, % or em',
      this._escapeCSS(width)
    );

    assert('invalid height property; use auto, px, % or em',
      this._escapeCSS(height)
    );

    return Ember.String.htmlSafe(`width: ${width}; height: ${height};`);
  }),

  _escapeCSS(css) {
    return /(^auto$|^\d*px$|^\d*%$|^\d*em$)/.test(css);
  },

  didInsertElement() {
    this._super(...arguments);

    let defaults = {columnDefs: [], rowData: []};
    const agGridOptions = typeof config !== "undefined" ? config.agGrid : false;

    if (!this.get('gridOptions')) {
      this.set('gridOptions', defaults);
    }

    run.scheduleOnce('afterRender', () => {
      if (agGridOptions && agGridOptions.useEnterprise && agGridOptions.licenseKey) {
        agGrid.LicenseManager.setLicenseKey(agGridOptions.licenseKey);
      }

      new agGrid.Grid(this.$('.agGrid')[0], this.get('gridOptions'));

    });
  },

  willDestroyElement() {
    this._super(...arguments);
    this.get('gridOptions').api.destroy();
  }

});
<commit_msg>Fixes error by checking if gridOptions and gridOptions api exists before tying to destroy component<commit_after>import Ember from 'ember';
import config from 'ember-get-config';

const {
  Component,
  computed,
  run,
  assert
} = Ember;

export default Component.extend({

  classNames: ['ag-grid-container'],
  tagName: 'div',
  theme: 'ag-fresh',
  width: '100%',
  height: '400px',
  gridOptions: undefined,

  containerStyle: computed('width', 'height', function () {
    let width = this.get('width');
    let height = this.get('height');

    assert('invalid width property; use auto, px, % or em',
      this._escapeCSS(width)
    );

    assert('invalid height property; use auto, px, % or em',
      this._escapeCSS(height)
    );

    return Ember.String.htmlSafe(`width: ${width}; height: ${height};`);
  }),

  _escapeCSS(css) {
    return /(^auto$|^\d*px$|^\d*%$|^\d*em$)/.test(css);
  },

  didInsertElement() {
    this._super(...arguments);

    let defaults = {columnDefs: [], rowData: []};
    const agGridOptions = typeof config !== "undefined" ? config.agGrid : false;

    if (!this.get('gridOptions')) {
      this.set('gridOptions', defaults);
    }

    run.scheduleOnce('afterRender', () => {
      if (agGridOptions && agGridOptions.useEnterprise && agGridOptions.licenseKey) {
        agGrid.LicenseManager.setLicenseKey(agGridOptions.licenseKey);
      }

      new agGrid.Grid(this.$('.agGrid')[0], this.get('gridOptions'));

    });
  },

  willDestroyElement() {
    this._super(...arguments);
    if (this.get('gridOptions') && this.get('gridOptions').api) {
      this.get('gridOptions').api.destroy();
    }
  }

});
<|endoftext|>


<commit_before>/**
  @module ember-flexberry-gis
*/

import Ember from 'ember';
import BaseMapCommand from './base';

/**
  Go to map-command.
  Moves map to a given geographic point.

  @class GoToMapCommand
  @extends BaseMapCommand
*/
export default BaseMapCommand.extend({
  /**
    Executes map-command.

    @method execute
  */
  _execute(options) {
    this._super(...arguments);

    let point = Ember.get(options, 'point');
    let crs = Ember.get(options, 'crs');
    let xCaption = Ember.get(options, 'xCaption');
    let yCaption = Ember.get(options, 'yCaption');

    let latlng = null;
    latlng = crs.unproject(point);

    let leafletMap = this.get('leafletMap');
    leafletMap.panTo(latlng);

    let popupContent = `${xCaption}: ${latlng.lng}; ${yCaption}: ${latlng.lat}`;

    leafletMap.openPopup(popupContent, latlng);
  }
});
<commit_msg>serach layer does not refresh after go to<commit_after>/**
  @module ember-flexberry-gis
*/

import Ember from 'ember';
import BaseMapCommand from './base';

/**
  Go to map-command.
  Moves map to a given geographic point.

  @class GoToMapCommand
  @extends BaseMapCommand
*/
export default BaseMapCommand.extend({
  /**
    Executes map-command.

    @method execute
  */
  _execute(options) {
    this._super(...arguments);

    let point = Ember.get(options, 'point');
    let crs = Ember.get(options, 'crs');
    let xCaption = Ember.get(options, 'xCaption');
    let yCaption = Ember.get(options, 'yCaption');

    let latlng = null;
    latlng = crs.unproject(point);

    let leafletMap = this.get('leafletMap');
    let popupContent = `${xCaption}: ${latlng.lng}; ${yCaption}: ${latlng.lat}`;

    leafletMap.openPopup(popupContent, latlng);
    leafletMap.panTo(latlng);
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
const { keys, create } = Object; // jshint ignore:line
const {computed, observer, $, A, run, on, typeOf, debug, defineProperty, get, set, inject, isEmpty} = Ember;  // jshint ignore:line

var ApiSurface = Ember.Mixin.create({
    // Selectize API surface
    // ------------------------------
    // bound values passed straight through to control
    apiPassThrough: [
      'optgroups',
      'inputClass','onInitialize','onDestroy','sortField','placeholder','copyClassesToDropdown',
      'create','createOnBlur','createFilter','highlight','persist','openOnFocus','maxOptions','maxItems','hideSelected',
      'allowEmptyOption','scrollDuration','dropdownParent','addPrecedence','selectOnTab',
      'optgroupField','optgroupValueField','optgroupLabelField',
      'score'
    ],
    // Arguably not needed except for "meta" reasons; these are props which are consumed directly by a CP
    // rather than Selectize (which would recieve a state change indirectly)
    apiIntermediate: [
      'valueField', 'labelField',
      'optgroupField', 'optgroupValueField', 'optgroupLabelField'
    ],
    // CP's to be used rather than bound value
    apiProcessed: [
      '_optgroupOrder', '_plugins', '_searchField', '_sortField'
    ],
    // Static mappings to API
    apiStaticMappings: {
      valueField: 'value',
      labelField: 'label',
      optgroupField: 'group'
    },
    copyClassesToDropdown: true,

    optgroups: null, // the array of optgroups
    optgroupField: 'group', // property name on "options" which refers to optgroupsValueField
    optgroupValueField: 'id', // the displayed name for optgroup
    optgroupLabelField: 'name', // property on "optgroups" array for the "value" which will match options property
    optgroupOrder: null, // array of optgroup keys in a particular order
    _optgroupOrder: computed('optgroupOrder', function() {
      let optgroupOrder = this.get('optgroupOrder');
      if (!optgroupOrder) {
        optgroupOrder = [];
      }

      return typeOf(optgroupOrder) === 'array' ? optgroupOrder : [optgroupOrder];
    }),
    plugins: null,
    _plugins: computed('plugins', function() {
      const plugins = this.get('plugins');
      return typeOf(plugins) === 'string' ? plugins.split(',') : plugins;
    }),

    onInitialize: null,
    onDestroy: null,
    labelField: 'name',
    valueField: 'id', // the field in the incoming hash which will be used for assigning a value to the input selector
    searchField: 'name', // property/properties to search through for a match
    _searchField: computed('searchField', function() {
      const searchField = this.get('searchField');
      return typeOf(searchField) === 'string' ? searchField.split(',') : searchField;
    }),
    searchConjunction: 'and', // when searching for multiple terms (seperated by a space)
    sortField: 'name',
    // Selectize allows "sortField" to be an array of objects or a string value;
    // we will just simplify this to the more versatile array of objects which also
    // allows the optional attribute "direction" (which is "asc" or "desc")
    _sortField: computed('sortField', function() {
      const sortField = this.get('sortField');
      const sortFields = typeOf(sortField) === 'string' ? sortField.split(',') : sortField;

      return sortFields.map( item => {
        switch(typeOf(item)) {
          case 'string':
            return {field: item};
          case 'object':
            return item;
          default:
            debug('an invalid property was passed to the sortField property: ' + JSON.stringify(item));
            return null;
        }
      }).filter( item => {
        return item !== null;
      });
    }),

    create: false, // allows user to create new items not on the list (can be true, false, or callback)
    createOnBlur: false,
    createFilter: null,
    highlight: true,
    persist: true, // options user created will show up after deselected
    openOnFocus: true,
    maxOptions: 1000,
    maxItems: 10000,
    hideSelected: false, // do not show items as option when already selected
    allowEmptyOption: false,
    scrollDuration: 60,
    dropdownParent: null,
    addPrecedence: false,
    selectOnTab: true,
    inputClass: 'form-control selectize-input',
    // callback function to score the result (default used if left as null)
    score: null,
    placeholder: 'Select tags',
    loadingMessage: 'loading ...',

    // Component Event Handling
    _onChange:function(value) {
      const valueObject = this.get('valueObject');
      this.set('value', value);
      if (isEmpty(value)) {
        this.set('selected',false);
      } else {
        this.set('selected',true);
      }

      this.sendAction('onChange', {
        value: value,
        context: valueObject,
        component: this
      });
    },
    _onLoad:function(data) {
      this.sendAction('onLoad', {
        items: data,
        count: data.length
      });
    },
    _onOptionAdd:function(value,valueObject) {
      this.sendAction('onOption', {
        action: 'add',
        option: value,
        context: valueObject,
        component: this
      });
    },
    _onOptionRemove:function(value) {
      this.sendAction('onOption', {
        action: 'remove',
        option: value,
        component: this
      });
    },
    _onDropdownOpen:function($dropdown) {
      this.sendAction('onDropdown', {
        action: 'open',
        component: this,
        value: get(this,'value'),
        $dropdown: $dropdown
      });
    },
    _onDropdownClose:function($dropdown) {
      this.sendAction('onDropdown', {
        action: 'close',
        component: this,
        value: get(this,'value'),
        $dropdown: $dropdown
      });
    },
    _onItemAdd:function(value, $item) {
      this.sendAction('onItem', {
        action: 'add',
        component: this,
        message: `added ${value} to the list`,
        value: value,
        $item: $item
      });
    },
    _onItemRemove:function(value) {
      this.sendAction('onItem', {
        action:'remove',
        message: `removed ${value} from the list`,
        value: get(this,'value'),
        component: this
      });
    },
    _onType:function(value) {
      this.sendAction('onType', {
        component: this,
        text: value
      });
    },

    selected: false,
    selectize: null,

});

// NAMED FOR EMBER INSPECTOR
ApiSurface[Ember.NAME_KEY] = 'selectize api surface';
export default ApiSurface;
<commit_msg>Add missing closeAfterSelect option to api-surface<commit_after>import Ember from 'ember';
const { keys, create } = Object; // jshint ignore:line
const {computed, observer, $, A, run, on, typeOf, debug, defineProperty, get, set, inject, isEmpty} = Ember;  // jshint ignore:line

var ApiSurface = Ember.Mixin.create({
    // Selectize API surface
    // ------------------------------
    // bound values passed straight through to control
    apiPassThrough: [
      'optgroups',
      'inputClass','onInitialize','onDestroy','sortField','placeholder','copyClassesToDropdown',
      'create','createOnBlur','createFilter','highlight','persist','openOnFocus','maxOptions','maxItems','hideSelected',
      'allowEmptyOption','scrollDuration','dropdownParent','addPrecedence','selectOnTab',
      'optgroupField','optgroupValueField','optgroupLabelField',
      'score', 'closeAfterSelect'
    ],
    // Arguably not needed except for "meta" reasons; these are props which are consumed directly by a CP
    // rather than Selectize (which would recieve a state change indirectly)
    apiIntermediate: [
      'valueField', 'labelField',
      'optgroupField', 'optgroupValueField', 'optgroupLabelField'
    ],
    // CP's to be used rather than bound value
    apiProcessed: [
      '_optgroupOrder', '_plugins', '_searchField', '_sortField'
    ],
    // Static mappings to API
    apiStaticMappings: {
      valueField: 'value',
      labelField: 'label',
      optgroupField: 'group'
    },
    copyClassesToDropdown: true,

    optgroups: null, // the array of optgroups
    optgroupField: 'group', // property name on "options" which refers to optgroupsValueField
    optgroupValueField: 'id', // the displayed name for optgroup
    optgroupLabelField: 'name', // property on "optgroups" array for the "value" which will match options property
    optgroupOrder: null, // array of optgroup keys in a particular order
    _optgroupOrder: computed('optgroupOrder', function() {
      let optgroupOrder = this.get('optgroupOrder');
      if (!optgroupOrder) {
        optgroupOrder = [];
      }

      return typeOf(optgroupOrder) === 'array' ? optgroupOrder : [optgroupOrder];
    }),
    plugins: null,
    _plugins: computed('plugins', function() {
      const plugins = this.get('plugins');
      return typeOf(plugins) === 'string' ? plugins.split(',') : plugins;
    }),

    onInitialize: null,
    onDestroy: null,
    labelField: 'name',
    valueField: 'id', // the field in the incoming hash which will be used for assigning a value to the input selector
    searchField: 'name', // property/properties to search through for a match
    _searchField: computed('searchField', function() {
      const searchField = this.get('searchField');
      return typeOf(searchField) === 'string' ? searchField.split(',') : searchField;
    }),
    searchConjunction: 'and', // when searching for multiple terms (seperated by a space)
    sortField: 'name',
    // Selectize allows "sortField" to be an array of objects or a string value;
    // we will just simplify this to the more versatile array of objects which also
    // allows the optional attribute "direction" (which is "asc" or "desc")
    _sortField: computed('sortField', function() {
      const sortField = this.get('sortField');
      const sortFields = typeOf(sortField) === 'string' ? sortField.split(',') : sortField;

      return sortFields.map( item => {
        switch(typeOf(item)) {
          case 'string':
            return {field: item};
          case 'object':
            return item;
          default:
            debug('an invalid property was passed to the sortField property: ' + JSON.stringify(item));
            return null;
        }
      }).filter( item => {
        return item !== null;
      });
    }),

    create: false, // allows user to create new items not on the list (can be true, false, or callback)
    createOnBlur: false,
    createFilter: null,
    highlight: true,
    persist: true, // options user created will show up after deselected
    openOnFocus: true,
    maxOptions: 1000,
    maxItems: 10000,
    hideSelected: false, // do not show items as option when already selected
    allowEmptyOption: false,
    scrollDuration: 60,
    dropdownParent: null,
    addPrecedence: false,
    selectOnTab: true,
    inputClass: 'form-control selectize-input',
    // callback function to score the result (default used if left as null)
    score: null,
    placeholder: 'Select tags',
    loadingMessage: 'loading ...',
    closeAfterSelect: false,

    // Component Event Handling
    _onChange:function(value) {
      const valueObject = this.get('valueObject');
      this.set('value', value);
      if (isEmpty(value)) {
        this.set('selected',false);
      } else {
        this.set('selected',true);
      }

      this.sendAction('onChange', {
        value: value,
        context: valueObject,
        component: this
      });
    },
    _onLoad:function(data) {
      this.sendAction('onLoad', {
        items: data,
        count: data.length
      });
    },
    _onOptionAdd:function(value,valueObject) {
      this.sendAction('onOption', {
        action: 'add',
        option: value,
        context: valueObject,
        component: this
      });
    },
    _onOptionRemove:function(value) {
      this.sendAction('onOption', {
        action: 'remove',
        option: value,
        component: this
      });
    },
    _onDropdownOpen:function($dropdown) {
      this.sendAction('onDropdown', {
        action: 'open',
        component: this,
        value: get(this,'value'),
        $dropdown: $dropdown
      });
    },
    _onDropdownClose:function($dropdown) {
      this.sendAction('onDropdown', {
        action: 'close',
        component: this,
        value: get(this,'value'),
        $dropdown: $dropdown
      });
    },
    _onItemAdd:function(value, $item) {
      this.sendAction('onItem', {
        action: 'add',
        component: this,
        message: `added ${value} to the list`,
        value: value,
        $item: $item
      });
    },
    _onItemRemove:function(value) {
      this.sendAction('onItem', {
        action:'remove',
        message: `removed ${value} from the list`,
        value: get(this,'value'),
        component: this
      });
    },
    _onType:function(value) {
      this.sendAction('onType', {
        component: this,
        text: value
      });
    },

    selected: false,
    selectize: null,

});

// NAMED FOR EMBER INSPECTOR
ApiSurface[Ember.NAME_KEY] = 'selectize api surface';
export default ApiSurface;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013, Yahoo! Inc. All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint node: true, nomen: true, stupid: true, indent: 4 */
/*global YUI */

/**
 * Routines to report on whether the user agent has JavaScript disabled.
 *
 * @module mojito-jscheck-addon
 */

YUI.add('mojito-jscheck-addon', function (Y, NAME) {
    'use strict';

    var JS_IS_DISABLED = 'disabled',
        JS_IS_ENABLED = 'enabled',
        JS_IS_INDETERMINATE = 'indeterminate',

        path = require('path'),
        fs = require('fs'),
        qs = require('querystring'),
        UglifyJS = require('uglify-js'),

        config = {
            enabled: true,
            param: 'js',
            cookie: {
                name: 'js'
            }
        },

        nojsHandler,
        jsParamRegexp,

        initialized = false;

    /**
     * Access point: ac.jscheck.*
     * This server-side jscheck add-on allows you to easily determine
     * whether JavaScript is enabled or disabled on the client.
     * @class mojito.addons.ac.jscheck
     * @constructor
     */
    function Addon(command, adapter, ac) {
        var code, req;

        if (!initialized) {

            // Here, we compute a few things once, for better performance.
            // Note: the configuration is checked in the middleware, so we
            // don't need to duplicate that code...

            Y.mix(config, ac.config.getAppConfig().jscheck, true, null, 0, true);

            if (!config.hasOwnProperty('enabled') || config.enabled) {

                code = fs.readFileSync(path.join(__dirname, '../../assets/jscheck-manual-inline.js'), 'utf-8');

                if (!config.hasOwnProperty('jsmin') || config.jsmin) {
                    try {
                        code = UglifyJS.minify(code, { fromString: true }).code;
                    } catch (e) {
                        Y.log(e.message, 'warn', NAME);
                    }
                }

                nojsHandler = '';

                jsParamRegexp = new RegExp('[?&]' + encodeURIComponent(config.param) + '=([^&]*)');
            }

            initialized = true;
        }

        this.ac = ac;
        this.originalUrl = ac.http.getRequest().url;

        req = adapter.req;

        if (!req.globals) {
            req.globals = {};
        }

        if (req.globals['jscheck.addon']) {
            // Return our per-request singleton.
            return req.globals['jscheck.addon'];
        }
    }

    Addon.prototype = {

        namespace: 'jscheck',

        /**
         * Indicates whether the user agent has JavaScript enabled.
         *
         * @method status
         * @return {String}
         */
        status: function () {
            if (config.hasOwnProperty('enabled') && !config.enabled) {
                return JS_IS_INDETERMINATE;
            }

            var v, o, m;

            v = this.ac.cookie.get(encodeURIComponent(config.cookie.name));

            if (config.cookie.sub) {
                o = qs.parse(v);
                v = o[config.cookie.sub];
            }

            if (v === '0') {
                return JS_IS_DISABLED;
            }

            m = this.originalUrl.match(jsParamRegexp);

            if (m && m[1] === '0') {
                return JS_IS_DISABLED;
            }

            return JS_IS_ENABLED;
        },

        /**
         * Depending on the status, runs certain actions, which in turn can
         * affect the reported status for that user in future requests...
         *
         * @method run
         */
        run: function () {
            // This add-on is a singleton. By doing the following, we ensure
            // that subsequent calls to the run() method will not do anything...
            this.run = function () {};

            if (config.hasOwnProperty('enabled') && !config.enabled) {
                return;
            }

            var ac = this.ac,
                status = this.status(),
                params,
                redirectUrl,
                nojsRedirect;

            Y.log('JavaScript appears to be ' + status, 'info', NAME);

            if (status === JS_IS_DISABLED) {
                ac.assets.addBlob(nojsHandler, 'bottom');
                return;
            }

            // Do not redirect if the request comes from track.corp...
            // For more info, see bz#6124384 Note: This is Yahoo!-specific.
            // Remove when the aforementioned ticket has been closed!

            params = ac.params.url();
            if (params.hasOwnProperty('ultdebug') ||
                    params.hasOwnProperty('yhldebug')) {
                return;
            }

            redirectUrl = this.originalUrl;

            if (redirectUrl.indexOf('?') === -1) {
                redirectUrl += '?';
            } else {
                redirectUrl += '&';
            }

            redirectUrl += encodeURIComponent(config.param) + '=0';

            try {
                // Avoid XSS, but avoid double encoding...
                redirectUrl = encodeURI(redirectUrl).replace(/%25/g, '%');
            } catch (e) {
                Y.log(e.message + '\n[redirectUrl was "' + redirectUrl + '"]', 'warn', NAME);
                return;
            }

            nojsRedirect = '<meta http-equiv="refresh" content="0;url=' + redirectUrl + '">';

            ac.assets.addBlob(nojsRedirect, 'prefetch');
        }
    };

    Y.mojito.addons.ac.jscheck = Addon;

}, '0.1.0', {
    requires: [
        'mojito',
        'mojito-config-addon',
        'mojito-params-addon',
        'mojito-cookie-addon',
        'mojito-assets-addon',
        'mojito-http-addon',
        'escape'
    ]
});
<commit_msg>Changed info logLevel to debug.<commit_after>/*
 * Copyright (c) 2013, Yahoo! Inc. All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

/*jslint node: true, nomen: true, stupid: true, indent: 4 */
/*global YUI */

/**
 * Routines to report on whether the user agent has JavaScript disabled.
 *
 * @module mojito-jscheck-addon
 */

YUI.add('mojito-jscheck-addon', function (Y, NAME) {
    'use strict';

    var JS_IS_DISABLED = 'disabled',
        JS_IS_ENABLED = 'enabled',
        JS_IS_INDETERMINATE = 'indeterminate',

        path = require('path'),
        fs = require('fs'),
        qs = require('querystring'),
        UglifyJS = require('uglify-js'),

        config = {
            enabled: true,
            param: 'js',
            cookie: {
                name: 'js'
            }
        },

        nojsHandler,
        jsParamRegexp,

        initialized = false;

    /**
     * Access point: ac.jscheck.*
     * This server-side jscheck add-on allows you to easily determine
     * whether JavaScript is enabled or disabled on the client.
     * @class mojito.addons.ac.jscheck
     * @constructor
     */
    function Addon(command, adapter, ac) {
        var code, req;

        if (!initialized) {

            // Here, we compute a few things once, for better performance.
            // Note: the configuration is checked in the middleware, so we
            // don't need to duplicate that code...

            Y.mix(config, ac.config.getAppConfig().jscheck, true, null, 0, true);

            if (!config.hasOwnProperty('enabled') || config.enabled) {

                code = fs.readFileSync(path.join(__dirname, '../../assets/jscheck-manual-inline.js'), 'utf-8');

                if (!config.hasOwnProperty('jsmin') || config.jsmin) {
                    try {
                        code = UglifyJS.minify(code, { fromString: true }).code;
                    } catch (e) {
                        Y.log(e.message, 'warn', NAME);
                    }
                }

                nojsHandler = '';

                jsParamRegexp = new RegExp('[?&]' + encodeURIComponent(config.param) + '=([^&]*)');
            }

            initialized = true;
        }

        this.ac = ac;
        this.originalUrl = ac.http.getRequest().url;

        req = adapter.req;

        if (!req.globals) {
            req.globals = {};
        }

        if (req.globals['jscheck.addon']) {
            // Return our per-request singleton.
            return req.globals['jscheck.addon'];
        }
    }

    Addon.prototype = {

        namespace: 'jscheck',

        /**
         * Indicates whether the user agent has JavaScript enabled.
         *
         * @method status
         * @return {String}
         */
        status: function () {
            if (config.hasOwnProperty('enabled') && !config.enabled) {
                return JS_IS_INDETERMINATE;
            }

            var v, o, m;

            v = this.ac.cookie.get(encodeURIComponent(config.cookie.name));

            if (config.cookie.sub) {
                o = qs.parse(v);
                v = o[config.cookie.sub];
            }

            if (v === '0') {
                return JS_IS_DISABLED;
            }

            m = this.originalUrl.match(jsParamRegexp);

            if (m && m[1] === '0') {
                return JS_IS_DISABLED;
            }

            return JS_IS_ENABLED;
        },

        /**
         * Depending on the status, runs certain actions, which in turn can
         * affect the reported status for that user in future requests...
         *
         * @method run
         */
        run: function () {
            // This add-on is a singleton. By doing the following, we ensure
            // that subsequent calls to the run() method will not do anything...
            this.run = function () {};

            if (config.hasOwnProperty('enabled') && !config.enabled) {
                return;
            }

            var ac = this.ac,
                status = this.status(),
                params,
                redirectUrl,
                nojsRedirect;

            Y.log('JavaScript appears to be ' + status, 'debug', NAME);

            if (status === JS_IS_DISABLED) {
                ac.assets.addBlob(nojsHandler, 'bottom');
                return;
            }

            // Do not redirect if the request comes from track.corp...
            // For more info, see bz#6124384 Note: This is Yahoo!-specific.
            // Remove when the aforementioned ticket has been closed!

            params = ac.params.url();
            if (params.hasOwnProperty('ultdebug') ||
                    params.hasOwnProperty('yhldebug')) {
                return;
            }

            redirectUrl = this.originalUrl;

            if (redirectUrl.indexOf('?') === -1) {
                redirectUrl += '?';
            } else {
                redirectUrl += '&';
            }

            redirectUrl += encodeURIComponent(config.param) + '=0';

            try {
                // Avoid XSS, but avoid double encoding...
                redirectUrl = encodeURI(redirectUrl).replace(/%25/g, '%');
            } catch (e) {
                Y.log(e.message + '\n[redirectUrl was "' + redirectUrl + '"]', 'warn', NAME);
                return;
            }

            nojsRedirect = '<meta http-equiv="refresh" content="0;url=' + redirectUrl + '">';

            ac.assets.addBlob(nojsRedirect, 'prefetch');
        }
    };

    Y.mojito.addons.ac.jscheck = Addon;

}, '0.1.0', {
    requires: [
        'mojito',
        'mojito-config-addon',
        'mojito-params-addon',
        'mojito-cookie-addon',
        'mojito-assets-addon',
        'mojito-http-addon',
        'escape'
    ]
});
<|endoftext|>


<commit_before>import { createReducer } from 'utils';
import * as actions      from '../actions';

const initialState = require('json!./../../config/drinks.json');

// set index as as identifier
initialState.map((drink, index) => drink.id = 'drink-' + (index + 1));

export default createReducer(initialState, {
  [actions.ADD_DRINK]    : (state, action) => [...state, action]
});

export const selectedDrink = createReducer(null, {
  [actions.SELECT_DRINK] : (state, action) => action.id
});
<commit_msg>add id on creation<commit_after>import { createReducer } from 'utils';
import * as actions      from '../actions';

const initialState = require('json!./../../config/drinks.json');

// set index as as identifier
const generateId = (index) => 'drink-' + (index + 1);
initialState.map((drink, index) => drink.id = generateId(index));

export default createReducer(initialState, {
  [actions.ADD_DRINK]    : (state, action) => [...state, {id: generateId(state.length), ...action}]
});

export const selectedDrink = createReducer(null, {
  [actions.SELECT_DRINK] : (state, action) => action.id
});
<|endoftext|>


<commit_before>/**
 * @file autolink.js
 * @brief javascript code for autolink addon
 * @author NAVER (developers@xpressengine.com)
 */
(function($){
	var protocol_re = '(https?|ftp|news|telnet|irc|mms)://';
	var domain_re   = '(?:[^./]+\\.)+[^./]+';
	var max_255_re  = '(?:1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9]?[0-9])';
	var ip_re       = '(?:'+max_255_re+'\\.){3}'+max_255_re;
	var port_re     = '(?::([0-9]+))?';
	var user_re     = '(?:/~\\w+)?';
	var path_re     = '(?:/[\\w!@$%&!?+=_~"/.,:;-]*)?';
	var hash_re     = '(?:#[\\w!@$%&!?+=_~"/.,:;-]*)?';

	var url_regex = new RegExp('('+protocol_re+'('+domain_re+'|'+ip_re+'|localhost'+')'+port_re+user_re+path_re+hash_re+')', 'ig');

	var AutoLink = xe.createPlugin("autolink", {
		targets : [],
		init : function() {
			this.targets = [];
		},
		API_ONREADY : function() {
			var thisPlugin = this;

			// extract target text nodes
			this.extractTargets($('.xe_content'));

			$(this.targets).each(function(){
				thisPlugin.cast('AUTOLINK', [this]);
			});
		},
		API_AUTOLINK : function(oSender, params) {
			var textNode = params[0];
			if(!$(textNode).parent().length || $(textNode).parent().get(0).nodeName.toLowerCase() == 'a') return;
			var content  = textNode.nodeValue;
			var dummy    = $('');

			//content = content.replace(/</g, '<').replace(/>/g, '>');
			content = content.replace(url_regex, '$1');

			$(textNode).before(dummy);
			$(textNode).replaceWith(content);
			params[0] = dummy.next('a');
			dummy.remove();
		},
		extractTargets : function(obj) {
			var thisPlugin = this;
			var wrap = $('.xe_content', obj);
			if(wrap.length) {
				this.extractTargets(wrap);
				return;
			}

			$(obj).contents().each(function(){
				var node_name = this.nodeName.toLowerCase();
				if($.inArray(node_name, ['a', 'pre', 'xml', 'textarea', 'input', 'select', 'option', 'code', 'script', 'style', 'iframe', 'button', 'img', 'embed', 'object', 'ins']) != -1) return;

				// FIX ME : When this meanless code wasn't executed, url_regex do not run correctly. why?
				url_regex.exec('');

				if(this.nodeType == 3) { // text node
					var content = this.nodeValue;

					if(content.length < 5) return;

					if(!/(http|https|ftp|news|telnet|irc|mms):\/\//i.test(content)) return;

					thisPlugin.targets.push(this);
				} else {
					thisPlugin.extractTargets(this);
				}
			});
		}
	});

	xe.registerPlugin(new AutoLink());
})(jQuery);
<commit_msg>autolink 문제 수정 https://www.xetown.com/contact/303840<commit_after>/**
 * @file autolink.js
 * @brief javascript code for autolink addon
 * @author NAVER (developers@xpressengine.com)
 */
(function($){
	var protocol_re = '(https?|ftp|news|telnet|irc|mms)://';
	var domain_re   = '(?:[^\\s./]+\\.)+[^\\s./]+';
	var max_255_re  = '(?:1[0-9]{2}|2[0-4][0-9]|25[0-5]|[1-9]?[0-9])';
	var ip_re       = '(?:'+max_255_re+'\\.){3}'+max_255_re;
	var port_re     = '(?::([0-9]+))?';
	var user_re     = '(?:/~\\w+)?';
	var path_re     = '(?:/[\\w!@$%&!?+=_~"/.,:;-]*)?';
	var hash_re     = '(?:#[\\w!@$%&!?+=_~"/.,:;-]*)?';

	var url_regex = new RegExp('('+protocol_re+'('+domain_re+'|'+ip_re+'|localhost'+')'+port_re+user_re+path_re+hash_re+')', 'ig');

	var AutoLink = xe.createPlugin("autolink", {
		targets : [],
		init : function() {
			this.targets = [];
		},
		API_ONREADY : function() {
			var thisPlugin = this;

			// extract target text nodes
			this.extractTargets($('.xe_content'));

			$(this.targets).each(function(){
				thisPlugin.cast('AUTOLINK', [this]);
			});
		},
		API_AUTOLINK : function(oSender, params) {
			var textNode = params[0];
			if(!$(textNode).parent().length || $(textNode).parent().get(0).nodeName.toLowerCase() == 'a') return;
			var content  = textNode.nodeValue;
			var dummy    = $('');

			//content = content.replace(/</g, '<').replace(/>/g, '>');
			content = content.replace(url_regex, '$1');

			$(textNode).before(dummy);
			$(textNode).replaceWith(content);
			params[0] = dummy.next('a');
			dummy.remove();
		},
		extractTargets : function(obj) {
			var thisPlugin = this;
			var wrap = $('.xe_content', obj);
			if(wrap.length) {
				this.extractTargets(wrap);
				return;
			}

			$(obj).contents().each(function(){
				var node_name = this.nodeName.toLowerCase();
				if($.inArray(node_name, ['a', 'pre', 'xml', 'textarea', 'input', 'select', 'option', 'code', 'script', 'style', 'iframe', 'button', 'img', 'embed', 'object', 'ins']) != -1) return;

				// FIX ME : When this meanless code wasn't executed, url_regex do not run correctly. why?
				url_regex.exec('');

				if(this.nodeType == 3) { // text node
					var content = this.nodeValue;

					if(content.length < 5) return;

					if(!/(http|https|ftp|news|telnet|irc|mms):\/\//i.test(content)) return;

					thisPlugin.targets.push(this);
				} else {
					thisPlugin.extractTargets(this);
				}
			});
		}
	});

	xe.registerPlugin(new AutoLink());
})(jQuery);
<|endoftext|>


<commit_before>(function() {
  var modes = ["clike", "css", "javascript"];
  var continueLineComment = true;

  for (var i = 0; i < modes.length; ++i)
    CodeMirror.extendMode(modes[i], {blockCommentContinue: " * "});

  function continueComment(cm) {
    var pos = cm.getCursor(), token = cm.getTokenAt(pos);
    if (token.type != "comment" || cm.getOption("disableInput")) return CodeMirror.Pass;
    var mode = CodeMirror.innerMode(cm.getMode(), token.state).mode;

    var insert;
    if (mode.blockCommentStart && mode.blockCommentContinue) {
      var end = token.string.indexOf(mode.blockCommentEnd);
      var full = cm.getRange(CodeMirror.Pos(pos.line, 0), CodeMirror.Pos(pos.line, token.end)), found;
      if (end != -1 && end == token.string.length - mode.blockCommentEnd.length && pos.ch >= end) {
        // Comment ended, don't continue it
      } else if (token.string.indexOf(mode.blockCommentStart) == 0) {
        insert = full.slice(0, token.start);
        if (!/^\s*$/.test(insert)) {
          insert = "";
          for (var i = 0; i < token.start; ++i) insert += " ";
        }
      } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 &&
                 found + mode.blockCommentContinue.length > token.start &&
                 /^\s*$/.test(full.slice(0, found))) {
        insert = full.slice(0, found);
      }
      if (insert != null) insert += mode.blockCommentContinue;
    }
    if (insert == null && mode.lineComment && continueLineComment) {
      var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment);
      if (found > -1) {
        insert = line.slice(0, found);
        if (/\S/.test(insert)) insert = null;
        else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0];
      }
    }

    if (insert != null)
      cm.replaceSelection("\n" + insert, "end");
    else
      return CodeMirror.Pass;
  }

  CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
    if (prev && prev != CodeMirror.Init)
      cm.removeKeyMap("continueComment");
    if (val) {
      var key = "Enter";
      if (typeof val == "string") {
        key = val;
      } else if (typeof val == "object") {
        if (val.key)
          key = val.key;
        if (val.continueLineComment != undefined)
          continueLineComment = val.continueLineComment
      }
      var map = {name: "continueComment"};
      map[key] = continueComment;
      cm.addKeyMap(map);
    }
  });
})();
<commit_msg>[continuecomment addon] Don't make the line-comment option global<commit_after>(function() {
  var modes = ["clike", "css", "javascript"];

  for (var i = 0; i < modes.length; ++i)
    CodeMirror.extendMode(modes[i], {blockCommentContinue: " * "});

  function continueComment(cm) {
    var pos = cm.getCursor(), token = cm.getTokenAt(pos);
    if (token.type != "comment" || cm.getOption("disableInput")) return CodeMirror.Pass;
    var mode = CodeMirror.innerMode(cm.getMode(), token.state).mode;

    var insert;
    if (mode.blockCommentStart && mode.blockCommentContinue) {
      var end = token.string.indexOf(mode.blockCommentEnd);
      var full = cm.getRange(CodeMirror.Pos(pos.line, 0), CodeMirror.Pos(pos.line, token.end)), found;
      if (end != -1 && end == token.string.length - mode.blockCommentEnd.length && pos.ch >= end) {
        // Comment ended, don't continue it
      } else if (token.string.indexOf(mode.blockCommentStart) == 0) {
        insert = full.slice(0, token.start);
        if (!/^\s*$/.test(insert)) {
          insert = "";
          for (var i = 0; i < token.start; ++i) insert += " ";
        }
      } else if ((found = full.indexOf(mode.blockCommentContinue)) != -1 &&
                 found + mode.blockCommentContinue.length > token.start &&
                 /^\s*$/.test(full.slice(0, found))) {
        insert = full.slice(0, found);
      }
      if (insert != null) insert += mode.blockCommentContinue;
    }
    if (insert == null && mode.lineComment && continueLineCommentEnabled(cm)) {
      var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment);
      if (found > -1) {
        insert = line.slice(0, found);
        if (/\S/.test(insert)) insert = null;
        else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0];
      }
    }

    if (insert != null)
      cm.replaceSelection("\n" + insert, "end");
    else
      return CodeMirror.Pass;
  }

  function continueLineCommentEnabled(cm) {
    var opt = cm.getOption("continueComments");
    if (opt && typeof opt == "object")
      return opt.continueLineComment !== false;
    return true;
  }

  CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
    if (prev && prev != CodeMirror.Init)
      cm.removeKeyMap("continueComment");
    if (val) {
      var key = "Enter";
      if (typeof val == "string")
        key = val;
      else if (typeof val == "object" && val.key)
        key = val.key;
      var map = {name: "continueComment"};
      map[key] = continueComment;
      cm.addKeyMap(map);
    }
  });
})();
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/bread-crumbs';
import getOwner from 'ember-getowner-polyfill';

const {
  get,
  Component,
  computed,
  copy,
  getWithDefault,
  assert,
  deprecate,
  isEmpty,
  typeOf,
  setProperties,
  A: emberArray,
  String: { classify }
} = Ember;
const {
  bool,
  readOnly
} = computed;

export default Component.extend({
  layout,
  tagName: 'ol',
  linkable: true,
  reverse: false,
  classNameBindings: ['breadCrumbClass'],
  hasBlock: bool('template').readOnly(),
  currentUrl: readOnly('applicationRoute.router.url'),
  currentRouteName: readOnly('applicationRoute.controller.currentRouteName'),

  routeHierarchy: computed('currentUrl', 'currentRouteName', 'reverse', {
    get() {
      const currentRouteName = getWithDefault(this, 'currentRouteName', false);

      assert('[ember-crumbly] Could not find a current route', currentRouteName);

      const routeNames = currentRouteName.split('.');
      const filteredRouteNames = this._filterIndexAndLoadingRoutes(routeNames);
      const crumbs = this._lookupBreadCrumb(routeNames, filteredRouteNames);

      return get(this, 'reverse') ? crumbs.reverse() : crumbs;
    }
  }).readOnly(),

  breadCrumbClass: computed('outputStyle', {
    get() {
      let className = 'breadcrumb';
      const outputStyle = getWithDefault(this, 'outputStyle', '');
      if (isEmpty(outputStyle)) {
        deprecate('outputStyle option will be deprecated in the next major release', false);
      }
      const lowerCaseOutputStyle = outputStyle.toLowerCase();

      if (lowerCaseOutputStyle === 'foundation') {
        className = 'breadcrumbs';
      }

      return className;
    }
  }).readOnly(),

  _guessRoutePath(routeNames, name, index) {
    const routes = routeNames.slice(0, index + 1);

    if (routes.length === 1) {
      let path = `${name}.index`;

      return (this._lookupRoute(path)) ? path : name;
    }

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

  _filterIndexAndLoadingRoutes(routeNames) {
    return routeNames.filter((name) => !(name === 'index' || name === 'loading'));
  },

  _lookupRoute(routeName) {
    return getOwner(this).lookup(`route:${routeName}`);
  },

  _lookupBreadCrumb(routeNames, filteredRouteNames) {
    const defaultLinkable = get(this, 'linkable');
    const pathLength = filteredRouteNames.length;
    const breadCrumbs = filteredRouteNames.map((name, index) => {
      const path = this._guessRoutePath(routeNames, name, index);
      const route = this._lookupRoute(path);
      const isHead = index === 0;
      const isTail = index === pathLength - 1;

      const crumbLinkable = (index === pathLength - 1) ? false : defaultLinkable;

      assert(`[ember-crumbly] \`route:${path}\` was not found`, route);

      let breadCrumb = copy(getWithDefault(route, 'breadCrumb', {
        title: classify(name)
      }));

      if (typeOf(breadCrumb) === 'null') {
        return;
      } else {
        setProperties(breadCrumb, {
          path,
          isHead,
          isTail,
          linkable: breadCrumb.hasOwnProperty('linkable') ? breadCrumb.linkable : crumbLinkable
        });
      }

      return breadCrumb;
    });

    return emberArray(breadCrumbs.filter((breadCrumb) => typeOf(breadCrumb) !== 'undefined'));
  }
});
<commit_msg>Should only output deprecation warning if outputStyle is given<commit_after>import Ember from 'ember';
import layout from '../templates/components/bread-crumbs';
import getOwner from 'ember-getowner-polyfill';

const {
  get,
  Component,
  computed,
  copy,
  getWithDefault,
  assert,
  deprecate,
  isPresent,
  typeOf,
  setProperties,
  A: emberArray,
  String: { classify }
} = Ember;
const {
  bool,
  readOnly
} = computed;

export default Component.extend({
  layout,
  tagName: 'ol',
  linkable: true,
  reverse: false,
  classNameBindings: ['breadCrumbClass'],
  hasBlock: bool('template').readOnly(),
  currentUrl: readOnly('applicationRoute.router.url'),
  currentRouteName: readOnly('applicationRoute.controller.currentRouteName'),

  routeHierarchy: computed('currentUrl', 'currentRouteName', 'reverse', {
    get() {
      const currentRouteName = getWithDefault(this, 'currentRouteName', false);

      assert('[ember-crumbly] Could not find a current route', currentRouteName);

      const routeNames = currentRouteName.split('.');
      const filteredRouteNames = this._filterIndexAndLoadingRoutes(routeNames);
      const crumbs = this._lookupBreadCrumb(routeNames, filteredRouteNames);

      return get(this, 'reverse') ? crumbs.reverse() : crumbs;
    }
  }).readOnly(),

  breadCrumbClass: computed('outputStyle', {
    get() {
      let className = 'breadcrumb';
      const outputStyle = getWithDefault(this, 'outputStyle', '');
      if (isPresent(outputStyle)) {
        deprecate('outputStyle option will be deprecated in the next major release', false, { id: 'ember-crumbly.outputStyle', until: '2.0.0' });
      }
      const lowerCaseOutputStyle = outputStyle.toLowerCase();

      if (lowerCaseOutputStyle === 'foundation') {
        className = 'breadcrumbs';
      }

      return className;
    }
  }).readOnly(),

  _guessRoutePath(routeNames, name, index) {
    const routes = routeNames.slice(0, index + 1);

    if (routes.length === 1) {
      let path = `${name}.index`;

      return (this._lookupRoute(path)) ? path : name;
    }

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

  _filterIndexAndLoadingRoutes(routeNames) {
    return routeNames.filter((name) => !(name === 'index' || name === 'loading'));
  },

  _lookupRoute(routeName) {
    return getOwner(this).lookup(`route:${routeName}`);
  },

  _lookupBreadCrumb(routeNames, filteredRouteNames) {
    const defaultLinkable = get(this, 'linkable');
    const pathLength = filteredRouteNames.length;
    const breadCrumbs = filteredRouteNames.map((name, index) => {
      const path = this._guessRoutePath(routeNames, name, index);
      const route = this._lookupRoute(path);
      const isHead = index === 0;
      const isTail = index === pathLength - 1;

      const crumbLinkable = (index === pathLength - 1) ? false : defaultLinkable;

      assert(`[ember-crumbly] \`route:${path}\` was not found`, route);

      let breadCrumb = copy(getWithDefault(route, 'breadCrumb', {
        title: classify(name)
      }));

      if (typeOf(breadCrumb) === 'null') {
        return;
      } else {
        setProperties(breadCrumb, {
          path,
          isHead,
          isTail,
          linkable: breadCrumb.hasOwnProperty('linkable') ? breadCrumb.linkable : crumbLinkable
        });
      }

      return breadCrumb;
    });

    return emberArray(breadCrumbs.filter((breadCrumb) => typeOf(breadCrumb) !== 'undefined'));
  }
});
<|endoftext|>


<commit_before>/**
 * @module ember-flexberry
 */

import Ember from 'ember';

/**
 * ModalDialog component for SemanticUI.
 *
 * @class ModalDialog
 * @extends Ember.Component
 */
export default Ember.Component.extend({
  /**
   * Flag indicates whether to show apply button or not.
   *
   * @property useOkButton
   * @type Boolean
   * @default true
   */
  useOkButton: true,

  /**
   * Flag indicates whether to show close button or not.
   *
   * @property useCloseButton
   * @type Boolean
   * @default true
   */
  useCloseButton: true,

  /**
   * Flag indicates whether an image content is viewed at modal dialog or not.
   *
   * @property viewImageContent
   * @type Boolean
   * @default false
   */
  viewImageContent: false,

  /**
   * Flag: indicates buttons toolbar visibility,
   * true if at least one of buttons is visible.
   *
   * @property toolbarVisible
   * @type Boolean
   * @default true
   * @readonly
   */
  toolbarVisible: Ember.computed('useOkButton', 'useCloseButton', function () {
    return this.get('useOkButton') || this.get('useCloseButton');
  }),

  /**
   * Semantic-UI Modal settings,
   * more info at http://semantic-ui.com/modules/modal.html#settings
   *
   * @property settings
   * @type Object
   * @default {}
   */
  settings: {},

  modalWindowHeight: undefined,

  modalWindowWidth: undefined,

  modalWindowContentHeight: 400,

  modalWindowHeightComputed: Ember.computed('modalWindowHeight', function () {
    var height = this.get('modalWindowHeight');
    if (height && typeof height === 'number') {
      return height;
    }

    return 600;
  }),

  modalWindowWidthComputed: Ember.computed('modalWindowWidth', function () {
    var width = this.get('modalWindowWidth');
    if (width && typeof width === 'number') {
      return width;
    }

    return 750;
  }),

  modalWindowContentHeightComputed: Ember.computed('modalWindowContentHeight', function () {
    var height = this.get('modalWindowContentHeight');
    if (height && typeof height === 'number') {
      return height;
    }

    return 400;
  }),

  didInsertElement: function () {
    let _this = this;
    let modalSettings = Ember.$.extend({
        onApprove: function () {
          _this.sendAction('ok');
        },
        onDeny: function () {
          _this.sendAction('close');
        },
        onHidden: function () {
          _this.sendAction('close');
          this.remove();
        },
        onVisible: function () {
          Ember.run(() => {
            var wholeHeight = Ember.$(this).outerHeight();
            var headHeight = Ember.$('.header', this).outerHeight();
            var actionsHeight = Ember.$('.actions', this).outerHeight();
            var result = wholeHeight - headHeight - actionsHeight;
            _this.set('modalWindowContentHeight', result);
            _this.sendAction('created', Ember.$(this));
          });
        }
      },
      _this.get('settings'));

    this.$('.ui.modal').modal(modalSettings).modal('show');
  }
});
<commit_msg>Fix quotes in documentation comment<commit_after>/**
 * @module ember-flexberry
 */

import Ember from 'ember';

/**
 * ModalDialog component for SemanticUI.
 *
 * @class ModalDialog
 * @extends Ember.Component
 */
export default Ember.Component.extend({
  /**
   * Flag indicates whether to show apply button or not.
   *
   * @property useOkButton
   * @type Boolean
   * @default true
   */
  useOkButton: true,

  /**
   * Flag indicates whether to show close button or not.
   *
   * @property useCloseButton
   * @type Boolean
   * @default true
   */
  useCloseButton: true,

  /**
   * Flag indicates whether an image content is viewed at modal dialog or not.
   *
   * @property viewImageContent
   * @type Boolean
   * @default false
   */
  viewImageContent: false,

  /**
   * Flag: indicates buttons toolbar visibility,
   * `true` if at least one of buttons is visible.
   *
   * @property toolbarVisible
   * @type Boolean
   * @default true
   * @readonly
   */
  toolbarVisible: Ember.computed('useOkButton', 'useCloseButton', function () {
    return this.get('useOkButton') || this.get('useCloseButton');
  }),

  /**
   * Semantic-UI Modal settings,
   * more info at http://semantic-ui.com/modules/modal.html#settings
   *
   * @property settings
   * @type Object
   * @default {}
   */
  settings: {},

  modalWindowHeight: undefined,

  modalWindowWidth: undefined,

  modalWindowContentHeight: 400,

  modalWindowHeightComputed: Ember.computed('modalWindowHeight', function () {
    var height = this.get('modalWindowHeight');
    if (height && typeof height === 'number') {
      return height;
    }

    return 600;
  }),

  modalWindowWidthComputed: Ember.computed('modalWindowWidth', function () {
    var width = this.get('modalWindowWidth');
    if (width && typeof width === 'number') {
      return width;
    }

    return 750;
  }),

  modalWindowContentHeightComputed: Ember.computed('modalWindowContentHeight', function () {
    var height = this.get('modalWindowContentHeight');
    if (height && typeof height === 'number') {
      return height;
    }

    return 400;
  }),

  didInsertElement: function () {
    let _this = this;
    let modalSettings = Ember.$.extend({
        onApprove: function () {
          _this.sendAction('ok');
        },
        onDeny: function () {
          _this.sendAction('close');
        },
        onHidden: function () {
          _this.sendAction('close');
          this.remove();
        },
        onVisible: function () {
          Ember.run(() => {
            var wholeHeight = Ember.$(this).outerHeight();
            var headHeight = Ember.$('.header', this).outerHeight();
            var actionsHeight = Ember.$('.actions', this).outerHeight();
            var result = wholeHeight - headHeight - actionsHeight;
            _this.set('modalWindowContentHeight', result);
            _this.sendAction('created', Ember.$(this));
          });
        }
      },
      _this.get('settings'));

    this.$('.ui.modal').modal(modalSettings).modal('show');
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/music-player';

export default Ember.Component.extend({
  layout: layout,
  volume: 15,

  isPlaying: false,
  isOpen: false,
  volumeRange: false,
  pauseOnInit: false,
  timeDuration: 0,
  timeProgress: 0,

  playing: {
    title: '',
    artist: '',
    cover: ''
  },

  current_song: null,

  handleMeta( song, timeLong ) {
    let current_song = this.get('current_song');

    this.set('playing.title', song.title);
    this.set('playing.artist', song.artist);
    this.set('playing.cover', song.cover);

    current_song.addEventListener('timeupdate', () => {
      let time = parseInt(current_song.currentTime, 10);
      let progress = ((time * 100) / timeLong).toFixed(1);

      this.set('current_time', moment.duration(time, "minutes").format("h:mm"));
      this.set('timeProgress', progress);
    });
  },

  cleanMeta() {
    this.set('playing.title', '');
    this.set('playing.artist', '');
    this.set('playing.cover', '');

    this.set('current_time', 0);
  },

  stopCurrentSong() {
    let current_song = this.get('current_song');

    if ( current_song && !current_song.paused ) {
      current_song.pause();
      current_song.currentTime = 0;
    }
  },

  handleVolume: Ember.observer('volume', function() {
    let volume = this.get('volume') / 100;

    this.get('current_song').volume = volume;
  }),

  handlePlaylist( song ) {
    let current_song = this.get('current_song');
    const playlist   = this.get('playlist');

    current_song.addEventListener('ended', () => {
      let current_index = playlist.findIndex( (item) => {
        return item.title === song.title;
      });

      let next_index = playlist[current_index + 1];

      if ( next_index ) {

        this.send('playAudio', next_index);

      } else {
        this.send('stopAudio');
        this.cleanMeta();
      }
    });
  },

  playlistUpdate: Ember.observer('playlist', function() {
    this.send('playAudio');
  }),

  actions: {
    playerOpen() {
      this.set('isOpen', true);
    },

    playerClose() {
      this.set('isOpen', false);
    },

    playAudio( audio ) {
      let song = audio;

      this.stopCurrentSong();

      if ( !audio ) {
        song = this.get('playlist')[0];
      }

      // this.set('current_song', new Audio('data/' + song.file.mp3));
      this.set('current_song', new Audio(song.file.mp3));

      const current_song = this.get('current_song');

      this.handleVolume();
      this.handlePlaylist( song );

      let pauseOnInit = this.get('pauseOnInit')
      console.log('pauseOnInit', pauseOnInit);

      if(!pauseOnInit) {
        this.set('pauseOnInit', true);
      }else {
        current_song.play();
        this.set('isPlaying', true);
        console.log('current_song', current_song);

        current_song.addEventListener('loadedmetadata', () => {
          let timeLong = current_song.duration;
          this.handleMeta( song, moment.duration(timeLong, "seconds").format("s"));
          this.set('timeDuration', moment.duration(timeLong, "minutes").format("h:mm"));
        });
      }
    },

    pauseAudio() {
      let current_song = this.get('current_song');

      if ( current_song && !current_song.paused ) {
        current_song.pause();
        this.set('isPlaying', false);
      } else {
        current_song.play();
        this.set('isPlaying', true);
      }

    },

    stopAudio() {
      this.stopCurrentSong();
      this.set('isPlaying', false);
    },

    showVolume() {
      this.set('volumeRange', !this.get('volumeRange'));
    }
  }
});
<commit_msg>test init<commit_after>import Ember from 'ember';
import layout from '../templates/components/music-player';

export default Ember.Component.extend({
  layout: layout,
  volume: 15,

  isPlaying: false,
  isOpen: false,
  volumeRange: false,
  pauseOnInit: false,
  timeDuration: 0,
  timeProgress: 0,

  playing: {
    title: '',
    artist: '',
    cover: ''
  },

  current_song: null,

  handleMeta( song, timeLong ) {
    let current_song = this.get('current_song');

    this.set('playing.title', song.title);
    this.set('playing.artist', song.artist);
    this.set('playing.cover', song.cover);

    current_song.addEventListener('timeupdate', () => {
      let time = parseInt(current_song.currentTime, 10);
      let progress = ((time * 100) / timeLong).toFixed(1);

      this.set('current_time', moment.duration(time, "minutes").format("h:mm"));
      this.set('timeProgress', progress);
    });
  },

  cleanMeta() {
    this.set('playing.title', '');
    this.set('playing.artist', '');
    this.set('playing.cover', '');

    this.set('current_time', 0);
  },

  stopCurrentSong() {
    let current_song = this.get('current_song');

    if ( current_song && !current_song.paused ) {
      current_song.pause();
      current_song.currentTime = 0;
    }
  },

  handleVolume: Ember.observer('volume', function() {
    let volume = this.get('volume') / 100;

    this.get('current_song').volume = volume;
  }),

  handlePlaylist( song ) {
    let current_song = this.get('current_song');
    const playlist   = this.get('playlist');

    current_song.addEventListener('ended', () => {
      let current_index = playlist.findIndex( (item) => {
        return item.title === song.title;
      });

      let next_index = playlist[current_index + 1];

      if ( next_index ) {

        this.send('playAudio', next_index);

      } else {
        this.send('stopAudio');
        this.cleanMeta();
      }
    });
  },

  playlistUpdate: Ember.observer('playlist', function() {
    this.send('playAudio');
  }),

  actions: {
    playerOpen() {
      this.set('isOpen', true);
    },

    playerClose() {
      this.set('isOpen', false);
    },

    playAudio( audio ) {
      let song = audio;

      this.stopCurrentSong();

      if ( !audio ) {
        song = this.get('playlist')[0];
      }

      // this.set('current_song', new Audio('data/' + song.file.mp3));
      this.set('current_song', new Audio(song.file.mp3));

      const current_song = this.get('current_song');

      this.handleVolume();
      this.handlePlaylist( song );

      let pauseOnInit = this.get('pauseOnInit')
      console.log('pauseOnInit', pauseOnInit);

      if(!pauseOnInit) {
        this.set('pauseOnInit', true);
      }else {
        current_song.play();
        this.set('isPlaying', true);
        console.log('current_song', current_song);
      }

      current_song.addEventListener('loadedmetadata', () => {
        let timeLong = current_song.duration;
        this.handleMeta( song, moment.duration(timeLong, "seconds").format("s"));
        this.set('timeDuration', moment.duration(timeLong, "minutes").format("h:mm"));
      });
    },

    pauseAudio() {
      let current_song = this.get('current_song');

      if ( current_song && !current_song.paused ) {
        current_song.pause();
        this.set('isPlaying', false);
      } else {
        current_song.play();
        this.set('isPlaying', true);
      }

    },

    stopAudio() {
      this.stopCurrentSong();
      this.set('isPlaying', false);
    },

    showVolume() {
      this.set('volumeRange', !this.get('volumeRange'));
    }
  }
});
<|endoftext|>