<commit_before>//--------------------------------------------------
// Photo-booth service
// by: Alexander Terczka <alex@mail.at>
//--------------------------------------------------

// --- settings
var slideshowdir = "images/slideshow/";
var port = 8082;

// --- requires
var fs = require('fs');
var express = require('express');
var exec = require('child_process').exec;

var app = express();

var slides=[];

function read_slideshow_dir(callback)
{
    fs.readdir(slideshowdir,function (err,files) {
	if (err) { throw new Error(err); }
	slides=files;
	callback();
    });
}

//
// ----  API URLs
//
    app.get("/capture",function(req,res) {
        // Capture a photo using die capture shell script
	// and send the name to the browser or error text
        exec('./capture-photo.sh', function (error, stdout, stderr) {
  	    if (error) res.send({error: "Capture Script Fehler"});
  	    else if (stdout=="ERROR") res.send({error: "Kamera Fehler"});
  	    else res.send({image:stdout.trim()});
	});
    });

    app.get("/images.json",function(req,res) {
        res.send(slides);
    });

    app.get("/new.images.json",function(req,res) {
        // TODO: browser asks what images to show
	// server answers delayed (long polling) when nothing changed
        res.send("new.images.json");
    });

//
// ---- Client Libraries
//
    app.use("/jquery",express.static('node_modules/jquery/dist/'));

//
// ----  serve static files from "htdocs" files
//
    app.get('/', function (req, res) {
        res.sendFile(__dirname+"/htdocs/index.html");
    });

    app.use(express.static('htdocs'));
    app.use("/images",express.static('images/slideshow/'));

//
// ---- Startup
//
read_slideshow_dir(run);

//
// ---- GO!
//
function run()
{
    app.listen(port, function () { console.log("Photo-booth service listening on port "+port+"!"); });
}
<commit_msg>read slideshow dir handling changed<commit_after>//--------------------------------------------------
// Photo-booth service
// by: Alexander Terczka <alex@mail.at>
//--------------------------------------------------

// --- settings
var slideshowdir = "images/slideshow/";
var port = 8082;

// --- requires
var fs = require('fs');
var express = require('express');
var exec = require('child_process').exec;

var app = express();

function read_slideshow_dir(callback)
{
    fs.readdir(slideshowdir,function (err,files) {
	if (err) { throw new Error(err); }
	callback(files);
    });
}

//
// ----  API URLs
//
    app.get("/capture",function(req,res) {
        // Capture a photo using die capture shell script
	// and send the name to the browser or error text
        exec('./capture-photo.sh', function (error, stdout, stderr) {
  	    if (error) res.send({error: "Capture Script Fehler"});
  	    else if (stdout.trim()=="ERROR") res.send({error: "Kamera Fehler"});
  	    else res.send({image:stdout.trim()});
	});
    });

    app.get("/images.json",function(req,res) {
        read_slideshow_dir(function (data) { res.send(data); });
    });

    app.get("/new.images.json",function(req,res) {
        // TODO: browser asks what images to show
	// server answers delayed (long polling) when nothing changed
        res.send("new.images.json");
    });

//
// ---- Client Libraries
//
    app.use("/jquery",express.static('node_modules/jquery/dist/'));

//
// ----  serve static files from "htdocs" files
//
    app.get('/', function (req, res) {
        res.sendFile(__dirname+"/htdocs/index.html");
    });

    app.use(express.static('htdocs'));
    app.use("/images",express.static('images/slideshow/'));

//
// ---- Startup
//

//
// ---- GO!
//
    app.listen(port, function () { console.log("Photo-booth service listening on port "+port+"!"); });
<|endoftext|>


<commit_before>var api = require('./api');
var pap = require('../pap');

// TODO: Check how to share app with PAP
function init(settings) {
    return new Promise(function(resolve, reject) {
        pap.init(settings.pap).then(function() {
            api.init(settings.pdp, pap).then(function(fresh) {
                resolve(fresh);
            }, function(e) {
                reject(e);
            });
        }, function(e) {
            reject(e);
        });
    });
}

function finish() {
    return new Promise(function(resolve, reject) {
        api.finish().then(function() {
            pap.finish().then(function(r) {
                resolve(r);
            }, function(e) {
                reject(e);
            });
        }, function(e) {
            reject(e);
        });
    });
}

module.exports = {
    init: init,
    finish: finish,
    checkRead : api.checkRead,
    checkWrite : api.checkWrite,
    pap: pap
}
<commit_msg>Allow PDP to be initialized with existing PAP and export new API<commit_after>var api = require('./api');
var pap = require('../pap');

var Promise = require("bluebird");

var initialized = false;

function init(settings, _pap) {
    if(initialized) {
        // console.log(process.pid + ": PDP has already been initialized. Skip");
        return Promise.resolve(this);
    } else {
        // console.log(process.pid + ": Init PDP.");
        initialized = true;
    }

    if(_pap === undefined) {
        // console.log("PDP init WO PAP");
        return pap.init(settings).
            then(api.init.bind(null, settings, pap));
    } else {
        // console.log("PDP init WITH PAP");
        api.init(settings, _pap)
        return Promise.resolve(this);
    }
}

function finish() {
    return new Promise(function(resolve, reject) {
        api.finish().then(function() {
            pap.finish().then(function(r) {
                resolve(r);
            }, function(e) {
                reject(e);
            });
        }, function(e) {
            reject(e);
        });
    });
}

