<commit_before>/*
 * library dependencies:
 *      jquery 1.8.3
 * external dependencies:
 *      base.js ajax.genericAction()
 */

// fansWorld freindship plugin 1.0

$(document).ready(function () {
    "use strict";
    var pluginName = "fwFriendship";
    var defaults = {
        propertyName: "fansworld",
        userId: null,
        // custom callback events
        onError: function(error) {},
        addFriend: function(data) {},
        onRemoveFriend: function(data) {}
    };
    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    Plugin.prototype = {
        init: function () {
            var that = this;
            var self = $(that.element);
            that.options.userId = self.attr('data-user-id');
            self.addClass(that._name);

            if (window.isLoggedIn) {
                self.on('click', that.addFriend);
            } else {
                self.on('click',function(event) {
                    $('[data-login-btn]').click();
                });
            }
        },
        addFriend: function(event) {
            var that = this;
            var self = $(this);
            event.preventDefault();
            if (!window.isLoggedIn) {
                $('[data-login-btn]').click();
                return false;
            }
            var plugin = $(this).data('fwFriendship');
            plugin.toggleFriendship($(event.srcElement).attr('data-user-id'));
        },
        toggleFriendship: function(userId) {
            var that = this;
            var self = $(that.element);
            var targetId = self.attr('data-user-id');
            var friendGroups = [];
            $("ul.friendgroupsList li input:checkbox:checked").each(function(k, el){
                friendgroups[k] = $(el).val();
            });
            ajax.genericAction(
                'friendship_ajaxaddfriend',
                {
                    'target': targetId,
                    'friendgroups': friendGroups
                },
                function(responseJSON) {
                    if(responseJSON.error) {
                        window.error(data.message);
                        return that.options.onError(error);
                    }
                    if(responseJSON) {
                        if(responseJSON.friendship) {
                            that.onAddFriend(responseJSON);
                        }
                    }
                },
                function(error) {
                    window.error(error.responseText);
                    window.notice(data.message);
                    return that.options.onError(error);
                });
        },
        onAddFriend: function(data) {
            var that = this;
            window.notice(data.message);
            return that.options.onAddFriend(that, data);
        },
        onRemoveFriend: function(data){
            var that = this;
            window.notice(data.message);
            return that.options.onRemoveFriend(that, data);
        },
        destroy: function() {
            var that = this;
            $(that.element).unbind("destroyed", that.teardown);
            that.teardown();
        },
        teardown: function() {
            var that = this;
            $.removeData($(that.element)[0], that._name);
            $(that.element).removeClass(that._name);
            that.unbind();
            that.element = null;
        },
        bind: function() { },
        unbind: function() { }
    };
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };
});
//Attach plugin to all matching element
$(document).ready(function () {
    "use strict";

    $("[data-friendship-add]:not('[data-override]')").fwFriendship({
        onAddFriend: function(plugin, data) {
            var self = $(plugin.element);
            self.addClass('unfan');
            self.removeClass('befun');
            self.get(0).lastChild.nodeValue = "Eres Fan";
        },
        onRemoveFriend: function(plugin, data) {
            var self = $(plugin.element);
            self.addClass('befun');
            self.removeClass('unfan');
            self.get(0).lastChild.nodeValue = "Ser Fan";
        }
    });

    $("[data-friendship-remove]:not('[data-override]')").fwFriendship({
        onRemoveFriend: function(plugin, data) {
            window.location.reload();
        }
    });
});<commit_msg>aviso<commit_after>/*
 * library dependencies:
 *      jquery 1.8.3
 * external dependencies:
 *      base.js ajax.genericAction()
 */

// fansWorld freindship plugin 1.0

$(document).ready(function () {
    "use strict";
    var pluginName = "fwFriendship";
    var defaults = {
        propertyName: "fansworld",
        userId: null,
        // custom callback events
        onError: function(error) {},
        addFriend: function(data) {},
        onRemoveFriend: function(data) {}
    };
    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    Plugin.prototype = {
        init: function () {
            var that = this;
            var self = $(that.element);
            that.options.userId = self.attr('data-user-id');
            self.addClass(that._name);

            if (window.isLoggedIn) {
                self.on('click', that.addFriend);
            } else {
                self.on('click',function(event) {
                    $('[data-login-btn]').click();
                });
            }
        },
        addFriend: function(event) {
            var that = this;
            var self = $(this);
            event.preventDefault();
            if (!window.isLoggedIn) {
                $('[data-login-btn]').click();
                return false;
            }
            var plugin = $(this).data('fwFriendship');
            plugin.toggleFriendship($(event.srcElement).attr('data-user-id'));
        },
        toggleFriendship: function(userId) {
            var that = this;
            var self = $(that.element);
            var targetId = self.attr('data-user-id');
            var friendGroups = [];
            $("ul.friendgroupsList li input:checkbox:checked").each(function(k, el){
                friendgroups[k] = $(el).val();
            });
            ajax.genericAction(
                'friendship_ajaxaddfriend',
                {
                    'target': targetId,
                    'friendgroups': friendGroups
                },
                function(responseJSON) {
                    if(responseJSON.error) {
                        window.error(responseJSON.message);
                        return that.options.onError(error);
                    }
                    if(responseJSON) {
                        if(responseJSON.friendship) {
                            that.onAddFriend(responseJSON);
                        }
                    }
                },
                function(error) {
                    window.error(error.responseText);
                    window.notice(data.message);
                    return that.options.onError(error);
                });
        },
        onAddFriend: function(data) {
            var that = this;
            window.notice(data.message);
            return that.options.onAddFriend(that, data);
        },
        onRemoveFriend: function(data){
            var that = this;
            window.notice(data.message);
            return that.options.onRemoveFriend(that, data);
        },
        destroy: function() {
            var that = this;
            $(that.element).unbind("destroyed", that.teardown);
            that.teardown();
        },
        teardown: function() {
            var that = this;
            $.removeData($(that.element)[0], that._name);
            $(that.element).removeClass(that._name);
            that.unbind();
            that.element = null;
        },
        bind: function() { },
        unbind: function() { }
    };
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };
});
//Attach plugin to all matching element
$(document).ready(function () {
    "use strict";

    $("[data-friendship-add]:not('[data-override]')").fwFriendship({
        onAddFriend: function(plugin, data) {
            var self = $(plugin.element);
            self.addClass('unfan');
            self.removeClass('befun');
            self.get(0).lastChild.nodeValue = "Eres Fan";
        },
        onRemoveFriend: function(plugin, data) {
            var self = $(plugin.element);
            self.addClass('befun');
            self.removeClass('unfan');
            self.get(0).lastChild.nodeValue = "Ser Fan";
        }
    });

    $("[data-friendship-remove]:not('[data-override]')").fwFriendship({
        onRemoveFriend: function(plugin, data) {
            window.location.reload();
        }
    });
});<|endoftext|>


<commit_before>'use strict';

exports.type = 'perItem';

exports.active = true;

exports.description = 'merges multiple paths in one if possible';

exports.params = {
    collapseRepeated: true,
    leadingZero: true,
    negativeExtraSpace: true,
    noSpaceAfterFlags: true
};

var path2js = require('./_path.js').path2js,
    js2path = require('./_path.js').js2path,
    intersects = require('./_path.js').intersects;

/**
 * Merge multiple Paths into one.
 *
 * @param {Object} item current iteration item
 * @return {Boolean} if false, item will be filtered out
 *
 * @author Kir Belevich, Lev Solntsev
 */
