<commit_before>var uploader = null;
var browserName=navigator.appName;

(function($) {

    $.filePicker = {
        conf: {
            url: '',
            urls: ''
        }
    };

    // constructor
    function FilePicker(root, conf) {

        // current instance
        var self = this,
            tabs = null,
            browse_pane = null,
            upload_pane = null;
        root.data('overlay').onLoad(function (){
            this.getOverlay().data('filePicker').load();
            $(document).find('.file-picker-overlay').css('z-index', '1');
            $('img').css('z-index', '0');
        });
        root.data('overlay').onClose(function (){
            upload_pane.empty();
            browse_pane.empty();
            $(document).find('.plupload').remove();
        });
        root.append($('<div>').addClass('file-picker'));
        root = root.find('.file-picker');

        // methods
        $.extend(self, {

            getConf: function() {
                return conf;
            },

            getRoot: function() {
                return root;
            },

            load: function() {
                tabs.tabs('div.panes > div.pane', {effect: 'fade', fadeOutSpeed: 400});
                tabs.tabs().onClick(function(e, index) {
                    self.tabClick(e, index);
                });
                $.get(conf.url, function(response) {
                    conf.urls = response.urls;
                    self.getFiles();
                    self.getForm();
                });
            },

            tabClick: function(e, index) {
                $(document).find('.plupload').remove();
                if (index == 1) {
                    self.getForm();
                }else if (index == 0){
                    self.getFiles();
                }
            },

            getForm: function(data){
                if (!data) {
                    $.get(conf.urls.upload.file, {}, function(response){
                        self.displayForm(response);
                        self.setupUpload();
                    });
                } else {
                    $.post(conf.urls.upload.file, data, function(response){
                        if (response['insert']) {
                            $(self).trigger("onImageClick", [response.insert]);
                            self.getForm();
                        }else{
                            self.displayForm(response);
                            self.setupUpload();
                            var upload_form = upload_pane.find('.upload_form');
                            submit = $('<input>').
                                attr({'type': 'submit', 'value': 'Submit'}).
                                click( function(e) {
                                    e.preventDefault();
                                    var upload_form = upload_pane.find('.upload_form');
                                    data = {};
                                    $(':input', upload_form).each(function() {
                                        data[this.name]=this.value;
                                    });
                                    self.getForm(data);
                                })
                            upload_form.append(submit);
                        }
                    });
                }
            },

            displayForm: function(data){
                var pane = root.find('.file-picker-upload');
                pane.empty();
                pane.append($('<h2>').text('Select file to upload'));
                var browse = $('<input>').val('Select a file').attr({
                    'type': 'button',
                    'id': 'select-a-file'
                }).addClass('select-a-file');
                pane.append(browse);
                var runtime = $('<div>').addClass('runtime');
                pane.append(runtime);
                pane.append($('<ul>').addClass('upload-list'));
                pane.append($('<h3>').text('File details'));
                var form = $('<form>').attr({
                    'method': 'post', 'class': 'upload_form', 'action':''
                });
                var table = $('<table>').html(data.form)
                form.append(table);
                pane.append(form);
            },

            getFiles: function(data) {
                if (!data) {
                    data = {};
                }
                $.get(conf.urls.browse.files, data, function(response) {
                    self.displayFiles(response);
                });
            },

            setupUpload: function() {
                uploader = new plupload.Uploader({
                    runtimes : 'html5,flash',
                    browse_button : 'select-a-file',
                    max_file_size : '20mb',
                    url : conf.urls.upload.file,
                    flash_swf_url : '/media/plupload.flash.swf'
                });

                uploader.bind('Init', function(up, params) {
                    upload_pane.find('.runtime').html('Upload runtime: ' + params.runtime);
                });

                uploader.bind('PostInit', function(up) {
                    if (browserName != "Microsoft Internet Explorer") {
                        $(document).find('div.plupload').css({'position': 'fixed'});
                    }
                });

                uploader.bind('FilesAdded', function(up, files) {
                    var list = upload_pane.find('.upload-list');
                    list.empty();
                    $.each(files, function(i, file) {
                        var li = $('<li>').attr({'id': file.id});
                        li.append($('<span>').text(file.name + ' (' + plupload.formatSize(file.size) + ') '));
                        li.append('<b>');
                        list.append(li);
                        up.removeFile(file);
                        upload_pane.find('.add_to_model').remove();
                    });
                });

                uploader.bind('QueueChanged', function(up) {
                    if ( up.files.length > 0 && uploader.state != 2) {
                        uploader.start();
                    }
                });

                uploader.bind('UploadProgress', function(up, file) {
                    $('#' + file.id + " b").html(file.percent + "%");
                });

                uploader.bind('FileUploaded', function(uploader, file, response){
                    submit = $('<input>').attr(
                            {'class': 'add_to_model', 'type': 'submit', 'value': 'Submit'}
                        ).
                        click( function(e) {
                            e.preventDefault();
                            var upload_form = upload_pane.find('.upload_form');
                            var data = {};
                            $(':input', upload_form).each(function() {
                                data[this.name]=this.value;
                            });
                            data['file'] = response['response'];
                            self.getForm(data);
                        })
                        var upload_form = upload_pane.find('.upload_form');
                        upload_form.append(submit);
                });
                uploader.init();
            },

            displayFiles: function(data) {
                var files = data.result;
                browse_pane.empty();
                browse_pane.append($('<h2>').text('Select file to insert'));
                var table = $('<table>').addClass('file-list');
                var tr = $('<tr>');
                var form = $('<form>').attr({
                     'action': "",
                     'method': 'get',
                     'class': 'file-picker-search'
                });
                form.append(
                    $('<input>').attr({ 'type': 'text',
                    'class':'search_val','name':'search'}).val(data.search)
                );
                form.append(
                    $('<input>').attr({ 'type': 'submit', 'value':'Search'})
                    .addClass('search_val').click(
                    function(e) {
                        e.preventDefault();
                        self.getFiles(
                        {'search': browse_pane.find('.search_val').val() }
                        );
                    })
                );
                var tr = $('<tr>');
                tr.append($('<th>').text(data.link_header));
                $.each(files[0].extra, function(key, value){
                    tr.append($('<th>').text(key));
                });
                table.append(tr);
                $.each(files, function(idx, file) {
                    var tr = $('<tr>');
                    var a = $('<a>').click(function(e) {
                        $(self).trigger("onImageClick", [file.insert]);
                    });
                    a.append(file.link_content);
                    tr.append($('<td>').append(a));
                    $.each(file.extra, function(key,value){
                        tr.append($('<td>').text(value));
                    });
                    table.append(tr);
                });
                var div = $('<div>').attr({'class': 'scrollable'});
                browse_pane.append(form);
                browse_pane.append(div.append(table));
                var footer = $('<div>').attr('class', 'footer');
                var next = $('<a>').attr({
                        'title': 'Next',
                        'href': '#'
                    }).text('Next')
                if (data.has_next) {
                    next.click(function(e) {
                        e.preventDefault();
                        self.getFiles({'page': data.page + 1,
                        'search': browse_pane.find('.search_val').val()});
                    });
                } else {
                    next.css('color', '#bbb');
                }
                var previous = $('<a>').attr({
                        'title': 'Next',
                        'href': '#'
                    }).text('Previous ')
                if (data.has_previous) {
                    previous.click(function(e) {
                        e.preventDefault();
                        self.getFiles({'page': data.page - 1,
                        'search': browse_pane.find('.search_val').val()});
                    });
                } else {
                    previous.css('color', '#bbb');
                }
                footer.append(previous);
                $.each(data.pages, function(index, value){
                        var list = $('<a>').attr({
                            'title': value,
                            'href': '#'
                        }).text(value+' ')
                        if (data.page==value) {
                            list.css('color', '#bbb');
                        } else {
                            list.click(function(e) {
                                e.preventDefault();
                                self.getFiles({'page': value,
                                'search': browse_pane.find('.search_val').val()});
                            });
                        }
                        footer.append(list);
                });
                footer.append(next);
                browse_pane.append(footer);
            }
        });

        // callbacks
        $.each(['onImageClick'], function(i, name) {
            // configuration
            if ($.isFunction(conf[name])) {
                $(self).bind(name, conf[name]);
            }
            self[name] = function(fn) {
                $(self).bind(name, fn);
                return self;
            };
        });

        // setup tabs
        var tabs = $('<ul>').addClass('css-tabs').addClass('file-picker-tabs');
        tabs.append($('<li>').append($('<a>').attr('href', '#').text('Browse')));
        tabs.append($('<li>').append($('<a>').attr('href', '#').text('Upload')));
        var panes = $('<div>').addClass('panes');
        browse_pane = $('<div>').addClass('file-picker-browse').addClass('pane');
        browse_pane.append($('<h2>').text('Browse for a file'));
        panes.append(browse_pane);
        upload_pane = $('<div>').addClass('file-picker-upload').addClass('pane')
        panes.append(upload_pane);
        root.append(tabs);
        root.append(panes);
    }

    // jQuery plugin implementation
    $.fn.filePicker = function(conf) {
        // already constructed --> return API
        var el = this.data("filePicker");
        if (el) { return el; }

        conf = $.extend({}, $.filePicker.conf, conf);

        this.each(function() {
            el = new FilePicker($(this), conf);
            $(this).data("filePicker", el);
        });

        return conf.api ? el: this;
    };

})(jQuery);

function insertAtCaret(areaId,text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") { txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos = range.text.length;
    } else if (br == "ff") strPos = txtarea.selectionStart;
    var front = (txtarea.value).substring(0,strPos);
    var back = (txtarea.value).substring(strPos,txtarea.value.length);
    txtarea.value=front+text+back;
    strPos = strPos + text.length;
    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    } else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}
<commit_msg>catch errors in JS<commit_after>var uploader = null;
var browserName=navigator.appName;

