<commit_before>Travis.Controllers.Application = Backbone.Controller.extend({
  routes: {
    '':                                          'recent',
    // '!/:owner':               'byOwner',
    // FIXME: I would suggest to use !/repositories/:owner/:name, to make it more rest-like.
    // Because, for instance, now we should put myRepositories on top so that it could get matched. Unambigous routes rule!
    '!/:owner/:name/L:line_number':              'repository',
    '!/:owner/:name':                            'repository',
    '!/:owner/:name/builds':                     'repositoryHistory',
    '!/:owner/:name/builds/:id/L:line_number':   'repositoryBuild',
    '!/:owner/:name/builds/:id':                 'repositoryBuild',
  },
  initialize: function() {
    _.bindAll(this, 'recent', 'byUser', 'repository', 'repositoryHistory', 'repositoryBuild', 'repositoryShow', 'repositorySelected',
              'buildQueued', 'buildStarted', 'buildLogged', 'buildFinished', 'buildRemoved');
  },

  run: function() {
    this.repositories = new Travis.Collections.Repositories();
    this.builds       = new Travis.Collections.AllBuilds();
    this.jobs         = new Travis.Collections.Jobs([], { queue: 'builds' });
    this.jobsRails    = new Travis.Collections.Jobs([], { queue: 'rails' });
    this.workers      = new Travis.Collections.Workers();

    this.repositoriesList = new Travis.Views.Repositories.List();
    this.repositoryShow   = new Travis.Views.Repository.Show({ parent: this });
    this.workersView      = new Travis.Views.Workers.List();
    this.jobsView         = new Travis.Views.Jobs.List({ queue: 'builds' });
    this.jobsRailsView    = new Travis.Views.Jobs.List({ queue: 'rails' });

    $('#left #tab_recent .tab').append(this.repositoriesList.render().el);
    $('#main').append(this.repositoryShow.render().el);

    this.repositoriesList.attachTo(this.repositories);
    this.repositoryShow.attachTo(this.repositories)
    this.workersView.attachTo(this.workers)
    this.jobsView.attachTo(this.jobs)
    this.jobsRailsView.attachTo(this.jobsRails)
    this.repositories.bind('select', this.repositorySelected);

    this.bind('build:started',    this.buildStarted);
    this.bind('build:finished',   this.buildFinished);
    this.bind('build:configured', this.buildConfigured);
    this.bind('build:log',        this.buildLogged);
    this.bind('build:queued',     this.buildQueued);
    this.bind('build:removed',    this.buildRemoved);

    this.workers.fetch();
    this.jobs.fetch();
    this.jobsRails.fetch();
  },

  // actions

  recent: function() {
    this.reset();
    this.followBuilds = true;
    this.selectTab('current');
    this.repositories.whenFetched(_.bind(function () {
      this.repositories.selectLast();

    }, this));
  },
  repository: function(owner, name, line_number) {
    this.reset();
    this.trackPage();
    this.startLoading();
    window.params = { owner: owner, name: name, line_number: line_number, action: 'repository' }
    this.selectTab('current');
    this.repositories.whenFetched(_.bind(function(repositories) {
      repositories.selectLastBy({ slug: owner + '/' + name });

    }, this));
  },
  repositoryHistory: function(owner, name) {
    this.reset();
    this.trackPage();
    this.selectTab('history');
    this.repositories.whenFetched(_.bind(function(repositories) {
      repositories.selectLastBy({ slug: owner + '/' + name })

    }, this));
  },
  repositoryBuild: function(owner, name, buildId, line_number) {
    this.reset();
    this.trackPage();
    this.startLoading();
    window.params = { owner: owner, name: name, build_id: buildId, line_number: line_number, action: 'repositoryBuild' }
    this.buildId = parseInt(buildId);
    this.selectTab('build');
    this.repositories.whenFetched(_.bind(function(repositories) {
      repositories.selectLastBy({ slug: owner + '/' + name })

    }, this));
  },

  // helpers
  reset: function() {
    delete this.buildId;
    delete this.tab;
    this.followBuilds = false;
    window.params = {};
  },
  startLoading: function() {
    $('#main').addClass('loading')
  },
  stopLoading: function() {
    $('#main').removeClass('loading')
  },
  trackPage: function() {
    window._gauges = window._gauges || [];
    window._gauges.push(['track']);
  },

  // internal events
  repositorySelected: function(repository) {
    repository.builds.bind('finish_get_or_fetch', function() { this.stopLoading() }.bind(this))

    switch(this.tab) {
      case 'current':
        repository.builds.select(repository.get('last_build_id'));
        break;
      case 'build':
        repository.builds.select(this.buildId);
        break;
      case 'history':
        if(!repository.builds.fetched) repository.builds.fetch();
        break;
    };
  },

  // external events

  buildQueued: function(data) {
    this.addBuild(data);
  },
  buildStarted: function(data) {
    this.removeBuild(data);
    this.repositories.update(data);

    if((this.followBuilds || this.tab == 'current' && this.repositories.selected().get('slug') == data.slug) && !this.buildId && !data.build.parent_id) {
      var repository = this.repositories.get(data.id);
      if(!repository.selected) repository.select();
      repository.builds.select(data.build.id);
    }
  },
  buildConfigured: function(data) {
    this.removeBuild(data);
    this.repositories.update(data);
  },
  buildFinished: function(data) {
    this.repositories.update(data);
  },
  buildRemoved: function(data) {
    this.removeBuild(data);
  },
  buildLogged: function(data) {
    this.repositories.update(data);
  },
  selectTab: function(tab) {
    this.tab = tab;
    this.repositoryShow.activateTab(this.tab);
  },
  addJob: function(data) {
    this.jobsCollection().add({ number: data.build.number, id: data.build.id, repository: { slug: data.slug } });
  },
  removeJob: function(data) {
    this.jobsCollection().remove({ id: data.build.id });
  },
  jobsCollection: function(data) {
    return this.buildingRails(data) ? this.jobsRails : this.jobs;
  },
  buildingRails: function (data) {
    return data.slug && data.slug.match(/rails/);
  }
});

<commit_msg>js fix: it's addJob and removeJob<commit_after>Travis.Controllers.Application = Backbone.Controller.extend({
  routes: {
    '':                                          'recent',
    // '!/:owner':               'byOwner',
    // FIXME: I would suggest to use !/repositories/:owner/:name, to make it more rest-like.
    // Because, for instance, now we should put myRepositories on top so that it could get matched. Unambigous routes rule!
    '!/:owner/:name/L:line_number':              'repository',
    '!/:owner/:name':                            'repository',
    '!/:owner/:name/builds':                     'repositoryHistory',
    '!/:owner/:name/builds/:id/L:line_number':   'repositoryBuild',
    '!/:owner/:name/builds/:id':                 'repositoryBuild',
  },
  initialize: function() {
    _.bindAll(this, 'recent', 'byUser', 'repository', 'repositoryHistory', 'repositoryBuild', 'repositoryShow', 'repositorySelected',
              'buildQueued', 'buildStarted', 'buildLogged', 'buildFinished', 'buildRemoved');
  },

  run: function() {
    this.repositories = new Travis.Collections.Repositories();
    this.builds       = new Travis.Collections.AllBuilds();
    this.jobs         = new Travis.Collections.Jobs([], { queue: 'builds' });
    this.jobsRails    = new Travis.Collections.Jobs([], { queue: 'rails' });
    this.workers      = new Travis.Collections.Workers();

    this.repositoriesList = new Travis.Views.Repositories.List();
    this.repositoryShow   = new Travis.Views.Repository.Show({ parent: this });
    this.workersView      = new Travis.Views.Workers.List();
    this.jobsView         = new Travis.Views.Jobs.List({ queue: 'builds' });
    this.jobsRailsView    = new Travis.Views.Jobs.List({ queue: 'rails' });

    $('#left #tab_recent .tab').append(this.repositoriesList.render().el);
    $('#main').append(this.repositoryShow.render().el);

    this.repositoriesList.attachTo(this.repositories);
    this.repositoryShow.attachTo(this.repositories)
    this.workersView.attachTo(this.workers)
    this.jobsView.attachTo(this.jobs)
    this.jobsRailsView.attachTo(this.jobsRails)
    this.repositories.bind('select', this.repositorySelected);

    this.bind('build:started',    this.buildStarted);
    this.bind('build:finished',   this.buildFinished);
    this.bind('build:configured', this.buildConfigured);
    this.bind('build:log',        this.buildLogged);
    this.bind('build:queued',     this.buildQueued);
    this.bind('build:removed',    this.buildRemoved);

    this.workers.fetch();
    this.jobs.fetch();
    this.jobsRails.fetch();
  },

  // actions

  recent: function() {
    this.reset();
    this.followBuilds = true;
    this.selectTab('current');
    this.repositories.whenFetched(_.bind(function () {
      this.repositories.selectLast();

    }, this));
  },
  repository: function(owner, name, line_number) {
    this.reset();
    this.trackPage();
    this.startLoading();
    window.params = { owner: owner, name: name, line_number: line_number, action: 'repository' }
    this.selectTab('current');
    this.repositories.whenFetched(_.bind(function(repositories) {
      repositories.selectLastBy({ slug: owner + '/' + name });

    }, this));
  },
  repositoryHistory: function(owner, name) {
    this.reset();
    this.trackPage();
    this.selectTab('history');
    this.repositories.whenFetched(_.bind(function(repositories) {
      repositories.selectLastBy({ slug: owner + '/' + name })

    }, this));
  },
  repositoryBuild: function(owner, name, buildId, line_number) {
    this.reset();
    this.trackPage();
    this.startLoading();
    window.params = { owner: owner, name: name, build_id: buildId, line_number: line_number, action: 'repositoryBuild' }
    this.buildId = parseInt(buildId);
    this.selectTab('build');
    this.repositories.whenFetched(_.bind(function(repositories) {
      repositories.selectLastBy({ slug: owner + '/' + name })

    }, this));
  },

  // helpers
  reset: function() {
    delete this.buildId;
    delete this.tab;
    this.followBuilds = false;
    window.params = {};
  },
  startLoading: function() {
    $('#main').addClass('loading')
  },
  stopLoading: function() {
    $('#main').removeClass('loading')
  },
  trackPage: function() {
    window._gauges = window._gauges || [];
    window._gauges.push(['track']);
  },

  // internal events
  repositorySelected: function(repository) {
    repository.builds.bind('finish_get_or_fetch', function() { this.stopLoading() }.bind(this))

    switch(this.tab) {
      case 'current':
        repository.builds.select(repository.get('last_build_id'));
        break;
      case 'build':
        repository.builds.select(this.buildId);
        break;
      case 'history':
        if(!repository.builds.fetched) repository.builds.fetch();
        break;
    };
  },

  // external events

  buildQueued: function(data) {
    this.addJob(data);
  },
  buildStarted: function(data) {
    this.removeJob(data);
    this.repositories.update(data);

    if((this.followBuilds || this.tab == 'current' && this.repositories.selected().get('slug') == data.slug) && !this.buildId && !data.build.parent_id) {
      var repository = this.repositories.get(data.id);
      if(!repository.selected) repository.select();
      repository.builds.select(data.build.id);
    }
  },
  buildConfigured: function(data) {
    this.removeJob(data);
    this.repositories.update(data);
  },
  buildFinished: function(data) {
    this.repositories.update(data);
  },
  buildRemoved: function(data) {
    this.removeJob(data);
  },
  buildLogged: function(data) {
    this.repositories.update(data);
  },
  selectTab: function(tab) {
    this.tab = tab;
    this.repositoryShow.activateTab(this.tab);
  },
  addJob: function(data) {
    this.jobsCollection().add({ number: data.build.number, id: data.build.id, repository: { slug: data.slug } });
  },
  removeJob: function(data) {
    this.jobsCollection().remove({ id: data.build.id });
  },
  jobsCollection: function(data) {
    return this.buildingRails(data) ? this.jobsRails : this.jobs;
  },
  buildingRails: function (data) {
    return data.slug && data.slug.match(/rails/);
  }
});

