<commit_before>var CloudCommander;
var CloudFunc;
CloudCommander.keyBinding = (function(){
    "use strict";

    var Util = new CloudCommander.Util();

    /* saving state of tabs varibles */
    var lTabPanel   = {
        left        : 0,
        right       : 0

    };

    /* Key constants*/
    var lKEY = {
        TAB         : 9,
        ENTER       : 13,

        PAGE_DOWN   : 34,
        END         : 35,
        HOME        : 36,
        UP          : 38,
        DOWN        : 40,

        D           : 68,
        Q           : 81,
        R           : 82,
        S           : 83,

        F2          : 113,
        F3          : 114,
        F4          : 115
    };

    var key_event = function(event){
            var lCurrentFile,
                lName, i;
            /* если клавиши можно обрабатывать*/
            if(CloudCommander.keyBinded && event){
                /* если нажали таб:
                 * переносим курсор на
                 * правую панель, если
                 * мы были на левой и
                 * наоборот
                 */
                if(event.keyCode === lKEY.TAB){
                    console.log('Tab pressed');

                    try{
                        lCurrentFile = Util.getCurrentFile();

                        /* changing parent panel of curent-file */
                        var lPanel = Util.getPanel();
                        var lId = lPanel.id;

                        lTabPanel[lId] = lCurrentFile;

                        lPanel = Util.getPanel({active:false});
                        lId = lPanel.id;

                        if(lTabPanel[lId])
                            Util.setCurrentFile(lTabPanel[lId].className);
                        else{
                            var lFirstFileOnList =
                                lPanel.getElementsByTagName('li')[2];

                            Util.setCurrentFile(lFirstFileOnList);
                        }
                        Util.unSetCurrentFile(lCurrentFile);

                    }catch(error){console.log(error);}
                }
                /* if f2 pressed */
                else if(event.keyCode === lKEY.F2){

                }

                /* if f3 pressed */
                else if(event.keyCode === lKEY.F3){
                    if (typeof CloudCommander.Viewer === 'function')
                        CloudCommander.Viewer();
                }

                /* if alt+f3 pressed */
                else if(event.keyCode === lKEY.F3 &&
                    event.altKey){
                        if (typeof CloudCommander.Terminal === 'function')
                        CloudCommander.Terminal();
                }

                 /* if f4 pressed */
                else if(event.keyCode === lKEY.F4) {
                    Util.Images.showLoad();

                    if (typeof CloudCommander.Editor === 'function')
                        CloudCommander.Editor();
                 }

                /* навигация по таблице файлов*/
                /* если нажали клавишу вверх*/
                else if(event.keyCode === lKEY.UP){
                    /* получаем выдленный файл*/
                    lCurrentFile = Util.getCurrentFile();

                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile) return;

                    /* если это строка существет и
                     * если она не заголовок
                     * файловой таблицы
                     */
                    if(lCurrentFile.previousSibling &&
                       lCurrentFile.previousSibling.className!=='fm_header' ){
                        /* убираем выделение с текущего элемента */
                        lCurrentFile.className='';
                        /* и выделяем предыдущую строку*/
                        lCurrentFile.previousSibling.className =
                            CloudCommander.CURRENT_FILE;

                        /* scrolling to current file*/
                        if(lCurrentFile.previousSibling)
                            lCurrentFile.previousSibling
                                .scrollIntoViewIfNeeded();
                    }
                }

                /* если нажали клавишу в низ*/
                else if(event.keyCode === lKEY.DOWN){
                    /* получаем выдленный файл*/
                    lCurrentFile = Util.getCurrentFile();

                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile)return;

                    /* если это не последняя строка */
                    if(lCurrentFile.nextSibling){

                        /* убираем с него выделение */
                        lCurrentFile.className='';

                        /* выделяем следующую строку*/
                        lCurrentFile.nextSibling.className =
                            CloudCommander.CURRENT_FILE;

                        /* scrolling to current file*/
                        lCurrentFile.nextSibling.scrollIntoViewIfNeeded();
                    }
                }

                /* если нажали клавишу Home
                 * переходим к самому верхнему
                 * элементу
                 */
                else if(event.keyCode === lKEY.HOME){
                        lCurrentFile = Util.getCurrentFile();
                        /* убираем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* получаем первый элемент*/
                        lCurrentFile.parentElement.firstElementChild
                        /* пропускаем путь и заголовки столбиков*/
                            .nextElementSibling.nextElementSibling
                            /* выделяем верхий файл */
                            .className=CloudCommander.CURRENT_FILE;

                        /* move scrollbar to top */
                        Util.getPanel().scrollByLines(-100000000000000);
                }

                /* если нажали клавишу End
                 * выделяем последний элемент
                 */
                else if( event.keyCode === lKEY.END){
                        lCurrentFile = Util.getCurrentFile();
                        /* снимаем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* выделяем самый нижний файл */
                        lCurrentFile.parentElement.lastElementChild
                            .className = CloudCommander.CURRENT_FILE;

                        /* move scrollbar to bottom*/
                        Util.getPanel().scrollByLines(100000000000000);
                }

                /* если нажали клавишу page down
                 * проматываем экран
                 */
                else if(event.keyCode === lKEY.PAGE_DOWN){
                    Util.getPanel().scrollByPages(1);

                    lCurrentFile = Util.getCurrentFile();
                    for(i=0; i<30; i++){
                        if(!lCurrentFile.nextSibling) break;

                        lCurrentFile = lCurrentFile.nextSibling;
                    }
                    Util.getCurrentFile().className = '';
                    lCurrentFile.className = CloudCommander.CURRENT_FILE;
                }

                /* если нажали клавишу page up
                 * проматываем экран
                 */
                else if(event.keyCode === 33){
                     Util.getPanel().scrollByPages(-1);

                    lCurrentFile = Util.getCurrentFile();
                    for(i=0; i<30; i++){
                        if(!lCurrentFile.previousSibling) break;
                        else try{
                            lCurrentFile
                                .previousSibling
                                    .previousSibling
                                        .previousSibling
                                            .previousSibling;
                            }
                            catch(pError){
                                break;
                            }
                        lCurrentFile = lCurrentFile.previousSibling;
                    }
                    Util.getCurrentFile().className = '';
                    lCurrentFile.className = CloudCommander.CURRENT_FILE;
                }

                /* если нажали Enter - открываем папку*/
                else if(event.keyCode === 13){
                    lCurrentFile = Util.getByClass(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile.length)return;
                    lCurrentFile=lCurrentFile[0];
                    /* из него достаём спан с именем файла*/
                    lName=lCurrentFile.getElementsByClassName('name');
                    /* если нету (что вряд ли) - выходим*/
                    if(!lName)return false;
                    /* достаём все ссылки*/
                    var lATag=lName[0].getElementsByTagName('a');
                    /* если нету - выходим */
                    if(!lATag)return false;

                    /* вызываем ajaxload привязанный через changelinks
                     * пробулем нажать на ссылку, если не получиться
                     * (opera, ie), вызываем событие onclick,
                     * которое пока не прописано у файлов
                     */

                     if(lCurrentFile.onclick)lCurrentFile.onclick(true);
                     else try{
                         lATag[0].click();
                     }
                     catch(error){
                         console.log(error);
                     }
                }

                /* если нажали <ctr>+r
                 * обновляем страницу,
                 * загружаем содержимое каталога
                 * при этом данные берём всегда с
                 * сервера, а не из кэша
                 * (обновляем кэш)
                 */
                else if(event.keyCode === lKEY.R &&
                    event.ctrlKey){
                    console.log('<ctrl>+r pressed');
                    console.log('reloading page...');
                    console.log('press <alt>+q to remove all key-handlers');
                    /* Программно нажимаем на кнопку перезагрузки
                     * содержимого каталога
                     */
                    var lRefreshIcon                = Util
                        .getByClass(CloudFunc.REFRESHICON);

                    if(lRefreshIcon)lRefreshIcon    = lRefreshIcon[0];
                    if(lRefreshIcon){
                        /* находим файл который сейчас выделен */
                         lCurrentFile       = Util.getCurrentFile();

                         /* получаем название файла*/
                         var lSelectedName  = lCurrentFile
                            .getElementsByTagName('a')[0].textContent;
                         /* если нашли элемент нажимаем него
                          * а если не можем - нажимаем на
                          * ссылку, на которую повешен eventHandler
                          * onclick
                          */
                        if(lRefreshIcon.click)
                            lRefreshIcon.parentElement.click();
                        else
                            lRefreshIcon.parentElement.onclick();

                        CloudCommander._currentToParent(lSelectedName);
                        }
                    }

                /* если нажали <ctrl>+d чистим кэш */
                else if(event.keyCode === lKEY.D &&
                    event.ctrlKey){
                        console.log('<ctrl>+d pressed');
                        console.log('clearing cache...');
                        console.log('press <alt>+q to remove all key-handlers');

                        var lClearCache = Util.getById('clear-cache');
                        if(lClearCache && lClearCache.onclick)lClearCache.onclick();
                }

                /* если нажали <alt>+q
                 * убираем все обработчики
                 * нажатий клавиш
                 */
                else if(event.keyCode === lKEY.Q &&
                    event.altKey){
                        //document.removeEventListener('keydown', key_event,false);
                        console.log('<alt>+q pressed');
                        console.log('<ctrl>+r reload key-handerl - removed');
                        console.log('<ctrl>+s clear cache key-handler - removed');
                        console.log('press <alt>+s to to set them');

                        /* обработчик нажатий клавиш снят*/
                        CloudCommander.keyBinded = false;
                }

                event.preventDefault();//запрет на дальнейшее действие
            }

            /* если нажали <alt>+s
             * устанавливаем все обработчики
             * нажатий клавиш
             */
            else if(event && event.keyCode === lKEY.S &&
                event.altKey){
                    /* обрабатываем нажатия на клавиши*/
                    CloudCommander.keyBinded = true;

                    console.log('<alt>+s pressed');
                    console.log('<ctrl>+r reload key-handerl - set');
                    console.log('<ctrl>+s clear cache key-handler - set');
                    console.log('press <alt>+q to remove them');
            }

        return false;
    };

    /* добавляем обработчик клавишь */
    if(document.addEventListener)
        document.addEventListener('keydown', key_event,false);
    else document.onkeydown = key_event;
    /* клавиши назначены*/
    CloudCommander.keyBinded=true;
});<commit_msg>fixed bug with ignoring all browser defined keys<commit_after>var CloudCommander;
var CloudFunc;
CloudCommander.keyBinding = (function(){
    "use strict";

    var Util = new CloudCommander.Util();

    /* saving state of tabs varibles */
    var lTabPanel   = {
        left        : 0,
        right       : 0

    };

    /* Key constants*/
    var lKEY = {
        TAB         : 9,
        ENTER       : 13,

        PAGE_DOWN   : 34,
        END         : 35,
        HOME        : 36,
        UP          : 38,
        DOWN        : 40,

        D           : 68,
        Q           : 81,
        R           : 82,
        S           : 83,

        F2          : 113,
        F3          : 114,
        F4          : 115
    };

    var key_event = function(event){
            var lCurrentFile,
                lName, i;
            /* если клавиши можно обрабатывать*/
            if(CloudCommander.keyBinded && event){
                /* если нажали таб:
                 * переносим курсор на
                 * правую панель, если
                 * мы были на левой и
                 * наоборот
                 */
                if(event.keyCode === lKEY.TAB){
                    console.log('Tab pressed');

                    try{
                        lCurrentFile = Util.getCurrentFile();

                        /* changing parent panel of curent-file */
                        var lPanel = Util.getPanel();
                        var lId = lPanel.id;

                        lTabPanel[lId] = lCurrentFile;

                        lPanel = Util.getPanel({active:false});
                        lId = lPanel.id;

                        if(lTabPanel[lId])
                            Util.setCurrentFile(lTabPanel[lId].className);
                        else{
                            var lFirstFileOnList =
                                lPanel.getElementsByTagName('li')[2];

                            Util.setCurrentFile(lFirstFileOnList);
                        }
                        Util.unSetCurrentFile(lCurrentFile);

                    }catch(error){console.log(error);}

                  	event.preventDefault();//запрет на дальнейшее действие
                }
                /* if f2 pressed */
                else if(event.keyCode === lKEY.F2){

                }

                /* if f3 pressed */
                else if(event.keyCode === lKEY.F3){
                    if (typeof CloudCommander.Viewer === 'function')
                        CloudCommander.Viewer();

                  	event.preventDefault();//запрет на дальнейшее действие
                }

                /* if alt+f3 pressed */
                else if(event.keyCode === lKEY.F3 &&
                    event.altKey){
                        if (typeof CloudCommander.Terminal === 'function')
                        	CloudCommander.Terminal();

                  		event.preventDefault();//запрет на дальнейшее действие
                }

                 /* if f4 pressed */
                else if(event.keyCode === lKEY.F4) {
                    Util.Images.showLoad();

                    if (typeof CloudCommander.Editor === 'function')
                        CloudCommander.Editor();

                  	event.preventDefault();//запрет на дальнейшее действие
                 }

                /* навигация по таблице файлов*/
                /* если нажали клавишу вверх*/
                else if(event.keyCode === lKEY.UP){
                    /* получаем выдленный файл*/
                    lCurrentFile = Util.getCurrentFile();

                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile) return;

                    /* если это строка существет и
                     * если она не заголовок
                     * файловой таблицы
                     */
                    if(lCurrentFile.previousSibling &&
                       lCurrentFile.previousSibling.className!=='fm_header' ){
                        /* убираем выделение с текущего элемента */
                        lCurrentFile.className='';
                        /* и выделяем предыдущую строку*/
                        Util.setCurrentFile(lCurrentFile.previousSibling);

                        /* scrolling to current file*/
                        if(lCurrentFile.previousSibling)
                            lCurrentFile.previousSibling
                                .scrollIntoViewIfNeeded();
                    }

                  	event.preventDefault();//запрет на дальнейшее действие
                }

                /* если нажали клавишу в низ*/
                else if(event.keyCode === lKEY.DOWN){
                    /* получаем выдленный файл*/
                    lCurrentFile = Util.getCurrentFile();

                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile)return;

                    /* если это не последняя строка */
                    if(lCurrentFile.nextSibling){

                        /* убираем с него выделение */
                        lCurrentFile.className='';

                        /* выделяем следующую строку*/
                      	Util.setCurrentFile(lCurrentFile.nextSibling);

                        /* scrolling to current file*/
                        lCurrentFile.nextSibling.scrollIntoViewIfNeeded();

                      	event.preventDefault();//запрет на дальнейшее действие
                    }
                }

                /* если нажали клавишу Home
                 * переходим к самому верхнему
                 * элементу
                 */
                else if(event.keyCode === lKEY.HOME){
                        lCurrentFile = Util.getCurrentFile();
                        /* убираем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* получаем первый элемент*/
                  		/* пропускаем путь и заголовки столбиков*/
                        /* выделяем верхий файл */
                  		Util.setCurrentFile(lCurrentFile
                          .parentElement.firstElementChild
                            .nextElementSibling.nextElementSibling);

                        /* move scrollbar to top */
                        Util.getPanel().scrollByLines(-100000000000000);

                  		event.preventDefault();//запрет на дальнейшее действие
                }

                /* если нажали клавишу End
                 * выделяем последний элемент
                 */
                else if( event.keyCode === lKEY.END){
                        lCurrentFile = Util.getCurrentFile();
                        /* снимаем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* выделяем самый нижний файл */
                        Util.setCurrentFile(lCurrentFile
							.parentElement.lastElementChild);

                        /* move scrollbar to bottom*/
                        Util.getPanel().scrollByLines(100000000000000);

                  		event.preventDefault();//запрет на дальнейшее действие
                }

                /* если нажали клавишу page down
                 * проматываем экран
                 */
                else if(event.keyCode === lKEY.PAGE_DOWN){
                    Util.getPanel().scrollByPages(1);

                    lCurrentFile = Util.getCurrentFile();
                    for(i=0; i<30; i++){
                        if(!lCurrentFile.nextSibling) break;

                        lCurrentFile = lCurrentFile.nextSibling;
                    }
                    Util.getCurrentFile().className = '';
                    Util.setCurrentFile(lCurrentFile);

                    event.preventDefault();//запрет на дальнейшее действие
                }

                /* если нажали клавишу page up
                 * проматываем экран
                 */
                else if(event.keyCode === 33){
                     Util.getPanel().scrollByPages(-1);

                    lCurrentFile = Util.getCurrentFile();
                    for(i=0; i<30; i++){
                        if(!lCurrentFile.previousSibling) break;
                        else try{
                            lCurrentFile
                                .previousSibling
                                    .previousSibling
                                        .previousSibling
                                            .previousSibling;
                            }
                            catch(pError){
                                break;
                            }
                        lCurrentFile = lCurrentFile.previousSibling;
                    }
                    Util.getCurrentFile().className = '';
                  	Util.setCurrentFile(lCurrentFile);

                  	event.preventDefault();//запрет на дальнейшее действие
                }

                /* если нажали Enter - открываем папку*/
                else if(event.keyCode === 13){
                    lCurrentFile = Util.getCurrentFile();
                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile)return;

                    /* из него достаём спан с именем файла*/
                    lName = lCurrentFile.getElementsByClassName('name');
                    /* если нету (что вряд ли) - выходим*/
                    if(!lName)return false;
                    /* достаём все ссылки*/
                    var lATag = lName[0].getElementsByTagName('a');
                    /* если нету - выходим */
                    if(!lATag)return false;

                    /* вызываем ajaxload привязанный через changelinks
                     * пробуем нажать на ссылку, если не получиться
                     * (opera, ie), вызываем событие onclick,
                     */

                     if(lCurrentFile.onclick)lCurrentFile.onclick(true);
                     else try{
                         lATag[0].click();
                     }
                     catch(error){
                         console.log(error);
                     }

                	event.preventDefault();//запрет на дальнейшее действие
                }

                /* если нажали <ctr>+r
                 * обновляем страницу,
                 * загружаем содержимое каталога
                 * при этом данные берём всегда с
                 * сервера, а не из кэша
                 * (обновляем кэш)
                 */
                else if(event.keyCode === lKEY.R &&
                    event.ctrlKey){
                    console.log('<ctrl>+r pressed');
                    console.log('reloading page...');
                    console.log('press <alt>+q to remove all key-handlers');
                    /* Программно нажимаем на кнопку перезагрузки
                     * содержимого каталога
                     */
                    var lRefreshIcon                = Util
                        .getByClass(CloudFunc.REFRESHICON);

                    if(lRefreshIcon)lRefreshIcon    = lRefreshIcon[0];
                    if(lRefreshIcon){
                        /* находим файл который сейчас выделен */
                         lCurrentFile       = Util.getCurrentFile();

                         /* получаем название файла*/
                         var lSelectedName  = lCurrentFile
                            .getElementsByTagName('a')[0].textContent;
                         /* если нашли элемент нажимаем него
                          * а если не можем - нажимаем на
                          * ссылку, на которую повешен eventHandler
                          * onclick
                          */
                        if(lRefreshIcon.click)
                            lRefreshIcon.parentElement.click();
                        else
                            lRefreshIcon.parentElement.onclick();

                        CloudCommander._currentToParent(lSelectedName);

                        event.preventDefault();//запрет на дальнейшее действие
                    }
                }

                /* если нажали <ctrl>+d чистим кэш */
                else if(event.keyCode === lKEY.D &&
                    event.ctrlKey){
                        console.log('<ctrl>+d pressed');
                        console.log('clearing cache...');
                        console.log('press <alt>+q to remove all key-handlers');

                        var lClearCache = Util.getById('clear-cache');
                        if(lClearCache && lClearCache.onclick)
                        	lClearCache.onclick();

                		event.preventDefault();//запрет на дальнейшее действие
                }

                /* если нажали <alt>+q
                 * убираем все обработчики
                 * нажатий клавиш
                 */
                else if(event.keyCode === lKEY.Q &&
                    event.altKey){
                        //document.removeEventListener('keydown', key_event,false);
                        console.log('<alt>+q pressed');
                        console.log('<ctrl>+r reload key-handerl - removed');
                        console.log('<ctrl>+s clear cache key-handler - removed');
                        console.log('press <alt>+s to to set them');

                        /* обработчик нажатий клавиш снят*/
                        CloudCommander.keyBinded = false;

                  		event.preventDefault();//запрет на дальнейшее действие
                }
            }

            /* если нажали <alt>+s
             * устанавливаем все обработчики
             * нажатий клавиш
             */
            else if(event && event.keyCode === lKEY.S &&
                event.altKey){
                    /* обрабатываем нажатия на клавиши*/
                    CloudCommander.keyBinded = true;

                    console.log('<alt>+s pressed');
                    console.log('<ctrl>+r reload key-handerl - set');
                    console.log('<ctrl>+s clear cache key-handler - set');
                    console.log('press <alt>+q to remove them');

              		event.preventDefault();//запрет на дальнейшее действие
            }

        return false;
    };

    /* добавляем обработчик клавишь */
    if(document.addEventListener)
        document.addEventListener('keydown', key_event,false);
    else document.onkeydown = key_event;
    /* клавиши назначены*/
    CloudCommander.keyBinded=true;
});<|endoftext|>