(function($) {

    $.filePicker = {
        conf: {
            url: '',
            urls: ''
        }
    };

    // constructor
    function FilePicker(root, conf) {

        // current instance
        var self = this,
            tabs = null,
            browse_pane = null,
            upload_pane = null;
        root.data('overlay').onLoad(function (){
            this.getOverlay().data('filePicker').load();
            $(document).find('.file-picker-overlay').css('z-index', '1');
            $('img').css('z-index', '0');
        });
        root.data('overlay').onClose(function (){
            upload_pane.empty();
            browse_pane.empty();
            $(document).find('.plupload').remove();
        });
        root.append($('<div>').addClass('file-picker'));
        root = root.find('.file-picker');

        // methods
        $.extend(self, {

            getConf: function() {
                return conf;
            },

            getRoot: function() {
                return root;
            },

            load: function() {
                tabs.tabs('div.panes > div.pane', {effect: 'fade', fadeOutSpeed: 400});
                tabs.tabs().onClick(function(e, index) {
                    self.tabClick(e, index);
                });
                $.get(conf.url, function(response) {
                    conf.urls = response.urls;
                    self.getFiles();
                    self.getForm();
                });
            },

            tabClick: function(e, index) {
                $(document).find('.plupload').remove();
                if (index == 1) {
                    self.getForm();
                }else if (index == 0){
                    self.getFiles();
                }
            },

            getForm: function(data){
                if (!data) {
                    $.get(conf.urls.upload.file, {}, function(response){
                        self.displayForm(response);
                        self.setupUpload();
                    });
                } else {
                    $.post(conf.urls.upload.file, data, function(response) {
                        if (response.errors) {
                            $.each(response.errors, function(idx) {
                                console.error(this);
                            });
                            return;
                        }
                        if (response['insert']) {
                            $(self).trigger("onImageClick", [response.insert]);
                            self.getForm();
                        } else {
                            self.displayForm(response);
                            self.setupUpload();
                            var upload_form = upload_pane.find('.upload_form');
                            submit = $('<input>').
                                attr({'type': 'submit', 'value': 'Submit'}).
                                click( function(e) {
                                    e.preventDefault();
                                    var upload_form = upload_pane.find('.upload_form');
                                    data = {};
                                    $(':input', upload_form).each(function() {
                                        data[this.name]=this.value;
                                    });
                                    self.getForm(data);
                                })
                            upload_form.append(submit);
                        }
                    });
                }
            },

            displayForm: function(data){
                var pane = root.find('.file-picker-upload');
                pane.empty();
                pane.append($('<h2>').text('Select file to upload'));
                var browse = $('<input>').val('Select a file').attr({
                    'type': 'button',
                    'id': 'select-a-file'
                }).addClass('select-a-file');
                pane.append(browse);
                var runtime = $('<div>').addClass('runtime');
                pane.append(runtime);
                pane.append($('<ul>').addClass('upload-list'));
                pane.append($('<h3>').text('File details'));
                var form = $('<form>').attr({
                    'method': 'post', 'class': 'upload_form', 'action':''
                });
                var table = $('<table>').html(data.form)
                form.append(table);
                pane.append(form);
            },

            getFiles: function(data) {
                if (!data) {
                    data = {};
                }
                $.get(conf.urls.browse.files, data, function(response) {
                    self.displayFiles(response);
                });
            },

            setupUpload: function() {
                uploader = new plupload.Uploader({
                    runtimes : 'html5,flash',
                    browse_button : 'select-a-file',
                    max_file_size : '20mb',
                    url : conf.urls.upload.file,
                    flash_swf_url : '/media/plupload.flash.swf'
                });

                uploader.bind('Init', function(up, params) {
                    upload_pane.find('.runtime').html('Upload runtime: ' + params.runtime);
                });

                uploader.bind('PostInit', function(up) {
                    if (browserName != "Microsoft Internet Explorer") {
                        $(document).find('div.plupload').css({'position': 'fixed'});
                    }
                });

                uploader.bind('FilesAdded', function(up, files) {
                    var list = upload_pane.find('.upload-list');
                    list.empty();
                    $.each(files, function(i, file) {
                        var li = $('<li>').attr({'id': file.id});
                        li.append($('<span>').text(file.name + ' (' + plupload.formatSize(file.size) + ') '));
                        li.append('<b>');
                        list.append(li);
                        up.removeFile(file);
                        upload_pane.find('.add_to_model').remove();
                    });
                });

                uploader.bind('QueueChanged', function(up) {
                    if ( up.files.length > 0 && uploader.state != 2) {
                        uploader.start();
                    }
                });

                uploader.bind('UploadProgress', function(up, file) {
                    $('#' + file.id + " b").html(file.percent + "%");
                });

                uploader.bind('FileUploaded', function(uploader, file, response){
                    submit = $('<input>').attr(
                            {'class': 'add_to_model', 'type': 'submit', 'value': 'Submit'}
                        ).
                        click( function(e) {
                            e.preventDefault();
                            var upload_form = upload_pane.find('.upload_form');
                            var data = {};
                            $(':input', upload_form).each(function() {
                                data[this.name]=this.value;
                            });
                            data['file'] = response['response'];
                            self.getForm(data);
                        })
                        var upload_form = upload_pane.find('.upload_form');
                        upload_form.append(submit);
                });
                uploader.init();
            },

            displayFiles: function(data) {
                var files = data.result;
                browse_pane.empty();
                browse_pane.append($('<h2>').text('Select file to insert'));
                var table = $('<table>').addClass('file-list');
                var tr = $('<tr>');
                var form = $('<form>').attr({
                     'action': "",
                     'method': 'get',
                     'class': 'file-picker-search'
                });
                form.append(
                    $('<input>').attr({ 'type': 'text',
                    'class':'search_val','name':'search'}).val(data.search)
                );
                form.append(
                    $('<input>').attr({ 'type': 'submit', 'value':'Search'})
                    .addClass('search_val').click(
                    function(e) {
                        e.preventDefault();
                        self.getFiles(
                        {'search': browse_pane.find('.search_val').val() }
                        );
                    })
                );
                var tr = $('<tr>');
                tr.append($('<th>').text(data.link_header));
                $.each(files[0].extra, function(key, value){
                    tr.append($('<th>').text(key));
                });
                table.append(tr);
                $.each(files, function(idx, file) {
                    var tr = $('<tr>');
                    var a = $('<a>').click(function(e) {
                        $(self).trigger("onImageClick", [file.insert]);
                    });
                    a.append(file.link_content);
                    tr.append($('<td>').append(a));
                    $.each(file.extra, function(key,value){
                        tr.append($('<td>').text(value));
                    });
                    table.append(tr);
                });
                var div = $('<div>').attr({'class': 'scrollable'});
                browse_pane.append(form);
                browse_pane.append(div.append(table));
                var footer = $('<div>').attr('class', 'footer');
                var next = $('<a>').attr({
                        'title': 'Next',
                        'href': '#'
                    }).text('Next')
                if (data.has_next) {
                    next.click(function(e) {
                        e.preventDefault();
                        self.getFiles({'page': data.page + 1,
                        'search': browse_pane.find('.search_val').val()});
                    });
                } else {
                    next.css('color', '#bbb');
                }
                var previous = $('<a>').attr({
                        'title': 'Next',
                        'href': '#'
                    }).text('Previous ')
                if (data.has_previous) {
                    previous.click(function(e) {
                        e.preventDefault();
                        self.getFiles({'page': data.page - 1,
                        'search': browse_pane.find('.search_val').val()});
                    });
                } else {
                    previous.css('color', '#bbb');
                }
                footer.append(previous);
                $.each(data.pages, function(index, value){
                        var list = $('<a>').attr({
                            'title': value,
                            'href': '#'
                        }).text(value+' ')
                        if (data.page==value) {
                            list.css('color', '#bbb');
                        } else {
                            list.click(function(e) {
                                e.preventDefault();
                                self.getFiles({'page': value,
                                'search': browse_pane.find('.search_val').val()});
                            });
                        }
                        footer.append(list);
                });
                footer.append(next);
                browse_pane.append(footer);
            }
        });

        // callbacks
        $.each(['onImageClick'], function(i, name) {
            // configuration
            if ($.isFunction(conf[name])) {
                $(self).bind(name, conf[name]);
            }
            self[name] = function(fn) {
                $(self).bind(name, fn);
                return self;
            };
        });

        // setup tabs
        var tabs = $('<ul>').addClass('css-tabs').addClass('file-picker-tabs');
        tabs.append($('<li>').append($('<a>').attr('href', '#').text('Browse')));
        tabs.append($('<li>').append($('<a>').attr('href', '#').text('Upload')));
        var panes = $('<div>').addClass('panes');
        browse_pane = $('<div>').addClass('file-picker-browse').addClass('pane');
        browse_pane.append($('<h2>').text('Browse for a file'));
        panes.append(browse_pane);
        upload_pane = $('<div>').addClass('file-picker-upload').addClass('pane')
        panes.append(upload_pane);
        root.append(tabs);
        root.append(panes);
    }

    // jQuery plugin implementation
    $.fn.filePicker = function(conf) {
        // already constructed --> return API
        var el = this.data("filePicker");
        if (el) { return el; }

        conf = $.extend({}, $.filePicker.conf, conf);

        this.each(function() {
            el = new FilePicker($(this), conf);
            $(this).data("filePicker", el);
        });

        return conf.api ? el: this;
    };

})(jQuery);

function insertAtCaret(areaId,text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") { txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos = range.text.length;
    } else if (br == "ff") strPos = txtarea.selectionStart;
    var front = (txtarea.value).substring(0,strPos);
    var back = (txtarea.value).substring(strPos,txtarea.value.length);
    txtarea.value=front+text+back;
    strPos = strPos + text.length;
    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    } else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}
<|endoftext|>


<commit_before>
var gatherer = require('../lib/gatherer')
var db = require('mongo-promise')
var _ = require('lodash')
var rsvp = require('rsvp')