<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//  Copyright (C) 2008-2011  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// CodeCell
//============================================================================

var IPython = (function (IPython) {
    "use strict";

    var utils = IPython.utils;
    var key   = IPython.utils.keycodes;

    var CodeCell = function (kernel) {
        // The kernel doesn't have to be set at creation time, in that case
        // it will be null and set_kernel has to be called later.
        this.kernel = kernel || null;
        this.code_mirror = null;
        this.input_prompt_number = null;
        this.tooltip_on_tab = true;
        this.collapsed = false;
        IPython.Cell.apply(this, arguments);
    };

    CodeCell.prototype = new IPython.Cell();

    CodeCell.prototype.create_element = function () {
        var cell =  $('

').addClass('cell border-box-sizing code_cell vbox');
        cell.attr('tabindex','2');
        var input = $('

').addClass('input hbox');
        input.append($('
').addClass('prompt input_prompt'));
        var input_area = $('
').addClass('input_area box-flex1');
        this.code_mirror = CodeMirror(input_area.get(0), {
            indentUnit : 4,
            mode: 'python',
            theme: 'ipython',
            readOnly: this.read_only,
            extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess",'Backspace':"delSpaceToPrevTabStop"},
            onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
        });
        input.append(input_area);
        var output = $('

');
        cell.append(input).append(output);
        this.element = cell;
        this.output_area = new IPython.OutputArea(output, true);

        // construct a completer only if class exist
        // otherwise no print view
        if (IPython.Completer !== undefined)
        {
            this.completer = new IPython.Completer(this);
        }
    };

    CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
        // This method gets called in CodeMirror's onKeyDown/onKeyPress
        // handlers and is used to provide custom key handling. Its return
        // value is used to determine if CodeMirror should ignore the event:
        // true = ignore, false = don't ignore.

        if (this.read_only){
            return false;
        }

        var that = this;
        // whatever key is pressed, first, cancel the tooltip request before
        // they are sent, and remove tooltip if any, except for tab again
        if (event.type === 'keydown' && event.which != key.TAB ) {
            IPython.tooltip.remove_and_cancel_tooltip();
        };

        var cur = editor.getCursor();

        if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey)) {
            // Always ignore shift-enter in CodeMirror as we handle it.
            return true;
        } else if (event.which === 40 && event.type === 'keypress' && IPython.tooltip.time_before_tooltip >= 0) {
            // triger on keypress (!) otherwise inconsistent event.which depending on plateform
            // browser and keyboard layout !
            // Pressing '(' , request tooltip, don't forget to reappend it
            IPython.tooltip.pending(that);
        } else if (event.which === key.UPARROW && event.type === 'keydown') {
            // If we are not at the top, let CM handle the up arrow and
            // prevent the global keydown handler from handling it.
            if (!that.at_top()) {
                event.stop();
                return false;
            } else {
                return true;
            };
        } else if (event.which === key.ESC) {
            IPython.tooltip.remove_and_cancel_tooltip(true);
            return true;
        } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
            // If we are not at the bottom, let CM handle the down arrow and
            // prevent the global keydown handler from handling it.
            if (!that.at_bottom()) {
                event.stop();
                return false;
            } else {
                return true;
            };
        } else if (event.keyCode === key.TAB && event.type == 'keydown') {
            // Tab completion.
            //Do not trim here because of tooltip
            var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
            if (pre_cursor.trim() === "") {
                // Don't autocomplete if the part of the line before the cursor
                // is empty.  In this case, let CodeMirror handle indentation.
                return false;
            } else if ((pre_cursor.substr(-1) === "("|| pre_cursor.substr(-1) === " ") && that.tooltip_on_tab ) {
                IPython.tooltip.request(that);
                // Prevent the event from bubbling up.
                event.stop();
                // Prevent CodeMirror from handling the tab.
                return true;
            } else {
                event.stop();
                this.completer.startCompletion();
                return true;
            };
        } else {
            // keypress/keyup also trigger on TAB press, and we don't want to
            // use those to disable tab completion.
            return false;
        };
        return false;
    };

    // Kernel related calls.

    CodeCell.prototype.set_kernel = function (kernel) {
        this.kernel = kernel;
    }

    CodeCell.prototype.execute = function () {
        this.output_area.clear_output(true, true, true);
        this.set_input_prompt('*');
        this.element.addClass("running");
        var callbacks = {
            'execute_reply': $.proxy(this._handle_execute_reply, this),
            'output': $.proxy(this.output_area.handle_output, this.output_area),
            'clear_output': $.proxy(this.output_area.handle_clear_output, this.output_area),
            'set_next_input': $.proxy(this._handle_set_next_input, this)
        };
        var msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false});
    };

    CodeCell.prototype._handle_execute_reply = function (content) {
        this.set_input_prompt(content.execution_count);
        this.element.removeClass("running");
        $([IPython.events]).trigger('set_dirty.Notebook', {'value': true});
    }

    CodeCell.prototype._handle_set_next_input = function (text) {
        var data = {'cell': this, 'text': text}
        $([IPython.events]).trigger('set_next_input.Notebook', data);
    }

    // Basic cell manipulation.

    CodeCell.prototype.select = function () {
        IPython.Cell.prototype.select.apply(this);
        this.code_mirror.refresh();
        this.code_mirror.focus();
        // We used to need an additional refresh() after the focus, but
        // it appears that this has been fixed in CM. This bug would show
        // up on FF when a newly loaded markdown cell was edited.
    };

    CodeCell.prototype.select_all = function () {
        var start = {line: 0, ch: 0};
        var nlines = this.code_mirror.lineCount();
        var last_line = this.code_mirror.getLine(nlines-1);
        var end = {line: nlines-1, ch: last_line.length};
        this.code_mirror.setSelection(start, end);
    };

    CodeCell.prototype.collapse = function () {
        this.collapsed = true;
        this.output_area.collapse();
    };

    CodeCell.prototype.expand = function () {
        this.collapsed = false;
        this.output_area.expand();
    };

    CodeCell.prototype.toggle_output = function () {
        this.collapsed = Boolean(1 - this.collapsed);
        this.output_area.toggle_output();
    };

    CodeCell.prototype.toggle_output_scroll = function () {
    this.output_area.toggle_scroll();
    };

    CodeCell.prototype.set_input_prompt = function (number) {
        this.input_prompt_number = number;
        var ns = number || " ";
        this.element.find('div.input_prompt').html('In [' + ns + ']:');
    };

    CodeCell.prototype.clear_input = function () {
        this.code_mirror.setValue('');
    };

    CodeCell.prototype.get_text = function () {
        return this.code_mirror.getValue();
    };

    CodeCell.prototype.set_text = function (code) {
        return this.code_mirror.setValue(code);
    };

    CodeCell.prototype.at_top = function () {
        var cursor = this.code_mirror.getCursor();
        if (cursor.line === 0 && cursor.ch === 0) {
            return true;
        } else {
            return false;
        }
    };

    CodeCell.prototype.at_bottom = function () {
        var cursor = this.code_mirror.getCursor();
        if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
            return true;
        } else {
            return false;
        }
    };

    CodeCell.prototype.clear_output = function (stdout, stderr, other) {
        this.output_area.clear_output(stdout, stderr, other);
    };

    // JSON serialization

    CodeCell.prototype.fromJSON = function (data) {
        IPython.Cell.prototype.fromJSON.apply(this, arguments);
        if (data.cell_type === 'code') {
            if (data.input !== undefined) {
                this.set_text(data.input);
                // make this value the starting point, so that we can only undo
                // to this state, instead of a blank cell
                this.code_mirror.clearHistory();
            }
            if (data.prompt_number !== undefined) {
                this.set_input_prompt(data.prompt_number);
            } else {
                this.set_input_prompt();
            };
            this.output_area.fromJSON(data.outputs);
            if (data.collapsed !== undefined) {
                if (data.collapsed) {
                    this.collapse();
                } else {
                    this.expand();
                };
            };
        };
    };

    CodeCell.prototype.toJSON = function () {
        var data = IPython.Cell.prototype.toJSON.apply(this);
        data.input = this.get_text();
        data.cell_type = 'code';
        if (this.input_prompt_number) {
            data.prompt_number = this.input_prompt_number;
        };
        var outputs = this.output_area.toJSON();
        data.outputs = outputs;
        data.language = 'python';
        data.collapsed = this.collapsed;
        return data;
    };

    IPython.CodeCell = CodeCell;

    return IPython;
}(IPython));
<commit_msg>add ability to create continuation prompt<commit_after>//----------------------------------------------------------------------------
//  Copyright (C) 2008-2011  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

//============================================================================
// CodeCell
//============================================================================