<commit_before>'use strict';

var React = require('react');
var ColorPicker = require('./color-picker');
var SearchStore = require('./search-store');
var _ = require('underscore');

var searchableTypes = [
  'name',
  'defaultValue',
  'value',
  'label'
];

var FormCollection = React.createClass({
  areDefined: function (value) {
    return typeof value !== 'undefined';
  },

  areInValue: function (value, term) {
    return value.toLowerCase().indexOf(term) >= 0;
  },

  containsSearchTerm: function (value, key) {
    var self = this;
    var searchTerm = this.props.searchTerm.toLowerCase().replace(/\s+?/gi, ' ');
    var searchTerms = searchTerm.split(' ');

    return searchableTypes.indexOf(key) >= 0 &&
      value &&
      (
        value.toLowerCase().indexOf(searchTerm) >= 0 ||
        _.every(searchTerms, self.areInValue.bind(self, value))
      );
  },

  addToSearch: function (val) {
    console.log(val);
    SearchStore.action('setSearchTerm', val);
  },

  create: {
    subHeader: function (child) {
      if (this.props.searchTerm) {
        return undefined;
      }
      return (

child.value

      );
    },

    variable: function (child, index) {
      var self = this;
      var colorPicker, label;

      if (this.props.searchTerm && !_.any(child, this.containsSearchTerm)) {
        return undefined;
      }

      if (child.type === 'color') {
        colorPicker = (
          <ColorPicker
            setValue={self.props.updateVariable.bind(null, self.props.index, index)}
            value={child.value}
            defaultValue={child.defaultValue} />
        );
      }

      if (child.label) {
        label = (

            {child.label}

        );
      }

      return (

          {label}

            {child.name}

            <input
              text='text'
              className='form-control'
              placeholder={child.defaultValue}
              value={child.value}
              onChange={self.props.updateVariable.bind(null, self.props.index, index)} />
            {colorPicker}

      );
    }
  },

  render: function () {
    var self = this;
    var description, hasSearchResults, children;

    var isNotActiveCollection = typeof this.props.activeIndex !== 'undefined' &&
      this.props.index !== this.props.activeIndex;
    var isActiveCollection = typeof this.props.activeIndex !== 'undefined' &&
      this.props.index === this.props.activeIndex;

    if (isNotActiveCollection && !this.props.searchTerm) {
      return false;
    }

    if (isActiveCollection || this.props.searchTerm) {
      children = this.props.group.children.map(function (child, index) {
        return self.create[child.element].call(self, child, index);
      });
    }

    if (isActiveCollection && this.props.group.description) {
      description = (

{this.props.group.description}

      );
    }

    if (this.props.searchTerm) {
      hasSearchResults = _.any(children, this.areDefined);

      if (!hasSearchResults) {
        return false;
      }
    }

    return (

{this.props.group.value}

            {description}
            {children}

    );
  }
});