module.exports = {

  warmMany: function(arr) {
    var obj = arr[0]
    if (!obj) return
    this.warm(obj).then(setTimeout(this.warmMany.bind(this, arr.slice(1)), 2000))
  },

  warm: function(obj) {
    return new rsvp.Promise(function(res, rej) {
      if (!obj.refs.length) return res()

      gatherer.gather({
        refs: obj.refs,
        adapters: this.adapters
      }).then(function(data) {
        data._entityId = obj._id.toString()
        db[this.collection].findAndModify({ _entityId: obj._id }, null, data, { upsert: true, 'new':true }).then(function(doc) {
          res(doc)
        })
      }.bind(this))
    }.bind(this))
  },

  isOutdated: function(obj) {
    if (!obj._meta || !obj._meta.fields) return true

    var now = Date.now() / 1000
    var expiries = _.pluck(obj._meta.fields, 'expires')
    return _.any(expiries, function(exp) { return exp < now })
  },

  search: function(params) {

    var fields = params.fields
    var query = this.buildQuery(params.q || {})
    var opts = { skip: parseInt(params.skip || 0), limit: parseInt(params.limit || 500) }

    return db[this.collection].find(query, fields, opts).then(function(results) {
      _.filter(results, this.isOutdated).forEach(this.warm.bind(this))
      return results
    }.bind(this))
  },

  validateRefs: function(refs) {
    return refs.map(function(ref) {
      if (!this.adapters[ref.adapter].canUse(ref.id)) {
        ref.status = 'broken'
      }
      return ref
    }, this)
  }

}
<commit_msg>with promise redo<commit_after>
var gatherer = require('../lib/gatherer')
var db = require('mongo-promise')
var _ = require('lodash')
var rsvp = require('rsvp')

module.exports = {

  warmMany: function(arr) {
    var obj = arr[0]
    if (!obj) return
    this.warm(obj).then(setTimeout(this.warmMany.bind(this, arr.slice(1)), 2000))
  },

  warm: function(obj) {
    if (!obj.refs.length) return new rsvp.Promise(function(res) { res() })

    return gatherer.gather({
      refs: obj.refs,
      adapters: this.adapters
    }).then(function(data) {
      data._entityId = obj._id.toString()
      return db[this.collection].findAndModify({ _entityId: obj._id }, null, data, { upsert: true, 'new':true }).then(function(doc) {
        return doc
      })
    }.bind(this), function() { console.log('ERROR: ', arguments) })
  },

  isOutdated: function(obj) {
    if (!obj._meta || !obj._meta.fields) return true

    var now = Date.now() / 1000
    var expiries = _.pluck(obj._meta.fields, 'expires')
    return _.any(expiries, function(exp) { return exp < now })
  },

  search: function(params) {

    var fields = params.fields
    var query = this.buildQuery(params.q || {})
    var opts = { skip: parseInt(params.skip || 0), limit: parseInt(params.limit || 500) }

    return db[this.collection].find(query, fields, opts).then(function(results) {
      _.filter(results, this.isOutdated).forEach(this.warm.bind(this))
      return results
    }.bind(this))
  },

  validateRefs: function(refs) {
    return refs.map(function(ref) {
      if (!this.adapters[ref.adapter].canUse(ref.id)) {
        ref.status = 'broken'
      }
      return ref
    }, this)
  }

}
<|endoftext|>


<commit_before>import Morph from "./Morph.js"

import { Graph } from 'src/client/triples/triples.js';
import lively from 'src/client/lively.js';

export default class AddTriple extends Morph {
  async initialize() {
    this.windowTitle = "Add Triple";

    let input = this.get("#inputSubject");
    this.selectors.forEach(({ input }) => this.get(input).addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        this.save();
      }
    }));

    let button = this.get('#save');
    button.addEventListener('click', event => this.save());

    this.selectors.forEach(({ list }) => this.prepareDatalist(list));
  }

  /** subject, predicate, object */
  get spo() { return this.selectors; }

  get selectors() {
    return [{
      input: '#inputSubject',
      list: '#subject'
    }, {
      input: '#inputPredicate',
      list: '#predicate'
    }, {
      input: '#inputObject',
      list: '#object'
    }]
  }

  async prepareDatalist(listSelector) {
    let graph = Graph.getInstance();
    await graph.loadFromDir('https://lively4/dropbox/');

    let selection = this.get(listSelector);
    graph.getKnots().forEach(knot => {
      let option = document.createElement('option');

      option.innerHTML = knot.label();
      option.value = knot.url;
      option.dataset.url = knot.url;

      selection.appendChild(option);
    });
  }

  // https://derickbailey.com/2016/03/23/get-a-data-attribute-value-from-the-selected-datalist-option/
  getURLFor(inputSelector, listSelector) {
    let input = this.get(inputSelector);
    let list = this.get(listSelector);

    var value = input.value;
    lively.notify('input value: ' + value);
    // TODO: value could be a literal or a url
    var option = this.get(`${listSelector} [value='${value}']`);
    // value could also be an external url
    if(!option) return;
    lively.notify(option.innerHTML)
    window.myOption = option;
    let id = option.dataset.url;
    lively.notify('url: ' + id);
    return id;
  }

  async save() {
    let graph = Graph.getInstance();

    const subjectURL = this.getURLFor('#inputSubject', '#subject');
    const predicateURL = this.getURLFor('#inputPredicate', '#predicate');
    const objectURL = this.getURLFor('#inputObject', '#object');

    graph.createTriple(
      subjectURL,
      predicateURL,
      objectURL
    );
  }
}
<commit_msg>AUTO-COMMIT templates/add-triple.js<commit_after>import Morph from "./Morph.js"

import { Graph } from 'src/client/triples/triples.js';
import lively from 'src/client/lively.js';

export default class AddTriple extends Morph {
  async initialize() {
    this.windowTitle = "Add Triple";

    let input = this.get("#inputSubject");
    this.selectors.forEach(({ input }) => this.get(input).addEventListener('keyup',  event => {
      if (event.keyCode == 13) { // ENTER
        this.save();
      }
    }));

    let button = this.get('#save');
    button.addEventListener('click', event => this.save());

    this.selectors.forEach(({ list }) => this.prepareDatalist(list));
  }

  /** subject, predicate, object */
  get spo() { return this.selectors; }

  get selectors() {
    return [{
      input: '#inputSubject',
      list: '#subject'
    }, {
      input: '#inputPredicate',
      list: '#predicate'
    }, {
      input: '#inputObject',
      list: '#object'
    }]
  }

  async prepareDatalist(listSelector) {
    let graph = Graph.getInstance();
    await graph.loadFromDir('https://lively4/dropbox/');

    let selection = this.get(listSelector);
    graph.getKnots().forEach(knot => {
      let option = document.createElement('option');

      option.innerHTML = knot.label();
      option.value = knot.url;
      option.dataset.url = knot.url;

      selection.appendChild(option);
    });
  }

  // https://derickbailey.com/2016/03/23/get-a-data-attribute-value-from-the-selected-datalist-option/
  getURLFor(inputSelector, listSelector) {
    let input = this.get(inputSelector);
    let list = this.get(listSelector);

    var value = input.value;
    lively.notify('input value: ' + value);
    // TODO: check for empty value ('')
    // TODO: value could be a literal or a url
    var option = this.get(`${listSelector} [value='${value}']`);
    // value could also be an external url
    if(!option) return;
    lively.notify(option.innerHTML)
    window.myOption = option;
    let id = option.dataset.url;
    lively.notify('url: ' + id);
    return id;
  }

  async save() {
    let graph = Graph.getInstance();

    const subjectURL = this.getURLFor('#inputSubject', '#subject');
    const predicateURL = this.getURLFor('#inputPredicate', '#predicate');
    const objectURL = this.getURLFor('#inputObject', '#object');

    graph.createTriple(
      subjectURL,
      predicateURL,
      objectURL
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

var fs     = require('fs'),
    path   = require('path'),
    util   = require('util'),
    yeoman = require('yeoman-generator'),

    controllerGenerator = require('../controller/index'),
    modelGenerator      = require('../model/index'),
    viewGenerator       = require('../view/index');

var walk = function(dir, done) {
  var results = [];
  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);
    list.forEach(function(file) {
      file = dir + '/' + file;
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function(err, res) {
            results = results.concat(res);
            if (!--pending) done(null, results);
          });
        } else {
          results.push(file);
          if (!--pending) done(null, results);
        }
      });
    });
  });
};

var ChaplinGenerator = module.exports = function ChaplinGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(ChaplinGenerator, yeoman.generators.Base);

ChaplinGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [
    {
      name: 'appName',
      message: 'Application name'
    },
    {
      name: 'controllerSuffix',
      message: 'Controller suffix (leave this blank if you dont want one)'
    }
    /*
    {
      name: 'generateControllers',
      message: 'Generate controllers now? (Y/n)'
    },
    {
      name: 'generateModels',
      message: 'Generate models now? (Y/n)'
    },
    {
      name: 'generateViews',
      message: 'Generate views now? (Y/n)'
    }
    */
  ];

  this.prompt(prompts, function (props) {
    this.appName = props.appName;

    if(typeof props.controllerSuffix == 'string' && props.controllerSuffix.length > 0) {
      this.controllerSuffix = props.controllerSuffix;
    }

    else {
      this.controllerSuffix = '';
    }

    this.generateControllers = ( props.generateControllers && props.generateControllers.toLowerCase() === 'y' );
    this.generateModels      = ( props.generateModels && props.generateModels.toLowerCase() === 'y' );
    this.generateViews       = ( props.generateViews && props.generateViews.toLowerCase() === 'y' );

    cb();

  }.bind(this));
};

ChaplinGenerator.prototype.app = function app() {
  var cb = this.async();

  this.mkdir('app');
  this.mkdir('app/assets');
  this.mkdir('app/assets/fonts');
  this.mkdir('app/assets/img');
  this.mkdir('app/controllers');
  this.mkdir('app/lib');
  this.mkdir('app/models');
  this.mkdir('app/styles');
  this.mkdir('app/templates');
  this.mkdir('app/views');
  this.mkdir('test');

  this.template('_bower.json', 'bower.json');
  this.template('_config.json', 'config.json');
  this.template('_package.json', 'package.json');
  this.copy('Gruntfile.coffee', 'Gruntfile.coffee');
  this.template('app/_initialize.coffee', 'app/initialize.coffee');
  this.copy('app/controllers/_home.coffee', 'app/controllers/home' + this.controllerSuffix + '.coffee')

  var _this = this;

  walk(__dirname + '/templates/app', function(err, files) {
    if (err) throw err;

    files.forEach(function(file) {

      // Ignore .DS_Store files as well as files that start with _.
      if((file.indexOf('.DS_Store') < 1) && (file.indexOf('_') < 1)) {

        file = file.replace(__dirname + '/templates/', '');

        _this.copy(file, file);
      }
    });

    cb();
  }.bind(this));

}