exports.fn = function(item, params) {

    if (!item.isElem() || item.isEmpty()) return;

    var prevContentItem = null,
        prevContentItemKeys = null;

    item.content = item.content.filter(function(contentItem) {

        if (prevContentItem &&
            prevContentItem.isElem('path') &&
            prevContentItem.isEmpty() &&
            prevContentItem.hasAttr('d') &&
            contentItem.isElem('path') &&
            contentItem.isEmpty() &&
            contentItem.hasAttr('d')
        ) {

            if (!prevContentItemKeys) {
                prevContentItemKeys = Object.keys(prevContentItem.attrs);
            }

            var contentItemAttrs = Object.keys(contentItem.attrs),
                equalData = prevContentItemKeys.length == contentItemAttrs.length &&
                    contentItemAttrs.every(function(key) {
                        return key == 'd' ||
                            prevContentItem.hasAttr(key) &&
                            prevContentItem.attr(key).value == contentItem.attr(key).value;
                    }),
                prevPathJS = path2js(prevContentItem),
                curPathJS = path2js(contentItem);

            if (equalData && !intersects(prevPathJS, curPathJS)) {
                js2path(prevContentItem, prevPathJS.concat(curPathJS), params);
                return false;
            }
        }

        prevContentItem = contentItem;
        prevContentItemKeys = null;
        return true;

    });

};
<commit_msg>(Fix #800) Add option to the mergePaths plugin, forcing all path attributes to be combined (#1084)<commit_after>'use strict';

exports.type = 'perItem';

exports.active = true;

exports.description = 'merges multiple paths in one if possible';

exports.params = {
    collapseRepeated: true,
    force: false,
    leadingZero: true,
    negativeExtraSpace: true,
    noSpaceAfterFlags: true
};

var path2js = require('./_path.js').path2js,
    js2path = require('./_path.js').js2path,
    intersects = require('./_path.js').intersects;

/**
 * Merge multiple Paths into one.
 *
 * @param {Object} item current iteration item
 * @return {Boolean} if false, item will be filtered out
 *
 * @author Kir Belevich, Lev Solntsev
 */
exports.fn = function(item, params) {

    if (!item.isElem() || item.isEmpty()) return;

    var prevContentItem = null,
        prevContentItemKeys = null;

    item.content = item.content.filter(function(contentItem) {

        if (prevContentItem &&
            prevContentItem.isElem('path') &&
            prevContentItem.isEmpty() &&
            prevContentItem.hasAttr('d') &&
            contentItem.isElem('path') &&
            contentItem.isEmpty() &&
            contentItem.hasAttr('d')
        ) {

            if (!prevContentItemKeys) {
                prevContentItemKeys = Object.keys(prevContentItem.attrs);
            }

            var contentItemAttrs = Object.keys(contentItem.attrs),
                equalData = prevContentItemKeys.length == contentItemAttrs.length &&
                    contentItemAttrs.every(function(key) {
                        return key == 'd' ||
                            prevContentItem.hasAttr(key) &&
                            prevContentItem.attr(key).value == contentItem.attr(key).value;
                    }),
                prevPathJS = path2js(prevContentItem),
                curPathJS = path2js(contentItem);

            if (params.force || equalData && !intersects(prevPathJS, curPathJS)) {
                js2path(prevContentItem, prevPathJS.concat(curPathJS), params);
                return false;
            }
        }

        prevContentItem = contentItem;
        prevContentItemKeys = null;
        return true;

    });

};
<|endoftext|>


<commit_before>import {List} from 'immutable';

import {
  SELECT_TOOL_DRAWING_LINE,
  BEGIN_DRAWING_LINE,
  UPDATE_DRAWING_LINE,
  END_DRAWING_LINE,
  SELECT_TOOL_DRAWING_HOLE,
  BEGIN_DRAWING_HOLE,
  UPDATE_DRAWING_HOLE,
  END_DRAWING_HOLE,
  MODE_WAITING_DRAWING_LINE,
  MODE_WAITING_DRAWING_HOLE,
  MODE_DRAWING_HOLE,
  MODE_DRAWING_LINE
} from '../constants';

import * as Geometry from '../utils/geometry';
import {addLine, replaceLineVertex, removeLine, splitLine, select, unselect} from '../utils/layer-operations';
import {nearestDrawingHelper, addPointHelper, addLineHelper} from '../utils/drawing-helpers';

export default function (state, action) {
  switch (action.type) {
    case SELECT_TOOL_DRAWING_LINE:
      return state.set('mode', MODE_WAITING_DRAWING_LINE);

    case BEGIN_DRAWING_LINE:
      return beginDrawingLine(state, action.layerID, action.x, action.y);

    case UPDATE_DRAWING_LINE:
      return updateDrawingLine(state, action.layerID, action.x, action.y);

    case END_DRAWING_LINE:
      return endDrawingLine(state, action.layerID, action.x, action.y);

    case SELECT_TOOL_DRAWING_HOLE:
      return state.set('mode', MODE_WAITING_DRAWING_HOLE);

    case BEGIN_DRAWING_HOLE:
      return updateDrawingHole(state, action.layerID, action.x, action.y);

    case UPDATE_DRAWING_HOLE:
      return updateDrawingHole(state, action.layerID, action.x, action.y);

    case END_DRAWING_HOLE:
      return endDrawingHole(state, action.layerID, action.x, action.y);

    default:
      return state;
  }
}

/** lines operations **/
function beginDrawingLine(state, layerID, x, y) {
  let a, b, c;

  let drawingHelpers = (new List()).withMutations(drawingHelpers => {
    state.getIn(['scene', 'layers', layerID, 'vertices'])
      .forEach(({id: vertexID, x, y}) => {
        addPointHelper(drawingHelpers, x, y, 10, 5, vertexID);

        ({a, b, c} = Geometry.horizontalLine(y));
        addLineHelper(drawingHelpers, a, b, c, 10, 1, vertexID);
        ({a, b, c} = Geometry.verticalLine(x));
        addLineHelper(drawingHelpers, a, b, c, 10, 1, vertexID);
      });
  });

  let nearestHelper = nearestDrawingHelper(state.drawingHelpers, x, y);
  let helper = null;
  if (nearestHelper) {
    ({x, y} = nearestHelper.point);
    helper = nearestHelper.helper;
  }

  drawingHelpers = drawingHelpers.withMutations(drawingHelpers => {
    ({a, b, c} = Geometry.horizontalLine(y));
    addLineHelper(drawingHelpers, a, b, c, 10, 3, null);
    ({a, b, c} = Geometry.verticalLine(x));
    addLineHelper(drawingHelpers, a, b, c, 10, 3, null);
  });

  let scene = state.scene.updateIn(['layers', layerID], layer => layer.withMutations(layer => {
    let {line} = addLine(layer, 'wall-generic', x, y, x, y);
    select(layer, 'lines', line.id);
  }));

  return state.merge({
    mode: MODE_DRAWING_LINE,
    scene, drawingHelpers,
    nearestDrawingHelper: helper
  });
}

function updateDrawingLine(state, layerID, x, y) {

  let nearestHelper = nearestDrawingHelper(state.drawingHelpers, x, y);
  let helper = null;
  if (nearestHelper) {
    ({x, y} = nearestHelper.point);
    helper = nearestHelper.helper;
  }

  let scene = state.scene.updateIn(['layers', layerID], layer => {
    let lineID = layer.getIn(['selected', 'lines']).first();
    ({layer} = replaceLineVertex(layer, lineID, 1, x, y));
    return layer;
  });

  return state.merge({
    scene,
    nearestDrawingHelper: helper
  });
}

function endDrawingLine(state, layerID, x, y) {
  let nearestHelper = nearestDrawingHelper(state.drawingHelpers, x, y);
  if (nearestHelper) {
    ({x, y} = nearestHelper.point);
  }

  let scene = state.scene.updateIn(['layers', layerID], layer => {
    let lineID = layer.getIn(['selected', 'lines']).first();
    let line = layer.getIn(['lines', lineID]);
    ({layer} = replaceLineVertex(layer, lineID, 1, x, y));
    layer = unselect(layer, 'lines', lineID);
    return layer;
  });

  return state.merge({
    mode: MODE_WAITING_DRAWING_LINE,
    scene,
    drawingHelpers: new List(),
    nearestDrawingHelper: null
  });
}

/** holes operations **/
function beginDrawingHole(state, layerID, x, y) {
  return state.merge({mode: MODE_DRAWING_HOLE});
}

function updateDrawingHole(state, layerID, x, y) {
  return state;
}

function endDrawingHole(state, layerID, x, y) {
  return state.merge({mode: MODE_WAITING_DRAWING_HOLE});
}
<commit_msg>change point helper priority<commit_after>import {List} from 'immutable';

import {
  SELECT_TOOL_DRAWING_LINE,
  BEGIN_DRAWING_LINE,
  UPDATE_DRAWING_LINE,
  END_DRAWING_LINE,
  SELECT_TOOL_DRAWING_HOLE,
  BEGIN_DRAWING_HOLE,
  UPDATE_DRAWING_HOLE,
  END_DRAWING_HOLE,
  MODE_WAITING_DRAWING_LINE,
  MODE_WAITING_DRAWING_HOLE,
  MODE_DRAWING_HOLE,
  MODE_DRAWING_LINE
} from '../constants';

import * as Geometry from '../utils/geometry';
import {addLine, replaceLineVertex, removeLine, splitLine, select, unselect} from '../utils/layer-operations';
import {nearestDrawingHelper, addPointHelper, addLineHelper} from '../utils/drawing-helpers';

export default function (state, action) {
  switch (action.type) {
    case SELECT_TOOL_DRAWING_LINE:
      return state.set('mode', MODE_WAITING_DRAWING_LINE);

    case BEGIN_DRAWING_LINE:
      return beginDrawingLine(state, action.layerID, action.x, action.y);

    case UPDATE_DRAWING_LINE:
      return updateDrawingLine(state, action.layerID, action.x, action.y);

    case END_DRAWING_LINE:
      return endDrawingLine(state, action.layerID, action.x, action.y);

    case SELECT_TOOL_DRAWING_HOLE:
      return state.set('mode', MODE_WAITING_DRAWING_HOLE);

    case BEGIN_DRAWING_HOLE:
      return updateDrawingHole(state, action.layerID, action.x, action.y);

    case UPDATE_DRAWING_HOLE:
      return updateDrawingHole(state, action.layerID, action.x, action.y);

    case END_DRAWING_HOLE:
      return endDrawingHole(state, action.layerID, action.x, action.y);

    default:
      return state;
  }
}

/** lines operations **/
function beginDrawingLine(state, layerID, x, y) {
  let a, b, c;

  let drawingHelpers = (new List()).withMutations(drawingHelpers => {
    state.getIn(['scene', 'layers', layerID, 'vertices'])
      .forEach(({id: vertexID, x, y}) => {
        addPointHelper(drawingHelpers, x, y, 10, 10, vertexID);

        ({a, b, c} = Geometry.horizontalLine(y));
        addLineHelper(drawingHelpers, a, b, c, 10, 1, vertexID);
        ({a, b, c} = Geometry.verticalLine(x));
        addLineHelper(drawingHelpers, a, b, c, 10, 1, vertexID);
      });
  });

  let nearestHelper = nearestDrawingHelper(state.drawingHelpers, x, y);
  let helper = null;
  if (nearestHelper) {
    ({x, y} = nearestHelper.point);
    helper = nearestHelper.helper;
  }

  drawingHelpers = drawingHelpers.withMutations(drawingHelpers => {
    ({a, b, c} = Geometry.horizontalLine(y));
    addLineHelper(drawingHelpers, a, b, c, 10, 3, null);
    ({a, b, c} = Geometry.verticalLine(x));
    addLineHelper(drawingHelpers, a, b, c, 10, 3, null);
  });

  let scene = state.scene.updateIn(['layers', layerID], layer => layer.withMutations(layer => {
    let {line} = addLine(layer, 'wall-generic', x, y, x, y);
    select(layer, 'lines', line.id);
  }));

  return state.merge({
    mode: MODE_DRAWING_LINE,
    scene, drawingHelpers,
    nearestDrawingHelper: helper
  });
}

function updateDrawingLine(state, layerID, x, y) {

  let nearestHelper = nearestDrawingHelper(state.drawingHelpers, x, y);
  let helper = null;
  if (nearestHelper) {
    ({x, y} = nearestHelper.point);
    helper = nearestHelper.helper;
  }

  let scene = state.scene.updateIn(['layers', layerID], layer => {
    let lineID = layer.getIn(['selected', 'lines']).first();
    ({layer} = replaceLineVertex(layer, lineID, 1, x, y));
    return layer;
  });

  return state.merge({
    scene,
    nearestDrawingHelper: helper
  });
}

function endDrawingLine(state, layerID, x, y) {
  let nearestHelper = nearestDrawingHelper(state.drawingHelpers, x, y);
  if (nearestHelper) {
    ({x, y} = nearestHelper.point);
  }

  let scene = state.scene.updateIn(['layers', layerID], layer => {
    let lineID = layer.getIn(['selected', 'lines']).first();
    let line = layer.getIn(['lines', lineID]);
    ({layer} = replaceLineVertex(layer, lineID, 1, x, y));
    layer = unselect(layer, 'lines', lineID);
    return layer;
  });

  return state.merge({
    mode: MODE_WAITING_DRAWING_LINE,
    scene,
    drawingHelpers: new List(),
    nearestDrawingHelper: null
  });
}

/** holes operations **/
function beginDrawingHole(state, layerID, x, y) {
  return state.merge({mode: MODE_DRAWING_HOLE});
}

function updateDrawingHole(state, layerID, x, y) {
  return state;
}

function endDrawingHole(state, layerID, x, y) {
  return state.merge({mode: MODE_WAITING_DRAWING_HOLE});
}
<|endoftext|>


<commit_before>
var fs = require('fs-extra');
var pathExtra = require('path-extra');
var assert = require('assert');

var cozyLight = require('../lib/cozy-light');
var actions = cozyLight.actions;
var configHelpers = cozyLight.configHelpers;
var npmHelpers = cozyLight.npmHelpers;

var fixturesDir = pathExtra.join( __dirname, 'fixtures');
var workingDir = pathExtra.join( __dirname, '.test-working_dir');
var cozyHOME = pathExtra.join(workingDir, '.cozy-light' );

cozyLight.init({home:workingDir});

describe('NPM Helpers', function () {

  describe('install', function () {

    before(function(){
      fs.removeSync(workingDir);
      fs.mkdirSync(workingDir);
      fs.mkdirSync(cozyHOME);
      process.chdir(cozyHOME);
    });

    after(function(){
      try {
        fs.removeSync(workingDir);
      } catch(err) {
        console.log(err);
      }
    });

    it('should install a module.', function (done) {
      this.timeout(60000);
      var destPath = configHelpers.modulePath('hello');
      npmHelpers.install('cozy-labs/hello', function (err) {
        assert.equal(err, null, 'Cannot install module.');
        assert(fs.existsSync(destPath),
          'Module is not installed in the cozy-light folder.');
        done();
      });
    });
    it('should link a module.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      var destPath = configHelpers.modulePath('hello');
      npmHelpers.link(testapp, function (err) {
        assert.equal(err, null, 'Cannot link module.');
        assert(fs.existsSync(destPath),
          'Module is not linked in the cozy-light folder.');
        done();
      });
    });
  });

  describe('uninstall', function(){

    before(function(){
      fs.removeSync(workingDir);
      fs.mkdirSync(workingDir);
      fs.mkdirSync(cozyHOME);
      process.chdir(cozyHOME);
    });

    after(function(){
      try {
        fs.removeSync(workingDir);
      } catch(err) {
        console.log(err);
      }
    });

    it('should remove a remote module.', function (done) {
      this.timeout(60000);
      var destPath = configHelpers.modulePath('hello');
      var srcModule = 'cozy-labs/hello';
      process.chdir(cozyHOME);
      npmHelpers.install(srcModule, function (err) {
        assert.equal(err, null, 'Cannot install module.');
        assert(fs.existsSync(destPath),
          'Module is not linked in the cozy-light folder.');
        npmHelpers.uninstall('hello', function (err) {
          assert.equal(err, null, 'Cannot uninstall module.');
          assert(!fs.existsSync(destPath),
            'Module is not removed from the cozy-light folder. '+destPath);
          done();
        });
      });
    });
    it('should remove a local module.', function (done) {
      var destPath = configHelpers.modulePath('test-app');
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      assert(!fs.existsSync(destPath),
        'Module is not removed from the cozy-light folder.');
      npmHelpers.link(testapp, function (err) {
        assert.equal(err, null, 'Cannot install module.');
        assert(fs.existsSync(destPath),
          'Module is not linked in the cozy-light folder.');
        process.chdir(cozyHOME);
        npmHelpers.uninstall('test-app', function (err) {
          assert.equal(err, null, 'Cannot uninstall module.');
          assert(!fs.existsSync(destPath),
            'Module is not removed from the cozy-light folder.');
          done();
        });
      });
    });
  });

  describe('fetchManifest', function(){

    before(function(){
      fs.removeSync(workingDir);
      fs.mkdirSync(workingDir);
      fs.mkdirSync(cozyHOME);
      process.chdir(cozyHOME);
    });

    after(function(){
      try {
        fs.removeSync(workingDir);
      } catch(err) {
        console.log(err);
      }
    });

    it('should fetch manifest from a remote module', function (done) {
      this.timeout(60000);
      npmHelpers.fetchManifest('cozy-labs/hello',
        function (err, manifest, type) {
          assert.equal(err, null, 'Cannot fetch manifest.');
          assert.equal('url', type);
          assert.equal('hello', manifest.name);
          done();
        });
    });
    it('should fetch manifest from an absolute module path.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      npmHelpers.fetchManifest(testapp, function (err, manifest, type) {
        assert.equal(err, null, 'Cannot fetch from ' + testapp + '.');
        assert.equal('file', type);
        assert.equal('test-app', manifest.name);
        done();
      });
    });
    it('should fetch manifest from a relative module path.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      npmHelpers.fetchManifest(testapp, function (err, manifest, type) {
        assert.equal(err, null, 'Cannot fetch from ' + testapp + '.');
        assert.equal('file', type);
        assert.equal('test-app', manifest.name);
        done();
      });
    });
  });

  describe('fetchInstall', function(){

    before(function(){
      fs.removeSync(workingDir);
      fs.mkdirSync(workingDir);
      fs.mkdirSync(cozyHOME);
      process.chdir(cozyHOME);
    });

    after(function(){
      try {
        fs.removeSync(workingDir);
      } catch(err) {
        console.log(err);
      }
    });

    it('should fetch then install remote module.', function (done) {
      this.timeout(60000);
      npmHelpers.fetchInstall('cozy-labs/hello',
        function (err, manifest, type) {
          assert.equal(err, null, 'Cannot install module.');
          assert.equal('url', type);
          assert.equal('hello', manifest.name);
          done();
        });
    });
    it('should fetch then install an absolute module path.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      npmHelpers.fetchManifest(testapp, function (err, manifest, type) {
        assert.equal(err, null, 'Cannot install from ' + testapp + '.');
        assert.equal('file', type);
        assert.equal('test-app', manifest.name);
        done();
      });
    });
    it('should fetch then install a relative module path.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      npmHelpers.fetchManifest(testapp, function (err, manifest, type) {
        assert.equal(err, null, 'Cannot install from ' + testapp + '.');
        assert.equal('file', type);
        assert.equal('test-app', manifest.name);
        done();
      });
    });
  });
});
<commit_msg>pass the tests<commit_after>
var fs = require('fs-extra');
var pathExtra = require('path-extra');
var assert = require('assert');