var IPython = (function (IPython) {
    "use strict";

    var utils = IPython.utils;
    var key   = IPython.utils.keycodes;

    var CodeCell = function (kernel) {
        // The kernel doesn't have to be set at creation time, in that case
        // it will be null and set_kernel has to be called later.
        this.kernel = kernel || null;
        this.code_mirror = null;
        this.input_prompt_number = null;
        this.tooltip_on_tab = true;
        this.collapsed = false;
        IPython.Cell.apply(this, arguments);
    };

    CodeCell.prototype = new IPython.Cell();

    CodeCell.prototype.create_element = function () {
        var cell =  $('

').addClass('cell border-box-sizing code_cell vbox');
        cell.attr('tabindex','2');
        var input = $('

').addClass('input hbox');
        input.append($('
').addClass('prompt input_prompt'));
        var input_area = $('
').addClass('input_area box-flex1');
        this.code_mirror = CodeMirror(input_area.get(0), {
            indentUnit : 4,
            mode: 'python',
            theme: 'ipython',
            readOnly: this.read_only,
            onUpdate: $.proxy(function(){this.set_input_prompt()},this),
            extraKeys: {"Tab": "indentMore","Shift-Tab" : "indentLess",'Backspace':"delSpaceToPrevTabStop"},
            onKeyEvent: $.proxy(this.handle_codemirror_keyevent,this)
        });
        input.append(input_area);
        var output = $('

');
        cell.append(input).append(output);
        this.element = cell;
        this.output_area = new IPython.OutputArea(output, true);

        // construct a completer only if class exist
        // otherwise no print view
        if (IPython.Completer !== undefined)
        {
            this.completer = new IPython.Completer(this);
        }
    };

    CodeCell.prototype.handle_codemirror_keyevent = function (editor, event) {
        // This method gets called in CodeMirror's onKeyDown/onKeyPress
        // handlers and is used to provide custom key handling. Its return
        // value is used to determine if CodeMirror should ignore the event:
        // true = ignore, false = don't ignore.

        if (this.read_only){
            return false;
        }

        var that = this;
        // whatever key is pressed, first, cancel the tooltip request before
        // they are sent, and remove tooltip if any, except for tab again
        if (event.type === 'keydown' && event.which != key.TAB ) {
            IPython.tooltip.remove_and_cancel_tooltip();
        };

        var cur = editor.getCursor();

        if (event.keyCode === key.ENTER && (event.shiftKey || event.ctrlKey)) {
            // Always ignore shift-enter in CodeMirror as we handle it.
            return true;
        } else if (event.which === 40 && event.type === 'keypress' && IPython.tooltip.time_before_tooltip >= 0) {
            // triger on keypress (!) otherwise inconsistent event.which depending on plateform
            // browser and keyboard layout !
            // Pressing '(' , request tooltip, don't forget to reappend it
            IPython.tooltip.pending(that);
        } else if (event.which === key.UPARROW && event.type === 'keydown') {
            // If we are not at the top, let CM handle the up arrow and
            // prevent the global keydown handler from handling it.
            if (!that.at_top()) {
                event.stop();
                return false;
            } else {
                return true;
            };
        } else if (event.which === key.ESC) {
            IPython.tooltip.remove_and_cancel_tooltip(true);
            return true;
        } else if (event.which === key.DOWNARROW && event.type === 'keydown') {
            // If we are not at the bottom, let CM handle the down arrow and
            // prevent the global keydown handler from handling it.
            if (!that.at_bottom()) {
                event.stop();
                return false;
            } else {
                return true;
            };
        } else if (event.keyCode === key.TAB && event.type == 'keydown') {
            // Tab completion.
            //Do not trim here because of tooltip
            var pre_cursor = editor.getRange({line:cur.line,ch:0},cur);
            if (pre_cursor.trim() === "") {
                // Don't autocomplete if the part of the line before the cursor
                // is empty.  In this case, let CodeMirror handle indentation.
                return false;
            } else if ((pre_cursor.substr(-1) === "("|| pre_cursor.substr(-1) === " ") && that.tooltip_on_tab ) {
                IPython.tooltip.request(that);
                // Prevent the event from bubbling up.
                event.stop();
                // Prevent CodeMirror from handling the tab.
                return true;
            } else {
                event.stop();
                this.completer.startCompletion();
                return true;
            };
        } else {
            // keypress/keyup also trigger on TAB press, and we don't want to
            // use those to disable tab completion.
            return false;
        };
        return false;
    };

    // Kernel related calls.

    CodeCell.prototype.set_kernel = function (kernel) {
        this.kernel = kernel;
    }

    CodeCell.prototype.execute = function () {
        this.output_area.clear_output(true, true, true);
        this.set_input_prompt('*');
        this.element.addClass("running");
        var callbacks = {
            'execute_reply': $.proxy(this._handle_execute_reply, this),
            'output': $.proxy(this.output_area.handle_output, this.output_area),
            'clear_output': $.proxy(this.output_area.handle_clear_output, this.output_area),
            'set_next_input': $.proxy(this._handle_set_next_input, this)
        };
        var msg_id = this.kernel.execute(this.get_text(), callbacks, {silent: false});
    };

    CodeCell.prototype._handle_execute_reply = function (content) {
        this.set_input_prompt(content.execution_count);
        this.element.removeClass("running");
        $([IPython.events]).trigger('set_dirty.Notebook', {'value': true});
    }

    CodeCell.prototype._handle_set_next_input = function (text) {
        var data = {'cell': this, 'text': text}
        $([IPython.events]).trigger('set_next_input.Notebook', data);
    }

    // Basic cell manipulation.

    CodeCell.prototype.select = function () {
        IPython.Cell.prototype.select.apply(this);
        this.code_mirror.refresh();
        this.code_mirror.focus();
        // We used to need an additional refresh() after the focus, but
        // it appears that this has been fixed in CM. This bug would show
        // up on FF when a newly loaded markdown cell was edited.
    };

    CodeCell.prototype.select_all = function () {
        var start = {line: 0, ch: 0};
        var nlines = this.code_mirror.lineCount();
        var last_line = this.code_mirror.getLine(nlines-1);
        var end = {line: nlines-1, ch: last_line.length};
        this.code_mirror.setSelection(start, end);
    };

    CodeCell.prototype.collapse = function () {
        this.collapsed = true;
        this.output_area.collapse();
    };

    CodeCell.prototype.expand = function () {
        this.collapsed = false;
        this.output_area.expand();
    };

    CodeCell.prototype.toggle_output = function () {
        this.collapsed = Boolean(1 - this.collapsed);
        this.output_area.toggle_output();
    };

    CodeCell.prototype.toggle_output_scroll = function () {
    this.output_area.toggle_scroll();
    };

    CodeCell.input_prompt_classical = function (prompt_value, lines_number) {
        var ns = prompt_value || " ";
        return 'In [' + ns + ']:'
    };

    CodeCell.input_prompt_continuation = function (prompt_value, lines_number) {
        var html = [CodeCell.input_prompt_classical(prompt_value, lines_number)];
        for(var i=1; i < lines_number; i++){html.push(['...:'])};
        return html.join('
')
    };

    CodeCell.input_prompt_function = CodeCell.input_prompt_classical;

    CodeCell.prototype.set_input_prompt = function (number) {
        var nline = 1
        if( this.code_mirror != undefined) {
           nline = this.code_mirror.lineCount();
        }
        if (number){
            this.input_prompt_number = number;
        }
        var prompt_html = CodeCell.input_prompt_function(this.input_prompt_number, nline);
        this.element.find('div.input_prompt').html(prompt_html);
    };

    CodeCell.prototype.clear_input = function () {
        this.code_mirror.setValue('');
    };

    CodeCell.prototype.get_text = function () {
        return this.code_mirror.getValue();
    };

    CodeCell.prototype.set_text = function (code) {
        return this.code_mirror.setValue(code);
    };

    CodeCell.prototype.at_top = function () {
        var cursor = this.code_mirror.getCursor();
        if (cursor.line === 0 && cursor.ch === 0) {
            return true;
        } else {
            return false;
        }
    };

    CodeCell.prototype.at_bottom = function () {
        var cursor = this.code_mirror.getCursor();
        if (cursor.line === (this.code_mirror.lineCount()-1) && cursor.ch === this.code_mirror.getLine(cursor.line).length) {
            return true;
        } else {
            return false;
        }
    };

    CodeCell.prototype.clear_output = function (stdout, stderr, other) {
        this.output_area.clear_output(stdout, stderr, other);
    };

    // JSON serialization

    CodeCell.prototype.fromJSON = function (data) {
        IPython.Cell.prototype.fromJSON.apply(this, arguments);
        if (data.cell_type === 'code') {
            if (data.input !== undefined) {
                this.set_text(data.input);
                // make this value the starting point, so that we can only undo
                // to this state, instead of a blank cell
                this.code_mirror.clearHistory();
            }
            if (data.prompt_number !== undefined) {
                this.set_input_prompt(data.prompt_number);
            } else {
                this.set_input_prompt();
            };
            this.output_area.fromJSON(data.outputs);
            if (data.collapsed !== undefined) {
                if (data.collapsed) {
                    this.collapse();
                } else {
                    this.expand();
                };
            };
        };
    };

    CodeCell.prototype.toJSON = function () {
        var data = IPython.Cell.prototype.toJSON.apply(this);
        data.input = this.get_text();
        data.cell_type = 'code';
        if (this.input_prompt_number) {
            data.prompt_number = this.input_prompt_number;
        };
        var outputs = this.output_area.toJSON();
        data.outputs = outputs;
        data.language = 'python';
        data.collapsed = this.collapsed;
        return data;
    };

    IPython.CodeCell = CodeCell;

    return IPython;
}(IPython));
<|endoftext|>


<commit_before>(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(["jquery", "knockout"], factory);
	} else {
		// Browser globals
		factory(jQuery, ko);
	}
}(this, function ($, ko) {
	ko.bindingHandlers.inlineConfirm = {
		init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
			var span = $('').addClass('button__text');
			span.appendTo($(element));

			$(element).click(function () {
				var textValues = ko.utils.unwrapObservable(valueAccessor());
				var submitFunction = ko.utils.unwrapObservable(allBindingsAccessor().submitFunction);
				var timeOut = ko.utils.unwrapObservable(allBindingsAccessor().confirmTimeout) || 3000;
				var disabled = ko.utils.unwrapObservable(allBindingsAccessor().disable);

				if (!disabled) {
					var stepIndex = textValues.indexOf(span.text());
					if (stepIndex < textValues.length - 2) {
						element.resetTimer = setTimeout(function () {
							span.text(textValues[stepIndex]);
						}, timeOut);

						span.text(textValues[stepIndex + 1]);
					}
					else if (stepIndex === textValues.length - 2) {

						if (element.resetTimer) {
							clearTimeout(element.resetTimer);
							element.resetTimer = null;
						}

						$(element).addClass("is-busy");
						span.text(textValues[textValues.length - 1]);

						if (submitFunction) {
							if (typeof (submitFunction) !== 'function') {
								throw new typeError('expected typeof "submitFunction" to be "function"');
							}
							submitFunction.call(ko.dataFor(this), ko.dataFor(this));
						}
					}
				}

				//let the click continue
				return !submitFunction && !disabled;
			});
		},
		update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
			var span = $(element).find('.button__text');
			span.text(ko.utils.unwrapObservable(valueAccessor())[0]);
			$(element).removeClass("is-busy");
		}
	};
}));
<commit_msg>Adding bootstrap danger class only on confirm.<commit_after>(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define(["jquery", "knockout"], factory);
	} else {
		// Browser globals
		factory(jQuery, ko);
	}
}(this, function ($, ko) {
	ko.bindingHandlers.inlineConfirm = {
		init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
			var span = $('').addClass('button__text');
			span.appendTo($(element));

			$(element).click(function () {
				var textValues = ko.utils.unwrapObservable(valueAccessor());
				var submitFunction = ko.utils.unwrapObservable(allBindingsAccessor().submitFunction);
				var timeOut = ko.utils.unwrapObservable(allBindingsAccessor().confirmTimeout) || 3000;
				var disabled = ko.utils.unwrapObservable(allBindingsAccessor().disable);

				if (!disabled) {
					var stepIndex = textValues.indexOf(span.text());
					if (stepIndex < textValues.length - 2) {
						element.resetTimer = setTimeout(function () {
							span.text(textValues[stepIndex]);
							//Remove the bootstrap danger class.
							$(element).removeClass("btn-danger");
						}, timeOut);

						span.text(textValues[stepIndex + 1]);
						//Check if the element is bootstrapped. If so, add the bootstrap danger class.
						if ($(element).attr("class").toLowerCase().indexOf("btn-") >= 0) {
							$(element).addClass("btn-danger");
						}
					}
					else if (stepIndex === textValues.length - 2) {

						if (element.resetTimer) {
							clearTimeout(element.resetTimer);
							element.resetTimer = null;
						}

						$(element).addClass("is-busy");
						//Remove the bootstrap danger class.
						$(element).removeClass("btn-danger");
						span.text(textValues[textValues.length - 1]);

						if (submitFunction) {
							if (typeof (submitFunction) !== 'function') {
								throw new typeError('expected typeof "submitFunction" to be "function"');
							}
							submitFunction.call(ko.dataFor(this), ko.dataFor(this));
							//Reset the button after the function has finished executing.
							span.text(textValues[0]);
						}
					}
				}

				//let the click continue
				return !submitFunction && !disabled;
			});
		},
		update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
			var span = $(element).find('.button__text');
			span.text(ko.utils.unwrapObservable(valueAccessor())[0]);
			$(element).removeClass("is-busy");
		}
	};
}));