/*
ChaplinGenerator.prototype.generateRequests = function(){
   var cb = this.async(),
      prompts = [];

    if( this.generateControllers ){
      prompts.push({
        name: 'controllerNames',
        message: 'Name your controllers ( Ex: users posts items/comments )'
      });
    }

    if( this.generateModels ){
      prompts.push({
        name: 'modelNames',
        message: 'Name your models ( Ex: user post items/comment )'
      });
    }

    if( this.generateViews ){
      prompts.push({
        name: 'viewNames',
        message: 'Name your views ( Ex: home cart items/comments )'
      });
    }

    // Run callback if there were no prompts added
    if( !prompts.length ){
      cb();
      return;
    }

    this.prompt( prompts, function( props ){
      var fileCount = 1,
        onFinished = function(){
          fileCount--;
          if( !fileCount ){
            cb();
          }
        },
        createFiles = function( name, args, appendStr ) {
          var appendName = appendStr || '';

          if( args && args.length ){
            var arr = args.split(' ');
            fileCount += arr.length;
            for( var cur = 0; cur < arr.length; cur ++){
              this.invoke('chaplin:'+name, { args: [ arr[cur]+ appendName ] }, onFinished );
            }
          }
        }.bind( this );

      createFiles( 'view', props.viewNames );
      createFiles( 'model', props.modelNames );
      createFiles( 'controller', props.controllerNames ); //Append -controller to all controllers

      // Run this first once in case no filenames were passed
      onFinished();

    }.bind(this));

};
*/

ChaplinGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<commit_msg>Fix ignoring wrong files in copying folder structure<commit_after>'use strict';

var fs     = require('fs'),
    path   = require('path'),
    util   = require('util'),
    yeoman = require('yeoman-generator'),

    controllerGenerator = require('../controller/index'),
    modelGenerator      = require('../model/index'),
    viewGenerator       = require('../view/index');

var walk = function(dir, done) {
  var results = [];
  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);
    list.forEach(function(file) {
      file = dir + '/' + file;
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function(err, res) {
            results = results.concat(res);
            if (!--pending) done(null, results);
          });
        } else {
          results.push(file);
          if (!--pending) done(null, results);
        }
      });
    });
  });
};

var ChaplinGenerator = module.exports = function ChaplinGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(ChaplinGenerator, yeoman.generators.Base);

ChaplinGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [
    {
      name: 'appName',
      message: 'Application name'
    },
    {
      name: 'controllerSuffix',
      message: 'Controller suffix (leave this blank if you dont want one)'
    }
    /*
    {
      name: 'generateControllers',
      message: 'Generate controllers now? (Y/n)'
    },
    {
      name: 'generateModels',
      message: 'Generate models now? (Y/n)'
    },
    {
      name: 'generateViews',
      message: 'Generate views now? (Y/n)'
    }
    */
  ];

  this.prompt(prompts, function (props) {
    this.appName = props.appName;

    if(typeof props.controllerSuffix == 'string' && props.controllerSuffix.length > 0) {
      this.controllerSuffix = props.controllerSuffix;
    }

    else {
      this.controllerSuffix = '';
    }

    this.generateControllers = ( props.generateControllers && props.generateControllers.toLowerCase() === 'y' );
    this.generateModels      = ( props.generateModels && props.generateModels.toLowerCase() === 'y' );
    this.generateViews       = ( props.generateViews && props.generateViews.toLowerCase() === 'y' );

    cb();

  }.bind(this));
};

ChaplinGenerator.prototype.app = function app() {
  var cb = this.async();

  this.mkdir('app');
  this.mkdir('app/assets');
  this.mkdir('app/assets/fonts');
  this.mkdir('app/assets/img');
  this.mkdir('app/controllers');
  this.mkdir('app/lib');
  this.mkdir('app/models');
  this.mkdir('app/styles');
  this.mkdir('app/templates');
  this.mkdir('app/views');
  this.mkdir('test');

  this.template('_bower.json', 'bower.json');
  this.template('_config.json', 'config.json');
  this.template('_package.json', 'package.json');
  this.copy('Gruntfile.coffee', 'Gruntfile.coffee');
  this.template('app/_initialize.coffee', 'app/initialize.coffee');
  this.copy('app/controllers/_home.coffee', 'app/controllers/home' + this.controllerSuffix + '.coffee')

  var _this = this;

  walk(__dirname + '/templates/app', function(err, files) {
    if (err) throw err;

    files.forEach(function(file) {

      // Ignore .DS_Store files as well as files that start with _.
      if ( file.indexOf('.DS_Store') === -1 && file.indexOf('_') === -1 ) {

        file = file.replace(__dirname + '/templates/', '');

        _this.copy(file, file);
      }
    });

    cb();
  }.bind(this));

}

/*
ChaplinGenerator.prototype.generateRequests = function(){
   var cb = this.async(),
      prompts = [];

    if( this.generateControllers ){
      prompts.push({
        name: 'controllerNames',
        message: 'Name your controllers ( Ex: users posts items/comments )'
      });
    }

    if( this.generateModels ){
      prompts.push({
        name: 'modelNames',
        message: 'Name your models ( Ex: user post items/comment )'
      });
    }

    if( this.generateViews ){
      prompts.push({
        name: 'viewNames',
        message: 'Name your views ( Ex: home cart items/comments )'
      });
    }

    // Run callback if there were no prompts added
    if( !prompts.length ){
      cb();
      return;
    }

    this.prompt( prompts, function( props ){
      var fileCount = 1,
        onFinished = function(){
          fileCount--;
          if( !fileCount ){
            cb();
          }
        },
        createFiles = function( name, args, appendStr ) {
          var appendName = appendStr || '';

          if( args && args.length ){
            var arr = args.split(' ');
            fileCount += arr.length;
            for( var cur = 0; cur < arr.length; cur ++){
              this.invoke('chaplin:'+name, { args: [ arr[cur]+ appendName ] }, onFinished );
            }
          }
        }.bind( this );

      createFiles( 'view', props.viewNames );
      createFiles( 'model', props.modelNames );
      createFiles( 'controller', props.controllerNames ); //Append -controller to all controllers

      // Run this first once in case no filenames were passed
      onFinished();

    }.bind(this));

};
*/

ChaplinGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>/**
 * @providesModule ZeroProj.Utils.FontUtils
 */

import { Platform } from 'react-native';
import _ from 'lodash';
import Singleton from 'singleton';

const FONT_FAMILY = Platform.select({
  android: 'SanFrancisco',
  ios: 'System',
});

const FONT_ALIGNS = {
  center: 'center',
  left: 'left',
  right: 'right',
};

const FONT_STYLES = {
  italic: 'italic',
  normal: 'normal',
};

// SF font weight: https://gist.github.com/anhari/02f930b6894cc30561c57892e893f540
// Normal & Bold uses default fontWeight configs
const FONT_WEIGHTS = {
  ultralight:         '100',
  light:              '200',
  regular:            '400',
  medium:             '500',
  semibold:           '600',
  normal:             'normal',
  bold:               'bold',
};

class FontUtils extends Singleton {
  aligns = FONT_ALIGNS;
  font = FONT_FAMILY;
  styles = FONT_STYLES;
  weights = FONT_WEIGHTS;

  build({
    align = FONT_ALIGNS.left,
    background = 'transparent',
    color = 'black',
    family = FONT_FAMILY,
    size = 13,
    style = FONT_STYLES.normal,
    weight = FONT_WEIGHTS.regular,
    ...extraProps
  } = {}) {
    const fontFace = Platform.select({
      android: {
        fontFamily: `${family}${_.capitalize(weight)}${_.capitalize(style)}`,
        fontStyle: FONT_STYLES.normal,
        fontWeight: FONT_WEIGHTS.normal,
      },
      ios: {
        fontFamily: family,
        fontStyle: style,
        fontWeight: FONT_WEIGHTS[weight] || FONT_WEIGHTS.normal,
      },
    });

    return {
      color,
      backgroundColor: background,
      fontSize: size,
      textAlign: align,
      ...extraProps,
      ...fontFace,
    };
  }
}

export default FontUtils.get();
<commit_msg>Refine FontUtils<commit_after>/**
 * @providesModule ZeroProj.Utils.FontUtils
 */

import { Platform } from 'react-native';
import Singleton from 'singleton';
import _ from 'lodash';

/**
 * For custom fonts:
 * const FONT_FAMILY = Platform.select({ android: 'SanFrancisco', ios: 'System' })
 */
const FONT_FAMILY = 'System';
const FONT_ALIGNS = { center: 'center', left: 'left', right: 'right' };
const FONT_STYLES = { italic: 'italic', normal: 'normal' };

// SF font weight: https://gist.github.com/anhari/02f930b6894cc30561c57892e893f540
// Normal & Bold uses default fontWeight configs
const FONT_WEIGHTS = {
  bold:               'bold',
  light:              '200',
  medium:             '500',
  normal:             'normal',
  semibold:           '600',
  regular:            '400',
  ultralight:         '100',
};

function transformFontConfigs({ family, style, weight }) {
  const customConfigs = {
    fontFamily: `${family}${_.capitalize(weight)}${_.capitalize(style)}`,
    fontStyle: FONT_STYLES.normal,
    fontWeight: FONT_WEIGHTS.normal,
  };

  const defaultConfigs = {
    fontFamily: family,
    fontStyle: style,
    fontWeight: FONT_WEIGHTS[weight] || FONT_WEIGHTS.normal,
  };

  return Platform.select({
    // Use custom configs for custom fonts on Android
    android: family === 'System' ? defaultConfigs : customConfigs,
    ios: defaultConfigs,
  });
}

class FontUtils extends Singleton {
  aligns = FONT_ALIGNS;
  styles = FONT_STYLES;
  weights = FONT_WEIGHTS;

  build({
    align = FONT_ALIGNS.left,
    background = 'transparent',
    color = 'black',
    family = FONT_FAMILY,
    size = 13,
    style = FONT_STYLES.normal,
    weight = FONT_WEIGHTS.regular,
    ...extraProps
  } = {}) {
    return {
      color,
      backgroundColor: background,
      fontSize: size,
      textAlign: align,
      ...extraProps,
      ...transformFontConfigs({ family, style, weight }),
    };
  }
}

export default FontUtils.get();
<|endoftext|>


<commit_before>App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return ['red', 'yellow', 'blue'];
  }
});
<commit_msg>Fix linting issues.<commit_after>/* global Ember */

'use strict';

var App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return ['red', 'yellow', 'blue'];
  }
});
<|endoftext|>