module.exports = {
    init: init,
    finish: finish,
    checkRead: api.checkRead,
    checkWrite: api.checkWrite,
    checkAccess: api.checkAccess,
    pap: pap
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import Base from '../mixins/base';

export default Ember.Mixin.create(Base, {
  module: 'modal',
  classNames: [ 'ui', 'modal' ],
  closable: false,
  transition: 'horizontal flip',

  setup: function() {
    this.set('hiding', false);
  }.on('init'),

  didInsertElement: function() {
    this._super();
    this.execute('show');
  },

  willDestroyElement: function() {
    this._super();
    Ember.assert("Semantic modal was destoryed without being properly hidden. Don't call closeModal from the controller.", this.get('hiding'));
  },

  onHide: function() {
    this.set('hiding', true);
    var controller = this.checkControllerForAction('hide');
    if (controller) {
      // we don't pass in view, since you can't stop it from hiding once it starts
      controller.send('hide');
    }
  },

  onHidden: function() {
    if (this.get('controller')) {
      this.get('controller').send('closeModal');
    }
  },

  onDeny: function() {
    var controller = this.checkControllerForAction('deny');
    if (controller) {
      // if controller handles approves, they must manually call view.execute('hide')
      controller.send('deny', this);
      return false
    }
    return true;
  },

  onApprove: function() {
    var controller = this.checkControllerForAction('approve');
    if (controller) {
      // if controller handles approves, they must manually call view.execute('hide')
      controller.send('approve', this);
      return false
    }
    return true;
  },

  checkControllerForAction: function(action) {
    var controller = this.get('controller');
    if (typeof controller !== "undefined" && controller !== null &&
        typeof controller._actions !== "undefined" && controller._actions !== null &&
        typeof controller._actions[action] !== "undefined" && controller._actions[action] !== null) {
      return controller;
    }
    return false
  }
});
<commit_msg>Updating description<commit_after>import Ember from 'ember';
import Base from '../mixins/base';

export default Ember.Mixin.create(Base, {
  module: 'modal',
  classNames: [ 'ui', 'modal' ],
  closable: false,
  transition: 'horizontal flip',

  setup: function() {
    this.set('hiding', false);
  }.on('init'),

  didInsertElement: function() {
    this._super();
    this.execute('show');
  },

  willDestroyElement: function() {
    this._super();
    Ember.assert("Semantic modal was destoryed without being properly hidden. Don't call closeModal from the controller. Instead add an approve or deny action, and then call view.execute('hide') from the view passed in.", this.get('hiding'));
  },

  onHide: function() {
    this.set('hiding', true);
    var controller = this.checkControllerForAction('hide');
    if (controller) {
      // we don't pass in view, since you can't stop it from hiding once it starts
      controller.send('hide');
    }
  },

  onHidden: function() {
    if (this.get('controller')) {
      this.get('controller').send('closeModal');
    }
  },

  onDeny: function() {
    var controller = this.checkControllerForAction('deny');
    if (controller) {
      // if controller handles approves, they must manually call view.execute('hide')
      controller.send('deny', this);
      return false
    }
    return true;
  },

  onApprove: function() {
    var controller = this.checkControllerForAction('approve');
    if (controller) {
      // if controller handles approves, they must manually call view.execute('hide')
      controller.send('approve', this);
      return false
    }
    return true;
  },

  checkControllerForAction: function(action) {
    var controller = this.get('controller');
    if (typeof controller !== "undefined" && controller !== null &&
        typeof controller._actions !== "undefined" && controller._actions !== null &&
        typeof controller._actions[action] !== "undefined" && controller._actions[action] !== null) {
      return controller;
    }
    return false
  }
});
<|endoftext|>


<commit_before><commit_msg>auto-download test data on 'npm run test'<commit_after><|endoftext|>


<commit_before>import Ember from 'ember';
import XHRError from './xhr-error';

const { get, isNone } = Ember;

export function getContext(router) {
  var infos = router.currentState.routerJsState.handlerInfos;

  var url = router.get('location').getURL().split("?")[0];
  var routeName = infos[infos.length - 1].name;

  var firstSegments = routeName.replace(".index", "").replace(/\./g, ' ');
  var prettyRouteName = Ember.String.capitalize(firstSegments);

  return prettyRouteName + " (" + routeName + ", " + url + ")";
}

export function generateError(cause, stack) {
  var error = new Error(cause);
  error.stack = stack;
  return error;
}

export function getError(error) {
  if (!error) {
    return new Error();
  }

  const resource = get(error, 'resource');
  let message;

  // Trace XHR JSON error.
  if (!isNone(message = get(error, 'responseJSON'))) {
    return new XHRError(resource, JSON.stringify(message));
  // Trace XHR Text error.
  } else if (!isNone(message = get(error, 'responseText'))) {
    return new XHRError(resource, message);
  // Trace XHR unknown error.
  } else if (!isNone(message = get(error, 'status'))) {
    const statusText = get(error, 'statusText');

    return new XHRError(resource, `status='${message}' statusText='${statusText}'`);
  // Trace JSON objects.
  } else if (typeof error === 'object') {
    try {
      message = JSON.stringify(error);

      return new Error(message);
    } catch(e) {
      // NOOP.
    }
  }

  return new Error(error);
}
<commit_msg>implement ember-http with RSVP interface<commit_after>import Ember from 'ember';
import XHRError from './xhr-error';

const { get, isNone } = Ember;

export function getContext(router) {
  const infos = router.currentState.routerJsState.handlerInfos;
  const url = router.get('location').getURL().split('?')[0];
  const routeName = infos[infos.length - 1].name;
  const firstSegments = routeName.replace('.index', '').replace(/\./g, ' ');
  const prettyRouteName = Ember.String.capitalize(firstSegments);

  return `${prettyRouteName} (${routeName}, ${url})`;
}

export function generateError(cause, stack) {
  const error = new Error(cause);

  error.stack = stack;

  return error;
}

export function getError(error) {
  if (!error) {
    return new Error();
  }

  // get jqXHR from rejection triggered by ember-http (RSVP promises).
  if (error.jqXHR) {
    error = error.jqXHR;
  }

  const resource = get(error, 'resource');
  let message;

  // Trace XHR JSON error.
  if (!isNone(message = get(error, 'responseJSON'))) {
    return new XHRError(resource, JSON.stringify(message));
  // Trace XHR Text error.
  } else if (!isNone(message = get(error, 'responseText'))) {
    return new XHRError(resource, message);
  // Trace XHR unknown error.
  } else if (!isNone(message = get(error, 'status'))) {
    const statusText = get(error, 'statusText');

    return new XHRError(resource, `status='${message}' statusText='${statusText}'`);
  // Trace JSON objects.
  } else if (typeof error === 'object') {
    try {
      message = JSON.stringify(error);

      return new Error(message);
    } catch(e) {
      // NOOP.
    }
  }

  return new Error(error);
}
<|endoftext|>


<commit_before>define(function(require) {
var Backbone = require('backbone'),
    ContentView = require('streamhub-backbone/views/ContentView'),
    FeedTickerView = require('streamhub-ticker/views/FeedTickerView');

var TickerView = Backbone.View.extend(
{
    initialize: function (opts) {
        var self = this;

        this.$el.addClass(this.className);
        this.$el.hide();
        this.feedCollection = opts.feedCollection;
        this.childViews = {};
        this.metaElement = opts.metaElement;

        this.sources = opts.sources || {};

        this.collection.on('add', this._insertItem, this);
        // Fill the ticker with initial data
        this.collection.each(function(item) {
            self._insertItem(item, self.collection);
        });
        this.render();

        // Add feed items for any initially passed data (eg cache)
        this.feedCollection.each(function (model, index, collection) {
            self._addFeedItem(model, collection);
        });

        if (this.feedCollection) {
            this.feedCollection.on('add', this._addFeedItem, this);
        }
    },
    className: "hub-TickerView",
    render: function () {
        this.$el.fadeIn();
        // Scroll to latest tick
        var latest = this.collection.at(this.collection.length-1),
            latestId = latest && latest.get('id');
        if (latestId) {
            this.scrollTo(latestId);
        }
    }
});

TickerView.prototype._insertItem = function (item, col) {
    if (!item.get('author')) { return; }

    var feedEl = $(document.createElement('div'));
    feedEl.addClass('item-feed-view');

    var contentEl = $(document.createElement('div'));
    contentEl.addClass('item-content-view');

    var itemEl = $(document.createElement('div'));
    itemEl.append(feedEl);
    itemEl.append(contentEl);

    var itemMetaEl = $('
' + item.get('bodyHtml') + '
').find(this.metaElement);
    var itemMeta = {};
    try { itemMeta = JSON.parse(itemMetaEl.text()); } catch (ex) {}

    itemEl
      .addClass('hub-item')
      .attr('data-hub-contentid', item.get('id'))
      .attr('data-hub-createdAt', item.get('createdAt'))
      .attr('data-hub-source-id', item.get('sourceId'));

    if (itemMeta.eventType) {
        itemEl.attr('data-hub-event-type', itemMeta.eventType);
    }
    if (itemMeta.eventUrl) {
        itemEl.attr('data-hub-event-url', itemMeta.eventUrl);
        contentEl.css('background', 'url(' + itemMeta.eventUrl + ') no-repeat 0px 0px');
    }
    if (itemMeta.eventImportant) {
        itemEl.attr('data-hub-event-important', itemMeta.eventImportant);
    }

    var contentView = new ContentView({
        model: item,
        el: contentEl
    });

    var subCol = new Backbone.Collection();
    subCol.comparator = function(i) { return i.get('createdAt'); };

    var feedView = new FeedTickerView({
        collection: subCol,
        el: feedEl,
        sources: this.sources
    });
    feedView.render();

    this.childViews[item.get('createdAt')] = {feedView:feedView, item: item};

    this._animateAdd(itemEl, col, col.indexOf(item));

    //this._rebalanceFeedItems(item, col);

    return itemEl;
};

TickerView.prototype._animateAdd = function(itemEl, col, index) {
    var prev = col.at(index-1);
    var next = col.at(index+1);
    var origScrollWidth = this.$el[0].scrollWidth;
    var prevEl = prev ? this.$el.find('.hub-item[data-hub-contentid="' + prev.get('id') + '"]') : null;

    if (prevEl && prevEl.length > 0) {
        itemEl.insertAfter(prevEl);
    } else {
        this.$el.prepend(itemEl);
    }
    var newScrollWidth = this.$el[0].scrollWidth;
    var diff = newScrollWidth - origScrollWidth;

    if (!this.paused && col._initialized) {
        this.$el.animate({
            scrollLeft: this.$el.scrollLeft() + diff
        }, 500);
    } else if (!col._initialized) {
        this.$el.scrollLeft(this.$el.scrollLeft() + diff);
    }
};

TickerView.prototype._rebalanceFeedItems = function(item, col) {
    var index = col.indexOf(item);
    var createdAt = item.get('createdAt');
    var feedCol = this.childViews[createdAt].feedView.collection;

    // this is going to trace backwards, then forewards along the the feed items,
    // in each collection, moving feed item that need to be in this newly added item's collection
    var prev;
    var prevFeedItem;
    var prevCursor = 0;
    while (!prevFeedItem || prevFeedItem.get('createdAt') > createdAt) {
        while (!prevFeedItem) {
            prev = null;
            prevCursor++;
            var prevItem = col.at(index-prevCursor);
            if (prevItem) {
                prev = this.childViews[prevItem.get('id')];
            }
            if (!prev) { break; }
            prevFeedItem = prev.item.collection.last();
        }
        if (!prev) { break; }
        if (prevFeedItem.get('createdAt') > createdAt) {
            console.log("Shuffled from prev: ", prevFeedItem.get('createdAt'), ' > ', createdAt);
            prev.item.collection.remove(prevFeedItem);
            feedCol.add(prevFeedItem);
        }
        prevFeedItem = prev.item.collection.last();
    }

    var next;
    var nextFeedItem;
    var nextCursor = 0;

    while (!nextFeedItem || nextFeedItem.get('createdAt') < createdAt) {
        while (!nextFeedItem) {
            next = null;
            nextCursor++;
            var nextItem = col.at(index+nextCursor);
            if (nextItem) {
                next = this.childViews[nextItem.get('id')];
            }
            if (!next) { break; }
            nextFeedItem = next.item.collection.first();
        }
        if (!next) { break; }
        if (nextFeedItem.get('createdAt') < createdAt) {
            console.log("Shuffled from next: ", nextFeedItem.get('createdAt'), ' < ', createdAt);
            next.item.collection.remove(nextFeedItem);
            feedCol.add(nextFeedItem);
        }
        nextFeedItem = next.item.collection.first();
    }
};

TickerView.prototype._addFeedItem = function(item, col) {
    // parse the tree
    var itemCreatedAt = item.get('createdAt');
    var keys = Object.keys(this.childViews).sort();

    if (keys.length === 0) {
        return;
    }

    for (var i = 0; i < keys.length; i++) {
        if (itemCreatedAt > keys[i] && (i == keys.length - 1 || itemCreatedAt < keys[i+1])) {
            var feedView = this.childViews[keys[i]].feedView;
            feedView.collection.add(item);
            break;
        }
    }
};

TickerView.prototype.scrollTo = function(contentId) {
    var itemEl = this.$el.find('[data-hub-contentid="'+ contentId +'"]');
    this.$el.animate({
        scrollLeft: this.$el.scrollLeft() + itemEl.offset().left - window.outerWidth + itemEl.outerWidth()
    }, 500);
    return itemEl;
};

return TickerView;
});
<commit_msg>Don't assume feedCollection will be there<commit_after>define(function(require) {
var Backbone = require('backbone'),
    ContentView = require('streamhub-backbone/views/ContentView'),
    FeedTickerView = require('streamhub-ticker/views/FeedTickerView');

var TickerView = Backbone.View.extend(
{
    initialize: function (opts) {
        var self = this;

        this.$el.addClass(this.className);
        this.$el.hide();
        this.feedCollection = opts.feedCollection;
        this.childViews = {};
        this.metaElement = opts.metaElement;

        this.sources = opts.sources || {};

        this.collection.on('add', this._insertItem, this);
        // Fill the ticker with initial data
        this.collection.each(function(item) {
            self._insertItem(item, self.collection);
        });
        this.render();

        if (this.feedCollection) {
            // Add feed items for any initially passed data (eg cache)
            this.feedCollection.each(function (model, index, collection) {
                self._addFeedItem(model, collection);
            });
            this.feedCollection.on('add', this._addFeedItem, this);
        }
    },
    className: "hub-TickerView",
    render: function () {
        this.$el.fadeIn();
        // Scroll to latest tick
        var latest = this.collection.at(this.collection.length-1),
            latestId = latest && latest.get('id');
        if (latestId) {
            this.scrollTo(latestId);
        }
    }
});

TickerView.prototype._insertItem = function (item, col) {
    if (!item.get('author')) { return; }

    var feedEl = $(document.createElement('div'));
    feedEl.addClass('item-feed-view');

    var contentEl = $(document.createElement('div'));
    contentEl.addClass('item-content-view');

    var itemEl = $(document.createElement('div'));
    itemEl.append(feedEl);
    itemEl.append(contentEl);

    var itemMetaEl = $('
' + item.get('bodyHtml') + '
').find(this.metaElement);
    var itemMeta = {};
    try { itemMeta = JSON.parse(itemMetaEl.text()); } catch (ex) {}

    itemEl
      .addClass('hub-item')
      .attr('data-hub-contentid', item.get('id'))
      .attr('data-hub-createdAt', item.get('createdAt'))
      .attr('data-hub-source-id', item.get('sourceId'));

    if (itemMeta.eventType) {
        itemEl.attr('data-hub-event-type', itemMeta.eventType);
    }
    if (itemMeta.eventUrl) {
        itemEl.attr('data-hub-event-url', itemMeta.eventUrl);
        contentEl.css('background', 'url(' + itemMeta.eventUrl + ') no-repeat 0px 0px');
    }
    if (itemMeta.eventImportant) {
        itemEl.attr('data-hub-event-important', itemMeta.eventImportant);
    }

    var contentView = new ContentView({
        model: item,
        el: contentEl
    });

    var subCol = new Backbone.Collection();
    subCol.comparator = function(i) { return i.get('createdAt'); };

    var feedView = new FeedTickerView({
        collection: subCol,
        el: feedEl,
        sources: this.sources
    });
    feedView.render();

    this.childViews[item.get('createdAt')] = {feedView:feedView, item: item};

    this._animateAdd(itemEl, col, col.indexOf(item));

    //this._rebalanceFeedItems(item, col);

    return itemEl;
};

TickerView.prototype._animateAdd = function(itemEl, col, index) {
    var prev = col.at(index-1);
    var next = col.at(index+1);
    var origScrollWidth = this.$el[0].scrollWidth;
    var prevEl = prev ? this.$el.find('.hub-item[data-hub-contentid="' + prev.get('id') + '"]') : null;

    if (prevEl && prevEl.length > 0) {
        itemEl.insertAfter(prevEl);
    } else {
        this.$el.prepend(itemEl);
    }
    var newScrollWidth = this.$el[0].scrollWidth;
    var diff = newScrollWidth - origScrollWidth;

    if (!this.paused && col._initialized) {
        this.$el.animate({
            scrollLeft: this.$el.scrollLeft() + diff
        }, 500);
    } else if (!col._initialized) {
        this.$el.scrollLeft(this.$el.scrollLeft() + diff);
    }
};

TickerView.prototype._rebalanceFeedItems = function(item, col) {
    var index = col.indexOf(item);
    var createdAt = item.get('createdAt');
    var feedCol = this.childViews[createdAt].feedView.collection;

    // this is going to trace backwards, then forewards along the the feed items,
    // in each collection, moving feed item that need to be in this newly added item's collection
    var prev;
    var prevFeedItem;
    var prevCursor = 0;
    while (!prevFeedItem || prevFeedItem.get('createdAt') > createdAt) {
        while (!prevFeedItem) {
            prev = null;
            prevCursor++;
            var prevItem = col.at(index-prevCursor);
            if (prevItem) {
                prev = this.childViews[prevItem.get('id')];
            }
            if (!prev) { break; }
            prevFeedItem = prev.item.collection.last();
        }
        if (!prev) { break; }
        if (prevFeedItem.get('createdAt') > createdAt) {
            console.log("Shuffled from prev: ", prevFeedItem.get('createdAt'), ' > ', createdAt);
            prev.item.collection.remove(prevFeedItem);
            feedCol.add(prevFeedItem);
        }
        prevFeedItem = prev.item.collection.last();
    }

    var next;
    var nextFeedItem;
    var nextCursor = 0;

    while (!nextFeedItem || nextFeedItem.get('createdAt') < createdAt) {
        while (!nextFeedItem) {
            next = null;
            nextCursor++;
            var nextItem = col.at(index+nextCursor);
            if (nextItem) {
                next = this.childViews[nextItem.get('id')];
            }
            if (!next) { break; }
            nextFeedItem = next.item.collection.first();
        }
        if (!next) { break; }
        if (nextFeedItem.get('createdAt') < createdAt) {
            console.log("Shuffled from next: ", nextFeedItem.get('createdAt'), ' < ', createdAt);
            next.item.collection.remove(nextFeedItem);
            feedCol.add(nextFeedItem);
        }
        nextFeedItem = next.item.collection.first();
    }
};

TickerView.prototype._addFeedItem = function(item, col) {
    // parse the tree
    var itemCreatedAt = item.get('createdAt');
    var keys = Object.keys(this.childViews).sort();

    if (keys.length === 0) {
        return;
    }

    for (var i = 0; i < keys.length; i++) {
        if (itemCreatedAt > keys[i] && (i == keys.length - 1 || itemCreatedAt < keys[i+1])) {
            var feedView = this.childViews[keys[i]].feedView;
            feedView.collection.add(item);
            break;
        }
    }
};

TickerView.prototype.scrollTo = function(contentId) {
    var itemEl = this.$el.find('[data-hub-contentid="'+ contentId +'"]');
    this.$el.animate({
        scrollLeft: this.$el.scrollLeft() + itemEl.offset().left - window.outerWidth + itemEl.outerWidth()
    }, 500);
    return itemEl;
};

return TickerView;
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
const coffeeScriptPlugin = require("./coffeescript_loader_plugin")
const pathsResolverPlugin = require("./paths_resolver_plugin")
const globImportPlugin = require("./glob_import_plugin")
// const envFilePlugin = require("esbuild-envfile-plugin")
const envFilePlugin = require("./esbuild-plugin-env")
const entryPoints = require("./entrypoints")

const esbuild = require("esbuild")
const path = require("path")
const args = process.argv.slice(2)
const watch = args.indexOf("--watch") >= 0
const production =
  args.indexOf("--production") >= 0 || process.env.RAILS_ENV === "production"
const log = console.log.bind(console)

const config = {
  entryPoints: entryPoints(
    [
      // all "*" are replaced with the path tokens and joined by "_"
      { path: "app/javascript/*.{js,jsx,coffee}" }, // all js and jsx files in app/javascript folder
      {
        path: "plugins/*/app/javascript/plugin.{js,jsx,coffee}",
        suffix: "plugin",
      }, // all plugin.js files in all plugins
      {
        path: "plugins/*/app/javascript/widgets/*/init.{js,jsx,coffee}",
        suffix: "widget",
      },
    ],
    { log: true }
  ),
  bundle: true,
  platform: "browser",
  // format: "esm",
  // splitting: true,
  outdir: "app/assets/builds",
  plugins: [
    envFilePlugin,
    pathsResolverPlugin({
      lib: "app/javascript/lib",
      core: "app/javascript/core",
      plugins: "plugins",
      config: "config",
    }),
    globImportPlugin(),
    coffeeScriptPlugin(),
  ],
  //loader: { ".js": "jsx" },
  target: ["es6", "chrome58", "firefox57", "safari11", "edge18"],
  // watch: watch && {
  //   onRebuild(error, result) {
  //     if (!error) {
  //       console.log("\033[2J")
  //       console.log(
  //         "\x1b[32m%s\x1b[0m",
  //         "Rebuild completed successfully with no errors! Don't worry Be Happy :)"
  //       ) //cyan
  //       console.log("watching...")
  //     }
  //   },
  // },
  minify: production,
  sourcemap: !production,
  inject: [path.resolve(__dirname, "./react-shim.js")],
  // map global this to window
  define: { this: "window" },
  allowOverwrite: true,
  loader: { ".css": "text" },
}

// function compile(options = {}) {
//   if (options.clear) console.clear() // log("\033[2J")
//   log("Compiling...")
//   return esbuild.build(config).then(() => {
//     log(
//       "\x1b[32m%s\x1b[0m",
//       "Rebuild completed successfully with no errors! Don't worry Be Happy :)"
//     ) //cyan
//   })
// }

function compile(options = {}) {
  if (options.clear) console.clear() // log("\033[2J")
  log("Compiling...")

  // return esbuild
  //   .serve(
  //     {
  //       servedir: "www",
  //       port: 8080,
  //     },
  //     { ...config, outdir: "www/js" }
  //   )
  //   .then((server) => {
  //     log("Stop", server)
  //     // Call "stop" on the web server to stop serving
  //     //server.stop()
  //   })

  return esbuild.build(config).then(() => {
    log(
      "\x1b[32m%s\x1b[0m",
      "Rebuild completed successfully with no errors! Don't worry Be Happy :)"
    ) //cyan
  })
}

if (watch) {
  compile().then(() => {
    //******************************************** */
    const chokidar = require("chokidar")
    // Initialize watcher.
    const watcher = chokidar.watch(Object.values(config.entryPoints), {
      ignored: /(^|[\/\\])\../, // ignore dotfiles
      persistent: true,
      ignoreInitial: true,
    })

    // Add event listeners.
    watcher
      .on("ready", () => log("Watching..."))
      .on("add", (path) => {
        log(`File ${path} has been added`)
        watcher.add(path)
        compile({ clear: true })
      })
      .on("change", (path) => {
        log(`File ${path} has been changed`)
        compile({ clear: true })
      })
      .on("unlink", (path) => {
        log(`File ${path} has been removed`)
        compile({ clear: true })
      })
      .on("addDir", (path) => {
        log(`Directory ${path} has been added`)
        watch.add(`${path}*.{js,jsx,coffee}`)
        compile({ clear: true })
      })
      .on("unlinkDir", (path) => {
        log(`Directory ${path} has been removed`)
        compile({ clear: true })
      })
      .on("error", (error) => log(`Watcher error: ${error}`))
  })
} else {
  compile()
}
<commit_msg>fix and beautify for es-build<commit_after>#!/usr/bin/env node
const coffeeScriptPlugin = require("./coffeescript_loader_plugin")
const pathsResolverPlugin = require("./paths_resolver_plugin")
const globImportPlugin = require("./glob_import_plugin")
// const envFilePlugin = require("esbuild-envfile-plugin")
const envFilePlugin = require("./esbuild-plugin-env")
const entryPoints = require("./entrypoints")

const esbuild = require("esbuild")
const path = require("path")
const args = process.argv.slice(2)
const watch = args.indexOf("--watch") >= 0
const production =
  args.indexOf("--production") >= 0 || process.env.RAILS_ENV === "production"
const log = console.log.bind(console)

const config = {
  entryPoints: entryPoints(
    [
      // all "*" are replaced with the path tokens and joined by "_"
      { path: "app/javascript/*.{js,jsx,coffee}" }, // all js and jsx files in app/javascript folder
      {
        path: "plugins/*/app/javascript/plugin.{js,jsx,coffee}",
        suffix: "plugin",
      }, // all plugin.js files in all plugins
      {
        path: "plugins/*/app/javascript/widgets/*/init.{js,jsx,coffee}",
        suffix: "widget",
      },
    ],
    { log: true }
  ),
  bundle: true,
  platform: "browser",
  // format: "esm",
  // splitting: true,
  outdir: "app/assets/builds",
  plugins: [
    envFilePlugin,
    pathsResolverPlugin({
      lib: "app/javascript/lib",
      core: "app/javascript/core",
      plugins: "plugins",
      config: "config",
    }),
    globImportPlugin(),
    coffeeScriptPlugin(),
  ],
  //loader: { ".js": "jsx" },
  target: ["es6", "chrome58", "firefox57", "safari11", "edge18"],
  // watch: watch && {
  //   onRebuild(error, result) {
  //     if (!error) {
  //       console.log("\033[2J")
  //       console.log(
  //         "\x1b[32m%s\x1b[0m",
  //         "Rebuild completed successfully with no errors! Don't worry Be Happy :)"
  //       ) //cyan
  //       console.log("watching...")
  //     }
  //   },
  // },
  minify: production,
  sourcemap: !production,
  inject: [path.resolve(__dirname, "./react-shim.js")],
  // map global this to window
  define: { this: "window" },
  allowOverwrite: true,
  loader: { ".css": "text" },
}

// function compile(options = {}) {
//   if (options.clear) console.clear() // log("\033[2J")
//   log("Compiling...")
//   return esbuild.build(config).then(() => {
//     log(
//       "\x1b[32m%s\x1b[0m",
//       "Rebuild completed successfully with no errors! Don't worry Be Happy :)"
//     ) //cyan
//   })
// }

const grey = "\x1b[30m%s\x1b[0m"
const red = "\x1b[31m%s\x1b[0m"
const green = "\x1b[32m%s\x1b[0m"
const yellow = "\x1b[33m%s\x1b[0m"
const blue = "\x1b[34m%s\x1b[0m"

function compile(options = {}) {
  if (options.clear) console.clear()
  if (options.change) {
    log(yellow, "◻ Change detected -> compile")
  } else {
    log(yellow, "◻ First compile...")
  }

  return esbuild
    .build(config)
    .then(() => {
      log(
        green,
        " ◻ Compile completed successfully with no errors! Don't worry Be Happy 🙂"
      )
    })
    .catch((error) => {
      log(red, "Compile completed with error 😐")
      console.error(error)
    })
}

if (watch) {
  compile().then(() => {
    //******************************************** */
    const chokidar = require("chokidar")
    // Initialize watcher.
    const watcher = chokidar.watch(
      Object.values([
        "app/javascript/**/*.{js,jsx,coffee}",
        "plugins/*/app/javascript/**/*.{js,jsx,coffee}",
      ]),
      {
        ignored: /(^|[\/\\])\../, // ignore dotfiles
        persistent: true,
        ignoreInitial: true,
      }
    )

    // Add event listeners.
    watcher
      .on("ready", () => {
        log(blue, " ◻ Watching for changes 👀")
      })
      .on("add", (path) => {
        watcher.add(path)
        compile({ clear: true, change: true }).then(() => {
          log(grey, "  ◻ Reason: file has been added 🚀")
          log(grey, `  ◻ File: ${path}`)
        })
      })
      .on("change", (path) => {
        compile({ clear: true, change: true }).then(() => {
          log(grey, "  ◻ Reason: file has been changed 🔄")
          log(grey, `  ◻ File: ${path}`)
        })
      })
      .on("unlink", (path) => {
        compile({ clear: true, change: true }).then(() => {
          log(grey, "  ◻ Reason: file has been removed 💀")
          log(grey, `  ◻ File: ${path}`)
        })
      })
      .on("addDir", (path) => {
        watch.add(`${path}*.{js,jsx,coffee}`)
        compile({ clear: true, change: true })
        log(grey, "  ◻ Reason: directory has been added 🚀")
        log(grey, `  ◻ Directory: ${path}`)
      })
      .on("unlinkDir", (path) => {
        compile({ clear: true, change: true })
        log(grey, "  ◻ Reason: directory has been removed 💀")
        log(grey, `  ◻ Directory: ${path}`)
      })
      .on("error", (error) => log(red, `Watcher error: ${error} 👎`))
  })
} else {
  compile()
}
<|endoftext|>


<commit_before>elation.require(['elements.ui.panel', 'elements.ui.togglebutton'], function() {
  elation.elements.define('ui.collapsiblepanel', class extends elation.elements.ui.panel {
    init() {
      super.init();
      this.defineAttributes({
        collapsed: { type: 'boolean', default: false },
        peek: { type: 'boolean', default: false },
        hideempty: { type: 'boolean', default: false }
      });

      this.handleMouseMove = this.handleMouseMove.bind(this);
      this.handleMouseUp = this.handleMouseUp.bind(this);
    }
    create() {
      super.create();

      // We want to put our content inside of two wrapper divs, which will let us
      // slide our content in and out in an efficient way.  We use hardware-accelerated
      // CSS transforms for smooth animations, and the containing div uses overflow to
      // make the content disappear when collapsed.

      // Extract our children - we'll reparent them later
      var children = [];
      while (this.childNodes.length > 0) {
        children.push(this.childNodes[0]);
        this.removeChild(this.childNodes[0]);
      }

      // The handle that's used to toggle this panel open or closed
      this.handle = elation.elements.create('ui.togglebutton', {
        append: this,
        class: 'collapse',
        label: '',
        onactivate: (ev) => this.expand(),
        ondeactivate: (ev) => this.collapse(),
        onmousedown: (ev) => this.startResize(ev)
      });

      // Our outer wrapper
      this.container = elation.elements.create('div', {
        append: this,
        class: 'container'
      });

      // Our main container
      this.inner = elation.elements.create('div', {
        append: this.container,
        class: 'container-inner'
      });

      // Re-add the children
      for (var i = 0; i < children.length; i++) {
        this.inner.appendChild(children[i]);
      }

      this.addclass('default');

      if (this.collapsed) {
        this.collapse();
      } else {
        this.expand();
      }
    }
    appendChild(child) {
      return (this.inner ? this.inner.appendChild(child) : HTMLElement.prototype.appendChild.call(this, child));
    }
    updateLabel() {
      let dirs = {
        'up': '^',
        'down': 'v',
        'left': '<',
        'right': '>',
      };
      let dir = 'right';
      if (this.top) {
        dir = (this.collapsed ? 'down' : 'up');
      } else if (this.bottom) {
        dir = (this.collapsed ? 'up' : 'down');
      }
      if (this.left) {
        dir = (this.collapsed ? 'right' : 'left');
      } else if (this.right) {
        dir = (this.collapsed ? 'left' : 'right');
      }
      this.handle.setLabel(dirs[dir]);
    }
    render() {
      super.render();
/*
      var collapsed = this.collapsed;
      this.collapsed = false;
      this.collapsed = collapsed;
*/
      if (this.hideempty && this.inner) {
        if (this.inner.childNodes.length == 0) {
          this.hide();
        } else {
          this.show();
        }
      }
    }
    collapse() {
      var dim = this.inner.getBoundingClientRect();
      this.inner.style.width = dim.width + 'px';
      if (this.left || this.right) {
        this.container.style.width = '0px';
      } else if (this.top || this.bottom) {
        this.container.style.height = '0px';
      }
      this.collapsed = true;
      //this.style.width = 0;
      this.updateLabel();
    }
    expand() {
      if (this.inner.offsetWidth == 0) {
        this.inner.style.width = 'auto';
      } else {
        //this.style.width = this.inner.offsetWidth + 'px';
      }
      this.container.style.width = 'auto';
      this.container.style.height = 'auto';
      this.collapsed = false;
      this.updateLabel();
    }
    startResize(ev) {
      window.addEventListener('mousemove', this.handleMouseMove);
      window.addEventListener('mouseup', this.handleMouseUp);
      this.resizepos = [ev.clientX, ev.clientY];
    }
    handleMouseMove(ev) {
      if (this.hasclass('default')) {
        this.removeclass('default');
      }
      if (this.top || this.bottom) {
        var height = this.inner.offsetHeight + (this.resizepos[1] - ev.clientY);
        this.container.style.height = height + 'px';
        this.inner.style.height = height + 'px';
      }
      if (this.left || this.right) {
        var width = this.inner.offsetWidth + (this.resizepos[0] - ev.clientX);
        this.container.style.width = width + 'px';
        this.inner.style.width = width + 'px';
      }
      this.resizepos[0] = ev.clientX;
      this.resizepos[1] = ev.clientY;
    }
    handleMouseUp(ev) {
      window.removeEventListener('mousemove', this.handleMouseMove);
      window.removeEventListener('mouseup', this.handleMouseUp);
    }
  });
});

<commit_msg>Collapsible panel class and mouse handling fix<commit_after>elation.require(['elements.ui.panel', 'elements.ui.togglebutton'], function() {
  elation.elements.define('ui.collapsiblepanel', class extends elation.elements.ui.panel {
    init() {
      super.init();
      this.defineAttributes({
        collapsed: { type: 'boolean', default: false },
        peek: { type: 'boolean', default: false },
        hideempty: { type: 'boolean', default: false }
      });

      this.handleMouseMove = this.handleMouseMove.bind(this);
      this.handleMouseUp = this.handleMouseUp.bind(this);
    }
    create() {
      super.create();

      // We want to put our content inside of two wrapper divs, which will let us
      // slide our content in and out in an efficient way.  We use hardware-accelerated
      // CSS transforms for smooth animations, and the containing div uses overflow to
      // make the content disappear when collapsed.

      // Extract our children - we'll reparent them later
      var children = [];
      while (this.childNodes.length > 0) {
        children.push(this.childNodes[0]);
        this.removeChild(this.childNodes[0]);
      }

      // The handle that's used to toggle this panel open or closed
      this.handle = elation.elements.create('ui.togglebutton', {
        append: this,
        label: '',
        onactivate: (ev) => this.expand(),
        ondeactivate: (ev) => this.collapse(),
        onmousedown: (ev) => this.startResize(ev)
      });
      this.handle.addclass('collapse');

      // Our outer wrapper
      this.container = elation.elements.create('div', {
        append: this,
        class: 'container'
      });

      // Our main container
      this.inner = elation.elements.create('div', {
        append: this.container,
        class: 'container-inner'
      });

      // Re-add the children
      for (var i = 0; i < children.length; i++) {
        this.inner.appendChild(children[i]);
      }

      this.addclass('default');

      if (this.collapsed) {
        this.collapse();
      } else {
        this.expand();
      }
    }
    appendChild(child) {
      return (this.inner ? this.inner.appendChild(child) : HTMLElement.prototype.appendChild.call(this, child));
    }
    updateLabel() {
      let dirs = {
        'up': '^',
        'down': 'v',
        'left': '<',
        'right': '>',
      };
      let dir = 'right';
      if (this.top) {
        dir = (this.collapsed ? 'down' : 'up');
      } else if (this.bottom) {
        dir = (this.collapsed ? 'up' : 'down');
      }
      if (this.left) {
        dir = (this.collapsed ? 'right' : 'left');
      } else if (this.right) {
        dir = (this.collapsed ? 'left' : 'right');
      }
      this.handle.setLabel(dirs[dir]);
    }
    render() {
      super.render();
/*
      var collapsed = this.collapsed;
      this.collapsed = false;
      this.collapsed = collapsed;
*/
      if (this.hideempty && this.inner) {
        if (this.inner.childNodes.length == 0) {
          this.hide();
        } else {
          this.show();
        }
      }
    }
    collapse() {
      var dim = this.inner.getBoundingClientRect();
      this.inner.style.width = dim.width + 'px';
      if (this.left || this.right) {
        this.container.style.width = '0px';
      } else if (this.top || this.bottom) {
        this.container.style.height = '0px';
      }
      this.collapsed = true;
      //this.style.width = 0;
      this.updateLabel();
    }
    expand() {
      if (this.inner.offsetWidth == 0) {
        this.inner.style.width = 'auto';
      } else {
        //this.style.width = this.inner.offsetWidth + 'px';
      }
      this.container.style.width = 'auto';
      this.container.style.height = 'auto';
      this.collapsed = false;
      this.updateLabel();
    }
    startResize(ev) {
      if (ev.button == 0) {
        window.addEventListener('mousemove', this.handleMouseMove);
        window.addEventListener('mouseup', this.handleMouseUp);
        this.resizepos = [ev.clientX, ev.clientY];
      }
    }
    handleMouseMove(ev) {
      if (this.hasclass('default')) {
        this.removeclass('default');
      }
      if (this.top || this.bottom) {
        var height = this.inner.offsetHeight + (this.resizepos[1] - ev.clientY);
        this.container.style.height = height + 'px';
        this.inner.style.height = height + 'px';
      }
      if (this.left || this.right) {
        var width = this.inner.offsetWidth + (this.resizepos[0] - ev.clientX);
        this.container.style.width = width + 'px';
        this.inner.style.width = width + 'px';
      }
      this.resizepos[0] = ev.clientX;
      this.resizepos[1] = ev.clientY;
    }
    handleMouseUp(ev) {
      window.removeEventListener('mousemove', this.handleMouseMove);
      window.removeEventListener('mouseup', this.handleMouseUp);
    }
  });
});

<|endoftext|>


<commit_before>
// userMsg.js
// This contains functions to display a message to the user.
// The convenience functions are probably the ones you want to use rather
// than show().

import React from 'react';
import { render } from 'react-dom';
import Prompt from '/imports/component/Prompt';
import utils from '/imports/common/utils';

var seq = 0,
    wrapPrefix = 'prompt',
    callback = {}; // a list of callbacks for all prompts

function closeHandler (wrapId, result) {

    // Destroy and free memory for this component.
    utils.destroyReactContainer(wrapId);

    // Let the caller know the result.
    if (callback[wrapId]) {
        callback[wrapId](result);
        delete callback[wrapId];
    }
}

exports.show = function (promptStr, opts) {

    // You probably want to use one of the convenience functions below to
    // display your prompt. However, this describes the options.
    // Create a Prompt instance which will be destroyed on close.
    // The only required parm is opts.promptStr.
    // @param         promptStr: the prompt string to show in the modal
    // @param     opts.severity: one of [error, info, warning], optional;
    //                           default is no color in prompt
    // @param         opts.link: http link to appear after the prompt, optional
    // @param     opts.linkText: text to appear instead of actual link, optional
    // @param opts.textInputStr: the text to put in the input box, optional
    // @param     opts.fadeAway: True means the modal fades after so many
    //                           seconds: default for info and warning is
    //                           true; default for other severities is false
    // @param opts.contentClass: a class to attach to the prompt content
    // @param opts.callback: function to call upon modal close, optional

    seq += 1;
    opts.wrapId = wrapPrefix + seq;
    if (opts.callback) {
        callback[opts.wrapId] = opts.callback;
        delete opts.callback;
    }
    opts.promptStr = promptStr;
    opts.isOpen = true;
    opts.closeHandler = closeHandler;

    var prompt = render(
        <Prompt
            promptStr = {promptStr}
         />, utils.createReactRoot(opts.wrapId)
    );

    // Set state to the options.
    prompt.setState(opts);
};

function adjustPromptStr (promptStr, prefix, suffix) {
    if (prefix) {
        promptStr = prefix + ' ' + promptStr;
    }
    if (suffix) {
        promptStr += ' ' + suffix;
    }
    return promptStr;
}

exports.info = function (promptStr, opts) {
    opts = opts || {};
    opts.severity = 'info';
    exports.show(promptStr, opts);
};

exports.warn = function (promptStr, opts) {
    opts = opts || {};
    opts.severity = 'warn';
    exports.show(promptStr, opts);
};

exports.error = function (promptStr, opts) {
    opts = opts || {};
    opts.severity = 'error';
    exports.show(promptStr, opts);
};

exports.jobSuccess = function (result, opts) {

    // Report a job success given a result from an http request.
    // @param  result: result object returned from the data server
    // @param  opts.prefix: text to prepend to the user message, optional
    // @param  opts.suffix: text to append to the user message, optional

    var promptStr = 'results: ';
    opts = opts || {};
    opts.link = result.url;
    opts.severity = 'info';
    opts.fadeAway = false;
    if (!opts.contentClass) {
        opts.contentClass = 'wider';
    }
    exports.show(adjustPromptStr(promptStr, opts.prefix, opts.suffix), opts);
};

exports.jobError = function (result, opts) {

    // Report a job error given an error result from an http request.
    // @param  result: result object returned from the data server
    // @param  opts.prefix: text to prepend to the user message, optional
    // @param  opts.suffix: text to append to the user message, optional
    // @param  opts.link: http link to appear after the prompt, optional
    // @param  opts.linkStr: text to appear instead of actual link, optional

    opts = opts || {};
    opts.severity = 'error';
    opts.logStr = (result.stackTrace) ?
        'Server Error ' + result.stackTrace : null,

    exports.show(adjustPromptStr(result.error, opts.prefix, opts.suffix), opts);
};

exports.jobSubmitted = function (opts) {
    // Report a job submitted.
    // @param  opts.prefix: text to prepend to the user message, optional
    // @param  opts.suffix: text to append to the user message, optional

    var promptStr = 'Request submitted. ' +
        'Results will return when complete.';
    opts = opts || {};
    opts.severity = 'info';

    exports.show(adjustPromptStr(promptStr, opts.prefix, opts.suffix), opts);
};
<commit_msg>quiet warning from react<commit_after>
// userMsg.js
// This contains functions to display a message to the user.
// The convenience functions are probably the ones you want to use rather
// than show().

import React from 'react';
import { render } from 'react-dom';
import Prompt from '/imports/component/Prompt';
import utils from '/imports/common/utils';

var seq = 0,
    wrapPrefix = 'prompt',
    callback = {}; // a list of callbacks for all prompts

function closeHandler (wrapId, result) {

    // Destroy and free memory for this component.
    utils.destroyReactContainer(wrapId);

    // Let the caller know the result.
    if (callback[wrapId]) {
        callback[wrapId](result);
        delete callback[wrapId];
    }
}

exports.show = function (promptStr, opts) {

    // You probably want to use one of the convenience functions below to
    // display your prompt. However, this describes the options.
    // Create a Prompt instance which will be destroyed on close.
    // The only required parm is opts.promptStr.
    // @param         promptStr: the prompt string to show in the modal
    // @param     opts.severity: one of [error, info, warning], optional;
    //                           default is no color in prompt
    // @param         opts.link: http link to appear after the prompt, optional
    // @param     opts.linkText: text to appear instead of actual link, optional
    // @param opts.textInputStr: the text to put in the input box, optional
    // @param     opts.fadeAway: True means the modal fades after so many
    //                           seconds: default for info and warning is
    //                           true; default for other severities is false
    // @param opts.contentClass: a class to attach to the prompt content
    // @param opts.callback: function to call upon modal close, optional

    seq += 1;
    opts.wrapId = wrapPrefix + seq;
    if (opts.callback) {
        callback[opts.wrapId] = opts.callback;
        delete opts.callback;
    }
    opts.promptStr = promptStr;
    opts.isOpen = true;
    opts.closeHandler = closeHandler;
    appElement = utils.createReactRoot(opts.wrapId);

    var prompt = render(
        <Prompt
            promptStr = {promptStr}
            appElement = {appElement}
         />, appElement
    );

    // Set state to the options.
    prompt.setState(opts);
};

function adjustPromptStr (promptStr, prefix, suffix) {
    if (prefix) {
        promptStr = prefix + ' ' + promptStr;
    }
    if (suffix) {
        promptStr += ' ' + suffix;
    }
    return promptStr;
}

exports.info = function (promptStr, opts) {
    opts = opts || {};
    opts.severity = 'info';
    exports.show(promptStr, opts);
};

exports.warn = function (promptStr, opts) {
    opts = opts || {};
    opts.severity = 'warn';
    exports.show(promptStr, opts);
};

exports.error = function (promptStr, opts) {
    opts = opts || {};
    opts.severity = 'error';
    exports.show(promptStr, opts);
};

exports.jobSuccess = function (result, opts) {

    // Report a job success given a result from an http request.
    // @param  result: result object returned from the data server
    // @param  opts.prefix: text to prepend to the user message, optional
    // @param  opts.suffix: text to append to the user message, optional

    var promptStr = 'results: ';
    opts = opts || {};
    opts.link = result.url;
    opts.severity = 'info';
    opts.fadeAway = false;
    if (!opts.contentClass) {
        opts.contentClass = 'wider';
    }
    exports.show(adjustPromptStr(promptStr, opts.prefix, opts.suffix), opts);
};

exports.jobError = function (result, opts) {

    // Report a job error given an error result from an http request.
    // @param  result: result object returned from the data server
    // @param  opts.prefix: text to prepend to the user message, optional
    // @param  opts.suffix: text to append to the user message, optional
    // @param  opts.link: http link to appear after the prompt, optional
    // @param  opts.linkStr: text to appear instead of actual link, optional

    opts = opts || {};
    opts.severity = 'error';
    opts.logStr = (result.stackTrace) ?
        'Server Error ' + result.stackTrace : null,

    exports.show(adjustPromptStr(result.error, opts.prefix, opts.suffix), opts);
};

exports.jobSubmitted = function (opts) {
    // Report a job submitted.
    // @param  opts.prefix: text to prepend to the user message, optional
    // @param  opts.suffix: text to append to the user message, optional

    var promptStr = 'Request submitted. ' +
        'Results will return when complete.';
    opts = opts || {};
    opts.severity = 'info';

    exports.show(adjustPromptStr(promptStr, opts.prefix, opts.suffix), opts);
};
<|endoftext|>


<commit_before>
// get the city monument list from Wikimedia monument datatbase
// and strip a few wiki tags
// https://commons.wikimedia.org/wiki/Commons:Monuments_database/API
// http://toolserver.org/~erfgoed/api/api.php
//
// Zepto.js is used to get JSONP data from toolserver

'use strict';

define([], function() {

	var baseURL = 'http://toolserver.org/~erfgoed/api/api.php?';

	var params = $.param({
		format: 'json',
		action: 'search',
		srcontry: 'fr',  //TODO get this from coodinate
		srlang: 'fr',    //TODO get this from the phone
		coord: window.sessionStorage.getItem('position_latitude') + ',' + window.sessionStorage.getItem('position_longitude'),
		radius: '5000',  //TODO add a setting for this
		props: 'name|address|municipality|image'
	});

	var requestURL = baseURL + params + '&callback=?'

	$.getJSON(requestURL, function(monumentsData){
		var data = JSON.stringify(monumentsData);
		console.log(data)
		// TODO clean wiki formating like [[city]]
		// TODO sage to localstorage
	})

});

// example centered in Nice with a 5000m radius with the more usefull fields
// http://toolserver.org/~erfgoed/api/api.php?&format=json&action=search&srcountry=fr&srlang=fr&coord=43.69073,7.294788&radius=5000&props=name|address|municipality|image

// TODO clean the [[]] from the wiki syntax in the restults ...
// TODO maybe drop adresslookup ? we can work with long lat and radius
// or just use it for country lookup
// anyway this maybe usefull later for manual monument search
<commit_msg>Update the monument list search<commit_after>
// get the city monument list from Wikimedia monument datatbase
// and strip a few wiki tags
// https://commons.wikimedia.org/wiki/Commons:Monuments_database/API
// http://toolserver.org/~erfgoed/api/api.php
//
// Zepto.js is used to get JSONP data from toolserver

'use strict';

define([], function() {

	// generate the lookup address
	var baseURL = 'http://toolserver.org/~erfgoed/api/api.php?';
	var params = $.param({
		format: 'json',
		action: 'search',
		srcontry: window.localStorage.getItem('position_country'),
		srlang: navigator.language,
		coord: window.localStorage.getItem('position_latitude') + ',' + window.localStorage.getItem('position_longitude'),
		radius: '1000',  //TODO add a setting for this
		//limit: 10, //TODO maybe add a limit in settings
		props: 'name|address|municipality|image'
	});
	var requestURL = baseURL + params + '&callback=?'

    // get the JSONP data from the external source
	$.getJSON(requestURL, function(jsonData){
		var monuments_list = JSON.stringify(jsonData);
		// TODO clean wiki formating like [[city]]
		// or use address from nominatim ?

		// save the monument list in the localStorage
		window.localStorage.setItem('monuments_list', monuments_list);
	})

});

// example centered in Nice with a 5000m radius with the most usefull fields
// http://toolserver.org/~erfgoed/api/api.php?&format=json&action=search&srcountry=fr&srlang=fr&coord=43.69073,7.294788&radius=5000&props=name|address|municipality|image
<|endoftext|>


<commit_before>// JavaScript Document

onDeviceReady = function(){
	var ref = window.open('http://apache.org', '_blank', 'location=yes');
}
showVideo= function(videoCode){
	var url = "http://www.youtube.com/embed/"+videoCode
	sessionStorage.setItem("videoURL",url);
	window.location.href = "video.html";

	/* $.mobile.changePage("video.html", {
            transition: "pop",
            reverse: false,
            changeHash: false
        }); */
}

vermas = function(url){
	sessionStorage.setItem("vermasurl",url);
	//window.location.href = "vermas.html";
	if(url != null){
		window.open(url, '_blank');
	}

}

facebookGo = function(url){
	sessionStorage.setItem("compartirurl",url);

	if(url != null){
		window.open('https://m.facebook.com/sharer.php?u='+url, '_blank');
	}
}

twitterGo = function(url,title){
	sessionStorage.setItem("compartirurl",url);

	if(title == null){
		title=""
	}

	if(url != null){
		//window.open("https://twitter.com/share?url='"+url+"'&screen_name=enticconfio&text="+title, '_blank');
		window.open('https://twitter.com/share?url='+url+'screen_name=enticconfio&text='+title, '_blank');
	}
}

 generateItem = function(itemd,collapsible){

	var typeItem 	= itemd["type"];
	var title 	    = itemd["title"];
	if(title == null || title == 'null')
		title = "Novedad sin titulo";
	var url 	    = itemd["url"];

	if(!/^(http:\/\/).+$/i.test(url))
	 	url = null

	var vermas 	    = itemd["urlmas"];
	var texto 	    = itemd["text"];
	if(texto==null || texto == "null")
		texto = "";

	var articulo = $('

');

	articulo.append("
"+title+"
");
	 var vermasLinks = "";
			if(vermas!=null && vermas != "" && vermas.match(/null/g)==null){
				vermasLinks = '

ver mas

'+'Compartir en Facebook!!

Compartir en Twitter!!

';
								//href="https://www.facebook.com/sharer/sharer.php?u='+vermas+'" target="_blank"
								//'+vermas+'\'

			}
	switch (typeItem){
		case "video":
			pattern = /.*\/v\/([A-z0-9]*)/i
				var videoCode = null
				if(url != null){
					regResponse = pattern.exec(url)
					if(regResponse != null)
						videoCode = regResponse[1];
				}

			var parrafo = [];

			if(texto!="")
				texto += '

';

			var video = "";
			if(videoCode != null)
				video = '';
			else
				video = 'No llego la data del video';

			parrafo = $('
'+texto+'
'+video+vermasLinks+'
');
			articulo.append(parrafo);
			if(url != null){
				//$("#video_container").attr("src",url);
				/*popup_video = '

';
				articulo.append(popup_video);*/
			}
		break;
		case "text":
			var parrafo = $('
'+(texto!="null"?texto:"")+'
'+vermasLinks+'
');
			articulo.append(parrafo);
		break;
		case "imageText":
			var parrafo = "";
			if(url != null){
				parrafo = $('

'+(texto!="null"?texto:"")+'
'+vermasLinks+'
');
			}else{
				parrafo = $('
'+(texto!="null"?texto:"")+'
'+vermasLinks+'
');
			}

			articulo.append(parrafo);
			break;
		case "image":
			var parrafo = "";
			if(url != null){
				parrafo = $('

'+vermasLinks+'
');
				articulo.append(parrafo);
			}else{
				parrafo = $('
Imagen no disponible
'+vermasLinks+'
');
				articulo.append(parrafo);
			}
			break;
	}

	$(collapsible).append(articulo);
	$(collapsible).trigger('create');
  }

  itemFail = function(collapsibleSetId){
	  		var articulo = $('

');
	articulo.append("
No Hay Novedades
");
		var parrafo = $('
Verifica si estas conectado a internet
');
		articulo.append(parrafo);
		$(collapsibleSetId).append(articulo);
		$(collapsibleSetId).trigger('create');

	}<commit_msg>Share on Twitter<commit_after>// JavaScript Document

onDeviceReady = function(){
	var ref = window.open('http://apache.org', '_blank', 'location=yes');
}
showVideo= function(videoCode){
	var url = "http://www.youtube.com/embed/"+videoCode
	sessionStorage.setItem("videoURL",url);
	window.location.href = "video.html";

	/* $.mobile.changePage("video.html", {
            transition: "pop",
            reverse: false,
            changeHash: false
        }); */
}

vermas = function(url){
	sessionStorage.setItem("vermasurl",url);
	//window.location.href = "vermas.html";
	if(url != null){
		window.open(url, '_blank');
	}

}

facebookGo = function(url){
	sessionStorage.setItem("compartirurl",url);

	if(url != null){
		window.open('https://m.facebook.com/sharer.php?u='+url, '_blank');
	}
}

twitterGo = function(url,title){
	sessionStorage.setItem("compartirurl",url);

	if(title == null){
		title=""
	}

	if(url != null){
		//window.open("https://twitter.com/share?url='"+url+"'&screen_name=enticconfio&text="+title, '_blank');
		window.open('https://twitter.com/share?url='+url+'&screen_name=enticconfio&text='+title, '_blank');
	}
}

 generateItem = function(itemd,collapsible){

	var typeItem 	= itemd["type"];
	var title 	    = itemd["title"];
	if(title == null || title == 'null')
		title = "Novedad sin titulo";
	var url 	    = itemd["url"];

	if(!/^(http:\/\/).+$/i.test(url))
	 	url = null

	var vermas 	    = itemd["urlmas"];
	var texto 	    = itemd["text"];
	if(texto==null || texto == "null")
		texto = "";

	var articulo = $('

');

	articulo.append("
"+title+"
");
	 var vermasLinks = "";
			if(vermas!=null && vermas != "" && vermas.match(/null/g)==null){
				vermasLinks = '

ver mas

'+'Compartir en Facebook!!

Compartir en Twitter!!

';
								//href="https://www.facebook.com/sharer/sharer.php?u='+vermas+'" target="_blank"
								//'+vermas+'\'

			}
	switch (typeItem){
		case "video":
			pattern = /.*\/v\/([A-z0-9]*)/i
				var videoCode = null
				if(url != null){
					regResponse = pattern.exec(url)
					if(regResponse != null)
						videoCode = regResponse[1];
				}

			var parrafo = [];

			if(texto!="")
				texto += '

';

			var video = "";
			if(videoCode != null)
				video = '';
			else
				video = 'No llego la data del video';

			parrafo = $('
'+texto+'
'+video+vermasLinks+'
');
			articulo.append(parrafo);
			if(url != null){
				//$("#video_container").attr("src",url);
				/*popup_video = '

';
				articulo.append(popup_video);*/
			}
		break;
		case "text":
			var parrafo = $('
'+(texto!="null"?texto:"")+'
'+vermasLinks+'
');
			articulo.append(parrafo);
		break;
		case "imageText":
			var parrafo = "";
			if(url != null){
				parrafo = $('

'+(texto!="null"?texto:"")+'
'+vermasLinks+'
');
			}else{
				parrafo = $('
'+(texto!="null"?texto:"")+'
'+vermasLinks+'
');
			}

			articulo.append(parrafo);
			break;
		case "image":
			var parrafo = "";
			if(url != null){
				parrafo = $('

'+vermasLinks+'
');
				articulo.append(parrafo);
			}else{
				parrafo = $('
Imagen no disponible
'+vermasLinks+'
');
				articulo.append(parrafo);
			}
			break;
	}

	$(collapsible).append(articulo);
	$(collapsible).trigger('create');
  }

  itemFail = function(collapsibleSetId){
	  		var articulo = $('

');
	articulo.append("
No Hay Novedades
");
		var parrafo = $('
Verifica si estas conectado a internet
');
		articulo.append(parrafo);
		$(collapsibleSetId).append(articulo);
		$(collapsibleSetId).trigger('create');

	}<|endoftext|>


<commit_before>import PropTypes from 'prop-types';

import Container from 'react-bootstrap/Container';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import Tooltip from 'react-bootstrap/Tooltip';
import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
import Dropdown from 'react-bootstrap/Dropdown';
import styled from 'astroturf';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDiscord } from '@fortawesome/free-brands-svg-icons/faDiscord';
import { faGithub } from '@fortawesome/free-brands-svg-icons/faGithub';

import logo from '../assets/logo.svg';

const Banner = styled(Navbar).attrs({
  as: 'header',
  variant: 'dark',
  role: 'banner',
})`
  @import '../css/theme.scss';

  composes: text-light justify-content-center from global;
  min-height: 4rem;
  background-color: $darker;
  filter: none;
  -webkit-filter: none;

  a {
    margin-left: 1em;
    color: $brand;
  }

  @include media-breakpoint-up(md) {
    z-index: 1040;
  }
`;

const StyledNavbar = styled(Navbar).attrs({
  as: 'header',
  variant: 'dark',
  role: 'banner',
})`
  @import '../css/theme.scss';

  min-height: 4rem;
  background-color: $darker;
  z-index: 1;

  @include media-breakpoint-up(md) {
    position: sticky;
    top: 0rem;
    z-index: 1040;
  }
`;

const SkipToContentLink = styled('a')`
  composes: visually-hidden visually-hidden-focusable bg-primary text-white px-4 py-2 me-2 from global;
`;

const StyledNavLink = styled(Nav.Link)`
  @import '../css/theme.scss';

  & + & {
    margin-left: $spacer;
  }

  &:global(.active) {
    font-width: 700;
  }
`;

const StyledDropdown = styled(Dropdown)`
  @import '../css/theme.scss';

  margin-right: $spacer;
`;

const NAV_LINKS = [
  {
    link: '/',
    title: 'Home',
    exact: true,
  },
  {
    link: '/getting-started/introduction',
    title: 'Getting Started',
  },
  {
    link: '/components/alerts',
    title: 'Components',
  },
];

const propTypes = {
  activePage: PropTypes.string,
};

function NavMain({ activePage }) {
  return (
    <>
      <Banner>
        Black Lives Matter.

          Support the Equal Justice Initiative.

      </Banner>

            ))}

            <OverlayTrigger
              placement="bottom"
              delay={{ show: 200 }}
              overlay={<Tooltip id="t-github">Github</Tooltip>}
            >

            </OverlayTrigger>
            <OverlayTrigger
              placement="bottom"
              delay={{ show: 200 }}
              overlay={<Tooltip id="t-discord">Discord</Tooltip>}
            >

            </OverlayTrigger>

        </Container>
      </StyledNavbar>
    </>
  );
}

NavMain.propTypes = propTypes;

export default NavMain;
<commit_msg>docs: update bs4 version number (#5931)<commit_after>import PropTypes from 'prop-types';

import Container from 'react-bootstrap/Container';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import Tooltip from 'react-bootstrap/Tooltip';
import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
import Dropdown from 'react-bootstrap/Dropdown';
import styled from 'astroturf';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDiscord } from '@fortawesome/free-brands-svg-icons/faDiscord';
import { faGithub } from '@fortawesome/free-brands-svg-icons/faGithub';

import logo from '../assets/logo.svg';

const Banner = styled(Navbar).attrs({
  as: 'header',
  variant: 'dark',
  role: 'banner',
})`
  @import '../css/theme.scss';

  composes: text-light justify-content-center from global;
  min-height: 4rem;
  background-color: $darker;
  filter: none;
  -webkit-filter: none;

  a {
    margin-left: 1em;
    color: $brand;
  }

  @include media-breakpoint-up(md) {
    z-index: 1040;
  }
`;

const StyledNavbar = styled(Navbar).attrs({
  as: 'header',
  variant: 'dark',
  role: 'banner',
})`
  @import '../css/theme.scss';

  min-height: 4rem;
  background-color: $darker;
  z-index: 1;

  @include media-breakpoint-up(md) {
    position: sticky;
    top: 0rem;
    z-index: 1040;
  }
`;

const SkipToContentLink = styled('a')`
  composes: visually-hidden visually-hidden-focusable bg-primary text-white px-4 py-2 me-2 from global;
`;

const StyledNavLink = styled(Nav.Link)`
  @import '../css/theme.scss';

  & + & {
    margin-left: $spacer;
  }

  &:global(.active) {
    font-width: 700;
  }
`;

const StyledDropdown = styled(Dropdown)`
  @import '../css/theme.scss';

  margin-right: $spacer;
`;

const NAV_LINKS = [
  {
    link: '/',
    title: 'Home',
    exact: true,
  },
  {
    link: '/getting-started/introduction',
    title: 'Getting Started',
  },
  {
    link: '/components/alerts',
    title: 'Components',
  },
];

const propTypes = {
  activePage: PropTypes.string,
};

function NavMain({ activePage }) {
  return (
    <>
      <Banner>
        Black Lives Matter.

          Support the Equal Justice Initiative.

      </Banner>

            ))}

            <OverlayTrigger
              placement="bottom"
              delay={{ show: 200 }}
              overlay={<Tooltip id="t-github">Github</Tooltip>}
            >

            </OverlayTrigger>
            <OverlayTrigger
              placement="bottom"
              delay={{ show: 200 }}
              overlay={<Tooltip id="t-discord">Discord</Tooltip>}
            >

            </OverlayTrigger>

        </Container>
      </StyledNavbar>
    </>
  );
}

NavMain.propTypes = propTypes;

export default NavMain;
<|endoftext|>


<commit_before>app.router = (function () {
    var router = {
        redrawSearch: true
    }

    var blockHashChangeEvent = false;
    var oldHash = null;

    function changeHashWithNoReload(jqXHR) {
        var changeHash = jqXHR.getResponseHeader('X-Ajax-Redirect');
        if (changeHash) {
            window.location.replace(location.protocol+'//'+location.host+'/#'+changeHash);
            blockHashChangeEvent = true;
        }
    }

    function changePageTitle(jqXHR) {
        var title = jqXHR.getResponseHeader('X-Ajax-PageTitle');
        if (title) {
            document.title = decodeURIComponent(title);
        }
    }

    function scrollContent(newHash) {
        var parts = newHash.split('/');
        var lastId = parts[parts.length-2];
        if ($('#'+ lastId).length == 0 && $('.b-results__link').length) {
            var parts = $('.b-results__link').attr('href').split('/');
            var lastId = parts[parts.length-2];
        }
        if ($('#'+ lastId).length) {
            $.scrollTo($('#'+ lastId), {offset:{ top:-100}});
        }
    }

    router.hashChangeCallback = function (event) {
        if (blockHashChangeEvent) {
            blockHashChangeEvent = false;
            return;
        }

        var newHash = event.fragment;
        if (!(oldHash === null && newHash == '')) {
            $('.js-ajax-loader').trigger('start');
            $.ajax({
                url: newHash,
                dataType: 'html',
                success: function(html, text, jqXHR) {
                    changeHashWithNoReload(jqXHR);
                    changePageTitle(jqXHR);
                    if (router.redrawSearch) {
                        $('#js-content').html(html);
                        $('#js-search-form input:first').focus();
                    } else {
                        $('#js-main-content').html($(html).find('#js-main-content').html());
                        $('#js-version').html($(html).find('#js-version').html());
                    }
                    scrollContent(newHash);
                    $('.js-ajax-loader').trigger('stop');
                    router.redrawSearch = true;
                },
                error: function(){
                    $('.js-ajax-loader').trigger('stop');
                }
            });
        }

        oldHash = newHash;
    };

    return router;

}());

$(function(){
    $(window).bind('hashchange', app.router.hashChangeCallback);
    $(window).trigger('hashchange');

    // Handle normal urls as Ajax hash urls
    $('.js-ajax').live('click', function(e){
        e.preventDefault();
        jQuery.bbq.pushState('#' + $(this).attr('href').split(location.host).pop());
    });

    // Search form ajax handling
    $('#js-search-form').live('submit', function(e){
        e.preventDefault();
        jQuery.bbq.pushState('#' + $(this).attr('action').split(location.host).pop() + '?' + $(this).serialize());
    });
});
<commit_msg>fix scrollContent for page with no results<commit_after>app.router = (function () {
    var router = {
        redrawSearch: true
    }

    var blockHashChangeEvent = false;
    var oldHash = null;

    function changeHashWithNoReload(jqXHR) {
        var changeHash = jqXHR.getResponseHeader('X-Ajax-Redirect');
        if (changeHash) {
            window.location.replace(location.protocol+'//'+location.host+'/#'+changeHash);
            blockHashChangeEvent = true;
        }
    }

    function changePageTitle(jqXHR) {
        var title = jqXHR.getResponseHeader('X-Ajax-PageTitle');
        if (title) {
            document.title = decodeURIComponent(title);
        }
    }

    function scrollContent(newHash) {
        var parts = newHash.split('/');
        var lastId = parts[parts.length-2];
        if ($('#'+ lastId).length == 0 && $('.b-results__link').length) {
            var parts = $('.b-results__link').attr('href').split('/');
            var lastId = parts[parts.length-2];
        }
        if ($('#'+ lastId).length) {
            $.scrollTo($('#'+ lastId), {offset:{ top:-100}});
        } else {
            $.scrollTo(0);
        }
    }

    router.hashChangeCallback = function (event) {
        if (blockHashChangeEvent) {
            blockHashChangeEvent = false;
            return;
        }

        var newHash = event.fragment;
        if (!(oldHash === null && newHash == '')) {
            $('.js-ajax-loader').trigger('start');
            $.ajax({
                url: newHash,
                dataType: 'html',
                success: function(html, text, jqXHR) {
                    changeHashWithNoReload(jqXHR);
                    changePageTitle(jqXHR);
                    if (router.redrawSearch) {
                        $('#js-content').html(html);
                        $('#js-search-form input:first').focus();
                    } else {
                        $('#js-main-content').html($(html).find('#js-main-content').html());
                        $('#js-version').html($(html).find('#js-version').html());
                    }
                    scrollContent(newHash);
                    $('.js-ajax-loader').trigger('stop');
                    router.redrawSearch = true;
                },
                error: function(){
                    $('.js-ajax-loader').trigger('stop');
                }
            });
        }

        oldHash = newHash;
    };

    return router;

}());

$(function(){
    $(window).bind('hashchange', app.router.hashChangeCallback);
    $(window).trigger('hashchange');

    // Handle normal urls as Ajax hash urls
    $('.js-ajax').live('click', function(e){
        e.preventDefault();
        jQuery.bbq.pushState('#' + $(this).attr('href').split(location.host).pop());
    });

    // Search form ajax handling
    $('#js-search-form').live('submit', function(e){
        e.preventDefault();
        jQuery.bbq.pushState('#' + $(this).attr('action').split(location.host).pop() + '?' + $(this).serialize());
    });
});
<|endoftext|>


<commit_before>/**
 * @fileoverview Script to create a new RingoJS web application.
 */

var {join, Path, makeDirectory, move, copy, exists, symbolicLink, base} = require('fs');
var engine = require('ringo/engine');
var shell = require('ringo/shell');
var Parser = require('ringo/args').Parser;

export('createApplication', 'createPackage', 'main', 'description');

/** @ignore */
var description = "Create a new RingoJS web application or package";

/**
 * Create a new RingoJS web application at the given path.
 * @param path the path where to create the application
 */
function createApplication(path, options) {
    var dest = getTargetDir(path);
    var home = engine.properties["ringo.home"];

    if (options.appengine) {
        var symlink = Boolean(options.symlink);
        copyTree(home, "apps/admin/skeletons/appengine", dest);
        copyTree(home, "apps/admin/skeletons/app", join(dest, "WEB-INF", "app"));
        copyTree(home, "modules", join(dest, "WEB-INF", "modules"), symlink);
        fixAppEngineDirs(dest);
        copyJars(home, dest, symlink);
    } else {
        copyTree(home, "apps/admin/skeletons/app", dest);
    }
}

/**
 * Create a new RingoJS package at the given path.
 * @param path the path where to create the package
 */
function createPackage(path, options) {
    var dest = getTargetDir(path);
    var home = engine.properties["ringo.home"];

    copyTree(home, "apps/admin/skeletons/package", dest);
}

function copyTree(home, from, to, symlink) {
    var source = new Path(home, from);
    if (!source.exists() || !source.isDirectory()) {
        throw new Error("Can't find directory " + source);
    }
    var msg = symlink ? "Linking" : "Copying";
    shell.write(" +", msg, from, "to", to, "... ");
    if (symlink) {
        symbolicLink(source, to);
    } else {
        source.copyTree(to);
    }
    print("done");
}

function fixAppEngineDirs(dest) {
    var webinf = join(dest, "WEB-INF");
    makeDirectory(join(webinf, "lib"));
    makeDirectory(join(webinf, "packages"));
    var staticDir = join(webinf, "app", "static");
    if (exists(staticDir)) {
        move(staticDir, join(dest, "static"));
    }
}

function copyJars(home, dest, symlink) {
    var jars = [
        "ringo.jar",
        "js.jar",
        "jnr-posix/jaffl-0.5.jar",
        "jnr-posix/jnr-posix-1.1.3.jar"
    ];
    var libsrc = join(home, "lib");
    var libdest = join(dest, "WEB-INF", "lib");
    var msg = symlink ? "Linking" : "Copying";
    shell.write(" +", msg, "jar files to", libdest, "... ");
    for each (var jar in jars) {
        if (symlink) {
            symbolicLink(join(libsrc, jar), join(libdest, base(jar)));
        } else {
            copy(join(libsrc, jar), join(libdest, base(jar)));
        }
    }
    shell.writeln("done");
}

function getTargetDir(path) {
    if (!path) {
        throw new Error("No destination path given");
    }

    var dest = new Path(path);

    if (dest.exists() && !dest.isDirectory()) {
        throw dest + " exists but is not a directory.";
    } else if (dest.isDirectory() && dest.list().length > 0) {
        throw new Error("Directory " + dest + " exists but is not empty");
    }

    return dest;
}

/**
 * Create a new RingoJS web application from the command line.
 * @param args
 */
function main(args) {
    var script = args.shift();
    var parser = new Parser();
    parser.addOption("a", "appengine", null, "Create a new Google App Engine application");
    parser.addOption("s", "symlink", null, "Create symbolic links for jar and module files");
    parser.addOption("p", "package", null, "Create a new package");
    parser.addOption("h", "help", null, "Print help message and exit");
    var opts = parser.parse(args);
    if (opts.help) {
        print("Creates a new RingoJS application or package");
        print("Usage:");
        print("  ringo " + script + " [path]");
        print("Options:");
        print(parser.help());
        return;
    }

    var path = args[0]
            || shell.readln("Please enter the path for your application/package: ");

    if (!path) {
        print("No path, exiting.");
    } else if (opts.package) {
        createPackage(path, opts);
    } else {
        createApplication(path, opts);
    }
}

if (require.main == module.id) {
    try {
        main(system.args);
    } catch (error) {
        print(error);
        print("Use -h or --help to get a list of available options.");
    }
}
<commit_msg>Change skeletons path from apps to tools.<commit_after>/**
 * @fileoverview Script to create a new RingoJS web application.
 */

var {join, Path, makeDirectory, move, copy, exists, symbolicLink, base} = require('fs');
var engine = require('ringo/engine');
var shell = require('ringo/shell');
var Parser = require('ringo/args').Parser;

export('createApplication', 'createPackage', 'main', 'description');

/** @ignore */
var description = "Create a new RingoJS web application or package";

/**
 * Create a new RingoJS web application at the given path.
 * @param path the path where to create the application
 */
function createApplication(path, options) {
    var dest = getTargetDir(path);
    var home = engine.properties["ringo.home"];
    var skeletons = "tools/admin/skeletons/";

    if (options.appengine) {
        var symlink = Boolean(options.symlink);
        copyTree(home, skeletons + "appengine", dest);
        copyTree(home, skeletons + "app", join(dest, "WEB-INF", "app"));
        copyTree(home, "modules", join(dest, "WEB-INF", "modules"), symlink);
        fixAppEngineDirs(dest);
        copyJars(home, dest, symlink);
    } else {
        copyTree(home, skeletons + "app", dest);
    }
}

/**
 * Create a new RingoJS package at the given path.
 * @param path the path where to create the package
 */
function createPackage(path, options) {
    var dest = getTargetDir(path);
    var home = engine.properties["ringo.home"];

    copyTree(home, "tools/admin/skeletons/package", dest);
}

function copyTree(home, from, to, symlink) {
    var source = new Path(home, from);
    if (!source.exists() || !source.isDirectory()) {
        throw new Error("Can't find directory " + source);
    }
    var msg = symlink ? "Linking" : "Copying";
    shell.write(" +", msg, from, "to", to, "... ");
    if (symlink) {
        symbolicLink(source, to);
    } else {
        source.copyTree(to);
    }
    print("done");
}

function fixAppEngineDirs(dest) {
    var webinf = join(dest, "WEB-INF");
    makeDirectory(join(webinf, "lib"));
    makeDirectory(join(webinf, "packages"));
    var staticDir = join(webinf, "app", "static");
    if (exists(staticDir)) {
        move(staticDir, join(dest, "static"));
    }
}

function copyJars(home, dest, symlink) {
    var jars = [
        "ringo.jar",
        "js.jar",
        "jnr-posix/jaffl-0.5.jar",
        "jnr-posix/jnr-posix-1.1.3.jar"
    ];
    var libsrc = join(home, "lib");
    var libdest = join(dest, "WEB-INF", "lib");
    var msg = symlink ? "Linking" : "Copying";
    shell.write(" +", msg, "jar files to", libdest, "... ");
    for each (var jar in jars) {
        if (symlink) {
            symbolicLink(join(libsrc, jar), join(libdest, base(jar)));
        } else {
            copy(join(libsrc, jar), join(libdest, base(jar)));
        }
    }
    shell.writeln("done");
}

function getTargetDir(path) {
    if (!path) {
        throw new Error("No destination path given");
    }

    var dest = new Path(path);

    if (dest.exists() && !dest.isDirectory()) {
        throw dest + " exists but is not a directory.";
    } else if (dest.isDirectory() && dest.list().length > 0) {
        throw new Error("Directory " + dest + " exists but is not empty");
    }

    return dest;
}

/**
 * Create a new RingoJS web application from the command line.
 * @param args
 */
function main(args) {
    var script = args.shift();
    var parser = new Parser();
    parser.addOption("a", "appengine", null, "Create a new Google App Engine application");
    parser.addOption("s", "symlink", null, "Create symbolic links for jar and module files");
    parser.addOption("p", "package", null, "Create a new package");
    parser.addOption("h", "help", null, "Print help message and exit");
    var opts = parser.parse(args);
    if (opts.help) {
        print("Creates a new RingoJS application or package");
        print("Usage:");
        print("  ringo " + script + " [path]");
        print("Options:");
        print(parser.help());
        return;
    }

    var path = args[0]
            || shell.readln("Please enter the path for your application/package: ");

    if (!path) {
        print("No path, exiting.");
    } else if (opts.package) {
        createPackage(path, opts);
    } else {
        createApplication(path, opts);
    }
}

if (require.main == module.id) {
    try {
        main(system.args);
    } catch (error) {
        print(error);
        print("Use -h or --help to get a list of available options.");
    }
}
<|endoftext|>


<commit_before>
function positionClients(ctx, p, startAngle, clients, startDistance) {
  if (clients === 0) {
    return;
  }

  var radius = 3;
  var a = 1.2;

  for (var orbit = 0, i = 0; i < clients; orbit++) {
    var distance = startDistance + orbit * 2 * radius * a;
    var n = Math.floor((Math.PI * distance) / (a * radius));
    var delta = clients - i;

    for (var j = 0; j < Math.min(delta, n); i++, j++) {
      var angle = 2 * Math.PI / n * j;
      var x = p.x + distance * Math.cos(angle + startAngle);
      var y = p.y + distance * Math.sin(angle + startAngle);

      ctx.moveTo(x, y);
      ctx.arc(x, y, radius, 0, 2 * Math.PI);
    }
  }
}

function createDraw() {
  var self = {};

  var ctx;
  var width;
  var height;

  var transform;

  var selectedNodes = [];
  var selectedLinks = [];

  var clientColor = '#e6324b';
  var highlightColor = 'rgba(255, 255, 255, 0.2)';
  var linkScale = d3.interpolate('#F02311', '#04C714');
  var bandwidthWidthScale = d3.interpolateNumber(1.0, 3.0);
  var bandwidthAlphaScale = d3.interpolateNumber(0.1, 0.8);
  var labelColor = '#fff';

  var NODE_RADIUS = 15;
  var LINE_RADIUS = 12;

  function drawDetailNode(d) {
    if (transform.k > 1) {
      var clientCount = d.o.getClientCount();
      if (clientCount > 0) {
        ctx.beginPath();
        positionClients(ctx, d, Math.PI, clientCount, 15);
        ctx.fillStyle = clientColor;
        ctx.fill();
      }

      ctx.beginPath();
      ctx.textAlign = 'center';
      ctx.fillStyle = labelColor;
      ctx.fillText(d.o.name, d.x, d.y + 20);

      var packetCount = d.o.getPacketCount();
      if (packetCount > 0) {
        ctx.beginPath();
        ctx.textAlign = 'center';
        ctx.fillStyle = 'black';
        ctx.fillText(packetCount, d.x, d.y + 3);
      }
    }
  }

  function drawHighlightNode(d) {
    if (selectedNodes.includes(d)) {
      ctx.arc(d.x, d.y, NODE_RADIUS * 1.5, 0, 2 * Math.PI);
      ctx.fillStyle = highlightColor;
      ctx.fill();
      ctx.beginPath();
    }
  }

  function drawHighlightLink(d, to) {
    if (selectedLinks.includes(d)) {
      ctx.lineTo(to[0], to[1]);
      ctx.strokeStyle = highlightColor;
      ctx.lineWidth = LINE_RADIUS * 2;
      ctx.lineCap = 'round';
      ctx.stroke();
      to = [d.source.x, d.source.y];
    }
    return to;
  }

  self.drawNode = function drawNode(d) {
    if (d.x < transform.invertX(0) || d.y < transform.invertY(0) || transform.invertX(width) < d.x || transform.invertY(height) < d.y) {
      return;
    }
    ctx.beginPath();

    drawHighlightNode(d);

    ctx.moveTo(d.x + 3, d.y);
    ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI);
    ctx.fillStyle = d.o.getNodeColor();
    ctx.fill();

    drawDetailNode(d);
  };

  self.drawLink = function drawLink(d) {
    var zero = transform.invert([0, 0]);
    var area = transform.invert([width, height]);
    if (d.source.x < zero[0] && d.target.x < zero[0] || d.source.y < zero[1] && d.target.y < zero[1] ||
        d.source.x > area[0] && d.target.x > area[0] || d.source.y > area[1] && d.target.y > area[1]) {
      return;
    }
    ctx.beginPath();
    ctx.moveTo(d.source.x, d.source.y);
    var to = [d.target.x, d.target.y];

    to = drawHighlightLink(d, to);

    ctx.lineTo(to[0], to[1]);
    ctx.strokeStyle = linkScale(d.quality / 100);
    ctx.lineWidth = bandwidthWidthScale(d.bandwidth / 100);
    ctx.globalAlpha = bandwidthAlphaScale(d.bandwidth / 100);

    ctx.stroke();
    ctx.globalAlpha = 1;
  };

  self.setCTX = function setCTX(newValue) {
    ctx = newValue;
  };

  self.getSelectedIntNodes = function getSelectedIntNodes() {
    return selectedNodes;
  };

  self.getSelectedIntLinks = function getSelectedIntLinks() {
    return selectedLinks;
  };

  self.clearSelection = function clearSelection() {
    selectedNodes = [];
    selectedLinks = [];
  };

  self.setSelection = function setSelection(nodes, links) {
    selectedNodes = nodes;
    selectedLinks = links;
  };

  self.selectNode = function selectNode(node) {
    if (d3.event && d3.event.ctrlKey) {
      var i = selectedNodes.indexOf(node);
      if (i < 0) {
        selectedNodes.push(node);
      } else {
        selectedNodes.splice(i, 1);
      }
    } else {
      selectedNodes = [node];
      selectedLinks = [];
    }
  };

  self.selectLink = function selectLink(link) {
    if (d3.event && d3.event.ctrlKey) {
      var i = selectedLinks.indexOf(link);
      if (i < 0) {
        selectedLinks.push(link);
      } else {
        selectedLinks.splice(i, 1);
      }
    } else {
      selectedNodes = [];
      selectedLinks = [link];
    }
  };

  self.setTransform = function setTransform(newValue) {
    transform = newValue;
  };

  self.setMaxArea = function setMaxArea(newWidth, newHeight) {
    width = newWidth;
    height = newHeight;
  };

  return self;
}
<commit_msg>basic support for highlighting of nodes/links<commit_after>
function positionClients(ctx, p, startAngle, clients, startDistance) {
  if (clients === 0) {
    return;
  }

  var radius = 3;
  var a = 1.2;

  for (var orbit = 0, i = 0; i < clients; orbit++) {
    var distance = startDistance + orbit * 2 * radius * a;
    var n = Math.floor((Math.PI * distance) / (a * radius));
    var delta = clients - i;

    for (var j = 0; j < Math.min(delta, n); i++, j++) {
      var angle = 2 * Math.PI / n * j;
      var x = p.x + distance * Math.cos(angle + startAngle);
      var y = p.y + distance * Math.sin(angle + startAngle);

      ctx.moveTo(x, y);
      ctx.arc(x, y, radius, 0, 2 * Math.PI);
    }
  }
}

function createDraw() {
  var self = {};

  var ctx;
  var width;
  var height;

  var transform;

  var selectedNodes = [];
  var selectedLinks = [];

  var highlightedNodes = [];
  var highlightedLinks = [];

  var clientColor = '#e6324b';
  var selectColor = 'rgba(255, 255, 255, 0.2)';
  var highlightColor = 'rgba(255, 255, 255, 0.2)';
  var linkScale = d3.interpolate('#F02311', '#04C714');
  var bandwidthWidthScale = d3.interpolateNumber(1.0, 3.0);
  var bandwidthAlphaScale = d3.interpolateNumber(0.1, 0.8);
  var labelColor = '#fff';

  var NODE_RADIUS = 15;
  var LINE_RADIUS = 12;

  function drawDetailNode(d) {
    if (transform.k > 1) {
      var clientCount = d.o.getClientCount();
      if (clientCount > 0) {
        ctx.beginPath();
        positionClients(ctx, d, Math.PI, clientCount, 15);
        ctx.fillStyle = clientColor;
        ctx.fill();
      }

      ctx.beginPath();
      ctx.textAlign = 'center';
      ctx.fillStyle = labelColor;
      ctx.fillText(d.o.name, d.x, d.y + 20);

      var packetCount = d.o.getPacketCount();
      if (packetCount > 0) {
        ctx.beginPath();
        ctx.textAlign = 'center';
        ctx.fillStyle = 'black';
        ctx.fillText(packetCount, d.x, d.y + 3);
      }
    }
  }

  function drawHighlightNode(d) {
    if (highlightedNodes.includes(d)) {
      ctx.arc(d.x, d.y, NODE_RADIUS * 1.5, 0, 2 * Math.PI);
      ctx.fillStyle = highlightColor;
      ctx.fill();
      ctx.beginPath();
    }
  }

  function drawSelectedNode(d) {
    if (selectedNodes.includes(d)) {
      ctx.arc(d.x, d.y, NODE_RADIUS * 1.5, 0, 2 * Math.PI);
      ctx.fillStyle = selectColor;
      ctx.fill();
      ctx.beginPath();
    }
  }

  function drawHighlightLink(d, to) {
    if (highlightedLinks.includes(d)) {
      ctx.lineTo(to[0], to[1]);
      ctx.strokeStyle = highlightColor;
      ctx.lineWidth = LINE_RADIUS * 2;
      ctx.lineCap = 'round';
      ctx.stroke();
      to = [d.source.x, d.source.y];
    }
    return to;
  }

  function drawSelectLink(d, to) {
    if (selectedLinks.includes(d)) {
      ctx.lineTo(to[0], to[1]);
      ctx.strokeStyle = selectColor;
      ctx.lineWidth = LINE_RADIUS * 2;
      ctx.lineCap = 'round';
      ctx.stroke();
      to = [d.source.x, d.source.y];
    }
    return to;
  }

  self.drawNode = function drawNode(d) {
    if (d.x < transform.invertX(0) || d.y < transform.invertY(0) || transform.invertX(width) < d.x || transform.invertY(height) < d.y) {
      return;
    }
    ctx.beginPath();

    drawSelectedNode(d);
    drawHighlightNode(d);

    ctx.moveTo(d.x + 3, d.y);
    ctx.arc(d.x, d.y, 8, 0, 2 * Math.PI);
    ctx.fillStyle = d.o.getNodeColor();
    ctx.fill();

    drawDetailNode(d);
  };

  self.drawLink = function drawLink(d) {
    var zero = transform.invert([0, 0]);
    var area = transform.invert([width, height]);
    if (d.source.x < zero[0] && d.target.x < zero[0] || d.source.y < zero[1] && d.target.y < zero[1] ||
        d.source.x > area[0] && d.target.x > area[0] || d.source.y > area[1] && d.target.y > area[1]) {
      return;
    }
    ctx.beginPath();
    ctx.moveTo(d.source.x, d.source.y);
    var to = [d.target.x, d.target.y];

    to = drawSelectLink(d, to);
    to = drawHighlightLink(d, to);

    ctx.lineTo(to[0], to[1]);
    ctx.strokeStyle = linkScale(d.quality / 100);
    ctx.lineWidth = bandwidthWidthScale(d.bandwidth / 100);
    ctx.globalAlpha = bandwidthAlphaScale(d.bandwidth / 100);

    ctx.stroke();
    ctx.globalAlpha = 1;
  };

  self.setCTX = function setCTX(newValue) {
    ctx = newValue;
  };

  self.getSelectedIntNodes = function getSelectedIntNodes() {
    return selectedNodes;
  };

  self.getSelectedIntLinks = function getSelectedIntLinks() {
    return selectedLinks;
  };

  self.clearSelection = function clearSelection() {
    selectedNodes = [];
    selectedLinks = [];
  };

  self.setSelection = function setSelection(nodes, links) {
    selectedNodes = nodes;
    selectedLinks = links;
  };

  self.setHighlight = function setHighlight(nodes, links) {
    highlightedNodes = nodes;
    highlightedLinks = links;
  };

  self.clearHighlight = function clearHighlight() {
    highlightedNodes = [];
    highlightedLinks = [];
  };

  self.selectNode = function selectNode(node) {
    if (d3.event && d3.event.ctrlKey) {
      var i = selectedNodes.indexOf(node);
      if (i < 0) {
        selectedNodes.push(node);
      } else {
        selectedNodes.splice(i, 1);
      }
    } else {
      selectedNodes = [node];
      selectedLinks = [];
    }
  };

  self.selectLink = function selectLink(link) {
    if (d3.event && d3.event.ctrlKey) {
      var i = selectedLinks.indexOf(link);
      if (i < 0) {
        selectedLinks.push(link);
      } else {
        selectedLinks.splice(i, 1);
      }
    } else {
      selectedNodes = [];
      selectedLinks = [link];
    }
  };

  self.setTransform = function setTransform(newValue) {
    transform = newValue;
  };

  self.setMaxArea = function setMaxArea(newWidth, newHeight) {
    width = newWidth;
    height = newHeight;
  };

  return self;
}
<|endoftext|>