function ViewModel() {
  this.execute = function(){
    alert("executed");
  };
}

ko.applyBindings(new ViewModel());
<|endoftext|>


<commit_before>import FULLSTOP_BASE_URL from 'FULLSTOP_BASE_URL';
// import {createAction} from 'redux-actions';
// import Types from './fullstop-types';
import request from 'common/src/superagent';
import {Provider, RequestConfig, saveRoute} from 'common/src/oauth-provider';
import {Actions} from 'flummox';

function fetchViolations(params) {
    return request
            .get(`${FULLSTOP_BASE_URL}/violations`)
            .accept('json')
            .query({
                accounts: params.accounts,
                size: params.size || 10,
                from: params.from ? params.from.toISOString() : '',
                to: (params.to || new Date()).toISOString(),
                page: params.page || 0,
                checked: params.showResolved && !params.showUnresolved ?
                            true :
                            !params.showResolved && params.showUnresolved ?
                                false :
                                undefined
            })
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => [res.body, res.body.content]);
}

function fetchViolation(violationId) {
    return request
            .get(`${FULLSTOP_BASE_URL}/violations/${violationId}`)
            .accept('json')
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => res.body)
            .catch(e => {
                e.violationId = violationId;
                throw e;
            });
}

function resolveViolation(violationId, message) {
    return request
            .post(`${FULLSTOP_BASE_URL}/violations/${violationId}/resolution`)
            .accept('json')
            .type('text/plain')
            .send(message)
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => res.body);
}

function fetchViolationTypes() {
    return request
            .get(`${FULLSTOP_BASE_URL}/violation-types`)
            .accept('json')
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => res.body);
}

function fetchViolationCount(params) {
    return request
            .get(`${FULLSTOP_BASE_URL}/violation-count`)
            .query({
                accounts: params.accounts,
                to: params.to ? params.to.toISOString() : (new Date()).toISOString(),
                from: params.from ? params.from.toISOString() : ''
            })
            .accept('json')
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => res.body);
}

function fetchViolationCountIn(account, params) {
    return request
            .get(`${FULLSTOP_BASE_URL}/violation-count/${account}`)
            .query({
                to: (params.to || new Date()).toISOString(),
                from: params.from ? params.from.toISOString() : '',
                resolved: params.showResolved && !params.showUnresolved ?
                            true :
                            !params.showResolved && params.showUnresolved ?
                                false :
                                undefined
            })
            .accept('json')
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => [account, res.body]);
}

function deleteViolations() {
    return true;
}

function updateSearchParams(params) {
    return params;
}

// for now wrap in flummox actions
export default class FullstopActions extends Actions {
    resolveViolation() {
        return resolveViolation.apply(this, arguments);
    }

    fetchViolation() {
        return fetchViolation.apply(this, arguments);
    }

    fetchViolations() {
        return fetchViolations.apply(this, arguments);
    }

    fetchViolationTypes() {
        return fetchViolationTypes();
    }

    fetchViolationCount() {
        return fetchViolationCount.apply(this, arguments);
    }

    fetchViolationCountIn(account, params) {
        return fetchViolationCountIn(account, params);
    }

    deleteViolations() {
        return deleteViolations();
    }

    updateSearchParams(params) {
        return updateSearchParams(params);
    }
}

/* this is for later, when all is redux */

// let fetchViolation = createAction(Types.FETCH_VIOLATION, _fetchViolation),
//     fetchViolations = createAction(Types.FETCH_VIOLATIONS, _fetchViolations),
//     resolveViolation = createAction(Types.RESOLVE_VIOLATION, _resolveViolation),
//     deleteViolations = createAction(Types.DELETE_VIOLATIONS);

export {
    fetchViolations,
    fetchViolation,
    fetchViolationTypes,
    fetchViolationCount,
    fetchViolationCountIn,
    resolveViolation,
    deleteViolations,
    updateSearchParams
};
<commit_msg>#330 use resolve filter for violation count<commit_after>import FULLSTOP_BASE_URL from 'FULLSTOP_BASE_URL';
// import {createAction} from 'redux-actions';
// import Types from './fullstop-types';
import request from 'common/src/superagent';
import {Provider, RequestConfig, saveRoute} from 'common/src/oauth-provider';
import {Actions} from 'flummox';

function fetchViolations(params) {
    return request
            .get(`${FULLSTOP_BASE_URL}/violations`)
            .accept('json')
            .query({
                accounts: params.accounts,
                size: params.size || 10,
                from: params.from ? params.from.toISOString() : '',
                to: (params.to || new Date()).toISOString(),
                page: params.page || 0,
                checked: params.showResolved && !params.showUnresolved ?
                            true :
                            !params.showResolved && params.showUnresolved ?
                                false :
                                undefined
            })
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => [res.body, res.body.content]);
}

function fetchViolation(violationId) {
    return request
            .get(`${FULLSTOP_BASE_URL}/violations/${violationId}`)
            .accept('json')
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => res.body)
            .catch(e => {
                e.violationId = violationId;
                throw e;
            });
}

function resolveViolation(violationId, message) {
    return request
            .post(`${FULLSTOP_BASE_URL}/violations/${violationId}/resolution`)
            .accept('json')
            .type('text/plain')
            .send(message)
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => res.body);
}

function fetchViolationTypes() {
    return request
            .get(`${FULLSTOP_BASE_URL}/violation-types`)
            .accept('json')
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => res.body);
}

function fetchViolationCount(params) {
    return request
            .get(`${FULLSTOP_BASE_URL}/violation-count`)
            .query({
                accounts: params.accounts,
                to: params.to ? params.to.toISOString() : (new Date()).toISOString(),
                from: params.from ? params.from.toISOString() : '',
                resolved: params.showResolved && !params.showUnresolved ?
                            true :
                            !params.showResolved && params.showUnresolved ?
                                false :
                                undefined
            })
            .accept('json')
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => res.body);
}

function fetchViolationCountIn(account, params) {
    return request
            .get(`${FULLSTOP_BASE_URL}/violation-count/${account}`)
            .query({
                to: (params.to || new Date()).toISOString(),
                from: params.from ? params.from.toISOString() : '',
                resolved: params.showResolved && !params.showUnresolved ?
                            true :
                            !params.showResolved && params.showUnresolved ?
                                false :
                                undefined
            })
            .accept('json')
            .oauth(Provider, RequestConfig)
            .exec(saveRoute)
            .then(res => [account, res.body]);
}

function deleteViolations() {
    return true;
}

function updateSearchParams(params) {
    return params;
}

// for now wrap in flummox actions
export default class FullstopActions extends Actions {
    resolveViolation() {
        return resolveViolation.apply(this, arguments);
    }

    fetchViolation() {
        return fetchViolation.apply(this, arguments);
    }

    fetchViolations() {
        return fetchViolations.apply(this, arguments);
    }

    fetchViolationTypes() {
        return fetchViolationTypes();
    }

    fetchViolationCount() {
        return fetchViolationCount.apply(this, arguments);
    }