<commit_before>'use strict';

var yeoman = require('yeoman-generator');
var generators = yeoman.generators;
var yosay = require('yosay');

var GulpBoilerplateGenerator = generators.Base.extend({

  welcome: function() {
    this.log(yosay(
      'Welcome to the Gulp Boilerplate generator!'
    ));
  },

  scaffoldFolders: function () {
    this.mkdir('gulp');
    this.mkdir('gulp/tasks');
    this.mkdir('src');
    this.mkdir('src/sass');
    this.mkdir('src/js');
    this.mkdir('src/images');
    this.mkdir('src/fonts');
    this.mkdir('src/jade');
    this.mkdir('src/jade/layouts');
    this.mkdir('src/jade/views');
  },

  appFiles: function () {
    this.directory('gulp/tasks');
    this.directory('src/sass');
    this.directory('src/js');
    this.directory('src/jade');
    this.directory('src/images');
    this.directory('src/fonts');
  },

  projectfiles: function () {
    this.copy('gulp/config.json', 'gulp/config.json');
    this.copy('README.md', 'README.md');
    this.copy('Gemfile', 'Gemfile');
    this.copy('config.rb', 'config.rb');
    this.copy('gulpfile.js', 'gulpfile.js');
    this.copy('package.json', 'package.json');
  },

  runNpm: function () {
    this.npmInstall();
  },

  end: function () {
    console.log('\nPlease wait, installing node dev dependencies...\n');
  }
});

module.exports = GulpBoilerplateGenerator;<commit_msg>add .gitignore file..<commit_after>'use strict';

var yeoman = require('yeoman-generator');
var generators = yeoman.generators;
var yosay = require('yosay');

var GulpBoilerplateGenerator = generators.Base.extend({

  welcome: function() {
    this.log(yosay(
      'Welcome to the Gulp Boilerplate generator!'
    ));
  },

  scaffoldFolders: function () {
    this.mkdir('gulp');
    this.mkdir('gulp/tasks');
    this.mkdir('src');
    this.mkdir('src/sass');
    this.mkdir('src/js');
    this.mkdir('src/images');
    this.mkdir('src/fonts');
    this.mkdir('src/jade');
    this.mkdir('src/jade/layouts');
    this.mkdir('src/jade/views');
  },

  appFiles: function () {
    this.directory('gulp/tasks');
    this.directory('src/sass');
    this.directory('src/js');
    this.directory('src/jade');
    this.directory('src/images');
    this.directory('src/fonts');
  },

  projectfiles: function () {
    this.copy('gulp/config.json', 'gulp/config.json');
    this.copy('.gitignore', '.gitignore');
    this.copy('README.md', 'README.md');
    this.copy('Gemfile', 'Gemfile');
    this.copy('config.rb', 'config.rb');
    this.copy('gulpfile.js', 'gulpfile.js');
    this.copy('package.json', 'package.json');
  },

  runNpm: function () {
    this.npmInstall();
  },

  end: function () {
    console.log('\nPlease wait, installing node dev dependencies...\n');
  }
});

module.exports = GulpBoilerplateGenerator;<|endoftext|>


<commit_before>'use strict';

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var React = require('react');

var SelectInput = (function (_React$Component) {
  _inherits(SelectInput, _React$Component);

  function SelectInput(props) {
    _classCallCheck(this, SelectInput);

    _get(Object.getPrototypeOf(SelectInput.prototype), 'constructor', this).call(this, props);

    this.state = {
      value: this.props.value
    };
  }

  _createClass(SelectInput, [{
    key: 'handleChange',
    value: function handleChange(e) {
      this.setState({
        value: e.target.value
      }, this.props.onChange.bind(null, e.target.value));
    }
  }, {
    key: 'render',
    value: function render() {
      var options = this.props.options.map(function (opt) {
        return React.createElement(
          'option',
          { key: opt.value,
            value: opt.value },
          opt.text
        );
      });

      return React.createElement(
        'select',
        { name: this.props.name,
          id: this.props.id,
          className: this.props.classes.select,
          value: this.state.value,
          ref: 'select',
          required: this.props.required ? 'required' : undefined,
          onChange: this.handleChange.bind(this),
          onBlur: this.props.onBlur.bind(null, this.state.value) },
        options
      );
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      /*
       * Selects automatically pick the first item, so
       * make sure we set it.
       */
      this.handleChange({
        target: {
          value: this.refs.select.getDOMNode().value
        }
      });
    }
  }]);

  return SelectInput;
})(React.Component);

;

SelectInput.defaultProps = {
  classes: {},
  name: undefined,
  id: undefined,
  value: undefined,
  options: [],
  onChange: function onChange() {},
  onBlur: function onBlur() {}
};

module.exports = SelectInput;<commit_msg>Update selectInput.js<commit_after>'use strict';

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var React = require('react');

var SelectInput = (function (_React$Component) {
  _inherits(SelectInput, _React$Component);

  function SelectInput(props) {
    _classCallCheck(this, SelectInput);

    _get(Object.getPrototypeOf(SelectInput.prototype), 'constructor', this).call(this, props);

    this.state = {
      value: this.props.value
    };
  }

  _createClass(SelectInput, [{
    key: 'handleChange',
    value: function handleChange(e) {
      this.setState({
        value: e.target.value
      }, this.props.onChange.bind(null, e.target.value));
    }
  }, {
    key: 'render',
    value: function render() {
      var options = this.props.options.map(function (opt) {
        return React.createElement(
          'option',
          { key: opt.value,
            value: opt.value },
          opt.text
        );
      });

      return React.createElement(
        'select',
        { name: this.props.name,
          id: this.props.id,
          className: this.props.classes.select,
          value: this.state.value,
          ref: 'select',
          required: this.props.required ? 'required' : undefined,
          onChange: this.handleChange.bind(this),
          onBlur: this.props.onBlur.bind(null, this.state.value) },
        options
      );
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      /*
       * Selects automatically pick the first item, so
       * make sure we set it.
       */
      this.handleChange({
        target: {
          value: this.refs.select.value
        }
      });
    }
  }]);

  return SelectInput;
})(React.Component);

;

SelectInput.defaultProps = {
  classes: {},
  name: undefined,
  id: undefined,
  value: undefined,
  options: [],
  onChange: function onChange() {},
  onBlur: function onBlur() {}
};

module.exports = SelectInput;
<|endoftext|>


<commit_before>'use strict';

/**
 * Create a new Operation in the database.
 * This should be used to keep track of long running operations, that
 * require sending status updates to the user.
 * After creating an operation instance it is possible to store logs.
 *
 * @param {Object} db Database connection to use.
 *
 * @return {Operation} Instance of Operation
 *
 * @throws {MissingDB} If initialized without a db
 * @throws {OpComplete} If starting an operation already completed
 * @throws {OpRunning} If starting an operation that is already running
 * @throws {OpNotFound} If loading a non existent operation
 * @throws {OpNotRunning} If finishing a non running operation
 */
export default class Operation {
  constructor (db) {
    if (!db) throw new Error('Missing db instance');

    this.db = db;
    this
      ._setId(null)
      ._setName(null)
      ._setStatus(null);
  }

  _setStatus (status) {
    this.status = status;
    return this;
  }

  _setId (id) {
    this.id = id;
    return this;
  }

  _setName (name) {
    this.name = name;
    return this;
  }

  _load (opts) {
    return this.db(Operation.opTable)
      .select('*')
      .where(opts)
      .then(res => {
        if (!res.length) return Promise.reject(new Error('Operation does not exist'));
        let op = res[0];

        return this
          ._setId(op.id)
          ._setName(op.name)
          ._setStatus(op.status);
      }, err => Promise.reject(err));
  }

  /**
   * Start a new operation with the given name for the project/scenario.
   * There can't be two operations with the same name/project/scenario running
   * at the same time.
   *
   * @param  {String} name   Name of the operation
   * @param  {Number} projId Project Id
   * @param  {Number} scId   Scenario Id
   *
   * @return {Operation}     This operation instance
   */
  start (name, projId, scId) {
    if (!name || !projId || !scId) {
      throw new Error('Missing parameters');
    }

    if (this.isCompleted()) {
      return Promise.reject(new Error('Operation already complete'));
    }

    if (this.isStarted()) {
      return Promise.reject(new Error('Operation already running'));
    }

    // Check that there isn't another operation with the same values
    // that is not complete.
    return this.db(Operation.opTable)
      .select('id')
      .where({
        name,
        project_id: projId,
        scenario_id: scId
      })
      .andWhereNot('status', Operation.status.complete)
      .then(res => {
        if (res.length) {
          throw new Error('Operation with the same name, project_id and scenario_id is already running');
        }
      })
      .then(() => {
        this.projId = projId;
        this.scId = scId;
        this
          ._setName(name)
          ._setStatus(Operation.status.running);

        return this.db(Operation.opTable)
          .returning('*')
          .insert({
            name,
            project_id: this.projId,
            scenario_id: this.scId,
            status: this.getStatus(),
            created_at: (new Date()),
            updated_at: (new Date())
          });
      })
      .then(res => {
        this.id = res[0].id;
        return this;
      })
      .catch(err => {
        if (err.message.match(/Operation with the same/)) {
          return Promise.reject(err);
        }
        throw err;
      });
  }

  /**
   * Sets the status of the operation to complete.
   *
   * @return {Operation}     This operation instance
   */
  finish () {
    if (!this.isStarted()) {
      return Promise.reject(new Error('Operation not running'));
    }

    this._setStatus(Operation.status.complete);

    return this.db(Operation.opTable)
      .update({
        updated_at: (new Date()),
        status: this.getStatus()
      })
      .where('id', this.id)
      .then(res => {
        return this;
      }, err => Promise.reject(err));
  }

  /**
   * Load the operation by its id.
   *
   * @return {Operation}     This operation instance
   */
  loadById (id) {
    return this._load({id});
  }

  /**
   * Load the operation by name, project, scenario
   *
   * @param  {String} name   Name of the operation
   * @param  {Number} projId Project Id
   * @param  {Number} scId   Scenario Id
   *
   * @return {Operation}     This operation instance
   */
  loadByData (name, projId, scId) {
    return this._load({
      name,
      project_id: projId,
      scenario_id: scId
    });
  }