module.exports = FormCollection;
<commit_msg>Fix tests<commit_after>'use strict';

var React = require('react');
var ColorPicker = require('./color-picker');
var SearchStore = require('./search-store');
var _ = require('underscore');

var searchableTypes = [
  'name',
  'defaultValue',
  'value',
  'label'
];

var FormCollection = React.createClass({
  areDefined: function (value) {
    return typeof value !== 'undefined';
  },

  areInValue: function (value, term) {
    return value.toLowerCase().indexOf(term) >= 0;
  },

  containsSearchTerm: function (value, key) {
    var self = this;
    var searchTerm = this.props.searchTerm.toLowerCase().replace(/\s+?/gi, ' ');
    var searchTerms = searchTerm.split(' ');

    return searchableTypes.indexOf(key) >= 0 &&
      value &&
      (
        value.toLowerCase().indexOf(searchTerm) >= 0 ||
        _.every(searchTerms, self.areInValue.bind(self, value))
      );
  },

  addToSearch: function (val) {
    console.log(val);
    SearchStore.action('setSearchTerm', val);
  },

  create: {
    subHeader: function (child) {
      if (this.props.searchTerm) {
        return undefined;
      }
      return (

child.value

      );
    },

    variable: function (child, index) {
      var self = this;
      var colorPicker, label;

      if (this.props.searchTerm && !_.any(child, this.containsSearchTerm)) {
        return undefined;
      }

      if (child.type === 'color') {
        colorPicker = (
          <ColorPicker
            setValue={self.props.updateVariable.bind(null, self.props.index, index)}
            value={child.value}
            defaultValue={child.defaultValue} />
        );
      }

      if (child.label) {
        label = (

            {child.label}

        );
      }

      return (

          {label}

            {child.name}

            <input
              text='text'
              className='form-control'
              placeholder={child.defaultValue}
              value={child.value}
              onChange={self.props.updateVariable.bind(null, self.props.index, index)} />
            {colorPicker}

      );
    }
  },

  render: function () {
    var self = this;
    var description, hasSearchResults, children;

    var isNotActiveCollection = typeof this.props.activeIndex !== 'undefined' &&
      this.props.index !== this.props.activeIndex;
    var isActiveCollection = typeof this.props.activeIndex !== 'undefined' &&
      this.props.index === this.props.activeIndex;

    if (isNotActiveCollection && !this.props.searchTerm) {
      return false;
    }

    if (isActiveCollection || this.props.searchTerm) {
      children = this.props.group.children.map(function (child, index) {
        return self.create[child.element].call(self, child, index);
      });
    }

    if (isActiveCollection && this.props.group.description) {
      description = (

{this.props.group.description}

      );
    }

    if (this.props.searchTerm) {
      hasSearchResults = _.any(children, this.areDefined);

      if (!hasSearchResults) {
        return false;
      }
    }

    return (

{this.props.group.value}

            {description}
            {children}

    );
  }
});

module.exports = FormCollection;
<|endoftext|>


<commit_before>
// notes:
// implement starting a file that was started before
// implement checking for an existing file in the container
// implement logging
// implement configuration file
// implement some kind of username/password/container

var config = require("config");
var promise = require("bluebird");
var express = require("express");
var bodyParser = require("body-parser");
var wasb = require("azure-storage");
var fs = require("fs");
var base64 = require("base64-stream");
var stream = require("stream");

var app = express();
app.use(express.static("client"));

var storageAccount = config.get("storageAccount");
var storageKey = config.get("storageKey");

// the current upload queue
var pending = {
    list: [],

    add: function(container, name, overwrite) {

        // connect to Azure Storage
        var service = wasb.createBlobService(storageAccount, storageKey);

        // use or create the container
        var ensureContainer = new promise(function(resolve, reject) {
            try {
                service.createContainerIfNotExists(container, function(error, result, response) {
                    if (error) {
                        console.log("createContainerIfNotExists: " + error);
                        reject("container?");
                    } else {
                        resolve(result);
                    }
                });
            } catch (ex) {
                console.log("createContainerIfNotExists: " + ex);
                reject("container?");
            }
        });

        // check to see if the blob already exists
        var canWriteFile = new promise(function(resolve, reject) {
            try {
                service.doesBlobExist(container, name, function(error, result, response) {
                    if (error) {
                        console.log("doesBlobExist: " + error);
                        reject("exists?");
                    } else {
                        if (!result.exists || overwrite) {
                            resolve(result);
                        } else {
                            reject("exists");
                        }
                    }
                });
            } catch (ex) {
                console.log("doesBlobExist: " + ex);
                reject("exists?");
            }
        });

        var begin = new promise(function(resolve, reject) {
            try {

                // create a writable block blob
                var writer = service.createWriteStreamToBlockBlob(container, name, function(error, result, response) {
                    if (error) {
                        console.log("createWriteStreamToBlockBlob: " + error);
                    }
                });

                // create a reference for the file
                var file = {
                    container: container,
                    name: name,
                    sequence: 0,
                    writer: writer
                };

                // add to pending list
                pending.list.push(file);
                resolve(file);

            } catch (ex) {
                console.log("createWriteStreamToBlockBlob: " + ex);
                reject("write?");
            }
        });

        // process those actions in serial
        return promise.each([ensureContainer, canWriteFile, begin], function(result) { }).then(function(results) {
            return results[2];
        }, function(error) {
            return promise.reject(error);
        });

    },

    remove: function(container, name) {
        for (var i = 0; i < this.list.length; i++) {
            if (this.list[i].container == container && this.list[i].name == name) {
                this.list.splice(i, 1);
                return;
            }
        }
    },

    find: function(container, name) {
        for (var i = 0; i < this.list.length; i++) {
            if (this.list[i].container == container && this.list[i].name == name) return this.list[i];
        }
        return null;
    }

};

// hello
app.get("/hello", function(req, res) {
   res.send("hello");
});