    fetchViolationCountIn(account, params) {
        return fetchViolationCountIn(account, params);
    }

    deleteViolations() {
        return deleteViolations();
    }

    updateSearchParams(params) {
        return updateSearchParams(params);
    }
}

/* this is for later, when all is redux */

// let fetchViolation = createAction(Types.FETCH_VIOLATION, _fetchViolation),
//     fetchViolations = createAction(Types.FETCH_VIOLATIONS, _fetchViolations),
//     resolveViolation = createAction(Types.RESOLVE_VIOLATION, _resolveViolation),
//     deleteViolations = createAction(Types.DELETE_VIOLATIONS);

export {
    fetchViolations,
    fetchViolation,
    fetchViolationTypes,
    fetchViolationCount,
    fetchViolationCountIn,
    resolveViolation,
    deleteViolations,
    updateSearchParams
};
<|endoftext|>


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

	mare.views.ChildDetails = Backbone.View.extend({
		// This view controls the content of the modal window, create an element to insert into the modal
		tagName: 'section',
		// Give the container for our view a class we can hook into
  		className: 'child-details',

		initialize: function initialize() {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;
			// Create a hook to access the gallery template
			var html = $('#child-details-template').html();
			// Compile the template to be used during rendering/repainting the gallery
			this.template = Handlebars.compile(html);
			// Initialize the details modal once we've fetched the basic child data, this is needed because the details will be appended to the same collection
			mare.promises.childrenDataLoaded.done(function() {
				view.collection = mare.collections.children;
				// Bind event handler for when child details are returned
				view.on('child-details-loaded', view.render);
			});
		},

		bindEvents: function bindEvents() {
  			$('.modal__close').click(this.closeModal);
			$('.profile-navigation__previous').click(this.handleNavClick);
			$('.profile-navigation__next').click(this.handleNavClick);
		},

		unbindEvents: function unbindEvents() {
			$('.modal__close').unbind('click');
			$('.profile-navigation__previous').unbind('click');
			$('.profile-navigation__next').unbind('click');
		},

		render: function render(childModel) {
			// Depending on the order of the collection, the next and previous differs per rendering
			this.setNavigation(childModel);
			// Pass the child model to through the template we stored during initialization
			var html = this.template(childModel.toJSON());
			this.$el.html(html);
			// Render the contents area and tabs
			$('.modal-container__contents').html(this.$el);
			// Remove the loading indicator and display the details content
			$('.modal-container__loading').fadeOut(function() {
				$('.modal-container__contents').fadeIn();
			});
			// Set a data attribute with the displayed child's id for use in next/prev navigation
			this.$el.attr('data-registration-number', childModel.get('registrationNumber'));
			// Set up the modal tab click events
			this.initializeModalTabs();
			// Bind click events for the newly rendered elements
			this.bindEvents();

		},

		setNavigation: function setNavigation(childModel) {
			// Get the index of the current child model in the children collection
			var childIndex = this.collection.indexOf(childModel);
			// Check to see if there are children to navigate to before and after the currently displayed child
			var hasPrevious = childIndex > 0;
			var hasNext = childIndex !== this.collection.length - 1;
			// Set the index of the previous/next child for easy access in the collection
			var previousIndex = hasPrevious ? childIndex - 1 : undefined;
			var nextIndex = hasNext ? childIndex + 1 : undefined;
			// Set whether there are previous and next children, as well as their indices, so we have the information during rendering
			childModel.set('hasPrevious', hasPrevious);
			childModel.set('hasNext', hasNext);
			childModel.set('previousIndex', previousIndex);
			childModel.set('nextIndex', nextIndex);
		},

		getChildByRegistrationNumber: function getChildByRegistrationNumber(registrationNumber) {
			// Find the child with the matching registration number and store it in childModel
			var childModel = this.collection.find(function(child) {
				return child.get('registrationNumber') === registrationNumber;
			});
			// Return the matching child model
			return childModel;
		},

		getChildByIndex: function getChildByIndex(index) {
			// Fetch the child at the specified index in the children collection
			return this.collection.at(index);

		},

		/* When a child card is clicked, display detailed information for that child in a modal window */
		handleGalleryClick: function handleGalleryClick(event) {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;

			var selectedChild		= $(event.currentTarget),
				registrationNumber	= selectedChild.data('registration-number'),
				childModel			= this.getChildByRegistrationNumber(registrationNumber);
			// Open the modal immediately with a loading indicator to keep the site feeling snappy
			this.openModal();
			// Fetch the child details information
			this.getDetails(childModel);
		},

		handleNavClick: function handleNavClick(event) {
			var selectedChild = $(event.currentTarget),
				index = selectedChild.data('child-index');
			// This event is called from a click event so the view context is lost, we need to explicitly call all functions
			var child = mare.views.childDetails.getChildByIndex(index);
			// Fade displayed child details if any are shown, and display the loading indicator
			$('.modal-container__contents').fadeOut(function() {
				$('.modal-container__loading').fadeIn(function() {
					mare.views.childDetails.getDetails(child);
				});
			});
		},

		/* Make a call to fetch data for the current child to show detailed information for */
		getDetails: function getDetails(childModel) {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;
			// Submit a request to the service layer to fetch child data if we don't have it
			if(!childModel.get('hasDetails')) {
				$.ajax({
					dataType: 'json',
					url: '/services/get-child-details',
					type: 'POST',
					data: {
						registrationNumber: childModel.get('registrationNumber')
					}
				}).done(function(childDetails) {
					// Append the new fields to the child model and set a flag so fetch the same child information a second time
					childModel.set(childDetails);
					childModel.set('hasDetails', true);
					// Emit an event when we have new child details to render
					view.trigger('child-details-loaded', childModel);

				}).fail(function(err) {
					// TODO: Show an error message to the user
					console.log(err);
				});
			} else {
				// We already have the child details but still want to show the child so announce that we have the child details
				view.trigger('child-details-loaded', childModel);
			}
		},

		/* Open the modal container */
		// TODO: This should be moved to a more appropriate location that's accessible to all pages
		openModal: function openModal() {
			$('.modal__background').fadeIn();
			$('.modal-container__contents').hide();
			$('.modal-container__loading').show();
			$('.modal__container').fadeIn();

			mare.utils.disablePageScrolling();
		},

		/* Close the modal container */
		// TODO: This should be moved to a more appropriate location that's accessible to all pages
		closeModal: function closeModal() {
			$('.modal__background').fadeOut();
			$('.modal__container').fadeOut();

			mare.utils.enablePageScrolling();
			// This event is called from a click event so the view context is lost, we need to explicitly call all functions
			mare.views.childDetails.clearModalContents();
		},

		/* Clear out the current contents of the modal */
		// TODO: This should be moved to a more appropriate location that's accessible to all pages
		clearModalContents: function clearModalContents() {
			$('.modal-container__contents').html('');
		},

		/* initialize tabbing within the modal window */
		// TOOD: consider making this more generic and pulling it into a location that's accessible to all pages
		initializeModalTabs: function initializeModalTabs() {
			// DOM cache any commonly used elements to improve performance
			// TODO: possilby pull these and all other elements used regulary into the initialize function prefixed with this
			var $profileTabs = $('.profile-tabs__tab'),
				$selectedTab = $('.profile-tabs__tab--selected'),
				$profileTabContents = $('.profile-tab__contents'),
				$selectedTabContents = $('.profile-tab__contents--selected')

			$profileTabs.removeClass('profile-tabs__tab--selected');
			$profileTabs.first().addClass('profile-tabs__tab--selected');

			$profileTabContents.removeClass('profile-tab__contents--selected');
			$profileTabContents.first().addClass('profile-tab__contents--selected');

			$profileTabs.on('click', function() {
				if($(this).hasClass('profile-tabs__tab--selected')) {
					return;
				}

				var selectedContentType = $(this).data('tab');

				$selectedTab.removeClass('profile-tabs__tab--selected');
				$(this).addClass('profile-tabs__tab--selected');

				$selectedTabContents.removeClass('profile-tab__contents--selected');
				$('[data-contents=' + selectedContentType + ']').addClass('profile-tab__contents--selected');

			});
		}

	});
})();<commit_msg>gallery page - fix tab navigation<commit_after>(function () {
	'use strict';

	mare.views.ChildDetails = Backbone.View.extend({
		// This view controls the content of the modal window, create an element to insert into the modal
		tagName: 'section',
		// Give the container for our view a class we can hook into
  		className: 'child-details',

		initialize: function initialize() {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;
			// Create a hook to access the gallery template
			var html = $('#child-details-template').html();
			// Compile the template to be used during rendering/repainting the gallery
			this.template = Handlebars.compile(html);
			// Initialize the details modal once we've fetched the basic child data, this is needed because the details will be appended to the same collection
			mare.promises.childrenDataLoaded.done(function() {
				view.collection = mare.collections.children;
				// Bind event handler for when child details are returned
				view.on('child-details-loaded', view.render);
			});
		},

		bindEvents: function bindEvents() {
  			$('.modal__close').click(this.closeModal);
			$('.profile-navigation__previous').click(this.handleNavClick);
			$('.profile-navigation__next').click(this.handleNavClick);
		},

		unbindEvents: function unbindEvents() {
			$('.modal__close').unbind('click');
			$('.profile-navigation__previous').unbind('click');
			$('.profile-navigation__next').unbind('click');
			$('.profile-tabs__tab').unbind('click');
		},

		render: function render(childModel) {
			// Depending on the order of the collection, the next and previous differs per rendering
			this.setNavigation(childModel);
			// Pass the child model to through the template we stored during initialization
			var html = this.template(childModel.toJSON());
			this.$el.html(html);
			// Render the contents area and tabs
			$('.modal-container__contents').html(this.$el);
			// Remove the loading indicator and display the details content
			$('.modal-container__loading').fadeOut(function() {
				$('.modal-container__contents').fadeIn();
			});
			// Set a data attribute with the displayed child's id for use in next/prev navigation
			this.$el.attr('data-registration-number', childModel.get('registrationNumber'));
			// Set up the modal tab click events
			this.initializeModalTabs();
			// Bind click events for the newly rendered elements
			this.bindEvents();

		},

		setNavigation: function setNavigation(childModel) {
			// Get the index of the current child model in the children collection
			var childIndex = this.collection.indexOf(childModel);
			// Check to see if there are children to navigate to before and after the currently displayed child
			var hasPrevious = childIndex > 0;
			var hasNext = childIndex !== this.collection.length - 1;
			// Set the index of the previous/next child for easy access in the collection
			var previousIndex = hasPrevious ? childIndex - 1 : undefined;
			var nextIndex = hasNext ? childIndex + 1 : undefined;
			// Set whether there are previous and next children, as well as their indices, so we have the information during rendering
			childModel.set('hasPrevious', hasPrevious);
			childModel.set('hasNext', hasNext);
			childModel.set('previousIndex', previousIndex);
			childModel.set('nextIndex', nextIndex);
		},

		getChildByRegistrationNumber: function getChildByRegistrationNumber(registrationNumber) {
			// Find the child with the matching registration number and store it in childModel
			var childModel = this.collection.find(function(child) {
				return child.get('registrationNumber') === registrationNumber;
			});
			// Return the matching child model
			return childModel;
		},

		getChildByIndex: function getChildByIndex(index) {
			// Fetch the child at the specified index in the children collection
			return this.collection.at(index);

		},

		/* When a child card is clicked, display detailed information for that child in a modal window */
		handleGalleryClick: function handleGalleryClick(event) {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;

			var selectedChild		= $(event.currentTarget),
				registrationNumber	= selectedChild.data('registration-number'),
				childModel			= this.getChildByRegistrationNumber(registrationNumber);
			// Open the modal immediately with a loading indicator to keep the site feeling snappy
			this.openModal();
			// Fetch the child details information
			this.getDetails(childModel);
		},

		handleNavClick: function handleNavClick(event) {
			// This event is called from a click event so the view context is lost, we need to explicitly call all functions
			mare.views.childDetails.unbindEvents();

			var selectedChild = $(event.currentTarget),
				index = selectedChild.data('child-index');

			var child = mare.views.childDetails.getChildByIndex(index);
			// Fade displayed child details if any are shown, and display the loading indicator
			$('.modal-container__contents').fadeOut(function() {
				$('.modal-container__loading').fadeIn(function() {
					mare.views.childDetails.getDetails(child);
				});
			});
		},

		/* Make a call to fetch data for the current child to show detailed information for */
		getDetails: function getDetails(childModel) {
			// Store a reference to this for insde callbacks where context is lost
			var view = this;
			// Submit a request to the service layer to fetch child data if we don't have it
			if(!childModel.get('hasDetails')) {
				$.ajax({
					dataType: 'json',
					url: '/services/get-child-details',
					type: 'POST',
					data: {
						registrationNumber: childModel.get('registrationNumber')
					}
				}).done(function(childDetails) {
					// Append the new fields to the child model and set a flag so fetch the same child information a second time
					childModel.set(childDetails);
					childModel.set('hasDetails', true);
					// Emit an event when we have new child details to render
					view.trigger('child-details-loaded', childModel);

				}).fail(function(err) {
					// TODO: Show an error message to the user
					console.log(err);
				});
			} else {
				// We already have the child details but still want to show the child so announce that we have the child details
				view.trigger('child-details-loaded', childModel);
			}
		},

		/* Open the modal container */
		// TODO: This should be moved to a more appropriate location that's accessible to all pages
		openModal: function openModal() {
			$('.modal__background').fadeIn();
			$('.modal-container__contents').hide();
			$('.modal-container__loading').show();
			$('.modal__container').fadeIn();

			mare.utils.disablePageScrolling();
		},

		/* Close the modal container */
		// TODO: This should be moved to a more appropriate location that's accessible to all pages
		closeModal: function closeModal() {
			// This event is called from a click event so the view context is lost, we need to explicitly call all functions
			mare.views.childDetails.unbindEvents();

			$('.modal__background').fadeOut();
			$('.modal__container').fadeOut();

			mare.utils.enablePageScrolling();
			// This event is called from a click event so the view context is lost, we need to explicitly call all functions
			mare.views.childDetails.clearModalContents();
		},

		/* Clear out the current contents of the modal */
		// TODO: This should be moved to a more appropriate location that's accessible to all pages
		clearModalContents: function clearModalContents() {
			$('.modal-container__contents').html('');
		},

		/* initialize tabbing within the modal window */
		// TOOD: consider making this more generic and pulling it into a location that's accessible to all pages
		initializeModalTabs: function initializeModalTabs() {
			// DOM cache any commonly used elements to improve performance
			var $profileTabs = $('.profile-tabs__tab')

			$profileTabs.on('click', function() {
				// DOM cache any commonly used elements to improve performance
				var $selectedTab			= $('.profile-tabs__tab--selected'),
					$selectedTabContents	= $('.profile-tab__contents--selected');

				if($(this).hasClass('profile-tabs__tab--selected')) {
					return;
				}

				var selectedContentType = $(this).data('tab');

				$selectedTab.removeClass('profile-tabs__tab--selected');
				$(this).addClass('profile-tabs__tab--selected');

				$selectedTabContents.removeClass('profile-tab__contents--selected');
				$('[data-contents=' + selectedContentType + ']').addClass('profile-tab__contents--selected');

			});
		}

	});
})();<|endoftext|>