  /**
   * Log an entry to the database.
   *
   * @param  {Number} code   Operation code
   * @param  {Any} data      Any arbitrary data. It will be stored as json
   *                         format. If `data` is not an object it will be
   *                         stored as {message: `data`}
   * @return {Operation}     This operation instance
   */
  log (code, data = null) {
    if (this.isCompleted()) {
      return Promise.reject(new Error('Operation already complete'));
    }

    if (!this.isStarted()) {
      return Promise.reject(new Error('Operation not running'));
    }

    if (data !== null && data.toString() !== '[object Object]') {
      data = {message: data};
    }

    return this.db.transaction(trx => {
      return trx(Operation.opTable)
        .update({updated_at: (new Date())})
        .where('id', this.id)
        .then(() => {
          return trx(Operation.logTable)
            .insert({
              operation_id: this.id,
              code,
              data,
              created_at: (new Date())
            });
        })
        .then(() => this);
    });
  }

  /**
   * Returns all the operation logs.
   *
   * @return {Promise}     The db query. Results are sorted newest first.
   */
  fetchOperationLogs () {
    return this.db(Operation.logTable)
      .select('*')
      .where('operation_id', this.getId())
      .orderBy('id', 'desc');
  }

  /**
   * Returns the last the operation log.
   *
   * @return {Promise}     The db query.
   */
  fetchLastOperationLog () {
    return this.db(Operation.logTable)
      .select('*')
      .where('operation_id', this.getId())
      .orderBy('id', 'desc')
      .limit(1);
  }

  /**
   * Get the operation id.
   *
   * @return {Number|Null}     The operation id or null if not started.
   */
  getId () {
    return this.id;
  }

  /**
   * Whether the operation was started.
   *
   * @return {Boolean}
   */
  isStarted () {
    return this.getStatus() === Operation.status.running;
  }

  /**
   * Whether the operation was completed.
   *
   * @return {Boolean}
   */
  isCompleted () {
    return this.getStatus() === Operation.status.complete;
  }

  /**
   * Get the operation status.
   *
   * @return {String|Null}     The operation status or null if not started.
   */
  getStatus () {
    return this.status;
  }

  /**
   * Get the operation name.
   *
   * @return {String|Null}     The operation name or null if not started.
   */
  getName () {
    return this.name;
  }
}

Operation.opTable = 'operations';
Operation.logTable = 'operations_logs';

Operation.status = {
  running: 'running',
  complete: 'complete'
};
<commit_msg>Ensure correct order of operations<commit_after>'use strict';

/**
 * Create a new Operation in the database.
 * This should be used to keep track of long running operations, that
 * require sending status updates to the user.
 * After creating an operation instance it is possible to store logs.
 *
 * @param {Object} db Database connection to use.
 *
 * @return {Operation} Instance of Operation
 *
 * @throws {MissingDB} If initialized without a db
 * @throws {OpComplete} If starting an operation already completed
 * @throws {OpRunning} If starting an operation that is already running
 * @throws {OpNotFound} If loading a non existent operation
 * @throws {OpNotRunning} If finishing a non running operation
 */
export default class Operation {
  constructor (db) {
    if (!db) throw new Error('Missing db instance');

    this.db = db;
    this
      ._setId(null)
      ._setName(null)
      ._setStatus(null);
  }

  _setStatus (status) {
    this.status = status;
    return this;
  }

  _setId (id) {
    this.id = id;
    return this;
  }

  _setName (name) {
    this.name = name;
    return this;
  }

  _load (opts) {
    return this.db(Operation.opTable)
      .select('*')
      .where(opts)
      .orderBy('created_at', 'desc')
      .then(res => {
        if (!res.length) return Promise.reject(new Error('Operation does not exist'));
        let op = res[0];

        return this
          ._setId(op.id)
          ._setName(op.name)
          ._setStatus(op.status);
      }, err => Promise.reject(err));
  }

  /**
   * Start a new operation with the given name for the project/scenario.
   * There can't be two operations with the same name/project/scenario running
   * at the same time.
   *
   * @param  {String} name   Name of the operation
   * @param  {Number} projId Project Id
   * @param  {Number} scId   Scenario Id
   *
   * @return {Operation}     This operation instance
   */
  start (name, projId, scId) {
    if (!name || !projId || !scId) {
      throw new Error('Missing parameters');
    }

    if (this.isCompleted()) {
      return Promise.reject(new Error('Operation already complete'));
    }

    if (this.isStarted()) {
      return Promise.reject(new Error('Operation already running'));
    }

    // Check that there isn't another operation with the same values
    // that is not complete.
    return this.db(Operation.opTable)
      .select('id')
      .where({
        name,
        project_id: projId,
        scenario_id: scId
      })
      .andWhereNot('status', Operation.status.complete)
      .then(res => {
        if (res.length) {
          throw new Error('Operation with the same name, project_id and scenario_id is already running');
        }
      })
      .then(() => {
        this.projId = projId;
        this.scId = scId;
        this
          ._setName(name)
          ._setStatus(Operation.status.running);

        return this.db(Operation.opTable)
          .returning('*')
          .insert({
            name,
            project_id: this.projId,
            scenario_id: this.scId,
            status: this.getStatus(),
            created_at: (new Date()),
            updated_at: (new Date())
          });
      })
      .then(res => {
        this.id = res[0].id;
        return this;
      })
      .catch(err => {
        if (err.message.match(/Operation with the same/)) {
          return Promise.reject(err);
        }
        throw err;
      });
  }

  /**
   * Sets the status of the operation to complete.
   *
   * @return {Operation}     This operation instance
   */
  finish () {
    if (!this.isStarted()) {
      return Promise.reject(new Error('Operation not running'));
    }

    this._setStatus(Operation.status.complete);

    return this.db(Operation.opTable)
      .update({
        updated_at: (new Date()),
        status: this.getStatus()
      })
      .where('id', this.id)
      .then(res => {
        return this;
      }, err => Promise.reject(err));
  }

  /**
   * Load the operation by its id.
   *
   * @return {Operation}     This operation instance
   */
  loadById (id) {
    return this._load({id});
  }

  /**
   * Load the operation by name, project, scenario
   *
   * @param  {String} name   Name of the operation
   * @param  {Number} projId Project Id
   * @param  {Number} scId   Scenario Id
   *
   * @return {Operation}     This operation instance
   */
  loadByData (name, projId, scId) {
    return this._load({
      name,
      project_id: projId,
      scenario_id: scId
    });
  }

  /**
   * Log an entry to the database.
   *
   * @param  {Number} code   Operation code
   * @param  {Any} data      Any arbitrary data. It will be stored as json
   *                         format. If `data` is not an object it will be
   *                         stored as {message: `data`}
   * @return {Operation}     This operation instance
   */
  log (code, data = null) {
    if (this.isCompleted()) {
      return Promise.reject(new Error('Operation already complete'));
    }

    if (!this.isStarted()) {
      return Promise.reject(new Error('Operation not running'));
    }

    if (data !== null && data.toString() !== '[object Object]') {
      data = {message: data};
    }

    return this.db.transaction(trx => {
      return trx(Operation.opTable)
        .update({updated_at: (new Date())})
        .where('id', this.id)
        .then(() => {
          return trx(Operation.logTable)
            .insert({
              operation_id: this.id,
              code,
              data,
              created_at: (new Date())
            });
        })
        .then(() => this);
    });
  }

  /**
   * Returns all the operation logs.
   *
   * @return {Promise}     The db query. Results are sorted newest first.
   */
  fetchOperationLogs () {
    return this.db(Operation.logTable)
      .select('*')
      .where('operation_id', this.getId())
      .orderBy('id', 'desc');
  }

  /**
   * Returns the last the operation log.
   *
   * @return {Promise}     The db query.
   */
  fetchLastOperationLog () {
    return this.db(Operation.logTable)
      .select('*')
      .where('operation_id', this.getId())
      .orderBy('id', 'desc')
      .limit(1);
  }

  /**
   * Get the operation id.
   *
   * @return {Number|Null}     The operation id or null if not started.
   */
  getId () {
    return this.id;
  }

  /**
   * Whether the operation was started.
   *
   * @return {Boolean}
   */
  isStarted () {
    return this.getStatus() === Operation.status.running;
  }

  /**
   * Whether the operation was completed.
   *
   * @return {Boolean}
   */
  isCompleted () {
    return this.getStatus() === Operation.status.complete;
  }

  /**
   * Get the operation status.
   *
   * @return {String|Null}     The operation status or null if not started.
   */
  getStatus () {
    return this.status;
  }

  /**
   * Get the operation name.
   *
   * @return {String|Null}     The operation name or null if not started.
   */
  getName () {
    return this.name;
  }
}

Operation.opTable = 'operations';
Operation.logTable = 'operations_logs';

Operation.status = {
  running: 'running',
  complete: 'complete'
};
<|endoftext|>


<commit_before>// This ensures the sync and rebuild child processes can be killed cleanly
var cleanExit = function() { process.exit();};
process.on('SIGINT', cleanExit); // catch ctrl-c
process.on('SIGTERM', cleanExit); // catch kill

var root = require('helper').rootDir;
var fs = require('fs-extra');

// Create empty directories if they don't exist
fs.ensureDirSync(root + '/blogs');
fs.ensureDirSync(root + '/tmp');
fs.ensureDirSync(root + '/logs');
fs.ensureDirSync(root + '/db');
fs.ensureDirSync(root + '/secrets');
fs.ensureDirSync(root + '/static');

var config = require('config');
var analytics = require('./middleware').analytics;
var scheduler = require('./scheduler');
var express = require('express');
var compression = require('compression');
var vhost = require('vhost');
var helmet = require('helmet');
var session = require('express-session');
var redis = require('redis').createClient();
var Store = require('connect-redis')(session);

var dashboard = require('./dashboard');
var site = require('./site');
var blogs = require('./blogs');

// All together now
var server = express();

// Session settings
// It is important that session
// comes before the cache so we
// know what to serve to which user

var sessionOptions = {
  secret: config.session.secret,
  saveUninitialized: false,
  resave: false,
  proxy: true,
  cookie: {
    httpOnly: true,
    secure: config.environment !== 'development'
  },
  store: new Store({
    client: redis,
    port: config.redis.port
  })
};