// home page
app.get("/", function(req, res) {
    res.redirect("/index.htm");
});

// extend the response object to include the custom error messages
express.response.sendError = function(error) {
    console.log("error: " + JSON.stringify(error));
    switch(error) {
        case "exception":
            this.status(500).send({ code: 100, msg: "The application raised an exception. Please refresh your browser and try again later or contact the system administrator." });
            break;
        case "malformed":
            this.status(500).send({ code: 110, msg: "The request sent to the server was malformed. Please refresh your browser and try again or contact the system administrator." });
            break;
        case "container?":
        case "list?":
        case "exists?":
        case "write?":
            this.status(500).send({ code: 200, msg: "The file repository cannot be accessed right now, please try again later." });
            break;
        case "exists":
            this.status(500).send({ code: 300, msg: "The file already exists, please flag to overwrite the existing file or upload with a different filename." });
            break;
        case "out-of-sync":
            this.status(500).send({ code: 400, msg: "The upload packets were not in the expected order. Please refresh your browser and select the file for upload again." });
            break;
        default:
            this.status(500).send({ code: 999, msg: "Unknown error." });
            break;
    }
}

// get a list of objects in the server container
app.get("/list", function(req, res) {
    if (req.query.container) {
        var service = wasb.createBlobService(storageAccount, storageKey);
        var list = new promise(function(resolve, reject) {
            try {
                service.listBlobsSegmented(req.query.container, null, {
                    maxResults: 100
                }, function(error, result, response) {
                    if (error) {
                        console.log("listBlobsSegmented: " + error);
                        reject("list?");
                    } else {
                        resolve(result);
                    }
                });
            } catch (ex) {
                console.log("listBlobsSegmented: " + ex);
                reject("list?");
            }
        });
        list.then(function(result) {
            var response = [];
            result.entries.forEach(function(entry) {
                response.push({
                    "name": entry.name,
                    "size": entry.contentLength,
                    "ts": entry.lastModified
                });
            });
            res.status(200).send(response);
        }, function(error) {
            res.sendError(error);
        }).catch(function(ex) {
            console.log(ex);
            res.sendError("exception");
        });
    } else {
        res.sendError("malformed");
    }
});

// upload all or part of a file
app.post("/upload", function(req, res) {
    if (req.query.container && req.query.name && req.query.cmd && req.query.seq) {
        var overwrite = (req.query.overwrite == "true");
        var file = pending.find(req.query.container, req.query.name);
        var decoder = base64.decode();
        switch(req.query.cmd) {

            case "complete":
                if (!file) {
                    // upload the file
                    pending.add(req.query.container, req.query.name, overwrite).then(function(file) {
                        req.pipe(decoder).pipe(file.writer);
                        pending.remove(req.query.container, req.query.name);
                        res.status(200).end();
                    }, function(error) {
                        res.sendError(error);
                    }).catch(function(ex) {
                        console.log(ex);
                        res.sendError("exception");
                    });
                } else {
                    // replace the in-progress upload (implicit replace)
                    file.writer.end();
                    pending.remove(req.query.container, req.query.name);
                    pending.add(req.query.container, req.query.name, true).then(function(file) {
                        req.pipe(decoder).pipe(file.writer);
                        pending.remove(req.query.container, req.query.name);
                        res.status(200).end();
                    }, function(error) {
                        pending.remove(req.query.container, req.query.name);
                        res.sendError(error);
                    }).catch(function(ex) {
                        console.log(ex);
                        res.sendError("exception");
                    });
                }
                break;

            case "begin":
                if (!file) {
                    // upload the file
                    pending.add(req.query.container, req.query.name, overwrite).then(function(file) {
                        req.pipe(decoder).pipe(file.writer, { end: false });
                        file.sequence++;
                        res.status(200).end();
                    }, function(error) {
                        pending.remove(req.query.container, req.query.name);
                        res.sendError(error);
                    }).catch(function(ex) {
                        console.log(ex);
                        res.sendError("exception");
                    });
                } else {
                    // resume the in-progress upload (implicit continue)
                    res.status(500).send("implement continue!!!");
                }
                break;

            case "continue":
                if (file.sequence == req.query.seq) {
                    req.pipe(decoder).pipe(file.writer, { end: false });
                    file.sequence++;
                    res.status(200).end();
                } else if (req.query.seq < file.sequence) {
                    // the request sequence can be lower if it didn't get confirmation of a commit, let it catch up
                    res.status(200).end();
                } else {
                    res.sendError("out-of-sync");
                }
                break;

            case "end":
                if (file.sequence == req.query.seq) {
                    req.pipe(decoder).pipe(file.writer);
                    pending.remove(req.query.container, req.query.name);
                    res.status(200).end();
                } else if (req.query.seq < file.sequence) {
                    // the request sequence can be lower if it didn't get confirmation of a commit, let it catch up
                    res.status(200).end();
                } else {
                    res.sendError("out-of-sync");
                }
                break;

            case "abort":
                pending.remove(req.query.container, req.query.name);
                res.status(200).end();
                break;

        }
    } else {
        res.sendError("malformed");
    }
});

// start the server
var port = process.env.port || 80;
app.listen(port, function() {
   console.log("listening on port " + port + "...");
});

// alert on unhandled rejections
process.on("unhandledRejection", function(reason, p) {
    console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ", reason);
});<commit_msg>more features 2<commit_after>
// notes:
// implement starting a file that was started before
// implement checking for an existing file in the container
// implement logging
// implement some kind of username/password/container

var config = require("config");
var promise = require("bluebird");
var express = require("express");
var bodyParser = require("body-parser");
var wasb = require("azure-storage");
var fs = require("fs");
var base64 = require("base64-stream");
var stream = require("stream");

var app = express();
app.use(express.static("client"));

var storageAccount = config.get("storageAccount");
var storageKey = config.get("storageKey");

// the current upload queue
var pending = {
    list: [],

    add: function(container, name, overwrite) {

        // connect to Azure Storage
        var service = wasb.createBlobService(storageAccount, storageKey);

        // use or create the container
        var ensureContainer = new promise(function(resolve, reject) {
            try {
                service.createContainerIfNotExists(container, function(error, result, response) {
                    if (error) {
                        console.log("createContainerIfNotExists: " + error);
                        reject("container?");
                    } else {
                        resolve(result);
                    }
                });
            } catch (ex) {
                console.log("createContainerIfNotExists: " + ex);
                reject("container?");
            }
        });

        // check to see if the blob already exists
        var canWriteFile = new promise(function(resolve, reject) {
            try {
                service.doesBlobExist(container, name, function(error, result, response) {
                    if (error) {
                        console.log("doesBlobExist: " + error);
                        reject("exists?");
                    } else {
                        if (!result.exists || overwrite) {
                            resolve(result);
                        } else {
                            reject("exists");
                        }
                    }
                });
            } catch (ex) {
                console.log("doesBlobExist: " + ex);
                reject("exists?");
            }
        });

        var begin = new promise(function(resolve, reject) {
            try {

                // create a writable block blob
                var writer = service.createWriteStreamToBlockBlob(container, name, function(error, result, response) {
                    if (error) {
                        console.log("createWriteStreamToBlockBlob: " + error);
                    }
                });

                // create a reference for the file
                var file = {
                    container: container,
                    name: name,
                    sequence: 0,
                    writer: writer
                };

                // add to pending list
                pending.list.push(file);
                resolve(file);

            } catch (ex) {
                console.log("createWriteStreamToBlockBlob: " + ex);
                reject("write?");
            }
        });

        // process those actions in serial
        return promise.each([ensureContainer, canWriteFile, begin], function(result) { }).then(function(results) {
            return results[2];
        }, function(error) {
            return promise.reject(error);
        });

    },

    remove: function(container, name) {
        for (var i = 0; i < this.list.length; i++) {
            if (this.list[i].container == container && this.list[i].name == name) {
                this.list.splice(i, 1);
                return;
            }
        }
    },

    find: function(container, name) {
        for (var i = 0; i < this.list.length; i++) {
            if (this.list[i].container == container && this.list[i].name == name) return this.list[i];
        }
        return null;
    }

};

// hello
app.get("/hello", function(req, res) {
   res.send("hello");
});

// home page
app.get("/", function(req, res) {
    res.redirect("/index.htm");
});

// extend the response object to include the custom error messages
express.response.sendError = function(error) {
    console.log("error: " + JSON.stringify(error));
    switch(error) {
        case "exception":
            this.status(500).send({ code: 100, msg: "The application raised an exception. Please refresh your browser and try again later or contact the system administrator." });
            break;
        case "malformed":
            this.status(500).send({ code: 110, msg: "The request sent to the server was malformed. Please refresh your browser and try again or contact the system administrator." });
            break;
        case "container?":
        case "list?":
        case "exists?":
        case "write?":
            this.status(500).send({ code: 200, msg: "The file repository cannot be accessed right now, please try again later." });
            break;
        case "exists":
            this.status(500).send({ code: 300, msg: "The file already exists, please flag to overwrite the existing file or upload with a different filename." });
            break;
        case "out-of-sync":
            this.status(500).send({ code: 400, msg: "The upload packets were not in the expected order. Please refresh your browser and select the file for upload again." });
            break;
        default:
            this.status(500).send({ code: 999, msg: "Unknown error." });
            break;
    }
}

// get a list of objects in the server container
app.get("/list", function(req, res) {
    if (req.query.container) {
        var service = wasb.createBlobService(storageAccount, storageKey);
        var list = new promise(function(resolve, reject) {
            try {
                service.listBlobsSegmented(req.query.container, null, {
                    maxResults: 100
                }, function(error, result, response) {
                    if (error) {
                        console.log("listBlobsSegmented: " + error);
                        reject("list?");
                    } else {
                        resolve(result);
                    }
                });
            } catch (ex) {
                console.log("listBlobsSegmented: " + ex);
                reject("list?");
            }
        });
        list.then(function(result) {
            var response = [];
            result.entries.forEach(function(entry) {
                response.push({
                    "name": entry.name,
                    "size": entry.contentLength,
                    "ts": entry.lastModified
                });
            });
            res.status(200).send(response);
        }, function(error) {
            res.sendError(error);
        }).catch(function(ex) {
            console.log(ex);
            res.sendError("exception");
        });
    } else {
        res.sendError("malformed");
    }
});