var cozyLight = require('../lib/cozy-light');
var actions = cozyLight.actions;
var configHelpers = cozyLight.configHelpers;
var npmHelpers = cozyLight.npmHelpers;

var fixturesDir = pathExtra.join( __dirname, 'fixtures');
var workingDir = pathExtra.join( __dirname, '.test-working_dir');

cozyLight.init({home:workingDir});

describe('NPM Helpers', function () {

  describe('install', function () {

    before(function(){
      fs.removeSync(workingDir);
      fs.mkdirSync(workingDir);
      process.chdir(workingDir);
    });

    after(function(){
      try {
        fs.removeSync(workingDir);
      } catch(err) {
        console.log(err);
      }
    });

    it('should install a module.', function (done) {
      this.timeout(60000);
      var destPath = configHelpers.modulePath('hello');
      npmHelpers.install('cozy-labs/hello', function (err) {
        assert.equal(err, null, 'Cannot install module.');
        assert(fs.existsSync(destPath),
          'Module is not installed in the cozy-light folder.');
        done();
      });
    });
    it('should link a module.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      var destPath = configHelpers.modulePath('test-app');
      npmHelpers.link(testapp, function (err) {
        assert.equal(err, null, 'Cannot link module.');
        assert(fs.existsSync(destPath),
          'Module is not linked in the cozy-light folder.');
        done();
      });
    });
  });

  describe('uninstall', function(){

    before(function(){
      fs.removeSync(workingDir);
      fs.mkdirSync(workingDir);
      process.chdir(workingDir);
    });

    after(function(){
      try {
        fs.removeSync(workingDir);
      } catch(err) {
        console.log(err);
      }
    });

    it('should remove a remote module.', function (done) {
      this.timeout(60000);
      var destPath = configHelpers.modulePath('hello');
      var srcModule = 'cozy-labs/hello';
      process.chdir(workingDir);
      npmHelpers.install(srcModule, function (err) {
        assert.equal(err, null, 'Cannot install module.');
        assert(fs.existsSync(destPath),
          'Module is not linked in the cozy-light folder.');
        npmHelpers.uninstall('hello', function (err) {
          assert.equal(err, null, 'Cannot uninstall module.');
          assert(!fs.existsSync(destPath),
            'Module is not removed from the cozy-light folder. '+destPath);
          done();
        });
      });
    });
    it('should remove a local module.', function (done) {
      var destPath = configHelpers.modulePath('test-app');
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      assert(!fs.existsSync(destPath),
        'Module is not removed from the cozy-light folder.');
      npmHelpers.link(testapp, function (err) {
        assert.equal(err, null, 'Cannot install module.');
        assert(fs.existsSync(destPath),
          'Module is not linked in the cozy-light folder.');
        process.chdir(workingDir);
        npmHelpers.uninstall('test-app', function (err) {
          assert.equal(err, null, 'Cannot uninstall module.');
          assert(!fs.existsSync(destPath),
            'Module is not removed from the cozy-light folder.');
          done();
        });
      });
    });
  });

  describe('fetchManifest', function(){

    before(function(){
      fs.removeSync(workingDir);
      fs.mkdirSync(workingDir);
      process.chdir(workingDir);
    });

    after(function(){
      try {
        fs.removeSync(workingDir);
      } catch(err) {
        console.log(err);
      }
    });

    it('should fetch manifest from a remote module', function (done) {
      this.timeout(60000);
      npmHelpers.fetchManifest('cozy-labs/hello',
        function (err, manifest, type) {
          assert.equal(err, null, 'Cannot fetch manifest.');
          assert.equal('url', type);
          assert.equal('hello', manifest.name);
          done();
        });
    });
    it('should fetch manifest from an absolute module path.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      npmHelpers.fetchManifest(testapp, function (err, manifest, type) {
        assert.equal(err, null, 'Cannot fetch from ' + testapp + '.');
        assert.equal('file', type);
        assert.equal('test-app', manifest.name);
        done();
      });
    });
    it('should fetch manifest from a relative module path.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      npmHelpers.fetchManifest(testapp, function (err, manifest, type) {
        assert.equal(err, null, 'Cannot fetch from ' + testapp + '.');
        assert.equal('file', type);
        assert.equal('test-app', manifest.name);
        done();
      });
    });
  });

  describe('fetchInstall', function(){

    before(function(){
      fs.removeSync(workingDir);
      fs.mkdirSync(workingDir);
      process.chdir(workingDir);
    });

    after(function(){
      try {
        fs.removeSync(workingDir);
      } catch(err) {
        console.log(err);
      }
    });

    it('should fetch then install remote module.', function (done) {
      this.timeout(60000);
      npmHelpers.fetchInstall('cozy-labs/hello',
        function (err, manifest, type) {
          assert.equal(err, null, 'Cannot install module.');
          assert.equal('url', type);
          assert.equal('hello', manifest.name);
          done();
        });
    });
    it('should fetch then install an absolute module path.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      npmHelpers.fetchManifest(testapp, function (err, manifest, type) {
        assert.equal(err, null, 'Cannot install from ' + testapp + '.');
        assert.equal('file', type);
        assert.equal('test-app', manifest.name);
        done();
      });
    });
    it('should fetch then install a relative module path.', function (done) {
      var testapp = pathExtra.join(fixturesDir, 'test-app');
      npmHelpers.fetchManifest(testapp, function (err, manifest, type) {
        assert.equal(err, null, 'Cannot install from ' + testapp + '.');
        assert.equal('file', type);
        assert.equal('test-app', manifest.name);
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>var offerUtils = (function (){
  'use strict';
  return {
    getMockOffers: function (){
      return [
      {'id': '1',
      'location': 'Asian Chef',
      'title': 'Sweet & Sour Chicken',
      'description': 'Kanafilee aedviljadega rikkalikus magushapus kastmes.',
      'price': 3.4,
      'tags': ['lind']},
      {'id': '2',
      'location': 'Bulgarian Chef',
      'title': 'Sweet & Sour Pork',
      'description': 'Seafilee aedviljadega rikkalikus magushapus kastmes.',
      'price': 3.3,
      'tags': ['siga']},
      {'id': '3',
      'location': 'Caesar Chef',
      'title': 'Sweet & Sour Beef',
      'description': 'Veisefilee aedviljadega rikkalikus magushapus kastmes.',
      'price': 3.6,
      'tags': ['loom']}
      ];
    },
    matchers: {
      toContainId: function (expected){
        var actual = this.actual;
        var notText = this.isNot ? ' not' : '';

        this.message = function(){
          return 'Expected ' + actual + notText + ' to contain id ' + expected;
        };

        return actual.some(function (elem){
          return elem.id === expected;
        });
      }
    }
  };
})();
<commit_msg>add to HaveIdOrder matcher<commit_after>var offerUtils = (function (){
  'use strict';
  return {
    getMockOffers: function (){
      return [
      {'id': '1',
      'location': 'Asian Chef',
      'title': 'Sweet & Sour Chicken',
      'description': 'Kanafilee aedviljadega rikkalikus magushapus kastmes.',
      'price': 3.4,
      'tags': ['lind']},
      {'id': '2',
      'location': 'Bulgarian Chef',
      'title': 'Sweet & Sour Pork',
      'description': 'Seafilee aedviljadega rikkalikus magushapus kastmes.',
      'price': 3.3,
      'tags': ['siga']},
      {'id': '3',
      'location': 'Caesar Chef',
      'title': 'Sweet & Sour Beef',
      'description': 'Veisefilee aedviljadega rikkalikus magushapus kastmes.',
      'price': 3.6,
      'tags': ['loom']}
      ];
    },
    matchers: {
      toContainId: function (expected){
        var actual = this.actual;
        var notText = this.isNot ? ' not' : '';

        this.message = function(){
          return 'Expected ' + actual + notText + ' to contain id ' + expected;
        };

        return actual.some(function (elem){
          return elem.id === expected;
        });
      },
      toHaveIdOrder: function (expected){
        var actual = this.actual;
        var actualIds = actual.map(function (elem){
          return elem.id;
        });
        var notText = this.isNot ? ' not' : '';

        this.message = function(){
          return 'Expected offers ' + notText + ' to be ordered like: ' + expected + '. Got: ' + actualIds;
        };

        var sameLength = actual.length === expected.length;
        var sameIdOrder = expected.every(function (id, index){
          return actual[index].id === id;
        });
        return sameLength && sameIdOrder;
      }
    }
  };
})();
<|endoftext|>


<commit_before>/* © 2015 Antiun Ingeniería, S.L.
 * © 2015 Lorenzo Battistini - Agile Business Group
 * License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
 */

odoo.define('website_cookie_notice.cookie_notice', function (require) {
    "use strict";

    var ajax = require('web.ajax');
    var base = require('web_editor.base');

    base.ready().done(function() {
        $(".cc-cookies .btn-primary").click(function(e) {
            e.preventDefault();
            ajax.jsonRpc('/website_cookie_notice/ok', 'call').then(function (data) {
                if (data.result == 'ok') {
                    $(e.target).closest(".cc-cookies").hide("fast");
                }
            });
        });
    });
}
);
<commit_msg>[FIX][12.0] website_cookie_notice travis warning<commit_after>/* © 2015 Antiun Ingeniería, S.L.
 * © 2015 Lorenzo Battistini - Agile Business Group
 * License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
 */

odoo.define('website_cookie_notice.cookie_notice', function (require) {
    "use strict";

    var ajax = require('web.ajax');
    var base = require('web_editor.base');

    base.ready().done(function () {
        $(".cc-cookies .btn-primary").click(function (e) {
            e.preventDefault();
            ajax.jsonRpc('/website_cookie_notice/ok', 'call')
                .then(function (data) {
                    if (data.result === 'ok') {
                        $(e.target).closest(".cc-cookies").hide("fast");
                    }
                });
        });
    });
}
);
<|endoftext|>


<commit_before>/*
Select variants to include in a search
Goal is to produce a variant filter that maps closely - but not exactly - to an xbrowse VariantFilter
todo: is that the goal?
 */
window.SelectVariantsView = Backbone.View.extend({

    initialize: function(options) {

        this.hbc = this.options.hbc;
        this.dictionary = this.hbc.dictionary;
        this.project_options = this.hbc.project_options;

        this.annotDefs = this.dictionary.annotation_reference.definitions_grouped;
        this.defaultVariantFilters = this.dictionary.default_variant_filters;
        this.annotationReference = this.dictionary.annotation_reference;
        this.defaultQualityFilters = this.dictionary.default_quality_filters;

        this.reference_populations = this.project_options.reference_populations || [];

        this.vartype_widget = new OrdinalFilterView({
            field_name: 'vartype',
            choices: [
                {slug: 'snp', title: 'SNPs'},
                {slug: 'indel', title: 'In/Dels'},
            ],
        });

        this.polyphen_widget = new OrdinalFilterView({
            field_name: 'polyphen',
            choices: [
                {slug: 'probably_damaging', title: 'Probably damaging'},
                {slug: 'possibly_damaging', title: 'Possibly damaging'},
                {slug: 'benign', title: 'Benign'},
                {slug: 'no_score', title: 'No prediction'},
            ],
        });

        this.sift_widget = new OrdinalFilterView({
            field_name: 'sift',
            choices: [
                {slug: 'damaging', title: 'Damaging'},
                {slug: 'tolerated', title: 'Tolerated'},
                {slug: 'no_score', title: 'No prediction'},
            ],
        });

        this.muttaster_widget = new OrdinalFilterView({
            field_name: 'muttaster',
            choices: [
                {slug: 'disease_causing', title: 'Disease Causing'},
                {slug: 'polymorphism', title: 'Polymorphism'},
                {slug: 'no_score', title: 'No Prediction'},
            ],
        });

        this.fathmm_widget = new OrdinalFilterView({
            field_name: 'fathmm',
            choices: [
                {slug: 'damaging', title: 'Damaging'},
                {slug: 'tolerated', title: 'Tolerated'},
                {slug: 'no_score', title: 'No Prediction'},
            ],
        });

    },

    template: _.template($('#tpl-select-variants').html()),

    events: {
        "change #variant-presets-select": "standardSelectChange",
        "click a.toggle-annotation-details": "toggleAnnotDetails",
        "change .input-annot-parent": "inputAnnotParent",
        "change .input-annot-child": "inputAnnotChild",
        'change .enable-prediction': 'enablePrediction',
        'change #gene_list_select': 'setGeneList'
    },

    setGeneList: function(event) {
    	if(event.currentTarget.value == '---') {
    		$('#region-genes').text('');
    	} else {
    		_.each(this.hbc.gene_lists, function(gene_list) {
	    		if(gene_list['slug'] == event.currentTarget.value) {
	    			var genes_string = _.map(gene_list['genes'], function(gene) {
	    				return gene['gene_id'];
	    			}).join('\n');
    				$('#region-genes').text(genes_string);
    			}
    		});
    	}
    },

    toggleAnnotDetails: function(event) {
        var annotGroup = $(event.target).data('annot');
        var box = this.$('.annotation-details[data-annot="' + annotGroup + '"]');
        box.toggle();
    },

    inputAnnotParent: function(event) {
        var annotGroup = $(event.target).data('annot');
        if ($(event.target).is(':checked')) {
            this.$('.input-annot-child[data-parent="' + annotGroup + '"]').attr('checked', 'checked');
        } else {
            this.$('.input-annot-child[data-parent="' + annotGroup + '"]').removeAttr('checked');
        }
    },

    inputAnnotChild: function(event) {
        var annotGroup = $(event.target).data('parent');
        if (!$(event.target).is(':checked')) {
            this.$('.input-annot-parent[data-annot="' + annotGroup + '"]').removeAttr('checked');
        }
    },

    render: function() {
        $(this.el).html(this.template({
        	hbc: this.hbc,
            annotDefs: this.annotDefs,
            defaultVariantFilters: this.defaultVariantFilters,
            reference_populations: this.reference_populations,
        }));

        this.create_ref_freq_sliders();
        this.vartype_widget.setElement(this.$('#vartype-widget-container')).render();
        this.polyphen_widget.setElement(this.$('#polyphen-widget-container')).render();
        this.sift_widget.setElement(this.$('#sift-widget-container')).render();
        this.muttaster_widget.setElement(this.$('#muttaster-widget-container')).render();
        this.fathmm_widget.setElement(this.$('#fathmm-widget-container')).render();
        utils.initializeHovers(this);

        return this;
    },

    getVariantFilter: function() {

        var that = this;

        var variantFilter = new VariantFilter();

        // so_annotations
        var annots = [];
        that.$('input.input-annot-child:checked').each(function() {
            annots.push($(this).data('annot'));
        });
        if (annots.length > 0) {
            variantFilter.set('so_annotations', annots);
        }

        // variant types
        if (this.vartype_widget.isActive()) {
            variantFilter.set('variant_types', this.vartype_widget.getSelections());
        }

        // allele frequency
        var frequency_filters = [];
        _.each(this.ref_freq_sliders, function(s, population) {
            var freq = parseFloat(utils.freqInverse(s.slider("value")));
            if (freq < 1) {
                frequency_filters.push([population, freq]);
            }
        });
        variantFilter.set('ref_freqs', frequency_filters);

        // predictions
        var annotations = {};
        if (this.polyphen_widget.isActive()) {
            var str_annots = this.polyphen_widget.getSelections();
            for (var i=0; i<str_annots.length; i++) {
                if (str_annots[i] == 'no_score') {
                    str_annots[i] = null;
                }
            }
            annotations.polyphen = str_annots;
        }
        if (this.sift_widget.isActive()) {
            var str_annots = this.sift_widget.getSelections();
            for (var i=0; i<str_annots.length; i++) {
                if (str_annots[i] == 'no_score') {
                    str_annots[i] = null;
                }
            }
            annotations.sift = str_annots;
        }
        if (this.muttaster_widget.isActive()) {
            var str_annots = this.muttaster_widget.getSelections();
            for (var i=0; i<str_annots.length; i++) {
                if (str_annots[i] == 'no_score') {
                    str_annots[i] = null;
                }
            }
            annotations.muttaster = str_annots;
        }
        if (this.fathmm_widget.isActive()) {
            var str_annots = this.fathmm_widget.getSelections();
            for (var i=0; i<str_annots.length; i++) {
                if (str_annots[i] == 'no_score') {
                    str_annots[i] = null;
                }
            }
            annotations.fathmm = str_annots;
        }
        variantFilter.set('annotations', annotations);

        // regions
        var region_text = $.trim(this.$('#region-coords').val());
        if (region_text != "") {
            variantFilter.set('regions', region_text.split('\n'));
        }

        // genes
        var genes_text = $.trim(this.$('#region-genes').val());
        if (genes_text != "") {
            variantFilter.set('genes_raw', genes_text);
        }

        return variantFilter;
    },

    standardSelectChange: function(event) {
        var filterSlug = $(event.target).val();
        var standardFilter = _.find(this.defaultVariantFilters, function(x) { return x.slug == filterSlug });

        if (standardFilter != undefined) {
            this.loadFromVariantFilter(standardFilter.variant_filter);
        } else {
            this.loadFromVariantFilter();
        }
        this.$('#variant-presets-select').val(filterSlug);
    },

    // TODO: get this out of here!
    create_ref_freq_sliders: function() {
        var that = this;

        this.ref_freq_sliders = {};
        _.each(this.reference_populations, function(pop) {
            var freqSliderInitialVal = 6;
            var newslider = that.$('.freq-slider[data-population="' + pop.slug + '"]').slider({
                min: 1,
                max: 6,
                step: 1,
                value: freqSliderInitialVal,
                slide: function(event, ui) {
                    that.$('.freq-slider-label[data-population="' + pop.slug + '"]').text( sliders.freqInverse(ui.value) );
                    that.$('.freq-slider-label[data-population="' + pop.slug + '"]').css("margin-left",(ui.value-1)/5*100+"%");
                }
            });
            that.ref_freq_sliders[pop.slug] = newslider;
            this.$( "#freqSliderLabel" ).text( sliders.freqInverse(freqSliderInitialVal) );
            this.$( "#freqSliderLabel" ).css("margin-left",(freqSliderInitialVal-1)/(5)*100+"%");
        });
    },

    setSlider: function(population, val) {
	    if(this.ref_freq_sliders[population]) {
		this.$('.freq-slider-label[data-population="' + population + '"]').text( val );
		this.$('.freq-slider-label[data-population="' + population + '"]').css("margin-left",(utils.freqIndex(val)-1)/(5)*100+"%");
		this.ref_freq_sliders[population].slider('value', utils.freqIndex(val));
	    }
    },

    /*
    TODO: right now we load from a javascript dict, but the get* methods return
    a backbone model. They should be consistent, but not sure which to use.
    */
    loadFromVariantFilter: function(variantFilter) {

        this.render();

        if (variantFilter == undefined) {
            variantFilter = {};
        }

        if (variantFilter.so_annotations != undefined) {
            var annots = variantFilter.so_annotations;
            this.$('.input-annot-child').each(function() {
                if (annots.indexOf($(this).data('annot')) == -1) {
                    $(this).attr('checked', false);
                } else {
                    $(this).attr('checked', true);
                }
            });

            for (var g in this.annotationReference.groups_map) {
                this.$('.input-annot-parent[data-annot="' + g + '"]').attr('checked', 'checked');
                var children = this.annotationReference.groups_map[g].children;
                _.each(children, function(c) {
                    if (!this.$('.input-annot-child[data-annot="' + c + '"]').is(':checked')) {
                        this.$('.input-annot-parent[data-annot="' + g + '"]').removeAttr('checked');
                    }
                });
            }
        }

        if (variantFilter.variant_types) {
            this.vartype_widget.set_selections(variantFilter.variant_types);
        }

        // update frequency slider
        if (variantFilter.ref_freqs != undefined) {
            var that = this;
            _.each(variantFilter.ref_freqs, function(ref_freq) {
                that.setSlider(ref_freq[0], ref_freq[1]);
            });
        }

        // polyphen
        //if (variantFilter.polyphen != undefined) {
        //    this.polyphen_widget.set_selections(variantFilter.polyphen);
        //    this.expand_section('predictions');
        //}
        //if (variantFilter.sift != undefined) {
        //    this.sift_widget.set_selections(variantFilter.sift);
        //    this.expand_section('predictions');
        //}

        //if (variantFilter.genes_raw != undefined) {
        //    this.$('#region-genes').html(variantFilter.genes_raw)
        //}
    },

    enablePrediction: function(event) {
        var prediction = $(event.target).attr('name');
        var state = $(event.target).val();
        this.setPredictionState(prediction, state);
    },

    setPredictionState: function(prediction, state) {
        if (state == 'all') {
            this.$('.enable-prediction[name="' + prediction + '"]').removeAttr('checked');
            this.$('.enable-prediction[name="' + prediction + '"][value="' + state + '"]').attr('checked', 'checked');
            this.$('.input-' + prediction).attr('disabled', 'disabled');
            this.$('.input-' + prediction).removeAttr('checked');
        } else {
            this.$('.input-' + prediction).removeAttr('disabled');
            this.$('.input-' + prediction).attr('checked', 'checked');
        }
    },

    // ensure a particular collapse is expanded
    expand_section: function(section_key) {
        this.$('#collapse-'+section_key).collapse('show');
    },

    // opposite of above
    collapse_section: function(section_key) {
        this.$('#collapse-'+section_key).collapse('show');
    },
});
<commit_msg>hotfix: selecting top-level functional annotation filters (like 'nonsense') worked when checked the first time, but not when unchecked and then checked again. This is now fixed.<commit_after>/*
Select variants to include in a search
Goal is to produce a variant filter that maps closely - but not exactly - to an xbrowse VariantFilter
todo: is that the goal?
 */
window.SelectVariantsView = Backbone.View.extend({

    initialize: function(options) {

        this.hbc = this.options.hbc;
        this.dictionary = this.hbc.dictionary;
        this.project_options = this.hbc.project_options;

        this.annotDefs = this.dictionary.annotation_reference.definitions_grouped;
        this.defaultVariantFilters = this.dictionary.default_variant_filters;
        this.annotationReference = this.dictionary.annotation_reference;
        this.defaultQualityFilters = this.dictionary.default_quality_filters;

        this.reference_populations = this.project_options.reference_populations || [];

        this.vartype_widget = new OrdinalFilterView({
            field_name: 'vartype',
            choices: [
                {slug: 'snp', title: 'SNPs'},
                {slug: 'indel', title: 'In/Dels'},
            ],
        });

        this.polyphen_widget = new OrdinalFilterView({
            field_name: 'polyphen',
            choices: [
                {slug: 'probably_damaging', title: 'Probably damaging'},
                {slug: 'possibly_damaging', title: 'Possibly damaging'},
                {slug: 'benign', title: 'Benign'},
                {slug: 'no_score', title: 'No prediction'},
            ],
        });

        this.sift_widget = new OrdinalFilterView({
            field_name: 'sift',
            choices: [
                {slug: 'damaging', title: 'Damaging'},
                {slug: 'tolerated', title: 'Tolerated'},
                {slug: 'no_score', title: 'No prediction'},
            ],
        });

        this.muttaster_widget = new OrdinalFilterView({
            field_name: 'muttaster',
            choices: [
                {slug: 'disease_causing', title: 'Disease Causing'},
                {slug: 'polymorphism', title: 'Polymorphism'},
                {slug: 'no_score', title: 'No Prediction'},
            ],
        });

        this.fathmm_widget = new OrdinalFilterView({
            field_name: 'fathmm',
            choices: [
                {slug: 'damaging', title: 'Damaging'},
                {slug: 'tolerated', title: 'Tolerated'},
                {slug: 'no_score', title: 'No Prediction'},
            ],
        });

    },

    template: _.template($('#tpl-select-variants').html()),

    events: {
        "change #variant-presets-select": "standardSelectChange",
        "click a.toggle-annotation-details": "toggleAnnotDetails",
        "change .input-annot-parent": "inputAnnotParent",
        "change .input-annot-child": "inputAnnotChild",
        'change .enable-prediction': 'enablePrediction',
        'change #gene_list_select': 'setGeneList'
    },

    setGeneList: function(event) {
    	if(event.currentTarget.value == '---') {
    		$('#region-genes').text('');
    	} else {
    		_.each(this.hbc.gene_lists, function(gene_list) {
	    		if(gene_list['slug'] == event.currentTarget.value) {
	    			var genes_string = _.map(gene_list['genes'], function(gene) {
	    				return gene['gene_id'];
	    			}).join('\n');
    				$('#region-genes').text(genes_string);
    			}
    		});
    	}
    },

    toggleAnnotDetails: function(event) {
        var annotGroup = $(event.target).data('annot');
        var box = this.$('.annotation-details[data-annot="' + annotGroup + '"]');
        box.toggle();
    },

    inputAnnotParent: function(event) {
        var annotGroup = $(event.target).data('annot');
        if ($(event.target).is(':checked')) {
            this.$('.input-annot-child[data-parent="' + annotGroup + '"]').prop('checked', true);
        } else {
            this.$('.input-annot-child[data-parent="' + annotGroup + '"]').prop('checked', false);
        }
    },

    inputAnnotChild: function(event) {
        var annotGroup = $(event.target).data('parent');
        if (!$(event.target).is(':checked')) {
            this.$('.input-annot-parent[data-annot="' + annotGroup + '"]').prop('checked', false);
        }
    },

    render: function() {
        $(this.el).html(this.template({
        	hbc: this.hbc,
            annotDefs: this.annotDefs,
            defaultVariantFilters: this.defaultVariantFilters,
            reference_populations: this.reference_populations,
        }));

        this.create_ref_freq_sliders();
        this.vartype_widget.setElement(this.$('#vartype-widget-container')).render();
        this.polyphen_widget.setElement(this.$('#polyphen-widget-container')).render();
        this.sift_widget.setElement(this.$('#sift-widget-container')).render();
        this.muttaster_widget.setElement(this.$('#muttaster-widget-container')).render();
        this.fathmm_widget.setElement(this.$('#fathmm-widget-container')).render();
        utils.initializeHovers(this);

        return this;
    },

    getVariantFilter: function() {

        var that = this;

        var variantFilter = new VariantFilter();

        // so_annotations
        var annots = [];
        that.$('input.input-annot-child:checked').each(function() {
            annots.push($(this).data('annot'));
        });

        // variant types
        if (this.vartype_widget.isActive()) {
            variantFilter.set('variant_types', this.vartype_widget.getSelections());
        }

        // allele frequency
        var frequency_filters = [];
        _.each(this.ref_freq_sliders, function(s, population) {
            var freq = parseFloat(utils.freqInverse(s.slider("value")));
            if (freq < 1) {
                frequency_filters.push([population, freq]);
            }
        });
        variantFilter.set('ref_freqs', frequency_filters);

        // predictions
        var annotations = {};
        if (this.polyphen_widget.isActive()) {
            var str_annots = this.polyphen_widget.getSelections();
            for (var i=0; i<str_annots.length; i++) {
                if (str_annots[i] == 'no_score') {
                    str_annots[i] = null;
                }
            }
            annotations.polyphen = str_annots;
        }
        if (this.sift_widget.isActive()) {
            var str_annots = this.sift_widget.getSelections();
            for (var i=0; i<str_annots.length; i++) {
                if (str_annots[i] == 'no_score') {
                    str_annots[i] = null;
                }
            }
            annotations.sift = str_annots;
        }
        if (this.muttaster_widget.isActive()) {
            var str_annots = this.muttaster_widget.getSelections();
            for (var i=0; i<str_annots.length; i++) {
                if (str_annots[i] == 'no_score') {
                    str_annots[i] = null;
                }
            }
            annotations.muttaster = str_annots;
        }
        if (this.fathmm_widget.isActive()) {
            var str_annots = this.fathmm_widget.getSelections();
            for (var i=0; i<str_annots.length; i++) {
                if (str_annots[i] == 'no_score') {
                    str_annots[i] = null;
                }
            }
            annotations.fathmm = str_annots;
        }
        variantFilter.set('annotations', annotations);

        // regions
        var region_text = $.trim(this.$('#region-coords').val());
        if (region_text != "") {
            variantFilter.set('regions', region_text.split('\n'));
        }

        // genes
        var genes_text = $.trim(this.$('#region-genes').val());
        if (genes_text != "") {
            variantFilter.set('genes_raw', genes_text);
        }

        return variantFilter;
    },

    standardSelectChange: function(event) {
        var filterSlug = $(event.target).val();
        var standardFilter = _.find(this.defaultVariantFilters, function(x) { return x.slug == filterSlug });

        if (standardFilter != undefined) {
            this.loadFromVariantFilter(standardFilter.variant_filter);
        } else {
            this.loadFromVariantFilter();
        }
        this.$('#variant-presets-select').val(filterSlug);
    },

    // TODO: get this out of here!
    create_ref_freq_sliders: function() {
        var that = this;

        this.ref_freq_sliders = {};
        _.each(this.reference_populations, function(pop) {
            var freqSliderInitialVal = 6;
            var newslider = that.$('.freq-slider[data-population="' + pop.slug + '"]').slider({
                min: 1,
                max: 6,
                step: 1,
                value: freqSliderInitialVal,
                slide: function(event, ui) {
                    that.$('.freq-slider-label[data-population="' + pop.slug + '"]').text( sliders.freqInverse(ui.value) );
                    that.$('.freq-slider-label[data-population="' + pop.slug + '"]').css("margin-left",(ui.value-1)/5*100+"%");
                }
            });
            that.ref_freq_sliders[pop.slug] = newslider;
            this.$( "#freqSliderLabel" ).text( sliders.freqInverse(freqSliderInitialVal) );
            this.$( "#freqSliderLabel" ).css("margin-left",(freqSliderInitialVal-1)/(5)*100+"%");
        });
    },

    setSlider: function(population, val) {
	    if(this.ref_freq_sliders[population]) {
		this.$('.freq-slider-label[data-population="' + population + '"]').text( val );
		this.$('.freq-slider-label[data-population="' + population + '"]').css("margin-left",(utils.freqIndex(val)-1)/(5)*100+"%");
		this.ref_freq_sliders[population].slider('value', utils.freqIndex(val));
	    }
    },

    /*
    TODO: right now we load from a javascript dict, but the get* methods return
    a backbone model. They should be consistent, but not sure which to use.
    */
    loadFromVariantFilter: function(variantFilter) {

        this.render();

        if (variantFilter == undefined) {
            variantFilter = {};
        }

        if (variantFilter.so_annotations != undefined) {
            var annots = variantFilter.so_annotations;
            this.$('.input-annot-child').each(function() {
                if (annots.indexOf($(this).data('annot')) == -1) {
                    $(this).prop('checked', false);
                } else {
                    $(this).prop('checked', true);
                }
            });

            for (var g in this.annotationReference.groups_map) {
                this.$('.input-annot-parent[data-annot="' + g + '"]').prop('checked', true);
                var children = this.annotationReference.groups_map[g].children;
                _.each(children, function(c) {
                    if (!this.$('.input-annot-child[data-annot="' + c + '"]').is(':checked')) {
                        this.$('.input-annot-parent[data-annot="' + g + '"]').prop('checked', false);
                    }
                });
            }
        }

        if (variantFilter.variant_types) {
            this.vartype_widget.set_selections(variantFilter.variant_types);
        }

        // update frequency slider
        if (variantFilter.ref_freqs != undefined) {
            var that = this;
            _.each(variantFilter.ref_freqs, function(ref_freq) {
                that.setSlider(ref_freq[0], ref_freq[1]);
            });
        }

        // polyphen
        //if (variantFilter.polyphen != undefined) {
        //    this.polyphen_widget.set_selections(variantFilter.polyphen);
        //    this.expand_section('predictions');
        //}
        //if (variantFilter.sift != undefined) {
        //    this.sift_widget.set_selections(variantFilter.sift);
        //    this.expand_section('predictions');
        //}

        //if (variantFilter.genes_raw != undefined) {
        //    this.$('#region-genes').html(variantFilter.genes_raw)
        //}
    },

    enablePrediction: function(event) {
        var prediction = $(event.target).attr('name');
        var state = $(event.target).val();
        this.setPredictionState(prediction, state);
    },

    setPredictionState: function(prediction, state) {
        if (state == 'all') {
            this.$('.enable-prediction[name="' + prediction + '"]').prop('checked', false);
            this.$('.enable-prediction[name="' + prediction + '"][value="' + state + '"]').prop('checked', true);
            this.$('.input-' + prediction).attr('disabled', 'disabled');
            this.$('.input-' + prediction).removeAttr('checked');
        } else {
            this.$('.input-' + prediction).removeAttr('disabled');
            this.$('.input-' + prediction).attr('checked', 'checked');
        }
    },

    // ensure a particular collapse is expanded
    expand_section: function(section_key) {
        this.$('#collapse-'+section_key).collapse('show');
    },

    // opposite of above
    collapse_section: function(section_key) {
        this.$('#collapse-'+section_key).collapse('show');
    },
});
<|endoftext|>


<commit_before>'use strict'
module.exports = ficInflate

const Bluebird = require('bluebird')
const qw = require('qw')

const progress = use('progress')

// Take a fic and fetch all its chapters and ensure its per-chapter metadata
// is fully complete.

function ficInflate (fic, fetch, tracker) {
  if (!tracker) tracker = progress.tracker
  return fic.then(fic => {
    const fics = [fic].concat(fic.fics)
    const completion = new Map()
    for (let fic of fics) {
      completion.set(fic, tracker.newItem(fic.title, fic.chapters.length))
    }
    return Bluebird.map(fics, fic => {
      const tracker = completion.get(fic)
      process.emit('debug', 'Inflating', fic.title, 'chapters:', fic.chapters.length)
      let words = 0
      return Bluebird.map(fic.chapters, chapterInfo => {
        const chapterContent = chapterInfo.getContent(fetch)
        return progress.completeWorkWhenResolved(chapterContent, tracker).then(chapter => {
          process.emit('debug', `Got content for #${chapterInfo.order}: ${chapterInfo.name}`)
          progress.show(fic.title, `${chapterInfo.name}`)
          chapterInfo.words = chapter.words
          words += chapter.words
          if (chapterInfo.link == null) chapterInfo.link = chapter.chapterLink
          for (let prop of qw`name author authorUrl created modified headings`) {
            if (chapterInfo[prop] == null) chapterInfo[prop] = chapter[prop]
          }
          if (chapterInfo.author === fic.author || chapterInfo.authorUrl === fic.authorUrl) {
            chapterInfo.author = null
            chapterInfo.authorUrl = null
          }
        }).catch(err => {
          chapterInfo.error = err
          process.emit('error', err.message)
        })
      }).finally(() => {
        if (!fic.words) fic.words = words
        if (fic.chapters.length) {
          const firstChapter = fic.chapters[0]
          const lastChapter = fic.chapters[fic.chapters.length - 1]
          if (firstChapter.created == null && firstChapter.modified == null && fic.created != null) {
            firstChapter.created = fic.created
          }
          if (lastChapter.created == null && lastChapter.modified == null && fic.modified != null) {
            lastChapter.modified = fic.modified
          }
        }
        tracker.finish()
      })
    })
  }).thenReturn(fic)
}
<commit_msg>fic-inflate: Allow calling with non-promises<commit_after>'use strict'
module.exports = ficInflate

const Bluebird = require('bluebird')
const qw = require('qw')

const progress = use('progress')

// Take a fic and fetch all its chapters and ensure its per-chapter metadata
// is fully complete.

function ficInflate (fic, fetch, tracker) {
  if (!tracker) tracker = progress.tracker
  return Bluebird.resolve(fic).then(fic => {
    const fics = [fic].concat(fic.fics)
    const completion = new Map()
    for (let fic of fics) {
      completion.set(fic, tracker.newItem(fic.title, fic.chapters.length))
    }
    return Bluebird.map(fics, fic => {
      const tracker = completion.get(fic)
      process.emit('debug', 'Inflating', fic.title, 'chapters:', fic.chapters.length)
      let words = 0
      return Bluebird.map(fic.chapters, chapterInfo => {
        const chapterContent = chapterInfo.getContent(fetch)
        return progress.completeWorkWhenResolved(chapterContent, tracker).then(chapter => {
          process.emit('debug', `Got content for #${chapterInfo.order}: ${chapterInfo.name}`)
          progress.show(fic.title, `${chapterInfo.name}`)
          chapterInfo.words = chapter.words
          words += chapter.words
          if (chapterInfo.link == null) chapterInfo.link = chapter.chapterLink
          for (let prop of qw`name author authorUrl created modified headings`) {
            if (chapterInfo[prop] == null) chapterInfo[prop] = chapter[prop]
          }
          if (chapterInfo.author === fic.author || chapterInfo.authorUrl === fic.authorUrl) {
            chapterInfo.author = null
            chapterInfo.authorUrl = null
          }
        }).catch(err => {
          chapterInfo.error = err
          process.emit('error', err.message)
        })
      }).finally(() => {
        if (!fic.words) fic.words = words
        if (fic.chapters.length) {
          const firstChapter = fic.chapters[0]
          const lastChapter = fic.chapters[fic.chapters.length - 1]
          if (firstChapter.created == null && firstChapter.modified == null && fic.created != null) {
            firstChapter.created = fic.created
          }
          if (lastChapter.created == null && lastChapter.modified == null && fic.modified != null) {
            lastChapter.modified = fic.modified
          }
        }
        tracker.finish()
      })
    })
  }).thenReturn(fic)
}
<|endoftext|>


<commit_before>'use strict';

require('./lib/common/init');

var spawn = require('child_process').spawn,
    path = require('path'),
    fs = require('fs')
;

// Retrieve gulp command path.
var gulpCommandPath = path.join(__dirname, 'node_modules/.bin/gulp');

try {
    fs.statSync(gulpCommandPath);
} catch (error) {
    // Handle not existing modules folder.
    if (!(error.code in {'ENOENT': true, 'ENOTDIR': true})) {
        throw error;
    }

    gulpCommandPath = path.join(__dirname, '../../node_modules/.bin/gulp');
}

// Handle "&&" separated commands.
var commands = process.argv.slice(2).join(' ').split('&&');

for (var i = 0; i < commands.length; i++) {
    var command = commands[i],
        commandParts = command.split(' '),
        task = commandParts[0]
    ;

    if (task in {'execute-cmd': true, '$': true}) {
        command = '{0} --cmd {1} {2}'.format(
            commandParts.shift(),
            commandParts.shift(),
            commandParts.join(' ')
        );
    }

    var args = process.argv.slice(2, 3).concat(['--colors']).concat(process.argv.slice(3));

    for (var j = 1; j < args.length; j++) {
        // Escape value parameter to avoid being interpreted as a task by gulp.
        if (/^[^-"]/.test(args[j])) {
            args[j] = '---{0}'.format(args[j]);
        }
    }

    // Forward the task execution to gulp.
    var child = spawn(
            gulpCommandPath,
            args,
            {
                cwd: path.dirname(require.main.filename)
            }
        ),
        errored = false;
    ;

    child.stdout.on('data', function(data) {
        process.stdout.write(data);
    });
    child.stderr.on('data', function(data) {
        errored = true;
        process.stderr.write(data);
    });
    child.on('close', function(data) {
        process.exit(errored ? 1 : 0);
    });
}<commit_msg>Fix Windows command compatibility<commit_after>'use strict';

require('./lib/common/init');

var spawn = require('child_process').spawn,
    path = require('path'),
    fs = require('fs'),
    os = require('os')
;

// Retrieve gulp command path.
var gulpCommandPath = path.join(
        __dirname,
        -1 === os.platform().indexOf('win')
            ? 'node_modules/.bin/gulp'
            : 'node_modules/.bin/gulp.cmd'
    )
;

try {
    fs.statSync(gulpCommandPath);
} catch (error) {
    // Handle not existing modules folder.
    if (!(error.code in {'ENOENT': true, 'ENOTDIR': true})) {
        throw error;
    }

    gulpCommandPath = path.join(
        __dirname,
        -1 === os.platform().indexOf('win')
            ? '../../node_modules/.bin/gulp'
            : '../../node_modules/.bin/gulp.cmd'
    );
}

// Handle "&&" separated commands.
var commands = process.argv.slice(2).join(' ').split('&&');

for (var i = 0; i < commands.length; i++) {
    var command = commands[i],
        commandParts = command.split(' '),
        task = commandParts[0]
    ;

    if (task in {'execute-cmd': true, '$': true}) {
        command = '{0} --cmd {1} {2}'.format(
            commandParts.shift(),
            commandParts.shift(),
            commandParts.join(' ')
        );
    }

    var args = process.argv.slice(2, 3).concat(['--colors']).concat(process.argv.slice(3));

    for (var j = 1; j < args.length; j++) {
        // Escape value parameter to avoid being interpreted as a task by gulp.
        if (/^[^-"]/.test(args[j])) {
            args[j] = '---{0}'.format(args[j]);
        }
    }

    // Forward the task execution to gulp.
    var child = spawn(
            gulpCommandPath,
            args,
            {
                cwd: path.dirname(require.main.filename)
            }
        ),
        errored = false;
    ;

    child.stdout.on('data', function(data) {
        process.stdout.write(data);
    });
    child.stderr.on('data', function(data) {
        errored = true;
        process.stderr.write(data);
    });
    child.on('close', function(data) {
        process.exit(errored ? 1 : 0);
    });
}<|endoftext|>


<commit_before>"use strict";

var m      = require("mithril"),
    assign = require("lodash.assign"),

    db = require("../lib/firebase");

function update(db, name, val) {
    var args = {};

    args[name] = val;

    db.update(args);
}

module.exports = {
    display : {
        controller : function(options) {
            var ctrl  = this,
                field = db.child("fields/" + options.field),
                data  = db.child("data/" + options.data);

            ctrl.field = null;
            ctrl.data  = {
                value : ""
            };

            field.on("value", function(snap) {
                ctrl.field = snap.val();

                m.redraw();
            });

            data.on("value", function(snap) {
                ctrl.data = snap.val();

                m.redraw();
            });

            ctrl.oninput = function(value) {
                data.update({
                    value : value
                });
            };
        },

        view : function(ctrl) {
            if(!ctrl.field) {
                return m("span", "Loading...");
            }

            return m("label", ctrl.field.name,
                m("input", assign({}, ctrl.field, ctrl.data, {
                    oninput : m.withAttr("value", ctrl.oninput)
                }))
            );
        }
    },

    edit : {
        controller : function(options) {
            var ctrl  = this,
                field = db.child("fields/" + options.field);

            ctrl.options = options;
            ctrl.field   = null;

            field.on("value", function(snap) {
                ctrl.field = snap.val();

                m.redraw();
            });

            ctrl.nameChange        = update.bind(null, field, "name");
            ctrl.placeholderChange = update.bind(null, field, "placeholder");
            ctrl.disabledChange    = update.bind(null, field, "disabled");
            ctrl.readonlyChange    = update.bind(null, field, "readonly");
        },

        view : function(ctrl) {
            if(!ctrl.field) {
                return m("span", "Loading...");
            }

            return m("ul",
                m("li",
                    m("label",
                        "Name",
                        m("input", {
                            oninput : m.withAttr("value", ctrl.nameChange),
                            value   : ctrl.field.name || ""
                        })
                    )
                ),
                m("li",
                    m("label",
                        "Placeholder",
                        m("input", {
                            oninput : m.withAttr("value", ctrl.placeholderChange),
                            value   : ctrl.field.placeholder || ""
                        })
                    )
                ),
                m("li",
                    m("label",
                        m("input[type=checkbox]", {
                            onclick : m.withAttr("checked", ctrl.disabledChange),
                            checked : ctrl.field.disabled || false
                        }),
                        "Disabled"
                    )
                ),
                m("li",
                    m("label",
                        m("input[type=checkbox]", {
                            onclick : m.withAttr("checked", ctrl.readonlyChange),
                            checked : ctrl.field.readonly || false
                        }),
                        "Read-Only"
                    )
                )
            );
        }
    }
};
<commit_msg>Keep fields db entries lean :muscle:<commit_after>"use strict";

var m      = require("mithril"),
    assign = require("lodash.assign"),

    db = require("../lib/firebase");

function update(db, name, val) {
    var args = {};

    if(!val) {
        return db.child(name).remove();
    }

    args[name] = val;

    db.update(args);
}

module.exports = {
    display : {
        controller : function(options) {
            var ctrl  = this,
                field = db.child("fields/" + options.field),
                data  = db.child("data/" + options.data);

            ctrl.field = null;
            ctrl.data  = {
                value : ""
            };

            field.on("value", function(snap) {
                ctrl.field = snap.val();

                m.redraw();
            });

            data.on("value", function(snap) {
                ctrl.data = snap.val();

                m.redraw();
            });

            ctrl.oninput = function(value) {
                data.update({
                    value : value
                });
            };
        },

        view : function(ctrl) {
            if(!ctrl.field) {
                return m("span", "Loading...");
            }

            return m("label", ctrl.field.name,
                m("input", assign({}, ctrl.field, ctrl.data, {
                    oninput : m.withAttr("value", ctrl.oninput)
                }))
            );
        }
    },

    edit : {
        controller : function(options) {
            var ctrl  = this,
                field = db.child("fields/" + options.field);

            ctrl.options = options;
            ctrl.field   = null;

            field.on("value", function(snap) {
                ctrl.field = snap.val();

                m.redraw();
            });

            ctrl.nameChange        = update.bind(null, field, "name");
            ctrl.placeholderChange = update.bind(null, field, "placeholder");
            ctrl.disabledChange    = update.bind(null, field, "disabled");
            ctrl.readonlyChange    = update.bind(null, field, "readonly");
        },

        view : function(ctrl) {
            if(!ctrl.field) {
                return m("span", "Loading...");
            }

            return m("ul",
                m("li",
                    m("label",
                        "Name",
                        m("input", {
                            oninput : m.withAttr("value", ctrl.nameChange),
                            value   : ctrl.field.name || ""
                        })
                    )
                ),
                m("li",
                    m("label",
                        "Placeholder",
                        m("input", {
                            oninput : m.withAttr("value", ctrl.placeholderChange),
                            value   : ctrl.field.placeholder || ""
                        })
                    )
                ),
                m("li",
                    m("label",
                        m("input[type=checkbox]", {
                            onclick : m.withAttr("checked", ctrl.disabledChange),
                            checked : ctrl.field.disabled || false
                        }),
                        "Disabled"
                    )
                ),
                m("li",
                    m("label",
                        m("input[type=checkbox]", {
                            onclick : m.withAttr("checked", ctrl.readonlyChange),
                            checked : ctrl.field.readonly || false
                        }),
                        "Read-Only"
                    )
                )
            );
        }
    }
};
<|endoftext|>


<commit_before>"use strict";

var m      = require("mithril"),
    assign = require("lodash.assign"),

    db = require("../lib/firebase");

function update(db, name, val) {
    var args = {};

    if(!val) {
        return db.child(name).remove();
    }

    args[name] = val;

    db.update(args);
}

module.exports = {
    display : {
        controller : function(options) {
            var ctrl = this;

            ctrl.field = {};

            options.field.on("value", function(snap) {
                ctrl.field = snap.val();

                m.redraw();
            });

            if(options.data) {
                options.data.on("value", function(snap) {
                    ctrl.data = snap.val();

                    m.redraw();
                });
            }

            ctrl.oninput = function(value) {
                options.callback(value);
            };
        },

        view : function(ctrl) {
            if(!ctrl.field) {
                return m("span", "Loading...");
            }

            return m("label", ctrl.field.name + ": ",
                m("input", assign({}, ctrl.field, { value : ctrl.data || "" }, {
                    oninput : m.withAttr("value", ctrl.oninput)
                }))
            );
        }
    },

    edit : {
        controller : function(options) {
            var ctrl  = this;

            ctrl.field = null;

            options.field.on("value", function(snap) {
                ctrl.field = snap.val();

                m.redraw();
            });

            ctrl.nameChange        = update.bind(null, options.field, "name");
            ctrl.placeholderChange = update.bind(null, options.field, "placeholder");
            ctrl.disabledChange    = update.bind(null, options.field, "disabled");
            ctrl.readonlyChange    = update.bind(null, options.field, "readonly");
        },

        view : function(ctrl) {
            if(!ctrl.field) {
                return m("span", "Loading...");
            }

            return m("ul",
                m("li",
                    m("label",
                        "Name: ",
                        m("input", {
                            oninput : m.withAttr("value", ctrl.nameChange),
                            value   : ctrl.field.name || "",
                            config  : function(el, init) {
                                if(init) {
                                    return;
                                }

                                el.select();
                            }
                        })
                    )
                ),
                m("li",
                    m("label",
                        "Placeholder: ",
                        m("input", {
                            oninput : m.withAttr("value", ctrl.placeholderChange),
                            value   : ctrl.field.placeholder || ""
                        })
                    )
                ),
                m("li",
                    m("label",
                        m("input[type=checkbox]", {
                            onclick : m.withAttr("checked", ctrl.disabledChange),
                            checked : ctrl.field.disabled || false
                        }),
                        " Disabled"
                    )
                ),
                m("li",
                    m("label",
                        m("input[type=checkbox]", {
                            onclick : m.withAttr("checked", ctrl.readonlyChange),
                            checked : ctrl.field.readonly || false
                        }),
                        " Read-Only"
                    )
                )
            );
        }
    }
};
<commit_msg>Simplify a touch<commit_after>"use strict";

var m      = require("mithril"),
    assign = require("lodash.assign"),

    db = require("../lib/firebase");

module.exports = {
    display : {
        controller : function(options) {
            var ctrl = this;

            ctrl.field = {};

            options.field.on("value", function(snap) {
                ctrl.field = snap.val();

                m.redraw();
            });

            if(options.data) {
                options.data.on("value", function(snap) {
                    ctrl.data = snap.val();

                    m.redraw();
                });
            }

            ctrl.oninput = function(value) {
                options.callback(value);
            };
        },

        view : function(ctrl) {
            if(!ctrl.field) {
                return m("span", "Loading...");
            }

            return m("label", ctrl.field.name + ": ",
                m("input", assign({}, ctrl.field, { value : ctrl.data || "" }, {
                    oninput : m.withAttr("value", ctrl.oninput)
                }))
            );
        }
    },

    edit : {
        controller : function(options) {
            var ctrl  = this;

            ctrl.field = null;

            options.field.on("value", function(snap) {
                ctrl.field = snap.val();

                m.redraw();
            });

            ctrl.update = function(name, val) {
                var args = {};

                if(!val) {
                    return options.field.child(name).remove();
                }

                args[name] = val;

                options.field.update(args);
            }
        },

        view : function(ctrl) {
            if(!ctrl.field) {
                return m("span", "Loading...");
            }

            return m("ul",
                m("li",
                    m("label",
                        "Name: ",
                        m("input", {
                            oninput : m.withAttr("value", ctrl.update.bind(ctrl, "name")),
                            value   : ctrl.field.name || "",
                            config  : function(el, init) {
                                if(init) {
                                    return;
                                }

                                el.select();
                            }
                        })
                    )
                ),
                m("li",
                    m("label",
                        "Placeholder: ",
                        m("input", {
                            oninput : m.withAttr("value", ctrl.update.bind(ctrl, "placeholder")),
                            value   : ctrl.field.placeholder || ""
                        })
                    )
                ),
                m("li",
                    m("label",
                        m("input[type=checkbox]", {
                            onclick : m.withAttr("checked", ctrl.update.bind(ctrl, "disabled")),
                            checked : ctrl.field.disabled || false
                        }),
                        " Disabled"
                    )
                ),
                m("li",
                    m("label",
                        m("input[type=checkbox]", {
                            onclick : m.withAttr("checked", ctrl.update.bind(ctrl, "readonly")),
                            checked : ctrl.field.readonly || false
                        }),
                        " Read-Only"
                    )
                )
            );
        }
    }
};
<|endoftext|>