// Prevent IE users from executing
// downloads in your site's context
// Prevent some browsers from
// sniffing some mimetypes
// Don't allow Blot to be used in iframes
// Create directive at /crossdomain.xml
// which prevents flash from doing shit
// Rendering middleware
server
  .disable('x-powered-by')
  .use(compression())
  .set('trust proxy', 'loopback')
  .use(helmet.ieNoOpen())
  .use(helmet.noSniff())
  .use(helmet.frameguard('allow-from', config.host))
  .use(helmet.crossdomain())
  .use(analytics.middleware)
  .use(function(req, res, next) {
    res.setHeader('Cache-Hit', 'false')
    next();
  })
  .use(vhost(config.host, session(sessionOptions)))
  .use(vhost(config.host, function(req, res, next){

    if (!req.session || !req.session.uid) return next();

    dashboard(req, res, next);
  }))
  .use(vhost(config.host, site))

  // It is important that this route returns
  // 200 so that the script which determines
  // whether the server is health runs OK!
  // Don't remove it unless you change monit.rc
  // It needs to be here because VHOSTS prevent
  // it from working under the sites app
  .use('/health', function(req, res, next){
    if (req.hostname === 'localhost') res.send('OK');
    return next();
  })

  .use(blogs);

// Create an HTTP service.
server.listen(config.port);

console.log('Server started! Now listening for requests on port ' + config.port);

// Unleash the daemon for backups, syncs and emails
scheduler();

// Build template files and watch for changes
// if (config.environment === 'development')
//   require('../scripts/build');<commit_msg>Fixed helmet upgrade bug<commit_after>// This ensures the sync and rebuild child processes can be killed cleanly
var cleanExit = function() { process.exit();};
process.on('SIGINT', cleanExit); // catch ctrl-c
process.on('SIGTERM', cleanExit); // catch kill

var root = require('helper').rootDir;
var fs = require('fs-extra');

// Create empty directories if they don't exist
fs.ensureDirSync(root + '/blogs');
fs.ensureDirSync(root + '/tmp');
fs.ensureDirSync(root + '/logs');
fs.ensureDirSync(root + '/db');
fs.ensureDirSync(root + '/secrets');
fs.ensureDirSync(root + '/static');

var config = require('config');
var analytics = require('./middleware').analytics;
var scheduler = require('./scheduler');
var express = require('express');
var compression = require('compression');
var vhost = require('vhost');
var helmet = require('helmet');
var session = require('express-session');
var redis = require('redis').createClient();
var Store = require('connect-redis')(session);

var dashboard = require('./dashboard');
var site = require('./site');
var blogs = require('./blogs');

// All together now
var server = express();

// Session settings
// It is important that session
// comes before the cache so we
// know what to serve to which user

var sessionOptions = {
  secret: config.session.secret,
  saveUninitialized: false,
  resave: false,
  proxy: true,
  cookie: {
    httpOnly: true,
    secure: config.environment !== 'development'
  },
  store: new Store({
    client: redis,
    port: config.redis.port
  })
};

// Prevent IE users from executing
// downloads in your site's context
// Prevent some browsers from
// sniffing some mimetypes
// Don't allow Blot to be used in iframes
// Create directive at /crossdomain.xml
// which prevents flash from doing shit
// Rendering middleware

console.log('WARNING RENABLE CROSS DOMAINS (helmet)');

server
  .disable('x-powered-by')
  .use(compression())
  .set('trust proxy', 'loopback')
  .use(helmet.ieNoOpen())
  .use(helmet.noSniff())
  .use(helmet.frameguard('allow-from', config.host))
  // .use(helmet.crossdomain())
  .use(analytics.middleware)
  .use(function(req, res, next) {
    res.setHeader('Cache-Hit', 'false')
    next();
  })
  .use(vhost(config.host, session(sessionOptions)))
  .use(vhost(config.host, function(req, res, next){

    if (!req.session || !req.session.uid) return next();

    dashboard(req, res, next);
  }))
  .use(vhost(config.host, site))

  // It is important that this route returns
  // 200 so that the script which determines
  // whether the server is health runs OK!
  // Don't remove it unless you change monit.rc
  // It needs to be here because VHOSTS prevent
  // it from working under the sites app
  .use('/health', function(req, res, next){
    if (req.hostname === 'localhost') res.send('OK');
    return next();
  })

  .use(blogs);

// Create an HTTP service.
server.listen(config.port);

console.log('Server started! Now listening for requests on port ' + config.port);

// Unleash the daemon for backups, syncs and emails
scheduler();

// Build template files and watch for changes
// if (config.environment === 'development')
//   require('../scripts/build');<|endoftext|>