// upload all or part of a file
app.post("/upload", function(req, res) {
    if (req.query.container && req.query.name && req.query.cmd && req.query.seq) {
        var overwrite = (req.query.overwrite == "true");
        var file = pending.find(req.query.container, req.query.name);
        var decoder = base64.decode();
        switch(req.query.cmd) {

            case "complete":
                if (!file) {
                    // upload the file
                    pending.add(req.query.container, req.query.name, overwrite).then(function(file) {
                        req.pipe(decoder).pipe(file.writer);
                        pending.remove(req.query.container, req.query.name);
                        res.status(200).end();
                    }, function(error) {
                        res.sendError(error);
                    }).catch(function(ex) {
                        console.log(ex);
                        res.sendError("exception");
                    });
                } else {
                    // replace the in-progress upload (implicit replace)
                    file.writer.end();
                    pending.remove(req.query.container, req.query.name);
                    pending.add(req.query.container, req.query.name, true).then(function(file) {
                        req.pipe(decoder).pipe(file.writer);
                        pending.remove(req.query.container, req.query.name);
                        res.status(200).end();
                    }, function(error) {
                        pending.remove(req.query.container, req.query.name);
                        res.sendError(error);
                    }).catch(function(ex) {
                        console.log(ex);
                        res.sendError("exception");
                    });
                }
                break;

            case "begin":
                if (!file) {
                    // upload the file
                    pending.add(req.query.container, req.query.name, overwrite).then(function(file) {
                        req.pipe(decoder).pipe(file.writer, { end: false });
                        file.sequence++;
                        res.status(200).end();
                    }, function(error) {
                        pending.remove(req.query.container, req.query.name);
                        res.sendError(error);
                    }).catch(function(ex) {
                        console.log(ex);
                        res.sendError("exception");
                    });
                } else {
                    // resume the in-progress upload (implicit continue)
                    res.status(500).send("implement continue!!!");
                }
                break;

            case "continue":
                if (file.sequence == req.query.seq) {
                    req.pipe(decoder).pipe(file.writer, { end: false });
                    file.sequence++;
                    res.status(200).end();
                } else if (req.query.seq < file.sequence) {
                    // the request sequence can be lower if it didn't get confirmation of a commit, let it catch up
                    res.status(200).end();
                } else {
                    res.sendError("out-of-sync");
                }
                break;

            case "end":
                if (file.sequence == req.query.seq) {
                    req.pipe(decoder).pipe(file.writer);
                    pending.remove(req.query.container, req.query.name);
                    res.status(200).end();
                } else if (req.query.seq < file.sequence) {
                    // the request sequence can be lower if it didn't get confirmation of a commit, let it catch up
                    res.status(200).end();
                } else {
                    res.sendError("out-of-sync");
                }
                break;

            case "abort":
                pending.remove(req.query.container, req.query.name);
                res.status(200).end();
                break;

        }
    } else {
        res.sendError("malformed");
    }
});

// start the server
var port = process.env.port || 80;
app.listen(port, function() {
   console.log("listening on port " + port + "...");
});

// alert on unhandled rejections
process.on("unhandledRejection", function(reason, p) {
    console.log("Possibly Unhandled Rejection at: Promise ", p, " reason: ", reason);
});<|endoftext|>


<commit_before>const NewRelic = require("newrelic");
const ParseServer = require("parse-server").ParseServer;
const ParseDashboard = require("parse-dashboard");
const BodyParser = require("body-parser");
const Express = require("express");
const Compression = require("compression");
const Favicon = require("serve-favicon");
const helmet = require("helmet");

// Server Config
const DB_URL = process.env.MONGODB_URI;
const PORT = process.env.PORT;
const SERVER_URL = process.env.SERVER_URL;
const APP_NAME = process.env.APP_NAME;
const APP_ID = process.env.APP_ID;
const FILE_KEY = process.env.FILE_KEY;
const MASTER_KEY = process.env.MASTER_KEY;
const ALLOW_INSECURE_HTTP = process.env.PARSE_DASHBOARD_ALLOW_INSECURE_HTTP;

// Parse Platform Server
const api = new ParseServer({
    databaseURI: DB_URL,
    cloud: process.cwd() + "/cloud/main.js",
    appId: APP_ID,
    masterKey: MASTER_KEY,
    fileKey: FILE_KEY,
    serverURL: SERVER_URL,
    "filesAdapter": {
        "module": "parse-server-fs-adapter",
        "options": {
            "filesSubDirectory": "my/files/folder" // optional
        }
    }
});

// Parse Platform Dashboard
const dashboard = new ParseDashboard({
    "apps": [
        {
            "serverURL": SERVER_URL,
            "appId": APP_ID,
            "masterKey": MASTER_KEY,
            "appName": APP_NAME
        }
    ],
    "users": [
        {
            "apps": [{"appId": APP_ID}],
            "user": process.env.DASHBOARD_ID,
            "pass": process.env.DASHBOARD_PW
        }
    ]
}, ALLOW_INSECURE_HTTP);

// Express 설정
const app = Express();
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.engine("html", require("ejs").renderFile);
app.use("/public", Express.static(__dirname + "/public"));
app.use(BodyParser.urlencoded({extended: true}));
app.use(BodyParser.json());
app.locals.newrelic = NewRelic;

// Favicon
// From http://www.favicon-generator.org/
app.use(Favicon(__dirname + "/public/favicon/favicon-32x32.png"));

// gzip
app.use(Compression());

// user helmet for safety
app.use(helmet());

// disable for safety
app.disable("x-powered-by");

// Router
app.use("/parse", api);
app.use("/dashboard", dashboard);
app.use("/", require("./router/main/main.js"));
app.use("/api/data/read", require("./router/api/read"));

// Handle 404 - Keep this as a last route
app.use(function (req, res, next) {
    res.status(404);
    res.send("404: File Not Found");
    res.render("index.html");
});

app.listen(PORT, function () {
    console.log("Trend Reader Working");
});<commit_msg>test<commit_after>const NewRelic = require("newrelic");
const ParseServer = require("parse-server").ParseServer;
const ParseDashboard = require("parse-dashboard");
const BodyParser = require("body-parser");
const Express = require("express");
const Compression = require("compression");
const Favicon = require("serve-favicon");
const helmet = require("helmet");

// Server Config
const DB_URL = process.env.MONGODB_URI;
const PORT = process.env.PORT;
const SERVER_URL = process.env.SERVER_URL;
const APP_NAME = process.env.APP_NAME;
const APP_ID = process.env.APP_ID;
const FILE_KEY = process.env.FILE_KEY;
const MASTER_KEY = process.env.MASTER_KEY;
const ALLOW_INSECURE_HTTP = true;

// Parse Platform Server
const api = new ParseServer({
    databaseURI: DB_URL,
    cloud: process.cwd() + "/cloud/main.js",
    appId: APP_ID,
    masterKey: MASTER_KEY,
    fileKey: FILE_KEY,
    serverURL: SERVER_URL,
    "filesAdapter": {
        "module": "parse-server-fs-adapter",
        "options": {
            "filesSubDirectory": "my/files/folder" // optional
        }
    }
});

// Parse Platform Dashboard
const dashboard = new ParseDashboard({
    "apps": [
        {
            "serverURL": SERVER_URL,
            "appId": APP_ID,
            "masterKey": MASTER_KEY,
            "appName": APP_NAME
        }
    ],
    "users": [
        {
            "apps": [{"appId": APP_ID}],
            "user": process.env.DASHBOARD_ID,
            "pass": process.env.DASHBOARD_PW
        }
    ]
}, ALLOW_INSECURE_HTTP);

// Express 설정
const app = Express();
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.engine("html", require("ejs").renderFile);
app.use("/public", Express.static(__dirname + "/public"));
app.use(BodyParser.urlencoded({extended: true}));
app.use(BodyParser.json());
app.locals.newrelic = NewRelic;

// Favicon
// From http://www.favicon-generator.org/
app.use(Favicon(__dirname + "/public/favicon/favicon-32x32.png"));

// gzip
app.use(Compression());

// user helmet for safety
app.use(helmet());

// disable for safety
app.disable("x-powered-by");

// Router
app.use("/parse", api);
app.use("/dashboard", dashboard);
app.use("/", require("./router/main/main.js"));
app.use("/api/data/read", require("./router/api/read"));

// Handle 404 - Keep this as a last route
app.use(function (req, res, next) {
    res.status(404);
    res.send("404: File Not Found");
    res.render("index.html");
});

app.listen(PORT, function () {
    console.log("Trend Reader Working");
});<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import { setSearchTerm } from './actionCreators'
const { string, func, object } = React.PropTypes