<commit_before>/*
 * Filename: index.js
 */
var self = this; // Set the context locally, for access protection
/**
 * Create a new System that let users create sub-system.
 * @return {System}
 */
function System() {
  console.log('systems system - System called');
  // add key value pairs here
  // self's are not directly publicly accessible, only through their public method(s)
  // use self's here for protection from direct access
  self._filename = ''; // Will be set
  self._filepath = ''; // Will be set
  self._proxies = {}; // Will be set
  self._title = 'System'; // Default
}

System.prototype.proxies = function() {
  return self._proxies;
}

System.prototype.setproxies = function(fnOrValue) {
  console.log('systems system setproxies() called');
  self._proxies = fnOrValue;
}

System.prototype.filename = function() {
  console.log('systems system filename() called');
  return self._filename;
}

System.prototype.setfilename = function(fnOrValue) {
  self._filename = fnOrValue;
}

System.prototype.filepath = function() {
  console.log('systems system filepath() called');
  return self._filepath;
}

System.prototype.setfilepath = function(fnOrValue) {
  self._filepath = fnOrValue;
}

System.prototype.title = function() {
  console.log('systems system title() called');
  return self._title;
}

System.prototype.settitle = function(fnOrValue) {
  self._title = fnOrValue;
}

System.prototype.execute = function(arguments) {
  console.log('systems system execute - called');
  console.log('systems system execute - arguments: ', arguments); // WORKS!!
  // Required modules
  var _instructions = {};
  var instruction = {};
  var _proxies = require('../../proxies/proxies');

  console.log('systems system execute +++++++ CHECKPOINT 000')

  var _arguments = arguments;
  var _filename = this.filename();
  var _filepath = this.filepath();
  var _title = this.title();
  /*
   * ONLY ENDPOINTS OF _proxies ARE Promises, e.g. _proxies().proxy().libraries().library().path()
   * WE POSTPONE TO USE A Promise DOWN THE OBJECT HIERARCHY AS FAR DOWN AS FEASIBLE
   * UNTIL WE NEED THE Promise RESOLVED
   */
  console.log('systems system execute - _proxies: ', _proxies)
  var promise = _proxies().proxy().libraries().library().promise();
  var join = promise.join;
  // Start of the chain
  join(_proxies(), function(proxies) {
    console.log('systems system execute - proxies: ',
      proxies) // Works: Proxies {}

    return (proxies);
  }) /* EOF join proxies */
  .then(function(proxies) {

    console.log('systems system execute - documentation +++++++ CHECKPOINT 000')

    var _documentations = _proxies().proxy().documentations();
    _documentations.setproxies(_proxies);
    _documentations.setfilepath(_filepath);
    _documentations.setfilename(_filename);
    var _title = 'Documentations';
    var _linktitle = 'Documentation';
    var _document = 'documentation.html';
    var _directory = 'documentation';

    // START TEST AREA

    var _jsdom = _proxies().proxy().libraries().library().jsdom();
    console.log('systems system execute - documentation _jsdom: ', _jsdom)

    // END TEST AREA

    _documentations.append('<title>' + _title + '</title>'
      ,'
' + _title +
      '

 \
      ' + _linktitle + '

');

/*
    var _documentation = _documentations.documentation();

    console.log('systems system execute - documentation +++++++ CHECKPOINT 001')

    console.log('systems system execute - documentation: ',
      _documentation) // Works: Documentation {}
    //_documentation.setfilepath(_filepath); Gets set inside documentations
    //_documentations.setfilename(_filename); Gets set inside documentations
    var _title = 'Documentation';
    var _linktitle = 'UML';
    var _document = 'uml.html';
    var _directory = 'uml';

    console.log('systems system execute - documentation +++++++ CHECKPOINT 002')

    _documentation.append('<title>' + _title + '</title>'
      ,'
' + _title +
      '

 \
      ' + _linktitle + '

');

    console.log('systems system execute - documentation +++++++ CHECKPOINT 003')

*/
/*
    var _uml = _documentation.uml();

    console.log('systems system execute - documentation +++++++ CHECKPOINT 004')

    console.log('systems system execute - uml: ',
      _uml) // Works: UML {}
    //_uml.setfilepath(_filepath); Gets set inside documentation
    //_uml.setfilename(_filename); Gets set inside documentation
    var _title = 'UML';
    var _linktitle = 'Sequence Diagram';
    var _document = 'sequencediagram.html';
    var _directory = 'sequencediagram';

    console.log('systems system execute - documentation +++++++ CHECKPOINT 005')

    _uml.append('<title>' + _title + '</title>'
      ,'
' + _title +
      '

 \
      ' + _linktitle + '

');

*/
/*
    var _sequencediagram = _uml.sequencediagram();

    console.log('systems system execute - documentation +++++++ CHECKPOINT 006')

    console.log('systems system execute - sequencediagram: ',
      _sequencediagram) // Works: SequenceDiagram {}
    //_sequencediagram.setfilepath(_filepath); Gets set inside uml
    //_sequencediagram.setfilename(_filename); Gets set inside uml
    var _title = 'Sequence Diagram';
    var _linktitle = 'Foo';
    var _document = 'foo.html';
    var _directory = 'foo';

    console.log('systems system execute - documentation +++++++ CHECKPOINT 007')

    _sequencediagram.append('<title>' + _title + '</title>'
      ,'
' + _title +
      '

 \
      ' + _linktitle + '

');
*/

    var resourceForUuid = {};
    var layerForLayer = {};
    var instructionsForInstructions = {};
    var uuid = {};
    var additionalArgument = _arguments;
    var arrayOfPromises = [];
    /*
     * The value of arguments will be the optional additional command line arguments, e.g. a JSON file {uuid:1234}
     * Handle non-exception-throwing cases.
     * Neither JSON.parse(false) or JSON.parse(1234) throw errors,
     * hence the type-checking.
     * But JSON.parse(null) returns 'null', and typeof null === "object"
     * so we must check for that, too.
     */
    if (additionalArgument
      && typeof additionalArgument === 'object'
      && additionalArgument !== null) {
      /*
       * Now we have the object additionalArgument
       */
      console.log('systems system execute - additionalArgument: ',
        additionalArgument)
      console.log('systems system execute - additionalArgument.system: ',
        additionalArgument.system)
      /*
       * The additionalArgument.system is an Array of Objects
       * so we have to loop through the array.
       */
      console.log('systems system execute - additionalArgument.system.length: ',
          additionalArgument.system.length)

      for (var i = 0; i < additionalArgument.system.length; i++) {
        console.log('systems system execute - \
            additionalArgument.system[',i,']: ',
            additionalArgument.system[i])
        console.log('systems system execute - \
            additionalArgument.system[',i,'].uuid: ',
            additionalArgument.system[i].uuid)
        /* Get a resource, by comparing with the uuid */
        /*
         * Note: console.log('systems execute - resource: ', _proxies().proxy().resources().resource);
         * Returns: function () { return new ResourcesResource(); }
         * Note: console.log('systems execute - _proxies().proxy().resources().resource(): ',
         *         _proxies().proxy().resources().resource());
         * Returns: Resource {}
         * Note: console.log('systems execute - _proxies().proxy().resources().resource()._6e8bc430_9c3a_11d9_9669_0800200c9a66: ',
         *         _proxies().proxy().resources().resource()._6e8bc430_9c3a_11d9_9669_0800200c9a66);
         * Note: console.log('systems execute - _proxies().proxy().resources().resource()._6e8bc430_9c3a_11d9_9669_0800200c9a66(): ',
         *         _proxies().proxy().resources().resource()._6e8bc430_9c3a_11d9_9669_0800200c9a66());
         */
        var _resource = _proxies().proxy().resources().resource();
        console.log('systems system execute - resource: ', _resource)
        for (var key in _resource) {
          console.log('systems system execute - key: ', key)
          /*
           * Strip prefix _ if present on key.
           * Then substitute all _ for - if present on key.
           */
          var keyUuid = key.replace(/^\_/, '').replace(/_/g, '\-');
          console.log('systems system execute - keyUuid: ', keyUuid);
          if (additionalArgument.system[i].uuid == keyUuid) {
            console.log('systems system execute - uuid == keyUuid');
            /* Do something */
            resourceForUuid = _resource[key]();
            break;
          }
        }
        /* Validate resourceForUuid */
        if (Object.keys(resourceForUuid).length == 0) {
          /* Raise an error, the resourceForUuid has not been found */
          throw new Error('No resource found for \
              additionalArgument.system[',i,'].uuid: ',
              additionalArgument.system[i].uuid)
          /* TO FIX: for some reason the value of uuid is empty here */
        } else {
          console.log('systems system execute - resourceForUuid: ',
              resourceForUuid)
        };

        console.log('systems system execute - \
            additionalArgument.system[',i,'].instructions: ',
            additionalArgument.system[i].instructions)
        var _instructions = _proxies().proxy().instructions();
        var _instruction = _instructions.instruction();
        console.log('systems system execute - instruction: ', _instruction)
        for (var key in _instruction) {
          var keyLayer = key;
          /* HANDLE THE instructions HERE LIKEWISE, BUT BREAK IT DOWN PER instruction */
          /* TEMP PLACEHOLDER */
          instructionsForInstructions = [{start: 'true'}];
          break;
        } // EOF for
        // Validate instructionsForInstructions
        if (Object.keys(instructionsForInstructions).length == 0) {
          /* Raise an error, the instructionForInstruction has not been found */
          throw new Error('No instructions found for \
              additionalArgument.system[',i,'].instructions: ',
              additionalArgument.system[i].instructions)
          /* TO FIX: for some reason the value of instruction is empty here */
        } else {
          console.log('systems system execute - instructionsForInstructions: ',
              instructionsForInstructions)
        }
        /* OLD: layer = additionalArgument.layer; */
        console.log('systems system execute - \
            additionalArgument.system[',i,'].layer: ',
            additionalArgument.system[i].layer)
        var _layers = _proxies().proxy().layers();
        var _layer = _layers.layer();
        _layer.setproxies(proxies);
        _layer.setresource(resourceForUuid);
        _layer.setinstructions(instructionsForInstructions);
        console.log('systems system execute - layer: ', _layer)
        for (var key in _layer) {
          var keyLayer = key;
          console.log('systems system execute - keyLayer: ', keyLayer)
          if (additionalArgument.system[i].layer == keyLayer) {
            console.log('systems system execute - layer == keyLayer')
            /* Do something */
            layerForLayer = _layer[key]();
            break;
          }
        }
        /*
         * Validate layerForLayer
         * if(Object.keys(layerForLayer).length == 0) {  // THIS VALIDATES IF THERE ARE KEYS WITHIN e.g. Business LAYER, NOT A GOOD CHECK, CHANGE IT!!
         *   raise an error, the layerForLayer has not been found
         *   throw new Error('No layer found for additionalArgument.system[',i,'].layer: ', additionalArgument.system[i].layer); // TO FIX: for some reason the value of layer is empty here
         * } else {
         */
        console.log('systems system execute - layerForLayer: ', layerForLayer)
        /*
         * NOW MAKE THE LAYER DO ITS THING, EXECUTE ITS FUNCTION THAT RETURNS A PROMISE
         * Add the function that returns a Promise
         */
        arrayOfPromises.push(layerForLayer.execute());
        /*
         * } // EOF else
         */
      } // EOF for additionalArgument.system.length
    } // EOF if additionalArgument
    /* Return an array of all promiese from the layers */
    return arrayOfPromises;
  }) // EOF then proxies
  .then(function(arrayOfPromises) {
    console.log('systems system execute - arrayOfPromises: ', arrayOfPromises)
    _proxies().proxy().libraries().library().promise()
    .all(arrayOfPromises)
    .catch(function(error) {
      console.log('systems system execute - all error: ', error)
    })
    .finally(function() {
      console.log('systems system execute - all finally')
    });
  }) // EOF then resourceForUuid
  .catch(function(error) {
    console.log('systems system execute - error: ', error)
  }) // EOF catch
  .finally(function() {
    console.log('systems system execute - finally');
  }); // EOF finally
} // EOF execute

module.exports = System;
<commit_msg>Modified<commit_after>/*
 * Filename: index.js
 */
var self = this; // Set the context locally, for access protection
/**
 * Create a new System that let users create sub-system.
 * @return {System}
 */
function System() {
  console.log('systems system - System called');
  // add key value pairs here
  // self's are not directly publicly accessible, only through their public method(s)
  // use self's here for protection from direct access
  self._filename = ''; // Will be set
  self._filepath = ''; // Will be set
  self._proxies = {}; // Will be set
  self._title = 'System'; // Default
}

System.prototype.proxies = function() {
  return self._proxies;
}

System.prototype.setproxies = function(fnOrValue) {
  console.log('systems system setproxies() called');
  self._proxies = fnOrValue;
}

System.prototype.filename = function() {
  console.log('systems system filename() called');
  return self._filename;
}

System.prototype.setfilename = function(fnOrValue) {
  self._filename = fnOrValue;
}

System.prototype.filepath = function() {
  console.log('systems system filepath() called');
  return self._filepath;
}

System.prototype.setfilepath = function(fnOrValue) {
  self._filepath = fnOrValue;
}

System.prototype.title = function() {
  console.log('systems system title() called');
  return self._title;
}

System.prototype.settitle = function(fnOrValue) {
  self._title = fnOrValue;
}

System.prototype.execute = function(arguments) {
  console.log('systems system execute - called');
  console.log('systems system execute - arguments: ', arguments); // WORKS!!
  // Required modules
  var _instructions = {};
  var instruction = {};
  var _proxies = require('../../proxies/proxies');

  console.log('systems system execute +++++++ CHECKPOINT 000')

  var _arguments = arguments;
  var _filename = this.filename();
  var _filepath = this.filepath();
  var _title = this.title();
  /*
   * ONLY ENDPOINTS OF _proxies ARE Promises, e.g. _proxies().proxy().libraries().library().path()
   * WE POSTPONE TO USE A Promise DOWN THE OBJECT HIERARCHY AS FAR DOWN AS FEASIBLE
   * UNTIL WE NEED THE Promise RESOLVED
   */
  console.log('systems system execute - _proxies: ', _proxies)
  var promise = _proxies().proxy().libraries().library().promise();
  var join = promise.join;
  // Start of the chain
  join(_proxies(), function(proxies) {
    console.log('systems system execute - proxies: ',
      proxies) // Works: Proxies {}

    return (proxies);
  }) /* EOF join proxies */
  .then(function(proxies) {

    console.log('systems system execute - documentation +++++++ CHECKPOINT 000')

    var _documentations = _proxies().proxy().documentations();
    _documentations.setproxies(_proxies);
    _documentations.setfilepath(_filepath);
    _documentations.setfilename(_filename);
    var _title = 'Documentations';
    var _linktitle = 'Documentation';
    var _document = 'documentation.html';
    var _directory = 'documentation';

    // START TEST AREA

    var _jsdom = _proxies().proxy().libraries().library().jsdom();
    console.log('systems system execute - documentation _jsdom: ', _jsdom)

    // END TEST AREA

    _documentations.append('<title>' + _title + '</title>'
      ,'
' + _title +
      '

 \
      ' + _linktitle + '

');

    var _documentation = _documentations.documentation(); // Throws error  [TypeError: path must be a string]  Fix it!!

    console.log('systems system execute - documentation +++++++ CHECKPOINT 001')
/*
    console.log('systems system execute - documentation: ',
      _documentation) // Works: Documentation {}
    //_documentation.setfilepath(_filepath); Gets set inside documentations
    //_documentations.setfilename(_filename); Gets set inside documentations
    var _title = 'Documentation';
    var _linktitle = 'UML';
    var _document = 'uml.html';
    var _directory = 'uml';

    console.log('systems system execute - documentation +++++++ CHECKPOINT 002')

    _documentation.append('<title>' + _title + '</title>'
      ,'
' + _title +
      '

 \
      ' + _linktitle + '

');

    console.log('systems system execute - documentation +++++++ CHECKPOINT 003')

*/
/*
    var _uml = _documentation.uml();

    console.log('systems system execute - documentation +++++++ CHECKPOINT 004')

    console.log('systems system execute - uml: ',
      _uml) // Works: UML {}
    //_uml.setfilepath(_filepath); Gets set inside documentation
    //_uml.setfilename(_filename); Gets set inside documentation
    var _title = 'UML';
    var _linktitle = 'Sequence Diagram';
    var _document = 'sequencediagram.html';
    var _directory = 'sequencediagram';

    console.log('systems system execute - documentation +++++++ CHECKPOINT 005')

    _uml.append('<title>' + _title + '</title>'
      ,'
' + _title +
      '

 \
      ' + _linktitle + '

');

*/
/*
    var _sequencediagram = _uml.sequencediagram();

    console.log('systems system execute - documentation +++++++ CHECKPOINT 006')

    console.log('systems system execute - sequencediagram: ',
      _sequencediagram) // Works: SequenceDiagram {}
    //_sequencediagram.setfilepath(_filepath); Gets set inside uml
    //_sequencediagram.setfilename(_filename); Gets set inside uml
    var _title = 'Sequence Diagram';
    var _linktitle = 'Foo';
    var _document = 'foo.html';
    var _directory = 'foo';

    console.log('systems system execute - documentation +++++++ CHECKPOINT 007')

    _sequencediagram.append('<title>' + _title + '</title>'
      ,'
' + _title +
      '

 \
      ' + _linktitle + '

');
*/

    var resourceForUuid = {};
    var layerForLayer = {};
    var instructionsForInstructions = {};
    var uuid = {};
    var additionalArgument = _arguments;
    var arrayOfPromises = [];
    /*
     * The value of arguments will be the optional additional command line arguments, e.g. a JSON file {uuid:1234}
     * Handle non-exception-throwing cases.
     * Neither JSON.parse(false) or JSON.parse(1234) throw errors,
     * hence the type-checking.
     * But JSON.parse(null) returns 'null', and typeof null === "object"
     * so we must check for that, too.
     */
    if (additionalArgument
      && typeof additionalArgument === 'object'
      && additionalArgument !== null) {
      /*
       * Now we have the object additionalArgument
       */
      console.log('systems system execute - additionalArgument: ',
        additionalArgument)
      console.log('systems system execute - additionalArgument.system: ',
        additionalArgument.system)
      /*
       * The additionalArgument.system is an Array of Objects
       * so we have to loop through the array.
       */
      console.log('systems system execute - additionalArgument.system.length: ',
          additionalArgument.system.length)

      for (var i = 0; i < additionalArgument.system.length; i++) {
        console.log('systems system execute - \
            additionalArgument.system[',i,']: ',
            additionalArgument.system[i])
        console.log('systems system execute - \
            additionalArgument.system[',i,'].uuid: ',
            additionalArgument.system[i].uuid)
        /* Get a resource, by comparing with the uuid */
        /*
         * Note: console.log('systems execute - resource: ', _proxies().proxy().resources().resource);
         * Returns: function () { return new ResourcesResource(); }
         * Note: console.log('systems execute - _proxies().proxy().resources().resource(): ',
         *         _proxies().proxy().resources().resource());
         * Returns: Resource {}
         * Note: console.log('systems execute - _proxies().proxy().resources().resource()._6e8bc430_9c3a_11d9_9669_0800200c9a66: ',
         *         _proxies().proxy().resources().resource()._6e8bc430_9c3a_11d9_9669_0800200c9a66);
         * Note: console.log('systems execute - _proxies().proxy().resources().resource()._6e8bc430_9c3a_11d9_9669_0800200c9a66(): ',
         *         _proxies().proxy().resources().resource()._6e8bc430_9c3a_11d9_9669_0800200c9a66());
         */
        var _resource = _proxies().proxy().resources().resource();
        console.log('systems system execute - resource: ', _resource)
        for (var key in _resource) {
          console.log('systems system execute - key: ', key)
          /*
           * Strip prefix _ if present on key.
           * Then substitute all _ for - if present on key.
           */
          var keyUuid = key.replace(/^\_/, '').replace(/_/g, '\-');
          console.log('systems system execute - keyUuid: ', keyUuid);
          if (additionalArgument.system[i].uuid == keyUuid) {
            console.log('systems system execute - uuid == keyUuid');
            /* Do something */
            resourceForUuid = _resource[key]();
            break;
          }
        }
        /* Validate resourceForUuid */
        if (Object.keys(resourceForUuid).length == 0) {
          /* Raise an error, the resourceForUuid has not been found */
          throw new Error('No resource found for \
              additionalArgument.system[',i,'].uuid: ',
              additionalArgument.system[i].uuid)
          /* TO FIX: for some reason the value of uuid is empty here */
        } else {
          console.log('systems system execute - resourceForUuid: ',
              resourceForUuid)
        };

        console.log('systems system execute - \
            additionalArgument.system[',i,'].instructions: ',
            additionalArgument.system[i].instructions)
        var _instructions = _proxies().proxy().instructions();
        var _instruction = _instructions.instruction();
        console.log('systems system execute - instruction: ', _instruction)
        for (var key in _instruction) {
          var keyLayer = key;
          /* HANDLE THE instructions HERE LIKEWISE, BUT BREAK IT DOWN PER instruction */
          /* TEMP PLACEHOLDER */
          instructionsForInstructions = [{start: 'true'}];
          break;
        } // EOF for
        // Validate instructionsForInstructions
        if (Object.keys(instructionsForInstructions).length == 0) {
          /* Raise an error, the instructionForInstruction has not been found */
          throw new Error('No instructions found for \
              additionalArgument.system[',i,'].instructions: ',
              additionalArgument.system[i].instructions)
          /* TO FIX: for some reason the value of instruction is empty here */
        } else {
          console.log('systems system execute - instructionsForInstructions: ',
              instructionsForInstructions)
        }
        /* OLD: layer = additionalArgument.layer; */
        console.log('systems system execute - \
            additionalArgument.system[',i,'].layer: ',
            additionalArgument.system[i].layer)
        var _layers = _proxies().proxy().layers();
        var _layer = _layers.layer();
        _layer.setproxies(proxies);
        _layer.setresource(resourceForUuid);
        _layer.setinstructions(instructionsForInstructions);
        console.log('systems system execute - layer: ', _layer)
        for (var key in _layer) {
          var keyLayer = key;
          console.log('systems system execute - keyLayer: ', keyLayer)
          if (additionalArgument.system[i].layer == keyLayer) {
            console.log('systems system execute - layer == keyLayer')
            /* Do something */
            layerForLayer = _layer[key]();
            break;
          }
        }
        /*
         * Validate layerForLayer
         * if(Object.keys(layerForLayer).length == 0) {  // THIS VALIDATES IF THERE ARE KEYS WITHIN e.g. Business LAYER, NOT A GOOD CHECK, CHANGE IT!!
         *   raise an error, the layerForLayer has not been found
         *   throw new Error('No layer found for additionalArgument.system[',i,'].layer: ', additionalArgument.system[i].layer); // TO FIX: for some reason the value of layer is empty here
         * } else {
         */
        console.log('systems system execute - layerForLayer: ', layerForLayer)
        /*
         * NOW MAKE THE LAYER DO ITS THING, EXECUTE ITS FUNCTION THAT RETURNS A PROMISE
         * Add the function that returns a Promise
         */
        arrayOfPromises.push(layerForLayer.execute());
        /*
         * } // EOF else
         */
      } // EOF for additionalArgument.system.length
    } // EOF if additionalArgument
    /* Return an array of all promiese from the layers */
    return arrayOfPromises;
  }) // EOF then proxies
  .then(function(arrayOfPromises) {
    console.log('systems system execute - arrayOfPromises: ', arrayOfPromises)
    _proxies().proxy().libraries().library().promise()
    .all(arrayOfPromises)
    .catch(function(error) {
      console.log('systems system execute - all error: ', error)
    })
    .finally(function() {
      console.log('systems system execute - all finally')
    });
  }) // EOF then resourceForUuid
  .catch(function(error) {
    console.log('systems system execute - error: ', error)
  }) // EOF catch
  .finally(function() {
    console.log('systems system execute - finally');
  }); // EOF finally
} // EOF execute

module.exports = System;
<|endoftext|>


<commit_before>TDP.commands.touchScreenEvents = {

  event_mappings: {
    'swiperight': 'moveRight',
    'swipeleft': 'moveLeft',
    'swipedown': 'moveDown',
    'swipeup': 'moveUp',
    'tap': 'specialAttack'
  },

  init: function() {
    var action;
    if (this.onMobile()) {
      $.each(
        Object.keys(this.event_mappings),
        function(i, event_name) {
          action = TDP.commands.touchScreenEvents.event_mappings[event_name];
          $(document).off(
            event_name,
            '#TDP_board'
          );
          $(document).on(
            event_name,
            '#TDP_board',
            function(e){
              e.preventDefault();
              TDP.player[action]();
            }
          )
        }
      );
    }
  },

  onMobile: function() {
    return $.support.touch;
  }

};

<commit_msg>Touch screen events tested on, um, desktop<commit_after>TDP.commands.touchScreenEvents = {

  event_mappings: {
    'swiperight': 'moveRight',
    'swipeleft': 'moveLeft',
    'swipedown': 'moveDown',
    'swipeup': 'moveUp',
    'tap': 'specialAttack'
  },

  init: function () {
    if (this.onMobile()) {
      $.each(
        Object.keys(this.event_mappings),
        function (i, event_name) {
          var action_name = TDP.commands.touchScreenEvents.event_mappings[event_name];
          console.log(event_name);
          console.log(action_name);
          $(document).on(
            event_name,
            'div#TDP_board',
            function (e) {
              e.preventDefault();
              TDP.player[action_name]();
            }
          );
        }
      );
    }
  },

  onMobile: function () {
    return $.support.touch;
  }

};

<|endoftext|>