<commit_before>if("undefined"==typeof jQuery.aljs)throw new Error("Please include the ALJS initializer file");!function(s){var e='

',t='<svg aria-hidden="true" class="slds-icon slds-icon-standard-account slds-icon--small"><use xlink:href="{{objectIconUrl}}"></use></svg>{{selectedResultLabel}}<button class="slds-button slds-button--icon-bare"><svg aria-hidden="true" class="slds-button__icon"><use xlink:href="{{assetsLocation}}/assets/icons/utility-sprite/svg/symbols.svg#close"></use></svg>Remove</button>',l='

',i='
<button class="slds-button"><svg aria-hidden="true" class="slds-icon slds-icon-text-default slds-icon--small"><use xlink:href="{{assetsLocation}}/assets/icons/utility-sprite/svg/symbols.svg#search"></use></svg>"{{searchTerm}}" in {{objectPluralLabel}}</button>
',n='
<button class="slds-button"><svg aria-hidden="true" class="slds-icon slds-icon-text-default slds-icon--small"><use xlink:href="{{assetsLocation}}/assets/icons/utility-sprite/svg/symbols.svg#add"></use></svg>Add {{objectLabel}}</button>
',a='
<svg aria-hidden="true" class="slds-icon slds-icon-standard-account slds-icon--small"><use xlink:href="{{objectIconUrl}}"></use></svg>{{resultLabel}}
',o=function(t,l){this.$el=s(t),this.$lookupContainer=this.$el.closest(".slds-lookup"),this.isSingle="single"===this.$lookupContainer.data("select"),this.settings=l,this.isSingle?this.$singleSelect=s(e).insertBefore(this.$el):(this.$multiSelect=s(e).appendTo(this.$lookupContainer.find(".slds-form-element")),this.selectedResults=[]),this.isStringEmpty(l.searchTerm)?l.initialSelectedResult&&this.setSingleSelect(l.initialSelectedResult.label):(this.$el.val(l.searchTerm),this.setSingleSelect()),this.initLookup()};o.prototype={constructor:o,isStringEmpty:function(s){return null===s||"undefined"==typeof s||""===s.trim()},initLookup:function(){this.$el.on("focus",this,this.runSearch).on("keyup",this,this.runSearch).on("blur",this,this.handleBlur)},runSearch:function(s){var e=s.data,t=e.$el.val();e.isStringEmpty(t)?e.getDefaultResults():e.getSearchTermResults(t)},setMultiSelect:function(e){var l=this,i=this.$multiSelect.html(""),n=this.$lookupContainer;e.length>0?(e.forEach(function(e){var n=s(t.replace("{{objectIconUrl}}",l.settings.objectIconUrl).replace("{{assetsLocation}}",l.settings.assetsLocation).replace("{{selectedResultLabel}}",e.label));n.attr("id",e.id),n.on("click","a, button",l,l.clearMultiSelectResult),i.append(n)}),i.addClass("slds-show").removeClass("slds-hide"),n.addClass("slds-has-selection")):(i.html(""),i.addClass("slds-hide").removeClass("slds-show"),n.removeClass("slds-has-selection"))},setSingleSelect:function(s){var e=this,l=s||"";this.$singleSelect.html(t.replace("{{objectIconUrl}}",this.settings.objectIconUrl).replace("{{assetsLocation}}",this.settings.assetsLocation).replace("{{selectedResultLabel}}",l)),s?(this.$singleSelect.addClass("slds-show").removeClass("slds-hide"),this.$el.addClass("slds-hide"),this.$lookupContainer.addClass("slds-has-selection"),this.$singleSelect.one("click","a, button",this,this.clearSingleSelect)):(this.$singleSelect.addClass("slds-hide").removeClass("slds-show"),this.$el.val("").removeClass("slds-hide"),this.$lookupContainer.removeClass("slds-has-selection"),window.setTimeout(function(){e.$el.focus()},100))},getSearchTermResults:function(s){var e=this;if(this.settings.items.length>0)this.searchResults=this.settings.items.filter(function(e){return null!==e.label.match(s)}),this.renderSearchResults();else{var t=function(s){e.searchResults=s,e.renderSearchResults()};this.settings.filledSearchTermQuery(s,t)}},getDefaultResults:function(){var s=this;if(this.settings.items.length>0)this.searchResults=this.settings.items,this.renderSearchResults();else{var e=function(e){s.searchResults=e,s.renderSearchResults()};this.settings.emptySearchTermQuery(e)}},renderSearchResults:function(){this.closeSearchDropdown();var e=s(l),t=e.find("ul.slds-lookup__list"),o=this.$el.val(),c=this;if(!this.isStringEmpty(o)&&o.length>1&&t.before(i.replace("{{searchTerm}}",o).replace("{{objectPluralLabel}}",this.settings.objectPluralLabel).replace("{{assetsLocation}}",s.aljs.assetsLocation)),this.searchResults.forEach(function(s){if(c.isSingle)t.append(a.replace("{{resultLabel}}",s.label).replace("{{resultId}}",s.id).replace("{{objectIconUrl}}",c.settings.objectIconUrl));else if(c.selectedResults){var e=c.selectedResults.map(function(s){return s.id});(0===e.length||-1===e.indexOf(s.id))&&t.append(a.replace("{{resultLabel}}",s.label).replace("{{resultId}}",s.id).replace("{{objectIconUrl}}",c.settings.objectIconUrl))}}),this.settings.clickAddFunction){t.after(n.replace("{{objectLabel}}",this.settings.objectLabel).replace("{{assetsLocation}}",s.aljs.assetsLocation))}t.one("click","a",this,this.clickResult),this.$lookupSearchContainer=e,e.appendTo(this.$lookupContainer)},closeSearchDropdown:function(){this.$lookupSearchContainer&&(this.$lookupSearchContainer.remove(),this.$lookupSearchContainer=null)},handleBlur:function(e){var t=e.data;0===s(e.relatedTarget).closest(".slds-lookup__menu").length&&t.$lookupSearchContainer&&t.closeSearchDropdown()},clickResult:function(e){var t=e.data,l=s(this).attr("id");t.selectResult(l)},selectResult:function(s){var e=this.searchResults.filter(function(e){return e.id==s});this.closeSearchDropdown(),this.isSingle?(this.selectedResult=e.length>0?e[0]:null,this.setSingleSelect(this.selectedResult.label)):e.length>0&&(this.selectedResults.push(e[0]),this.setMultiSelect(this.selectedResults))},clearSingleSelect:function(s){var e=s.data;e.setSingleSelect()},clearMultiSelectResult:function(e){var t,l=e.data,i=s(this).closest("span.slds-pill"),n=i.attr("id");l.selectedResults.forEach(function(s,e){s.id==n&&(t=e)}),"undefined"!=typeof t&&null!==t&&(l.selectedResults.splice(t,1),l.setMultiSelect(l.selectedResults))}},s.fn.lookup=function(e){var t,l=arguments,i=s.extend({assetsLocation:s.aljs.assetsLocation,objectPluralLabel:"Stuffs",objectLabel:"Stuff",objectIconUrl:"assets/icons/standard-sprite/svg/symbols.svg#account",searchTerm:"",items:[],emptySearchTermQuery:function(){callback([])},filledSearchTermQuery:function(s,e){e([])},clickAddFunction:null},"object"==typeof e?e:{});if(this.each(function(){var n=s(this),a=n.data("aljs-lookup");if(!a){var c=new o(this,i);n.data("aljs-lookup",a=c)}"string"==typeof e&&(t=a[e](l[1],l[2]))}),void 0===t||t instanceof Picklist)return this;if(this.length>1)throw new Error("Using only allowed for the collection of a single element ("+option+" function)");return t}}(jQuery);<commit_msg>Minified<commit_after>if("undefined"==typeof jQuery.aljs)throw new Error("Please include the ALJS initializer file");!function(s){var e='

',t='<svg aria-hidden="true" class="slds-icon slds-icon-standard-account slds-icon--small"><use xlink:href="{{objectIconUrl}}"></use></svg>{{selectedResultLabel}}<button class="slds-button slds-button--icon-bare"><svg aria-hidden="true" class="slds-button__icon"><use xlink:href="{{assetsLocation}}/assets/icons/utility-sprite/svg/symbols.svg#close"></use></svg>Remove</button>',l='

',i='
<button class="slds-button"><svg aria-hidden="true" class="slds-icon slds-icon-text-default slds-icon--small"><use xlink:href="{{assetsLocation}}/assets/icons/utility-sprite/svg/symbols.svg#search"></use></svg>"{{searchTerm}}" in {{objectPluralLabel}}</button>
',n='
<button class="slds-button"><svg aria-hidden="true" class="slds-icon slds-icon-text-default slds-icon--small"><use xlink:href="{{assetsLocation}}/assets/icons/utility-sprite/svg/symbols.svg#add"></use></svg>Add {{objectLabel}}</button>
',a='
<svg aria-hidden="true" class="slds-icon slds-icon-standard-account slds-icon--small"><use xlink:href="{{objectIconUrl}}"></use></svg>{{resultLabel}}
',o=function(t,l){this.$el=s(t),this.$lookupContainer=this.$el.closest(".slds-lookup"),this.isSingle="single"===this.$lookupContainer.data("select"),this.settings=l,this.isSingle?this.$singleSelect=s(e).insertBefore(this.$el):(this.$multiSelect=s(e).appendTo(this.$lookupContainer.find(".slds-form-element")),this.selectedResults=[]),this.isStringEmpty(l.searchTerm)?l.initialSelectedResult&&this.setSingleSelect(l.initialSelectedResult.label):(this.$el.val(l.searchTerm),this.setSingleSelect()),this.initLookup()};o.prototype={constructor:o,isStringEmpty:function(s){return null===s||"undefined"==typeof s||""===s.trim()},initLookup:function(){var e=this;this.$el.on("focus",this,this.runSearch).on("keyup",this,this.runSearch).on("blur",this,this.handleBlur),this.$lookupContainer.on("keyup",function(t){t.stopPropagation();var l=s(this).find("a:focus");27===t.keyCode&&e.$el.blur(),40===t.keyCode&&(l.length>0?l.parent().next().find("a").focus():s(this).find(".slds-lookup__list").find("a:first").focus()),38===t.keyCode&&(l.length>0?l.parent().prev().find("a").focus():s(this).find(".slds-lookup__list").find("a:last").focus())})},runSearch:function(s){var e=s.data,t=e.$el.val();e.isStringEmpty(t)?e.getDefaultResults():e.getSearchTermResults(t)},setMultiSelect:function(e){var l=this,i=this.$multiSelect.html(""),n=this.$lookupContainer;e.length>0?(e.forEach(function(e){var n=s(t.replace("{{objectIconUrl}}",l.settings.objectIconUrl).replace("{{assetsLocation}}",l.settings.assetsLocation).replace("{{selectedResultLabel}}",e.label));n.removeClass("slds-pill--bare").attr("id",e.id).on("click","a, button",l,l.clearMultiSelectResult),i.append(n)}),i.addClass("slds-show").removeClass("slds-hide"),n.addClass("slds-has-selection")):(i.html(""),i.addClass("slds-hide").removeClass("slds-show"),n.removeClass("slds-has-selection"))},setSingleSelect:function(s){var e=this,l=s||"";this.$singleSelect.html(t.replace("{{objectIconUrl}}",this.settings.objectIconUrl).replace("{{assetsLocation}}",this.settings.assetsLocation).replace("{{selectedResultLabel}}",l)),s?(this.$singleSelect.addClass("slds-show").removeClass("slds-hide"),this.$el.addClass("slds-hide"),this.$lookupContainer.addClass("slds-has-selection"),this.$singleSelect.one("click","a, button",this,this.clearSingleSelect)):(this.$singleSelect.addClass("slds-hide").removeClass("slds-show"),this.$el.val("").removeClass("slds-hide"),this.$lookupContainer.removeClass("slds-has-selection"),window.setTimeout(function(){e.$el.focus()},100))},getSearchTermResults:function(s){var e=this;if(this.settings.items.length>0)this.searchResults=this.settings.items.filter(function(e){return null!==e.label.match(s)}),this.renderSearchResults();else{var t=function(s){e.searchResults=s,e.renderSearchResults()};this.settings.filledSearchTermQuery(s,t)}},getDefaultResults:function(){var s=this;if(this.settings.items.length>0)this.searchResults=this.settings.items,this.renderSearchResults();else{var e=function(e){s.searchResults=e,s.renderSearchResults()};this.settings.emptySearchTermQuery(e)}},renderSearchResults:function(){this.closeSearchDropdown();var e=s(l),t=e.find("ul.slds-lookup__list"),o=this.$el.val(),c=this;if(!this.isStringEmpty(o)&&o.length>1&&t.before(i.replace("{{searchTerm}}",o).replace("{{objectPluralLabel}}",this.settings.objectPluralLabel).replace("{{assetsLocation}}",s.aljs.assetsLocation)),this.searchResults.forEach(function(e){var l;if(c.isSingle)l=t.append(a.replace("{{resultLabel}}",e.label).replace("{{resultId}}",e.id).replace("{{objectIconUrl}}",c.settings.objectIconUrl));else if(c.selectedResults){var i=c.selectedResults.map(function(s){return s.id});(0===i.length||-1===i.indexOf(e.id))&&(l=t.append(a.replace("{{resultLabel}}",e.label).replace("{{resultId}}",e.id).replace("{{objectIconUrl}}",c.settings.objectIconUrl)))}l&&l.find("a").on("focus",function(){c.$el.attr("aria-activedescendant",s(this).attr("id"))}).on("blur",c,c.handleBlur)}),this.settings.clickAddFunction){t.after(n.replace("{{objectLabel}}",this.settings.objectLabel).replace("{{assetsLocation}}",s.aljs.assetsLocation))}t.one("click","a",this,this.clickResult),this.$lookupSearchContainer=e,e.appendTo(this.$lookupContainer),this.$el.attr("aria-expanded","true")},closeSearchDropdown:function(){this.$lookupSearchContainer&&(this.$lookupSearchContainer.remove(),this.$lookupSearchContainer=null),this.$el.attr("aria-expanded","false"),this.$el.attr("aria-activedescendant",null)},handleBlur:function(e){var t=e.data;0===s(e.relatedTarget).closest(".slds-lookup__menu").length&&t.$lookupSearchContainer&&t.closeSearchDropdown()},clickResult:function(e){var t=e.data,l=s(this).attr("id");t.selectResult(l)},selectResult:function(s){var e=this.searchResults.filter(function(e){return e.id==s});this.closeSearchDropdown(),this.isSingle?(this.selectedResult=e.length>0?e[0]:null,this.setSingleSelect(this.selectedResult.label)):e.length>0&&(this.selectedResults.push(e[0]),this.setMultiSelect(this.selectedResults),this.$el.val(""))},clearSingleSelect:function(s){var e=s.data;e.setSingleSelect()},clearMultiSelectResult:function(e){var t,l=e.data,i=s(this).closest("span.slds-pill"),n=i.attr("id");l.selectedResults.forEach(function(s,e){s.id==n&&(t=e)}),"undefined"!=typeof t&&null!==t&&(l.selectedResults.splice(t,1),l.setMultiSelect(l.selectedResults))}},s.fn.lookup=function(e){var t,l=arguments,i=s.extend({assetsLocation:s.aljs.assetsLocation,objectPluralLabel:"Stuffs",objectLabel:"Stuff",objectIconUrl:"assets/icons/standard-sprite/svg/symbols.svg#account",searchTerm:"",items:[],emptySearchTermQuery:function(){callback([])},filledSearchTermQuery:function(s,e){e([])},clickAddFunction:null},"object"==typeof e?e:{});if(this.each(function(){var n=s(this),a=n.data("aljs-lookup");if(!a){var c=new o(this,i);n.data("aljs-lookup",a=c)}"string"==typeof e&&(t=a[e](l[1],l[2]))}),void 0===t||t instanceof Picklist)return this;if(this.length>1)throw new Error("Using only allowed for the collection of a single element ("+option+" function)");return t}}(jQuery);<|endoftext|>