const Landing = React.createClass({
  contextTypes: {
    router: object
  },
  propTypes: {
    searchTerm: string,
    dispatchSetSearchTerm: func
  },
  handleSearchTermChange (event) {
    this.props.dispatchSetSearchTerm(event.target.value)
  },
  handleSearchSubmit (event) {
    event.preventDefault()
    this.context.router.transitionTo('/search')
  },
  render () {
    return (

svideo

        <form onSubmit={this.handleSearchSubmit}>
          <input onChange={this.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' />
        </form>
        <Link to='/search'>or Browse All...dd</Link>

     )
  }
})

const mapStateToProps = (state) => {
  return {
    searchTerm: state.searchTerm
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    dispatchSetSearchTerm (searchTerm) {
      dispatch(setSearchTerm)
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Landing)
<commit_msg>small commit<commit_after>import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import { setSearchTerm } from './actionCreators'
const { string, func, object } = React.PropTypes

const Landing = React.createClass({
  contextTypes: {
    router: object
  },
  propTypes: {
    searchTerm: string,
    dispatchSetSearchTerm: func
  },
  handleSearchTermChange (event) {
    this.props.dispatchSetSearchTerm(event.target.value)
  },
  handleSearchSubmit (event) {
    event.preventDefault()
    this.context.router.transitionTo('/search')
  },
  render () {
    return (

svideo

        <form onSubmit={this.handleSearchSubmit}>
          <input onChange={this.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' />
        </form>
        <Link to='/search'>or Browse All</Link>

     )

const mapStateToProps = (state) => {
  return {
    searchTerm: state.searchTerm
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    dispatchSetSearchTerm (searchTerm) {
      dispatch(setSearchTerm)
    }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Landing)
<|endoftext|>


<commit_before>describe("luga.data.DetailSet", function(){

	"use strict";

	var emptyDs, loadedDs, testRecords, detailSet, emptyDetailSet, testObserver;
	beforeEach(function(){

		testRecords = getJSONFixture("data/ladies.json");
		emptyDs = new luga.data.DataSet({uuid: "test"});
		loadedDs = new luga.data.DataSet({uuid: "myDs", records: testRecords});

		detailSet = new luga.data.DetailSet({uuid: "detailTest", parentDataSet: loadedDs});
		emptyDetailSet = new luga.data.DetailSet({uuid: "emptyDetailTest", parentDataSet: emptyDs});

		testObserver = {
			onDataChangedHandler: function(){
			}
		};
		detailSet.addObserver(testObserver);
		spyOn(testObserver, "onDataChangedHandler");

	});

	afterEach(function() {
		luga.data.dataSourceRegistry = {};
	});

	it("Is the detailSet class", function(){
		expect(jQuery.isFunction(luga.data.DetailSet)).toEqual(true);
	});

	it("Implements the Notifier interface", function(){
		expect(jQuery.isFunction(detailSet.addObserver)).toEqual(true);
		expect(jQuery.isFunction(detailSet.notifyObservers)).toEqual(true);
		expect(jQuery.isArray(detailSet.observers)).toEqual(true);
	});

	describe("Accepts an Options object as single argument", function(){

		describe("options.uuid", function(){
			it("Acts as unique identifier that will be stored inside a global registry", function(){
				var ds = new luga.data.DetailSet({uuid: "uniqueId", parentDataSet: emptyDs});
				expect(luga.data.dataSourceRegistry.uniqueId).toEqual(ds);
			});
			it("Throws an exception if not specified", function(){
				expect(function(){
					new luga.data.DetailSet({dataSet: emptyDs});
				}).toThrow();
			});
		});

		describe("options.parentDataSet", function(){
			it("Is the dataSource that will be used by the detailSet", function(){
				var ds = new luga.data.DetailSet({uuid: "uniqueId", parentDataSet: emptyDs});
				expect(ds.parentDataSet).toEqual(emptyDs);
			});
			it("Throws an exception if not specified", function(){
				expect(function(){
					new luga.data.DetailSet({uuid: "uniqueId"});
				}).toThrow();
			});
		});

		describe("Once initialized:", function(){
			it("Calls luga.data.setDataSource()", function(){
				spyOn(luga.data, "setDataSource").and.callFake(function(){
				});
				var testDetailSet = new luga.data.DetailSet({uuid: "test", parentDataSet: emptyDs});
				expect(luga.data.setDataSource).toHaveBeenCalledWith("test", testDetailSet);
			});
			it("Register itself as observer of options.dataSet", function(){
				expect(emptyDs.observers[0]).toEqual(emptyDetailSet);
			});
			it("Points its .row property to options.dataSet's current row", function(){
				expect(emptyDetailSet.row).toEqual(emptyDs.getCurrentRow());
				expect(detailSet.row).toEqual(loadedDs.getCurrentRow());
			});
		});

		describe(".getContext()", function(){
			it("Returns the associated detailSet's context", function(){
				var contextMaster = new luga.data.DataSet({uuid: "contextMaster"});
				contextMaster.insert(testRecords);
				var contextDetail = new luga.data.DetailSet({uuid: "contextDetail", parentDataSet: contextMaster});
				var context = contextDetail.getContext();
				expect(context.entity).toEqual(loadedDs.getCurrentRow());
			});
		});

		describe(".getState()", function(){
			it("Returns the associated dataSet's current state", function(){
				expect(detailSet.getState()).toEqual(loadedDs.getState());
			});
		});

		describe(".fetchRow()", function(){

			describe("First:", function(){
				it("Grabs the associated dataSet's current row", function(){
					spyOn(loadedDs, "getCurrentRow").and.callFake(function(){
					});
					detailSet.fetchRow();
					expect(loadedDs.getCurrentRow).toHaveBeenCalled();
					expect(loadedDs.getCurrentRow()).toEqual(detailSet.row);
				});
			});

			describe("Then:", function(){
				it("Triggers a 'dataChanged' notification", function(){
					detailSet.fetchRow();
					expect(testObserver.onDataChangedHandler).toHaveBeenCalledWith({dataSource: detailSet});
				});
			});

		});

		describe(".onCurrentRowChangedHandler()", function(){
			it("Is invoked whenever the associated dataSet's currentRow changes", function(){
				spyOn(detailSet, "onCurrentRowChangedHandler");
				loadedDs.setCurrentRowIndex(2);
				expect(detailSet.onCurrentRowChangedHandler).toHaveBeenCalled();
			});
			it("Invokes .fetchRow()", function(){
				spyOn(detailSet, "fetchRow");
				detailSet.onCurrentRowChangedHandler();
				expect(detailSet.fetchRow).toHaveBeenCalled();
			});
		});

		describe(".onDataChangedHandler()", function(){
			it("Is invoked whenever the associated dataSet's data changes", function(){
				spyOn(emptyDetailSet, "onDataChangedHandler");
				emptyDs.insert(testRecords);
				expect(emptyDetailSet.onDataChangedHandler).toHaveBeenCalled();
			});
			it("Invokes .fetchRow()", function(){
				spyOn(emptyDetailSet, "fetchRow");
				emptyDetailSet.onDataChangedHandler();
				expect(emptyDetailSet.fetchRow).toHaveBeenCalled();
			});
		});

		describe(".onStateChangedHandler()", function(){
			it("Is invoked whenever the associated dataSet's state changes", function(){
				spyOn(emptyDetailSet, "onStateChangedHandler");
				emptyDs.insert(testRecords);
				expect(emptyDetailSet.onStateChangedHandler).toHaveBeenCalled();
			});
			it("Invokes .fetchRow()", function(){
				spyOn(emptyDetailSet, "fetchRow");
				emptyDetailSet.onStateChangedHandler();
				expect(emptyDetailSet.fetchRow).toHaveBeenCalled();
			});
		});

	});

});<commit_msg>Test: Minor tweak to old test. Use duckType matcher<commit_after>describe("luga.data.DetailSet", function(){

	"use strict";

	var emptyDs, loadedDs, testRecords, detailSet, emptyDetailSet, testObserver;
	beforeEach(function(){

		testRecords = getJSONFixture("data/ladies.json");
		emptyDs = new luga.data.DataSet({uuid: "test"});
		loadedDs = new luga.data.DataSet({uuid: "myDs", records: testRecords});

		detailSet = new luga.data.DetailSet({uuid: "detailTest", parentDataSet: loadedDs});
		emptyDetailSet = new luga.data.DetailSet({uuid: "emptyDetailTest", parentDataSet: emptyDs});

		testObserver = {
			onDataChangedHandler: function(){
			}
		};
		detailSet.addObserver(testObserver);
		spyOn(testObserver, "onDataChangedHandler");

	});

	afterEach(function() {
		luga.data.dataSourceRegistry = {};
	});

	it("Is the detailSet class", function(){
		expect(jQuery.isFunction(luga.data.DetailSet)).toEqual(true);
	});

	it("Implements the luga.Notifier interface", function(){
		var MockNotifier = function(){
			luga.extend(luga.Notifier, this);
		};
		expect(detailSet).toMatchDuckType(new MockNotifier());
	});

	describe("Accepts an Options object as single argument", function(){

		describe("options.uuid", function(){
			it("Acts as unique identifier that will be stored inside a global registry", function(){
				var ds = new luga.data.DetailSet({uuid: "uniqueId", parentDataSet: emptyDs});
				expect(luga.data.dataSourceRegistry.uniqueId).toEqual(ds);
			});
			it("Throws an exception if not specified", function(){
				expect(function(){
					new luga.data.DetailSet({dataSet: emptyDs});
				}).toThrow();
			});
		});

		describe("options.parentDataSet", function(){
			it("Is the dataSource that will be used by the detailSet", function(){
				var ds = new luga.data.DetailSet({uuid: "uniqueId", parentDataSet: emptyDs});
				expect(ds.parentDataSet).toEqual(emptyDs);
			});
			it("Throws an exception if not specified", function(){
				expect(function(){
					new luga.data.DetailSet({uuid: "uniqueId"});
				}).toThrow();
			});
		});

		describe("Once initialized:", function(){
			it("Calls luga.data.setDataSource()", function(){
				spyOn(luga.data, "setDataSource").and.callFake(function(){
				});
				var testDetailSet = new luga.data.DetailSet({uuid: "test", parentDataSet: emptyDs});
				expect(luga.data.setDataSource).toHaveBeenCalledWith("test", testDetailSet);
			});
			it("Register itself as observer of options.dataSet", function(){
				expect(emptyDs.observers[0]).toEqual(emptyDetailSet);
			});
			it("Points its .row property to options.dataSet's current row", function(){
				expect(emptyDetailSet.row).toEqual(emptyDs.getCurrentRow());
				expect(detailSet.row).toEqual(loadedDs.getCurrentRow());
			});
		});

		describe(".getContext()", function(){
			it("Returns the associated detailSet's context", function(){
				var contextMaster = new luga.data.DataSet({uuid: "contextMaster"});
				contextMaster.insert(testRecords);
				var contextDetail = new luga.data.DetailSet({uuid: "contextDetail", parentDataSet: contextMaster});
				var context = contextDetail.getContext();
				expect(context.entity).toEqual(loadedDs.getCurrentRow());
			});
		});

		describe(".getState()", function(){
			it("Returns the associated dataSet's current state", function(){
				expect(detailSet.getState()).toEqual(loadedDs.getState());
			});
		});

		describe(".fetchRow()", function(){

			describe("First:", function(){
				it("Grabs the associated dataSet's current row", function(){
					spyOn(loadedDs, "getCurrentRow").and.callFake(function(){
					});
					detailSet.fetchRow();
					expect(loadedDs.getCurrentRow).toHaveBeenCalled();
					expect(loadedDs.getCurrentRow()).toEqual(detailSet.row);
				});
			});

			describe("Then:", function(){
				it("Triggers a 'dataChanged' notification", function(){
					detailSet.fetchRow();
					expect(testObserver.onDataChangedHandler).toHaveBeenCalledWith({dataSource: detailSet});
				});
			});

		});

		describe(".onCurrentRowChangedHandler()", function(){
			it("Is invoked whenever the associated dataSet's currentRow changes", function(){
				spyOn(detailSet, "onCurrentRowChangedHandler");
				loadedDs.setCurrentRowIndex(2);
				expect(detailSet.onCurrentRowChangedHandler).toHaveBeenCalled();
			});
			it("Invokes .fetchRow()", function(){
				spyOn(detailSet, "fetchRow");
				detailSet.onCurrentRowChangedHandler();
				expect(detailSet.fetchRow).toHaveBeenCalled();
			});
		});

		describe(".onDataChangedHandler()", function(){
			it("Is invoked whenever the associated dataSet's data changes", function(){
				spyOn(emptyDetailSet, "onDataChangedHandler");
				emptyDs.insert(testRecords);
				expect(emptyDetailSet.onDataChangedHandler).toHaveBeenCalled();
			});
			it("Invokes .fetchRow()", function(){
				spyOn(emptyDetailSet, "fetchRow");
				emptyDetailSet.onDataChangedHandler();
				expect(emptyDetailSet.fetchRow).toHaveBeenCalled();
			});
		});

		describe(".onStateChangedHandler()", function(){
			it("Is invoked whenever the associated dataSet's state changes", function(){
				spyOn(emptyDetailSet, "onStateChangedHandler");
				emptyDs.insert(testRecords);
				expect(emptyDetailSet.onStateChangedHandler).toHaveBeenCalled();
			});
			it("Invokes .fetchRow()", function(){
				spyOn(emptyDetailSet, "fetchRow");
				emptyDetailSet.onStateChangedHandler();
				expect(emptyDetailSet.fetchRow).toHaveBeenCalled();
			});
		});

	});

});<|endoftext|>


<commit_before>var Util, DOM, CloudFunc, CloudCmd;

(function (Util, DOM, CloudFunc, CloudCmd) {
    'use strict';

     CloudCmd.Listeners = new ListenersProto(Util, DOM, CloudFunc, CloudCmd);

     function ListenersProto(Util, DOM, CloudFunc, CloudCmd) {
        var Info                = DOM.CurrentInfo,
            Storage             = DOM.Storage,
            Events              = DOM.Events,
            EventsFiles         = {
                'mousedown' : Util.exec.with(execIfNotUL, setCurrentFileByEvent),
                'click'     : onClick,
                'dragstart' : Util.exec.with(execIfNotUL, onDragStart),
                'dblclick'  : Util.exec.with(execIfNotUL, onDblClick),
                'touchstart': Util.exec.with(execIfNotUL, onTouch)
            };

        this.init = function () {
            contextMenu();
            dragndrop();
            unload();
            pop();
            resize();
        };

        this.initKeysPanel          = function() {
            var keysElement     = DOM.getById('js-keyspanel');

            if (keysElement)
                Events.addClick(keysElement, function(event) {
                    var element = event.target,
                        id              = element.id,
                        operation       = function(name) {
                            var Operation = CloudCmd.Operation,
                                fn = Operation.show.bind(null, name);

                            return fn;
                        },

                        clickFuncs      = {
                            'f1'        : CloudCmd.Help.show,
                            'f2'        : DOM.renameCurrent,
                            'f3'        : CloudCmd.View.show,
                            'f4'        : CloudCmd.Edit.show,
                            'f5'        : operation('copy'),
                            'f6'        : operation('move'),
                            'f7'        : DOM.promptNewDir,
                            'f8'        : operation('delete'),
                            'f9'        : CloudCmd.Menu.show,
                            'f10'       : CloudCmd.Config.show,
                            '~'         : CloudCmd.Konsole.show,
                            'contact'   : CloudCmd.Contact.show,
                        },

                        func    = clickFuncs[id];

                    if (func)
                        func();
                });
        };

        this.setOnPanel             = function(side) {
            var panel,
                filesElement,
                pathElement;

            if (typeof side === 'string')
                panel       = DOM.getByDataName('js-' + side);
            else
                panel       = side;

            filesElement    = DOM.getByDataName('js-files', panel);
            pathElement     = DOM.getByDataName('js-path', panel);

            /* ставим загрузку гифа на клик*/
            Events.addClick(pathElement, getPathListener(panel));
            Events.add(filesElement, EventsFiles);
        };

        function getPathListener(panel) {
            var fn = onPathElementClick.bind(null, panel);

            return fn;
        }

        function onPathElementClick(panel, event) {
            var link, href, url,
                namePanel,
                nameInfoPanel,
                infoPanel   = Info.panel,
                noCurrent   = false,
                element     = event.target,
                attr        = element.getAttribute('data-name');

            switch (attr) {
            case 'js-clear-storage':
                Storage.clear();
                break;

            case 'js-refresh':
                namePanel           = panel.getAttribute('data-name');

                if (infoPanel)
                    nameInfoPanel   = infoPanel.getAttribute('data-name');

                if (namePanel !== nameInfoPanel)
                    noCurrent = true;

                CloudCmd.refresh(panel, {
                    noCurrent: noCurrent
                });

                event.preventDefault();
                break;

            case 'js-path-link':
                url         = CloudCmd.HOST;
                href        = element.href;
                link        = href.replace(url, '');
                /**
                 * browser doesn't replace % -> %25%
                 * do it for him
                 */
                link        = link.replace('%%', '%25%');
                link        = decodeURI(link);
                link        = link.replace(CloudFunc.FS, '') || '/';

                CloudCmd.loadDir({
                    path        : link,
                    isRefresh   : false
                });

                event.preventDefault();
            }
        }

        function execIfNotUL(callback, event) {
            var element = event.target,
                tag     = element.tagName;

            if (tag !== 'UL')
                callback(event);
        }

        function onClick(event) {
            var ctrl    = event.ctrlKey;

            if (!ctrl)
                event.preventDefault();

            changePanel(event.target);
        }

        function changePanel(element) {
            var panel   = Info.panel,
                files   = DOM.getByDataName('js-files', panel),
                ul      = getULElement(element);

            if (ul !== files)
                DOM.changePanel();
        }

        function onDblClick(event) {
            var current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current),
                path        = DOM.getCurrentPath(current);

            if (isDir) {
                CloudCmd.loadDir({
                    path: path
                });

                event.preventDefault();
            }
        }

        function onTouch(event) {
            var isCurrent,
                current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current);

            if (isDir) {
                isCurrent   = DOM.isCurrentFile(current);

                if (isCurrent) {
                    CloudCmd.loadDir({
                        path: DOM.getCurrentPath(current)
                    });

                    event.preventDefault();
                }
            }
        }

         /*
          * download file from browser to desktop
          * in Chrome (HTML5)
          */
        function onDragStart(event) {
            var apiURL      = CloudFunc.apiURL,
                element     = getLIElement(event.target),
                EXT         = '.tar.gz',
                isDir       = Info.isDir,
                link        = DOM.getCurrentLink(element),
                name        = DOM.getCurrentName(element);

            /* if it's directory - adding json extension */
            if (isDir) {
                name            += EXT;
                link            = document.createElement('a');
                link.textContent   = name;
                link.href          = apiURL + '/pack' + Info.path + EXT;
            }

            event.dataTransfer.setData('DownloadURL',
                'application/octet-stream'  + ':' +
                name                        + ':' +
                link);
        }

        function getLIElement(element) {
            if (element)
                while (element.tagName !== 'LI')
                    element = element.parentElement;

            return element;
        }

        function getULElement(element) {
            while (element.tagName !== 'UL')
                element     = element.parentElement;

            return element;
        }

        function setCurrentFileByEvent(event) {
            var element = getLIElement(event.target);
            DOM.setCurrentFile(element);
        }

        function contextMenu() {
            Events.addOnce('contextmenu', DOM.getFM(), function(event) {
                CloudCmd.Menu.show({
                    x: event.clientX,
                    y: event.clientY
                });
            });

            Events.addContextMenu(document, function(event) {
                CloudCmd.Menu.ENABLED || event.preventDefault();
            });
        }

        function dragndrop() {
            var panels          = DOM.getByClassAll('panel'),
                forEach         = Array.prototype.forEach,

                select          = function() {
                    forEach.call(panels, function(panel) {
                        panel.classList.add('selected-panel');
                    });
                },

                unselect        = function() {
                    forEach.call(panels, function(panel) {
                        panel.classList.remove('selected-panel');
                    });
                },
                onDrop          = function(event) {
                    var files   = event.dataTransfer.files,
                        items   = event.dataTransfer.items;

                    event.preventDefault();

                    if (items && items[0].webkitGetAsEntry)
                        DOM.uploadDirectory(items);
                    else
                        DOM.uploadFiles(files);
                },
                /**
                 * In Mac OS Chrome dropEffect = 'none'
                 * so drop do not firing up when try
                 * to upload file from download bar
                 */
                onDragOver      = function(event) {
                    var dataTransfer    = event.dataTransfer,
                        effectAllowed   = dataTransfer.effectAllowed;

                    if (/move|linkMove/.test(effectAllowed))
                        dataTransfer.dropEffect = 'move';
                    else
                        dataTransfer.dropEffect = 'copy';

                    event.preventDefault();
                };

            Events.add('dragenter', select);
            Events.add(['dragleave', 'drop'], unselect);

            forEach.call(panels, function(panel) {
                Events.add('dragover', panel, onDragOver)
                      .add('drop', panel, onDrop);
            });
        }

        function unload() {
            DOM.Events.add(['unload', 'beforeunload'], function (event) {
                var ret,
                    Key     = CloudCmd.Key,
                    isBind  = Key && Key.isBind();

                if (!isBind) {
                    event.preventDefault();
                    ret = 'Please make sure that you saved all work.';
                }

                return ret;
            });
        }

        function pop() {
            Events.add('popstate', function(event) {
                var path    = event.state || '';

                path        = path.replace(CloudFunc.FS, '');

                if (!path)
                    CloudCmd.route(location.hash);
                else
                    CloudCmd.loadDir({
                        path        : path,
                        history     : false
                    });
            });
        }

        function resize() {
            Events.add('resize', function() {
                var name, isLeft,
                    is      = window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH,
                    panel   = Info.panel;

                if (panel) {
                    name    = panel.getAttribute('data-name'),
                    isLeft  = name === 'js-left';
                }

                if (is && !isLeft)
                    DOM.changePanel();
            });
        }

     }

})(Util, DOM, CloudFunc, CloudCmd);
<commit_msg>fix(listeners) onDblClick: add "/"<commit_after>var Util, DOM, CloudFunc, CloudCmd;

(function (Util, DOM, CloudFunc, CloudCmd) {
    'use strict';

     CloudCmd.Listeners = new ListenersProto(Util, DOM, CloudFunc, CloudCmd);

     function ListenersProto(Util, DOM, CloudFunc, CloudCmd) {
        var Info                = DOM.CurrentInfo,
            Storage             = DOM.Storage,
            Events              = DOM.Events,
            EventsFiles         = {
                'mousedown' : Util.exec.with(execIfNotUL, setCurrentFileByEvent),
                'click'     : onClick,
                'dragstart' : Util.exec.with(execIfNotUL, onDragStart),
                'dblclick'  : Util.exec.with(execIfNotUL, onDblClick),
                'touchstart': Util.exec.with(execIfNotUL, onTouch)
            };

        this.init = function () {
            contextMenu();
            dragndrop();
            unload();
            pop();
            resize();
        };

        this.initKeysPanel          = function() {
            var keysElement     = DOM.getById('js-keyspanel');

            if (keysElement)
                Events.addClick(keysElement, function(event) {
                    var element = event.target,
                        id              = element.id,
                        operation       = function(name) {
                            var Operation = CloudCmd.Operation,
                                fn = Operation.show.bind(null, name);

                            return fn;
                        },

                        clickFuncs      = {
                            'f1'        : CloudCmd.Help.show,
                            'f2'        : DOM.renameCurrent,
                            'f3'        : CloudCmd.View.show,
                            'f4'        : CloudCmd.Edit.show,
                            'f5'        : operation('copy'),
                            'f6'        : operation('move'),
                            'f7'        : DOM.promptNewDir,
                            'f8'        : operation('delete'),
                            'f9'        : CloudCmd.Menu.show,
                            'f10'       : CloudCmd.Config.show,
                            '~'         : CloudCmd.Konsole.show,
                            'contact'   : CloudCmd.Contact.show,
                        },

                        func    = clickFuncs[id];

                    if (func)
                        func();
                });
        };

        this.setOnPanel             = function(side) {
            var panel,
                filesElement,
                pathElement;

            if (typeof side === 'string')
                panel       = DOM.getByDataName('js-' + side);
            else
                panel       = side;

            filesElement    = DOM.getByDataName('js-files', panel);
            pathElement     = DOM.getByDataName('js-path', panel);

            /* ставим загрузку гифа на клик*/
            Events.addClick(pathElement, getPathListener(panel));
            Events.add(filesElement, EventsFiles);
        };

        function getPathListener(panel) {
            var fn = onPathElementClick.bind(null, panel);

            return fn;
        }

        function onPathElementClick(panel, event) {
            var link, href, url,
                namePanel,
                nameInfoPanel,
                infoPanel   = Info.panel,
                noCurrent   = false,
                element     = event.target,
                attr        = element.getAttribute('data-name');

            switch (attr) {
            case 'js-clear-storage':
                Storage.clear();
                break;

            case 'js-refresh':
                namePanel           = panel.getAttribute('data-name');

                if (infoPanel)
                    nameInfoPanel   = infoPanel.getAttribute('data-name');

                if (namePanel !== nameInfoPanel)
                    noCurrent = true;

                CloudCmd.refresh(panel, {
                    noCurrent: noCurrent
                });

                event.preventDefault();
                break;

            case 'js-path-link':
                url         = CloudCmd.HOST;
                href        = element.href;
                link        = href.replace(url, '');
                /**
                 * browser doesn't replace % -> %25%
                 * do it for him
                 */
                link        = link.replace('%%', '%25%');
                link        = decodeURI(link);
                link        = link.replace(CloudFunc.FS, '') || '/';

                CloudCmd.loadDir({
                    path        : link,
                    isRefresh   : false
                });

                event.preventDefault();
            }
        }

        function execIfNotUL(callback, event) {
            var element = event.target,
                tag     = element.tagName;

            if (tag !== 'UL')
                callback(event);
        }

        function onClick(event) {
            var ctrl    = event.ctrlKey;

            if (!ctrl)
                event.preventDefault();

            changePanel(event.target);
        }

        function changePanel(element) {
            var panel   = Info.panel,
                files   = DOM.getByDataName('js-files', panel),
                ul      = getULElement(element);

            if (ul !== files)
                DOM.changePanel();
        }

        function onDblClick(event) {
            var current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current),
                path        = DOM.getCurrentPath(current);

            if (isDir) {
                CloudCmd.loadDir({
                    path: path + '/'
                });

                event.preventDefault();
            }
        }

        function onTouch(event) {
            var isCurrent,
                current     = getLIElement(event.target),
                isDir       = DOM.isCurrentIsDir(current);

            if (isDir) {
                isCurrent   = DOM.isCurrentFile(current);

                if (isCurrent) {
                    CloudCmd.loadDir({
                        path: DOM.getCurrentPath(current)
                    });

                    event.preventDefault();
                }
            }
        }

         /*
          * download file from browser to desktop
          * in Chrome (HTML5)
          */
        function onDragStart(event) {
            var apiURL      = CloudFunc.apiURL,
                element     = getLIElement(event.target),
                EXT         = '.tar.gz',
                isDir       = Info.isDir,
                link        = DOM.getCurrentLink(element),
                name        = DOM.getCurrentName(element);

            /* if it's directory - adding json extension */
            if (isDir) {
                name            += EXT;
                link            = document.createElement('a');
                link.textContent   = name;
                link.href          = apiURL + '/pack' + Info.path + EXT;
            }

            event.dataTransfer.setData('DownloadURL',
                'application/octet-stream'  + ':' +
                name                        + ':' +
                link);
        }

        function getLIElement(element) {
            if (element)
                while (element.tagName !== 'LI')
                    element = element.parentElement;

            return element;
        }

        function getULElement(element) {
            while (element.tagName !== 'UL')
                element     = element.parentElement;

            return element;
        }

        function setCurrentFileByEvent(event) {
            var element = getLIElement(event.target);
            DOM.setCurrentFile(element);
        }

        function contextMenu() {
            Events.addOnce('contextmenu', DOM.getFM(), function(event) {
                CloudCmd.Menu.show({
                    x: event.clientX,
                    y: event.clientY
                });
            });

            Events.addContextMenu(document, function(event) {
                CloudCmd.Menu.ENABLED || event.preventDefault();
            });
        }

        function dragndrop() {
            var panels          = DOM.getByClassAll('panel'),
                forEach         = Array.prototype.forEach,

                select          = function() {
                    forEach.call(panels, function(panel) {
                        panel.classList.add('selected-panel');
                    });
                },

                unselect        = function() {
                    forEach.call(panels, function(panel) {
                        panel.classList.remove('selected-panel');
                    });
                },
                onDrop          = function(event) {
                    var files   = event.dataTransfer.files,
                        items   = event.dataTransfer.items;

                    event.preventDefault();

                    if (items && items[0].webkitGetAsEntry)
                        DOM.uploadDirectory(items);
                    else
                        DOM.uploadFiles(files);
                },
                /**
                 * In Mac OS Chrome dropEffect = 'none'
                 * so drop do not firing up when try
                 * to upload file from download bar
                 */
                onDragOver      = function(event) {
                    var dataTransfer    = event.dataTransfer,
                        effectAllowed   = dataTransfer.effectAllowed;

                    if (/move|linkMove/.test(effectAllowed))
                        dataTransfer.dropEffect = 'move';
                    else
                        dataTransfer.dropEffect = 'copy';

                    event.preventDefault();
                };

            Events.add('dragenter', select);
            Events.add(['dragleave', 'drop'], unselect);

            forEach.call(panels, function(panel) {
                Events.add('dragover', panel, onDragOver)
                      .add('drop', panel, onDrop);
            });
        }

        function unload() {
            DOM.Events.add(['unload', 'beforeunload'], function (event) {
                var ret,
                    Key     = CloudCmd.Key,
                    isBind  = Key && Key.isBind();

                if (!isBind) {
                    event.preventDefault();
                    ret = 'Please make sure that you saved all work.';
                }

                return ret;
            });
        }

        function pop() {
            Events.add('popstate', function(event) {
                var path    = event.state || '';

                path        = path.replace(CloudFunc.FS, '');

                if (!path)
                    CloudCmd.route(location.hash);
                else
                    CloudCmd.loadDir({
                        path        : path,
                        history     : false
                    });
            });
        }

        function resize() {
            Events.add('resize', function() {
                var name, isLeft,
                    is      = window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH,
                    panel   = Info.panel;

                if (panel) {
                    name    = panel.getAttribute('data-name'),
                    isLeft  = name === 'js-left';
                }

                if (is && !isLeft)
                    DOM.changePanel();
            });
        }

     }

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